servo_url/
origin.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::RefCell;
6use std::net::IpAddr;
7use std::rc::Rc;
8
9use malloc_size_of::malloc_size_of_is_0;
10use malloc_size_of_derive::MallocSizeOf;
11use serde::{Deserialize, Serialize};
12use url::{Host, Origin};
13use uuid::Uuid;
14
15/// The origin of an URL
16#[derive(Clone, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
17pub enum ImmutableOrigin {
18    /// A globally unique identifier
19    Opaque(OpaqueOrigin),
20
21    /// Consists of the URL's scheme, host and port
22    Tuple(String, Host, u16),
23}
24
25impl ImmutableOrigin {
26    pub fn new(origin: Origin) -> ImmutableOrigin {
27        match origin {
28            Origin::Opaque(_) => ImmutableOrigin::new_opaque(),
29            Origin::Tuple(scheme, host, port) => ImmutableOrigin::Tuple(scheme, host, port),
30        }
31    }
32
33    pub fn same_origin(&self, other: &MutableOrigin) -> bool {
34        self == other.immutable()
35    }
36
37    pub fn same_origin_domain(&self, other: &MutableOrigin) -> bool {
38        !other.has_domain() && self == other.immutable()
39    }
40
41    /// Creates a new opaque origin that is only equal to itself.
42    pub fn new_opaque() -> ImmutableOrigin {
43        ImmutableOrigin::Opaque(OpaqueOrigin::Opaque(Uuid::new_v4()))
44    }
45
46    // For use in mixed security context tests because data: URL workers inherit contexts
47    pub fn new_opaque_data_url_worker() -> ImmutableOrigin {
48        ImmutableOrigin::Opaque(OpaqueOrigin::SecureWorkerFromDataUrl(Uuid::new_v4()))
49    }
50
51    pub fn scheme(&self) -> Option<&str> {
52        match *self {
53            ImmutableOrigin::Opaque(_) => None,
54            ImmutableOrigin::Tuple(ref scheme, _, _) => Some(&**scheme),
55        }
56    }
57
58    pub fn host(&self) -> Option<&Host> {
59        match *self {
60            ImmutableOrigin::Opaque(_) => None,
61            ImmutableOrigin::Tuple(_, ref host, _) => Some(host),
62        }
63    }
64
65    pub fn port(&self) -> Option<u16> {
66        match *self {
67            ImmutableOrigin::Opaque(_) => None,
68            ImmutableOrigin::Tuple(_, _, port) => Some(port),
69        }
70    }
71
72    pub fn into_url_origin(self) -> Origin {
73        match self {
74            ImmutableOrigin::Opaque(_) => Origin::new_opaque(),
75            ImmutableOrigin::Tuple(scheme, host, port) => Origin::Tuple(scheme, host, port),
76        }
77    }
78
79    /// Return whether this origin is a (scheme, host, port) tuple
80    /// (as opposed to an opaque origin).
81    pub fn is_tuple(&self) -> bool {
82        match *self {
83            ImmutableOrigin::Opaque(..) => false,
84            ImmutableOrigin::Tuple(..) => true,
85        }
86    }
87
88    /// <https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy>
89    pub fn is_potentially_trustworthy(&self) -> bool {
90        // 1. If origin is an opaque origin return "Not Trustworthy"
91        if matches!(self, ImmutableOrigin::Opaque(_)) {
92            return false;
93        }
94
95        if let ImmutableOrigin::Tuple(scheme, host, _) = self {
96            // 3. If origin’s scheme is either "https" or "wss", return "Potentially Trustworthy"
97            if scheme == "https" || scheme == "wss" {
98                return true;
99            }
100            // 6. If origin’s scheme is "file", return "Potentially Trustworthy".
101            if scheme == "file" {
102                return true;
103            }
104
105            // 4. If origin’s host matches one of the CIDR notations 127.0.0.0/8 or ::1/128,
106            // return "Potentially Trustworthy".
107            if let Ok(ip_addr) = host.to_string().parse::<IpAddr>() {
108                return ip_addr.is_loopback();
109            }
110            // 5. If the user agent conforms to the name resolution rules in
111            // [let-localhost-be-localhost] and one of the following is true:
112            // * origin’s host is "localhost" or "localhost."
113            // * origin’s host ends with ".localhost" or ".localhost."
114            // then return "Potentially Trustworthy".
115            if let Host::Domain(domain) = host {
116                if domain == "localhost" || domain.ends_with(".localhost") {
117                    return true;
118                }
119            }
120        }
121        // 9. Return "Not Trustworthy".
122        false
123    }
124
125    /// <https://html.spec.whatwg.org/multipage/#ascii-serialisation-of-an-origin>
126    pub fn ascii_serialization(&self) -> String {
127        self.clone().into_url_origin().ascii_serialization()
128    }
129}
130
131/// Opaque identifier for URLs that have file or other schemes
132#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
133pub enum OpaqueOrigin {
134    Opaque(Uuid),
135    // Workers created from `data:` urls will have opaque origins but need to be treated
136    // as inheriting the secure context they were created in. This tracks that the origin
137    // was created in such a context
138    SecureWorkerFromDataUrl(Uuid),
139}
140malloc_size_of_is_0!(OpaqueOrigin);
141
142/// A representation of an [origin](https://html.spec.whatwg.org/multipage/#origin-2).
143#[derive(Clone, Debug, Deserialize, Serialize)]
144pub struct MutableOrigin(Rc<(ImmutableOrigin, RefCell<Option<Host>>)>);
145
146malloc_size_of_is_0!(MutableOrigin);
147
148impl MutableOrigin {
149    pub fn new(origin: ImmutableOrigin) -> MutableOrigin {
150        MutableOrigin(Rc::new((origin, RefCell::new(None))))
151    }
152
153    pub fn immutable(&self) -> &ImmutableOrigin {
154        &(self.0).0
155    }
156
157    pub fn is_tuple(&self) -> bool {
158        self.immutable().is_tuple()
159    }
160
161    pub fn scheme(&self) -> Option<&str> {
162        self.immutable().scheme()
163    }
164
165    pub fn host(&self) -> Option<&Host> {
166        self.immutable().host()
167    }
168
169    pub fn port(&self) -> Option<u16> {
170        self.immutable().port()
171    }
172
173    pub fn same_origin(&self, other: &MutableOrigin) -> bool {
174        self.immutable() == other.immutable()
175    }
176
177    pub fn same_origin_domain(&self, other: &MutableOrigin) -> bool {
178        if let Some(ref self_domain) = *(self.0).1.borrow() {
179            if let Some(ref other_domain) = *(other.0).1.borrow() {
180                self_domain == other_domain &&
181                    self.immutable().scheme() == other.immutable().scheme()
182            } else {
183                false
184            }
185        } else {
186            self.immutable().same_origin_domain(other)
187        }
188    }
189
190    pub fn domain(&self) -> Option<Host> {
191        (self.0).1.borrow().clone()
192    }
193
194    pub fn set_domain(&self, domain: Host) {
195        *(self.0).1.borrow_mut() = Some(domain);
196    }
197
198    pub fn has_domain(&self) -> bool {
199        (self.0).1.borrow().is_some()
200    }
201
202    pub fn effective_domain(&self) -> Option<Host> {
203        self.immutable()
204            .host()
205            .map(|host| self.domain().unwrap_or_else(|| host.clone()))
206    }
207}