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

'use strict';

var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;

Cu.import('resource://gre/modules/XPCOMUtils.jsm');
Cu.import('resource://gre/modules/Services.jsm');
Cu.import('resource://gre/modules/Task.jsm');
Cu.import('resource://gre/modules/Timer.jsm');
Cu.import('resource://gre/modules/Promise.jsm');
Cu.import('resource://gre/modules/Preferences.jsm');
Cu.import('resource://gre/modules/PlacesUtils.jsm');
Cu.import('resource://gre/modules/ObjectUtils.jsm');

XPCOMUtils.defineLazyModuleGetter(this, 'PlacesTestUtils',
                                  'resource://testing-common/PlacesTestUtils.jsm');
XPCOMUtils.defineLazyServiceGetter(this, 'PushServiceComponent',
                                   '@mozilla.org/push/Service;1', 'nsIPushService');

const serviceExports = Cu.import('resource://gre/modules/PushService.jsm', {});
const servicePrefs = new Preferences('dom.push.');

const WEBSOCKET_CLOSE_GOING_AWAY = 1001;

const MS_IN_ONE_DAY = 24 * 60 * 60 * 1000;

var isParent = Cc['@mozilla.org/xre/runtime;1']
                 .getService(Ci.nsIXULRuntime).processType ==
                 Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;

// Stop and clean up after the PushService.
Services.obs.addObserver(function observe(subject, topic, data) {
  Services.obs.removeObserver(observe, topic, false);
  serviceExports.PushService.uninit();
  // Occasionally, `profile-change-teardown` and `xpcom-shutdown` will fire
  // before the PushService and AlarmService finish writing to IndexedDB. This
  // causes spurious errors and crashes, so we spin the event loop to let the
  // writes finish.
  let done = false;
  setTimeout(() => done = true, 1000);
  let thread = Services.tm.mainThread;
  while (!done) {
    try {
      thread.processNextEvent(true);
    } catch (e) {
      Cu.reportError(e);
    }
  }
}, 'profile-change-net-teardown', false);

/**
 * Gates a function so that it is called only after the wrapper is called a
 * given number of times.
 *
 * @param {Number} times The number of wrapper calls before |func| is called.
 * @param {Function} func The function to gate.
 * @returns {Function} The gated function wrapper.
 */
function after(times, func) {
  return function afterFunc() {
    if (--times <= 0) {
      return func.apply(this, arguments);
    }
  };
}

/**
 * Defers one or more callbacks until the next turn of the event loop. Multiple
 * callbacks are executed in order.
 *
 * @param {Function[]} callbacks The callbacks to execute. One callback will be
 *  executed per tick.
 */
function waterfall(...callbacks) {
  callbacks.reduce((promise, callback) => promise.then(() => {
    callback();
  }), Promise.resolve()).catch(Cu.reportError);
}

/**
 * Waits for an observer notification to fire.
 *
 * @param {String} topic The notification topic.
 * @returns {Promise} A promise that fulfills when the notification is fired.
 */
function promiseObserverNotification(topic, matchFunc) {
  return new Promise((resolve, reject) => {
    Services.obs.addObserver(function observe(subject, topic, data) {
      let matches = typeof matchFunc != 'function' || matchFunc(subject, data);
      if (!matches) {
        return;
      }
      Services.obs.removeObserver(observe, topic, false);
      resolve({subject, data});
    }, topic, false);
  });
}

/**
 * Wraps an object in a proxy that traps property gets and returns stubs. If
 * the stub is a function, the original value will be passed as the first
 * argument. If the original value is a function, the proxy returns a wrapper
 * that calls the stub; otherwise, the stub is called as a getter.
 *
 * @param {Object} target The object to wrap.
 * @param {Object} stubs An object containing stubbed values and functions.
 * @returns {Proxy} A proxy that returns stubs for property gets.
 */
function makeStub(target, stubs) {
  return new Proxy(target, {
    get(target, property) {
      if (!stubs || typeof stubs != 'object' || !(property in stubs)) {
        return target[property];
      }
      let stub = stubs[property];
      if (typeof stub != 'function') {
        return stub;
      }
      let original = target[property];
      if (typeof original != 'function') {
        return stub.call(this, original);
      }
      return function callStub(...params) {
        return stub.call(this, original, ...params);
      };
    }
  });
}

/**
 * Sets default PushService preferences. All pref names are prefixed with
 * `dom.push.`; any additional preferences will override the defaults.
 *
 * @param {Object} [prefs] Additional preferences to set.
 */
