Skip to main content

rightkit_browser/
policy.rs

1//! Effect admission, network (SSRF/host) policy, and lifecycle events.
2//!
3//! Order per effect (EFF-001): the [`NetworkPolicy`] (policy stage) decides
4//! first, then the caller-supplied [`AdmissionHook`] (approval stage) sees a
5//! typed [`AdmissionRequest`]; a denial at either stage happens before any side
6//! effect. Every network request a page makes, including redirect hops and
7//! subresources, is checked again inside the browser before it leaves the
8//! machine, and every TCP connection Chrome opens goes through an in-process
9//! pinning proxy that re-checks the address it actually connects to.
10//!
11//! Default policy blocks:
12//! * loopback (`127.0.0.0/8`, `::1`, `localhost`, `*.localhost`),
13//! * link-local (`169.254.0.0/16`, `fe80::/10`) including the cloud metadata
14//!   address `169.254.169.254` and the `metadata.google.internal` names. These
15//!   are *hard* blocks: no allow list, address-class allowance, or callback can
16//!   open them unless [`NetworkPolicy::hard_block_link_local`] is turned off,
17//! * private (`10/8`, `172.16/12`, `192.168/16`, `100.64/10` CGNAT,
18//!   `fc00::/7`, `fec0::/10`), unspecified (`0.0.0.0/8`, `::`), multicast,
19//!   and reserved/documentation/benchmark ranges,
20//! * IPv6 forms that embed one of the above IPv4 addresses
21//!   (`::ffff:a.b.c.d` mapped, `::a.b.c.d` compatible, `64:ff9b::/96` NAT64,
22//!   `2002::/16` 6to4),
23//! * hosts that do not resolve (fail closed),
24//! * every scheme other than `http`/`https` (`file:`, `ws:`, `chrome:`, ...)
25//!   unless listed in [`NetworkPolicy::allowed_schemes`]. `about:blank`, and
26//!   `data:`/`blob:` *subresources*, never touch the network and are allowed;
27//!   `data:`/`blob:` *documents* need the scheme to be allowed.
28//!
29//! Hostnames are resolved and every resolved address is checked (the worst
30//! address decides). The resolution is cached and shared with the pinning
31//! proxy, and the proxy only connects to addresses the request check vetted,
32//! so a name that rebinds from public to private between check and connect
33//! cannot reach a blocked address.
34//!
35//! Traffic page interception never sees (WebSocket handshakes, requests from
36//! dedicated/shared/service workers, Chrome's own fetchers) still reaches the
37//! pinning proxy. When a per-request callback is set, the proxy runs the same
38//! check for every `host:port` no page check of this session allowed, with
39//! resource type `Connect` and URL `https://host:port/` (a plain-HTTP proxy
40//! request is checked with its full URL); a refusal is a typed `Denied` event
41//! with `what = "Connect"` and nothing is connected (#925).
42//!
43//! A [`DestinationFilter`] (installed with [`NetworkPolicy::with_destination_filter`]) closes the
44//! list by resource class: a script, a worker, a fetch, an XHR, a WebSocket and every other
45//! connection must go to a listed host and port, not only the page address. It runs in the same
46//! place as the per-request callback, for page requests and for proxied connections alike, can only
47//! deny (a request it permits still meets every default block above), and cannot be dropped by a
48//! later [`NetworkPolicy::allow_with`].
49//!
50//! Known gaps (documented, not silently covered):
51//! * For that non-intercepted traffic the callback decides per `host:port`
52//!   only; path-level decisions apply only to intercepted requests. A closed
53//!   allowlist must return `Deny` for everything else: `Default` (or `false`)
54//!   leaves public destinations allowed, as for any request.
55//! * Once a page check allows a `host:port`, later non-intercepted traffic to
56//!   the same pair is not decided again.
57//! * [`crate::BrowserSession::pinned_connections`] also records failed
58//!   connection attempts, so it is not an egress audit on its own.
59//! * WebRTC UDP is restricted to proxied routes by Chrome flag; this is not
60//!   independently verified by a test.
61
62use futures::future::BoxFuture;
63use std::collections::{HashMap, HashSet};
64use std::fmt;
65use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
66use std::sync::{Arc, Mutex};
67use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
68
69// ---------------------------------------------------------------------------
70// Admission (approval stage)
71// ---------------------------------------------------------------------------
72
73#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
74pub enum ActionKind {
75    Navigate,
76    Reload,
77    History,
78    Click,
79    DoubleClick,
80    Hover,
81    Drag,
82    Wheel,
83    Press,
84    TypeText,
85    Fill,
86    Select,
87    Upload,
88    Eval,
89}
90
91/// One typed request to perform an effect. Typed text is never included, only
92/// its length, so admission logs stay content-free.
93#[derive(Clone, Debug)]
94pub struct AdmissionRequest {
95    pub session_id: String,
96    pub page_id: String,
97    pub action: ActionKind,
98    /// Destination for `Navigate`; otherwise the page's current URL.
99    pub url: Option<String>,
100    /// Human-readable target (selector, ref, point, key chord, file path).
101    pub target: Option<String>,
102    /// Extra detail: script source for `Eval`, `chars=N` for typing.
103    pub detail: Option<String>,
104}
105
106#[derive(Clone, Debug, Eq, PartialEq)]
107pub enum Decision {
108    Allow,
109    Deny(String),
110}
111
112pub type AdmissionHook =
113    Arc<dyn Fn(AdmissionRequest) -> BoxFuture<'static, Decision> + Send + Sync>;
114
115// ---------------------------------------------------------------------------
116// Address classification
117// ---------------------------------------------------------------------------
118
119/// Address class of a destination. Everything except `Public` is blocked by default.
120#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
121pub enum AddressClass {
122    Public,
123    Loopback,
124    /// `169.254/16`, `fe80::/10`; includes the cloud metadata endpoint.
125    LinkLocal,
126    /// RFC 1918, CGNAT `100.64/10`, ULA `fc00::/7`, site-local `fec0::/10`.
127    Private,
128    /// IETF protocol assignments, documentation, benchmarking, `240/4`,
129    /// broadcast, `2001:db8::/32`, Teredo.
130    Reserved,
131    Unspecified,
132    Multicast,
133}
134
135pub fn classify_ip(ip: IpAddr) -> AddressClass {
136    match ip {
137        IpAddr::V4(v4) => classify_v4(v4),
138        IpAddr::V6(v6) => classify_v6(v6),
139    }
140}
141
142fn classify_v4(ip: Ipv4Addr) -> AddressClass {
143    let [a, b, c, _] = ip.octets();
144    if a == 127 {
145        AddressClass::Loopback
146    } else if a == 0 {
147        AddressClass::Unspecified
148    } else if a == 169 && b == 254 {
149        AddressClass::LinkLocal
150    } else if a == 10
151        || (a == 172 && (16..=31).contains(&b))
152        || (a == 192 && b == 168)
153        || (a == 100 && (64..=127).contains(&b))
154    {
155        AddressClass::Private
156    } else if (224..=239).contains(&a) {
157        AddressClass::Multicast
158    } else if a >= 240
159        || (a == 192 && b == 0 && c == 0)
160        || (a == 192 && b == 0 && c == 2)
161        || (a == 198 && (b == 18 || b == 19))
162        || (a == 198 && b == 51 && c == 100)
163        || (a == 203 && b == 0 && c == 113)
164    {
165        AddressClass::Reserved
166    } else {
167        AddressClass::Public
168    }
169}
170
171fn v4_from_segments(hi: u16, lo: u16) -> Ipv4Addr {
172    Ipv4Addr::new((hi >> 8) as u8, hi as u8, (lo >> 8) as u8, lo as u8)
173}
174
175fn classify_v6(v6: Ipv6Addr) -> AddressClass {
176    let s = v6.segments();
177    if v6.is_loopback() {
178        return AddressClass::Loopback;
179    }
180    if v6.is_unspecified() {
181        return AddressClass::Unspecified;
182    }
183    // ::ffff:a.b.c.d (IPv4-mapped).
184    if let Some(v4) = v6.to_ipv4_mapped() {
185        return classify_v4(v4);
186    }
187    // ::a.b.c.d (deprecated IPv4-compatible).
188    if s[..6] == [0, 0, 0, 0, 0, 0] {
189        return classify_v4(v4_from_segments(s[6], s[7]));
190    }
191    // 64:ff9b::/96 (NAT64) embeds an IPv4 address in the low 32 bits.
192    if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {
193        return classify_v4(v4_from_segments(s[6], s[7]));
194    }
195    // 2002::/16 (6to4) embeds an IPv4 address in bits 16..48.
196    if s[0] == 0x2002 {
197        return classify_v4(v4_from_segments(s[1], s[2]));
198    }
199    if v6.is_multicast() {
200        AddressClass::Multicast
201    } else if s[0] & 0xffc0 == 0xfe80 {
202        AddressClass::LinkLocal
203    } else if s[0] & 0xfe00 == 0xfc00 || s[0] & 0xffc0 == 0xfec0 {
204        AddressClass::Private
205    } else if (s[0] == 0x2001 && s[1] == 0x0db8) || (s[0] == 0x2001 && s[1] == 0) {
206        AddressClass::Reserved
207    } else {
208        AddressClass::Public
209    }
210}
211
212/// Hostnames that always mean "cloud instance metadata".
213fn is_metadata_host(host: &str) -> bool {
214    matches!(
215        host,
216        "metadata" | "metadata.google.internal" | "metadata.goog" | "instance-data"
217    ) || host.ends_with(".metadata.google.internal")
218}
219
220/// Lowercase, strip IPv6 brackets and one trailing dot.
221fn normalize_host(host: &str) -> String {
222    let h = host.trim_matches(['[', ']']).to_ascii_lowercase();
223    h.strip_suffix('.').map(str::to_string).unwrap_or(h)
224}
225
226// ---------------------------------------------------------------------------
227// Network policy (policy stage)
228// ---------------------------------------------------------------------------
229
230/// Why the network policy refused a request.
231#[derive(Clone, Debug, Eq, PartialEq)]
232pub enum BlockReason {
233    InvalidUrl(String),
234    /// The scheme is not in `allowed_schemes`.
235    Scheme(String),
236    NoHost,
237    /// The host has no addresses (fail closed).
238    Unresolved {
239        host: String,
240    },
241    /// The host is, or resolves to, a blocked address.
242    Address {
243        host: String,
244        ip: IpAddr,
245        class: AddressClass,
246    },
247    /// A cloud metadata hostname.
248    MetadataHost {
249        host: String,
250    },
251    /// The per-request callback denied it.
252    Callback(String),
253}
254
255impl BlockReason {
256    /// True when no allow list, class allowance, or callback can override it.
257    pub fn is_hard(&self, hard_block_link_local: bool) -> bool {
258        hard_block_link_local
259            && matches!(
260                self,
261                BlockReason::MetadataHost { .. }
262                    | BlockReason::Address {
263                        class: AddressClass::LinkLocal,
264                        ..
265                    }
266            )
267    }
268}
269
270impl fmt::Display for BlockReason {
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        match self {
273            BlockReason::InvalidUrl(e) => write!(f, "unparseable url: {e}"),
274            BlockReason::Scheme(s) => write!(f, "scheme '{s}' is blocked"),
275            BlockReason::NoHost => write!(f, "request has no host"),
276            BlockReason::Unresolved { host } => write!(f, "host '{host}' did not resolve"),
277            BlockReason::Address { host, ip, class } => {
278                if host == &ip.to_string() {
279                    write!(f, "address {ip} is {class:?}")
280                } else {
281                    write!(f, "host '{host}' resolves to {class:?} address {ip}")
282                }
283            }
284            BlockReason::MetadataHost { host } => {
285                write!(f, "host '{host}' is a cloud metadata endpoint")
286            }
287            BlockReason::Callback(r) => write!(f, "denied by policy callback: {r}"),
288        }
289    }
290}
291
292/// Typed network-policy denial returned as [`crate::BrowserError::Blocked`].
293#[derive(Clone, Debug, Eq, PartialEq)]
294pub struct PolicyDenial {
295    pub url: String,
296    pub resource_type: String,
297    pub reason: BlockReason,
298}
299
300impl fmt::Display for PolicyDenial {
301    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302        write!(f, "{} ({}): {}", self.url, self.resource_type, self.reason)
303    }
304}
305
306/// One network request about to leave the browser, as seen by the allow callback.
307#[derive(Clone, Debug)]
308pub struct BrowserRequest {
309    pub url: String,
310    pub scheme: String,
311    /// Normalized host; empty for host-less schemes (`file:`, `data:`).
312    pub host: String,
313    pub port: Option<u16>,
314    /// Worst class across `addresses`; `None` for host-less schemes.
315    pub class: Option<AddressClass>,
316    /// Every address the host resolved to (all are checked).
317    pub addresses: Vec<IpAddr>,
318    /// `Navigation`, `Document`, `Image`, `Script`, `Fetch`, ...
319    pub resource_type: String,
320    /// What the defaults would do: `None` allows, `Some(reason)` blocks.
321    pub default_block: Option<BlockReason>,
322}
323
324/// Former name, kept for existing callers.
325pub type NetworkRequest = BrowserRequest;
326
327/// Answer of the per-request allow callback.
328#[derive(Clone, Debug, Eq, PartialEq)]
329pub enum PolicyDecision {
330    /// Allow, overriding a default block (hard blocks still apply).
331    Allow,
332    /// Deny, even if the defaults would allow.
333    Deny(String),
334    /// Apply the configured defaults.
335    Default,
336}
337
338/// `true` allows, `false` defers to the defaults.
339impl From<bool> for PolicyDecision {
340    fn from(b: bool) -> Self {
341        if b {
342            PolicyDecision::Allow
343        } else {
344            PolicyDecision::Default
345        }
346    }
347}
348
349pub type AllowCallback = Arc<dyn Fn(&BrowserRequest) -> PolicyDecision + Send + Sync>;
350pub type Resolver = Arc<dyn Fn(&str) -> Vec<IpAddr> + Send + Sync>;
351
352/// Per-host resolution shared by the request check and the pinning proxy.
353type ResolvedCache = Arc<Mutex<HashMap<String, (Instant, Vec<IpAddr>)>>>;
354
355/// Typed SSRF/host policy. See the module docs for defaults.
356#[derive(Clone)]
357pub struct NetworkPolicy {
358    /// Hosts (exact, case-insensitive) allowed even when their address class is blocked.
359    pub allow_hosts: Vec<String>,
360    /// Address classes allowed for every host (e.g. `Loopback` for local dev servers).
361    pub allow_classes: Vec<AddressClass>,
362    /// Lowercase schemes that may be requested. Default `["http", "https"]`.
363    pub allowed_schemes: Vec<String>,
364    /// Called for every checked request; see [`PolicyDecision`].
365    pub allow_request: Option<AllowCallback>,
366    /// Link-local and metadata destinations cannot be allowed (default `true`).
367    pub hard_block_link_local: bool,
368    /// Disable every check (trusted callers only).
369    pub unrestricted: bool,
370    /// Replaces the system resolver (offline tests, pinned DNS, split-horizon setups).
371    pub resolver: Option<Resolver>,
372    resolved: ResolvedCache,
373    /// Non-public addresses an explicit allow let through, per host.
374    approved: Arc<Mutex<HashMap<String, Vec<IpAddr>>>>,
375    /// The closed destination list, when one is installed.
376    destinations: Option<DestinationFilter>,
377}
378
379impl Default for NetworkPolicy {
380    fn default() -> Self {
381        Self {
382            allow_hosts: Vec::new(),
383            allow_classes: Vec::new(),
384            allowed_schemes: vec!["http".into(), "https".into()],
385            allow_request: None,
386            hard_block_link_local: true,
387            unrestricted: false,
388            resolver: None,
389            resolved: ResolvedCache::default(),
390            approved: Arc::default(),
391            destinations: None,
392        }
393    }
394}
395
396impl fmt::Debug for NetworkPolicy {
397    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
398        f.debug_struct("NetworkPolicy")
399            .field("allow_hosts", &self.allow_hosts)
400            .field("allow_classes", &self.allow_classes)
401            .field("allowed_schemes", &self.allowed_schemes)
402            .field("allow_request", &self.allow_request.is_some())
403            .field("hard_block_link_local", &self.hard_block_link_local)
404            .field("unrestricted", &self.unrestricted)
405            .field("destinations", &self.destinations)
406            .finish()
407    }
408}
409
410/// Copy of the old string-only blocked record, kept per page.
411#[derive(Clone, Debug, Eq, PartialEq)]
412pub struct BlockedRequest {
413    pub url: String,
414    pub reason: String,
415}
416
417// ---------------------------------------------------------------------------
418// Destination filter (script, worker, fetch and socket destinations)
419// ---------------------------------------------------------------------------
420
421/// What a request is for, from its resource type. Unknown types count as [`ResourceClass::Connect`],
422/// the most restricted class.
423#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
424pub enum ResourceClass {
425    /// A navigation or a document, frames included.
426    Document,
427    /// A script or a worker script.
428    Script,
429    /// A request that carries data out: fetch, XHR, WebSocket, event source, ping, preflight, report,
430    /// a proxied connection and anything not named elsewhere.
431    Connect,
432    /// A stylesheet, image, media, font, text track or manifest. These can still carry data in a
433    /// query string, so a closed list covers them too.
434    Passive,
435}
436
437impl ResourceClass {
438    /// Every class.
439    pub const ALL: [ResourceClass; 4] = [
440        ResourceClass::Document,
441        ResourceClass::Script,
442        ResourceClass::Connect,
443        ResourceClass::Passive,
444    ];
445
446    /// The class of a resource type as the network check names it (`Navigation`, `Document`,
447    /// `Script`, `XHR`, `Fetch`, `WebSocket`, `Connect`, ...).
448    pub fn of(resource_type: &str) -> Self {
449        match resource_type {
450            "Navigation" | "Document" => ResourceClass::Document,
451            "Script" | "Worker" | "SharedWorker" | "ServiceWorker" => ResourceClass::Script,
452            "Stylesheet" | "Image" | "Media" | "Font" | "TextTrack" | "Manifest" => {
453                ResourceClass::Passive
454            }
455            _ => ResourceClass::Connect,
456        }
457    }
458}
459
460#[derive(Clone, Debug, Eq, PartialEq)]
461enum HostMatch {
462    Exact(String),
463    /// The domain itself and every subdomain of it, on a label boundary.
464    Subdomains(String),
465}
466
467/// One allowed destination: a host (exact, or a domain with its subdomains), the ports it may be
468/// reached on and the resource classes it may serve. Only `https` and `wss` ever match; a plaintext
469/// scheme does not, so a credentialed session never speaks `http` or `ws`.
470#[derive(Clone, Debug, Eq, PartialEq)]
471pub struct DestinationRule {
472    host: HostMatch,
473    ports: Vec<u16>,
474    classes: Vec<ResourceClass>,
475}
476
477/// A plain DNS name of at least two labels: no wildcard, scheme, port, path or IP address. Whether a
478/// domain is a public suffix (`co.uk`) is not known here; naming one allows every site under it.
479fn check_rule_host(host: &str) -> crate::error::Result<String> {
480    let h = normalize_host(host);
481    let ok = !h.is_empty()
482        && h.len() <= 253
483        && h.parse::<IpAddr>().is_err()
484        && h.split('.').count() >= 2
485        && h.split('.').all(|l| {
486            !l.is_empty()
487                && l.len() <= 63
488                && !l.starts_with('-')
489                && !l.ends_with('-')
490                && l.bytes()
491                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
492        });
493    if ok {
494        Ok(h)
495    } else {
496        Err(crate::error::BrowserError::Invalid(
497            "a destination rule host must be a plain DNS name of two labels or more (no wildcard, scheme, port, path or IP address)"
498                .into(),
499        ))
500    }
501}
502
503impl DestinationRule {
504    /// One host, exactly. Port 443 and every resource class until narrowed.
505    pub fn exact(host: &str) -> crate::error::Result<Self> {
506        Ok(Self {
507            host: HostMatch::Exact(check_rule_host(host)?),
508            ports: vec![443],
509            classes: ResourceClass::ALL.to_vec(),
510        })
511    }
512
513    /// A domain and every subdomain of it (`example.com` and `a.example.com`, never `notexample.com`).
514    /// Port 443 and every resource class until narrowed.
515    pub fn subdomains_of(domain: &str) -> crate::error::Result<Self> {
516        Ok(Self {
517            host: HostMatch::Subdomains(check_rule_host(domain)?),
518            ports: vec![443],
519            classes: ResourceClass::ALL.to_vec(),
520        })
521    }
522
523    /// Replace the allowed ports. An empty list allows none, so the rule never matches.
524    pub fn on_ports(mut self, ports: &[u16]) -> Self {
525        self.ports = ports.to_vec();
526        self
527    }
528
529    /// Replace the allowed resource classes. An empty list allows none, so the rule never matches.
530    pub fn for_classes(mut self, classes: &[ResourceClass]) -> Self {
531        self.classes = classes.to_vec();
532        self
533    }
534
535    fn matches(&self, host: &str, port: u16, class: ResourceClass) -> bool {
536        let host_ok = match &self.host {
537            HostMatch::Exact(h) => host == h,
538            HostMatch::Subdomains(d) => {
539                host == d
540                    || host
541                        .strip_suffix(d.as_str())
542                        .is_some_and(|prefix| prefix.ends_with('.'))
543            }
544        };
545        host_ok && self.ports.contains(&port) && self.classes.contains(&class)
546    }
547}
548
549/// A closed list of destinations. A request that matches no rule is denied, whatever its class;
550/// a request that matches one is left to the defaults and the per-request callback, never allowed
551/// over a default block. Install it with [`NetworkPolicy::with_destination_filter`].
552///
553/// This is what makes script, worker, fetch, XHR and socket destinations as filtered as the page
554/// address: each hop of a redirect, each subresource and each proxied connection is decided by its
555/// own host, port and class. An empty filter denies every networked request.
556#[derive(Clone, Debug, Default, Eq, PartialEq)]
557pub struct DestinationFilter {
558    rules: Vec<DestinationRule>,
559}
560
561impl DestinationFilter {
562    pub fn new() -> Self {
563        Self::default()
564    }
565
566    pub fn rule(mut self, rule: DestinationRule) -> Self {
567        self.rules.push(rule);
568        self
569    }
570
571    pub fn rules(&self) -> &[DestinationRule] {
572        &self.rules
573    }
574
575    /// True when some rule lists this request's scheme, host, port and class.
576    pub fn permits(&self, request: &BrowserRequest) -> bool {
577        if !matches!(request.scheme.as_str(), "https" | "wss") || request.host.is_empty() {
578            return false;
579        }
580        let Some(port) = request.port else {
581            return false;
582        };
583        let class = ResourceClass::of(&request.resource_type);
584        self.rules
585            .iter()
586            .any(|rule| rule.matches(&request.host, port, class))
587    }
588
589    /// `Default` when permitted, otherwise `Deny`. Never `Allow`. The reason names the class, host
590    /// and port, never the URL, so a query string cannot reach a log.
591    pub fn decide(&self, request: &BrowserRequest) -> PolicyDecision {
592        if self.permits(request) {
593            return PolicyDecision::Default;
594        }
595        let target = match request.port {
596            Some(port) => format!("{}:{port}", request.host),
597            None => request.host.clone(),
598        };
599        PolicyDecision::Deny(format!(
600            "{:?} destination {target} is not on the destination list",
601            ResourceClass::of(&request.resource_type)
602        ))
603    }
604}
605
606impl NetworkPolicy {
607    /// Policy with every check off.
608    pub fn unrestricted() -> Self {
609        Self {
610            unrestricted: true,
611            ..Self::default()
612        }
613    }
614
615    pub fn allow_host(mut self, host: impl Into<String>) -> Self {
616        self.allow_hosts.push(normalize_host(&host.into()));
617        self
618    }
619
620    pub fn allow_class(mut self, class: AddressClass) -> Self {
621        self.allow_classes.push(class);
622        self
623    }
624
625    pub fn allow_scheme(mut self, scheme: impl Into<String>) -> Self {
626        self.allowed_schemes
627            .push(scheme.into().to_ascii_lowercase());
628        self
629    }
630
631    pub fn hard_block_link_local(mut self, on: bool) -> Self {
632        self.hard_block_link_local = on;
633        self
634    }
635
636    pub fn with_resolver(
637        mut self,
638        f: impl Fn(&str) -> Vec<IpAddr> + Send + Sync + 'static,
639    ) -> Self {
640        self.resolver = Some(Arc::new(f));
641        self
642    }
643
644    /// Per-request callback. Returning `bool` works too: `true` allows,
645    /// `false` defers to the defaults.
646    pub fn allow_with<D: Into<PolicyDecision>>(
647        mut self,
648        f: impl Fn(&BrowserRequest) -> D + Send + Sync + 'static,
649    ) -> Self {
650        self.allow_request = Some(Arc::new(move |r| f(r).into()));
651        self
652    }
653
654    /// Close the destination list (see [`DestinationFilter`]). It also turns `unrestricted` off, so
655    /// a filter is never silently ignored; it composes with [`Self::allow_with`] in either order and
656    /// runs first.
657    pub fn with_destination_filter(mut self, filter: DestinationFilter) -> Self {
658        self.unrestricted = false;
659        self.destinations = Some(filter);
660        self
661    }
662
663    fn scheme_allowed(&self, scheme: &str) -> bool {
664        self.allowed_schemes.iter().any(|s| s == scheme)
665    }
666
667    fn address_allowed(&self, host: &str, class: AddressClass) -> bool {
668        class == AddressClass::Public
669            || self.allow_classes.contains(&class)
670            || self.allow_hosts.iter().any(|h| h == host)
671    }
672
673    /// `Ok(())` when the request may proceed, otherwise why it is blocked.
674    pub async fn check(&self, url: &str, resource_type: &str) -> Result<(), BlockReason> {
675        if self.unrestricted {
676            return Ok(());
677        }
678        let parsed = url::Url::parse(url).map_err(|e| BlockReason::InvalidUrl(e.to_string()))?;
679        let scheme = parsed.scheme().to_ascii_lowercase();
680        let is_document = matches!(resource_type, "Navigation" | "Document");
681        if scheme == "about" && parsed.path() == "blank" {
682            return Ok(());
683        }
684        if matches!(scheme.as_str(), "data" | "blob") && !is_document {
685            return Ok(()); // inert subresource: never touches the network
686        }
687        let networked = matches!(scheme.as_str(), "http" | "https" | "ws" | "wss");
688        let mut default_block =
689            (!self.scheme_allowed(&scheme)).then(|| BlockReason::Scheme(scheme.clone()));
690        let mut host = String::new();
691        let mut class = None;
692        let mut addresses = Vec::new();
693        if networked {
694            host = normalize_host(parsed.host_str().unwrap_or(""));
695            if host.is_empty() {
696                return Err(BlockReason::NoHost);
697            }
698            if is_metadata_host(&host) {
699                let r = BlockReason::MetadataHost { host: host.clone() };
700                if r.is_hard(self.hard_block_link_local) {
701                    return Err(r);
702                }
703                default_block.get_or_insert(r);
704            }
705            let (c, worst, ips) = self.host_class(&host).await;
706            class = Some(c);
707            addresses = ips;
708            if addresses.is_empty() {
709                return Err(BlockReason::Unresolved { host });
710            }
711            if !self.address_allowed(&host, c)
712                || (c == AddressClass::LinkLocal && self.hard_block_link_local)
713            {
714                let r = BlockReason::Address {
715                    host: host.clone(),
716                    ip: worst,
717                    class: c,
718                };
719                if r.is_hard(self.hard_block_link_local) {
720                    return Err(r);
721                }
722                default_block.get_or_insert(r);
723            }
724        }
725        let decision = if self.allow_request.is_some() || self.destinations.is_some() {
726            let request = BrowserRequest {
727                url: url.to_string(),
728                scheme: scheme.clone(),
729                host: host.clone(),
730                port: parsed.port_or_known_default(),
731                class,
732                addresses: addresses.clone(),
733                resource_type: resource_type.to_string(),
734                default_block: default_block.clone(),
735            };
736            let listed = match &self.destinations {
737                Some(filter) => filter.decide(&request),
738                None => PolicyDecision::Default,
739            };
740            match (listed, &self.allow_request) {
741                (PolicyDecision::Deny(reason), _) => PolicyDecision::Deny(reason),
742                (_, Some(cb)) => cb(&request),
743                (_, None) => PolicyDecision::Default,
744            }
745        } else {
746            PolicyDecision::Default
747        };
748        let allowed = match decision {
749            PolicyDecision::Allow => true,
750            PolicyDecision::Deny(r) => return Err(BlockReason::Callback(r)),
751            PolicyDecision::Default => match default_block {
752                Some(r) => return Err(r),
753                None => true,
754            },
755        };
756        if allowed && networked && class != Some(AddressClass::Public) {
757            self.approved
758                .lock()
759                .unwrap()
760                .entry(host)
761                .or_default()
762                .extend(addresses);
763        }
764        Ok(())
765    }
766
767    /// Addresses the proxy may connect to for `host`: the same cached
768    /// resolution the request check used. A non-public address passes only if
769    /// its class is allowed, the host is listed, or the request check
770    /// explicitly approved that exact address, so anything that bypassed
771    /// interception (workers, rebinding) cannot reach a blocked range.
772    pub(crate) async fn pin(&self, host: &str) -> Result<Vec<IpAddr>, BlockReason> {
773        let host = normalize_host(host);
774        if self.hard_block_link_local && is_metadata_host(&host) {
775            return Err(BlockReason::MetadataHost { host });
776        }
777        let (_, _, ips) = self.host_class(&host).await;
778        if ips.is_empty() {
779            return Err(BlockReason::Unresolved { host });
780        }
781        let approved = self
782            .approved
783            .lock()
784            .unwrap()
785            .get(&host)
786            .cloned()
787            .unwrap_or_default();
788        for ip in &ips {
789            let class = classify_ip(*ip);
790            let hard = self.hard_block_link_local && class == AddressClass::LinkLocal;
791            let ok = !hard && (self.address_allowed(&host, class) || approved.contains(ip));
792            if !ok {
793                return Err(BlockReason::Address {
794                    host,
795                    ip: *ip,
796                    class,
797                });
798            }
799        }
800        Ok(ips)
801    }
802
803    /// Worst class across the host's addresses (any blocked address blocks the
804    /// host), the address that produced it, and every address.
805    async fn host_class(&self, host: &str) -> (AddressClass, IpAddr, Vec<IpAddr>) {
806        let unspecified = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
807        if let Ok(ip) = host.parse::<IpAddr>() {
808            return (classify_ip(ip), ip, vec![ip]);
809        }
810        if host == "localhost" || host.ends_with(".localhost") {
811            let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
812            return (AddressClass::Loopback, ip, vec![ip]);
813        }
814        let addrs = self.resolve(host).await;
815        let worst = addrs
816            .iter()
817            .copied()
818            .find(|ip| classify_ip(*ip) != AddressClass::Public);
819        match worst {
820            Some(ip) => (classify_ip(ip), ip, addrs),
821            None => (
822                AddressClass::Public,
823                addrs.first().copied().unwrap_or(unspecified),
824                addrs,
825            ),
826        }
827    }
828
829    async fn resolve(&self, host: &str) -> Vec<IpAddr> {
830        const TTL: Duration = Duration::from_secs(30);
831        if let Some((at, v)) = self.resolved.lock().unwrap().get(host) {
832            if at.elapsed() < TTL {
833                return v.clone();
834            }
835        }
836        let found: Vec<IpAddr> = if let Some(r) = &self.resolver {
837            r(host)
838        } else {
839            match tokio::time::timeout(Duration::from_secs(3), tokio::net::lookup_host((host, 0)))
840                .await
841            {
842                Ok(Ok(it)) => it.map(|a| a.ip()).collect(),
843                _ => Vec::new(), // fail closed: an unresolved host is refused
844            }
845        };
846        self.resolved
847            .lock()
848            .unwrap()
849            .insert(host.to_string(), (Instant::now(), found.clone()));
850        found
851    }
852}
853
854// ---------------------------------------------------------------------------
855// Lifecycle events
856// ---------------------------------------------------------------------------
857
858#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
859pub enum LifecycleKind {
860    Start,
861    Stop,
862    /// Chrome or a renderer died without being asked to.
863    Crash,
864    /// Admission or network policy refused something before any side effect.
865    Denied,
866}
867
868impl LifecycleKind {
869    pub fn label(self) -> &'static str {
870        match self {
871            LifecycleKind::Start => "start",
872            LifecycleKind::Stop => "stop",
873            LifecycleKind::Crash => "crash",
874            LifecycleKind::Denied => "denied",
875        }
876    }
877}
878
879/// One structured, content-free lifecycle event for the caller's journal.
880/// Never carries typed text, page content, or full URLs.
881#[derive(Clone, Debug)]
882pub struct BrowserEvent {
883    pub kind: LifecycleKind,
884    pub session_id: String,
885    pub reason: String,
886    pub at: SystemTime,
887    pub page_id: Option<String>,
888    /// Chrome's OS process id (start/stop/crash).
889    pub pid: Option<u32>,
890    /// What was denied: an [`ActionKind`] name, a resource type, or `Connect`.
891    pub what: Option<String>,
892    /// Typed network-policy reason for `Denied` events from the network policy.
893    pub blocked: Option<BlockReason>,
894}
895
896impl BrowserEvent {
897    pub(crate) fn new(kind: LifecycleKind, session_id: &str, reason: impl Into<String>) -> Self {
898        Self {
899            kind,
900            session_id: session_id.to_string(),
901            reason: reason.into(),
902            at: SystemTime::now(),
903            page_id: None,
904            pid: None,
905            what: None,
906            blocked: None,
907        }
908    }
909
910    pub fn timestamp_ms(&self) -> u64 {
911        self.at
912            .duration_since(UNIX_EPOCH)
913            .map(|d| d.as_millis() as u64)
914            .unwrap_or(0)
915    }
916
917    pub fn to_json(&self) -> serde_json::Value {
918        serde_json::json!({
919            "event": self.kind.label(),
920            "session_id": self.session_id,
921            "reason": self.reason,
922            "ts_ms": self.timestamp_ms(),
923            "page_id": self.page_id,
924            "pid": self.pid,
925            "what": self.what,
926        })
927    }
928}
929
930pub type EventSink = Arc<dyn Fn(&BrowserEvent) + Send + Sync>;
931
932/// Everything pages share about effect control.
933pub(crate) struct Guard {
934    pub session_id: String,
935    pub admission: Option<AdmissionHook>,
936    pub network: NetworkPolicy,
937    pub events: Option<EventSink>,
938    /// This session's `(host, port)` pairs a page request check allowed; the proxy does not
939    /// decide those again (#925).
940    pub page_allowed: Mutex<HashSet<(String, u16)>>,
941}
942
943/// The `(host, port)` an allowed networked request leaves for, keyed as the proxy sees it.
944fn networked_pair(url: &str) -> Option<(String, u16)> {
945    let parsed = url::Url::parse(url).ok()?;
946    if !matches!(parsed.scheme(), "http" | "https" | "ws" | "wss") {
947        return None;
948    }
949    let host = normalize_host(parsed.host_str()?);
950    Some((host, parsed.port_or_known_default()?))
951}
952
953/// The URL a CONNECT `host:port` is checked as; CONNECT has no path.
954fn connect_url(host: &str, port: u16) -> String {
955    let host = normalize_host(host);
956    if host.contains(':') {
957        format!("https://[{host}]:{port}/")
958    } else {
959        format!("https://{host}:{port}/")
960    }
961}
962
963impl Guard {
964    pub fn emit(&self, e: BrowserEvent) {
965        if let Some(s) = &self.events {
966            s(&e);
967        }
968    }
969
970    pub fn emit_kind(
971        &self,
972        kind: LifecycleKind,
973        reason: impl Into<String>,
974        f: impl FnOnce(&mut BrowserEvent),
975    ) {
976        let mut e = BrowserEvent::new(kind, &self.session_id, reason);
977        f(&mut e);
978        self.emit(e);
979    }
980
981    pub fn denied_network(&self, page_id: Option<&str>, what: &str, reason: &BlockReason) {
982        self.emit_kind(LifecycleKind::Denied, reason.to_string(), |e| {
983            e.page_id = page_id.map(str::to_string);
984            e.what = Some(what.to_string());
985            e.blocked = Some(reason.clone());
986        });
987    }
988
989    pub async fn admit(&self, req: AdmissionRequest) -> crate::error::Result<()> {
990        let what = format!("{:?}", req.action);
991        let page_id = req.page_id.clone();
992        if let Some(hook) = &self.admission {
993            if let Decision::Deny(reason) = hook(req).await {
994                self.emit_kind(LifecycleKind::Denied, reason.clone(), |e| {
995                    e.page_id = Some(page_id);
996                    e.what = Some(what);
997                });
998                return Err(crate::error::BrowserError::Denied(reason));
999            }
1000        }
1001        Ok(())
1002    }
1003
1004    /// [`NetworkPolicy::check`] for a request page interception saw. An allowed networked
1005    /// request records its `(host, port)` for this session.
1006    pub async fn check_request(&self, url: &str, kind: &str) -> Result<(), BlockReason> {
1007        self.network.check(url, kind).await?;
1008        if let Some(pair) = networked_pair(url) {
1009            self.page_allowed.lock().unwrap().insert(pair);
1010        }
1011        Ok(())
1012    }
1013
1014    /// The proxy's decision for one connection: CONNECT `host:port`, or a plain-HTTP `url`.
1015    /// With a per-request callback set, a pair no page check of this session allowed gets the
1016    /// same check page requests get, as resource type `Connect`; then the address is pinned.
1017    /// Without a callback the decision is the pin alone, as before.
1018    pub(crate) async fn admit_proxied(
1019        &self,
1020        host: &str,
1021        port: u16,
1022        url: Option<&str>,
1023    ) -> Result<Vec<IpAddr>, BlockReason> {
1024        let decide = (self.network.allow_request.is_some() || self.network.destinations.is_some())
1025            && !self
1026                .page_allowed
1027                .lock()
1028                .unwrap()
1029                .contains(&(normalize_host(host), port));
1030        if decide {
1031            let connect;
1032            let url = match url {
1033                Some(url) => url,
1034                None => {
1035                    connect = connect_url(host, port);
1036                    &connect
1037                }
1038            };
1039            self.network.check(url, "Connect").await?;
1040        }
1041        self.network.pin(host).await
1042    }
1043
1044    pub async fn check_url(
1045        &self,
1046        page_id: Option<&str>,
1047        url: &str,
1048        kind: &str,
1049    ) -> crate::error::Result<()> {
1050        match self.check_request(url, kind).await {
1051            Ok(()) => Ok(()),
1052            Err(reason) => {
1053                self.denied_network(page_id, kind, &reason);
1054                Err(crate::error::BrowserError::Blocked(PolicyDenial {
1055                    url: url.to_string(),
1056                    resource_type: kind.to_string(),
1057                    reason,
1058                }))
1059            }
1060        }
1061    }
1062}