agentmux_srv/server/identity_auth_spawn.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Subprocess spawn/drain engine for the pre-launch OAuth flow.
5//!
6//! Split out of `identity_handlers.rs` (module-organization pass, see
7//! `docs/specs/PLAN_LOGIN_SINGLE_PATH_CONSOLIDATION_2026_07_20.md`) —
8//! owns `spawn_auth_cli` (plain piped-stdio spawn), `spawn_auth_cli_pty`
9//! (PTY-backed spawn for providers whose auth subcommand requires an
10//! interactive TTY), and `confirm_authenticated` (the shared
11//! authCheckCommand probe both spawn paths use). Both spawn paths call
12//! into `identity_auth_persist::persist_oauth_success` on the OAuth-
13//! success path.
14
15use std::sync::Arc;
16
17use crate::backend::mps::Broker;
18use crate::backend::storage::store::Store;
19
20#[path = "identity_auth_spawn_steps.rs"]
21mod steps;
22
23/// Spawn the provider's auth-login CLI and drive the session through
24/// to a terminal state. Background-only — returns immediately. The
25/// drain task feeds stdout+stderr lines into
26/// `AuthSessionManager::record_line`; on a login-success pattern OR
27/// child exit, runs the provider's authCheckCommand to confirm and
28/// transitions to Success or Failed.
29///
30/// On the success path (CLI exited cleanly + authCheckCommand passed),
31/// persists a standalone `IdentityAccount` (`persist_oauth_direct_account`)
32/// with `SecretRef::OAuthConfigDir` pointing at `bundle_dir` (the
33/// account's own isolation dir — see `compute_and_ensure_account_dir`),
34/// status `valid`. `account_id` is the id minted/reused for that account.
35/// After this point, future launches of any agent linked to the account
36/// resolve through `inject_identity_env`'s oauth-class dispatch and reuse
37/// the same CLI-managed tokens.
38///
39/// `into_bundle_id`/`direct_account` are vestigial parameters kept only
40/// so the wire request shape and call sites don't need touching — bundle
41/// mode (binding into `db_identity_bundles`) was retired in Phase 4c of
42/// SPEC_PRESET_TO_BUNDLE_REFACTOR_2026_07_02.md; `persist_oauth_success`
43/// always takes the direct-account path now.
44#[allow(clippy::too_many_arguments)]
45pub(crate) fn spawn_auth_cli(
46 mgr: Arc<crate::identity::auth_session::AuthSessionManager>,
47 mstore: Arc<Store>,
48 identity_store: Arc<Store>,
49 broker: Arc<Broker>,
50 session_id: String,
51 provider_id: String,
52 into_bundle_id: Option<String>,
53 bundle_dir: Option<String>,
54 direct_account: bool,
55 account_id: String,
56 cli_path: String,
57 auth_login_args: Vec<String>,
58 auth_check_args: Vec<String>,
59 auth_env: std::collections::HashMap<String, String>,
60 requires_tty: bool,
61) {
62 use tokio::sync::mpsc;
63
64 // Channel for SubmitAuthCallback → CLI stdin forwarding.
65 // Buffer of 4 is enough — only one URL per session in normal use.
66 let (stdin_tx, stdin_rx) = mpsc::channel::<String>(4);
67
68 let login = Arc::new(steps::Login {
69 mgr,
70 mstore,
71 identity_store,
72 broker,
73 session_id,
74 provider_id,
75 into_bundle_id,
76 bundle_dir,
77 direct_account,
78 account_id,
79 cli_path,
80 auth_login_args,
81 auth_check_args,
82 auth_env,
83 });
84
85 // PTY branch: providers like OpenClaw whose auth subcommand
86 // refuses to run when `isatty()==0`. Spawn via portable_pty so the
87 // child sees an interactive terminal, feed PTY output through the
88 // same record_line matcher the pipes path uses. Stdout/stderr are
89 // merged into the single PTY stream — record_line handles both as
90 // identical input.
91 if requires_tty {
92 steps::spawn_auth_cli_pty(login, stdin_tx, stdin_rx);
93 return;
94 }
95
96 steps::spawn_piped(login, stdin_tx, stdin_rx);
97}
98
99/// How long a provider's auth-status check may take (`confirm_authenticated`).
100const AUTH_CHECK_TIMEOUT_SECS: u64 = 30;
101
102/// Run the provider's auth-check subcommand and return true if it
103/// exits 0. Failure modes (binary missing, network error, etc.) are
104/// all treated as "not authenticated" — the caller will then either
105/// keep waiting (drain task loop) or transition to Failed (exit
106/// fallback).
107async fn confirm_authenticated(
108 cli_path: &str,
109 args: &[String],
110 env: &std::collections::HashMap<String, String>,
111) -> bool {
112 use std::process::Stdio;
113 // Through the shim parser (`make_cli_cmd`): a raw npm `.cmd` shim spawned
114 // with piped stdio can drop its arguments or never run the CLI, which
115 // would report a good login as failed. It also sets CREATE_NO_WINDOW, so
116 // the probe, polled during an auth flow, flashes no console.
117 let mut c = agentmux_common::make_cli_cmd(cli_path);
118 // The third spawn of this same provider CLI in this file — the auth-check
119 // poll driven from the OAuth drain loop. Same strict policy as the other
120 // two. (ReAgent P0, round 4, on #3326.)
121 crate::backend::pane_env::sanitize_external_command(&mut c);
122 c.args(args)
123 .envs(env)
124 .stdin(Stdio::null())
125 .stdout(Stdio::null())
126 .stderr(Stdio::null())
127 .kill_on_drop(true);
128 // A status check that hangs counts as not logged in (and is killed on drop).
129 match tokio::time::timeout(std::time::Duration::from_secs(AUTH_CHECK_TIMEOUT_SECS), c.status()).await {
130 Ok(Ok(s)) => s.success(),
131 _ => false,
132 }
133}
134
135#[cfg(test)]
136#[path = "identity_auth_spawn_tests.rs"]
137mod tests;