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 "CloudKitMockXCTest.h"
28 #import <ApplePushService/ApplePushService.h>
29 #import <Foundation/Foundation.h>
30 #import <CloudKit/CloudKit.h>
31 #import <CloudKit/CloudKit_Private.h>
32 #import <CloudKit/CKContainer_Private.h>
33 #import <OCMock/OCMock.h>
35 #include "OSX/sec/securityd/Regressions/SecdTestKeychainUtilities.h"
36 #include <utilities/SecFileLocations.h>
37 #include <securityd/SecItemServer.h>
40 #include <securityd/spi.h>
43 #include <Security/SecureObjectSync/SOSViews.h>
45 #include <utilities/SecDb.h>
46 #include <securityd/SecItemServer.h>
47 #include <keychain/ckks/CKKS.h>
48 #include <keychain/ckks/CKKSViewManager.h>
49 #include <keychain/ckks/CKKSKeychainView.h>
50 #include <keychain/ckks/CKKSItem.h>
51 #include <keychain/ckks/CKKSOutgoingQueueEntry.h>
52 #include <keychain/ckks/CKKSKey.h>
53 #include "keychain/ckks/CKKSGroupOperation.h"
54 #include "keychain/ckks/CKKSLockStateTracker.h"
56 #import "MockCloudKit.h"
58 @interface BoolHolder : NSObject
62 @implementation BoolHolder
65 // Inform OCMock about the internals of CKContainer
66 @interface CKContainer ()
67 - (void)_checkSelfCloudServicesEntitlement;
71 @implementation CloudKitMockXCTest
79 securityd_init_local_spi();
86 // All tests start with the same flag set.
87 SecCKKSTestResetFlags();
88 SecCKKSTestSetDisableSOS(true);
90 self.silentFetchesAllowed = true;
92 __weak __typeof(self) weakSelf = self;
93 self.operationQueue = [[NSOperationQueue alloc] init];
94 self.operationQueue.maxConcurrentOperationCount = 1;
96 self.zones = [[NSMutableDictionary alloc] init];
98 self.mockDatabase = OCMStrictClassMock([CKDatabase class]);
99 self.mockContainer = OCMClassMock([CKContainer class]);
100 OCMStub([self.mockContainer containerWithIdentifier:[OCMArg isKindOfClass:[NSString class]]]).andReturn(self.mockContainer);
101 OCMStub([self.mockContainer defaultContainer]).andReturn(self.mockContainer);
102 OCMStub([self.mockContainer alloc]).andReturn(self.mockContainer);
103 OCMStub([self.mockContainer containerIdentifier]).andReturn(SecCKKSContainerName);
104 OCMStub([self.mockContainer initWithContainerID: [OCMArg any] options: [OCMArg any]]).andReturn(self.mockContainer);
105 OCMStub([self.mockContainer privateCloudDatabase]).andReturn(self.mockDatabase);
106 OCMStub([self.mockContainer serverPreferredPushEnvironmentWithCompletionHandler: ([OCMArg invokeBlockWithArgs:@"fake APS push string", [NSNull null], nil])]);
108 // If you want to change this, you'll need to update the mock
109 _ckDeviceID = @"fake-cloudkit-device-id";
110 OCMStub([self.mockContainer fetchCurrentDeviceIDWithCompletionHandler: ([OCMArg invokeBlockWithArgs:self.ckDeviceID, [NSNull null], nil])]);
112 self.accountStatus = CKAccountStatusAvailable;
113 self.supportsDeviceToDeviceEncryption = YES;
115 // Inject a fake operation dependency into the manager object, so that the tests can perform setup and mock expectations before zone setup begins
116 // Also blocks all CK account state retrieval operations (but not circle status ones)
117 self.ckaccountHoldOperation = [NSBlockOperation named:@"ckaccount-hold" withBlock:^{
118 secnotice("ckks", "CKKS CK account status test hold released");
121 OCMStub([self.mockContainer accountStatusWithCompletionHandler:
122 [OCMArg checkWithBlock:^BOOL(void (^passedBlock) (CKAccountStatus accountStatus,
123 NSError * _Nullable error)) {
126 __strong __typeof(self) strongSelf = weakSelf;
127 NSBlockOperation* fulfillBlock = [NSBlockOperation named:@"account-status-completion" withBlock: ^{
128 passedBlock(weakSelf.accountStatus, nil);
130 [fulfillBlock addDependency: strongSelf.ckaccountHoldOperation];
131 [strongSelf.operationQueue addOperation: fulfillBlock];
138 OCMStub([self.mockContainer accountInfoWithCompletionHandler:
139 [OCMArg checkWithBlock:^BOOL(void (^passedBlock) (CKAccountInfo* accountInfo,
141 __strong __typeof(self) strongSelf = weakSelf;
142 if(passedBlock && strongSelf) {
143 NSBlockOperation* fulfillBlock = [NSBlockOperation named:@"account-info-completion" withBlock: ^{
144 __strong __typeof(self) blockStrongSelf = weakSelf;
145 CKAccountInfo* account = [[CKAccountInfo alloc] init];
146 account.accountStatus = blockStrongSelf.accountStatus;
147 account.supportsDeviceToDeviceEncryption = blockStrongSelf.supportsDeviceToDeviceEncryption;
148 account.accountPartition = CKAccountPartitionTypeProduction;
149 passedBlock((CKAccountInfo*)account, nil);
151 [fulfillBlock addDependency: strongSelf.ckaccountHoldOperation];
152 [strongSelf.operationQueue addOperation: fulfillBlock];
159 self.circleStatus = kSOSCCInCircle;
160 self.mockAccountStateTracker = OCMClassMock([CKKSCKAccountStateTracker class]);
161 OCMStub([self.mockAccountStateTracker getCircleStatus]).andCall(self, @selector(circleStatus));
163 // If we're in circle, come up with a fake circle id. Otherwise, return an error.
164 self.circlePeerID = @"fake-circle-id";
165 OCMStub([self.mockAccountStateTracker fetchCirclePeerID:
166 [OCMArg checkWithBlock:^BOOL(void (^passedBlock) (NSString* peerID,
168 __strong __typeof(self) strongSelf = weakSelf;
169 if(passedBlock && strongSelf) {
170 if(strongSelf.circleStatus == kSOSCCInCircle) {
171 passedBlock(strongSelf.circlePeerID, nil);
173 passedBlock(nil, [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey:@"no account, no circle id"}]);
181 self.aksLockState = false; // Lie and say AKS is always unlocked
182 self.mockLockStateTracker = OCMClassMock([CKKSLockStateTracker class]);
183 OCMStub([self.mockLockStateTracker queryAKSLocked]).andCall(self, @selector(aksLockState));
185 self.mockFakeCKModifyRecordZonesOperation = OCMClassMock([FakeCKModifyRecordZonesOperation class]);
186 OCMStub([self.mockFakeCKModifyRecordZonesOperation ckdb]).andReturn(self.zones);
188 self.mockFakeCKModifySubscriptionsOperation = OCMClassMock([FakeCKModifySubscriptionsOperation class]);
189 OCMStub([self.mockFakeCKModifySubscriptionsOperation ckdb]).andReturn(self.zones);
191 self.mockFakeCKFetchRecordZoneChangesOperation = OCMClassMock([FakeCKFetchRecordZoneChangesOperation class]);
192 OCMStub([self.mockFakeCKFetchRecordZoneChangesOperation ckdb]).andReturn(self.zones);
194 self.mockFakeCKFetchRecordsOperation = OCMClassMock([FakeCKFetchRecordsOperation class]);
195 OCMStub([self.mockFakeCKFetchRecordsOperation ckdb]).andReturn(self.zones);
197 self.mockFakeCKQueryOperation = OCMClassMock([FakeCKQueryOperation class]);
198 OCMStub([self.mockFakeCKQueryOperation ckdb]).andReturn(self.zones);
201 OCMStub([self.mockDatabase addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
202 __strong __typeof(self) strongSelf = weakSelf;
204 if ([obj isKindOfClass: [FakeCKFetchRecordZoneChangesOperation class]]) {
205 if(strongSelf.silentFetchesAllowed) {
208 FakeCKFetchRecordZoneChangesOperation *frzco = (FakeCKFetchRecordZoneChangesOperation *)obj;
209 [frzco addNullableDependency:strongSelf.ckFetchHoldOperation];
210 [strongSelf.operationQueue addOperation: frzco];
216 OCMStub([self.mockDatabase addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
217 __strong __typeof(self) strongSelf = weakSelf;
219 if ([obj isKindOfClass: [FakeCKFetchRecordsOperation class]]) {
220 if(strongSelf.silentFetchesAllowed) {
223 FakeCKFetchRecordsOperation *ffro = (FakeCKFetchRecordsOperation *)obj;
224 [ffro addNullableDependency:strongSelf.ckFetchHoldOperation];
225 [strongSelf.operationQueue addOperation: ffro];
231 OCMStub([self.mockDatabase addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
232 __strong __typeof(self) strongSelf = weakSelf;
234 if ([obj isKindOfClass: [FakeCKQueryOperation class]]) {
235 if(strongSelf.silentFetchesAllowed) {
238 FakeCKQueryOperation *fqo = (FakeCKQueryOperation *)obj;
239 [fqo addNullableDependency:strongSelf.ckFetchHoldOperation];
240 [strongSelf.operationQueue addOperation: fqo];
247 self.testZoneID = [[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName];
249 // Inject a fake operation dependency into the manager object, so that the tests can perform setup and mock expectations before zone setup begins
250 // Also blocks all CK account state retrieval operations (but not circle status ones)
251 self.ckksHoldOperation = [[NSBlockOperation alloc] init];
252 [self.ckksHoldOperation addExecutionBlock:^{
253 secnotice("ckks", "CKKS testing hold released");
255 self.ckksHoldOperation.name = @"ckks-hold";
257 //self.mockCKKSViewManagerClass = OCMClassMock([CKKSViewManager class]);
259 // We don't want to use class mocks here, because they don't play well with partial mocks
260 self.mockCKKSViewManager = OCMPartialMock(
261 [[CKKSViewManager alloc] initWithContainerName:SecCKKSContainerName
262 usePCS:SecCKKSContainerUsePCS
263 fetchRecordZoneChangesOperationClass:[FakeCKFetchRecordZoneChangesOperation class]
264 fetchRecordsOperationClass:[FakeCKFetchRecordsOperation class]
265 queryOperationClass:[FakeCKQueryOperation class]
266 modifySubscriptionsOperationClass:[FakeCKModifySubscriptionsOperation class]
267 modifyRecordZonesOperationClass:[FakeCKModifyRecordZonesOperation class]
268 apsConnectionClass:[FakeAPSConnection class]
269 nsnotificationCenterClass:[FakeNSNotificationCenter class]
270 notifierClass:[FakeCKKSNotifier class]
271 setupHold:self.ckksHoldOperation]);
273 OCMStub([self.mockCKKSViewManager viewList]).andCall(self, @selector(managedViewList));
274 OCMStub([self.mockCKKSViewManager syncBackupAndNotifyAboutSync]);
276 self.injectedManager = self.mockCKKSViewManager;
278 [CKKSViewManager resetManager:false setTo:self.injectedManager];
280 // Make a new fake keychain
281 NSString* smallName = [self.name componentsSeparatedByString:@" "][1];
282 smallName = [smallName stringByReplacingOccurrencesOfString:@"]" withString:@""];
284 NSString* tmp_dir = [NSString stringWithFormat: @"/tmp/%@.%X", smallName, arc4random()];
285 [[NSFileManager defaultManager] createDirectoryAtPath:[NSString stringWithFormat: @"%@/Library/Keychains", tmp_dir] withIntermediateDirectories:YES attributes:nil error:NULL];
287 SetCustomHomeURLString((__bridge CFStringRef) tmp_dir);
288 SecKeychainDbReset(NULL);
290 // Actually load the database.
291 kc_with_dbt(true, NULL, ^bool (SecDbConnectionRef dbt) { return false; });
294 -(CKKSCKAccountStateTracker*)accountStateTracker {
295 return self.injectedManager.accountTracker;
298 -(CKKSLockStateTracker*)lockStateTracker {
299 return self.injectedManager.lockStateTracker;
302 -(NSSet*)managedViewList {
303 return (NSSet*) CFBridgingRelease(SOSViewCopyViewSet(kViewSetCKKS));
306 -(void)expectCKFetch {
307 [self expectCKFetchAndRunBeforeFinished: nil];
310 -(void)expectCKFetchAndRunBeforeFinished: (void (^)())blockAfterFetch {
311 // Create an object for the block to retain and modify
312 BoolHolder* runAlready = [[BoolHolder alloc] init];
314 __weak __typeof(self) weakSelf = self;
315 [[self.mockDatabase expect] addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
316 __strong __typeof(self) strongSelf = weakSelf;
317 if(runAlready.state) {
321 if ([obj isKindOfClass: [FakeCKFetchRecordZoneChangesOperation class]]) {
323 runAlready.state = true;
325 FakeCKFetchRecordZoneChangesOperation *frzco = (FakeCKFetchRecordZoneChangesOperation *)obj;
326 frzco.blockAfterFetch = blockAfterFetch;
327 [frzco addNullableDependency: strongSelf.ckFetchHoldOperation];
328 [strongSelf.operationQueue addOperation: frzco];
334 -(void)expectCKFetchByRecordID {
335 // Create an object for the block to retain and modify
336 BoolHolder* runAlready = [[BoolHolder alloc] init];
338 __weak __typeof(self) weakSelf = self;
339 [[self.mockDatabase expect] addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
340 __strong __typeof(self) strongSelf = weakSelf;
341 if(runAlready.state) {
345 if ([obj isKindOfClass: [FakeCKFetchRecordsOperation class]]) {
347 runAlready.state = true;
349 FakeCKFetchRecordsOperation *ffro = (FakeCKFetchRecordsOperation *)obj;
350 [ffro addNullableDependency: strongSelf.ckFetchHoldOperation];
351 [strongSelf.operationQueue addOperation: ffro];
358 -(void)expectCKFetchByQuery {
359 // Create an object for the block to retain and modify
360 BoolHolder* runAlready = [[BoolHolder alloc] init];
362 __weak __typeof(self) weakSelf = self;
363 [[self.mockDatabase expect] addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
364 __strong __typeof(self) strongSelf = weakSelf;
365 if(runAlready.state) {
369 if ([obj isKindOfClass: [FakeCKQueryOperation class]]) {
371 runAlready.state = true;
373 FakeCKQueryOperation *fqo = (FakeCKQueryOperation *)obj;
374 [fqo addNullableDependency: strongSelf.ckFetchHoldOperation];
375 [strongSelf.operationQueue addOperation: fqo];
381 - (void)startCKKSSubsystem {
382 [self startCKAccountStatusMock];
383 [self startCKKSSubsystemOnly];
386 - (void)startCKKSSubsystemOnly {
387 // Note: currently, based on how we're mocking up the zone creation and zone subscription operation,
388 // they will 'fire' before this method is called. It's harmless, since the mocks immediately succeed
389 // and return; it's just a tad confusing.
390 if([self.ckksHoldOperation isPending]) {
391 [self.operationQueue addOperation: self.ckksHoldOperation];
395 - (void)startCKAccountStatusMock {
396 // Note: currently, based on how we're mocking up the zone creation and zone subscription operation,
397 // they will 'fire' before this method is called. It's harmless, since the mocks immediately succeed
398 // and return; it's just a tad confusing.
399 if([self.ckaccountHoldOperation isPending]) {
400 [self.operationQueue addOperation: self.ckaccountHoldOperation];
404 -(void)holdCloudKitModifications {
405 XCTAssertFalse([self.ckModifyHoldOperation isPending], "Shouldn't already be a pending cloudkit modify hold operation");
406 self.ckModifyHoldOperation = [NSBlockOperation blockOperationWithBlock:^{
407 secnotice("ckks", "Released CloudKit modification hold.");
410 -(void)releaseCloudKitModificationHold {
411 if([self.ckModifyHoldOperation isPending]) {
412 [self.operationQueue addOperation: self.ckModifyHoldOperation];
416 -(void)holdCloudKitFetches {
417 XCTAssertFalse([self.ckFetchHoldOperation isPending], "Shouldn't already be a pending cloudkit fetch hold operation");
418 self.ckFetchHoldOperation = [NSBlockOperation blockOperationWithBlock:^{
419 secnotice("ckks", "Released CloudKit fetch hold.");
422 -(void)releaseCloudKitFetchHold {
423 if([self.ckFetchHoldOperation isPending]) {
424 [self.operationQueue addOperation: self.ckFetchHoldOperation];
428 - (void)expectCKModifyItemRecords: (NSUInteger) expectedNumberOfRecords currentKeyPointerRecords: (NSUInteger) expectedCurrentKeyRecords zoneID: (CKRecordZoneID*) zoneID {
429 [self expectCKModifyItemRecords:expectedNumberOfRecords
430 currentKeyPointerRecords:expectedCurrentKeyRecords
435 - (void)expectCKModifyItemRecords: (NSUInteger) expectedNumberOfRecords currentKeyPointerRecords: (NSUInteger) expectedCurrentKeyRecords zoneID: (CKRecordZoneID*) zoneID checkItem: (BOOL (^)(CKRecord*)) checkItem {
436 [self expectCKModifyItemRecords:expectedNumberOfRecords
438 currentKeyPointerRecords:expectedCurrentKeyRecords
440 checkItem:checkItem];
443 - (void)expectCKModifyItemRecords:(NSUInteger)expectedNumberOfModifiedRecords
444 deletedRecords:(NSUInteger)expectedNumberOfDeletedRecords
445 currentKeyPointerRecords:(NSUInteger)expectedCurrentKeyRecords
446 zoneID:(CKRecordZoneID*)zoneID
447 checkItem:(BOOL (^)(CKRecord*))checkItem {
448 // We're updating the device state type on every update, so add it in here
449 NSMutableDictionary* expectedRecords = [@{SecCKRecordItemType: [NSNumber numberWithUnsignedInteger: expectedNumberOfModifiedRecords],
450 SecCKRecordCurrentKeyType: [NSNumber numberWithUnsignedInteger: expectedCurrentKeyRecords],
451 SecCKRecordDeviceStateType: [NSNumber numberWithUnsignedInt: 1],
454 if(SecCKKSSyncManifests()) {
455 expectedRecords[SecCKRecordManifestType] = [NSNumber numberWithInt: 1];
456 expectedRecords[SecCKRecordManifestLeafType] = [NSNumber numberWithInt: 72];
459 NSDictionary* deletedRecords = nil;
460 if(expectedNumberOfDeletedRecords != 0) {
461 deletedRecords = @{SecCKRecordItemType: [NSNumber numberWithUnsignedInteger: expectedNumberOfDeletedRecords]};
464 [self expectCKModifyRecords:expectedRecords
465 deletedRecordTypeCounts:deletedRecords
467 checkModifiedRecord: ^BOOL (CKRecord* record){
468 if([record.recordType isEqualToString: SecCKRecordItemType] && checkItem) {
469 return checkItem(record);
474 runAfterModification:nil];
479 - (void)expectCKModifyKeyRecords:(NSUInteger)expectedNumberOfRecords
480 currentKeyPointerRecords:(NSUInteger)expectedCurrentKeyRecords
481 tlkShareRecords:(NSUInteger)expectedTLKShareRecords
482 zoneID:(CKRecordZoneID*)zoneID {
483 NSNumber* nkeys = [NSNumber numberWithUnsignedInteger: expectedNumberOfRecords];
484 NSNumber* ncurrentkeys = [NSNumber numberWithUnsignedInteger: expectedCurrentKeyRecords];
485 NSNumber* ntlkshares = [NSNumber numberWithUnsignedInteger: expectedTLKShareRecords];
487 [self expectCKModifyRecords:@{SecCKRecordIntermediateKeyType: nkeys,
488 SecCKRecordCurrentKeyType: ncurrentkeys,
489 SecCKRecordTLKShareType: ntlkshares,
491 deletedRecordTypeCounts:nil
493 checkModifiedRecord:nil
494 runAfterModification:nil];
497 - (void)expectCKModifyRecords:(NSDictionary<NSString*, NSNumber*>*) expectedRecordTypeCounts
498 deletedRecordTypeCounts:(NSDictionary<NSString*, NSNumber*>*) expectedDeletedRecordTypeCounts
499 zoneID:(CKRecordZoneID*) zoneID
500 checkModifiedRecord:(BOOL (^)(CKRecord*)) checkModifiedRecord
501 runAfterModification:(void (^) ())afterModification
503 __weak __typeof(self) weakSelf = self;
505 // Create an object for the block to retain and modify
506 BoolHolder* runAlready = [[BoolHolder alloc] init];
508 secnotice("fakecloudkit", "expecting an operation matching modifications: %@ deletions: %@",
509 expectedRecordTypeCounts, expectedDeletedRecordTypeCounts);
511 [[self.mockDatabase expect] addOperation:[OCMArg checkWithBlock:^BOOL(id obj) {
512 secnotice("fakecloudkit", "Received an operation, checking");
513 __block bool matches = false;
514 if(runAlready.state) {
515 secnotice("fakecloudkit", "Run already, skipping");
519 if ([obj isKindOfClass:[CKModifyRecordsOperation class]]) {
520 __strong __typeof(weakSelf) strongSelf = weakSelf;
521 XCTAssertNotNil(strongSelf, "self exists");
523 CKModifyRecordsOperation *op = (CKModifyRecordsOperation *)obj;
526 NSMutableDictionary<NSString*, NSNumber*>* modifiedRecordTypeCounts = [[NSMutableDictionary alloc] init];
527 NSMutableDictionary<NSString*, NSNumber*>* deletedRecordTypeCounts = [[NSMutableDictionary alloc] init];
529 // First: check if it matches. If it does, _then_ execute the operation.
530 // Supports single-zone atomic writes only
533 // We only care about atomic operations
534 secnotice("fakecloudkit", "Not an atomic operation; quitting: %@", op);
538 FakeCKZone* zone = strongSelf.zones[zoneID];
539 XCTAssertNotNil(zone, "Have a zone for these records");
541 for(CKRecord* record in op.recordsToSave) {
542 if(![record.recordID.zoneID isEqual: zoneID]) {
543 secnotice("fakecloudkit", "Modified record zone ID mismatch: %@ %@", zoneID, record.recordID.zoneID);
547 if([zone errorFromSavingRecord: record]) {
548 secnotice("fakecloudkit", "Record zone rejected record write: %@", record);
552 NSNumber* currentCountNumber = modifiedRecordTypeCounts[record.recordType];
553 NSUInteger currentCount = currentCountNumber ? [currentCountNumber unsignedIntegerValue] : 0;
554 modifiedRecordTypeCounts[record.recordType] = [NSNumber numberWithUnsignedInteger: currentCount + 1];
557 for(CKRecordID* recordID in op.recordIDsToDelete) {
558 if(![recordID.zoneID isEqual: zoneID]) {
560 secnotice("fakecloudkit", "Deleted record zone ID mismatch: %@ %@", zoneID, recordID.zoneID);
563 // Find the object in CloudKit, and record its type
564 CKRecord* record = strongSelf.zones[zoneID].currentDatabase[recordID];
566 NSNumber* currentCountNumber = deletedRecordTypeCounts[record.recordType];
567 NSUInteger currentCount = currentCountNumber ? [currentCountNumber unsignedIntegerValue] : 0;
568 deletedRecordTypeCounts[record.recordType] = [NSNumber numberWithUnsignedInteger: currentCount + 1];
572 NSMutableDictionary* filteredExpectedRecordTypeCounts = [expectedRecordTypeCounts mutableCopy];
573 for(NSString* key in filteredExpectedRecordTypeCounts.allKeys) {
574 if([filteredExpectedRecordTypeCounts[key] isEqual: [NSNumber numberWithInt:0]]) {
575 filteredExpectedRecordTypeCounts[key] = nil;
578 filteredExpectedRecordTypeCounts[SecCKRecordManifestType] = modifiedRecordTypeCounts[SecCKRecordManifestType];
579 filteredExpectedRecordTypeCounts[SecCKRecordManifestLeafType] = modifiedRecordTypeCounts[SecCKRecordManifestLeafType];
581 // Inspect that we have exactly the same records as we expect
582 if(expectedRecordTypeCounts) {
583 matches &= !![modifiedRecordTypeCounts isEqual: filteredExpectedRecordTypeCounts];
585 secnotice("fakecloudkit", "Record number mismatch: %@ %@", modifiedRecordTypeCounts, filteredExpectedRecordTypeCounts);
589 matches &= op.recordsToSave.count == 0u;
591 secnotice("fakecloudkit", "Record number mismatch: %@ 0", modifiedRecordTypeCounts);
595 if(expectedDeletedRecordTypeCounts) {
596 matches &= !![deletedRecordTypeCounts isEqual: expectedDeletedRecordTypeCounts];
598 secnotice("fakecloudkit", "Deleted record number mismatch: %@ %@", deletedRecordTypeCounts, expectedDeletedRecordTypeCounts);
602 matches &= op.recordIDsToDelete.count == 0u;
604 secnotice("fakecloudkit", "Deleted record number mismatch: %@ 0", deletedRecordTypeCounts);
609 // We have the right number of things, and their etags match. Ensure that they have the right etags
610 if(matches && checkModifiedRecord) {
611 // Clearly we have the right number of things. Call checkRecord on them...
612 for(CKRecord* record in op.recordsToSave) {
613 matches &= !!(checkModifiedRecord(record));
615 secnotice("fakecloudkit", "Check record reports NO: %@ 0", record);
622 // Emulate cloudkit and schedule the operation for execution. Be sure to wait for this operation
623 // if you'd like to read the data from this write.
624 NSBlockOperation* ckop = [NSBlockOperation named:@"cloudkit-write" withBlock: ^{
625 @synchronized(zone.currentDatabase) {
626 NSMutableArray* savedRecords = [[NSMutableArray alloc] init];
627 for(CKRecord* record in op.recordsToSave) {
628 CKRecord* reflectedRecord = [record copy];
629 reflectedRecord.modificationDate = [NSDate date];
631 [zone addToZone: reflectedRecord];
633 [savedRecords addObject:reflectedRecord];
634 op.perRecordCompletionBlock(reflectedRecord, nil);
636 for(CKRecordID* recordID in op.recordIDsToDelete) {
637 // I don't believe CloudKit fails an operation if you delete a record that's not there, so:
638 [zone deleteCKRecordIDFromZone: recordID];
641 op.modifyRecordsCompletionBlock(savedRecords, op.recordIDsToDelete, nil);
643 if(afterModification) {
650 [ckop addNullableDependency:strongSelf.ckModifyHoldOperation];
651 [strongSelf.operationQueue addOperation: ckop];
655 runAlready.state = true;
657 return matches ? YES : NO;
661 - (void)failNextZoneCreation:(CKRecordZoneID*)zoneID {
662 XCTAssertNil(self.zones[zoneID], "Zone does not exist yet");
663 self.zones[zoneID] = [[FakeCKZone alloc] initZone: zoneID];
664 self.zones[zoneID].creationError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain code:CKErrorNetworkUnavailable userInfo:@{}];
667 // Report success, but don't actually create the zone.
668 // This way, you can find ZoneNotFound errors later on
669 - (void)failNextZoneCreationSilently:(CKRecordZoneID*)zoneID {
670 XCTAssertNil(self.zones[zoneID], "Zone does not exist yet");
671 self.zones[zoneID] = [[FakeCKZone alloc] initZone: zoneID];
672 self.zones[zoneID].failCreationSilently = true;
675 - (void)failNextZoneSubscription:(CKRecordZoneID*)zoneID {
676 XCTAssertNotNil(self.zones[zoneID], "Zone exists");
677 self.zones[zoneID].subscriptionError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain code:CKErrorNetworkUnavailable userInfo:@{}];
680 - (void)failNextZoneSubscription:(CKRecordZoneID*)zoneID withError:(NSError*)error {
681 XCTAssertNotNil(self.zones[zoneID], "Zone exists");
682 self.zones[zoneID].subscriptionError = error;
685 - (void)failNextCKAtomicModifyItemRecordsUpdateFailure:(CKRecordZoneID*)zoneID {
686 [self failNextCKAtomicModifyItemRecordsUpdateFailure:zoneID blockAfterReject:nil];
689 - (void)failNextCKAtomicModifyItemRecordsUpdateFailure:(CKRecordZoneID*)zoneID blockAfterReject: (void (^)())blockAfterReject {
690 [self failNextCKAtomicModifyItemRecordsUpdateFailure:zoneID blockAfterReject:blockAfterReject withError:nil];
693 - (void)failNextCKAtomicModifyItemRecordsUpdateFailure:(CKRecordZoneID*)zoneID blockAfterReject: (void (^)())blockAfterReject withError:(NSError*)error {
694 __weak __typeof(self) weakSelf = self;
696 [[self.mockDatabase expect] addOperation:[OCMArg checkWithBlock:^BOOL(id obj) {
697 __strong __typeof(weakSelf) strongSelf = weakSelf;
698 XCTAssertNotNil(strongSelf, "self exists");
700 __block bool rejected = false;
701 if ([obj isKindOfClass:[CKModifyRecordsOperation class]]) {
702 CKModifyRecordsOperation *op = (CKModifyRecordsOperation *)obj;
705 // We only care about atomic operations
709 // We want to only match zone updates pertaining to this zone
710 for(CKRecord* record in op.recordsToSave) {
711 if(![record.recordID.zoneID isEqual: zoneID]) {
716 FakeCKZone* zone = strongSelf.zones[zoneID];
717 XCTAssertNotNil(zone, "Have a zone for these records");
722 [strongSelf rejectWrite: op withError:error];
724 NSMutableDictionary<CKRecordID*, NSError*>* failedRecords = [[NSMutableDictionary alloc] init];
725 [strongSelf rejectWrite: op failedRecords:failedRecords];
728 if(blockAfterReject) {
732 return rejected ? YES : NO;
736 - (void)expectCKAtomicModifyItemRecordsUpdateFailure:(CKRecordZoneID*)zoneID {
737 __weak __typeof(self) weakSelf = self;
739 [[self.mockDatabase expect] addOperation:[OCMArg checkWithBlock:^BOOL(id obj) {
740 __strong __typeof(weakSelf) strongSelf = weakSelf;
741 XCTAssertNotNil(strongSelf, "self exists");
743 __block bool rejected = false;
744 if ([obj isKindOfClass:[CKModifyRecordsOperation class]]) {
745 CKModifyRecordsOperation *op = (CKModifyRecordsOperation *)obj;
748 // We only care about atomic operations
752 // We want to only match zone updates pertaining to this zone
753 for(CKRecord* record in op.recordsToSave) {
754 if(![record.recordID.zoneID isEqual: zoneID]) {
759 FakeCKZone* zone = strongSelf.zones[zoneID];
760 XCTAssertNotNil(zone, "Have a zone for these records");
762 NSMutableDictionary<CKRecordID*, NSError*>* failedRecords = [[NSMutableDictionary alloc] init];
764 @synchronized(zone.currentDatabase) {
765 for(CKRecord* record in op.recordsToSave) {
766 // Check if we should allow this transaction
767 NSError* recordSaveError = [zone errorFromSavingRecord: record];
768 if(recordSaveError) {
769 failedRecords[record.recordID] = recordSaveError;
776 [strongSelf rejectWrite: op failedRecords:failedRecords];
779 return rejected ? YES : NO;
783 -(void)rejectWrite:(CKModifyRecordsOperation*)op withError:(NSError*)error {
784 // Emulate cloudkit and schedule the operation for execution. Be sure to wait for this operation
785 // if you'd like to read the data from this write.
786 NSBlockOperation* ckop = [NSBlockOperation named:@"cloudkit-reject-write-error" withBlock: ^{
787 op.modifyRecordsCompletionBlock(nil, nil, error);
790 [ckop addNullableDependency: self.ckModifyHoldOperation];
791 [self.operationQueue addOperation: ckop];
794 -(void)rejectWrite:(CKModifyRecordsOperation*)op failedRecords:(NSMutableDictionary<CKRecordID*, NSError*>*)failedRecords {
795 // Add the batch request failed errors
796 for(CKRecord* record in op.recordsToSave) {
797 NSError* exists = failedRecords[record.recordID];
799 // TODO: might have important userInfo, but we're not mocking that yet
800 failedRecords[record.recordID] = [[CKPrettyError alloc] initWithDomain: CKErrorDomain code: CKErrorBatchRequestFailed userInfo: @{}];
804 NSError* error = [[CKPrettyError alloc] initWithDomain: CKErrorDomain code: CKErrorPartialFailure userInfo: @{CKPartialErrorsByItemIDKey: failedRecords}];
806 // Emulate cloudkit and schedule the operation for execution. Be sure to wait for this operation
807 // if you'd like to read the data from this write.
808 NSBlockOperation* ckop = [NSBlockOperation named:@"cloudkit-reject-write" withBlock: ^{
809 op.modifyRecordsCompletionBlock(nil, nil, error);
812 [ckop addNullableDependency: self.ckModifyHoldOperation];
813 [self.operationQueue addOperation: ckop];
816 - (void)expectCKDeleteItemRecords:(NSUInteger)expectedNumberOfRecords
817 zoneID:(CKRecordZoneID*) zoneID {
819 // We're updating the device state type on every update, so add it in here
820 NSMutableDictionary* expectedRecords = [@{
821 SecCKRecordDeviceStateType: [NSNumber numberWithUnsignedInt: 1],
823 if(SecCKKSSyncManifests()) {
824 // TODO: this really shouldn't be 2.
825 expectedRecords[SecCKRecordManifestType] = [NSNumber numberWithInt: 2];
826 expectedRecords[SecCKRecordManifestLeafType] = [NSNumber numberWithInt: 72];
829 [self expectCKModifyRecords:expectedRecords
830 deletedRecordTypeCounts:@{SecCKRecordItemType: [NSNumber numberWithUnsignedInteger: expectedNumberOfRecords]}
832 checkModifiedRecord:nil
833 runAfterModification:nil];
836 -(void)waitForCKModifications {
837 // CloudKit modifications are put on the local queue.
838 // This is heavyweight but should suffice.
839 [self.operationQueue waitUntilAllOperationsAreFinished];
843 // Put teardown code here. This method is called after the invocation of each test method in the class.
845 if(SecCKKSIsEnabled()) {
846 // Ensure we don't have any blocking operations
847 self.accountStatus = CKAccountStatusNoAccount;
848 [self startCKKSSubsystem];
850 [self waitForCKModifications];
852 XCTAssertEqual(0, [self.injectedManager.completedSecCKKSInitialize wait:2*NSEC_PER_SEC],
853 "Timeout did not occur waiting for SecCKKSInitialize");
855 // Make sure this happens before teardown.
856 XCTAssertEqual(0, [self.accountStateTracker.finishedInitialCalls wait:1*NSEC_PER_SEC], "Account state tracker initialized itself");
861 [self.injectedManager cancelPendingOperations];
862 [CKKSViewManager resetManager:true setTo:nil];
863 self.injectedManager = nil;
864 [self.mockCKKSViewManager stopMocking];
865 self.mockCKKSViewManager = nil;
867 [self.mockAccountStateTracker stopMocking];
868 self.mockAccountStateTracker = nil;
870 [self.mockLockStateTracker stopMocking];
871 self.mockLockStateTracker = nil;
873 [self.mockFakeCKModifyRecordZonesOperation stopMocking];
874 self.mockFakeCKModifyRecordZonesOperation = nil;
876 [self.mockFakeCKModifySubscriptionsOperation stopMocking];
877 self.mockFakeCKModifySubscriptionsOperation = nil;
879 [self.mockFakeCKFetchRecordZoneChangesOperation stopMocking];
880 self.mockFakeCKFetchRecordZoneChangesOperation = nil;
882 [self.mockFakeCKFetchRecordsOperation stopMocking];
883 self.mockFakeCKFetchRecordsOperation = nil;
885 [self.mockFakeCKQueryOperation stopMocking];
886 self.mockFakeCKQueryOperation = nil;
888 [self.mockDatabase stopMocking];
889 self.mockDatabase = nil;
891 [self.mockContainer stopMocking];
892 self.mockContainer = nil;
895 self.operationQueue = nil;
896 self.ckksHoldOperation = nil;
897 self.ckaccountHoldOperation = nil;
899 SecCKKSTestResetFlags();
902 - (CKKSKey*) fakeTLK: (CKRecordZoneID*)zoneID {
903 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey:[[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="]
904 uuid:[[NSUUID UUID] UUIDString]
905 keyclass:SecCKKSKeyClassTLK
906 state: SecCKKSProcessedStateLocal
910 [key CKRecordWithZoneID: zoneID];
914 - (NSError*)ckInternalServerExtensionError:(NSInteger)code description:(NSString*)desc {
915 NSError* extensionError = [[CKPrettyError alloc] initWithDomain:@"CloudkitKeychainService"
918 CKErrorServerDescriptionKey: desc,
919 NSLocalizedDescriptionKey: desc,
921 NSError* internalError = [[CKPrettyError alloc] initWithDomain:CKInternalErrorDomain
922 code:CKErrorInternalPluginError
923 userInfo:@{CKErrorServerDescriptionKey: desc,
924 NSLocalizedDescriptionKey: desc,
925 NSUnderlyingErrorKey: extensionError,
927 NSError* error = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
928 code:CKErrorServerRejectedRequest
929 userInfo:@{NSUnderlyingErrorKey: internalError,
930 CKErrorServerDescriptionKey: desc,
931 NSLocalizedDescriptionKey: desc,
932 CKContainerIDKey: SecCKKSContainerName,