1use serde_json::{Map, Value};
27
28#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct HostPattern(String);
32
33impl HostPattern {
34 pub fn new(pattern: &str) -> Result<Self, String> {
36 let p = pattern.trim().to_ascii_lowercase();
37 let host = p.strip_prefix("*.").unwrap_or(&p);
38 let valid = p == "*"
39 || (!host.is_empty()
40 && host.chars().all(|c| {
41 c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '[' | ']')
42 }));
43 if valid {
44 Ok(Self(p))
45 } else {
46 Err(format!("invalid host pattern `{pattern}`"))
47 }
48 }
49
50 pub fn matches(&self, host: &str) -> bool {
52 match self.0.strip_prefix("*.") {
53 _ if self.0 == "*" => true,
54 Some(suffix) => {
55 host.len() > suffix.len() + 1 && host.ends_with(suffix) && {
56 let dot = host.len() - suffix.len() - 1;
57 host.as_bytes()[dot] == b'.'
58 }
59 }
60 None => self.0 == host,
61 }
62 }
63
64 pub fn as_str(&self) -> &str {
66 &self.0
67 }
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct HttpGrant {
74 pub host: HostPattern,
76 pub methods: Vec<String>,
78 pub schemes: Vec<String>,
80 pub path_prefix: Option<String>,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Default)]
86pub struct NetworkGrants {
87 pub hosts: Vec<HostPattern>,
89 pub http: Vec<HttpGrant>,
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Default)]
95pub struct Capabilities {
96 pub network: NetworkGrants,
98 pub webview: Option<Vec<HostPattern>>,
100 pub status_bar: bool,
102 pub clipboard: bool,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct UrlParts<'a> {
109 pub scheme: String,
111 pub host: String,
113 pub path: &'a str,
115}
116
117pub fn parse_url(url: &str) -> Option<UrlParts<'_>> {
120 let (scheme, rest) = url.split_once("://")?;
121 if scheme.is_empty()
122 || !scheme
123 .chars()
124 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
125 {
126 return None;
127 }
128 let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
129 let (authority, path) = rest.split_at(end);
130 let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
132 let host = if let Some(v6) = host_port.strip_prefix('[') {
133 format!("[{}]", v6.split_once(']')?.0)
134 } else {
135 host_port.split(':').next().unwrap_or_default().to_owned()
136 };
137 if host.is_empty() {
138 return None;
139 }
140 Some(UrlParts {
141 scheme: scheme.to_ascii_lowercase(),
142 host: host.to_ascii_lowercase().trim_end_matches('.').to_owned(),
143 path: if path.is_empty() { "/" } else { path },
144 })
145}
146
147impl Capabilities {
148 pub fn all() -> Self {
150 let any = vec![HostPattern("*".into())];
151 Self {
152 network: NetworkGrants {
153 hosts: any.clone(),
154 http: Vec::new(),
155 },
156 webview: Some(any),
157 status_bar: true,
158 clipboard: true,
159 }
160 }
161
162 pub fn from_json(value: &Value) -> Result<Self, String> {
164 let obj = object(value, "capabilities")?;
165 known(
166 obj,
167 "capabilities",
168 &["network", "webview", "statusBar", "clipboard"],
169 )?;
170 let mut caps = Capabilities::default();
171 if let Some(network) = obj.get("network") {
172 let network = object(network, "capabilities.network")?;
173 known(network, "capabilities.network", &["hosts", "http"])?;
174 if let Some(hosts) = network.get("hosts") {
175 caps.network.hosts = patterns(hosts, "capabilities.network.hosts")?;
176 }
177 if let Some(http) = network.get("http") {
178 let list = http
179 .as_array()
180 .ok_or("capabilities.network.http must be an array")?;
181 for grant in list {
182 let g = object(grant, "capabilities.network.http[]")?;
183 known(
184 g,
185 "capabilities.network.http[]",
186 &["host", "methods", "schemes", "pathPrefix"],
187 )?;
188 let host = g
189 .get("host")
190 .and_then(Value::as_str)
191 .ok_or("capabilities.network.http[] needs a `host`")?;
192 let strings = |key: &str, upper: bool| -> Result<Vec<String>, String> {
193 match g.get(key) {
194 None => Ok(Vec::new()),
195 Some(v) => strings(v, &format!("capabilities.network.http[].{key}"))
196 .map(|l| {
197 l.into_iter()
198 .map(|s| {
199 if upper {
200 s.to_ascii_uppercase()
201 } else {
202 s.to_ascii_lowercase()
203 }
204 })
205 .collect()
206 }),
207 }
208 };
209 caps.network.http.push(HttpGrant {
210 host: HostPattern::new(host)?,
211 methods: strings("methods", true)?,
212 schemes: strings("schemes", false)?,
213 path_prefix: match g.get("pathPrefix") {
214 None => None,
215 Some(v) => Some(
216 v.as_str()
217 .ok_or(
218 "capabilities.network.http[].pathPrefix must be a string",
219 )?
220 .to_owned(),
221 ),
222 },
223 });
224 }
225 }
226 }
227 if let Some(webview) = obj.get("webview") {
228 let webview = object(webview, "capabilities.webview")?;
229 known(webview, "capabilities.webview", &["hosts"])?;
230 caps.webview = Some(match webview.get("hosts") {
231 Some(hosts) => patterns(hosts, "capabilities.webview.hosts")?,
232 None => Vec::new(),
233 });
234 }
235 if let Some(status_bar) = obj.get("statusBar") {
236 caps.status_bar = status_bar
237 .as_bool()
238 .ok_or("capabilities.statusBar must be a boolean")?;
239 }
240 if let Some(clipboard) = obj.get("clipboard") {
241 caps.clipboard = clipboard
242 .as_bool()
243 .ok_or("capabilities.clipboard must be a boolean")?;
244 }
245 Ok(caps)
246 }
247
248 pub fn to_json(&self) -> Value {
250 let list =
251 |l: &[HostPattern]| Value::from(l.iter().map(|p| p.0.clone()).collect::<Vec<_>>());
252 let mut network = Map::new();
253 network.insert("hosts".into(), list(&self.network.hosts));
254 let http: Vec<Value> = self
255 .network
256 .http
257 .iter()
258 .map(|g| {
259 let mut o = Map::new();
260 o.insert("host".into(), g.host.0.clone().into());
261 if !g.methods.is_empty() {
262 o.insert("methods".into(), g.methods.clone().into());
263 }
264 if !g.schemes.is_empty() {
265 o.insert("schemes".into(), g.schemes.clone().into());
266 }
267 if let Some(p) = &g.path_prefix {
268 o.insert("pathPrefix".into(), p.clone().into());
269 }
270 Value::Object(o)
271 })
272 .collect();
273 network.insert("http".into(), http.into());
274 let mut obj = Map::new();
275 obj.insert("network".into(), Value::Object(network));
276 if let Some(hosts) = &self.webview {
277 let mut w = Map::new();
278 w.insert("hosts".into(), list(hosts));
279 obj.insert("webview".into(), Value::Object(w));
280 }
281 obj.insert("statusBar".into(), self.status_bar.into());
282 obj.insert("clipboard".into(), self.clipboard.into());
283 Value::Object(obj)
284 }
285
286 fn allows_http(&self, method: &str, url: &UrlParts<'_>) -> bool {
287 if !matches!(url.scheme.as_str(), "http" | "https" | "ws" | "wss") {
288 return false;
289 }
290 self.network.hosts.iter().any(|h| h.matches(&url.host))
291 || self.network.http.iter().any(|g| {
292 g.host.matches(&url.host)
293 && (g.methods.is_empty()
294 || g.methods.iter().any(|m| m.eq_ignore_ascii_case(method)))
295 && (g.schemes.is_empty() || g.schemes.contains(&url.scheme))
296 && g.path_prefix
297 .as_deref()
298 .is_none_or(|p| url.path.starts_with(p))
299 })
300 }
301
302 fn allows_webview(&self, url: &UrlParts<'_>) -> bool {
303 matches!(url.scheme.as_str(), "http" | "https")
304 && self
305 .webview
306 .as_ref()
307 .is_some_and(|hosts| hosts.iter().any(|h| h.matches(&url.host)))
308 }
309}
310
311fn object<'a>(value: &'a Value, what: &str) -> Result<&'a Map<String, Value>, String> {
312 value
313 .as_object()
314 .ok_or_else(|| format!("{what} must be an object"))
315}
316
317fn known(obj: &Map<String, Value>, what: &str, keys: &[&str]) -> Result<(), String> {
318 match obj.keys().find(|k| !keys.contains(&k.as_str())) {
319 Some(k) => Err(format!(
320 "{what}: unknown key `{k}` (known: {})",
321 keys.join(", ")
322 )),
323 None => Ok(()),
324 }
325}
326
327fn strings(value: &Value, what: &str) -> Result<Vec<String>, String> {
328 value
329 .as_array()
330 .and_then(|a| a.iter().map(|v| v.as_str().map(str::to_owned)).collect())
331 .ok_or_else(|| format!("{what} must be an array of strings"))
332}
333
334fn patterns(value: &Value, what: &str) -> Result<Vec<HostPattern>, String> {
335 strings(value, what)?
336 .iter()
337 .map(|p| HostPattern::new(p))
338 .collect()
339}
340
341#[derive(Debug, Clone, PartialEq, Eq)]
344pub struct Access {
345 pub declared: Capabilities,
347 pub granted: Option<Capabilities>,
349}
350
351impl Default for Access {
352 fn default() -> Self {
353 Self::all()
354 }
355}
356
357impl Access {
358 pub fn all() -> Self {
360 Self {
361 declared: Capabilities::all(),
362 granted: None,
363 }
364 }
365
366 fn each(&self, f: impl Fn(&Capabilities) -> bool) -> bool {
367 f(&self.declared) && self.granted.as_ref().is_none_or(f)
368 }
369
370 pub fn is_unrestricted(&self) -> bool {
373 let all = Capabilities::all();
374 self.declared == all && self.granted.as_ref().is_none_or(|g| *g == all)
375 }
376
377 pub fn allows_http(&self, method: &str, url: &str) -> bool {
380 if url.starts_with("asset:") {
381 return true;
382 }
383 let Some(parts) = parse_url(url) else {
384 return false;
385 };
386 self.each(|c| c.allows_http(method, &parts))
387 }
388
389 pub fn allows_media(&self, uri: &str) -> bool {
392 if !uri.contains("://") || uri.starts_with("asset:") || uri.starts_with("data:") {
393 return true;
394 }
395 self.allows_http("GET", uri)
396 }
397
398 pub fn media_redirect(&self, base: &str, location: &str) -> Result<String, String> {
404 let url = resolve_reference(base, location);
405 if !(url.starts_with("http://") || url.starts_with("https://")) {
406 return Err(format!("redirect to `{url}` is not an http(s) URL"));
407 }
408 if !self.is_unrestricted() && !self.allows_media(&url) {
409 return Err(format!(
410 "redirect to `{url}` is not granted by capabilities.network"
411 ));
412 }
413 Ok(url)
414 }
415
416 pub fn allows_webviews(&self) -> bool {
418 self.each(|c| c.webview.is_some())
419 }
420
421 pub fn allows_webview(&self, url: &str) -> bool {
424 if url == "about:blank" {
425 return self.allows_webviews();
426 }
427 let Some(parts) = parse_url(url) else {
428 return false;
429 };
430 self.each(|c| c.allows_webview(&parts))
431 }
432
433 pub fn allows_status_bar(&self) -> bool {
435 self.each(|c| c.status_bar)
436 }
437
438 pub fn allows_clipboard(&self) -> bool {
440 self.each(|c| c.clipboard)
441 }
442}
443
444pub fn resolve_reference(base: &str, location: &str) -> String {
447 if location.contains("://") {
448 return location.to_owned();
449 }
450 let Some((scheme, rest)) = base.split_once("://") else {
451 return location.to_owned();
452 };
453 if let Some(net) = location.strip_prefix("//") {
454 return format!("{scheme}://{net}");
455 }
456 let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
457 let origin = format!("{scheme}://{}", &rest[..authority_end]);
458 if location.starts_with('/') {
459 return format!("{origin}{location}");
460 }
461 let path = &rest[authority_end..];
462 let path = path.split(['?', '#']).next().unwrap_or_default();
463 let dir = path.rsplit_once('/').map_or("", |(d, _)| d);
464 format!("{origin}{dir}/{location}")
465}
466
467#[cfg(test)]
468mod tests {
469 use super::*;
470
471 fn caps(json: &str) -> Capabilities {
472 Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap()
473 }
474
475 #[test]
476 fn denies_unless_listed() {
477 let access = Access {
478 declared: caps("{}"),
479 granted: None,
480 };
481 assert!(!access.allows_http("GET", "https://example.com/"));
482 assert!(!access.allows_media("https://example.com/a.png"));
483 assert!(access.allows_media("asset:/logo.png"));
484 assert!(access.allows_media("logo.png"));
485 assert!(!access.allows_webview("https://example.com/"));
486 assert!(!access.allows_status_bar());
487 assert!(!access.allows_clipboard());
488 assert!(Access::all().is_unrestricted());
489 }
490
491 #[test]
492 fn hosts_and_finer_grants() {
493 let c = caps(
494 r#"{ "network": {
495 "hosts": ["*.example.org"],
496 "http": [{ "host": "api.example.com", "methods": ["get"], "pathPrefix": "/v1/" }]
497 } }"#,
498 );
499 let a = Access {
500 declared: c,
501 granted: None,
502 };
503 assert!(a.allows_http("POST", "https://api.example.org/x"));
504 assert!(!a.allows_http("GET", "https://example.org/"));
505 assert!(!a.allows_http("GET", "https://example.org.evil.io/"));
506 assert!(!a.allows_http("GET", "https://evilexample.org/"));
507 assert!(a.allows_http("GET", "https://API.example.com/v1/quote"));
508 assert!(!a.allows_http("POST", "https://api.example.com/v1/quote"));
509 assert!(!a.allows_http("GET", "https://api.example.com/v2/"));
510 assert!(!a.allows_http("GET", "file://api.example.com/v1/"));
511 assert!(!a.allows_http("GET", "https://api.example.org@evil.io/"));
513 assert!(a.allows_http("GET", "https://user:pw@api.example.org:8443/"));
514 }
515
516 #[test]
517 fn the_embedder_grants_at_most() {
518 let a = Access {
519 declared: caps(
520 r#"{ "network": { "hosts": ["a.com", "b.com"] }, "statusBar": true, "clipboard": true }"#,
521 ),
522 granted: Some(caps(
523 r#"{ "network": { "hosts": ["b.com"] }, "clipboard": true }"#,
524 )),
525 };
526 assert!(a.allows_clipboard());
527 assert!(!a.allows_http("GET", "https://a.com/"));
528 assert!(a.allows_http("GET", "https://b.com/"));
529 assert!(!a.allows_status_bar());
530 }
531
532 #[test]
533 fn typos_are_errors() {
534 let bad =
535 |json: &str| Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap_err();
536 assert!(bad(r#"{ "netwrok": {} }"#).contains("unknown key `netwrok`"));
537 assert!(bad(r#"{ "network": { "host": [] } }"#).contains("unknown key `host`"));
538 assert!(bad(r#"{ "network": { "hosts": ["exa mple.com"] } }"#).contains("invalid host"));
539 let c = caps(
540 r#"{ "network": { "hosts": ["a.com"], "http": [{ "host": "b.com", "methods": ["GET"] }] }, "webview": { "hosts": ["*"] } }"#,
541 );
542 assert_eq!(Capabilities::from_json(&c.to_json()).unwrap(), c);
543 }
544
545 #[test]
546 fn media_redirects_are_checked() {
547 let a = Access {
548 declared: Capabilities::from_json(
549 &serde_json::json!({ "network": { "hosts": ["a.com"] } }),
550 )
551 .unwrap(),
552 granted: None,
553 };
554 let from = "https://a.com/x/y.png";
555 assert_eq!(
556 a.media_redirect(from, "/z.png").unwrap(),
557 "https://a.com/z.png"
558 );
559 assert_eq!(
560 a.media_redirect(from, "z.png").unwrap(),
561 "https://a.com/x/z.png"
562 );
563 assert!(a.media_redirect(from, "https://b.com/z.png").is_err());
564 assert!(a.media_redirect(from, "//b.com/z.png").is_err());
565 assert!(a.media_redirect(from, "file:///etc/passwd").is_err());
566 assert!(
567 Access::default()
568 .media_redirect(from, "//b.com/z.png")
569 .is_ok()
570 );
571 assert!(
572 Access::default()
573 .media_redirect(from, "ftp://b.com/z.png")
574 .is_err()
575 );
576 }
577}