SPB Git

Repository Public

SharedStateTests.swift 18.4 KB 201 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/SPMailSystem/Tests/SPMailSystemTests/SharedStateTests.swift3// Description: What the extensions may show: the app lock as seen from outside the app, widget content per privacy level and lock, the4// redaction applied by the notification service extension, the shared store (container and keychain fallback), the sealed share queue5// (chunked files, truncation, tampering) and the detection of the APNs environment from a provisioning profile.6import Foundation7import Testing8import SPMailCore9@testable import SPMailSystem1011private let mbA = "d4246e1d-0dd3-4922-943f-657ae17d2876", mbB = "ee8fa5c0-2caf-41b6-860f-7e2667e94e0c"12private let t0 = Date(timeIntervalSince1970: 1_800_000_000)1314private func snapshot(_ level: PushPreview) throws -> WidgetSnapshot {15    let recent = try (0..<3).map { i in16        try #require(SearchResult(json: ["mailbox_id": .string(mbA), "email_id": .string("M\(i)"), "thread_id": .string("T\(i)"), "from": [["name": "Jeanne Tremblay", "email": "jeanne@stg.spboucher.ai"]],17                                         "subject": .string("Sujet confidentiel \(i)"), "preview": "aperçu secret", "received_at": .string(ISO8601DateFormatter().string(from: t0.addingTimeInterval(Double(-60 * i)))), "keywords": ["$seen": false]]))18    }19    let reminder = try #require(Reminder(json: ["id": "1", "mailbox_id": .string(mbA), "email_id": "M9", "subject": "Relance secrète", "counterpart": ["name": "Marc", "email": "marc@stg.spboucher.ai"], "due_at": .string(ISO8601DateFormatter().string(from: t0.addingTimeInterval(-3600))), "status": "due"]))20    return WidgetSnapshot(unread: [.init(mailboxId: mbA, address: "a@stg.spboucher.ai", unread: 3), .init(mailboxId: mbB, address: "b@stg.spboucher.ai", unread: 4)], recent: recent, reminders: [reminder], preview: level, generatedAt: t0)21}22private func state(preview: PushPreview = .full, hide: Bool = false, lock: LockSnapshot = LockSnapshot(), signedIn: Bool = true) -> ExtensionState {23    ExtensionState(signedIn: signedIn, preview: preview, hideContent: hide, lock: lock, mailboxes: [.init(id: mbA, address: "a@stg.spboucher.ai", name: "A"), .init(id: mbB, address: "b@stg.spboucher.ai", name: "B")], defaultMailboxId: mbB, baseURL: "https://mail.spboucher.ai", updatedAt: t0)24}2526@Suite struct LockAndRedactionTests {27    @Test func lockSeenFromAnExtension() {28        #expect(!LockSnapshot(enabled: false, locked: true, leftAt: t0).conceals(now: t0.addingTimeInterval(9999)))29        #expect(LockSnapshot(enabled: true, afterMinutes: 5, locked: true).conceals(now: t0))30        // in front: readable; left 4 minutes ago with a 5-minute delay: still readable; 6 minutes: concealed — although the app never ran in between31        #expect(!LockSnapshot(enabled: true, afterMinutes: 5).conceals(now: t0))32        #expect(!LockSnapshot(enabled: true, afterMinutes: 5, leftAt: t0).conceals(now: t0.addingTimeInterval(240)))33        #expect(LockSnapshot(enabled: true, afterMinutes: 5, leftAt: t0).conceals(now: t0.addingTimeInterval(360)))34        // « as soon as the app is left »35        #expect(LockSnapshot(enabled: true, afterMinutes: 0, leftAt: t0).conceals(now: t0) && !LockSnapshot(enabled: true, afterMinutes: 0).conceals(now: t0))36    }3738    @Test func snapshotRedactionByPrivacyLevelAndLock() throws {39        let full = try snapshot(.full)40        // level full: everything written is shown41        guard case .content(let shown) = WidgetContent.resolve(state: state(), snapshot: full, now: t0) else { Issue.record("expected content"); return }42        #expect(shown == full && shown.conversations[0].sender == "Jeanne Tremblay" && shown.conversations[0].subject == "Sujet confidentiel 0" && shown.conversations[0].preview == "aperçu secret")43        // the preference was lowered to `sender` after the snapshot was written: subjects and previews go, senders stay44        guard case .content(let sender) = WidgetContent.resolve(state: state(preview: .sender), snapshot: full, now: t0) else { Issue.record("expected content"); return }45        #expect(sender.previewLevel == "sender" && sender.conversations.allSatisfy { $0.sender == "Jeanne Tremblay" && $0.subject == nil && $0.preview == nil } && sender.reminders.allSatisfy { $0.subject == nil && $0.counterpart == "Marc" })46        #expect(sender.totalUnread == 7 && sender.conversations.map(\.emailId) == full.conversations.map(\.emailId))47        // `none`, or the device switch « hide sender and subject »: counts and opaque identifiers only48        for s in [state(preview: .none), state(hide: true)] {49            guard case .content(let hidden) = WidgetContent.resolve(state: s, snapshot: full, now: t0) else { Issue.record("expected content"); return }50            #expect(hidden.previewLevel == "none" && hidden.conversations.allSatisfy { $0.sender == nil && $0.subject == nil && $0.preview == nil } && hidden.reminders.allSatisfy { $0.subject == nil && $0.counterpart == nil })51            let encoded = String(decoding: try JSONEncoder().encode(hidden), as: UTF8.self)52            #expect(!encoded.contains("Jeanne") && !encoded.contains("confidentiel") && !encoded.contains("secret") && !encoded.contains("Marc") && hidden.totalUnread == 7 && hidden.remindersDue == 1)53        }54        // a level is never raised: a snapshot written at `sender` shows no subject even if the preference says `full` now55        guard case .content(let still) = WidgetContent.resolve(state: state(preview: .full), snapshot: try snapshot(.sender), now: t0) else { Issue.record("expected content"); return }56        #expect(still.conversations.allSatisfy { $0.subject == nil && $0.sender != nil })57        // locked, or would be locked if opened now: nothing of the snapshot at all58        #expect(WidgetContent.resolve(state: state(lock: LockSnapshot(enabled: true, locked: true)), snapshot: full, now: t0) == .locked)59        #expect(WidgetContent.resolve(state: state(lock: LockSnapshot(enabled: true, afterMinutes: 1, leftAt: t0)), snapshot: full, now: t0.addingTimeInterval(120)) == .locked)60        if case .content = WidgetContent.resolve(state: state(lock: LockSnapshot(enabled: true, afterMinutes: 1, leftAt: t0)), snapshot: full, now: t0.addingTimeInterval(30)) {} else { Issue.record("expected content before the delay") }61        // signed out, never written, or a state without snapshot62        #expect(WidgetContent.resolve(state: nil, snapshot: full, now: t0) == .signedOut && WidgetContent.resolve(state: state(signedIn: false), snapshot: full, now: t0) == .signedOut && WidgetContent.resolve(state: state(), snapshot: nil, now: t0) == .signedOut)63    }6465    @Test func notificationRedaction() {66        let full = NotificationText(title: "Alice Martin", subtitle: "Budget 2027", body: "Voici les chiffres…")67        func r(_ s: ExtensionState?, kind: NotificationPayload.Kind = .new, french: Bool = true, now: Date = t0) -> NotificationText? { NotificationRedactor.redact(full, kind: kind, state: s, french: french, now: now) }68        #expect(r(state()) == nil)69        #expect(r(state(preview: .sender)) == NotificationText(title: "Alice Martin", body: "Nouveau message"))70        #expect(r(state(preview: .none)) == NotificationText(title: "SP Mail", body: "Nouveau message") && r(state(hide: true)) == r(state(preview: .none)))71        // locked: no sender, no subject — whatever the server was allowed to send72        #expect(r(state(lock: LockSnapshot(enabled: true, locked: true))) == NotificationText(title: "SP Mail", body: "Nouveau message"))73        #expect(r(state(lock: LockSnapshot(enabled: true, afterMinutes: 5, leftAt: t0)), now: t0.addingTimeInterval(301)) == NotificationText(title: "SP Mail", body: "Nouveau message"))74        // no readable state (token unavailable, first run): the most private level, never a crash75        #expect(r(nil) == NotificationText(title: "SP Mail", body: "Nouveau message") && r(state(signedIn: false)) == NotificationText(title: "SP Mail", body: "Nouveau message"))76        #expect(r(state(preview: .none), kind: .reminder, french: false) == NotificationText(title: "SP Mail", body: "Follow-up reminder") && r(state(preview: .none), kind: .snooze) == NotificationText(title: "SP Mail", body: "Un message mis en veille est de retour"))77        // test notifications and operator alerts carry no mail content: left alone; an already generic notification is not rewritten78        #expect(r(state(preview: .none), kind: .test) == nil && r(state(preview: .none), kind: .alert) == nil)79        #expect(NotificationRedactor.redact(NotificationText(title: "SP Mail", body: "Nouveau message"), kind: .new, state: state(preview: .none), french: true, now: t0) == nil)80    }81}8283@Suite struct SharedStoreTests {84    private func temp() -> URL { FileManager.default.temporaryDirectory.appendingPathComponent("spmail-system-\(UUID().uuidString)", isDirectory: true) }8586    @Test func environmentFromBundleIdentifier() {87        #expect(!SharedEnvironment.current(bundleIdentifier: "ai.spboucher.spmail").dev && !SharedEnvironment.current(bundleIdentifier: "ai.spboucher.spmail.ios.widgets").dev)88        #expect(SharedEnvironment.current(bundleIdentifier: "ai.spboucher.spmail.dev").dev && SharedEnvironment.current(bundleIdentifier: "ai.spboucher.spmail.ios.dev.share").dev)89        #expect(!SharedEnvironment.current(bundleIdentifier: "ai.spboucher.spmail.developer").dev)90        #expect(SharedEnvironment(dev: false).appGroup == "group.ai.spboucher.spmail" && SharedEnvironment(dev: true).appGroup == "group.ai.spboucher.spmail.dev" && SharedEnvironment(dev: true).urlScheme == "spmail-dev")91    }9293    @Test func tokenStateAndSnapshotThroughTheContainer() throws {94        let dir = temp(); defer { try? FileManager.default.removeItem(at: dir) }95        let shared = InMemorySecretStore(), own = InMemorySecretStore()96        let app = SharedStore(environment: SharedEnvironment(dev: true), directory: dir, secrets: shared)97        #expect(app.token() == nil && app.state() == nil && app.snapshot() == nil && app.widgetContent(now: t0) == .signedOut)98        // sign-in: the token is copied (the original stays), state and snapshot are written99        own.write(SecretKeys.bearerToken, Data("tok-123".utf8))100        #expect(app.migrateToken(from: own) == .copied && app.migrateToken(from: own) == .upToDate && own.read(SecretKeys.bearerToken) == Data("tok-123".utf8))101        app.write(state()); app.write(try snapshot(.full))102        // the extension: another instance on the same directory and keychain group103        let ext = SharedStore(environment: SharedEnvironment(dev: true), directory: dir, secrets: shared)104        let fullSnapshot = try snapshot(.full)105        #expect(ext.token() == "tok-123" && ext.state() == state() && ext.snapshot() == fullSnapshot)106        if case .content = ext.widgetContent(now: t0) {} else { Issue.record("expected content") }107        // the snapshot on disk is sealed108        let bytes = try Data(contentsOf: dir.appendingPathComponent("widget-snapshot.sealed"))109        #expect(bytes.range(of: Data("Jeanne".utf8)) == nil && bytes.range(of: Data("stg.spboucher.ai".utf8)) == nil)110        // sign-out: everything shared is gone, the extension sees « signed out »111        own.delete(SecretKeys.bearerToken)112        #expect(app.migrateToken(from: own) == .signedOut)113        app.clear(baseURL: "https://mail.spboucher.ai")114        #expect(ext.token() == nil && ext.snapshot() == nil && ext.state()?.signedIn == false && ext.widgetContent(now: t0) == .signedOut && ext.shareQueue.pending(now: t0).isEmpty)115        #expect(!FileManager.default.fileExists(atPath: dir.appendingPathComponent("widget-snapshot.sealed").path))116    }117118    @Test func withoutAContainerTheSnapshotFallsBackToTheKeychain() throws {119        let shared = InMemorySecretStore()120        let app = SharedStore(environment: SharedEnvironment(dev: false), directory: nil, secrets: shared)121        #expect(!app.hasContainer && !app.shareQueue.acceptsFiles)122        app.write(state(preview: .sender)); app.write(try snapshot(.sender))123        let ext = SharedStore(environment: SharedEnvironment(dev: false), directory: nil, secrets: shared)124        let senderSnapshot = try snapshot(.sender)125        #expect(ext.snapshot() == senderSnapshot)126        guard case .content(let c) = ext.widgetContent(now: t0) else { Issue.record("expected content"); return }127        #expect(c.totalUnread == 7 && c.conversations.allSatisfy { $0.subject == nil })128        // a text-only share is queued through the keychain; a share with files is refused (the extension then sends through the API)129        let draft = try ext.shareQueue.enqueue(ShareDraft(to: ["b@stg.spboucher.ai"], subject: "Lien", note: "https://example.org", createdAt: t0))130        #expect(app.shareQueue.pending(now: t0) == [draft])131        #expect(throws: ShareQueueError.self) { try ext.shareQueue.enqueue(ShareDraft(createdAt: t0), sources: [ShareSource(url: URL(fileURLWithPath: "/etc/hosts"), name: "hosts", type: "text/plain")]) }132        app.shareQueue.remove(draft.id)133        #expect(app.shareQueue.pending(now: t0).isEmpty)134        app.clear(baseURL: "https://mail.spboucher.ai")135        #expect(ext.snapshot() == nil)136    }137138    @Test func shareQueueSealsFilesInChunks() throws {139        let dir = temp(), work = temp(); defer { try? FileManager.default.removeItem(at: dir); try? FileManager.default.removeItem(at: work) }140        try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)141        let shared = InMemorySecretStore()142        let ext = SharedStore(environment: SharedEnvironment(dev: true), directory: dir, secrets: shared), app = SharedStore(environment: SharedEnvironment(dev: true), directory: dir, secrets: shared)143        // 2.5 chunks of recognisable data, an exact multiple of the chunk size, and an empty file144        var big = Data(); for i in 0..<(ShareQueue.chunkSize * 5 / 2 / 8) { var v = UInt64(i); big.append(Data(bytes: &v, count: 8)) }145        let exact = Data(repeating: 0x41, count: ShareQueue.chunkSize * 2)146        let files: [(String, Data)] = [("gros.bin", big), ("exact.bin", exact), ("vide.txt", Data()), ("note.txt", Data("PLAINTEXT-MARKER pièce jointe".utf8))]147        for (name, data) in files { try data.write(to: work.appendingPathComponent(name)) }148        let draft = try ext.shareQueue.enqueue(ShareDraft(mailboxId: mbA, to: ["b@stg.spboucher.ai"], subject: "Fichiers", note: "Voir PJ", createdAt: t0),149                                               sources: files.map { ShareSource(url: work.appendingPathComponent($0.0), name: $0.0, type: "application/octet-stream") })150        #expect(draft.files.map(\.size) == files.map(\.1.count) && draft.totalSize == files.reduce(0) { $0 + $1.1.count })151        // nothing readable in the container: neither the manifest nor the files152        let queueDir = dir.appendingPathComponent("share-queue").appendingPathComponent(draft.id)153        for f in try FileManager.default.contentsOfDirectory(at: queueDir, includingPropertiesForKeys: nil) {154            let d = try Data(contentsOf: f)155            #expect(d.range(of: Data("PLAINTEXT-MARKER".utf8)) == nil && d.range(of: Data("stg.spboucher.ai".utf8)) == nil && d.range(of: Data("Fichiers".utf8)) == nil)156        }157        // the app reads the same draft and opens each file back, byte for byte158        let pending = app.shareQueue.pending(now: t0)159        #expect(pending == [draft])160        for (file, original) in zip(draft.files, files) {161            let out = work.appendingPathComponent("out-" + file.name)162            try app.shareQueue.open(file, of: draft, to: out)163            let back = try Data(contentsOf: out)164            #expect(back == original.1, "\(file.name)")165        }166        // truncated (last chunk removed) and tampered files are refused167        let sealedBig = queueDir.appendingPathComponent(draft.files[0].stored)168        let whole = try Data(contentsOf: sealedBig)169        let firstLength = Int(whole.prefix(4).reduce(UInt32(0)) { $0 << 8 | UInt32($1) })170        try whole.prefix(4 + firstLength).write(to: sealedBig)171        #expect(throws: (any Error).self) { try app.shareQueue.open(draft.files[0], of: draft, to: work.appendingPathComponent("t")) }172        var tampered = whole; tampered[100] ^= 0xff173        try tampered.write(to: sealedBig)174        #expect(throws: (any Error).self) { try app.shareQueue.open(draft.files[0], of: draft, to: work.appendingPathComponent("t")) }175        // another key (another install) reads nothing; an expired draft is dropped176        #expect(SharedStore(environment: SharedEnvironment(dev: true), directory: dir, secrets: InMemorySecretStore()).shareQueue.pending(now: t0).isEmpty)177        #expect(app.shareQueue.pending(now: t0.addingTimeInterval(8 * 86400)).isEmpty && !FileManager.default.fileExists(atPath: queueDir.path))178    }179}180181@Suite struct PushEnvironmentTests {182    private func profile(_ entitlements: String) -> Data {183        // a provisioning profile is a CMS envelope: binary noise around the property list184        var d = Data([0x30, 0x82, 0x1f, 0x00, 0x06, 0x09, 0x2a, 0x86])185        d.append(Data("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"><plist version=\"1.0\"><dict><key>Name</key><string>SP Mail</string><key>Entitlements</key><dict>\(entitlements)</dict></dict></plist>".utf8))186        d.append(Data([0xa0, 0x82, 0x0d, 0x00, 0xff, 0xfe]))187        return d188    }189    @Test func environmentDetection() {190        #expect(PushEnvironmentDetector.environment(profile: profile("<key>aps-environment</key><string>development</string>")) == .sandbox)191        #expect(PushEnvironmentDetector.environment(profile: profile("<key>aps-environment</key><string>production</string>")) == .production)192        // macOS profiles (Developer ID) use the prefixed key193        #expect(PushEnvironmentDetector.environment(profile: profile("<key>com.apple.developer.aps-environment</key><string>production</string>")) == .production)194        // no push entitlement, an unknown value, or not a profile at all: unknown — the app then does not register rather than guess195        #expect(PushEnvironmentDetector.environment(profile: profile("<key>get-task-allow</key><true/>")) == nil)196        #expect(PushEnvironmentDetector.environment(profile: profile("<key>aps-environment</key><string>staging</string>")) == nil)197        #expect(PushEnvironmentDetector.environment(profile: Data("garbage".utf8)) == nil && PushEnvironmentDetector.environment(profile: Data()) == nil)198        #expect(PushEnvironmentDetector.environment(entitlement: "Development") == .sandbox && PushEnvironmentDetector.environment(entitlement: nil) == nil)199    }200}201
Files main
Menu

Theme