chainguard_sandbox/workspaces/
auth.rs1use 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
15pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
17
18pub trait TokenSource: Send + Sync {
25 fn token(&self) -> BoxFuture<'_, Result<String>>;
27 fn invalidate(&self) {}
29}
30
31pub type SharedTokenSource = Arc<dyn TokenSource>;
33
34#[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(..)") }
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
67pub 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#[derive(Debug, Clone, Default)]
79pub struct ChainctlToken {
80 pub path: String,
82 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
121pub 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
148const FETCH_TIMEOUT: Duration = Duration::from_secs(11 * 60);
150
151pub 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
239pub(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
249pub(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}