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