Skip to main content

agentmux_srv_core/identity/
oauth_tokens.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What srv does with a service-OAuth account's tokens once it has them:
5//! read the keychain blob, take the account's email from the ID token,
6//! refresh near expiry, revoke on delete, and keep the user's own OAuth
7//! client (BYO) in the keychain.
8//! docs/specs/SPEC_GOOGLE_CONNECTORS_GMAIL_CALENDAR_DRIVE_2026_10_14.md G0
9//! (§2.1's gaps, §3.1, D2, D8).
10//!
11//! The flow that obtains the tokens is `oauth_client`. Every network call
12//! here goes through [`OAuthHttp`] and every keychain call through
13//! [`TokenSecrets`], so tests stub both and never reach Google.
14//!
15//! No token, refresh token, client secret or ID token is ever logged, put in
16//! an error string, or returned over RPC: errors carry an HTTP status and the
17//! provider's `error` code, nothing from the request.
18
19use std::collections::HashMap;
20use std::future::Future;
21use std::sync::{Arc, Mutex, OnceLock};
22
23use base64::Engine as _;
24use base64::engine::general_purpose::URL_SAFE_NO_PAD;
25use serde::{Deserialize, Serialize};
26use zeroize::{Zeroize, Zeroizing};
27
28use crate::backend::storage::store::{IdentityAccount, SecretRef, Store};
29use crate::identity::oauth_client::ServiceOAuthConfig;
30
31/// Refresh an access token this many seconds before it expires.
32pub const REFRESH_MARGIN_SECS: i64 = 60;
33
34/// The account status a refresh answered with `invalid_grant` leaves behind.
35/// The Connectors card shows it as "Reconnect needed" (identity-manager.tsx).
36pub const STATUS_NEEDS_REAUTH: &str = "needs_reauth";
37
38/// The start of every error that means "reconnect, don't retry".
39pub const RECONNECT_NEEDED: &str = "Reconnect needed";
40
41// ── The keychain blob ───────────────────────────────────────────────────────
42
43/// An OAuth account's keychain entry: `{access_token, refresh_token,
44/// expires_at}` as JSON, plus the client secret of a BYO client that has one,
45/// so a refresh uses the same client the account was made with (D8) even
46/// after the saved BYO client is cleared or replaced.
47#[derive(Clone, Serialize, Deserialize)]
48pub struct TokenBlob {
49    pub access_token: String,
50    #[serde(default)]
51    pub refresh_token: Option<String>,
52    /// Unix seconds; 0 when the provider gave no lifetime (never refreshed).
53    #[serde(default)]
54    pub expires_at: i64,
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub client_secret: Option<String>,
57}
58
59impl std::fmt::Debug for TokenBlob {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        f.debug_struct("TokenBlob")
62            .field("refresh_token", &self.refresh_token.as_ref().map(|_| "<redacted>"))
63            .field("expires_at", &self.expires_at)
64            .finish_non_exhaustive()
65    }
66}
67
68impl Drop for TokenBlob {
69    fn drop(&mut self) {
70        self.access_token.zeroize();
71        if let Some(r) = self.refresh_token.as_mut() {
72            r.zeroize();
73        }
74        if let Some(s) = self.client_secret.as_mut() {
75            s.zeroize();
76        }
77    }
78}
79
80impl TokenBlob {
81    /// The blob in a stored secret, or `None` for a plain secret (an API key
82    /// or PAT), which is not JSON or has no `access_token`.
83    pub fn parse(secret: &str) -> Option<TokenBlob> {
84        let trimmed = secret.trim_start();
85        if !trimmed.starts_with('{') {
86            return None;
87        }
88        let blob: TokenBlob = serde_json::from_str(trimmed).ok()?;
89        (!blob.access_token.is_empty()).then_some(blob)
90    }
91
92    /// The blob for a token endpoint's answer. A refresh that returns no
93    /// `refresh_token` keeps `previous_refresh` (RFC 6749 §6).
94    pub fn from_token_response(
95        json: &serde_json::Value,
96        now: i64,
97        previous_refresh: Option<&str>,
98        client_secret: Option<&str>,
99    ) -> Result<TokenBlob, String> {
100        let access_token = json
101            .get("access_token")
102            .and_then(|v| v.as_str())
103            .filter(|s| !s.is_empty())
104            .ok_or("the token response carried no access token")?;
105        let expires_in = json.get("expires_in").and_then(|v| v.as_i64()).unwrap_or(0);
106        let refresh_token = json
107            .get("refresh_token")
108            .and_then(|v| v.as_str())
109            .filter(|s| !s.is_empty())
110            .or(previous_refresh)
111            .map(str::to_string);
112        Ok(TokenBlob {
113            access_token: access_token.to_string(),
114            refresh_token,
115            expires_at: if expires_in > 0 { now + expires_in } else { 0 },
116            client_secret: client_secret.map(str::to_string),
117        })
118    }
119
120    pub fn to_json(&self) -> Zeroizing<String> {
121        Zeroizing::new(serde_json::to_string(self).unwrap_or_default())
122    }
123
124    /// Whether the access token expires within [`REFRESH_MARGIN_SECS`].
125    pub fn needs_refresh(&self, now: i64) -> bool {
126        self.expires_at > 0 && now >= self.expires_at - REFRESH_MARGIN_SECS
127    }
128}
129
130/// The value to use as a token for a stored secret: the `access_token` of an
131/// OAuth blob, or the secret itself when it is a plain key. An OAuth-connected
132/// GitHub account used to reach agents as `GH_TOKEN='{"access_token":…}'`
133/// (spec §2.3).
134pub fn bearer_value(mut secret: String) -> String {
135    match TokenBlob::parse(&secret) {
136        Some(blob) => {
137            secret.zeroize();
138            blob.access_token.clone()
139        }
140        None => secret,
141    }
142}
143
144// ── Scopes ──────────────────────────────────────────────────────────────────
145
146/// The scopes a token response granted. Google, Microsoft and Slack separate
147/// them with spaces, GitHub with commas. RFC 6749 §5.1 lets a server omit
148/// `scope` when it granted exactly what was asked, so then it is `requested`.
149pub fn granted_scopes(token_response: &serde_json::Value, requested: &[String]) -> Vec<String> {
150    let Some(raw) = token_response.get("scope").and_then(|v| v.as_str()) else {
151        return requested.to_vec();
152    };
153    let mut out: Vec<String> = Vec::new();
154    for s in raw.split(|c: char| c.is_whitespace() || c == ',').filter(|s| !s.is_empty()) {
155        if !out.iter().any(|o| o == s) {
156            out.push(s.to_string());
157        }
158    }
159    out
160}
161
162/// The full name Google answers with for a short scope it accepts.
163fn canonical_scope(scope: &str) -> &str {
164    match scope {
165        "email" => "https://www.googleapis.com/auth/userinfo.email",
166        "profile" => "https://www.googleapis.com/auth/userinfo.profile",
167        other => other,
168    }
169}
170
171/// What was asked for and not granted: the user can untick any scope on
172/// Google's consent screen (granular consent, spec §3.1). `email` and
173/// `profile` match the full names Google returns for them.
174pub fn missing_scopes(requested: &[String], granted: &[String]) -> Vec<String> {
175    requested
176        .iter()
177        .filter(|r| !granted.iter().any(|g| canonical_scope(g) == canonical_scope(r)))
178        .cloned()
179        .collect()
180}
181
182// ── The ID token ────────────────────────────────────────────────────────────
183
184/// What srv keeps from an ID token. Not secret.
185#[derive(Debug, Clone, Default, PartialEq, Eq)]
186pub struct IdTokenClaims {
187    pub email: Option<String>,
188    pub email_verified: bool,
189    /// The provider's stable user id (`sub`).
190    pub subject: Option<String>,
191}
192
193/// Read an ID token's claims. It came straight from the token endpoint over
194/// TLS, so per OIDC Core §3.1.3.7 (6) the TLS server check stands in for the
195/// signature; the issuer, audience and expiry are still checked. Errors never
196/// quote the token.
197pub fn id_token_claims(
198    id_token: &str,
199    issuers: &[&str],
200    client_id: &str,
201    now: i64,
202) -> Result<IdTokenClaims, String> {
203    let mut parts = id_token.split('.');
204    let (Some(_header), Some(payload), Some(_sig), None) = (parts.next(), parts.next(), parts.next(), parts.next())
205    else {
206        return Err("the ID token is not a JWT".to_string());
207    };
208    let bytes = URL_SAFE_NO_PAD
209        .decode(payload.trim_end_matches('='))
210        .map_err(|_| "the ID token's payload is not base64url".to_string())?;
211    let claims: serde_json::Value =
212        serde_json::from_slice(&bytes).map_err(|_| "the ID token's payload is not JSON".to_string())?;
213
214    let iss = claims.get("iss").and_then(|v| v.as_str()).unwrap_or("");
215    if !issuers.contains(&iss) {
216        return Err(format!("the ID token's issuer is not one of {issuers:?}"));
217    }
218    let aud_ok = match claims.get("aud") {
219        Some(serde_json::Value::String(a)) => a == client_id,
220        Some(serde_json::Value::Array(a)) => {
221            // Several audiences: ours must be one, and `azp` must name us.
222            a.iter().any(|v| v.as_str() == Some(client_id))
223                && claims.get("azp").and_then(|v| v.as_str()) == Some(client_id)
224        }
225        _ => false,
226    };
227    if !aud_ok {
228        return Err("the ID token was issued for another client".to_string());
229    }
230    // Five minutes of clock skew.
231    if let Some(exp) = claims.get("exp").and_then(|v| v.as_i64()) {
232        if now > exp + 300 {
233            return Err("the ID token has expired".to_string());
234        }
235    }
236    let text = |k: &str| claims.get(k).and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
237    let email_verified = match claims.get("email_verified") {
238        Some(serde_json::Value::Bool(b)) => *b,
239        Some(serde_json::Value::String(s)) => s == "true",
240        _ => false,
241    };
242    Ok(IdTokenClaims { email: text("email"), email_verified, subject: text("sub") })
243}
244
245// ── HTTP and keychain seams ─────────────────────────────────────────────────
246
247/// A provider's HTTP answer: the status and the JSON body (`{}` when the body
248/// isn't JSON). A token response's body holds tokens, so `Debug` shows only
249/// the status and the OAuth error code.
250#[derive(Clone)]
251pub struct HttpReply {
252    pub status: u16,
253    pub body: serde_json::Value,
254}
255
256impl std::fmt::Debug for HttpReply {
257    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258        f.debug_struct("HttpReply").field("status", &self.status).field("error", &self.error_code()).finish_non_exhaustive()
259    }
260}
261
262impl HttpReply {
263    fn ok(&self) -> bool {
264        (200..300).contains(&self.status)
265    }
266    /// The OAuth `error` code (RFC 6749 §5.2), kept to `[a-z_]` so nothing
267    /// else from a body reaches a message.
268    pub fn error_code(&self) -> Option<String> {
269        let code = self.body.get("error")?.as_str()?;
270        let clean: String = code.chars().filter(|c| c.is_ascii_lowercase() || *c == '_').take(64).collect();
271        (!clean.is_empty()).then_some(clean)
272    }
273}
274
275/// The calls srv makes to a provider's OAuth endpoints.
276pub trait OAuthHttp: Sync {
277    fn post_form(&self, url: &str, params: &[(&str, String)]) -> impl Future<Output = Result<HttpReply, String>> + Send;
278    fn get_bearer(&self, url: &str, token: &str) -> impl Future<Output = Result<HttpReply, String>> + Send;
279}
280
281/// [`OAuthHttp`] over the network.
282pub struct LiveHttp;
283
284impl OAuthHttp for LiveHttp {
285    async fn post_form(&self, url: &str, params: &[(&str, String)]) -> Result<HttpReply, String> {
286        let resp = crate::identity::oauth_client::http()
287            .post(url)
288            .header("Accept", "application/json")
289            .form(params)
290            .send()
291            .await
292            .map_err(|e| format!("request failed: {}", e.without_url()))?;
293        let status = resp.status().as_u16();
294        let body = resp.json().await.unwrap_or_else(|_| serde_json::json!({}));
295        Ok(HttpReply { status, body })
296    }
297
298    async fn get_bearer(&self, url: &str, token: &str) -> Result<HttpReply, String> {
299        let resp = crate::identity::oauth_client::http()
300            .get(url)
301            .bearer_auth(token)
302            .send()
303            .await
304            .map_err(|e| format!("request failed: {}", e.without_url()))?;
305        let status = resp.status().as_u16();
306        let body = resp.json().await.unwrap_or_else(|_| serde_json::json!({}));
307        Ok(HttpReply { status, body })
308    }
309}
310
311/// Reads and writes of an account's keychain entry.
312pub trait TokenSecrets: Sync {
313    fn get(&self, account_id: &str) -> impl Future<Output = Result<Option<Zeroizing<String>>, String>> + Send;
314    fn put(&self, account_id: &str, value: &str) -> impl Future<Output = Result<(), String>> + Send;
315}
316
317/// [`TokenSecrets`] over `secret_store`, off the async workers (the keyring
318/// calls block).
319pub struct KeychainSecrets;
320
321impl TokenSecrets for KeychainSecrets {
322    async fn get(&self, account_id: &str) -> Result<Option<Zeroizing<String>>, String> {
323        let id = account_id.to_string();
324        tokio::task::spawn_blocking(move || crate::identity::secret_store::get_optional(&id))
325            .await
326            .map_err(|e| format!("keychain task: {e}"))?
327    }
328
329    async fn put(&self, account_id: &str, value: &str) -> Result<(), String> {
330        let (id, value) = (account_id.to_string(), Zeroizing::new(value.to_string()));
331        tokio::task::spawn_blocking(move || crate::identity::secret_store::put(&id, &value))
332            .await
333            .map_err(|e| format!("keychain task: {e}"))?
334    }
335}
336
337// ── Which client an account was made with (D8) ──────────────────────────────
338
339/// Where an account's OAuth client came from: AgentMux's own, the user's own,
340/// or the user's own created as an "Internal" Workspace app.
341#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
342#[serde(rename_all = "lowercase")]
343pub enum ClientMode {
344    #[default]
345    Builtin,
346    Byo,
347    Workspace,
348}
349
350impl ClientMode {
351    pub fn as_str(self) -> &'static str {
352        match self {
353            ClientMode::Builtin => "builtin",
354            ClientMode::Byo => "byo",
355            ClientMode::Workspace => "workspace",
356        }
357    }
358
359    /// A user-supplied client's mode from the RPC's `clientMode`.
360    pub fn parse_user(s: Option<&str>) -> Result<ClientMode, String> {
361        match s.unwrap_or("byo") {
362            "" | "byo" => Ok(ClientMode::Byo),
363            "workspace" => Ok(ClientMode::Workspace),
364            other => Err(format!("unknown client mode '{other}' (byo or workspace)")),
365        }
366    }
367}
368
369/// The client an account was made with, as recorded in its context
370/// (`context.oauth_client`). The client id isn't secret.
371pub fn account_client(account: &IdentityAccount) -> Option<(ClientMode, String)> {
372    let c = account.context.get("oauth_client")?;
373    let id = c.get("client_id")?.as_str().filter(|s| !s.is_empty())?;
374    let mode = c
375        .get("mode")
376        .and_then(|m| serde_json::from_value(m.clone()).ok())
377        .unwrap_or_default();
378    Some((mode, id.to_string()))
379}
380
381// ── The user's own client, saved in the keychain (D8) ───────────────────────
382
383/// A BYO OAuth client saved for a provider, reused by later connects.
384#[derive(Clone, Serialize, Deserialize)]
385pub struct SavedClient {
386    pub client_id: String,
387    #[serde(default)]
388    pub client_secret: Option<String>,
389    #[serde(default)]
390    pub mode: ClientMode,
391}
392
393impl std::fmt::Debug for SavedClient {
394    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
395        f.debug_struct("SavedClient")
396            .field("client_id", &self.client_id)
397            .field("client_secret", &self.client_secret.as_ref().map(|_| "<redacted>"))
398            .field("mode", &self.mode)
399            .finish()
400    }
401}
402
403impl Drop for SavedClient {
404    fn drop(&mut self) {
405        if let Some(s) = self.client_secret.as_mut() {
406            s.zeroize();
407        }
408    }
409}
410
411/// The keychain entry a provider's saved client lives in.
412pub fn saved_client_key(provider: &str) -> String {
413    format!("oauth-client:{provider}")
414}
415
416/// The client saved for `provider`, if any. Blocking (keychain).
417pub fn load_saved_client(provider: &str) -> Result<Option<SavedClient>, String> {
418    let Some(raw) = crate::identity::secret_store::get_optional(&saved_client_key(provider))? else {
419        return Ok(None);
420    };
421    Ok(serde_json::from_str::<SavedClient>(&raw).ok().filter(|c| !c.client_id.is_empty()))
422}
423
424/// Save `client` for `provider`, replacing any saved before. Blocking.
425pub fn save_client(provider: &str, client: &SavedClient) -> Result<(), String> {
426    let json = Zeroizing::new(serde_json::to_string(client).map_err(|e| e.to_string())?);
427    crate::identity::secret_store::put(&saved_client_key(provider), &json)
428}
429
430/// Forget the client saved for `provider`. Accounts made with it keep working:
431/// each keeps its own copy of what a refresh needs. Returns whether one was
432/// saved. Blocking.
433pub fn clear_saved_client(provider: &str) -> Result<bool, String> {
434    let existed = crate::identity::secret_store::get_optional(&saved_client_key(provider))?.is_some();
435    crate::identity::secret_store::delete(&saved_client_key(provider))?;
436    Ok(existed)
437}
438
439// ── Refresh ─────────────────────────────────────────────────────────────────
440
441/// Why a refresh produced no token.
442#[derive(Debug, PartialEq, Eq)]
443pub enum RefreshError {
444    /// The grant is gone (`invalid_grant`, or no refresh token): the user has
445    /// to reconnect. Never retried.
446    Reauth(String),
447    /// Anything else (offline, a 5xx, a misconfigured client).
448    Failed(String),
449}
450
451/// Exchange `blob`'s refresh token for a new access token with the client the
452/// account was made with. Pure apart from `http`.
453pub async fn refresh_blob<H: OAuthHttp>(
454    http: &H,
455    cfg: &ServiceOAuthConfig,
456    client_id: &str,
457    blob: &TokenBlob,
458    now: i64,
459) -> Result<TokenBlob, RefreshError> {
460    let Some(refresh) = blob.refresh_token.as_deref().filter(|r| !r.is_empty()) else {
461        return Err(RefreshError::Reauth("the access token expired and there is no refresh token".to_string()));
462    };
463    let mut params = vec![
464        ("grant_type", "refresh_token".to_string()),
465        ("refresh_token", refresh.to_string()),
466        ("client_id", client_id.to_string()),
467    ];
468    // An account made with AgentMux's own client keeps no secret: the build has it.
469    let secret = blob.client_secret.clone().or_else(|| crate::identity::oauth_client::builtin_secret_for(cfg, client_id));
470    if let Some(secret) = secret {
471        params.push(("client_secret", secret));
472    }
473    let reply = http
474        .post_form(cfg.token_url, &params)
475        .await
476        .map_err(|e| RefreshError::Failed(format!("token refresh failed: {e}")))?;
477    for (_, v) in params.iter_mut() {
478        v.zeroize();
479    }
480    if reply.ok() {
481        return TokenBlob::from_token_response(&reply.body, now, Some(refresh), blob.client_secret.as_deref())
482            .map_err(RefreshError::Failed);
483    }
484    match reply.error_code().as_deref() {
485        Some("invalid_grant") => Err(RefreshError::Reauth(
486            "the provider no longer accepts this account's grant (invalid_grant)".to_string(),
487        )),
488        Some(code) => Err(RefreshError::Failed(format!("the token endpoint returned {} ({code})", reply.status))),
489        None => Err(RefreshError::Failed(format!("the token endpoint returned {}", reply.status))),
490    }
491}
492
493/// One lock per account, so two callers needing a token at once make one
494/// refresh, not two.
495fn refresh_lock(account_id: &str) -> Arc<tokio::sync::Mutex<()>> {
496    static LOCKS: OnceLock<Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>> = OnceLock::new();
497    let mut map = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
498    map.entry(account_id.to_string()).or_default().clone()
499}
500
501/// Set an account's status in the account store and its global mirror.
502pub(crate) fn set_status(id_store: &Store, identity_store: &Store, account_id: &str, status: &str) {
503    for store in [id_store, identity_store] {
504        if let Err(e) = store.identity_set_status(account_id, status) {
505            tracing::warn!(target: "identity", account_id = %account_id, error = %e, "identity.oauth: status write failed");
506        }
507    }
508    // A refresh the provider refused (needs_reauth) or a reconnect (valid) shows on the card now.
509    crate::identity::accounts_changed::announce();
510}
511
512/// A valid access token for `account`: the stored one, or a refreshed one
513/// when it expires within [`REFRESH_MARGIN_SECS`] (written back to the
514/// keychain). A plain (non-OAuth) secret is returned as it is. A grant the
515/// provider no longer accepts marks the account [`STATUS_NEEDS_REAUTH`] and
516/// fails with [`RECONNECT_NEEDED`]; it is never retried.
517///
518/// `broker` is the store behind AgentMux Cloud's sign-in and this install's key: the
519/// way a GitHub grant made through the broker is refreshed (spec §4.1 item 4).
520pub async fn access_token_for<H: OAuthHttp, S: TokenSecrets>(
521    http: &H,
522    secrets: &S,
523    id_store: &Store,
524    identity_store: &Store,
525    account: &IdentityAccount,
526    broker: Option<&Arc<Store>>,
527) -> Result<Zeroizing<String>, String> {
528    if !matches!(account.secret_ref, SecretRef::Keychain { .. }) {
529        return Err("this account keeps no token in the keychain".to_string());
530    }
531    let read = || async {
532        secrets
533            .get(&account.id)
534            .await?
535            .ok_or_else(|| "no stored token for this account".to_string())
536    };
537    let raw = read().await?;
538    let Some(blob) = TokenBlob::parse(&raw) else {
539        return Ok(raw);
540    };
541    let now = chrono::Utc::now().timestamp();
542    if !blob.needs_refresh(now) {
543        return Ok(Zeroizing::new(blob.access_token.clone()));
544    }
545
546    let lock = refresh_lock(&account.id);
547    let _guard = lock.lock().await;
548    // Another caller may have refreshed while this one waited.
549    let raw = read().await?;
550    let blob = TokenBlob::parse(&raw).ok_or("the stored token is no longer an OAuth token")?;
551    let now = chrono::Utc::now().timestamp();
552    if !blob.needs_refresh(now) {
553        return Ok(Zeroizing::new(blob.access_token.clone()));
554    }
555
556    let reauth = |why: String| {
557        tracing::warn!(
558            target: "identity",
559            account_id = %account.id,
560            provider = %account.provider,
561            reason = %why,
562            "identity.oauth: refresh refused, account needs reconnecting"
563        );
564        set_status(id_store, identity_store, &account.id, STATUS_NEEDS_REAUTH);
565        format!("{RECONNECT_NEEDED}: {why}. Connect the {} account again in Connectors.", account.provider)
566    };
567    let cfg = crate::identity::oauth_client::config_for(&account.provider)
568        .ok_or_else(|| format!("unknown OAuth provider: {}", account.provider))?;
569    // The refresh token is single use at GitHub: what the broker returns is stored below
570    // before anything else can fail.
571    let refreshed = if crate::identity::github_connect::is_brokered(account) {
572        match broker {
573            Some(mstore) => crate::identity::github_connect::refresh_blob(mstore, &blob, now).await,
574            None => Err(RefreshError::Failed("no AgentMux Cloud connection to refresh the GitHub grant through".to_string())),
575        }
576    } else {
577        let Some((_, client_id)) = account_client(account) else {
578            return Err(reauth("the account doesn't record the OAuth client it was made with".to_string()));
579        };
580        refresh_blob(http, &cfg, &client_id, &blob, now).await
581    };
582    match refreshed {
583        Ok(fresh) => {
584            secrets.put(&account.id, &fresh.to_json()).await?;
585            if account.status != "valid" {
586                set_status(id_store, identity_store, &account.id, "valid");
587            }
588            tracing::info!(target: "identity", account_id = %account.id, provider = %account.provider, "identity.oauth: access token refreshed");
589            Ok(Zeroizing::new(fresh.access_token.clone()))
590        }
591        Err(RefreshError::Reauth(why)) => Err(reauth(why)),
592        Err(RefreshError::Failed(why)) => Err(why),
593    }
594}
595
596// ── Revoke ──────────────────────────────────────────────────────────────────
597
598/// Revoke `blob`'s grant at `revoke_url` (RFC 7009). The refresh token is
599/// sent when there is one: revoking it ends the whole grant, where an
600/// access token may already have expired.
601pub async fn revoke_blob<H: OAuthHttp>(http: &H, revoke_url: &str, blob: &TokenBlob) -> Result<(), String> {
602    let (token, is_refresh) = match blob.refresh_token.as_deref().filter(|r| !r.is_empty()) {
603        Some(r) => (r, true),
604        None => (blob.access_token.as_str(), false),
605    };
606    let mut params = [("token", token.to_string())];
607    let reply = http.post_form(revoke_url, &params).await;
608    params[0].1.zeroize();
609    let reply = reply.map_err(|e| format!("couldn't reach the revoke endpoint: {e}"))?;
610    if reply.ok() {
611        return Ok(());
612    }
613    // A refresh token the provider no longer knows means the grant is
614    // already gone (revoked by the user, or expired).
615    if is_refresh && reply.error_code().as_deref() == Some("invalid_token") {
616        return Ok(());
617    }
618    Err(match reply.error_code() {
619        Some(code) => format!("the revoke endpoint returned {} ({code})", reply.status),
620        None => format!("the revoke endpoint returned {}", reply.status),
621    })
622}
623
624/// Before an OAuth account is deleted, revoke its grant at the provider, so
625/// it doesn't live on there (spec §7 "Disconnect"). `None` when there's
626/// nothing to revoke: not an OAuth account, a provider with no revoke
627/// endpoint, or no stored token. Otherwise
628/// `{ outcome: "revoked" | "failed", detail? }`, for the delete's result.
629pub async fn revoke_before_delete<H: OAuthHttp, S: TokenSecrets>(
630    http: &H,
631    secrets: &S,
632    account: &IdentityAccount,
633) -> Option<serde_json::Value> {
634    if account.kind != "oauth" || !matches!(account.secret_ref, SecretRef::Keychain { .. }) {
635        return None;
636    }
637    let revoke_url = crate::identity::oauth_client::config_for(&account.provider)?.revoke_url?;
638    let raw = match secrets.get(&account.id).await {
639        Ok(Some(raw)) => raw,
640        Ok(None) => return None,
641        Err(e) => return Some(revoke_failed(account, format!("couldn't read the stored token: {e}"))),
642    };
643    let blob = TokenBlob::parse(&raw)?;
644    match revoke_blob(http, revoke_url, &blob).await {
645        Ok(()) => {
646            tracing::info!(target: "identity", account_id = %account.id, provider = %account.provider, "identity.delete: grant revoked at the provider");
647            Some(serde_json::json!({ "outcome": "revoked" }))
648        }
649        Err(e) => Some(revoke_failed(account, e)),
650    }
651}
652
653fn revoke_failed(account: &IdentityAccount, detail: String) -> serde_json::Value {
654    tracing::warn!(target: "identity", account_id = %account.id, provider = %account.provider, error = %detail, "identity.delete: revoking the grant failed");
655    serde_json::json!({ "outcome": "failed", "detail": detail })
656}
657
658#[cfg(any(test, feature = "test-support"))]
659#[path = "oauth_tokens_tests.rs"]
660pub mod tests;