field_ios

In-the-field app for Radroots on iOS
git clone https://radroots.dev/git/field_ios.git
Log | Files | Refs | README | LICENSE

TeraHistoricalOwnerTests.swift (7678B)


      1 import Darwin
      2 import Foundation
      3 import RadrootsKit
      4 @testable import TeraApp
      5 import TeraKitBindings
      6 import XCTest
      7 
      8 @MainActor
      9 final class TeraHistoricalOwnerTests: XCTestCase {
     10   func testHistoricalConfigurationMediaAndNativeReceiptKeepTheirOriginalIdentities() async throws {
     11     let fixture = try TeraHistoricalOwnerFixture()
     12     defer { fixture.remove() }
     13     let roots = try fixture.roots()
     14     let configuration = try TeraConfigurationStore(bootstrap: fixture.bootstrap(), roots: roots, clock: .fixed(unixSeconds: 1_700_000_000))
     15     let selected = try await configuration.load()
     16     XCTAssertEqual(selected.bundleIdentifier, try fixture.text(fixture.host, "bundle_identifier"))
     17     XCTAssertEqual(selected.keychainServicePrefix, try fixture.text(fixture.host, "keychain_service_prefix"))
     18     XCTAssertEqual(selected.generation, 1)
     19     let generation = try await configuration.sourceGeneration()
     20     XCTAssertEqual(generation.generationHex, try fixture.generation)
     21     XCTAssertEqual(generation.createdAtUnixMilliseconds, try fixture.number(fixture.host, "generation_created_at_unix_ms"))
     22     let blob = try fixture.blob()
     23     let legacy = try fixture.root.appendingPathComponent(fixture.text(fixture.host, "staged_relative_path"))
     24     let original = try Data(contentsOf: legacy)
     25     try TeraDurableMediaRoots.restoreLegacyBlob(blob, roots: roots)
     26     XCTAssertEqual(try RadrootsAppleFileAccess(roots: roots).readStagedBlob(blob), original)
     27     XCTAssertEqual(try Data(contentsOf: legacy), original)
     28     let store = RadrootsAppleBackgroundTransferStore(roots: roots)
     29     let snapshots = try await store.loadSnapshots()
     30     XCTAssertEqual(snapshots.count, 1)
     31     let snapshot = try XCTUnwrap(snapshots.first)
     32     XCTAssertEqual(snapshot.identifier.rawValue, try fixture.text(fixture.native, "native_identifier"))
     33     XCTAssertEqual(snapshot.state, .awaitingVerification)
     34     XCTAssertEqual(snapshot.request.headers, [:])
     35     XCTAssertEqual(snapshot.request.expectedSourceSHA256, blob.blobID)
     36     try FileManager.default.removeItem(at: roots.temporaryRoot)
     37     try FileManager.default.removeItem(at: roots.cacheRoot)
     38     try TeraDurableMediaRoots.restoreLegacyBlob(blob, roots: roots)
     39     XCTAssertEqual(try RadrootsAppleFileAccess(roots: roots).readStagedBlob(blob), original)
     40     let reopened = try await RadrootsAppleBackgroundTransferStore(roots: roots).loadSnapshots()
     41     XCTAssertEqual(reopened, snapshots)
     42     // Typed historical persistence is read without instantiating an OS driver.
     43   }
     44 
     45   func testInstalledCurrentBinaryReadsAndReopensAllHistoricalAcknowledgedDraftsWithoutSigner() async throws {
     46     let fixture = try TeraHistoricalOwnerFixture()
     47     defer { fixture.remove() }
     48     for _ in 0 ..< 2 {
     49       let runtime = try await fixture.runtime()
     50       try await fixture.assertStatuses(runtime)
     51       let signed = try await runtime.phase1DraftStatus(draftId: String(repeating: "0", count: 31) + "3")
     52       XCTAssertEqual(signed.settlement?.signed, 1)
     53       // The historical owner signed this work and retained pending delivery;
     54       // migration must preserve its original zero local-admission count.
     55       XCTAssertEqual(signed.settlement?.admitted, 0)
     56       XCTAssertEqual(signed.settlement?.pending, 1)
     57       XCTAssertEqual(signed.settlement?.deliveryPlans, 1)
     58       _ = try await runtime.shutdown()
     59     }
     60   }
     61 
     62   func testNativeColdRestoreOfHistoricalOutboxRetainsMediaAndCannotGrantResumeWithoutReview() async throws {
     63     let fixture = try TeraHistoricalOwnerFixture()
     64     defer { fixture.remove() }
     65     let roots = try fixture.roots()
     66     let blob = try fixture.blob()
     67     try TeraDurableMediaRoots.restoreLegacyBlob(blob, roots: roots)
     68     let signer = ComposerForbiddenSigner()
     69     let backup = try await captureHistoricalBackup(fixture, roots: roots, blob: blob, signer: signer)
     70     // This isolated fixture now simulates a fresh process after actual close.
     71     // Production never removes its live PID marker to grant cold admission.
     72     let access = RadrootsAppleFileAccess(roots: roots)
     73     try access.delete(RadrootsFileReference(scope: .data, relativePath: "\(TeraMediaProcessUse.directory)/\(getpid())"))
     74     try FileManager.default.removeItem(at: roots.stagedBlobURL(for: blob))
     75     let store = try FfiRestoreStore(applicationSupportDirectory: roots.dataRoot.path, publicKey: backup.publicKey,
     76                                     sourceGeneration: backup.sourceGeneration, sourceGenerationCreatedAtMs: fixture.number(fixture.host, "generation_created_at_unix_ms"), protectedData: .available)
     77     let request = try FfiRestoreRequest(attemptId: String(repeating: "18", count: 16), backup: backup,
     78                                         requestedAtMs: TeraClock.system.unixMilliseconds(requirePositive: true))
     79     let restorer = try TeraLocalRestoreHost(roots: roots, activeTransfers: { [] }, protectedData: { true })
     80     let guardRecord = try await restorer.restore(store: store, request: request)
     81     XCTAssertEqual(try TeraHistoricalOwnerFixture.hash(access.readStagedBlob(blob)), blob.blobID)
     82     do { _ = try await fixture.runtime(); XCTFail("Ordinary startup must refuse a retained restore guard") } catch {}
     83     let restored = try await TeraRuntime.withHostSignerAndRestoreGuard(store: store,
     84                                                                        hostSigner: TeraGeneratedHostSigner(signer: signer), guard: guardRecord.bytes, localBackups: true)
     85     try await fixture.assertStatuses(restored)
     86     let status = try await restored.applicationRestoreStatus()
     87     XCTAssertEqual(status?.phase, .held)
     88     XCTAssertEqual(status?.targets.count, 4)
     89     do {
     90       _ = try await restored.reviewRestoredWork()
     91       XCTFail("Historical local provenance cannot grant a fresh target review")
     92     } catch {
     93       XCTAssertEqual(TeraGeneratedRuntimeFailure.from(error).code, "restore_reconciliation_required")
     94     }
     95     try await fixture.assertStatuses(restored)
     96     _ = try await restored.shutdown()
     97     let requests = await signer.requests
     98     XCTAssertEqual(requests, 0)
     99   }
    100 
    101   private func captureHistoricalBackup(_ fixture: TeraHistoricalOwnerFixture, roots: RadrootsAppleFileRoots,
    102                                        blob: RadrootsStagedBlobReference, signer: ComposerForbiddenSigner) async throws -> FfiBackupRequest
    103   {
    104     let now = try TeraClock.system.unixMilliseconds(requirePositive: true)
    105     let backup = try FfiBackupRequest(schemaVersion: 1, backupId: String(repeating: "17", count: 16), publicKey: fixture.publicKey,
    106                                       sourceGeneration: fixture.generation, requestedAtUnixMs: now, maximumBytes: 128 * 1024 * 1024)
    107     let host = try TeraLocalBackupHost(roots: roots, publicKey: backup.publicKey, generation: backup.sourceGeneration, protectedData: { true })
    108     try await host.prepare(request: backup)
    109     let runtime = try await TeraRuntime.withHostSignerAndLocalBackups(applicationSupportDirectory: roots.dataRoot.path,
    110                                                                       publicKeyHex: backup.publicKey, sourceGenerationHex: backup.sourceGeneration,
    111                                                                       sourceGenerationCreatedAtUnixMs: fixture.number(fixture.host, "generation_created_at_unix_ms"),
    112                                                                       protectedData: .available, hostSigner: TeraGeneratedHostSigner(signer: signer))
    113     try await fixture.assertStatuses(runtime)
    114     let captured = try await host.capture(runtime: runtime, request: backup)
    115     XCTAssertEqual(captured.media.count, 1)
    116     XCTAssertEqual(captured.media.first?.sha256, blob.blobID)
    117     _ = try await runtime.shutdown()
    118     return backup
    119   }
    120 }