function setPrefs(prefs = {}) {
  let defaultPrefs = Object.assign({
    loglevel: 'all',
    serverURL: 'wss://push.example.org',
    'connection.enabled': true,
    userAgentID: '',
    enabled: true,
    // Defaults taken from /modules/libpref/init/all.js.
    requestTimeout: 10000,
    retryBaseInterval: 5000,
    pingInterval: 30 * 60 * 1000,
    // Misc. defaults.
    'http2.maxRetries': 2,
    'http2.retryInterval': 500,
    'http2.reset_retry_count_after_ms': 60000,
    maxQuotaPerSubscription: 16,
    quotaUpdateDelay: 3000,
    'testing.notifyWorkers': false,
  }, prefs);
  for (let pref in defaultPrefs) {
    servicePrefs.set(pref, defaultPrefs[pref]);
  }
}

function compareAscending(a, b) {
  return a > b ? 1 : a < b ? -1 : 0;
}

/**
 * Creates a mock WebSocket object that implements a subset of the
 * nsIWebSocketChannel interface used by the PushService.
 *
 * The given protocol handlers are invoked for each Simple Push command sent
 * by the PushService. The ping handler is optional; all others will throw if
 * the PushService sends a command for which no handler is registered.
 *
 * All nsIWebSocketListener methods will be called asynchronously.
 * serverSendMsg() and serverClose() can be used to respond to client messages
 * and close the "server" end of the connection, respectively.
 *
 * @param {nsIURI} originalURI The original WebSocket URL.
 * @param {Function} options.onHello The "hello" handshake command handler.
 * @param {Function} options.onRegister The "register" command handler.
 * @param {Function} options.onUnregister The "unregister" command handler.
 * @param {Function} options.onACK The "ack" command handler.
 * @param {Function} [options.onPing] An optional ping handler.
 */
function MockWebSocket(originalURI, handlers = {}) {
  this._originalURI = originalURI;
  this._onHello = handlers.onHello;
  this._onRegister = handlers.onRegister;
  this._onUnregister = handlers.onUnregister;
  this._onACK = handlers.onACK;
  this._onPing = handlers.onPing;
}

MockWebSocket.prototype = {
  _originalURI: null,
  _onHello: null,
  _onRegister: null,
  _onUnregister: null,
  _onACK: null,
  _onPing: null,

  _listener: null,
  _context: null,

  QueryInterface: XPCOMUtils.generateQI([
    Ci.nsISupports,
    Ci.nsIWebSocketChannel
  ]),

  get originalURI() {
    return this._originalURI;
  },

  asyncOpen(uri, origin, windowId, listener, context) {
    this._listener = listener;
    this._context = context;
    waterfall(() => this._listener.onStart(this._context));
  },

  _handleMessage(msg) {
    let messageType, request;
    if (msg == '{}') {
      request = {};
      messageType = 'ping';
    } else {
      request = JSON.parse(msg);
      messageType = request.messageType;
    }
    switch (messageType) {
    case 'hello':
      if (typeof this._onHello != 'function') {
        throw new Error('Unexpected handshake request');
      }
      this._onHello(request);
      break;

    case 'register':
      if (typeof this._onRegister != 'function') {
        throw new Error('Unexpected register request');
      }
      this._onRegister(request);
      break;

    case 'unregister':
      if (typeof this._onUnregister != 'function') {
        throw new Error('Unexpected unregister request');
      }
      this._onUnregister(request);
      break;

    case 'ack':
      if (typeof this._onACK != 'function') {
        throw new Error('Unexpected acknowledgement');
      }
      this._onACK(request);
      break;

    case 'ping':
      if (typeof this._onPing == 'function') {
        this._onPing(request);
      } else {
        // Echo ping packets.
        this.serverSendMsg('{}');
      }
      break;

    default:
      throw new Error('Unexpected message: ' + messageType);
    }
  },

  sendMsg(msg) {
    this._handleMessage(msg);
  },

  close(code, reason) {
    waterfall(() => this._listener.onStop(this._context, Cr.NS_OK));
  },

  /**
   * Responds with the given message, calling onMessageAvailable() and
   * onAcknowledge() synchronously. Throws if the message is not a string.
   * Used by the tests to respond to client commands.
   *
   * @param {String} msg The message to send to the client.
   */
  serverSendMsg(msg) {
    if (typeof msg != 'string') {
      throw new Error('Invalid response message');
    }
    waterfall(
      () => this._listener.onMessageAvailable(this._context, msg),
      () => this._listener.onAcknowledge(this._context, 0)
    );
  },

  /**
   * Closes the server end of the connection, calling onServerClose()
   * followed by onStop(). Used to test abrupt connection termination.
   *
   * @param {Number} [statusCode] The WebSocket connection close code.
   * @param {String} [reason] The connection close reason.
   */
  serverClose(statusCode, reason = '') {
    if (!isFinite(statusCode)) {
      statusCode = WEBSOCKET_CLOSE_GOING_AWAY;
    }
    waterfall(
      () => this._listener.onServerClose(this._context, statusCode, reason),
      () => this._listener.onStop(this._context, Cr.NS_BASE_STREAM_CLOSED)
    );
  },

  serverInterrupt(result = Cr.NS_ERROR_NET_RESET) {
    waterfall(() => this._listener.onStop(this._context, result));
  },
};

