Skip to main content

agentmux_srv_core/identity/
oauth_client.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Service-account OAuth 2.0 client for Connectors → Accounts.
5//!
6//! Distinct from the CLI-provider OAuth in `auth_session.rs` (which scrapes a
7//! spawned CLI's stdout): this drives the flow itself — opens the system
8//! browser, runs a transient loopback listener (or polls a device endpoint),
9//! exchanges the code, and stores the resulting tokens in the OS keychain.
10//!
11//! Security posture follows RFC 8252 (OAuth for Native Apps), RFC 7636
12//! (PKCE, S256), RFC 8628 (Device Grant), and RFC 9700 (Security BCP):
13//!   - Authorization Code + PKCE(S256) over a loopback `127.0.0.1:<ephemeral>`
14//!     redirect for code-flow providers (Google, Microsoft).
15//!   - Device Authorization Grant for GitHub (no client secret needed).
16//!   - High-entropy `state` generated and verified on the callback (CSRF).
17//!   - Public clients carry no secret; secret-mandatory providers (Slack) use
18//!     BYO credentials (the user supplies their own client_id/secret).
19//!   - Tokens are stored in the OS keychain (never the DB, never logged).
20//!
21//! **Client status:** the per-provider built-in `client_id`s are not yet
22//! provisioned (`client_id: None` below), so a flow runs with the user's own
23//! client (BYO), which is saved in the keychain after the first successful
24//! connect and reused (`oauth_tokens::SavedClient`, spec D8). With neither,
25//! `start` returns a clear "not configured" error and no flow runs.
26//!
27//! What happens to the tokens afterwards (refresh, revoke, the ID token) is
28//! `oauth_tokens`. docs/specs/SPEC_GOOGLE_CONNECTORS_GMAIL_CALENDAR_DRIVE_2026_10_14.md
29//! G0; the original design is docs/specs/archive/SPEC_TRUST_CENTER_2026_06_15.md §4.2/§12.1.
30
31use std::collections::HashMap;
32use std::sync::{Arc, Mutex, OnceLock};
33use std::time::{Duration, Instant};
34
35use base64::Engine as _;
36use base64::engine::general_purpose::URL_SAFE_NO_PAD;
37use sha2::{Digest, Sha256};
38
39use crate::identity::oauth_tokens::{
40    self, ClientMode, IdTokenClaims, OAuthHttp, SavedClient, TokenBlob, TokenSecrets,
41};
42
43/// How a provider's OAuth flow is driven.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum OAuthFlow {
46    /// Authorization Code + PKCE over a loopback redirect (Google, Microsoft).
47    AuthCodePkce,
48    /// Device Authorization Grant — RFC 8628 (GitHub, headless).
49    Device,
50}
51
52/// Static per-service OAuth configuration. `client_id` is `None` in the
53/// shipped scaffold — supply it (or BYO) to activate the provider.
54#[derive(Debug, Clone)]
55pub struct ServiceOAuthConfig {
56    pub provider: &'static str,
57    pub flow: OAuthFlow,
58    /// Public client id. `None` ⇒ provider not configured (BYO required).
59    pub client_id: Option<&'static str>,
60    pub auth_url: &'static str,
61    pub token_url: &'static str,
62    /// Device authorization endpoint (Device flow only).
63    pub device_url: Option<&'static str>,
64    /// The base scopes every connect asks for. A connect can add more
65    /// (`StartOptions::extra_scopes`).
66    pub scopes: &'static [&'static str],
67    /// True for providers whose token exchange mandates a client_secret
68    /// (Slack). Such providers require BYO credentials on a desktop client.
69    pub requires_secret: bool,
70    /// Extra query parameters on the authorization URL, after the standard
71    /// ones.
72    pub extra_auth_params: &'static [(&'static str, &'static str)],
73    /// RFC 7009 revocation endpoint, called before the account is deleted.
74    pub revoke_url: Option<&'static str>,
75    /// Accepted `iss` values of the ID token. Empty ⇒ the ID token isn't read.
76    pub id_token_issuers: &'static [&'static str],
77}
78
79/// Per-provider catalog. Endpoints + flow choice follow each provider's
80/// native-app guidance (see SPEC §12.1). `client_id` intentionally `None`
81/// until provisioned.
82pub fn config_for(provider: &str) -> Option<ServiceOAuthConfig> {
83    match provider {
84        "google" => Some(ServiceOAuthConfig {
85            provider: "google",
86            flow: OAuthFlow::AuthCodePkce,
87            client_id: Some(GOOGLE_CLIENT_ID),
88            auth_url: "https://accounts.google.com/o/oauth2/v2/auth",
89            token_url: "https://oauth2.googleapis.com/token",
90            device_url: None,
91            scopes: &["openid", "email", "profile"],
92            // Google's token endpoint refuses a Desktop client's code exchange
93            // and refresh without its secret, the built-in client's too (checked
94            // against it: "client_secret is missing"). That secret isn't
95            // confidential (RFC 8252 §8.5), but it stays out of the public repo:
96            // the release build injects it (`builtin_client_secret`).
97            requires_secret: true,
98            // A refresh token is returned only with `access_type=offline`,
99            // and again on a later consent only with `prompt=consent`;
100            // `include_granted_scopes` makes each new token cover every scope
101            // granted so far (incremental authorization). Spec §3.1.
102            extra_auth_params: &[
103                ("access_type", "offline"),
104                ("prompt", "consent"),
105                ("include_granted_scopes", "true"),
106            ],
107            revoke_url: Some("https://oauth2.googleapis.com/revoke"),
108            id_token_issuers: &["https://accounts.google.com", "accounts.google.com"],
109        }),
110        "microsoft" => Some(ServiceOAuthConfig {
111            provider: "microsoft",
112            flow: OAuthFlow::AuthCodePkce,
113            client_id: None, // TODO
114            auth_url: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
115            token_url: "https://login.microsoftonline.com/common/oauth2/v2.0/token",
116            device_url: None,
117            scopes: &["openid", "profile", "email", "offline_access", "User.Read"],
118            requires_secret: false,
119            extra_auth_params: &[],
120            revoke_url: None,
121            // `common` issues per-tenant issuers; not read until Microsoft
122            // gets its own stage.
123            id_token_issuers: &[],
124        }),
125        "github" => Some(ServiceOAuthConfig {
126            provider: "github",
127            flow: OAuthFlow::Device, // no client secret needed
128            client_id: None, // TODO
129            auth_url: "https://github.com/login/oauth/authorize",
130            token_url: "https://github.com/login/oauth/access_token",
131            device_url: Some("https://github.com/login/device/code"),
132            scopes: &["repo", "read:org", "user:email"],
133            requires_secret: false,
134            extra_auth_params: &[],
135            // GitHub revokes only with the client secret (Basic auth), which
136            // a device-flow client doesn't have.
137            revoke_url: None,
138            id_token_issuers: &[],
139        }),
140        "slack" => Some(ServiceOAuthConfig {
141            provider: "slack",
142            flow: OAuthFlow::AuthCodePkce,
143            client_id: None, // BYO only
144            auth_url: "https://slack.com/oauth/v2/authorize",
145            token_url: "https://slack.com/api/oauth.v2.access",
146            device_url: None,
147            scopes: &["users:read"],
148            requires_secret: true,
149            extra_auth_params: &[],
150            revoke_url: None,
151            id_token_issuers: &[],
152        }),
153        _ => None,
154    }
155}
156
157/// The scopes a connect asks for: the provider's base scopes, then `extra`
158/// (a service being turned on), without repeats. Each must be an RFC 6749
159/// §3.3 scope token.
160pub fn requested_scopes(cfg: &ServiceOAuthConfig, extra: &[String]) -> Result<Vec<String>, String> {
161    let mut out: Vec<String> = cfg.scopes.iter().map(|s| s.to_string()).collect();
162    for s in extra {
163        let s = s.trim();
164        let valid = !s.is_empty()
165            && s.len() <= 256
166            && s.bytes().all(|b| b == 0x21 || (0x23..=0x5B).contains(&b) || (0x5D..=0x7E).contains(&b));
167        if !valid {
168            return Err(format!("'{s}' is not a valid OAuth scope"));
169        }
170        if !out.iter().any(|o| o == s) {
171            out.push(s.to_string());
172        }
173    }
174    Ok(out)
175}
176
177/// The authorization URL for a code flow: the standard parameters, PKCE
178/// (S256) and `state`, then the provider's `extra_auth_params`.
179pub fn build_auth_url(
180    cfg: &ServiceOAuthConfig,
181    client_id: &str,
182    redirect_uri: &str,
183    scopes: &[String],
184    state: &str,
185    code_challenge: &str,
186) -> String {
187    let mut url = format!(
188        "{}?response_type=code&client_id={}&redirect_uri={}&scope={}&state={}&code_challenge={}&code_challenge_method=S256",
189        cfg.auth_url,
190        enc(client_id),
191        enc(redirect_uri),
192        enc(&scopes.join(" ")),
193        enc(state),
194        enc(code_challenge),
195    );
196    for (k, v) in cfg.extra_auth_params {
197        url.push_str(&format!("&{}={}", enc(k), enc(v)));
198    }
199    url
200}
201
202/// The page a code flow sends the person to: Google's file picker, or the consent screen
203/// (starting on the account `login_hint` names, when the flow has one).
204fn consent_url(ctx: &FlowCtx, picker: bool, redirect_uri: &str, state: &str, challenge: &str) -> String {
205    if picker {
206        return build_picker_url(&ctx.cfg, &ctx.client.client_id, redirect_uri, state, challenge, account_email(ctx).as_deref());
207    }
208    let mut url = build_auth_url(&ctx.cfg, &ctx.client.client_id, redirect_uri, &ctx.requested, state, challenge);
209    if let Some(hint) = ctx.login_hint.as_deref().filter(|h| !h.is_empty()) {
210        url.push_str(&format!("&login_hint={}", enc(hint)));
211    }
212    url
213}
214
215/// The email of the account a flow is for, when it already has one.
216fn account_email(ctx: &FlowCtx) -> Option<String> {
217    match &ctx.target {
218        FlowTarget::Existing(a) => a.context.get("email").and_then(|v| v.as_str()).map(str::to_string),
219        FlowTarget::New { .. } => None,
220    }
221}
222
223/// The scope Google's desktop picker takes, and the only one it takes: the request
224/// can't be combined with other scopes (spec §3.3).
225pub const PICKER_SCOPE: &str = "https://www.googleapis.com/auth/drive.file";
226
227/// The authorization URL that opens Google's file picker in the browser:
228/// `drive.file` alone, `trigger_onepick` and `prompt=consent`, no refresh
229/// token and no earlier scopes asked for (spec §3.3, Google's "Picker for
230/// desktop and mobile apps").
231pub fn build_picker_url(
232    cfg: &ServiceOAuthConfig,
233    client_id: &str,
234    redirect_uri: &str,
235    state: &str,
236    code_challenge: &str,
237    login_hint: Option<&str>,
238) -> String {
239    let mut url = format!(
240        "{}?response_type=code&client_id={}&redirect_uri={}&scope={}&state={}&code_challenge={}&code_challenge_method=S256&prompt=consent&trigger_onepick=true&allow_multiple=true",
241        cfg.auth_url,
242        enc(client_id),
243        enc(redirect_uri),
244        enc(PICKER_SCOPE),
245        enc(state),
246        enc(code_challenge),
247    );
248    // The account the files are for, so Google offers that one first.
249    if let Some(hint) = login_hint.map(str::trim).filter(|h| !h.is_empty()) {
250        url.push_str(&format!("&login_hint={}", enc(hint)));
251    }
252    url
253}
254
255/// The Google user a picker's token belongs to, from Drive's `about` (answered to `drive.file`).
256/// None when Google doesn't say; the check then can't run.
257async fn picker_user(access_token: &str) -> Option<String> {
258    let reply = http()
259        .get("https://www.googleapis.com/drive/v3/about")
260        .query(&[("fields", "user(emailAddress)")])
261        .bearer_auth(access_token)
262        .send()
263        .await
264        .ok()?;
265    if !reply.status().is_success() {
266        return None;
267    }
268    let body: serde_json::Value = reply.json().await.ok()?;
269    body.pointer("/user/emailAddress")?.as_str().map(str::to_string)
270}
271
272/// A sentence when the picker was used as another Google user than the account's, so the
273/// files are not the account's to read. Nothing when they agree or either is unknown.
274fn picker_user_mismatch(expected: Option<&str>, got: Option<&str>) -> Option<String> {
275    match (expected.map(str::trim).filter(|s| !s.is_empty()), got) {
276        (Some(want), Some(got)) if !want.eq_ignore_ascii_case(got) => Some(format!(
277            "the file picker was used as {got}, but this AgentMux account is {want}: pick again, signed in to Google as {want}"
278        )),
279        _ => None,
280    }
281}
282
283/// The request line of an HTTP request read from `r`: everything up to the first line end,
284/// at most [`MAX_REQUEST_LINE`] bytes. The picker's callback carries every picked file id in
285/// its query, which a single small read can cut off.
286async fn read_request_line<R: tokio::io::AsyncRead + Unpin>(r: &mut R) -> String {
287    use tokio::io::AsyncReadExt;
288    let mut buf: Vec<u8> = Vec::with_capacity(4096);
289    let mut chunk = [0u8; 4096];
290    while buf.len() < MAX_REQUEST_LINE && !buf.contains(&b'\n') {
291        match r.read(&mut chunk).await {
292            Ok(0) | Err(_) => break,
293            Ok(n) => buf.extend_from_slice(&chunk[..n]),
294        }
295    }
296    String::from_utf8_lossy(&buf).into_owned()
297}
298
299/// The longest callback request line read: room for [`MAX_PICKED`] file ids with the code and
300/// the state.
301const MAX_REQUEST_LINE: usize = 32 * 1024;
302
303// ── PKCE + state helpers (RFC 7636 §4, RFC 8252 §8.9) ───────────────────────
304
305/// A PKCE verifier/challenge pair. `challenge = BASE64URL(SHA256(verifier))`.
306pub struct PkcePair {
307    pub verifier: String,
308    pub challenge: String,
309}
310
311/// Generate a PKCE pair. The verifier is 256 bits of CSPRNG entropy (two v4
312/// UUIDs, as `uuid` draws from the OS RNG) base64url-encoded — well within the
313/// 43–128 char range, charset-safe. Challenge uses S256 (never `plain`).
314pub fn pkce_pair() -> PkcePair {
315    let a = uuid::Uuid::new_v4();
316    let b = uuid::Uuid::new_v4();
317    let mut raw = [0u8; 32];
318    raw[..16].copy_from_slice(a.as_bytes());
319    raw[16..].copy_from_slice(b.as_bytes());
320    let verifier = URL_SAFE_NO_PAD.encode(raw);
321
322    let mut hasher = Sha256::new();
323    hasher.update(verifier.as_bytes());
324    let challenge = URL_SAFE_NO_PAD.encode(hasher.finalize());
325
326    PkcePair { verifier, challenge }
327}
328
329/// High-entropy CSRF `state` value. Verified byte-for-byte on the callback.
330pub fn random_state() -> String {
331    uuid::Uuid::new_v4().to_string()
332}
333
334// ── Session manager ─────────────────────────────────────────────────────────
335
336const SESSION_TIMEOUT: Duration = Duration::from_secs(300);
337
338/// Terminal/transient status surfaced to the frontend poll.
339#[derive(Debug, Clone)]
340pub enum OAuthStatus {
341    /// Seeded the instant a session is created, before the spawned task has
342    /// emitted its first real status. Non-terminal so an early poll doesn't
343    /// see a terminal value and abort the flow.
344    Pending,
345    /// Code flow: browser opened to `auth_url`; awaiting the loopback callback.
346    UrlAvailable { auth_url: String },
347    /// Device flow: show `user_code` + `verification_uri`; polling in progress.
348    CodeEmitted { user_code: String, verification_uri: String },
349    /// Done — the account row + keychain token are persisted. `granted_scopes`
350    /// is what the provider granted; `missing_scopes` what was asked for and
351    /// unticked on the consent screen (a partial grant).
352    Success {
353        account_id: String,
354        granted_scopes: Vec<String>,
355        missing_scopes: Vec<String>,
356        email: Option<String>,
357    },
358    Failed { error: String },
359    /// Google's file picker finished: the Drive files the person picked for this
360    /// account's client (spec §3.3). The account's tokens are untouched.
361    Picked { account_id: String, file_ids: Vec<String> },
362    /// A brokered connect for another GitHub user than the account is connected as:
363    /// the flow stopped, and the frontend asks, then starts again with `replace_user`.
364    ConfirmUser { current_login: String, current_id: u64, new_login: String, new_id: u64 },
365}
366
367impl OAuthStatus {
368    pub fn is_terminal(&self) -> bool {
369        matches!(
370            self,
371            OAuthStatus::Success { .. } | OAuthStatus::Failed { .. } | OAuthStatus::ConfirmUser { .. } | OAuthStatus::Picked { .. }
372        )
373    }
374}
375
376struct OAuthSession {
377    status: OAuthStatus,
378    started_at: Instant,
379    /// Set once the flow has what it needs and is about to write the account
380    /// (`begin_commit`). A cancel after that is too late: the account is being
381    /// written, and reporting "cancelled" would be a lie.
382    committing: bool,
383    /// Tells the flow's task to stop (cancel, timeout). Per flow, so one
384    /// flow's cancel never reaches another.
385    stop: tokio::sync::watch::Sender<bool>,
386}
387
388/// The flow task's end of its session's stop signal.
389pub struct StopSignal(tokio::sync::watch::Receiver<bool>);
390
391impl StopSignal {
392    /// Resolves once the session was cancelled or timed out, or was dropped
393    /// from the manager (a flow nobody can poll any more).
394    async fn stopped(&mut self) {
395        let _ = self.0.wait_for(|stop| *stop).await;
396    }
397}
398
399#[derive(Default)]
400pub struct OAuthSessionManager {
401    sessions: Mutex<HashMap<String, OAuthSession>>,
402}
403
404/// How long a session entry is retained before it's pruned. Generous margin
405/// over the 5-min flow timeout so a slow frontend poll still finds its result.
406const SESSION_RETENTION: Duration = Duration::from_secs(900);
407
408impl OAuthSessionManager {
409    fn new_session(&self, status: OAuthStatus) -> (String, StopSignal) {
410        let id = format!("oauth-{}", uuid::Uuid::new_v4());
411        let (stop, rx) = tokio::sync::watch::channel(false);
412        let mut guard = self.sessions.lock().unwrap();
413        // Prune stale entries so the global map can't grow unbounded over the
414        // process lifetime (terminal + timed-out sessions are GC'd here).
415        guard.retain(|_, s| s.started_at.elapsed() < SESSION_RETENTION);
416        guard.insert(id.clone(), OAuthSession { status, started_at: Instant::now(), committing: false, stop });
417        (id, StopSignal(rx))
418    }
419
420    /// Record the flow's progress. A terminal status is final: a flow that
421    /// finishes after its session was cancelled or timed out cannot turn it
422    /// back into `Success`. Returns whether the status was applied.
423    fn set_status(&self, id: &str, status: OAuthStatus) -> bool {
424        let mut guard = self.sessions.lock().unwrap();
425        match guard.get_mut(id) {
426            Some(s) if !s.status.is_terminal() => {
427                s.status = status;
428                true
429            }
430            _ => false,
431        }
432    }
433
434    /// The flow has its callback (or token) and is about to write the account.
435    /// Returns false when the session already ended (cancelled, timed out):
436    /// the flow must write nothing. When true, a later cancel is refused.
437    fn begin_commit(&self, id: &str) -> bool {
438        let mut guard = self.sessions.lock().unwrap();
439        let Some(s) = guard.get_mut(id) else { return false };
440        Self::sweep_timeout(s);
441        if s.status.is_terminal() {
442            return false;
443        }
444        s.committing = true;
445        true
446    }
447
448    fn sweep_timeout(s: &mut OAuthSession) {
449        if !s.status.is_terminal() && !s.committing && s.started_at.elapsed() > SESSION_TIMEOUT {
450            s.status = OAuthStatus::Failed { error: "authorization timed out".into() };
451            let _ = s.stop.send(true);
452        }
453    }
454
455    /// Current status, sweeping the 5-minute timeout to `Failed`.
456    pub fn poll(&self, id: &str) -> Option<OAuthStatus> {
457        let mut guard = self.sessions.lock().unwrap();
458        let s = guard.get_mut(id)?;
459        Self::sweep_timeout(s);
460        Some(s.status.clone())
461    }
462
463    /// Cancel a flow, finally: its status becomes `Failed("cancelled")`, its
464    /// task is told to stop, and nothing it does afterwards changes the status
465    /// or writes an account. Returns true when the session is now cancelled (or
466    /// had already ended), false when it is unknown or already committing
467    /// (too late to cancel).
468    pub fn cancel(&self, id: &str) -> bool {
469        let mut guard = self.sessions.lock().unwrap();
470        let Some(s) = guard.get_mut(id) else { return false };
471        if s.status.is_terminal() {
472            return true;
473        }
474        if s.committing {
475            return false;
476        }
477        s.status = OAuthStatus::Failed { error: "cancelled".into() };
478        let _ = s.stop.send(true);
479        true
480    }
481}
482
483/// Process-global manager. A dedicated singleton (rather than an AppState
484/// field) keeps this scaffold's blast radius small; service-OAuth sessions are
485/// short-lived and window-agnostic.
486pub fn manager() -> &'static OAuthSessionManager {
487    static M: OnceLock<OAuthSessionManager> = OnceLock::new();
488    M.get_or_init(OAuthSessionManager::default)
489}
490
491/// BYO OAuth-app credentials, supplied by the user for secret-mandatory
492/// providers (Slack) or to override the built-in public client.
493#[derive(Clone)]
494pub struct ByoCredentials {
495    pub client_id: String,
496    pub client_secret: Option<String>,
497    /// `Byo`, or `Workspace` for a client created as an organization's
498    /// "Internal" app (D8).
499    pub mode: ClientMode,
500}
501
502/// The client a flow runs with, and where it came from.
503#[derive(Clone)]
504pub struct ResolvedClient {
505    pub client_id: String,
506    pub client_secret: Option<String>,
507    pub mode: ClientMode,
508}
509
510impl std::fmt::Debug for ResolvedClient {
511    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512        f.debug_struct("ResolvedClient")
513            .field("client_id", &self.client_id)
514            .field("client_secret", &self.client_secret.as_ref().map(|_| "<redacted>"))
515            .field("mode", &self.mode)
516            .finish()
517    }
518}
519
520/// AgentMux's own client id for a provider: the shipped one, or (GitHub) the one a
521/// developer's build was given.
522fn builtin_client_id(cfg: &ServiceOAuthConfig) -> Option<String> {
523    cfg.client_id.map(str::to_string).or_else(|| {
524        (cfg.provider == github_connect::PROVIDER).then(github_connect::client_id_override).flatten()
525    })
526}
527
528/// AgentMux's own Google client id, from the `agentmux-connectors` project. Public:
529/// it is in every authorization URL.
530pub const GOOGLE_CLIENT_ID: &str = "1026607634671-pvql7gvgsf1oi5uo0rdvaoqj426ik9jq.apps.googleusercontent.com";
531
532/// The secret of AgentMux's own client for a provider. Google issues one to a Desktop
533/// client and won't exchange a code or refresh without it, but it is kept out of the
534/// public repo: the release build injects it as `AGENTMUX_GOOGLE_CLIENT_SECRET` at compile
535/// time, and the same variable at run time overrides it (a developer's build, a test).
536/// `None` in a build that has neither, which then offers no Google sign-in.
537fn builtin_client_secret(cfg: &ServiceOAuthConfig) -> Option<String> {
538    if cfg.provider != "google" {
539        return None;
540    }
541    pick_secret(std::env::var("AGENTMUX_GOOGLE_CLIENT_SECRET").ok(), option_env!("AGENTMUX_GOOGLE_CLIENT_SECRET"))
542}
543
544/// The run-time value if it has one, else the compile-time one; blanks count as none.
545fn pick_secret(runtime: Option<String>, compiled: Option<&str>) -> Option<String> {
546    let clean = |v: &str| Some(v.trim().to_string()).filter(|v| !v.is_empty());
547    runtime.as_deref().and_then(clean).or_else(|| compiled.and_then(clean))
548}
549
550/// The secret to refresh with when the account's own copy has none: AgentMux's, if the
551/// account was made with AgentMux's own client. A built-in account never stores the
552/// secret, so a rotated one reaches it at the next refresh.
553pub(crate) fn builtin_secret_for(cfg: &ServiceOAuthConfig, client_id: &str) -> Option<String> {
554    (cfg.client_id == Some(client_id)).then(|| builtin_client_secret(cfg)).flatten()
555}
556
557/// Whether the build has a client of its own for the provider, secret included where the
558/// provider demands one.
559pub fn builtin_client_available(cfg: &ServiceOAuthConfig) -> bool {
560    builtin_client_id(cfg).is_some() && (!cfg.requires_secret || builtin_client_secret(cfg).is_some())
561}
562
563/// Resolve the client a flow runs with: credentials passed with the request,
564/// else the user's client saved for this provider, else the built-in one.
565/// Returns an error string when none is available (the "not configured"
566/// gate) or when a secret-mandatory provider is missing its secret.
567pub fn resolve_client(
568    cfg: &ServiceOAuthConfig,
569    byo: Option<&ByoCredentials>,
570    saved: Option<&SavedClient>,
571) -> Result<ResolvedClient, String> {
572    resolve_client_with(cfg, byo, saved, builtin_client_secret(cfg))
573}
574
575/// `resolve_client` with the built-in client's secret given, so a test needn't set the environment.
576fn resolve_client_with(
577    cfg: &ServiceOAuthConfig,
578    byo: Option<&ByoCredentials>,
579    saved: Option<&SavedClient>,
580    builtin_secret: Option<String>,
581) -> Result<ResolvedClient, String> {
582    let client = if let Some(b) = byo {
583        ResolvedClient { client_id: b.client_id.clone(), client_secret: b.client_secret.clone(), mode: b.mode }
584    } else if let Some(s) = saved {
585        ResolvedClient { client_id: s.client_id.clone(), client_secret: s.client_secret.clone(), mode: s.mode }
586    } else if let Some(id) = builtin_client_id(cfg) {
587        ResolvedClient { client_id: id, client_secret: builtin_secret, mode: ClientMode::Builtin }
588    } else {
589        return Err(format!(
590            "{} OAuth is not configured yet — no client id available. \
591             Supply your own OAuth app credentials (BYO) to continue.",
592            cfg.provider
593        ));
594    };
595    if cfg.requires_secret && client.client_secret.is_none() {
596        // The built-in client's secret comes with the build; the user's own brings theirs.
597        return Err(if client.mode == ClientMode::Builtin {
598            format!("{} sign-in isn't available in this build of AgentMux.", cfg.provider)
599        } else {
600            format!(
601                "{} requires a client secret — register your own OAuth app and \
602                 supply its client id + secret (BYO).",
603                cfg.provider
604            )
605        });
606    }
607    Ok(client)
608}
609
610// ── Flow execution ──────────────────────────────────────────────────────────
611
612use crate::backend::storage::store::{IdentityAccount, SecretRef, Store};
613use crate::identity::github_connect;
614use crate::util::open_browser;
615
616pub(crate) fn http() -> &'static reqwest::Client {
617    static C: OnceLock<reqwest::Client> = OnceLock::new();
618    C.get_or_init(|| {
619        crate::http_client::client_with(|b| b.timeout(Duration::from_secs(20)).user_agent("AgentMux"))
620    })
621}
622
623/// What a flow connects: a new account, or an existing one authorized again
624/// — a service turned on (more scopes) or a reconnect — whose keychain entry
625/// is updated in place.
626#[derive(Debug, Clone)]
627pub enum FlowTarget {
628    New { name: String },
629    Existing(IdentityAccount),
630}
631
632/// What `start` needs besides the provider.
633pub struct StartOptions {
634    pub target: FlowTarget,
635    /// Client credentials passed with the request.
636    pub byo: Option<ByoCredentials>,
637    /// The user's client saved for this provider, used when `byo` is `None`.
638    pub saved: Option<SavedClient>,
639    /// Scopes beyond the provider's base ones.
640    pub extra_scopes: Vec<String>,
641    /// Save `byo` for this provider once the flow succeeds.
642    pub save_client: bool,
643    /// Signed in to AgentMux Cloud. GitHub's grant is made through the broker then, and
644    /// by the device flow otherwise (the broker is where the App's secret is).
645    pub cloud_signed_in: bool,
646    /// A brokered connect for another GitHub user than the account's, which the person
647    /// agreed to (spec §6.2).
648    pub replace_user: bool,
649    /// Open the consent page in the system browser (the Accounts panel). An agent's connect
650    /// turns it off and opens the page in a browser pane it drives instead.
651    pub open_system_browser: bool,
652    /// The email Google's account picker starts on (`login_hint`); none for the panel.
653    pub login_hint: Option<String>,
654}
655
656/// Refuse to re-authorize `account` as `provider` unless it is a keychain
657/// OAuth account of that provider.
658pub fn check_reauth_target(account: &IdentityAccount, provider: &str) -> Result<(), String> {
659    if account.provider != provider {
660        return Err(format!("account {} is a {} account, not {provider}", account.id, account.provider));
661    }
662    if account.kind != "oauth" || !matches!(account.secret_ref, SecretRef::Keychain { .. }) {
663        return Err(format!("account {} was not connected with OAuth here; connect it again instead", account.id));
664    }
665    Ok(())
666}
667
668/// The account's non-secret context after a successful flow: what was there
669/// before, plus the granted scopes, the client it was made with (D8), and
670/// the email and user id from the ID token.
671pub fn oauth_context(
672    existing: Option<&serde_json::Value>,
673    granted: &[String],
674    claims: Option<&IdTokenClaims>,
675    client: &ResolvedClient,
676) -> serde_json::Value {
677    let mut ctx = existing.filter(|c| c.is_object()).cloned().unwrap_or_else(|| serde_json::json!({}));
678    ctx["oauth"] = serde_json::json!(true);
679    ctx["granted_scopes"] = serde_json::json!(granted);
680    ctx["oauth_client"] = serde_json::json!({ "mode": client.mode.as_str(), "client_id": client.client_id });
681    if let Some(c) = claims {
682        if let Some(email) = &c.email {
683            ctx["email"] = serde_json::json!(email);
684            ctx["email_verified"] = serde_json::json!(c.email_verified);
685        }
686        if let Some(sub) = &c.subject {
687            ctx["subject"] = serde_json::json!(sub);
688        }
689    }
690    ctx
691}
692
693/// A reconnect must sign in as the same user the account already is:
694/// otherwise one account would silently become another's.
695fn check_same_user(existing: &serde_json::Value, claims: Option<&IdTokenClaims>) -> Result<(), String> {
696    let Some(c) = claims else { return Ok(()) };
697    let had = |k: &str| existing.get(k).and_then(|v| v.as_str()).filter(|s| !s.is_empty());
698    if let (Some(old), Some(new)) = (had("subject"), c.subject.as_deref()) {
699        if old != new {
700            let who = c.email.as_deref().unwrap_or("another user");
701            let was = had("email").unwrap_or("another user");
702            return Err(format!(
703                "you signed in as {who}, but this account is {was}. Sign in as {was}, or connect {who} as a new account."
704            ));
705        }
706        return Ok(());
707    }
708    if let (Some(old), Some(new)) = (had("email"), c.email.as_deref()) {
709        if !old.eq_ignore_ascii_case(new) {
710            return Err(format!(
711                "you signed in as {new}, but this account is {old}. Sign in as {old}, or connect {new} as a new account."
712            ));
713        }
714    }
715    Ok(())
716}
717
718/// Everything the flow's last step needs.
719struct FlowCtx {
720    cfg: ServiceOAuthConfig,
721    client: ResolvedClient,
722    target: FlowTarget,
723    requested: Vec<String>,
724    save_client: bool,
725    mstore: Arc<Store>,
726    identity_store: Arc<Store>,
727    open_system_browser: bool,
728    login_hint: Option<String>,
729}
730
731/// The last step of a flow: read the token response (granted scopes, the ID
732/// token), write the tokens to the keychain and the account row, and answer
733/// the frontend's poll. A new account's keychain entry is removed again if its
734/// row can't be written.
735async fn finish<S: TokenSecrets>(ctx: &FlowCtx, secrets: &S, json: &serde_json::Value) -> Result<OAuthStatus, String> {
736    let now = chrono::Utc::now().timestamp();
737    let granted = oauth_tokens::granted_scopes(json, &ctx.requested);
738    let missing = oauth_tokens::missing_scopes(&ctx.requested, &granted);
739    let claims = match (ctx.cfg.id_token_issuers.is_empty(), json.get("id_token").and_then(|v| v.as_str())) {
740        (false, Some(id_token)) => Some(
741            oauth_tokens::id_token_claims(id_token, ctx.cfg.id_token_issuers, &ctx.client.client_id, now)
742                .map_err(|e| format!("sign-in rejected: {e}"))?,
743        ),
744        _ => None,
745    };
746
747    let (account_id, existing) = match &ctx.target {
748        FlowTarget::New { .. } => (uuid::Uuid::new_v4().to_string(), None),
749        FlowTarget::Existing(acct) => {
750            check_same_user(&acct.context, claims.as_ref())?;
751            (acct.id.clone(), Some(acct))
752        }
753    };
754    // A reconnect that gets no new refresh token keeps the one it had.
755    let previous = match existing {
756        Some(acct) => secrets.get(&acct.id).await.ok().flatten().and_then(|raw| TokenBlob::parse(&raw)),
757        None => None,
758    };
759    let blob = TokenBlob::from_token_response(
760        json,
761        now,
762        previous.as_ref().and_then(|b| b.refresh_token.as_deref()),
763        // AgentMux's own secret is read from the build at each refresh, never kept in the blob.
764        ctx.client.client_secret.as_deref().filter(|_| ctx.client.mode != ClientMode::Builtin),
765    )?;
766    secrets.put(&account_id, &blob.to_json()).await?;
767
768    let mut context = oauth_context(existing.map(|a| &a.context), &granted, claims.as_ref(), &ctx.client);
769    // GitHub: who is connected, and whether the broker refreshes it.
770    let github = ctx.cfg.provider == github_connect::PROVIDER;
771    if github {
772        github_connect::stamp_context(&mut context, json);
773    }
774    let label = if github { github_connect::display_name_for(json) } else { None };
775    let email = claims.as_ref().and_then(|c| c.email.clone());
776    let now_ms = chrono::Utc::now().timestamp_millis();
777    let account = match &ctx.target {
778        FlowTarget::New { name } => IdentityAccount {
779            id: account_id.clone(),
780            name: if name.trim().is_empty() { ctx.cfg.provider.to_string() } else { name.clone() },
781            provider: ctx.cfg.provider.to_string(),
782            kind: "oauth".to_string(),
783            display_name: label.clone().or_else(|| email.clone()).unwrap_or_default(),
784            secret_ref: SecretRef::Keychain {
785                service: crate::identity::secret_store::SERVICE.to_string(),
786                account: crate::identity::secret_store::account_key(&account_id),
787            },
788            context,
789            status: "valid".to_string(),
790            created_at: now_ms,
791            updated_at: now_ms,
792        },
793        FlowTarget::Existing(acct) => IdentityAccount {
794            // A GitHub grant that couldn't say who it is doesn't keep the previous user's name.
795            display_name: label.clone().or_else(|| email.clone()).unwrap_or_else(|| if github { String::new() } else { acct.display_name.clone() }),
796            context,
797            status: "valid".to_string(),
798            updated_at: now_ms,
799            ..acct.clone()
800        },
801    };
802    if let Err(e) = ctx.mstore.identity_upsert_with_mirror(&ctx.identity_store, &account) {
803        if existing.is_none() {
804            let id = account_id.clone();
805            let _ = tokio::task::spawn_blocking(move || crate::identity::secret_store::delete(&id)).await;
806        }
807        return Err(format!("persist failed: {e}"));
808    }
809    // Windows show the account at once, whoever started the connect (the panel, an agent).
810    crate::identity::accounts_changed::announce();
811    Ok(OAuthStatus::Success { account_id, granted_scopes: granted, missing_scopes: missing, email })
812}
813
814/// [`finish`] against the keychain, then save a BYO client passed with the
815/// request (D8) so the next connect doesn't ask for it again. Saving is
816/// best-effort: the account is already connected.
817async fn complete(ctx: &FlowCtx, json: &serde_json::Value) -> OAuthStatus {
818    // A GitHub grant the device flow made says nothing of who it is: ask GitHub, so the
819    // account reads "@login". Best effort: the grant works without it.
820    let mut named;
821    let mut json = json;
822    if ctx.cfg.provider == github_connect::PROVIDER && github_connect::identity_in(json).is_none() {
823        if let Some(token) = json.get("access_token").and_then(|v| v.as_str()) {
824            match github_connect::user_of_token(token).await {
825                Ok((id, login)) => {
826                    named = json.clone();
827                    named["github_user_id"] = serde_json::json!(id);
828                    named["login"] = serde_json::json!(login);
829                    json = &named;
830                }
831                Err(e) => tracing::warn!(target: "identity", error = %e, "identity.github: couldn't tell who the new grant is"),
832            }
833        }
834    }
835    let status = match finish(ctx, &oauth_tokens::KeychainSecrets, json).await {
836        Ok(s) => s,
837        Err(error) => return OAuthStatus::Failed { error },
838    };
839    // A completed sign-in proves the account works, so its agents stop being
840    // signed out (#2237).
841    if let OAuthStatus::Success { account_id, .. } = &status {
842        crate::identity::sign_in_hook::after_sign_in(account_id);
843    }
844    if ctx.save_client && ctx.client.mode != ClientMode::Builtin {
845        let provider = ctx.cfg.provider;
846        let saved = SavedClient {
847            client_id: ctx.client.client_id.clone(),
848            client_secret: ctx.client.client_secret.clone(),
849            mode: ctx.client.mode,
850        };
851        let res = tokio::task::spawn_blocking(move || oauth_tokens::save_client(provider, &saved)).await;
852        if let Err(e) = res.map_err(|e| e.to_string()).and_then(|r| r) {
853            tracing::warn!(target: "identity", provider = %provider, error = %e, "identity.oauth: saving the OAuth client failed");
854        }
855    }
856    status
857}
858
859/// URL-encode a query component (RFC 3986 unreserved kept).
860fn enc(s: &str) -> String {
861    let mut out = String::with_capacity(s.len());
862    for b in s.bytes() {
863        match b {
864            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
865            _ => out.push_str(&format!("%{b:02X}")),
866        }
867    }
868    out
869}
870
871/// Start an OAuth flow. Resolves config + client (gating on "not configured"),
872/// creates a session, and spawns the background task that drives it. Returns
873/// `(session_id, initial_status)`. The frontend then polls `manager().poll`.
874pub fn start(
875    provider: &str,
876    opts: StartOptions,
877    mstore: Arc<Store>,
878    identity_store: Arc<Store>,
879) -> Result<(String, OAuthStatus), String> {
880    let cfg = config_for(provider).ok_or_else(|| format!("unknown OAuth provider: {provider}"))?;
881    if let FlowTarget::Existing(acct) = &opts.target {
882        check_reauth_target(acct, provider)?;
883    }
884    let client = resolve_client(&cfg, opts.byo.as_ref(), opts.saved.as_ref())?;
885    let requested = requested_scopes(&cfg, &opts.extra_scopes)?;
886    let ctx = FlowCtx {
887        cfg,
888        client,
889        target: opts.target,
890        requested,
891        save_client: opts.save_client && opts.byo.is_some(),
892        mstore,
893        identity_store,
894        open_system_browser: opts.open_system_browser,
895        login_hint: opts.login_hint,
896    };
897    if needs_cloud_sign_in(ctx.cfg.provider, opts.cloud_signed_in, &ctx.client) {
898        return Err(NEEDS_CLOUD_SIGN_IN.to_string());
899    }
900    if let Some(why) = scope_not_offered(ctx.cfg.provider, &ctx.requested, &ctx.client, &ctx.target) {
901        return Err(why);
902    }
903    let brokered = runs_through_broker(ctx.cfg.provider, opts.cloud_signed_in, &ctx.client);
904    match ctx.cfg.flow {
905        OAuthFlow::AuthCodePkce => start_code_flow(ctx, None, false),
906        OAuthFlow::Device if brokered => start_code_flow(ctx, Some(BrokerLeg { replace: opts.replace_user }), false),
907        OAuthFlow::Device => start_device_flow(ctx),
908    }
909}
910
911/// Open Google's file picker for `account` in the system browser, with the client the
912/// account was made with (a picked file is the client's to read, so no other client
913/// will do). The result is [`OAuthStatus::Picked`]; the account's tokens are not
914/// changed. Needs Drive turned on for the account (`drive.file` granted).
915pub fn start_picker(
916    account: IdentityAccount,
917    client: ResolvedClient,
918    mstore: Arc<Store>,
919    identity_store: Arc<Store>,
920) -> Result<(String, OAuthStatus), String> {
921    check_reauth_target(&account, "google")?;
922    let granted = account.context.get("granted_scopes").and_then(|v| v.as_array());
923    if !granted.is_some_and(|g| g.iter().any(|s| s.as_str() == Some(PICKER_SCOPE))) {
924        return Err("turn Drive on for this account first: it hasn't granted the Drive permission".to_string());
925    }
926    let cfg = config_for("google").ok_or("unknown OAuth provider: google")?;
927    let ctx = FlowCtx {
928        cfg,
929        client,
930        target: FlowTarget::Existing(account),
931        requested: vec![PICKER_SCOPE.to_string()],
932        save_client: false,
933        mstore,
934        identity_store,
935        open_system_browser: true,
936        login_hint: None,
937    };
938    start_code_flow(ctx, None, true)
939}
940
941/// The client `account` was made with, secret included (its token blob keeps a copy, D8):
942/// the picker has to run as that client.
943pub async fn picker_client<S: TokenSecrets>(secrets: &S, account: &IdentityAccount) -> Result<ResolvedClient, String> {
944    let (mode, client_id) = oauth_tokens::account_client(account)
945        .ok_or("this account doesn't record which OAuth client it was made with: connect it again first")?;
946    let mut client_secret = secrets.get(&account.id).await?.and_then(|raw| TokenBlob::parse(&raw)).and_then(|b| b.client_secret.clone());
947    if client_secret.is_none() && mode == ClientMode::Builtin {
948        client_secret = config_for(&account.provider).and_then(|cfg| builtin_secret_for(&cfg, &client_id));
949    }
950    Ok(ResolvedClient { client_id, client_secret, mode })
951}
952
953/// What a GitHub connect answers when the person isn't signed in to AgentMux Cloud: a code the UI
954/// turns into "Sign in to AgentMux Cloud to connect GitHub" and a sign-in button, never a bare error
955/// (`frontend/app/view/accounts/github-cloud-gate.ts` has the same string). GitHub through AgentMux's
956/// own App is a Cloud feature (the Connect with GitHub design).
957pub const NEEDS_CLOUD_SIGN_IN: &str = "needs-cloud-sign-in";
958
959/// Whether a GitHub connect with AgentMux's own App has to stop because the person isn't signed
960/// in to AgentMux Cloud. A client the person brought is their own App and costs us nothing.
961fn needs_cloud_sign_in(provider: &str, cloud_signed_in: bool, client: &ResolvedClient) -> bool {
962    provider == github_connect::PROVIDER && !cloud_signed_in && client.mode == ClientMode::Builtin
963}
964
965/// Why `requested` can't be asked on `client`, if it can't: AgentMux's own Google client asks only for the
966/// services Google has approved for it in this build (`google_offered`). A client the person brought is
967/// reviewed against their own project, so it is not limited. A Reconnect asks again for the scopes the account
968/// already holds; that keeps a service on, it does not turn one on, so those are not checked.
969fn scope_not_offered(provider: &str, requested: &[String], client: &ResolvedClient, target: &FlowTarget) -> Option<String> {
970    if provider != "google" || client.mode != ClientMode::Builtin {
971        return None;
972    }
973    let held: Vec<&str> = match target {
974        FlowTarget::Existing(acct) => acct
975            .context
976            .get("granted_scopes")
977            .and_then(serde_json::Value::as_array)
978            .map(|a| a.iter().filter_map(serde_json::Value::as_str).collect())
979            .unwrap_or_default(),
980        FlowTarget::New { .. } => Vec::new(),
981    };
982    let new: Vec<String> = requested.iter().filter(|s| !held.contains(&s.as_str())).cloned().collect();
983    super::google_offered::first_not_offered(&new, &super::google_offered::offered())
984}
985
986/// Whether a GitHub connect goes through AgentMux Cloud's broker: the person is signed in to
987/// AgentMux Cloud, and the flow runs with AgentMux's own App. The broker exchanges the code with
988/// that App's secret, so a client the person brought or saved (their own app) can't be used with
989/// it: that connect stays a device flow with their app.
990fn runs_through_broker(provider: &str, cloud_signed_in: bool, client: &ResolvedClient) -> bool {
991    provider == github_connect::PROVIDER && cloud_signed_in && client.mode == ClientMode::Builtin
992}
993
994/// A code flow whose exchange goes through the broker instead of the provider's token
995/// endpoint.
996struct BrokerLeg {
997    replace: bool,
998}
999
1000/// The broker's leg of a connect: the code and its PKCE verifier become the person's
1001/// grant, or the question of whether another GitHub user may replace the account's.
1002async fn broker_exchange(ctx: &FlowCtx, code: &str, verifier: &str, redirect_uri: &str, replace: bool) -> OAuthStatus {
1003    use crate::muxbus::github_broker;
1004    let who = match github_broker::caller(&ctx.mstore).await {
1005        Ok(who) => who,
1006        // A sign-in that lapsed since the connect began is the same question as none. The other
1007        // reasons ("not running yet", "the key can't be read") are not fixed by signing in.
1008        Err(e) if e.needs_sign_in() => return OAuthStatus::Failed { error: NEEDS_CLOUD_SIGN_IN.to_string() },
1009        Err(e) => return OAuthStatus::Failed { error: e.to_string() },
1010    };
1011    settle_grant(ctx, github_broker::exchange_code(http(), &who, code, verifier, redirect_uri, replace).await).await
1012}
1013
1014/// What a code exchange's answer means for the flow: the person's grant becomes the account, or
1015/// another GitHub user than the account's is the question of whether they may replace it.
1016async fn settle_grant(
1017    ctx: &FlowCtx,
1018    answer: Result<crate::muxbus::github_broker::TokenGrant, crate::muxbus::github_broker::BrokerError>,
1019) -> OAuthStatus {
1020    use crate::muxbus::github_broker::BrokerError;
1021    match answer {
1022        Ok(grant) => complete(ctx, &github_connect::grant_json(&grant, chrono::Utc::now().timestamp_millis())).await,
1023        Err(BrokerError::UserMismatch { current, new }) => OAuthStatus::ConfirmUser {
1024            current_login: current.login,
1025            current_id: current.github_user_id,
1026            new_login: new.login,
1027            new_id: new.github_user_id,
1028        },
1029        Err(e) => OAuthStatus::Failed { error: e.to_string() },
1030    }
1031}
1032
1033/// Whether this connect is a first one that can be done in one browser trip (spec §4.4): the broker has no
1034/// installation linked to the account yet, so GitHub's install page, which authorizes the person as it
1035/// installs, replaces the authorize page. A broker that can't be asked leaves the connect as it was.
1036async fn first_connect_in_one_trip(ctx: &FlowCtx) -> bool {
1037    use crate::muxbus::github_broker;
1038    let Ok(who) = github_broker::caller(&ctx.mstore).await else { return false };
1039    matches!(github_broker::installations(http(), &who).await, Ok(links) if links.is_empty())
1040}
1041
1042/// How an install trip ended.
1043enum TripEnd {
1044    /// Nothing was started, so the usual authorize-page flow goes on.
1045    NotATrip,
1046    /// The person cancelled; nothing was written.
1047    Cancelled,
1048    Ended(OAuthStatus),
1049}
1050
1051/// A first GitHub connect through the broker is one trip to GitHub's install page, not two. Whether this
1052/// was one, and so the whole flow: `false` leaves the usual authorize-page flow to go on.
1053async fn run_first_connect_trip(ctx: &FlowCtx, sid: &str, stop: &mut StopSignal, broker: Option<&BrokerLeg>) -> bool {
1054    if !broker.is_some_and(|leg| !leg.replace) || !first_connect_in_one_trip(ctx).await {
1055        return false;
1056    }
1057    match install_trip(ctx, sid, stop).await {
1058        TripEnd::NotATrip => false,
1059        TripEnd::Cancelled => true,
1060        TripEnd::Ended(status) => {
1061            manager().set_status(sid, status);
1062            true
1063        }
1064    }
1065}
1066
1067/// The one-trip first connect: the install page opens instead of the authorize page, GitHub's callback
1068/// lands on the cloud relay (which the broker's `state` ties to this account), and the code that comes
1069/// back is the person's grant. The installation GitHub reports is then linked. Whatever goes wrong before
1070/// the browser opens (the broker or the relay can't be reached, or isn't set up for a trip) is no trip:
1071/// the usual flow goes on, as it did before.
1072async fn install_trip(ctx: &FlowCtx, sid: &str, stop: &mut StopSignal) -> TripEnd {
1073    use crate::identity::github_trip::{self, Polled};
1074    use crate::muxbus::github_broker;
1075    let fail = |error: String| TripEnd::Ended(OAuthStatus::Failed { error });
1076    let Ok(who) = github_broker::caller(&ctx.mstore).await else { return TripEnd::NotATrip };
1077    let issued = match github_broker::installation_state(http(), &who).await {
1078        // The broker says when it is set up for a trip (GitHub's callback goes to the relay): until then it
1079        // would be a page that never answers.
1080        Ok(issued) if issued.one_trip && super::github_installs::is_install_page(&issued.install_url) => issued,
1081        _ => return TripEnd::NotATrip,
1082    };
1083    let relay_base = crate::muxbus::relay::rest_base_url().trim_end_matches('/').to_string();
1084    let key = github_trip::relay_key(&issued.state);
1085    if let Err(e) = github_trip::register(http(), &relay_base, &key).await {
1086        tracing::warn!(target: "identity", error = %e, "identity.github: no one-trip connect, using the authorize page");
1087        return TripEnd::NotATrip;
1088    }
1089    manager().set_status(sid, OAuthStatus::UrlAvailable { auth_url: issued.install_url.clone() });
1090    if ctx.open_system_browser {
1091        open_browser(&issued.install_url);
1092    }
1093    let (code, installation_id) = loop {
1094        tokio::select! {
1095            _ = stop.stopped() => return TripEnd::Cancelled,
1096            _ = tokio::time::sleep(Duration::from_secs(1)) => {}
1097        }
1098        match github_trip::poll_once(http(), &relay_base, &key).await {
1099            Polled::Pending => {}
1100            Polled::Ready { code, installation_id, .. } => break (code, installation_id),
1101            Polled::Failed(why) => return fail(callback_error_message(ctx.cfg.provider, &why)),
1102            Polled::Gone => return fail("this connection attempt expired or was completed elsewhere: connect again".to_string()),
1103        }
1104    };
1105    // From here the flow writes the account: a cancel that already happened wins.
1106    if !manager().begin_commit(sid) {
1107        return TripEnd::Cancelled;
1108    }
1109    let redirect_uri = github_trip::callback_uri(&relay_base);
1110    let grant = github_broker::exchange_trip_code(http(), &who, &code, &issued.state, &redirect_uri, false).await;
1111    let token = grant.as_ref().ok().map(|g| g.access_token.clone());
1112    let status = settle_grant(ctx, grant).await;
1113    if let (OAuthStatus::Success { .. }, Some(token)) = (&status, token) {
1114        // Best effort: the connect worked, and Settings → Accounts links it later (Check for installations).
1115        if let Err(e) = github_broker::link_installation(http(), &who, installation_id, &issued.state, &token).await {
1116            tracing::warn!(target: "identity", error = %e, installation_id, "identity.github: the one-trip connect's installation wasn't linked");
1117        }
1118    }
1119    TripEnd::Ended(status)
1120}
1121
1122fn start_code_flow(ctx: FlowCtx, broker: Option<BrokerLeg>, picker: bool) -> Result<(String, OAuthStatus), String> {
1123    use tokio::io::AsyncWriteExt;
1124    use tokio::net::TcpListener;
1125
1126    let pkce = pkce_pair();
1127    let state = random_state();
1128
1129    let (session_id, mut stop) = manager().new_session(OAuthStatus::Pending);
1130    let sid = session_id.clone();
1131
1132    tokio::spawn(async move {
1133        if run_first_connect_trip(&ctx, &sid, &mut stop, broker.as_ref()).await { return; }
1134        // Transient loopback listener on an OS-assigned ephemeral port. Use the
1135        // 127.0.0.1 literal (not "localhost") per RFC 8252 §7.3.
1136        let listener = match TcpListener::bind("127.0.0.1:0").await {
1137            Ok(l) => l,
1138            Err(e) => {
1139                manager().set_status(&sid, OAuthStatus::Failed { error: format!("bind failed: {e}") });
1140                return;
1141            }
1142        };
1143        let port = listener.local_addr().map(|a| a.port()).unwrap_or(0);
1144        let redirect_uri = format!("http://127.0.0.1:{port}/callback");
1145
1146        let auth_url = consent_url(&ctx, picker, &redirect_uri, &state, &pkce.challenge);
1147        manager().set_status(&sid, OAuthStatus::UrlAvailable { auth_url: auth_url.clone() });
1148        if ctx.open_system_browser { open_browser(&auth_url); }
1149
1150        // Await the single inbound callback (the session timeout sweep bounds
1151        // total wait; this accept has its own guard too).
1152        // A cancel (or the timeout sweep) ends the wait and drops the listener.
1153        let accept = tokio::select! {
1154            _ = stop.stopped() => return,
1155            accept = tokio::time::timeout(SESSION_TIMEOUT, listener.accept()) => accept,
1156        };
1157        let mut stream = match accept {
1158            Ok(Ok((s, _))) => s,
1159            _ => {
1160                manager().set_status(&sid, OAuthStatus::Failed { error: "no callback received".into() });
1161                return;
1162            }
1163        };
1164        let req = read_request_line(&mut stream).await;
1165        let callback = parse_callback(&req);
1166        let _ = stream
1167            .write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<html><body>You can close this tab and return to AgentMux.</body></html>")
1168            .await;
1169
1170        // CSRF: reject a callback whose state doesn't match (RFC 8252 §8.9).
1171        if callback.state.as_deref() != Some(state.as_str()) {
1172            manager().set_status(&sid, OAuthStatus::Failed { error: "state mismatch — possible CSRF, aborted".into() });
1173            return;
1174        }
1175        if let Some(code) = callback.error.as_deref() {
1176            manager().set_status(&sid, OAuthStatus::Failed { error: callback_error_message(ctx.cfg.provider, code) });
1177            return;
1178        }
1179        // The picker's answer is the files. A code that comes with them is exchanged only so
1180        // Google finishes the grant; its tokens are dropped (the account keeps its own).
1181        if picker {
1182            let file_ids = picked_ids(callback.picked_file_ids.as_deref());
1183            if let Some(code) = callback.code.clone() {
1184                let mut params = vec![
1185                    ("grant_type", "authorization_code".to_string()),
1186                    ("client_id", ctx.client.client_id.clone()),
1187                    ("code", code),
1188                    ("redirect_uri", redirect_uri.clone()),
1189                    ("code_verifier", pkce.verifier.clone()),
1190                ];
1191                if let Some(secret) = ctx.client.client_secret.as_ref() {
1192                    params.push(("client_secret", secret.clone()));
1193                }
1194                match exchange(ctx.cfg.token_url, &params).await {
1195                    Ok(tokens) => {
1196                        let user = match tokens.get("access_token").and_then(|v| v.as_str()) {
1197                            Some(t) => picker_user(t).await,
1198                            None => None,
1199                        };
1200                        if let Some(error) = picker_user_mismatch(account_email(&ctx).as_deref(), user.as_deref()) {
1201                            manager().set_status(&sid, OAuthStatus::Failed { error });
1202                            return;
1203                        }
1204                    }
1205                    Err(e) => {
1206                        tracing::warn!(target: "identity", error = %e, "identity.oauth: the picker's code wasn't exchanged; the picked files may still be usable");
1207                    }
1208                }
1209            }
1210            let account_id = match &ctx.target {
1211                FlowTarget::Existing(a) => a.id.clone(),
1212                FlowTarget::New { .. } => String::new(),
1213            };
1214            manager().set_status(&sid, OAuthStatus::Picked { account_id, file_ids });
1215            return;
1216        }
1217        let code = match callback.code {
1218            Some(c) => c,
1219            None => {
1220                manager().set_status(&sid, OAuthStatus::Failed { error: "no authorization code in callback".into() });
1221                return;
1222            }
1223        };
1224
1225        // From here the flow writes the account: a cancel that already
1226        // happened wins and nothing is written; a later one is refused.
1227        if !manager().begin_commit(&sid) {
1228            return;
1229        }
1230        // Through the broker, which holds the App's client secret.
1231        if let Some(leg) = broker {
1232            let status = broker_exchange(&ctx, &code, &pkce.verifier, &redirect_uri, leg.replace).await;
1233            manager().set_status(&sid, status);
1234            return;
1235        }
1236        // Exchange the code (+ PKCE verifier) for tokens.
1237        let mut params = vec![
1238            ("grant_type", "authorization_code".to_string()),
1239            ("client_id", ctx.client.client_id.clone()),
1240            ("code", code),
1241            ("redirect_uri", redirect_uri),
1242            ("code_verifier", pkce.verifier.clone()),
1243        ];
1244        if let Some(secret) = ctx.client.client_secret.as_ref() {
1245            params.push(("client_secret", secret.clone()));
1246        }
1247        let status = match exchange(ctx.cfg.token_url, &params).await {
1248            Ok(json) => complete(&ctx, &json).await,
1249            Err(error) => OAuthStatus::Failed { error },
1250        };
1251        manager().set_status(&sid, status);
1252    });
1253
1254    Ok((session_id, OAuthStatus::UrlAvailable { auth_url: String::new() }))
1255}
1256
1257fn start_device_flow(ctx: FlowCtx) -> Result<(String, OAuthStatus), String> {
1258    let device_url = ctx.cfg.device_url.ok_or("provider has no device endpoint")?.to_string();
1259    let scopes = ctx.requested.join(" ");
1260    let (session_id, mut stop) = manager().new_session(OAuthStatus::Pending);
1261    let sid = session_id.clone();
1262    let client_id = ctx.client.client_id.clone();
1263
1264    tokio::spawn(async move {
1265        // 1. Device authorization request.
1266        let params = [("client_id", client_id.clone()), ("scope", scopes)];
1267        let resp = match http().post(&device_url).header("Accept", "application/json").form(&params).send().await {
1268            Ok(r) => r,
1269            Err(e) => {
1270                manager().set_status(&sid, OAuthStatus::Failed { error: format!("device request failed: {e}") });
1271                return;
1272            }
1273        };
1274        let json: serde_json::Value = resp.json().await.unwrap_or_else(|_| serde_json::json!({}));
1275        let device_code = json.get("device_code").and_then(|v| v.as_str()).unwrap_or("").to_string();
1276        let user_code = json.get("user_code").and_then(|v| v.as_str()).unwrap_or("").to_string();
1277        let verification_uri = json
1278            .get("verification_uri")
1279            .and_then(|v| v.as_str())
1280            .unwrap_or("https://github.com/login/device")
1281            .to_string();
1282        let mut interval = json.get("interval").and_then(|v| v.as_u64()).unwrap_or(5);
1283        if device_code.is_empty() {
1284            manager().set_status(&sid, OAuthStatus::Failed { error: "no device_code in response".into() });
1285            return;
1286        }
1287        manager().set_status(&sid, OAuthStatus::CodeEmitted { user_code, verification_uri });
1288
1289        // 2. Poll the token endpoint (RFC 8628 §3.4–3.5).
1290        loop {
1291            // A cancel (or the timeout sweep) ends the wait at once.
1292            tokio::select! {
1293                _ = stop.stopped() => return,
1294                _ = tokio::time::sleep(Duration::from_secs(interval)) => {}
1295            }
1296            // Stop if the session was cancelled / timed out by the manager.
1297            match manager().poll(&sid) {
1298                Some(s) if s.is_terminal() => return,
1299                None => return,
1300                _ => {}
1301            }
1302            let p = [
1303                ("client_id", client_id.clone()),
1304                ("device_code", device_code.clone()),
1305                ("grant_type", "urn:ietf:params:oauth:grant-type:device_code".to_string()),
1306            ];
1307            let r = match http().post(ctx.cfg.token_url).header("Accept", "application/json").form(&p).send().await {
1308                Ok(r) => r,
1309                Err(e) => {
1310                    manager().set_status(&sid, OAuthStatus::Failed { error: format!("poll failed: {e}") });
1311                    return;
1312                }
1313            };
1314            let j: serde_json::Value = r.json().await.unwrap_or_else(|_| serde_json::json!({}));
1315            if j.get("access_token").is_some() {
1316                // The token is in hand; a cancel that already happened wins and
1317                // nothing is written, a later one is refused.
1318                if !manager().begin_commit(&sid) {
1319                    return;
1320                }
1321                manager().set_status(&sid, complete(&ctx, &j).await);
1322                return;
1323            }
1324            match j.get("error").and_then(|v| v.as_str()) {
1325                Some("authorization_pending") => {}
1326                Some("slow_down") => interval += 5, // RFC 8628 §3.5
1327                Some("access_denied") => {
1328                    manager().set_status(&sid, OAuthStatus::Failed { error: "access denied".into() });
1329                    return;
1330                }
1331                Some("expired_token") | Some(_) => {
1332                    manager().set_status(&sid, OAuthStatus::Failed { error: "device code expired".into() });
1333                    return;
1334                }
1335                None => {}
1336            }
1337        }
1338    });
1339
1340    Ok((session_id, OAuthStatus::CodeEmitted { user_code: String::new(), verification_uri: String::new() }))
1341}
1342
1343/// The code exchange. A failure names the status and the OAuth `error` code,
1344/// never anything from the request.
1345async fn exchange(token_url: &str, params: &[(&str, String)]) -> Result<serde_json::Value, String> {
1346    let reply = oauth_tokens::LiveHttp
1347        .post_form(token_url, params)
1348        .await
1349        .map_err(|e| format!("token exchange failed: {e}"))?;
1350    if !(200..300).contains(&reply.status) {
1351        return Err(match reply.error_code() {
1352            Some(code) => format!("token endpoint returned {} ({code})", reply.status),
1353            None => format!("token endpoint returned {}", reply.status),
1354        });
1355    }
1356    Ok(reply.body)
1357}
1358
1359/// What the provider sent back to the loopback listener.
1360#[derive(Debug, Default, PartialEq, Eq)]
1361struct Callback {
1362    code: Option<String>,
1363    state: Option<String>,
1364    /// The OAuth `error` (RFC 6749 §4.1.2.1), kept to `[a-z_]`.
1365    error: Option<String>,
1366    /// Google's picker: the ids of the files the person picked, comma separated.
1367    picked_file_ids: Option<String>,
1368}
1369
1370/// The most files one pick returns.
1371const MAX_PICKED: usize = 100;
1372
1373/// Drive file ids from the picker's `picked_file_ids`: letters, digits, `-` and `_` only.
1374fn picked_ids(raw: Option<&str>) -> Vec<String> {
1375    raw.unwrap_or("")
1376        .split(',')
1377        .map(str::trim)
1378        .filter(|id| !id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
1379        .take(MAX_PICKED)
1380        .map(str::to_string)
1381        .collect()
1382}
1383
1384/// Extract `code`, `state` and `error` from a raw HTTP request line
1385/// `GET /callback?code=...&state=... HTTP/1.1`.
1386fn parse_callback(req: &str) -> Callback {
1387    let first = req.lines().next().unwrap_or("");
1388    let path = first.split_whitespace().nth(1).unwrap_or("");
1389    let query = path.split('?').nth(1).unwrap_or("");
1390    let mut out = Callback::default();
1391    for pair in query.split('&') {
1392        let mut it = pair.splitn(2, '=');
1393        match (it.next(), it.next()) {
1394            (Some("code"), Some(v)) => out.code = Some(percent_decode(v)),
1395            (Some("state"), Some(v)) => out.state = Some(percent_decode(v)),
1396            (Some("picked_file_ids"), Some(v)) => out.picked_file_ids = Some(percent_decode(v)),
1397            (Some("error"), Some(v)) => {
1398                let clean: String = percent_decode(v)
1399                    .chars()
1400                    .filter(|c| c.is_ascii_lowercase() || *c == '_')
1401                    .take(64)
1402                    .collect();
1403                out.error = Some(if clean.is_empty() { "unknown_error".to_string() } else { clean });
1404            }
1405            _ => {}
1406        }
1407    }
1408    out
1409}
1410
1411/// The sentence a flow fails with when the provider answered with an error.
1412fn callback_error_message(provider: &str, code: &str) -> String {
1413    match code {
1414        "access_denied" => "access denied: the consent screen was cancelled or declined".to_string(),
1415        "admin_policy_enforced" => format!(
1416            "blocked by your organization: a {provider} Workspace administrator doesn't allow this app \
1417             (admin_policy_enforced). Ask the administrator to allow it, or use a Workspace internal client."
1418        ),
1419        other => format!("{provider} refused the sign-in ({other})"),
1420    }
1421}
1422
1423fn percent_decode(s: &str) -> String {
1424    let bytes = s.replace('+', " ");
1425    let bytes = bytes.as_bytes();
1426    let mut out = Vec::with_capacity(bytes.len());
1427    let mut i = 0;
1428    while i < bytes.len() {
1429        if bytes[i] == b'%' && i + 2 < bytes.len() {
1430            if let Ok(b) = u8::from_str_radix(&String::from_utf8_lossy(&bytes[i + 1..i + 3]), 16) {
1431                out.push(b);
1432                i += 3;
1433                continue;
1434            }
1435        }
1436        out.push(bytes[i]);
1437        i += 1;
1438    }
1439    String::from_utf8_lossy(&out).to_string()
1440}
1441
1442#[cfg(test)]
1443#[path = "oauth_client_tests.rs"]
1444mod tests;