Skip to main content

chainguard_sandbox/workspaces/
auth.rs

1//! Token sources for the sandbox plane: static tokens, chainctl, the cache.
2
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::{Arc, Mutex};
6use std::time::{Duration, SystemTime, UNIX_EPOCH};
7
8use base64::Engine as _;
9use tokio::sync::watch;
10
11use super::login::{BrowserLoginToken, LoginOptions};
12use super::{DEFAULT_AUDIENCE, ENV_AUTH_TOKEN};
13use crate::{Error, Result};
14
15/// A boxed, sendable future, as returned by [`TokenSource::token`].
16pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
17
18/// Returns a Chainguard bearer token whose audience includes [`DEFAULT_AUDIENCE`] (or, for the
19/// platform API, [`PLATFORM_AUDIENCE`](super::PLATFORM_AUDIENCE)).
20///
21/// Implement it with a function through [`token_fn`]. Caching sources also implement
22/// [`invalidate`](TokenSource::invalidate): the client calls it when the plane answers
23/// `Unauthenticated`, so the next call fetches a fresh token.
24pub trait TokenSource: Send + Sync {
25    /// Returns a token.
26    fn token(&self) -> BoxFuture<'_, Result<String>>;
27    /// Forgets a cached token. The default does nothing.
28    fn invalidate(&self) {}
29}
30
31/// A shared token source.
32pub type SharedTokenSource = Arc<dyn TokenSource>;
33
34/// Always returns the same token.
35#[derive(Clone)]
36pub struct StaticToken(pub String);
37
38impl std::fmt::Debug for StaticToken {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.write_str("StaticToken(..)") // never print the token
41    }
42}
43
44impl TokenSource for StaticToken {
45    fn token(&self) -> BoxFuture<'_, Result<String>> {
46        Box::pin(async move {
47            if self.0.is_empty() {
48                return Err(Error::other("workspaces: empty token"));
49            }
50            Ok(self.0.clone())
51        })
52    }
53}
54
55struct FnToken<F>(F);
56
57impl<F, Fut> TokenSource for FnToken<F>
58where
59    F: Fn() -> Fut + Send + Sync,
60    Fut: Future<Output = Result<String>> + Send + 'static,
61{
62    fn token(&self) -> BoxFuture<'_, Result<String>> {
63        Box::pin((self.0)())
64    }
65}
66
67/// Adapts an async function to a [`TokenSource`].
68pub fn token_fn<F, Fut>(f: F) -> SharedTokenSource
69where
70    F: Fn() -> Fut + Send + Sync + 'static,
71    Fut: Future<Output = Result<String>> + Send + 'static,
72{
73    Arc::new(FnToken(f))
74}
75
76/// Mints tokens by running `chainctl auth token --audience <audience>`. It needs a prior
77/// `chainctl auth login`.
78#[derive(Debug, Clone, Default)]
79pub struct ChainctlToken {
80    /// Path to chainctl; defaults to "chainctl" on `$PATH`.
81    pub path: String,
82    /// Defaults to [`DEFAULT_AUDIENCE`].
83    pub audience: String,
84}
85
86impl TokenSource for ChainctlToken {
87    fn token(&self) -> BoxFuture<'_, Result<String>> {
88        Box::pin(async move {
89            let path = if self.path.is_empty() {
90                "chainctl"
91            } else {
92                &self.path
93            };
94            let aud = if self.audience.is_empty() {
95                DEFAULT_AUDIENCE
96            } else {
97                &self.audience
98            };
99            let out = tokio::process::Command::new(path)
100                .args(["auth", "token", "--audience", aud])
101                .kill_on_drop(true)
102                .output()
103                .await
104                .map_err(|e| Error::io(format!("chainctl auth token --audience {aud}"), e))?;
105            if !out.status.success() {
106                return Err(Error::other(format!(
107                    "chainctl auth token --audience {aud}: {}: {}",
108                    out.status,
109                    String::from_utf8_lossy(&out.stderr).trim()
110                )));
111            }
112            let tok = String::from_utf8_lossy(&out.stdout).trim().to_string();
113            if tok.is_empty() {
114                return Err(Error::other("chainctl auth token returned no token"));
115            }
116            Ok(tok)
117        })
118    }
119}
120
121/// `$CHAINCTL_AUTH_TOKEN` when set, otherwise the library's own login (a cached
122/// [`BrowserLoginToken`]): tokens are minted from the saved login, and a browser login runs when
123/// there is none. chainctl isn't used; set `$CHAINGUARD_SANDBOX_AUTH=chainctl` to mint tokens with
124/// it instead. `$CHAINGUARD_SANDBOX_SOCIAL_LOGIN` preselects the login's social provider (github,
125/// google-oauth2, gitlab), and `$CHAINGUARD_SANDBOX_NO_BROWSER=1` makes a missing login an error
126/// ([`Error::LoginRequired`]) instead of opening a browser.
127pub fn default_token_source() -> SharedTokenSource {
128    if let Some(t) = env_nonempty(ENV_AUTH_TOKEN) {
129        return Arc::new(StaticToken(t));
130    }
131    if std::env::var("CHAINGUARD_SANDBOX_AUTH").as_deref() == Ok("chainctl") {
132        return cached(Arc::new(ChainctlToken::default()));
133    }
134    cached(Arc::new(BrowserLoginToken {
135        login: LoginOptions {
136            connection: std::env::var("CHAINGUARD_SANDBOX_SOCIAL_LOGIN").unwrap_or_default(),
137            ..Default::default()
138        },
139        no_browser: std::env::var("CHAINGUARD_SANDBOX_NO_BROWSER").as_deref() == Ok("1"),
140        ..Default::default()
141    }))
142}
143
144pub(crate) fn env_nonempty(name: &str) -> Option<String> {
145    std::env::var(name).ok().filter(|v| !v.is_empty())
146}
147
148/// How long a shared fetch may take: room for a browser login (10 minutes) plus the refresh.
149const FETCH_TIMEOUT: Duration = Duration::from_secs(11 * 60);
150
151/// Reuses a token until a minute before the `exp` claim of the JWT. Tokens whose expiry can't be
152/// read are cached for five minutes. Concurrent callers share one fetch, which runs on its own
153/// task, so one caller giving up (dropping its future) doesn't fail the others. The client drops
154/// the cached token when the plane answers `Unauthenticated` (see [`TokenSource::invalidate`]).
155pub fn cached(src: SharedTokenSource) -> SharedTokenSource {
156    Arc::new(Cached(Arc::new(CacheInner {
157        src,
158        state: Mutex::new(CacheState::default()),
159    })))
160}
161
162struct Cached(Arc<CacheInner>);
163
164struct CacheInner {
165    src: SharedTokenSource,
166    state: Mutex<CacheState>,
167}
168
169#[derive(Default)]
170struct CacheState {
171    tok: String,
172    exp: Option<SystemTime>,
173    inflight: Option<watch::Receiver<Option<Result<String>>>>,
174}
175
176impl TokenSource for Cached {
177    fn token(&self) -> BoxFuture<'_, Result<String>> {
178        Box::pin(async move {
179            let mut rx = {
180                let mut st = self.0.state.lock().unwrap();
181                if !st.tok.is_empty()
182                    && st
183                        .exp
184                        .is_some_and(|e| e > SystemTime::now() + Duration::from_secs(60))
185                {
186                    return Ok(st.tok.clone());
187                }
188                match &st.inflight {
189                    Some(rx) => rx.clone(),
190                    None => {
191                        let (tx, rx) = watch::channel(None);
192                        st.inflight = Some(rx.clone());
193                        let inner = self.0.clone();
194                        tokio::spawn(async move {
195                            let r = match tokio::time::timeout(FETCH_TIMEOUT, inner.src.token())
196                                .await
197                            {
198                                Ok(r) => r,
199                                Err(_) => Err(Error::other(
200                                    "workspaces: getting a token took longer than 11 minutes",
201                                )),
202                            };
203                            {
204                                let mut st = inner.state.lock().unwrap();
205                                if let Ok(t) = &r {
206                                    st.tok = t.clone();
207                                    st.exp = Some(jwt_expiry(t).unwrap_or_else(|| {
208                                        SystemTime::now() + Duration::from_secs(300)
209                                    }));
210                                }
211                                st.inflight = None;
212                            }
213                            let _ = tx.send(Some(r));
214                        });
215                        rx
216                    }
217                }
218            };
219            loop {
220                if let Some(r) = rx.borrow_and_update().clone() {
221                    return r;
222                }
223                if rx.changed().await.is_err() {
224                    return Err(Error::other(
225                        "workspaces: the token fetch ended without a result",
226                    ));
227                }
228            }
229        })
230    }
231
232    fn invalidate(&self) {
233        let mut st = self.0.state.lock().unwrap();
234        st.tok.clear();
235        st.exp = None;
236    }
237}
238
239/// Reads the unverified `exp` claim of a JWT.
240pub(crate) fn jwt_expiry(tok: &str) -> Option<SystemTime> {
241    let claims = jwt_claims_json(tok)?;
242    let exp = claims.get("exp")?.as_i64()?;
243    if exp == 0 {
244        return None;
245    }
246    Some(UNIX_EPOCH + Duration::from_secs(exp.max(0) as u64))
247}
248
249/// Decodes a JWT's payload without verifying it.
250pub(crate) fn jwt_claims_json(tok: &str) -> Option<serde_json::Value> {
251    let parts: Vec<&str> = tok.split('.').collect();
252    if parts.len() != 3 {
253        return None;
254    }
255    let b = base64::engine::general_purpose::URL_SAFE_NO_PAD
256        .decode(parts[1])
257        .ok()?;
258    serde_json::from_slice(&b).ok()
259}