2 * Copyright (c) 2017 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@
25 #import <Foundation/Foundation.h>
26 #import <Foundation/NSKeyedArchiver_Private.h>
27 #import <CloudKit/CloudKit.h>
28 #import <CloudKit/CloudKit_Private.h>
30 #import "keychain/ot/OTCloudStore.h"
31 #import "keychain/ot/OTCloudStoreState.h"
32 #import "keychain/ckks/CKKSZoneStateEntry.h"
33 #import "keychain/ckks/CKKS.h"
34 #import "keychain/ot/OTDefines.h"
35 #import "keychain/ckks/CKKSReachabilityTracker.h"
36 #import <utilities/debugging.h>
39 NS_ASSUME_NONNULL_BEGIN
41 /* Octagon Trust Local Context Record Constants */
42 static NSString* OTCKRecordContextID = @"contextID";
43 static NSString* OTCKRecordDSID = @"accountDSID";
44 static NSString* OTCKRecordContextName = @"contextName";
45 static NSString* OTCKRecordZoneCreated = @"zoneCreated";
46 static NSString* OTCKRecordSubscribedToChanges = @"subscribedToChanges";
47 static NSString* OTCKRecordChangeToken = @"changeToken";
48 static NSString* OTCKRecordEgoPeerID = @"egoPeerID";
49 static NSString* OTCKRecordEgoPeerCreationDate = @"egoPeerCreationDate";
50 static NSString* OTCKRecordRecoverySigningSPKI = @"recoverySigningSPKI";
51 static NSString* OTCKRecordRecoveryEncryptionSPKI = @"recoveryEncryptionSPKI";
52 static NSString* OTCKRecordBottledPeerTableEntry = @"bottledPeer";
54 /* Octagon Trust Local Peer Record */
55 static NSString* OTCKRecordPeerID = @"peerID";
56 static NSString* OTCKRecordPermanentInfo = @"permanentInfo";
57 static NSString* OTCKRecordStableInfo = @"stableInfo";
58 static NSString* OTCKRecordDynamicInfo = @"dynamicInfo";
59 static NSString* OTCKRecordRecoveryVoucher = @"recoveryVoucher";
60 static NSString* OTCKRecordIsEgoPeer = @"isEgoPeer";
62 /* Octagon Trust BottledPeerSchema */
63 static NSString* OTCKRecordEscrowRecordID = @"escrowRecordID";
64 static NSString* OTCKRecordBottle = @"bottle";
65 static NSString* OTCKRecordSPID = @"spID";
66 static NSString* OTCKRecordEscrowSigningSPKI = @"escrowSigningSPKI";
67 static NSString* OTCKRecordPeerSigningSPKI = @"peerSigningSPKI";
68 static NSString* OTCKRecordSignatureFromEscrow = @"signatureUsingEscrow";
69 static NSString* OTCKRecordSignatureFromPeerKey = @"signatureUsingPeerKey";
70 static NSString* OTCKRecordEncodedRecord = @"encodedRecord";
72 /* Octagon Table Names */
73 static NSString* const contextTable = @"context";
74 static NSString* const peerTable = @"peer";
75 static NSString* const bottledPeerTable = @"bp";
77 /* Octagon Trust Schemas */
78 static NSString* const octagonZoneName = @"OctagonTrustZone";
80 /* Octagon Cloud Kit defines */
81 static NSString* OTCKContainerName = @"com.apple.security.keychain";
82 static NSString* OTCKZoneName = @"OctagonTrust";
83 static NSString* OTCKRecordName = @"bp-";
84 static NSString* OTCKRecordBottledPeerType = @"OTBottledPeer";
86 @interface OTCloudStore ()
87 @property (nonatomic, strong) NSString* dsid;
88 @property (nonatomic, strong) NSString* containerName;
89 @property (nonatomic, strong) CKModifyRecordsOperation* modifyRecordsOperation;
90 @property (nonatomic, strong) CKDatabaseOperation<CKKSFetchRecordZoneChangesOperation>* fetchRecordZoneChangesOperation;
91 @property (nonatomic, strong) NSOperationQueue *operationQueue;
92 @property (nonatomic, strong) OTLocalStore* localStore;
93 @property (nonatomic, strong) CKKSResultOperation* viewSetupOperation;
94 @property (nonatomic, strong) NSError* error;
97 @class CKKSAPSReceiver;
99 @interface OTCloudStore()
101 @property CKDatabaseOperation<CKKSModifyRecordZonesOperation>* zoneCreationOperation;
102 @property CKDatabaseOperation<CKKSModifyRecordZonesOperation>* zoneDeletionOperation;
103 @property CKDatabaseOperation<CKKSModifySubscriptionsOperation>* zoneSubscriptionOperation;
105 @property NSOperation* accountLoggedInDependency;
107 @property NSHashTable<NSOperation*>* accountOperations;
110 @implementation OTCloudStore
112 - (instancetype) initWithContainer:(CKContainer*) container
113 zoneName:(NSString*)zoneName
114 accountTracker:(nullable CKKSCKAccountStateTracker*)accountTracker
115 reachabilityTracker:(nullable CKKSReachabilityTracker*)reachabilityTracker
116 localStore:(OTLocalStore*)localStore
117 contextID:(NSString*)contextID
119 fetchRecordZoneChangesOperationClass:(Class<CKKSFetchRecordZoneChangesOperation>) fetchRecordZoneChangesOperationClass
120 fetchRecordsOperationClass:(Class<CKKSFetchRecordsOperation>)fetchRecordsOperationClass
121 queryOperationClass:(Class<CKKSQueryOperation>)queryOperationClass
122 modifySubscriptionsOperationClass:(Class<CKKSModifySubscriptionsOperation>) modifySubscriptionsOperationClass
123 modifyRecordZonesOperationClass:(Class<CKKSModifyRecordZonesOperation>) modifyRecordZonesOperationClass
124 apsConnectionClass:(Class<CKKSAPSConnection>) apsConnectionClass
125 operationQueue:(nullable NSOperationQueue *)operationQueue
128 self = [super initWithContainer:container
130 accountTracker:accountTracker
131 reachabilityTracker:reachabilityTracker
132 fetchRecordZoneChangesOperationClass:fetchRecordZoneChangesOperationClass
133 fetchRecordsOperationClass:fetchRecordsOperationClass
134 queryOperationClass:queryOperationClass
135 modifySubscriptionsOperationClass:modifySubscriptionsOperationClass
136 modifyRecordZonesOperationClass:modifyRecordZonesOperationClass
137 apsConnectionClass:apsConnectionClass];
140 if (!operationQueue) {
141 operationQueue = [[NSOperationQueue alloc] init];
143 _contextID = [contextID copy];
144 _localStore = localStore;
145 _containerName = OTCKContainerName;
147 _operationQueue = operationQueue;
148 self.queue = dispatch_queue_create([[NSString stringWithFormat:@"OctagonTrustQueue.%@.zone.%@", container.containerIdentifier, zoneName] UTF8String], DISPATCH_QUEUE_SERIAL);
149 [self initializeZone];
155 -(CKKSResultOperation*) otFetchAndProcessUpdates
157 CKKSResultOperation* fetchOp = [CKKSResultOperation named:@"fetch-and-process-updates-watcher" withBlock:^{}];
159 __weak __typeof(self) weakSelf = self;
161 [self dispatchSync: ^bool{
163 OTCloudStoreState* state = [OTCloudStoreState state: self.zoneName];
165 CKFetchRecordZoneChangesConfiguration* options = [[CKFetchRecordZoneChangesConfiguration alloc] init];
166 options.previousServerChangeToken = state.changeToken;
168 self.fetchRecordZoneChangesOperation = [[[self.fetchRecordZoneChangesOperationClass class] alloc] initWithRecordZoneIDs:@[self.zoneID] configurationsByRecordZoneID:@{self.zoneID : options}];
170 self.fetchRecordZoneChangesOperation.recordChangedBlock = ^(CKRecord *record) {
171 secinfo("octagon", "CloudKit notification: record changed(%@): %@", [record recordType], record);
172 __strong __typeof(weakSelf) strongSelf = weakSelf;
175 secnotice("octagon", "received callback for released object");
176 fetchOp.error = [NSError errorWithDomain:octagonErrorDomain code:OTErrorOTCloudStore userInfo:@{NSLocalizedDescriptionKey: @"received callback for released object"}];
178 fetchOp.descriptionErrorCode = CKKSResultDescriptionPendingBottledPeerFetchRecords;
182 if ([record.recordType isEqualToString:OTCKRecordBottledPeerType]) {
183 NSError* localError = nil;
185 //write to localStore
186 OTBottledPeerRecord *rec = [[OTBottledPeerRecord alloc] init];
187 rec.bottle = record[OTCKRecordBottle];
188 rec.spID = record[OTCKRecordSPID];
189 rec.escrowRecordID = record[OTCKRecordEscrowRecordID];
190 rec.escrowedSigningSPKI = record[OTCKRecordEscrowSigningSPKI];
191 rec.peerSigningSPKI = record[OTCKRecordPeerSigningSPKI];
192 rec.signatureUsingEscrowKey = record[OTCKRecordSignatureFromEscrow];
193 rec.signatureUsingPeerKey = record[OTCKRecordSignatureFromPeerKey];
194 rec.encodedRecord = [strongSelf recordToData:record];
195 rec.launched = @"YES";
196 BOOL result = [strongSelf.localStore insertBottledPeerRecord:rec escrowRecordID:record[OTCKRecordEscrowRecordID] error:&localError];
197 if(!result || localError){
198 secerror("Could not write bottled peer record:%@ to database: %@", record.recordID.recordName, localError);
199 fetchOp.error = localError;
200 fetchOp.descriptionErrorCode = CKKSResultDescriptionPendingBottledPeerFetchRecords;
203 secnotice("octagon", "fetched changes: %@", record);
207 self.fetchRecordZoneChangesOperation.recordWithIDWasDeletedBlock = ^(CKRecordID *RecordID, NSString *recordType) {
208 secinfo("octagon", "CloudKit notification: deleted record(%@): %@", recordType, RecordID);
211 self.fetchRecordZoneChangesOperation.recordZoneChangeTokensUpdatedBlock = ^(CKRecordZoneID *recordZoneID, CKServerChangeToken *serverChangeToken, NSData *clientChangeTokenData) {
212 __strong __typeof(weakSelf) strongSelf = weakSelf;
213 NSError* error = nil;
214 OTCloudStoreState* state = [OTCloudStoreState state: strongSelf.zoneName];
215 secdebug("octagon", "Received a new server change token: %@ %@", serverChangeToken, clientChangeTokenData);
216 state.changeToken = serverChangeToken;
219 secerror("octagon: Couldn't save new server change token: %@", error);
220 fetchOp.error = error;
221 fetchOp.descriptionErrorCode = CKKSResultDescriptionPendingBottledPeerFetchRecords;
225 // Completion blocks don't count for dependencies. Use this intermediate operation hack instead.
226 NSBlockOperation* recordZoneChangesCompletedOperation = [[NSBlockOperation alloc] init];
227 self.fetchRecordZoneChangesOperation.recordZoneFetchCompletionBlock = ^(CKRecordZoneID *recordZoneID, CKServerChangeToken *serverChangeToken, NSData *clientChangeTokenData, BOOL moreComing, NSError * recordZoneError) {
228 __strong __typeof(weakSelf) strongSelf = weakSelf;
230 secnotice("octagon", "received callback for released object");
233 if(recordZoneError) {
234 secerror("octagon: FetchRecordZoneChanges(%@) error: %@", strongSelf.zoneName, recordZoneError);
235 fetchOp.error = recordZoneError;
236 fetchOp.descriptionErrorCode = CKKSResultDescriptionPendingBottledPeerFetchRecords;
239 // TODO: fetch state here
240 if(serverChangeToken) {
241 NSError* error = nil;
242 secdebug("octagon", "Zone change fetch complete: received a new server change token: %@ %@", serverChangeToken, clientChangeTokenData);
243 state.changeToken = serverChangeToken;
245 secerror("octagon: Couldn't save new server change token: %@", error);
246 fetchOp.error = error;
247 fetchOp.descriptionErrorCode = CKKSResultDescriptionPendingBottledPeerFetchRecords;
250 secdebug("octagon", "Record zone fetch complete: changeToken=%@ error=%@", serverChangeToken, recordZoneError);
252 [strongSelf.operationQueue addOperation: recordZoneChangesCompletedOperation];
253 [strongSelf.operationQueue addOperation: fetchOp];
256 self.fetchRecordZoneChangesOperation.fetchRecordZoneChangesCompletionBlock = ^(NSError * _Nullable operationError) {
257 __strong __typeof(weakSelf) strongSelf = weakSelf;
259 secnotice("octagon", "received callback for released object");
260 fetchOp.error = [NSError errorWithDomain:octagonErrorDomain code:OTErrorOTCloudStore userInfo:@{NSLocalizedDescriptionKey: @"received callback for released object"}];
261 fetchOp.descriptionErrorCode = CKKSResultDescriptionPendingBottledPeerFetchRecords;
264 secnotice("octagon", "Record zone changes fetch complete: error=%@", operationError);
268 [self.database addOperation: self.fetchRecordZoneChangesOperation];
274 - (void)notifyZoneChange:(CKRecordZoneNotification* _Nullable)notification
276 secnotice("octagon", "received notify zone change. notification: %@", notification);
278 CKKSResultOperation* op = [CKKSResultOperation named:@"cloudkit-fetch-and-process-changes" withBlock:^{}];
280 [op addSuccessDependency: [self otFetchAndProcessUpdates]];
282 [op timeout:(SecCKKSTestsEnabled() ? 2*NSEC_PER_SEC : 120*NSEC_PER_SEC)];
283 [self.operationQueue addOperation: op];
285 [op waitUntilFinished];
286 if(op.error != nil) {
287 secerror("octagon: failed to fetch changes error:%@", op.error);
290 secnotice("octagon", "downloaded bottled peer records");
294 -(BOOL) downloadBottledPeerRecord:(NSError**)error
296 secnotice("octagon", "downloadBottledPeerRecord");
298 CKKSResultOperation* op = [CKKSResultOperation named:@"cloudkit-fetch-and-process-changes" withBlock:^{}];
300 [op addSuccessDependency: [self otFetchAndProcessUpdates]];
302 [op timeout:(SecCKKSTestsEnabled() ? 2*NSEC_PER_SEC : 120*NSEC_PER_SEC)];
303 [self.operationQueue addOperation: op];
305 [op waitUntilFinished];
306 if(op.error != nil) {
307 secerror("octagon: failed to fetch changes error:%@", op.error);
314 secnotice("octagon", "downloaded bottled peer records");
319 - (nullable NSArray*) retrieveListOfEligibleEscrowRecordIDs:(NSError**)error
321 NSError* localError = nil;
323 NSMutableArray* recordIDs = [NSMutableArray array];
325 //fetch any recent changes first before gathering escrow record ids
326 CKKSResultOperation* op = [CKKSResultOperation named:@"cloudkit-fetch-and-process-changes" withBlock:^{}];
328 secnotice("octagon", "Beginning CloudKit fetch");
329 [op addSuccessDependency: [self otFetchAndProcessUpdates]];
331 [op timeout:(SecCKKSTestsEnabled() ? 2*NSEC_PER_SEC : 120*NSEC_PER_SEC)];
332 [self.operationQueue addOperation: op];
334 [op waitUntilFinished];
335 if(op.error != nil) {
336 secnotice("octagon", "failed to fetch changes error:%@", op.error);
339 secnotice("octagon", "checking local store for bottles");
341 //check localstore for bottles
342 NSArray* localStoreBottledPeerRecords = [self.localStore readAllLocalBottledPeerRecords:&localError];
343 if(!localStoreBottledPeerRecords)
345 secerror("octagon: local store contains no bottled peer entries: %@", localError);
351 for(OTBottledPeerRecord* entry in localStoreBottledPeerRecords){
352 NSString* escrowID = entry.escrowRecordID;
353 if(escrowID && ![recordIDs containsObject:escrowID]){
354 [recordIDs addObject:escrowID];
361 -(CKRecord*) dataToRecord:(NSData*)encodedRecord
363 NSKeyedUnarchiver *coder = [[NSKeyedUnarchiver alloc] initForReadingFromData:encodedRecord error:nil];
364 CKRecord* record = [[CKRecord alloc] initWithCoder:coder];
365 [coder finishDecoding];
369 -(NSData*) recordToData:(CKRecord*)record
371 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initRequiringSecureCoding:YES];
372 [record encodeWithCoder:archiver];
373 [archiver finishEncoding];
375 return archiver.encodedData;
378 -( CKRecord* _Nullable ) CKRecordFromMirror:(CKRecordID*)recordID bpRecord:(OTBottledPeerRecord*)bprecord escrowRecordID:(NSString*)escrowRecordID error:(NSError**)error
380 CKRecord* record = nil;
382 OTBottledPeerRecord* recordFromDB = [self.localStore readLocalBottledPeerRecordWithRecordID:recordID.recordName error:error];
383 if(recordFromDB && recordFromDB.encodedRecord != nil){
384 record = [self dataToRecord:recordFromDB.encodedRecord];
387 record = [[CKRecord alloc] initWithRecordType:OTCKRecordBottledPeerType recordID:recordID];
391 secerror("octagon: failed to create cloud kit record");
393 *error = [NSError errorWithDomain:octagonErrorDomain code:OTErrorOTCloudStore userInfo:@{NSLocalizedDescriptionKey: @"failed to create cloud kit record"}];
397 record[OTCKRecordPeerID] = bprecord.peerID;
398 record[OTCKRecordSPID] = bprecord.spID;
399 record[OTCKRecordEscrowSigningSPKI] = bprecord.escrowedSigningSPKI;
400 record[OTCKRecordPeerSigningSPKI] = bprecord.peerSigningSPKI;
401 record[OTCKRecordEscrowRecordID] = escrowRecordID;
402 record[OTCKRecordBottle] = bprecord.bottle;
403 record[OTCKRecordSignatureFromEscrow] = bprecord.signatureUsingEscrowKey;
404 record[OTCKRecordSignatureFromPeerKey] = bprecord.signatureUsingPeerKey;
409 -(CKKSResultOperation*) modifyRecords:(NSArray<CKRecord *>*) recordsToSave deleteRecordIDs:(NSArray<CKRecordID*>*) recordIDsToDelete
411 __weak __typeof(self) weakSelf = self;
412 CKKSResultOperation* modifyOp = [CKKSResultOperation named:@"modify-records-watcher" withBlock:^{}];
414 [self dispatchSync: ^bool{
415 self.modifyRecordsOperation = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave recordIDsToDelete:recordIDsToDelete];
417 self.modifyRecordsOperation.atomic = YES;
418 self.modifyRecordsOperation.longLived = NO; // The keys are only in memory; mark this explicitly not long-lived
420 // Currently done during buddy. User is waiting.
421 self.modifyRecordsOperation.configuration.automaticallyRetryNetworkFailures = NO;
422 self.modifyRecordsOperation.configuration.discretionaryNetworkBehavior = CKOperationDiscretionaryNetworkBehaviorNonDiscretionary;
424 self.modifyRecordsOperation.savePolicy = CKRecordSaveIfServerRecordUnchanged;
426 self.modifyRecordsOperation.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
427 // These should all fail or succeed as one. Do the hard work in the records completion block.
429 secnotice("octagon", "Successfully completed upload for %@", record.recordID.recordName);
432 secerror("octagon: error on row: %@ %@", record.recordID.recordName, error);
433 modifyOp.error = error;
434 modifyOp.descriptionErrorCode = CKKSResultDescriptionPendingBottledPeerModifyRecords;
435 [weakSelf.operationQueue addOperation:modifyOp];
438 self.modifyRecordsOperation.modifyRecordsCompletionBlock = ^(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deletedRecordIDs, NSError *error) {
439 secnotice("octagon", "Completed trust update");
440 __strong __typeof(weakSelf) strongSelf = weakSelf;
443 modifyOp.error = error;
444 modifyOp.descriptionErrorCode = CKKSResultDescriptionPendingBottledPeerModifyRecords;
445 secerror("octagon: received error from cloudkit: %@", error);
446 if([error.domain isEqualToString:CKErrorDomain] && (error.code == CKErrorPartialFailure)) {
447 NSMutableDictionary<CKRecordID*, NSError*>* failedRecords = error.userInfo[CKPartialErrorsByItemIDKey];
448 ckksnotice("octagon", strongSelf, "failed records %@", failedRecords);
453 secerror("octagon: received callback for released object");
454 modifyOp.error = [NSError errorWithDomain:octagonErrorDomain code:OTErrorOTCloudStore userInfo:@{NSLocalizedDescriptionKey: @"received callback for released object"}];
455 modifyOp.descriptionErrorCode = CKKSResultDescriptionPendingBottledPeerModifyRecords;
456 [strongSelf.operationQueue addOperation:modifyOp];
460 if(savedRecords && [savedRecords count] > 0){
461 for(CKRecord* record in savedRecords){
462 NSError* localError = nil;
463 secnotice("octagon", "saving recordID: %@ changeToken:%@", record.recordID.recordName, record.recordChangeTag);
465 //write to localStore
466 OTBottledPeerRecord *rec = [[OTBottledPeerRecord alloc] init];
467 rec.bottle = record[OTCKRecordBottle];
468 rec.spID = record[OTCKRecordSPID];
469 rec.escrowRecordID = record[OTCKRecordEscrowRecordID];
470 rec.signatureUsingEscrowKey = record[OTCKRecordSignatureFromEscrow];
471 rec.signatureUsingPeerKey = record[OTCKRecordSignatureFromPeerKey];
472 rec.encodedRecord = [strongSelf recordToData:record];
473 rec.launched = @"YES";
474 rec.escrowedSigningSPKI = record[OTCKRecordEscrowSigningSPKI];
475 rec.peerSigningSPKI = record[OTCKRecordPeerSigningSPKI];
477 BOOL result = [strongSelf.localStore insertBottledPeerRecord:rec escrowRecordID:record[OTCKRecordEscrowRecordID] error:&localError];
479 if(!result || localError){
480 secerror("Could not write bottled peer record:%@ to database: %@", record.recordID.recordName, localError);
484 secerror("octagon: could not save to database: %@", localError);
485 modifyOp.error = localError;
486 modifyOp.descriptionErrorCode = CKKSResultDescriptionPendingBottledPeerModifyRecords;
490 else if(deletedRecordIDs && [deletedRecordIDs count] >0){
491 for(CKRecordID* recordID in deletedRecordIDs){
492 secnotice("octagon", "removed recordID: %@", recordID);
493 NSError* localError = nil;
494 BOOL result = [strongSelf.localStore deleteBottledPeer:recordID.recordName error:&localError];
496 secerror("octagon: could not remove record id: %@, error:%@", recordID, localError);
497 modifyOp.error = localError;
498 modifyOp.descriptionErrorCode = CKKSResultDescriptionPendingBottledPeerModifyRecords;
502 [strongSelf.operationQueue addOperation:modifyOp];
507 [self.database addOperation: self.modifyRecordsOperation];
511 - (BOOL) uploadBottledPeerRecord:(OTBottledPeerRecord *)bprecord
512 escrowRecordID:(NSString *)escrowRecordID
513 error:(NSError**)error
515 secnotice("octagon", "sending bottled peer to cloudkit");
518 CKRecordID* recordID = [[CKRecordID alloc] initWithRecordName:bprecord.recordName zoneID:self.zoneID];
519 CKRecord *record = [self CKRecordFromMirror:recordID bpRecord:bprecord escrowRecordID:escrowRecordID error:error];
524 CKKSResultOperation* op = [CKKSResultOperation named:@"cloudkit-modify-changes" withBlock:^{}];
526 secnotice("octagon", "Beginning CloudKit ModifyRecords");
527 [op addSuccessDependency: [self modifyRecords:@[ record ] deleteRecordIDs:@[]]];
529 [op timeout:(SecCKKSTestsEnabled() ? 2*NSEC_PER_SEC : 120*NSEC_PER_SEC)];
530 [self.operationQueue addOperation: op];
532 [op waitUntilFinished];
533 if(op.error != nil) {
534 secerror("octagon: failed to commit record changes error:%@", op.error);
540 secnotice("octagon", "successfully uploaded record: %@", bprecord.recordName);
544 -(BOOL) removeBottledPeerRecordID:(CKRecordID*)recordID error:(NSError**)error
546 secnotice("octagon", "removing bottled peer from cloudkit");
549 NSMutableArray<CKRecordID*>* recordIDsToRemove = [[NSMutableArray alloc] init];
550 [recordIDsToRemove addObject:recordID];
552 CKKSResultOperation* op = [CKKSResultOperation named:@"cloudkit-modify-changes" withBlock:^{}];
554 secnotice("octagon", "Beginning CloudKit ModifyRecords");
555 [op addSuccessDependency: [self modifyRecords:[NSMutableArray array] deleteRecordIDs:recordIDsToRemove]];
557 [op timeout:(SecCKKSTestsEnabled() ? 2*NSEC_PER_SEC : 120*NSEC_PER_SEC)];
558 [self.operationQueue addOperation: op];
560 [op waitUntilFinished];
561 if(op.error != nil) {
562 secerror("octagon: ailed to commit record changes error:%@", op.error);
572 - (void)_onqueueHandleCKLogin {
573 if(!SecCKKSIsEnabled()) {
574 ckksnotice("ckks", self, "Skipping CloudKit initialization due to disabled CKKS");
578 dispatch_assert_queue(self.queue);
580 __weak __typeof(self) weakSelf = self;
582 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry state: self.zoneName];
583 [self handleCKLogin:ckse.ckzonecreated zoneSubscribed:ckse.ckzonesubscribed];
585 self.viewSetupOperation = [CKKSResultOperation operationWithBlock: ^{
586 __strong __typeof(weakSelf) strongSelf = weakSelf;
588 ckkserror("ckks", strongSelf, "received callback for released object");
592 __block bool quit = false;
594 [strongSelf dispatchSync: ^bool {
595 ckksnotice("octagon", strongSelf, "Zone setup progress: %@ %d %@ %d %@",
596 [CKKSCKAccountStateTracker stringFromAccountStatus:strongSelf.accountStatus],
597 strongSelf.zoneCreated, strongSelf.zoneCreatedError, strongSelf.zoneSubscribed, strongSelf.zoneSubscribedError);
599 NSError* error = nil;
600 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry state: strongSelf.zoneName];
601 ckse.ckzonecreated = strongSelf.zoneCreated;
602 ckse.ckzonesubscribed = strongSelf.zoneSubscribed;
604 // Although, if the zone subscribed error says there's no zone, mark down that there's no zone
605 if(strongSelf.zoneSubscribedError &&
606 [strongSelf.zoneSubscribedError.domain isEqualToString:CKErrorDomain] && strongSelf.zoneSubscribedError.code == CKErrorPartialFailure) {
607 NSError* subscriptionError = strongSelf.zoneSubscribedError.userInfo[CKPartialErrorsByItemIDKey][strongSelf.zoneID];
608 if(subscriptionError && [subscriptionError.domain isEqualToString:CKErrorDomain] && subscriptionError.code == CKErrorZoneNotFound) {
610 ckkserror("octagon", strongSelf, "zone subscription error appears to say the zone doesn't exist, fixing status: %@", strongSelf.zoneSubscribedError);
611 ckse.ckzonecreated = false;
615 [ckse saveToDatabase: &error];
617 ckkserror("octagon", strongSelf, "couldn't save zone creation status for %@: %@", strongSelf.zoneName, error);
620 if(!strongSelf.zoneCreated || !strongSelf.zoneSubscribed || strongSelf.accountStatus != CKAccountStatusAvailable) {
621 // Something has gone very wrong. Error out and maybe retry.
624 // Note that CKKSZone has probably called [handleLogout]; which means we have a key hierarchy reset queued up. Error here anyway.
625 NSError* realReason = strongSelf.zoneCreatedError ? strongSelf.zoneCreatedError : strongSelf.zoneSubscribedError;
626 strongSelf.viewSetupOperation.error = realReason;
636 ckkserror("octagon", strongSelf, "Quitting setup.");
640 self.viewSetupOperation.name = @"zone-setup";
642 [self.viewSetupOperation addNullableDependency: self.zoneSetupOperation];
643 [self scheduleAccountStatusOperation: self.viewSetupOperation];
646 - (void)handleCKLogin
648 ckksinfo("octagon", self, "received a notification of CK login");
650 __weak __typeof(self) weakSelf = self;
651 CKKSResultOperation* login = [CKKSResultOperation named:@"octagon-login" withBlock:^{
652 __strong __typeof(self) strongSelf = weakSelf;
654 [strongSelf dispatchSync:^bool{
655 strongSelf.accountStatus = CKKSAccountStatusAvailable;
656 [strongSelf _onqueueHandleCKLogin];
661 [self scheduleAccountStatusOperation:login];
664 - (bool)_onqueueResetLocalData: (NSError * __autoreleasing *) error {
665 dispatch_assert_queue(self.queue);
667 NSError* localerror = nil;
668 bool setError = false;
670 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry state: self.zoneName];
671 ckse.ckzonecreated = false;
672 ckse.ckzonesubscribed = false;
673 ckse.changeToken = NULL;
674 [ckse saveToDatabase: &localerror];
676 ckkserror("ckks", self, "couldn't reset zone status for %@: %@", self.zoneName, localerror);
677 if(error && !setError) {
678 *error = localerror; setError = true;
682 BOOL result = [_localStore removeAllBottledPeerRecords:&localerror];
685 secerror("octagon: failed to move all bottled peer entries for context: %@ error: %@", self.contextID, localerror);
687 return (localerror == nil && !setError);
690 -(CKKSResultOperation*) resetOctagonTrustZone:(NSError**)error
692 // On a reset, we should cancel all existing operations
693 [self cancelAllOperations];
694 CKKSResultOperation* reset = [super deleteCloudKitZoneOperation:nil];
695 [self scheduleOperationWithoutDependencies:reset];
697 __weak __typeof(self) weakSelf = self;
698 CKKSGroupOperation* resetFollowUp = [[CKKSGroupOperation alloc] init];
699 resetFollowUp.name = @"cloudkit-reset-follow-up-group";
701 [resetFollowUp runBeforeGroupFinished: [CKKSResultOperation named:@"cloudkit-reset-follow-up" withBlock: ^{
702 __strong __typeof(weakSelf) strongSelf = weakSelf;
704 ckkserror("octagon", strongSelf, "received callback for released object");
709 ckksnotice("octagon", strongSelf, "Successfully deleted zone %@", strongSelf.zoneName);
710 __block NSError* error = nil;
712 [strongSelf dispatchSync: ^bool{
713 [strongSelf _onqueueResetLocalData: &error];
717 // Shouldn't ever happen, since reset is a successDependency
718 ckkserror("ckks", strongSelf, "Couldn't reset zone %@: %@", strongSelf.zoneName, reset.error);
722 [resetFollowUp addSuccessDependency:reset];
723 [self scheduleOperationWithoutDependencies:resetFollowUp];
728 -(BOOL) performReset:(NSError**)error
731 CKKSResultOperation* op = [CKKSResultOperation named:@"cloudkit-reset-zones-waiter" withBlock:^{}];
733 secnotice("octagon", "Beginning CloudKit reset for Octagon Trust");
734 [op addSuccessDependency:[self resetOctagonTrustZone:error]];
736 [op timeout:(SecCKKSTestsEnabled() ? 2*NSEC_PER_SEC : 120*NSEC_PER_SEC)];
737 [self.operationQueue addOperation: op];
739 [op waitUntilFinished];
741 secnotice("octagon", "Completed rpcResetCloudKit");
742 __weak __typeof(self) weakSelf = self;
743 CKKSResultOperation* login = [CKKSResultOperation named:@"octagon-login" withBlock:^{
744 __strong __typeof(self) strongSelf = weakSelf;
746 [strongSelf dispatchSync:^bool{
747 strongSelf.accountStatus = CKKSAccountStatusAvailable;
748 [strongSelf handleCKLogin:false zoneSubscribed:false];
753 [self.operationQueue addOperation:login];
756 secnotice("octagon", "Completed rpcResetCloudKit with error: %@", op.error);
767 NS_ASSUME_NONNULL_END