oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import Security
3import Testing
4@testable import EquipoShareCore
5
6@Test func selectionRequiresExactAccountAndLiveIdentity() throws {
7 let store = MemorySecretStore()
8 let now = Date(timeIntervalSince1970: 1000)
9 let selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "a@example.net", team: "Team", generation: "g")
10 let account = ShareAccount(origin: selection.origin, credential: .init(token: "secret", expiresAt: now.addingTimeInterval(60)), address: selection.person, oficinaIdentity: "id", oficinaSessionHash: "hash")
11 try store.write(JSONEncoder().encode(selection), account: ShareSelection.key)
12 try store.write(JSONEncoder().encode(account), account: selection.origin.absoluteString)
13 let auth = ShareAuthentication(store: store, identityIsLive: { _, _ in true })
14 #expect(try auth.read(now: now).selection == selection)
15 #expect(throws: ShareFailure.signedOut) { try ShareAuthentication(store: store, identityIsLive: { _, _ in false }).read(now: now) }
16 #expect(throws: ShareFailure.signedOut) { try auth.read(now: now.addingTimeInterval(60)) }
17 store.remove(ShareSelection.key)
18 #expect(throws: ShareFailure.signedOut) { try auth.read(now: now) }
19}
20
21@Test func shareKeychainUsesHostServiceAndExplicitGroup() {
22 let query = KeychainSecretStore.shared.query("selected")
23 #expect(query[kSecAttrService as String] as? String == "works.oficina.equipo.device")
24 #expect(query[kSecAttrAccessGroup as String] as? String == "9U4A84C4WK.works.oficina.equipo")
25}
26
27@Test func interruptedSendRetainsExactRequestAndBinding() throws {
28 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
29 defer { try? FileManager.default.removeItem(at: folder) }
30 let journal = ShareJournal(directory: folder)
31 let selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "a@example.net", team: "Team", generation: "g")
32 let write = try ShareMessage(text: "A bug", project: "p", attachments: ["a"]).pending()
33 let now = Date()
34 try journal.save(write, selection: selection, now: now)
35 let restored = try #require(try journal.load(selection: selection, now: now.addingTimeInterval(20)))
36 #expect(restored == write)
37 let body = try #require(JSONSerialization.jsonObject(with: restored.body) as? [String: Any])
38 #expect(body["idempotency_key"] as? String == restored.key)
39 #expect(body["attachments"] as? [String] == ["a"])
40 #expect(body["project_id"] as? String == "p")
41 var other = selection; other.person = "b@example.net"
42 #expect(try journal.load(selection: other, now: now) == nil)
43 // Even a misplaced journal cannot cross the recipient boundary.
44 try FileManager.default.copyItem(at: journal.file(for: selection), to: journal.file(for: other))
45 #expect(throws: ShareFailure.signedOut) { try journal.load(selection: other, now: now) }
46 #expect(throws: ShareFailure.expiredJournal) { try journal.load(selection: selection, now: now.addingTimeInterval(86_400)) }
47}
48
49@Test func screenshotWindowIsExplicitAndDoesNotUpload() {
50 let now = Date(timeIntervalSince1970: 1000)
51 var policy = ScreenshotPolicy()
52 #expect(!policy.shouldExplain)
53 policy.plusTapped()
54 #expect(policy.shouldExplain)
55 policy.decline()
56 #expect(!policy.shouldExplain)
57 #expect(!policy.eligible(id: "a", created: now, isScreenshot: true, hidden: false, permitted: false, now: now))
58 #expect(policy.eligible(id: "a", created: now.addingTimeInterval(-300), isScreenshot: true, hidden: false, permitted: true, now: now))
59 #expect(!policy.eligible(id: "a", created: now.addingTimeInterval(-301), isScreenshot: true, hidden: false, permitted: true, now: now))
60 #expect(!policy.eligible(id: "a", created: now.addingTimeInterval(1), isScreenshot: true, hidden: false, permitted: true, now: now))
61 policy.dismiss("a", created: now)
62 #expect(!policy.eligible(id: "a", created: now, isScreenshot: true, hidden: false, permitted: true, now: now))
63}
64
65@MainActor @Test func uncertainSendRetriesSameKeyAndDoubleTapDoesNothing() async throws {
66 let store = MemorySecretStore(), folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
67 defer { try? FileManager.default.removeItem(at: folder) }
68 let selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "a@example.net", team: "Team")
69 let account = ShareAccount(origin: selection.origin, credential: .init(token: "secret", expiresAt: Date().addingTimeInterval(600)), address: selection.person, oficinaIdentity: nil, oficinaSessionHash: nil)
70 try store.write(JSONEncoder().encode(selection), account: ShareSelection.key)
71 try store.write(JSONEncoder().encode(account), account: selection.origin.absoluteString)
72 let transport = LostReply()
73 let sender = ShareSender(auth: ShareAuthentication(store: store), transport: transport, journal: ShareJournal(directory: folder))
74 sender.text = "Bug"
75 let first = Task { await sender.send() }
76 while await transport.requests.isEmpty { await Task.yield() }
77 await sender.send()
78 #expect(await transport.requests.count == 1)
79 await transport.release()
80 await first.value
81 #expect(!sender.finished)
82 #expect(sender.pending != nil)
83 await sender.send()
84 #expect(sender.finished)
85 let requests = await transport.requests
86 #expect(requests.count == 2)
87 #expect(requests[0].httpBody == requests[1].httpBody)
88 #expect(requests[0].value(forHTTPHeaderField: "Idempotency-Key") == requests[1].value(forHTTPHeaderField: "Idempotency-Key"))
89 #expect(requests.allSatisfy { $0.value(forHTTPHeaderField: "Authorization") == "Bearer secret" && !$0.httpShouldHandleCookies })
90 #expect(try ShareJournal(directory: folder).load(selection: selection) == nil)
91}
92private actor LostReply: ShareTransport {
93 var requests: [URLRequest] = []
94 var waiting: CheckedContinuation<Void, Never>?
95 func send(_ request: URLRequest, file: URL?, progress: @escaping @Sendable (Double) -> Void) async throws -> ShareResponse {
96 requests.append(request)
97 if requests.count == 1 { await withCheckedContinuation { waiting = $0 }; throw URLError(.networkConnectionLost) }
98 return ShareResponse(status: 200, data: Data(#"{"message":{"id":"m"}}"#.utf8))
99 }
100 func release() { waiting?.resume(); waiting = nil }
101}
102
103@Test func messageRejectsCountDuplicatesEmptyAndOversize() {
104 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: [])] {
105 #expect(throws: ShareFailure.invalidInput) { try message.pending() }
106 }
107}
108
109@Test func journalNeverOverwritesAnUnresolvedSendOrClearsANewerOne() throws {
110 let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
111 defer { try? FileManager.default.removeItem(at: directory) }
112 let journal = ShareJournal(directory: directory), selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "p", team: "T")
113 let first = try ShareMessage(text: "First", project: nil, attachments: []).pending()
114 let next = try ShareMessage(text: "Next", project: nil, attachments: []).pending()
115 try journal.save(first, selection: selection)
116 try journal.save(next, selection: selection)
117 #expect(try journal.loadAll(selection: selection) == [first, next])
118 #expect(throws: ShareFailure.unconfirmed) { try journal.save(ShareWrite(key: first.key, body: next.body), selection: selection) }
119 journal.clear(selection: selection, key: first.key)
120 try journal.save(next, selection: selection)
121 journal.clear(selection: selection, key: first.key)
122 #expect(try journal.load(selection: selection) == next)
123}
124
125@Test func concurrentJournalWritersKeepEveryIndependentRequest() async throws {
126 let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
127 defer { try? FileManager.default.removeItem(at: directory) }
128 let journal = ShareJournal(directory: directory), selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "p", team: "T")
129 let writes = try (0..<4).map { try ShareMessage(text: "Message \($0)", project: nil, attachments: []).pending() }
130 let successes = await withTaskGroup(of: Int.self) { group in
131 for write in writes { group.addTask { do { try journal.save(write, selection: selection); return 1 } catch { return 0 } } }
132 var total = 0; for await n in group { total += n }; return total
133 }
134 #expect(successes == 4)
135 #expect(Set(try journal.loadAll(selection: selection).map(\.key)) == Set(writes.map(\.key)))
136 #expect(writes.contains(try #require(try journal.load(selection: selection))))
137}
138
139@Test func journalClockOrderDoesNotDiscardOrExtendPendingRequest() throws {
140 let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
141 defer { try? FileManager.default.removeItem(at: directory) }
142 let journal = ShareJournal(directory: directory), selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "p", team: "T")
143 let write = try ShareMessage(text: "First", project: nil, attachments: []).pending(), now = Date()
144 try journal.save(write, selection: selection, now: now)
145 #expect(try journal.load(selection: selection, now: now.addingTimeInterval(-1)) == write)
146 try journal.save(write, selection: selection, now: now.addingTimeInterval(3600))
147 #expect(throws: ShareFailure.expiredJournal) { try journal.load(selection: selection, now: now.addingTimeInterval(86400)) }
148}
149
150@Test func legacyJournalLoadsWithoutReplacingTheNewShare() throws {
151 let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
152 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
153 defer { try? FileManager.default.removeItem(at: directory) }
154 let journal = ShareJournal(directory: directory), selection = ShareSelection(origin: URL(string: "https://team.example")!, person: "p", team: "T")
155 let old = try ShareMessage(text: "Old", project: nil, attachments: []).pending()
156 try JSONEncoder().encode(ShareJournal.Record(selection: selection, created: Date(), write: old)).write(to: journal.file(for: selection))
157 #expect(try journal.loadAll(selection: selection) == [old])
158 let new = try ShareMessage(text: "New", project: nil, attachments: []).pending()
159 try journal.save(new, selection: selection)
160 #expect(try journal.loadAll(selection: selection) == [old, new])
161}
162