summaryrefslogtreecommitdiffstats
path: root/services/sync/tests/unit/test_records_crypto.js
blob: 8b841653cdfe047707da54f95d61598ba40a721f (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

const { CollectionKeyManager, CryptoWrapper } = ChromeUtils.importESModule(
  "resource://services-sync/record.sys.mjs"
);
const { Service } = ChromeUtils.importESModule(
  "resource://services-sync/service.sys.mjs"
);

var cryptoWrap;

function crypted_resource_handler(metadata, response) {
  let obj = {
    id: "resource",
    modified: cryptoWrap.modified,
    payload: JSON.stringify(cryptoWrap.payload),
  };
  return httpd_basic_auth_handler(JSON.stringify(obj), metadata, response);
}

function prepareCryptoWrap(collection, id) {
  let w = new CryptoWrapper();
  w.cleartext.stuff = "my payload here";
  w.collection = collection;
  w.id = id;
  return w;
}

add_task(async function test_records_crypto() {
  let server;

  await configureIdentity({ username: "john@example.com" });
  let keyBundle = Service.identity.syncKeyBundle;

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

    log.info("Setting up server and authenticator");

    server = httpd_setup({ "/steam/resource": crypted_resource_handler });

    log.info("Creating a record");

    cryptoWrap = prepareCryptoWrap("steam", "resource");

    log.info("cryptoWrap: " + cryptoWrap.toString());

    log.info("Encrypting a record");

    await cryptoWrap.encrypt(keyBundle);
    log.info("Ciphertext is " + cryptoWrap.ciphertext);
    Assert.ok(cryptoWrap.ciphertext != null);

    let firstIV = cryptoWrap.IV;

    log.info("Decrypting the record");

    let payload = await cryptoWrap.decrypt(keyBundle);
    Assert.equal(payload.stuff, "my payload here");
    Assert.notEqual(payload, cryptoWrap.payload); // wrap.data.payload is the encrypted one

    log.info("Make sure multiple decrypts cause failures");
    let error = "";
    try {
      payload = await cryptoWrap.decrypt(keyBundle);
    } catch (ex) {
      error = ex;
    }
    Assert.equal(error.message, "No ciphertext: nothing to decrypt?");

    log.info("Re-encrypting the record with alternate payload");

    cryptoWrap.cleartext.stuff = "another payload";
    await cryptoWrap.encrypt(keyBundle);
    let secondIV = cryptoWrap.IV;
    payload = await cryptoWrap.decrypt(keyBundle);
    Assert.equal(payload.stuff, "another payload");

    log.info("Make sure multiple encrypts use different IVs");
    Assert.notEqual(firstIV, secondIV);

    log.info(await "Make sure differing ids cause failures");
    await cryptoWrap.encrypt(keyBundle);
    cryptoWrap.data.id = "other";
    error = "";
    try {
      await cryptoWrap.decrypt(keyBundle);
    } catch (ex) {
      error = ex;
    }
    Assert.equal(error.message, "Record id mismatch: resource != other");

    log.info("Make sure wrong hmacs cause failures");
    await cryptoWrap.encrypt(keyBundle);
    cryptoWrap.hmac = "foo";
    error = "";
    try {
      await cryptoWrap.decrypt(keyBundle);
    } catch (ex) {
      error = ex;
    }
    Assert.equal(
      error.message.substr(0, 42),
      "Record SHA256 HMAC mismatch: should be foo"
    );

    // Checking per-collection keys and default key handling.

    await generateNewKeys(Service.collectionKeys);
    let bookmarkItem = prepareCryptoWrap("bookmarks", "foo");
    await bookmarkItem.encrypt(
      Service.collectionKeys.keyForCollection("bookmarks")
    );
    log.info("Ciphertext is " + bookmarkItem.ciphertext);
    Assert.ok(bookmarkItem.ciphertext != null);
    log.info("Decrypting the record explicitly with the default key.");
    Assert.equal(
      (await bookmarkItem.decrypt(Service.collectionKeys._default)).stuff,
      "my payload here"
    );

    // Per-collection keys.
    // Generate a key for "bookmarks".
    await generateNewKeys(Service.collectionKeys, ["bookmarks"]);
    bookmarkItem = prepareCryptoWrap("bookmarks", "foo");
    Assert.equal(bookmarkItem.collection, "bookmarks");

    // Encrypt. This'll use the "bookmarks" encryption key, because we have a
    // special key for it. The same key will need to be used for decryption.
    await bookmarkItem.encrypt(
      Service.collectionKeys.keyForCollection("bookmarks")
    );
    Assert.ok(bookmarkItem.ciphertext != null);

    // Attempt to use the default key, because this is a collision that could
    // conceivably occur in the real world. Decryption will error, because
    // it's not the bookmarks key.
    let err;
    try {
      await bookmarkItem.decrypt(Service.collectionKeys._default);
    } catch (ex) {
      err = ex;
    }
    Assert.equal("Record SHA256 HMAC mismatch", err.message.substr(0, 27));

    // Explicitly check that it's using the bookmarks key.
    // This should succeed.
    Assert.equal(
      (
        await bookmarkItem.decrypt(
          Service.collectionKeys.keyForCollection("bookmarks")
        )
      ).stuff,
      "my payload here"
    );

    Assert.ok(Service.collectionKeys.hasKeysFor(["bookmarks"]));

    // Add a key for some new collection and verify that it isn't the
    // default key.
    Assert.ok(!Service.collectionKeys.hasKeysFor(["forms"]));
    Assert.ok(!Service.collectionKeys.hasKeysFor(["bookmarks", "forms"]));
    let oldFormsKey = Service.collectionKeys.keyForCollection("forms");
    Assert.equal(oldFormsKey, Service.collectionKeys._default);
    let newKeys = await Service.collectionKeys.ensureKeysFor(["forms"]);
    Assert.ok(newKeys.hasKeysFor(["forms"]));
    Assert.ok(newKeys.hasKeysFor(["bookmarks", "forms"]));
    let newFormsKey = newKeys.keyForCollection("forms");
    Assert.notEqual(newFormsKey, oldFormsKey);

    // Verify that this doesn't overwrite keys
    let regetKeys = await newKeys.ensureKeysFor(["forms"]);
    Assert.equal(regetKeys.keyForCollection("forms"), newFormsKey);

    const emptyKeys = new CollectionKeyManager();
    payload = {
      default: Service.collectionKeys._default.keyPairB64,
      collections: {},
    };
    // Verify that not passing `modified` doesn't throw
    emptyKeys.setContents(payload, null);

    log.info("Done!");
  } finally {
    await promiseStopServer(server);
  }
});