1use 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
31pub const REFRESH_MARGIN_SECS: i64 = 60;
33
34pub const STATUS_NEEDS_REAUTH: &str = "needs_reauth";
37
38pub const RECONNECT_NEEDED: &str = "Reconnect needed";
40
41#[derive(Clone, Serialize, Deserialize)]
48pub struct TokenBlob {
49 pub access_token: String,
50 #[serde(default)]
51 pub refresh_token: Option<String>,
52 #[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 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 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 pub fn needs_refresh(&self, now: i64) -> bool {
126 self.expires_at > 0 && now >= self.expires_at - REFRESH_MARGIN_SECS
127 }
128}
129
130pub 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
144pub 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
162fn 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
171pub 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
186pub struct IdTokenClaims {
187 pub email: Option<String>,
188 pub email_verified: bool,
189 pub subject: Option<String>,
191}
192
193pub 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 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 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#[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 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
275pub 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
281pub 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
311pub 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
317pub 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#[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 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
369pub 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#[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
411pub fn saved_client_key(provider: &str) -> String {
413 format!("oauth-client:{provider}")
414}
415
416pub 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
424pub 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
430pub 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#[derive(Debug, PartialEq, Eq)]
443pub enum RefreshError {
444 Reauth(String),
447 Failed(String),
449}
450
451pub 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 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, ¶ms)
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
493fn 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
501pub(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 crate::identity::accounts_changed::announce();
510}
511
512pub 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 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 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
596pub 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, ¶ms).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 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
624pub 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;