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