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/OctagonAPSReceiver.h"
37 #import "keychain/ckks/CKKSKey.h"
38 #import "keychain/ckks/CKKSPeer.h"
39 #import "keychain/ckks/CKKSTLKShareRecord.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/OctagonAPSReceiverTests.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] findOrCreateView:@"Manatee"];
74 XCTAssertNotNil(self.manateeView, "CKKSViewManager created the Manatee view");
75 [self.ckksViews addObject:self.manateeView];
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 + (APSIncomingMessage*)messageWithTracingEnabledForZoneID:(CKRecordZoneID*)zoneID {
91 APSIncomingMessage* apsMessage = [OctagonAPSReceiverTests messageForZoneID:zoneID];
92 NSUUID* nsuuid = [NSUUID UUID];
94 [nsuuid getUUIDBytes:(unsigned char*)&uuid];
95 NSData* uuidData = [NSData dataWithBytes:&uuid length:sizeof(uuid)];
97 apsMessage.tracingUUID = uuidData;
98 apsMessage.tracingEnabled = YES;
103 - (void)testSendPushMetricUponRequest {
104 for(CKRecordZoneID* zoneID in self.ckksZones) {
105 [self putFakeKeyHierarchyInCloudKit:zoneID];
106 [self saveTLKMaterialToKeychain:zoneID];
107 [self expectCKKSTLKSelfShareUpload:zoneID];
110 [self startCKKSSubsystem];
112 for(CKKSKeychainView* view in self.ckksViews) {
113 XCTAssertEqual(0, [view.keyHierarchyConditions[SecCKKSZoneKeyStateReady] wait:20*NSEC_PER_SEC], "Key state should enter 'ready' for view %@", view);
116 OCMVerifyAllWithDelay(self.mockDatabase, 20);
118 CKRecord* keychainRecord = [self createFakeRecord:self.keychainZoneID recordName:@"7B598D31-F9C5-481E-98AC-5A507ACB2D85" withAccount:@"keychain-view"];
119 [self.keychainZone addToZone: keychainRecord];
121 // Manatee gets one too!
122 CKRecord* manateeRecord = [self createFakeRecord:self.manateeZoneID recordName:@"7B598D31-F9C5-481E-98AC-000000000000" withAccount:@"manatee-view"];
123 [self.manateeZone addToZone:manateeRecord];
125 // Trigger a notification just for keychain zone. Both keychain and Manatee should process their incoming queues, and receive their items.
126 CKKSResultOperation* keychainProcessOp = [self.keychainView resultsOfNextProcessIncomingQueueOperation];
127 XCTAssertNotNil(keychainProcessOp, "Should have gotten a promise operation from Keychain");
128 CKKSResultOperation* manateeProcessOp = [self.manateeView resultsOfNextProcessIncomingQueueOperation];
129 XCTAssertNotNil(manateeProcessOp, "Should have gotten a promise operation from Manatee");
131 // 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
132 // to a queue (and thus become 'finished')
133 CKKSResultOperation* keychainProcessTimeoutOp = [CKKSResultOperation named:@"keychain-timeout" withBlock:^{}];
134 [keychainProcessTimeoutOp timeout:20*NSEC_PER_SEC];
135 [keychainProcessTimeoutOp addSuccessDependency:keychainProcessOp];
136 [self.operationQueue addOperation:keychainProcessTimeoutOp];
138 CKKSResultOperation* manateeProcessTimeoutOp = [CKKSResultOperation named:@"manatee-timeout" withBlock:^{}];
139 [manateeProcessTimeoutOp timeout:20*NSEC_PER_SEC];
140 [manateeProcessTimeoutOp addSuccessDependency:manateeProcessOp];
141 [self.operationQueue addOperation:manateeProcessTimeoutOp];
143 APSIncomingMessage* apsMessage = [CKKSAPSHandlingTests messageWithTracingEnabledForZoneID:self.keychainZoneID];
145 // Inject a message at the APS layer
146 // 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.
147 OctagonAPSReceiver* apsReceiver = [OctagonAPSReceiver receiverForEnvironment:self.apsEnvironment
148 namedDelegatePort:SecCKKSAPSNamedPort
149 apsConnectionClass:[FakeAPSConnection class]];
150 XCTAssertNotNil(apsReceiver, "Should have gotten an APS receiver");
152 // Also, CKKS should handle this in one single fetch
153 self.silentFetchesAllowed = false;
154 [self expectCKFetch];
156 // Expect two metric pushes, one from receiving the push and one from after we finish the fetch
157 // AFAICT there's no way to introspect a metric object to ensure we did it right
158 OCMExpect([self.mockContainerExpectations submitEventMetric:[OCMArg any]]);
159 OCMExpect([self.mockContainerExpectations submitEventMetric:[OCMArg any]]);
162 [apsReceiver connection:nil didReceiveIncomingMessage:apsMessage];
164 OCMVerifyAllWithDelay(self.mockContainerExpectations, 16);
166 // Now, wait for both views to run their processing
167 [keychainProcessTimeoutOp waitUntilFinished];
168 XCTAssertNil(keychainProcessTimeoutOp.error, "Shouldn't have been any error processing incoming queue (keychain)");
170 [manateeProcessTimeoutOp waitUntilFinished];
171 XCTAssertNil(manateeProcessTimeoutOp.error, "Shouldn't have been any error processing incoming queue (manatee)");
173 [self findGenericPassword:@"keychain-view" expecting:errSecSuccess];
174 [self findGenericPassword:@"manatee-view" expecting:errSecSuccess];
177 - (void)testDoNotSendPushMetricWithoutRequest {
178 for(CKRecordZoneID* zoneID in self.ckksZones) {
179 [self putFakeKeyHierarchyInCloudKit:zoneID];
180 [self saveTLKMaterialToKeychain:zoneID];
181 [self expectCKKSTLKSelfShareUpload:zoneID];
184 [self startCKKSSubsystem];
186 for(CKKSKeychainView* view in self.ckksViews) {
187 XCTAssertEqual(0, [view.keyHierarchyConditions[SecCKKSZoneKeyStateReady] wait:20*NSEC_PER_SEC], "Key state should enter 'ready' for view %@", view);
190 OCMVerifyAllWithDelay(self.mockDatabase, 20);
192 CKRecord* keychainRecord = [self createFakeRecord:self.keychainZoneID recordName:@"7B598D31-F9C5-481E-98AC-5A507ACB2D85" withAccount:@"keychain-view"];
193 [self.keychainZone addToZone: keychainRecord];
195 // Trigger a notification just for keychain zone. Both keychain and Manatee should process their incoming queues, and receive their items.
196 CKKSResultOperation* keychainProcessOp = [self.keychainView resultsOfNextProcessIncomingQueueOperation];
197 XCTAssertNotNil(keychainProcessOp, "Should have gotten a promise operation from Keychain");
199 // 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
200 // to a queue (and thus become 'finished')
201 CKKSResultOperation* keychainProcessTimeoutOp = [CKKSResultOperation named:@"keychain-timeout" withBlock:^{}];
202 [keychainProcessTimeoutOp timeout:20*NSEC_PER_SEC];
203 [keychainProcessTimeoutOp addSuccessDependency:keychainProcessOp];
204 [self.operationQueue addOperation:keychainProcessTimeoutOp];
206 // Create a push that matchs all push tracing patterns except for the enabled flag
207 APSIncomingMessage* apsMessage = [CKKSAPSHandlingTests messageWithTracingEnabledForZoneID:self.keychainZoneID];
208 apsMessage.tracingEnabled = NO;
210 // Inject a message at the APS layer
211 // 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.
212 OctagonAPSReceiver* apsReceiver = [OctagonAPSReceiver receiverForEnvironment:self.apsEnvironment
213 namedDelegatePort:SecCKKSAPSNamedPort
214 apsConnectionClass:[FakeAPSConnection class]];
215 XCTAssertNotNil(apsReceiver, "Should have gotten an APS receiver");
217 // Also, CKKS should handle this in one single fetch
218 self.silentFetchesAllowed = false;
219 [self expectCKFetch];
221 // Any metric push is verboten
222 OCMReject([self.mockContainerExpectations submitEventMetric:[OCMArg any]]);
225 [apsReceiver connection:nil didReceiveIncomingMessage:apsMessage];
226 OCMVerifyAllWithDelay(self.mockContainerExpectations, 16);
228 // Now, wait for both views to run their processing
229 [keychainProcessTimeoutOp waitUntilFinished];
230 XCTAssertNil(keychainProcessTimeoutOp.error, "Shouldn't have been any error processing incoming queue (keychain)");
232 [self findGenericPassword:@"keychain-view" expecting:errSecSuccess];
235 - (void)testSendPushMetricEvenIfPushArrivesEarly {
236 CKRecordZoneID* pushTestZone = [[CKRecordZoneID alloc] initWithZoneName:@"PushTestZone" ownerName:CKCurrentUserDefaultName];
237 [self.ckksZones addObject:pushTestZone];
238 self.zones[pushTestZone] = [[FakeCKZone alloc] initZone: pushTestZone];
240 NSMutableSet* viewList = [self.mockSOSAdapter.selfPeer.viewList mutableCopy];
241 [viewList addObject:@"PushTestZone"];
242 CKKSSOSSelfPeer* newSelfPeer = [[CKKSSOSSelfPeer alloc] initWithSOSPeerID:self.mockSOSAdapter.selfPeer.peerID
243 encryptionKey:self.mockSOSAdapter.selfPeer.encryptionKey
244 signingKey:self.mockSOSAdapter.selfPeer.signingKey
246 self.mockSOSAdapter.selfPeer = newSelfPeer;
248 for(CKRecordZoneID* zoneID in self.ckksZones) {
249 [self putFakeKeyHierarchyInCloudKit:zoneID];
250 [self saveTLKMaterialToKeychain:zoneID];
251 [self expectCKKSTLKSelfShareUpload:zoneID];
254 // The push wakes securityd, so it happens before pushTestZone is created locally
255 // Send 2, just to test our infrastructure
256 APSIncomingMessage* apsMessage = [CKKSAPSHandlingTests messageWithTracingEnabledForZoneID:pushTestZone];
257 APSIncomingMessage* apsMessage2 = [CKKSAPSHandlingTests messageWithTracingEnabledForZoneID:pushTestZone];
259 // Inject a message at the APS layer
260 // 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.
261 OctagonAPSReceiver* apsReceiver = [OctagonAPSReceiver receiverForEnvironment:self.apsEnvironment
262 namedDelegatePort:SecCKKSAPSNamedPort
263 apsConnectionClass:[FakeAPSConnection class]];
264 XCTAssertNotNil(apsReceiver, "Should have gotten an APS receiver");
266 [apsReceiver connection:nil didReceiveIncomingMessage:apsMessage];
267 [apsReceiver connection:nil didReceiveIncomingMessage:apsMessage2];
269 // Expect four metric pushes, two per push: one from receiving the push and one from after we finish the fetch
270 // AFAICT there's no way to introspect a metric object to ensure we did it right
271 OCMExpect([self.mockContainerExpectations submitEventMetric:[OCMArg any]]);
272 OCMExpect([self.mockContainerExpectations submitEventMetric:[OCMArg any]]);
273 OCMExpect([self.mockContainerExpectations submitEventMetric:[OCMArg any]]);
274 OCMExpect([self.mockContainerExpectations submitEventMetric:[OCMArg any]]);
277 CKKSKeychainView* pushTestView = [self.injectedManager findOrCreateView:pushTestZone.zoneName];
278 [self.ckksViews addObject:pushTestView];
280 [self startCKKSSubsystem];
282 for(CKKSKeychainView* view in self.ckksViews) {
283 XCTAssertEqual(0, [view.keyHierarchyConditions[SecCKKSZoneKeyStateReady] wait:20*NSEC_PER_SEC], "Key state should enter 'ready' for view %@", view);
285 OCMVerifyAllWithDelay(self.mockDatabase, 20);
288 - (void)testDropStalePushes {
289 CKRecordZoneID* pushTestZone = [[CKRecordZoneID alloc] initWithZoneName:@"PushTestZone" ownerName:CKCurrentUserDefaultName];
291 APSIncomingMessage* apsMessage = [CKKSAPSHandlingTests messageWithTracingEnabledForZoneID:pushTestZone];
293 // Don't use the global map here, because we need to ensure we create a new object (to use the stalePushTimeout we injected above)
294 OctagonAPSReceiver* apsReceiver = OCMPartialMock([[OctagonAPSReceiver alloc] initWithEnvironmentName:self.apsEnvironment
295 namedDelegatePort:SecCKKSAPSNamedPort
296 apsConnectionClass:[FakeAPSConnection class]
297 stalePushTimeout:4 * NSEC_PER_SEC]);
298 XCTAssertNotNil(apsReceiver, "Should have gotten an APS receiver");
300 OCMExpect([apsReceiver reportDroppedPushes:[OCMArg any]]);
301 [apsReceiver connection:nil didReceiveIncomingMessage:apsMessage];
303 XCTAssertEqual(apsReceiver.haveStalePushes, YES, "should have stale pushes");
304 OCMVerifyAllWithDelay((id)apsReceiver, 20);
305 XCTAssertEqual(apsReceiver.haveStalePushes, NO, "should no longer have stale pushes");