var setUpServiceInParent = Task.async(function* (service, db) {
  if (!isParent) {
    return;
  }

  let userAgentID = 'ce704e41-cb77-4206-b07b-5bf47114791b';
  setPrefs({
    userAgentID: userAgentID,
  });

  yield db.put({
    channelID: '6e2814e1-5f84-489e-b542-855cc1311f09',
    pushEndpoint: 'https://example.org/push/get',
    scope: 'https://example.com/get/ok',
    originAttributes: '',
    version: 1,
    pushCount: 10,
    lastPush: 1438360548322,
    quota: 16,
  });
  yield db.put({
    channelID: '3a414737-2fd0-44c0-af05-7efc172475fc',
    pushEndpoint: 'https://example.org/push/unsub',
    scope: 'https://example.com/unsub/ok',
    originAttributes: '',
    version: 2,
    pushCount: 10,
    lastPush: 1438360848322,
    quota: 4,
  });
  yield db.put({
    channelID: 'ca3054e8-b59b-4ea0-9c23-4a3c518f3161',
    pushEndpoint: 'https://example.org/push/stale',
    scope: 'https://example.com/unsub/fail',
    originAttributes: '',
    version: 3,
    pushCount: 10,
    lastPush: 1438362348322,
    quota: 1,
  });

  service.init({
    serverURI: 'wss://push.example.org/',
    db: makeStub(db, {
      put(prev, record) {
        if (record.scope == 'https://example.com/sub/fail') {
          return Promise.reject('synergies not aligned');
        }
        return prev.call(this, record);
      },
      delete: function(prev, channelID) {
        if (channelID == 'ca3054e8-b59b-4ea0-9c23-4a3c518f3161') {
          return Promise.reject('splines not reticulated');
        }
        return prev.call(this, channelID);
      },
      getByIdentifiers(prev, identifiers) {
        if (identifiers.scope == 'https://example.com/get/fail') {
          return Promise.reject('qualia unsynchronized');
        }
        return prev.call(this, identifiers);
      },
    }),
    makeWebSocket(uri) {
      return new MockWebSocket(uri, {
        onHello(request) {
          this.serverSendMsg(JSON.stringify({
            messageType: 'hello',
            uaid: userAgentID,
            status: 200,
          }));
        },
        onRegister(request) {
          if (request.key) {
            let appServerKey = new Uint8Array(
              ChromeUtils.base64URLDecode(request.key, {
                padding: "require",
              })
            );
            equal(appServerKey.length, 65, 'Wrong app server key length');
            equal(appServerKey[0], 4, 'Wrong app server key format');
          }
          this.serverSendMsg(JSON.stringify({
            messageType: 'register',
            uaid: userAgentID,
            channelID: request.channelID,
            status: 200,
            pushEndpoint: 'https://example.org/push/' + request.channelID,
          }));
        },
        onUnregister(request) {
          this.serverSendMsg(JSON.stringify({
            messageType: 'unregister',
            channelID: request.channelID,
            status: 200,
          }));
        },
      });
    },
  });
});

var tearDownServiceInParent = Task.async(function* (db) {
  if (!isParent) {
    return;
  }

  let record = yield db.getByIdentifiers({
    scope: 'https://example.com/sub/ok',
    originAttributes: '',
  });
  ok(record.pushEndpoint.startsWith('https://example.org/push'),
    'Wrong push endpoint in subscription record');

  record = yield db.getByIdentifiers({
    scope: 'https://example.net/scope/1',
    originAttributes: ChromeUtils.originAttributesToSuffix(
      { appId: 1, inIsolatedMozBrowser: true }),
  });
  ok(record.pushEndpoint.startsWith('https://example.org/push'),
    'Wrong push endpoint in app record');

  record = yield db.getByKeyID('3a414737-2fd0-44c0-af05-7efc172475fc');
  ok(!record, 'Unsubscribed record should not exist');
});

function putTestRecord(db, keyID, scope, quota) {
  return db.put({
    channelID: keyID,
    pushEndpoint: 'https://example.org/push/' + keyID,
    scope: scope,
    pushCount: 0,
    lastPush: 0,
    version: null,
    originAttributes: '',
    quota: quota,
    systemRecord: quota == Infinity,
  });
}

function getAllKeyIDs(db) {
  return db.getAllKeyIDs().then(records =>
    records.map(record => record.keyID).sort(compareAscending)
  );
}