Skip to main content

agentmux_srv/server/agent_handlers/
identity.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4
5use std::sync::Arc;
6
7use serde_json::json;
8
9use crate::backend::rpc::engine::WshRpcEngine;
10use crate::backend::rpc_types::{
11    COMMAND_LIST_IDENTITY_ACCOUNTS, COMMAND_GET_IDENTITY_ACCOUNT,
12    COMMAND_UPSERT_IDENTITY_ACCOUNT, COMMAND_DELETE_IDENTITY_ACCOUNT,
13    COMMAND_ACCOUNT_KEY_VERIFY,
14    COMMAND_ACCOUNT_OAUTH_START, COMMAND_ACCOUNT_OAUTH_POLL, COMMAND_ACCOUNT_OAUTH_CANCEL,
15    COMMAND_ACCOUNT_OAUTH_CLIENT_GET, COMMAND_ACCOUNT_OAUTH_CLIENT_CLEAR, COMMAND_GITHUB_CONNECTION, COMMAND_GITHUB_INSTALLATIONS,
16    COMMAND_LINK_AGENT_IDENTITY, COMMAND_UNLINK_AGENT_IDENTITY,
17    COMMAND_LIST_AGENT_IDENTITIES, COMMAND_LIST_ALL_AGENT_IDENTITIES,
18    COMMAND_LIST_NAMED_AGENTS, COMMAND_HIDE_NAMED_AGENT,
19    CommandHideNamedAgentData,
20    CommandListIdentityAccountsData, CommandGetIdentityAccountData,
21    CommandDeleteIdentityAccountData,
22    CommandLinkAgentIdentityData, CommandUnlinkAgentIdentityData,
23    CommandListAgentIdentitiesData, CommandListAllAgentIdentitiesData,
24};
25use crate::backend::storage::store::{
26    IdentityAccount, SecretRef,
27};
28
29use super::super::AppState;
30
31mod accounts;
32mod links;
33mod named_agents;
34mod oauth;
35
36/// Refuses to persist an OAuth account bound directly to its provider's
37/// ambient home dir (e.g. `~/.claude`) — nothing downstream validates
38/// `secret_ref.dir`, and a real, currently-live account configured exactly
39/// this way was found in this repo's own data
40/// (`docs/status/STATUS_IDENTITY_ISOLATION_GATE_NOT_ENFORCING_2026_08_20.md`
41/// §8). Split out of the `upsertidentityaccount` handler closure so it's
42/// directly unit-testable without spinning up the RPC engine. See
43/// `docs/specs/SPEC_BLOCK_AMBIENT_HOME_DIR_IDENTITY_BINDING_2026_08_25.md`.
44fn reject_ambient_home_dir_binding(account: &IdentityAccount) -> Result<(), String> {
45    let SecretRef::OAuthConfigDir { dir } = &account.secret_ref else {
46        return Ok(());
47    };
48    let Some(provider_cfg) = crate::backend::providers::get_provider(
49        &crate::backend::providers::resolve_provider_alias(&account.provider),
50    ) else {
51        return Ok(());
52    };
53    if crate::backend::providers::is_provider_ambient_home_dir(provider_cfg, dir) {
54        return Err(format!(
55            "upsertidentityaccount: refusing to bind {} identity to its \
56             ambient home directory ({dir}) — this would let a spawned \
57             agent silently share your personal CLI login/session state \
58             instead of using an isolated AgentMux account. Use an \
59             isolated config dir for this account instead.",
60            account.provider,
61        ));
62    }
63    Ok(())
64}
65
66/// Request for `account.key.verify` (account key flow). The `api_key`
67/// field is a secret — never log this struct.
68#[derive(serde::Deserialize)]
69#[serde(rename_all = "camelCase")]
70struct VerifyKeyReq {
71    /// Service id: "github" | "openai" | "anthropic" | "slack" | … .
72    provider: String,
73    /// Account display name (user-chosen label).
74    name: String,
75    #[serde(default)]
76    display_name: String,
77    /// Account kind; defaults to "api_key" when empty.
78    #[serde(default)]
79    kind: String,
80    /// The pasted secret. Used once to (optionally) validate + store in the
81    /// OS keychain, then dropped. Never persisted in the DB, never logged.
82    api_key: String,
83    /// When true, run a live validation probe before storing (user clicked
84    /// "Validate"). When false, store with status "unknown" (the "Save
85    /// without validating" air-gapped path).
86    #[serde(default)]
87    validate: bool,
88    /// Set to replace the key on an existing account; empty mints a new one.
89    #[serde(default)]
90    account_id: String,
91    /// User-entered, non-secret context (github_username, scopes, notes, …).
92    /// Merged over any existing context so editing a key never wipes fields
93    /// the user set previously.
94    #[serde(default)]
95    context: serde_json::Value,
96}
97
98/// Request for `account.oauth.start`. `clientId`/`clientSecret` are BYO OAuth
99/// app credentials (optional; required for secret-mandatory providers). Never
100/// log this struct: `clientSecret` is a secret.
101#[derive(serde::Deserialize)]
102#[serde(rename_all = "camelCase")]
103struct OAuthStartReq {
104    provider: String,
105    /// The new account's label; ignored when `accountId` is set.
106    #[serde(default)]
107    name: String,
108    #[serde(default)]
109    client_id: Option<String>,
110    #[serde(default)]
111    client_secret: Option<String>,
112    /// `"byo"` (default) or `"workspace"`: what kind of client `clientId` is.
113    #[serde(default)]
114    client_mode: Option<String>,
115    /// Save `clientId`/`clientSecret` in the keychain for later connects to
116    /// this provider once the flow succeeds (default true).
117    #[serde(default)]
118    save_client: Option<bool>,
119    /// Scopes beyond the provider's base ones (a service being turned on).
120    #[serde(default)]
121    scopes: Vec<String>,
122    /// Authorize this existing account again (turn a service on, or
123    /// reconnect) instead of creating a new one.
124    #[serde(default)]
125    account_id: Option<String>,
126    /// GitHub: the person agreed to replace the GitHub user this AgentMux account is
127    /// connected as with the one who just authorized.
128    #[serde(default)]
129    replace_github_user: bool,
130    /// Run with AgentMux's own client even though the person has saved one of their own (the
131    /// GitHub App choice: its title promises the App).
132    #[serde(default)]
133    use_builtin_client: bool,
134}
135
136#[derive(serde::Deserialize, serde::Serialize, ts_rs::TS)]
137#[ts(export, export_to = "../../../frontend/types/rpc/")]
138#[serde(rename_all = "camelCase")]
139pub struct OAuthSessionReq {
140    pub session_id: String,
141}
142
143/// Request for `github.connection`: nothing.
144#[derive(Default, serde::Deserialize, serde::Serialize, ts_rs::TS)]
145#[ts(export, export_to = "../../../frontend/types/rpc/")]
146#[serde(rename_all = "camelCase")]
147pub struct GithubConnectionReq {}
148
149/// Request for `account.oauth.client.get` / `account.oauth.client.clear`.
150#[derive(serde::Deserialize, serde::Serialize, ts_rs::TS)]
151#[ts(export, export_to = "../../../frontend/types/rpc/")]
152#[serde(rename_all = "camelCase")]
153pub struct OAuthClientReq {
154    pub provider: String,
155}
156
157/// What `account.oauth.client.get` answers: whether the user's own client is
158/// saved for the provider, never its secret.
159#[derive(serde::Serialize, ts_rs::TS)]
160#[ts(export, export_to = "../../../frontend/types/rpc/")]
161#[serde(rename_all = "camelCase")]
162pub struct AccountOAuthClientInfo {
163    saved: bool,
164    #[serde(skip_serializing_if = "Option::is_none")]
165    #[ts(optional)]
166    client_id: Option<String>,
167    has_secret: bool,
168    #[serde(skip_serializing_if = "Option::is_none")]
169    #[ts(optional, type = "\"byo\" | \"workspace\"")]
170    mode: Option<String>,
171    /// Whether AgentMux ships its own client for the provider (the one-click
172    /// path); false means a connect needs the user's own client.
173    builtin_available: bool,
174    /// For Google: the services AgentMux's own client may ask for in this build (`google_offered`);
175    /// empty for any other provider, and moot for a client the person brought.
176    offered_services: Vec<String>,
177}
178
179/// What `account.oauth.client.clear` answers: whether a client was saved.
180#[derive(serde::Serialize, ts_rs::TS)]
181#[ts(export, export_to = "../../../frontend/types/rpc/")]
182#[serde(rename_all = "camelCase")]
183pub struct AccountOAuthClientClearResult {
184    cleared: bool,
185}
186
187/// Whether AgentMux ships its own client for `provider`, and (Google) which services it may ask for in this build.
188fn builtin_client_of(provider: &str) -> Result<(bool, Vec<String>), String> {
189    let cfg = crate::identity::oauth_client::config_for(provider)
190        .ok_or_else(|| format!("account.oauth.client.get: unknown OAuth provider: {provider}"))?;
191    let offered = if provider == "google" { crate::identity::google_offered::offered() } else { Vec::new() };
192    Ok((crate::identity::oauth_client::builtin_client_available(&cfg), offered))
193}
194
195/// The `OAuthStartReq` fields that become `oauth_client::StartOptions`,
196/// minus the reads (saved client, existing account) the handler does.
197fn byo_from_req(req: &OAuthStartReq) -> Result<Option<crate::identity::oauth_client::ByoCredentials>, String> {
198    let Some(client_id) = req.client_id.as_deref().map(str::trim).filter(|s| !s.is_empty()) else {
199        return Ok(None);
200    };
201    let mode = crate::identity::oauth_tokens::ClientMode::parse_user(req.client_mode.as_deref())?;
202    Ok(Some(crate::identity::oauth_client::ByoCredentials {
203        client_id: client_id.to_string(),
204        client_secret: req.client_secret.clone().filter(|s| !s.is_empty()),
205        mode,
206    }))
207}
208
209/// Whether a start reads the person's saved client: only when the request brought none and did not ask
210/// for AgentMux's own.
211fn reads_saved_client(req: &OAuthStartReq, byo: &Option<crate::identity::oauth_client::ByoCredentials>) -> bool {
212    byo.is_none() && !req.use_builtin_client
213}
214
215/// Serialize an OAuthStatus to the frontend wire shape.
216/// What the Accounts panel's Connect starts a flow with: the consent page opens in the system
217/// browser, and Google's account picker has no hint.
218fn panel_start_options(
219    req: &OAuthStartReq,
220    target: crate::identity::oauth_client::FlowTarget,
221    byo: Option<crate::identity::oauth_client::ByoCredentials>,
222    saved: Option<crate::identity::oauth_tokens::SavedClient>,
223    cloud_signed_in: bool,
224) -> crate::identity::oauth_client::StartOptions {
225    crate::identity::oauth_client::StartOptions {
226        target,
227        byo,
228        saved,
229        extra_scopes: req.scopes.clone(),
230        save_client: req.save_client.unwrap_or(true),
231        cloud_signed_in,
232        replace_user: req.replace_github_user,
233        open_system_browser: true,
234        login_hint: None,
235    }
236}
237
238fn oauth_status_wire(s: &crate::identity::oauth_client::OAuthStatus) -> serde_json::Value {
239    use crate::identity::oauth_client::OAuthStatus;
240    match s {
241        OAuthStatus::Pending => serde_json::json!({ "status": "pending" }),
242        OAuthStatus::UrlAvailable { auth_url } => {
243            serde_json::json!({ "status": "url-available", "authUrl": auth_url })
244        }
245        OAuthStatus::CodeEmitted { user_code, verification_uri } => serde_json::json!({
246            "status": "code-emitted",
247            "userCode": user_code,
248            "verificationUri": verification_uri,
249        }),
250        OAuthStatus::Success { account_id, granted_scopes, missing_scopes, email } => serde_json::json!({
251            "status": "success",
252            "accountId": account_id,
253            "grantedScopes": granted_scopes,
254            "missingScopes": missing_scopes,
255            "email": email,
256        }),
257        OAuthStatus::Failed { error } => serde_json::json!({ "status": "failed", "error": error }),
258        OAuthStatus::Picked { account_id, file_ids } => {
259            serde_json::json!({ "status": "picked", "accountId": account_id, "fileIds": file_ids })
260        }
261        OAuthStatus::ConfirmUser { current_login, current_id, new_login, new_id } => serde_json::json!({
262            "status": "confirm-user",
263            "currentLogin": current_login,
264            "currentId": current_id,
265            "newLogin": new_login,
266            "newId": new_id,
267        }),
268    }
269}
270
271/// Whether a delete stops, keeping the account, because revoking its grant
272/// failed and the caller asked for the revoke to succeed first.
273pub(super) fn revoke_keeps_account(revoke_report: &serde_json::Value, require_revoke: bool) -> bool {
274    require_revoke && revoke_report.get("outcome").and_then(|v| v.as_str()) == Some("failed")
275}
276
277/// Shallow-merge the keys of `overlay` (if both are JSON objects) into `base`.
278fn merge_json_object(base: &mut serde_json::Value, overlay: &serde_json::Value) {
279    if let (Some(b), Some(o)) = (base.as_object_mut(), overlay.as_object()) {
280        for (k, v) in o {
281            b.insert(k.clone(), v.clone());
282        }
283    }
284}
285
286/// What `deleteidentityaccount` answers.
287#[derive(serde::Serialize, ts_rs::TS)]
288#[ts(export, export_to = "../../../frontend/types/rpc/")]
289#[serde(rename_all = "camelCase")]
290pub struct DeleteIdentityAccountResult {
291    pub(crate) deleted: bool,
292    /// Agents whose link to the account was removed (delete-time disclosure).
293    pub(crate) affected_agents: Vec<String>,
294    /// What removing the saved login did; null when there was no account row.
295    #[ts(type = "{ outcome: \"removed\" | \"absent\" | \"skipped\" | \"failed\" | \"none\"; path?: string; detail?: string; historyKept?: boolean; historyPath?: string } | null")]
296    pub(crate) cleanup: serde_json::Value,
297    /// Revoking an OAuth account's grant at the provider (Google) before the
298    /// delete; null when there was nothing to revoke. `failed` means the grant
299    /// may live on at the provider. With `require_revoke` the account was then
300    /// kept (`deleted: false`) so the delete can be retried; without it the
301    /// account is gone and the grant is left to the provider's account page.
302    #[ts(type = "{ outcome: \"revoked\" | \"failed\"; detail?: string } | null")]
303    pub(crate) revoke: serde_json::Value,
304}
305
306/// What `account.key.verify` answers: `{ valid: false, error }` when validation
307/// failed, otherwise every field but `error` (the same keys the handler sent).
308#[derive(serde::Serialize, ts_rs::TS)]
309#[ts(export, export_to = "../../../frontend/types/rpc/")]
310#[serde(rename_all = "camelCase")]
311pub struct AccountKeyVerifyResult {
312    valid: bool,
313    #[serde(skip_serializing_if = "Option::is_none")]
314    #[ts(optional)]
315    error: Option<String>,
316    #[serde(skip_serializing_if = "Option::is_none")]
317    #[ts(optional)]
318    account_id: Option<String>,
319    #[serde(skip_serializing_if = "Option::is_none")]
320    #[ts(optional, type = "string")]
321    masked_tail: Option<serde_json::Value>,
322    #[serde(skip_serializing_if = "Option::is_none")]
323    #[ts(optional)]
324    status: Option<String>,
325    #[serde(skip_serializing_if = "Option::is_none")]
326    #[ts(optional, type = "Record<string, unknown>")]
327    metadata: Option<serde_json::Value>,
328}
329
330/// What `account.oauth.start` answers: `{ sessionId, status }`, or `{ error }`.
331#[derive(serde::Serialize, ts_rs::TS)]
332#[ts(export, export_to = "../../../frontend/types/rpc/")]
333#[serde(rename_all = "camelCase")]
334pub struct AccountOAuthStartResult {
335    #[serde(skip_serializing_if = "Option::is_none")]
336    #[ts(optional)]
337    session_id: Option<String>,
338    /// `oauth_status_wire`'s shape, which the frontend models as OAuthFlowStatus.
339    #[serde(skip_serializing_if = "Option::is_none")]
340    #[ts(optional, type = "import(\"@/app/store/rpc-api/types\").OAuthFlowStatus")]
341    status: Option<serde_json::Value>,
342    #[serde(skip_serializing_if = "Option::is_none")]
343    #[ts(optional)]
344    error: Option<String>,
345}
346
347/// `github.installations`: the installations of the GitHub App this account is linked to.
348fn register_github_installations(engine: &Arc<WshRpcEngine>, state: &AppState) {
349    let mstore = state.id_store.clone();
350    let identity_store = state.identity_store.clone();
351    engine.register_typed(
352        COMMAND_GITHUB_INSTALLATIONS,
353        move |req: crate::identity::github_installs::GithubInstallationsReq, _ctx| {
354            let mstore = mstore.clone();
355            let identity_store = identity_store.clone();
356            async move { Ok(crate::identity::github_installs::run(&mstore, &identity_store, req).await) }
357        },
358    );
359}
360
361pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
362    register_accounts(engine, state);
363    register_oauth(engine, state);
364    register_agent_links(engine, state);
365    register_named_agents(engine, state);
366}
367
368/// Identity account CRUD. `id_store` routes to shared/store.db when available so accounts survive version
369/// upgrades, and falls back to `mstore` transparently.
370fn register_accounts(engine: &Arc<WshRpcEngine>, state: &AppState) {
371    let (mstore, identity_store, broker) = (state.id_store.clone(), state.identity_store.clone(), state.broker.clone());
372    {
373        let (mstore, identity_store) = (mstore.clone(), identity_store.clone());
374        engine.register_typed(COMMAND_LIST_IDENTITY_ACCOUNTS, move |cmd: CommandListIdentityAccountsData, _ctx| {
375            accounts::list_identity_accounts(mstore.clone(), identity_store.clone(), cmd.provider)
376        });
377    }
378    {
379        let mstore = mstore.clone();
380        engine.register_typed(COMMAND_GET_IDENTITY_ACCOUNT, move |cmd: CommandGetIdentityAccountData, _ctx| {
381            let mstore = mstore.clone();
382            async move { accounts::get_identity_account(&mstore, &cmd.id) }
383        });
384    }
385    // `Value` request: callers send a partial account (generated-manifest.json keeps `Partial<IdentityAccount>`),
386    // which is parsed into an `IdentityAccount`.
387    {
388        let (mstore, identity_store, broker) = (mstore.clone(), identity_store.clone(), broker.clone());
389        engine.register_typed(COMMAND_UPSERT_IDENTITY_ACCOUNT, move |data: serde_json::Value, _ctx| {
390            let (mstore, identity_store, broker) = (mstore.clone(), identity_store.clone(), broker.clone());
391            async move { accounts::upsert_identity_account(&mstore, &identity_store, &broker, data) }
392        });
393    }
394    // `Value` request, parsed into `VerifyKeyReq`; the stub keeps its type.
395    {
396        let (mstore, identity_store, broker) = (mstore.clone(), identity_store.clone(), broker.clone());
397        engine.register_typed(COMMAND_ACCOUNT_KEY_VERIFY, move |data: serde_json::Value, _ctx| {
398            accounts::verify_account_key(mstore.clone(), identity_store.clone(), broker.clone(), data)
399        });
400    }
401    engine.register_typed(COMMAND_DELETE_IDENTITY_ACCOUNT, move |cmd: CommandDeleteIdentityAccountData, _ctx| {
402        let (mstore, identity_store, broker) = (mstore.clone(), identity_store.clone(), broker.clone());
403        async move { super::identity_delete::delete_identity_account(&mstore, &identity_store, &broker, &cmd.id, cmd.require_revoke).await }
404    });
405}
406
407/// Service OAuth, and the GitHub connection that rides on it.
408fn register_oauth(engine: &Arc<WshRpcEngine>, state: &AppState) {
409    let (mstore, identity_store) = (state.id_store.clone(), state.identity_store.clone());
410    {
411        let (mstore, identity_store) = (mstore.clone(), identity_store.clone());
412        // `Value` request, parsed into `OAuthStartReq`; the stub keeps its type.
413        engine.register_typed(COMMAND_ACCOUNT_OAUTH_START, move |data: serde_json::Value, _ctx| {
414            oauth::start_oauth(mstore.clone(), identity_store.clone(), data)
415        });
416    }
417    engine.register_typed(COMMAND_ACCOUNT_OAUTH_CLIENT_GET, move |req: OAuthClientReq, _ctx| oauth::oauth_client_info(req));
418    engine.register_typed(COMMAND_ACCOUNT_OAUTH_CLIENT_CLEAR, move |req: OAuthClientReq, _ctx| oauth::clear_oauth_client(req));
419    engine.register_typed(COMMAND_ACCOUNT_OAUTH_POLL, move |req: OAuthSessionReq, _ctx| async move { oauth::poll_oauth(&req) });
420    engine.register_typed(COMMAND_ACCOUNT_OAUTH_CANCEL, move |req: OAuthSessionReq, _ctx| async move { Ok(oauth::cancel_oauth(&req)) });
421    // What the broker says about the GitHub connection; a grant it says is gone marks the brokered account as
422    // needing to be connected again (spec §5.7).
423    engine.register_typed(COMMAND_GITHUB_CONNECTION, move |_req: GithubConnectionReq, _ctx| {
424        let (mstore, identity_store) = (mstore.clone(), identity_store.clone());
425        async move { Ok(crate::identity::github_connect::sync_connection(&mstore, &identity_store).await) }
426    });
427    register_github_installations(engine, state);
428}
429
430/// The agent ↔ identity junction.
431fn register_agent_links(engine: &Arc<WshRpcEngine>, state: &AppState) {
432    let deps = Arc::new(links::LinkDeps {
433        identity_store: state.identity_store.clone(),
434        broker: state.broker.clone(),
435        panes: state.mstore.clone(),
436        event_bus: state.event_bus.clone(),
437    });
438    {
439        let deps = deps.clone();
440        engine.register_typed(COMMAND_LINK_AGENT_IDENTITY, move |cmd: CommandLinkAgentIdentityData, _ctx| {
441            let deps = deps.clone();
442            async move { links::link_agent_identity(&deps, &cmd) }
443        });
444    }
445    {
446        let deps = deps.clone();
447        engine.register_typed(COMMAND_UNLINK_AGENT_IDENTITY, move |cmd: CommandUnlinkAgentIdentityData, _ctx| {
448            let deps = deps.clone();
449            async move { links::unlink_agent_identity(&deps, &cmd) }
450        });
451    }
452    {
453        let deps = deps.clone();
454        engine.register_typed(COMMAND_LIST_AGENT_IDENTITIES, move |cmd: CommandListAgentIdentitiesData, _ctx| {
455            let deps = deps.clone();
456            async move {
457                deps.identity_store.agent_identity_list_for_agent(&cmd.agent_id).map_err(|e| format!("listagentidentities: {e}"))
458            }
459        });
460    }
461    // Every direct link across every agent: see the constant's doc comment.
462    engine.register_typed(COMMAND_LIST_ALL_AGENT_IDENTITIES, move |_req: CommandListAllAgentIdentitiesData, _ctx| {
463        let deps = deps.clone();
464        async move { deps.identity_store.agent_identity_list_all().map_err(|e| format!("listallagentidentities: {e}")) }
465    });
466}
467
468/// Named agent continuation (v8).
469fn register_named_agents(engine: &Arc<WshRpcEngine>, state: &AppState) {
470    let (mstore, id_store, identity_store) = (state.mstore.clone(), state.id_store.clone(), state.identity_store.clone());
471    let broker = state.broker.clone();
472    {
473        let mstore = mstore.clone();
474        engine.register_typed(COMMAND_LIST_NAMED_AGENTS, move |data: serde_json::Value, _ctx| {
475            let (mstore, id_store, identity_store) = (mstore.clone(), id_store.clone(), identity_store.clone());
476            async move { named_agents::list_named_agents(&mstore, &id_store, &identity_store, data) }
477        });
478    }
479    engine.register_typed(COMMAND_HIDE_NAMED_AGENT, move |cmd: CommandHideNamedAgentData, _ctx| {
480        let (mstore, broker) = (mstore.clone(), broker.clone());
481        async move { named_agents::hide_named_agent(&mstore, &broker, &cmd.id) }
482    });
483}
484
485#[cfg(test)]
486mod oauth_rpc_tests {
487    use super::*;
488    use crate::identity::oauth_client::OAuthStatus;
489    use crate::identity::oauth_tokens::ClientMode;
490
491    #[test]
492    fn a_start_reads_the_saved_client_unless_it_brings_one_or_asks_for_agentmuxs_own() {
493        let plain: OAuthStartReq = serde_json::from_value(json!({ "provider": "github" })).unwrap();
494        let builtin: OAuthStartReq = serde_json::from_value(json!({ "provider": "github", "useBuiltinClient": true })).unwrap();
495        let with_client: OAuthStartReq = serde_json::from_value(json!({ "provider": "github", "clientId": "Iv1.mine" })).unwrap();
496        let none = byo_from_req(&plain).unwrap();
497        let some = byo_from_req(&with_client).unwrap();
498        assert!(reads_saved_client(&plain, &none), "a request with no client uses the saved one, as before");
499        assert!(!reads_saved_client(&builtin, &none), "the App choice must not run with a saved client of the person's own");
500        assert!(!reads_saved_client(&with_client, &some), "a client sent with the request is the one used");
501    }
502
503    #[test]
504    fn a_start_request_without_the_new_fields_still_parses() {
505        let old: OAuthStartReq =
506            serde_json::from_value(json!({ "provider": "google", "name": "Work", "clientId": "cid" })).unwrap();
507        assert!(old.scopes.is_empty() && old.account_id.is_none() && old.save_client.is_none());
508        let byo = byo_from_req(&old).unwrap().unwrap();
509        assert_eq!((byo.client_id.as_str(), byo.mode, byo.client_secret), ("cid", ClientMode::Byo, None));
510    }
511
512    #[test]
513    fn a_start_request_can_turn_a_service_on_for_an_existing_account() {
514        let req: OAuthStartReq = serde_json::from_value(json!({
515            "provider": "google",
516            "accountId": "acc-1",
517            "scopes": ["https://www.googleapis.com/auth/calendar.events.readonly"],
518            "clientId": " cid ", "clientSecret": "", "clientMode": "workspace", "saveClient": false,
519        }))
520        .unwrap();
521        assert_eq!(req.account_id.as_deref(), Some("acc-1"));
522        assert_eq!(req.scopes.len(), 1);
523        assert_eq!(req.save_client, Some(false));
524        let byo = byo_from_req(&req).unwrap().unwrap();
525        assert_eq!((byo.client_id.as_str(), byo.mode, byo.client_secret), ("cid", ClientMode::Workspace, None));
526        // A blank client id means "none passed"; an unknown mode is refused.
527        let blank: OAuthStartReq = serde_json::from_value(json!({ "provider": "google", "clientId": "  " })).unwrap();
528        assert!(byo_from_req(&blank).unwrap().is_none());
529        let bad: OAuthStartReq =
530            serde_json::from_value(json!({ "provider": "google", "clientId": "c", "clientMode": "builtin" })).unwrap();
531        assert!(byo_from_req(&bad).is_err());
532    }
533
534    #[test]
535    fn success_reports_the_granted_and_missing_scopes_and_email() {
536        let wire = oauth_status_wire(&OAuthStatus::Success {
537            account_id: "acc-1".into(),
538            granted_scopes: vec!["openid".into()],
539            missing_scopes: vec!["https://www.googleapis.com/auth/calendar.events".into()],
540            email: Some("me@example.com".into()),
541        });
542        assert_eq!(
543            wire,
544            json!({
545                "status": "success", "accountId": "acc-1", "grantedScopes": ["openid"],
546                "missingScopes": ["https://www.googleapis.com/auth/calendar.events"], "email": "me@example.com",
547            })
548        );
549    }
550
551    #[test]
552    fn only_a_failed_revoke_with_require_revoke_keeps_the_account() {
553        let failed = json!({ "outcome": "failed", "detail": "offline" });
554        assert!(revoke_keeps_account(&failed, true));
555        assert!(!revoke_keeps_account(&failed, false), "by default the account is deleted anyway");
556        assert!(!revoke_keeps_account(&json!({ "outcome": "revoked" }), true));
557        assert!(!revoke_keeps_account(&serde_json::Value::Null, true));
558        // The old request shape still parses, and doesn't require the revoke.
559        let old: CommandDeleteIdentityAccountData = serde_json::from_value(json!({ "id": "acc-1" })).unwrap();
560        assert!(!old.require_revoke);
561    }
562
563    #[test]
564    fn the_delete_result_carries_the_revoke_outcome() {
565        let r = DeleteIdentityAccountResult {
566            deleted: true,
567            affected_agents: vec![],
568            cleanup: json!({ "outcome": "removed" }),
569            revoke: json!({ "outcome": "revoked" }),
570        };
571        let v = serde_json::to_value(r).unwrap();
572        assert_eq!(v["revoke"]["outcome"], "revoked");
573        assert_eq!(v["cleanup"]["outcome"], "removed");
574    }
575
576    #[tokio::test]
577    async fn the_saved_client_commands_are_registered_typed() {
578        let state = crate::server::tests::test_state();
579        let (engine, _rx) = crate::backend::rpc::engine::WshRpcEngine::new();
580        register(&engine, &state);
581        let schema = engine.schema_json();
582        let rows = schema.as_array().unwrap();
583        let row = |c: &str| rows.iter().find(|r| r["command"] == c).unwrap_or_else(|| panic!("{c} missing")).clone();
584        assert_eq!(row(COMMAND_ACCOUNT_OAUTH_CLIENT_GET)["responseName"], "AccountOAuthClientInfo");
585        assert_eq!(row(COMMAND_ACCOUNT_OAUTH_CLIENT_CLEAR)["responseName"], "AccountOAuthClientClearResult");
586        assert_eq!(row(COMMAND_ACCOUNT_OAUTH_CLIENT_CLEAR)["requestName"], "OAuthClientReq");
587    }
588}
589
590#[cfg(test)]
591mod ambient_home_dir_binding_tests {
592    use super::*;
593    use crate::server::tests::test_state;
594
595    fn make_account(provider: &str, secret_ref: SecretRef) -> IdentityAccount {
596        IdentityAccount {
597            id: "acct-1".to_string(),
598            name: "test".to_string(),
599            provider: provider.to_string(),
600            kind: "pat".to_string(),
601            display_name: String::new(),
602            secret_ref,
603            context: serde_json::json!({}),
604            status: "unknown".to_string(),
605            created_at: 0,
606            updated_at: 0,
607        }
608    }
609
610    // docs/specs/SPEC_BLOCK_AMBIENT_HOME_DIR_IDENTITY_BINDING_2026_08_25.md.
611    // Uses the REAL get_home_dir() (not a mock) — same reasoning as the
612    // inject.rs spawn-time test, deterministic regardless of whether
613    // ~/.claude exists on the test machine.
614    #[test]
615    fn refuses_oauth_config_dir_pointed_at_the_ambient_home() {
616        let ambient = crate::backend::base::get_home_dir()
617            .join(".claude")
618            .to_string_lossy()
619            .into_owned();
620        let account = make_account("claude", SecretRef::OAuthConfigDir { dir: ambient.clone() });
621
622        let err = reject_ambient_home_dir_binding(&account)
623            .expect_err("must refuse an account bound to the ambient home dir");
624        assert!(err.contains(&ambient), "error should name the offending dir: {err}");
625        assert!(err.contains("claude"), "error should name the provider: {err}");
626    }
627
628    #[test]
629    fn allows_oauth_config_dir_pointed_at_an_isolated_dir() {
630        let isolated = crate::backend::base::get_home_dir()
631            .join(".agentmux")
632            .join("shared")
633            .join("identities")
634            .join("some-id")
635            .join("claude")
636            .to_string_lossy()
637            .into_owned();
638        let account = make_account("claude", SecretRef::OAuthConfigDir { dir: isolated });
639
640        assert!(reject_ambient_home_dir_binding(&account).is_ok());
641    }
642
643    #[test]
644    fn allows_non_oauth_secret_refs_unconditionally() {
645        let account = make_account("github", SecretRef::Env { env_var: "GITHUB_TOKEN".to_string() });
646        assert!(reject_ambient_home_dir_binding(&account).is_ok());
647    }
648
649    #[test]
650    fn allows_an_unknown_provider_id_unconditionally() {
651        // get_provider() returns None for an unrecognized id — the guard
652        // has nothing to check against, so it must not block (matches the
653        // existing "unknown provider" skip behavior elsewhere in this
654        // codebase, not a new failure mode).
655        let account = make_account(
656            "not-a-real-provider",
657            SecretRef::OAuthConfigDir { dir: "/tmp/whatever".to_string() },
658        );
659        assert!(reject_ambient_home_dir_binding(&account).is_ok());
660    }
661
662    /// `hidenamedagent` is recorded in the engine's schema with its exact
663    /// type names. `HideNamedAgentResult` didn't exist before this
664    /// migration; the handler used to answer with an anonymous
665    /// `json!({"hidden": ..})`.
666    #[tokio::test]
667    async fn register_typed_records_hidenamedagent() {
668        let state = test_state();
669        let (engine, _rx) = crate::backend::rpc::engine::WshRpcEngine::new();
670        register(&engine, &state);
671        let schema = engine.schema_json();
672        let rows = schema.as_array().unwrap();
673        let row = rows
674            .iter()
675            .find(|r| r["command"] == COMMAND_HIDE_NAMED_AGENT)
676            .expect("hidenamedagent missing from the schema");
677        assert_eq!(row["requestName"], "CommandHideNamedAgentData");
678        assert_eq!(row["responseName"], "HideNamedAgentResult");
679        // listnamedagents keeps a loose `Value` request (a malformed body means the
680        // defaults), but its response is recorded, so the generated stub returns NamedAgentRow.
681        let list = rows
682            .iter()
683            .find(|r| r["command"] == COMMAND_LIST_NAMED_AGENTS)
684            .expect("listnamedagents missing from the schema");
685        assert_eq!(list["requestName"], "Value");
686        assert_eq!(list["responseTs"]["name"], "Array<NamedAgentRow>");
687    }
688}