]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/tests/CKKSSQLTests.m
Security-58286.20.16.tar.gz
[apple/security.git] / keychain / ckks / tests / CKKSSQLTests.m
1 /*
2 * Copyright (c) 2016 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 <XCTest/XCTest.h>
27 #import "CloudKitMockXCTest.h"
28
29 #import "keychain/ckks/CKKS.h"
30 #import "keychain/ckks/CKKSKey.h"
31 #import "keychain/ckks/CKKSOutgoingQueueEntry.h"
32 #import "keychain/ckks/CKKSZoneStateEntry.h"
33 #import "keychain/ckks/CKKSDeviceStateEntry.h"
34 #import "keychain/ckks/CKKSRateLimiter.h"
35
36 #include <securityd/SecItemServer.h>
37
38 @interface CloudKitKeychainSQLTests : CloudKitMockXCTest
39 @end
40
41 @implementation CloudKitKeychainSQLTests
42
43 + (void)setUp {
44 [super setUp];
45 }
46
47 - (void)setUp {
48 SecCKKSDisable();
49 [super setUp];
50 }
51
52 - (void)tearDown {
53 [super tearDown];
54 SecCKKSResetSyncing();
55 }
56
57 - (void)addTestZoneEntries {
58 CKKSOutgoingQueueEntry* one = [[CKKSOutgoingQueueEntry alloc] initWithCKKSItem:
59 [[CKKSItem alloc] initWithUUID:[[NSUUID UUID] UUIDString]
60 parentKeyUUID:[[NSUUID UUID] UUIDString]
61 zoneID:self.testZoneID
62 encItem:[@"nonsense" dataUsingEncoding:NSUTF8StringEncoding]
63 wrappedkey:[[CKKSWrappedAESSIVKey alloc]initWithBase64: @"KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI="]
64 generationCount:0
65 encver:0]
66 action:SecCKKSActionAdd
67 state:SecCKKSStateError
68 waitUntil:nil
69 accessGroup:@"nope"];
70
71
72 CKKSOutgoingQueueEntry* two = [[CKKSOutgoingQueueEntry alloc] initWithCKKSItem:
73 [[CKKSItem alloc] initWithUUID:[[NSUUID UUID] UUIDString]
74 parentKeyUUID:[[NSUUID UUID] UUIDString]
75 zoneID:self.testZoneID
76 encItem:[@"nonsense" dataUsingEncoding:NSUTF8StringEncoding]
77 wrappedkey:[[CKKSWrappedAESSIVKey alloc]initWithBase64: @"KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI="]
78 generationCount:0
79 encver:0]
80 action:SecCKKSActionAdd
81 state:SecCKKSStateNew
82 waitUntil:nil
83 accessGroup:@"nope"];
84
85 CKKSOutgoingQueueEntry* three = [[CKKSOutgoingQueueEntry alloc] initWithCKKSItem:
86 [[CKKSItem alloc] initWithUUID:[[NSUUID UUID] UUIDString]
87 parentKeyUUID:[[NSUUID UUID] UUIDString]
88 zoneID:self.testZoneID
89 encItem:[@"nonsense" dataUsingEncoding:NSUTF8StringEncoding]
90 wrappedkey:[[CKKSWrappedAESSIVKey alloc]initWithBase64: @"KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI="]
91 generationCount:0
92 encver:0]
93 action:SecCKKSActionModify
94 state:SecCKKSStateError
95 waitUntil:nil
96 accessGroup:@"nope"];
97
98 NSError* error = nil;
99 [one saveToDatabase:&error];
100 [two saveToDatabase: &error];
101 [three saveToDatabase: &error];
102 XCTAssertNil(error, "no error saving ZoneStateEntries to database");
103 }
104
105 - (void)testCKKSOutgoingQueueEntry {
106 NSString* testUUID = @"157A3171-0677-451B-9EAE-0DDC4D4315B0";
107 NSUUID* testKeyUUID = [[NSUUID alloc] init];
108
109 NSError * nserror;
110 __block CFErrorRef error = NULL;
111
112 CKKSOutgoingQueueEntry* shouldFail = [CKKSOutgoingQueueEntry fromDatabase:testUUID state:SecCKKSStateInFlight zoneID:self.testZoneID error: &nserror];
113 XCTAssertNil(shouldFail, "Can't find a nonexisting object");
114 XCTAssertNotNil(nserror, "NSError exists when things break");
115
116 __weak __typeof(self) weakSelf = self;
117 kc_with_dbt(true, &error, ^bool (SecDbConnectionRef dbconn) {
118 __strong __typeof(weakSelf) strongSelf = weakSelf;
119 XCTAssertNotNil(strongSelf, "called while self still exists");
120
121 NSString * sql = @"insert INTO outgoingqueue (UUID, parentKeyUUID, ckzone, action, state, accessgroup, gencount, encitem, wrappedkey, encver) VALUES (?,?,?,?,?,?,?,?,?,?);";
122 SecDbPrepare(dbconn, (__bridge CFStringRef) sql, &error, ^void (sqlite3_stmt *stmt) {
123 SecDbBindText(stmt, 1, [testUUID UTF8String], strlen([testUUID UTF8String]), NULL, &error);
124 SecDbBindText(stmt, 2, [[testKeyUUID UUIDString] UTF8String], strlen([[testKeyUUID UUIDString] UTF8String]), NULL, &error);
125 SecDbBindObject(stmt, 3, (__bridge CFStringRef) weakSelf.testZoneID.zoneName, &error);
126 SecDbBindText(stmt, 4, "newitem", strlen("newitem"), NULL, &error);
127 SecDbBindText(stmt, 5, "unprocessed", strlen("unprocessed"), NULL, &error);
128 SecDbBindText(stmt, 6, "com.apple.access", strlen("com.apple.access"), NULL, &error);
129 SecDbBindText(stmt, 7, "0", strlen("0"), NULL, &error);
130 SecDbBindText(stmt, 8, "bm9uc2Vuc2UK", strlen("bm9uc2Vuc2UK"), NULL, &error);
131 SecDbBindObject(stmt, 9, CFSTR("KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI="), &error);
132 SecDbBindText(stmt, 10, "0", strlen("0"), NULL, &error);
133
134 SecDbStep(dbconn, stmt, &error, ^(bool *stop) {
135 // don't do anything, I guess?
136 });
137
138 XCTAssertNil((__bridge NSError*)error, @"no error occurred while adding row to database");
139
140 CFReleaseNull(error);
141 });
142 XCTAssertNil((__bridge NSError*)error, @"no error occurred preparing sql");
143
144 CFReleaseNull(error);
145 return true;
146 });
147
148 // Create another oqe with different values
149 CKKSItem* baseitem = [[CKKSItem alloc] initWithUUID: [[NSUUID UUID] UUIDString]
150 parentKeyUUID:[[NSUUID UUID] UUIDString]
151 zoneID:self.testZoneID
152 encItem:[@"nonsense" dataUsingEncoding:NSUTF8StringEncoding]
153 wrappedkey:[[CKKSWrappedAESSIVKey alloc]initWithBase64: @"KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI="]
154 generationCount:0
155 encver:0];
156 CKKSOutgoingQueueEntry* other = [[CKKSOutgoingQueueEntry alloc] initWithCKKSItem:baseitem
157 action:SecCKKSActionAdd
158 state:SecCKKSStateError
159 waitUntil:[NSDate date]
160 accessGroup:@"nope"];
161 [other saveToDatabase:&nserror];
162 XCTAssertNil(nserror, "no error occurred saving to database");
163
164 CKKSOutgoingQueueEntry * oqe = [CKKSOutgoingQueueEntry fromDatabase:testUUID state:@"unprocessed" zoneID:self.testZoneID error: &nserror];
165 XCTAssertNil(nserror, "no error occurred creating from database");
166
167 XCTAssertNotNil(oqe, "load outgoing queue entry from database");
168 XCTAssertEqualObjects(oqe.state, @"unprocessed", "state matches what was in the DB");
169
170 oqe.item.parentKeyUUID = @"not a parent key either";
171 oqe.action = @"null";
172 oqe.state = @"savedtocloud";
173 oqe.accessgroup = @"com.evil.access";
174 oqe.item.generationCount = (NSInteger) 1;
175 oqe.item.base64encitem = @"bW9yZW5vbnNlbnNlCg==";
176 oqe.item.encver = 1;
177
178 XCTAssertTrue([oqe saveToDatabase: &nserror], "saving to database");
179
180 CKKSOutgoingQueueEntry * oqe2 = [CKKSOutgoingQueueEntry fromDatabase:testUUID state:@"savedtocloud" zoneID:self.testZoneID error: &nserror];
181 XCTAssertNil(nserror, "no error occurred");
182
183 XCTAssertEqualObjects(oqe2.item.parentKeyUUID, @"not a parent key either", @"parent key uuid persisted through db save and load");
184 XCTAssertEqualObjects(oqe2.item.zoneID , self.testZoneID , @"zone id persisted through db save and load");
185 XCTAssertEqualObjects(oqe2.action , @"null" , @"action persisted through db save and load");
186 XCTAssertEqualObjects(oqe2.state , @"savedtocloud" , @"state persisted through db save and load");
187 XCTAssertEqual( oqe2.waitUntil , nil , @"no date when none given");
188 XCTAssertEqualObjects(oqe2.accessgroup , @"com.evil.access" , @"accessgroup persisted through db save and load");
189 XCTAssertEqual( oqe2.item.generationCount, (NSUInteger) 1 , @"generationCount persisted through db save and load");
190 XCTAssertEqualObjects(oqe2.item.base64encitem, @"bW9yZW5vbnNlbnNlCg==" , @"encitem persisted through db save and load");
191 XCTAssertEqual( oqe2.item.encver, 1 , @"encver persisted through db save and load");
192 XCTAssertEqualObjects([oqe2.item.wrappedkey base64WrappedKey], @"KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI=",
193 @"wrapped key persisted through db save and load");
194
195 // Test 'all' methods
196 NSArray<CKKSOutgoingQueueEntry*>* oqes = [CKKSOutgoingQueueEntry all:&nserror];
197 XCTAssertNil(nserror, "no error occurred");
198 XCTAssertNotNil(oqes, "receive oqes from database");
199 XCTAssert([oqes count] == 2, "received 2 oqes from all");
200
201 NSArray<CKKSOutgoingQueueEntry*>* oqeswhere = [CKKSOutgoingQueueEntry allWhere: @{@"state": @"savedtocloud"} error:&nserror];
202 XCTAssertNil(nserror, "no error occurred");
203 XCTAssertNotNil(oqeswhere, "receive oqes from database");
204 XCTAssert([oqeswhere count] == 1, "received 1 oqe from allWhere");
205
206 // Test row deletion
207 nserror = nil;
208 [oqe2 deleteFromDatabase:&nserror];
209 XCTAssertNil(nserror, "No NSError exists when deleting existing item");
210 oqe2 = [CKKSOutgoingQueueEntry fromDatabase:testUUID state:@"savedtocloud" zoneID:self.testZoneID error: &nserror];
211 XCTAssertNil(oqe2, "Can't find a nonexisting object");
212 XCTAssertNotNil(nserror, "NSError exists when things break");
213
214 // Test loading other
215 nserror = nil;
216 CKKSOutgoingQueueEntry* other2 = [CKKSOutgoingQueueEntry fromDatabase: other.item.uuid state:SecCKKSStateError zoneID:self.testZoneID error:&nserror];
217 XCTAssertNil(nserror, "No error loading other2 from database");
218 XCTAssertNotNil(other2, "Able to re-load other.");
219 XCTAssertEqualObjects(other, other2, "loaded object is equal to object");
220 }
221
222 -(void)testCKKSZoneStateEntrySQL {
223 CKKSZoneStateEntry* zse = [[CKKSZoneStateEntry alloc] initWithCKZone: @"sqltest"
224 zoneCreated: true
225 zoneSubscribed: true
226 changeToken: [@"nonsense" dataUsingEncoding:NSUTF8StringEncoding]
227 lastFetch: [NSDate date]
228 encodedRateLimiter:nil];
229 zse.rateLimiter = [[CKKSRateLimiter alloc] init];
230
231 CKKSZoneStateEntry* zseClone = [[CKKSZoneStateEntry alloc] initWithCKZone: @"sqltest"
232 zoneCreated: true
233 zoneSubscribed: true
234 changeToken: [@"nonsense" dataUsingEncoding:NSUTF8StringEncoding]
235 lastFetch: zse.lastFetchTime
236 encodedRateLimiter:zse.encodedRateLimiter];
237
238 CKKSZoneStateEntry* zseDifferent = [[CKKSZoneStateEntry alloc] initWithCKZone: @"sqltest"
239 zoneCreated: true
240 zoneSubscribed: true
241 changeToken: [@"allnonsense" dataUsingEncoding:NSUTF8StringEncoding]
242 lastFetch: zse.lastFetchTime
243 encodedRateLimiter:zse.encodedRateLimiter];
244 XCTAssertEqualObjects(zse, zseClone, "CKKSZoneStateEntry isEqual of equal objects seems sane");
245 XCTAssertNotEqualObjects(zse, zseDifferent, "CKKSZoneStateEntry isEqual of nonequal objects seems sane");
246
247 NSError* error = nil;
248 CKKSZoneStateEntry* loaded = [CKKSZoneStateEntry tryFromDatabase: @"sqltest" error:&error];
249 XCTAssertNil(error, "No error trying to load nonexistent record");
250 XCTAssertNil(loaded, "No record saved in database");
251
252 [zse saveToDatabase: &error];
253 XCTAssertNil(error, "no error saving CKKSZoneStateEntry to database");
254
255 loaded = [CKKSZoneStateEntry tryFromDatabase: @"sqltest" error:&error];
256 XCTAssertNil(error, "No error trying to load saved record");
257 XCTAssertNotNil(loaded, "CKKSZoneStateEntry came back out of database");
258
259 XCTAssertEqualObjects(zse.ckzone, loaded.ckzone, "ckzone persisted through db save and load");
260 XCTAssertEqual (zse.ckzonecreated, loaded.ckzonecreated, "ckzonecreated persisted through db save and load");
261 XCTAssertEqual (zse.ckzonesubscribed, loaded.ckzonesubscribed, "ckzonesubscribed persisted through db save and load");
262 XCTAssertEqualObjects(zse.encodedChangeToken, loaded.encodedChangeToken, "encodedChangeToken persisted through db save and load");
263
264 XCTAssert([[NSCalendar currentCalendar] isDate:zse.lastFetchTime equalToDate: loaded.lastFetchTime toUnitGranularity:NSCalendarUnitSecond],
265 "lastFetchTime persisted through db save and load");
266 }
267
268 -(void)testRoundtripCKKSDeviceStateEntry {
269 // Very simple test: can these objects roundtrip through the db?
270 NSString* testUUID = @"157A3171-0677-451B-9EAE-0DDC4D4315B0";
271 CKKSDeviceStateEntry* cdse = [[CKKSDeviceStateEntry alloc] initForDevice:testUUID
272 circlePeerID:@"asdf"
273 circleStatus:kSOSCCInCircle
274 keyState:SecCKKSZoneKeyStateReady
275 currentTLKUUID:@"tlk"
276 currentClassAUUID:@"classA"
277 currentClassCUUID:@"classC"
278 zoneID:self.testZoneID
279 encodedCKRecord:nil];
280 XCTAssertNotNil(cdse, "Constructor works");
281 NSError* saveError = nil;
282 [cdse saveToDatabase:&saveError];
283 XCTAssertNil(saveError, "No error saving cdse to database");
284
285 NSError* loadError = nil;
286 CKKSDeviceStateEntry* loadedCDSE = [CKKSDeviceStateEntry fromDatabase:testUUID zoneID:self.testZoneID error:&loadError];
287 XCTAssertNil(loadError, "No error loading CDSE");
288 XCTAssertNotNil(loadedCDSE, "Received a CDSE back");
289
290 XCTAssertEqualObjects(cdse, loadedCDSE, "Roundtripping CKKSDeviceStateEntry ends up with equivalent objects");
291 }
292
293 // disabled, as CKKS syncing is disabled in this class.
294 // To re-enable, need to add flags CKKS syncing to perform queue actions but not automatically start queue processing operations
295 -(void)disabledtestItemAddCreatesCKKSOutgoingQueueEntry {
296 CFMutableDictionaryRef attrs;
297 CFDataRef data;
298
299 NSError* error;
300
301 NSArray* oqes = [CKKSOutgoingQueueEntry all: &error];
302 XCTAssertEqual([oqes count], 0ul, @"Nothing in outgoing queue");
303 XCTAssertNil(error, @"No error loading queue");
304
305 attrs = CFDictionaryCreateMutable( NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks );
306 CFDictionarySetValue( attrs, kSecClass, kSecClassGenericPassword );
307 CFDictionarySetValue( attrs, kSecAttrAccessible, kSecAttrAccessibleAlways );
308 CFDictionarySetValue( attrs, kSecAttrLabel, CFSTR( "TestLabel" ) );
309 CFDictionarySetValue( attrs, kSecAttrDescription, CFSTR( "TestDescription" ) );
310 CFDictionarySetValue( attrs, kSecAttrAccount, CFSTR( "TestAccount" ) );
311 CFDictionarySetValue( attrs, kSecAttrService, CFSTR( "TestService" ) );
312 CFDictionarySetValue( attrs, kSecAttrAccessGroup, CFSTR("com.apple.lakitu"));
313 data = CFDataCreate( NULL, (const uint8_t *) "important data", strlen("important data"));
314 CFDictionarySetValue( attrs, kSecValueData, data );
315 CFRelease( data );
316
317 XCTAssertEqual(SecItemAdd(attrs, NULL), errSecSuccess, @"Adding item works flawlessly");
318
319 oqes = [CKKSOutgoingQueueEntry all: &error];
320 XCTAssertEqual([oqes count], 1ul, @"Single entry in outgoing queue after adding item");
321 XCTAssertNil(error, @"No error loading queue");
322
323 CFDictionarySetValue( attrs, kSecAttrLabel, CFSTR( "TestLabel2" ) );
324 CFDictionarySetValue( attrs, kSecAttrAccount, CFSTR( "TestAccount2" ) );
325 CFDictionarySetValue( attrs, kSecAttrService, CFSTR( "TestService2" ) );
326 XCTAssertEqual(SecItemAdd(attrs, NULL), errSecSuccess);
327 CFRelease( attrs );
328
329 oqes = [CKKSOutgoingQueueEntry all: &error];
330 XCTAssertEqual([oqes count], 2ul, @"Two entries in outgoing queue after adding item");
331 XCTAssertNil(error, @"No error loading queue");
332 }
333
334 - (void)testCKKSKey {
335 CKKSKey* key = nil;
336 NSString* testUUID = @"157A3171-0677-451B-9EAE-0DDC4D4315B0";
337 NSString* testParentUUID = @"f5e7f20f-0885-48f9-b75d-9f0cfd2171b6";
338
339 NSData* testCKRecord = [@"nonsense" dataUsingEncoding:NSUTF8StringEncoding];
340
341 CKKSWrappedAESSIVKey* wrappedkey = [[CKKSWrappedAESSIVKey alloc] initWithBase64:@"KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI="];
342
343 NSError* error = nil;
344
345 key = [CKKSKey fromDatabase:testUUID zoneID:self.testZoneID error:&error];
346 XCTAssertNil(key, "key does not exist yet");
347 XCTAssertNotNil(error, "error exists when things go wrong");
348 error = nil;
349
350 key = [[CKKSKey alloc] initWithWrappedAESKey: wrappedkey
351 uuid: testUUID
352 parentKeyUUID:testParentUUID
353 keyclass:SecCKKSKeyClassA
354 state: SecCKKSProcessedStateLocal
355 zoneID:self.testZoneID
356 encodedCKRecord:testCKRecord
357 currentkey:true];
358 XCTAssertNotNil(key, "could create key");
359
360 [key saveToDatabase: &error];
361 XCTAssertNil(error, "could save key to database");
362 error = nil;
363
364 CKKSKey* key2 = [CKKSKey fromDatabase:testUUID zoneID:self.testZoneID error:&error];
365 XCTAssertNil(error, "no error exists when loading key");
366 XCTAssertNotNil(key2, "key was fetched properly");
367
368 XCTAssertEqualObjects(key.uuid, key2.uuid, "key uuids match");
369 XCTAssertEqualObjects(key.parentKeyUUID, key2.parentKeyUUID, "parent key uuids match");
370 XCTAssertEqualObjects(key.state, key2.state, "key states match");
371 XCTAssertEqualObjects(key.encodedCKRecord, key2.encodedCKRecord, "encodedCKRecord match");
372 XCTAssertEqualObjects(key.wrappedkey, key2.wrappedkey, "wrapped keys match");
373 XCTAssertEqual(key.currentkey, key2.currentkey, "currentkey match");
374 }
375
376 - (void)testWhere {
377 NSError* error = nil;
378
379 NSData* testCKRecord = [@"nonsense" dataUsingEncoding:NSUTF8StringEncoding];
380
381 CKKSKey* tlk = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="]
382 uuid:@"8b2aeb7f-4af3-43e9-b6e6-70d5c728ebf7"
383 keyclass:SecCKKSKeyClassTLK
384 state: SecCKKSProcessedStateLocal
385 zoneID:self.testZoneID
386 encodedCKRecord: testCKRecord
387 currentkey: true];
388 XCTAssertTrue([tlk saveToDatabase: &error], "TLK saved to database");
389 XCTAssertNil(error, "no error saving TLK to database");
390
391 CKKSKey* wrappedKey = [[CKKSKey alloc] initWrappedBy: tlk
392 AESKey:[CKKSAESSIVKey randomKey]
393 uuid:@"157A3171-0677-451B-9EAE-0DDC4D4315B0"
394 keyclass:SecCKKSKeyClassC
395 state: SecCKKSProcessedStateLocal
396 zoneID:self.testZoneID
397 encodedCKRecord:testCKRecord
398 currentkey:true];
399 XCTAssertTrue([wrappedKey saveToDatabase: &error], "key saved to database");
400 XCTAssertNil(error, "no error saving key to database");
401
402 NSArray<CKKSKey*>* tlks = [CKKSKey allWhere: @{@"UUID": @"8b2aeb7f-4af3-43e9-b6e6-70d5c728ebf7"} error: &error];
403 XCTAssertNotNil(tlks, "Returned some array from allWhere");
404 XCTAssertNil(error, "no error back from allWhere");
405 XCTAssertEqual([tlks count], 1ul, "Received one row (and expected one row)");
406
407 NSArray<CKKSKey*>* selfWrapped = [CKKSKey allWhere: @{@"parentKeyUUID": [CKKSSQLWhereObject op:@"=" string:@"uuid"]} error: &error];
408 XCTAssertNotNil(selfWrapped, "Returned some array from allWhere");
409 XCTAssertNil(error, "no error back from allWhere");
410 XCTAssertEqual([selfWrapped count], 1ul, "Received one row (and expected one row)");
411 }
412
413 - (void)testGroupBy {
414 [self addTestZoneEntries];
415 NSError* error = nil;
416
417 __block NSMutableDictionary<NSString*, NSString*>* results = [[NSMutableDictionary alloc] init];
418 NSDictionary* expectedResults = nil;
419
420 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
421 where: nil
422 columns: @[@"action", @"count(rowid)"]
423 groupBy: @[@"action"]
424 orderBy:nil
425 limit: -1
426 processRow: ^(NSDictionary* row) {
427 results[row[@"action"]] = row[@"count(rowid)"];
428 }
429 error: &error];
430
431 XCTAssertNil(error, "no error doing group by query");
432 expectedResults = @{
433 SecCKKSActionAdd: @"2",
434 SecCKKSActionModify: @"1"
435 };
436 XCTAssertEqualObjects(results, expectedResults, "Recieved correct group by result");
437
438 // Now test with a where clause:
439 results = [[NSMutableDictionary alloc] init];
440 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
441 where: @{@"state": SecCKKSStateError}
442 columns: @[@"action", @"count(rowid)"]
443 groupBy: @[@"action"]
444 orderBy:nil
445 limit: -1
446 processRow: ^(NSDictionary* row) {
447 results[row[@"action"]] = row[@"count(rowid)"];
448 }
449 error: &error];
450
451 XCTAssertNil(error, "no error doing where+group by query");
452 expectedResults = @{
453 SecCKKSActionAdd: @"1",
454 SecCKKSActionModify: @"1"
455 };
456 XCTAssertEqualObjects(results, expectedResults, "Recieved correct where+group by result");
457 }
458
459 - (void)testOrderBy {
460 [self addTestZoneEntries];
461 NSError* error = nil;
462
463 __block NSMutableArray* rows = [[NSMutableArray alloc] init];
464
465 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
466 where: nil
467 columns: @[@"action", @"uuid"]
468 groupBy:nil
469 orderBy:@[@"uuid"]
470 limit:-1
471 processRow: ^(NSDictionary* row) {
472 [rows addObject:row];
473 }
474 error: &error];
475
476 XCTAssertNil(error, "no error doing order by query");
477 XCTAssertEqual(rows.count, 3u, "got three items");
478
479 XCTAssertEqual([rows[0][@"uuid"] compare: rows[1][@"uuid"]], NSOrderedAscending, "first order is fine");
480 XCTAssertEqual([rows[1][@"uuid"] compare: rows[2][@"uuid"]], NSOrderedAscending, "second order is fine");
481
482 // Check that order-by + limit works to page
483 __block NSString* lastUUID = nil;
484 __block NSString* uuid = nil;
485 uint64_t count = 0;
486
487 while(count == 0 || uuid != nil) {
488 uuid = nil;
489 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
490 where: lastUUID ? @{@"UUID": [CKKSSQLWhereObject op:@">" stringValue:lastUUID]} : nil
491 columns: @[@"action", @"UUID"]
492 groupBy:nil
493 orderBy:@[@"uuid"]
494 limit:1
495 processRow: ^(NSDictionary* row) {
496 XCTAssertNil(uuid, "Only one row returned");
497 uuid = row[@"UUID"];
498 }
499 error: &error];
500 XCTAssertNil(error, "No error doing SQL");
501 if(uuid && lastUUID) {
502 XCTAssertEqual([lastUUID compare:uuid], NSOrderedAscending, "uuids returning in right order");
503 }
504 lastUUID = uuid;
505 count += 1;
506 }
507 XCTAssertEqual(count, 4u, "Received 3 objects (and 1 nil)");
508 }
509
510 - (void)testLimit {
511 [self addTestZoneEntries];
512 NSError* error = nil;
513
514 __block NSMutableDictionary<NSString*, NSString*>* results = [[NSMutableDictionary alloc] init];
515
516 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
517 where: nil
518 columns: @[@"uuid", @"action"]
519 groupBy: nil
520 orderBy:nil
521 limit: -1
522 processRow: ^(NSDictionary* row) {
523 results[row[@"uuid"]] = row[@"action"];
524 }
525 error: &error];
526
527 XCTAssertNil(error, "no error doing vanilla query");
528 XCTAssertEqual(results.count, 3u, "Received three elements in normal query");
529 results = [[NSMutableDictionary alloc] init];
530
531 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
532 where: nil
533 columns: @[@"uuid", @"action"]
534 groupBy: nil
535 orderBy:nil
536 limit: 1
537 processRow: ^(NSDictionary* row) {
538 results[row[@"uuid"]] = row[@"action"];
539 }
540 error: &error];
541
542 XCTAssertNil(error, "no error doing limit query");
543 XCTAssertEqual(results.count, 1u, "Received one element in limited query");
544 results = [[NSMutableDictionary alloc] init];
545
546 // Now test with a where clause:
547 results = [[NSMutableDictionary alloc] init];
548 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
549 where: @{@"state": SecCKKSStateError}
550 columns: @[@"uuid", @"action"]
551 groupBy: nil
552 orderBy:nil
553 limit: 3
554 processRow: ^(NSDictionary* row) {
555 results[row[@"uuid"]] = row[@"action"];
556 }
557 error: &error];
558
559 XCTAssertNil(error, "no error doing limit+where query");
560 XCTAssertEqual(results.count, 2u, "Received two elements in where+limited query");
561 results = [[NSMutableDictionary alloc] init];
562
563 results = [[NSMutableDictionary alloc] init];
564 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
565 where: @{@"state": SecCKKSStateError}
566 columns: @[@"uuid", @"action"]
567 groupBy: nil
568 orderBy:nil
569 limit: 1
570 processRow: ^(NSDictionary* row) {
571 results[row[@"uuid"]] = row[@"action"];
572 }
573 error: &error];
574
575 XCTAssertNil(error, "no error doing limit+where query");
576 XCTAssertEqual(results.count, 1u, "Received one element in where+limited query");
577 results = [[NSMutableDictionary alloc] init];
578 }
579
580 @end
581
582 #endif