alien_core/resources/
sandbox_credentials.rs1use serde::Deserialize;
6use std::fmt;
7
8pub const MAX_SANDBOX_CREDENTIAL_RULES: usize = 32;
10pub const MAX_SANDBOX_CREDENTIAL_VALUE_BYTES: usize = 8 * 1024;
12
13const RESERVED_HEADERS: [&str; 8] = [
15 "host",
16 "content-length",
17 "transfer-encoding",
18 "connection",
19 "proxy-authorization",
20 "upgrade",
21 "trailer",
22 "te",
23];
24
25#[derive(Clone, PartialEq, Eq, Deserialize)]
27#[serde(transparent)]
28pub struct CredentialValue(String);
29
30impl CredentialValue {
31 pub fn new(value: impl Into<String>) -> Self {
32 Self(value.into())
33 }
34 pub fn expose(&self) -> &str {
36 &self.0
37 }
38}
39
40impl fmt::Debug for CredentialValue {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 f.write_str("<redacted>")
43 }
44}
45
46impl From<String> for CredentialValue {
47 fn from(value: String) -> Self {
48 Self(value)
49 }
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
59#[serde(rename_all = "camelCase", deny_unknown_fields)]
60pub struct SandboxCredentialRule {
61 #[serde(default)]
63 pub host: Option<String>,
64 #[serde(default)]
66 pub link: Option<String>,
67 #[serde(default)]
69 pub port: Option<u16>,
70 #[serde(default)]
72 pub method: Option<String>,
73 #[serde(default)]
75 pub path: Option<String>,
76 pub header: String,
78 #[serde(default)]
80 pub value_prefix: Option<String>,
81 pub value: CredentialValue,
83}
84
85impl SandboxCredentialRule {
86 pub fn to_wire(&self) -> serde_json::Value {
89 let mut wire = serde_json::json!({ "header": self.header, "value": self.value.0 });
90 for (name, field) in [
91 ("host", self.host.clone().map(serde_json::Value::from)),
92 ("link", self.link.clone().map(serde_json::Value::from)),
93 ("port", self.port.map(serde_json::Value::from)),
94 ("method", self.method.clone().map(serde_json::Value::from)),
95 ("path", self.path.clone().map(serde_json::Value::from)),
96 (
97 "valuePrefix",
98 self.value_prefix.clone().map(serde_json::Value::from),
99 ),
100 ] {
101 if let Some(field) = field {
102 wire[name] = field;
103 }
104 }
105 wire
106 }
107
108 pub fn validate(&self) -> Result<(), String> {
110 match (&self.host, &self.link) {
111 (Some(host), None) => {
112 let valid = !host.is_empty()
113 && host.len() <= 253
114 && host.parse::<std::net::IpAddr>().is_err()
115 && host.split('.').all(|label| {
116 !label.is_empty()
117 && label.len() <= 63
118 && label
119 .bytes()
120 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
121 });
122 if !valid {
123 return Err(format!(
124 "credential host '{host}' must be an exact lowercase DNS name"
125 ));
126 }
127 }
128 (None, Some(link)) if !link.is_empty() => {}
129 _ => return Err("a credential rule names exactly one host or link".into()),
130 }
131 if self.port == Some(0) {
132 return Err("credential port must be between 1 and 65535".into());
133 }
134 if let Some(method) = &self.method {
135 if method.is_empty() || !method.bytes().all(|b| b.is_ascii_uppercase()) {
136 return Err(format!(
137 "credential method '{method}' must be an uppercase HTTP method"
138 ));
139 }
140 }
141 if let Some(path) = &self.path {
142 if !path.starts_with('/')
143 || path.contains(['?', '#', '%', '\\'])
144 || path.split('/').any(|part| part == "." || part == "..")
145 || path.len() > 2048
146 {
147 return Err(format!(
148 "credential path '{path}' must be an absolute path without query, escapes or dot segments"
149 ));
150 }
151 }
152 let header = self.header.to_ascii_lowercase();
153 if header.is_empty()
154 || !header
155 .bytes()
156 .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
157 {
158 return Err(format!(
159 "credential header '{}' is not a valid header name",
160 self.header
161 ));
162 }
163 if RESERVED_HEADERS.contains(&header.as_str()) {
164 return Err(format!(
165 "credential header '{}' routes or frames the request and cannot be set",
166 self.header
167 ));
168 }
169 let prefix = self.value_prefix.as_deref().unwrap_or("");
170 let value = self.value.expose();
171 if value.is_empty() || prefix.len() + value.len() > MAX_SANDBOX_CREDENTIAL_VALUE_BYTES {
172 return Err(format!(
173 "credential value must be 1 to {MAX_SANDBOX_CREDENTIAL_VALUE_BYTES} bytes"
174 ));
175 }
176 if prefix
177 .bytes()
178 .chain(value.bytes())
179 .any(|b| (b < 0x20 && b != b'\t') || b == 0x7f)
180 {
181 return Err("credential value contains a control character".into());
182 }
183 Ok(())
184 }
185}
186
187pub fn validate_sandbox_credentials(rules: &[SandboxCredentialRule]) -> Result<(), String> {
189 if rules.len() > MAX_SANDBOX_CREDENTIAL_RULES {
190 return Err(format!(
191 "a sandbox holds at most {MAX_SANDBOX_CREDENTIAL_RULES} credential rules"
192 ));
193 }
194 for (index, rule) in rules.iter().enumerate() {
195 rule.validate()
196 .map_err(|reason| format!("credential rule {index}: {reason}"))?;
197 }
198 Ok(())
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204
205 const VALUE: &str = "fixture-value-31c7";
206
207 fn rule(json: serde_json::Value) -> SandboxCredentialRule {
208 serde_json::from_value(json).unwrap()
209 }
210
211 #[test]
212 fn debug_and_errors_never_contain_the_value() {
213 let valid = rule(
214 serde_json::json!({"host":"api.example.com","header":"Authorization","valuePrefix":"Bearer ","value":VALUE}),
215 );
216 assert!(valid.validate().is_ok());
217 assert!(!format!("{valid:?}").contains(VALUE));
218 for invalid in [
219 serde_json::json!({"host":"*.example.com","header":"Authorization","value":VALUE}),
220 serde_json::json!({"host":"1.2.3.4","header":"Authorization","value":VALUE}),
221 serde_json::json!({"link":"connector","host":"a.example.com","header":"Authorization","value":VALUE}),
222 serde_json::json!({"link":"connector","header":"Host","value":VALUE}),
223 serde_json::json!({"link":"connector","header":"Authorization","path":"/a/../b","value":VALUE}),
224 serde_json::json!({"link":"connector","header":"Authorization","method":"get","value":VALUE}),
225 serde_json::json!({"link":"connector","header":"Authorization","value":format!("{VALUE}\r\nX: y")}),
226 ] {
227 let error = rule(invalid).validate().unwrap_err();
228 assert!(!error.contains(VALUE), "{error}");
229 }
230 }
231}