]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/tests/MockCloudKit.m
Security-59306.61.1.tar.gz
[apple/security.git] / keychain / ckks / tests / MockCloudKit.m
1 /*
2 * Copyright (c) 2016 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #if OCTAGON
25
26 #import "keychain/ckks/tests/MockCloudKit.h"
27 #import "keychain/ckks/CKKS.h"
28 #import "keychain/ckks/CKKSRecordHolder.h"
29 #import "keychain/ckks/CKKSReachabilityTracker.h"
30
31 #import <CloudKit/CloudKit.h>
32 #import <CloudKit/CloudKit_Private.h>
33 #include <security_utilities/debugging.h>
34 #import <Foundation/Foundation.h>
35 #import <Foundation/NSDistributedNotificationCenter.h>
36
37 @implementation FakeCKOperation
38
39 - (BOOL)isFinishingOnCallbackQueue
40 {
41 return NO;
42 }
43 @end
44
45 @implementation FakeCKModifyRecordZonesOperation
46 @synthesize database = _database;
47 @synthesize recordZonesToSave = _recordZonesToSave;
48 @synthesize recordZoneIDsToDelete = _recordZoneIDsToDelete;
49 @synthesize modifyRecordZonesCompletionBlock = _modifyRecordZonesCompletionBlock;
50 @synthesize group = _group;
51
52 - (CKOperationConfiguration*)configuration {
53 return _configuration;
54 }
55
56 - (void)setConfiguration:(CKOperationConfiguration*)configuration {
57 if(configuration) {
58 _configuration = configuration;
59 } else {
60 _configuration = [[CKOperationConfiguration alloc] init];
61 }
62 }
63
64 - (instancetype)initWithRecordZonesToSave:(nullable NSArray<CKRecordZone *> *)recordZonesToSave recordZoneIDsToDelete:(nullable NSArray<CKRecordZoneID *> *)recordZoneIDsToDelete {
65 if(self = [super init]) {
66 _recordZonesToSave = recordZonesToSave;
67 _recordZoneIDsToDelete = recordZoneIDsToDelete;
68 _modifyRecordZonesCompletionBlock = nil;
69
70 _recordZonesSaved = nil;
71 _recordZoneIDsDeleted = nil;
72 _creationError = nil;
73
74 __weak __typeof(self) weakSelf = self;
75 self.completionBlock = ^{
76 __strong __typeof(weakSelf) strongSelf = weakSelf;
77 if(!strongSelf) {
78 secerror("ckks: received callback for released object");
79 return;
80 }
81
82 strongSelf.modifyRecordZonesCompletionBlock(strongSelf.recordZonesSaved, strongSelf.recordZoneIDsDeleted, strongSelf.creationError);
83 };
84 }
85 return self;
86 }
87
88 -(void)main {
89 // Create the zones we want; delete the ones we don't
90 // No error handling whatsoever
91 FakeCKDatabase* ckdb = [FakeCKModifyRecordZonesOperation ckdb];
92
93 NSError* possibleError = [FakeCKModifyRecordZonesOperation shouldFailModifyRecordZonesOperation];
94 if(possibleError) {
95 self.creationError = possibleError;
96 return;
97 }
98
99 for(CKRecordZone* zone in self.recordZonesToSave) {
100 bool skipCreation = false;
101 FakeCKZone* fakezone = ckdb[zone.zoneID];
102 if(fakezone.failCreationSilently) {
103 // Don't report an error, but do delete the zone
104 ckdb[zone.zoneID] = nil;
105 skipCreation = true;
106
107 } else if(fakezone.creationError) {
108
109 // Not the best way to do this, but it's an error
110 // Needs fixing if you want to support multiple zone failures
111 self.creationError = fakezone.creationError;
112
113 // 'clear' the error
114 ckdb[zone.zoneID] = nil;
115 skipCreation = true;
116
117 } else if(fakezone) {
118 // Don't remake the zone, but report to the client that it was created
119 skipCreation = true;
120 }
121
122 if(!skipCreation) {
123 // Create the zone:
124 secnotice("ckks", "Creating zone %@", zone);
125 ckdb[zone.zoneID] = [[FakeCKZone alloc] initZone: zone.zoneID];
126 }
127
128 if(!self.recordZonesSaved) {
129 self.recordZonesSaved = [[NSMutableArray alloc] init];
130 }
131 [self.recordZonesSaved addObject:zone];
132 }
133
134 for(CKRecordZoneID* zoneID in self.recordZoneIDsToDelete) {
135 FakeCKZone* zone = ckdb[zoneID];
136
137 if(zone) {
138 // The zone exists.
139 [FakeCKModifyRecordZonesOperation ensureZoneDeletionAllowed:zone];
140
141 ckdb[zoneID] = nil;
142
143 if(!self.recordZoneIDsDeleted) {
144 self.recordZoneIDsDeleted = [[NSMutableArray alloc] init];
145 }
146 [self.recordZoneIDsDeleted addObject:zoneID];
147
148 } else {
149 // The zone does not exist! CloudKit will tell us that the deletion failed.
150 if(!self.creationError) {
151 self.creationError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain code:CKErrorPartialFailure userInfo:@{
152 CKErrorRetryAfterKey: @(0.2),
153 }];
154 }
155
156 // There really should be a better way to do this...
157 NSMutableDictionary* newDictionary = [self.creationError.userInfo mutableCopy] ?: [NSMutableDictionary dictionary];
158 NSMutableDictionary* newPartials = newDictionary[CKPartialErrorsByItemIDKey] ?: [NSMutableDictionary dictionary];
159 newPartials[zoneID] = [[CKPrettyError alloc] initWithDomain:CKErrorDomain code:CKErrorZoneNotFound
160 userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Mock CloudKit: zone '%@' not found", zoneID.zoneName]}];
161 newDictionary[CKPartialErrorsByItemIDKey] = newPartials;
162
163 self.creationError = [[CKPrettyError alloc] initWithDomain:self.creationError.domain code:self.creationError.code userInfo:newDictionary];
164 }
165 }
166 }
167
168 +(FakeCKDatabase*) ckdb {
169 // Shouldn't ever be called: must be mocked out.
170 @throw [NSException exceptionWithName:NSInternalInconsistencyException
171 reason:[NSString stringWithFormat:@"+ckdb[] must be mocked out for use"]
172 userInfo:nil];
173 }
174
175 + (NSError* _Nullable)shouldFailModifyRecordZonesOperation
176 {
177 // Should be mocked out!
178 return nil;
179 }
180
181 +(void)ensureZoneDeletionAllowed:(FakeCKZone*)zone {
182 // Shouldn't ever be called; will be mocked out
183 (void)zone;
184 }
185 @end
186
187 @implementation FakeCKModifySubscriptionsOperation
188 @synthesize database = _database;
189 @synthesize group = _group;
190 @synthesize subscriptionsToSave = _subscriptionsToSave;
191 @synthesize subscriptionIDsToDelete = _subscriptionIDsToDelete;
192 @synthesize modifySubscriptionsCompletionBlock = _modifySubscriptionsCompletionBlock;
193
194 - (CKOperationConfiguration*)configuration {
195 return _configuration;
196 }
197
198 - (void)setConfiguration:(CKOperationConfiguration*)configuration {
199 if(configuration) {
200 _configuration = configuration;
201 } else {
202 _configuration = [[CKOperationConfiguration alloc] init];
203 }
204 }
205
206 - (instancetype)initWithSubscriptionsToSave:(nullable NSArray<CKSubscription *> *)subscriptionsToSave subscriptionIDsToDelete:(nullable NSArray<NSString *> *)subscriptionIDsToDelete {
207 if(self = [super init]) {
208 _subscriptionsToSave = subscriptionsToSave;
209 _subscriptionIDsToDelete = subscriptionIDsToDelete;
210 _modifySubscriptionsCompletionBlock = nil;
211
212 __weak __typeof(self) weakSelf = self;
213 self.completionBlock = ^{
214 __strong __typeof(weakSelf) strongSelf = weakSelf;
215 if(!strongSelf) {
216 secerror("ckks: received callback for released object");
217 return;
218 }
219
220 strongSelf.modifySubscriptionsCompletionBlock(strongSelf.subscriptionsSaved, strongSelf.subscriptionIDsDeleted, strongSelf.subscriptionError);
221 };
222 }
223 return self;
224 }
225
226 -(void)main {
227 FakeCKDatabase* ckdb = [FakeCKModifySubscriptionsOperation ckdb];
228
229 // Are these CKRecordZoneSubscription? Who knows!
230 for(CKRecordZoneSubscription* subscription in self.subscriptionsToSave) {
231 FakeCKZone* fakezone = ckdb[subscription.zoneID];
232
233 if(!fakezone) {
234 // This is an error: the zone doesn't exist
235 ckksnotice("fakeck", subscription.zoneID, "failing subscription for missing zone");
236 self.subscriptionError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
237 code:CKErrorPartialFailure
238 userInfo:@{
239 CKErrorRetryAfterKey: @(0.2),
240 CKPartialErrorsByItemIDKey:
241 @{subscription.zoneID:[[CKPrettyError alloc] initWithDomain:CKErrorDomain
242 code:CKErrorZoneNotFound
243 userInfo:@{}]}
244 }];
245
246 } else if(fakezone.subscriptionError) {
247 ckksnotice("fakeck", subscription.zoneID, "failing subscription with injected error %@", fakezone.subscriptionError);
248 // Not the best way to do this, but it's an error
249 // Needs fixing if you want to support multiple zone failures
250 self.subscriptionError = fakezone.subscriptionError;
251
252 // 'clear' the error
253 fakezone.subscriptionError = nil;
254 } else {
255 ckksnotice("fakeck", subscription.zoneID, "Successfully subscribed to zone");
256 if(!self.subscriptionsSaved) {
257 self.subscriptionsSaved = [[NSMutableArray alloc] init];
258 }
259 [self.subscriptionsSaved addObject:subscription];
260 }
261 }
262
263 for(NSString* subscriptionID in self.subscriptionIDsToDelete) {
264 secnotice("fakeck", "Successfully deleted subscription: %@", subscriptionID);
265 if(!self.subscriptionIDsDeleted) {
266 self.subscriptionIDsDeleted = [[NSMutableArray alloc] init];
267 }
268
269 [self.subscriptionIDsDeleted addObject:subscriptionID];
270 }
271 }
272
273 +(FakeCKDatabase*) ckdb {
274 // Shouldn't ever be called: must be mocked out.
275 @throw [NSException exceptionWithName:NSInternalInconsistencyException
276 reason:[NSString stringWithFormat:@"+ckdb[] must be mocked out for use"]
277 userInfo:nil];
278 }
279 @end
280
281 @implementation FakeCKFetchRecordZoneChangesOperation
282 @synthesize database = _database;
283 @synthesize recordZoneIDs = _recordZoneIDs;
284 @synthesize configurationsByRecordZoneID = _configurationsByRecordZoneID;
285
286 @synthesize fetchAllChanges = _fetchAllChanges;
287 @synthesize recordChangedBlock = _recordChangedBlock;
288
289 @synthesize recordWithIDWasDeletedBlock = _recordWithIDWasDeletedBlock;
290 @synthesize recordZoneChangeTokensUpdatedBlock = _recordZoneChangeTokensUpdatedBlock;
291 @synthesize recordZoneFetchCompletionBlock = _recordZoneFetchCompletionBlock;
292 @synthesize fetchRecordZoneChangesCompletionBlock = _fetchRecordZoneChangesCompletionBlock;
293
294 @synthesize operationID = _operationID;
295 @synthesize resolvedConfiguration = _resolvedConfiguration;
296 @synthesize group = _group;
297
298 - (CKOperationConfiguration*)configuration {
299 return _configuration;
300 }
301
302 - (void)setConfiguration:(CKOperationConfiguration*)configuration {
303 if(configuration) {
304 _configuration = configuration;
305 } else {
306 _configuration = [[CKOperationConfiguration alloc] init];
307 }
308 }
309
310 - (instancetype)initWithRecordZoneIDs:(NSArray<CKRecordZoneID *> *)recordZoneIDs configurationsByRecordZoneID:(nullable NSDictionary<CKRecordZoneID *, CKFetchRecordZoneChangesConfiguration *> *)configurationsByRecordZoneID {
311 if(self = [super init]) {
312 _recordZoneIDs = recordZoneIDs;
313 _configurationsByRecordZoneID = configurationsByRecordZoneID;
314
315 _operationID = @"fake-operation-ID";
316 }
317 return self;
318 }
319
320 + (bool)isNetworkReachable
321 {
322 // For mocking purposes.
323 return true;
324 }
325
326 - (void)main {
327 // iterate through database, and return items that aren't in lastDatabase
328 FakeCKDatabase* ckdb = [FakeCKFetchRecordZoneChangesOperation ckdb];
329 if(self.recordZoneIDs.count == 0) {
330 secerror("fakeck: No zones to fetch. Likely a bug?");
331 }
332
333 for(CKRecordZoneID* zoneID in self.recordZoneIDs) {
334 FakeCKZone* zone = ckdb[zoneID];
335 if(!zone) {
336 // Only really supports a single zone failure
337 ckksnotice("fakeck", zoneID, "Fetched for a missing zone %@", zoneID);
338 NSError* zoneNotFoundError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
339 code:CKErrorZoneNotFound
340 userInfo:@{}];
341 NSError* error = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
342 code:CKErrorPartialFailure
343 userInfo:@{CKPartialErrorsByItemIDKey: @{zoneID:zoneNotFoundError}}];
344
345 self.fetchRecordZoneChangesCompletionBlock(error);
346 return;
347 }
348
349 ++zone.fetchRecordZoneChangesOperationCount;
350 [zone.fetchRecordZoneChangesTimestamps addObject: [NSDate date]];
351
352 bool networkReachable = [FakeCKFetchRecordZoneChangesOperation isNetworkReachable];
353 if (!networkReachable) {
354 NSError *networkError = [NSError errorWithDomain:CKErrorDomain code:CKErrorNetworkFailure userInfo:NULL];
355 self.fetchRecordZoneChangesCompletionBlock(networkError);
356 return;
357 }
358
359 // Not precisely correct in the case of multiple zone fetches.
360 NSError* mockError = [zone popFetchChangesError];
361 if(mockError) {
362 self.fetchRecordZoneChangesCompletionBlock(mockError);
363 return;
364 }
365
366 // Extract the database at the last time they asked
367 CKServerChangeToken* fetchToken = self.configurationsByRecordZoneID[zoneID].previousServerChangeToken;
368 __block NSMutableDictionary<CKRecordID*, CKRecord*>* lastDatabase = nil;
369 __block NSDictionary<CKRecordID*, CKRecord*>* currentDatabase = nil;
370 __block CKServerChangeToken* currentChangeToken = nil;
371 __block bool moreComing = false;
372
373 __block NSError* opError = nil;
374
375 dispatch_sync(zone.queue, ^{
376 lastDatabase = fetchToken ? zone.pastDatabases[fetchToken] : nil;
377
378 // You can fetch with the current change token; that's fine
379 if([fetchToken isEqual:zone.currentChangeToken]) {
380 lastDatabase = zone.currentDatabase;
381 }
382
383 currentDatabase = zone.currentDatabase;
384 currentChangeToken = zone.currentChangeToken;
385
386 if (zone.limitFetchTo != nil) {
387 currentDatabase = zone.pastDatabases[zone.limitFetchTo];
388 currentChangeToken = zone.limitFetchTo;
389 zone.limitFetchTo = nil;
390 opError = zone.limitFetchError;
391 moreComing = true;
392 }
393 });
394
395 ckksnotice("fakeck", zone.zoneID, "FakeCKFetchRecordZoneChangesOperation(%@): database is currently %@ change token %@ database then: %@", zone.zoneID, currentDatabase, fetchToken, lastDatabase);
396
397 if(!lastDatabase && fetchToken) {
398 ckksnotice("fakeck", zone.zoneID, "no database for this change token: failing fetch with 'CKErrorChangeTokenExpired'");
399 self.fetchRecordZoneChangesCompletionBlock([[CKPrettyError alloc]
400 initWithDomain:CKErrorDomain
401 code:CKErrorPartialFailure userInfo:@{CKPartialErrorsByItemIDKey:
402 @{zoneID:[[CKPrettyError alloc] initWithDomain:CKErrorDomain code:CKErrorChangeTokenExpired userInfo:@{}]}
403 }]);
404 return;
405 }
406
407 [currentDatabase enumerateKeysAndObjectsUsingBlock:^(CKRecordID * _Nonnull recordID, CKRecord * _Nonnull record, BOOL * _Nonnull stop) {
408 id last = [lastDatabase objectForKey: recordID];
409 if(!last || ![record isEqual:last]) {
410 self.recordChangedBlock(record);
411 }
412 }];
413
414 // iterate through lastDatabase, and delete items that aren't in database
415 [lastDatabase enumerateKeysAndObjectsUsingBlock:^(CKRecordID * _Nonnull recordID, CKRecord * _Nonnull record, BOOL * _Nonnull stop) {
416
417 id current = [currentDatabase objectForKey: recordID];
418 if(current == nil) {
419 self.recordWithIDWasDeletedBlock(recordID, [record recordType]);
420 }
421 }];
422
423 self.recordZoneChangeTokensUpdatedBlock(zoneID, currentChangeToken, nil);
424 self.recordZoneFetchCompletionBlock(zoneID, currentChangeToken, nil, moreComing, opError);
425
426 if(self.blockAfterFetch) {
427 self.blockAfterFetch();
428 }
429
430 }
431
432 self.fetchRecordZoneChangesCompletionBlock(nil);
433 }
434
435 +(FakeCKDatabase*) ckdb {
436 // Shouldn't ever be called: must be mocked out.
437 @throw [NSException exceptionWithName:NSInternalInconsistencyException
438 reason:[NSString stringWithFormat:@"+ckdb[] must be mocked out for use"]
439 userInfo:nil];
440 }
441 @end
442
443 @implementation FakeCKFetchRecordsOperation
444 @synthesize database = _database;
445 @synthesize recordIDs = _recordIDs;
446 @synthesize desiredKeys = _desiredKeys;
447 @synthesize configuration = _configuration;
448
449 @synthesize perRecordProgressBlock = _perRecordProgressBlock;
450 @synthesize perRecordCompletionBlock = _perRecordCompletionBlock;
451
452 @synthesize fetchRecordsCompletionBlock = _fetchRecordsCompletionBlock;
453
454 - (instancetype)init {
455 if((self = [super init])) {
456
457 }
458 return self;
459 }
460 - (instancetype)initWithRecordIDs:(NSArray<CKRecordID *> *)recordIDs {
461 if((self = [super init])) {
462 _recordIDs = recordIDs;
463 }
464 return self;
465 }
466
467 - (void)main {
468 FakeCKDatabase* ckdb = [FakeCKFetchRecordsOperation ckdb];
469
470 // Doesn't call the per-record progress block
471 NSMutableDictionary<CKRecordID*, CKRecord*>* records = [NSMutableDictionary dictionary];
472 NSError* operror = nil;
473
474 for(CKRecordID* recordID in self.recordIDs) {
475 CKRecordZoneID* zoneID = recordID.zoneID;
476 FakeCKZone* zone = ckdb[zoneID];
477
478 if(!zone) {
479 ckksnotice("fakeck", zoneID, "Fetched for a missing zone %@", zoneID);
480 NSError* zoneNotFoundError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
481 code:CKErrorZoneNotFound
482 userInfo:@{}];
483 NSError* error = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
484 code:CKErrorPartialFailure
485 userInfo:@{CKPartialErrorsByItemIDKey: @{zoneID:zoneNotFoundError}}];
486
487 // Not strictly right, but good enough for now
488 self.fetchRecordsCompletionBlock(nil, error);
489 return;
490 }
491
492 CKRecord* record = zone.currentDatabase[recordID];
493 if(record) {
494 if(self.perRecordCompletionBlock) {
495 self.perRecordCompletionBlock(record, recordID, nil);
496 }
497 records[recordID] = record;
498 } else {
499 secerror("fakeck: Should be an error fetching %@", recordID);
500
501 if(!operror) {
502 operror = [[CKPrettyError alloc] initWithDomain:CKErrorDomain code:CKErrorPartialFailure userInfo:nil];
503 }
504
505 // There really should be a better way to do this...
506 NSMutableDictionary* newDictionary = [operror.userInfo mutableCopy] ?: [NSMutableDictionary dictionary];
507 NSMutableDictionary* newPartials = newDictionary[CKPartialErrorsByItemIDKey] ?: [NSMutableDictionary dictionary];
508 newPartials[recordID] = [[CKPrettyError alloc] initWithDomain:operror.domain code:CKErrorUnknownItem
509 userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Mock CloudKit: no record of %@", recordID]}];
510 newDictionary[CKPartialErrorsByItemIDKey] = newPartials;
511
512 operror = [[CKPrettyError alloc] initWithDomain:operror.domain code:operror.code userInfo:newDictionary];
513
514 /// TODO: do this better
515 if(self.perRecordCompletionBlock) {
516 self.perRecordCompletionBlock(nil, recordID, newPartials[zoneID]);
517 }
518 }
519 }
520
521 if(self.fetchRecordsCompletionBlock) {
522 self.fetchRecordsCompletionBlock(records, operror);
523 }
524 }
525
526 +(FakeCKDatabase*) ckdb {
527 // Shouldn't ever be called: must be mocked out.
528 @throw [NSException exceptionWithName:NSInternalInconsistencyException
529 reason:[NSString stringWithFormat:@"+ckdb[] must be mocked out for use"]
530 userInfo:nil];
531 }
532 @end
533
534
535 @implementation FakeCKQueryOperation
536 @synthesize query = _query;
537 @synthesize cursor = _cursor;
538 @synthesize zoneID = _zoneID;
539 @synthesize resultsLimit = _resultsLimit;
540 @synthesize desiredKeys = _desiredKeys;
541 @synthesize recordFetchedBlock = _recordFetchedBlock;
542 @synthesize queryCompletionBlock = _queryCompletionBlock;
543
544 - (instancetype)initWithQuery:(CKQuery *)query {
545 if((self = [super init])) {
546 _query = query;
547 }
548 return self;
549 }
550
551 - (void)main {
552 FakeCKDatabase* ckdb = [FakeCKFetchRecordsOperation ckdb];
553
554 FakeCKZone* zone = ckdb[self.zoneID];
555 if(!zone) {
556 ckksnotice("fakeck", self.zoneID, "Queried a missing zone %@", self.zoneID);
557
558 // I'm really not sure if this is right, but...
559 NSError* zoneNotFoundError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
560 code:CKErrorZoneNotFound
561 userInfo:@{
562 CKErrorRetryAfterKey: @(0.2),
563 }];
564 self.queryCompletionBlock(nil, zoneNotFoundError);
565 return;
566 }
567
568 NSMutableArray<CKRecord*>* matches = [NSMutableArray array];
569 for(CKRecordID* recordID in zone.currentDatabase.keyEnumerator) {
570 CKRecord* record = zone.currentDatabase[recordID];
571
572 if([self.query.recordType isEqualToString: record.recordType] &&
573 [self.query.predicate evaluateWithObject:record]) {
574
575 [matches addObject:record];
576 self.recordFetchedBlock(record);
577 }
578 }
579
580 if(self.queryCompletionBlock) {
581 // The query cursor will be non-null if there are more than self.resultsLimit classes. Don't implement this.
582 self.queryCompletionBlock(nil, nil);
583 }
584 }
585
586
587 +(FakeCKDatabase*) ckdb {
588 // Shouldn't ever be called: must be mocked out.
589 @throw [NSException exceptionWithName:NSInternalInconsistencyException
590 reason:[NSString stringWithFormat:@"+ckdb[] must be mocked out for use"]
591 userInfo:nil];
592 }
593 @end
594
595
596
597 // Do literally nothing
598 @implementation FakeAPSConnection
599 @synthesize delegate;
600
601 - (id)initWithEnvironmentName:(NSString *)environmentName namedDelegatePort:(NSString*)namedDelegatePort queue:(dispatch_queue_t)queue {
602 if(self = [super init]) {
603 }
604 return self;
605 }
606
607 - (void)setEnabledTopics:(NSArray<NSString *> *)enabledTopics {
608 }
609
610 - (void)setDarkWakeTopics:(NSArray<NSString *> *)darkWakeTopics {
611 }
612
613 @end
614
615 // Do literally nothing
616
617 @implementation FakeNSNotificationCenter
618 + (instancetype)defaultCenter {
619 return [[FakeNSNotificationCenter alloc] init];
620 }
621 - (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject {
622 }
623 - (void)removeObserver:(id)observer {
624 }
625 @end
626
627 @implementation FakeNSDistributedNotificationCenter
628 + (instancetype)defaultCenter
629 {
630 return [[FakeNSDistributedNotificationCenter alloc] init];
631 }
632 - (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject {
633 }
634 - (void)removeObserver:(id)observer {
635 }
636 - (void)postNotificationName:(NSNotificationName)name object:(nullable NSString *)object userInfo:(nullable NSDictionary *)userInfo options:(NSDistributedNotificationOptions)options
637 {
638 }
639 @end
640
641
642 @interface FakeCKZone ()
643 @property NSMutableArray<NSError*>* fetchErrors;
644 @end
645
646 @implementation FakeCKZone
647 - (instancetype)initZone: (CKRecordZoneID*) zoneID {
648 if(self = [super init]) {
649
650 _zoneID = zoneID;
651 _currentDatabase = [[NSMutableDictionary alloc] init];
652 _pastDatabases = [[NSMutableDictionary alloc] init];
653
654 _fetchErrors = [[NSMutableArray alloc] init];
655
656 _queue = dispatch_queue_create("fake-ckzone", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
657
658 _limitFetchTo = nil;
659 _fetchRecordZoneChangesOperationCount = 0;
660 _fetchRecordZoneChangesTimestamps = [[NSMutableArray alloc] init];
661 dispatch_sync(_queue, ^{
662 [self _onqueueRollChangeToken];
663 });
664 }
665 return self;
666 }
667
668 - (void)_onqueueRollChangeToken {
669 dispatch_assert_queue(self.queue);
670
671 NSData* changeToken = [[[NSUUID UUID] UUIDString] dataUsingEncoding:NSUTF8StringEncoding];
672 self.currentChangeToken = [[CKServerChangeToken alloc] initWithData: changeToken];
673 }
674
675 - (void)addToZone: (CKKSCKRecordHolder*) item zoneID: (CKRecordZoneID*) zoneID {
676 dispatch_sync(self.queue, ^{
677 [self _onqueueAddToZone:item zoneID:zoneID];
678 });
679 }
680
681 - (CKRecord*)_onqueueAddToZone:(CKKSCKRecordHolder*)item zoneID:(CKRecordZoneID*)zoneID {
682 dispatch_assert_queue(self.queue);
683
684 CKRecord* record = [item CKRecordWithZoneID: zoneID];
685
686 secnotice("fake-cloudkit", "adding item to zone(%@): %@", zoneID.zoneName, item);
687 secnotice("fake-cloudkit", "new record: %@", record);
688
689 [self _onqueueAddToZone: record];
690
691 // Save off the etag
692 item.storedCKRecord = record;
693 return record;
694 }
695
696 - (void)addToZone: (CKRecord*) record {
697 dispatch_sync(self.queue, ^{
698 [self _onqueueAddToZone:record];
699 });
700 }
701
702 - (CKRecord*)_onqueueAddToZone:(CKRecord*)record {
703 dispatch_assert_queue(self.queue);
704
705 // Save off this current databse
706 self.pastDatabases[self.currentChangeToken] = [self.currentDatabase mutableCopy];
707
708 [self _onqueueRollChangeToken];
709
710 record.etag = [self.currentChangeToken description];
711 ckksnotice("fakeck", self.zoneID, "change tag: %@ %@", record.recordChangeTag, record.recordID);
712 record.modificationDate = [NSDate date];
713 self.currentDatabase[record.recordID] = record;
714 return record;
715 }
716
717 - (NSError * _Nullable)errorFromSavingRecord:(CKRecord*) record {
718 CKRecord* existingRecord = self.currentDatabase[record.recordID];
719
720 // First, implement CKKS-specific server-side checks
721 if([record.recordType isEqualToString:SecCKRecordCurrentKeyType]) {
722 CKReference* parentKey = record[SecCKRecordParentKeyRefKey];
723
724 CKRecord* existingParentKey = self.currentDatabase[parentKey.recordID];
725
726 if(!existingParentKey) {
727 ckksnotice("fakeck", self.zoneID, "bad sync key reference! Fail the write: %@ %@", record, existingRecord);
728
729 return [FakeCKZone internalPluginError:@"CloudkitKeychainService" code:CKKSServerMissingRecord description:@"synckey record: record not found"];
730 }
731 }
732 //
733
734 if(existingRecord && ![existingRecord.recordChangeTag isEqualToString: record.recordChangeTag]) {
735 ckksnotice("fakeck", self.zoneID, "change tag mismatch! Fail the write: %@ %@", record, existingRecord);
736
737 // TODO: doesn't yet support CKRecordChangedErrorAncestorRecordKey, since I don't understand it
738 return [[CKPrettyError alloc] initWithDomain:CKErrorDomain code:CKErrorServerRecordChanged
739 userInfo:@{CKRecordChangedErrorClientRecordKey:record,
740 CKRecordChangedErrorServerRecordKey:existingRecord}];
741 }
742
743 if(!existingRecord && record.etag != nil) {
744 ckksnotice("fakeck", self.zoneID, "update to a record that doesn't exist! Fail the write: %@", record);
745 return [[CKPrettyError alloc] initWithDomain:CKErrorDomain code:CKErrorUnknownItem
746 userInfo:nil];
747 }
748 return nil;
749 }
750
751 - (void)addCKRecordToZone:(CKRecord*) record {
752 if([self errorFromSavingRecord: record]) {
753 ckksnotice("fakeck", self.zoneID, "change tag mismatch! Fail the write!");
754 }
755
756 [self addToZone: record];
757 }
758
759 - (void)deleteFromHistory:(CKRecordID*)recordID {
760 for(NSMutableDictionary* pastDatabase in self.pastDatabases.objectEnumerator) {
761 [pastDatabase removeObjectForKey:recordID];
762 }
763 [self.currentDatabase removeObjectForKey:recordID];
764 }
765
766
767 - (NSError*)deleteCKRecordIDFromZone:(CKRecordID*) recordID {
768 // todo: fail somehow
769 dispatch_sync(self.queue, ^{
770 self.pastDatabases[self.currentChangeToken] = [self.currentDatabase mutableCopy];
771 [self _onqueueRollChangeToken];
772
773 [self.currentDatabase removeObjectForKey: recordID];
774 });
775 return nil;
776 }
777
778 - (void)failNextFetchWith: (NSError*) fetchChangesError {
779 @synchronized(self.fetchErrors) {
780 [self.fetchErrors addObject: fetchChangesError];
781 }
782 }
783
784 - (NSError * _Nullable)popFetchChangesError {
785 NSError* error = nil;
786 @synchronized(self.fetchErrors) {
787 if(self.fetchErrors.count > 0) {
788 error = self.fetchErrors[0];
789 [self.fetchErrors removeObjectAtIndex:0];
790 }
791 }
792 return error;
793 }
794
795 + (NSError*)internalPluginError:(NSString*)serverDomain code:(NSInteger)code description:(NSString*)desc
796 {
797 // Note: uses SecCKKSContainerName, but that's probably okay
798 NSError* extensionError = [[CKPrettyError alloc] initWithDomain:serverDomain
799 code:code
800 userInfo:@{
801 CKErrorServerDescriptionKey: desc,
802 NSLocalizedDescriptionKey: desc,
803 }];
804 NSError* internalError = [[CKPrettyError alloc] initWithDomain:CKInternalErrorDomain
805 code:CKErrorInternalPluginError
806 userInfo:@{CKErrorServerDescriptionKey: desc,
807 NSLocalizedDescriptionKey: desc,
808 NSUnderlyingErrorKey: extensionError,
809 }];
810 NSError* error = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
811 code:CKErrorServerRejectedRequest
812 userInfo:@{NSUnderlyingErrorKey: internalError,
813 CKErrorServerDescriptionKey: desc,
814 NSLocalizedDescriptionKey: desc,
815 CKContainerIDKey: SecCKKSContainerName,
816 }];
817
818 return error;
819 }
820 @end
821
822 @implementation FakeCKKSNotifier
823 +(void)post:(NSString*)notification {
824 if(notification) {
825 // This isn't actually fake, but XCTest likes NSNotificationCenter a whole lot.
826 // These notifications shouldn't escape this process, so it's perfect.
827 secnotice("ckks", "sending fake NSNotification %@", notification);
828 [[NSNotificationCenter defaultCenter] postNotificationName:notification object:nil];
829 }
830 }
831 @end
832
833 #endif // OCTAGON
834