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//! Known gaps (documented, not silently covered):
44//! * For that non-intercepted traffic the callback decides per `host:port`
45//!   only; path-level decisions apply only to intercepted requests. A closed
46//!   allowlist must return `Deny` for everything else: `Default` (or `false`)
47//!   leaves public destinations allowed, as for any request.
48//! * Once a page check allows a `host:port`, later non-intercepted traffic to
49//!   the same pair is not decided again.
50//! * [`crate::BrowserSession::pinned_connections`] also records failed
51//!   connection attempts, so it is not an egress audit on its own.
52//! * WebRTC UDP is restricted to proxied routes by Chrome flag; this is not
53//!   independently verified by a test.
54
55use futures::future::BoxFuture;
56use std::collections::{HashMap, HashSet};
57use std::fmt;
58use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
59use std::sync::{Arc, Mutex};
60use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
61
62// ---------------------------------------------------------------------------
63// Admission (approval stage)
64// ---------------------------------------------------------------------------
65
66#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
67pub enum ActionKind {
68    Navigate,
69    Reload,
70    History,
71    Click,
72    DoubleClick,
73    Hover,
74    Drag,
75    Wheel,
76    Press,
77    TypeText,
78    Fill,
79    Select,
80    Upload,
81    Eval,
82}
83
84/// One typed request to perform an effect. Typed text is never included, only
85/// its length, so admission logs stay content-free.
86#[derive(Clone, Debug)]
87pub struct AdmissionRequest {
88    pub session_id: String,
89    pub page_id: String,
90    pub action: ActionKind,
91    /// Destination for `Navigate`; otherwise the page's current URL.
92    pub url: Option<String>,
93    /// Human-readable target (selector, ref, point, key chord, file path).
94    pub target: Option<String>,
95    /// Extra detail: script source for `Eval`, `chars=N` for typing.
96    pub detail: Option<String>,
97}
98
99#[derive(Clone, Debug, Eq, PartialEq)]
100pub enum Decision {
101    Allow,
102    Deny(String),
103}
104
105pub type AdmissionHook =
106    Arc<dyn Fn(AdmissionRequest) -> BoxFuture<'static, Decision> + Send + Sync>;
107
108// ---------------------------------------------------------------------------
109// Address classification
110// ---------------------------------------------------------------------------
111
112/// Address class of a destination. Everything except `Public` is blocked by default.
113#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
114pub enum AddressClass {
115    Public,
116    Loopback,
117    /// `169.254/16`, `fe80::/10`; includes the cloud metadata endpoint.
118    LinkLocal,
119    /// RFC 1918, CGNAT `100.64/10`, ULA `fc00::/7`, site-local `fec0::/10`.
120    Private,
121    /// IETF protocol assignments, documentation, benchmarking, `240/4`,
122    /// broadcast, `2001:db8::/32`, Teredo.
123    Reserved,
124    Unspecified,
125    Multicast,
126}
127
128pub fn classify_ip(ip: IpAddr) -> AddressClass {
129    match ip {
130        IpAddr::V4(v4) => classify_v4(v4),
131        IpAddr::V6(v6) => classify_v6(v6),
132    }
133}
134
135fn classify_v4(ip: Ipv4Addr) -> AddressClass {
136    let [a, b, c, _] = ip.octets();
137    if a == 127 {
138        AddressClass::Loopback
139    } else if a == 0 {
140        AddressClass::Unspecified
141    } else if a == 169 && b == 254 {
142        AddressClass::LinkLocal
143    } else if a == 10
144        || (a == 172 && (16..=31).contains(&b))
145        || (a == 192 && b == 168)
146        || (a == 100 && (64..=127).contains(&b))
147    {
148        AddressClass::Private
149    } else if (224..=239).contains(&a) {
150        AddressClass::Multicast
151    } else if a >= 240
152        || (a == 192 && b == 0 && c == 0)
153        || (a == 192 && b == 0 && c == 2)
154        || (a == 198 && (b == 18 || b == 19))
155        || (a == 198 && b == 51 && c == 100)
156        || (a == 203 && b == 0 && c == 113)
157    {
158        AddressClass::Reserved
159    } else {
160        AddressClass::Public
161    }
162}
163
164fn v4_from_segments(hi: u16, lo: u16) -> Ipv4Addr {
165    Ipv4Addr::new((hi >> 8) as u8, hi as u8, (lo >> 8) as u8, lo as u8)
166}
167
168fn classify_v6(v6: Ipv6Addr) -> AddressClass {
169    let s = v6.segments();
170    if v6.is_loopback() {
171        return AddressClass::Loopback;
172    }
173    if v6.is_unspecified() {
174        return AddressClass::Unspecified;
175    }
176    // ::ffff:a.b.c.d (IPv4-mapped).
177    if let Some(v4) = v6.to_ipv4_mapped() {
178        return classify_v4(v4);
179    }
180    // ::a.b.c.d (deprecated IPv4-compatible).
181    if s[..6] == [0, 0, 0, 0, 0, 0] {
182        return classify_v4(v4_from_segments(s[6], s[7]));
183    }
184    // 64:ff9b::/96 (NAT64) embeds an IPv4 address in the low 32 bits.
185    if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {
186        return classify_v4(v4_from_segments(s[6], s[7]));
187    }
188    // 2002::/16 (6to4) embeds an IPv4 address in bits 16..48.
189    if s[0] == 0x2002 {
190        return classify_v4(v4_from_segments(s[1], s[2]));
191    }
192    if v6.is_multicast() {
193        AddressClass::Multicast
194    } else if s[0] & 0xffc0 == 0xfe80 {
195        AddressClass::LinkLocal
196    } else if s[0] & 0xfe00 == 0xfc00 || s[0] & 0xffc0 == 0xfec0 {
197        AddressClass::Private
198    } else if (s[0] == 0x2001 && s[1] == 0x0db8) || (s[0] == 0x2001 && s[1] == 0) {
199        AddressClass::Reserved
200    } else {
201        AddressClass::Public
202    }
203}
204
205/// Hostnames that always mean "cloud instance metadata".
206fn is_metadata_host(host: &str) -> bool {
207    matches!(
208        host,
209        "metadata" | "metadata.google.internal" | "metadata.goog" | "instance-data"
210    ) || host.ends_with(".metadata.google.internal")
211}
212
213/// Lowercase, strip IPv6 brackets and one trailing dot.
214fn normalize_host(host: &str) -> String {
215    let h = host.trim_matches(['[', ']']).to_ascii_lowercase();
216    h.strip_suffix('.').map(str::to_string).unwrap_or(h)
217}
218
219// ---------------------------------------------------------------------------
220// Network policy (policy stage)
221// ---------------------------------------------------------------------------
222
223/// Why the network policy refused a request.
224#[derive(Clone, Debug, Eq, PartialEq)]
225pub enum BlockReason {
226    InvalidUrl(String),
227    /// The scheme is not in `allowed_schemes`.
228    Scheme(String),
229    NoHost,
230    /// The host has no addresses (fail closed).
231    Unresolved {
232        host: String,
233    },
234    /// The host is, or resolves to, a blocked address.
235    Address {
236        host: String,
237        ip: IpAddr,
238        class: AddressClass,
239    },
240    /// A cloud metadata hostname.
241    MetadataHost {
242        host: String,
243    },
244    /// The per-request callback denied it.
245    Callback(String),
246}
247
248impl BlockReason {
249    /// True when no allow list, class allowance, or callback can override it.
250    pub fn is_hard(&self, hard_block_link_local: bool) -> bool {
251        hard_block_link_local
252            && matches!(
253                self,
254                BlockReason::MetadataHost { .. }
255                    | BlockReason::Address {
256                        class: AddressClass::LinkLocal,
257                        ..
258                    }
259            )
260    }
261}
262
263impl fmt::Display for BlockReason {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        match self {
266            BlockReason::InvalidUrl(e) => write!(f, "unparseable url: {e}"),
267            BlockReason::Scheme(s) => write!(f, "scheme '{s}' is blocked"),
268            BlockReason::NoHost => write!(f, "request has no host"),
269            BlockReason::Unresolved { host } => write!(f, "host '{host}' did not resolve"),
270            BlockReason::Address { host, ip, class } => {
271                if host == &ip.to_string() {
272                    write!(f, "address {ip} is {class:?}")
273                } else {
274                    write!(f, "host '{host}' resolves to {class:?} address {ip}")
275                }
276            }
277            BlockReason::MetadataHost { host } => {
278                write!(f, "host '{host}' is a cloud metadata endpoint")
279            }
280            BlockReason::Callback(r) => write!(f, "denied by policy callback: {r}"),
281        }
282    }
283}
284
285/// Typed network-policy denial returned as [`crate::BrowserError::Blocked`].
286#[derive(Clone, Debug, Eq, PartialEq)]
287pub struct PolicyDenial {
288    pub url: String,
289    pub resource_type: String,
290    pub reason: BlockReason,
291}
292
293impl fmt::Display for PolicyDenial {
294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295        write!(f, "{} ({}): {}", self.url, self.resource_type, self.reason)
296    }
297}
298
299/// One network request about to leave the browser, as seen by the allow callback.
300#[derive(Clone, Debug)]
301pub struct BrowserRequest {
302    pub url: String,
303    pub scheme: String,
304    /// Normalized host; empty for host-less schemes (`file:`, `data:`).
305    pub host: String,
306    pub port: Option<u16>,
307    /// Worst class across `addresses`; `None` for host-less schemes.
308    pub class: Option<AddressClass>,
309    /// Every address the host resolved to (all are checked).
310    pub addresses: Vec<IpAddr>,
311    /// `Navigation`, `Document`, `Image`, `Script`, `Fetch`, ...
312    pub resource_type: String,
313    /// What the defaults would do: `None` allows, `Some(reason)` blocks.
314    pub default_block: Option<BlockReason>,
315}
316
317/// Former name, kept for existing callers.
318pub type NetworkRequest = BrowserRequest;
319
320/// Answer of the per-request allow callback.
321#[derive(Clone, Debug, Eq, PartialEq)]
322pub enum PolicyDecision {
323    /// Allow, overriding a default block (hard blocks still apply).
324    Allow,
325    /// Deny, even if the defaults would allow.
326    Deny(String),
327    /// Apply the configured defaults.
328    Default,
329}
330
331/// `true` allows, `false` defers to the defaults.
332impl From<bool> for PolicyDecision {
333    fn from(b: bool) -> Self {
334        if b {
335            PolicyDecision::Allow
336        } else {
337            PolicyDecision::Default
338        }
339    }
340}
341
342pub type AllowCallback = Arc<dyn Fn(&BrowserRequest) -> PolicyDecision + Send + Sync>;
343pub type Resolver = Arc<dyn Fn(&str) -> Vec<IpAddr> + Send + Sync>;
344
345/// Per-host resolution shared by the request check and the pinning proxy.
346type ResolvedCache = Arc<Mutex<HashMap<String, (Instant, Vec<IpAddr>)>>>;
347
348/// Typed SSRF/host policy. See the module docs for defaults.
349#[derive(Clone)]
350pub struct NetworkPolicy {
351    /// Hosts (exact, case-insensitive) allowed even when their address class is blocked.
352    pub allow_hosts: Vec<String>,
353    /// Address classes allowed for every host (e.g. `Loopback` for local dev servers).
354    pub allow_classes: Vec<AddressClass>,
355    /// Lowercase schemes that may be requested. Default `["http", "https"]`.
356    pub allowed_schemes: Vec<String>,
357    /// Called for every checked request; see [`PolicyDecision`].
358    pub allow_request: Option<AllowCallback>,
359    /// Link-local and metadata destinations cannot be allowed (default `true`).
360    pub hard_block_link_local: bool,
361    /// Disable every check (trusted callers only).
362    pub unrestricted: bool,
363    /// Replaces the system resolver (offline tests, pinned DNS, split-horizon setups).
364    pub resolver: Option<Resolver>,
365    resolved: ResolvedCache,
366    /// Non-public addresses an explicit allow let through, per host.
367    approved: Arc<Mutex<HashMap<String, Vec<IpAddr>>>>,
368}
369
370impl Default for NetworkPolicy {
371    fn default() -> Self {
372        Self {
373            allow_hosts: Vec::new(),
374            allow_classes: Vec::new(),
375            allowed_schemes: vec!["http".into(), "https".into()],
376            allow_request: None,
377            hard_block_link_local: true,
378            unrestricted: false,
379            resolver: None,
380            resolved: ResolvedCache::default(),
381            approved: Arc::default(),
382        }
383    }
384}
385
386impl fmt::Debug for NetworkPolicy {
387    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
388        f.debug_struct("NetworkPolicy")
389            .field("allow_hosts", &self.allow_hosts)
390            .field("allow_classes", &self.allow_classes)
391            .field("allowed_schemes", &self.allowed_schemes)
392            .field("allow_request", &self.allow_request.is_some())
393            .field("hard_block_link_local", &self.hard_block_link_local)
394            .field("unrestricted", &self.unrestricted)
395            .finish()
396    }
397}
398
399/// Copy of the old string-only blocked record, kept per page.
400#[derive(Clone, Debug, Eq, PartialEq)]
401pub struct BlockedRequest {
402    pub url: String,
403    pub reason: String,
404}
405
406impl NetworkPolicy {
407    /// Policy with every check off.
408    pub fn unrestricted() -> Self {
409        Self {
410            unrestricted: true,
411            ..Self::default()
412        }
413    }
414
415    pub fn allow_host(mut self, host: impl Into<String>) -> Self {
416        self.allow_hosts.push(normalize_host(&host.into()));
417        self
418    }
419
420    pub fn allow_class(mut self, class: AddressClass) -> Self {
421        self.allow_classes.push(class);
422        self
423    }
424
425    pub fn allow_scheme(mut self, scheme: impl Into<String>) -> Self {
426        self.allowed_schemes
427            .push(scheme.into().to_ascii_lowercase());
428        self
429    }
430
431    pub fn hard_block_link_local(mut self, on: bool) -> Self {
432        self.hard_block_link_local = on;
433        self
434    }
435
436    pub fn with_resolver(
437        mut self,
438        f: impl Fn(&str) -> Vec<IpAddr> + Send + Sync + 'static,
439    ) -> Self {
440        self.resolver = Some(Arc::new(f));
441        self
442    }
443
444    /// Per-request callback. Returning `bool` works too: `true` allows,
445    /// `false` defers to the defaults.
446    pub fn allow_with<D: Into<PolicyDecision>>(
447        mut self,
448        f: impl Fn(&BrowserRequest) -> D + Send + Sync + 'static,
449    ) -> Self {
450        self.allow_request = Some(Arc::new(move |r| f(r).into()));
451        self
452    }
453
454    fn scheme_allowed(&self, scheme: &str) -> bool {
455        self.allowed_schemes.iter().any(|s| s == scheme)
456    }
457
458    fn address_allowed(&self, host: &str, class: AddressClass) -> bool {
459        class == AddressClass::Public
460            || self.allow_classes.contains(&class)
461            || self.allow_hosts.iter().any(|h| h == host)
462    }
463
464    /// `Ok(())` when the request may proceed, otherwise why it is blocked.
465    pub async fn check(&self, url: &str, resource_type: &str) -> Result<(), BlockReason> {
466        if self.unrestricted {
467            return Ok(());
468        }
469        let parsed = url::Url::parse(url).map_err(|e| BlockReason::InvalidUrl(e.to_string()))?;
470        let scheme = parsed.scheme().to_ascii_lowercase();
471        let is_document = matches!(resource_type, "Navigation" | "Document");
472        if scheme == "about" && parsed.path() == "blank" {
473            return Ok(());
474        }
475        if matches!(scheme.as_str(), "data" | "blob") && !is_document {
476            return Ok(()); // inert subresource: never touches the network
477        }
478        let networked = matches!(scheme.as_str(), "http" | "https" | "ws" | "wss");
479        let mut default_block =
480            (!self.scheme_allowed(&scheme)).then(|| BlockReason::Scheme(scheme.clone()));
481        let mut host = String::new();
482        let mut class = None;
483        let mut addresses = Vec::new();
484        if networked {
485            host = normalize_host(parsed.host_str().unwrap_or(""));
486            if host.is_empty() {
487                return Err(BlockReason::NoHost);
488            }
489            if is_metadata_host(&host) {
490                let r = BlockReason::MetadataHost { host: host.clone() };
491                if r.is_hard(self.hard_block_link_local) {
492                    return Err(r);
493                }
494                default_block.get_or_insert(r);
495            }
496            let (c, worst, ips) = self.host_class(&host).await;
497            class = Some(c);
498            addresses = ips;
499            if addresses.is_empty() {
500                return Err(BlockReason::Unresolved { host });
501            }
502            if !self.address_allowed(&host, c)
503                || (c == AddressClass::LinkLocal && self.hard_block_link_local)
504            {
505                let r = BlockReason::Address {
506                    host: host.clone(),
507                    ip: worst,
508                    class: c,
509                };
510                if r.is_hard(self.hard_block_link_local) {
511                    return Err(r);
512                }
513                default_block.get_or_insert(r);
514            }
515        }
516        let decision = match &self.allow_request {
517            Some(cb) => cb(&BrowserRequest {
518                url: url.to_string(),
519                scheme: scheme.clone(),
520                host: host.clone(),
521                port: parsed.port_or_known_default(),
522                class,
523                addresses: addresses.clone(),
524                resource_type: resource_type.to_string(),
525                default_block: default_block.clone(),
526            }),
527            None => PolicyDecision::Default,
528        };
529        let allowed = match decision {
530            PolicyDecision::Allow => true,
531            PolicyDecision::Deny(r) => return Err(BlockReason::Callback(r)),
532            PolicyDecision::Default => match default_block {
533                Some(r) => return Err(r),
534                None => true,
535            },
536        };
537        if allowed && networked && class != Some(AddressClass::Public) {
538            self.approved
539                .lock()
540                .unwrap()
541                .entry(host)
542                .or_default()
543                .extend(addresses);
544        }
545        Ok(())
546    }
547
548    /// Addresses the proxy may connect to for `host`: the same cached
549    /// resolution the request check used. A non-public address passes only if
550    /// its class is allowed, the host is listed, or the request check
551    /// explicitly approved that exact address, so anything that bypassed
552    /// interception (workers, rebinding) cannot reach a blocked range.
553    pub(crate) async fn pin(&self, host: &str) -> Result<Vec<IpAddr>, BlockReason> {
554        let host = normalize_host(host);
555        if self.hard_block_link_local && is_metadata_host(&host) {
556            return Err(BlockReason::MetadataHost { host });
557        }
558        let (_, _, ips) = self.host_class(&host).await;
559        if ips.is_empty() {
560            return Err(BlockReason::Unresolved { host });
561        }
562        let approved = self
563            .approved
564            .lock()
565            .unwrap()
566            .get(&host)
567            .cloned()
568            .unwrap_or_default();
569        for ip in &ips {
570            let class = classify_ip(*ip);
571            let hard = self.hard_block_link_local && class == AddressClass::LinkLocal;
572            let ok = !hard && (self.address_allowed(&host, class) || approved.contains(ip));
573            if !ok {
574                return Err(BlockReason::Address {
575                    host,
576                    ip: *ip,
577                    class,
578                });
579            }
580        }
581        Ok(ips)
582    }
583
584    /// Worst class across the host's addresses (any blocked address blocks the
585    /// host), the address that produced it, and every address.
586    async fn host_class(&self, host: &str) -> (AddressClass, IpAddr, Vec<IpAddr>) {
587        let unspecified = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
588        if let Ok(ip) = host.parse::<IpAddr>() {
589            return (classify_ip(ip), ip, vec![ip]);
590        }
591        if host == "localhost" || host.ends_with(".localhost") {
592            let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
593            return (AddressClass::Loopback, ip, vec![ip]);
594        }
595        let addrs = self.resolve(host).await;
596        let worst = addrs
597            .iter()
598            .copied()
599            .find(|ip| classify_ip(*ip) != AddressClass::Public);
600        match worst {
601            Some(ip) => (classify_ip(ip), ip, addrs),
602            None => (
603                AddressClass::Public,
604                addrs.first().copied().unwrap_or(unspecified),
605                addrs,
606            ),
607        }
608    }
609
610    async fn resolve(&self, host: &str) -> Vec<IpAddr> {
611        const TTL: Duration = Duration::from_secs(30);
612        if let Some((at, v)) = self.resolved.lock().unwrap().get(host) {
613            if at.elapsed() < TTL {
614                return v.clone();
615            }
616        }
617        let found: Vec<IpAddr> = if let Some(r) = &self.resolver {
618            r(host)
619        } else {
620            match tokio::time::timeout(Duration::from_secs(3), tokio::net::lookup_host((host, 0)))
621                .await
622            {
623                Ok(Ok(it)) => it.map(|a| a.ip()).collect(),
624                _ => Vec::new(), // fail closed: an unresolved host is refused
625            }
626        };
627        self.resolved
628            .lock()
629            .unwrap()
630            .insert(host.to_string(), (Instant::now(), found.clone()));
631        found
632    }
633}
634
635// ---------------------------------------------------------------------------
636// Lifecycle events
637// ---------------------------------------------------------------------------
638
639#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
640pub enum LifecycleKind {
641    Start,
642    Stop,
643    /// Chrome or a renderer died without being asked to.
644    Crash,
645    /// Admission or network policy refused something before any side effect.
646    Denied,
647}
648
649impl LifecycleKind {
650    pub fn label(self) -> &'static str {
651        match self {
652            LifecycleKind::Start => "start",
653            LifecycleKind::Stop => "stop",
654            LifecycleKind::Crash => "crash",
655            LifecycleKind::Denied => "denied",
656        }
657    }
658}
659
660/// One structured, content-free lifecycle event for the caller's journal.
661/// Never carries typed text, page content, or full URLs.
662#[derive(Clone, Debug)]
663pub struct BrowserEvent {
664    pub kind: LifecycleKind,
665    pub session_id: String,
666    pub reason: String,
667    pub at: SystemTime,
668    pub page_id: Option<String>,
669    /// Chrome's OS process id (start/stop/crash).
670    pub pid: Option<u32>,
671    /// What was denied: an [`ActionKind`] name, a resource type, or `Connect`.
672    pub what: Option<String>,
673    /// Typed network-policy reason for `Denied` events from the network policy.
674    pub blocked: Option<BlockReason>,
675}
676
677impl BrowserEvent {
678    pub(crate) fn new(kind: LifecycleKind, session_id: &str, reason: impl Into<String>) -> Self {
679        Self {
680            kind,
681            session_id: session_id.to_string(),
682            reason: reason.into(),
683            at: SystemTime::now(),
684            page_id: None,
685            pid: None,
686            what: None,
687            blocked: None,
688        }
689    }
690
691    pub fn timestamp_ms(&self) -> u64 {
692        self.at
693            .duration_since(UNIX_EPOCH)
694            .map(|d| d.as_millis() as u64)
695            .unwrap_or(0)
696    }
697
698    pub fn to_json(&self) -> serde_json::Value {
699        serde_json::json!({
700            "event": self.kind.label(),
701            "session_id": self.session_id,
702            "reason": self.reason,
703            "ts_ms": self.timestamp_ms(),
704            "page_id": self.page_id,
705            "pid": self.pid,
706            "what": self.what,
707        })
708    }
709}
710
711pub type EventSink = Arc<dyn Fn(&BrowserEvent) + Send + Sync>;
712
713/// Everything pages share about effect control.
714pub(crate) struct Guard {
715    pub session_id: String,
716    pub admission: Option<AdmissionHook>,
717    pub network: NetworkPolicy,
718    pub events: Option<EventSink>,
719    /// This session's `(host, port)` pairs a page request check allowed; the proxy does not
720    /// decide those again (#925).
721    pub page_allowed: Mutex<HashSet<(String, u16)>>,
722}
723
724/// The `(host, port)` an allowed networked request leaves for, keyed as the proxy sees it.
725fn networked_pair(url: &str) -> Option<(String, u16)> {
726    let parsed = url::Url::parse(url).ok()?;
727    if !matches!(parsed.scheme(), "http" | "https" | "ws" | "wss") {
728        return None;
729    }
730    let host = normalize_host(parsed.host_str()?);
731    Some((host, parsed.port_or_known_default()?))
732}
733
734/// The URL a CONNECT `host:port` is checked as; CONNECT has no path.
735fn connect_url(host: &str, port: u16) -> String {
736    let host = normalize_host(host);
737    if host.contains(':') {
738        format!("https://[{host}]:{port}/")
739    } else {
740        format!("https://{host}:{port}/")
741    }
742}
743
744impl Guard {
745    pub fn emit(&self, e: BrowserEvent) {
746        if let Some(s) = &self.events {
747            s(&e);
748        }
749    }
750
751    pub fn emit_kind(
752        &self,
753        kind: LifecycleKind,
754        reason: impl Into<String>,
755        f: impl FnOnce(&mut BrowserEvent),
756    ) {
757        let mut e = BrowserEvent::new(kind, &self.session_id, reason);
758        f(&mut e);
759        self.emit(e);
760    }
761
762    pub fn denied_network(&self, page_id: Option<&str>, what: &str, reason: &BlockReason) {
763        self.emit_kind(LifecycleKind::Denied, reason.to_string(), |e| {
764            e.page_id = page_id.map(str::to_string);
765            e.what = Some(what.to_string());
766            e.blocked = Some(reason.clone());
767        });
768    }
769
770    pub async fn admit(&self, req: AdmissionRequest) -> crate::error::Result<()> {
771        let what = format!("{:?}", req.action);
772        let page_id = req.page_id.clone();
773        if let Some(hook) = &self.admission {
774            if let Decision::Deny(reason) = hook(req).await {
775                self.emit_kind(LifecycleKind::Denied, reason.clone(), |e| {
776                    e.page_id = Some(page_id);
777                    e.what = Some(what);
778                });
779                return Err(crate::error::BrowserError::Denied(reason));
780            }
781        }
782        Ok(())
783    }
784
785    /// [`NetworkPolicy::check`] for a request page interception saw. An allowed networked
786    /// request records its `(host, port)` for this session.
787    pub async fn check_request(&self, url: &str, kind: &str) -> Result<(), BlockReason> {
788        self.network.check(url, kind).await?;
789        if let Some(pair) = networked_pair(url) {
790            self.page_allowed.lock().unwrap().insert(pair);
791        }
792        Ok(())
793    }
794
795    /// The proxy's decision for one connection: CONNECT `host:port`, or a plain-HTTP `url`.
796    /// With a per-request callback set, a pair no page check of this session allowed gets the
797    /// same check page requests get, as resource type `Connect`; then the address is pinned.
798    /// Without a callback the decision is the pin alone, as before.
799    pub(crate) async fn admit_proxied(
800        &self,
801        host: &str,
802        port: u16,
803        url: Option<&str>,
804    ) -> Result<Vec<IpAddr>, BlockReason> {
805        let decide = self.network.allow_request.is_some()
806            && !self
807                .page_allowed
808                .lock()
809                .unwrap()
810                .contains(&(normalize_host(host), port));
811        if decide {
812            let connect;
813            let url = match url {
814                Some(url) => url,
815                None => {
816                    connect = connect_url(host, port);
817                    &connect
818                }
819            };
820            self.network.check(url, "Connect").await?;
821        }
822        self.network.pin(host).await
823    }
824
825    pub async fn check_url(
826        &self,
827        page_id: Option<&str>,
828        url: &str,
829        kind: &str,
830    ) -> crate::error::Result<()> {
831        match self.check_request(url, kind).await {
832            Ok(()) => Ok(()),
833            Err(reason) => {
834                self.denied_network(page_id, kind, &reason);
835                Err(crate::error::BrowserError::Blocked(PolicyDenial {
836                    url: url.to_string(),
837                    resource_type: kind.to_string(),
838                    reason,
839                }))
840            }
841        }
842    }
843}