summaryrefslogtreecommitdiffstats
path: root/netwerk/test/browser/browser_103_redirect_from_server.js
blob: 0357d11516a0de8c601173cd6c51d15678ee8680 (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

Services.prefs.setBoolPref("network.early-hints.enabled", true);

registerCleanupFunction(function () {
  Services.prefs.clearUserPref("network.early-hints.enabled");
});

// This function tests Early Hint responses before and in between HTTP redirects.
//
// Arguments:
// - name: String identifying the test case for easier parsing in the log
// - chain and destination: defines the redirect chain, see example below
//                          note: ALL preloaded urls must be image urls
// - expected: number of normal, cancelled and completed hinted responses.
//
// # Example
// The parameter values of
// ```
// chain = [
//  {link:"https://link1", host:"https://host1.com"},
//  {link:"https://link2", host:"https://host2.com"},
// ]
// ```
// and `destination = "https://host3.com/page.html" would result in the
// following HTTP exchange (simplified):
//
// ```
// > GET https://host1.com/redirect?something1
//
// < 103 Early Hints
// < Link: <https://link1>;rel=preload;as=image
// <
// < 307 Temporary Redirect
// < Location: https://host2.com/redirect?something2
// <
//
// > GET https://host2.com/redirect?something2
//
// < 103 Early Hints
// < Link: <https://link2>;rel=preload;as=image
// <
// < 307 Temporary Redirect
// < Location: https://host3.com/page.html
// <
//
// > GET https://host3.com/page.html
//
// < [...] Result depends on the final page
// ```
//
// Legend:
// * `>` indicates a request going from client to server
// * `<` indicates a response going from server to client
// * all lines are terminated with a `\r\n`
//
async function test_hint_redirect(
  name,
  chain,
  destination,
  hint_destination,
  expected
) {
  // pass the full redirect chain as a url parameter. Each redirect is handled
  // by `early_hint_redirect_html.sjs` which url-decodes the query string and
  // redirects to the result
  let links = [];
  let url = destination;
  for (let i = chain.length - 1; i >= 0; i--) {
    let qp = new URLSearchParams();
    if (chain[i].link != "") {
      qp.append("link", "<" + chain[i].link + ">;rel=preload;as=image");
      links.push(chain[i].link);
    }
    qp.append("location", url);

    url = `${
      chain[i].host
    }/browser/netwerk/test/browser/early_hint_redirect_html.sjs?${qp.toString()}`;
  }
  if (hint_destination != "") {
    links.push(hint_destination);
  }

  // reset the count
  let headers = new Headers();
  headers.append("X-Early-Hint-Count-Start", "");
  await fetch(
    "https://example.com/browser/netwerk/test/browser/early_hint_pixel_count.sjs",
    { headers }
  );

  // main request and all other must get their respective OnStopRequest
  let numRequestRemaining =
    expected.normal + expected.hinted + expected.cancelled;
  let observed = {
    hinted: 0,
    normal: 0,
    cancelled: 0,
  };
  // store channelIds
  let observedChannelIds = [];
  let callback;
  let promise = new Promise(resolve => {
    callback = resolve;
  });
  if (numRequestRemaining > 0) {
    let observer = {
      QueryInterface: ChromeUtils.generateQI(["nsIObserver"]),
      observe(aSubject, aTopic, aData) {
        aSubject.QueryInterface(Ci.nsIIdentChannel);
        let id = aSubject.channelId;
        if (observedChannelIds.includes(id)) {
          return;
        }
        aSubject.QueryInterface(Ci.nsIRequest);
        dump("Observer aSubject.name " + aSubject.name + "\n");
        if (aTopic == "http-on-stop-request" && links.includes(aSubject.name)) {
          if (aSubject.status == Cr.NS_ERROR_ABORT) {
            observed.cancelled += 1;
          } else {
            aSubject.QueryInterface(Ci.nsIHttpChannel);
            let initiator = "";
            try {
              initiator = aSubject.getRequestHeader("X-Moz");
            } catch {}
            if (initiator == "early hint") {
              observed.hinted += 1;
            } else {
              observed.normal += 1;
            }
          }
          observedChannelIds.push(id);
          numRequestRemaining -= 1;
          dump("Observer numRequestRemaining " + numRequestRemaining + "\n");
        }
        if (numRequestRemaining == 0) {
          Services.obs.removeObserver(observer, "http-on-stop-request");
          callback();
        }
      },
    };
    Services.obs.addObserver(observer, "http-on-stop-request");
  } else {
    callback();
  }

  await BrowserTestUtils.withNewTab(
    {
      gBrowser,
      url,
      waitForLoad: true,
    },
    async function () {}
  );

  // wait until all requests are stopped, especially the cancelled ones
  await promise;

  let got = await fetch(
    "https://example.com/browser/netwerk/test/browser/early_hint_pixel_count.sjs"
  ).then(response => response.json());

  // stringify to pretty print assert output
  let g = JSON.stringify(observed);
  let e = JSON.stringify(expected);
  Assert.equal(
    expected.normal,
    observed.normal,
    `${name} normal observed from client expected ${expected.normal} (${e}) got ${observed.normal} (${g})`
  );
  Assert.equal(
    expected.hinted,
    observed.hinted,
    `${name} hinted observed from client expected ${expected.hinted} (${e})  got ${observed.hinted} (${g})`
  );
  Assert.equal(
    expected.cancelled,
    observed.cancelled,
    `${name} cancelled observed from client expected ${expected.cancelled} (${e})  got ${observed.cancelled} (${g})`
  );

  // each cancelled request might be cancelled after the request was already
  // made. Allow cancelled responses to count towards the hinted to avoid
  // intermittent test failures.
  Assert.ok(
    expected.hinted <= got.hinted &&
      got.hinted <= expected.hinted + expected.cancelled,
    `${name}: unexpected amount of hinted request made got ${
      got.hinted
    }, expected between ${expected.hinted} and ${
      expected.hinted + expected.cancelled
    }`
  );
  Assert.ok(
    got.normal == expected.normal,
    `${name}: unexpected amount of normal request made expected ${expected.normal}, got ${got.normal}`
  );
  Assert.equal(numRequestRemaining, 0, "Requests remaining");
}

add_task(async function double_redirect_cross_origin() {
  await test_hint_redirect(
    "double_redirect_cross_origin_both_hints",
    [
      {
        link: "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
        host: "https://example.com/",
      },
      {
        link: "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
        host: "https://example.net",
      },
    ],
    "https://example.org/browser/netwerk/test/browser/early_hint_asset_html.sjs?as=image&hinted=1",
    "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
    { hinted: 1, normal: 0, cancelled: 2 }
  );
  await test_hint_redirect(
    "double_redirect_second_hint",
    [
      {
        link: "",
        host: "https://example.com/",
      },
      {
        link: "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
        host: "https://example.net",
      },
    ],
    "https://example.org/browser/netwerk/test/browser/early_hint_asset_html.sjs?as=image&hinted=1",
    "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
    { hinted: 1, normal: 0, cancelled: 1 }
  );
  await test_hint_redirect(
    "double_redirect_first_hint",
    [
      {
        link: "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
        host: "https://example.com/",
      },
      {
        link: "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
        host: "https://example.net",
      },
    ],
    "https://example.org/browser/netwerk/test/browser/early_hint_asset_html.sjs?as=image&hinted=0",
    "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
    { hinted: 0, normal: 1, cancelled: 2 }
  );
});

add_task(async function redirect_cross_origin() {
  await test_hint_redirect(
    "redirect_cross_origin_start_second_preload",
    [
      {
        link: "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
        host: "https://example.net",
      },
    ],
    "https://example.org/browser/netwerk/test/browser/early_hint_asset_html.sjs?as=image&hinted=1",
    "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
    { hinted: 1, normal: 0, cancelled: 1 }
  );
  await test_hint_redirect(
    "redirect_cross_origin_dont_use_first_preload",
    [
      {
        link: "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image&a",
        host: "https://example.net",
      },
    ],
    "https://example.org/browser/netwerk/test/browser/early_hint_asset_html.sjs?as=image&hinted=0",
    "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
    { hinted: 0, normal: 1, cancelled: 1 }
  );
});

add_task(async function redirect_same_origin() {
  await test_hint_redirect(
    "hint_before_redirect_same_origin",
    [
      {
        link: "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
        host: "https://example.org",
      },
    ],
    "https://example.org/browser/netwerk/test/browser/early_hint_asset_html.sjs?as=image&hinted=1",
    "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
    { hinted: 1, normal: 0, cancelled: 0 }
  );
  await test_hint_redirect(
    "hint_after_redirect_same_origin",
    [
      {
        link: "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
        host: "https://example.org",
      },
    ],
    "https://example.org/browser/netwerk/test/browser/early_hint_asset_html.sjs?as=image&hinted=0",
    "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
    { hinted: 1, normal: 0, cancelled: 0 }
  );
  await test_hint_redirect(
    "hint_after_redirect_same_origin",
    [
      {
        link: "",
        host: "https://example.org",
      },
    ],
    "https://example.org/browser/netwerk/test/browser/early_hint_asset_html.sjs?as=image&hinted=1",
    "https://example.org/browser/netwerk/test/browser/early_hint_asset.sjs?as=image",
    { hinted: 1, normal: 0, cancelled: 0 }
  );
});