1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum OAuthFlow {
46 AuthCodePkce,
48 Device,
50}
51
52#[derive(Debug, Clone)]
55pub struct ServiceOAuthConfig {
56 pub provider: &'static str,
57 pub flow: OAuthFlow,
58 pub client_id: Option<&'static str>,
60 pub auth_url: &'static str,
61 pub token_url: &'static str,
62 pub device_url: Option<&'static str>,
64 pub scopes: &'static [&'static str],
67 pub requires_secret: bool,
70 pub extra_auth_params: &'static [(&'static str, &'static str)],
73 pub revoke_url: Option<&'static str>,
75 pub id_token_issuers: &'static [&'static str],
77}
78
79pub 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 requires_secret: true,
98 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, 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 id_token_issuers: &[],
124 }),
125 "github" => Some(ServiceOAuthConfig {
126 provider: "github",
127 flow: OAuthFlow::Device, client_id: None, 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 revoke_url: None,
138 id_token_issuers: &[],
139 }),
140 "slack" => Some(ServiceOAuthConfig {
141 provider: "slack",
142 flow: OAuthFlow::AuthCodePkce,
143 client_id: None, 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
157pub 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
177pub 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
202fn 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
215fn 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
223pub const PICKER_SCOPE: &str = "https://www.googleapis.com/auth/drive.file";
226
227pub 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 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
255async 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
272fn 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
283async 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
299const MAX_REQUEST_LINE: usize = 32 * 1024;
302
303pub struct PkcePair {
307 pub verifier: String,
308 pub challenge: String,
309}
310
311pub 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
329pub fn random_state() -> String {
331 uuid::Uuid::new_v4().to_string()
332}
333
334const SESSION_TIMEOUT: Duration = Duration::from_secs(300);
337
338#[derive(Debug, Clone)]
340pub enum OAuthStatus {
341 Pending,
345 UrlAvailable { auth_url: String },
347 CodeEmitted { user_code: String, verification_uri: String },
349 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 Picked { account_id: String, file_ids: Vec<String> },
362 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 committing: bool,
383 stop: tokio::sync::watch::Sender<bool>,
386}
387
388pub struct StopSignal(tokio::sync::watch::Receiver<bool>);
390
391impl StopSignal {
392 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
404const 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 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 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 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 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 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
483pub fn manager() -> &'static OAuthSessionManager {
487 static M: OnceLock<OAuthSessionManager> = OnceLock::new();
488 M.get_or_init(OAuthSessionManager::default)
489}
490
491#[derive(Clone)]
494pub struct ByoCredentials {
495 pub client_id: String,
496 pub client_secret: Option<String>,
497 pub mode: ClientMode,
500}
501
502#[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
520fn 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
528pub const GOOGLE_CLIENT_ID: &str = "1026607634671-pvql7gvgsf1oi5uo0rdvaoqj426ik9jq.apps.googleusercontent.com";
531
532fn 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
544fn 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
550pub(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
557pub 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
563pub 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
575fn 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 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
610use 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#[derive(Debug, Clone)]
627pub enum FlowTarget {
628 New { name: String },
629 Existing(IdentityAccount),
630}
631
632pub struct StartOptions {
634 pub target: FlowTarget,
635 pub byo: Option<ByoCredentials>,
637 pub saved: Option<SavedClient>,
639 pub extra_scopes: Vec<String>,
641 pub save_client: bool,
643 pub cloud_signed_in: bool,
646 pub replace_user: bool,
649 pub open_system_browser: bool,
652 pub login_hint: Option<String>,
654}
655
656pub 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
668pub 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
693fn 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
718struct 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
731async 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 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 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 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 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 crate::identity::accounts_changed::announce();
811 Ok(OAuthStatus::Success { account_id, granted_scopes: granted, missing_scopes: missing, email })
812}
813
814async fn complete(ctx: &FlowCtx, json: &serde_json::Value) -> OAuthStatus {
818 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 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
859fn 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
871pub 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
911pub 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
941pub 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
953pub const NEEDS_CLOUD_SIGN_IN: &str = "needs-cloud-sign-in";
958
959fn 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
965fn 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
986fn 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
994struct BrokerLeg {
997 replace: bool,
998}
999
1000async 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 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
1014async 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
1033async 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
1042enum TripEnd {
1044 NotATrip,
1046 Cancelled,
1048 Ended(OAuthStatus),
1049}
1050
1051async 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
1067async 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 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 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 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 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 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 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 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, ¶ms).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 if !manager().begin_commit(&sid) {
1228 return;
1229 }
1230 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 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, ¶ms).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 let params = [("client_id", client_id.clone()), ("scope", scopes)];
1267 let resp = match http().post(&device_url).header("Accept", "application/json").form(¶ms).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 loop {
1291 tokio::select! {
1293 _ = stop.stopped() => return,
1294 _ = tokio::time::sleep(Duration::from_secs(interval)) => {}
1295 }
1296 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 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, 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
1343async 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#[derive(Debug, Default, PartialEq, Eq)]
1361struct Callback {
1362 code: Option<String>,
1363 state: Option<String>,
1364 error: Option<String>,
1366 picked_file_ids: Option<String>,
1368}
1369
1370const MAX_PICKED: usize = 100;
1372
1373fn 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
1384fn 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
1411fn 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;