import Foundation import Testing @testable import EquipoShareCore @Test(arguments: ["missing-selection", "missing-account", "person", "origin", "expired", "token", "identity", "generation", "http", "path", "query"]) func shareAuthorityRefusesChangedOrUnavailableBinding(_ fault: String) throws { let store = MemorySecretStore(), now = Date() let good = ShareSelection(origin: URL(string: "https://team.example")!, person: "a@example.net", team: "Team", generation: "one") var selection = good if fault == "generation" { selection.generation = "two" } if fault == "http" { selection.origin = URL(string: "http://team.example")! } if fault == "path" { selection.origin = URL(string: "https://team.example/other")! } if fault == "query" { selection.origin = URL(string: "https://team.example?q=x")! } let account = ShareAccount(origin: fault == "origin" ? URL(string: "https://other.example")! : selection.origin, credential: .init(token: fault == "token" ? "" : "bearer", expiresAt: now.addingTimeInterval(fault == "expired" ? -1 : 100)), address: fault == "person" ? "other@example.net" : good.person, oficinaIdentity: "id", oficinaSessionHash: "hash") if fault != "missing-selection" { try store.write(JSONEncoder().encode(selection), account: ShareSelection.key) } if fault != "missing-account" { try store.write(JSONEncoder().encode(account), account: selection.origin.absoluteString) } let auth = ShareAuthentication(store: store, identityIsLive: { _, _ in fault != "identity" }) #expect(throws: ShareFailure.signedOut) { if fault == "generation" { _ = try auth.require(good, now: now) } else { _ = try auth.read(now: now) } } } @Test(arguments: ["not-screenshot", "hidden", "denied", "future", "old", "dismissed"]) func screenshotRefusesIneligibleAssets(_ fault: String) { let now = Date(), id = "s" var policy = ScreenshotPolicy() if fault == "dismissed" { policy.dismiss(id, created: now) } let created = now.addingTimeInterval(fault == "future" ? 1 : fault == "old" ? -301 : -1) #expect(!policy.eligible(id: id, created: created, isScreenshot: fault != "not-screenshot", hidden: fault == "hidden", permitted: fault != "denied", now: now)) } @MainActor @Test func accountSwitchAfterReadCannotCommitSendSuccess() async throws { let store = MemorySecretStore(), directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: directory) } let selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "a@example.net", team: "Team") try store.write(JSONEncoder().encode(selection), account: ShareSelection.key) try store.write(JSONEncoder().encode(ShareAccount(origin: selection.origin, credential: .init(token: "secret", expiresAt: Date().addingTimeInterval(60)), address: selection.person, oficinaIdentity: nil, oficinaSessionHash: nil)), account: selection.origin.absoluteString) let sender = ShareSender(auth: ShareAuthentication(store: store), transport: SwitchOnReply(store: store), journal: ShareJournal(directory: directory)) sender.text = "Bug"; await sender.send() #expect(!sender.finished) #expect(sender.error == .signedOut) #expect(sender.selection == nil) } private struct SwitchOnReply: ShareTransport { let store: MemorySecretStore func send(_ request: URLRequest, file: URL?, progress: @escaping @Sendable (Double) -> Void) async throws -> ShareResponse { store.remove(ShareSelection.key) return .init(status: 200, data: Data(#"{"message":{"id":"sent"}}"#.utf8)) } } @MainActor @Test(arguments: ["cancelled", "401", "403", "oversize"]) func refusedOrCancelledResponsesNeverFinish(_ fault: String) async throws { let store = MemorySecretStore(), directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: directory) } let selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "a@example.net", team: "Team") try store.write(JSONEncoder().encode(selection), account: ShareSelection.key) try store.write(JSONEncoder().encode(ShareAccount(origin: selection.origin, credential: .init(token: "secret", expiresAt: Date().addingTimeInterval(60)), address: selection.person, oficinaIdentity: nil, oficinaSessionHash: nil)), account: selection.origin.absoluteString) let sender = ShareSender(auth: ShareAuthentication(store: store), transport: RefusedResponse(fault: fault), journal: ShareJournal(directory: directory)) sender.text = "Bug" let task = Task { await sender.send() }; await task.value #expect(!sender.finished) if ["401", "403"].contains(fault) { #expect(sender.selection == nil); #expect(sender.error == .signedOut) } } private struct RefusedResponse: ShareTransport { let fault: String func send(_ request: URLRequest, file: URL?, progress: @escaping @Sendable (Double) -> Void) async throws -> ShareResponse { if fault == "cancelled" { withUnsafeCurrentTask { $0?.cancel() } } let body = #"{"message":{"id":"sent"}}"# + (fault == "oversize" ? String(repeating: " ", count: 128 * 1024) : "") return .init(status: Int(fault) ?? 200, data: Data(body.utf8)) } } @Test(arguments: ["valid", "removed", "wrong-hash", "expired", "old", "new-version", "other-identity", "missing-session", "old-grant", "malformed-grant"]) func pinnedOficinaRecordsRequireLiveIdentityAndBoundSession(_ fault: String) { let grant = fault == "malformed-grant" ? "AQ" : "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" let identity = Data("{\"v\":1,\"identity_id\":\"person\",\"grant\":\"\(grant)\"}".utf8) let session = Data("{\"grant_id\":\"\(fault == "old-grant" ? "old" : fault == "malformed-grant" ? "jtbgCLytFO7uf7AmMnW8kA" : "L4vtVQrojtsak8-oO3BFRA")\",\"v\":\(fault == "new-version" ? 2 : 1),\"identity_id\":\"\(fault == "other-identity" ? "other" : "person")\",\"session\":{\"name\":\"session\",\"value\":\"session-secret\"},\"minted_at\":\(fault == "old" ? -604800 : 900),\"expires_at\":\(fault == "expired" ? 1000 : 1100)}".utf8) let live = SharedIdentity.validate(identityData: fault == "removed" ? [] : [identity], sessions: fault == "missing-session" ? [] : [session], identity: "person", hash: fault == "wrong-hash" ? "other" : "E1-n1nFGylQPF-UeEB1F3lse3ejqihP5x7k7caoh-KQ", now: Date(timeIntervalSince1970: 1000)) #expect(live == (fault == "valid")) }