gosub-sonar 0.3.0

Browser-agnostic priority-scheduled HTTP/HTTPS fetching library
Documentation
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! Computing the `Origin` header and the `Sec-Fetch-*` fetch metadata headers ([spec]).
//!
//! The `Sec-Fetch-*` headers describe how a request came about: what the resource is for
//! ([`Sec-Fetch-Dest`]), the request mode ([`Sec-Fetch-Mode`]), how the target relates to the
//! initiating site ([`Sec-Fetch-Site`]), and whether a user asked for it ([`Sec-Fetch-User`]).
//! `Origin` names the initiator on requests with side effects (non-GET) and on CORS requests.
//!
//! Set [`FetchRequest::destination`] and [`FetchRequest::mode`] to describe the request;
//! [`FetchRequest::origin`] is the initiating origin behind `Sec-Fetch-Site` and `Origin`.
//! The fetcher owns these headers and overwrites hand-set values, matching the forbidden
//! header name rules in browsers.
//!
//! Like `Referer`, the values are recomputed at every redirect hop. `Sec-Fetch-Site` can only
//! degrade across a chain, and `Origin` becomes the literal `null` once the chain redirects
//! away from an origin the request had already left.
//!
//! `Sec-Fetch-Site: same-site` means same scheme and same registrable domain (eTLD+1, per the
//! public suffix list), so `a.example.com` → `b.example.com` is same-site while
//! `a.github.io` → `b.github.io` is not. Same host on another port is same-site too, since a
//! site has no port.
//!
//! Inert on `wasm32`: these are forbidden header names there, so the browser strips ours and
//! applies its own.
//!
//! [spec]: https://w3c.github.io/webappsec-fetch-metadata/
//! [`Sec-Fetch-Dest`]: RequestDestination
//! [`Sec-Fetch-Mode`]: RequestMode
//! [`Sec-Fetch-Site`]: SecFetchSite
//! [`Sec-Fetch-User`]: crate::net::types::Initiator
//! [`FetchRequest::destination`]: crate::net::types::FetchRequest::destination
//! [`FetchRequest::mode`]: crate::net::types::FetchRequest::mode
//! [`FetchRequest::origin`]: crate::net::types::FetchRequest::origin

use crate::net::mixed_content::is_potentially_trustworthy;
use crate::net::referrer::ReferrerPolicy;
use http::{header, HeaderMap, HeaderValue, Method};
use url::{Host, Origin, Url};

static SEC_FETCH_DEST: header::HeaderName = header::HeaderName::from_static("sec-fetch-dest");
static SEC_FETCH_MODE: header::HeaderName = header::HeaderName::from_static("sec-fetch-mode");
static SEC_FETCH_SITE: header::HeaderName = header::HeaderName::from_static("sec-fetch-site");
static SEC_FETCH_USER: header::HeaderName = header::HeaderName::from_static("sec-fetch-user");

/// What the fetched resource will be used as — the request's *destination* ([Fetch §2.2.5]),
/// sent as `Sec-Fetch-Dest`.
///
/// [Fetch §2.2.5]: https://fetch.spec.whatwg.org/#concept-request-destination
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
pub enum RequestDestination {
    /// No particular destination (the default — e.g. `fetch()`, beacons, downloads).
    /// Sent as the token `empty`.
    #[default]
    Empty,
    /// `<audio>`
    Audio,
    /// `audioWorklet.addModule()`
    AudioWorklet,
    /// A top-level navigation
    Document,
    /// `<embed>`
    Embed,
    /// `@font-face`
    Font,
    /// `<frame>` navigation
    Frame,
    /// `<iframe>` navigation
    Iframe,
    /// `<img>`, `background-image`, favicon, …
    Image,
    /// JSON module import
    Json,
    /// `<link rel="manifest">`
    Manifest,
    /// `<object>`
    Object,
    /// `CSS.paintWorklet.addModule()`
    PaintWorklet,
    /// CSP or other reporting
    Report,
    /// `<script>`, module imports, `importScripts()`
    Script,
    /// Service worker registration
    ServiceWorker,
    /// `new SharedWorker()`
    SharedWorker,
    /// `<link rel="stylesheet">`, `@import`
    Style,
    /// `<track>`
    Track,
    /// `<video>`
    Video,
    /// `new Worker()`
    Worker,
    /// `<?xml-stylesheet?>` XSLT
    Xslt,
}

