1use 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#[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 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 pub fn new() -> Self {
87 Self::default()
88 }
89
90 #[must_use]
107 pub fn allow_private_networks(mut self) -> Self {
108 self.allow_private = true;
109 self
110 }
111
112 #[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 #[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 #[must_use]
141 pub fn max_redirects(mut self, max_redirects: usize) -> Self {
142 self.max_redirects = max_redirects;
143 self
144 }
145
146 #[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 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 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 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 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 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 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
267fn 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
282pub(crate) fn redact_url(url: &reqwest::Url) -> String {
284 let mut shown = url.clone();
285 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
295pub async fn execute_http(config: &HttpNodeConfig, ctx: &NodeContext) -> Result<NodeOutput> {
301 execute_http_with_policy(config, ctx, &HttpActionPolicy::default()).await
302}
303
304pub 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
337pub(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
349fn 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
382async 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 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 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 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
442fn 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
473fn 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
482fn 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 let _ = shown.set_password(Some(&policy.digest("password", password.as_bytes())));
499 }
500 shown
501}
502
503fn 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
514fn 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
534fn 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
552fn 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
596fn 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
604pub(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
670pub(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 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
806fn 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
831fn 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 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
857fn 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
878async 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 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
904fn 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 #[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}