Skip to content

feat(ios): Encrypted Vaults VaultStore orchestration + leak-closure suite (#304) - #326

Closed
libravault-xyz wants to merge 2 commits into
devfrom
feat/ios-vault-store-orchestration
Closed

libravault-xyz wants to merge 2 commits into
devfrom
feat/ios-vault-store-orchestration

Conversation

@libravault-xyz

Copy link
Copy Markdown
Collaborator

What

Swift port of Android's VaultStore.kt + VaultSessionManager.kt — the orchestration layer tying #301 (VaultRegistry/UnlockAttemptThrottle), #302 (VaultManifest), and #303 (SecureEnclaveHardwareKeyWrap) into the actual vault lifecycle API, plus the leak-closure guarantee (static + behavioral) that makes the feature trustworthy end-to-end. The last piece of #201's split.

  • VaultConfig.swift — vault.json persistence (Secure Enclave-wrapped KEK-wrapped VMK + independent recovery-key wrap)
  • VaultStore.swift — create / unlockWithPin / unlockWithRecoveryKey / lock, streaming crash-safe import, cover art, highlights, bookmarks
  • VaultSessionManager.swift — an actor (first in this codebase) owning the registry + one VaultStore per touched vault, giving the same single-writer guarantee Android gets from a shared Mutex, enforced by the compiler
  • VaultForegroundLockObserver.swift — locks every open vault on willResignActive, kept separate so the actor's own tests never simulate app-lifecycle notifications
  • Leak-closure suite: a static grep guard over Sources/VaultStore/ for plaintext-persistence identifiers, plus a behavioral scan of every byte on disk for plaintext title/author/highlight/bookmark/cover-art content

Included in this PR: a principal-dev test-coverage review pass

Reviewed the above against VaultStoreTests.swift/VaultConfigTests.swift/VaultSessionManagerTests.swift/VaultLeakClosureTests.swift and found + fixed:

  • Real bug: VaultStore.create()'s failure-path VMK scrub was a no-op — var vmkCopy = newVault.vmk; vmkCopy.secureZero() zeroed a copy-on-write-forked copy, not newVault.vmk itself, because Data has value semantics (Android's newVault.vmk.fill(0) doesn't have this bug — ByteArray has reference semantics). NewVault.vmk is now var and gets zeroed in place.
  • VaultConfig.read had no negative-path coverage (missing file / malformed base64 → .malformedHeader) despite its own doc comment documenting both. Added both.
  • setCoverArt's finalize-rename failure path had no regression test, unlike its sibling importFile (which has one specifically because "Android's own review caught" that exact ordering bug once already). Added the equivalent test; confirmed Android has the same gap and filed [test] Android VaultStoreTest has no regression test for setCoverArt's finalize-rename failure path #322 to port it there too.
  • VaultSessionManager's wrong-PIN/throttled outcomes were only ever exercised via VaultStore directly, never through the actor itself. Added coverage.

Risk

ios/.../Sources/VaultStore/** is a sensitive_paths entry in .github/agent-policy.yml — flagged plainly, reviewed by the user directly (not auto-merge eligible by policy regardless of QA/principal-review outcome). No local Xcode/Swift toolchain available to compile-check — CI is the first real build signal, same caveat every prior PR in this series has carried.

Closes #304, #201. Progresses #190.

🤖 Generated with Claude Code

libravault-xyz and others added 2 commits August 19, 2026 10:41
…-closure suite (#304)

Swift port of Android's VaultStore.kt + VaultSessionManager.kt, plus the
leak-closure guarantee that makes the whole Encrypted Vaults feature
trustworthy end-to-end. Ties together #301 (VaultRegistry/
UnlockAttemptThrottle), #302 (VaultManifest), #303
(SecureEnclaveHardwareKeyWrap) - the last piece of #201's split.

What's here:
- Sources/VaultStore/VaultConfig.swift: vault.json persistence (Secure
  Enclave-wrapped KEK-wrapped VMK + independent recovery-key wrap).
  Deliberately does not store the inner KEK-wrapped blob a second time
  in the clear - same reasoning Android's VaultConfigDto documents for
  an early draft's mistake.
- Sources/VaultStore/VaultStore.swift: create/unlockWithPin/
  unlockWithRecoveryKey/lock, import (streaming, crash-safe
  rename-then-manifest ordering), cover art, highlights, bookmarks,
  openReader. Not thread-safe by design, same as VaultFileReader -
  single-writer boundary is VaultSessionManager's job.
- Sources/VaultStore/VaultSessionManager.swift: an actor (first in this
  codebase) owning the VaultRegistry + one VaultStore per touched
  vault, giving the same single-writer guarantee Android gets from a
  shared Mutex, enforced by the compiler instead of by convention.
- Sources/VaultStore/VaultForegroundLockObserver.swift: locks every
  open vault on UIApplication.willResignActiveNotification, per the
  design scoped in #201's split. Deliberately a separate type from the
  actor, so VaultSessionManager's own tests never need to simulate app
  lifecycle notifications.
- Leak-closure suite, per #201's scoping comment
  (#201 (comment)):
  VaultStoreHasNoLeakSurfaceDependencyTests.swift (static grep guard
  over Sources/VaultStore/ for ReadingDataPersistence/CoverArtCache,
  located via #filePath since there's no per-module compilation
  boundary to enforce this structurally) + VaultLeakClosureTests.swift
  (behavioral: title/author/highlights/bookmarks/cover-art bytes
  scanned for on disk, mirrors VaultLeakClosureTest.kt case-by-case).
- VaultStoreTests.swift/VaultConfigTests.swift/
  VaultSessionManagerTests.swift/VaultForegroundLockObserverTests.swift,
  FakeHardwareKeyWrap.swift (test double, mirrors Android's testing/
  FakeHardwareKeyWrap.kt).

Elevated risk vs #302/#303, flagged plainly: this is the first actor
and the first async test methods in this codebase, and
VaultForegroundLockObserverTests exercises a real NotificationCenter/
UIApplication.willResignActiveNotification path rather than pure
logic. No local Xcode to compile-check against, same caveat every
prior PR in this series carried.

Closes #304, #201, progresses #190.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
… 3 test gaps

Principal-dev test-coverage review of the VaultStore orchestration work
(#304) found one real bug and three missing regression tests:

- VaultStore.create()'s failure-path cleanup zeroed a COW-forked copy of
  the VMK (`var vmkCopy = newVault.vmk; vmkCopy.secureZero()`), not
  newVault.vmk itself, silently defeating the scrub. NewVault.vmk was a
  `let`, which made the copy-then-zero mistake the only thing that would
  even compile. Android's port (`newVault.vmk.fill(0)`) doesn't have this
  bug because ByteArray has reference semantics, not Data's copy-on-write
  value semantics. Fixed by making NewVault.vmk `var` and zeroing it
  directly.
- VaultConfig.read had zero negative-path coverage despite its own doc
  comment documenting the missing-file and malformed-base64 throw paths.
- setCoverArt's finalize-rename failure had no regression test, unlike its
  sibling importFile (which has one specifically because "Android's own
  review caught" that exact ordering bug once already). Confirmed Android
  has the same gap and filed #322 to port the equivalent test there.
- VaultSessionManager's wrong-PIN/throttled outcomes were only ever
  exercised via VaultStore directly, never through the actor itself (the
  actual entry point the app calls).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@libravault-xyz

Copy link
Copy Markdown
Collaborator Author

Principal review: request-changes (risk:high → human-merge regardless, but this needs real rework, not just a human rubber-stamp)

Headline finding: this PR is stale/duplicate and its head commit is proven-broken by CI logs

dev already contains this entire feature, merged via PR #319 (5f51422 feat(ios): implement Encrypted Vaults VaultStore orchestration + leak-closure suite (#319), dev's current tip), which closes the same issues (#304/#201) this PR also targets — both are now CLOSED. #326's branch point predates that merge, which is exactly why GitHub reports this PR as mergeable: CONFLICTING right now.

Worse: comparing #319's already-merged version against #326's head, #319 shipped the correct, working version of VaultStoreHasNoLeakSurfaceDependencyTests.swift (with a stripLineComments helper + its own regression test), while #326's head commit (ca85044…) has a regressed, broken version of the exact same file — a naive contents.contains("CoverArtCache") check that trips on the benign doc-comment prose already in VaultStore.swift (3×) and VaultManifest.swift (1×), neither of which is an actual code reference.

I didn't just infer this — I verified it against real CI logs:

  • The PR's actual head commit (c1530680910f07b9fd97fa9e1b9e4480cccf0716) has zero check-runs (gh api repos/LibraVault/reader/commits/c1530680.../check-runs → total_count: 0). pr-intake.yml only fires on opened/reopened, not plain synchronize, so the second ("test-coverage review") commit never got CI or a risk label — the PR currently carries no risk:* label at all.
  • The first commit's own SHA (ca85044ed91722f2bd1214eb26e8664b3c8cc8e8) does have a Build & Test iOS (Simulator) check-run, and it's a FAILURE (run 32244060242). Its log shows exactly the predicted failure:
    VaultStoreHasNoLeakSurfaceDependencyTests.swift:62: error: ... XCTAssertFalse failed -
      VaultManifest.swift references 'CoverArtCache' — Sources/VaultStore/ must never touch ...
    VaultStoreHasNoLeakSurfaceDependencyTests.swift:62: error: ... XCTAssertFalse failed -
      VaultStore.swift references 'CoverArtCache' — Sources/VaultStore/ must never touch ...
    ** TEST FAILED **
    
  • The green checks visible in the PR's gh run list history (QA Agent, Principal Review Agent, iOS App Build & Test all "success" around 11:01–11:16) were run against a different, now-orphaned SHA 921fffe00610d8d600586ac2709f3fbf49dcc143 — an intermediate amend where the dev-agent had already fixed this exact false-positive (added stripLineComments). That fix was silently lost: the branch was later force-pushed back to the original, still-broken ca85044, and the "test-coverage review" commit (c153068) was built on top of that stale base — it never touches this file and never re-triggered CI (confirmed via git diff ca85044..c153068 --stat).

Net effect: the PR's current, actual head commit will fail its own leak-closure test suite, and nothing in this PR's history has ever caught that, because CI never ran against the real final state.

What I'd actually recommend

Close/don't merge #326 as-is. The one thing in it that's genuinely missing from dev is the VMK-scrub fix + the 3 new regression tests from commit c153068 — dev's current VaultKeyMaterial.swift/VaultStore.swift (via #319) still has the original bug (let vmk: Data, var vmkCopy = newVault.vmk; vmkCopy.secureZero(), which zeroes a COW-forked copy, not the real buffer — verified this reasoning against Data's copy-on-write + Swift's mutating-through-lvalue semantics: newVault.vmk.secureZero() writes any COW fork back into the property's own storage slot, while var vmkCopy = …; vmkCopy.secureZero() forks and zeroes a separate variable, leaving the original untouched). The right move is a small, fresh PR against current dev that ports over just that fix + those 3 tests, cleanly on top of #319's (correct) leak-closure test.

Other findings

  • [CONFIRMED, minor] PR body's Risk section only names Sources/VaultStore/** as the touched sensitive path. The diff also touches ios/.../Sources/VaultCrypto/VaultKeyMaterial.swift, a separate agent-policy.yml sensitive_paths entry. Doesn't change the risk outcome (both independently force risk:high; I confirmed by running classify_pr_risk.py locally against origin/dev...origin/feat/ios-vault-store-orchestration), but disclosure should be complete.
  • [CONFIRMED, low severity] VaultForegroundLockObserver.deinit hardcodes NotificationCenter.default.removeObserver(token) instead of storing/using the notificationCenter actually passed to init. Harmless today (the default and only real call site both use .default), but it means deinit is a silent no-op whenever a non-default center is used — which is exactly what this PR's own VaultForegroundLockObserverTests.swift does, papering over it with withExtendedLifetime. Fix: store private let notificationCenter: NotificationCenter and call notificationCenter.removeObserver(token).
  • Verified the VMK-scrub fix itself is correct Swift (see above) — no other secureZero() call site in the diff has the same copy-then-zero shape (lock()'s vmk?.secureZero() mutates the class's own stored property directly, no issue).
  • Verified the leak-surface test's #filePath-based path math against the real repo layout, and confirmed the project uses Xcode 16 PBXFileSystemSynchronizedRootGroup for both LibraVault/LibraVaultTests, so new files don't need .pbxproj entries (a real gotcha this project structure avoids).
  • New tests in c153068 are not vacuous — traced each one against the implementation it targets (VaultConfig.read's malformed-base64 guard, setCoverArt's finalize-rename ordering, VaultSessionManager's thin pass-through of unlock outcomes).
  • No local Xcode/Swift toolchain available — I did not compile or run anything myself; all pass/fail claims above are backed by actual GitHub Actions run logs, not assumption.

Outcome: human-merge. risk:high is correct (Sources/VaultCrypto/** and Sources/VaultStore/** both match sensitive_paths), and independent of that, this PR has a CONFIRMED, CI-log-verified failing test at its actual head plus an unresolved merge conflict against dev from a since-merged duplicate PR (#319). Recommend closing this PR rather than merging it, and cutting a fresh small PR for just the still-missing VMK fix + tests.

@libravault-xyz

Copy link
Copy Markdown
Collaborator Author

Superseded — this branch predates #319 (already merged to dev, closing the same #304/#201). Re-opening the still-needed fix (VaultStore.create()'s VMK-scrub bug) + 3 test additions as a fresh PR rebased on current dev. Thanks to the review agent for catching this before merge: #326 (comment)

@libravault-xyz
libravault-xyz deleted the feat/ios-vault-store-orchestration branch August 19, 2026 19:30
libravault-xyz added a commit that referenced this pull request Aug 20, 2026
…very 4h (#335)

* feat(ci): add every-4h human-merge sweep for the needs-human-merge backlog

docs/agent-team-pipeline.md's state machine ends most risk:high PRs at
status:needs-human-merge — correct by design, but until now that backlog
only got cleared when a human noticed it and manually asked Claude Code to
review + merge each one (as happened this session for PRs #327 and #324,
plus closing #292 and #326 as stale/superseded along the way).

This adds a new, separate workflow that automates the noticing, not the
judgment:

- human-merge-sweep.yml: schedule-triggered (every 4 hours) +
  workflow_dispatch for manual testing. Plain GITHUB_TOKEN — merging/
  closing PRs isn't blocked by this repo's "Actions can't create/approve
  PRs" setting the way *opening* one is (principal-review.yml's own
  auto-merge step already proves this), so no App-token minting needed.
- human-merge-sweep-agent.md: the actual review persona. Re-verifies each
  status:needs-human-merge PR is still current (stale/conflicting PRs get
  closed with an explanation if genuinely superseded, left alone if
  ambiguous), does a real second review (reads the whole diff, cross-
  checks claims against ground truth, checks for vacuous tests) before
  merging, and separately sweeps ALL open PRs for the same staleness
  pattern regardless of label. Hard rule, not a judgment call: never
  merges anything touching .github/workflows/**, .github/agent-policy.yml,
  or .claude/agents/** — that class of change always needs a human
  directly, however clean it looks.
- human-merge-sweep-log.md: audit trail, same spirit as auto-merge-log.md
  but for this human-merge-routed path instead of the risk:low auto-merge
  path.

This PR itself is exactly the kind of change its own new agent is
hard-coded to never touch (.github/workflows/**, .claude/agents/**) — by
design, flagging it plainly rather than leaving that as an implicit
assumption: needs a human's own read, this session will not self-merge it
even if CI is green.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(ci): extend human-merge sweep to cover status:needs-info too

status:needs-human-merge isn't the only place the pipeline parks work on
a human — status:needs-info (issue triage that's underspecified, or a
PR whose QA/review run crashed or hit workflow-file drift) blocks on a
human just as silently, and was out of scope for the sweep as first
built.

Adds Part 3 to human-merge-sweep-agent.md, deliberately more conservative
than Parts 1-2 given how different the task is — "is this safe to
merge/close" is a mechanical check, "does this actually need a human" is
not:

- Detects when status:needs-info was applied because the *pipeline*
  crashed (turn budget exhausted, workflow-file drift) rather than
  because there's a real open question, and retries the stage that
  crashed — at most once per item, logged to human-merge-sweep-log.md
  same as a merge.
- For everything else — the default assumption, not an edge case — never
  answers, never changes a label, never invents scope. Only ever ensures
  a clear comment exists naming the actual open question, so a human can
  answer faster.
- Hard-excludes anything labeled security/release-blocker
  (agent-policy.yml's sensitive_issue_labels) from all autonomous action,
  including investigation.

Bumped --max-turns 120→160 (three backlogs to work per run now, not two)
and broadened human-merge-sweep-log.md's scope/column naming (PR → Item)
to cover issues and retries alongside merges/closes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(ci): missing id-token permission + retry using the wrong token

Two CONFIRMED findings from principal review of PR #335's own diff:

- permissions: was missing id-token: write. Every sibling workflow
  invoking claude-code-action carries this with an identical comment
  citing issue #158 ("Could not fetch an OIDC token" after 3 retries) —
  missed here, and continue-on-error: true on the agent step would have
  swallowed the failure silently, forever, every 4 hours.
- Part 3's retry action re-applies status:ready-for-dev/needs-qa/
  needs-review to restart a crashed pipeline stage — that label change
  must trigger the corresponding workflow, which a plain GITHUB_TOKEN
  cannot do (see docs/agent-team-pipeline.md's "Cross-workflow
  triggering"; pr-intake.yml already mints an App token for exactly this
  reason). Fixed by minting the same pipeline App token and passing it to
  the agent step as a distinctly-named PIPELINE_APP_TOKEN, with explicit
  instructions (both in the workflow prompt and the persona file) that
  it's used for that one action only — everything else stays on the
  default GH_TOKEN, unchanged.

Also tightened the retry-dedup check flagged as a plausible weak point:
"grep the comment history for retry text" is now "grep for an exact
<!-- human-merge-sweep-retry --> marker, always the first line of the
retry comment" — an exact string match instead of a fuzzy read.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
libravault-xyz pushed a commit that referenced this pull request Aug 20, 2026
…344)

Previously a manually-opened PR with no resolvable "Closes #N" line
exited pr-intake.yml's guard early with no risk:*/status:* label
applied at all, requiring a human to notice and hand-label it (as
happened for PRs #326, #335, #342). Now it still runs
classify_pr_risk.py and routes into the pipeline — status:needs-qa
when an issue is linked (unchanged), status:needs-review when it
isn't, since qa-agent.yml hard-stops on a missing linked issue (no
acceptance criteria to check) while principal-review.yml already
tolerates one gracefully.

Closes #343

Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] iOS Encrypted Vaults 2d/2d: VaultStore orchestration + leak-closure suite

1 participant