import Foundation import Security import Testing @testable import EquipoShareCore @Test func selectionRequiresExactAccountAndLiveIdentity() throws { let store = MemorySecretStore() let now = Date(timeIntervalSince1970: 1000) let selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "a@example.net", team: "Team", generation: "g") let account = ShareAccount(origin: selection.origin, credential: .init(token: "secret", expiresAt: now.addingTimeInterval(60)), address: selection.person, oficinaIdentity: "id", oficinaSessionHash: "hash") try store.write(JSONEncoder().encode(selection), account: ShareSelection.key) try store.write(JSONEncoder().encode(account), account: selection.origin.absoluteString) let auth = ShareAuthentication(store: store, identityIsLive: { _, _ in true }) #expect(try auth.read(now: now).selection == selection) #expect(throws: ShareFailure.signedOut) { try ShareAuthentication(store: store, identityIsLive: { _, _ in false }).read(now: now) } #expect(throws: ShareFailure.signedOut) { try auth.read(now: now.addingTimeInterval(60)) } store.remove(ShareSelection.key) #expect(throws: ShareFailure.signedOut) { try auth.read(now: now) } } @Test func shareKeychainUsesHostServiceAndExplicitGroup() { let query = KeychainSecretStore.shared.query("selected") #expect(query[kSecAttrService as String] as? String == "works.oficina.equipo.device") #expect(query[kSecAttrAccessGroup as String] as? String == "9U4A84C4WK.works.oficina.equipo") } @Test func interruptedSendRetainsExactRequestAndBinding() throws { let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: folder) } let journal = ShareJournal(directory: folder) let selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "a@example.net", team: "Team", generation: "g") let write = try ShareMessage(text: "A bug", project: "p", attachments: ["a"]).pending() let now = Date() try journal.save(write, selection: selection, now: now) let restored = try #require(try journal.load(selection: selection, now: now.addingTimeInterval(20))) #expect(restored == write) let body = try #require(JSONSerialization.jsonObject(with: restored.body) as? [String: Any]) #expect(body["idempotency_key"] as? String == restored.key) #expect(body["attachments"] as? [String] == ["a"]) #expect(body["project_id"] as? String == "p") var other = selection; other.person = "b@example.net" #expect(try journal.load(selection: other, now: now) == nil) // Even a misplaced journal cannot cross the recipient boundary. try FileManager.default.copyItem(at: journal.file(for: selection), to: journal.file(for: other)) #expect(throws: ShareFailure.signedOut) { try journal.load(selection: other, now: now) } #expect(throws: ShareFailure.expiredJournal) { try journal.load(selection: selection, now: now.addingTimeInterval(86_400)) } } @Test func screenshotWindowIsExplicitAndDoesNotUpload() { let now = Date(timeIntervalSince1970: 1000) var policy = ScreenshotPolicy() #expect(!policy.shouldExplain) policy.plusTapped() #expect(policy.shouldExplain) policy.decline() #expect(!policy.shouldExplain) #expect(!policy.eligible(id: "a", created: now, isScreenshot: true, hidden: false, permitted: false, now: now)) #expect(policy.eligible(id: "a", created: now.addingTimeInterval(-300), isScreenshot: true, hidden: false, permitted: true, now: now)) #expect(!policy.eligible(id: "a", created: now.addingTimeInterval(-301), isScreenshot: true, hidden: false, permitted: true, now: now)) #expect(!policy.eligible(id: "a", created: now.addingTimeInterval(1), isScreenshot: true, hidden: false, permitted: true, now: now)) policy.dismiss("a", created: now) #expect(!policy.eligible(id: "a", created: now, isScreenshot: true, hidden: false, permitted: true, now: now)) } @MainActor @Test func uncertainSendRetriesSameKeyAndDoubleTapDoesNothing() async throws { let store = MemorySecretStore(), folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: folder) } let selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "a@example.net", team: "Team") let account = ShareAccount(origin: selection.origin, credential: .init(token: "secret", expiresAt: Date().addingTimeInterval(600)), address: selection.person, oficinaIdentity: nil, oficinaSessionHash: nil) try store.write(JSONEncoder().encode(selection), account: ShareSelection.key) try store.write(JSONEncoder().encode(account), account: selection.origin.absoluteString) let transport = LostReply() let sender = ShareSender(auth: ShareAuthentication(store: store), transport: transport, journal: ShareJournal(directory: folder)) sender.text = "Bug" let first = Task { await sender.send() } while await transport.requests.isEmpty { await Task.yield() } await sender.send() #expect(await transport.requests.count == 1) await transport.release() await first.value #expect(!sender.finished) #expect(sender.pending != nil) await sender.send() #expect(sender.finished) let requests = await transport.requests #expect(requests.count == 2) #expect(requests[0].httpBody == requests[1].httpBody) #expect(requests[0].value(forHTTPHeaderField: "Idempotency-Key") == requests[1].value(forHTTPHeaderField: "Idempotency-Key")) #expect(requests.allSatisfy { $0.value(forHTTPHeaderField: "Authorization") == "Bearer secret" && !$0.httpShouldHandleCookies }) #expect(try ShareJournal(directory: folder).load(selection: selection) == nil) } private actor LostReply: ShareTransport { var requests: [URLRequest] = [] var waiting: CheckedContinuation? func send(_ request: URLRequest, file: URL?, progress: @escaping @Sendable (Double) -> Void) async throws -> ShareResponse { requests.append(request) if requests.count == 1 { await withCheckedContinuation { waiting = $0 }; throw URLError(.networkConnectionLost) } return ShareResponse(status: 200, data: Data(#"{"message":{"id":"m"}}"#.utf8)) } func release() { waiting?.resume(); waiting = nil } } @Test func messageRejectsCountDuplicatesEmptyAndOversize() { for message in [ShareMessage(text: "", project: nil, attachments: []), ShareMessage(text: "a", project: nil, attachments: ["a", "a"]), ShareMessage(text: "a", project: nil, attachments: (1...6).map(String.init)), ShareMessage(text: String(repeating: "x", count: 16385), project: nil, attachments: [])] { #expect(throws: ShareFailure.invalidInput) { try message.pending() } } } @Test func journalNeverOverwritesAnUnresolvedSendOrClearsANewerOne() throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: directory) } let journal = ShareJournal(directory: directory), selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "p", team: "T") let first = try ShareMessage(text: "First", project: nil, attachments: []).pending() let next = try ShareMessage(text: "Next", project: nil, attachments: []).pending() try journal.save(first, selection: selection) try journal.save(next, selection: selection) #expect(try journal.loadAll(selection: selection) == [first, next]) #expect(throws: ShareFailure.unconfirmed) { try journal.save(ShareWrite(key: first.key, body: next.body), selection: selection) } journal.clear(selection: selection, key: first.key) try journal.save(next, selection: selection) journal.clear(selection: selection, key: first.key) #expect(try journal.load(selection: selection) == next) } @Test func concurrentJournalWritersKeepEveryIndependentRequest() async throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: directory) } let journal = ShareJournal(directory: directory), selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "p", team: "T") let writes = try (0..<4).map { try ShareMessage(text: "Message \($0)", project: nil, attachments: []).pending() } let successes = await withTaskGroup(of: Int.self) { group in for write in writes { group.addTask { do { try journal.save(write, selection: selection); return 1 } catch { return 0 } } } var total = 0; for await n in group { total += n }; return total } #expect(successes == 4) #expect(Set(try journal.loadAll(selection: selection).map(\.key)) == Set(writes.map(\.key))) #expect(writes.contains(try #require(try journal.load(selection: selection)))) } @Test func journalClockOrderDoesNotDiscardOrExtendPendingRequest() throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: directory) } let journal = ShareJournal(directory: directory), selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "p", team: "T") let write = try ShareMessage(text: "First", project: nil, attachments: []).pending(), now = Date() try journal.save(write, selection: selection, now: now) #expect(try journal.load(selection: selection, now: now.addingTimeInterval(-1)) == write) try journal.save(write, selection: selection, now: now.addingTimeInterval(3600)) #expect(throws: ShareFailure.expiredJournal) { try journal.load(selection: selection, now: now.addingTimeInterval(86400)) } } @Test func legacyJournalLoadsWithoutReplacingTheNewShare() throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } let journal = ShareJournal(directory: directory), selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "p", team: "T") let old = try ShareMessage(text: "Old", project: nil, attachments: []).pending() try JSONEncoder().encode(ShareJournal.Record(selection: selection, created: Date(), write: old)).write(to: journal.file(for: selection)) #expect(try journal.loadAll(selection: selection) == [old]) let new = try ShareMessage(text: "New", project: nil, attachments: []).pending() try journal.save(new, selection: selection) #expect(try journal.loadAll(selection: selection) == [old, new]) }