Skip to main content

openmoat_core/secret/
mint.rs

1//! Brokered secrets OpenMoat mints itself for one session (ADR-118): the
2//! schema of `source: { mint: … }`, of a secret's `helper:`, and their
3//! validation. Signing and sending the minting request is the CLI's job
4//! (`secrets/mint.rs`), and only `openmoat proxy` and `openmoat run`'s proxy
5//! do it.
6//!
7//! Each provider here has an official call that turns a credential the person
8//! holds into a narrower one that expires on its own: a GitHub App
9//! installation token limited to named repositories and permissions, an AWS
10//! STS session limited by a session policy, a Google Cloud service account
11//! access token limited to named scopes. Every narrowing field is required:
12//! a mint that would hand out everything the person's credential can do is
13//! refused here, so the token the agent's side can use is never wider than
14//! the policy says.
15
16use std::collections::BTreeMap;
17
18use serde::{Deserialize, Serialize};
19
20use super::command::duration_secs;
21
22/// The most repositories one GitHub installation token may name (GitHub's own limit).
23pub const MAX_GITHUB_REPOSITORIES: usize = 500;
24/// The shortest AWS STS session (AWS's own limit, 15 minutes).
25pub const MIN_AWS_LIFETIME_SECS: u64 = 15 * 60;
26/// The longest AWS STS session (AWS's own limit, 12 hours).
27pub const MAX_AWS_LIFETIME_SECS: u64 = 12 * 60 * 60;
28/// The shortest Google Cloud access token a mint asks for.
29pub const MIN_GCP_LIFETIME_SECS: u64 = 60;
30/// The longest Google Cloud access token without an organisation policy
31/// that extends it (Google's default limit, 1 hour).
32pub const MAX_GCP_LIFETIME_SECS: u64 = 60 * 60;
33/// The lifetime a mint asks for when the policy names none.
34pub const DEFAULT_LIFETIME: &str = "15m";
35/// Where the AWS CLI keeps long-lived keys, read by the proxy only.
36pub const AWS_CREDENTIALS: &str = "~/.aws/credentials";
37/// Where `gcloud auth application-default login` keeps its credential.
38pub const GCP_CREDENTIALS: &str = "~/.config/gcloud/application_default_credentials.json";
39/// The scope prefix every Google OAuth scope has.
40const GCP_SCOPE_PREFIX: &str = "https://www.googleapis.com/auth/";
41
42/// `source: { mint: { <provider>: … } }`. `Debug` names the provider only.
43#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "kebab-case", deny_unknown_fields)]
45pub enum MintSource {
46    /// A GitHub App installation access token (one hour, GitHub's limit).
47    GithubApp(GithubApp),
48    /// AWS STS `AssumeRole` credentials with a session policy.
49    AwsSts(AwsSts),
50    /// A Google Cloud service account access token (`generateAccessToken`).
51    Gcp(Gcp),
52}
53
54/// `mint: { github-app: … }`.
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(deny_unknown_fields)]
57pub struct GithubApp {
58    /// The App's client ID or numeric App ID: the JWT's issuer.
59    pub app: String,
60    /// The installation the token is for.
61    pub installation: u64,
62    /// The App's private key (PEM), absolute or under `~/`; read by the proxy only.
63    pub key: String,
64    /// The repositories (names, without the owner) the token may reach.
65    pub repositories: Vec<String>,
66    /// The permissions the token gets, `contents: read` and so on.
67    pub permissions: BTreeMap<String, String>,
68    /// How long before the token expires a new one is minted; 10 minutes when unset.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub refresh_before: Option<String>,
71}
72
73/// `mint: { aws-sts: … }`.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(deny_unknown_fields)]
76pub struct AwsSts {
77    /// The role to assume, `arn:aws:iam::<account>:role/<name>`.
78    pub role: String,
79    /// The region whose STS endpoint is asked, `us-east-1` and so on.
80    pub region: String,
81    /// The profile of the credentials file the long-lived keys are in; `default` when unset.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub profile: Option<String>,
84    /// The credentials file; [`AWS_CREDENTIALS`] when unset.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub credentials: Option<String>,
87    /// The actions the session may take (`s3:GetObject`); never `*`.
88    pub actions: Vec<String>,
89    /// The resources it may take them on (ARNs); never `*`.
90    pub resources: Vec<String>,
91    /// How long the session lasts, 15m to 12h; [`DEFAULT_LIFETIME`] when unset.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub lifetime: Option<String>,
94    /// How long before it ends a new one is minted; a fifth of the lifetime when unset.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub refresh_before: Option<String>,
97}
98
99/// `mint: { gcp: … }`.
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(deny_unknown_fields)]
102pub struct Gcp {
103    /// The service account the token is for, `name@project.iam.gserviceaccount.com`.
104    pub service_account: String,
105    /// The credential that may impersonate it (`authorized_user` or
106    /// `service_account` JSON); [`GCP_CREDENTIALS`] when unset.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub credentials: Option<String>,
109    /// The OAuth scopes the token gets.
110    pub scopes: Vec<String>,
111    /// How long the token lasts, 1m to 1h; [`DEFAULT_LIFETIME`] when unset.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub lifetime: Option<String>,
114    /// How long before it ends a new one is minted; a fifth of the lifetime when unset.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub refresh_before: Option<String>,
117}
118
119/// `helper:` of a secret: a local helper protocol of a tool, through which
120/// the tool gets the value from the proxy when it asks for the secret's host,
121/// without TLS termination (ADR-118). The value then reaches that tool's
122/// process: use it for minted, short-lived values.
123#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
124#[serde(rename_all = "lowercase", deny_unknown_fields)]
125pub enum Helper {
126    /// git's credential helper, for `https://<host>`; `username` is what git
127    /// sends with the value (`x-access-token` for a GitHub App token).
128    Git {
129        /// The user name git sends with the value.
130        username: String,
131    },
132    /// The AWS CLI's and SDKs' `credential_process`, for an `aws-sts` mint.
133    Aws,
134}
135
136impl Helper {
137    /// The helper's name in the wire protocol and in audit rows.
138    #[must_use]
139    pub fn tool(&self) -> &'static str {
140        match self {
141            Self::Git { .. } => "git",
142            Self::Aws => "aws",
143        }
144    }
145}
146
147impl std::fmt::Debug for MintSource {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        f.debug_struct("MintSource")
150            .field("provider", &self.provider())
151            .finish_non_exhaustive()
152    }
153}
154
155impl MintSource {
156    /// The provider's name as the policy writes it.
157    #[must_use]
158    pub fn provider(&self) -> &'static str {
159        match self {
160            Self::GithubApp(_) => "github-app",
161            Self::AwsSts(_) => "aws-sts",
162            Self::Gcp(_) => "gcp",
163        }
164    }
165
166    /// The files the proxy reads the person's own credential from: the
167    /// agent must be denied them (`openmoat policy lint` warns otherwise).
168    #[must_use]
169    pub fn files(&self) -> Vec<&str> {
170        match self {
171            Self::GithubApp(g) => vec![g.key.as_str()],
172            Self::AwsSts(a) => vec![a.credentials.as_deref().unwrap_or(AWS_CREDENTIALS)],
173            Self::Gcp(g) => vec![g.credentials.as_deref().unwrap_or(GCP_CREDENTIALS)],
174        }
175    }
176
177    /// The lifetime asked for, in seconds; GitHub's tokens always last an hour.
178    #[must_use]
179    pub fn lifetime_secs(&self) -> u64 {
180        let asked = |l: &Option<String>| {
181            duration_secs(l.as_deref().unwrap_or(DEFAULT_LIFETIME)).unwrap_or(15 * 60)
182        };
183        match self {
184            Self::GithubApp(_) => 60 * 60,
185            Self::AwsSts(a) => asked(&a.lifetime),
186            Self::Gcp(g) => asked(&g.lifetime),
187        }
188    }
189
190    /// How long before the value expires a new one is minted, in seconds:
191    /// `refresh_before`, else 10 minutes for GitHub and a fifth of the
192    /// lifetime for the others.
193    #[must_use]
194    pub fn refresh_before_secs(&self) -> u64 {
195        let (written, default) = match self {
196            Self::GithubApp(g) => (&g.refresh_before, 10 * 60),
197            Self::AwsSts(a) => (&a.refresh_before, self.lifetime_secs() / 5),
198            Self::Gcp(g) => (&g.refresh_before, self.lifetime_secs() / 5),
199        };
200        written
201            .as_deref()
202            .and_then(duration_secs)
203            .unwrap_or(default)
204            .max(10)
205    }
206}
207
208/// Why `source` cannot be used, if it cannot.
209pub(super) fn check(source: &MintSource) -> Result<(), String> {
210    for file in source.files() {
211        if !(crate::paths::is_absolute(file) || file.starts_with("~/")) {
212            return Err(format!(
213                "mint file `{file}` must be absolute or start with `~/`"
214            ));
215        }
216    }
217    match source {
218        MintSource::GithubApp(g) => check_github(g),
219        MintSource::AwsSts(a) => check_aws(a),
220        MintSource::Gcp(g) => check_gcp(g),
221    }?;
222    let lifetime = source.lifetime_secs();
223    let before = source.refresh_before_secs();
224    if before >= lifetime {
225        return Err("mint refresh_before must be shorter than the lifetime".into());
226    }
227    Ok(())
228}
229
230fn check_github(g: &GithubApp) -> Result<(), String> {
231    if g.app.is_empty()
232        || !g
233            .app
234            .bytes()
235            .all(|b| b.is_ascii_alphanumeric() || b == b'.')
236    {
237        return Err("github-app `app` must be the App's client ID or numeric App ID".into());
238    }
239    if g.installation == 0 {
240        return Err("github-app `installation` must be the installation's numeric ID".into());
241    }
242    if g.repositories.is_empty() || g.repositories.len() > MAX_GITHUB_REPOSITORIES {
243        return Err(format!(
244            "github-app `repositories` must name 1 to {MAX_GITHUB_REPOSITORIES} repositories: \
245             without them the token reaches every repository of the installation"
246        ));
247    }
248    let name = |s: &str| {
249        !s.is_empty()
250            && s.len() <= 100
251            && s.bytes()
252                .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
253    };
254    if let Some(bad) = g.repositories.iter().find(|r| !name(r)) {
255        return Err(format!(
256            "github-app repository `{bad}` must be a repository name without its owner"
257        ));
258    }
259    if g.permissions.is_empty() {
260        return Err(
261            "github-app `permissions` must name each permission the token gets: without them \
262             it gets every permission of the App"
263                .into(),
264        );
265    }
266    for (permission, level) in &g.permissions {
267        if permission.is_empty()
268            || !permission
269                .bytes()
270                .all(|b| b.is_ascii_lowercase() || b == b'_')
271        {
272            return Err(format!(
273                "github-app permission `{permission}` is not a permission name"
274            ));
275        }
276        if !matches!(level.as_str(), "read" | "write" | "admin") {
277            return Err(format!(
278                "github-app permission `{permission}` must be `read`, `write` or `admin`"
279            ));
280        }
281    }
282    lifetime_text("github-app", None, g.refresh_before.as_deref(), (1, 1))
283}
284
285fn check_aws(a: &AwsSts) -> Result<(), String> {
286    let role = a.role.split(':').collect::<Vec<_>>();
287    let partition_ok = role.get(1).is_some_and(|p| p.starts_with("aws"));
288    let account_ok = role
289        .get(4)
290        .is_some_and(|n| n.len() == 12 && n.bytes().all(|b| b.is_ascii_digit()));
291    if role.len() != 6
292        || role[0] != "arn"
293        || !partition_ok
294        || role[2] != "iam"
295        || !account_ok
296        || !role[5].starts_with("role/")
297        || a.role.chars().any(char::is_control)
298    {
299        return Err(format!(
300            "aws-sts `role` `{}` must be a role ARN, arn:aws:iam::<account>:role/<name>",
301            a.role
302        ));
303    }
304    if a.region.is_empty()
305        || !a
306            .region
307            .bytes()
308            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
309    {
310        return Err(format!(
311            "aws-sts `region` `{}` is not a region name",
312            a.region
313        ));
314    }
315    if let Some(profile) = &a.profile
316        && (profile.is_empty()
317            || profile.contains([']', '['])
318            || profile.chars().any(char::is_control))
319    {
320        return Err("aws-sts `profile` is not a profile name".into());
321    }
322    if a.actions.is_empty() || a.resources.is_empty() {
323        return Err(
324            "aws-sts needs `actions` and `resources`: the session policy is what narrows the \
325             session below the role's own permissions"
326                .into(),
327        );
328    }
329    for action in &a.actions {
330        let (service, name) = action.split_once(':').unwrap_or(("", ""));
331        let ok = |s: &str, star: bool| {
332            !s.is_empty()
333                && s.bytes()
334                    .all(|b| b.is_ascii_alphanumeric() || b == b'-' || (star && b == b'*'))
335        };
336        if !ok(service, false) || !ok(name, true) || name == "*" {
337            return Err(format!(
338                "aws-sts action `{action}` must be `service:Action` and not every action of a \
339                 service"
340            ));
341        }
342    }
343    for resource in &a.resources {
344        if !resource.starts_with("arn:")
345            || resource == "arn:*"
346            || resource
347                .chars()
348                .any(|c| c.is_control() || c == '"' || c == '\\')
349        {
350            return Err(format!(
351                "aws-sts resource `{resource}` must be an ARN, not `*`"
352            ));
353        }
354    }
355    lifetime_text(
356        "aws-sts",
357        a.lifetime.as_deref(),
358        a.refresh_before.as_deref(),
359        (MIN_AWS_LIFETIME_SECS, MAX_AWS_LIFETIME_SECS),
360    )
361}
362
363fn check_gcp(g: &Gcp) -> Result<(), String> {
364    let account = &g.service_account;
365    let (name, domain) = account.split_once('@').unwrap_or(("", ""));
366    if name.is_empty()
367        || !domain.ends_with(".gserviceaccount.com")
368        || !account
369            .bytes()
370            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"@.-_".contains(&b))
371    {
372        return Err(format!(
373            "gcp `service_account` `{account}` must be a service account's email"
374        ));
375    }
376    if g.scopes.is_empty() {
377        return Err("gcp `scopes` must name the OAuth scopes the token gets".into());
378    }
379    if let Some(bad) = g.scopes.iter().find(|s| {
380        s.strip_prefix(GCP_SCOPE_PREFIX).is_none_or(|rest| {
381            rest.is_empty()
382                || !rest
383                    .bytes()
384                    .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
385        })
386    }) {
387        return Err(format!(
388            "gcp scope `{bad}` must be a Google OAuth scope, {GCP_SCOPE_PREFIX}…"
389        ));
390    }
391    lifetime_text(
392        "gcp",
393        g.lifetime.as_deref(),
394        g.refresh_before.as_deref(),
395        (MIN_GCP_LIFETIME_SECS, MAX_GCP_LIFETIME_SECS),
396    )
397}
398
399/// `lifetime` and `refresh_before` as written: durations, the lifetime within `range`.
400fn lifetime_text(
401    provider: &str,
402    lifetime: Option<&str>,
403    before: Option<&str>,
404    (min, max): (u64, u64),
405) -> Result<(), String> {
406    if let Some(text) = lifetime {
407        let secs = duration_secs(text).ok_or_else(|| {
408            format!("{provider} lifetime `{text}` is not a duration such as `15m`")
409        })?;
410        if !(min..=max).contains(&secs) {
411            return Err(format!(
412                "{provider} lifetime `{text}` must be from {min}s to {max}s"
413            ));
414        }
415    }
416    if let Some(text) = before
417        && duration_secs(text).is_none_or(|s| s < 10)
418    {
419        return Err(format!(
420            "{provider} refresh_before `{text}` must be a duration of at least 10s"
421        ));
422    }
423    Ok(())
424}
425
426/// Why `helper` cannot carry a secret with `source` to `host`, if it cannot.
427pub(super) fn check_helper(
428    helper: Option<&Helper>,
429    source: &super::Source,
430    host: &str,
431) -> Result<(), String> {
432    let aws_mint = matches!(source, super::Source::Mint(MintSource::AwsSts(_)));
433    match helper {
434        None if aws_mint => Err(
435            "an `aws-sts` mint needs `helper: aws`: AWS requests are signed by the client, so \
436             the proxy cannot put the credentials in a header"
437                .into(),
438        ),
439        Some(Helper::Aws) if !aws_mint => {
440            Err("`helper: aws` hands out credentials an `aws-sts` mint made, nothing else".into())
441        }
442        None | Some(Helper::Aws) => Ok(()),
443        Some(Helper::Git { username }) => {
444            if host.parse::<core::net::Ipv4Addr>().is_ok() {
445                return Err(format!(
446                    "`helper: git` needs a DNS name; {host} is an address"
447                ));
448            }
449            if username.is_empty()
450                || !username
451                    .bytes()
452                    .all(|b| b.is_ascii_alphanumeric() || b"._-@".contains(&b))
453            {
454                return Err(
455                    "`helper: git` needs a user name of letters, digits, `.`, `_`, `-` or `@`"
456                        .into(),
457                );
458            }
459            Ok(())
460        }
461    }
462}