1use 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#[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#[derive(Clone, Debug)]
94pub struct AdmissionRequest {
95 pub session_id: String,
96 pub page_id: String,
97 pub action: ActionKind,
98 pub url: Option<String>,
100 pub target: Option<String>,
102 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#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
121pub enum AddressClass {
122 Public,
123 Loopback,
124 LinkLocal,
126 Private,
128 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 if let Some(v4) = v6.to_ipv4_mapped() {
185 return classify_v4(v4);
186 }
187 if s[..6] == [0, 0, 0, 0, 0, 0] {
189 return classify_v4(v4_from_segments(s[6], s[7]));
190 }
191 if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {
193 return classify_v4(v4_from_segments(s[6], s[7]));
194 }
195 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
212fn 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
220fn 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#[derive(Clone, Debug, Eq, PartialEq)]
232pub enum BlockReason {
233 InvalidUrl(String),
234 Scheme(String),
236 NoHost,
237 Unresolved {
239 host: String,
240 },
241 Address {
243 host: String,
244 ip: IpAddr,
245 class: AddressClass,
246 },
247 MetadataHost {
249 host: String,
250 },
251 Callback(String),
253}
254
255impl BlockReason {
256 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#[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#[derive(Clone, Debug)]
308pub struct BrowserRequest {
309 pub url: String,
310 pub scheme: String,
311 pub host: String,
313 pub port: Option<u16>,
314 pub class: Option<AddressClass>,
316 pub addresses: Vec<IpAddr>,
318 pub resource_type: String,
320 pub default_block: Option<BlockReason>,
322}
323
324pub type NetworkRequest = BrowserRequest;
326
327#[derive(Clone, Debug, Eq, PartialEq)]
329pub enum PolicyDecision {
330 Allow,
332 Deny(String),
334 Default,
336}
337
338impl 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
352type ResolvedCache = Arc<Mutex<HashMap<String, (Instant, Vec<IpAddr>)>>>;
354
355#[derive(Clone)]
357pub struct NetworkPolicy {
358 pub allow_hosts: Vec<String>,
360 pub allow_classes: Vec<AddressClass>,
362 pub allowed_schemes: Vec<String>,
364 pub allow_request: Option<AllowCallback>,
366 pub hard_block_link_local: bool,
368 pub unrestricted: bool,
370 pub resolver: Option<Resolver>,
372 resolved: ResolvedCache,
373 approved: Arc<Mutex<HashMap<String, Vec<IpAddr>>>>,
375 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#[derive(Clone, Debug, Eq, PartialEq)]
412pub struct BlockedRequest {
413 pub url: String,
414 pub reason: String,
415}
416
417#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
424pub enum ResourceClass {
425 Document,
427 Script,
429 Connect,
432 Passive,
435}
436
437impl ResourceClass {
438 pub const ALL: [ResourceClass; 4] = [
440 ResourceClass::Document,
441 ResourceClass::Script,
442 ResourceClass::Connect,
443 ResourceClass::Passive,
444 ];
445
446 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 Subdomains(String),
465}
466
467#[derive(Clone, Debug, Eq, PartialEq)]
471pub struct DestinationRule {
472 host: HostMatch,
473 ports: Vec<u16>,
474 classes: Vec<ResourceClass>,
475}
476
477fn 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 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 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 pub fn on_ports(mut self, ports: &[u16]) -> Self {
525 self.ports = ports.to_vec();
526 self
527 }
528
529 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#[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 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 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 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 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 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 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(()); }
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 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 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(), }
845 };
846 self.resolved
847 .lock()
848 .unwrap()
849 .insert(host.to_string(), (Instant::now(), found.clone()));
850 found
851 }
852}
853
854#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
859pub enum LifecycleKind {
860 Start,
861 Stop,
862 Crash,
864 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#[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 pub pid: Option<u32>,
890 pub what: Option<String>,
892 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
932pub(crate) struct Guard {
934 pub session_id: String,
935 pub admission: Option<AdmissionHook>,
936 pub network: NetworkPolicy,
937 pub events: Option<EventSink>,
938 pub page_allowed: Mutex<HashSet<(String, u16)>>,
941}
942
943fn 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
953fn 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 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 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}