Skip to main content

adk_graph/action/
http.rs

1//! HTTP action node executor (requires `action-http` feature).
2//!
3//! Implements HTTP requests with method, URL interpolation, headers,
4//! authentication (bearer/basic/api_key), body (json/form/raw),
5//! response parsing (json/text), and status code validation.
6//!
7//! The URL is interpolated from workflow state, so every request, and every
8//! redirect it follows, is checked against an [`HttpActionPolicy`], which by default
9//! admits public addresses only. Logs and errors show the URL without its query string
10//! or credentials.
11//!
12//! The same policy governs the notification node's webhook and the RSS node's
13//! feed URL.
14
15use std::collections::HashMap;
16
17use adk_action::{HttpAuth, HttpBody, HttpMethod, HttpNodeConfig, interpolate_variables};
18use adk_core::egress::{EgressPolicy, EgressResolver, is_non_public};
19use serde_json::{Value, json};
20
21use crate::error::{GraphError, Result};
22use crate::node::{NodeContext, NodeOutput};
23
24/// Which URLs the HTTP, notification, and RSS action nodes may request.
25///
26/// | Setting | Default |
27/// |---------|---------|
28/// | Schemes | `https` and `http` |
29/// | Hosts | Any host |
30/// | Addresses | Public only: a host that is, or resolves to, a loopback, private, link-local, cloud metadata, CGNAT, unique-local, multicast, reserved or IPv4-embedding IPv6 address is refused ([`adk_core::egress::is_non_public`]) |
31/// | Redirects | Up to 5, each checked against this policy |
32///
33/// Host names are resolved inside the HTTP client by a resolver that refuses non-public
34/// answers, so the address checked is the address connected to, and system proxies are not
35/// used. [`allow_private_networks`](Self::allow_private_networks) admits every address, and
36/// with it the system proxies, for workflows that call services on a private network.
37///
38/// # Example
39///
40/// ```rust,ignore
41/// use adk_graph::action::ActionNodeExecutor;
42/// use adk_graph::action::http::HttpActionPolicy;
43///
44/// let policy = HttpActionPolicy::new()
45///     .allow_schemes(["https"])
46///     .allow_hosts(["api.example.com", "*.internal.example.com"])
47///     .max_redirects(0);
48/// let executor = ActionNodeExecutor::new(config).with_http_policy(policy);
49/// ```
50#[derive(Clone)]
51pub struct HttpActionPolicy {
52    allowed_schemes: Vec<String>,
53    allowed_hosts: Option<Vec<String>>,
54    max_redirects: usize,
55    allow_private: bool,
56    /// The host's secret a governed call's credential digests are keyed with.
57    credential_key: Option<std::sync::Arc<[u8]>>,
58}
59
60impl std::fmt::Debug for HttpActionPolicy {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        f.debug_struct("HttpActionPolicy")
63            .field("allowed_schemes", &self.allowed_schemes)
64            .field("allowed_hosts", &self.allowed_hosts)
65            .field("max_redirects", &self.max_redirects)
66            .field("allow_private", &self.allow_private)
67            .field("credential_key", &self.credential_key.as_ref().map(|_| "[set]"))
68            .finish()
69    }
70}
71
72impl Default for HttpActionPolicy {
73    fn default() -> Self {
74        Self {
75            allowed_schemes: vec!["https".to_string(), "http".to_string()],
76            allowed_hosts: None,
77            max_redirects: 5,
78            allow_private: false,
79            credential_key: None,
80        }
81    }
82}
83
84impl HttpActionPolicy {
85    /// Creates the default policy: `https` and `http`, any public host, 5 checked redirects.
86    pub fn new() -> Self {
87        Self::default()
88    }
89
90    /// Admits loopback, private, link-local and other non-public addresses, and requests
91    /// through the system proxies.
92    ///
93    /// Use it only for workflows whose URLs an operator controls: a URL interpolated from
94    /// state can then reach the host's own services and the cloud metadata endpoint.
95    /// Combine it with [`allow_hosts`](Self::allow_hosts) to name the internal hosts.
96    ///
97    /// # Example
98    ///
99    /// ```rust,ignore
100    /// use adk_graph::action::http::HttpActionPolicy;
101    ///
102    /// let policy = HttpActionPolicy::new()
103    ///     .allow_hosts(["billing.internal.example.com"])
104    ///     .allow_private_networks();
105    /// ```
106    #[must_use]
107    pub fn allow_private_networks(mut self) -> Self {
108        self.allow_private = true;
109        self
110    }
111
112    /// Replaces the permitted URL schemes, compared case-insensitively.
113    #[must_use]
114    pub fn allow_schemes<I, S>(mut self, schemes: I) -> Self
115    where
116        I: IntoIterator<Item = S>,
117        S: Into<String>,
118    {
119        self.allowed_schemes =
120            schemes.into_iter().map(|scheme| scheme.into().to_ascii_lowercase()).collect();
121        self
122    }
123
124    /// Restricts requests to these hosts.
125    ///
126    /// An entry is an exact host name or IP address, or `*.example.com` for any
127    /// subdomain of `example.com` (not `example.com` itself). Matching ignores case.
128    #[must_use]
129    pub fn allow_hosts<I, S>(mut self, hosts: I) -> Self
130    where
131        I: IntoIterator<Item = S>,
132        S: Into<String>,
133    {
134        self.allowed_hosts =
135            Some(hosts.into_iter().map(|host| host.into().to_ascii_lowercase()).collect());
136        self
137    }
138
139    /// Sets how many redirects a request may follow; `0` follows none.
140    #[must_use]
141    pub fn max_redirects(mut self, max_redirects: usize) -> Self {
142        self.max_redirects = max_redirects;
143        self
144    }
145
146    /// Keys the digests a governed call shows its credentials as with `key`, a secret only
147    /// the host holds (spec 3.3 §12).
148    ///
149    /// Without a key a digest is a plain SHA-256 of the credential, which binds the call
150    /// exactly but lets anyone who sees the decision test guesses of a weak credential,
151    /// such as a password, against it. With a key the digest is an HMAC-SHA256 under it.
152    /// Keep the key stable: a call's digests are part of its action-ledger key, so a new
153    /// key makes an approved call, and a fork of it, a new call.
154    ///
155    /// # Example
156    ///
157    /// ```rust,ignore
158    /// use adk_graph::action::http::HttpActionPolicy;
159    ///
160    /// let policy = HttpActionPolicy::new().credential_key(std::env::var("DIGEST_KEY")?);
161    /// ```
162    #[must_use]
163    pub fn credential_key(mut self, key: impl AsRef<[u8]>) -> Self {
164        self.credential_key = Some(std::sync::Arc::from(key.as_ref()));
165        self
166    }
167
168    /// The `sha256:` digest a credential named `name` is shown and bound as.
169    ///
170    /// Domain-separated by the name, so equal values under different names differ.
171    fn digest(&self, name: &str, value: &[u8]) -> String {
172        use sha2::{Digest, Sha256};
173        let mut message = b"adk-graph.http-credential\0".to_vec();
174        message.extend_from_slice(name.to_ascii_lowercase().as_bytes());
175        message.push(0);
176        message.extend_from_slice(value);
177        let digest = match &self.credential_key {
178            None => Sha256::digest(&message).to_vec(),
179            Some(key) => hmac_sha256(key, &message).to_vec(),
180        };
181        let mut shown = String::with_capacity(7 + 64);
182        shown.push_str("sha256:");
183        for byte in digest {
184            use std::fmt::Write as _;
185            let _ = write!(shown, "{byte:02x}");
186        }
187        shown
188    }
189
190    /// Explains why `url` is not permitted, if it is not.
191    pub(crate) fn check(&self, url: &reqwest::Url) -> std::result::Result<(), String> {
192        let scheme = url.scheme();
193        if !self.allowed_schemes.iter().any(|allowed| allowed == scheme) {
194            return Err(format!(
195                "URL scheme '{scheme}' is not permitted by the HTTP action policy; permitted \
196                 schemes: {}",
197                self.allowed_schemes.join(", ")
198            ));
199        }
200        let host = url.host_str().unwrap_or_default().to_ascii_lowercase();
201        if let Some(allowed_hosts) = &self.allowed_hosts {
202            let permitted = allowed_hosts.iter().any(|allowed| match allowed.strip_prefix("*.") {
203                Some(domain) => host.strip_suffix(domain).is_some_and(|rest| rest.ends_with('.')),
204                None => *allowed == host,
205            });
206            if !permitted {
207                return Err(format!(
208                    "host '{host}' is not in the HTTP action policy allowlist; add it with \
209                     `HttpActionPolicy::allow_hosts`"
210                ));
211            }
212        }
213        if self.allow_private {
214            return Ok(());
215        }
216        // An address literal is never resolved, so the resolver cannot check it. IPv6 hosts
217        // are serialized in brackets, and every IPv4 form as a dotted quad.
218        let unbracketed = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(&host);
219        let non_public = match unbracketed.parse::<std::net::IpAddr>() {
220            Ok(ip) => is_non_public(ip),
221            Err(_) => {
222                let name = host.trim_end_matches('.');
223                name == "localhost" || name.ends_with(".localhost")
224            }
225        };
226        if non_public {
227            return Err(format!(
228                "host '{host}' is a loopback, private, link-local or other non-public address, \
229                 which the HTTP action policy refuses by default; for a workflow whose URLs an \
230                 operator controls, set `HttpActionPolicy::allow_private_networks`"
231            ));
232        }
233        Ok(())
234    }
235
236    /// A client whose redirects are checked against this policy and, unless private networks
237    /// are allowed, whose resolver refuses non-public addresses.
238    pub(crate) fn client(&self) -> std::result::Result<reqwest::Client, String> {
239        let mut builder = reqwest::Client::builder().redirect(self.redirect_policy());
240        if !self.allow_private {
241            // A proxy would resolve the host itself, out of the resolver's reach.
242            let resolver = EgressResolver::new(EgressPolicy::public_only());
243            builder = builder.no_proxy().dns_resolver(std::sync::Arc::new(resolver));
244        }
245        builder.build().map_err(|e| format!("failed to build the HTTP client: {e}"))
246    }
247
248    /// A redirect policy that re-applies [`Self::check`] to every hop.
249    fn redirect_policy(&self) -> reqwest::redirect::Policy {
250        if self.max_redirects == 0 {
251            return reqwest::redirect::Policy::none();
252        }
253        let policy = self.clone();
254        reqwest::redirect::Policy::custom(move |attempt| {
255            if attempt.previous().len() > policy.max_redirects {
256                let limit = policy.max_redirects;
257                attempt.error(format!("stopped after {limit} redirects"))
258            } else if let Err(reason) = policy.check(attempt.url()) {
259                attempt.error(format!("redirect refused: {reason}"))
260            } else {
261                attempt.follow()
262            }
263        })
264    }
265}
266
267/// HMAC-SHA256 of `message` under `key` (RFC 2104).
268fn hmac_sha256(key: &[u8], message: &[u8]) -> [u8; 32] {
269    use sha2::{Digest, Sha256};
270    const BLOCK: usize = 64;
271    let mut block = [0u8; BLOCK];
272    if key.len() > BLOCK {
273        block[..32].copy_from_slice(&Sha256::digest(key));
274    } else {
275        block[..key.len()].copy_from_slice(key);
276    }
277    let pad = |byte: u8| block.iter().map(|k| k ^ byte).collect::<Vec<u8>>();
278    let inner = Sha256::new().chain_update(pad(0x36)).chain_update(message).finalize();
279    Sha256::new().chain_update(pad(0x5c)).chain_update(inner).finalize().into()
280}
281
282/// The URL as it may be logged: no credentials, query string, or fragment.
283pub(crate) fn redact_url(url: &reqwest::Url) -> String {
284    let mut shown = url.clone();
285    // Both fail only for URLs that cannot carry credentials, which have none.
286    let _ = shown.set_username("");
287    let _ = shown.set_password(None);
288    if shown.query().is_some() {
289        shown.set_query(Some("redacted"));
290    }
291    shown.set_fragment(None);
292    shown.to_string()
293}
294
295/// Execute an HTTP action node under the default [`HttpActionPolicy`].
296///
297/// # Errors
298///
299/// See [`execute_http_with_policy`].
300pub async fn execute_http(config: &HttpNodeConfig, ctx: &NodeContext) -> Result<NodeOutput> {
301    execute_http_with_policy(config, ctx, &HttpActionPolicy::default()).await
302}
303
304/// Execute an HTTP action node under `policy`.
305///
306/// # Example
307///
308/// ```rust,ignore
309/// use adk_graph::action::http::{HttpActionPolicy, execute_http_with_policy};
310///
311/// let policy = HttpActionPolicy::new().allow_hosts(["api.example.com"]);
312/// let output = execute_http_with_policy(&config, &ctx, &policy).await?;
313/// ```
314///
315/// # Errors
316///
317/// Returns [`GraphError::NodeExecutionFailed`] when the interpolated URL is not
318/// a valid absolute URL, the policy refuses it or a redirect, the request fails,
319/// the status fails validation, or the response cannot be parsed.
320pub async fn execute_http_with_policy(
321    config: &HttpNodeConfig,
322    ctx: &NodeContext,
323    policy: &HttpActionPolicy,
324) -> Result<NodeOutput> {
325    let node_id = &config.standard.id;
326    let fail = |message: String| GraphError::NodeExecutionFailed { node: node_id.clone(), message };
327    let (client, request) = build_request(config, &ctx.state, policy).map_err(fail)?;
328    tracing::debug!(
329        node = %node_id,
330        url = %redact_url(request.url()),
331        method = ?config.method,
332        "executing HTTP node"
333    );
334    send(config, &client, request, ctx.governed_call()).await
335}
336
337/// Fails with why the node's request cannot be built for `state`, if it cannot: an
338/// invalid URL, one the policy refuses, or a client that cannot be built. Nothing is sent.
339pub(crate) fn buildable(
340    config: &HttpNodeConfig,
341    state: &HashMap<String, Value>,
342    policy: &HttpActionPolicy,
343) -> Result<()> {
344    build_request(config, state, policy).map(drop).map_err(|message| {
345        GraphError::NodeExecutionFailed { node: config.standard.id.clone(), message }
346    })
347}
348
349/// The request an HTTP node sends for `state`, with a client that checks its redirects.
350///
351/// The URL is checked against `policy` before anything is built. The raw URL is never
352/// echoed in an error: it may carry a secret.
353fn build_request(
354    config: &HttpNodeConfig,
355    state: &HashMap<String, Value>,
356    policy: &HttpActionPolicy,
357) -> std::result::Result<(reqwest::Client, reqwest::Request), String> {
358    let url = reqwest::Url::parse(&interpolate_variables(&config.url, state))
359        .map_err(|e| format!("HTTP node URL is not a valid absolute URL: {e}"))?;
360    policy.check(&url)?;
361    let client = policy.client()?;
362    let mut request = match config.method {
363        HttpMethod::Get => client.get(url),
364        HttpMethod::Post => client.post(url),
365        HttpMethod::Put => client.put(url),
366        HttpMethod::Patch => client.patch(url),
367        HttpMethod::Delete => client.delete(url),
368        HttpMethod::Head => client.head(url),
369        HttpMethod::Options => client.request(reqwest::Method::OPTIONS, url),
370    };
371    for (key, value) in &config.headers {
372        request = request.header(key.as_str(), interpolate_variables(value, state));
373    }
374    request = apply_auth(request, &config.auth, state);
375    request = apply_body(request, &config.body, state).map_err(|e| e.to_string())?;
376    let request = request
377        .build()
378        .map_err(|e| format!("failed to build the HTTP request: {}", e.without_url()))?;
379    Ok((client, request))
380}
381
382/// Sends `request` and maps its response to the node's output.
383///
384/// For a governed call (spec 3.3 §12) a failure after the request may have reached the
385/// server — no answer, an answer that fails validation, or one that cannot be read — is
386/// `graph.outcome_unknown`, because the call may have taken effect; only a connection that
387/// was never made is a plain failure.
388async fn send(
389    config: &HttpNodeConfig,
390    client: &reqwest::Client,
391    request: reqwest::Request,
392    governed: bool,
393) -> Result<NodeOutput> {
394    let node_id = &config.standard.id;
395    let output_key = &config.standard.mapping.output_key;
396    let shown_url = redact_url(request.url());
397    let sent = |message: String| {
398        if governed {
399            crate::governed::sent_without_outcome(node_id, &message)
400        } else {
401            GraphError::NodeExecutionFailed { node: node_id.clone(), message }
402        }
403    };
404    // `without_url` keeps the full URL, query string included, out of the error.
405    let response = client.execute(request).await.map_err(|e| {
406        let connect = e.is_connect();
407        let message = format!("HTTP request to {shown_url} failed: {}", e.without_url());
408        if connect {
409            GraphError::NodeExecutionFailed { node: node_id.clone(), message }
410        } else {
411            sent(message)
412        }
413    })?;
414
415    let status = response.status().as_u16();
416
417    // Validate status code
418    if let Some(pattern) = &config.response.status_validation
419        && !validate_status(status, pattern)
420    {
421        return Err(sent(format!(
422            "HTTP status {status} does not match validation pattern '{pattern}'"
423        )));
424    }
425
426    // Parse response
427    let result = parse_response(response, &config.response.response_type, node_id).await.map_err(
428        |error| match error {
429            GraphError::NodeExecutionFailed { message, .. } => sent(message),
430            other => other,
431        },
432    )?;
433
434    let output_value = json!({
435        "status": status,
436        "data": result,
437    });
438
439    Ok(NodeOutput::new().with_update(output_key, output_value))
440}
441
442/// Whether a header, query parameter or form field named `name` carries a credential.
443fn is_credential(name: &str) -> bool {
444    const NAMES: [&str; 8] = [
445        "authorization",
446        "proxy-authorization",
447        "cookie",
448        "set-cookie",
449        "key",
450        "sig",
451        "code",
452        "pwd",
453    ];
454    const PARTS: [&str; 13] = [
455        "auth",
456        "token",
457        "secret",
458        "passw",
459        "cookie",
460        "session",
461        "signature",
462        "credential",
463        "api-key",
464        "api_key",
465        "apikey",
466        "access_key",
467        "private",
468    ];
469    let name = name.to_ascii_lowercase();
470    NAMES.contains(&name.as_str()) || PARTS.iter().any(|part| name.contains(part))
471}
472
473/// Every value of the header `name`, joined as one field value.
474fn header_value(
475    headers: &reqwest::header::HeaderMap,
476    name: &reqwest::header::HeaderName,
477) -> Vec<u8> {
478    let values: Vec<&[u8]> = headers.get_all(name).iter().map(|value| value.as_bytes()).collect();
479    values.join(&b", "[..])
480}
481
482/// `url` with each credential in its query, and its password, replaced by its digest.
483fn digested_url(policy: &HttpActionPolicy, url: &reqwest::Url) -> reqwest::Url {
484    let mut shown = url.clone();
485    let pairs: Vec<(String, String)> = url.query_pairs().into_owned().collect();
486    if pairs.iter().any(|(name, _)| is_credential(name)) {
487        shown.query_pairs_mut().clear().extend_pairs(pairs.iter().map(|(name, value)| {
488            let value = if is_credential(name) {
489                policy.digest(name, value.as_bytes())
490            } else {
491                value.clone()
492            };
493            (name.clone(), value)
494        }));
495    }
496    if let Some(password) = url.password() {
497        // Fails only for URLs that cannot carry credentials, which have none.
498        let _ = shown.set_password(Some(&policy.digest("password", password.as_bytes())));
499    }
500    shown
501}
502
503/// The header an API-key authentication sends its key in, lower-cased: a credential
504/// whatever its name.
505fn api_key_header(config: &HttpNodeConfig, state: &HashMap<String, Value>) -> Option<String> {
506    match &config.auth {
507        HttpAuth::ApiKey(api_key) => {
508            Some(interpolate_variables(&api_key.header, state).to_ascii_lowercase())
509        }
510        HttpAuth::None | HttpAuth::Bearer(_) | HttpAuth::Basic(_) => None,
511    }
512}
513
514/// `state` with each string under a secret-looking key replaced by its digest, and each
515/// digest paired with the value it stands for.
516fn digested_state(
517    policy: &HttpActionPolicy,
518    state: &HashMap<String, Value>,
519) -> (HashMap<String, Value>, Vec<(String, String)>) {
520    let mut shown = state.clone();
521    let mut digests = Vec::new();
522    for (key, value) in state {
523        if let Value::String(raw) = value
524            && is_credential(key)
525        {
526            let digest = policy.digest(key, raw.as_bytes());
527            shown.insert(key.clone(), Value::String(digest.clone()));
528            digests.push((digest, raw.clone()));
529        }
530    }
531    (shown, digests)
532}
533
534/// `body` with each string under a secret-looking key, at any depth, replaced by its digest.
535fn digested_json(policy: &HttpActionPolicy, body: &Value, key: Option<&str>) -> Value {
536    match body {
537        Value::String(raw) if key.is_some_and(is_credential) => {
538            Value::String(policy.digest(key.unwrap_or_default(), raw.as_bytes()))
539        }
540        Value::Object(map) => Value::Object(
541            map.iter()
542                .map(|(name, value)| (name.clone(), digested_json(policy, value, Some(name))))
543                .collect(),
544        ),
545        Value::Array(items) => {
546            Value::Array(items.iter().map(|item| digested_json(policy, item, key)).collect())
547        }
548        other => other.clone(),
549    }
550}
551
552/// `approved` with each digest under a secret-looking key replaced by the value `current`
553/// holds at the same place; fails naming the field whose credential changed.
554fn restored_json(
555    policy: &HttpActionPolicy,
556    approved: &Value,
557    current: Option<&Value>,
558    key: Option<&str>,
559) -> std::result::Result<Value, String> {
560    match approved {
561        Value::String(digest)
562            if key.is_some_and(is_credential) && digest.starts_with("sha256:") =>
563        {
564            let name = key.unwrap_or_default();
565            current
566                .and_then(Value::as_str)
567                .filter(|raw| policy.digest(name, raw.as_bytes()) == *digest)
568                .map(|raw| Value::String(raw.to_string()))
569                .ok_or_else(|| format!("the credential in body field '{name}'"))
570        }
571        Value::Object(map) => map
572            .iter()
573            .map(|(name, value)| {
574                restored_json(
575                    policy,
576                    value,
577                    current.and_then(|current| current.get(name)),
578                    Some(name),
579                )
580                .map(|value| (name.clone(), value))
581            })
582            .collect::<std::result::Result<serde_json::Map<_, _>, _>>()
583            .map(Value::Object),
584        Value::Array(items) => items
585            .iter()
586            .enumerate()
587            .map(|(at, item)| {
588                restored_json(policy, item, current.and_then(|current| current.get(at)), key)
589            })
590            .collect::<std::result::Result<Vec<_>, _>>()
591            .map(Value::Array),
592        other => Ok(other.clone()),
593    }
594}
595
596/// Whether `text` still holds a credential digest: `sha256:` and 64 hex digits.
597fn holds_digest(text: &str) -> bool {
598    text.match_indices("sha256:").any(|(at, _)| {
599        let hex = &text.as_bytes()[at + 7..];
600        hex.len() >= 64 && hex[..64].iter().all(u8::is_ascii_hexdigit)
601    })
602}
603
604/// The call an HTTP node makes for `state`, as an approver sees it and as its record
605/// binds it (spec 3.3 §12, §7.1).
606///
607/// Carries the method, the full URL with its query, every header (authentication
608/// included) and the body. Credentials appear as `sha256:` digests, so the call is bound
609/// exactly while the decision shows no secret: authorization and cookie headers, an API
610/// key's header whatever its name, headers, query parameters, form fields and JSON body
611/// fields with secret-looking names, and in a raw body the values of state keys with
612/// secret-looking names. A request that cannot be built is described by its method and
613/// why, never by the state it read.
614pub(crate) fn call_args(
615    config: &HttpNodeConfig,
616    state: &HashMap<String, Value>,
617    policy: &HttpActionPolicy,
618) -> Option<Value> {
619    let request = match build_request(config, state, policy) {
620        Ok((_, request)) => request,
621        Err(error) => {
622            return Some(json!({ "method": format!("{:?}", config.method), "error": error }));
623        }
624    };
625    let api_key = api_key_header(config, state);
626    let secret = |name: &str| is_credential(name) || api_key.as_deref() == Some(name);
627    let mut headers = serde_json::Map::new();
628    for name in request.headers().keys() {
629        let raw = header_value(request.headers(), name);
630        let value = if secret(name.as_str()) {
631            policy.digest(name.as_str(), &raw)
632        } else {
633            String::from_utf8_lossy(&raw).into_owned()
634        };
635        headers.insert(name.as_str().to_string(), Value::String(value));
636    }
637    let mut call = json!({
638        "method": request.method().as_str(),
639        "url": digested_url(policy, request.url()).as_str(),
640        "headers": headers,
641    });
642    match &config.body {
643        HttpBody::None => {}
644        HttpBody::Json { data } => {
645            call["body"] = digested_json(policy, &interpolate_json_values(data, state), None);
646        }
647        HttpBody::Form { fields } => {
648            let form: serde_json::Map<String, Value> = fields
649                .iter()
650                .map(|(name, value)| {
651                    let value = interpolate_variables(value, state);
652                    let value = if is_credential(name) {
653                        policy.digest(name, value.as_bytes())
654                    } else {
655                        value
656                    };
657                    (name.clone(), Value::String(value))
658                })
659                .collect();
660            call["form"] = Value::Object(form);
661        }
662        HttpBody::Raw { content, .. } => {
663            let (shown, _) = digested_state(policy, state);
664            call["rawBody"] = Value::String(interpolate_variables(content, &shown));
665        }
666    }
667    Some(call)
668}
669
670/// Sends exactly `args`, a call [`call_args`] described and an approver may have edited
671/// (spec 3.3 §7.1, §7.5).
672///
673/// Each digest in `args` is replaced by the credential `state` holds now; a digest that
674/// no longer matches it refuses the call, which is then not sent.
675///
676/// # Errors
677///
678/// Returns [`GovernedError::Refused`](crate::governed::GovernedError::Refused) when a
679/// credential changed or the policy refuses the URL, and the errors
680/// [`execute_http_with_policy`] returns.
681pub(crate) async fn run_call(
682    config: &HttpNodeConfig,
683    state: &HashMap<String, Value>,
684    policy: &HttpActionPolicy,
685    args: &Value,
686    governed: bool,
687) -> Result<NodeOutput> {
688    let node = config.standard.id.clone();
689    let refuse = |reason: String| -> GraphError {
690        crate::governed::GovernedError::Refused { node: node.clone(), reason }.into()
691    };
692    let changed = |what: String| {
693        refuse(format!("{what} changed since the call was approved; the call was not sent"))
694    };
695    let (client, current) = build_request(config, state, policy).map_err(&refuse)?;
696    let api_key = api_key_header(config, state);
697    let secret = |name: &str| {
698        is_credential(name) || api_key.as_deref() == Some(name.to_ascii_lowercase().as_str())
699    };
700
701    let method = args["method"]
702        .as_str()
703        .and_then(|method| reqwest::Method::from_bytes(method.as_bytes()).ok())
704        .ok_or_else(|| refuse("the call has no valid method".to_string()))?;
705    let mut url = args["url"]
706        .as_str()
707        .and_then(|url| reqwest::Url::parse(url).ok())
708        .ok_or_else(|| refuse("the call has no valid URL".to_string()))?;
709
710    // Credentials in the query and the password come back from the current request.
711    let pairs: Vec<(String, String)> = url.query_pairs().into_owned().collect();
712    if pairs.iter().any(|(name, value)| is_credential(name) && value.starts_with("sha256:")) {
713        let mut resolved = Vec::with_capacity(pairs.len());
714        for (name, value) in pairs {
715            if is_credential(&name) && value.starts_with("sha256:") {
716                let current_value = current
717                    .url()
718                    .query_pairs()
719                    .find(|(key, raw)| {
720                        *key == name && policy.digest(&name, raw.as_bytes()) == value
721                    })
722                    .map(|(_, raw)| raw.into_owned())
723                    .ok_or_else(|| {
724                        changed(format!("the credential in query parameter '{name}'"))
725                    })?;
726                resolved.push((name, current_value));
727            } else {
728                resolved.push((name, value));
729            }
730        }
731        url.query_pairs_mut().clear().extend_pairs(resolved);
732    }
733    if url.password().is_some() {
734        if digested_url(policy, current.url()).password() != url.password() {
735            return Err(changed("the URL's password".to_string()));
736        }
737        let _ = url.set_password(current.url().password());
738    }
739    policy.check(&url).map_err(&refuse)?;
740
741    let mut request = client.request(method, url);
742    if let Some(headers) = args["headers"].as_object() {
743        for (name, value) in headers {
744            let value = value.as_str().unwrap_or_default();
745            if secret(name) && value.starts_with("sha256:") {
746                let header = reqwest::header::HeaderName::from_bytes(name.as_bytes())
747                    .map_err(|_| refuse(format!("'{name}' is not a valid header name")))?;
748                let raw = header_value(current.headers(), &header);
749                if raw.is_empty() || policy.digest(name, &raw) != value {
750                    return Err(changed(format!("the credential in header '{name}'")));
751                }
752                request = request.header(header, raw);
753            } else {
754                request = request.header(name.as_str(), value);
755            }
756        }
757    }
758    if let Some(body) = args.get("body") {
759        let current_body = match &config.body {
760            HttpBody::Json { data } => Some(interpolate_json_values(data, state)),
761            _ => None,
762        };
763        let body = restored_json(policy, body, current_body.as_ref(), None).map_err(changed)?;
764        request = request.json(&body);
765    } else if let Some(form) = args["form"].as_object() {
766        let current_form: HashMap<String, String> = match &config.body {
767            HttpBody::Form { fields } => fields
768                .iter()
769                .map(|(name, value)| (name.clone(), interpolate_variables(value, state)))
770                .collect(),
771            _ => HashMap::new(),
772        };
773        let mut fields = HashMap::with_capacity(form.len());
774        for (name, value) in form {
775            let value = value.as_str().unwrap_or_default().to_string();
776            let value = if is_credential(name) && value.starts_with("sha256:") {
777                current_form
778                    .get(name)
779                    .filter(|raw| policy.digest(name, raw.as_bytes()) == value)
780                    .cloned()
781                    .ok_or_else(|| changed(format!("the credential in form field '{name}'")))?
782            } else {
783                value
784            };
785            fields.insert(name.clone(), value);
786        }
787        request = request.form(&fields);
788    } else if let Some(raw) = args["rawBody"].as_str() {
789        let (_, digests) = digested_state(policy, state);
790        let mut raw = raw.to_string();
791        for (digest, value) in &digests {
792            raw = raw.replace(digest.as_str(), value);
793        }
794        if holds_digest(&raw) {
795            return Err(changed("a credential in the raw body".to_string()));
796        }
797        request = request.body(raw);
798    }
799    let request = request
800        .build()
801        .map_err(|e| refuse(format!("the call could not be built: {}", e.without_url())))?;
802    tracing::debug!(node = %config.standard.id, url = %redact_url(request.url()), "sending an approved HTTP call");
803    send(config, &client, request, governed).await
804}
805
806/// Apply authentication to the request builder.
807fn apply_auth(
808    request: reqwest::RequestBuilder,
809    auth: &HttpAuth,
810    state: &HashMap<String, Value>,
811) -> reqwest::RequestBuilder {
812    match auth {
813        HttpAuth::None => request,
814        HttpAuth::Bearer(bearer) => {
815            let token = interpolate_variables(&bearer.token, state);
816            request.bearer_auth(token)
817        }
818        HttpAuth::Basic(basic) => {
819            let username = interpolate_variables(&basic.username, state);
820            let password = interpolate_variables(&basic.password, state);
821            request.basic_auth(username, Some(password))
822        }
823        HttpAuth::ApiKey(api_key) => {
824            let header = interpolate_variables(&api_key.header, state);
825            let value = interpolate_variables(&api_key.value, state);
826            request.header(header, value)
827        }
828    }
829}
830
831/// Apply body to the request builder.
832fn apply_body(
833    request: reqwest::RequestBuilder,
834    body: &HttpBody,
835    state: &HashMap<String, Value>,
836) -> Result<reqwest::RequestBuilder> {
837    match body {
838        HttpBody::None => Ok(request),
839        HttpBody::Json { data } => {
840            // Interpolate string values within the JSON data
841            let interpolated = interpolate_json_values(data, state);
842            Ok(request.json(&interpolated))
843        }
844        HttpBody::Form { fields } => {
845            let interpolated: HashMap<String, String> =
846                fields.iter().map(|(k, v)| (k.clone(), interpolate_variables(v, state))).collect();
847            Ok(request.form(&interpolated))
848        }
849        HttpBody::Raw { content, content_type } => {
850            let interpolated_content = interpolate_variables(content, state);
851            let interpolated_ct = interpolate_variables(content_type, state);
852            Ok(request.header("Content-Type", interpolated_ct).body(interpolated_content))
853        }
854    }
855}
856
857/// Recursively interpolate string values within a JSON value.
858fn interpolate_json_values(value: &Value, state: &HashMap<String, Value>) -> Value {
859    match value {
860        Value::String(s) => {
861            let interpolated = interpolate_variables(s, state);
862            Value::String(interpolated)
863        }
864        Value::Object(map) => {
865            let new_map: serde_json::Map<String, Value> =
866                map.iter().map(|(k, v)| (k.clone(), interpolate_json_values(v, state))).collect();
867            Value::Object(new_map)
868        }
869        Value::Array(arr) => {
870            let new_arr: Vec<Value> =
871                arr.iter().map(|v| interpolate_json_values(v, state)).collect();
872            Value::Array(new_arr)
873        }
874        other => other.clone(),
875    }
876}
877
878/// Parse the HTTP response based on the configured response type.
879async fn parse_response(
880    response: reqwest::Response,
881    response_type: &str,
882    node_id: &str,
883) -> Result<Value> {
884    match response_type {
885        "json" => {
886            let json_value: Value =
887                response.json().await.map_err(|e| GraphError::NodeExecutionFailed {
888                    node: node_id.to_string(),
889                    message: format!("failed to parse JSON response: {e}"),
890                })?;
891            Ok(json_value)
892        }
893        _ => {
894            // Default to text
895            let text = response.text().await.map_err(|e| GraphError::NodeExecutionFailed {
896                node: node_id.to_string(),
897                message: format!("failed to read response text: {e}"),
898            })?;
899            Ok(Value::String(text))
900        }
901    }
902}
903
904/// Validate an HTTP status code against a pattern string.
905///
906/// Supported patterns:
907/// - Single code: `"200"`
908/// - Comma-separated: `"200,201,204"`
909/// - Range: `"200-299"`
910/// - Mixed: `"200-299,404"`
911fn validate_status(status: u16, pattern: &str) -> bool {
912    for part in pattern.split(',') {
913        let part = part.trim();
914        if let Some((start_str, end_str)) = part.split_once('-') {
915            if let (Ok(start), Ok(end)) =
916                (start_str.trim().parse::<u16>(), end_str.trim().parse::<u16>())
917                && status >= start
918                && status <= end
919            {
920                return true;
921            }
922        } else if let Ok(code) = part.parse::<u16>()
923            && status == code
924        {
925            return true;
926        }
927    }
928    false
929}
930
931#[cfg(test)]
932mod tests {
933    use super::*;
934
935    fn url(raw: &str) -> reqwest::Url {
936        reqwest::Url::parse(raw).expect("valid URL")
937    }
938
939    #[test]
940    fn a_file_url_is_rejected_by_default() {
941        let error = HttpActionPolicy::default().check(&url("file:///etc/passwd")).unwrap_err();
942        assert!(error.contains("scheme 'file' is not permitted"), "{error}");
943    }
944
945    #[test]
946    fn http_and_https_to_public_hosts_are_permitted_by_default() {
947        let policy = HttpActionPolicy::default();
948        for raw in ["https://example.com/a", "http://93.184.216.34/", "https://[2606:4700::1111]/"]
949        {
950            assert_eq!(policy.check(&url(raw)), Ok(()), "{raw}");
951        }
952    }
953
954    #[test]
955    fn non_public_addresses_are_refused_unless_private_networks_are_allowed() {
956        let internal = [
957            "http://127.0.0.1:8080/",
958            "http://0x7f.1/",
959            "http://169.254.169.254/latest/meta-data/",
960            "http://10.0.0.1/",
961            "http://172.16.4.2/",
962            "http://192.168.1.1/",
963            "http://100.64.0.1/",
964            "http://0.0.0.0/",
965            "http://[::1]/",
966            "http://[::ffff:169.254.169.254]/",
967            "http://[64:ff9b::a9fe:a9fe]/",
968            "http://[fd00:ec2::254]/",
969            "http://[fe80::1]/",
970            "http://localhost/",
971            "http://LOCALHOST./",
972            "http://api.localhost/",
973        ];
974        let default = HttpActionPolicy::default();
975        let opted_in = HttpActionPolicy::new().allow_private_networks();
976        for raw in internal {
977            let error = default.check(&url(raw)).unwrap_err();
978            assert!(error.contains("allow_private_networks"), "{raw}: {error}");
979            assert_eq!(opted_in.check(&url(raw)), Ok(()), "{raw}");
980        }
981    }
982
983    #[test]
984    fn an_allowlisted_host_is_still_refused_at_a_non_public_address() {
985        let policy = HttpActionPolicy::new().allow_hosts(["127.0.0.1"]);
986        assert!(policy.check(&url("http://127.0.0.1/")).unwrap_err().contains("non-public"));
987        let opted_in = policy.allow_private_networks();
988        assert_eq!(opted_in.check(&url("http://127.0.0.1/")), Ok(()));
989    }
990
991    /// The client checks the address a name resolves to when it connects, so a name that
992    /// resolves to loopback is refused on the first request and on every redirect.
993    #[tokio::test]
994    async fn the_default_client_refuses_a_name_that_resolves_to_loopback() {
995        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
996        let port = listener.local_addr().unwrap().port();
997        let target = format!("http://localhost:{port}/");
998
999        let error = HttpActionPolicy::default().client().unwrap().get(&target).send().await;
1000        let error = error.expect_err("a name for loopback must not be connected to");
1001        assert!(error.is_connect(), "{error:?}");
1002        let accepted =
1003            tokio::time::timeout(std::time::Duration::from_millis(200), listener.accept()).await;
1004        assert!(accepted.is_err(), "no connection reached the listener");
1005
1006        let opted_in = HttpActionPolicy::new().allow_private_networks().client().unwrap();
1007        let request = tokio::spawn(async move { opted_in.get(&target).send().await });
1008        let accepted =
1009            tokio::time::timeout(std::time::Duration::from_secs(5), listener.accept()).await;
1010        assert!(matches!(accepted, Ok(Ok(_))), "the opt-in connects");
1011        request.abort();
1012    }
1013
1014    #[test]
1015    fn the_host_allowlist_matches_exact_hosts_and_subdomain_wildcards() {
1016        let policy = HttpActionPolicy::new().allow_hosts(["api.example.com", "*.Internal.test"]);
1017        let outcomes: Vec<bool> = [
1018            "https://API.example.com/v1",
1019            "https://a.internal.test/",
1020            "https://b.a.internal.test/",
1021            "https://internal.test/",
1022            "https://evilinternal.test/",
1023            "https://example.com/",
1024        ]
1025        .into_iter()
1026        .map(|raw| policy.check(&url(raw)).is_ok())
1027        .collect();
1028        assert_eq!(outcomes, vec![true, true, true, false, false, false]);
1029    }
1030
1031    #[test]
1032    fn a_scheme_list_replaces_the_default() {
1033        let policy = HttpActionPolicy::new().allow_schemes(["HTTPS"]);
1034        assert!(policy.check(&url("http://example.com/")).is_err());
1035        assert!(policy.check(&url("https://example.com/")).is_ok());
1036    }
1037
1038    #[test]
1039    fn a_logged_url_has_no_query_or_credentials() {
1040        assert_eq!(
1041            redact_url(&url("https://user:pass@example.com/path?token=secret#frag")),
1042            "https://example.com/path?redacted"
1043        );
1044        assert_eq!(redact_url(&url("https://example.com/path")), "https://example.com/path");
1045    }
1046
1047    #[test]
1048    fn hmac_sha256_matches_rfc_4231() {
1049        let mac = hmac_sha256(b"Jefe", b"what do ya want for nothing?");
1050        let hex: String = mac.iter().map(|byte| format!("{byte:02x}")).collect();
1051        assert_eq!(hex, "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843");
1052    }
1053
1054    #[test]
1055    fn a_keyed_digest_cannot_be_checked_without_the_key() {
1056        let plain = HttpActionPolicy::new();
1057        let keyed = HttpActionPolicy::new().credential_key("host-secret");
1058        let guess = plain.digest("password", b"Summer2026!");
1059        assert_ne!(keyed.digest("password", b"Summer2026!"), guess);
1060        assert_eq!(
1061            keyed.digest("password", b"Summer2026!"),
1062            keyed.digest("Password", b"Summer2026!"),
1063            "the name is compared without case"
1064        );
1065        assert!(!format!("{keyed:?}").contains("host-secret"));
1066    }
1067
1068    #[test]
1069    fn test_validate_status_single() {
1070        assert!(validate_status(200, "200"));
1071        assert!(!validate_status(201, "200"));
1072    }
1073
1074    #[test]
1075    fn test_validate_status_range() {
1076        assert!(validate_status(200, "200-299"));
1077        assert!(validate_status(250, "200-299"));
1078        assert!(validate_status(299, "200-299"));
1079        assert!(!validate_status(300, "200-299"));
1080        assert!(!validate_status(199, "200-299"));
1081    }
1082
1083    #[test]
1084    fn test_validate_status_comma_separated() {
1085        assert!(validate_status(200, "200,201,204"));
1086        assert!(validate_status(201, "200,201,204"));
1087        assert!(validate_status(204, "200,201,204"));
1088        assert!(!validate_status(202, "200,201,204"));
1089    }
1090
1091    #[test]
1092    fn test_validate_status_mixed() {
1093        assert!(validate_status(200, "200-299,404"));
1094        assert!(validate_status(404, "200-299,404"));
1095        assert!(!validate_status(500, "200-299,404"));
1096    }
1097}