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}
844
845#[cfg(test)]
846mod tests {
847 use super::*;
848
849 fn ip(s: &str) -> IpAddr {
850 s.parse().unwrap()
851 }
852
853 fn block_on<F: std::future::Future>(f: F) -> F::Output {
854 tokio::runtime::Builder::new_current_thread()
855 .enable_all()
856 .build()
857 .unwrap()
858 .block_on(f)
859 }
860
861 fn offline() -> NetworkPolicy {
864 NetworkPolicy::default().with_resolver(|h| match h {
865 "public.example" => vec![ip("93.184.216.34")],
866 "rebind.example" => vec![ip("93.184.216.34"), ip("10.0.0.7")],
867 "meta.example" => vec![ip("169.254.169.254")],
868 "mapped.example" => vec![ip("::ffff:192.168.1.1")],
869 "dev.example" => vec![ip("127.0.0.1")],
870 _ => vec![],
871 })
872 }
873
874 fn check(p: &NetworkPolicy, url: &str) -> Result<(), BlockReason> {
875 block_on(p.check(url, "Navigation"))
876 }
877
878 #[test]
879 fn classifies_every_blocked_v4_range() {
880 let cases = [
881 ("127.0.0.1", AddressClass::Loopback),
882 ("127.255.255.254", AddressClass::Loopback),
883 ("169.254.169.254", AddressClass::LinkLocal),
884 ("169.254.0.1", AddressClass::LinkLocal),
885 ("10.0.0.1", AddressClass::Private),
886 ("10.255.255.255", AddressClass::Private),
887 ("172.16.0.1", AddressClass::Private),
888 ("172.31.255.255", AddressClass::Private),
889 ("192.168.0.1", AddressClass::Private),
890 ("100.64.0.1", AddressClass::Private),
891 ("100.127.255.255", AddressClass::Private),
892 ("0.0.0.0", AddressClass::Unspecified),
893 ("0.1.2.3", AddressClass::Unspecified),
894 ("224.0.0.1", AddressClass::Multicast),
895 ("255.255.255.255", AddressClass::Reserved),
896 ("240.0.0.1", AddressClass::Reserved),
897 ("192.0.2.1", AddressClass::Reserved),
898 ("198.18.0.1", AddressClass::Reserved),
899 ("198.51.100.1", AddressClass::Reserved),
900 ("203.0.113.1", AddressClass::Reserved),
901 ];
902 for (s, want) in cases {
903 assert_eq!(classify_ip(ip(s)), want, "{s}");
904 }
905 for s in [
906 "8.8.8.8",
907 "93.184.216.34",
908 "172.32.0.1",
909 "172.15.255.255",
910 "100.63.255.255",
911 "100.128.0.1",
912 "169.253.1.1",
913 ] {
914 assert_eq!(classify_ip(ip(s)), AddressClass::Public, "{s}");
915 }
916 }
917
918 #[test]
919 fn classifies_every_blocked_v6_range_and_embedded_v4() {
920 let cases = [
921 ("::1", AddressClass::Loopback),
922 ("::", AddressClass::Unspecified),
923 ("fe80::1", AddressClass::LinkLocal),
924 ("febf::1", AddressClass::LinkLocal),
925 ("fc00::1", AddressClass::Private),
926 ("fd00:ec2::254", AddressClass::Private),
927 ("fec0::1", AddressClass::Private),
928 ("ff02::1", AddressClass::Multicast),
929 ("2001:db8::1", AddressClass::Reserved),
930 ("::ffff:127.0.0.1", AddressClass::Loopback),
932 ("::ffff:169.254.169.254", AddressClass::LinkLocal),
933 ("::ffff:10.1.2.3", AddressClass::Private),
934 ("::ffff:192.168.1.1", AddressClass::Private),
935 ("::ffff:0.0.0.0", AddressClass::Unspecified),
936 ("::127.0.0.1", AddressClass::Loopback),
938 ("64:ff9b::a9fe:a9fe", AddressClass::LinkLocal),
939 ("64:ff9b::7f00:1", AddressClass::Loopback),
940 ("2002:c0a8:0101::1", AddressClass::Private),
941 ("2002:7f00:0001::1", AddressClass::Loopback),
942 ];
943 for (s, want) in cases {
944 assert_eq!(classify_ip(ip(s)), want, "{s}");
945 }
946 for s in [
947 "2606:4700:4700::1111",
948 "::ffff:8.8.8.8",
949 "64:ff9b::808:808",
950 "2002:0808:0808::1",
951 ] {
952 assert_eq!(classify_ip(ip(s)), AddressClass::Public, "{s}");
953 }
954 }
955
956 #[test]
957 fn default_policy_blocks_literals_localhost_and_metadata() {
958 let p = offline();
959 for url in [
960 "http://127.0.0.1/",
961 "http://127.1.2.3:8080/x",
962 "http://localhost/",
963 "http://LOCALHOST./",
964 "http://app.localhost/",
965 "http://[::1]/",
966 "http://169.254.169.254/latest/meta-data/",
967 "http://[fe80::1]/",
968 "http://10.0.0.5/",
969 "http://172.20.1.1/",
970 "http://192.168.1.1/",
971 "http://100.64.1.1/",
972 "http://[fc00::1]/",
973 "http://0.0.0.0/",
974 "http://[::]/",
975 "http://[::ffff:127.0.0.1]/",
976 "http://[::ffff:169.254.169.254]/",
977 "http://[::ffff:10.0.0.1]/",
978 "http://2130706433/", "http://0x7f.0.0.1/", "http://metadata.google.internal/computeMetadata/v1/",
981 ] {
982 let r = check(&p, url);
983 assert!(r.is_err(), "{url} was allowed");
984 }
985 assert_eq!(check(&p, "https://public.example/"), Ok(()));
986 assert_eq!(check(&p, "http://8.8.8.8/"), Ok(()));
987 }
988
989 #[test]
990 fn every_resolved_address_is_checked_and_mapped_v6_resolution_blocks() {
991 let p = offline();
992 match check(&p, "https://rebind.example/") {
993 Err(BlockReason::Address { ip: a, class, .. }) => {
994 assert_eq!(a, ip("10.0.0.7"));
995 assert_eq!(class, AddressClass::Private);
996 }
997 other => panic!("{other:?}"),
998 }
999 assert!(matches!(
1000 check(&p, "https://mapped.example/"),
1001 Err(BlockReason::Address {
1002 class: AddressClass::Private,
1003 ..
1004 })
1005 ));
1006 assert!(matches!(
1007 check(&p, "https://meta.example/"),
1008 Err(BlockReason::Address {
1009 class: AddressClass::LinkLocal,
1010 ..
1011 })
1012 ));
1013 assert_eq!(
1015 check(&p, "https://nowhere.example/"),
1016 Err(BlockReason::Unresolved {
1017 host: "nowhere.example".into()
1018 })
1019 );
1020 }
1021
1022 #[test]
1023 fn schemes_other_than_http_are_blocked_unless_allowed() {
1024 let p = offline();
1025 for url in [
1026 "file:///etc/passwd",
1027 "chrome://settings",
1028 "ftp://public.example/",
1029 "ws://public.example/",
1030 "wss://public.example/",
1031 "javascript:alert(1)",
1032 "about:config",
1033 ] {
1034 assert!(
1035 matches!(check(&p, url), Err(BlockReason::Scheme(_))),
1036 "{url}: {:?}",
1037 check(&p, url)
1038 );
1039 }
1040 assert_eq!(check(&p, "about:blank"), Ok(()));
1042 assert_eq!(
1043 block_on(p.check("data:image/png;base64,AA==", "Image")),
1044 Ok(())
1045 );
1046 assert!(matches!(
1047 block_on(p.check("data:text/html,<h1>x</h1>", "Document")),
1048 Err(BlockReason::Scheme(_))
1049 ));
1050 let p = offline().allow_scheme("file").allow_scheme("wss");
1051 assert_eq!(check(&p, "file:///tmp/x.html"), Ok(()));
1052 assert_eq!(check(&p, "wss://public.example/socket"), Ok(()));
1053 assert!(check(&p, "wss://127.0.0.1/").is_err());
1055 }
1056
1057 #[test]
1058 fn allow_callback_overrides_both_ways_but_not_hard_blocks() {
1059 let seen: Arc<Mutex<Vec<BrowserRequest>>> = Arc::default();
1060 let s2 = seen.clone();
1061 let p = offline().allow_with(move |r: &BrowserRequest| {
1062 s2.lock().unwrap().push(r.clone());
1063 match r.host.as_str() {
1064 "127.0.0.1" if r.port == Some(3000) => PolicyDecision::Allow,
1065 "public.example" => PolicyDecision::Deny("not on the list".into()),
1066 "169.254.169.254" | "meta.example" => PolicyDecision::Allow,
1067 _ => PolicyDecision::Default,
1068 }
1069 });
1070 assert_eq!(check(&p, "http://127.0.0.1:3000/"), Ok(()));
1071 assert!(check(&p, "http://127.0.0.1:3001/").is_err());
1072 assert_eq!(
1073 check(&p, "https://public.example/"),
1074 Err(BlockReason::Callback("not on the list".into()))
1075 );
1076 let before = seen.lock().unwrap().len();
1078 assert!(check(&p, "http://169.254.169.254/").is_err());
1079 assert!(check(&p, "https://meta.example/").is_err());
1080 assert_eq!(seen.lock().unwrap().len(), before);
1081 let s = seen.lock().unwrap();
1083 let r = s.iter().find(|r| r.port == Some(3000)).unwrap();
1084 assert_eq!(r.class, Some(AddressClass::Loopback));
1085 assert!(matches!(r.default_block, Some(BlockReason::Address { .. })));
1086 let r = s.iter().find(|r| r.host == "public.example").unwrap();
1087 assert_eq!(r.default_block, None);
1088 drop(s);
1089
1090 let p = offline().allow_with(|r: &BrowserRequest| r.host == "10.0.0.5");
1092 assert_eq!(check(&p, "http://10.0.0.5/"), Ok(()));
1093 assert!(check(&p, "http://10.0.0.6/").is_err());
1094 assert_eq!(check(&p, "https://public.example/"), Ok(()));
1095
1096 let p = offline()
1098 .hard_block_link_local(false)
1099 .allow_host("169.254.169.254");
1100 assert_eq!(check(&p, "http://169.254.169.254/"), Ok(()));
1101 }
1102
1103 #[test]
1104 fn class_and_host_allowances() {
1105 let p = offline().allow_class(AddressClass::Loopback);
1106 assert_eq!(check(&p, "http://localhost:5173/"), Ok(()));
1107 assert_eq!(check(&p, "https://dev.example/"), Ok(()));
1108 assert!(check(&p, "http://10.0.0.1/").is_err());
1109 assert!(check(&p, "http://169.254.169.254/").is_err());
1110 let p = offline().allow_host("Rebind.Example.");
1111 assert_eq!(check(&p, "https://rebind.example/"), Ok(()));
1112 let p = offline()
1114 .allow_host("meta.example")
1115 .allow_class(AddressClass::LinkLocal);
1116 assert!(check(&p, "https://meta.example/").is_err());
1117 }
1118
1119 #[test]
1120 fn pin_only_connects_to_vetted_addresses() {
1121 let p = offline();
1122 assert_eq!(
1124 block_on(p.pin("public.example")).unwrap(),
1125 vec![ip("93.184.216.34")]
1126 );
1127 assert!(block_on(p.pin("rebind.example")).is_err());
1129 assert!(block_on(p.pin("dev.example")).is_err());
1130 assert!(block_on(p.pin("metadata.google.internal")).is_err());
1131 assert!(block_on(p.pin("nowhere.example")).is_err());
1132 let p = offline().allow_with(|r: &BrowserRequest| r.host == "dev.example");
1134 assert_eq!(check(&p, "https://dev.example/"), Ok(()));
1135 assert_eq!(
1136 block_on(p.pin("dev.example")).unwrap(),
1137 vec![ip("127.0.0.1")]
1138 );
1139 }
1140
1141 #[test]
1142 fn rebinding_after_check_is_refused_at_connect() {
1143 let n = Arc::new(Mutex::new(0u32));
1146 let n2 = n.clone();
1147 let p = NetworkPolicy::default().with_resolver(move |_| {
1148 let mut g = n2.lock().unwrap();
1149 *g += 1;
1150 if *g == 1 {
1151 vec![ip("93.184.216.34")]
1152 } else {
1153 vec![ip("10.9.9.9")]
1154 }
1155 });
1156 assert_eq!(check(&p, "https://flip.example/"), Ok(()));
1157 p.resolved.lock().unwrap().clear(); assert!(matches!(
1159 block_on(p.pin("flip.example")),
1160 Err(BlockReason::Address {
1161 class: AddressClass::Private,
1162 ..
1163 })
1164 ));
1165 }
1166
1167 #[test]
1168 fn unrestricted_allows_everything() {
1169 let p = NetworkPolicy::unrestricted();
1170 assert_eq!(check(&p, "file:///etc/hosts"), Ok(()));
1171 assert_eq!(check(&p, "http://169.254.169.254/"), Ok(()));
1172 }
1173
1174 #[test]
1175 fn denials_emit_typed_events_with_session_reason_and_timestamp() {
1176 let events: Arc<Mutex<Vec<BrowserEvent>>> = Arc::default();
1177 let e2 = events.clone();
1178 let g = Guard {
1179 session_id: "bs-test".into(),
1180 admission: Some(Arc::new(|_req| {
1181 Box::pin(async { Decision::Deny("needs approval".into()) })
1182 })),
1183 network: offline(),
1184 events: Some(Arc::new(move |e: &BrowserEvent| {
1185 e2.lock().unwrap().push(e.clone())
1186 })),
1187 page_allowed: Mutex::default(),
1188 };
1189 let before = SystemTime::now();
1190 let err = block_on(g.check_url(Some("p1"), "http://10.0.0.1/", "Navigation")).unwrap_err();
1191 match err {
1192 crate::BrowserError::Blocked(d) => {
1193 assert_eq!(d.resource_type, "Navigation");
1194 assert!(matches!(
1195 d.reason,
1196 BlockReason::Address {
1197 class: AddressClass::Private,
1198 ..
1199 }
1200 ));
1201 }
1202 other => panic!("{other:?}"),
1203 }
1204 let err = block_on(g.admit(AdmissionRequest {
1205 session_id: "bs-test".into(),
1206 page_id: "p1".into(),
1207 action: ActionKind::Click,
1208 url: None,
1209 target: None,
1210 detail: None,
1211 }))
1212 .unwrap_err();
1213 assert!(matches!(err, crate::BrowserError::Denied(ref r) if r == "needs approval"));
1214 let ev = events.lock().unwrap();
1215 assert_eq!(ev.len(), 2);
1216 for e in ev.iter() {
1217 assert_eq!(e.kind, LifecycleKind::Denied);
1218 assert_eq!(e.session_id, "bs-test");
1219 assert_eq!(e.page_id.as_deref(), Some("p1"));
1220 assert!(!e.reason.is_empty());
1221 assert!(e.at >= before);
1222 assert!(e.timestamp_ms() > 0);
1223 let j = e.to_json();
1224 assert_eq!(j["event"], "denied");
1225 assert_eq!(j["session_id"], "bs-test");
1226 }
1227 assert!(ev[0].blocked.is_some());
1228 assert_eq!(ev[0].what.as_deref(), Some("Navigation"));
1229 assert_eq!(ev[1].what.as_deref(), Some("Click"));
1230 assert!(ev[1].blocked.is_none());
1231 }
1232}