impl RequestDestination {
    /// The token sent in `Sec-Fetch-Dest`. The empty destination is sent as `empty`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Empty => "empty",
            Self::Audio => "audio",
            Self::AudioWorklet => "audioworklet",
            Self::Document => "document",
            Self::Embed => "embed",
            Self::Font => "font",
            Self::Frame => "frame",
            Self::Iframe => "iframe",
            Self::Image => "image",
            Self::Json => "json",
            Self::Manifest => "manifest",
            Self::Object => "object",
            Self::PaintWorklet => "paintworklet",
            Self::Report => "report",
            Self::Script => "script",
            Self::ServiceWorker => "serviceworker",
            Self::SharedWorker => "sharedworker",
            Self::Style => "style",
            Self::Track => "track",
            Self::Video => "video",
            Self::Worker => "worker",
            Self::Xslt => "xslt",
        }
    }
}

/// How the request relates to cross-origin rules — the request's *mode* ([Fetch §2.2.5]),
/// sent as `Sec-Fetch-Mode`.
///
/// This crate does not enforce CORS; the mode only shapes the `Sec-Fetch-Mode` and `Origin`
/// headers so the server sees the same request a browser would send.
///
/// [Fetch §2.2.5]: https://fetch.spec.whatwg.org/#concept-request-mode
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
pub enum RequestMode {
    /// Cross-origin allowed without the response being readable cross-origin — how browsers
    /// load `<img>`, `<script>`, and most other markup-initiated subresources. The default.
    #[default]
    NoCors,
    /// A CORS request (`fetch()`, `XMLHttpRequest`, `crossorigin` attributes). Sends `Origin`
    /// on cross-origin requests.
    Cors,
    /// Only same-origin fetches make sense for this request.
    SameOrigin,
    /// A navigation (document, frame, or iframe load). Enables `Sec-Fetch-User`.
    Navigate,
    /// A WebSocket handshake. Always sends `Origin`.
    Websocket,
}

impl RequestMode {
    /// The token sent in `Sec-Fetch-Mode`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NoCors => "no-cors",
            Self::Cors => "cors",
            Self::SameOrigin => "same-origin",
            Self::Navigate => "navigate",
            Self::Websocket => "websocket",
        }
    }
}

/// The relation between the initiating origin and the request target, sent as `Sec-Fetch-Site`.
///
/// Ordered so that [`min`](Ord::min) degrades correctly across a redirect chain:
/// `same-origin` > `same-site` > `cross-site`.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub enum SecFetchSite {
    /// The request was not triggered by web content at all (no initiating origin — e.g. an
    /// address bar navigation or a bookmark).
    None,
    /// The target belongs to a different site than the initiator.
    CrossSite,
    /// Same site (same scheme and registrable domain), different origin.
    SameSite,
    /// The target is the initiator's own origin.
    SameOrigin,
}

impl SecFetchSite {
    /// The token sent in `Sec-Fetch-Site`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::CrossSite => "cross-site",
            Self::SameSite => "same-site",
            Self::SameOrigin => "same-origin",
        }
    }
}

/// Classify one hop's target against the initiating origin.
///
/// Never returns [`SecFetchSite::None`]; that value means there is no initiating origin at
/// all. Same site is schemeful: same scheme and [`same_site_host`] hosts.
pub(crate) fn classify_site(initiator: &Origin, target: &Url) -> SecFetchSite {
    let target_origin = target.origin();
    if *initiator == target_origin {
        return SecFetchSite::SameOrigin;
    }
    match (initiator, &target_origin) {
        (Origin::Tuple(s1, h1, _), Origin::Tuple(s2, h2, _))
            if s1 == s2 && same_site_host(h1, h2) =>
        {
            SecFetchSite::SameSite
        }
        _ => SecFetchSite::CrossSite,
    }
}

