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(servo_rand::random_uuid()))
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(
49            servo_rand::random_uuid(),
50        ))
51    }
52
53    pub fn scheme(&self) -> Option<&str> {
54        match *self {
55            ImmutableOrigin::Opaque(_) => None,
56            ImmutableOrigin::Tuple(ref scheme, _, _) => Some(&**scheme),
57        }
58    }
59
60    pub fn host(&self) -> Option<&Host> {
61        match *self {
62            ImmutableOrigin::Opaque(_) => None,
63            ImmutableOrigin::Tuple(_, ref host, _) => Some(host),
64        }
65    }
66
67    pub fn port(&self) -> Option<u16> {
68        match *self {
69            ImmutableOrigin::Opaque(_) => None,
70            ImmutableOrigin::Tuple(_, _, port) => Some(port),
71        }
72    }
73
74    pub fn into_url_origin(self) -> Origin {
75        match self {
76            ImmutableOrigin::Opaque(_) => Origin::new_opaque(),
77            ImmutableOrigin::Tuple(scheme, host, port) => Origin::Tuple(scheme, host, port),
78        }
79    }
80
81    /// Return whether this origin is a (scheme, host, port) tuple
82    /// (as opposed to an opaque origin).
83    pub fn is_tuple(&self) -> bool {
84        match *self {
85            ImmutableOrigin::Opaque(..) => false,
86            ImmutableOrigin::Tuple(..) => true,
87        }
88    }
89
90    /// <https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy>
91    pub fn is_potentially_trustworthy(&self) -> bool {
92        // 1. If origin is an opaque origin return "Not Trustworthy"
93        if matches!(self, ImmutableOrigin::Opaque(_)) {
94            return false;
95        }
96
97        if let ImmutableOrigin::Tuple(scheme, host, _) = self {
98            // 3. If origin’s scheme is either "https" or "wss", return "Potentially Trustworthy"
99            if scheme == "https" || scheme == "wss" {
100                return true;
101            }
102            // 6. If origin’s scheme is "file", return "Potentially Trustworthy".
103            if scheme == "file" {
104                return true;
105            }
106
107            // 4. If origin’s host matches one of the CIDR notations 127.0.0.0/8 or ::1/128,
108            // return "Potentially Trustworthy".
109            if let Ok(ip_addr) = host.to_string().parse::<IpAddr>() {
110                return ip_addr.is_loopback();
111            }
112            // 5. If the user agent conforms to the name resolution rules in
113            // [let-localhost-be-localhost] and one of the following is true:
114            // * origin’s host is "localhost" or "localhost."
115            // * origin’s host ends with ".localhost" or ".localhost."
116            // then return "Potentially Trustworthy".
117            if let Host::Domain(domain) = host {
118                if domain == "localhost" || domain.ends_with(".localhost") {
119                    return true;
120                }
121            }
122        }
123        // 9. Return "Not Trustworthy".
124        false
125    }
126
127    /// <https://html.spec.whatwg.org/multipage/#ascii-serialisation-of-an-origin>
128    pub fn ascii_serialization(&self) -> String {
129        self.clone().into_url_origin().ascii_serialization()
130    }
131}
132
133/// Opaque identifier for URLs that have file or other schemes
134#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
135pub enum OpaqueOrigin {
136    Opaque(Uuid),
137    // Workers created from `data:` urls will have opaque origins but need to be treated
138    // as inheriting the secure context they were created in. This tracks that the origin
139    // was created in such a context
140    SecureWorkerFromDataUrl(Uuid),
141}
142malloc_size_of_is_0!(OpaqueOrigin);
143
144/// A representation of an [origin](https://html.spec.whatwg.org/multipage/#origin-2).
145#[derive(Clone, Debug, Deserialize, Serialize)]
146pub struct MutableOrigin(Rc<(ImmutableOrigin, RefCell<Option<Host>>)>);
147
148malloc_size_of_is_0!(MutableOrigin);
149
150impl MutableOrigin {
151    pub fn new(origin: ImmutableOrigin) -> MutableOrigin {
152        MutableOrigin(Rc::new((origin, RefCell::new(None))))
153    }
154
155    pub fn immutable(&self) -> &ImmutableOrigin {
156        &(self.0).0
157    }
158
159    pub fn is_tuple(&self) -> bool {
160        self.immutable().is_tuple()
161    }
162
163    pub fn scheme(&self) -> Option<&str> {
164        self.immutable().scheme()
165    }
166
167    pub fn host(&self) -> Option<&Host> {
168        self.immutable().host()
169    }
170
171    pub fn port(&self) -> Option<u16> {
172        self.immutable().port()
173    }
174
175    pub fn same_origin(&self, other: &MutableOrigin) -> bool {
176        self.immutable() == other.immutable()
177    }
178
179    pub fn same_origin_domain(&self, other: &MutableOrigin) -> bool {
180        if let Some(ref self_domain) = *(self.0).1.borrow() {
181            if let Some(ref other_domain) = *(other.0).1.borrow() {
182                self_domain == other_domain &&
183                    self.immutable().scheme() == other.immutable().scheme()
184            } else {
185                false
186            }
187        } else {
188            self.immutable().same_origin_domain(other)
189        }
190    }
191
192    pub fn domain(&self) -> Option<Host> {
193        (self.0).1.borrow().clone()
194    }
195
196    pub fn set_domain(&self, domain: Host) {
197        *(self.0).1.borrow_mut() = Some(domain);
198    }
199
200    pub fn has_domain(&self) -> bool {
201        (self.0).1.borrow().is_some()
202    }
203
204    pub fn effective_domain(&self) -> Option<Host> {
205        self.immutable()
206            .host()
207            .map(|host| self.domain().unwrap_or_else(|| host.clone()))
208    }
209}