2 * Copyright (c) 2016 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
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"
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>
37 @implementation FakeCKOperation
39 - (BOOL)isFinishingOnCallbackQueue
45 @implementation FakeCKModifyRecordZonesOperation
46 @synthesize database = _database;
47 @synthesize recordZonesToSave = _recordZonesToSave;
48 @synthesize recordZoneIDsToDelete = _recordZoneIDsToDelete;
49 @synthesize modifyRecordZonesCompletionBlock = _modifyRecordZonesCompletionBlock;
50 @synthesize group = _group;
52 - (CKOperationConfiguration*)configuration {
53 return _configuration;
56 - (void)setConfiguration:(CKOperationConfiguration*)configuration {
58 _configuration = configuration;
60 _configuration = [[CKOperationConfiguration alloc] init];
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;
70 _recordZonesSaved = nil;
71 _recordZoneIDsDeleted = nil;
74 __weak __typeof(self) weakSelf = self;
75 self.completionBlock = ^{
76 __strong __typeof(weakSelf) strongSelf = weakSelf;
78 secerror("ckks: received callback for released object");
82 strongSelf.modifyRecordZonesCompletionBlock(strongSelf.recordZonesSaved, strongSelf.recordZoneIDsDeleted, strongSelf.creationError);
89 // Create the zones we want; delete the ones we don't
90 // No error handling whatsoever
91 FakeCKDatabase* ckdb = [FakeCKModifyRecordZonesOperation ckdb];
93 NSError* possibleError = [FakeCKModifyRecordZonesOperation shouldFailModifyRecordZonesOperation];
95 self.creationError = possibleError;
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;
107 } else if(fakezone.creationError) {
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;
114 ckdb[zone.zoneID] = nil;
117 } else if(fakezone) {
118 // Don't remake the zone, but report to the client that it was created
124 secnotice("ckks", "Creating zone %@", zone);
125 ckdb[zone.zoneID] = [[FakeCKZone alloc] initZone: zone.zoneID];
128 if(!self.recordZonesSaved) {
129 self.recordZonesSaved = [[NSMutableArray alloc] init];
131 [self.recordZonesSaved addObject:zone];
134 for(CKRecordZoneID* zoneID in self.recordZoneIDsToDelete) {
135 FakeCKZone* zone = ckdb[zoneID];
139 [FakeCKModifyRecordZonesOperation ensureZoneDeletionAllowed:zone];
143 if(!self.recordZoneIDsDeleted) {
144 self.recordZoneIDsDeleted = [[NSMutableArray alloc] init];
146 [self.recordZoneIDsDeleted addObject:zoneID];
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),
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;
163 self.creationError = [[CKPrettyError alloc] initWithDomain:self.creationError.domain code:self.creationError.code userInfo:newDictionary];
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"]
175 + (NSError* _Nullable)shouldFailModifyRecordZonesOperation
177 // Should be mocked out!
181 +(void)ensureZoneDeletionAllowed:(FakeCKZone*)zone {
182 // Shouldn't ever be called; will be mocked out
187 @implementation FakeCKModifySubscriptionsOperation
188 @synthesize database = _database;
189 @synthesize group = _group;
190 @synthesize subscriptionsToSave = _subscriptionsToSave;
191 @synthesize subscriptionIDsToDelete = _subscriptionIDsToDelete;
192 @synthesize modifySubscriptionsCompletionBlock = _modifySubscriptionsCompletionBlock;
194 - (CKOperationConfiguration*)configuration {
195 return _configuration;
198 - (void)setConfiguration:(CKOperationConfiguration*)configuration {
200 _configuration = configuration;
202 _configuration = [[CKOperationConfiguration alloc] init];
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;
212 __weak __typeof(self) weakSelf = self;
213 self.completionBlock = ^{
214 __strong __typeof(weakSelf) strongSelf = weakSelf;
216 secerror("ckks: received callback for released object");
220 strongSelf.modifySubscriptionsCompletionBlock(strongSelf.subscriptionsSaved, strongSelf.subscriptionIDsDeleted, strongSelf.subscriptionError);
227 FakeCKDatabase* ckdb = [FakeCKModifySubscriptionsOperation ckdb];
229 // Are these CKRecordZoneSubscription? Who knows!
230 for(CKRecordZoneSubscription* subscription in self.subscriptionsToSave) {
231 FakeCKZone* fakezone = ckdb[subscription.zoneID];
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
239 CKErrorRetryAfterKey: @(0.2),
240 CKPartialErrorsByItemIDKey:
241 @{subscription.zoneID:[[CKPrettyError alloc] initWithDomain:CKErrorDomain
242 code:CKErrorZoneNotFound
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;
253 fakezone.subscriptionError = nil;
255 ckksnotice("fakeck", subscription.zoneID, "Successfully subscribed to zone");
256 if(!self.subscriptionsSaved) {
257 self.subscriptionsSaved = [[NSMutableArray alloc] init];
259 [self.subscriptionsSaved addObject:subscription];
263 for(NSString* subscriptionID in self.subscriptionIDsToDelete) {
264 secnotice("fakeck", "Successfully deleted subscription: %@", subscriptionID);
265 if(!self.subscriptionIDsDeleted) {
266 self.subscriptionIDsDeleted = [[NSMutableArray alloc] init];
269 [self.subscriptionIDsDeleted addObject:subscriptionID];
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"]
281 @implementation FakeCKFetchRecordZoneChangesOperation
282 @synthesize database = _database;
283 @synthesize recordZoneIDs = _recordZoneIDs;
284 @synthesize configurationsByRecordZoneID = _configurationsByRecordZoneID;
286 @synthesize fetchAllChanges = _fetchAllChanges;
287 @synthesize recordChangedBlock = _recordChangedBlock;
289 @synthesize recordWithIDWasDeletedBlock = _recordWithIDWasDeletedBlock;
290 @synthesize recordZoneChangeTokensUpdatedBlock = _recordZoneChangeTokensUpdatedBlock;
291 @synthesize recordZoneFetchCompletionBlock = _recordZoneFetchCompletionBlock;
292 @synthesize fetchRecordZoneChangesCompletionBlock = _fetchRecordZoneChangesCompletionBlock;
294 @synthesize operationID = _operationID;
295 @synthesize resolvedConfiguration = _resolvedConfiguration;
296 @synthesize group = _group;
298 - (CKOperationConfiguration*)configuration {
299 return _configuration;
302 - (void)setConfiguration:(CKOperationConfiguration*)configuration {
304 _configuration = configuration;
306 _configuration = [[CKOperationConfiguration alloc] init];
310 - (instancetype)initWithRecordZoneIDs:(NSArray<CKRecordZoneID *> *)recordZoneIDs configurationsByRecordZoneID:(nullable NSDictionary<CKRecordZoneID *, CKFetchRecordZoneChangesConfiguration *> *)configurationsByRecordZoneID {
311 if(self = [super init]) {
312 _recordZoneIDs = recordZoneIDs;
313 _configurationsByRecordZoneID = configurationsByRecordZoneID;
315 _operationID = @"fake-operation-ID";
320 + (bool)isNetworkReachable
322 // For mocking purposes.
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?");
333 for(CKRecordZoneID* zoneID in self.recordZoneIDs) {
334 FakeCKZone* zone = ckdb[zoneID];
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
341 NSError* error = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
342 code:CKErrorPartialFailure
343 userInfo:@{CKPartialErrorsByItemIDKey: @{zoneID:zoneNotFoundError}}];
345 self.fetchRecordZoneChangesCompletionBlock(error);
349 ++zone.fetchRecordZoneChangesOperationCount;
350 [zone.fetchRecordZoneChangesTimestamps addObject: [NSDate date]];
352 bool networkReachable = [FakeCKFetchRecordZoneChangesOperation isNetworkReachable];
353 if (!networkReachable) {
354 NSError *networkError = [NSError errorWithDomain:CKErrorDomain code:CKErrorNetworkFailure userInfo:NULL];
355 self.fetchRecordZoneChangesCompletionBlock(networkError);
359 // Not precisely correct in the case of multiple zone fetches.
360 NSError* mockError = [zone popFetchChangesError];
362 self.fetchRecordZoneChangesCompletionBlock(mockError);
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;
373 __block NSError* opError = nil;
375 dispatch_sync(zone.queue, ^{
376 lastDatabase = fetchToken ? zone.pastDatabases[fetchToken] : nil;
378 // You can fetch with the current change token; that's fine
379 if([fetchToken isEqual:zone.currentChangeToken]) {
380 lastDatabase = zone.currentDatabase;
383 currentDatabase = zone.currentDatabase;
384 currentChangeToken = zone.currentChangeToken;
386 if (zone.limitFetchTo != nil) {
387 currentDatabase = zone.pastDatabases[zone.limitFetchTo];
388 currentChangeToken = zone.limitFetchTo;
389 zone.limitFetchTo = nil;
390 opError = zone.limitFetchError;
395 ckksnotice("fakeck", zone.zoneID, "FakeCKFetchRecordZoneChangesOperation(%@): database is currently %@ change token %@ database then: %@", zone.zoneID, currentDatabase, fetchToken, lastDatabase);
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:@{}]}
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);
414 // iterate through lastDatabase, and delete items that aren't in database
415 [lastDatabase enumerateKeysAndObjectsUsingBlock:^(CKRecordID * _Nonnull recordID, CKRecord * _Nonnull record, BOOL * _Nonnull stop) {
417 id current = [currentDatabase objectForKey: recordID];
419 self.recordWithIDWasDeletedBlock(recordID, [record recordType]);
423 self.recordZoneChangeTokensUpdatedBlock(zoneID, currentChangeToken, nil);
424 self.recordZoneFetchCompletionBlock(zoneID, currentChangeToken, nil, moreComing, opError);
426 if(self.blockAfterFetch) {
427 self.blockAfterFetch();
432 self.fetchRecordZoneChangesCompletionBlock(nil);
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"]
443 @implementation FakeCKFetchRecordsOperation
444 @synthesize database = _database;
445 @synthesize recordIDs = _recordIDs;
446 @synthesize desiredKeys = _desiredKeys;
447 @synthesize configuration = _configuration;
449 @synthesize perRecordProgressBlock = _perRecordProgressBlock;
450 @synthesize perRecordCompletionBlock = _perRecordCompletionBlock;
452 @synthesize fetchRecordsCompletionBlock = _fetchRecordsCompletionBlock;
454 - (instancetype)init {
455 if((self = [super init])) {
460 - (instancetype)initWithRecordIDs:(NSArray<CKRecordID *> *)recordIDs {
461 if((self = [super init])) {
462 _recordIDs = recordIDs;
468 FakeCKDatabase* ckdb = [FakeCKFetchRecordsOperation ckdb];
470 // Doesn't call the per-record progress block
471 NSMutableDictionary<CKRecordID*, CKRecord*>* records = [NSMutableDictionary dictionary];
472 NSError* operror = nil;
474 for(CKRecordID* recordID in self.recordIDs) {
475 CKRecordZoneID* zoneID = recordID.zoneID;
476 FakeCKZone* zone = ckdb[zoneID];
479 ckksnotice("fakeck", zoneID, "Fetched for a missing zone %@", zoneID);
480 NSError* zoneNotFoundError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
481 code:CKErrorZoneNotFound
483 NSError* error = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
484 code:CKErrorPartialFailure
485 userInfo:@{CKPartialErrorsByItemIDKey: @{zoneID:zoneNotFoundError}}];
487 // Not strictly right, but good enough for now
488 self.fetchRecordsCompletionBlock(nil, error);
492 CKRecord* record = zone.currentDatabase[recordID];
494 if(self.perRecordCompletionBlock) {
495 self.perRecordCompletionBlock(record, recordID, nil);
497 records[recordID] = record;
499 secerror("fakeck: Should be an error fetching %@", recordID);
502 operror = [[CKPrettyError alloc] initWithDomain:CKErrorDomain code:CKErrorPartialFailure userInfo:nil];
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;
512 operror = [[CKPrettyError alloc] initWithDomain:operror.domain code:operror.code userInfo:newDictionary];
514 /// TODO: do this better
515 if(self.perRecordCompletionBlock) {
516 self.perRecordCompletionBlock(nil, recordID, newPartials[zoneID]);
521 if(self.fetchRecordsCompletionBlock) {
522 self.fetchRecordsCompletionBlock(records, operror);
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"]
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;
544 - (instancetype)initWithQuery:(CKQuery *)query {
545 if((self = [super init])) {
552 FakeCKDatabase* ckdb = [FakeCKFetchRecordsOperation ckdb];
554 FakeCKZone* zone = ckdb[self.zoneID];
556 ckksnotice("fakeck", self.zoneID, "Queried a missing zone %@", self.zoneID);
558 // I'm really not sure if this is right, but...
559 NSError* zoneNotFoundError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
560 code:CKErrorZoneNotFound
562 CKErrorRetryAfterKey: @(0.2),
564 self.queryCompletionBlock(nil, zoneNotFoundError);
568 NSMutableArray<CKRecord*>* matches = [NSMutableArray array];
569 for(CKRecordID* recordID in zone.currentDatabase.keyEnumerator) {
570 CKRecord* record = zone.currentDatabase[recordID];
572 if([self.query.recordType isEqualToString: record.recordType] &&
573 [self.query.predicate evaluateWithObject:record]) {
575 [matches addObject:record];
576 self.recordFetchedBlock(record);
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);
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"]
597 // Do literally nothing
598 @implementation FakeAPSConnection
599 @synthesize delegate;
601 - (id)initWithEnvironmentName:(NSString *)environmentName namedDelegatePort:(NSString*)namedDelegatePort queue:(dispatch_queue_t)queue {
602 if(self = [super init]) {
607 - (void)setEnabledTopics:(NSArray<NSString *> *)enabledTopics {
610 - (void)setDarkWakeTopics:(NSArray<NSString *> *)darkWakeTopics {
615 // Do literally nothing
617 @implementation FakeNSNotificationCenter
618 + (instancetype)defaultCenter {
619 return [[FakeNSNotificationCenter alloc] init];
621 - (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject {
623 - (void)removeObserver:(id)observer {
627 @implementation FakeNSDistributedNotificationCenter
628 + (instancetype)defaultCenter
630 return [[FakeNSDistributedNotificationCenter alloc] init];
632 - (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject {
634 - (void)removeObserver:(id)observer {
636 - (void)postNotificationName:(NSNotificationName)name object:(nullable NSString *)object userInfo:(nullable NSDictionary *)userInfo options:(NSDistributedNotificationOptions)options
642 @interface FakeCKZone ()
643 @property NSMutableArray<NSError*>* fetchErrors;
646 @implementation FakeCKZone
647 - (instancetype)initZone: (CKRecordZoneID*) zoneID {
648 if(self = [super init]) {
651 _currentDatabase = [[NSMutableDictionary alloc] init];
652 _pastDatabases = [[NSMutableDictionary alloc] init];
654 _fetchErrors = [[NSMutableArray alloc] init];
656 _queue = dispatch_queue_create("fake-ckzone", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
659 _fetchRecordZoneChangesOperationCount = 0;
660 _fetchRecordZoneChangesTimestamps = [[NSMutableArray alloc] init];
661 dispatch_sync(_queue, ^{
662 [self _onqueueRollChangeToken];
668 - (void)_onqueueRollChangeToken {
669 dispatch_assert_queue(self.queue);
671 NSData* changeToken = [[[NSUUID UUID] UUIDString] dataUsingEncoding:NSUTF8StringEncoding];
672 self.currentChangeToken = [[CKServerChangeToken alloc] initWithData: changeToken];
675 - (void)addToZone: (CKKSCKRecordHolder*) item zoneID: (CKRecordZoneID*) zoneID {
676 dispatch_sync(self.queue, ^{
677 [self _onqueueAddToZone:item zoneID:zoneID];
681 - (CKRecord*)_onqueueAddToZone:(CKKSCKRecordHolder*)item zoneID:(CKRecordZoneID*)zoneID {
682 dispatch_assert_queue(self.queue);
684 CKRecord* record = [item CKRecordWithZoneID: zoneID];
686 secnotice("fake-cloudkit", "adding item to zone(%@): %@", zoneID.zoneName, item);
687 secnotice("fake-cloudkit", "new record: %@", record);
689 [self _onqueueAddToZone: record];
692 item.storedCKRecord = record;
696 - (void)addToZone: (CKRecord*) record {
697 dispatch_sync(self.queue, ^{
698 [self _onqueueAddToZone:record];
702 - (CKRecord*)_onqueueAddToZone:(CKRecord*)record {
703 dispatch_assert_queue(self.queue);
705 // Save off this current databse
706 self.pastDatabases[self.currentChangeToken] = [self.currentDatabase mutableCopy];
708 [self _onqueueRollChangeToken];
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;
717 - (NSError * _Nullable)errorFromSavingRecord:(CKRecord*) record {
718 CKRecord* existingRecord = self.currentDatabase[record.recordID];
720 // First, implement CKKS-specific server-side checks
721 if([record.recordType isEqualToString:SecCKRecordCurrentKeyType]) {
722 CKReference* parentKey = record[SecCKRecordParentKeyRefKey];
724 CKRecord* existingParentKey = self.currentDatabase[parentKey.recordID];
726 if(!existingParentKey) {
727 ckksnotice("fakeck", self.zoneID, "bad sync key reference! Fail the write: %@ %@", record, existingRecord);
729 return [FakeCKZone internalPluginError:@"CloudkitKeychainService" code:CKKSServerMissingRecord description:@"synckey record: record not found"];
734 if(existingRecord && ![existingRecord.recordChangeTag isEqualToString: record.recordChangeTag]) {
735 ckksnotice("fakeck", self.zoneID, "change tag mismatch! Fail the write: %@ %@", record, existingRecord);
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}];
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
751 - (void)addCKRecordToZone:(CKRecord*) record {
752 if([self errorFromSavingRecord: record]) {
753 ckksnotice("fakeck", self.zoneID, "change tag mismatch! Fail the write!");
756 [self addToZone: record];
759 - (void)deleteFromHistory:(CKRecordID*)recordID {
760 for(NSMutableDictionary* pastDatabase in self.pastDatabases.objectEnumerator) {
761 [pastDatabase removeObjectForKey:recordID];
763 [self.currentDatabase removeObjectForKey:recordID];
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];
773 [self.currentDatabase removeObjectForKey: recordID];
778 - (void)failNextFetchWith: (NSError*) fetchChangesError {
779 @synchronized(self.fetchErrors) {
780 [self.fetchErrors addObject: fetchChangesError];
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];
795 + (NSError*)internalPluginError:(NSString*)serverDomain code:(NSInteger)code description:(NSString*)desc
797 // Note: uses SecCKKSContainerName, but that's probably okay
798 NSError* extensionError = [[CKPrettyError alloc] initWithDomain:serverDomain
801 CKErrorServerDescriptionKey: desc,
802 NSLocalizedDescriptionKey: desc,
804 NSError* internalError = [[CKPrettyError alloc] initWithDomain:CKInternalErrorDomain
805 code:CKErrorInternalPluginError
806 userInfo:@{CKErrorServerDescriptionKey: desc,
807 NSLocalizedDescriptionKey: desc,
808 NSUnderlyingErrorKey: extensionError,
810 NSError* error = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
811 code:CKErrorServerRejectedRequest
812 userInfo:@{NSUnderlyingErrorKey: internalError,
813 CKErrorServerDescriptionKey: desc,
814 NSLocalizedDescriptionKey: desc,
815 CKContainerIDKey: SecCKKSContainerName,
822 @implementation FakeCKKSNotifier
823 +(void)post:(NSString*)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];