summaryrefslogtreecommitdiffstats
path: root/dom/push/test/xpcshell/test_permissions.js
blob: 1b3e3282bba9d4af9ce0fd49160e0f1f0c9c1a79 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const userAgentID = "2c43af06-ab6e-476a-adc4-16cbda54fb89";

let db;

function run_test() {
  do_get_profile();
  setPrefs({
    userAgentID,
  });

  db = PushServiceWebSocket.newPushDB();
  registerCleanupFunction(() => {
    return db.drop().then(_ => db.close());
  });

  run_next_test();
}

let unregisterDefers = {};

function promiseUnregister(keyID) {
  return new Promise(r => (unregisterDefers[keyID] = r));
}

function makePushPermission(url, capability) {
  return {
    QueryInterface: ChromeUtils.generateQI(["nsIPermission"]),
    capability: Ci.nsIPermissionManager[capability],
    expireTime: 0,
    expireType: Ci.nsIPermissionManager.EXPIRE_NEVER,
    principal: Services.scriptSecurityManager.createContentPrincipal(
      Services.io.newURI(url),
      {}
    ),
    type: "desktop-notification",
  };
}

function promiseObserverNotifications(topic, count) {
  let notifiedScopes = [];
  let subChangePromise = promiseObserverNotification(topic, (subject, data) => {
    notifiedScopes.push(data);
    return notifiedScopes.length == count;
  });
  return subChangePromise.then(_ => notifiedScopes.sort());
}

function promiseSubscriptionChanges(count) {
  return promiseObserverNotifications(
    PushServiceComponent.subscriptionChangeTopic,
    count
  );
}

function promiseSubscriptionModifications(count) {
  return promiseObserverNotifications(
    PushServiceComponent.subscriptionModifiedTopic,
    count
  );
}

function allExpired(...keyIDs) {
  return Promise.all(keyIDs.map(keyID => db.getByKeyID(keyID))).then(records =>
    records.every(record => record.isExpired())
  );
}

add_task(async function setUp() {
  // Active registration; quota should be reset to 16. Since the quota isn't
  // exposed to content, we shouldn't receive a subscription change event.
  await putTestRecord(db, "active-allow", "https://example.info/page/1", 8);

  // Expired registration; should be dropped.
  await putTestRecord(db, "expired-allow", "https://example.info/page/2", 0);

  // Active registration; should be expired when we change the permission
  // to "deny".
  await putTestRecord(
    db,
    "active-deny-changed",
    "https://example.xyz/page/1",
    16
  );

  // Two active registrations for a visited site. These will expire when we
  // add a "deny" permission.
  await putTestRecord(db, "active-deny-added-1", "https://example.net/ham", 16);
  await putTestRecord(
    db,
    "active-deny-added-2",
    "https://example.net/green",
    8
  );

  // An already-expired registration for a visited site. We shouldn't send an
  // `unregister` request for this one, but still receive an observer
  // notification when we restore permissions.
  await putTestRecord(db, "expired-deny-added", "https://example.net/eggs", 0);

  // A registration that should not be affected by permission list changes
  // because its quota is set to `Infinity`.
  await putTestRecord(db, "never-expires", "app://chrome/only", Infinity);

  // A registration that should be dropped when we clear the permission
  // list.
  await putTestRecord(db, "drop-on-clear", "https://example.edu/lonely", 16);

  let handshakeDone;
  let handshakePromise = new Promise(resolve => (handshakeDone = resolve));
  PushService.init({
    serverURI: "wss://push.example.org/",
    db,
    makeWebSocket(uri) {
      return new MockWebSocket(uri, {
        onHello(request) {
          this.serverSendMsg(
            JSON.stringify({
              messageType: "hello",
              status: 200,
              uaid: userAgentID,
            })
          );
          handshakeDone();
        },
        onUnregister(request) {
          let resolve = unregisterDefers[request.channelID];
          equal(
            typeof resolve,
            "function",
            "Dropped unexpected channel ID " + request.channelID
          );
          delete unregisterDefers[request.channelID];
          equal(
            request.code,
            202,
            "Expected permission revoked unregister reason"
          );
          resolve();
          this.serverSendMsg(
            JSON.stringify({
              messageType: "unregister",
              status: 200,
              channelID: request.channelID,
            })
          );
        },
        onACK(request) {},
      });
    },
  });
  await handshakePromise;
});

