Skip to main content

chainguard_sandbox/workspaces/
login.rs

1//! Browser login, without chainctl.
2//!
3//! The login flow is adapted from chainguard.dev/sdk/auth/login (v0.1.50, Copyright 2023
4//! Chainguard, Inc., Apache-2.0): a callback server on a random localhost port, and the issuer's
5//! /oauth page opened in the browser with `redirect=<callback>`. The issuer redirects back with
6//! ?token=…&refresh_token=…. The request parameters match what chainctl 0.2.398 sends.
7//!
8//! The saved login is shared with the Go, Python and TypeScript SDKs: same file, same format,
9//! same lock.
10
11use std::collections::BTreeMap;
12use std::io::Write as _;
13use std::path::{Path, PathBuf};
14use std::sync::{Arc, Mutex};
15use std::time::{Duration, SystemTime, UNIX_EPOCH};
16
17use base64::Engine as _;
18use tokio::sync::oneshot;
19
20use super::auth::{BoxFuture, TokenSource, jwt_claims_json};
21use super::http;
22use super::loopback::{LoopbackReply, LoopbackServer};
23use super::{DEFAULT_AUDIENCE, DEFAULT_ISSUER, PLATFORM_AUDIENCE};
24use crate::{Error, Result};
25
26crate::opaque_debug!(LoginOptions, LoginLock, BrowserLoginToken);
27
28/// Receives progress messages ("open this URL ..."). The default writes to stderr.
29pub type MessageSink = Arc<dyn Fn(&str) + Send + Sync>;
30
31/// Opens a URL in a browser; returns false if it couldn't (the URL is then printed instead).
32pub type UrlOpener = Arc<dyn Fn(&str) -> bool + Send + Sync>;
33
34pub(crate) fn say(out: &Option<MessageSink>, msg: &str) {
35    match out {
36        Some(f) => f(msg),
37        None => eprintln!("{msg}"),
38    }
39}
40
41/// Configures [`browser_login`].
42#[derive(Clone, Default)]
43pub struct LoginOptions {
44    /// Defaults to [`DEFAULT_ISSUER`].
45    pub issuer: String,
46    /// What the login's tokens may be minted for. Empty means [`default_login_audiences`]: the
47    /// sessions service plus Chainguard's account API.
48    pub audience: Vec<String>,
49    /// Preselects a social login: "github", "google-oauth2" or "gitlab". Empty lets the page ask.
50    pub connection: String,
51    /// Defaults to "auth0", as chainctl sends. Ignored with `identity_provider` or `org_name`.
52    pub client_id: String,
53    /// The ID of an organization's custom identity provider.
54    pub identity_provider: String,
55    /// The name of an organization with a custom identity provider (verified). At most one of
56    /// `identity_provider` and `org_name`.
57    pub org_name: String,
58    /// An assumable identity to log in as (optional).
59    pub identity: String,
60    /// Skips asking for a refresh token. Without one, every token after the first needs another
61    /// browser login.
62    pub no_refresh_token: bool,
63    /// Opens the login page. Defaults to [`open_browser`].
64    pub open_url: Option<UrlOpener>,
65    /// Receives the "open this URL" message. Defaults to stderr.
66    pub out: Option<MessageSink>,
67}
68
69/// What the issuer hands back.
70#[derive(Clone, Default)]
71pub struct LoginResult {
72    /// A Chainguard token for the requested audiences.
73    pub token: String,
74    /// Mints further tokens (see [`refresh_login`]); empty with `no_refresh_token`.
75    pub refresh_token: String,
76}
77
78impl std::fmt::Debug for LoginResult {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        f.write_str("LoginResult { .. }")
81    }
82}
83
84/// Runs the interactive login: opens the issuer's login page in a browser and waits for the
85/// redirect back to a localhost callback. Bound it with `tokio::time::timeout`.
86pub async fn browser_login(o: LoginOptions) -> Result<LoginResult> {
87    let issuer = if o.issuer.is_empty() {
88        DEFAULT_ISSUER.to_string()
89    } else {
90        o.issuer.clone()
91    };
92    let aud = if o.audience.is_empty() {
93        default_login_audiences()
94    } else {
95        o.audience.clone()
96    };
97    if !o.identity_provider.is_empty() && !o.org_name.is_empty() {
98        return Err(Error::other(
99            "workspaces: login: set at most one of identity_provider and org_name",
100        ));
101    }
102    let srv = LoginServer::start().await.map_err(|e| {
103        Error::io(
104            "workspaces: login: starting the localhost callback server",
105            e,
106        )
107    })?;
108
109    let mut p: Vec<(&str, &str)> = Vec::new();
110    let cid;
111    if !o.identity_provider.is_empty() {
112        p.push(("idp_id", &o.identity_provider));
113    } else if !o.org_name.is_empty() {
114        p.push(("idp_id", &o.org_name)); // the issuer takes a verified org name here too
115    } else {
116        cid = if o.client_id.is_empty() {
117            "auth0".to_string()
118        } else {
119            o.client_id.clone()
120        };
121        p.push(("client_id", &cid));
122        if !o.connection.is_empty() {
123            p.push(("connection", &o.connection));
124        }
125    }
126    let aud_joined = aud.join(",");
127    p.push(("audience", &aud_joined));
128    if !o.no_refresh_token {
129        p.push(("create_refresh_token", "true"));
130        p.push(("refresh_token_rotation", "true"));
131    }
132    if !o.identity.is_empty() {
133        p.push(("identity", &o.identity));
134    }
135    p.push(("skip_registration", "true"));
136    p.push(("exit", "redirect"));
137    p.push(("redirect", &srv.callback_url));
138    let u = format!("{}/oauth?{}", issuer.trim_end_matches('/'), http::query(&p));
139
140    let opened = match &o.open_url {
141        Some(f) => f(&u),
142        None => open_browser(&u),
143    };
144    if opened {
145        say(
146            &o.out,
147            &format!("Opened a browser to log in to Chainguard. If it didn't open, visit:\n  {u}"),
148        );
149    } else {
150        say(
151            &o.out,
152            &format!("Open this URL in a browser to log in to Chainguard:\n  {u}"),
153        );
154    }
155    let LoginServer {
156        result,
157        page_served,
158        server,
159        ..
160    } = srv;
161    let outcome = result.await.unwrap_or_else(|_| {
162        Err(Error::other(
163            "workspaces: login: the callback server stopped",
164        ))
165    });
166    if outcome.is_ok() {
167        // Keep serving until the browser has loaded the success page (the callback redirects
168        // there), so it doesn't show an error.
169        let _ = tokio::time::timeout(Duration::from_secs(5), page_served).await;
170    }
171    server.stop();
172    outcome
173}
174
175struct LoginServer {
176    server: LoopbackServer,
177    callback_url: String,
178    result: oneshot::Receiver<Result<LoginResult>>,
179    page_served: oneshot::Receiver<()>,
180}
181
182#[derive(Default)]
183struct LoginServerState {
184    result: Option<oneshot::Sender<Result<LoginResult>>>,
185    page: Option<oneshot::Sender<()>>,
186    got: bool,
187}
188
189impl LoginServer {
190    async fn start() -> std::io::Result<LoginServer> {
191        let (rtx, rrx) = oneshot::channel();
192        let (ptx, prx) = oneshot::channel();
193        let st = Arc::new(Mutex::new(LoginServerState {
194            result: Some(rtx),
195            page: Some(ptx),
196            got: false,
197        }));
198        let server = LoopbackServer::bind(0, move |req| login_handler(&st, req)).await?;
199        // The issuer only redirects to localhost; the host name is what chainctl sends.
200        let callback_url = format!(
201            "http://localhost:{}/callback?token=true&error=true",
202            server.port
203        );
204        Ok(LoginServer {
205            server,
206            callback_url,
207            result: rrx,
208            page_served: prx,
209        })
210    }
211}
212
213/// The callback server's handler, exported for tests through [`login_callback_server`].
214fn login_handler(
215    st: &Mutex<LoginServerState>,
216    req: super::loopback::LoopbackRequest,
217) -> LoopbackReply {
218    let headers = [
219        ("Cache-Control", "no-store"),
220        ("Referrer-Policy", "no-referrer"),
221    ];
222    if req.method != "GET" {
223        return LoopbackReply::text(405, &headers, "method not allowed");
224    }
225    let finish = |r: Result<LoginResult>| {
226        let mut s = st.lock().unwrap();
227        if let Some(tx) = s.result.take() {
228            s.got = true;
229            let _ = tx.send(r);
230        }
231    };
232    match req.path.as_str() {
233        "/callback" => {
234            let tok = req.query.get("token").cloned().unwrap_or_default();
235            if tok.is_empty() {
236                let code: i64 = req
237                    .query
238                    .get("status_code")
239                    .and_then(|c| c.parse().ok())
240                    .unwrap_or(0);
241                if code == 404 {
242                    finish(Err(Error::AccountNotFound));
243                    return LoopbackReply::text(
244                        404,
245                        &headers,
246                        "No Chainguard account was found for this login.",
247                    );
248                }
249                let msg = req
250                    .query
251                    .get("error")
252                    .filter(|m| !m.is_empty())
253                    .cloned()
254                    .unwrap_or_else(|| "login failed".into());
255                finish(Err(Error::other(format!(
256                    "workspaces: login: the issuer reported an error (status {code}): {msg}"
257                ))));
258                return LoopbackReply::text(400, &headers, format!("Login failed: {msg}"));
259            }
260            finish(Ok(LoginResult {
261                token: tok,
262                refresh_token: req.query.get("refresh_token").cloned().unwrap_or_default(),
263            }));
264            // Redirect so the tokens leave the address bar and history entry.
265            let mut r = LoopbackReply::text(303, &headers, "");
266            r.headers.push(("Location", "/".into()));
267            r
268        }
269        "/" => {
270            let mut s = st.lock().unwrap();
271            if !s.got {
272                return LoopbackReply::text(404, &headers, "404 page not found");
273            }
274            if let Some(tx) = s.page.take() {
275                let _ = tx.send(());
276            }
277            let mut h: Vec<(&'static str, &str)> = headers.to_vec();
278            h.push(("Content-Type", "text/html; charset=utf-8"));
279            LoopbackReply::text(200, &h, LOGIN_DONE_PAGE)
280        }
281        _ => LoopbackReply::text(404, &headers, "404 page not found"),
282    }
283}
284
285const LOGIN_DONE_PAGE: &str = r#"<!doctype html><html><head><meta charset="utf-8"><title>Login complete</title>
286<style>:root{color-scheme:light dark;font-family:system-ui,sans-serif}body{display:grid;place-items:center;height:100vh;margin:0}</style>
287</head><body><div><h1>Chainguard login complete</h1><p>You can close this tab and return to your program.</p></div></body></html>"#;
288
289/// Opens `u` in the default browser (open on macOS, xdg-open on Linux and BSDs, the URL handler
290/// on Windows). No shell is involved. Returns whether it worked.
291pub fn open_browser(u: &str) -> bool {
292    let mut cmd = if cfg!(target_os = "macos") {
293        std::process::Command::new("open")
294    } else if cfg!(windows) {
295        let mut c = std::process::Command::new("rundll32");
296        c.arg("url.dll,FileProtocolHandler");
297        c
298    } else {
299        std::process::Command::new("xdg-open")
300    };
301    cmd.arg(u)
302        .stdin(std::process::Stdio::null())
303        .stdout(std::process::Stdio::null())
304        .stderr(std::process::Stdio::null())
305        .status()
306        .map(|s| s.success())
307        .unwrap_or(false)
308}
309
310// ---- refresh tokens -----------------------------------------------------------------------
311
312/// Trades a refresh token for a token for `aud` ([`DEFAULT_AUDIENCE`] if empty). With rotation the
313/// issuer returns a new refresh token, which replaces the old one (empty if it didn't rotate).
314/// Returns `(token, new_refresh_token)`. A refused refresh token is [`Error::LoginExpired`].
315pub async fn refresh_login(
316    issuer: &str,
317    refresh_token: &str,
318    aud: &str,
319) -> Result<(String, String)> {
320    let issuer = if issuer.is_empty() {
321        DEFAULT_ISSUER
322    } else {
323        issuer
324    };
325    let aud = if aud.is_empty() {
326        DEFAULT_AUDIENCE
327    } else {
328        aud
329    };
330    // The HTTP binding takes the request fields as query parameters (a JSON body is ignored).
331    let url = format!(
332        "{}/sts/exchange_refresh_token?{}",
333        issuer.trim_end_matches('/'),
334        http::query(&[("aud", aud)])
335    );
336    let req = http::client()?
337        .post(url)
338        // The issuer refuses a POST without Content-Length (HTTP 411).
339        .header("Content-Length", "0")
340        .header("Authorization", format!("Bearer {refresh_token}"))
341        .header("Accept", "application/json");
342    let a = http::send(req, 1 << 20, "refreshing the login").await?;
343    if a.status != 200 {
344        let msg = http::error_message(&a.body);
345        if refresh_refused(a.status, &msg) {
346            return Err(Error::LoginExpired {
347                detail: format!("refreshing the login: HTTP {}: {msg}", a.status),
348            });
349        }
350        return Err(Error::Http {
351            context: "refreshing the login".into(),
352            status: a.status,
353            message: msg,
354        });
355    }
356    #[derive(serde::Deserialize, Default)]
357    struct Raw {
358        #[serde(default)]
359        token: String,
360    }
361    #[derive(serde::Deserialize)]
362    struct Pair {
363        #[serde(default)]
364        token: Raw,
365        #[serde(default, rename = "refreshToken")]
366        refresh_token: Raw,
367        #[serde(default, rename = "refresh_token")]
368        refresh_alt: Raw,
369    }
370    let pair: Pair = serde_json::from_slice(&a.body)
371        .map_err(|_| Error::other("refreshing the login: response has no token"))?;
372    if pair.token.token.is_empty() {
373        return Err(Error::other("refreshing the login: response has no token"));
374    }
375    let nr = if pair.refresh_token.token.is_empty() {
376        pair.refresh_alt.token
377    } else {
378        pair.refresh_token.token
379    };
380    Ok((pair.token.token, nr))
381}
382
383/// Whether the issuer refused the refresh token itself (expired, revoked, already spent), as
384/// opposed to a malformed request or an outage: 401/403, or 400 mentioning "refresh token".
385fn refresh_refused(status: u16, msg: &str) -> bool {
386    match status {
387        401 | 403 => true,
388        400 => msg.to_lowercase().contains("refresh token"),
389        _ => false,
390    }
391}
392
393/// What a browser login asks for: the sessions service and the account API.
394/// `$CHAINGUARD_SANDBOX_LOGIN_AUDIENCES` (comma-separated) overrides it.
395pub fn default_login_audiences() -> Vec<String> {
396    if let Ok(v) = std::env::var("CHAINGUARD_SANDBOX_LOGIN_AUDIENCES") {
397        let v = v.trim();
398        if !v.is_empty() {
399            return v
400                .split(',')
401                .map(str::trim)
402                .filter(|a| !a.is_empty())
403                .map(String::from)
404                .collect();
405        }
406    }
407    vec![DEFAULT_AUDIENCE.into(), PLATFORM_AUDIENCE.into()]
408}
409
410/// A refresh token's (unverified) expiry and audiences. Chainguard refresh tokens are
411/// base64-encoded JSON.
412fn refresh_claims(rt: &str) -> Option<(SystemTime, Vec<String>)> {
413    let b = base64::engine::general_purpose::STANDARD
414        .decode(rt)
415        .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(rt))
416        .ok()?;
417    let v: serde_json::Value = serde_json::from_slice(&b).ok()?;
418    let exp = v.get("exp")?.as_i64().filter(|e| *e != 0)?;
419    Some((
420        UNIX_EPOCH + Duration::from_secs(exp.max(0) as u64),
421        audiences(v.get("aud")),
422    ))
423}
424
425fn audiences(v: Option<&serde_json::Value>) -> Vec<String> {
426    match v {
427        Some(serde_json::Value::String(s)) => vec![s.clone()],
428        Some(serde_json::Value::Array(a)) => a
429            .iter()
430            .filter_map(|x| x.as_str().map(String::from))
431            .collect(),
432        _ => Vec::new(),
433    }
434}
435
436// ---- the saved login ----------------------------------------------------------------------
437
438/// Releases a [`LoginStore`] lock when dropped.
439pub struct LoginLock(Option<Box<dyn FnOnce() + Send + Sync>>);
440
441impl LoginLock {
442    /// A lock released by calling `unlock`.
443    pub fn new(unlock: impl FnOnce() + Send + Sync + 'static) -> Self {
444        LoginLock(Some(Box::new(unlock)))
445    }
446}
447
448impl Drop for LoginLock {
449    fn drop(&mut self) {
450        if let Some(f) = self.0.take() {
451            f();
452        }
453    }
454}
455
456/// Keeps refresh tokens between runs, per issuer.
457pub trait LoginStore: Send + Sync {
458    /// The saved refresh token, or "" when there is none.
459    fn load(&self, issuer: &str) -> Result<String>;
460    /// Saves a refresh token; "" deletes it.
461    fn save(&self, issuer: &str, refresh_token: &str) -> Result<()>;
462    /// Serializes refresh-and-save across processes (refresh tokens rotate, so two processes
463    /// must not spend the same one).
464    fn lock(&self) -> BoxFuture<'_, Result<LoginLock>>;
465}
466
467/// Stores logins in a JSON file (0600, in a 0700 directory). The Go, Python, TypeScript and Rust
468/// libraries share [`default_login_file`], so one login serves all four.
469#[derive(Debug, Clone, Default)]
470pub struct FileLoginStore {
471    /// Empty means [`default_login_file`].
472    pub path: PathBuf,
473}
474
475/// `<user config dir>/chainguard-sandbox/login.json`: on macOS
476/// `~/Library/Application Support/chainguard-sandbox/login.json`, on Linux `$XDG_CONFIG_HOME` (or
477/// `~/.config`)`/chainguard-sandbox/login.json`, on Windows `%AppData%`. Overridden by
478/// `$CHAINGUARD_SANDBOX_LOGIN_FILE`.
479pub fn default_login_file() -> PathBuf {
480    if let Some(p) = std::env::var_os("CHAINGUARD_SANDBOX_LOGIN_FILE").filter(|p| !p.is_empty()) {
481        return PathBuf::from(p);
482    }
483    user_config_dir()
484        .unwrap_or_else(std::env::temp_dir)
485        .join("chainguard-sandbox")
486        .join("login.json")
487}
488
489/// Go's `os.UserConfigDir`, which the other SDKs reproduce too.
490fn user_config_dir() -> Option<PathBuf> {
491    let nonempty = |k: &str| {
492        std::env::var_os(k)
493            .filter(|v| !v.is_empty())
494            .map(PathBuf::from)
495    };
496    if cfg!(windows) {
497        return nonempty("AppData");
498    }
499    if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
500        return nonempty("HOME").map(|h| h.join("Library/Application Support"));
501    }
502    if let Some(x) = nonempty("XDG_CONFIG_HOME") {
503        return x.is_absolute().then_some(x);
504    }
505    nonempty("HOME").map(|h| h.join(".config"))
506}
507
508#[derive(serde::Serialize, serde::Deserialize)]
509struct LoginFile {
510    #[serde(default)]
511    version: i32,
512    #[serde(default)]
513    logins: BTreeMap<String, SavedLogin>,
514}
515
516#[derive(serde::Serialize, serde::Deserialize)]
517struct SavedLogin {
518    #[serde(default)]
519    refresh_token: String,
520    #[serde(default)]
521    updated: String,
522}
523
524impl FileLoginStore {
525    fn file(&self) -> PathBuf {
526        if self.path.as_os_str().is_empty() {
527            default_login_file()
528        } else {
529            self.path.clone()
530        }
531    }
532
533    fn read(&self) -> Result<LoginFile> {
534        let p = self.file();
535        match std::fs::read(&p) {
536            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(LoginFile {
537                version: 1,
538                logins: BTreeMap::new(),
539            }),
540            Err(e) => Err(Error::io(p.display().to_string(), e)),
541            Ok(b) => serde_json::from_slice(&b)
542                .map_err(|e| Error::other(format!("{}: {e}", p.display()))),
543        }
544    }
545}
546
547impl LoginStore for FileLoginStore {
548    fn load(&self, issuer: &str) -> Result<String> {
549        Ok(self
550            .read()?
551            .logins
552            .get(&norm_issuer(issuer))
553            .map(|l| l.refresh_token.clone())
554            .unwrap_or_default())
555    }
556
557    fn save(&self, issuer: &str, refresh_token: &str) -> Result<()> {
558        // A corrupt file is replaced.
559        let mut lf = self.read().unwrap_or(LoginFile {
560            version: 1,
561            logins: BTreeMap::new(),
562        });
563        lf.version = 1;
564        if refresh_token.is_empty() {
565            lf.logins.remove(&norm_issuer(issuer));
566        } else {
567            let updated = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true);
568            lf.logins.insert(
569                norm_issuer(issuer),
570                SavedLogin {
571                    refresh_token: refresh_token.into(),
572                    updated,
573                },
574            );
575        }
576        let mut b = serde_json::to_vec_pretty(&lf).map_err(|e| Error::other(e.to_string()))?;
577        b.push(b'\n');
578        let p = self.file();
579        let dir = p.parent().unwrap_or(Path::new(".")).to_path_buf();
580        create_private_dir(&dir)?;
581        let tmp = dir.join(format!(".login-{}.json", random_hex(6)));
582        let write = || -> std::io::Result<()> {
583            let mut f = private_file(&tmp)?;
584            f.write_all(&b)?;
585            f.sync_all()?;
586            drop(f);
587            std::fs::rename(&tmp, &p)
588        };
589        let r = write();
590        if r.is_err() {
591            let _ = std::fs::remove_file(&tmp);
592        }
593        r.map_err(|e| Error::io(p.display().to_string(), e))
594    }
595
596    /// Takes `<file>.lock`, created exclusively; a lock older than two minutes is taken to be left
597    /// over from a crashed process. The same scheme as the Go, Python and TypeScript libraries.
598    fn lock(&self) -> BoxFuture<'_, Result<LoginLock>> {
599        Box::pin(async move {
600            let mut p = self.file().into_os_string();
601            p.push(".lock");
602            let p = PathBuf::from(p);
603            if let Some(d) = p.parent() {
604                create_private_dir(d)?;
605            }
606            let deadline = std::time::Instant::now() + Duration::from_secs(150);
607            loop {
608                match private_file(&p) {
609                    Ok(mut f) => {
610                        let _ = writeln!(f, "{}", std::process::id());
611                        let held = p.clone();
612                        return Ok(LoginLock::new(move || {
613                            let _ = std::fs::remove_file(held);
614                        }));
615                    }
616                    Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
617                    Err(e) => return Err(Error::io(p.display().to_string(), e)),
618                }
619                if let Ok(md) = std::fs::metadata(&p)
620                    && md
621                        .modified()
622                        .ok()
623                        .and_then(|m| m.elapsed().ok())
624                        .is_some_and(|age| age > Duration::from_secs(120))
625                {
626                    let _ = std::fs::remove_file(&p);
627                    continue;
628                }
629                if std::time::Instant::now() > deadline {
630                    return Err(Error::other(format!(
631                        "waiting for {}: timed out",
632                        p.display()
633                    )));
634                }
635                tokio::time::sleep(Duration::from_millis(100)).await;
636            }
637        })
638    }
639}
640
641fn create_private_dir(d: &Path) -> Result<()> {
642    let mut b = std::fs::DirBuilder::new();
643    b.recursive(true);
644    #[cfg(unix)]
645    {
646        use std::os::unix::fs::DirBuilderExt;
647        b.mode(0o700);
648    }
649    b.create(d)
650        .map_err(|e| Error::io(d.display().to_string(), e))
651}
652
653/// Creates p exclusively, mode 0600.
654fn private_file(p: &Path) -> std::io::Result<std::fs::File> {
655    let mut o = std::fs::OpenOptions::new();
656    o.write(true).create_new(true);
657    #[cfg(unix)]
658    {
659        use std::os::unix::fs::OpenOptionsExt;
660        o.mode(0o600);
661    }
662    o.open(p)
663}
664
665pub(crate) fn random_hex(n: usize) -> String {
666    let mut b = vec![0u8; n];
667    getrandom::fill(&mut b).expect("the system random number generator failed");
668    b.iter().map(|x| format!("{x:02x}")).collect()
669}
670
671fn norm_issuer(s: &str) -> String {
672    let s = if s.is_empty() { DEFAULT_ISSUER } else { s };
673    s.strip_suffix('/').unwrap_or(s).to_string()
674}
675
676// ---- the token source ---------------------------------------------------------------------
677
678/// A [`TokenSource`] backed by the library's own login: it mints tokens from the saved refresh
679/// token, and when there is none (or it has expired) runs [`browser_login`], unless `no_browser` is
680/// set. Wrap it in [`cached`](super::cached). Concurrent processes share the saved login safely.
681#[derive(Clone, Default)]
682pub struct BrowserLoginToken {
683    pub login: LoginOptions,
684    /// Defaults to [`FileLoginStore`] at [`default_login_file`].
685    pub store: Option<Arc<dyn LoginStore>>,
686    /// The audience of the returned tokens; defaults to [`DEFAULT_AUDIENCE`].
687    pub audience: String,
688    /// Fail with [`Error::LoginRequired`] instead of opening a browser.
689    pub no_browser: bool,
690    /// Bounds a browser login (default 10 minutes).
691    pub login_timeout: Option<Duration>,
692}
693
694impl BrowserLoginToken {
695    fn store(&self) -> Arc<dyn LoginStore> {
696        self.store
697            .clone()
698            .unwrap_or_else(|| Arc::new(FileLoginStore::default()))
699    }
700
701    async fn get(&self) -> Result<String> {
702        let aud = if self.audience.is_empty() {
703            DEFAULT_AUDIENCE.to_string()
704        } else {
705            self.audience.clone()
706        };
707        if let Some(tok) = self.saved_token(&aud).await? {
708            return Ok(tok);
709        }
710        if self.no_browser {
711            return Err(Error::LoginRequired { detail: None });
712        }
713        let mut o = self.login.clone();
714        if o.audience.is_empty() {
715            o.audience = default_login_audiences();
716        }
717        if !o.audience.contains(&aud) {
718            o.audience.push(aud.clone());
719        }
720        // No lock while the person logs in (that can take minutes).
721        let to = self.login_timeout.unwrap_or(Duration::from_secs(600));
722        let res = tokio::time::timeout(to, browser_login(o))
723            .await
724            .map_err(|_| {
725                Error::other(format!(
726                    "workspaces: login: no answer from the browser within {}s",
727                    to.as_secs()
728                ))
729            })??;
730        self.finish_login(res, &aud).await
731    }
732
733    /// Mints a token from the saved login, under the store's lock. `None` when there is no usable
734    /// saved login.
735    async fn saved_token(&self, aud: &str) -> Result<Option<String>> {
736        let st = self.store();
737        let _lock = st.lock().await?;
738        let rt = st.load(&self.login.issuer)?;
739        if rt.is_empty() {
740            return Ok(None);
741        }
742        match refresh_login(&self.login.issuer, &rt, aud).await {
743            Err(Error::LoginExpired { .. }) => {
744                // Forget the login only if it really is unusable: expired, or refused for an
745                // audience it covers. A login made without this audience is still good for its
746                // own audiences, so it's kept.
747                if let Some((exp, auds)) = refresh_claims(&rt)
748                    && SystemTime::now() < exp
749                    && !auds.iter().any(|a| a == aud)
750                {
751                    if self.no_browser {
752                        return Err(Error::LoginRequired {
753                            detail: Some(format!(
754                                "the saved login doesn't cover {aud}; log in again (chainguard-sandbox login) to add it"
755                            )),
756                        });
757                    }
758                    return Ok(None); // a browser login asks for it, then replaces the saved one
759                }
760                st.save(&self.login.issuer, "")?;
761                Ok(None)
762            }
763            Err(e) => Err(e),
764            Ok((tok, nrt)) => {
765                if !nrt.is_empty() && nrt != rt {
766                    st.save(&self.login.issuer, &nrt)
767                        .map_err(|e| Error::other(format!("saving the rotated login: {e}")))?;
768                }
769                Ok(Some(tok))
770            }
771        }
772    }
773
774    /// Saves a fresh login and returns a token for `aud`.
775    async fn finish_login(&self, res: LoginResult, aud: &str) -> Result<String> {
776        let st = self.store();
777        let _lock = st.lock().await?;
778        if !res.refresh_token.is_empty() {
779            st.save(&self.login.issuer, &res.refresh_token)
780                .map_err(|e| Error::other(format!("saving the login: {e}")))?;
781        }
782        if token_has_audience(&res.token, aud) {
783            return Ok(res.token);
784        }
785        if res.refresh_token.is_empty() {
786            return Err(Error::other(format!(
787                "workspaces: login: the token isn't for {aud} and there's no refresh token to mint one"
788            )));
789        }
790        let (tok, nrt) = refresh_login(&self.login.issuer, &res.refresh_token, aud).await?;
791        if !nrt.is_empty() {
792            st.save(&self.login.issuer, &nrt)
793                .map_err(|e| Error::other(format!("saving the rotated login: {e}")))?;
794        }
795        Ok(tok)
796    }
797}
798
799impl TokenSource for BrowserLoginToken {
800    fn token(&self) -> BoxFuture<'_, Result<String>> {
801        Box::pin(self.get())
802    }
803}
804
805/// Forgets the saved login for `issuer` ("" = [`DEFAULT_ISSUER`]). `None` uses the default file.
806pub fn logout(store: Option<&dyn LoginStore>, issuer: &str) -> Result<()> {
807    match store {
808        Some(s) => s.save(issuer, ""),
809        None => FileLoginStore::default().save(issuer, ""),
810    }
811}
812
813/// A token's unverified identity claims (for display).
814#[derive(Debug, Clone, Default)]
815pub struct Claims {
816    pub subject: String,
817    pub issuer: String,
818    pub audience: Vec<String>,
819    pub expiry: Option<SystemTime>,
820}
821
822/// Decodes a JWT's claims without verifying it.
823pub fn token_claims(tok: &str) -> Result<Claims> {
824    let v = jwt_claims_json(tok).ok_or_else(|| Error::other("not a JWT"))?;
825    let s = |k: &str| {
826        v.get(k)
827            .and_then(|x| x.as_str())
828            .unwrap_or_default()
829            .to_string()
830    };
831    let exp = v
832        .get("exp")
833        .and_then(|x| x.as_i64())
834        .map(|e| UNIX_EPOCH + Duration::from_secs(e.max(0) as u64));
835    Ok(Claims {
836        subject: s("sub"),
837        issuer: s("iss"),
838        audience: audiences(v.get("aud")),
839        expiry: exp,
840    })
841}
842
843fn token_has_audience(tok: &str, aud: &str) -> bool {
844    token_claims(tok)
845        .map(|c| c.audience.iter().any(|a| a == aud))
846        .unwrap_or(false)
847}
848
849/// Starts the login callback server alone and returns its callback URL plus a receiver for the
850/// result. For tests that play the browser.
851#[doc(hidden)]
852pub async fn login_callback_server() -> std::io::Result<(
853    String,
854    impl std::future::Future<Output = Result<LoginResult>>,
855    impl Drop,
856)> {
857    let srv = LoginServer::start().await?;
858    let LoginServer {
859        server,
860        callback_url,
861        result,
862        ..
863    } = srv;
864    let fut = async move {
865        result
866            .await
867            .unwrap_or_else(|_| Err(Error::other("stopped")))
868    };
869    Ok((callback_url, fut, server))
870}