]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/tests/CKKSLoggerTests.m
Security-58286.70.7.tar.gz
[apple/security.git] / keychain / ckks / tests / CKKSLoggerTests.m
1 /*
2 * Copyright (c) 2017 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #if OCTAGON
25
26 #import "CKKSTests.h"
27 #import "keychain/ckks/CKKSAnalytics.h"
28 #import <Security/SFSQLite.h>
29 #import <Foundation/Foundation.h>
30 #import <CloudKit/CloudKit.h>
31 #import <CloudKit/CloudKit_Private.h>
32 #import <XCTest/XCTest.h>
33 #import <OCMock/OCMock.h>
34
35 static NSString* tablePath = nil;
36
37 @interface SQLiteTests : XCTestCase
38 @end
39
40 @implementation SQLiteTests
41
42 + (void)setUp
43 {
44 [super setUp];
45
46 tablePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"test_table.db"];
47 }
48
49 - (void)setUp
50 {
51 [super setUp];
52
53 [[NSFileManager defaultManager] removeItemAtPath:tablePath error:nil];
54 }
55
56 - (void)tearDown
57 {
58 [[NSFileManager defaultManager] removeItemAtPath:tablePath error:nil];
59
60 [super tearDown];
61 }
62
63 - (void)testCreateLoggingDatabase
64 {
65 NSString* schema = @"CREATE table test (test_column INTEGER);";
66 SFSQLite* sqlTable = [[SFSQLite alloc] initWithPath:tablePath schema:schema];
67 NSError* error = nil;
68 XCTAssertTrue([sqlTable openWithError:&error], @"failed to open sql database");
69 XCTAssertNil(error, "encountered error opening database: %@", error);
70 XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:tablePath]);
71 [sqlTable close];
72 }
73
74 - (void)testInsertAndDelete
75 {
76 NSString* schema = @"CREATE table test (test_column INTEGER);";
77 SFSQLite* sqlTable = [[SFSQLite alloc] initWithPath:tablePath schema:schema];
78 NSError* error = nil;
79 XCTAssertTrue([sqlTable openWithError:&error], @"failed to open sql database");
80 XCTAssertNil(error, "encountered error opening database: %@", error);
81
82 [sqlTable insertOrReplaceInto:@"test" values:@{@"test_column" : @(1)}];
83 [sqlTable insertOrReplaceInto:@"test" values:@{@"test_column" : @(2)}];
84 [sqlTable insertOrReplaceInto:@"test" values:@{@"test_column" : @(3)}];
85 XCTAssertTrue([[sqlTable selectAllFrom:@"test" where:nil bindings:nil] count] == 3);
86
87 [sqlTable deleteFrom:@"test" where:@"test_column = ?" bindings:@[@3]];
88 XCTAssertTrue([[sqlTable selectAllFrom:@"test" where:nil bindings:nil] count] == 2);
89
90 [sqlTable executeSQL:@"delete from test"];
91 XCTAssertTrue([[sqlTable selectAllFrom:@"test" where:nil bindings:nil] count] == 0);
92 }
93
94 - (void)testDontCrashWhenThereAreNoWritePermissions
95 {
96 NSString* schema = @"CREATE table test (test_column INTEGER);";
97 SFSQLite* sqlTable = [[SFSQLite alloc] initWithPath:tablePath schema:schema];
98
99 NSError* error = nil;
100 XCTAssertNoThrow([sqlTable openWithError:&error], @"opening database threw an exception");
101 XCTAssertNil(error, "encountered error opening database: %@", error);
102 XCTAssertNoThrow([sqlTable close], @"closing database threw an exception");
103
104 NSDictionary* originalAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:tablePath error:&error];
105 XCTAssertNil(error, @"encountered error getting database file attributes: %@", error);
106
107 [[NSFileManager defaultManager] setAttributes:@{NSFilePosixPermissions : @(400), NSFileImmutable : @(YES)} ofItemAtPath:tablePath error:&error];
108 XCTAssertNil(error, @"encountered error setting database file attributes: %@", error);
109 XCTAssertNoThrow([sqlTable openWithError:&error]);
110 XCTAssertNotNil(error, @"failed to generate error when opening file without permissions");
111 error = nil;
112
113 [[NSFileManager defaultManager] setAttributes:originalAttributes ofItemAtPath:tablePath error:&error];
114 XCTAssertNil(error, @"encountered error setting database file attributes back to original attributes: %@", error);
115 }
116
117 - (void)testDontCrashFromInternalErrors
118 {
119 NSString* schema = @"CREATE table test (test_column INTEGER);";
120 SFSQLite* sqlTable = [[SFSQLite alloc] initWithPath:tablePath schema:schema];
121
122 NSError* error = nil;
123 XCTAssertTrue([sqlTable openWithError:&error], @"failed to open database");
124 XCTAssertNil(error, "encountered error opening database: %@", error);
125
126 // delete the table to create havoc
127 XCTAssertTrue([sqlTable executeSQL:@"drop table test;"], @"deleting test table should have worked");
128
129 XCTAssertNoThrow([sqlTable insertOrReplaceInto:@"test" values:@{@"test_column" : @(1)}], @"inserting into deleted table threw an exception");
130 }
131
132 @end
133
134 @interface CKKSAnalyticsTests : CloudKitKeychainSyncingTestsBase
135 @property id mockCKKSAnalytics;
136 @end
137
138 @implementation CKKSAnalyticsTests
139
140 - (void)setUp
141 {
142 self.mockCKKSAnalytics = OCMClassMock([CKKSAnalytics class]);
143 OCMStub([self.mockCKKSAnalytics databasePath]).andCall(self, @selector(databasePath));
144 [super setUp];
145 }
146
147 - (void)tearDown
148 {
149 [self.mockCKKSAnalytics stopMocking];
150 self.mockCKKSAnalytics = nil;
151 [super tearDown];
152 }
153
154 - (NSString*)databasePath
155 {
156 return [NSTemporaryDirectory() stringByAppendingPathComponent:@"test_ckks_analytics_v2.db"];
157 }
158
159 - (void)testLastSuccessfulXDate
160 {
161 [self createAndSaveFakeKeyHierarchy: self.keychainZoneID]; // Make life easy for this test.
162 [self startCKKSSubsystem];
163 CKRecord* ckr = [self createFakeRecord: self.keychainZoneID recordName:@"7B598D31-F9C5-481E-98AC-5A507ACB2D85"];
164 [self.keychainZone addToZone: ckr];
165
166 // Trigger a notification (with hilariously fake data)
167 [self.keychainView notifyZoneChange:nil];
168
169 [[[self.keychainView waitForFetchAndIncomingQueueProcessing] completionHandlerDidRunCondition] wait:4 * NSEC_PER_SEC];
170
171 NSDate* nowDate = [NSDate date];
172 NSTimeInterval timeInterval;
173
174 /*
175 * Check last sync date for class A
176 */
177 NSDate* syncADate = [[CKKSAnalytics logger] dateOfLastSuccessForEvent:CKKSEventProcessIncomingQueueClassA inView:self.keychainView];
178 XCTAssertNotNil(syncADate, "Failed to get a last successful A sync date");
179 timeInterval = [nowDate timeIntervalSinceDate:syncADate];
180 XCTAssertTrue(timeInterval >= 0.0 && timeInterval <= 15.0, "Last sync date does not look like a reasonable one");
181
182 /*
183 * Check last sync date for class C
184 */
185 NSDate *syncCDate = [[CKKSAnalytics logger] dateOfLastSuccessForEvent:CKKSEventProcessIncomingQueueClassC inView:self.keychainView];
186 XCTAssertNotNil(syncCDate, "Failed to get a last successful C sync date");
187 timeInterval = [nowDate timeIntervalSinceDate:syncCDate];
188 XCTAssertTrue(timeInterval >= 0.0 && timeInterval <= 15.0, "Last sync date does not look like a reasonable one");
189
190 /*
191 * Check last unlock date
192 */
193 NSDate* unlockDate = [[CKKSAnalytics logger] datePropertyForKey:CKKSAnalyticsLastUnlock];
194 XCTAssertNotNil(unlockDate, "Failed to get a last unlock date");
195 timeInterval = [nowDate timeIntervalSinceDate:unlockDate];
196 NSLog(@"timeinterval: %f\n", timeInterval);
197 XCTAssertTrue(timeInterval >= 0.0 && timeInterval <= 15.0, "Last unlock date does not look like a reasonable one");
198
199 sleep(1); // wait to be a differnt second
200
201 self.aksLockState = true;
202 [self.lockStateTracker recheck];
203
204 NSDate* newUnlockDate = [[CKKSAnalytics logger] datePropertyForKey:CKKSAnalyticsLastUnlock];
205 XCTAssertNotNil(newUnlockDate, "Failed to get a last unlock date");
206 XCTAssertEqualObjects(newUnlockDate, unlockDate, "unlock date not the same");
207
208 sleep(1); // wait to be a differnt second
209
210 self.aksLockState = false;
211 [self.lockStateTracker recheck];
212
213 sleep(1); // wait for the completion block to have time to fire
214
215 newUnlockDate = [[CKKSAnalytics logger] datePropertyForKey:CKKSAnalyticsLastUnlock];
216 XCTAssertNotNil(newUnlockDate, "Failed to get a last unlock date");
217 XCTAssertNotEqualObjects(newUnlockDate, unlockDate, "unlock date the same");
218 }
219
220 - (void)testRaceToCreateLoggers
221 {
222 dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
223 for (NSInteger i = 0; i < 5; i++) {
224 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
225 CKKSAnalytics* logger = [CKKSAnalytics logger];
226 [logger logSuccessForEvent:(CKKSAnalyticsFailableEvent*)@"test_event" inView:self.keychainView];
227 dispatch_semaphore_signal(semaphore);
228 });
229 }
230
231 for (NSInteger i = 0; i < 5; i++) {
232 dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
233 }
234 }
235
236 - (void)testUnderlayingError
237 {
238 NSDictionary *errorString = nil;
239 NSError *error = nil;
240
241 error = [NSError errorWithDomain:CKErrorDomain code:CKErrorPartialFailure userInfo:@{
242 CKPartialErrorsByItemIDKey : @{
243 @"recordid" : [NSError errorWithDomain:CKErrorDomain code:1 userInfo:nil],
244 }
245 }];
246
247 errorString = [[CKKSAnalytics logger] errorChain:error depth:0];
248
249 XCTAssertEqualObjects(errorString[@"domain"], CKErrorDomain, "error domain");
250 XCTAssertEqual([errorString[@"code"] intValue], CKErrorPartialFailure, "error code");
251
252 XCTAssertEqualObjects(errorString[@"oneCloudKitPartialFailure"][@"domain"], CKErrorDomain, "error domain");
253 XCTAssertEqual([errorString[@"oneCloudKitPartialFailure"][@"code"] intValue], 1, "error code");
254
255 /* interal partial error leaks out of CK */
256
257 error = [NSError errorWithDomain:CKErrorDomain code:CKErrorPartialFailure userInfo:@{
258 CKPartialErrorsByItemIDKey : @{
259 @"recordid1" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
260 @"recordid2" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
261 @"recordid3" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
262 @"recordid4" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
263 @"recordid5" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
264 @"recordid6" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
265 @"recordid7" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
266 @"recordid8" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
267 @"recordid9" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
268 @"recordid0" : [NSError errorWithDomain:CKErrorDomain code:1 userInfo:nil],
269 @"recordid10" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
270 @"recordid12" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
271 @"recordid13" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
272 @"recordid14" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
273 @"recordid15" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
274 @"recordid16" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
275 @"recordid17" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
276 @"recordid18" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
277 @"recordid19" : [NSError errorWithDomain:CKErrorDomain code:CKErrorBatchRequestFailed userInfo:nil],
278 }
279 }];
280
281 errorString = [[CKKSAnalytics logger] errorChain:error depth:0];
282
283 XCTAssertEqualObjects(errorString[@"domain"], CKErrorDomain, "error domain");
284 XCTAssertEqual([errorString[@"code"] intValue], CKErrorPartialFailure, "error code");
285
286 XCTAssertEqualObjects(errorString[@"oneCloudKitPartialFailure"][@"domain"], CKErrorDomain, "error domain");
287 XCTAssertEqualObjects(errorString[@"oneCloudKitPartialFailure"][@"code"], @1, "error code");
288
289
290
291
292 error = [NSError errorWithDomain:@"domain" code:1 userInfo:@{
293 NSUnderlyingErrorKey : [NSError errorWithDomain:CKErrorDomain code:1 userInfo:nil],
294 }];
295
296 errorString = [[CKKSAnalytics logger] errorChain:error depth:0];
297
298 XCTAssertEqualObjects(errorString[@"domain"], @"domain", "error domain");
299 XCTAssertEqual([errorString[@"code"] intValue], 1, "error code");
300
301 XCTAssertEqualObjects(errorString[@"child"][@"domain"], CKErrorDomain, "error domain");
302 XCTAssertEqual([errorString[@"child"][@"code"] intValue], 1, "error code");
303 }
304
305
306 @end
307
308 #endif