1use serde::{Deserialize, Serialize};
10
11use crate::host::{MAX_DNS_LABEL_LEN, MAX_DNS_NAME_LEN};
12use crate::policy::PolicyError;
13pub use crate::route::{MAX_ROUTES, METHOD_OVERRIDE_HEADERS, PathRefusal, RequestPath, Route};
14
15mod command;
16mod mint;
17
18pub use command::{CommandHome, CommandSource};
19pub use mint::{AWS_CREDENTIALS, AwsSts, GCP_CREDENTIALS, Gcp, GithubApp, Helper, MintSource};
20
21pub const SECRET_RULE_PREFIX: &str = "secrets.";
24
25const RESERVED_HEADERS: &[&str] = &[
28 "host",
29 "content-length",
30 "transfer-encoding",
31 "connection",
32 "keep-alive",
33 "proxy-connection",
34 "proxy-authenticate",
35 "proxy-authorization",
36 "te",
37 "trailer",
38 "upgrade",
39];
40
41#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(deny_unknown_fields)]
45pub struct Secret {
46 pub id: String,
49 pub host: String,
52 pub header: String,
54 pub source: Source,
56 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
60 pub plain_http: bool,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
65 pub port: Option<u16>,
66 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub tls: Option<Tls>,
71 #[serde(default, skip_serializing_if = "Vec::is_empty")]
76 pub allow: Vec<String>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub helper: Option<Helper>,
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "lowercase")]
88pub enum Tls {
89 Terminate,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
96#[non_exhaustive]
97pub enum Permit {
98 Unrestricted,
100 Rule(String),
102 Refused(String),
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(rename_all = "lowercase", deny_unknown_fields)]
110pub enum Source {
111 File(String),
113 Env(String),
115 Keychain {
117 service: String,
119 account: String,
121 },
122 Command(CommandSource),
125 Mint(MintSource),
129}
130
131impl Source {
132 #[must_use]
136 pub fn proxy_only(&self) -> bool {
137 matches!(self, Self::Command(_) | Self::Mint(_))
138 }
139
140 #[must_use]
143 pub fn describe(&self) -> String {
144 match self {
145 Self::Env(name) => format!("env {name}"),
146 Self::File(path) => format!("file {path}"),
147 Self::Keychain { service, .. } => format!("keychain {service}"),
148 Self::Command(command) => format!("command {}", command.program()),
149 Self::Mint(mint) => format!("mint {}", mint.provider()),
150 }
151 }
152}
153
154impl std::fmt::Debug for Secret {
155 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156 f.debug_struct("Secret")
157 .field("id", &self.id)
158 .finish_non_exhaustive()
159 }
160}
161
162impl Secret {
163 #[must_use]
166 pub fn placeholder(&self) -> String {
167 format!("moat-secret:{}:placeholder", self.id)
168 }
169
170 #[must_use]
172 pub fn plain_http_port(&self) -> u16 {
173 self.port.unwrap_or(80)
174 }
175
176 #[must_use]
180 pub fn is_loopback(&self) -> bool {
181 let host = self.host.as_str();
182 host == "localhost"
183 || host.ends_with(".localhost")
184 || host
185 .parse::<core::net::Ipv4Addr>()
186 .is_ok_and(|ip| ip.is_loopback())
187 }
188
189 #[must_use]
191 pub fn terminates(&self) -> bool {
192 self.tls == Some(Tls::Terminate)
193 }
194
195 #[must_use]
202 pub fn permit(&self, method: &str, target: &str, header_names: &[&str]) -> Permit {
203 if self.allow.is_empty() {
204 return Permit::Unrestricted;
205 }
206 let refused = |why: String| {
207 Permit::Refused(format!(
208 "{method} request to {} is refused for secret `{}`: {why}",
209 self.host, self.id
210 ))
211 };
212 let path = match RequestPath::parse(target) {
213 Ok(path) => path,
214 Err(why) => return refused(why.to_string()),
215 };
216 if let Some(name) = header_names.iter().find(|name| {
217 METHOD_OVERRIDE_HEADERS
218 .iter()
219 .any(|h| name.eq_ignore_ascii_case(h))
220 }) {
221 return refused(format!("its `{name}` header asks for another method"));
222 }
223 if path.overrides_method() {
224 return refused("its query names a `_method` parameter".to_owned());
225 }
226 self.allow
228 .iter()
229 .find(|rule| Route::parse(rule).is_ok_and(|r| r.matches(method, &path)))
230 .map_or_else(
231 || refused("it matches none of the secret's `allow` rules".to_owned()),
232 |rule| Permit::Rule(rule.clone()),
233 )
234 }
235}
236
237pub(crate) fn check(secrets: &[Secret]) -> Result<(), PolicyError> {
239 for (i, secret) in secrets.iter().enumerate() {
240 let fail = |problem: String| PolicyError::Rule {
241 rule: format!("{SECRET_RULE_PREFIX}{}", secret.id),
242 problem,
243 };
244 check_one(secret).map_err(fail)?;
245 if let Some(earlier) = secrets[..i].iter().find(|s| s.id == secret.id) {
246 return Err(PolicyError::DuplicateId(format!(
247 "{SECRET_RULE_PREFIX}{}",
248 earlier.id
249 )));
250 }
251 if let Some(earlier) = secrets[..i]
252 .iter()
253 .find(|s| s.host == secret.host && s.header.eq_ignore_ascii_case(&secret.header))
254 {
255 return Err(fail(format!(
256 "secret `{}` already sets {} for {}",
257 earlier.id, secret.header, secret.host
258 )));
259 }
260 }
261 Ok(())
262}
263
264fn check_one(secret: &Secret) -> Result<(), String> {
265 let id = &secret.id;
266 if id.is_empty()
267 || id.len() > 64
268 || !id
269 .bytes()
270 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
271 {
272 return Err("id must be 1 to 64 lowercase letters, digits or `-`".into());
273 }
274 if !is_host(&secret.host) {
275 return Err(format!(
276 "host `{}` must be one lowercase DNS name or IPv4 address, without port or pattern",
277 secret.host
278 ));
279 }
280 let header = &secret.header;
281 if header.is_empty() || !header.bytes().all(is_token_byte) {
282 return Err(format!("header `{header}` is not an HTTP header name"));
283 }
284 if RESERVED_HEADERS.contains(&header.to_ascii_lowercase().as_str()) {
285 return Err(format!(
286 "header `{header}` frames the request or connection; it cannot carry a secret"
287 ));
288 }
289 match secret.port {
290 Some(0) => return Err("port must be 1 to 65535".into()),
291 Some(port) if !secret.plain_http => {
292 return Err(format!(
293 "port {port} names where plain-HTTP requests get the value; it needs \
294 `plain_http: true`"
295 ));
296 }
297 _ => {}
298 }
299 check_transport(secret)?;
300 mint::check_helper(secret.helper.as_ref(), &secret.source, &secret.host)?;
301 if matches!(secret.source, Source::Mint(MintSource::AwsSts(_)))
302 && (secret.tls.is_some() || secret.plain_http || !secret.allow.is_empty())
303 {
304 return Err(
305 "an `aws-sts` mint goes through `helper: aws` only: AWS requests are signed by the \
306 client, so `tls`, `plain_http` and `allow` cannot apply"
307 .into(),
308 );
309 }
310 match &secret.source {
311 Source::File(path) if !(crate::paths::is_absolute(path) || path.starts_with("~/")) => Err(
312 format!("source file `{path}` must be absolute or start with `~/`"),
313 ),
314 Source::Env(name) if !is_env_name(name) => {
315 Err(format!("source env `{name}` is not a variable name"))
316 }
317 Source::Keychain { service, account }
318 if [service, account]
319 .iter()
320 .any(|s| s.is_empty() || s.chars().any(char::is_control)) =>
321 {
322 Err("source keychain needs a service and an account without control characters".into())
323 }
324 Source::Command(command) => command::check(command),
325 Source::Mint(mint) => mint::check(mint),
326 _ => Ok(()),
327 }
328}
329
330fn check_transport(secret: &Secret) -> Result<(), String> {
333 if secret.terminates() && secret.host.parse::<core::net::Ipv4Addr>().is_ok() {
334 return Err(format!(
335 "`tls: terminate` needs a DNS name; {} is an address, which the proxy's \
336 certificate authority may not sign for",
337 secret.host
338 ));
339 }
340 if secret.allow.is_empty() {
341 return Ok(());
342 }
343 if !secret.terminates() && !secret.plain_http {
344 return Err(
345 "`allow` rules need `tls: terminate` or `plain_http: true`: elsewhere the proxy \
346 cannot read the request"
347 .into(),
348 );
349 }
350 if secret.allow.len() > MAX_ROUTES {
351 return Err(format!("`allow` lists more than {MAX_ROUTES} rules"));
352 }
353 secret
354 .allow
355 .iter()
356 .try_for_each(|rule| Route::parse(rule).map(drop))
357}
358
359fn is_host(host: &str) -> bool {
361 host.len() <= MAX_DNS_NAME_LEN
362 && host.split('.').all(|label| {
363 !label.is_empty()
364 && label.len() <= MAX_DNS_LABEL_LEN
365 && label
366 .bytes()
367 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
368 })
369}
370
371fn is_token_byte(b: u8) -> bool {
373 b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
374}
375
376fn is_env_name(name: &str) -> bool {
377 let mut bytes = name.bytes();
378 bytes
379 .next()
380 .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
381 && bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
382}
383
384#[cfg(test)]
385mod tests;