2 * Copyright (c) 2018 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 <utilities/debugging.h>
28 #import <CloudKit/CloudKit_Private.h>
30 #import "keychain/ot/OTJoinWithVoucherOperation.h"
31 #import "keychain/ot/OTOperationDependencies.h"
32 #import "keychain/ot/OTFetchCKKSKeysOperation.h"
33 #import "keychain/ckks/CKKSNearFutureScheduler.h"
34 #import "keychain/ckks/CloudKitCategories.h"
36 #import "keychain/TrustedPeersHelper/TrustedPeersHelperProtocol.h"
37 #import "keychain/ot/ObjCImprovements.h"
38 #import "keychain/ot/OTStates.h"
40 @interface OTJoinWithVoucherOperation ()
41 @property OTOperationDependencies* deps;
43 @property OctagonState* ckksConflictState;
45 @property NSOperation* finishedOp;
46 @property int retries;
47 @property int maxRetries;
49 @property CKKSNearFutureScheduler* retrySched;
52 @implementation OTJoinWithVoucherOperation
54 @synthesize intendedState = _intendedState;
56 - (instancetype)initWithDependencies:(OTOperationDependencies*)dependencies
57 intendedState:(OctagonState*)intendedState
58 ckksConflictState:(OctagonState*)ckksConflictState
59 errorState:(OctagonState*)errorState
60 voucherData:(NSData*)voucherData
61 voucherSig:(NSData*)voucherSig
62 preapprovedKeys:(NSArray<NSData *>*)preapprovedKeys
64 if((self = [super init])) {
71 _intendedState = intendedState;
72 _nextState = errorState;
73 _ckksConflictState = ckksConflictState;
75 _voucherData = voucherData;
76 _voucherSig = voucherSig;
77 _preapprovedKeys = preapprovedKeys;
84 secnotice("octagon", "joining");
86 self.finishedOp = [[NSOperation alloc] init];
87 [self dependOnBeforeGroupFinished:self.finishedOp];
91 OTFetchCKKSKeysOperation* fetchKeysOp = [[OTFetchCKKSKeysOperation alloc] initWithDependencies:self.deps];
92 [self runBeforeGroupFinished:fetchKeysOp];
94 CKKSResultOperation* proceedWithKeys = [CKKSResultOperation named:@"vouch-with-keys"
97 [self proceedWithKeys:fetchKeysOp.viewKeySets
98 pendingTLKShares:fetchKeysOp.pendingTLKShares];
101 [proceedWithKeys addDependency:fetchKeysOp];
102 [self runBeforeGroupFinished:proceedWithKeys];
105 - (BOOL)isRetryable:(NSError* _Nonnull)error {
106 return [error isCuttlefishError:CuttlefishErrorTransactionalFailure];
109 - (int)retryDelay:(NSError* _Nonnull)error {
110 NSError* underlyingError = error.userInfo[NSUnderlyingErrorKey];
111 int ret = self->_delay;
112 if (underlyingError) {
113 id tmp = underlyingError.userInfo[@"retryafter"];
114 if ([tmp isKindOfClass:[NSNumber class]]) {
115 ret = [(NSNumber*)tmp intValue];
118 ret = MAX(MIN(ret, 32), self->_delay);
123 - (void)proceedWithKeys:(NSArray<CKKSKeychainBackedKeySet*>*)viewKeySets pendingTLKShares:(NSArray<CKKSTLKShare*>*)pendingTLKShares
127 [[self.deps.cuttlefishXPC remoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {
129 secerror("octagon: Can't talk with TrustedPeersHelper: %@", error);
130 [[CKKSAnalytics logger] logRecoverableError:error forEvent:OctagonEventJoinWithVoucher withAttributes:NULL];
132 [self runBeforeGroupFinished:self.finishedOp];
134 }] joinWithContainer:self.deps.containerName
135 context:self.deps.contextID
136 voucherData:self.voucherData
137 voucherSig:self.voucherSig
139 tlkShares:pendingTLKShares
140 preapprovedKeys:self.preapprovedKeys
141 reply:^(NSString * _Nullable peerID, NSArray<CKRecord*>* keyHierarchyRecords, NSError * _Nullable error) {
143 secerror("octagon: Error joining with voucher: %@", error);
144 [[CKKSAnalytics logger] logRecoverableError:error forEvent:OctagonEventJoinWithVoucher withAttributes:NULL];
146 if (self.retries < self.maxRetries && [self isRetryable:error]) {
148 if (!self.retrySched) {
149 self.retrySched = [[CKKSNearFutureScheduler alloc] initWithName:@"cuttlefish-join-retry"
151 keepProcessAlive:true
152 dependencyDescriptionCode:CKKSResultDescriptionNone
154 CKKSResultOperation* proceedWithKeys = [CKKSResultOperation named:@"vouch-with-keys"
157 secnotice("octagon", "retrying (%d/%d) join", self.retries, self->_maxRetries);
158 [self proceedWithKeys:viewKeySets
159 pendingTLKShares:pendingTLKShares];
162 [self runBeforeGroupFinished:proceedWithKeys];
165 int delay_s = [self retryDelay:error];
166 [self.retrySched waitUntil:delay_s*NSEC_PER_SEC];
167 [self.retrySched trigger];
171 // IF this is a CKKS conflict error, don't retry
172 if ([error isCuttlefishError:CuttlefishErrorKeyHierarchyAlreadyExists]) {
173 secnotice("octagon-ckks", "A CKKS key hierarchy is out of date; going to state '%@'", self.ckksConflictState);
174 self.nextState = self.ckksConflictState;
179 self.peerID = peerID;
181 [[CKKSAnalytics logger] logSuccessForEventNamed:OctagonEventJoinWithVoucher];
183 NSError* localError = nil;
184 BOOL persisted = [self.deps.stateHolder persistAccountChanges:^OTAccountMetadataClassC * _Nonnull(OTAccountMetadataClassC * _Nonnull metadata) {
185 metadata.trustState = OTAccountMetadataClassC_TrustState_TRUSTED;
186 metadata.peerID = peerID;
188 } error:&localError];
189 if(!persisted || localError) {
190 secnotice("octagon", "Couldn't persist results: %@", localError);
191 self.error = localError;
193 secerror("octagon: join successful");
194 self.nextState = self.intendedState;
197 // Tell CKKS about our shiny new records!
198 for (id key in self.deps.viewManager.views) {
199 CKKSKeychainView* view = self.deps.viewManager.views[key];
200 secnotice("octagon-ckks", "Providing join() records to %@", view);
201 [view receiveTLKUploadRecords: keyHierarchyRecords];
204 [self runBeforeGroupFinished:self.finishedOp];