summaryrefslogtreecommitdiffstats
path: root/services/fxaccounts/tests/xpcshell/test_telemetry.js
blob: 1f0976924643ce346e022ce3377a86496de8c817 (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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const { fxAccounts, FxAccounts } = ChromeUtils.import(
  "resource://gre/modules/FxAccounts.jsm"
);

const { PREF_ACCOUNT_ROOT } = ChromeUtils.import(
  "resource://gre/modules/FxAccountsCommon.js"
);

const { FxAccountsProfile } = ChromeUtils.import(
  "resource://gre/modules/FxAccountsProfile.jsm"
);

const { FxAccountsProfileClient } = ChromeUtils.import(
  "resource://gre/modules/FxAccountsProfileClient.jsm"
);

const { FxAccountsTelemetry } = ChromeUtils.import(
  "resource://gre/modules/FxAccountsTelemetry.jsm"
);

XPCOMUtils.defineLazyModuleGetters(this, {
  FxAccountsConfig: "resource://gre/modules/FxAccountsConfig.jsm",
  jwcrypto: "resource://services-crypto/jwcrypto.jsm",
  CryptoUtils: "resource://services-crypto/utils.js",
  PromiseUtils: "resource://gre/modules/PromiseUtils.jsm",
});

_("Misc tests for FxAccounts.telemetry");

const MOCK_HASHED_UID = "00112233445566778899aabbccddeeff";
const MOCK_DEVICE_ID = "ffeeddccbbaa99887766554433221100";

add_task(function test_sanitized_uid() {
  Services.prefs.deleteBranch(
    "identity.fxaccounts.account.telemetry.sanitized_uid"
  );

  // Returns `null` by default.
  Assert.equal(fxAccounts.telemetry.getSanitizedUID(), null);

  // Returns provided value if set.
  fxAccounts.telemetry._setHashedUID(MOCK_HASHED_UID);
  Assert.equal(fxAccounts.telemetry.getSanitizedUID(), MOCK_HASHED_UID);

  // Reverts to unset for falsey values.
  fxAccounts.telemetry._setHashedUID("");
  Assert.equal(fxAccounts.telemetry.getSanitizedUID(), null);
});

add_task(function test_sanitize_device_id() {
  Services.prefs.deleteBranch(
    "identity.fxaccounts.account.telemetry.sanitized_uid"
  );

  // Returns `null` by default.
  Assert.equal(fxAccounts.telemetry.sanitizeDeviceId(MOCK_DEVICE_ID), null);

  // Hashes with the sanitized UID if set.
  // (test value here is SHA256(MOCK_DEVICE_ID + MOCK_HASHED_UID))
  fxAccounts.telemetry._setHashedUID(MOCK_HASHED_UID);
  Assert.equal(
    fxAccounts.telemetry.sanitizeDeviceId(MOCK_DEVICE_ID),
    "dd7c845006df9baa1c6d756926519c8ce12f91230e11b6057bf8ec65f9b55c1a"
  );

  // Reverts to unset for falsey values.
  fxAccounts.telemetry._setHashedUID("");
  Assert.equal(fxAccounts.telemetry.sanitizeDeviceId(MOCK_DEVICE_ID), null);
});

add_task(async function test_getEcosystemAnonId() {
  const ecosystemAnonId = "aaaaaaaaaaaaaaa";
  const testCases = [
    {
      // testing retrieving the ecosystemAnonId from account state
      throw: false,
      accountStateObj: { ecosystemAnonId, ecosystemUserId: "eco-uid" },
      profileObj: { ecosystemAnonId: "bbbbbbbbbbbbbb" },
      expectedEcosystemAnonId: ecosystemAnonId,
    },
    {
      // testing retrieving the ecosystemAnonId when the profile contains it
      throw: false,
      accountStateObj: {},
      profileObj: { ecosystemAnonId },
      expectedEcosystemAnonId: ecosystemAnonId,
    },
    {
      // testing retrieving the ecosystemAnonId when the profile doesn't contain it
      throw: false,
      accountStateObj: {},
      profileObj: {},
      expectedEcosystemAnonId: null,
    },
    {
      // testing retrieving the ecosystemAnonId when the profile is null
      throw: true,
      accountStateObj: {},
      profileObj: null,
      expectedEcosystemAnonId: null,
    },
  ];

  for (const tc of testCases) {
    const profile = new FxAccountsProfile({
      profileServerUrl: "http://testURL",
    });
    const telemetry = new FxAccountsTelemetry({
      profile,
      withCurrentAccountState: async cb => {
        return cb({
          getUserAccountData: async () => {
            return { ...tc.accountStateObj };
          },
        });
      },
    });
    const mockProfile = sinon.mock(profile);
    const mockTelemetry = sinon.mock(telemetry);

    if (!tc.accountStateObj.ecosystemUserId) {
      if (tc.throw) {
        mockProfile
          .expects("getProfile")
          .once()
          .throws(Error);
      } else {
        mockProfile
          .expects("getProfile")
          .once()
          .returns(tc.profileObj);
      }
    }

    if (tc.expectedEcosystemAnonId) {
      mockTelemetry.expects("ensureEcosystemAnonId").never();
    } else {
      mockTelemetry
        .expects("ensureEcosystemAnonId")
        .once()
        .resolves("dddddddddd");
    }

    const actualEcoSystemAnonId = await telemetry.getEcosystemAnonId();
    mockProfile.verify();
    mockTelemetry.verify();
    Assert.equal(actualEcoSystemAnonId, tc.expectedEcosystemAnonId);
  }
});

add_task(async function test_ensureEcosystemAnonId_useAnonIdFromAccountState() {
  // If there's an eco-uid and anon-id in the account state,
  // we should use them without attempting any other updates.
  const expectedEcosystemAnonId = "account-state-anon-id";

  const telemetry = new FxAccountsTelemetry({
    withCurrentAccountState: async cb => {
      return cb({
        getUserAccountData: async () => {
          return {
            ecosystemAnonId: expectedEcosystemAnonId,
            ecosystemUserId: "account-state-eco-uid",
          };
        },
      });
    },
  });

  const actualEcoSystemAnonId = await telemetry.ensureEcosystemAnonId();

  Assert.equal(actualEcoSystemAnonId, expectedEcosystemAnonId);
});

add_task(async function test_ensureEcosystemAnonId_useUserIdFromAccountState() {
  // If there's an eco-uid in the account state but not anon-id,
  // we should generate and save our own unique anon-id.
  const expectedEcosystemUserId = "02".repeat(32);
  const expectedEcosystemAnonId = "bbbbbbbbbbbb";

  const mockedUpdate = sinon
    .mock()
    .once()
    .withExactArgs({
      ecosystemAnonId: expectedEcosystemAnonId,
    });
  const telemetry = new FxAccountsTelemetry({
    withCurrentAccountState: async cb => {
      return cb({
        getUserAccountData: async () => {
          return {
            // Note: no ecosystemAnonId field here.
            ecosystemUserId: expectedEcosystemUserId,
          };
        },
        updateUserAccountData: mockedUpdate,
      });
    },
  });
  const mockFxAccountsConfig = sinon.mock(FxAccountsConfig);
  const mockJwcrypto = sinon.mock(jwcrypto);

  mockFxAccountsConfig
    .expects("fetchConfigDocument")
    .once()
    .returns({
      ecosystem_anon_id_keys: ["testKey"],
    });

  mockJwcrypto
    .expects("generateJWE")
    .once()
    .withExactArgs("testKey", new TextEncoder().encode(expectedEcosystemUserId))
    .returns(expectedEcosystemAnonId);

  const actualEcosystemAnonId = await telemetry.ensureEcosystemAnonId();
  Assert.equal(expectedEcosystemAnonId, actualEcosystemAnonId);

  mockFxAccountsConfig.verify();
  mockJwcrypto.verify();
  mockedUpdate.verify();
});

add_task(async function test_ensureEcosystemAnonId_useValueFromProfile() {
  // If there's no eco-uid in the account state,
  // we should use the anon-id value present in the user's profile data.
  const expectedEcosystemAnonId = "bbbbbbbbbbbb";

  const profileClient = new FxAccountsProfileClient({
    serverURL: "http://testURL",
  });
  const profile = new FxAccountsProfile({ profileClient });
  const telemetry = new FxAccountsTelemetry({
    profile,
    withCurrentAccountState: async cb => {
      return cb({
        getUserAccountData: async () => {
          return {};
        },
      });
    },
  });
  const mockProfile = sinon.mock(profile);

  mockProfile
    .expects("ensureProfile")
    .withArgs(sinon.match({ staleOk: true }))
    .once()
    .returns({
      ecosystemAnonId: expectedEcosystemAnonId,
    });

  const actualEcosystemAnonId = await telemetry.ensureEcosystemAnonId();
  Assert.equal(expectedEcosystemAnonId, actualEcosystemAnonId);

  mockProfile.verify();
});

add_task(
  async function test_ensureEcosystemAnonId_generatePlaceholderInProfile() {
    // If there's no eco-uid in the account state, and no anon-id in the profile data,
    // we should generate a placeholder value and persist it to the profile data.
    const expectedEcosystemUserIdBytes = new Uint8Array(32);
    const expectedEcosystemUserId = "0".repeat(64);
    const expectedEcosystemAnonId = "bbbbbbbbbbbb";
    const profileClient = new FxAccountsProfileClient({
      serverURL: "http://testURL",
    });
    const profile = new FxAccountsProfile({ profileClient });
    const telemetry = new FxAccountsTelemetry({
      profile,
      withCurrentAccountState: async cb => {
        return cb({
          getUserAccountData: async () => {
            return {};
          },
        });
      },
    });
    const mockProfile = sinon.mock(profile);
    const mockFxAccountsConfig = sinon.mock(FxAccountsConfig);
    const mockJwcrypto = sinon.mock(jwcrypto);
    const mockCryptoUtils = sinon.mock(CryptoUtils);
    const mockProfileClient = sinon.mock(profileClient);

    mockProfile
      .expects("ensureProfile")
      .once()
      .returns({});

    mockCryptoUtils
      .expects("generateRandomBytes")
      .once()
      .withExactArgs(32)
      .returns(expectedEcosystemUserIdBytes);

    mockFxAccountsConfig
      .expects("fetchConfigDocument")
      .once()
      .returns({
        ecosystem_anon_id_keys: ["testKey"],
      });

    mockJwcrypto
      .expects("generateJWE")
      .once()
      .withExactArgs(
        "testKey",
        new TextEncoder().encode(expectedEcosystemUserId)
      )
      .returns(expectedEcosystemAnonId);

    mockProfileClient
      .expects("setEcosystemAnonId")
      .once()
      .withExactArgs(expectedEcosystemAnonId)
      .returns(null);

    const actualEcosystemAnonId = await telemetry.ensureEcosystemAnonId(true);
    Assert.equal(expectedEcosystemAnonId, actualEcosystemAnonId);

    mockProfile.verify();
    mockCryptoUtils.verify();
    mockFxAccountsConfig.verify();
    mockJwcrypto.verify();
    mockProfileClient.verify();
  }
);

add_task(async function test_ensureEcosystemAnonId_failToGenerateKeys() {
  // If we attempt to generate an anon-id but can't get the right keys,
  // we should fail with a sensible error.
  const expectedErrorMessage =
    "Unable to fetch ecosystem_anon_id_keys from FxA server";
  const testCases = [
    {
      accountStateObj: {},
      serverConfig: {},
    },
    {
      accountStateObj: {},
      serverConfig: {
        ecosystem_anon_id_keys: [],
      },
    },
    {
      accountStateObj: { ecosystemUserId: "bbbbbbbbbb" },
      serverConfig: {},
    },
    {
      accountStateObj: { ecosystemUserId: "bbbbbbbbbb" },
      serverConfig: {
        ecosystem_anon_id_keys: [],
      },
    },
  ];
  for (const tc of testCases) {
    const profile = new FxAccountsProfile({
      profileServerUrl: "http://testURL",
    });
    const telemetry = new FxAccountsTelemetry({
      profile,
      withCurrentAccountState: async cb => {
        return cb({
          getUserAccountData: async () => {
            return { ...tc.accountStateObj };
          },
        });
      },
    });
    const mockProfile = sinon.mock(profile);
    const mockFxAccountsConfig = sinon.mock(FxAccountsConfig);

    if (!tc.accountStateObj.ecosystemUserId) {
      mockProfile
        .expects("ensureProfile")
        .once()
        .returns({});
    } else {
      mockProfile.expects("ensureProfile").never();
    }

    mockFxAccountsConfig
      .expects("fetchConfigDocument")
      .once()
      .returns(tc.serverConfig);

    try {
      await telemetry.ensureEcosystemAnonId();
    } catch (e) {
      Assert.equal(expectedErrorMessage, e.message);
      mockProfile.verify();
      mockFxAccountsConfig.verify();
    }
  }
});

add_task(async function test_ensureEcosystemAnonId_selfRace() {
  // If we somehow end up calling `ensureEcosystemAnonId` twice,
  // we should serialize the requests rather than generting two
  // different placeholder ids.
  const expectedEcosystemAnonId = "self-race-id";

  const profileClient = new FxAccountsProfileClient({
    serverURL: "http://testURL",
  });
  const profile = new FxAccountsProfile({ profileClient });
  const telemetry = new FxAccountsTelemetry({
    profile,
    withCurrentAccountState: async cb => {
      return cb({
        getUserAccountData: async () => {
          return {};
        },
      });
    },
  });

  const mockProfile = sinon.mock(profile);
  const mockFxAccountsConfig = sinon.mock(FxAccountsConfig);
  const mockJwcrypto = sinon.mock(jwcrypto);
  const mockProfileClient = sinon.mock(profileClient);

  mockProfile
    .expects("ensureProfile")
    .once()
    .returns({});

  mockProfileClient
    .expects("setEcosystemAnonId")
    .once()
    .returns(null);

  // We are going to "block" the config document promise and make 2 calls
  // to ensureEcosystemAnonId() while blocked, just to ensure we don't
  // actually enter the ensureEcosystemAnonId() impl twice.
  const deferInConfigDocument = PromiseUtils.defer();
  const deferConfigDocument = PromiseUtils.defer();
  mockFxAccountsConfig
    .expects("fetchConfigDocument")
    .once()
    .callsFake(() => {
      deferInConfigDocument.resolve();
      return deferConfigDocument.promise;
    });

  mockJwcrypto
    .expects("generateJWE")
    .once()
    .returns(expectedEcosystemAnonId);

  let p1 = telemetry.ensureEcosystemAnonId();
  let p2 = telemetry.ensureEcosystemAnonId();

  // Make sure we've entered fetchConfigDocument
  await deferInConfigDocument.promise;
  // Let it go.
  deferConfigDocument.resolve({ ecosystem_anon_id_keys: ["testKey"] });

  Assert.equal(await p1, expectedEcosystemAnonId);
  Assert.equal(await p2, expectedEcosystemAnonId);

  // And all the `.once()` calls on the mocks are checking we only did the
  // work once.
  mockProfile.verify();
  mockFxAccountsConfig.verify();
  mockJwcrypto.verify();
  mockProfileClient.verify();
});

add_task(async function test_ensureEcosystemAnonId_clientRace() {
  // If we attempt to upload a placeholder anon-id to the user's profile,
  // and our write conflicts with another client doing a similar upload,
  // then we should recover and accept the server version.
  const expectedEcosystemAnonId = "bbbbbbbbbbbb";
  const expectedErrrorMessage = "test error at 'setEcosystemAnonId'";

  const testCases = [
    {
      errorCode: 412,
      errorMessage: null,
    },
    {
      errorCode: 405,
      errorMessage: expectedErrrorMessage,
    },
  ];

  for (const tc of testCases) {
    const profileClient = new FxAccountsProfileClient({
      serverURL: "http://testURL",
    });
    const profile = new FxAccountsProfile({ profileClient });
    const telemetry = new FxAccountsTelemetry({
      profile,
      withCurrentAccountState: async cb => {
        return cb({
          getUserAccountData: async () => {
            return {};
          },
        });
      },
    });
    const mockProfile = sinon.mock(profile);
    const mockFxAccountsConfig = sinon.mock(FxAccountsConfig);
    const mockJwcrypto = sinon.mock(jwcrypto);
    const mockProfileClient = sinon.mock(profileClient);

    mockProfile
      .expects("ensureProfile")
      .withArgs(sinon.match({ staleOk: true }))
      .once()
      .returns({});

    mockFxAccountsConfig
      .expects("fetchConfigDocument")
      .once()
      .returns({
        ecosystem_anon_id_keys: ["testKey"],
      });

    mockJwcrypto
      .expects("generateJWE")
      .once()
      .returns(expectedEcosystemAnonId);

    mockProfileClient
      .expects("setEcosystemAnonId")
      .once()
      .throws({
        code: tc.errorCode,
        message: tc.errorMessage,
      });

    if (tc.errorCode === 412) {
      mockProfile
        .expects("ensureProfile")
        .withArgs(sinon.match({ forceFresh: true }))
        .once()
        .returns({
          ecosystemAnonId: expectedEcosystemAnonId,
        });

      const actualEcosystemAnonId = await telemetry.ensureEcosystemAnonId();
      Assert.equal(expectedEcosystemAnonId, actualEcosystemAnonId);
    } else {
      try {
        await telemetry.ensureEcosystemAnonId();
      } catch (e) {
        Assert.equal(expectedErrrorMessage, e.message);
      }
    }

    mockProfile.verify();
    mockFxAccountsConfig.verify();
    mockJwcrypto.verify();
    mockProfileClient.verify();
  }
});