1use 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#[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#[derive(Clone, Debug)]
87pub struct AdmissionRequest {
88 pub session_id: String,
89 pub page_id: String,
90 pub action: ActionKind,
91 pub url: Option<String>,
93 pub target: Option<String>,
95 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#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
114pub enum AddressClass {
115 Public,
116 Loopback,
117 LinkLocal,
119 Private,
121 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 if let Some(v4) = v6.to_ipv4_mapped() {
178 return classify_v4(v4);
179 }
180 if s[..6] == [0, 0, 0, 0, 0, 0] {
182 return classify_v4(v4_from_segments(s[6], s[7]));
183 }
184 if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {
186 return classify_v4(v4_from_segments(s[6], s[7]));
187 }
188 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
205fn 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
213fn 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#[derive(Clone, Debug, Eq, PartialEq)]
225pub enum BlockReason {
226 InvalidUrl(String),
227 Scheme(String),
229 NoHost,
230 Unresolved {
232 host: String,
233 },
234 Address {
236 host: String,
237 ip: IpAddr,
238 class: AddressClass,
239 },
240 MetadataHost {
242 host: String,
243 },
244 Callback(String),
246}
247
248impl BlockReason {
249 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#[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#[derive(Clone, Debug)]
301pub struct BrowserRequest {
302 pub url: String,
303 pub scheme: String,
304 pub host: String,
306 pub port: Option<u16>,
307 pub class: Option<AddressClass>,
309 pub addresses: Vec<IpAddr>,
311 pub resource_type: String,
313 pub default_block: Option<BlockReason>,
315}
316
317pub type NetworkRequest = BrowserRequest;
319
320#[derive(Clone, Debug, Eq, PartialEq)]
322pub enum PolicyDecision {
323 Allow,
325 Deny(String),
327 Default,
329}
330
331impl 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
345type ResolvedCache = Arc<Mutex<HashMap<String, (Instant, Vec<IpAddr>)>>>;
347
348#[derive(Clone)]
350pub struct NetworkPolicy {
351 pub allow_hosts: Vec<String>,
353 pub allow_classes: Vec<AddressClass>,
355 pub allowed_schemes: Vec<String>,
357 pub allow_request: Option<AllowCallback>,
359 pub hard_block_link_local: bool,
361 pub unrestricted: bool,
363 pub resolver: Option<Resolver>,
365 resolved: ResolvedCache,
366 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#[derive(Clone, Debug, Eq, PartialEq)]
401pub struct BlockedRequest {
402 pub url: String,
403 pub reason: String,
404}
405
406impl NetworkPolicy {
407 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 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 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(()); }
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 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 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(), }
626 };
627 self.resolved
628 .lock()
629 .unwrap()
630 .insert(host.to_string(), (Instant::now(), found.clone()));
631 found
632 }
633}
634
635#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
640pub enum LifecycleKind {
641 Start,
642 Stop,
643 Crash,
645 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#[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 pub pid: Option<u32>,
671 pub what: Option<String>,
673 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
713pub(crate) struct Guard {
715 pub session_id: String,
716 pub admission: Option<AdmissionHook>,
717 pub network: NetworkPolicy,
718 pub events: Option<EventSink>,
719 pub page_allowed: Mutex<HashSet<(String, u16)>>,
722}
723
724fn 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
734fn 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 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 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}