Skip to main content

agentmux_srv/server/agent_handlers/identity/
oauth.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The service-OAuth RPCs (`account.oauth.start`, `.poll`, `.cancel`, `.client.get`, `.client.clear`),
5//! moved out of `identity::register` unchanged as named functions.
6
7use std::sync::Arc;
8
9use super::{
10    builtin_client_of, byo_from_req, oauth_status_wire, panel_start_options, reads_saved_client, AccountOAuthClientClearResult, AccountOAuthClientInfo,
11    AccountOAuthStartResult, OAuthClientReq, OAuthSessionReq, OAuthStartReq,
12};
13use crate::backend::rpc_types::AccountOAuthCancelResult;
14use crate::backend::storage::store::Store;
15use crate::identity::oauth_client::FlowTarget;
16
17/// Resolve config and client (gating on "not configured"), spawn the flow, return the session id and its
18/// first status. Poll and cancel drive the rest. With `accountId` it authorizes that account again (more
19/// scopes, or a reconnect) instead of creating one: spec G0 of
20/// docs/specs/SPEC_GOOGLE_CONNECTORS_GMAIL_CALENDAR_DRIVE_2026_10_14.md.
21pub(super) async fn start_oauth(
22    mstore: Arc<Store>,
23    identity_store: Arc<Store>,
24    data: serde_json::Value,
25) -> Result<AccountOAuthStartResult, String> {
26    // NB: `req.client_secret` is a secret, so never log `req`.
27    let req: OAuthStartReq = serde_json::from_value(data).map_err(|e| format!("account.oauth.start: {e}"))?;
28    let byo = match byo_from_req(&req) {
29        Ok(b) => b,
30        Err(e) => return Ok(start_failed(e)),
31    };
32    let target = match flow_target(&mstore, &req) {
33        Ok(t) => t,
34        Err(e) => return Ok(start_failed(e)),
35    };
36    let saved = if reads_saved_client(&req, &byo) { saved_client(&req.provider).await } else { None };
37    let cloud_signed_in = cloud_signed_in(&mstore, &req.provider).await;
38    let opts = panel_start_options(&req, target, byo, saved, cloud_signed_in);
39    match crate::identity::oauth_client::start(&req.provider, opts, mstore, identity_store) {
40        Ok((session_id, status)) => {
41            Ok(AccountOAuthStartResult { session_id: Some(session_id), status: Some(oauth_status_wire(&status)), error: None })
42        }
43        // "not configured" / unknown provider surface as a clean error field, not an RPC failure, so the UI can show it.
44        Err(e) => Ok(start_failed(e)),
45    }
46}
47
48fn start_failed(error: String) -> AccountOAuthStartResult {
49    AccountOAuthStartResult { session_id: None, status: None, error: Some(error) }
50}
51
52/// A new account, or the existing one the request names.
53fn flow_target(mstore: &Store, req: &OAuthStartReq) -> Result<FlowTarget, String> {
54    match req.account_id.as_deref().filter(|s| !s.is_empty()) {
55        None => Ok(FlowTarget::New { name: req.name.clone() }),
56        Some(id) => match mstore.identity_get(id) {
57            Ok(Some(acct)) => Ok(FlowTarget::Existing(acct)),
58            Ok(None) => Err(format!("account {id} not found")),
59            Err(e) => Err(format!("account {id} could not be read: {e}")),
60        },
61    }
62}
63
64/// The user's saved client, when none came with the request. A keychain that can't be read means none: the
65/// panel asks again.
66async fn saved_client(provider: &str) -> Option<crate::identity::oauth_tokens::SavedClient> {
67    let owned = provider.to_string();
68    let loaded = tokio::task::spawn_blocking(move || crate::identity::oauth_tokens::load_saved_client(&owned))
69        .await
70        .map_err(|e| format!("keychain task: {e}"))
71        .and_then(|r| r);
72    match loaded {
73        Ok(saved) => saved,
74        Err(e) => {
75            tracing::warn!(target: "identity", provider = %provider, error = %e, "account.oauth.start: the saved OAuth client could not be read");
76            None
77        }
78    }
79}
80
81/// GitHub connects through the broker when signed in to AgentMux Cloud.
82async fn cloud_signed_in(mstore: &Arc<Store>, provider: &str) -> bool {
83    if provider != crate::identity::github_connect::PROVIDER {
84        return false;
85    }
86    let store = mstore.clone();
87    tokio::task::spawn_blocking(move || store.muxbus_load().ok().flatten().is_some()).await.unwrap_or(false)
88}
89
90/// The user's own OAuth client saved for a provider (D8): whether there is one. Accounts made with it keep
91/// refreshing: each keeps its own copy of what a refresh needs.
92pub(super) async fn oauth_client_info(req: OAuthClientReq) -> Result<AccountOAuthClientInfo, String> {
93    let (builtin_available, offered_services) = builtin_client_of(&req.provider)?;
94    let provider = req.provider.clone();
95    let saved = tokio::task::spawn_blocking(move || crate::identity::oauth_tokens::load_saved_client(&provider))
96        .await
97        .map_err(|e| format!("account.oauth.client.get: keychain task: {e}"))?
98        .map_err(|e| format!("account.oauth.client.get: {e}"))?;
99    Ok(AccountOAuthClientInfo {
100        saved: saved.is_some(),
101        client_id: saved.as_ref().map(|c| c.client_id.clone()),
102        has_secret: saved.as_ref().is_some_and(|c| c.client_secret.is_some()),
103        mode: saved.as_ref().map(|c| c.mode.as_str().to_string()),
104        builtin_available,
105        offered_services,
106    })
107}
108
109/// Forgets the user's saved OAuth client for a provider.
110pub(super) async fn clear_oauth_client(req: OAuthClientReq) -> Result<AccountOAuthClientClearResult, String> {
111    if crate::identity::oauth_client::config_for(&req.provider).is_none() {
112        return Err(format!("account.oauth.client.clear: unknown OAuth provider: {}", req.provider));
113    }
114    let provider = req.provider.clone();
115    let cleared = tokio::task::spawn_blocking(move || crate::identity::oauth_tokens::clear_saved_client(&provider))
116        .await
117        .map_err(|e| format!("account.oauth.client.clear: keychain task: {e}"))?
118        .map_err(|e| format!("account.oauth.client.clear: {e}"))?;
119    tracing::info!(target: "identity", provider = %req.provider, cleared, "account.oauth.client.clear: saved OAuth client forgotten");
120    Ok(AccountOAuthClientClearResult { cleared })
121}
122
123/// The response stays `Value`: `oauth_status_wire` builds it, and the frontend models it as `OAuthFlowStatus`
124/// (generated-manifest.json `returns`).
125pub(super) fn poll_oauth(req: &OAuthSessionReq) -> Result<serde_json::Value, String> {
126    match crate::identity::oauth_client::manager().poll(&req.session_id) {
127        Some(s) => Ok(oauth_status_wire(&s)),
128        None => Err(format!("account.oauth.poll: unknown session {}", req.session_id)),
129    }
130}
131
132pub(super) fn cancel_oauth(req: &OAuthSessionReq) -> AccountOAuthCancelResult {
133    AccountOAuthCancelResult { cancelled: crate::identity::oauth_client::manager().cancel(&req.session_id) }
134}
135
136#[cfg(test)]
137mod tests {
138    use serde_json::json;
139
140    use super::*;
141
142    fn req(extra: serde_json::Value) -> OAuthStartReq {
143        let mut base = json!({ "provider": "google", "name": "Mail" });
144        base.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
145        serde_json::from_value(base).unwrap()
146    }
147
148    #[test]
149    fn a_start_without_an_account_makes_a_new_one_named_as_asked() {
150        let store = Store::open_in_memory().unwrap();
151        for empty in [json!({}), json!({ "accountId": "" })] {
152            match flow_target(&store, &req(empty)).unwrap() {
153                FlowTarget::New { name } => assert_eq!(name, "Mail"),
154                FlowTarget::Existing(_) => panic!("an empty account id means a new account"),
155            }
156        }
157    }
158
159    #[test]
160    fn a_start_for_an_account_the_store_does_not_hold_says_which() {
161        let store = Store::open_in_memory().unwrap();
162        let err = flow_target(&store, &req(json!({ "accountId": "ghost" }))).err().unwrap();
163        assert_eq!(err, "account ghost not found");
164    }
165
166    #[test]
167    fn a_start_that_fails_answers_with_only_the_error() {
168        let failed = start_failed("not configured".to_string());
169        assert_eq!((failed.session_id, failed.status, failed.error.as_deref()), (None, None, Some("not configured")));
170    }
171}