summaryrefslogtreecommitdiffstats
path: root/services/sync/tests/unit/test_keys.js
blob: a828b619cd9450e9644a7e50f1d92469900bff0b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/keys.js");
Cu.import("resource://services-sync/record.js");
Cu.import("resource://services-sync/util.js");

var collectionKeys = new CollectionKeyManager();

function sha256HMAC(message, key) {
  let h = Utils.makeHMACHasher(Ci.nsICryptoHMAC.SHA256, key);
  return Utils.digestBytes(message, h);
}

function do_check_keypair_eq(a, b) {
  do_check_eq(2, a.length);
  do_check_eq(2, b.length);
  do_check_eq(a[0], b[0]);
  do_check_eq(a[1], b[1]);
}

function test_time_keyFromString(iterations) {
  let k;
  let o;
  let b = new BulkKeyBundle("dummy");
  let d = Utils.decodeKeyBase32("ababcdefabcdefabcdefabcdef");
  b.generateRandom();

  _("Running " + iterations + " iterations of hmacKeyObject + sha256HMAC.");
  for (let i = 0; i < iterations; ++i) {
    let k = b.hmacKeyObject;
    o = sha256HMAC(d, k);
  }
  do_check_true(!!o);
  _("Done.");
}

add_test(function test_set_invalid_values() {
  _("Ensure that setting invalid encryption and HMAC key values is caught.");

  let bundle = new BulkKeyBundle("foo");

  let thrown = false;
  try {
    bundle.encryptionKey = null;
  } catch (ex) {
    thrown = true;
    do_check_eq(ex.message.indexOf("Encryption key can only be set to"), 0);
  } finally {
    do_check_true(thrown);
    thrown = false;
  }

  try {
    bundle.encryptionKey = ["trollololol"];
  } catch (ex) {
    thrown = true;
    do_check_eq(ex.message.indexOf("Encryption key can only be set to"), 0);
  } finally {
    do_check_true(thrown);
    thrown = false;
  }

  try {
    bundle.hmacKey = Utils.generateRandomBytes(15);
  } catch (ex) {
    thrown = true;
    do_check_eq(ex.message.indexOf("HMAC key must be at least 128"), 0);
  } finally {
    do_check_true(thrown);
    thrown = false;
  }

  try {
    bundle.hmacKey = null;
  } catch (ex) {
    thrown = true;
    do_check_eq(ex.message.indexOf("HMAC key can only be set to string"), 0);
  } finally {
    do_check_true(thrown);
    thrown = false;
  }

  try {
    bundle.hmacKey = ["trollolol"];
  } catch (ex) {
    thrown = true;
    do_check_eq(ex.message.indexOf("HMAC key can only be set to"), 0);
  } finally {
    do_check_true(thrown);
    thrown = false;
  }

  try {
    bundle.hmacKey = Utils.generateRandomBytes(15);
  } catch (ex) {
    thrown = true;
    do_check_eq(ex.message.indexOf("HMAC key must be at least 128"), 0);
  } finally {
    do_check_true(thrown);
    thrown = false;
  }

  run_next_test();
});

add_test(function test_repeated_hmac() {
  let testKey = "ababcdefabcdefabcdefabcdef";
  let k = Utils.makeHMACKey("foo");
  let one = sha256HMAC(Utils.decodeKeyBase32(testKey), k);
  let two = sha256HMAC(Utils.decodeKeyBase32(testKey), k);
  do_check_eq(one, two);

  run_next_test();
});

add_test(function test_sync_key_bundle_derivation() {
  _("Ensure derivation from known values works.");

  // The known values in this test were originally verified against Firefox
  // Home.
  let bundle = new SyncKeyBundle("st3fan", "q7ynpwq7vsc9m34hankbyi3s3i");

  // These should be compared to the results from Home, as they once were.
  let e = "14b8c09fa84e92729ee695160af6e0385f8f6215a25d14906e1747bdaa2de426";
  let h = "370e3566245d79fe602a3adb5137e42439cd2a571235197e0469d7d541b07875";

  let realE = Utils.bytesAsHex(bundle.encryptionKey);
  let realH = Utils.bytesAsHex(bundle.hmacKey);

  _("Real E: " + realE);
  _("Real H: " + realH);
  do_check_eq(realH, h);
  do_check_eq(realE, e);

  run_next_test();
});

