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>
34 #import <TrustedPeers/TrustedPeers.h>
35 #import <TrustedPeers/TPPBPolicyKeyViewMapping.h>
36 #import <TrustedPeers/TPDictionaryMatchingRules.h>
38 #include "keychain/securityd/Regressions/SecdTestKeychainUtilities.h"
39 #include <utilities/SecFileLocations.h>
40 #include "keychain/securityd/SecItemServer.h"
41 #include "keychain/securityd/SecItemDataSource.h"
44 #include "keychain/securityd/spi.h"
47 #include <Security/SecureObjectSync/SOSViews.h>
49 #include <utilities/SecDb.h>
50 #include "keychain/securityd/SecItemServer.h"
51 #include <keychain/ckks/CKKS.h>
52 #include <keychain/ckks/CKKSViewManager.h>
53 #include <keychain/ckks/CKKSKeychainView.h>
54 #include <keychain/ckks/CKKSItem.h>
55 #include <keychain/ckks/CKKSOutgoingQueueEntry.h>
56 #include <keychain/ckks/CKKSKey.h>
57 #include "keychain/ckks/CKKSGroupOperation.h"
58 #include "keychain/ckks/CKKSLockStateTracker.h"
59 #include "keychain/ckks/CKKSReachabilityTracker.h"
61 #include "keychain/ot/OT.h"
62 #include "keychain/ot/OTManager.h"
64 #import "tests/secdmockaks/mockaks.h"
65 #import "utilities/SecTapToRadar.h"
67 #import "MockCloudKit.h"
69 @interface BoolHolder : NSObject
73 @implementation BoolHolder
76 // Inform OCMock about the internals of CKContainer
77 @interface CKContainer ()
78 - (void)_checkSelfCloudServicesEntitlement;
82 @implementation CloudKitMockXCTest
83 @synthesize aksLockState = _aksLockState;
89 SecCKKSSetReduceRateLimiting(true);
93 securityd_init_local_spi();
97 - (BOOL)isRateLimited:(SecTapToRadar *)ttrRequest
99 return self.isTTRRatelimited;
102 - (BOOL)askUserIfTTR:(SecTapToRadar *)ttrRequest
107 - (void)triggerTapToRadar:(SecTapToRadar *)ttrRequest
109 [self.ttrExpectation fulfill];
115 NSString* testName = [self.name componentsSeparatedByString:@" "][1];
116 testName = [testName stringByReplacingOccurrencesOfString:@"]" withString:@""];
117 secnotice("ckkstest", "Beginning test %@", testName);
119 // All tests start with the same flag set.
120 SecCKKSTestResetFlags();
121 SecCKKSTestSetDisableSOS(true);
123 self.silentFetchesAllowed = true;
124 self.silentZoneDeletesAllowed = false; // Set to true if you want to do any deletes
126 __weak __typeof(self) weakSelf = self;
127 self.operationQueue = [[NSOperationQueue alloc] init];
128 self.operationQueue.maxConcurrentOperationCount = 1;
130 self.zones = self.zones ?: [[NSMutableDictionary alloc] init];
132 self.apsEnvironment = @"fake APS push string";
134 // Static variables are a scourge. Let's reset this one...
135 [OctagonAPSReceiver resetGlobalEnviornmentMap];
137 self.mockDatabaseExceptionCatcher = OCMStrictClassMock([CKDatabase class]);
138 self.mockDatabase = OCMStrictClassMock([CKDatabase class]);
139 self.mockContainerExpectations = OCMStrictClassMock([CKContainer class]);
140 self.mockContainer = OCMClassMock([CKContainer class]);
141 OCMStub([self.mockContainer containerWithIdentifier:[OCMArg isKindOfClass:[NSString class]]]).andReturn(self.mockContainer);
142 OCMStub([self.mockContainer defaultContainer]).andReturn(self.mockContainer);
143 OCMStub([self.mockContainer alloc]).andReturn(self.mockContainer);
144 OCMStub([self.mockContainer containerIdentifier]).andReturn(SecCKKSContainerName);
145 OCMStub([self.mockContainer initWithContainerID: [OCMArg any] options: [OCMArg any]]).andReturn(self.mockContainer);
146 OCMStub([self.mockContainer privateCloudDatabase]).andReturn(self.mockDatabaseExceptionCatcher);
147 OCMStub([self.mockContainer serverPreferredPushEnvironmentWithCompletionHandler: ([OCMArg invokeBlockWithArgs:self.apsEnvironment, [NSNull null], nil])]);
148 OCMStub([self.mockContainer submitEventMetric:[OCMArg any]]).andCall(self, @selector(ckcontainerSubmitEventMetric:));
150 // Use two layers of mockDatabase here, so we can both add Expectations and catch the exception (instead of crash) when one fails.
151 OCMStub([self.mockDatabaseExceptionCatcher addOperation:[OCMArg any]]).andCall(self, @selector(ckdatabaseAddOperation:));
153 // If you want to change this, you'll need to update the mock
154 _ckDeviceID = [NSString stringWithFormat:@"fake-cloudkit-device-id-%@", testName];
155 OCMStub([self.mockContainer fetchCurrentDeviceIDWithCompletionHandler: ([OCMArg invokeBlockWithArgs:self.ckDeviceID, [NSNull null], nil])]);
157 self.accountStatus = CKAccountStatusAvailable;
158 self.iCloudHasValidCredentials = YES;
160 self.fakeHSA2AccountStatus = CKKSAccountStatusAvailable;
162 // Inject a fake operation dependency so we won't respond with the CloudKit account status immediately
163 // The CKKSAccountStateTracker won't send any login/logout calls without that information, so this blocks all CKKS setup
164 self.ckaccountHoldOperation = [NSBlockOperation named:@"ckaccount-hold" withBlock:^{
165 secnotice("ckks", "CKKS CK account status test hold released");
168 OCMStub([self.mockContainer accountStatusWithCompletionHandler:
169 [OCMArg checkWithBlock:^BOOL(void (^passedBlock) (CKAccountStatus accountStatus,
170 NSError * _Nullable error)) {
173 __strong __typeof(self) strongSelf = weakSelf;
174 NSBlockOperation* fulfillBlock = [NSBlockOperation named:@"account-status-completion" withBlock: ^{
175 passedBlock(weakSelf.accountStatus, nil);
177 [fulfillBlock addDependency: strongSelf.ckaccountHoldOperation];
178 [strongSelf.operationQueue addOperation: fulfillBlock];
185 OCMStub([self.mockContainer accountInfoWithCompletionHandler:
186 [OCMArg checkWithBlock:^BOOL(void (^passedBlock) (CKAccountInfo* accountInfo,
188 __strong __typeof(self) strongSelf = weakSelf;
189 if(passedBlock && strongSelf) {
190 NSBlockOperation* fulfillBlock = [NSBlockOperation named:@"account-info-completion" withBlock: ^{
191 __strong __typeof(self) blockStrongSelf = weakSelf;
192 CKAccountInfo* account = [[CKAccountInfo alloc] init];
193 account.accountStatus = blockStrongSelf.accountStatus;
194 account.hasValidCredentials = blockStrongSelf.iCloudHasValidCredentials;
195 account.accountPartition = CKAccountPartitionTypeProduction;
196 passedBlock((CKAccountInfo*)account, nil);
198 [fulfillBlock addDependency: strongSelf.ckaccountHoldOperation];
199 [strongSelf.operationQueue addOperation: fulfillBlock];
206 self.mockAccountStateTracker = OCMClassMock([CKKSAccountStateTracker class]);
207 OCMStub([self.mockAccountStateTracker getCircleStatus]).andCall(self, @selector(circleStatus));
209 // Fake out SOS peers
210 // One trusted non-self peer, but it doesn't have any Octagon keys. Your test can change this if it wants.
211 // However, note that [self putFakeDeviceStatusInCloudKit:] will likely not do what you want after you change this
212 CKKSSOSSelfPeer* currentSelfPeer = [[CKKSSOSSelfPeer alloc] initWithSOSPeerID:@"local-peer"
213 encryptionKey:[[SFECKeyPair alloc] initRandomKeyPairWithSpecifier:[[SFECKeySpecifier alloc] initWithCurve:SFEllipticCurveNistp384]]
214 signingKey:[[SFECKeyPair alloc] initRandomKeyPairWithSpecifier:[[SFECKeySpecifier alloc] initWithCurve:SFEllipticCurveNistp384]]
215 viewList:self.managedViewList];
217 self.mockSOSAdapter = [[CKKSMockSOSPresentAdapter alloc] initWithSelfPeer:currentSelfPeer
218 trustedPeers:[NSSet set]
221 // If we're in circle, come up with a fake circle id. Otherwise, return an error.
222 OCMStub([self.mockAccountStateTracker fetchCirclePeerID:
223 [OCMArg checkWithBlock:^BOOL(void (^passedBlock) (NSString* peerID,
225 __strong __typeof(self) strongSelf = weakSelf;
226 if(passedBlock && strongSelf) {
227 if(strongSelf.mockSOSAdapter.circleStatus == kSOSCCInCircle) {
228 passedBlock(strongSelf.mockSOSAdapter.selfPeer.peerID, nil);
230 passedBlock(nil, [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey:@"no account, no circle id"}]);
238 self.aksLockState = false; // Lie and say AKS is always unlocked
239 self.mockLockStateTracker = OCMClassMock([CKKSLockStateTracker class]);
240 OCMStub([self.mockLockStateTracker queryAKSLocked]).andCall(self, @selector(aksLockState));
242 self.mockTTR = OCMClassMock([SecTapToRadar class]);
243 OCMStub([self.mockTTR isRateLimited:[OCMArg any]]).andCall(self, @selector(isRateLimited:));
244 OCMStub([self.mockTTR askUserIfTTR:[OCMArg any]]).andCall(self, @selector(askUserIfTTR:));
245 OCMStub([self.mockTTR triggerTapToRadar:[OCMArg any]]).andCall(self, @selector(triggerTapToRadar:));
246 self.isTTRRatelimited = true;
248 self.mockFakeCKModifyRecordZonesOperation = OCMClassMock([FakeCKModifyRecordZonesOperation class]);
249 OCMStub([self.mockFakeCKModifyRecordZonesOperation ckdb]).andReturn(self.zones);
250 OCMStub([self.mockFakeCKModifyRecordZonesOperation shouldFailModifyRecordZonesOperation]).andCall(self, @selector(shouldFailModifyRecordZonesOperation));
252 OCMStub([self.mockFakeCKModifyRecordZonesOperation ensureZoneDeletionAllowed:[OCMArg any]]).andCall(self, @selector(ensureZoneDeletionAllowed:));
254 self.mockFakeCKModifySubscriptionsOperation = OCMClassMock([FakeCKModifySubscriptionsOperation class]);
255 OCMStub([self.mockFakeCKModifySubscriptionsOperation ckdb]).andReturn(self.zones);
257 self.mockFakeCKFetchRecordZoneChangesOperation = OCMClassMock([FakeCKFetchRecordZoneChangesOperation class]);
258 OCMStub([self.mockFakeCKFetchRecordZoneChangesOperation ckdb]).andReturn(self.zones);
259 OCMStub([self.mockFakeCKFetchRecordZoneChangesOperation isNetworkReachable]).andCall(self, @selector(isNetworkReachable));
261 self.mockFakeCKFetchRecordsOperation = OCMClassMock([FakeCKFetchRecordsOperation class]);
262 OCMStub([self.mockFakeCKFetchRecordsOperation ckdb]).andReturn(self.zones);
264 self.mockFakeCKQueryOperation = OCMClassMock([FakeCKQueryOperation class]);
265 OCMStub([self.mockFakeCKQueryOperation ckdb]).andReturn(self.zones);
268 OCMStub([self.mockDatabase addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
269 __strong __typeof(self) strongSelf = weakSelf;
271 if ([obj isKindOfClass: [FakeCKFetchRecordZoneChangesOperation class]]) {
272 if(strongSelf.silentFetchesAllowed) {
275 FakeCKFetchRecordZoneChangesOperation *frzco = (FakeCKFetchRecordZoneChangesOperation *)obj;
276 [frzco addNullableDependency:strongSelf.ckFetchHoldOperation];
277 [strongSelf.operationQueue addOperation: frzco];
283 OCMStub([self.mockDatabase addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
284 __strong __typeof(self) strongSelf = weakSelf;
286 if ([obj isKindOfClass: [FakeCKFetchRecordsOperation class]]) {
287 if(strongSelf.silentFetchesAllowed) {
290 FakeCKFetchRecordsOperation *ffro = (FakeCKFetchRecordsOperation *)obj;
291 [ffro addNullableDependency:strongSelf.ckFetchHoldOperation];
292 [strongSelf.operationQueue addOperation: ffro];
298 OCMStub([self.mockDatabase addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
299 __strong __typeof(self) strongSelf = weakSelf;
301 if ([obj isKindOfClass: [FakeCKQueryOperation class]]) {
302 if(strongSelf.silentFetchesAllowed) {
305 FakeCKQueryOperation *fqo = (FakeCKQueryOperation *)obj;
306 [fqo addNullableDependency:strongSelf.ckFetchHoldOperation];
307 [strongSelf.operationQueue addOperation: fqo];
313 OCMStub([self.mockDatabase addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
314 __strong __typeof(self) strongSelf = weakSelf;
316 if ([obj isKindOfClass: [FakeCKModifyRecordZonesOperation class]]) {
317 FakeCKModifyRecordZonesOperation *frzco = (FakeCKModifyRecordZonesOperation *)obj;
318 [frzco addNullableDependency:strongSelf.ckModifyRecordZonesHoldOperation];
319 [strongSelf.operationQueue addOperation: frzco];
325 OCMStub([self.mockDatabase addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
326 __strong __typeof(self) strongSelf = weakSelf;
328 if ([obj isKindOfClass: [FakeCKModifySubscriptionsOperation class]]) {
329 FakeCKModifySubscriptionsOperation *frzco = (FakeCKModifySubscriptionsOperation *)obj;
330 [frzco addNullableDependency:strongSelf.ckModifySubscriptionsHoldOperation];
331 [strongSelf.operationQueue addOperation: frzco];
337 self.testZoneID = [[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName];
339 // We don't want to use class mocks here, because they don't play well with partial mocks
340 CKKSCloudKitClassDependencies* cloudKitClassDependencies = [[CKKSCloudKitClassDependencies alloc] initWithFetchRecordZoneChangesOperationClass:[FakeCKFetchRecordZoneChangesOperation class]
341 fetchRecordsOperationClass:[FakeCKFetchRecordsOperation class]
342 queryOperationClass:[FakeCKQueryOperation class]
343 modifySubscriptionsOperationClass:[FakeCKModifySubscriptionsOperation class]
344 modifyRecordZonesOperationClass:[FakeCKModifyRecordZonesOperation class]
345 apsConnectionClass:[FakeAPSConnection class]
346 nsnotificationCenterClass:[FakeNSNotificationCenter class]
347 nsdistributednotificationCenterClass:[FakeNSDistributedNotificationCenter class]
348 notifierClass:[FakeCKKSNotifier class]];
351 self.injectedOTManager = [self setUpOTManager:cloudKitClassDependencies];
352 [OTManager resetManager:false to:self.injectedOTManager];
354 self.mockCKKSViewManager = OCMPartialMock(self.injectedOTManager.viewManager);
355 self.injectedManager = self.mockCKKSViewManager;
357 [self.mockCKKSViewManager setOverrideCKKSViewsFromPolicy:!self.setCKKSViewsFromPolicyToNo];
358 OCMStub([self.mockCKKSViewManager defaultViewList]).andCall(self, @selector(managedViewList));
359 OCMStub([self.mockCKKSViewManager syncBackupAndNotifyAboutSync]);
360 OCMStub([self.mockCKKSViewManager waitForTrustReady]).andReturn(YES);
362 if(!self.disableConfigureCKKSViewManagerWithViews) {
363 // Normally, the Octagon state machine calls this. But, since we won't be running that, help it out.
364 [self.injectedManager setSyncingViews:[self managedViewList]
365 sortingPolicy:[self viewSortingPolicyForManagedViewList]];
368 // Lie and say network is available
369 [self.reachabilityTracker setNetworkReachability:true];
371 // Make a new fake keychain
372 NSString* tmp_dir = [NSString stringWithFormat: @"/tmp/%@.%X", testName, arc4random()];
373 [[NSFileManager defaultManager] createDirectoryAtPath:[NSString stringWithFormat: @"%@/Library/Keychains", tmp_dir] withIntermediateDirectories:YES attributes:nil error:NULL];
375 SetCustomHomeURLString((__bridge CFStringRef) tmp_dir);
376 SecKeychainDbReset(NULL);
378 // Actually load the database.
379 kc_with_dbt(true, NULL, ^bool (SecDbConnectionRef dbt) { return false; });
382 - (OTManager*)setUpOTManager:(CKKSCloudKitClassDependencies*)cloudKitClassDependencies
384 return [[OTManager alloc] initWithSOSAdapter:self.mockSOSAdapter
385 lockStateTracker:[[CKKSLockStateTracker alloc] init]
386 cloudKitClassDependencies:cloudKitClassDependencies];
390 - (SOSAccountStatus*)circleStatus {
391 NSError* error = nil;
392 SOSCCStatus status = [self.mockSOSAdapter circleStatus:&error];
393 return [[SOSAccountStatus alloc] init:status error:error];
398 return _aksLockState;
401 - (void)setAksLockState:(bool)aksLockState
405 [SecMockAKS lockClassA];
407 [SecMockAKS unlockAllClasses];
409 _aksLockState = aksLockState;
412 - (bool)isNetworkReachable {
413 return self.reachabilityTracker.currentReachability;
416 - (void)ckcontainerSubmitEventMetric:(CKEventMetric*)metric {
418 [self.mockContainerExpectations submitEventMetric:metric];
419 } @catch (NSException *exception) {
420 XCTFail("Received an container exception when trying to add a metric: %@", exception);
424 - (void)ckdatabaseAddOperation:(NSOperation*)op {
426 [self.mockDatabase addOperation:op];
427 } @catch (NSException *exception) {
428 XCTFail("Received an database exception: %@", exception);
432 - (NSError* _Nullable)shouldFailModifyRecordZonesOperation {
433 NSError* error = self.nextModifyRecordZonesError;
435 self.nextModifyRecordZonesError = nil;
441 - (void)ensureZoneDeletionAllowed:(FakeCKZone*)zone {
442 XCTAssertTrue(self.silentZoneDeletesAllowed, "Should be allowing zone deletes");
445 - (CKKSAccountStateTracker*)accountStateTracker {
446 return self.injectedOTManager.accountStateTracker;
449 -(CKKSLockStateTracker*)lockStateTracker {
450 return self.injectedOTManager.lockStateTracker;
453 -(CKKSReachabilityTracker*)reachabilityTracker {
454 return self.injectedManager.reachabilityTracker;
457 -(NSSet*)managedViewList {
458 return (NSSet*) CFBridgingRelease(SOSViewCopyViewSet(kViewSetCKKS));
461 - (TPPolicy*)viewSortingPolicyForManagedViewList
463 NSMutableArray<TPPBPolicyKeyViewMapping*>* rules = [NSMutableArray array];
465 for(NSString* viewName in self.managedViewList) {
466 TPPBPolicyKeyViewMapping* mapping = [[TPPBPolicyKeyViewMapping alloc] init];
467 mapping.view = viewName;
468 mapping.matchingRule = [TPDictionaryMatchingRule fieldMatch:@"vwht"
469 fieldRegex:[NSString stringWithFormat:@"^%@$", viewName]];
471 [rules addObject:mapping];
474 TPPolicy* policy = [TPPolicy policyWithModelToCategory:@[]
476 introducersByCategory:@{}
479 version:[[TPPolicyVersion alloc] initWithVersion:1 hash:@"fake-policy-for-views"]];
484 -(void)expectCKFetch {
485 [self expectCKFetchAndRunBeforeFinished: nil];
488 -(void)expectCKFetchAndRunBeforeFinished: (void (^)(void))blockAfterFetch {
489 [self expectCKFetchWithFilter:^BOOL(FakeCKFetchRecordZoneChangesOperation * op) {
492 runBeforeFinished:blockAfterFetch];
495 - (void)expectCKFetchWithFilter:(BOOL (^)(FakeCKFetchRecordZoneChangesOperation*))operationMatch
496 runBeforeFinished:(void (^)(void))blockAfterFetch
498 // Create an object for the block to retain and modify
499 BoolHolder* runAlready = [[BoolHolder alloc] init];
501 __weak __typeof(self) weakSelf = self;
502 [[self.mockDatabase expect] addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
503 __strong __typeof(self) strongSelf = weakSelf;
504 if(runAlready.state) {
508 secnotice("fakecloudkit", "Received an operation (%@), checking if it's a fetch changes", obj);
510 if ([obj isKindOfClass: [FakeCKFetchRecordZoneChangesOperation class]]) {
511 FakeCKFetchRecordZoneChangesOperation *frzco = (FakeCKFetchRecordZoneChangesOperation *)obj;
512 matches = operationMatch(frzco);
513 runAlready.state = true;
515 secnotice("fakecloudkit", "Running fetch changes: %@", obj);
516 frzco.blockAfterFetch = blockAfterFetch;
517 [frzco addNullableDependency: strongSelf.ckFetchHoldOperation];
518 [strongSelf.operationQueue addOperation: frzco];
524 -(void)expectCKFetchByRecordID {
525 // Create an object for the block to retain and modify
526 BoolHolder* runAlready = [[BoolHolder alloc] init];
528 __weak __typeof(self) weakSelf = self;
529 [[self.mockDatabase expect] addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
530 __strong __typeof(self) strongSelf = weakSelf;
531 if(runAlready.state) {
535 if ([obj isKindOfClass: [FakeCKFetchRecordsOperation class]]) {
537 runAlready.state = true;
539 FakeCKFetchRecordsOperation *ffro = (FakeCKFetchRecordsOperation *)obj;
540 [ffro addNullableDependency: strongSelf.ckFetchHoldOperation];
541 [strongSelf.operationQueue addOperation: ffro];
548 -(void)expectCKFetchByQuery {
549 // Create an object for the block to retain and modify
550 BoolHolder* runAlready = [[BoolHolder alloc] init];
552 __weak __typeof(self) weakSelf = self;
553 [[self.mockDatabase expect] addOperation: [OCMArg checkWithBlock:^BOOL(id obj) {
554 __strong __typeof(self) strongSelf = weakSelf;
555 if(runAlready.state) {
559 if ([obj isKindOfClass: [FakeCKQueryOperation class]]) {
561 runAlready.state = true;
563 FakeCKQueryOperation *fqo = (FakeCKQueryOperation *)obj;
564 [fqo addNullableDependency: strongSelf.ckFetchHoldOperation];
565 [strongSelf.operationQueue addOperation: fqo];
571 - (void)startCKKSSubsystem {
572 if(self.fakeHSA2AccountStatus != CKKSAccountStatusUnknown) {
573 [self.accountStateTracker setHSA2iCloudAccountStatus:self.fakeHSA2AccountStatus];
575 [self startCKAccountStatusMock];
578 - (void)startCKAccountStatusMock {
579 // Note: currently, based on how we're mocking up the zone creation and zone subscription operation,
580 // they will 'fire' before this method is called. It's harmless, since the mocks immediately succeed
581 // and return; it's just a tad confusing.
582 if([self.ckaccountHoldOperation isPending]) {
583 [self.operationQueue addOperation: self.ckaccountHoldOperation];
586 [self.accountStateTracker performInitialDispatches];
589 -(void)holdCloudKitModifications {
590 XCTAssertFalse([self.ckModifyHoldOperation isPending], "Shouldn't already be a pending cloudkit modify hold operation");
591 self.ckModifyHoldOperation = [NSBlockOperation blockOperationWithBlock:^{
592 secnotice("ckks", "Released CloudKit modification hold.");
595 -(void)releaseCloudKitModificationHold {
596 if([self.ckModifyHoldOperation isPending]) {
597 [self.operationQueue addOperation: self.ckModifyHoldOperation];
601 -(void)holdCloudKitFetches {
602 XCTAssertFalse([self.ckFetchHoldOperation isPending], "Shouldn't already be a pending cloudkit fetch hold operation");
603 self.ckFetchHoldOperation = [NSBlockOperation blockOperationWithBlock:^{
604 secnotice("ckks", "Released CloudKit fetch hold.");
607 -(void)releaseCloudKitFetchHold {
608 if([self.ckFetchHoldOperation isPending]) {
609 [self.operationQueue addOperation: self.ckFetchHoldOperation];
613 -(void)holdCloudKitModifyRecordZones {
614 XCTAssertFalse([self.ckModifyRecordZonesHoldOperation isPending], "Shouldn't already be a pending cloudkit zone create hold operation");
615 self.ckModifyRecordZonesHoldOperation = [NSBlockOperation blockOperationWithBlock:^{
616 secnotice("ckks", "Released CloudKit zone create hold.");
619 -(void)releaseCloudKitModifyRecordZonesHold {
620 if([self.ckModifyRecordZonesHoldOperation isPending]) {
621 [self.operationQueue addOperation: self.ckModifyRecordZonesHoldOperation];
625 -(void)holdCloudKitModifySubscription {
626 XCTAssertFalse([self.ckModifySubscriptionsHoldOperation isPending], "Shouldn't already be a pending cloudkit subscription hold operation");
627 self.ckModifySubscriptionsHoldOperation = [NSBlockOperation blockOperationWithBlock:^{
628 secnotice("ckks", "Released CloudKit zone create hold.");
631 -(void)releaseCloudKitModifySubscriptionHold {
632 if([self.ckModifySubscriptionsHoldOperation isPending]) {
633 [self.operationQueue addOperation: self.ckModifySubscriptionsHoldOperation];
637 - (void)expectCKModifyItemRecords: (NSUInteger) expectedNumberOfRecords currentKeyPointerRecords: (NSUInteger) expectedCurrentKeyRecords zoneID: (CKRecordZoneID*) zoneID {
638 [self expectCKModifyItemRecords:expectedNumberOfRecords
639 currentKeyPointerRecords:expectedCurrentKeyRecords
644 - (void)expectCKModifyItemRecords: (NSUInteger) expectedNumberOfRecords currentKeyPointerRecords: (NSUInteger) expectedCurrentKeyRecords zoneID: (CKRecordZoneID*) zoneID checkItem: (BOOL (^)(CKRecord*)) checkItem {
645 [self expectCKModifyItemRecords:expectedNumberOfRecords
647 currentKeyPointerRecords:expectedCurrentKeyRecords
649 checkItem:checkItem];
652 - (void)expectCKModifyItemRecords:(NSUInteger)expectedNumberOfModifiedRecords
653 deletedRecords:(NSUInteger)expectedNumberOfDeletedRecords
654 currentKeyPointerRecords:(NSUInteger)expectedCurrentKeyRecords
655 zoneID:(CKRecordZoneID*)zoneID
656 checkItem:(BOOL (^)(CKRecord*))checkItem {
657 // We're updating the device state type on every update, so add it in here
658 NSMutableDictionary* expectedRecords = [@{SecCKRecordItemType: [NSNumber numberWithUnsignedInteger: expectedNumberOfModifiedRecords],
659 SecCKRecordCurrentKeyType: [NSNumber numberWithUnsignedInteger: expectedCurrentKeyRecords],
660 SecCKRecordDeviceStateType: [NSNumber numberWithUnsignedInt: 1],
663 if(SecCKKSSyncManifests()) {
664 expectedRecords[SecCKRecordManifestType] = [NSNumber numberWithInt: 1];
665 expectedRecords[SecCKRecordManifestLeafType] = [NSNumber numberWithInt: 72];
668 NSDictionary* deletedRecords = nil;
669 if(expectedNumberOfDeletedRecords != 0) {
670 deletedRecords = @{SecCKRecordItemType: [NSNumber numberWithUnsignedInteger: expectedNumberOfDeletedRecords]};
673 [self expectCKModifyRecords:expectedRecords
674 deletedRecordTypeCounts:deletedRecords
676 checkModifiedRecord: ^BOOL (CKRecord* record){
677 if([record.recordType isEqualToString: SecCKRecordItemType] && checkItem) {
678 return checkItem(record);
683 runAfterModification:nil];
688 - (void)expectCKModifyKeyRecords:(NSUInteger)expectedNumberOfRecords
689 currentKeyPointerRecords:(NSUInteger)expectedCurrentKeyRecords
690 tlkShareRecords:(NSUInteger)expectedTLKShareRecords
691 zoneID:(CKRecordZoneID*)zoneID
693 return [self expectCKModifyKeyRecords:expectedNumberOfRecords
694 currentKeyPointerRecords:expectedCurrentKeyRecords
695 tlkShareRecords:expectedTLKShareRecords
697 checkModifiedRecord:nil];
700 - (void)expectCKModifyKeyRecords:(NSUInteger)expectedNumberOfRecords
701 currentKeyPointerRecords:(NSUInteger)expectedCurrentKeyRecords
702 tlkShareRecords:(NSUInteger)expectedTLKShareRecords
703 zoneID:(CKRecordZoneID*)zoneID
704 checkModifiedRecord:(BOOL (^_Nullable)(CKRecord*))checkModifiedRecord
706 NSNumber* nkeys = [NSNumber numberWithUnsignedInteger: expectedNumberOfRecords];
707 NSNumber* ncurrentkeys = [NSNumber numberWithUnsignedInteger: expectedCurrentKeyRecords];
708 NSNumber* ntlkshares = [NSNumber numberWithUnsignedInteger: expectedTLKShareRecords];
710 [self expectCKModifyRecords:@{SecCKRecordIntermediateKeyType: nkeys,
711 SecCKRecordCurrentKeyType: ncurrentkeys,
712 SecCKRecordTLKShareType: ntlkshares,
714 deletedRecordTypeCounts:nil
716 checkModifiedRecord:checkModifiedRecord
717 runAfterModification:nil];
720 - (void)expectCKModifyRecords:(NSDictionary<NSString*, NSNumber*>*) expectedRecordTypeCounts
721 deletedRecordTypeCounts:(NSDictionary<NSString*, NSNumber*>*) expectedDeletedRecordTypeCounts
722 zoneID:(CKRecordZoneID*) zoneID
723 checkModifiedRecord:(BOOL (^)(CKRecord*)) checkModifiedRecord
724 runAfterModification:(void (^) (void))afterModification
726 __weak __typeof(self) weakSelf = self;
728 // Create an object for the block to retain and modify
729 BoolHolder* runAlready = [[BoolHolder alloc] init];
731 secnotice("fakecloudkit", "expecting an operation matching modifications: %@ deletions: %@",
732 expectedRecordTypeCounts, expectedDeletedRecordTypeCounts);
734 [[self.mockDatabase expect] addOperation:[OCMArg checkWithBlock:^BOOL(id obj) {
735 secnotice("fakecloudkit", "Received an operation (%@), checking if it's a modification", obj);
736 __block bool matches = false;
737 if(runAlready.state) {
738 secnotice("fakecloudkit", "Run already, skipping");
742 if ([obj isKindOfClass:[CKModifyRecordsOperation class]]) {
743 __strong __typeof(weakSelf) strongSelf = weakSelf;
744 XCTAssertNotNil(strongSelf, "self exists");
746 CKModifyRecordsOperation *op = (CKModifyRecordsOperation *)obj;
749 NSMutableDictionary<NSString*, NSNumber*>* modifiedRecordTypeCounts = [[NSMutableDictionary alloc] init];
750 NSMutableDictionary<NSString*, NSNumber*>* deletedRecordTypeCounts = [[NSMutableDictionary alloc] init];
752 // First: check if it matches. If it does, _then_ execute the operation.
753 // Supports single-zone atomic writes only
756 // We only care about atomic operations
757 secnotice("fakecloudkit", "Not an atomic operation; quitting: %@", op);
761 FakeCKZone* zone = strongSelf.zones[zoneID];
762 XCTAssertNotNil(zone, "Have a zone for these records");
764 __block BOOL result = YES;
765 dispatch_sync(zone.queue, ^{
767 for(CKRecord* record in op.recordsToSave) {
768 if(![record.recordID.zoneID isEqual: zoneID]) {
769 secnotice("fakecloudkit", "Modified record zone ID mismatch: %@ %@", zoneID, record.recordID.zoneID);
774 NSError* recordError = [zone errorFromSavingRecord: record];
776 secnotice("fakecloudkit", "Record zone rejected record write: %@ %@", recordError, record);
777 XCTFail(@"Record zone rejected record write: %@ %@", recordError, record);
782 NSNumber* currentCountNumber = modifiedRecordTypeCounts[record.recordType];
783 NSUInteger currentCount = currentCountNumber ? [currentCountNumber unsignedIntegerValue] : 0;
784 modifiedRecordTypeCounts[record.recordType] = [NSNumber numberWithUnsignedInteger: currentCount + 1];
787 for(CKRecordID* recordID in op.recordIDsToDelete) {
788 if(![recordID.zoneID isEqual: zoneID]) {
790 secnotice("fakecloudkit", "Deleted record zone ID mismatch: %@ %@", zoneID, recordID.zoneID);
793 // Find the object in CloudKit, and record its type
794 CKRecord* record = strongSelf.zones[zoneID].currentDatabase[recordID];
796 NSNumber* currentCountNumber = deletedRecordTypeCounts[record.recordType];
797 NSUInteger currentCount = currentCountNumber ? [currentCountNumber unsignedIntegerValue] : 0;
798 deletedRecordTypeCounts[record.recordType] = [NSNumber numberWithUnsignedInteger: currentCount + 1];
802 NSMutableDictionary* filteredExpectedRecordTypeCounts = [expectedRecordTypeCounts mutableCopy];
803 for(NSString* key in filteredExpectedRecordTypeCounts.allKeys) {
804 if([filteredExpectedRecordTypeCounts[key] isEqual: [NSNumber numberWithInt:0]]) {
805 filteredExpectedRecordTypeCounts[key] = nil;
808 filteredExpectedRecordTypeCounts[SecCKRecordManifestType] = modifiedRecordTypeCounts[SecCKRecordManifestType];
809 filteredExpectedRecordTypeCounts[SecCKRecordManifestLeafType] = modifiedRecordTypeCounts[SecCKRecordManifestLeafType];
811 // Inspect that we have exactly the same records as we expect
812 if(expectedRecordTypeCounts) {
813 matches &= !![modifiedRecordTypeCounts isEqual: filteredExpectedRecordTypeCounts];
815 secnotice("fakecloudkit", "Record number mismatch: %@ %@", modifiedRecordTypeCounts, filteredExpectedRecordTypeCounts);
820 matches &= op.recordsToSave.count == 0u;
822 secnotice("fakecloudkit", "Record number mismatch: %@ 0", modifiedRecordTypeCounts);
827 if(expectedDeletedRecordTypeCounts) {
828 matches &= !![deletedRecordTypeCounts isEqual: expectedDeletedRecordTypeCounts];
830 secnotice("fakecloudkit", "Deleted record number mismatch: %@ %@", deletedRecordTypeCounts, expectedDeletedRecordTypeCounts);
835 matches &= op.recordIDsToDelete.count == 0u;
837 secnotice("fakecloudkit", "Deleted record number mismatch: %@ 0", deletedRecordTypeCounts);
843 // We have the right number of things, and their etags match. Ensure that they have the right etags
844 if(matches && checkModifiedRecord) {
845 // Clearly we have the right number of things. Call checkRecord on them...
846 for(CKRecord* record in op.recordsToSave) {
847 matches &= !!(checkModifiedRecord(record));
849 secnotice("fakecloudkit", "Check record reports NO: %@ 0", record);
857 // Emulate cloudkit and schedule the operation for execution. Be sure to wait for this operation
858 // if you'd like to read the data from this write.
859 NSBlockOperation* ckop = [NSBlockOperation named:@"cloudkit-write" withBlock: ^{
860 @synchronized(zone.currentDatabase) {
861 NSMutableArray* savedRecords = [[NSMutableArray alloc] init];
862 for(CKRecord* record in op.recordsToSave) {
863 CKRecord* reflectedRecord = [record copy];
864 reflectedRecord.modificationDate = [NSDate date];
866 [zone addToZone: reflectedRecord];
868 [savedRecords addObject:reflectedRecord];
869 op.perRecordCompletionBlock(reflectedRecord, nil);
871 for(CKRecordID* recordID in op.recordIDsToDelete) {
872 // I don't believe CloudKit fails an operation if you delete a record that's not there, so:
873 [zone deleteCKRecordIDFromZone: recordID];
876 if(afterModification) {
880 op.modifyRecordsCompletionBlock(savedRecords, op.recordIDsToDelete, nil);
884 [ckop addNullableDependency:strongSelf.ckModifyHoldOperation];
885 [strongSelf.operationQueue addOperation: ckop];
893 runAlready.state = true;
895 return matches ? YES : NO;
899 - (void)failNextZoneCreation:(CKRecordZoneID*)zoneID {
900 XCTAssertNil(self.zones[zoneID], "Zone does not exist yet");
901 self.zones[zoneID] = [[FakeCKZone alloc] initZone: zoneID];
902 self.zones[zoneID].creationError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain
903 code:CKErrorNetworkUnavailable
905 CKErrorRetryAfterKey: @(0.5),
909 // Report success, but don't actually create the zone.
910 // This way, you can find ZoneNotFound errors later on
911 - (void)failNextZoneCreationSilently:(CKRecordZoneID*)zoneID {
912 XCTAssertNil(self.zones[zoneID], "Zone does not exist yet");
913 self.zones[zoneID] = [[FakeCKZone alloc] initZone: zoneID];
914 self.zones[zoneID].failCreationSilently = true;
917 - (void)failNextZoneSubscription:(CKRecordZoneID*)zoneID {
918 XCTAssertNotNil(self.zones[zoneID], "Zone exists");
919 self.zones[zoneID].subscriptionError = [[CKPrettyError alloc] initWithDomain:CKErrorDomain code:CKErrorNetworkUnavailable userInfo:@{}];
922 - (void)failNextZoneSubscription:(CKRecordZoneID*)zoneID withError:(NSError*)error {
923 XCTAssertNotNil(self.zones[zoneID], "Zone exists");
924 self.zones[zoneID].subscriptionError = error;
927 - (void)failNextCKAtomicModifyItemRecordsUpdateFailure:(CKRecordZoneID*)zoneID {
928 [self failNextCKAtomicModifyItemRecordsUpdateFailure:zoneID blockAfterReject:nil];
931 - (void)failNextCKAtomicModifyItemRecordsUpdateFailure:(CKRecordZoneID*)zoneID blockAfterReject: (void (^)(void))blockAfterReject {
932 [self failNextCKAtomicModifyItemRecordsUpdateFailure:zoneID blockAfterReject:blockAfterReject withError:nil];
935 - (void)failNextCKAtomicModifyItemRecordsUpdateFailure:(CKRecordZoneID*)zoneID blockAfterReject: (void (^)(void))blockAfterReject withError:(NSError*)error {
936 __weak __typeof(self) weakSelf = self;
938 [[self.mockDatabase expect] addOperation:[OCMArg checkWithBlock:^BOOL(id obj) {
939 __strong __typeof(weakSelf) strongSelf = weakSelf;
940 XCTAssertNotNil(strongSelf, "self exists");
942 __block bool rejected = false;
943 if ([obj isKindOfClass:[CKModifyRecordsOperation class]]) {
944 CKModifyRecordsOperation *op = (CKModifyRecordsOperation *)obj;
947 // We only care about atomic operations
951 // We want to only match zone updates pertaining to this zone
952 for(CKRecord* record in op.recordsToSave) {
953 if(![record.recordID.zoneID isEqual: zoneID]) {
958 FakeCKZone* zone = strongSelf.zones[zoneID];
959 XCTAssertNotNil(zone, "Have a zone for these records");
964 [strongSelf rejectWrite: op withError:error];
966 NSMutableDictionary<CKRecordID*, NSError*>* failedRecords = [[NSMutableDictionary alloc] init];
967 [strongSelf rejectWrite: op failedRecords:failedRecords];
970 if(blockAfterReject) {
974 return rejected ? YES : NO;
978 - (void)expectCKAtomicModifyItemRecordsUpdateFailure:(CKRecordZoneID*)zoneID {
979 __weak __typeof(self) weakSelf = self;
981 [[self.mockDatabase expect] addOperation:[OCMArg checkWithBlock:^BOOL(id obj) {
982 __strong __typeof(weakSelf) strongSelf = weakSelf;
983 XCTAssertNotNil(strongSelf, "self exists");
985 __block bool rejected = false;
986 if ([obj isKindOfClass:[CKModifyRecordsOperation class]]) {
987 CKModifyRecordsOperation *op = (CKModifyRecordsOperation *)obj;
989 secnotice("fakecloudkit", "checking for expectCKAtomicModifyItemRecordsUpdateFailure");
992 // We only care about atomic operations
993 secnotice("fakecloudkit", "expectCKAtomicModifyItemRecordsUpdateFailure: update not atomic");
997 // We want to only match zone updates pertaining to this zone
998 for(CKRecord* record in op.recordsToSave) {
999 if(![record.recordID.zoneID isEqual: zoneID]) {
1000 secnotice("fakecloudkit", "expectCKAtomicModifyItemRecordsUpdateFailure: %@ is not %@", record.recordID.zoneID, zoneID);
1005 FakeCKZone* zone = strongSelf.zones[zoneID];
1006 XCTAssertNotNil(zone, "Have a zone for these records");
1008 NSMutableDictionary<CKRecordID*, NSError*>* failedRecords = [[NSMutableDictionary alloc] init];
1010 @synchronized(zone.currentDatabase) {
1011 for(CKRecord* record in op.recordsToSave) {
1012 // Check if we should allow this transaction
1013 NSError* recordSaveError = [zone errorFromSavingRecord: record];
1014 if(recordSaveError) {
1015 failedRecords[record.recordID] = recordSaveError;
1022 [strongSelf rejectWrite: op failedRecords:failedRecords];
1024 secnotice("fakecloudkit", "expectCKAtomicModifyItemRecordsUpdateFailure: doesn't seem like an error to us");
1027 return rejected ? YES : NO;
1031 -(void)rejectWrite:(CKModifyRecordsOperation*)op withError:(NSError*)error {
1032 // Emulate cloudkit and schedule the operation for execution. Be sure to wait for this operation
1033 // if you'd like to read the data from this write.
1034 NSBlockOperation* ckop = [NSBlockOperation named:@"cloudkit-reject-write-error" withBlock: ^{
1035 op.modifyRecordsCompletionBlock(nil, nil, error);
1036 op.isFinished = YES;
1038 [ckop addNullableDependency: self.ckModifyHoldOperation];
1039 [self.operationQueue addOperation: ckop];
1042 -(void)rejectWrite:(CKModifyRecordsOperation*)op failedRecords:(NSMutableDictionary<CKRecordID*, NSError*>*)failedRecords {
1043 // Add the batch request failed errors
1044 for(CKRecord* record in op.recordsToSave) {
1045 NSError* exists = failedRecords[record.recordID];
1047 // TODO: might have important userInfo, but we're not mocking that yet
1048 failedRecords[record.recordID] = [[CKPrettyError alloc] initWithDomain: CKErrorDomain code: CKErrorBatchRequestFailed userInfo: @{}];
1052 NSError* error = [[CKPrettyError alloc] initWithDomain: CKErrorDomain code: CKErrorPartialFailure userInfo: @{CKPartialErrorsByItemIDKey: failedRecords}];
1054 // Emulate cloudkit and schedule the operation for execution. Be sure to wait for this operation
1055 // if you'd like to read the data from this write.
1056 NSBlockOperation* ckop = [NSBlockOperation named:@"cloudkit-reject-write" withBlock: ^{
1057 op.modifyRecordsCompletionBlock(nil, nil, error);
1058 op.isFinished = YES;
1060 [ckop addNullableDependency: self.ckModifyHoldOperation];
1061 [self.operationQueue addOperation: ckop];
1064 - (void)expectCKDeleteItemRecords:(NSUInteger)expectedNumberOfRecords
1065 zoneID:(CKRecordZoneID*) zoneID {
1067 // We're updating the device state type on every update, so add it in here
1068 NSMutableDictionary* expectedRecords = [@{
1069 SecCKRecordDeviceStateType: [NSNumber numberWithUnsignedInteger:expectedNumberOfRecords],
1071 if(SecCKKSSyncManifests()) {
1072 // TODO: this really shouldn't be 2.
1073 expectedRecords[SecCKRecordManifestType] = [NSNumber numberWithInt: 2];
1074 expectedRecords[SecCKRecordManifestLeafType] = [NSNumber numberWithInt: 72];
1077 [self expectCKModifyRecords:expectedRecords
1078 deletedRecordTypeCounts:@{SecCKRecordItemType: [NSNumber numberWithUnsignedInteger: expectedNumberOfRecords]}
1080 checkModifiedRecord:nil
1081 runAfterModification:nil];
1084 -(void)waitForCKModifications {
1085 // CloudKit modifications are put on the local queue.
1086 // This is heavyweight but should suffice.
1087 [self.operationQueue waitUntilAllOperationsAreFinished];
1091 NSString* testName = [self.name componentsSeparatedByString:@" "][1];
1092 testName = [testName stringByReplacingOccurrencesOfString:@"]" withString:@""];
1093 secnotice("ckkstest", "Ending test %@", testName);
1095 if(SecCKKSIsEnabled()) {
1096 self.accountStatus = CKAccountStatusCouldNotDetermine;
1098 // If the test never initialized the account state, don't call status later
1099 bool callStatus = [self.ckaccountHoldOperation isFinished];
1100 [self.ckaccountHoldOperation cancel];
1101 self.ckaccountHoldOperation = nil;
1103 // Ensure we don't have any blocking operations left
1104 [self.operationQueue cancelAllOperations];
1105 [self waitForCKModifications];
1107 XCTAssertEqual(0, [self.injectedManager.completedSecCKKSInitialize wait:20*NSEC_PER_SEC],
1108 "Timeout did not occur waiting for SecCKKSInitialize");
1110 // Ensure that we can fetch zone status for all zones
1112 XCTestExpectation *statusReturned = [self expectationWithDescription:@"status returned"];
1113 [self.injectedManager rpcStatus:nil reply:^(NSArray<NSDictionary *> *result, NSError *error) {
1114 XCTAssertNil(error, "Should be no error fetching status");
1115 [statusReturned fulfill];
1117 [self waitForExpectations: @[statusReturned] timeout:20];
1119 // Make sure this happens before teardown.
1120 XCTAssertEqual(0, [self.accountStateTracker.finishedInitialDispatches wait:20*NSEC_PER_SEC], "Account state tracker initialized itself");
1122 dispatch_group_t accountChangesDelivered = [self.accountStateTracker checkForAllDeliveries];
1123 XCTAssertEqual(0, dispatch_group_wait(accountChangesDelivered, dispatch_time(DISPATCH_TIME_NOW, 10*NSEC_PER_SEC)), "Account state tracker finished delivering everything");
1129 [self.injectedManager cancelPendingOperations];
1130 [self.injectedManager clearAllViews];
1131 self.injectedManager = nil;
1133 [self.mockCKKSViewManager stopMocking];
1134 self.mockCKKSViewManager = nil;
1136 self.injectedOTManager.viewManager = nil;
1138 [self.injectedOTManager clearAllContexts];
1139 self.injectedOTManager = nil;
1140 [OTManager resetManager:true to:nil];
1142 [self.mockAccountStateTracker stopMocking];
1143 self.mockAccountStateTracker = nil;
1145 [self.mockLockStateTracker stopMocking];
1146 self.mockLockStateTracker = nil;
1148 [self.mockFakeCKModifyRecordZonesOperation stopMocking];
1149 self.mockFakeCKModifyRecordZonesOperation = nil;
1151 [self.mockFakeCKModifySubscriptionsOperation stopMocking];
1152 self.mockFakeCKModifySubscriptionsOperation = nil;
1154 [self.mockFakeCKFetchRecordZoneChangesOperation stopMocking];
1155 self.mockFakeCKFetchRecordZoneChangesOperation = nil;
1157 [self.mockFakeCKFetchRecordsOperation stopMocking];
1158 self.mockFakeCKFetchRecordsOperation = nil;
1160 [self.mockFakeCKQueryOperation stopMocking];
1161 self.mockFakeCKQueryOperation = nil;
1163 [self.mockDatabase stopMocking];
1164 self.mockDatabase = nil;
1166 [self.mockDatabaseExceptionCatcher stopMocking];
1167 self.mockDatabaseExceptionCatcher = nil;
1169 [self.mockContainer stopMocking];
1170 self.mockContainer = nil;
1172 [self.mockTTR stopMocking];
1174 self.ttrExpectation = nil;
1175 self.isTTRRatelimited = true;
1179 _mockSOSAdapter = nil;
1180 _mockOctagonAdapter = nil;
1182 // Bring the database down and delete it
1184 NSURL* keychainDir = (NSURL*)CFBridgingRelease(SecCopyHomeURL());
1186 SecItemDataSourceFactoryReleaseAll();
1187 SecKeychainDbForceClose();
1188 SecKeychainDbReset(NULL);
1190 // Only perform the desctructive step if the url matches what we expect!
1191 if([keychainDir.path hasPrefix:[NSString stringWithFormat:@"/tmp/%@", testName]]) {
1192 secnotice("ckkstest", "Removing test-specific keychain directory at %@", keychainDir);
1194 NSError* removeError = nil;
1195 [[NSFileManager defaultManager] removeItemAtURL:keychainDir error:&removeError];
1197 XCTAssertNil(removeError, "Should have been able to remove temporary files");
1199 XCTFail("Unsure what happened to the keychain directory URL: %@", keychainDir);
1202 SecCKKSTestResetFlags();
1205 - (CKKSKey*) fakeTLK: (CKRecordZoneID*)zoneID {
1206 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey:[[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="]
1207 uuid:[[NSUUID UUID] UUIDString]
1208 keyclass:SecCKKSKeyClassTLK
1209 state: SecCKKSProcessedStateLocal
1211 encodedCKRecord: nil
1213 [key CKRecordWithZoneID: zoneID];
1217 - (NSError*)ckInternalServerExtensionError:(NSInteger)code description:(NSString*)desc {
1218 return [FakeCKZone internalPluginError:@"CloudkitKeychainService" code:code description:desc];