1pub const MAX_ENTRIES: usize = 32;
15
16pub fn parse(entry: &str) -> Result<String, String> {
22 let entry = entry.trim();
23 if entry.is_empty() {
24 return Err("an empty entry".to_string());
25 }
26 let (wildcard, rest) = match entry.strip_prefix("*.") {
27 Some(rest) => (true, rest),
28 None => (false, entry),
29 };
30 let with_scheme = if rest.contains("://") { rest.to_string() } else { format!("https://{rest}") };
31 let bad = || format!("{entry:?} isn't a site (write example.com, *.example.com or https://example.com:8443)");
32 let url = url::Url::parse(&with_scheme).map_err(|_| bad())?;
33 if !matches!(url.scheme(), "http" | "https") {
34 return Err(format!("{entry:?} isn't an http or https site"));
35 }
36 let Some(host) = url.host() else { return Err(bad()) };
37 let Some(origin) = crate::url_guard::origin_string(&url) else { return Err(bad()) };
38 if !wildcard {
39 return Ok(origin);
40 }
41 match host {
42 url::Host::Domain(d) if d.contains('.') => {
43 Ok(origin.replacen("://", "://*.", 1))
45 }
46 _ => Err(format!("{entry:?}: `*.` goes in front of a domain name with a dot in it")),
47 }
48}
49
50pub fn parse_list(entries: &[String]) -> Result<Vec<String>, String> {
53 let mut out: Vec<String> = Vec::new();
54 for e in entries {
55 let p = parse(e)?;
56 if !out.contains(&p) {
57 out.push(p);
58 }
59 }
60 if out.len() > MAX_ENTRIES {
61 return Err(format!("at most {MAX_ENTRIES} sites"));
62 }
63 Ok(out)
64}
65
66pub fn target_origin(url: &str) -> Option<String> {
70 let u = url::Url::parse(url).ok()?;
71 let origin = crate::url_guard::checked_origin(&u)?;
72 match &origin {
73 url::Origin::Tuple(scheme, _, _) if scheme == "http" || scheme == "https" => Some(origin.ascii_serialization()),
74 _ => None,
75 }
76}
77
78pub fn bare_origin(url: &str) -> Option<String> {
83 let u = url::Url::parse(url.trim()).ok()?;
84 let bare = u.path() == "/" && u.query().is_none() && u.fragment().is_none() && u.username().is_empty() && u.password().is_none();
85 if bare { target_origin(u.as_str()) } else { None }
86}
87
88pub fn same_origin(a: &str, b: &str) -> bool {
92 match (target_origin(a.trim()), target_origin(b.trim())) {
93 (Some(x), Some(y)) => x == y,
94 _ => a.trim() == b.trim(),
95 }
96}
97
98pub fn allows(list: &[String], url: &str) -> bool {
101 if url::Url::parse(url).is_ok_and(|u| u.scheme() == "about") {
102 return true;
103 }
104 let Some(target) = target_origin(url) else { return false };
105 list.iter().any(|entry| entry_allows(entry, &target))
106}
107
108fn entry_allows(entry: &str, target: &str) -> bool {
109 if entry == target {
110 return true;
111 }
112 let Some((scheme, rest)) = entry.split_once("://*.") else { return false };
115 let Some(t_rest) = target.strip_prefix(scheme).and_then(|t| t.strip_prefix("://")) else {
116 return false;
117 };
118 let (domain, port) = split_port(rest);
119 let (t_host, t_port) = split_port(t_rest);
120 port == t_port && (t_host == domain || t_host.ends_with(&format!(".{domain}")))
121}
122
123fn split_port(s: &str) -> (&str, &str) {
126 if s.ends_with(']') {
127 return (s, "");
128 }
129 match s.rsplit_once(':') {
130 Some((h, p)) if !h.is_empty() && !p.is_empty() && p.bytes().all(|c| c.is_ascii_digit()) => (h, p),
131 _ => (s, ""),
132 }
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 #[test]
140 fn a_saved_site_and_a_page_origin_match_as_origins_not_as_strings() {
141 assert!(same_origin("http://host.example:8080", "http://host.example:8080/"));
143 assert!(same_origin("http://host.example:8080/", "http://host.example:8080"));
144 assert!(same_origin("HTTPS://Example.COM", "https://example.com/"));
146 assert!(same_origin("https://example.com:443", "https://example.com"));
148 assert!(same_origin("http://example.com:80/", "http://example.com"));
149 assert!(!same_origin("https://example.com:8443", "https://example.com"));
150 assert!(!same_origin("http://example.com:8080", "http://example.com:8081"));
151 assert!(!same_origin("http://example.com", "https://example.com"));
153 assert!(!same_origin("https://example.com.evil.test", "https://example.com"));
155 assert!(!same_origin("https://exarnple.com", "https://example.com"));
156 assert!(!same_origin("https://example.com@evil.test", "https://example.com"), "the host is what follows the @");
157 assert!(!same_origin("https://sub.example.com", "https://example.com"));
158 assert!(same_origin("https://example.com/login?next=/a", "https://example.com"));
160 assert!(same_origin("https://user@example.com/app", "https://example.com/"));
161 assert!(!same_origin("https://example.com/app", "https://example.com:8443"));
162 assert!(same_origin("example.com", " example.com "));
164 assert!(!same_origin("example.com", "https://example.com"));
165 }
166
167 #[test]
168 fn a_site_that_is_only_an_origin_is_stored_in_one_form_and_a_login_page_is_left_alone() {
169 assert_eq!(bare_origin("HTTPS://Example.com:443/").as_deref(), Some("https://example.com"));
170 assert_eq!(bare_origin("http://host.example:8080/").as_deref(), Some("http://host.example:8080"));
171 assert_eq!(bare_origin(" https://example.com ").as_deref(), Some("https://example.com"));
172 assert_eq!(bare_origin("https://example.com/login"), None, "a path is the login's own page");
173 assert_eq!(bare_origin("https://example.com/?a=1"), None);
174 assert_eq!(bare_origin("https://user@example.com"), None, "user information is not dropped without being asked");
175 assert_eq!(bare_origin("example.com"), None);
176 assert_eq!(bare_origin("about:blank"), None);
177 }
178
179 #[test]
180 fn entries_parse_to_their_normal_form() {
181 assert_eq!(parse("example.com").unwrap(), "https://example.com");
182 assert_eq!(parse(" Example.COM ").unwrap(), "https://example.com");
183 assert_eq!(parse("*.example.com").unwrap(), "https://*.example.com");
184 assert_eq!(parse("https://example.com:8443/a?b#c").unwrap(), "https://example.com:8443");
185 assert_eq!(parse("https://example.com:443").unwrap(), "https://example.com");
186 assert_eq!(parse("http://localhost:3000").unwrap(), "http://localhost:3000");
187 assert_eq!(parse("example.com/some/path").unwrap(), "https://example.com");
188 assert_eq!(parse("bücher.example").unwrap(), "https://xn--bcher-kva.example");
189 assert_eq!(parse("http://[::1]:8080").unwrap(), "http://[::1]:8080");
190 assert_eq!(parse("*.example.com:8443").unwrap(), "https://*.example.com:8443");
191 }
192
193 #[test]
194 fn bad_entries_are_refused() {
195 for bad in ["", " ", "ftp://example.com", "javascript:alert(1)", "*.localhost", "*.192.0.2.1", "https://", "*."] {
196 assert!(parse(bad).is_err(), "{bad:?}");
197 }
198 let many: Vec<String> = (0..=MAX_ENTRIES).map(|i| format!("s{i}.example.com")).collect();
199 assert!(parse_list(&many).is_err());
200 assert_eq!(parse_list(&["a.example".into(), "https://a.example/".into()]).unwrap(), vec!["https://a.example"]);
201 }
202
203 #[test]
204 fn a_list_allows_its_sites_and_nothing_else() {
205 let list = parse_list(&["example.com".into(), "*.docs.example.org".into(), "http://localhost:3000".into()]).unwrap();
206 let ok = |u: &str| allows(&list, u);
207 assert!(ok("https://example.com/"));
208 assert!(ok("https://example.com/deep/path?q=1"));
209 assert!(!ok("https://www.example.com/"), "a bare domain is just that host");
210 assert!(!ok("http://example.com/"), "http only when written out");
211 assert!(!ok("https://example.com:8443/"));
212 assert!(ok("https://docs.example.org/"));
213 assert!(ok("https://a.b.docs.example.org/"));
214 assert!(!ok("https://evil-docs.example.org/"));
215 assert!(!ok("https://docs.example.org.evil.example/"));
216 assert!(ok("http://localhost:3000/app"));
217 assert!(!ok("http://localhost:3001/"));
218 assert!(!ok("https://evil.example/"));
219 assert!(ok("blob:https://example.com/0f0e"));
221 assert!(!ok("blob:https://evil.example/0f0e"));
222 assert!(ok("about:blank"));
224 assert!(!ok("data:text/html,hi"));
225 assert!(!ok("file:///etc/passwd"));
226 assert!(!ok("not a url"));
227 }
228
229 #[test]
230 fn a_wildcard_keeps_its_port() {
231 let list = parse_list(&["*.example.com:8443".into()]).unwrap();
232 assert!(allows(&list, "https://a.example.com:8443/"));
233 assert!(!allows(&list, "https://a.example.com/"));
234 }
235
236 #[test]
237 fn target_origin_is_what_allow_adds() {
238 assert_eq!(target_origin("https://Evil.Example:443/x?y").as_deref(), Some("https://evil.example"));
239 assert_eq!(target_origin("blob:https://a.example/id").as_deref(), Some("https://a.example"));
240 assert_eq!(target_origin("about:blank"), None);
241 assert_eq!(target_origin("data:text/html,x"), None);
242 let added = vec![target_origin("https://new.example/path").unwrap()];
244 assert!(allows(&added, "https://new.example/other"));
245 }
246
247 #[test]
248 fn an_address_that_nests_blob_addresses_has_no_origin_and_is_not_allowed() {
249 let list = parse_list(&["https://a.example".into()]).unwrap();
250 let deep = format!("{}https://a.example/id", "blob:".repeat(50_000));
251 for url in ["blob:blob:https://a.example/id", deep.as_str()] {
252 assert_eq!(target_origin(url), None);
253 assert!(!allows(&list, url));
254 assert!(!same_origin(url, "https://a.example/"));
255 }
256 assert!(allows(&list, "blob:https://a.example/id"));
258 }
259}