Skip to main content

openmoat_core/
secret.rs

1//! Brokered secrets: the policy's `secrets:` list (ADR-020, docs/POLICY.md ยง2.1).
2//!
3//! OpenMoat keeps the value; the agent holds a placeholder; `moat proxy` puts the
4//! value into one header of requests to one host, and with `allow` rules only
5//! of the requests they name (`crate::route`, ADR-043). This module is the schema,
6//! its validation and the rules' matching: reading the source is the CLI's
7//! job, using the value is the proxy's.
8
9use 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
21/// What a brokered secret's id is prefixed with where it stands for a rule id
22/// (`secrets.<id>`): lint warnings, policy errors and sandbox losses.
23pub const SECRET_RULE_PREFIX: &str = "secrets.";
24
25/// Headers a secret may not be put in: they frame the request or the
26/// connection, so a secret there would change how the request is read.
27const 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/// One brokered secret. Its `Debug` output names only the id: where the value
42/// lives and where it goes say which secrets exist.
43#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(deny_unknown_fields)]
45pub struct Secret {
46    /// Stable identifier: lowercase letters, digits and `-`. It names the
47    /// placeholder and appears in audit rows; the value never does.
48    pub id: String,
49    /// The one host (a lowercase DNS name or IPv4 literal, no pattern) whose
50    /// requests receive the secret.
51    pub host: String,
52    /// The request header the secret goes in (`Authorization`, `X-Api-Key`).
53    pub header: String,
54    /// Where OpenMoat reads the value, written `{ env: NAME }` and so on.
55    pub source: Source,
56    /// Also inject into plain-HTTP requests, which carry the value in clear
57    /// text. Off unless set: without it a plain-HTTP request keeps the
58    /// placeholder.
59    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
60    pub plain_http: bool,
61    /// The port of the plain-HTTP requests that get the value, 1 to 65535;
62    /// 80 when unset. A request to another port of the host keeps the
63    /// placeholder. Only with `plain_http`.
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub port: Option<u16>,
66    /// `terminate`: `openmoat run`'s proxy decrypts HTTPS to `host` with its own
67    /// certificate authority and puts the value in there (ADR-043). Off unless
68    /// set: without it an HTTPS request keeps the placeholder.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub tls: Option<Tls>,
71    /// The only requests that may receive the value, `METHOD /path` each
72    /// ([`Route`]). Empty: every request to `host` does. With rules, any other
73    /// request to `host` that would get the value is refused before it is
74    /// added. Needs `tls: terminate` or `plain_http`, where requests can be read.
75    #[serde(default, skip_serializing_if = "Vec::is_empty")]
76    pub allow: Vec<String>,
77    /// A local helper of a tool (git's credential helper, AWS's
78    /// `credential_process`) that gets the value from the proxy when the tool
79    /// asks for `host`, without TLS termination (ADR-118). The value then
80    /// reaches that tool's process; meant for minted, short-lived values.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub helper: Option<Helper>,
83}
84
85/// How a brokered secret reaches HTTPS requests.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "lowercase")]
88pub enum Tls {
89    /// The proxy ends the agent's TLS with a certificate it makes for the host,
90    /// reads each request, and opens its own TLS to the host.
91    Terminate,
92}
93
94/// What a secret's `allow` rules say about one request.
95#[derive(Debug, Clone, PartialEq, Eq)]
96#[non_exhaustive]
97pub enum Permit {
98    /// The secret has no rules: every request to its host gets it.
99    Unrestricted,
100    /// The request matches this rule.
101    Rule(String),
102    /// The request matches no rule, or cannot be matched; why, without the path.
103    Refused(String),
104}
105
106/// Where OpenMoat reads a secret's value. The agent should not be able to read it
107/// there; `moat policy lint` warns when no deny rule covers the source.
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(rename_all = "lowercase", deny_unknown_fields)]
110pub enum Source {
111    /// A file, absolute or under `~/`; its contents without the trailing newline.
112    File(String),
113    /// An environment variable of the `moat proxy` process.
114    Env(String),
115    /// An item in the operating system's keychain.
116    Keychain {
117        /// Service name of the item.
118        service: String,
119        /// Account name of the item.
120        account: String,
121    },
122    /// A program the person chose, run by `openmoat proxy` only, whose answer
123    /// is used for at most a lifetime and refreshed before it ends (ADR-087).
124    Command(CommandSource),
125    /// A short-lived credential `openmoat proxy` mints from one the person
126    /// holds, narrowed to what the entry names, and mints again before it
127    /// ends (ADR-118).
128    Mint(MintSource),
129}
130
131impl Source {
132    /// Whether only `openmoat proxy` reads this source: a program it runs,
133    /// which `openmoat guard`, audit delivery and Claude Code's broker never
134    /// start.
135    #[must_use]
136    pub fn proxy_only(&self) -> bool {
137        matches!(self, Self::Command(_) | Self::Mint(_))
138    }
139
140    /// Where the value comes from, without anything that may be private:
141    /// `env NAME`, `file PATH`, `keychain SERVICE`, `command PROGRAM`.
142    #[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    /// What the agent holds instead of the value: `moat-secret:<id>:placeholder`.
164    /// Ids cannot contain `:`, so no placeholder occurs inside another.
165    #[must_use]
166    pub fn placeholder(&self) -> String {
167        format!("moat-secret:{}:placeholder", self.id)
168    }
169
170    /// The port of the plain-HTTP requests the value goes into: `port`, or 80.
171    #[must_use]
172    pub fn plain_http_port(&self) -> u16 {
173        self.port.unwrap_or(80)
174    }
175
176    /// True when the host is this machine: `localhost`, a name under it, or
177    /// `127.0.0.0/8`. Hosts are validated lowercase DNS names or IPv4. The
178    /// address type comes from `core`, which parses and does no I/O.
179    #[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    /// Whether `openmoat run`'s proxy decrypts HTTPS to the host (`tls: terminate`).
190    #[must_use]
191    pub fn terminates(&self) -> bool {
192        self.tls == Some(Tls::Terminate)
193    }
194
195    /// What the `allow` rules say about a `method` request for `target` (the
196    /// request line's target) whose headers are named `header_names`. With
197    /// rules, a request is refused when its path could be read as another
198    /// ([`PathRefusal`]) or it asks for another method ([`METHOD_OVERRIDE_HEADERS`],
199    /// a `_method` query parameter). Reasons never quote the path: it may hold
200    /// what the request is about.
201    #[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        // Validated when the policy loaded, so every rule parses.
227        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
237/// Validate the `secrets:` list. Errors name the secret as `secrets.<id>`.
238pub(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
330/// `tls` and `allow`: termination names a host a certificate can name, and
331/// rules need requests the proxy can read.
332fn 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
359/// The form `moat proxy` reports hosts in, so the comparison is exact.
360fn 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
371/// RFC 9110 `tchar`.
372fn 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;