Skip to main content

shaul_core/
header.rs

1use std::collections::BTreeSet;
2
3use http::{HeaderName, HeaderValue};
4use serde::{Deserialize, Serialize};
5
6use crate::error::{Error, Result};
7
8/// A validated HTTP header pair that can be persisted in a task sidecar.
9#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
10pub struct Header {
11    /// Header name, trimmed and validated as an HTTP header name.
12    pub name: String,
13    /// Header value, trimmed. May contain `${env:NAME}` placeholders that
14    /// backends expand when building the request.
15    pub value: String,
16}
17
18impl Header {
19    /// Trim and validate the pair, rejecting malformed HTTP header names and
20    /// values with [`Error::Config`].
21    pub fn new(name: impl AsRef<str>, value: impl AsRef<str>) -> Result<Self> {
22        let name = name.as_ref().trim().to_string();
23        let value = value.as_ref().trim().to_string();
24        HeaderName::from_bytes(name.as_bytes())
25            .map_err(|_| Error::Config(format!("invalid header name: {name}")))?;
26        HeaderValue::from_str(&value)
27            .map_err(|_| Error::Config(format!("invalid value for header {name}")))?;
28        Ok(Self { name, value })
29    }
30
31    /// Whether the header is one of the credential-bearing names
32    /// (`authorization`, `cookie`, `proxy-authorization`, `x-api-key`),
33    /// compared case-insensitively.
34    pub fn is_sensitive(&self) -> bool {
35        let name = self.name.to_ascii_lowercase();
36        matches!(
37            name.as_str(),
38            "authorization" | "cookie" | "proxy-authorization" | "x-api-key"
39        )
40    }
41
42    /// Clone the header, replacing the value with `<redacted>` when
43    /// [`is_sensitive`](Self::is_sensitive) is true.
44    pub fn redacted(&self) -> Self {
45        if self.is_sensitive() {
46            Self {
47                name: self.name.clone(),
48                value: "<redacted>".to_string(),
49            }
50        } else {
51            self.clone()
52        }
53    }
54}
55
56/// Expand `${env:NAME}` placeholders so secrets can be referenced by name in
57/// task sidecars and config files instead of being persisted as literal
58/// values. Missing variables are an error rather than an empty header.
59pub fn expand_env(value: &str) -> Result<String> {
60    let mut output = String::with_capacity(value.len());
61    let mut rest = value;
62    while let Some(start) = rest.find("${env:") {
63        output.push_str(&rest[..start]);
64        let after = &rest[start + 6..];
65        let Some(end) = after.find('}') else {
66            return Err(Error::Config(
67                "unterminated ${env:...} placeholder in header value".to_string(),
68            ));
69        };
70        let name = after[..end].trim();
71        let resolved = std::env::var(name)
72            .map_err(|_| Error::Config(format!("environment variable is not set: {name}")))?;
73        output.push_str(&resolved);
74        rest = &after[end + 1..];
75    }
76    output.push_str(rest);
77    Ok(output)
78}
79
80/// Authentication supplied for a task. Backends translate this into headers.
81#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
82#[serde(tag = "type", rename_all = "snake_case")]
83pub enum Auth {
84    /// Bearer-token authentication.
85    Bearer {
86        /// Token sent as the `Authorization: Bearer` credential.
87        token: String,
88    },
89    /// HTTP Basic authentication.
90    Basic {
91        /// User name for the Basic credentials.
92        username: String,
93        /// Password for the Basic credentials.
94        password: String,
95    },
96    /// An arbitrary header supplied as the credential, for schemes that do
97    /// not fit the variants above.
98    Header(Header),
99}
100
101impl Auth {
102    /// Construct a [`Auth::Bearer`] from a token.
103    pub fn bearer(token: impl Into<String>) -> Self {
104        Self::Bearer {
105            token: token.into(),
106        }
107    }
108
109    /// Construct an [`Auth::Basic`] from a username and password.
110    pub fn basic(username: impl Into<String>, password: impl Into<String>) -> Self {
111        Self::Basic {
112            username: username.into(),
113            password: password.into(),
114        }
115    }
116
117    /// Short label naming the scheme without revealing its secret: `bearer`,
118    /// `basic:<username>`, or `header:<name>`.
119    pub fn describe(&self) -> String {
120        match self {
121            Auth::Bearer { .. } => "bearer".to_string(),
122            Auth::Basic { username, .. } => format!("basic:{username}"),
123            Auth::Header(header) => format!("header:{}", header.name),
124        }
125    }
126}
127
128/// Per-task request overrides applied by every backend.
129#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
130pub struct RequestOptions {
131    /// Additional headers applied to every request of the task.
132    #[serde(default)]
133    pub headers: Vec<Header>,
134    /// Authentication that backends translate into request headers.
135    #[serde(default)]
136    pub auth: Option<Auth>,
137    /// Whether credential headers may follow redirects to another origin.
138    /// Defaults to `false`, which strips them on cross-origin redirects.
139    #[serde(default)]
140    pub allow_cross_origin_auth: bool,
141}
142
143impl RequestOptions {
144    /// Whether there is nothing to apply: no headers, no auth, and
145    /// cross-origin auth not enabled.
146    pub fn is_empty(&self) -> bool {
147        self.headers.is_empty() && self.auth.is_none() && !self.allow_cross_origin_auth
148    }
149
150    /// Merge global defaults with task overrides. Task headers win on name
151    /// collisions (case-insensitive). Auth becomes an `Authorization` header
152    /// unless the user already supplied one explicitly.
153    pub fn merged(&self, defaults: &[Header]) -> Self {
154        let mut headers = defaults.to_vec();
155        for header in &self.headers {
156            headers.retain(|existing| !existing.name.eq_ignore_ascii_case(&header.name));
157            headers.push(header.clone());
158        }
159
160        let mut auth = self.auth.clone();
161        let has_authorization = headers
162            .iter()
163            .any(|header| header.name.eq_ignore_ascii_case("authorization"));
164        if has_authorization {
165            auth = None;
166        }
167
168        Self {
169            headers,
170            auth,
171            allow_cross_origin_auth: self.allow_cross_origin_auth,
172        }
173    }
174
175    /// Header names that must never be forwarded across origins.
176    pub fn sensitive_header_names(&self) -> BTreeSet<String> {
177        self.headers
178            .iter()
179            .filter(|header| header.is_sensitive())
180            .map(|header| header.name.to_ascii_lowercase())
181            .chain(["authorization".to_string(), "cookie".to_string()])
182            .collect()
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn expands_environment_placeholders() {
192        let expanded = expand_env("prefix-${env:PATH}-suffix").unwrap();
193        assert!(expanded.starts_with("prefix-"));
194        assert!(expanded.ends_with("-suffix"));
195        assert!(expand_env("${env:SHAUL_TEST_MISSING_VARIABLE}").is_err());
196    }
197
198    #[test]
199    fn accepts_placeholder_header_values() {
200        let header = Header::new("Authorization", "Bearer ${env:PATH}").unwrap();
201        assert!(header.is_sensitive());
202    }
203}