Skip to main content

agentmux_srv/server/
identity_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pre-launch OAuth flow RPC handlers.
5//!
6//! Four commands per `docs/specs/SPEC_PRE_LAUNCH_OAUTH_FLOW_2026_05_14.md` §7
7//! (request types named after that section's RPCs), plus
8//! `identity.ensureaccountdir`:
9//!
10//!   * `auth.start`           — `StartProviderAuthReq`
11//!   * `auth.poll`            — `PollProviderAuthReq`
12//!   * `auth.submitcallback`  — `SubmitAuthCallbackReq`
13//!   * `auth.cancel`          — `CancelProviderAuthReq`
14//!
15//! The spec's fifth, `auth.submitapikey`, was removed: it was never built, and
16//! API-key accounts are added through `account.key.verify` and
17//! `upsertidentityaccount` instead.
18//!
19//! This module owns the RPC surface and dispatches into
20//! `crate::identity::auth_session::AuthSessionManager`. `auth.start` also
21//! spawns the provider CLI (`spawn_auth_cli`), which feeds stdout lines
22//! into the session via `record_line`.
23//!
24//! Split across four files (module-organization pass, see
25//! `docs/specs/PLAN_LOGIN_SINGLE_PATH_CONSOLIDATION_2026_07_20.md`):
26//! this file owns the RPC surface (wire types + `register_identity_handlers`);
27//! `identity_auth_spawn` owns the subprocess spawn/drain engine
28//! (`spawn_auth_cli`, `spawn_auth_cli_pty`, `confirm_authenticated`);
29//! `identity_auth_dirs` owns filesystem/directory provisioning
30//! (`compute_and_ensure_bundle_dir`, `compute_and_ensure_account_dir`);
31//! `identity_auth_persist` owns `IdentityAccount` persistence on OAuth
32//! success (`persist_oauth_direct_account`, `persist_oauth_success`).
33
34use std::sync::Arc;
35
36use serde::{Deserialize, Serialize};
37
38use crate::backend::rpc::engine::WshRpcEngine;
39
40use super::identity_auth_dirs::{caller_auth_dir, compute_and_ensure_account_dir, compute_and_ensure_bundle_dir};
41use super::identity_auth_spawn::spawn_auth_cli;
42use super::AppState;
43
44pub const COMMAND_AUTH_START: &str = "auth.start";
45pub const COMMAND_AUTH_POLL: &str = "auth.poll";
46pub const COMMAND_AUTH_SUBMIT_CALLBACK: &str = "auth.submitcallback";
47pub const COMMAND_AUTH_CANCEL: &str = "auth.cancel";
48/// Mints (or reuses) a per-account isolated config dir without spawning any
49/// CLI — a standalone entry point onto `compute_and_ensure_account_dir` for
50/// callers that need the dir BEFORE a credential exists in it — today the
51/// terminal-login tier, which must know where to point the login before it
52/// opens a terminal. (It previously also served `seed_provider_auth_from_global`,
53/// the copy-from-personal-`~/.claude` path removed 2026-08-31.) See
54/// `docs/specs/PLAN_LOGIN_SINGLE_PATH_CONSOLIDATION_2026_07_20.md` §7 —
55/// "single point, not global": every credential-bearing dir a running agent
56/// reads from must belong to a real `IdentityAccount` row, never the shared
57/// default dir.
58pub const COMMAND_ENSURE_ACCOUNT_DIR: &str = "identity.ensureaccountdir";
59
60pub use crate::backend::rpc_types::StartProviderAuthReq;
61
62#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
63#[ts(export, export_to = "../../../frontend/types/rpc/")]
64#[serde(rename_all = "camelCase")]
65pub struct PollProviderAuthReq {
66    pub session_id: String,
67}
68
69#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
70#[ts(export, export_to = "../../../frontend/types/rpc/")]
71#[serde(rename_all = "camelCase")]
72pub struct SubmitAuthCallbackReq {
73    pub session_id: String,
74    /// The redirect URL the user pasted back (browser-didn't-open
75    /// fallback). The handler writes it to the spawned CLI's stdin.
76    pub callback_url: String,
77}
78
79#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
80#[ts(export, export_to = "../../../frontend/types/rpc/")]
81#[serde(rename_all = "camelCase")]
82pub struct CancelProviderAuthReq {
83    pub session_id: String,
84}
85
86#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
87#[ts(export, export_to = "../../../frontend/types/rpc/")]
88#[serde(rename_all = "camelCase")]
89pub struct AckResp {
90    pub success: bool,
91    #[serde(skip_serializing_if = "Option::is_none")]
92    #[ts(optional)]
93    pub error: Option<String>,
94}
95
96#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
97#[ts(export, export_to = "../../../frontend/types/rpc/")]
98#[serde(rename_all = "camelCase")]
99pub struct EnsureAccountDirReq {
100    pub provider_id: String,
101    /// Non-empty to resolve an already-minted account's own dir
102    /// (reconnect-in-place); empty mints a fresh account id.
103    #[serde(default)]
104    pub existing_account_id: String,
105}
106
107#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
108#[ts(export, export_to = "../../../frontend/types/rpc/")]
109#[serde(rename_all = "camelCase")]
110pub struct EnsureAccountDirResp {
111    pub account_id: String,
112    /// `None` when the provider isn't oauth-class or the dir couldn't be
113    /// resolved/created — same soft-failure contract as `auth.start`'s
114    /// internal use of `compute_and_ensure_account_dir`.
115    #[serde(skip_serializing_if = "Option::is_none")]
116    #[ts(optional)]
117    pub dir: Option<String>,
118}
119
120/// Start a provider login: the body of `auth.start`, also what a remote `identity.signin.start` runs.
121/// Spawns the CLI and returns at once; the caller polls the session.
122pub(crate) fn start_provider_auth(state: &AppState, req: StartProviderAuthReq) -> crate::identity::auth_session::StartSessionResult {
123    let mgr = state.auth_session_manager.clone();
124    let mstore = state.id_store.clone();
125    let identity_store = state.identity_store.clone();
126    let broker = state.broker.clone();
127    tracing::info!(
128        provider_id = %req.provider_id,
129        cli_path = %req.cli_path,
130        into_bundle_id = ?req.into_bundle_id,
131        direct_account = req.direct_account,
132        "auth.start"
133    );
134    // `direct_account` mints/reuses an account id and resolves
135    // its own isolation dir, mirroring the dir into `auth_env`
136    // under the provider's `auth_config_dir_env_var` (e.g.
137    // `CLAUDE_CONFIG_DIR`), overriding whatever the frontend
138    // computed. No frontend caller sets it since the launch
139    // modal's `AuthFlowController` was removed; the agent pane's
140    // login takes the other branch and persists the account
141    // itself, with its own dir in `auth_env`.
142    //
143    // `into_bundle_id` in that branch is vestigial — bundle mode
144    // was retired in Phase 4c of
145    // SPEC_PRESET_TO_BUNDLE_REFACTOR_2026_07_02.md — kept only
146    // so this wire shape and its call sites don't need touching.
147    //
148    // Errors (path resolve, mkdir) log + fall back to the
149    // legacy env — never abort `auth.start` over a dir issue.
150    // Mirrors the `inject_identity_env` pattern.
151    let mut auth_env = req.auth_env;
152    let (account_id, bundle_dir) = if req.direct_account {
153        let (account_id, dir) = compute_and_ensure_account_dir(
154            &mstore,
155            &req.existing_account_id,
156            &req.provider_id,
157            &mut auth_env,
158        );
159        (account_id, dir)
160    } else {
161        let dir = compute_and_ensure_bundle_dir(
162            req.into_bundle_id.as_deref(),
163            &req.provider_id,
164            &mut auth_env,
165        );
166        (String::new(), dir)
167    };
168    // One live login per account directory (`start_session`): srv's
169    // own, or the one the caller chose when it persists the
170    // account itself.
171    let exclusive_key = bundle_dir
172        .clone()
173        .or_else(|| caller_auth_dir(&req.provider_id, &auth_env));
174    let r = mgr.start_session(req.provider_id.clone(), exclusive_key);
175    spawn_auth_cli(
176        mgr,
177        mstore,
178        identity_store,
179        broker,
180        r.session_id.clone(),
181        req.provider_id,
182        req.into_bundle_id,
183        bundle_dir,
184        req.direct_account,
185        account_id,
186        req.cli_path,
187        req.auth_login_args,
188        req.auth_check_args,
189        auth_env,
190        req.requires_tty,
191    );
192    r
193}
194
195pub fn register_identity_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
196    let mstore_for_ensure_dir = state.id_store.clone();
197    let state_for_start = state.clone();
198    engine.register_typed(
199        COMMAND_AUTH_START,
200        move |req: StartProviderAuthReq, _ctx| {
201            let state = state_for_start.clone();
202            async move { Ok(start_provider_auth(&state, req)) }
203        },
204    );
205
206    let mgr = state.auth_session_manager.clone();
207    engine.register_typed(
208        COMMAND_AUTH_POLL,
209        move |req: PollProviderAuthReq, _ctx| {
210            let mgr = mgr.clone();
211            async move {
212                let snap = mgr
213                    .poll_session(&req.session_id)
214                    .ok_or_else(|| format!("auth.poll: unknown session {}", req.session_id))?;
215                Ok(snap)
216            }
217        },
218    );
219
220    let mgr = state.auth_session_manager.clone();
221    engine.register_typed(
222        COMMAND_AUTH_CANCEL,
223        move |req: CancelProviderAuthReq, _ctx| {
224            let mgr = mgr.clone();
225            async move {
226                let ok = mgr.cancel_session(&req.session_id);
227                Ok(AckResp {
228                    success: ok,
229                    error: if ok {
230                        None
231                    } else {
232                        Some(format!("unknown or already-terminal session: {}", req.session_id))
233                    },
234                })
235            }
236        },
237    );
238
239    let mgr = state.auth_session_manager.clone();
240    engine.register_typed(
241        COMMAND_AUTH_SUBMIT_CALLBACK,
242        move |req: SubmitAuthCallbackReq, _ctx| {
243            let mgr = mgr.clone();
244            async move {
245                let delivered = mgr
246                    .send_to_stdin(&req.session_id, req.callback_url)
247                    .await;
248                Ok(AckResp {
249                    success: delivered,
250                    error: if delivered {
251                        None
252                    } else {
253                        Some(format!(
254                            "no stdin sender for session {} (process exited or session unknown)",
255                            req.session_id
256                        ))
257                    },
258                })
259            }
260        },
261    );
262
263    engine.register_typed(
264        COMMAND_ENSURE_ACCOUNT_DIR,
265        move |req: EnsureAccountDirReq, _ctx| {
266            let mstore = mstore_for_ensure_dir.clone();
267            async move {
268                let mut auth_env = std::collections::HashMap::new();
269                let (account_id, dir) = compute_and_ensure_account_dir(
270                    &mstore,
271                    &req.existing_account_id,
272                    &req.provider_id,
273                    &mut auth_env,
274                );
275                let resp = EnsureAccountDirResp { account_id, dir };
276                Ok(resp)
277            }
278        },
279    );
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    // Request shape parsing tests — verify the wire contract matches
287    // what the frontend (PR B) will send. The end-to-end RPC-engine
288    // invocation is covered at the integration level once the CLI
289    // spawn lands; the underlying AuthSessionManager behaviour is
290    // covered in `identity::auth_session::tests`.
291
292    #[test]
293    fn start_req_parses_minimal() {
294        let v = serde_json::json!({
295            "providerId": "claude",
296            "cliPath": "/usr/bin/claude",
297            "authLoginArgs": ["login"],
298            "authCheckArgs": ["whoami"]
299        });
300        let r: StartProviderAuthReq = serde_json::from_value(v).unwrap();
301        assert_eq!(r.provider_id, "claude");
302        assert_eq!(r.cli_path, "/usr/bin/claude");
303        assert_eq!(r.auth_login_args, vec!["login"]);
304        assert_eq!(r.auth_check_args, vec!["whoami"]);
305        assert!(r.into_bundle_id.is_none());
306        assert!(r.auth_env.is_empty());
307    }
308
309    #[test]
310    fn start_req_parses_with_bundle_id() {
311        let v = serde_json::json!({
312            "providerId": "codex",
313            "cliPath": "/usr/bin/codex",
314            "authLoginArgs": ["auth", "login"],
315            "authCheckArgs": ["auth", "status"],
316            "authEnv": { "FOO": "bar" },
317            "intoBundleId": "bundle-1"
318        });
319        let r: StartProviderAuthReq = serde_json::from_value(v).unwrap();
320        assert_eq!(r.provider_id, "codex");
321        assert_eq!(r.into_bundle_id.as_deref(), Some("bundle-1"));
322        assert_eq!(r.auth_env.get("FOO").map(String::as_str), Some("bar"));
323    }
324
325    #[test]
326    fn poll_req_round_trips() {
327        let v = serde_json::json!({ "sessionId": "auth-xyz" });
328        let r: PollProviderAuthReq = serde_json::from_value(v).unwrap();
329        assert_eq!(r.session_id, "auth-xyz");
330    }
331
332    #[test]
333    fn submit_callback_req_round_trips() {
334        let v = serde_json::json!({
335            "sessionId": "auth-xyz",
336            "callbackUrl": "https://example.com/cb?code=abc"
337        });
338        let r: SubmitAuthCallbackReq = serde_json::from_value(v).unwrap();
339        assert_eq!(r.session_id, "auth-xyz");
340        assert!(r.callback_url.contains("code=abc"));
341    }
342
343    #[test]
344    fn ack_resp_omits_error_when_success() {
345        let r = AckResp { success: true, error: None };
346        let v = serde_json::to_value(&r).unwrap();
347        assert_eq!(v, serde_json::json!({ "success": true }));
348    }
349
350    #[test]
351    fn ack_resp_includes_error_when_failure() {
352        let r = AckResp { success: false, error: Some("boom".into()) };
353        let v = serde_json::to_value(&r).unwrap();
354        assert_eq!(v, serde_json::json!({ "success": false, "error": "boom" }));
355    }
356
357    // ── Issue #1624 PR-C Part B: direct-account OAuth ─────────────
358
359    #[test]
360    fn start_req_parses_direct_account_fields() {
361        let v = serde_json::json!({
362            "providerId": "claude",
363            "cliPath": "/usr/bin/claude",
364            "authLoginArgs": ["login"],
365            "authCheckArgs": ["whoami"],
366            "directAccount": true,
367            "existingAccountId": "acc-1"
368        });
369        let r: StartProviderAuthReq = serde_json::from_value(v).unwrap();
370        assert!(r.direct_account);
371        assert_eq!(r.existing_account_id, "acc-1");
372    }
373
374    #[test]
375    fn start_req_direct_account_fields_default_when_absent() {
376        // Same minimal payload as start_req_parses_minimal — must still
377        // parse now that these two fields exist, defaulting to the
378        // legacy bundle-mode shape.
379        let v = serde_json::json!({
380            "providerId": "claude",
381            "cliPath": "/usr/bin/claude",
382            "authLoginArgs": ["login"],
383            "authCheckArgs": ["whoami"]
384        });
385        let r: StartProviderAuthReq = serde_json::from_value(v).unwrap();
386        assert!(!r.direct_account);
387        assert_eq!(r.existing_account_id, "");
388    }
389}
390
391// Request/result shape tests for the six auth/identity commands.
392#[cfg(test)]
393mod req_shape_tests {
394    use super::*;
395    use serde_json::json;
396
397    // auth.start is the one with real optionality. Four of its fields are
398    // #[serde(default)] on non-Option types, so they are omittable on the wire
399    // even though the generated binding marks them required -- the frontend
400    // derives the accurate shape (AuthStartInput). This pins the wire half,
401    // which TypeScript cannot check.
402    #[test]
403    fn auth_start_requires_only_four_fields() {
404        let minimal: StartProviderAuthReq = serde_json::from_value(json!({
405            "providerId": "claude",
406            "cliPath": "/usr/bin/claude",
407            "authLoginArgs": ["login"],
408            "authCheckArgs": ["whoami"],
409        }))
410        .expect("auth.start must accept just the four required fields");
411        assert!(minimal.into_bundle_id.is_none());
412        assert!(!minimal.direct_account);
413        assert_eq!(minimal.existing_account_id, "");
414        assert!(minimal.auth_env.is_empty());
415        assert!(!minimal.requires_tty);
416
417        assert!(
418            serde_json::from_value::<StartProviderAuthReq>(json!({"providerId": "c"})).is_err(),
419            "cliPath and the two arg lists have no defaults"
420        );
421    }
422
423    #[test]
424    fn the_session_id_commands_accept_their_payloads() {
425        serde_json::from_value::<PollProviderAuthReq>(json!({"sessionId": "s1"}))
426            .expect("auth.poll");
427        serde_json::from_value::<CancelProviderAuthReq>(json!({"sessionId": "s1"}))
428            .expect("auth.cancel");
429        serde_json::from_value::<SubmitAuthCallbackReq>(
430            json!({"sessionId": "s1", "callbackUrl": "http://localhost/cb"}),
431        )
432        .expect("auth.submitcallback");
433        serde_json::from_value::<EnsureAccountDirReq>(json!({"providerId": "claude"}))
434            .expect("identity.ensureaccountdir, existingAccountId omitted");
435
436        assert!(
437            serde_json::from_value::<PollProviderAuthReq>(json!({"session_id": "s1"})).is_err(),
438            "snake_case is not the wire format for these"
439        );
440    }
441
442    // AckResp.error and EnsureAccountDirResp.dir are both
443    // skip_serializing_if = "Option::is_none", so the key is OMITTED rather
444    // than nulled -- which is why the bindings say `error?` / `dir?`.
445    //
446    // Worth contrasting with InstallCancelResult in install_handlers.rs, which
447    // looks identical but writes an explicit null and is therefore
448    // `error: string | null`. Same-shaped Rust, different wire contract.
449    #[test]
450    fn the_ack_shapes_omit_their_optional_keys_rather_than_nulling_them() {
451        let ok = serde_json::to_value(AckResp { success: true, error: None }).expect("serializable");
452        assert_eq!(ok, json!({"success": true}));
453
454        let dir = serde_json::to_value(EnsureAccountDirResp {
455            account_id: "a1".to_string(),
456            dir: None,
457        })
458        .expect("serializable");
459        assert_eq!(dir, json!({"accountId": "a1"}));
460    }
461}