add_task(async function test_permissions_allow_added() {
  let subChangePromise = promiseSubscriptionChanges(1);

  await PushService._onPermissionChange(
    makePushPermission("https://example.info", "ALLOW_ACTION"),
    "added"
  );
  let notifiedScopes = await subChangePromise;

  deepEqual(
    notifiedScopes,
    ["https://example.info/page/2"],
    "Wrong scopes after adding allow"
  );

  let record = await db.getByKeyID("active-allow");
  equal(
    record.quota,
    16,
    "Should reset quota for active records after adding allow"
  );

  record = await db.getByKeyID("expired-allow");
  ok(!record, "Should drop expired records after adding allow");
});

add_task(async function test_permissions_allow_deleted() {
  let subModifiedPromise = promiseSubscriptionModifications(1);

  let unregisterPromise = promiseUnregister("active-allow");

  await PushService._onPermissionChange(
    makePushPermission("https://example.info", "ALLOW_ACTION"),
    "deleted"
  );

  await unregisterPromise;

  let notifiedScopes = await subModifiedPromise;
  deepEqual(
    notifiedScopes,
    ["https://example.info/page/1"],
    "Wrong scopes modified after deleting allow"
  );

  let record = await db.getByKeyID("active-allow");
  ok(record.isExpired(), "Should expire active record after deleting allow");
});

add_task(async function test_permissions_deny_added() {
  let subModifiedPromise = promiseSubscriptionModifications(2);

  let unregisterPromise = Promise.all([
    promiseUnregister("active-deny-added-1"),
    promiseUnregister("active-deny-added-2"),
  ]);

  await PushService._onPermissionChange(
    makePushPermission("https://example.net", "DENY_ACTION"),
    "added"
  );
  await unregisterPromise;

  let notifiedScopes = await subModifiedPromise;
  deepEqual(
    notifiedScopes,
    ["https://example.net/green", "https://example.net/ham"],
    "Wrong scopes modified after adding deny"
  );

  let isExpired = await allExpired("active-deny-added-1", "expired-deny-added");
  ok(isExpired, "Should expire all registrations after adding deny");
});

add_task(async function test_permissions_deny_deleted() {
  await PushService._onPermissionChange(
    makePushPermission("https://example.net", "DENY_ACTION"),
    "deleted"
  );

  let isExpired = await allExpired("active-deny-added-1", "expired-deny-added");
  ok(isExpired, "Should retain expired registrations after deleting deny");
});

add_task(async function test_permissions_allow_changed() {
  let subChangePromise = promiseSubscriptionChanges(3);

  await PushService._onPermissionChange(
    makePushPermission("https://example.net", "ALLOW_ACTION"),
    "changed"
  );

  let notifiedScopes = await subChangePromise;

  deepEqual(
    notifiedScopes,
    [
      "https://example.net/eggs",
      "https://example.net/green",
      "https://example.net/ham",
    ],
    "Wrong scopes after changing to allow"
  );

  let droppedRecords = await Promise.all([
    db.getByKeyID("active-deny-added-1"),
    db.getByKeyID("active-deny-added-2"),
    db.getByKeyID("expired-deny-added"),
  ]);
  ok(
    !droppedRecords.some(Boolean),
    "Should drop all expired registrations after changing to allow"
  );
});

add_task(async function test_permissions_deny_changed() {
  let subModifiedPromise = promiseSubscriptionModifications(1);

  let unregisterPromise = promiseUnregister("active-deny-changed");

  await PushService._onPermissionChange(
    makePushPermission("https://example.xyz", "DENY_ACTION"),
    "changed"
  );

  await unregisterPromise;

  let notifiedScopes = await subModifiedPromise;
  deepEqual(
    notifiedScopes,
    ["https://example.xyz/page/1"],
    "Wrong scopes modified after changing to deny"
  );

  let record = await db.getByKeyID("active-deny-changed");
  ok(record.isExpired(), "Should expire active record after changing to deny");
});

add_task(async function test_permissions_clear() {
  let subModifiedPromise = promiseSubscriptionModifications(3);

  deepEqual(
    await getAllKeyIDs(db),
    ["active-allow", "active-deny-changed", "drop-on-clear", "never-expires"],
    "Wrong records in database before clearing"
  );

  let unregisterPromise = Promise.all([
    promiseUnregister("active-allow"),
    promiseUnregister("active-deny-changed"),
    promiseUnregister("drop-on-clear"),
  ]);

  await PushService._onPermissionChange(null, "cleared");

  await unregisterPromise;

  let notifiedScopes = await subModifiedPromise;
  deepEqual(
    notifiedScopes,
    [
      "https://example.edu/lonely",
      "https://example.info/page/1",
      "https://example.xyz/page/1",
    ],
    "Wrong scopes modified after clearing registrations"
  );

  deepEqual(
    await getAllKeyIDs(db),
    ["never-expires"],
    "Unrestricted registrations should not be dropped"
  );
});