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 <CloudKit/CloudKit.h>
27 #import <XCTest/XCTest.h>
28 #import <OCMock/OCMock.h>
29 #import <SecurityFoundation/SFKey.h>
30 #import <SecurityFoundation/SFKey_Private.h>
31 #import <SecurityFoundation/SFDigestOperation.h>
33 #import "keychain/ckks/tests/CloudKitMockXCTest.h"
34 #import "keychain/ckks/tests/CloudKitKeychainSyncingMockXCTest.h"
35 #import "keychain/ckks/CKKS.h"
36 #import "keychain/ckks/CKKSAPSReceiver.h"
37 #import "keychain/ckks/CKKSKey.h"
38 #import "keychain/ckks/CKKSPeer.h"
39 #import "keychain/ckks/CKKSTLKShare.h"
40 #import "keychain/ckks/CKKSViewManager.h"
41 #import "keychain/ckks/CloudKitCategories.h"
43 #import "keychain/ckks/tests/MockCloudKit.h"
44 #import "keychain/ckks/tests/CKKSTests.h"
45 #import "keychain/ot/OTDefines.h"
47 #import "keychain/ckks/tests/CKKSAPSReceiverTests.h"
49 @interface CKKSAPSHandlingTests : CloudKitKeychainSyncingTestsBase
50 @property CKRecordZoneID* manateeZoneID;
51 @property CKKSKeychainView* manateeView;
52 @property FakeCKZone* manateeZone;
53 @property (readonly) ZoneKeys* manateeZoneKeys;
57 @implementation CKKSAPSHandlingTests
58 // We really just want two views here
59 - (NSSet*)managedViewList {
60 return [NSSet setWithObjects:@"keychain", @"Manatee", nil];
66 // Wait for the ViewManager to be brought up
67 XCTAssertEqual(0, [self.injectedManager.completedSecCKKSInitialize wait:20*NSEC_PER_SEC], "No timeout waiting for SecCKKSInitialize");
69 self.manateeZoneID = [[CKRecordZoneID alloc] initWithZoneName:@"Manatee" ownerName:CKCurrentUserDefaultName];
70 [self.ckksZones addObject:self.manateeZoneID];
71 self.manateeZone = [[FakeCKZone alloc] initZone: self.manateeZoneID];
72 self.zones[self.manateeZoneID] = self.manateeZone;
73 self.manateeView = [[CKKSViewManager manager] findView:@"Manatee"];
74 [self.ckksViews addObject:self.manateeView];
75 XCTAssertNotNil(self.manateeView, "CKKSViewManager created the Manatee view");
79 // If the test didn't already do this, allow each zone to spin up
80 self.accountStatus = CKAccountStatusNoAccount;
81 [self startCKKSSubsystem];
83 [self.manateeView halt];
84 [self.manateeView waitUntilAllOperationsAreFinished];
85 self.manateeView = nil;
90 - (void)testSendPushMetricUponRequest {
91 for(CKRecordZoneID* zoneID in self.ckksZones) {
92 [self putFakeKeyHierarchyInCloudKit:zoneID];
93 [self saveTLKMaterialToKeychain:zoneID];
94 [self expectCKKSTLKSelfShareUpload:zoneID];
97 [self startCKKSSubsystem];
99 for(CKKSKeychainView* view in self.ckksViews) {
100 XCTAssertEqual(0, [view.keyHierarchyConditions[SecCKKSZoneKeyStateReady] wait:20*NSEC_PER_SEC], "Key state should enter 'ready' for view %@", view);
103 OCMVerifyAllWithDelay(self.mockDatabase, 20);
105 CKRecord* keychainRecord = [self createFakeRecord:self.keychainZoneID recordName:@"7B598D31-F9C5-481E-98AC-5A507ACB2D85" withAccount:@"keychain-view"];
106 [self.keychainZone addToZone: keychainRecord];
108 // Manatee gets one too!
109 CKRecord* manateeRecord = [self createFakeRecord:self.manateeZoneID recordName:@"7B598D31-F9C5-481E-98AC-000000000000" withAccount:@"manatee-view"];
110 [self.manateeZone addToZone:manateeRecord];
112 // Trigger a notification just for keychain zone. Both keychain and Manatee should process their incoming queues, and receive their items.
113 CKKSResultOperation* keychainProcessOp = [self.keychainView resultsOfNextProcessIncomingQueueOperation];
114 XCTAssertNotNil(keychainProcessOp, "Should have gotten a promise operation from Keychain");
115 CKKSResultOperation* manateeProcessOp = [self.manateeView resultsOfNextProcessIncomingQueueOperation];
116 XCTAssertNotNil(manateeProcessOp, "Should have gotten a promise operation from Manatee");
118 // But if something goes wrong, don't block the whole test. Only way to do that is to make more operations, since there's no guarantee that the process ops above will ever be added
119 // to a queue (and thus become 'finished')
120 CKKSResultOperation* keychainProcessTimeoutOp = [CKKSResultOperation named:@"keychain-timeout" withBlock:^{}];
121 [keychainProcessTimeoutOp timeout:20*NSEC_PER_SEC];
122 [keychainProcessTimeoutOp addSuccessDependency:keychainProcessOp];
123 [self.operationQueue addOperation:keychainProcessTimeoutOp];
125 CKKSResultOperation* manateeProcessTimeoutOp = [CKKSResultOperation named:@"manatee-timeout" withBlock:^{}];
126 [manateeProcessTimeoutOp timeout:20*NSEC_PER_SEC];
127 [manateeProcessTimeoutOp addSuccessDependency:manateeProcessOp];
128 [self.operationQueue addOperation:manateeProcessTimeoutOp];
130 APSIncomingMessage* apsMessage = [CKKSAPSReceiverTests messageForZoneID:self.keychainZoneID];
131 NSUUID* nsuuid = [NSUUID UUID];
133 [nsuuid getUUIDBytes:(unsigned char*)&uuid];
134 NSData* uuidData = [NSData dataWithBytes:&uuid length:sizeof(uuid)];
136 apsMessage.tracingUUID = uuidData;
137 apsMessage.tracingEnabled = YES;
139 // Inject a message at the APS layer
140 // Because we can only make APS receivers once iCloud tells us the push environment after sign-in, we can't use our normal injection strategy, and fell back on global state.
141 CKKSAPSReceiver* apsReceiver = [CKKSAPSReceiver receiverForEnvironment:self.apsEnvironment
142 namedDelegatePort:SecCKKSAPSNamedPort
143 apsConnectionClass:[FakeAPSConnection class]];
144 XCTAssertNotNil(apsReceiver, "Should have gotten an APS receiver");
146 // Also, CKKS should handle this in one single fetch
147 self.silentFetchesAllowed = false;
148 [self expectCKFetch];
150 // Expect two metric pushes, one from receiving the push and one from after we finish the fetch
151 // AFAICT there's no way to introspect a metric object to ensure we did it right
152 OCMExpect([self.mockContainerExpectations submitEventMetric:[OCMArg any]]);
153 OCMExpect([self.mockContainerExpectations submitEventMetric:[OCMArg any]]);
156 [apsReceiver connection:nil didReceiveIncomingMessage:apsMessage];
158 OCMVerifyAllWithDelay(self.mockContainerExpectations, 16);
160 // Now, wait for both views to run their processing
161 [keychainProcessTimeoutOp waitUntilFinished];
162 XCTAssertNil(keychainProcessTimeoutOp.error, "Shouldn't have been any error processing incoming queue (keychain)");
164 [manateeProcessTimeoutOp waitUntilFinished];
165 XCTAssertNil(manateeProcessTimeoutOp.error, "Shouldn't have been any error processing incoming queue (manatee)");
167 [self findGenericPassword:@"keychain-view" expecting:errSecSuccess];
168 [self findGenericPassword:@"manatee-view" expecting:errSecSuccess];
171 - (void)testDoNotSendPushMetricWithoutRequest {
172 for(CKRecordZoneID* zoneID in self.ckksZones) {
173 [self putFakeKeyHierarchyInCloudKit:zoneID];
174 [self saveTLKMaterialToKeychain:zoneID];
175 [self expectCKKSTLKSelfShareUpload:zoneID];
178 [self startCKKSSubsystem];
180 for(CKKSKeychainView* view in self.ckksViews) {
181 XCTAssertEqual(0, [view.keyHierarchyConditions[SecCKKSZoneKeyStateReady] wait:20*NSEC_PER_SEC], "Key state should enter 'ready' for view %@", view);
184 OCMVerifyAllWithDelay(self.mockDatabase, 20);
186 CKRecord* keychainRecord = [self createFakeRecord:self.keychainZoneID recordName:@"7B598D31-F9C5-481E-98AC-5A507ACB2D85" withAccount:@"keychain-view"];
187 [self.keychainZone addToZone: keychainRecord];
189 // Trigger a notification just for keychain zone. Both keychain and Manatee should process their incoming queues, and receive their items.
190 CKKSResultOperation* keychainProcessOp = [self.keychainView resultsOfNextProcessIncomingQueueOperation];
191 XCTAssertNotNil(keychainProcessOp, "Should have gotten a promise operation from Keychain");
193 // But if something goes wrong, don't block the whole test. Only way to do that is to make more operations, since there's no guarantee that the process ops above will ever be added
194 // to a queue (and thus become 'finished')
195 CKKSResultOperation* keychainProcessTimeoutOp = [CKKSResultOperation named:@"keychain-timeout" withBlock:^{}];
196 [keychainProcessTimeoutOp timeout:20*NSEC_PER_SEC];
197 [keychainProcessTimeoutOp addSuccessDependency:keychainProcessOp];
198 [self.operationQueue addOperation:keychainProcessTimeoutOp];
200 APSIncomingMessage* apsMessage = [CKKSAPSReceiverTests messageForZoneID:self.keychainZoneID];
201 NSUUID* nsuuid = [NSUUID UUID];
203 [nsuuid getUUIDBytes:(unsigned char*)&uuid];
204 NSData* uuidData = [NSData dataWithBytes:&uuid length:sizeof(uuid)];
206 apsMessage.tracingUUID = uuidData;
207 apsMessage.tracingEnabled = NO;
209 // Inject a message at the APS layer
210 // Because we can only make APS receivers once iCloud tells us the push environment after sign-in, we can't use our normal injection strategy, and fell back on global state.
211 CKKSAPSReceiver* apsReceiver = [CKKSAPSReceiver receiverForEnvironment:self.apsEnvironment
212 namedDelegatePort:SecCKKSAPSNamedPort
213 apsConnectionClass:[FakeAPSConnection class]];
214 XCTAssertNotNil(apsReceiver, "Should have gotten an APS receiver");
216 // Also, CKKS should handle this in one single fetch
217 self.silentFetchesAllowed = false;
218 [self expectCKFetch];
220 // Any metric push is verboten
221 OCMReject([self.mockContainerExpectations submitEventMetric:[OCMArg any]]);
224 [apsReceiver connection:nil didReceiveIncomingMessage:apsMessage];
225 OCMVerifyAllWithDelay(self.mockContainerExpectations, 16);
227 // Now, wait for both views to run their processing
228 [keychainProcessTimeoutOp waitUntilFinished];
229 XCTAssertNil(keychainProcessTimeoutOp.error, "Shouldn't have been any error processing incoming queue (keychain)");
231 [self findGenericPassword:@"keychain-view" expecting:errSecSuccess];