Skip to main content

systemprompt_models/
net.rs

1//! Shared network timeout constants and outbound-URL validation.
2//!
3//! Centralised [`Duration`] values for HTTP client configuration, TCP
4//! readiness probes, and long-poll image generation, so every caller
5//! uses the same tuned timeouts, plus [`validate_outbound_url`] — the
6//! single SSRF guard applied to every operator-configured webhook
7//! destination (agent integrations and the governance authz hook).
8
9use std::time::Duration;
10use thiserror::Error;
11
12/// Rejection reason for an operator-configured outbound URL.
13#[derive(Debug, Error)]
14pub enum OutboundUrlError {
15    #[error("invalid url: {0}")]
16    Parse(String),
17    #[error("unsupported url scheme: {0}")]
18    Scheme(String),
19    #[error("http url only permitted for loopback hosts")]
20    NonLoopbackHttp,
21    #[error("host {0} is in a blocked private range")]
22    BlockedHost(String),
23}
24
25pub const HTTP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
26
27pub const HTTP_DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
28
29pub const HTTP_HEALTH_CHECK_TIMEOUT: Duration = Duration::from_secs(5);
30
31pub const HTTP_AUTH_VERIFY_TIMEOUT: Duration = Duration::from_secs(10);
32
33pub const HTTP_SYNC_DEPLOY_TIMEOUT: Duration = Duration::from_secs(60);
34
35pub const HTTP_STREAM_CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
36
37pub const HTTP_KEEPALIVE: Duration = Duration::from_secs(60);
38
39pub const HTTP_POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(90);
40
41pub const AGENT_MONITOR_TCP_TIMEOUT: Duration = Duration::from_secs(15);
42
43pub const AGENT_READINESS_TCP_TIMEOUT: Duration = Duration::from_secs(2);
44
45pub const IMAGE_GEN_LONG_POLL_TIMEOUT: Duration = Duration::from_secs(300);
46
47pub const IMAGE_GEN_OPENAI_TIMEOUT: Duration = Duration::from_secs(120);
48
49/// Default per-attempt timeout for a non-streaming AI provider request.
50pub const AI_PROVIDER_REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
51
52/// Default timeout for a single MCP tool-call RPC (excludes connection setup).
53pub const MCP_TOOL_EXECUTION_TIMEOUT: Duration = Duration::from_secs(30);
54
55/// Operator-supplied allowlist of non-loopback hostnames reachable over plain
56/// `http`.
57///
58/// Comma-separated, case-insensitive, exact domain match only — no globs, no
59/// IP, no port. The intended use is sealed-network demos (the air-gap scenario)
60/// and behind-the-firewall mock services, where the SSRF guard's default
61/// "loopback-only http" rule would otherwise reject a known-trusted internal
62/// hostname like `mock-inference`. **Default empty** — operator opts in by
63/// naming every host explicitly. Does not loosen the scheme, IP block, or
64/// private-range rules for any host outside the allowlist.
65pub const TRUSTED_HTTP_HOSTS_ENV: &str = "SYSTEMPROMPT_TRUSTED_HTTP_HOSTS";
66
67/// Parse [`TRUSTED_HTTP_HOSTS_ENV`] into a normalised allowlist.
68///
69/// Empty/missing → empty vec. Hosts are trimmed and lower-cased; empty
70/// entries (from `a,,b` typos) are dropped.
71#[must_use]
72pub fn trusted_http_hosts_from_env() -> Vec<String> {
73    std::env::var(TRUSTED_HTTP_HOSTS_ENV)
74        .ok()
75        .map(|raw| {
76            raw.split(',')
77                .map(|s| s.trim().to_ascii_lowercase())
78                .filter(|s| !s.is_empty())
79                .collect()
80        })
81        .unwrap_or_default()
82}
83
84/// Validate an operator-configured outbound webhook destination, returning the
85/// parsed URL on success.
86///
87/// Rejects destinations that point at the local host or known private network
88/// ranges; these would otherwise let a configured webhook exfiltrate
89/// cloud-metadata endpoints (e.g. `169.254.169.254`) or internal services on
90/// the same subnet. The scheme must be `https` for production destinations;
91/// `http` is allowed only for explicit loopback names used during local
92/// development.
93pub fn validate_outbound_url(url: &str) -> Result<url::Url, OutboundUrlError> {
94    let no_trust: [&str; 0] = [];
95    validate_outbound_url_with_trust(url, &no_trust)
96}
97
98/// Same as [`validate_outbound_url`], but accepts an explicit allowlist of
99/// hostnames the operator has marked as reachable over plain `http`.
100///
101/// A host in `trusted_http_hosts` is treated like `localhost` for the scheme
102/// gate (http accepted) and **also bypasses the private-range IP block** for
103/// that hostname's resolution path — the latter matters because in-network
104/// hostnames typically resolve to RFC1918 IPs that the standard guard
105/// rejects. The IP-blocklist is still enforced for every host *not* in the
106/// allowlist.
107///
108/// Matching is exact, case-insensitive, on the URL's parsed host. IPs in the
109/// allowlist are matched literally (allowlist callers should generally use
110/// hostnames, not addresses).
111pub fn validate_outbound_url_with_trust(
112    url: &str,
113    trusted_http_hosts: &[impl AsRef<str>],
114) -> Result<url::Url, OutboundUrlError> {
115    let parsed = url::Url::parse(url).map_err(|e| OutboundUrlError::Parse(e.to_string()))?;
116    let host = parsed
117        .host()
118        .ok_or_else(|| OutboundUrlError::Parse("missing host".to_owned()))?;
119
120    let is_loopback_host = match &host {
121        url::Host::Domain(d) => d.eq_ignore_ascii_case("localhost"),
122        url::Host::Ipv4(ip) => ip.is_loopback(),
123        url::Host::Ipv6(ip) => ip.is_loopback(),
124    };
125
126    let host_str = parsed.host_str().unwrap_or_default().to_ascii_lowercase();
127    let is_trusted = !host_str.is_empty()
128        && trusted_http_hosts
129            .iter()
130            .any(|h| h.as_ref().eq_ignore_ascii_case(&host_str));
131
132    match parsed.scheme() {
133        "https" => {},
134        "http" if is_loopback_host || is_trusted => {},
135        "http" => return Err(OutboundUrlError::NonLoopbackHttp),
136        scheme => return Err(OutboundUrlError::Scheme(scheme.to_owned())),
137    }
138
139    if is_loopback_host || is_trusted {
140        return Ok(parsed);
141    }
142
143    let blocked = match host {
144        url::Host::Domain(_) => false,
145        url::Host::Ipv4(ip) => is_blocked_v4(ip),
146        url::Host::Ipv6(ip) => {
147            // RFC 4291 §2.5.5.2: an ::ffff:0:0/96 address embeds a real IPv4
148            // address; treat it as that IPv4 address for SSRF purposes so a
149            // hand-crafted v4-mapped URL cannot bypass the v4 block list.
150            ip.to_ipv4_mapped().map_or_else(
151                || {
152                    let segments = ip.segments();
153                    let is_unique_local = (segments[0] & 0xfe00) == 0xfc00;
154                    let is_link_local = (segments[0] & 0xffc0) == 0xfe80;
155                    ip.is_loopback() || ip.is_unspecified() || is_unique_local || is_link_local
156                },
157                is_blocked_v4,
158            )
159        },
160    };
161    if blocked {
162        return Err(OutboundUrlError::BlockedHost(
163            parsed.host_str().unwrap_or_default().to_owned(),
164        ));
165    }
166    Ok(parsed)
167}
168
169/// RFC 6598 carrier-grade NAT range `100.64.0.0/10` — operator-routable but
170/// commonly bridges to internal services on cloud-provider managed networks.
171fn is_cgnat_shared_v4(ip: std::net::Ipv4Addr) -> bool {
172    let [a, b, _, _] = ip.octets();
173    a == 100 && (64..=127).contains(&b)
174}
175
176fn is_blocked_v4(ip: std::net::Ipv4Addr) -> bool {
177    ip.is_private()
178        || ip.is_loopback()
179        || ip.is_link_local()
180        || ip.is_unspecified()
181        || ip.is_broadcast()
182        || is_cgnat_shared_v4(ip)
183}