/// Two hosts are same site when they are equal, or both are domains with the same registrable
/// domain (HTML "same site"). IP addresses and hosts without a registrable domain (`localhost`,
/// a bare public suffix) only match themselves.
fn same_site_host(a: &Host, b: &Host) -> bool {
    if a == b {
        return true;
    }
    match (a, b) {
        (Host::Domain(a), Host::Domain(b)) => {
            match (registrable_domain(a), registrable_domain(b)) {
                (Some(a), Some(b)) => a == b,
                _ => false,
            }
        }
        _ => false,
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn registrable_domain(host: &str) -> Option<&str> {
    psl::domain_str(host)
}

// No public suffix list on wasm32; the browser sets Sec-Fetch-Site itself there anyway.
#[cfg(target_arch = "wasm32")]
fn registrable_domain(_host: &str) -> Option<&str> {
    None
}

/// Set (or clear) the four `Sec-Fetch-*` headers for one hop.
///
/// Per spec these only go to potentially trustworthy targets; a plaintext hop has them
/// removed, including values carried over from an earlier hop. `Sec-Fetch-User` is only ever
/// `?1` on a user-activated navigation; otherwise the header is absent.
pub(crate) fn apply_sec_fetch_headers(
    headers: &mut HeaderMap,
    target: &Url,
    destination: RequestDestination,
    mode: RequestMode,
    site: SecFetchSite,
    user_activated: bool,
) {
    if !is_potentially_trustworthy(target) {
        headers.remove(&SEC_FETCH_DEST);
        headers.remove(&SEC_FETCH_MODE);
        headers.remove(&SEC_FETCH_SITE);
        headers.remove(&SEC_FETCH_USER);
        return;
    }
    headers.insert(
        &SEC_FETCH_DEST,
        HeaderValue::from_static(destination.as_str()),
    );
    headers.insert(&SEC_FETCH_MODE, HeaderValue::from_static(mode.as_str()));
    headers.insert(&SEC_FETCH_SITE, HeaderValue::from_static(site.as_str()));
    if mode == RequestMode::Navigate && user_activated {
        headers.insert(&SEC_FETCH_USER, HeaderValue::from_static("?1"));
    } else {
        headers.remove(&SEC_FETCH_USER);
    }
}

/// The `Origin` header value for one hop, or `None` when the header must be omitted
/// (Fetch, *append a request `Origin` header*).
///
/// The header is sent on any method other than GET/HEAD, and on CORS-mode or WebSocket
/// requests that cross an origin. `tainted` is the request's *tainted origin flag*; once set,
/// the value is the literal `null`. On non-CORS requests the referrer policy caps `Origin`
/// the same way it caps `Referer`, so the header cannot leak what the policy just hid.
pub(crate) fn origin_header_value(
    initiator: &Origin,
    tainted: bool,
    method: &Method,
    mode: RequestMode,
    referrer_policy: ReferrerPolicy,
    target: &Url,
) -> Option<String> {
    let cors_like = matches!(mode, RequestMode::Cors | RequestMode::Websocket);
    let needed = !matches!(*method, Method::GET | Method::HEAD)
        || (cors_like && (tainted || *initiator != target.origin()));
    if !needed {
        return None;
    }
    if tainted {
        return Some("null".to_string());
    }
    // An opaque origin has no serialisation other than `null`.
    let Origin::Tuple(scheme, _, _) = initiator else {
        return Some("null".to_string());
    };
    if !cors_like {
        let cloaked = match referrer_policy {
            ReferrerPolicy::NoReferrer => true,
            ReferrerPolicy::NoReferrerWhenDowngrade
            | ReferrerPolicy::StrictOrigin
            | ReferrerPolicy::StrictOriginWhenCrossOrigin => {
                scheme == "https" && target.scheme() != "https"
            }
            ReferrerPolicy::SameOrigin => *initiator != target.origin(),
            ReferrerPolicy::Origin
            | ReferrerPolicy::OriginWhenCrossOrigin
            | ReferrerPolicy::UnsafeUrl => false,
        };
        if cloaked {
            return Some("null".to_string());
        }
    }
    Some(initiator.ascii_serialization())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn u(s: &str) -> Url {
        Url::parse(s).unwrap()
    }

    fn o(s: &str) -> Origin {
        u(s).origin()
    }

    #[test]
    fn site_classification() {
        let init = o("https://example.com");
        assert_eq!(
            classify_site(&init, &u("https://example.com/a")),
            SecFetchSite::SameOrigin
        );
        // A site has no port: same scheme and host on another port is still the same site.
        assert_eq!(
            classify_site(&init, &u("https://example.com:8443/a")),
            SecFetchSite::SameSite
        );
        // Schemeful sites: http and https on one host are different sites.
        assert_eq!(
            classify_site(&init, &u("http://example.com/a")),
            SecFetchSite::CrossSite
        );
        assert_eq!(
            classify_site(&init, &u("https://other.com/a")),
            SecFetchSite::CrossSite
        );
    }

    #[test]
    fn site_classification_uses_registrable_domain() {
        let init = o("https://a.example.com");
        // same eTLD+1
        assert_eq!(
            classify_site(&init, &u("https://b.example.com/")),
            SecFetchSite::SameSite
        );
        assert_eq!(
            classify_site(&init, &u("https://example.com/")),
            SecFetchSite::SameSite
        );
        assert_eq!(
            classify_site(&init, &u("https://deep.b.example.com:8443/")),
            SecFetchSite::SameSite
        );
        assert_eq!(
            classify_site(&init, &u("https://example.org/")),
            SecFetchSite::CrossSite
        );
        assert_eq!(
            classify_site(&init, &u("https://notexample.com/")),
            SecFetchSite::CrossSite
        );

        // multi-label public suffixes
        assert_eq!(
            classify_site(
                &o("https://x.example.co.uk"),
                &u("https://y.example.co.uk/")
            ),
            SecFetchSite::SameSite
        );
        assert_eq!(
            classify_site(&o("https://a.co.uk"), &u("https://b.co.uk/")),
            SecFetchSite::CrossSite
        );
        // private-section suffixes: every github.io user is its own site
        assert_eq!(
            classify_site(&o("https://a.github.io"), &u("https://b.github.io/")),
            SecFetchSite::CrossSite
        );

        // hosts without a registrable domain only match themselves
        assert_eq!(
            classify_site(&o("http://localhost:3000"), &u("http://localhost:4000/")),
            SecFetchSite::SameSite
        );
        assert_eq!(
            classify_site(&o("http://a.localhost"), &u("http://b.localhost/")),
            SecFetchSite::CrossSite
        );
        assert_eq!(
            classify_site(&o("http://127.0.0.1"), &u("http://127.0.0.1:8080/")),
            SecFetchSite::SameSite
        );
        assert_eq!(
            classify_site(&o("http://127.0.0.1"), &u("http://127.0.0.2/")),
            SecFetchSite::CrossSite
        );
    }

    /// `min` is how the redirect loop degrades the value across a chain, so the variant order
    /// is load-bearing.
    #[test]
    fn site_ordering_degrades() {
        assert_eq!(
            SecFetchSite::SameOrigin.min(SecFetchSite::CrossSite),
            SecFetchSite::CrossSite
        );
        assert_eq!(
            SecFetchSite::SameSite.min(SecFetchSite::SameOrigin),
            SecFetchSite::SameSite
        );
    }

    #[test]
    fn sec_fetch_headers_are_only_sent_to_trustworthy_targets() {
        let mut headers = HeaderMap::new();
        apply_sec_fetch_headers(
            &mut headers,
            &u("https://example.com/a"),
            RequestDestination::Image,
            RequestMode::NoCors,
            SecFetchSite::SameOrigin,
            false,
        );
        assert_eq!(headers.get("sec-fetch-dest").unwrap(), "image");
        assert_eq!(headers.get("sec-fetch-mode").unwrap(), "no-cors");
        assert_eq!(headers.get("sec-fetch-site").unwrap(), "same-origin");
        assert!(headers.get("sec-fetch-user").is_none());

        // A plaintext hop must clear values carried over from a trustworthy hop.
        apply_sec_fetch_headers(
            &mut headers,
            &u("http://example.com/a"),
            RequestDestination::Image,
            RequestMode::NoCors,
            SecFetchSite::SameOrigin,
            false,
        );
        assert!(headers.get("sec-fetch-dest").is_none());
        assert!(headers.get("sec-fetch-mode").is_none());
        assert!(headers.get("sec-fetch-site").is_none());
    }

    #[test]
    fn sec_fetch_user_requires_a_user_activated_navigation() {
        let target = u("https://example.com/a");
        let cases = [
            (RequestMode::Navigate, true, Some("?1")),
            (RequestMode::Navigate, false, None),
            (RequestMode::NoCors, true, None),
        ];
        for (mode, activated, expected) in cases {
            let mut headers = HeaderMap::new();
            apply_sec_fetch_headers(
                &mut headers,
                &target,
                RequestDestination::Document,
                mode,
                SecFetchSite::None,
                activated,
            );
            assert_eq!(
                headers.get("sec-fetch-user").map(|v| v.to_str().unwrap()),
                expected,
                "{mode:?} activated={activated}"
            );
        }
    }

    fn origin_for(
        initiator: &str,
        tainted: bool,
        method: Method,
        mode: RequestMode,
        policy: ReferrerPolicy,
        target: &str,
    ) -> Option<String> {
        origin_header_value(&o(initiator), tainted, &method, mode, policy, &u(target))
    }

    #[test]
    fn origin_is_sent_for_side_effect_methods_and_cors() {
        let policy = ReferrerPolicy::default();
        // A plain no-cors GET carries no Origin.
        assert_eq!(
            origin_for(
                "https://example.com",
                false,
                Method::GET,
                RequestMode::NoCors,
                policy,
                "https://other.com/a"
            ),
            None
        );
        // POST always identifies its sender.
        assert_eq!(
            origin_for(
                "https://example.com",
                false,
                Method::POST,
                RequestMode::NoCors,
                policy,
                "https://other.com/a"
            )
            .as_deref(),
            Some("https://example.com")
        );
        // A CORS GET sends Origin only when it actually crosses one.
        assert_eq!(
            origin_for(
                "https://example.com",
                false,
                Method::GET,
                RequestMode::Cors,
                policy,
                "https://example.com/a"
            ),
            None
        );
        assert_eq!(
            origin_for(
                "https://example.com",
                false,
                Method::GET,
                RequestMode::Cors,
                policy,
                "https://other.com/a"
            )
            .as_deref(),
            Some("https://example.com")
        );
        // A WebSocket handshake always sends it cross-origin.
        assert_eq!(
            origin_for(
                "https://example.com",
                false,
                Method::GET,
                RequestMode::Websocket,
                policy,
                "wss://other.com/a"
            )
            .as_deref(),
            Some("https://example.com")
        );
    }

    /// The referrer policy caps Origin on non-CORS requests, exactly as it caps Referer.
    #[test]
    fn origin_is_cloaked_by_the_referrer_policy() {
        // no-referrer hides the origin everywhere.
        assert_eq!(
            origin_for(
                "https://example.com",
                false,
                Method::POST,
                RequestMode::NoCors,
                ReferrerPolicy::NoReferrer,
                "https://example.com/a"
            )
            .as_deref(),
            Some("null")
        );
        // The strict policies hide it on an https → http downgrade.
        assert_eq!(
            origin_for(
                "https://example.com",
                false,
                Method::POST,
                RequestMode::NoCors,
                ReferrerPolicy::default(),
                "http://other.com/a"
            )
            .as_deref(),
            Some("null")
        );
        // same-origin hides it from every other origin.
        assert_eq!(
            origin_for(
                "https://example.com",
                false,
                Method::POST,
                RequestMode::NoCors,
                ReferrerPolicy::SameOrigin,
                "https://other.com/a"
            )
            .as_deref(),
            Some("null")
        );
        // CORS requests are exempt: the protocol requires the true origin.
        assert_eq!(
            origin_for(
                "https://example.com",
                false,
                Method::POST,
                RequestMode::Cors,
                ReferrerPolicy::NoReferrer,
                "https://other.com/a"
            )
            .as_deref(),
            Some("https://example.com")
        );
    }

    #[test]
    fn tainted_and_opaque_origins_serialise_as_null() {
        assert_eq!(
            origin_for(
                "https://example.com",
                true,
                Method::POST,
                RequestMode::NoCors,
                ReferrerPolicy::default(),
                "https://example.com/a"
            )
            .as_deref(),
            Some("null")
        );
        // data: URLs have an opaque origin.
        let opaque = u("data:text/html,hi").origin();
        assert_eq!(
            origin_header_value(
                &opaque,
                false,
                &Method::POST,
                RequestMode::NoCors,
                ReferrerPolicy::default(),
                &u("https://example.com/a")
            )
            .as_deref(),
            Some("null")
        );
    }
}