summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_dnr_webrequest.js
blob: 415ab42c5fd3cc3c8bbc69ff203a73f6618177db (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
"use strict";

add_setup(() => {
  Services.prefs.setBoolPref("extensions.manifestV3.enabled", true);
  Services.prefs.setBoolPref("extensions.dnr.enabled", true);
});

const server = createHttpServer({
  hosts: ["example.com", "redir"],
});
server.registerPathHandler("/never_reached", (req, res) => {
  Assert.ok(false, "Server should never have been reached");
});
server.registerPathHandler("/source", (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
});
server.registerPathHandler("/destination", (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
});

add_task(async function block_request_with_dnr() {
  async function background() {
    let onBeforeRequestPromise = new Promise(resolve => {
      browser.webRequest.onBeforeRequest.addListener(resolve, {
        urls: ["*://example.com/*"],
      });
    });
    await browser.declarativeNetRequest.updateSessionRules({
      addRules: [
        {
          id: 1,
          condition: { requestDomains: ["example.com"] },
          action: { type: "block" },
        },
      ],
    });

    await browser.test.assertRejects(
      fetch("http://example.com/never_reached"),
      "NetworkError when attempting to fetch resource.",
      "blocked by DNR rule"
    );
    // DNR is documented to take precedence over webRequest. We should still
    // receive the webRequest event, however.
    browser.test.log("Waiting for webRequest.onBeforeRequest...");
    await onBeforeRequestPromise;
    browser.test.log("Seen webRequest.onBeforeRequest!");

    browser.test.notifyPass();
  }
  let extension = ExtensionTestUtils.loadExtension({
    background,
    temporarilyInstalled: true, // Needed for granted_host_permissions
    allowInsecureRequests: true,
    manifest: {
      manifest_version: 3,
      granted_host_permissions: true,
      host_permissions: ["*://example.com/*"],
      permissions: ["declarativeNetRequest", "webRequest"],
    },
  });
  await extension.startup();
  await extension.awaitFinish();
  await extension.unload();
});

add_task(async function upgradeScheme_and_redirect_request_with_dnr() {
  async function background() {
    let onBeforeRequestSeen = [];
    browser.webRequest.onBeforeRequest.addListener(
      d => {
        onBeforeRequestSeen.push(d.url);
        // webRequest cancels, but DNR should actually be taking precedence.
        return { cancel: true };
      },
      { urls: ["*://example.com/*", "http://redir/here"] },
      ["blocking"]
    );
    await browser.declarativeNetRequest.updateSessionRules({
      addRules: [
        {
          id: 1,
          condition: { requestDomains: ["example.com"] },
          action: { type: "upgradeScheme" },
        },
        {
          id: 2,
          condition: { requestDomains: ["example.com"], urlFilter: "|https:*" },
          action: { type: "redirect", redirect: { url: "http://redir/here" } },
          // The upgradeScheme and redirect actions have equal precedence. To
          // make sure that the redirect action is executed when both rules
          // match, we assign a higher priority to the redirect action.
          priority: 2,
        },
      ],
    });

    await browser.test.assertRejects(
      fetch("http://example.com/never_reached"),
      "NetworkError when attempting to fetch resource.",
      "although initially redirected by DNR, ultimately blocked by webRequest"
    );
    // DNR is documented to take precedence over webRequest.
    // So we should actually see redirects according to the DNR rules, and
    // the webRequest listener should still be able to observe all requests.
    browser.test.assertDeepEq(
      [
        "http://example.com/never_reached",
        "https://example.com/never_reached",
        "http://redir/here",
      ],
      onBeforeRequestSeen,
      "Expected onBeforeRequest events"
    );

    browser.test.notifyPass();
  }
  let extension = ExtensionTestUtils.loadExtension({
    background,
    temporarilyInstalled: true, // Needed for granted_host_permissions
    manifest: {
      manifest_version: 3,
      granted_host_permissions: true,
      host_permissions: ["*://example.com/*", "*://redir/*"],
      permissions: [
        "declarativeNetRequest",
        "webRequest",
        "webRequestBlocking",
      ],
    },
  });
  await extension.startup();
  await extension.awaitFinish();
  await extension.unload();
});

add_task(async function block_request_with_webRequest_after_allow_with_dnr() {
  async function background() {
    let onBeforeRequestSeen = [];
    browser.webRequest.onBeforeRequest.addListener(
      d => {
        onBeforeRequestSeen.push(d.url);
        return { cancel: !d.url.includes("webRequestNoCancel") };
      },
      { urls: ["*://example.com/*"] },
      ["blocking"]
    );
    // All DNR actions that do not end up canceling/redirecting the request:
    await browser.declarativeNetRequest.updateSessionRules({
      addRules: [
        {
          id: 1,
          condition: { requestMethods: ["get"] },
          action: { type: "allow" },
        },
        {
          id: 2,
          condition: { requestMethods: ["put"] },
          action: {
            type: "modifyHeaders",
            requestHeaders: [{ operation: "set", header: "x", value: "y" }],
          },
        },
      ],
    });

    await browser.test.assertRejects(
      fetch("http://example.com/never_reached?1", { method: "get" }),
      "NetworkError when attempting to fetch resource.",
      "despite DNR 'allow' rule, still blocked by webRequest"
    );
    await browser.test.assertRejects(
      fetch("http://example.com/never_reached?2", { method: "put" }),
      "NetworkError when attempting to fetch resource.",
      "despite DNR 'modifyHeaders' rule, still blocked by webRequest"
    );
    // Just to rule out the request having been canceled by DNR instead of
    // webRequest, repeat the requests and verify that they succeed.
    await fetch("http://example.com/?webRequestNoCancel1", { method: "get" });
    await fetch("http://example.com/?webRequestNoCancel2", { method: "put" });

    browser.test.assertDeepEq(
      [
        "http://example.com/never_reached?1",
        "http://example.com/never_reached?2",
        "http://example.com/?webRequestNoCancel1",
        "http://example.com/?webRequestNoCancel2",
      ],
      onBeforeRequestSeen,
      "Expected onBeforeRequest events"
    );

    browser.test.notifyPass();
  }
  let extension = ExtensionTestUtils.loadExtension({
    background,
    temporarilyInstalled: true, // Needed for granted_host_permissions
    allowInsecureRequests: true,
    manifest: {
      manifest_version: 3,
      granted_host_permissions: true,
      host_permissions: ["*://example.com/*"],
      permissions: [
        "declarativeNetRequest",
        "webRequest",
        "webRequestBlocking",
      ],
    },
  });
  await extension.startup();
  await extension.awaitFinish();
  await extension.unload();
});

add_task(async function redirect_with_webRequest_after_failing_dnr_redirect() {
  async function background() {
    // Maximum length of a UTL is 1048576 (network.standard-url.max-length).
    const network_standard_url_max_length = 1048576;
    // updateSessionRules does some validation on the limit (as seen by
    // validate_action_redirect_transform in test_ext_dnr_session_rules.js),
    // but it is still possible to pass validation and fail in practice when
    // the existing URL + new component exceeds the limit.
    const VERY_LONG_STRING = "x".repeat(network_standard_url_max_length - 20);

    browser.webRequest.onBeforeRequest.addListener(
      d => {
        return { redirectUrl: "http://redir/destination?by-webrequest" };
      },
      { urls: ["*://example.com/*"] },
      ["blocking"]
    );
    await browser.declarativeNetRequest.updateSessionRules({
      addRules: [
        {
          id: 1,
          condition: { requestDomains: ["example.com"] },
          action: {
            type: "redirect",
            redirect: {
              transform: {
                host: "redir",
                path: "/destination",
                queryTransform: {
                  addOrReplaceParams: [
                    { key: "dnr", value: VERY_LONG_STRING, replaceOnly: true },
                  ],
                },
              },
            },
          },
        },
      ],
    });

    // Note: we are not expecting successful DNR redirects below, but in case
    // that ever changes (e.g. due to VERY_LONG_STRING not resulting in an
    // invalid URL), we will truncate the URL out of caution.
    // VERY_LONG_STRING consists of many 'X'. Shorten to avoid logspam.
    const shortx = s => s.replace(/x{10,}/g, xxx => `x{${xxx.length}}`);

    browser.test.assertEq(
      "http://redir/destination?1",
      shortx((await fetch("http://example.com/never_reached?1")).url),
      "Successful DNR redirect."
    );

    // DNR redirect failure is expected to be very rare, and only to occur when
    // an extension intentionally explores the boundaries of the DNR API. When
    // DNR fails, we fall back to allowing webRequest to take over.
    browser.test.assertEq(
      "http://redir/destination?by-webrequest",
      shortx((await fetch("http://example.com/source?dnr")).url),
      "When DNR fails, we fall back to webRequest redirect"
    );

    browser.test.notifyPass();
  }
  let extension = ExtensionTestUtils.loadExtension({
    background,
    temporarilyInstalled: true, // Needed for granted_host_permissions
    allowInsecureRequests: true,
    manifest: {
      manifest_version: 3,
      granted_host_permissions: true,
      host_permissions: ["*://example.com/*"],
      permissions: [
        "declarativeNetRequest",
        "webRequest",
        "webRequestBlocking",
      ],
    },
  });
  await extension.startup();
  await extension.awaitFinish();
  await extension.unload();
});