Skip to main content

url/
origin.rs

1// Copyright 2016 The rust-url developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use crate::host::Host;
10use crate::parser::default_port;
11use crate::Url;
12use alloc::borrow::ToOwned;
13use alloc::format;
14use alloc::string::String;
15use core::sync::atomic::{AtomicUsize, Ordering};
16
17pub fn url_origin(url: &Url) -> Origin {
18    let scheme = url.scheme();
19    match scheme {
20        "blob" => {
21            let result = Url::parse(url.path());
22            match result {
23                // https://url.spec.whatwg.org/#concept-url-origin
24                // The URL Standard takes the origin of the inner URL only for these schemes.
25                Ok(ref url) if matches!(url.scheme(), "http" | "https" | "file") => url_origin(url),
26                _ => Origin::new_opaque(),
27            }
28        }
29        "ftp" | "http" | "https" | "ws" | "wss" => Origin::Tuple(
30            scheme.to_owned(),
31            url.host().unwrap().to_owned(),
32            url.port_or_known_default().unwrap(),
33        ),
34        // TODO: Figure out what to do if the scheme is a file
35        "file" => Origin::new_opaque(),
36        _ => Origin::new_opaque(),
37    }
38}
39
40/// The origin of an URL
41///
42/// Two URLs with the same origin are considered
43/// to originate from the same entity and can therefore trust
44/// each other.
45///
46/// The origin is determined based on the scheme as follows:
47///
48/// - If the scheme is "blob" and the path component contains a URL
49///   with the scheme "http", "https", or "file", the origin is the
50///   origin of that URL. Otherwise it is an opaque origin.
51/// - If the scheme is "ftp", "http", "https", "ws", or "wss",
52///   then the origin is a tuple of the scheme, host, and port.
53/// - If the scheme is anything else, the origin is opaque, meaning
54///   the URL does not have the same origin as any other URL.
55///
56/// For more information see <https://url.spec.whatwg.org/#origin>
57#[derive(PartialEq, Eq, Hash, Clone, Debug)]
58pub enum Origin {
59    /// A globally unique identifier
60    Opaque(OpaqueOrigin),
61
62    /// Consists of the URL's scheme, host and port
63    Tuple(String, Host<String>, u16),
64}
65
66impl Origin {
67    /// Creates a new opaque origin that is only equal to itself.
68    pub fn new_opaque() -> Self {
69        static COUNTER: AtomicUsize = AtomicUsize::new(0);
70        Self::Opaque(OpaqueOrigin(COUNTER.fetch_add(1, Ordering::SeqCst)))
71    }
72
73    /// Return whether this origin is a (scheme, host, port) tuple
74    /// (as opposed to an opaque origin).
75    pub fn is_tuple(&self) -> bool {
76        matches!(*self, Self::Tuple(..))
77    }
78
79    /// <https://html.spec.whatwg.org/multipage/#ascii-serialisation-of-an-origin>
80    pub fn ascii_serialization(&self) -> String {
81        match *self {
82            Self::Opaque(_) => "null".to_owned(),
83            Self::Tuple(ref scheme, ref host, port) => {
84                if default_port(scheme) == Some(port) {
85                    format!("{scheme}://{host}")
86                } else {
87                    format!("{scheme}://{host}:{port}")
88                }
89            }
90        }
91    }
92
93    /// <https://html.spec.whatwg.org/multipage/#unicode-serialisation-of-an-origin>
94    pub fn unicode_serialization(&self) -> String {
95        match *self {
96            Self::Opaque(_) => "null".to_owned(),
97            Self::Tuple(ref scheme, ref host, port) => {
98                let host = match *host {
99                    Host::Domain(ref domain) => {
100                        let (domain, _errors) = idna::domain_to_unicode(domain);
101                        Host::Domain(domain)
102                    }
103                    _ => host.clone(),
104                };
105                if default_port(scheme) == Some(port) {
106                    format!("{scheme}://{host}")
107                } else {
108                    format!("{scheme}://{host}:{port}")
109                }
110            }
111        }
112    }
113}
114
115/// Opaque identifier for URLs that have file or other schemes
116#[derive(Eq, PartialEq, Hash, Clone, Debug)]
117pub struct OpaqueOrigin(usize);