1use std::collections::BTreeSet;
2
3use http::{HeaderName, HeaderValue};
4use serde::{Deserialize, Serialize};
5
6use crate::error::{Error, Result};
7
8#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
10pub struct Header {
11 pub name: String,
13 pub value: String,
16}
17
18impl Header {
19 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 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 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
56pub 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
82#[serde(tag = "type", rename_all = "snake_case")]
83pub enum Auth {
84 Bearer {
86 token: String,
88 },
89 Basic {
91 username: String,
93 password: String,
95 },
96 Header(Header),
99}
100
101impl Auth {
102 pub fn bearer(token: impl Into<String>) -> Self {
104 Self::Bearer {
105 token: token.into(),
106 }
107 }
108
109 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 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#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
130pub struct RequestOptions {
131 #[serde(default)]
133 pub headers: Vec<Header>,
134 #[serde(default)]
136 pub auth: Option<Auth>,
137 #[serde(default)]
140 pub allow_cross_origin_auth: bool,
141}
142
143impl RequestOptions {
144 pub fn is_empty(&self) -> bool {
147 self.headers.is_empty() && self.auth.is_none() && !self.allow_cross_origin_auth
148 }
149
150 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 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}