Skip to main content

chainguard_sandbox/workspaces/
exchange.rs

1//! Identity exchange for machines without a browser: CI jobs, servers, Kubernetes pods.
2
3use std::sync::Arc;
4
5use super::auth::{BoxFuture, TokenSource};
6use super::{DEFAULT_AUDIENCE, DEFAULT_ISSUER, http};
7use crate::{Error, Result};
8
9crate::opaque_debug!(IdentityExchange);
10
11/// Returns the external OIDC token presented to the STS.
12pub type IdTokenFn = Arc<dyn Fn() -> BoxFuture<'static, Result<String>> + Send + Sync>;
13
14/// A [`TokenSource`] that trades a token from an external OIDC issuer (GitHub Actions, GitLab, a
15/// Kubernetes service account, ...) for a Chainguard token, acting as a Chainguard *assumable
16/// identity* that trusts that issuer and subject.
17///
18/// One-time setup, by an organization owner:
19///
20/// ```text
21/// chainctl iam identities create <name> --parent <org> \
22///   --identity-issuer <issuer URL> --subject <subject> --role sandbox.user
23/// ```
24///
25/// It calls the same SecurityTokenService/Exchange API chainctl uses, over its HTTP binding
26/// (`POST /sts/exchange`). Wrap it in [`cached`](super::cached).
27#[derive(Clone)]
28pub struct IdentityExchange {
29    /// The assumable identity's ID (from `chainctl iam identities list`).
30    pub identity: String,
31    /// See [`github_actions_id_token`], [`env_id_token`] and [`file_id_token`].
32    pub id_token: IdTokenFn,
33    /// Defaults to [`DEFAULT_ISSUER`].
34    pub issuer: String,
35    /// Defaults to [`DEFAULT_AUDIENCE`].
36    pub audience: String,
37}
38
39impl TokenSource for IdentityExchange {
40    fn token(&self) -> BoxFuture<'_, Result<String>> {
41        Box::pin(async move {
42            if self.identity.is_empty() {
43                return Err(Error::other(
44                    "workspaces: IdentityExchange needs identity and id_token",
45                ));
46            }
47            let issuer = if self.issuer.is_empty() {
48                DEFAULT_ISSUER
49            } else {
50                &self.issuer
51            };
52            let aud = if self.audience.is_empty() {
53                DEFAULT_AUDIENCE
54            } else {
55                &self.audience
56            };
57            let idt = (self.id_token)()
58                .await
59                .map_err(|e| Error::other(format!("getting the OIDC token to exchange: {e}")))?;
60            let url = format!(
61                "{}/sts/exchange?{}",
62                issuer.trim_end_matches('/'),
63                http::query(&[("aud", aud), ("identity", &self.identity)])
64            );
65            let req = http::client()?
66                .post(url)
67                .header("Content-Length", "0")
68                .header("Authorization", format!("Bearer {idt}"))
69                .header("Accept", "application/json");
70            let a = http::send(req, 1 << 20, "STS exchange").await?;
71            if a.status != 200 {
72                return Err(Error::Http {
73                    context: format!("STS exchange for identity {}", self.identity),
74                    status: a.status,
75                    message: http::error_message(&a.body),
76                });
77            }
78            #[derive(serde::Deserialize)]
79            struct Tok {
80                #[serde(default)]
81                token: String,
82            }
83            match serde_json::from_slice::<Tok>(&a.body) {
84                Ok(t) if !t.token.is_empty() => Ok(t.token),
85                _ => Err(Error::other("STS exchange: response has no token")),
86            }
87        })
88    }
89}
90
91/// Fetches a GitHub Actions OIDC token whose audience is the Chainguard issuer (`""` =
92/// [`DEFAULT_ISSUER`]). The workflow needs `permissions: id-token: write`.
93pub fn github_actions_id_token(issuer: &str) -> IdTokenFn {
94    let issuer = if issuer.is_empty() {
95        DEFAULT_ISSUER.to_string()
96    } else {
97        issuer.to_string()
98    };
99    Arc::new(move || {
100        let issuer = issuer.clone();
101        Box::pin(async move {
102            let (Ok(req_url), Ok(req_tok)) = (
103                std::env::var("ACTIONS_ID_TOKEN_REQUEST_URL"),
104                std::env::var("ACTIONS_ID_TOKEN_REQUEST_TOKEN"),
105            ) else {
106                return Err(Error::other(
107                    "not in a GitHub Actions job with `permissions: id-token: write`",
108                ));
109            };
110            if req_url.is_empty() || req_tok.is_empty() {
111                return Err(Error::other(
112                    "not in a GitHub Actions job with `permissions: id-token: write`",
113                ));
114            }
115            let mut u = url::Url::parse(&req_url).map_err(|e| Error::other(e.to_string()))?;
116            let kept: Vec<(String, String)> = u
117                .query_pairs()
118                .into_owned()
119                .filter(|(k, _)| k != "audience")
120                .collect();
121            u.query_pairs_mut()
122                .clear()
123                .extend_pairs(kept)
124                .append_pair("audience", &issuer);
125            let req = http::client()?
126                .get(u)
127                .header("Authorization", format!("Bearer {req_tok}"));
128            let a = http::send(req, 1 << 20, "GitHub Actions OIDC token request").await?;
129            #[derive(serde::Deserialize)]
130            struct V {
131                #[serde(default)]
132                value: String,
133            }
134            match serde_json::from_slice::<V>(&a.body) {
135                Ok(v) if a.status == 200 && !v.value.is_empty() => Ok(v.value),
136                _ => Err(Error::other(format!(
137                    "GitHub Actions OIDC token request failed: HTTP {}",
138                    a.status
139                ))),
140            }
141        })
142    })
143}
144
145/// Reads the OIDC token from an environment variable (e.g. a GitLab CI `id_tokens:` variable).
146pub fn env_id_token(name: &str) -> IdTokenFn {
147    let name = name.to_string();
148    Arc::new(move || {
149        let name = name.clone();
150        Box::pin(async move {
151            match std::env::var(&name) {
152                Ok(v) if !v.trim().is_empty() => Ok(v.trim().to_string()),
153                _ => Err(Error::other(format!("${name} is empty"))),
154            }
155        })
156    })
157}
158
159/// Reads the OIDC token from a file on every call (e.g. a Kubernetes projected service-account
160/// token, which is rotated in place).
161pub fn file_id_token(path: impl Into<std::path::PathBuf>) -> IdTokenFn {
162    let path = path.into();
163    Arc::new(move || {
164        let path = path.clone();
165        Box::pin(async move {
166            let b = tokio::fs::read(&path)
167                .await
168                .map_err(|e| Error::io(path.display().to_string(), e))?;
169            let v = String::from_utf8_lossy(&b).trim().to_string();
170            if v.is_empty() {
171                return Err(Error::other(format!("{} is empty", path.display())));
172            }
173            Ok(v)
174        })
175    })
176}