After the signature fix, removal preflight still requires read access to filesystem root. Replace both ancestor walkers with an explicit pinned library capability without changing durability or deletion authority.
Concrete confined-process evidence: root open returns EPERM1 while the owned container open succeeds; production preflight fails red. The phone alert does not reveal its actual syscall/errno.
Preflight, export, verification, abandoned cleanup and rejected-selection protection share the trusted library anchor. Feature descendants are never resolved as symlinks; retained identities are checked before mutation.
Known markers, payload-free failure ledger, file/directory fsync, rename, owner locks, external-document preservation and bounded cleanup remain. Onboarding worktree/progress, account namespace, signing, model and parser source remain intact.
Ready to push
Four source reviews clear. Five confined checks and 137 affected executions pass (138 distinct executed IDs; four repeated negatives, one separate opt-in skip). Strict lint0/225, both native platforms and the actual host-container cancellation/relaunch journey pass. Corrected signed Release is verified and remains uninstalled; physical App Group acceptance remains pending.
Pass rate: 100% (142 of 142)
New tests: 5
Diff coverage: 78% (218 of 281 added lines)
7c0d4c3e351b5ea4f2a6f7b6fa85b08f138125a4 [bug]: Reproduce container-granted removal storage failure a06b95d5d59fd1c9285a666a4443c5ac8253d7ec [bug]: Anchor removal verification in the granted library c412d0efbaa5f7ab32a629556d81ab2b398f8fab [doc]: Record verified container fix and prepared Release The app can access its own storage but previously tried opening the system root before reaching it. It now starts at its granted library and checks each temporary folder. It still verifies a saved backup and removes temporary work before allowing removal.
FamilyOperationAccess retains FamilyLibraryDirectory, which pins the canonical host-library descriptor and rechecks that identity on reopen. openat plus O_NOFOLLOW validates every feature descendant. Cleanup obtains the original namespace descriptor through that capability; all staging and external-selection guard calls receive it explicitly. Failed open/create/inspection reports a bounded operation and errno without private paths.
Direct library open avoids ancestor file-read-data requirements while retained device/inode/mode and uid/type checks prevent root replacement and intermediate-link redirection. Staging revalidates its root before payload writes/cleanup. Durable known markers and cleanup JSON preserve file-sync, same-directory rename and directory-sync ordering. Constant-cost descriptor checks run on existing workers; no file-provider parent grant, account proof or deletion inventory changes are introduced. OS confinement and native synthetic-container checks are separate from physical App Group/live CloudKit proof.
Halo Family/Halo Family/Persistence/FamilyLibraryDirectory.swift
Why it matters. Removal must not require access outside its container.
What to look at. openDirectory / stagingComponent / requireIdentity
Halo Family/Halo Family/Persistence/FamilyRemovalCleanupState.swift
Why it matters. Stale or redirected metadata must not clear undisclosed verification work.
What to look at. init / withMetadataLock / retryCleanup
Tests/HaloPersistenceTests/FamilyRemovalContainerTests.swift
Why it matters. Unrestricted macOS/simulator tests missed the phone storage dependency.
What to look at. containerGrantedWithoutRootReadSupportsDurableVerification
Tests/HaloUITests/FamilyRemovalUITests.swift
Why it matters. Production export, scratch verification and cancellation must cooperate in the native sandbox.
What to look at. testRemovalNeedsVerifiedExternalExportAndCancelsBeforeIntent
No fsync, durable marker, metadata format, owner-lock, selected-document protection or cleanup limit is weakened. Both old root walkers are removed, with one explicit anchor across the complete preflight/export path.
Measured EPERM comes from an isolated confined Mac process. The native case uses the real simulator host container and a unique bounded synthetic library. Neither establishes physical App Group behavior, live file-provider transport or CloudKit removal.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | Storage authority | Preflight and staging open filesystem root despite granted library access. | Retain and propagate the host-library capability with no-follow feature traversal. |
| major | Regression coverage | Unrestricted test paths do not expose denied ancestor access. | Confined production red/green and actual native container export/cancel/relaunch check. |
| minor | Error diagnostics | Generic storage error loses the failed operation and errno. | Bounded stage/POSIX diagnostics without paths or contents. |
Source: local run at 2026-10-14T11:16:48.908105+00:00 · snapshot a06b95d5d59fd1c9285a666a4443c5ac8253d7ec
Baseline: none
Execution: passed · JUnit: 2 files · Coverage: 1 file · Baseline: absent
Coverage scope: as the project configures it
Totals: 142 passed · 0 failed · 1 skipped · 0 errored · 0 flaky
Derived by declaration name, from the diff (no baseline run).
Aggregate diff coverage: 78% (218 of 281 measurable added lines).
Head 34.2% (9325 of 27285 lines)
9 of 13 changed files matched coverage data.
CHANGELOG.md — no candidateTests/HaloUITests/FamilyRemovalUITests.swift — no candidatedocs/halo_family_design_pack/10-initial-implementation-results.md — no candidatespecs/bugfixes/ios-container-verification-storage/report.md — no candidateFiles that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base 4b36ffaeb0c5a855dfe483c9e7c97274bef51e43.
13 files: 10 code · 3 docs. Click to expand.
diff --git a/Halo Family/Halo Family/Persistence/BackupRepository.swift b/Halo Family/Halo Family/Persistence/BackupRepository.swiftindex 7916894..fc3f0ff 100644--- a/Halo Family/Halo Family/Persistence/BackupRepository.swift +++ b/Halo Family/Halo Family/Persistence/BackupRepository.swift @@ -125,7 +125,7 @@ final class BackupRepository { let draft = try drafts.open(family: supplement.family) do { try await Task.detached { try cleanup.recordFailure(family: supplement.family, operationID: operationID) }.value- let staging = try RemovalVerificationStaging(root: root, operationID: operationID)+ let staging = try RemovalVerificationStaging(root: root, operationID: operationID, library: operations.library) do { let archive = try await exportArchive(familyID: familyID, readable: true, supplement: supplement, staging: staging) return PreparedRemovalExport(archive: archive, supplement: supplement, staging: staging,@@ -151,10 +151,11 @@ final class BackupRepository { throw BackupError.changed } }- try FamilyRemovalArchive.requireExternalDocument(selectedFile, prepared: preparedExport, stagingRoot: stagingRoot) guard let operations = stack.access.familyOperations, let drafts = stack.access.familyDrafts else { throw FamilyOperationError.invalidMetadata }+ try FamilyRemovalArchive.requireExternalDocument(selectedFile, prepared: preparedExport,+ stagingRoot: stagingRoot, library: operations.library) let cleanup = try FamilyRemovalCleanupState(operations: operations, stagingRoot: stagingRoot) let draft = try drafts.open(family: expected.supplement.family) defer { try? drafts.close(draft) }@@ -164,10 +165,11 @@ final class BackupRepository { let cancellation = BackupCancellation() let task = Task.detached { try cleanup.recordFailure(family: expected.supplement.family, operationID: operationID)- let staging = try RemovalVerificationStaging(root: stagingRoot, operationID: operationID)+ let staging = try RemovalVerificationStaging(root: stagingRoot, operationID: operationID, library: operations.library) let result = Result { try FamilyRemovalArchive.coordinatedRead(selectedFile, coordination: coordination) { coordinated in try FamilyRemovalArchive.requireExternalDocument(coordinated, prepared: preparedExport,- stagingRoot: stagingRoot, verification: staging)+ stagingRoot: stagingRoot,+ library: operations.library, verification: staging) try cancellation.check() let before = try FamilyRemovalArchive.measure(coordinated, check: cancellation.check) let preview = try Self.readPreview(coordinated, model: model, payloadLimit: payloadLimit)
diff --git a/Halo Family/Halo Family/Persistence/FamilyLibraryDirectory.swift b/Halo Family/Halo Family/Persistence/FamilyLibraryDirectory.swiftnew file mode 100644index 0000000..8ac9ba3--- /dev/null+++ b/Halo Family/Halo Family/Persistence/FamilyLibraryDirectory.swift @@ -0,0 +1,109 @@+import Darwin+import Foundation++nonisolated enum RemovalStorageStage: String, Sendable {+ case libraryOpen = "library access"+ case directoryOpen = "verification directory access"+ case directoryCreate = "verification directory creation"+ case directoryInspect = "verification directory inspection"+}++/// Authority comes from the host's trusted store-library URL, never from a selected+/// document or an arbitrary staging parent. Pin that root; walk feature names no-follow.+nonisolated final class FamilyLibraryDirectory: @unchecked Sendable {+ let directory: URL+ private let descriptor: Int32++ init(trustedRoot: URL) throws {+ guard trustedRoot.isFileURL, trustedRoot.query == nil, trustedRoot.fragment == nil,+ trustedRoot.path != "/" else { throw RemovalArchiveError.unsafeStaging }+ let resolved = trustedRoot.resolvingSymlinksInPath()+ let opened = open(Self.fileSystemPath(resolved), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)+ guard opened >= 0 else { throw RemovalArchiveError.storageFailure(stage: .libraryOpen, code: errno) }+ do { try Self.requireOwnedDirectory(opened) } catch { close(opened); throw error }+ directory = URL(fileURLWithPath: Self.fileSystemPath(resolved), isDirectory: true)+ descriptor = opened+ }++ deinit { close(descriptor) }++ /// System aliases can differ in Foundation spelling; feature links are never resolved here.+ static func fileSystemPath(_ url: URL) -> String {+ let path = url.standardizedFileURL.path+ if path == "/tmp" || path.hasPrefix("/tmp/") || path == "/var" || path.hasPrefix("/var/") {+ return "/private" + path+ }+ return path+ }++ static func validComponent(_ value: String) -> Bool {+ !value.isEmpty && value != "." && value != ".." && value.utf8.count <= 64 &&+ !value.utf8.contains(0) && !value.contains("/")+ }++ func stagingComponent(for root: URL) throws -> String {+ guard root.isFileURL, root.query == nil, root.fragment == nil else { throw RemovalArchiveError.unsafeStaging }+ let literal = URL(fileURLWithPath: Self.fileSystemPath(root), isDirectory: true)+ guard literal.deletingLastPathComponent().path == directory.path,+ Self.validComponent(literal.lastPathComponent) else { throw RemovalArchiveError.unsafeStaging }+ return literal.lastPathComponent+ }++ /// Reopen the granted library itself, not '/', and reject replacement of its pinned identity.+ func openDirectory(relativePath: [String] = [], createLeaf: Bool = false) throws -> Int32 {+ guard relativePath.allSatisfy(Self.validComponent) else { throw RemovalArchiveError.unsafeStaging }+ var current = open(directory.path, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)+ guard current >= 0 else { throw RemovalArchiveError.storageFailure(stage: .libraryOpen, code: errno) }+ do {+ try Self.requireOwnedDirectory(current)+ guard Self.sameIdentity(current, descriptor) else { throw RemovalArchiveError.unsafeStaging }+ for (index, name) in relativePath.enumerated() {+ let child = try Self.openChild(name, in: current, create: createLeaf && index == relativePath.count - 1)+ close(current)+ current = child+ }+ return current+ } catch { close(current); throw error }+ }++ func requireIdentity(relativePath: [String], matching original: Int32) throws {+ let current = try openDirectory(relativePath: relativePath)+ defer { close(current) }+ guard Self.sameIdentity(current, original) else { throw RemovalArchiveError.unsafeStaging }+ }++ private static func openChild(_ name: String, in parent: Int32, create: Bool) throws -> Int32 {+ var opened = openat(parent, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)+ if opened < 0, errno == ENOENT, create {+ if mkdirat(parent, name, 0o700) != 0, errno != EEXIST {+ throw RemovalArchiveError.storageFailure(stage: .directoryCreate, code: errno)+ }+ opened = openat(parent, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)+ }+ guard opened >= 0 else { throw RemovalArchiveError.storageFailure(stage: .directoryOpen, code: errno) }+ do {+ try requireOwnedDirectory(opened)+ var named = stat(), actual = stat()+ guard fstatat(parent, name, &named, AT_SYMLINK_NOFOLLOW) == 0, fstat(opened, &actual) == 0 else {+ throw RemovalArchiveError.storageFailure(stage: .directoryInspect, code: errno)+ }+ guard named.st_dev == actual.st_dev, named.st_ino == actual.st_ino,+ named.st_mode == actual.st_mode else { throw RemovalArchiveError.unsafeStaging }+ return opened+ } catch { close(opened); throw error }+ }++ private static func requireOwnedDirectory(_ opened: Int32) throws {+ var status = stat()+ guard fstat(opened, &status) == 0 else {+ throw RemovalArchiveError.storageFailure(stage: .directoryInspect, code: errno)+ }+ guard status.st_mode & S_IFMT == S_IFDIR, status.st_uid == getuid() else { throw RemovalArchiveError.unsafeStaging }+ }++ private static func sameIdentity(_ first: Int32, _ second: Int32) -> Bool {+ var lhs = stat(), rhs = stat()+ return fstat(first, &lhs) == 0 && fstat(second, &rhs) == 0 &&+ lhs.st_dev == rhs.st_dev && lhs.st_ino == rhs.st_ino && lhs.st_mode == rhs.st_mode+ }+}
diff --git a/Halo Family/Halo Family/Persistence/FamilyOperationAccess.swift b/Halo Family/Halo Family/Persistence/FamilyOperationAccess.swiftindex bf259f6..a44956e 100644--- a/Halo Family/Halo Family/Persistence/FamilyOperationAccess.swift +++ b/Halo Family/Halo Family/Persistence/FamilyOperationAccess.swift @@ -134,16 +134,19 @@ nonisolated private final class FamilyFileLease: @unchecked Sendable { nonisolated final class FamilyOperationAccess: @unchecked Sendable { let directory: URL let namespace: String+ let library: FamilyLibraryDirectory private let descriptor: Int32 private let managerID = UUID() private static let metadataLimit = 65_536 init(directory: URL, namespace: String) throws { guard !namespace.isEmpty, namespace.utf8.count <= 256 else { throw FamilyOperationError.invalidMetadata }- let opened = try Self.openDirectory(in: directory, namespace: namespace)+ let library = try FamilyLibraryDirectory(trustedRoot: directory)+ let opened = try Self.openDirectory(in: library, namespace: namespace) self.directory = opened.0 descriptor = opened.1 self.namespace = namespace+ self.library = library } deinit { close(descriptor) }@@ -163,23 +166,24 @@ nonisolated final class FamilyOperationAccess: @unchecked Sendable { func ledgerURL(for family: FamilyAccessID) -> URL { directory.appendingPathComponent(key(family) + ".json") } func leaseURL(for family: FamilyAccessID) -> URL { directory.appendingPathComponent(key(family) + ".lock") } - private static func openDirectory(in base: URL, namespace: String) throws -> (URL, Int32) {- // Resolve the trusted library root once; feature-owned descendants must never be symlinks.- let base = base.resolvingSymlinksInPath()- let parent = open(base.path, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)- guard parent >= 0 else { throw FamilyOperationError.invalidMetadata }- defer { close(parent) }- func child(_ name: String, in parent: Int32) throws -> Int32 {- if mkdirat(parent, name, 0o700) != 0, errno != EEXIST { throw FamilyOperationError.invalidMetadata }- let opened = openat(parent, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)- guard opened >= 0 else { throw FamilyOperationError.invalidMetadata }- return opened- }- let operations = try child("FamilyOperations", in: parent)+ private static func openDirectory(in library: FamilyLibraryDirectory, namespace: String) throws -> (URL, Int32) {+ let operations = try library.openDirectory(relativePath: ["FamilyOperations"], createLeaf: true) defer { close(operations) } let namespaceKey = digest(namespace)- let scoped = try child(namespaceKey, in: operations)- return (base.appendingPathComponent("FamilyOperations/" + namespaceKey, isDirectory: true), scoped)+ let scoped = try library.openDirectory(relativePath: ["FamilyOperations", namespaceKey], createLeaf: true)+ return (library.directory.appendingPathComponent("FamilyOperations/" + namespaceKey, isDirectory: true), scoped)+ }++ /// Revalidate both named feature ancestors before exposing a descriptor to cleanup metadata.+ func openMetadataDirectory() throws -> Int32 {+ let current = try library.openDirectory(relativePath: ["FamilyOperations", Self.digest(namespace)])+ var original = stat(), actual = stat()+ guard fstat(descriptor, &original) == 0, fstat(current, &actual) == 0,+ original.st_dev == actual.st_dev, original.st_ino == actual.st_ino else {+ close(current)+ throw FamilyOperationError.invalidMetadata+ }+ return current } private func lease(_ family: FamilyAccessID, exclusive: Bool) throws -> FamilyFileLease {
diff --git a/Halo Family/Halo Family/Persistence/FamilyRemovalArchive.swift b/Halo Family/Halo Family/Persistence/FamilyRemovalArchive.swiftindex 2101f87..22b65d7 100644--- a/Halo Family/Halo Family/Persistence/FamilyRemovalArchive.swift +++ b/Halo Family/Halo Family/Persistence/FamilyRemovalArchive.swift @@ -217,10 +217,13 @@ nonisolated struct RemovalDocumentIdentity: Equatable, Sendable { nonisolated enum RemovalArchiveError: LocalizedError { case unsafeStaging, stagingBusy, cleanupFailed, selectedInsideStaging+ case storageFailure(stage: RemovalStorageStage, code: Int32) var errorDescription: String? { switch self { case .unsafeStaging: "Removal verification storage is unavailable. No family data was changed."+ case .storageFailure(let stage, let code):+ "Removal verification storage is unavailable (\(stage.rawValue), POSIX \(code)). No family data was changed." case .stagingBusy: "Another verification owns these temporary files. Wait for it to finish." case .cleanupFailed: "Temporary verification data could not be removed. Removal is unavailable until cleanup succeeds." case .selectedInsideStaging:@@ -254,12 +257,13 @@ nonisolated enum FamilyRemovalArchive { } static func requireExternalDocument(_ document: URL, prepared: PreparedRemovalExport?, stagingRoot: URL,+ library: FamilyLibraryDirectory, verification: RemovalVerificationStaging? = nil) throws { try prepared?.protectSelectedDocumentIfOwned(document) if let verification, isWithin(document, directory: verification.directory) { try verification.preserveSelectedDocument() } let forbidden = [stagingRoot] + (prepared.map { [$0.archive.deletingLastPathComponent().deletingLastPathComponent()] } ?? []) for root in forbidden where isWithin(document, directory: root) {- try RemovalVerificationStaging.preserveRejectedSelection(document, in: root)+ try RemovalVerificationStaging.preserveRejectedSelection(document, in: root, library: library) throw RemovalArchiveError.selectedInsideStaging } }
diff --git a/Halo Family/Halo Family/Persistence/FamilyRemovalCleanupState.swift b/Halo Family/Halo Family/Persistence/FamilyRemovalCleanupState.swiftindex 4e6053d..14da8b1 100644--- a/Halo Family/Halo Family/Persistence/FamilyRemovalCleanupState.swift +++ b/Halo Family/Halo Family/Persistence/FamilyRemovalCleanupState.swift @@ -20,31 +20,30 @@ nonisolated final class FamilyRemovalCleanupState: @unchecked Sendable { private static let metadataLimit = 32_768 static let maximumFailures = 128 private let namespace: String- private let directory: URL+ private let operations: FamilyOperationAccess+ private let libraryAnchor: FamilyLibraryDirectory private let library: URL private let rootComponent: String private let metadataDescriptor: Int32 private let libraryDescriptor: Int32 init(operations: FamilyOperationAccess, stagingRoot: URL) throws {- let directory = URL(fileURLWithPath: Self.fileSystemPath(operations.directory), isDirectory: true)- let library = directory.deletingLastPathComponent().deletingLastPathComponent()- let root = URL(fileURLWithPath: Self.fileSystemPath(stagingRoot), isDirectory: true)- guard stagingRoot.isFileURL, root.deletingLastPathComponent().path == library.path,- Self.validComponent(root.lastPathComponent) else { throw RemovalArchiveError.unsafeStaging }- let metadata = try Self.openDirectory(directory)+ let library = operations.library+ let component = try library.stagingComponent(for: stagingRoot)+ let metadata = try operations.openMetadataDirectory() do {- let parent = try Self.openDirectory(library)+ let parent = try library.openDirectory() do {- if let staging = try Self.openStaging(root.lastPathComponent, in: parent) { close(staging) }+ if let staging = try Self.openStaging(component, in: parent) { close(staging) } } catch { close(parent); throw error } metadataDescriptor = metadata libraryDescriptor = parent } catch { close(metadata); throw error } namespace = operations.namespace- self.directory = directory- self.library = library- rootComponent = root.lastPathComponent+ self.operations = operations+ libraryAnchor = library+ self.library = library.directory+ rootComponent = component } deinit { close(metadataDescriptor); close(libraryDescriptor) }@@ -79,7 +78,7 @@ nonisolated final class FamilyRemovalCleanupState: @unchecked Sendable { let failures = record.failures.filter { $0.rootComponent == component } guard let staging = try Self.openStaging(component, in: libraryDescriptor) else { continue } defer { close(staging) }- _ = try RemovalVerificationStaging.cleanupAbandoned(in: library.appendingPathComponent(component))+ _ = try RemovalVerificationStaging.cleanupAbandoned(in: library.appendingPathComponent(component), library: libraryAnchor) guard Self.sameFile(component, parent: libraryDescriptor, descriptor: staging) else { throw RemovalArchiveError.cleanupFailed }@@ -106,41 +105,11 @@ nonisolated final class FamilyRemovalCleanupState: @unchecked Sendable { !value.utf8.contains(0) && !value.contains("/") } - /// Foundation standardization can return /var or /tmp even for an already resolved URL.- /// Normalize only those established system aliases; feature components are walked no-follow.- private static func fileSystemPath(_ url: URL) -> String {- let path = url.standardizedFileURL.path- if path == "/tmp" || path.hasPrefix("/tmp/") || path == "/var" || path.hasPrefix("/var/") {- return "/private" + path- }- return path- }-- private static func openDirectory(_ directory: URL) throws -> Int32 {- guard directory.isFileURL else { throw RemovalArchiveError.unsafeStaging }- let path = fileSystemPath(directory)- let components = path.split(separator: "/").map(String.init)- var descriptor = open("/", O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)- guard descriptor >= 0 else { throw RemovalArchiveError.unsafeStaging }- for component in components {- let child = openat(descriptor, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)- close(descriptor)- guard child >= 0 else { throw RemovalArchiveError.unsafeStaging }- descriptor = child- }- var status = stat()- guard fstat(descriptor, &status) == 0, status.st_uid == getuid() else {- close(descriptor)- throw RemovalArchiveError.unsafeStaging- }- return descriptor- }- private static func openStaging(_ component: String, in parent: Int32) throws -> Int32? { guard validComponent(component) else { throw FamilyOperationError.invalidMetadata } let opened = openat(parent, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) if opened < 0, errno == ENOENT { return nil }- guard opened >= 0 else { throw RemovalArchiveError.unsafeStaging }+ guard opened >= 0 else { throw RemovalArchiveError.storageFailure(stage: .directoryOpen, code: errno) } var status = stat() guard fstat(opened, &status) == 0, status.st_uid == getuid(), sameFile(component, parent: parent, descriptor: opened) else { close(opened)@@ -163,7 +132,7 @@ nonisolated final class FamilyRemovalCleanupState: @unchecked Sendable { private func withMetadataLock<Value>(_ family: FamilyAccessID, exclusive: Bool, _ operation: () throws -> Value) throws -> Value {- let current = try Self.openDirectory(directory)+ let current = try operations.openMetadataDirectory() defer { close(current) } var original = stat(), actual = stat() guard fstat(metadataDescriptor, &original) == 0, fstat(current, &actual) == 0,
diff --git a/Halo Family/Halo Family/Persistence/RemovalExportStaging.swift b/Halo Family/Halo Family/Persistence/RemovalExportStaging.swiftindex 081d81a..dd1bc25 100644--- a/Halo Family/Halo Family/Persistence/RemovalExportStaging.swift +++ b/Halo Family/Halo Family/Persistence/RemovalExportStaging.swift @@ -67,9 +67,12 @@ nonisolated final class RemovalVerificationStaging: @unchecked Sendable { private let directoryDescriptor: Int32 private let ownerDescriptor: Int32 private let name: String+ private let library: FamilyLibraryDirectory+ private let rootComponent: String - init(root: URL, operationID: UUID) throws {- let descriptor = try Self.openRoot(root, create: true)+ init(root: URL, operationID: UUID, library: FamilyLibraryDirectory) throws {+ let component = try library.stagingComponent(for: root)+ let descriptor = try library.openDirectory(relativePath: [component], createLeaf: true) let name = operationID.uuidString.lowercased() guard mkdirat(descriptor, name, 0o700) == 0 else { close(descriptor)@@ -99,6 +102,8 @@ nonisolated final class RemovalVerificationStaging: @unchecked Sendable { ownerDescriptor = owner self.directory = directory self.operationID = operationID+ self.library = library+ rootComponent = component } deinit {@@ -116,6 +121,7 @@ nonisolated final class RemovalVerificationStaging: @unchecked Sendable { } func requireOwnership() throws {+ try library.requireIdentity(relativePath: [rootComponent], matching: rootDescriptor) guard Self.sameFile(name, parent: rootDescriptor, descriptor: directoryDescriptor), Self.sameFile("owner.lock", parent: directoryDescriptor, descriptor: ownerDescriptor) else { throw RemovalArchiveError.cleanupFailed@@ -130,14 +136,15 @@ nonisolated final class RemovalVerificationStaging: @unchecked Sendable { } /// Rejecting an older owned export must also exclude its exact operation from crash cleanup.- static func preserveRejectedSelection(_ document: URL, in root: URL) throws {+ static func preserveRejectedSelection(_ document: URL, in root: URL, library: FamilyLibraryDirectory) throws { let resolved = document.resolvingSymlinksInPath().standardizedFileURL.path let base = root.resolvingSymlinksInPath().standardizedFileURL.path guard resolved.hasPrefix(base + "/") else { return } let parts = resolved.dropFirst(base.count + 1).split(separator: "/").map(String.init) guard parts.count >= 2, let name = parts.first, let id = UUID(uuidString: name), name == id.uuidString.lowercased() else { throw RemovalArchiveError.unsafeStaging }- let parent = try openRoot(root, create: false)+ let component = try library.stagingComponent(for: root)+ let parent = try library.openDirectory(relativePath: [component]) defer { close(parent) } let child = openat(parent, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) guard child >= 0 else { throw RemovalArchiveError.cleanupFailed }@@ -204,8 +211,9 @@ nonisolated final class RemovalVerificationStaging: @unchecked Sendable { try handle.write(contentsOf: data) } - static func cleanupAbandoned(in root: URL) throws -> [UUID] {- let descriptor = try openRoot(root, create: true)+ static func cleanupAbandoned(in root: URL, library: FamilyLibraryDirectory) throws -> [UUID] {+ let component = try library.stagingComponent(for: root)+ let descriptor = try library.openDirectory(relativePath: [component], createLeaf: true) defer { close(descriptor) } var cleaned: [UUID] = [] for name in try FileManager.default.contentsOfDirectory(atPath: root.path) {@@ -225,6 +233,7 @@ nonisolated final class RemovalVerificationStaging: @unchecked Sendable { let folder = root.appendingPathComponent(name, isDirectory: true) var remaining = 100_000 guard try validateTree(folder, descriptor: child, depth: 0, remaining: &remaining) else { continue }+ try library.requireIdentity(relativePath: [component], matching: descriptor) try clean(folder, descriptor: child) guard sameFile(name, parent: descriptor, descriptor: child) else { throw RemovalArchiveError.cleanupFailed } guard unlinkat(descriptor, name, AT_REMOVEDIR) == 0 else { throw RemovalArchiveError.cleanupFailed }@@ -233,32 +242,6 @@ nonisolated final class RemovalVerificationStaging: @unchecked Sendable { return cleaned } - private static func openRoot(_ root: URL, create: Bool) throws -> Int32 {- guard root.isFileURL else { throw RemovalArchiveError.unsafeStaging }- var path = root.standardizedFileURL.path- // These two aliases are established macOS system paths, not feature-controlled links.- if path.hasPrefix("/tmp/") || path.hasPrefix("/var/") { path = "/private" + path }- let names = path.split(separator: "/").map(String.init)- guard !names.isEmpty else { throw RemovalArchiveError.unsafeStaging }- var descriptor = open("/", O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)- guard descriptor >= 0 else { throw RemovalArchiveError.unsafeStaging }- for (index, name) in names.enumerated() {- var child = openat(descriptor, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)- if child < 0, errno == ENOENT, create, index == names.count - 1,- mkdirat(descriptor, name, 0o700) == 0 {- child = openat(descriptor, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)- }- close(descriptor)- guard child >= 0 else { throw RemovalArchiveError.unsafeStaging }- descriptor = child- }- var status = stat()- guard fstat(descriptor, &status) == 0, status.st_uid == getuid() else {- close(descriptor); throw RemovalArchiveError.unsafeStaging- }- return descriptor- }- private static func validateTree(_ directory: URL, descriptor: Int32, depth: Int, remaining: inout Int) throws -> Bool { let names = try FileManager.default.contentsOfDirectory(atPath: directory.path) remaining -= names.count
diff --git a/Tests/HaloPersistenceTests/FamilyRemovalArchiveTests.swift b/Tests/HaloPersistenceTests/FamilyRemovalArchiveTests.swiftindex 452c5e3..4e18635 100644--- a/Tests/HaloPersistenceTests/FamilyRemovalArchiveTests.swift+++ b/Tests/HaloPersistenceTests/FamilyRemovalArchiveTests.swift@@ -216,11 +216,12 @@ struct FamilyRemovalArchiveTests { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) }+ let library = try FamilyLibraryDirectory(trustedRoot: directory) let root = directory.appendingPathComponent("Verifier")- let active = try RemovalVerificationStaging(root: root, operationID: UUID())+ let active = try RemovalVerificationStaging(root: root, operationID: UUID(), library: library) try Data([1]).write(to: active.directory.appendingPathComponent("Scratch.sqlite")) let abandonedID = UUID()- var abandoned: RemovalVerificationStaging? = try RemovalVerificationStaging(root: root, operationID: abandonedID)+ var abandoned: RemovalVerificationStaging? = try RemovalVerificationStaging(root: root, operationID: abandonedID, library: library) let abandonedDirectory = try #require(abandoned?.directory) try Data([2]).write(to: abandonedDirectory.appendingPathComponent("Scratch.sqlite")) try #require(abandoned).write(Data([2, 4]), to: "payloads/\(UUID().uuidString)/data.bin")@@ -234,7 +235,7 @@ struct FamilyRemovalArchiveTests { try Data([3]).write(to: outside.appendingPathComponent("Keep.bin")) let symlink = root.appendingPathComponent(UUID().uuidString.lowercased()) try FileManager.default.createSymbolicLink(at: symlink, withDestinationURL: outside)- #expect(try RemovalVerificationStaging.cleanupAbandoned(in: root) == [abandonedID])+ #expect(try RemovalVerificationStaging.cleanupAbandoned(in: root, library: library) == [abandonedID]) #expect(FileManager.default.fileExists(atPath: active.directory.path)) #expect(FileManager.default.fileExists(atPath: unrelated.path)) #expect(try Data(contentsOf: outside.appendingPathComponent("Keep.bin")) == Data([3]))@@ -280,8 +281,9 @@ struct FamilyRemovalArchiveTests { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) }+ let library = try FamilyLibraryDirectory(trustedRoot: directory) let root = directory.appendingPathComponent("Verifier")- let stage = try RemovalVerificationStaging(root: root, operationID: UUID())+ let stage = try RemovalVerificationStaging(root: root, operationID: UUID(), library: library) let unknown = stage.directory.appendingPathComponent("Unowned.bin") try Data([4]).write(to: unknown) #expect(throws: RemovalArchiveError.self) { try stage.cleanup() }@@ -290,13 +292,13 @@ struct FamilyRemovalArchiveTests { try stage.cleanup() let link = directory.appendingPathComponent("Linked") try FileManager.default.createSymbolicLink(at: link, withDestinationURL: root)- #expect(throws: RemovalArchiveError.self) { try RemovalVerificationStaging(root: link, operationID: UUID()) }+ #expect(throws: RemovalArchiveError.self) { try RemovalVerificationStaging(root: link, operationID: UUID(), library: library) } #expect(throws: RemovalArchiveError.self) {- try RemovalVerificationStaging(root: link.appendingPathComponent("Nested"), operationID: UUID())+ try RemovalVerificationStaging(root: link.appendingPathComponent("Nested"), operationID: UUID(), library: library) } let outside = directory.appendingPathComponent("Outside") try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: false)- let unsafe = try RemovalVerificationStaging(root: root, operationID: UUID())+ let unsafe = try RemovalVerificationStaging(root: root, operationID: UUID(), library: library) let payloadLink = unsafe.directory.appendingPathComponent("payloads") try FileManager.default.createSymbolicLink(at: payloadLink, withDestinationURL: outside) #expect(throws: RemovalArchiveError.self) {@@ -373,6 +375,7 @@ struct FamilyRemovalArchiveTests { @Test func ownedLocationRejectionPreservesSelectedBytesAcrossFailureAndLaterCleanup() async throws { try await withStore { stack, graph, directory in+ let library = try #require(stack.access.familyOperations).library let family = try graph.createFamily(name: "Synthetic location") let uuid = try #require(try graph.readable(family, entity: "FamilySpace").value(forKey: "id") as? UUID) let service = BackupRepository(stack: stack), coverage = supplement(uuid, in: stack)@@ -391,10 +394,10 @@ struct FamilyRemovalArchiveTests { #expect(throws: RemovalArchiveError.self) { try prepared?.discard() } prepared = nil let preparedRoot = archive.deletingLastPathComponent().deletingLastPathComponent()- #expect(try RemovalVerificationStaging.cleanupAbandoned(in: preparedRoot).isEmpty)+ #expect(try RemovalVerificationStaging.cleanupAbandoned(in: preparedRoot, library: library).isEmpty) #expect(try Data(contentsOf: selected) == bytes) - let owned = try RemovalVerificationStaging(root: verifierRoot, operationID: UUID())+ let owned = try RemovalVerificationStaging(root: verifierRoot, operationID: UUID(), library: library) let verifierSelection = owned.directory.appendingPathComponent("Scratch.sqlite") try bytes.write(to: verifierSelection) await #expect(throws: RemovalArchiveError.self) {@@ -405,7 +408,7 @@ struct FamilyRemovalArchiveTests { // The identical guard also handles a coordinator-supplied URL inside its active operation. #expect(throws: RemovalArchiveError.self) { try FamilyRemovalArchive.requireExternalDocument(verifierSelection, prepared: nil,- stagingRoot: verifierRoot, verification: owned)+ stagingRoot: verifierRoot, library: library, verification: owned) } #expect(throws: RemovalArchiveError.self) { try owned.cleanup() } #expect(try Data(contentsOf: verifierSelection) == bytes)@@ -423,6 +426,7 @@ struct FamilyRemovalArchiveTests { @Test func parentSymlinkIntoPreparedExportIsRejectedAndSelectedBytesSurviveCleanup() async throws { try await withStore { stack, graph, directory in+ let library = try #require(stack.access.familyOperations).library let family = try graph.createFamily(name: "Synthetic alias") let id = try #require(try graph.readable(family, entity: "FamilySpace").value(forKey: "id") as? UUID) let service = BackupRepository(stack: stack), coverage = supplement(id, in: stack)@@ -439,7 +443,7 @@ struct FamilyRemovalArchiveTests { #expect(throws: RemovalArchiveError.self) { try prepared?.discard() } prepared = nil #expect(try RemovalVerificationStaging.cleanupAbandoned(in: archive.deletingLastPathComponent()- .deletingLastPathComponent()).isEmpty)+ .deletingLastPathComponent(), library: library).isEmpty) #expect(try Data(contentsOf: selected) == bytes) } }@@ -448,16 +452,17 @@ struct FamilyRemovalArchiveTests { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) }+ let library = try FamilyLibraryDirectory(trustedRoot: directory) let root = directory.appendingPathComponent("Verifier")- var owned: RemovalVerificationStaging? = try RemovalVerificationStaging(root: root, operationID: UUID())+ var owned: RemovalVerificationStaging? = try RemovalVerificationStaging(root: root, operationID: UUID(), library: library) let selected = try #require(owned?.directory).appendingPathComponent("Halo Family Backup.zip") let bytes = Data("synthetic selected export".utf8) try owned?.write(bytes, to: selected.lastPathComponent) owned = nil #expect(throws: RemovalArchiveError.self) {- try FamilyRemovalArchive.requireExternalDocument(selected, prepared: nil, stagingRoot: root)+ try FamilyRemovalArchive.requireExternalDocument(selected, prepared: nil, stagingRoot: root, library: library) }- #expect(try RemovalVerificationStaging.cleanupAbandoned(in: root).isEmpty)+ #expect(try RemovalVerificationStaging.cleanupAbandoned(in: root, library: library).isEmpty) #expect(try Data(contentsOf: selected) == bytes) }
diff --git a/Tests/HaloPersistenceTests/FamilyRemovalCleanupTests.swift b/Tests/HaloPersistenceTests/FamilyRemovalCleanupTests.swiftindex cb7fed1..a51f7b8 100644--- a/Tests/HaloPersistenceTests/FamilyRemovalCleanupTests.swift+++ b/Tests/HaloPersistenceTests/FamilyRemovalCleanupTests.swift@@ -113,17 +113,19 @@ struct FamilyRemovalCleanupTests { try withDirectory { _, operations, root in let family = FamilyAccessID(family: UUID(), shared: false) let state = try FamilyRemovalCleanupState(operations: operations, stagingRoot: root)- let active = try RemovalVerificationStaging(root: root, operationID: UUID())+ let active = try RemovalVerificationStaging(root: root, operationID: UUID(), library: operations.library) try active.write(Data([1]), to: "Scratch.sqlite") try state.recordFailure(family: family, operationID: active.operationID)- var protected: RemovalVerificationStaging? = try RemovalVerificationStaging(root: root, operationID: UUID())+ var protected: RemovalVerificationStaging? = try RemovalVerificationStaging(root: root, operationID: UUID(),+ library: operations.library) let selected = try #require(protected?.directory).appendingPathComponent("Halo Family Backup.zip") let selectedBytes = Data("synthetic selected bytes".utf8) try protected?.write(selectedBytes, to: selected.lastPathComponent) try protected?.preserveSelectedDocument() try state.recordFailure(family: family, operationID: try #require(protected?.operationID)) protected = nil- var unknown: RemovalVerificationStaging? = try RemovalVerificationStaging(root: root, operationID: UUID())+ var unknown: RemovalVerificationStaging? = try RemovalVerificationStaging(root: root, operationID: UUID(),+ library: operations.library) let unknownDirectory = try #require(unknown?.directory), unknownID = try #require(unknown?.operationID) let sentinel = unknownDirectory.appendingPathComponent("Keep-unknown.bin") try Data([7, 9]).write(to: sentinel)@@ -146,7 +148,8 @@ struct FamilyRemovalCleanupTests { let state = try FamilyRemovalCleanupState(operations: operations, stagingRoot: root) let operationID = UUID() try state.recordFailure(family: family, operationID: operationID)- var abandoned: RemovalVerificationStaging? = try RemovalVerificationStaging(root: root, operationID: operationID)+ var abandoned: RemovalVerificationStaging? = try RemovalVerificationStaging(root: root, operationID: operationID,+ library: operations.library) let folder = try #require(abandoned?.directory) try abandoned?.write(Data([1, 3]), to: "Scratch.sqlite") try abandoned?.write(Data([2, 4]), to: "payloads/\(UUID().uuidString)/data.bin")@@ -173,7 +176,8 @@ struct FamilyRemovalCleanupTests { let canonical = try FamilyRemovalCleanupState(operations: operations, stagingRoot: root) let family = FamilyAccessID(family: UUID(), shared: false), operationID = UUID() try original.recordFailure(family: family, operationID: operationID)- var abandoned: RemovalVerificationStaging? = try RemovalVerificationStaging(root: injectedRoot, operationID: operationID)+ var abandoned: RemovalVerificationStaging? = try RemovalVerificationStaging(root: injectedRoot, operationID: operationID,+ library: operations.library) let folder = try #require(abandoned?.directory), sentinel = folder.appendingPathComponent("Keep-unknown.bin") try abandoned?.write(Data([1]), to: "Scratch.sqlite") try Data([2]).write(to: sentinel)
diff --git a/Tests/HaloPersistenceTests/FamilyRemovalContainerTests.swift b/Tests/HaloPersistenceTests/FamilyRemovalContainerTests.swiftnew file mode 100644index 0000000..2b880f2--- /dev/null+++ b/Tests/HaloPersistenceTests/FamilyRemovalContainerTests.swift@@ -0,0 +1,138 @@+import Darwin+import Foundation+import Testing+@testable import HaloPersistence++// Test-process-only confinement, applied after runtime startup. Never linked into the host.+@_silgen_name("sandbox_init")+private func confineRootRead(_ profile: UnsafePointer<CChar>, _ flags: UInt64,+ _ error: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?) -> Int32++struct FamilyRemovalContainerTests {+ @Test(.enabled(if: ProcessInfo.processInfo.environment["HALO_DENY_ROOT_READ"] == "1"))+ @MainActor func containerGrantedWithoutRootReadSupportsDurableVerification() async throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ let stack = try PersistenceStack(directory: directory), graph = FamilyRepository(stack: stack)+ let selectedFamily = try graph.createFamily(name: "Synthetic selected")+ _ = try graph.addChild(name: "Synthetic child", familyID: selectedFamily)+ _ = try graph.createFamily(name: "Synthetic retained")+ let operations = try #require(stack.access.familyOperations)+ let root = directory.appendingPathComponent("RemovalVerification")+ let progress = directory.appendingPathComponent("OnboardingProgress-v1.json"), sentinel = Data([8, 4, 2])+ try sentinel.write(to: progress)+ // Tighten only this isolated test process; the container remains accessible.+ #expect(confineRootRead("(version 1)(allow default)(deny file-read-data (literal \"/\"))", 0, nil) == 0)+ let denied = open("/", O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ let denial = errno+ if denied >= 0 { close(denied) }+ #expect(denied == -1 && denial == EPERM)+ let granted = open(directory.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ #expect(granted >= 0)+ if granted >= 0 { close(granted) }+ // Regression: real production preflight previously opened '/' and threw unsafeStaging.+ let state = try FamilyRemovalCleanupState(operations: operations, stagingRoot: root)+ let family = FamilyAccessID(family: UUID(), shared: false), operationID = UUID()+ try state.recordFailure(family: family, operationID: operationID)+ var staging: RemovalVerificationStaging? = try RemovalVerificationStaging(root: root, operationID: operationID,+ library: operations.library)+ try staging?.write(Data([1, 2, 3]), to: "family.json")+ #expect(throws: RemovalArchiveError.self) { try state.requireClear(family: family) }+ staging = nil+ #expect(try state.retryCleanup(family: family))+ let reopened = try FamilyRemovalCleanupState(operations: operations, stagingRoot: root)+ try reopened.requireClear(family: family)+ // Exercise the remaining real preflight/export/readback/scratch/discard path under that grant.+ let coordinator = try FamilyRemovalCoordinator(stack: stack)+ let supplement = try await coordinator.exportSupplement(familyID: selectedFamily)+ let backup = BackupRepository(stack: stack)+ let expected = try await backup.removalSnapshot(familyID: selectedFamily, supplement: supplement)+ let prepared = try await backup.prepareForRemoval(familyID: selectedFamily, supplement: supplement)+ let selected = directory.appendingPathComponent("Chosen.zip")+ try FileManager.default.copyItem(at: prepared.archive, to: selected)+ let selectedBytes = try Data(contentsOf: selected)+ let verified = try await backup.verifyRemovalExport(selectedFile: selected, expected: expected,+ stagingRoot: root, operationID: UUID(), preparedExport: prepared)+ #expect(verified.datasetFingerprint == expected.datasetFingerprint)+ #expect(prepared.isDiscarded)+ verified.documentAccess.close()+ let cancelled = try await backup.prepareForRemoval(familyID: selectedFamily, supplement: supplement)+ try cancelled.discard()+ let freshOperations = try FamilyOperationAccess(directory: directory, namespace: operations.namespace)+ let fresh = try FamilyRemovalCleanupState(operations: freshOperations, stagingRoot: root)+ try fresh.requireClear(family: supplement.family)+ #expect(try FileManager.default.contentsOfDirectory(atPath: root.path).isEmpty)+ #expect(try Data(contentsOf: selected) == selectedBytes)+ #expect(try Data(contentsOf: progress) == sentinel)+ #expect(try graph.families().count == 2)+ }++ @Test func retainedLibraryRejectsReplacementWithoutChangingEitherDirectory() throws {+ let fixture = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ let directory = fixture.appendingPathComponent("Library"), moved = fixture.appendingPathComponent("Original")+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: fixture) }+ let library = try FamilyLibraryDirectory(trustedRoot: directory)+ try FileManager.default.moveItem(at: directory, to: moved)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)+ let sentinel = directory.appendingPathComponent("Keep.bin"), bytes = Data([9, 3])+ try bytes.write(to: sentinel)+ #expect(throws: RemovalArchiveError.self) { try library.openDirectory(relativePath: ["RemovalVerification"], createLeaf: true) }+ #expect(try Data(contentsOf: sentinel) == bytes)+ #expect(try FileManager.default.contentsOfDirectory(atPath: moved.path).isEmpty)+ #expect(!FileManager.default.fileExists(atPath: directory.appendingPathComponent("RemovalVerification").path))+ }++ @Test func replacedFeatureAncestorCannotRedirectCleanupMetadata() throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)+ defer { try? FileManager.default.removeItem(at: directory) }+ let operations = try FamilyOperationAccess(directory: directory, namespace: "synthetic")+ let state = try FamilyRemovalCleanupState(operations: operations,+ stagingRoot: directory.appendingPathComponent("RemovalVerification"))+ let family = FamilyAccessID(family: UUID(), shared: false)+ try state.recordFailure(family: family, operationID: UUID())+ let original = directory.appendingPathComponent("FamilyOperations"), moved = directory.appendingPathComponent("Original")+ try FileManager.default.moveItem(at: original, to: moved)+ try FileManager.default.createSymbolicLink(at: original, withDestinationURL: moved)+ let files = try FileManager.default.contentsOfDirectory(at: operations.directory.resolvingSymlinksInPath(),+ includingPropertiesForKeys: nil)+ let before = try files.map { try Data(contentsOf: $0) }+ #expect(throws: RemovalArchiveError.self) { try state.retryCleanup(family: family) }+ #expect(try files.map { try Data(contentsOf: $0) } == before)+ }++ @Test func retainedStagingRejectsReplacedRootAndPreservesScratch() throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)+ defer { try? FileManager.default.removeItem(at: directory) }+ let library = try FamilyLibraryDirectory(trustedRoot: directory)+ let root = directory.appendingPathComponent("Verifier"), moved = directory.appendingPathComponent("Original")+ let stage = try RemovalVerificationStaging(root: root, operationID: UUID(), library: library)+ let bytes = Data([7, 5])+ try stage.write(bytes, to: "family.json")+ try FileManager.default.moveItem(at: root, to: moved)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false)+ #expect(throws: RemovalArchiveError.self) { try stage.write(Data([1]), to: "removal.json") }+ #expect(throws: RemovalArchiveError.self) { try stage.cleanup() }+ #expect(try Data(contentsOf: moved.appendingPathComponent(stage.operationID.uuidString.lowercased() + "/family.json")) == bytes)+ #expect(try FileManager.default.contentsOfDirectory(atPath: root.path).isEmpty)+ }++ @Test func storageDiagnosticCarriesStageAndErrnoWithoutPrivatePaths() throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)+ defer { try? FileManager.default.removeItem(at: directory) }+ let library = try FamilyLibraryDirectory(trustedRoot: directory)+ do {+ let opened = try library.openDirectory(relativePath: ["Missing"])+ close(opened)+ Issue.record("Absent verification directory must fail closed")+ } catch RemovalArchiveError.storageFailure(let stage, let code) {+ #expect(stage == .directoryOpen && code == ENOENT)+ let description = RemovalArchiveError.storageFailure(stage: stage, code: code).localizedDescription+ #expect(description.contains("POSIX \(ENOENT)"))+ #expect(!description.contains(directory.path) && !description.contains(directory.lastPathComponent))+ }+ }+}
diff --git a/Tests/HaloUITests/FamilyRemovalUITests.swift b/Tests/HaloUITests/FamilyRemovalUITests.swiftindex cca374b..c8b42ee 100644--- a/Tests/HaloUITests/FamilyRemovalUITests.swift+++ b/Tests/HaloUITests/FamilyRemovalUITests.swift@@ -30,6 +30,7 @@ extension WorkspaceUITests { } @MainActor func testRemovalNeedsVerifiedExternalExportAndCancelsBeforeIntent() {+ executionTimeAllowance = 120 let app = launchRemoval() openRemoval(in: app) XCTAssertFalse(app.buttons["removal.confirm"].exists)@@ -39,6 +40,17 @@ extension WorkspaceUITests { tap(app.buttons["settings.done"]) XCTAssertTrue(app.buttons["home.child.Avery"].waitForExistence(timeout: 10)) XCTAssertTrue(app.buttons["home.child.Jamie"].exists)+ // Same actual host-container library after restart: durable verification cleanup+ // must allow another export/readback/cancellation while preserving both families.+ let arguments = app.launchArguments+ app.terminate(); app.launchArguments = arguments; app.launch()+ openRemoval(in: app)+ XCTAssertFalse(app.buttons["removal.confirm"].exists)+ verifyRemovalDocument(in: app)+ tap(app.buttons["removal.cancel"])+ tap(app.buttons["settings.done"])+ XCTAssertTrue(app.buttons["home.child.Avery"].waitForExistence(timeout: 10))+ XCTAssertTrue(app.buttons["home.child.Jamie"].exists) app.terminate() }
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f3fe4b7..a13265b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,16 @@ ### Changed +- Record confined and actual native-container verification of the storage correction,+ preserved signing/model identity and the prepared, uninstalled optimized Release.++- Anchor removal verification storage at the granted library rather than filesystem+ root, retaining durable metadata and no-follow identity checks; report bounded+ storage-stage/POSIX errors and cover confined export, cleanup and relaunch.++- Reproduce removal verification's unnecessary filesystem-root access in a confined+ synthetic process using the real durable cleanup and staging helpers.+ - Record the separately authorized in-place signature-fix installation from a827fcb with unchanged package/signing/model identity, reusing the verified Release.
diff --git a/docs/halo_family_design_pack/10-initial-implementation-results.md b/docs/halo_family_design_pack/10-initial-implementation-results.mdindex 0ecd43d..b365407 100644--- a/docs/halo_family_design_pack/10-initial-implementation-results.md+++ b/docs/halo_family_design_pack/10-initial-implementation-results.md@@ -1,5 +1,51 @@ # Implementation evidence +## Granted-container removal storage correction — 2026-10-14++The phone running installed `a827fcb` passes the prior signature failure but removal+preflight reports “Removal verification storage is unavailable. No family data was+changed.” Both cleanup and staging helpers open `/` and every ancestor despite+already having a granted library. An isolated process restricted after runtime+startup measures root-open `EPERM (1)` with successful container-open; actual production+preflight reproduces `.unsafeStaging`. The phone's actual syscall/errno is unobserved.+The pre-start probe aborted before execution and is excluded from filesystem evidence.++Source `a06b95d` retains an explicit pinned library capability in+`FamilyOperationAccess`; preflight, export, verification, abandoned cleanup and+rejected-document protection use no-follow feature traversal from that root. Named+root/metadata identities are revalidated. No fsync, marker, lock, selected-document+protection or bounded-cleanup requirement changes. Bounded stage/POSIX diagnostics+carry no private paths. Onboarding worktree/progress, parser roles, account namespace,+model, permissions and signing remain unchanged.++Red:1 test/1 suite fails at production preflight after filesystem assertions pass,+1 issue/0 runner errors,0.010s runtime/7.585s driver. Confined green:5/5,0.160s runtime/+9.891s driver, including real coordinator/export/selected-byte readback/scratch+roundtrip/discard/reopen and replacement/progress-preservation negatives. Affected:+138 JUnit entries,137 executed/1 opt-in skip,12 suites,0 failures/errors,6.370s runtime/+8.585s driver. Together these are138 distinct executed IDs/142 executions with four+repeated negatives; the skipped confined case ran separately. Lint0/225, four source+reviews clear. Both sequential native platforms pass323.508s. All245 source inputs+match committed `a06b95d`; earlier611-case evidence retains its historical source.++The actual native host-container synthetic journey repeats preflight/export/readback/+cancellation after relaunch and preserves the existing children:1 case/1 execution+passes76.827s, normal driver completion90.813s, unchanged inputs. No removal confirmation+is exercised. The dedicated CA32CCC6 simulator is returned to Shutdown. The synthetic+library is derived from the host's own temporary directory inside its registered app+container; no production App Group catalog is opened.++Corrected optimized signed Release `a06b95d` passes119.891s, all245 inputs unchanged,+-O/WMO and no DEBUG. Exact installed `a827fcb` signer, profiles, entitlements and model+files match; Development declarations/account namespace are unchanged. Its production+signed host/widget projection passes10/10 in0.010s, driver2.311s. The30-file manifest,+source qualifications and receipts are under `/tmp/halo-storage-regression-20261014`.+**This corrected package is not installed; the phone remains on `a827fcb`.** Physical+App Group acceptance, live document-provider transport and CloudKit behavior remain+pending. No live data read/export/deletion, reset, uninstall, permissions/account/+signing change or onboarding interference occurs. See+[bug report](../../specs/bugfixes/ios-container-verification-storage/report.md).+ ## Physical iOS signature padding correction — 2026-10-14 The user reports that installed combined Release2329a8a rejects the Remove selected
diff --git a/specs/bugfixes/ios-container-verification-storage/report.md b/specs/bugfixes/ios-container-verification-storage/report.mdnew file mode 100644index 0000000..b985341--- /dev/null+++ b/specs/bugfixes/ios-container-verification-storage/report.md@@ -0,0 +1,115 @@+# Bugfix Report: iOS container verification storage++**Date:** 2026-10-14+**Status:** Fixed and verified in source; corrected Release prepared, installation withheld++## Description of the Issue++The phone running signed source `a827fcb` passes signature validation but opening+selected-family removal reports “Removal verification storage is unavailable.+No family data was changed.” No live deletion or diagnostic installation was run.++## Investigation Summary++`FamilyRemovalCleanupState.openDirectory` and+`RemovalVerificationStaging.openRoot` open `/`, then every ancestor of the granted+library. This unnecessarily requires access outside the app container. The existing+`FamilyOperationAccess` instead opens the trusted library directly and traverses+feature descendants with no-follow descriptors.++A disposable process restricted after runtime startup measured `open("/") = -1,+errno = EPERM (1)` while the owned container open succeeded. The real production+cleanup constructor fails in the same confined Swift test. The phone alert does+not expose its actual syscall/errno; this reproduces the concrete code defect+without claiming a measured phone syscall. The earlier pre-start confined probe+aborted before execution and is excluded from filesystem evidence.++## Discovered Root Cause++The two removal storage helpers mistake filesystem-root traversal for confinement+within an already granted library. Simulator and unrestricted macOS tests permit+that extra access and therefore missed the platform dependency.++## Resolution for the Issue++`FamilyLibraryDirectory` pins the host-supplied library and reopens that exact+directory directly, checking its identity before traversing validated feature names+with `openat`/`O_NOFOLLOW`. `FamilyOperationAccess` retains the capability and validates+the complete metadata ancestry before supplying a cleanup descriptor. Preflight,+export, verification, abandoned cleanup and rejected-document protection all use+the explicit anchor. Both filesystem-root walkers are removed.++Staging revalidates its pinned root before writes/cleanup. No-follow links, ownership,+inode checks, failure markers, locks, bounded cleanup, selected-document protection+and every durability sync are preserved. Storage open/create/inspection failures+retain a bounded stage and POSIX errno without private paths or payloads. No selected+document parent grant is added. Resolving an arbitrary staging parent or directly+opening a full metadata path was rejected because it would allow intermediate links.++## Regression Test++`FamilyRemovalContainerTests.containerGrantedWithoutRootReadSupportsDurableVerification`+applies a stricter sandbox only to its isolated test process after startup, proves+root denial and container access, then invokes actual production cleanup/staging.+Run alone with `HALO_DENY_ROOT_READ=1 make test` and+`TEST_FLAGS='--jobs 1 --no-parallel --filter FamilyRemovalContainerTests --xunit-output <isolated-output>'`.++## Verification++- Red: **1 test / 1 suite, 1 failing test / 1 issue, 0 runner errors**, 0.010s+ runtime, 7.585s driver; source inputs unchanged. Failure is `.unsafeStaging` at+ production preflight, after both filesystem assertions passed.+- Receipt: `/tmp/halo-storage-regression-20261014/storage-red-1-receipt.json`.+- Green: **5 executed tests / 1 suite**, 0 failures/errors, 0.160s runtime,+ 9.891s driver, unchanged inputs. The confined case now also exercises coordinator+ preflight, real export, selected-byte readback, scratch roundtrip, discard and+ metadata reopen; both synthetic families, selected export and onboarding sentinel+ remain unchanged. Replacement and sanitized diagnostic negatives also pass.+- Affected: JUnit **138 entries: 137 executed / 1 opt-in skip, 12 suites**,+ 0 failures/errors, 6.370s runtime, 8.585s driver, unchanged inputs. Includes the+ actual installed signed host/widget projection and family admission/draft/removal/+ metadata/archive/cleanup/owner-coordinator coverage. The separately executed+ confined case is not inferred from its skip here.+- Strict lint **0 violations / 225 files**. Initial six wrapping violations were+ corrected; the successful final lint is `storage-fix-lint-2.log`.+- Four independent source reviews found no blocker.+- Both sequential native platforms pass in **323.508s**, 0 build errors and+ unchanged inputs. All **245** test/build input hashes match committed source+ **`a06b95d5d59fd1c9285a666a4443c5ac8253d7ec`**, including the native build started+ before that source commit. See `source-qualification.json`.+- Native UI coverage repeats export, readback, cancellation and preflight across+ relaunch in the same bounded Debug synthetic host-container library. No removal+ confirmation is exercised by that targeted journey.+- That native journey passes **1 distinct case / 1 execution**, **76.827s** runtime,+ **90.813s** driver, normal completion and unchanged inputs. The dedicated+ `CA32CCC6-95B5-49A1-B9F0-EB4945213AE6` simulator is returned to Shutdown. Its+ actual registered app-container path is recorded in `storage-simulator-setup.json`;+ `SyntheticLaunch` derives the unique library from the host's own temporary URL.+- Optimized signed Release **`a06b95d`** passes in **119.891s**, all **245** inputs+ unchanged, `-O`/WMO and no DEBUG. Strict signatures, exact previous certificate,+ byte-identical profiles/entitlements/model files, account namespace and Development+ declarations match the actually installed `a827fcb` baseline. The new candidate's+ production host/widget signature projection passes **10 tests / 1 suite**,+ 0 failures/errors, **0.010s** runtime, **2.311s** driver.+- Candidate: `/tmp/halo-storage-regression-20261014/signed-release/ios/Build/Products/Release-iphoneos/Halo Family.app`.+ `storage-verified-package.json` and `storage-package-manifest.json` retain the+ verification and **30-file** manifest. **Not installed.** Phone remains on `a827fcb`.+- The confined and affected runs together contain **138 distinct executed IDs /+ 142 executions**, four repeated negative cases and one skipped entry whose confined+ case ran separately. Candidate projection and native UI counts are supplementary.+ No repeated broad suite is claimed; the earlier 611-case gate retains its old source.+- Physical App Group preflight/export/verification, live file-provider transport and+ native CloudKit behavior remain unverified. Simulator success is not phone proof.+- No account/signing changes, resets, permissions changes, real-data reads,+ installation or live removal. Onboarding's isolated worktree remains untouched.++## Prevention++Test granted-container operations with denied ancestor reads, as well as actual+native app-container export/verification/cancellation. Report bounded operation and+POSIX errno on filesystem failures without private paths or payloads.++## Related++- Draft PR4: https://github.com/ArjenSchwarz/halo-family/pull/4+- Signature-padding correction remains in this branch; this is a subsequent failure.
Red1/1 fails at production preflight after filesystem assertions pass. Confined green5/5 (0.160s); affected137 executed/1skip in12 suites (6.370s); all unchanged inputs. Platforms pass323.508s; native container1/1 passes76.827s with normal driver completion90.813s. Earlier611-case gate remains qualified to its historical source.
Release source a06b95d has unchanged signer, byte-identical profiles/entitlements/models, Development declarations and account namespace. Candidate host/widget production signature probe passes10/10. No corrected physical installation or live deletion is performed.