-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathMetaGlobalTests.swift
627 lines (521 loc) · 31.3 KB
/
MetaGlobalTests.swift
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@testable import Account
import Foundation
import Shared
import Storage
@testable import Sync
import XCGLogger
import XCTest
import SwiftyJSON
private let log = Logger.syncLogger
class MockSyncAuthState: SyncAuthState {
var clientName: String?
var enginesEnablements: [String : Bool]?
let serverRoot: String
let kSync: Data
var deviceID: String? {
return "mock_device_id"
}
init(serverRoot: String, kSync: Data) {
self.serverRoot = serverRoot
self.kSync = kSync
}
func invalidate() {
}
func token(_ now: Timestamp, canBeExpired: Bool) -> Deferred<Maybe<(token: TokenServerToken, forKey: Data)>> {
let token = TokenServerToken(id: "id", key: "key", api_endpoint: serverRoot, uid: UInt64(0), hashedFxAUID: "",
durationInSeconds: UInt64(5 * 60), remoteTimestamp: Timestamp(now - 1))
return deferMaybe((token, self.kSync))
}
}
class MetaGlobalTests: XCTestCase {
var server: MockSyncServer!
var serverRoot: String!
var kSync: Data!
var syncPrefs: Prefs!
var authState: SyncAuthState!
var stateMachine: SyncStateMachine!
override func setUp() {
kSync = Data.randomOfLength(64)!
server = MockSyncServer(username: "1234567")
server.start()
serverRoot = server.baseURL
syncPrefs = MockProfilePrefs()
authState = MockSyncAuthState(serverRoot: serverRoot, kSync: kSync)
stateMachine = SyncStateMachine(prefs: syncPrefs)
}
func storeMetaGlobal(metaGlobal: MetaGlobal) {
let envelope = EnvelopeJSON(JSON([
"id": "global",
"collection": "meta",
"payload": metaGlobal.asPayload().json.stringify()!,
"modified": Double(Date.now())/1000]))
server.storeRecords(records: [envelope], inCollection: "meta")
}
func storeCryptoKeys(keys: Keys) {
let keyBundle = KeyBundle.fromKSync(kSync)
let record = Record(id: "keys", payload: keys.asPayload()) as Record<CleartextPayloadJSON>
let serializer = keysPayloadSerializer(keyBundle: keyBundle, { $0.json })
let envelope = EnvelopeJSON(serializer(record)!)
server.storeRecords(records: [envelope], inCollection: "crypto")
}
func assertFreshStart(ready: Ready?, after: Timestamp) {
XCTAssertNotNil(ready)
guard let ready = ready else {
return
}
// We should have wiped.
// We should have uploaded new meta/global and crypto/keys.
XCTAssertGreaterThan(server.collections["meta"]?.records["global"]?.modified ?? 0, after)
XCTAssertGreaterThan(server.collections["meta"]?.modified ?? 0, after)
XCTAssertGreaterThan(server.collections["crypto"]?.records["keys"]?.modified ?? 0, after)
XCTAssertGreaterThan(server.collections["crypto"]?.modified ?? 0, after)
// And we should have downloaded meta/global and crypto/keys.
XCTAssertNotNil(ready.scratchpad.global)
XCTAssertNotNil(ready.scratchpad.keys)
// We should have the default engine configuration.
XCTAssertNotNil(ready.scratchpad.engineConfiguration)
guard let engineConfiguration = ready.scratchpad.engineConfiguration else {
return
}
XCTAssertEqual(engineConfiguration.enabled.sorted(), ["addons", "addresses", "bookmarks", "clients", "creditcards", "forms", "history", "passwords", "prefs", "tabs"])
XCTAssertEqual(engineConfiguration.declined, [])
// Basic verifications.
XCTAssertEqual(ready.collectionKeys.defaultBundle.encKey.count, 32)
if let clients = ready.scratchpad.global?.value.engines["clients"] {
XCTAssertTrue(clients.syncID.count == 12)
}
}
func testMetaGlobalVersionTooNew() {
// There's no recovery from a meta/global version "in the future": just bail out with an UpgradeRequiredError.
storeMetaGlobal(metaGlobal: MetaGlobal(syncID: "id", storageVersion: 6, engines: [String: EngineMeta](), declined: []))
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "clientUpgradeRequired"])
XCTAssertNotNil(result.failureValue as? ClientUpgradeRequiredError)
XCTAssertNil(result.successValue)
expectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testMetaGlobalVersionTooOld() {
// To recover from a meta/global version "in the past", fresh start.
storeMetaGlobal(metaGlobal: MetaGlobal(syncID: "id", storageVersion: 4, engines: [String: EngineMeta](), declined: []))
let afterStores = Date.now()
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "remoteUpgradeRequired",
"freshStartRequired", "serverConfigurationRequired", "initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
self.assertFreshStart(ready: result.successValue, after: afterStores)
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testMetaGlobalMissing() {
// To recover from a missing meta/global, fresh start.
let afterStores = Date.now()
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "missingMetaGlobal",
"freshStartRequired", "serverConfigurationRequired", "initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
self.assertFreshStart(ready: result.successValue, after: afterStores)
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testCryptoKeysMissing() {
// To recover from a missing crypto/keys, fresh start.
storeMetaGlobal(metaGlobal: createMetaGlobal(enginesEnablements: nil))
let afterStores = Date.now()
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "missingCryptoKeys", "freshStartRequired", "serverConfigurationRequired", "initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
self.assertFreshStart(ready: result.successValue, after: afterStores)
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testMetaGlobalAndCryptoKeysFresh() {
// When encountering a valid meta/global and crypto/keys, advance smoothly.
let metaGlobal = MetaGlobal(syncID: "id", storageVersion: 5, engines: [String: EngineMeta](), declined: [])
let cryptoKeys = Keys.random()
storeMetaGlobal(metaGlobal: metaGlobal)
storeCryptoKeys(keys: cryptoKeys)
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have downloaded meta/global and crypto/keys.
XCTAssertEqual(ready.scratchpad.global?.value, metaGlobal)
XCTAssertEqual(ready.scratchpad.keys?.value, cryptoKeys)
// We should have marked all local engines for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["bookmarks", "clients", "history", "passwords", "tabs"])
ready.clearLocalCommands()
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
let afterFirstSync = Date.now()
// Now, run through the state machine again. Nothing's changed remotely, so we should advance quickly.
let secondExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "hasMetaGlobal", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have not downloaded a fresh meta/global or crypto/keys.
XCTAssertLessThan(ready.scratchpad.global?.timestamp ?? Timestamp.max, afterFirstSync)
XCTAssertLessThan(ready.scratchpad.keys?.timestamp ?? Timestamp.max, afterFirstSync)
// We should not have marked any local engines for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), [])
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
secondExpectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testFailingOptimisticStateMachine() {
// We test only the optimistic state machine, knowing it will need to go through
// needsFreshMetaGlobal, and fail.
let metaGlobal = MetaGlobal(syncID: "id", storageVersion: 5, engines: [String: EngineMeta](), declined: [])
let cryptoKeys = Keys.random()
storeMetaGlobal(metaGlobal: metaGlobal)
storeCryptoKeys(keys: cryptoKeys)
stateMachine = SyncStateMachine(prefs: syncPrefs, allowingStates: SyncStateMachine.OptimisticStates)
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal"])
XCTAssertNotNil(result.failureValue)
if let failure = result.failureValue as? DisallowedStateError {
XCTAssertEqual(failure.state, SyncStateLabel.NeedsFreshMetaGlobal)
} else {
XCTFail("SyncStatus failed, but with a different error")
}
expectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testHappyOptimisticStateMachine() {
// We should be able to quickly progress through a constrained (a.k.a. optimistic) state machine
let metaGlobal = MetaGlobal(syncID: "id", storageVersion: 5, engines: [String: EngineMeta](), declined: [])
let cryptoKeys = Keys.random()
storeMetaGlobal(metaGlobal: metaGlobal)
storeCryptoKeys(keys: cryptoKeys)
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
expectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
// Now, run through the state machine again. Nothing's changed remotely, so we should advance quickly.
// We should be able to use this 'optimistic' path in an extension.
stateMachine = SyncStateMachine(prefs: syncPrefs, allowingStates: SyncStateMachine.OptimisticStates)
let secondExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "hasMetaGlobal", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
secondExpectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testUpdatedCryptoKeys() {
// When encountering a valid meta/global and crypto/keys, advance smoothly.
let metaGlobal = MetaGlobal(syncID: "id", storageVersion: 5, engines: [String: EngineMeta](), declined: [])
let cryptoKeys = Keys.random()
cryptoKeys.collectionKeys.updateValue(KeyBundle.random(), forKey: "bookmarks")
cryptoKeys.collectionKeys.updateValue(KeyBundle.random(), forKey: "clients")
storeMetaGlobal(metaGlobal: metaGlobal)
storeCryptoKeys(keys: cryptoKeys)
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have downloaded meta/global and crypto/keys.
XCTAssertEqual(ready.scratchpad.global?.value, metaGlobal)
XCTAssertEqual(ready.scratchpad.keys?.value, cryptoKeys)
// We should have marked all local engines for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["bookmarks", "clients", "history", "passwords", "tabs"])
ready.clearLocalCommands()
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
let afterFirstSync = Date.now()
// Store a fresh crypto/keys, with the same default key, one identical collection key, and one changed collection key.
let freshCryptoKeys = Keys(defaultBundle: cryptoKeys.defaultBundle)
freshCryptoKeys.collectionKeys.updateValue(cryptoKeys.forCollection("bookmarks"), forKey: "bookmarks")
freshCryptoKeys.collectionKeys.updateValue(KeyBundle.random(), forKey: "clients")
storeCryptoKeys(keys: freshCryptoKeys)
// Now, run through the state machine again.
let secondExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have not downloaded a fresh meta/global ...
XCTAssertLessThan(ready.scratchpad.global?.timestamp ?? Timestamp.max, afterFirstSync)
// ... but we should have downloaded a fresh crypto/keys.
XCTAssertGreaterThanOrEqual(ready.scratchpad.keys?.timestamp ?? Timestamp.min, afterFirstSync)
// We should have marked only the local engine with a changed key for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["clients"])
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
secondExpectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
let afterSecondSync = Date.now()
// Store a fresh crypto/keys, with a changed default key and one identical collection key, and one changed collection key.
let freshCryptoKeys2 = Keys.random()
freshCryptoKeys2.collectionKeys.updateValue(freshCryptoKeys.forCollection("bookmarks"), forKey: "bookmarks")
freshCryptoKeys2.collectionKeys.updateValue(KeyBundle.random(), forKey: "clients")
storeCryptoKeys(keys: freshCryptoKeys2)
// Now, run through the state machine again.
let thirdExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have not downloaded a fresh meta/global ...
XCTAssertLessThan(ready.scratchpad.global?.timestamp ?? Timestamp.max, afterSecondSync)
// ... but we should have downloaded a fresh crypto/keys.
XCTAssertGreaterThanOrEqual(ready.scratchpad.keys?.timestamp ?? Timestamp.min, afterSecondSync)
// We should have marked all local engines as needing reset, except for the engine whose key remained constant.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["clients", "history", "passwords", "tabs"])
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
thirdExpectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
let afterThirdSync = Date.now()
// Now store a random crypto/keys, with a different default key (and no bulk keys).
let randomCryptoKeys = Keys.random()
storeCryptoKeys(keys: randomCryptoKeys)
// Now, run through the state machine again.
let fourthExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have not downloaded a fresh meta/global ...
XCTAssertLessThan(ready.scratchpad.global?.timestamp ?? Timestamp.max, afterThirdSync)
// ... but we should have downloaded a fresh crypto/keys.
XCTAssertGreaterThanOrEqual(ready.scratchpad.keys?.timestamp ?? Timestamp.min, afterThirdSync)
// We should have marked all local engines for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["bookmarks", "clients", "history", "passwords", "tabs"])
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
fourthExpectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
private func createUnusualMetaGlobal() -> MetaGlobal {
let metaGlobal = MetaGlobal(syncID: "id", storageVersion: 5,
engines: ["bookmarks": EngineMeta(version: 1, syncID: "bookmarks"), "unknownEngine1": EngineMeta(version: 2, syncID: "engineId1")],
declined: ["clients", "forms", "unknownEngine2"])
return metaGlobal
}
func testEngineConfigurations() {
// When encountering a valid meta/global and crypto/keys, advance smoothly. Keep the engine configuration for re-upload.
let metaGlobal = createUnusualMetaGlobal()
let cryptoKeys = Keys.random()
storeMetaGlobal(metaGlobal: metaGlobal)
storeCryptoKeys(keys: cryptoKeys)
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// We should have saved the engine configuration.
XCTAssertNotNil(ready.scratchpad.engineConfiguration)
guard let engineConfiguration = ready.scratchpad.engineConfiguration else {
return
}
XCTAssertEqual(engineConfiguration, metaGlobal.engineConfiguration())
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
// Wipe meta/global.
server.removeAllItemsFromCollection(collection: "meta", atTime: Date.now())
// Now, run through the state machine again. We should produce and upload a meta/global reflecting our engine configuration.
let secondExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "missingMetaGlobal", "freshStartRequired", "serverConfigurationRequired", "initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// The downloaded meta/global should reflect our local engine configuration.
XCTAssertNotNil(ready.scratchpad.global)
guard let global = ready.scratchpad.global?.value else {
return
}
XCTAssertEqual(global.engineConfiguration(), metaGlobal.engineConfiguration())
// We should have the same cached engine configuration.
XCTAssertNotNil(ready.scratchpad.engineConfiguration)
guard let engineConfiguration = ready.scratchpad.engineConfiguration else {
return
}
XCTAssertEqual(engineConfiguration, metaGlobal.engineConfiguration())
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
secondExpectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testMetaGlobalModified() {
// When encountering a valid meta/global and crypto/keys, advance smoothly.
let metaGlobal = createUnusualMetaGlobal()
let cryptoKeys = Keys.random()
storeMetaGlobal(metaGlobal: metaGlobal)
storeCryptoKeys(keys: cryptoKeys)
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have downloaded meta/global and crypto/keys.
XCTAssertEqual(ready.scratchpad.global?.value, metaGlobal)
XCTAssertEqual(ready.scratchpad.keys?.value, cryptoKeys)
// We should have marked all local engines for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["bookmarks", "clients", "history", "passwords", "tabs"])
XCTAssertEqual(ready.enginesEnabled(), [])
XCTAssertEqual(ready.enginesDisabled(), [])
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
let afterFirstSync = Date.now()
// Store a meta/global with a new global syncID.
let newMetaGlobal = metaGlobal.withSyncID("newID")
storeMetaGlobal(metaGlobal: newMetaGlobal)
// Now, run through the state machine again.
let secondExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have downloaded a fresh meta/global ...
XCTAssertGreaterThanOrEqual(ready.scratchpad.global?.timestamp ?? Timestamp.min, afterFirstSync)
// ... and we should have downloaded a fresh crypto/keys -- but its timestamp is identical to the old one!
// Therefore, the "needsFreshCryptoKeys" stage above is our test that we re-downloaded crypto/keys.
// We should have marked all local engines for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["bookmarks", "clients", "history", "passwords", "tabs"])
// And our engine configuration should be unchanged.
XCTAssertNotNil(ready.scratchpad.global)
guard let global = ready.scratchpad.global?.value else {
return
}
XCTAssertEqual(global.engineConfiguration(), metaGlobal.engineConfiguration())
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
secondExpectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
// Now store a meta/global with a changed engine syncID, a new engine, and a new declined entry.
var engines = newMetaGlobal.engines
engines.updateValue(EngineMeta(version: 1, syncID: Bytes.generateGUID()), forKey: "bookmarks")
engines.updateValue(EngineMeta(version: 1, syncID: Bytes.generateGUID()), forKey: "forms")
engines.removeValue(forKey: "unknownEngine1")
var declined = newMetaGlobal.declined.filter({ $0 != "forms" })
declined.append("unknownEngine1")
let secondMetaGlobal = MetaGlobal(syncID: newMetaGlobal.syncID, storageVersion: 5, engines: engines, declined: declined)
storeMetaGlobal(metaGlobal: secondMetaGlobal)
syncPrefs.removeObjectForKey("scratchpad.localCommands")
// Now, run through the state machine again.
let thirdExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have downloaded a fresh meta/global ...
XCTAssertGreaterThanOrEqual(ready.scratchpad.global?.timestamp ?? Timestamp.min, afterFirstSync)
// ... and we should have downloaded a fresh crypto/keys -- but its timestamp is identical to the old one!
// Therefore, the "needsFreshCryptoKeys" stage above is our test that we re-downloaded crypto/keys.
// We should have marked the changed engine for local reset, and identified the enabled and disabled engines.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["bookmarks"])
XCTAssertEqual(ready.enginesEnabled(), ["forms"])
XCTAssertEqual(ready.enginesDisabled(), ["unknownEngine1"])
// And our engine configuration should reflect the new meta/global on the server.
XCTAssertNotNil(ready.scratchpad.global)
guard let global = ready.scratchpad.global?.value else {
return
}
XCTAssertEqual(global.engineConfiguration(), secondMetaGlobal.engineConfiguration())
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
thirdExpectation.fulfill()
}
waitForExpectations(timeout: 25) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
}