add_test(function test_keymanager() {
  let testKey = "ababcdefabcdefabcdefabcdef";
  let username = "john@example.com";

  // Decode the key here to mirror what generateEntry will do,
  // but pass it encoded into the KeyBundle call below.

  let sha256inputE = "" + HMAC_INPUT + username + "\x01";
  let key = Utils.makeHMACKey(Utils.decodeKeyBase32(testKey));
  let encryptKey = sha256HMAC(sha256inputE, key);

  let sha256inputH = encryptKey + HMAC_INPUT + username + "\x02";
  let hmacKey = sha256HMAC(sha256inputH, key);

  // Encryption key is stored in base64 for WeaveCrypto convenience.
  do_check_eq(encryptKey, new SyncKeyBundle(username, testKey).encryptionKey);
  do_check_eq(hmacKey,    new SyncKeyBundle(username, testKey).hmacKey);

  // Test with the same KeyBundle for both.
  let obj = new SyncKeyBundle(username, testKey);
  do_check_eq(hmacKey, obj.hmacKey);
  do_check_eq(encryptKey, obj.encryptionKey);

  run_next_test();
});

add_test(function test_collections_manager() {
  let log = Log.repository.getLogger("Test");
  Log.repository.rootLogger.addAppender(new Log.DumpAppender());

  let identity = new IdentityManager();

  identity.account = "john@example.com";
  identity.syncKey = "a-bbbbb-ccccc-ddddd-eeeee-fffff";

  let keyBundle = identity.syncKeyBundle;

  /*
   * Build a test version of storage/crypto/keys.
   * Encrypt it with the sync key.
   * Pass it into the CollectionKeyManager.
   */

  log.info("Building storage keys...");
  let storage_keys = new CryptoWrapper("crypto", "keys");
  let default_key64 = Svc.Crypto.generateRandomKey();
  let default_hmac64 = Svc.Crypto.generateRandomKey();
  let bookmarks_key64 = Svc.Crypto.generateRandomKey();
  let bookmarks_hmac64 = Svc.Crypto.generateRandomKey();

  storage_keys.cleartext = {
    "default": [default_key64, default_hmac64],
    "collections": {"bookmarks": [bookmarks_key64, bookmarks_hmac64]},
  };
  storage_keys.modified = Date.now()/1000;
  storage_keys.id = "keys";

  log.info("Encrypting storage keys...");

  // Use passphrase (sync key) itself to encrypt the key bundle.
  storage_keys.encrypt(keyBundle);

  // Sanity checking.
  do_check_true(null == storage_keys.cleartext);
  do_check_true(null != storage_keys.ciphertext);

  log.info("Updating collection keys.");

  // updateContents decrypts the object, releasing the payload for us to use.
  // Returns true, because the default key has changed.
  do_check_true(collectionKeys.updateContents(keyBundle, storage_keys));
  let payload = storage_keys.cleartext;

  _("CK: " + JSON.stringify(collectionKeys._collections));

  // Test that the CollectionKeyManager returns a similar WBO.
  let wbo = collectionKeys.asWBO("crypto", "keys");

  _("WBO: " + JSON.stringify(wbo));
  _("WBO cleartext: " + JSON.stringify(wbo.cleartext));

  // Check the individual contents.
  do_check_eq(wbo.collection, "crypto");
  do_check_eq(wbo.id, "keys");
  do_check_eq(undefined, wbo.modified);
  do_check_eq(collectionKeys.lastModified, storage_keys.modified);
  do_check_true(!!wbo.cleartext.default);
  do_check_keypair_eq(payload.default, wbo.cleartext.default);
  do_check_keypair_eq(payload.collections.bookmarks, wbo.cleartext.collections.bookmarks);

  do_check_true('bookmarks' in collectionKeys._collections);
  do_check_false('tabs' in collectionKeys._collections);

  _("Updating contents twice with the same data doesn't proceed.");
  storage_keys.encrypt(keyBundle);
  do_check_false(collectionKeys.updateContents(keyBundle, storage_keys));

  /*
   * Test that we get the right keys out when we ask for
   * a collection's tokens.
   */
  let b1 = new BulkKeyBundle("bookmarks");
  b1.keyPairB64 = [bookmarks_key64, bookmarks_hmac64];
  let b2 = collectionKeys.keyForCollection("bookmarks");
  do_check_keypair_eq(b1.keyPair, b2.keyPair);

  // Check key equality.
  do_check_true(b1.equals(b2));
  do_check_true(b2.equals(b1));

  b1 = new BulkKeyBundle("[default]");
  b1.keyPairB64 = [default_key64, default_hmac64];

  do_check_false(b1.equals(b2));
  do_check_false(b2.equals(b1));

  b2 = collectionKeys.keyForCollection(null);
  do_check_keypair_eq(b1.keyPair, b2.keyPair);

  /*
   * Checking for update times.
   */
  let info_collections = {};
  do_check_true(collectionKeys.updateNeeded(info_collections));
  info_collections["crypto"] = 5000;
  do_check_false(collectionKeys.updateNeeded(info_collections));
  info_collections["crypto"] = 1 + (Date.now()/1000);              // Add one in case computers are fast!
  do_check_true(collectionKeys.updateNeeded(info_collections));

  collectionKeys.lastModified = null;
  do_check_true(collectionKeys.updateNeeded({}));

  /*
   * Check _compareKeyBundleCollections.
   */
  function newBundle(name) {
    let r = new BulkKeyBundle(name);
    r.generateRandom();
    return r;
  }
  let k1 = newBundle("k1");
  let k2 = newBundle("k2");
  let k3 = newBundle("k3");
  let k4 = newBundle("k4");
  let k5 = newBundle("k5");
  let coll1 = {"foo": k1, "bar": k2};
  let coll2 = {"foo": k1, "bar": k2};
  let coll3 = {"foo": k1, "bar": k3};
  let coll4 = {"foo": k4};
  let coll5 = {"baz": k5, "bar": k2};
  let coll6 = {};

  let d1 = collectionKeys._compareKeyBundleCollections(coll1, coll2); // []
  let d2 = collectionKeys._compareKeyBundleCollections(coll1, coll3); // ["bar"]
  let d3 = collectionKeys._compareKeyBundleCollections(coll3, coll2); // ["bar"]
  let d4 = collectionKeys._compareKeyBundleCollections(coll1, coll4); // ["bar", "foo"]
  let d5 = collectionKeys._compareKeyBundleCollections(coll5, coll2); // ["baz", "foo"]
  let d6 = collectionKeys._compareKeyBundleCollections(coll6, coll1); // ["bar", "foo"]
  let d7 = collectionKeys._compareKeyBundleCollections(coll5, coll5); // []
  let d8 = collectionKeys._compareKeyBundleCollections(coll6, coll6); // []

  do_check_true(d1.same);
  do_check_false(d2.same);
  do_check_false(d3.same);
  do_check_false(d4.same);
  do_check_false(d5.same);
  do_check_false(d6.same);
  do_check_true(d7.same);
  do_check_true(d8.same);

  do_check_array_eq(d1.changed, []);
  do_check_array_eq(d2.changed, ["bar"]);
  do_check_array_eq(d3.changed, ["bar"]);
  do_check_array_eq(d4.changed, ["bar", "foo"]);
  do_check_array_eq(d5.changed, ["baz", "foo"]);
  do_check_array_eq(d6.changed, ["bar", "foo"]);

  run_next_test();
});

function run_test() {
  // Only do 1,000 to avoid a 5-second pause in test runs.
  test_time_keyFromString(1000);

  run_next_test();
}