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
56pub const TRUSTED_HTTP_HOSTS_ENV: &str = "SYSTEMPROMPT_TRUSTED_HTTP_HOSTS";
57
58#[must_use]
59pub fn trusted_http_hosts_from_env() -> Vec<String> {
60    std::env::var(TRUSTED_HTTP_HOSTS_ENV)
61        .ok()
62        .map(|raw| {
63            raw.split(',')
64                .map(|s| s.trim().to_ascii_lowercase())
65                .filter(|s| !s.is_empty())
66                .collect()
67        })
68        .unwrap_or_default()
69}
70
71// Why: spawned children re-validate outbound URLs when they load the profile
72// catalog, so the operator's process-wide trust assertion must travel with
73// them — env_clear would otherwise leave a child running with an empty
74// allowlist and reject sealed-network hostnames the parent already accepted.
75pub fn trusted_hosts_env_entry(
76    lookup: impl Fn(&str) -> Option<String>,
77) -> Option<(String, String)> {
78    lookup(TRUSTED_HTTP_HOSTS_ENV).map(|trusted| (TRUSTED_HTTP_HOSTS_ENV.to_owned(), trusted))
79}
80
81pub fn validate_outbound_url(url: &str) -> Result<url::Url, OutboundUrlError> {
82    let no_trust: [&str; 0] = [];
83    validate_outbound_url_with_trust(url, &no_trust)
84}
85
86pub fn validate_outbound_url_with_trust(
87    url: &str,
88    trusted_http_hosts: &[impl AsRef<str>],
89) -> Result<url::Url, OutboundUrlError> {
90    let parsed = url::Url::parse(url).map_err(|e| OutboundUrlError::Parse(e.to_string()))?;
91    let host = parsed
92        .host()
93        .ok_or_else(|| OutboundUrlError::Parse("missing host".to_owned()))?;
94
95    let is_loopback_host = match &host {
96        url::Host::Domain(d) => d.eq_ignore_ascii_case("localhost"),
97        url::Host::Ipv4(ip) => ip.is_loopback(),
98        url::Host::Ipv6(ip) => ip.is_loopback(),
99    };
100
101    let host_str = parsed.host_str().unwrap_or_default().to_ascii_lowercase();
102    let is_trusted = !host_str.is_empty()
103        && trusted_http_hosts
104            .iter()
105            .any(|h| h.as_ref().eq_ignore_ascii_case(&host_str));
106
107    match parsed.scheme() {
108        "https" => {},
109        "http" if is_loopback_host || is_trusted => {},
110        "http" => return Err(OutboundUrlError::NonLoopbackHttp),
111        scheme => return Err(OutboundUrlError::Scheme(scheme.to_owned())),
112    }
113
114    if is_loopback_host || is_trusted {
115        return Ok(parsed);
116    }
117
118    let blocked = match host {
119        url::Host::Domain(_) => false,
120        url::Host::Ipv4(ip) => is_blocked_v4(ip),
121        url::Host::Ipv6(ip) => {
122            // Why: RFC 4291 §2.5.5.2: an ::ffff:0:0/96 address embeds a real IPv4
123            // address; treat it as that IPv4 address for SSRF purposes so a
124            // hand-crafted v4-mapped URL cannot bypass the v4 block list.
125            ip.to_ipv4_mapped().map_or_else(
126                || {
127                    let segments = ip.segments();
128                    let is_unique_local = (segments[0] & 0xfe00) == 0xfc00;
129                    let is_link_local = (segments[0] & 0xffc0) == 0xfe80;
130                    ip.is_loopback() || ip.is_unspecified() || is_unique_local || is_link_local
131                },
132                is_blocked_v4,
133            )
134        },
135    };
136    if blocked {
137        return Err(OutboundUrlError::BlockedHost(
138            parsed.host_str().unwrap_or_default().to_owned(),
139        ));
140    }
141    Ok(parsed)
142}
143
144// Why: RFC 6598 carrier-grade NAT range `100.64.0.0/10` — operator-routable but
145// commonly bridges to internal services on cloud-provider managed networks.
146fn is_cgnat_shared_v4(ip: std::net::Ipv4Addr) -> bool {
147    let [a, b, _, _] = ip.octets();
148    a == 100 && (64..=127).contains(&b)
149}
150
151fn is_blocked_v4(ip: std::net::Ipv4Addr) -> bool {
152    ip.is_private()
153        || ip.is_loopback()
154        || ip.is_link_local()
155        || ip.is_unspecified()
156        || ip.is_broadcast()
157        || is_cgnat_shared_v4(ip)
158}