-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathCmxAttachTicketCompactCoderTests.swift
More file actions
347 lines (316 loc) · 12.6 KB
/
Copy pathCmxAttachTicketCompactCoderTests.swift
File metadata and controls
347 lines (316 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import Foundation
import Testing
@testable import CMUXMobileCore
/// Round-trip and cross-grammar coverage for ``CmxAttachTicketCompactCoder``.
///
/// The pairing QR moved from the legacy full-key `Codable` JSON to a compact
/// short-key grammar. These tests pin the compact encode shape (short keys,
/// dropped empties, no auth token, no display name, no expiry), prove
/// lossless round trips of what the grammar keeps, and pin the compatibility
/// matrix: a new decoder accepts the current grammar, the first compact
/// revision (extra `e`/`n` keys, explicit route ids and endpoint types), and
/// the legacy full-key grammar via the input router, while the legacy decoder
/// rejects compact payloads with a thrown error rather than a silently wrong
/// ticket.
private let compactCoder = CmxAttachTicketCompactCoder()
private func wholeSecondFutureExpiry() -> Date {
Date(timeIntervalSince1970: 4_000_000_000)
}
private func hostPortRoute(priority: Int = 0) throws -> CmxAttachRoute {
try CmxAttachRoute(
id: "tailscale",
kind: .tailscale,
endpoint: .hostPort(host: "100.64.1.2", port: 49831),
priority: priority
)
}
private func legacyDecoder() -> JSONDecoder {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return decoder
}
@Test func compactEncodeUsesShortKeysAndNeverCarriesAuthTokenNameOrExpiry() throws {
let ticket = try CmxAttachTicket(
workspaceID: "workspace-1",
terminalID: "terminal-9",
macDeviceID: "mac-1",
macDisplayName: "Studio",
macUserEmail: "user@example.com",
macPairingCompatibilityVersion: 1,
macAppVersion: "0.64.15",
macAppBuild: "42",
routes: [try hostPortRoute(priority: 1)],
expiresAt: wholeSecondFutureExpiry(),
authToken: "ticket-secret"
)
let data = try compactCoder.encode(ticket)
let json = try #require(String(data: data, encoding: .utf8))
#expect(!json.contains("auth_token"))
#expect(!json.contains("authToken"))
#expect(!json.contains("ticket-secret"))
#expect(!json.contains("workspaceID"))
#expect(!json.contains("version"))
#expect(json.contains("\"v\":1"))
#expect(json.contains("\"w\":\"workspace-1\""))
#expect(json.contains("\"d\":\"mac-1\""))
#expect(json.contains("\"u\":\"user@example.com\""))
#expect(json.contains("\"pc\":1"))
#expect(json.contains("\"av\":\"0.64.15\""))
#expect(json.contains("\"ab\":\"42\""))
// The grammar no longer carries the display name or an expiry: the name
// arrives post-handshake via `mobile.host.status`, and a pairing QR never
// expires.
#expect(!json.contains("Studio"))
#expect(!json.contains("4000000000"))
let object = try #require(
try JSONSerialization.jsonObject(with: data) as? [String: Any]
)
#expect(object["n"] == nil)
#expect(object["e"] == nil)
}
@Test func compactRoundTripsFullFieldTicketExceptDroppedQRFields() throws {
let routes = [
try hostPortRoute(priority: 2),
try CmxAttachRoute(
id: "iroh",
kind: .iroh,
endpoint: .peer(
id: "peer-1",
relayHint: "use1",
directAddrs: ["192.168.1.4:4242"],
relayURL: "https://relay.example"
),
priority: 1
),
try CmxAttachRoute(
id: "ws",
kind: .websocket,
endpoint: .url("wss://example.com/attach")
),
]
let ticket = try CmxAttachTicket(
workspaceID: "workspace-1",
terminalID: "terminal-9",
macDeviceID: "mac-1",
macDisplayName: "Studio",
macUserEmail: "user@example.com",
macPairingCompatibilityVersion: 1,
macAppVersion: "0.64.15",
macAppBuild: "42",
routes: routes,
expiresAt: wholeSecondFutureExpiry(),
authToken: "ticket-secret"
)
let decoded = try compactCoder.decode(
compactCoder.encode(ticket)
)
#expect(decoded.version == ticket.version)
#expect(decoded.workspaceID == ticket.workspaceID)
#expect(decoded.terminalID == ticket.terminalID)
#expect(decoded.macDeviceID == ticket.macDeviceID)
#expect(decoded.macUserEmail == ticket.macUserEmail)
#expect(decoded.macPairingCompatibilityVersion == ticket.macPairingCompatibilityVersion)
#expect(decoded.macAppVersion == ticket.macAppVersion)
#expect(decoded.macAppBuild == ticket.macAppBuild)
// Routes round-trip losslessly even with custom ids ("ws" differs from
// the synthesized "websocket", so it is carried verbatim).
#expect(decoded.routes == ticket.routes)
// Dropped by design: the auth token never authorizes anything, the name
// arrives via `mobile.host.status`, and a pairing QR never expires.
#expect(decoded.authToken == nil)
#expect(decoded.macDisplayName == nil)
#expect(decoded.expiresAt == nil)
#expect(!decoded.isExpired(at: .distantFuture))
}
@Test func compactRoundTripsMacWidePairingTicketAndDropsEmptyFields() throws {
// The shape the pairing window mints: Mac-wide (empty workspaceID), no
// terminal scope.
let ticket = try CmxAttachTicket(
workspaceID: "",
terminalID: nil,
macDeviceID: "mac-1",
macDisplayName: nil,
routes: [try hostPortRoute()],
expiresAt: wholeSecondFutureExpiry(),
authToken: "ticket-secret"
)
let data = try compactCoder.encode(ticket)
let object = try #require(
try JSONSerialization.jsonObject(with: data) as? [String: Any]
)
// Empty workspaceID, nil terminalID, the display name, and the expiry
// are all omitted.
#expect(object["w"] == nil)
#expect(object["t"] == nil)
#expect(object["n"] == nil)
#expect(object["e"] == nil)
let route = try #require((object["r"] as? [[String: Any]])?.first)
// priority 0 is the default and is omitted from the route, the id
// "tailscale" matches what the decoder resynthesizes from the kind, and
// the endpoint type is implied by `h` + `p`.
#expect(route["p"] == nil)
#expect(route["i"] == nil)
let endpoint = try #require(route["e"] as? [String: Any])
#expect(endpoint["t"] == nil)
let decoded = try compactCoder.decode(data)
#expect(decoded.workspaceID == "")
#expect(decoded.terminalID == nil)
#expect(decoded.macDisplayName == nil)
#expect(decoded.routes == ticket.routes)
}
@Test func compactRoundTripsRepeatedKindAndCustomRouteIDs() throws {
// First tailscale route gets the synthesized id "tailscale", the second
// "tailscale_2" (both omitted on the wire); the custom "vpn-backup" id
// differs from any synthesized id, so it rides verbatim.
let routes = [
try hostPortRoute(),
try CmxAttachRoute(
id: "tailscale_2",
kind: .tailscale,
endpoint: .hostPort(host: "100.64.1.3", port: 49832)
),
try CmxAttachRoute(
id: "vpn-backup",
kind: .tailscale,
endpoint: .hostPort(host: "100.64.1.4", port: 49833)
),
]
let ticket = try CmxAttachTicket(
workspaceID: "",
terminalID: nil,
macDeviceID: "mac-1",
macDisplayName: nil,
routes: routes
)
let data = try compactCoder.encode(ticket)
let object = try #require(
try JSONSerialization.jsonObject(with: data) as? [String: Any]
)
let encodedRoutes = try #require(object["r"] as? [[String: Any]])
#expect(encodedRoutes.count == 3)
#expect(encodedRoutes[0]["i"] == nil)
#expect(encodedRoutes[1]["i"] == nil)
#expect(encodedRoutes[2]["i"] as? String == "vpn-backup")
let decoded = try compactCoder.decode(data)
#expect(decoded.routes == routes)
}
@Test func compactDecodeAcceptsFirstRevisionPayloadAndDropsExpiryAndName() throws {
// A QR minted by the first compact revision: expiry under `e` (already in
// the past), display name under `n`, explicit route `i`, and explicit
// endpoint type `t`. It must keep pairing: the stale expiry and the name
// are dropped, the explicit ids and types are honored.
let firstRevision = Data("""
{"d":"mac-1","e":1000,"n":"Studio","r":[{"e":{"h":"100.64.1.2","p":49831,"t":"host_port"},"i":"tailscale","k":"tailscale"}],"v":1}
""".utf8)
let decoded = try compactCoder.decode(firstRevision)
#expect(decoded.macDeviceID == "mac-1")
#expect(decoded.macDisplayName == nil)
#expect(decoded.expiresAt == nil)
#expect(!decoded.isExpired(at: .distantFuture))
#expect(decoded.routes == [try hostPortRoute()])
}
@Test func legacyDecoderRejectsCompactPayloadLoudly() throws {
// Old-phone-scans-new-QR: the pre-compact decoder must throw (missing
// "version" key), never silently produce a wrong ticket.
let ticket = try CmxAttachTicket(
workspaceID: "",
terminalID: nil,
macDeviceID: "mac-1",
macDisplayName: "Studio",
routes: [try hostPortRoute()],
expiresAt: wholeSecondFutureExpiry()
)
let compact = try compactCoder.encode(ticket)
#expect(throws: DecodingError.self) {
try legacyDecoder().decode(CmxAttachTicket.self, from: compact)
}
}
@Test func compactDecoderRejectsLegacyPayload() throws {
// The compact decoder is never handed a legacy payload in production
// (the input router checks `isCompactPayload` first), but if it were it
// must throw, not mis-decode.
let ticket = try CmxAttachTicket(
workspaceID: "workspace-1",
terminalID: nil,
macDeviceID: "mac-1",
macDisplayName: nil,
routes: [try hostPortRoute()],
expiresAt: wholeSecondFutureExpiry()
)
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
let legacy = try encoder.encode(ticket)
#expect(compactCoder.isCompactPayload(legacy) == false)
#expect(throws: DecodingError.self) {
try compactCoder.decode(legacy)
}
}
@Test func compactPayloadDetectionDistinguishesGrammars() throws {
let ticket = try CmxAttachTicket(
workspaceID: "",
terminalID: nil,
macDeviceID: "mac-1",
macDisplayName: nil,
routes: [try hostPortRoute()],
expiresAt: wholeSecondFutureExpiry()
)
let compact = try compactCoder.encode(ticket)
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
let legacy = try encoder.encode(ticket)
#expect(compactCoder.isCompactPayload(compact))
#expect(!compactCoder.isCompactPayload(legacy))
#expect(!compactCoder.isCompactPayload(Data("not json".utf8)))
}
@Test func compactDecodeRejectsUnsupportedPayloadVersion() throws {
// The decoded `v` must reach validation: a future compact grammar
// revision that bumps the version has to fail loudly on today's phones,
// not silently misdecode as a version-1 ticket.
let futureVersion = Data("""
{"v":2,"d":"mac-1","r":[{"k":"tailscale","e":{"h":"100.64.1.2","p":49831}}]}
""".utf8)
#expect(throws: CmxAttachTicketError.unsupportedVersion(2)) {
try compactCoder.decode(futureVersion)
}
}
@Test func compactDecodeRejectsUnknownRouteKindAndEndpointType() throws {
let unknownKind = Data("""
{"v":1,"d":"mac-1","e":4000000000,"r":[{"i":"x","k":"carrier-pigeon","e":{"t":"host_port","h":"100.64.1.2","p":49831}}]}
""".utf8)
#expect(throws: DecodingError.self) {
try compactCoder.decode(unknownKind)
}
let unknownEndpoint = Data("""
{"v":1,"d":"mac-1","e":4000000000,"r":[{"i":"tailscale","k":"tailscale","e":{"t":"smoke-signal"}}]}
""".utf8)
#expect(throws: DecodingError.self) {
try compactCoder.decode(unknownEndpoint)
}
}
@Test func compactPayloadIsSmallerThanLegacyPayload() throws {
// The point of the grammar: the same Mac-wide pairing ticket (with the
// auth token the store mints today) must shrink enough to drop QR
// versions. Pin a ceiling near the 150-byte target so payload growth
// shows up in review.
let ticket = try CmxAttachTicket(
workspaceID: "",
terminalID: nil,
macDeviceID: UUID().uuidString,
macDisplayName: "Lawrence's MacBook Pro",
routes: [
try CmxAttachRoute(
id: "tailscale",
kind: .tailscale,
endpoint: .hostPort(host: "100.102.73.120", port: 49831)
),
],
expiresAt: wholeSecondFutureExpiry(),
authToken: "3q2-7wDqzfQqzKpQ4XB8x1n0o5pYkz9jW2sT8uVbLwM"
)
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
let legacy = try encoder.encode(ticket)
let compact = try compactCoder.encode(ticket)
#expect(compact.count < legacy.count)
#expect(compact.count <= 150)
}