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"
55 #include "keychain/ckks/CKKSReachabilityTracker.h"
57 #import "MockCloudKit.h"
59 @interface BoolHolder : NSObject
63 @implementation BoolHolder
66 // Inform OCMock about the internals of CKContainer
67 @interface CKContainer ()
68 - (void)_checkSelfCloudServicesEntitlement;
72 @implementation CloudKitMockXCTest
77 SecCKKSSetReduceRateLimiting(true);
81 securityd_init_local_spi();
88 NSString* testName = [self.name componentsSeparatedByString:@" "][1];
89 testName = [testName stringByReplacingOccurrencesOfString:@"]" withString:@""];
90 secnotice("ckkstest", "Beginning test %@", testName);
92 // All tests start with the same flag set.
93 SecCKKSTestResetFlags();
94 SecCKKSTestSetDisableSOS(true);
96 self.silentFetchesAllowed = true;
97 self.silentZoneDeletesAllowed = false; // Set to true if you want to do any deletes
99 __weak __typeof(self) weakSelf = self;
100 self.operationQueue = [[NSOperationQueue alloc] init];
101 self.operationQueue.maxConcurrentOperationCount = 1;
103 self.zones = [[NSMutableDictionary alloc] init];
105 self.apsEnvironment = @"fake APS push string";
107 self.mockDatabaseExceptionCatcher = OCMStrictClassMock([CKDatabase class]);
108 self.mockDatabase = OCMStrictClassMock([CKDatabase class]);
109 self.mockContainerExpectations = OCMStrictClassMock([CKContainer class]);
110 self.mockContainer = OCMClassMock([CKContainer class]);
111 OCMStub([self.mockContainer containerWithIdentifier:[OCMArg isKindOfClass:[NSString class]]]).andReturn(self.mockContainer);
112 OCMStub([self.mockContainer defaultContainer]).andReturn(self.mockContainer);
113 OCMStub([self.mockContainer alloc]).andReturn(self.mockContainer);
114 OCMStub([self.mockContainer containerIdentifier]).andReturn(SecCKKSContainerName);
115 OCMStub([self.mockContainer initWithContainerID: [OCMArg any] options: [OCMArg any]]).andReturn(self.mockContainer);
116 OCMStub([self.mockContainer privateCloudDatabase]).andReturn(self.mockDatabaseExceptionCatcher);
117 OCMStub([self.mockContainer serverPreferredPushEnvironmentWithCompletionHandler: ([OCMArg invokeBlockWithArgs:self.apsEnvironment, [NSNull null], nil])]);
118 OCMStub([self.mockContainer submitEventMetric:[OCMArg any]]).andCall(self, @selector(ckcontainerSubmitEventMetric:));
120 // Use two layers of mockDatabase here, so we can both add Expectations and catch the exception (instead of crash) when one fails.
121 OCMStub([self.mockDatabaseExceptionCatcher addOperation:[OCMArg any]]).andCall(self, @selector(ckdatabaseAddOperation:));
123 // If you want to change this, you'll need to update the mock
124 _ckDeviceID = [NSString stringWithFormat:@"fake-cloudkit-device-id-%@", testName];
125 OCMStub([self.mockContainer fetchCurrentDeviceIDWithCompletionHandler: ([OCMArg invokeBlockWithArgs:self.ckDeviceID, [NSNull null], nil])]);
127 self.accountStatus = CKAccountStatusAvailable;
128 self.supportsDeviceToDeviceEncryption = YES;
129 self.iCloudHasValidCredentials = YES;
131 // Inject a fake operation dependency so we won't respond with the CloudKit account status immediately
132 // The CKKSCKAccountStateTracker won't send any login/logout calls without that information, so this blocks all CKKS setup
133 self.ckaccountHoldOperation = [NSBlockOperation named:@"ckaccount-hold" withBlock:^{
134 secnotice("ckks", "CKKS CK account status test hold released");
137 OCMStub([self.mockContainer accountStatusWithCompletionHandler:
138 [OCMArg checkWithBlock:^BOOL(void (^passedBlock) (CKAccountStatus accountStatus,
139 NSError * _Nullable error)) {
142 __strong __typeof(self) strongSelf = weakSelf;
143 NSBlockOperation* fulfillBlock = [NSBlockOperation named:@"account-status-completion" withBlock: ^{
144 passedBlock(weakSelf.accountStatus, nil);
146 [fulfillBlock addDependency: strongSelf.ckaccountHoldOperation];
147 [strongSelf.operationQueue addOperation: fulfillBlock];
154 OCMStub([self.mockContainer accountInfoWithCompletionHandler:
155 [OCMArg checkWithBlock:^BOOL(void (^passedBlock) (CKAccountInfo* accountInfo,
157 __strong __typeof(self) strongSelf = weakSelf;
158 if(passedBlock && strongSelf) {
159 NSBlockOperation* fulfillBlock = [NSBlockOperation named:@"account-info-completion" withBlock: ^{
160 __strong __typeof(self) blockStrongSelf = weakSelf;
161 CKAccountInfo* account = [[CKAccountInfo alloc] init];
162 account.accountStatus = blockStrongSelf.accountStatus;
163 account.supportsDeviceToDeviceEncryption = blockStrongSelf.supportsDeviceToDeviceEncryption;
164 account.hasValidCredentials = blockStrongSelf.iCloudHasValidCredentials;
165 account.accountPartition = CKAccountPartitionTypeProduction;
166 passedBlock((CKAccountInfo*)account, nil);
168 [fulfillBlock addDependency: strongSelf.ckaccountHoldOperation];
169 [strongSelf.operationQueue addOperation: fulfillBlock];
176 self.circleStatus = [[SOSAccountStatus alloc] init:kSOSCCInCircle error:nil];
177 self.mockAccountStateTracker = OCMClassMock([CKKSCKAccountStateTracker class]);
178 OCMStub([self.mockAccountStateTracker getCircleStatus]).andCall(self, @selector(circleStatus));
180 // If we're in circle, come up with a fake circle id. Otherwise, return an error.
181 self.circlePeerID = [NSString stringWithFormat:@"fake-circle-id-%@", testName];
182 OCMStub([self.mockAccountStateTracker fetchCirclePeerID:
183 [OCMArg checkWithBlock:^BOOL(void (^passedBlock) (NSString* peerID,
185 __strong __typeof(self) strongSelf = weakSelf;
186 if(passedBlock && strongSelf) {
187 if(strongSelf.circleStatus.status == kSOSCCInCircle) {
188 passedBlock(strongSelf.circlePeerID, nil);
190 passedBlock(nil, [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey:@"no account, no circle id"}]);
198 self.aksLockState = false; // Lie and say AKS is always unlocked
199 self.mockLockStateTracker = OCMClassMock([CKKSLockStateTracker class]);
200 OCMStub([self.mockLockStateTracker queryAKSLocked]).andCall(self, @selector(aksLockState));
202 self.reachabilityFlags = kSCNetworkReachabilityFlagsReachable; // Lie and say network is available
203 self.mockReachabilityTracker = OCMClassMock([CKKSReachabilityTracker class]);
204 OCMStub([self.mockReachabilityTracker getReachabilityFlags:[OCMArg anyPointer]]).andCall(self, @selector(reachabilityFlags));
206 self.mockFakeCKModifyRecordZonesOperation = OCMClassMock([FakeCKModifyRecordZonesOperation class]);
207 OCMStub([self.mockFakeCKModifyRecordZonesOperation ckdb]).andReturn(self.zones);
208 OCMStub([self.mockFakeCKModifyRecordZonesOperation ensureZoneDeletionAllowed:[OCMArg any]]).andCall(self, @selector(ensureZoneDeletionAllowed:));
210 self.mockFakeCKModifySubscriptionsOperation = OCMClassMock([FakeCKModifySubscriptionsOperation class]);
211 OCMStub([self.mockFakeCKModifySubscriptionsOperation ckdb]).andReturn(self.zones);
213 self.mockFakeCKFetchRecordZoneChangesOperation = OCMClassMock([FakeCKFetchRecordZoneChangesOperation class]);
214 OCMStub([self.mockFakeCKFetchRecordZoneChangesOperation ckdb]).andReturn(self.zones);
216 self.mockFakeCKFetchRecordsOperation = OCMClassMock([FakeCKFetchRecordsOperation class]);
217 OCMStub([self.mockFakeCKFetchRecordsOperation ckdb]).andReturn(self.zones);
219 self.mockFakeCKQueryOperation = OCMClassMock([FakeCKQueryOperation class]);
220 OCMStub([self.mockFakeCKQueryOperation ckdb]).andReturn(self.zones);
223 OCMStub([self.mockDatabase addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
224 __strong __typeof(self) strongSelf = weakSelf;
226 if ([obj isKindOfClass: [FakeCKFetchRecordZoneChangesOperation class]]) {
227 if(strongSelf.silentFetchesAllowed) {
230 FakeCKFetchRecordZoneChangesOperation *frzco = (FakeCKFetchRecordZoneChangesOperation *)obj;
231 [frzco addNullableDependency:strongSelf.ckFetchHoldOperation];
232 [strongSelf.operationQueue addOperation: frzco];
238 OCMStub([self.mockDatabase addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
239 __strong __typeof(self) strongSelf = weakSelf;
241 if ([obj isKindOfClass: [FakeCKFetchRecordsOperation class]]) {
242 if(strongSelf.silentFetchesAllowed) {
245 FakeCKFetchRecordsOperation *ffro = (FakeCKFetchRecordsOperation *)obj;
246 [ffro addNullableDependency:strongSelf.ckFetchHoldOperation];
247 [strongSelf.operationQueue addOperation: ffro];
253 OCMStub([self.mockDatabase addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
254 __strong __typeof(self) strongSelf = weakSelf;
256 if ([obj isKindOfClass: [FakeCKQueryOperation class]]) {
257 if(strongSelf.silentFetchesAllowed) {
260 FakeCKQueryOperation *fqo = (FakeCKQueryOperation *)obj;
261 [fqo addNullableDependency:strongSelf.ckFetchHoldOperation];
262 [strongSelf.operationQueue addOperation: fqo];
269 self.testZoneID = [[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName];
271 // We don't want to use class mocks here, because they don't play well with partial mocks
272 self.mockCKKSViewManager = OCMPartialMock(
273 [[CKKSViewManager alloc] initWithContainerName:SecCKKSContainerName
274 usePCS:SecCKKSContainerUsePCS
275 fetchRecordZoneChangesOperationClass:[FakeCKFetchRecordZoneChangesOperation class]
276 fetchRecordsOperationClass:[FakeCKFetchRecordsOperation class]
277 queryOperationClass:[FakeCKQueryOperation class]
278 modifySubscriptionsOperationClass:[FakeCKModifySubscriptionsOperation class]
279 modifyRecordZonesOperationClass:[FakeCKModifyRecordZonesOperation class]
280 apsConnectionClass:[FakeAPSConnection class]
281 nsnotificationCenterClass:[FakeNSNotificationCenter class]
282 notifierClass:[FakeCKKSNotifier class]]);
284 OCMStub([self.mockCKKSViewManager viewList]).andCall(self, @selector(managedViewList));
285 OCMStub([self.mockCKKSViewManager syncBackupAndNotifyAboutSync]);
287 self.injectedManager = self.mockCKKSViewManager;
289 [CKKSViewManager resetManager:false setTo:self.injectedManager];
291 // Make a new fake keychain
292 NSString* tmp_dir = [NSString stringWithFormat: @"/tmp/%@.%X", testName, arc4random()];
293 [[NSFileManager defaultManager] createDirectoryAtPath:[NSString stringWithFormat: @"%@/Library/Keychains", tmp_dir] withIntermediateDirectories:YES attributes:nil error:NULL];
295 SetCustomHomeURLString((__bridge CFStringRef) tmp_dir);
296 SecKeychainDbReset(NULL);
298 // Actually load the database.
299 kc_with_dbt(true, NULL, ^bool (SecDbConnectionRef dbt) { return false; });
302 - (void)ckcontainerSubmitEventMetric:(CKEventMetric*)metric {
304 [self.mockContainerExpectations submitEventMetric:metric];
305 } @catch (NSException *exception) {
306 XCTFail("Received an container exception when trying to add a metric: %@", exception);
310 - (void)ckdatabaseAddOperation:(NSOperation*)op {
312 [self.mockDatabase addOperation:op];
313 } @catch (NSException *exception) {
314 XCTFail("Received an database exception: %@", exception);
319 - (void)ensureZoneDeletionAllowed:(FakeCKZone*)zone {
320 XCTAssertTrue(self.silentZoneDeletesAllowed, "Should be allowing zone deletes");
323 -(CKKSCKAccountStateTracker*)accountStateTracker {
324 return self.injectedManager.accountTracker;
327 -(CKKSLockStateTracker*)lockStateTracker {
328 return self.injectedManager.lockStateTracker;
331 -(CKKSReachabilityTracker*)reachabilityTracker {
332 return self.injectedManager.reachabilityTracker;
335 -(NSSet*)managedViewList {
336 return (NSSet*) CFBridgingRelease(SOSViewCopyViewSet(kViewSetCKKS));
339 -(void)expectCKFetch {
340 [self expectCKFetchAndRunBeforeFinished: nil];
343 -(void)expectCKFetchAndRunBeforeFinished: (void (^)(void))blockAfterFetch {
344 // Create an object for the block to retain and modify
345 BoolHolder* runAlready = [[BoolHolder alloc] init];
347 __weak __typeof(self) weakSelf = self;
348 [[self.mockDatabase expect] addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
349 __strong __typeof(self) strongSelf = weakSelf;
350 if(runAlready.state) {
354 secnotice("fakecloudkit", "Received an operation (%@), checking if it's a fetch changes", obj);
356 if ([obj isKindOfClass: [FakeCKFetchRecordZoneChangesOperation class]]) {
358 runAlready.state = true;
360 secnotice("fakecloudkit", "Running fetch changes: %@", obj);
361 FakeCKFetchRecordZoneChangesOperation *frzco = (FakeCKFetchRecordZoneChangesOperation *)obj;
362 frzco.blockAfterFetch = blockAfterFetch;
363 [frzco addNullableDependency: strongSelf.ckFetchHoldOperation];
364 [strongSelf.operationQueue addOperation: frzco];
370 -(void)expectCKFetchByRecordID {
371 // Create an object for the block to retain and modify
372 BoolHolder* runAlready = [[BoolHolder alloc] init];
374 __weak __typeof(self) weakSelf = self;
375 [[self.mockDatabase expect] addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
376 __strong __typeof(self) strongSelf = weakSelf;
377 if(runAlready.state) {
381 if ([obj isKindOfClass: [FakeCKFetchRecordsOperation class]]) {
383 runAlready.state = true;
385 FakeCKFetchRecordsOperation *ffro = (FakeCKFetchRecordsOperation *)obj;
386 [ffro addNullableDependency: strongSelf.ckFetchHoldOperation];
387 [strongSelf.operationQueue addOperation: ffro];
394 -(void)expectCKFetchByQuery {
395 // Create an object for the block to retain and modify
396 BoolHolder* runAlready = [[BoolHolder alloc] init];
398 __weak __typeof(self) weakSelf = self;
399 [[self.mockDatabase expect] addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
400 __strong __typeof(self) strongSelf = weakSelf;
401 if(runAlready.state) {
405 if ([obj isKindOfClass: [FakeCKQueryOperation class]]) {
407 runAlready.state = true;
409 FakeCKQueryOperation *fqo = (FakeCKQueryOperation *)obj;
410 [fqo addNullableDependency: strongSelf.ckFetchHoldOperation];
411 [strongSelf.operationQueue addOperation: fqo];
417 - (void)startCKKSSubsystem {
418 [self startCKAccountStatusMock];
421 - (void)startCKAccountStatusMock {
422 // Note: currently, based on how we're mocking up the zone creation and zone subscription operation,
423 // they will 'fire' before this method is called. It's harmless, since the mocks immediately succeed
424 // and return; it's just a tad confusing.
425 if([self.ckaccountHoldOperation isPending]) {
426 [self.operationQueue addOperation: self.ckaccountHoldOperation];
430 -(void)holdCloudKitModifications {
431 XCTAssertFalse([self.ckModifyHoldOperation isPending], "Shouldn't already be a pending cloudkit modify hold operation");
432 self.ckModifyHoldOperation = [NSBlockOperation blockOperationWithBlock:^{
433 secnotice("ckks", "Released CloudKit modification hold.");
436 -(void)releaseCloudKitModificationHold {
437 if([self.ckModifyHoldOperation isPending]) {
438 [self.operationQueue addOperation: self.ckModifyHoldOperation];
442 -(void)holdCloudKitFetches {
443 XCTAssertFalse([self.ckFetchHoldOperation isPending], "Shouldn't already be a pending cloudkit fetch hold operation");
444 self.ckFetchHoldOperation = [NSBlockOperation blockOperationWithBlock:^{
445 secnotice("ckks", "Released CloudKit fetch hold.");
448 -(void)releaseCloudKitFetchHold {
449 if([self.ckFetchHoldOperation isPending]) {
450 [self.operationQueue addOperation: self.ckFetchHoldOperation];
454 - (void)expectCKModifyItemRecords: (NSUInteger) expectedNumberOfRecords currentKeyPointerRecords: (NSUInteger) expectedCurrentKeyRecords zoneID: (CKRecordZoneID*) zoneID {
455 [self expectCKModifyItemRecords:expectedNumberOfRecords
456 currentKeyPointerRecords:expectedCurrentKeyRecords
461 - (void)expectCKModifyItemRecords: (NSUInteger) expectedNumberOfRecords currentKeyPointerRecords: (NSUInteger) expectedCurrentKeyRecords zoneID: (CKRecordZoneID*) zoneID checkItem: (BOOL (^)(CKRecord*)) checkItem {
462 [self expectCKModifyItemRecords:expectedNumberOfRecords
464 currentKeyPointerRecords:expectedCurrentKeyRecords
466 checkItem:checkItem];
469 - (void)expectCKModifyItemRecords:(NSUInteger)expectedNumberOfModifiedRecords
470 deletedRecords:(NSUInteger)expectedNumberOfDeletedRecords
471 currentKeyPointerRecords:(NSUInteger)expectedCurrentKeyRecords
472 zoneID:(CKRecordZoneID*)zoneID
473 checkItem:(BOOL (^)(CKRecord*))checkItem {
474 // We're updating the device state type on every update, so add it in here
475 NSMutableDictionary* expectedRecords = [@{SecCKRecordItemType: [NSNumber numberWithUnsignedInteger: expectedNumberOfModifiedRecords],
476 SecCKRecordCurrentKeyType: [NSNumber numberWithUnsignedInteger: expectedCurrentKeyRecords],
477 SecCKRecordDeviceStateType: [NSNumber numberWithUnsignedInt: 1],
480 if(SecCKKSSyncManifests()) {
481 expectedRecords[SecCKRecordManifestType] = [NSNumber numberWithInt: 1];
482 expectedRecords[SecCKRecordManifestLeafType] = [NSNumber numberWithInt: 72];
485 NSDictionary* deletedRecords = nil;
486 if(expectedNumberOfDeletedRecords != 0) {
487 deletedRecords = @{SecCKRecordItemType: [NSNumber numberWithUnsignedInteger: expectedNumberOfDeletedRecords]};
490 [self expectCKModifyRecords:expectedRecords
491 deletedRecordTypeCounts:deletedRecords
493 checkModifiedRecord: ^BOOL (CKRecord* record){
494 if([record.recordType isEqualToString: SecCKRecordItemType] && checkItem) {
495 return checkItem(record);
500 runAfterModification:nil];
505 - (void)expectCKModifyKeyRecords:(NSUInteger)expectedNumberOfRecords
506 currentKeyPointerRecords:(NSUInteger)expectedCurrentKeyRecords
507 tlkShareRecords:(NSUInteger)expectedTLKShareRecords
508 zoneID:(CKRecordZoneID*)zoneID
510 return [self expectCKModifyKeyRecords:expectedNumberOfRecords
511 currentKeyPointerRecords:expectedCurrentKeyRecords
512 tlkShareRecords:expectedTLKShareRecords
514 checkModifiedRecord:nil];
517 - (void)expectCKModifyKeyRecords:(NSUInteger)expectedNumberOfRecords
518 currentKeyPointerRecords:(NSUInteger)expectedCurrentKeyRecords
519 tlkShareRecords:(NSUInteger)expectedTLKShareRecords
520 zoneID:(CKRecordZoneID*)zoneID
521 checkModifiedRecord:(BOOL (^_Nullable)(CKRecord*))checkModifiedRecord
523 NSNumber* nkeys = [NSNumber numberWithUnsignedInteger: expectedNumberOfRecords];
524 NSNumber* ncurrentkeys = [NSNumber numberWithUnsignedInteger: expectedCurrentKeyRecords];
525 NSNumber* ntlkshares = [NSNumber numberWithUnsignedInteger: expectedTLKShareRecords];
527 [self expectCKModifyRecords:@{SecCKRecordIntermediateKeyType: nkeys,
528 SecCKRecordCurrentKeyType: ncurrentkeys,
529 SecCKRecordTLKShareType: ntlkshares,
531 deletedRecordTypeCounts:nil
533 checkModifiedRecord:checkModifiedRecord
534 runAfterModification:nil];
537 - (void)expectCKModifyRecords:(NSDictionary<NSString*, NSNumber*>*) expectedRecordTypeCounts
538 deletedRecordTypeCounts:(NSDictionary<NSString*, NSNumber*>*) expectedDeletedRecordTypeCounts
539 zoneID:(CKRecordZoneID*) zoneID
540 checkModifiedRecord:(BOOL (^)(CKRecord*)) checkModifiedRecord
541 runAfterModification:(void (^) (void))afterModification
543 __weak __typeof(self) weakSelf = self;
545 // Create an object for the block to retain and modify
546 BoolHolder* runAlready = [[BoolHolder alloc] init];
548 secnotice("fakecloudkit", "expecting an operation matching modifications: %@ deletions: %@",
549 expectedRecordTypeCounts, expectedDeletedRecordTypeCounts);
551 [[self.mockDatabase expect] addOperation:[OCMArg checkWithBlock:^BOOL(id obj) {
552 secnotice("fakecloudkit", "Received an operation (%@), checking if it's a modification", obj);
553 __block bool matches = false;
554 if(runAlready.state) {
555 secnotice("fakecloudkit", "Run already, skipping");
559 if ([obj isKindOfClass:[CKModifyRecordsOperation class]]) {
560 __strong __typeof(weakSelf) strongSelf = weakSelf;
561 XCTAssertNotNil(strongSelf, "self exists");
563 CKModifyRecordsOperation *op = (CKModifyRecordsOperation *)obj;
566 NSMutableDictionary<NSString*, NSNumber*>* modifiedRecordTypeCounts = [[NSMutableDictionary alloc] init];
567 NSMutableDictionary<NSString*, NSNumber*>* deletedRecordTypeCounts = [[NSMutableDictionary alloc] init];
569 // First: check if it matches. If it does, _then_ execute the operation.
570 // Supports single-zone atomic writes only
573 // We only care about atomic operations
574 secnotice("fakecloudkit", "Not an atomic operation; quitting: %@", op);
578 FakeCKZone* zone = strongSelf.zones[zoneID];
579 XCTAssertNotNil(zone, "Have a zone for these records");
581 __block BOOL result = YES;
582 dispatch_sync(zone.queue, ^{
584 for(CKRecord* record in op.recordsToSave) {
585 if(![record.recordID.zoneID isEqual: zoneID]) {
586 secnotice("fakecloudkit", "Modified record zone ID mismatch: %@ %@", zoneID, record.recordID.zoneID);
591 NSError* recordError = [zone errorFromSavingRecord: record];
593 secnotice("fakecloudkit", "Record zone rejected record write: %@ %@", recordError, record);
594 XCTFail(@"Record zone rejected record write: %@ %@", recordError, record);
599 NSNumber* currentCountNumber = modifiedRecordTypeCounts[record.recordType];
600 NSUInteger currentCount = currentCountNumber ? [currentCountNumber unsignedIntegerValue] : 0;
601 modifiedRecordTypeCounts[record.recordType] = [NSNumber numberWithUnsignedInteger: currentCount + 1];
604 for(CKRecordID* recordID in op.recordIDsToDelete) {
605 if(![recordID.zoneID isEqual: zoneID]) {
607 secnotice("fakecloudkit", "Deleted record zone ID mismatch: %@ %@", zoneID, recordID.zoneID);
610 // Find the object in CloudKit, and record its type
611 CKRecord* record = strongSelf.zones[zoneID].currentDatabase[recordID];
613 NSNumber* currentCountNumber = deletedRecordTypeCounts[record.recordType];
614 NSUInteger currentCount = currentCountNumber ? [currentCountNumber unsignedIntegerValue] : 0;
615 deletedRecordTypeCounts[record.recordType] = [NSNumber numberWithUnsignedInteger: currentCount + 1];
619 NSMutableDictionary* filteredExpectedRecordTypeCounts = [expectedRecordTypeCounts mutableCopy];
620 for(NSString* key in filteredExpectedRecordTypeCounts.allKeys) {
621 if([filteredExpectedRecordTypeCounts[key] isEqual: [NSNumber numberWithInt:0]]) {
622 filteredExpectedRecordTypeCounts[key] = nil;
625 filteredExpectedRecordTypeCounts[SecCKRecordManifestType] = modifiedRecordTypeCounts[SecCKRecordManifestType];
626 filteredExpectedRecordTypeCounts[SecCKRecordManifestLeafType] = modifiedRecordTypeCounts[SecCKRecordManifestLeafType];
628 // Inspect that we have exactly the same records as we expect
629 if(expectedRecordTypeCounts) {
630 matches &= !![modifiedRecordTypeCounts isEqual: filteredExpectedRecordTypeCounts];
632 secnotice("fakecloudkit", "Record number mismatch: %@ %@", modifiedRecordTypeCounts, filteredExpectedRecordTypeCounts);
637 matches &= op.recordsToSave.count == 0u;
639 secnotice("fakecloudkit", "Record number mismatch: %@ 0", modifiedRecordTypeCounts);
644 if(expectedDeletedRecordTypeCounts) {
645 matches &= !![deletedRecordTypeCounts isEqual: expectedDeletedRecordTypeCounts];
647 secnotice("fakecloudkit", "Deleted record number mismatch: %@ %@", deletedRecordTypeCounts, expectedDeletedRecordTypeCounts);
652 matches &= op.recordIDsToDelete.count == 0u;
654 secnotice("fakecloudkit", "Deleted record number mismatch: %@ 0", deletedRecordTypeCounts);
660 // We have the right number of things, and their etags match. Ensure that they have the right etags
661 if(matches && checkModifiedRecord) {
662 // Clearly we have the right number of things. Call checkRecord on them...
663 for(CKRecord* record in op.recordsToSave) {
664 matches &= !!(checkModifiedRecord(record));
666 secnotice("fakecloudkit", "Check record reports NO: %@ 0", record);
674 // Emulate cloudkit and schedule the operation for execution. Be sure to wait for this operation
675 // if you'd like to read the data from this write.
676 NSBlockOperation* ckop = [NSBlockOperation named:@"cloudkit-write" withBlock: ^{
677 @synchronized(zone.currentDatabase) {
678 NSMutableArray* savedRecords = [[NSMutableArray alloc] init];
679 for(CKRecord* record in op.recordsToSave) {
680 CKRecord* reflectedRecord = [record copy];
681 reflectedRecord.modificationDate = [NSDate date];
683 [zone addToZone: reflectedRecord];
685 [savedRecords addObject:reflectedRecord];
686 op.perRecordCompletionBlock(reflectedRecord, nil);
688 for(CKRecordID* recordID in op.recordIDsToDelete) {
689 // I don't believe CloudKit fails an operation if you delete a record that's not there, so:
690 [zone deleteCKRecordIDFromZone: recordID];
693 if(afterModification) {
697 op.modifyRecordsCompletionBlock(savedRecords, op.recordIDsToDelete, nil);
701 [ckop addNullableDependency:strongSelf.ckModifyHoldOperation];
702 [strongSelf.operationQueue addOperation: ckop];
710 runAlready.state = true;
712 return matches ? YES : NO;
716 - (void)failNextZoneCreation:(CKRecordZoneID*)zoneID {
717 XCTAssertNil(self.zones[zoneID], "Zone does not exist yet");
718 self.zones[zoneID] = [[FakeCKZone alloc] initZone: zoneID];
719 self.zones[zoneID].creationError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain code:CKErrorNetworkUnavailable userInfo:@{}];
722 // Report success, but don't actually create the zone.
723 // This way, you can find ZoneNotFound errors later on
724 - (void)failNextZoneCreationSilently:(CKRecordZoneID*)zoneID {
725 XCTAssertNil(self.zones[zoneID], "Zone does not exist yet");
726 self.zones[zoneID] = [[FakeCKZone alloc] initZone: zoneID];
727 self.zones[zoneID].failCreationSilently = true;
730 - (void)failNextZoneSubscription:(CKRecordZoneID*)zoneID {
731 XCTAssertNotNil(self.zones[zoneID], "Zone exists");
732 self.zones[zoneID].subscriptionError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain code:CKErrorNetworkUnavailable userInfo:@{}];
735 - (void)failNextZoneSubscription:(CKRecordZoneID*)zoneID withError:(NSError*)error {
736 XCTAssertNotNil(self.zones[zoneID], "Zone exists");
737 self.zones[zoneID].subscriptionError = error;
740 - (void)failNextCKAtomicModifyItemRecordsUpdateFailure:(CKRecordZoneID*)zoneID {
741 [self failNextCKAtomicModifyItemRecordsUpdateFailure:zoneID blockAfterReject:nil];
744 - (void)failNextCKAtomicModifyItemRecordsUpdateFailure:(CKRecordZoneID*)zoneID blockAfterReject: (void (^)(void))blockAfterReject {
745 [self failNextCKAtomicModifyItemRecordsUpdateFailure:zoneID blockAfterReject:blockAfterReject withError:nil];
748 - (void)failNextCKAtomicModifyItemRecordsUpdateFailure:(CKRecordZoneID*)zoneID blockAfterReject: (void (^)(void))blockAfterReject withError:(NSError*)error {
749 __weak __typeof(self) weakSelf = self;
751 [[self.mockDatabase expect] addOperation:[OCMArg checkWithBlock:^BOOL(id obj) {
752 __strong __typeof(weakSelf) strongSelf = weakSelf;
753 XCTAssertNotNil(strongSelf, "self exists");
755 __block bool rejected = false;
756 if ([obj isKindOfClass:[CKModifyRecordsOperation class]]) {
757 CKModifyRecordsOperation *op = (CKModifyRecordsOperation *)obj;
760 // We only care about atomic operations
764 // We want to only match zone updates pertaining to this zone
765 for(CKRecord* record in op.recordsToSave) {
766 if(![record.recordID.zoneID isEqual: zoneID]) {
771 FakeCKZone* zone = strongSelf.zones[zoneID];
772 XCTAssertNotNil(zone, "Have a zone for these records");
777 [strongSelf rejectWrite: op withError:error];
779 NSMutableDictionary<CKRecordID*, NSError*>* failedRecords = [[NSMutableDictionary alloc] init];
780 [strongSelf rejectWrite: op failedRecords:failedRecords];
783 if(blockAfterReject) {
787 return rejected ? YES : NO;
791 - (void)expectCKAtomicModifyItemRecordsUpdateFailure:(CKRecordZoneID*)zoneID {
792 __weak __typeof(self) weakSelf = self;
794 [[self.mockDatabase expect] addOperation:[OCMArg checkWithBlock:^BOOL(id obj) {
795 __strong __typeof(weakSelf) strongSelf = weakSelf;
796 XCTAssertNotNil(strongSelf, "self exists");
798 __block bool rejected = false;
799 if ([obj isKindOfClass:[CKModifyRecordsOperation class]]) {
800 CKModifyRecordsOperation *op = (CKModifyRecordsOperation *)obj;
802 secnotice("fakecloudkit", "checking for expectCKAtomicModifyItemRecordsUpdateFailure");
805 // We only care about atomic operations
806 secnotice("fakecloudkit", "expectCKAtomicModifyItemRecordsUpdateFailure: update not atomic");
810 // We want to only match zone updates pertaining to this zone
811 for(CKRecord* record in op.recordsToSave) {
812 if(![record.recordID.zoneID isEqual: zoneID]) {
813 secnotice("fakecloudkit", "expectCKAtomicModifyItemRecordsUpdateFailure: %@ is not %@", record.recordID.zoneID, zoneID);
818 FakeCKZone* zone = strongSelf.zones[zoneID];
819 XCTAssertNotNil(zone, "Have a zone for these records");
821 NSMutableDictionary<CKRecordID*, NSError*>* failedRecords = [[NSMutableDictionary alloc] init];
823 @synchronized(zone.currentDatabase) {
824 for(CKRecord* record in op.recordsToSave) {
825 // Check if we should allow this transaction
826 NSError* recordSaveError = [zone errorFromSavingRecord: record];
827 if(recordSaveError) {
828 failedRecords[record.recordID] = recordSaveError;
835 [strongSelf rejectWrite: op failedRecords:failedRecords];
837 secnotice("fakecloudkit", "expectCKAtomicModifyItemRecordsUpdateFailure: doesn't seem like an error to us");
840 return rejected ? YES : NO;
844 -(void)rejectWrite:(CKModifyRecordsOperation*)op withError:(NSError*)error {
845 // Emulate cloudkit and schedule the operation for execution. Be sure to wait for this operation
846 // if you'd like to read the data from this write.
847 NSBlockOperation* ckop = [NSBlockOperation named:@"cloudkit-reject-write-error" withBlock: ^{
848 op.modifyRecordsCompletionBlock(nil, nil, error);
851 [ckop addNullableDependency: self.ckModifyHoldOperation];
852 [self.operationQueue addOperation: ckop];
855 -(void)rejectWrite:(CKModifyRecordsOperation*)op failedRecords:(NSMutableDictionary<CKRecordID*, NSError*>*)failedRecords {
856 // Add the batch request failed errors
857 for(CKRecord* record in op.recordsToSave) {
858 NSError* exists = failedRecords[record.recordID];
860 // TODO: might have important userInfo, but we're not mocking that yet
861 failedRecords[record.recordID] = [[CKPrettyError alloc] initWithDomain: CKErrorDomain code: CKErrorBatchRequestFailed userInfo: @{}];
865 NSError* error = [[CKPrettyError alloc] initWithDomain: CKErrorDomain code: CKErrorPartialFailure userInfo: @{CKPartialErrorsByItemIDKey: failedRecords}];
867 // Emulate cloudkit and schedule the operation for execution. Be sure to wait for this operation
868 // if you'd like to read the data from this write.
869 NSBlockOperation* ckop = [NSBlockOperation named:@"cloudkit-reject-write" withBlock: ^{
870 op.modifyRecordsCompletionBlock(nil, nil, error);
873 [ckop addNullableDependency: self.ckModifyHoldOperation];
874 [self.operationQueue addOperation: ckop];
877 - (void)expectCKDeleteItemRecords:(NSUInteger)expectedNumberOfRecords
878 zoneID:(CKRecordZoneID*) zoneID {
880 // We're updating the device state type on every update, so add it in here
881 NSMutableDictionary* expectedRecords = [@{
882 SecCKRecordDeviceStateType: [NSNumber numberWithUnsignedInteger:expectedNumberOfRecords],
884 if(SecCKKSSyncManifests()) {
885 // TODO: this really shouldn't be 2.
886 expectedRecords[SecCKRecordManifestType] = [NSNumber numberWithInt: 2];
887 expectedRecords[SecCKRecordManifestLeafType] = [NSNumber numberWithInt: 72];
890 [self expectCKModifyRecords:expectedRecords
891 deletedRecordTypeCounts:@{SecCKRecordItemType: [NSNumber numberWithUnsignedInteger: expectedNumberOfRecords]}
893 checkModifiedRecord:nil
894 runAfterModification:nil];
897 -(void)waitForCKModifications {
898 // CloudKit modifications are put on the local queue.
899 // This is heavyweight but should suffice.
900 [self.operationQueue waitUntilAllOperationsAreFinished];
904 NSString* testName = [self.name componentsSeparatedByString:@" "][1];
905 testName = [testName stringByReplacingOccurrencesOfString:@"]" withString:@""];
906 secnotice("ckkstest", "Ending test %@", testName);
908 if(SecCKKSIsEnabled()) {
909 self.accountStatus = CKAccountStatusCouldNotDetermine;
911 // If the test never initialized the account state, don't call status later
912 bool callStatus = [self.ckaccountHoldOperation isFinished];
913 [self.ckaccountHoldOperation cancel];
914 self.ckaccountHoldOperation = nil;
916 // Ensure we don't have any blocking operations left
917 [self.operationQueue cancelAllOperations];
918 [self waitForCKModifications];
920 XCTAssertEqual(0, [self.injectedManager.completedSecCKKSInitialize wait:20*NSEC_PER_SEC],
921 "Timeout did not occur waiting for SecCKKSInitialize");
923 // Ensure that we can fetch zone status for all zones
925 XCTestExpectation *statusReturned = [self expectationWithDescription:@"status returned"];
926 [self.injectedManager rpcStatus:nil reply:^(NSArray<NSDictionary *> *result, NSError *error) {
927 XCTAssertNil(error, "Should be no error fetching status");
928 [statusReturned fulfill];
930 [self waitForExpectations: @[statusReturned] timeout:20];
933 // Make sure this happens before teardown.
934 XCTAssertEqual(0, [self.accountStateTracker.finishedInitialDispatches wait:20*NSEC_PER_SEC], "Account state tracker initialized itself");
936 dispatch_group_t accountChangesDelivered = [self.accountStateTracker checkForAllDeliveries];
937 XCTAssertEqual(0, dispatch_group_wait(accountChangesDelivered, dispatch_time(DISPATCH_TIME_NOW, 10*NSEC_PER_SEC)), "Account state tracker finished delivering everything");
942 [self.injectedManager cancelPendingOperations];
943 [CKKSViewManager resetManager:true setTo:nil];
944 self.injectedManager = nil;
945 [self.mockCKKSViewManager stopMocking];
946 self.mockCKKSViewManager = nil;
948 [self.mockAccountStateTracker stopMocking];
949 self.mockAccountStateTracker = nil;
951 [self.mockLockStateTracker stopMocking];
952 self.mockLockStateTracker = nil;
954 [self.mockReachabilityTracker stopMocking];
955 self.mockReachabilityTracker = nil;
957 [self.mockFakeCKModifyRecordZonesOperation stopMocking];
958 self.mockFakeCKModifyRecordZonesOperation = nil;
960 [self.mockFakeCKModifySubscriptionsOperation stopMocking];
961 self.mockFakeCKModifySubscriptionsOperation = nil;
963 [self.mockFakeCKFetchRecordZoneChangesOperation stopMocking];
964 self.mockFakeCKFetchRecordZoneChangesOperation = nil;
966 [self.mockFakeCKFetchRecordsOperation stopMocking];
967 self.mockFakeCKFetchRecordsOperation = nil;
969 [self.mockFakeCKQueryOperation stopMocking];
970 self.mockFakeCKQueryOperation = nil;
972 [self.mockDatabase stopMocking];
973 self.mockDatabase = nil;
975 [self.mockDatabaseExceptionCatcher stopMocking];
976 self.mockDatabaseExceptionCatcher = nil;
978 [self.mockContainer stopMocking];
979 self.mockContainer = nil;
983 self.operationQueue = nil;
985 SecCKKSTestResetFlags();
988 - (CKKSKey*) fakeTLK: (CKRecordZoneID*)zoneID {
989 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey:[[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="]
990 uuid:[[NSUUID UUID] UUIDString]
991 keyclass:SecCKKSKeyClassTLK
992 state: SecCKKSProcessedStateLocal
996 [key CKRecordWithZoneID: zoneID];
1000 - (NSError*)ckInternalServerExtensionError:(NSInteger)code description:(NSString*)desc {
1001 NSError* extensionError = [[CKPrettyError alloc] initWithDomain:@"CloudkitKeychainService"
1004 CKErrorServerDescriptionKey: desc,
1005 NSLocalizedDescriptionKey: desc,
1007 NSError* internalError = [[CKPrettyError alloc] initWithDomain:CKInternalErrorDomain
1008 code:CKErrorInternalPluginError
1009 userInfo:@{CKErrorServerDescriptionKey: desc,
1010 NSLocalizedDescriptionKey: desc,
1011 NSUnderlyingErrorKey: extensionError,
1013 NSError* error = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
1014 code:CKErrorServerRejectedRequest
1015 userInfo:@{NSUnderlyingErrorKey: internalError,
1016 CKErrorServerDescriptionKey: desc,
1017 NSLocalizedDescriptionKey: desc,
1018 CKContainerIDKey: SecCKKSContainerName,