summaryrefslogtreecommitdiffstats
path: root/services/fxaccounts/tests/xpcshell/test_oauth_tokens.js
blob: 82f174edd1a6eccdc5323a8d54032dfedc02b651 (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const { FxAccounts } = ChromeUtils.importESModule(
  "resource://gre/modules/FxAccounts.sys.mjs"
);
const { FxAccountsClient } = ChromeUtils.importESModule(
  "resource://gre/modules/FxAccountsClient.sys.mjs"
);
var { AccountState } = ChromeUtils.importESModule(
  "resource://gre/modules/FxAccounts.sys.mjs"
);

function promiseNotification(topic) {
  return new Promise(resolve => {
    let observe = () => {
      Services.obs.removeObserver(observe, topic);
      resolve();
    };
    Services.obs.addObserver(observe, topic);
  });
}

// Just enough mocks so we can avoid hawk and storage.
function MockStorageManager() {}

MockStorageManager.prototype = {
  promiseInitialized: Promise.resolve(),

  initialize(accountData) {
    this.accountData = accountData;
  },

  finalize() {
    return Promise.resolve();
  },

  getAccountData() {
    return Promise.resolve(this.accountData);
  },

  updateAccountData(updatedFields) {
    for (let [name, value] of Object.entries(updatedFields)) {
      if (value == null) {
        delete this.accountData[name];
      } else {
        this.accountData[name] = value;
      }
    }
    return Promise.resolve();
  },

  deleteAccountData() {
    this.accountData = null;
    return Promise.resolve();
  },
};

function MockFxAccountsClient(activeTokens) {
  this._email = "nobody@example.com";
  this._verified = false;

  this.accountStatus = function (uid) {
    return Promise.resolve(!!uid && !this._deletedOnServer);
  };

  this.signOut = function () {
    return Promise.resolve();
  };
  this.registerDevice = function () {
    return Promise.resolve();
  };
  this.updateDevice = function () {
    return Promise.resolve();
  };
  this.signOutAndDestroyDevice = function () {
    return Promise.resolve();
  };
  this.getDeviceList = function () {
    return Promise.resolve();
  };
  this.accessTokenWithSessionToken = function (
    sessionTokenHex,
    clientId,
    scope,
    ttl
  ) {
    let token = `token${this.numTokenFetches}`;
    if (ttl) {
      token += `-ttl-${ttl}`;
    }
    this.numTokenFetches += 1;
    this.activeTokens.add(token);
    print("accessTokenWithSessionToken returning token", token);
    return Promise.resolve({ access_token: token, ttl });
  };
  this.oauthDestroy = sinon.stub().callsFake((_clientId, token) => {
    this.activeTokens.delete(token);
    return Promise.resolve();
  });

  // Test only stuff.
  this.activeTokens = activeTokens;
  this.numTokenFetches = 0;

  FxAccountsClient.apply(this);
}

MockFxAccountsClient.prototype = {};
Object.setPrototypeOf(
  MockFxAccountsClient.prototype,
  FxAccountsClient.prototype
);

function MockFxAccounts() {
  // The FxA "auth" and "oauth" servers both share the same db of tokens,
  // so we need to simulate the same here in the tests.
  const activeTokens = new Set();
  return new FxAccounts({
    fxAccountsClient: new MockFxAccountsClient(activeTokens),
    newAccountState(credentials) {
      // we use a real accountState but mocked storage.
      let storage = new MockStorageManager();
      storage.initialize(credentials);
      return new AccountState(storage);
    },
    _getDeviceName() {
      return "mock device name";
    },
    fxaPushService: {
      registerPushEndpoint() {
        return new Promise(resolve => {
          resolve({
            endpoint: "http://mochi.test:8888",
          });
        });
      },
    },
  });
}

async function createMockFxA() {
  let fxa = new MockFxAccounts();
  let credentials = {
    email: "foo@example.com",
    uid: "1234@lcip.org",
    sessionToken: "dead",
    scopedKeys: {
      [SCOPE_OLD_SYNC]: {
        kid: "key id for sync key",
        k: "key material for sync key",
        kty: "oct",
      },
    },
    verified: true,
  };

  await fxa._internal.setSignedInUser(credentials);
  return fxa;
}

// The tests.

add_task(async function testRevoke() {
  let tokenOptions = { scope: "test-scope" };
  let fxa = await createMockFxA();
  let client = fxa._internal.fxAccountsClient;

  // get our first token and check we hit the mock.
  let token1 = await fxa.getOAuthToken(tokenOptions);
  equal(client.numTokenFetches, 1);
  equal(client.activeTokens.size, 1);
  ok(token1, "got a token");
  equal(token1, "token0");

  // drop the new token from our cache.
  await fxa.removeCachedOAuthToken({ token: token1 });
  ok(client.oauthDestroy.calledOnce);

  // the revoke should have been successful.
  equal(client.activeTokens.size, 0);
  // fetching it again hits the server.
  let token2 = await fxa.getOAuthToken(tokenOptions);
  equal(client.numTokenFetches, 2);
  equal(client.activeTokens.size, 1);
  ok(token2, "got a token");
  notEqual(token1, token2, "got a different token");
});

add_task(async function testSignOutDestroysTokens() {
  let fxa = await createMockFxA();
  let client = fxa._internal.fxAccountsClient;

  // get our first token and check we hit the mock.
  let token1 = await fxa.getOAuthToken({ scope: "test-scope" });
  equal(client.numTokenFetches, 1);
  equal(client.activeTokens.size, 1);
  ok(token1, "got a token");

  // get another
  let token2 = await fxa.getOAuthToken({ scope: "test-scope-2" });
  equal(client.numTokenFetches, 2);
  equal(client.activeTokens.size, 2);
  ok(token2, "got a token");
  notEqual(token1, token2, "got a different token");

  // FxA fires an observer when the "background" signout is complete.
  let signoutComplete = promiseNotification("testhelper-fxa-signout-complete");
  // now sign out - they should be removed.
  await fxa.signOut();
  await signoutComplete;
  ok(client.oauthDestroy.calledTwice);
  // No active tokens left.
  equal(client.activeTokens.size, 0);
});

add_task(async function testTokenRaces() {
  // Here we do 2 concurrent fetches each for 2 different token scopes (ie,
  // 4 token fetches in total).
  // This should provoke a potential race in the token fetching but we use
  // a map of in-flight token fetches, so we should still only perform 2
  // fetches, but each of the 4 calls should resolve with the correct values.
  let fxa = await createMockFxA();
  let client = fxa._internal.fxAccountsClient;

  let results = await Promise.all([
    fxa.getOAuthToken({ scope: "test-scope" }),
    fxa.getOAuthToken({ scope: "test-scope" }),
    fxa.getOAuthToken({ scope: "test-scope-2" }),
    fxa.getOAuthToken({ scope: "test-scope-2" }),
  ]);

  equal(client.numTokenFetches, 2, "should have fetched 2 tokens.");

  // Should have 2 unique tokens
  results.sort();
  equal(results[0], results[1]);
  equal(results[2], results[3]);
  // should be 2 active.
  equal(client.activeTokens.size, 2);
  await fxa.removeCachedOAuthToken({ token: results[0] });
  equal(client.activeTokens.size, 1);
  await fxa.removeCachedOAuthToken({ token: results[2] });
  equal(client.activeTokens.size, 0);
  ok(client.oauthDestroy.calledTwice);
});

add_task(async function testTokenTTL() {
  // This tests the TTL option passed into the method
  let fxa = await createMockFxA();
  let token = await fxa.getOAuthToken({ scope: "test-ttl", ttl: 1000 });
  equal(token, "token0-ttl-1000");
});