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
|
"use strict";
const url = SimpleTest.getTestFileURL("mockpushserviceparent.js");
const chromeScript = SpecialPowers.loadChromeScript(url);
/**
* Replaces `PushService.jsm` with a mock implementation that handles requests
* from the DOM API. This allows tests to simulate local errors and error
* reporting, bypassing the `PushService.jsm` machinery.
*/
async function replacePushService(mockService) {
chromeScript.addMessageListener("service-delivery-error", function (msg) {
mockService.reportDeliveryError(msg.messageId, msg.reason);
});
chromeScript.addMessageListener("service-request", function (msg) {
let promise;
try {
let handler = mockService[msg.name];
promise = Promise.resolve(handler(msg.params));
} catch (error) {
promise = Promise.reject(error);
}
promise.then(
result => {
chromeScript.sendAsyncMessage("service-response", {
id: msg.id,
result,
});
},
error => {
chromeScript.sendAsyncMessage("service-response", {
id: msg.id,
error,
});
}
);
});
await new Promise(resolve => {
chromeScript.addMessageListener("service-replaced", function onReplaced() {
chromeScript.removeMessageListener("service-replaced", onReplaced);
resolve();
});
chromeScript.sendAsyncMessage("service-replace");
});
}
async function restorePushService() {
await new Promise(resolve => {
chromeScript.addMessageListener("service-restored", function onRestored() {
chromeScript.removeMessageListener("service-restored", onRestored);
resolve();
});
chromeScript.sendAsyncMessage("service-restore");
});
}
let currentMockSocket = null;
/**
* Sets up a mock connection for the WebSocket backend. This only replaces
* the transport layer; `PushService.jsm` still handles DOM API requests,
* observes permission changes, writes to IndexedDB, and notifies service
* workers of incoming push messages.
*/
function setupMockPushSocket(mockWebSocket) {
currentMockSocket = mockWebSocket;
currentMockSocket._isActive = true;
chromeScript.sendAsyncMessage("socket-setup");
chromeScript.addMessageListener("socket-client-msg", function (msg) {
mockWebSocket.handleMessage(msg);
});
}
function teardownMockPushSocket() {
if (currentMockSocket) {
return new Promise(resolve => {
currentMockSocket._isActive = false;
chromeScript.addMessageListener("socket-server-teardown", resolve);
chromeScript.sendAsyncMessage("socket-teardown");
});
}
return Promise.resolve();
}
/**
* Minimal implementation of web sockets for use in testing. Forwards
* messages to a mock web socket in the parent process that is used
* by the push service.
*/
class MockWebSocket {
// Default implementation to make the push server work minimally.
// Override methods to implement custom functionality.
constructor() {
this.userAgentID = "8e1c93a9-139b-419c-b200-e715bb1e8ce8";
this.registerCount = 0;
// We only allow one active mock web socket to talk to the parent.
// This flag is used to keep track of which mock web socket is active.
this._isActive = false;
}
onHello(request) {
this.serverSendMsg(
JSON.stringify({
messageType: "hello",
uaid: this.userAgentID,
status: 200,
use_webpush: true,
})
);
}
onRegister(request) {
this.serverSendMsg(
JSON.stringify({
messageType: "register",
uaid: this.userAgentID,
channelID: request.channelID,
status: 200,
pushEndpoint: "https://example.com/endpoint/" + this.registerCount++,
})
);
}
onUnregister(request) {
this.serverSendMsg(
JSON.stringify({
messageType: "unregister",
channelID: request.channelID,
status: 200,
})
);
}
onAck(request) {
// Do nothing.
}
handleMessage(msg) {
let request = JSON.parse(msg);
let messageType = request.messageType;
switch (messageType) {
case "hello":
this.onHello(request);
break;
case "register":
this.onRegister(request);
break;
case "unregister":
this.onUnregister(request);
break;
case "ack":
this.onAck(request);
break;
default:
throw new Error("Unexpected message: " + messageType);
}
}
serverSendMsg(msg) {
if (this._isActive) {
chromeScript.sendAsyncMessage("socket-server-msg", msg);
}
}
}
// Remove permissions and prefs when the test finishes.
SimpleTest.registerCleanupFunction(async function () {
await new Promise(resolve => SpecialPowers.flushPermissions(resolve));
await SpecialPowers.flushPrefEnv();
await restorePushService();
await teardownMockPushSocket();
});
function setPushPermission(allow) {
let permissions = [
{ type: "desktop-notification", allow, context: document },
];
if (isXOrigin) {
// We need to add permission for the xorigin tests. In xorigin tests, the
// test page will be run under third-party context, so we need to use
// partitioned principal to add the permission.
let partitionedPrincipal =
SpecialPowers.wrap(document).partitionedPrincipal;
permissions.push({
type: "desktop-notification",
allow,
context: {
url: partitionedPrincipal.originNoSuffix,
originAttributes: {
partitionKey: partitionedPrincipal.originAttributes.partitionKey,
},
},
});
}
return SpecialPowers.pushPermissions(permissions);
}
function setupPrefs() {
return SpecialPowers.pushPrefEnv({
set: [
["dom.push.enabled", true],
["dom.push.connection.enabled", true],
["dom.push.maxRecentMessageIDsPerSubscription", 0],
["dom.serviceWorkers.exemptFromPerDomainMax", true],
["dom.serviceWorkers.enabled", true],
["dom.serviceWorkers.testing.enabled", true],
],
});
}
async function setupPrefsAndReplaceService(mockService) {
await replacePushService(mockService);
await setupPrefs();
}
function setupPrefsAndMockSocket(mockSocket) {
setupMockPushSocket(mockSocket);
return setupPrefs();
}
function injectControlledFrame(target = document.body) {
return new Promise(function (res, rej) {
var iframe = document.createElement("iframe");
iframe.src = "/tests/dom/push/test/frame.html";
var controlledFrame = {
remove() {
target.removeChild(iframe);
iframe = null;
},
waitOnWorkerMessage(type) {
return iframe
? iframe.contentWindow.waitOnWorkerMessage(type)
: Promise.reject(new Error("Frame removed from document"));
},
innerWindowId() {
return SpecialPowers.wrap(iframe).browsingContext.currentWindowContext
.innerWindowId;
},
};
iframe.onload = () => res(controlledFrame);
target.appendChild(iframe);
});
}
function sendRequestToWorker(request) {
return navigator.serviceWorker.ready.then(registration => {
return new Promise((resolve, reject) => {
var channel = new MessageChannel();
channel.port1.onmessage = e => {
(e.data.error ? reject : resolve)(e.data);
};
registration.active.postMessage(request, [channel.port2]);
});
});
}
function waitForActive(swr) {
let sw = swr.installing || swr.waiting || swr.active;
return new Promise(resolve => {
if (sw.state === "activated") {
resolve(swr);
return;
}
sw.addEventListener("statechange", function onStateChange(evt) {
if (sw.state === "activated") {
sw.removeEventListener("statechange", onStateChange);
resolve(swr);
}
});
});
}
function base64UrlDecode(s) {
s = s.replace(/-/g, "+").replace(/_/g, "/");
// Replace padding if it was stripped by the sender.
// See http://tools.ietf.org/html/rfc4648#section-4
switch (s.length % 4) {
case 0:
break; // No pad chars in this case
case 2:
s += "==";
break; // Two pad chars
case 3:
s += "=";
break; // One pad char
default:
throw new Error("Illegal base64url string!");
}
// With correct padding restored, apply the standard base64 decoder
var decoded = atob(s);
var array = new Uint8Array(new ArrayBuffer(decoded.length));
for (var i = 0; i < decoded.length; i++) {
array[i] = decoded.charCodeAt(i);
}
return array;
}
|