Skip to main content

agentmux_srv/server/app_api/
identity.rs

1use super::*;
2use crate::server::api_error::ApiError;
3
4/// `identity.self.accounts` and `identity.self.unlink`: the agent asking.
5#[derive(Debug, serde::Deserialize, ts_rs::TS)]
6#[ts(export, export_to = "../../../frontend/types/rpc/")]
7pub struct IdentitySelfAccountsReq {
8    pub agent_id: String,
9}
10
11/// `identity.self.accounts`: the provider accounts linked to the agent, with no secrets.
12#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
13#[ts(export, export_to = "../../../frontend/types/rpc/")]
14pub struct IdentitySelfAccountsResult {
15    pub accounts: Vec<IdentitySelfAccount>,
16}
17
18/// One linked account in `IdentitySelfAccountsResult`.
19#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
20#[ts(export, export_to = "../../../frontend/types/rpc/")]
21pub struct IdentitySelfAccount {
22    pub account_id: String,
23    pub provider: String,
24    pub name: String,
25    pub kind: String,
26    pub status: String,
27    pub masked_tail: String,
28    #[ts(type = "number")]
29    pub updated_at: i64,
30}
31
32/// `identity.account.upsert`: an account for the agent's own use, created or updated, and linked.
33#[derive(Debug, serde::Deserialize, ts_rs::TS)]
34#[ts(export, export_to = "../../../frontend/types/rpc/")]
35#[serde(rename_all = "snake_case")]
36pub struct IdentityAccountUpsertReq {
37    pub agent_id: String,
38    pub provider: String,
39    pub name: String,
40    #[serde(default)]
41    #[ts(as = "Option<String>", optional)]
42    pub kind: String,
43    pub secret: String,
44    #[serde(default)]
45    #[ts(as = "Option<bool>", optional)]
46    pub validate: bool,
47    #[serde(default)]
48    #[ts(as = "Option<String>", optional)]
49    pub account_id: String,
50}
51
52/// `identity.account.upsert`: the account as stored, and the validation result when one was asked for.
53#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
54#[ts(export, export_to = "../../../frontend/types/rpc/")]
55pub struct IdentityAccountUpsertResult {
56    pub account_id: String,
57    pub provider: String,
58    pub name: String,
59    #[ts(type = r#""valid" | "invalid" | "unknown""#)]
60    pub status: String,
61    pub masked_tail: String,
62    pub valid: bool,
63    pub error: Option<String>,
64}
65
66/// `identity.account.validate`: a stored account to probe, or a provider and secret to probe ad hoc.
67#[derive(Debug, Default, serde::Deserialize, ts_rs::TS)]
68#[ts(export, export_to = "../../../frontend/types/rpc/")]
69#[serde(rename_all = "snake_case")]
70pub struct IdentityAccountValidateReq {
71    #[serde(default)]
72    #[ts(as = "Option<String>", optional)]
73    pub agent_id: String,
74    #[serde(default)]
75    #[ts(as = "Option<String>", optional)]
76    pub account_id: String,
77    #[serde(default)]
78    #[ts(as = "Option<String>", optional)]
79    pub provider: String,
80    #[serde(default)]
81    #[ts(as = "Option<String>", optional)]
82    pub secret: String,
83}
84
85/// `identity.account.validate`: whether the provider accepted the key.
86#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
87#[ts(export, export_to = "../../../frontend/types/rpc/")]
88pub struct IdentityAccountValidateResult {
89    pub valid: bool,
90    #[ts(type = r#""valid" | "invalid""#)]
91    pub status: String,
92    pub masked_tail: String,
93    pub error: Option<String>,
94}
95
96impl IdentityAccountValidateResult {
97    fn of(outcome: crate::identity::key_validator::ValidationOutcome, masked_tail: String) -> Self {
98        IdentityAccountValidateResult {
99            valid: outcome.valid,
100            status: if outcome.valid { "valid" } else { "invalid" }.to_string(),
101            masked_tail,
102            error: outcome.error,
103        }
104    }
105}
106
107/// `identity.self.unlink`: the provider whose account to unlink from the agent.
108#[derive(Debug, serde::Deserialize, ts_rs::TS)]
109#[ts(export, export_to = "../../../frontend/types/rpc/")]
110pub struct IdentitySelfUnlinkReq {
111    pub agent_id: String,
112    pub provider: String,
113}
114
115/// `identity.self.unlink`: whether a link was removed.
116#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
117#[ts(export, export_to = "../../../frontend/types/rpc/")]
118pub struct IdentitySelfUnlinkResult {
119    pub unlinked: bool,
120}
121
122pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
123    register_identity_self_accounts(engine, state);
124    register_identity_account_upsert(engine, state);
125    register_identity_account_validate(engine, state);
126    register_identity_self_unlink(engine, state);
127}
128
129fn register_identity_self_accounts(engine: &Arc<WshRpcEngine>, state: &AppState) {
130    let state = state.clone();
131    engine.register_typed(COMMAND_IDENTITY_SELF_ACCOUNTS, move |req: IdentitySelfAccountsReq, ctx| {
132        let state = state.clone();
133        async move {
134            check_s1(&state.mstore, &ctx, &req.agent_id)?;
135            identity_self_accounts_impl(&state, &req.agent_id).await.map_err(|e| e.to_string())
136        }
137    });
138}
139
140fn register_identity_account_upsert(engine: &Arc<WshRpcEngine>, state: &AppState) {
141    let state = state.clone();
142    engine.register_typed(COMMAND_IDENTITY_ACCOUNT_UPSERT, move |req: IdentityAccountUpsertReq, ctx| {
143        let state = state.clone();
144        async move { identity_account_upsert(&state, &ctx, req).await }
145    });
146}
147
148/// `identity.account.upsert`: store the secret, optionally probe it, record the account and point the agent's
149/// provider link at it.
150pub(crate) async fn identity_account_upsert(
151    state: &AppState,
152    ctx: &RpcContext,
153    req: IdentityAccountUpsertReq,
154) -> Result<IdentityAccountUpsertResult, String> {
155    check_s1(&state.mstore, ctx, &req.agent_id)?;
156    if req.secret.is_empty() {
157        return Err("identity.account.upsert: secret must not be empty".to_string());
158    }
159
160    // The link table is keyed by definition id; req.agent_id is
161    // the S1 slug. Resolve once, use for every link-table call
162    // below. See resolve_agent_definition_id (mod.rs) for the
163    // two failure modes writing the slug causes.
164    let def_id = resolve_agent_definition_id(state, &req.agent_id)
165        .map_err(|e| format!("identity.account.upsert: {e}"))?;
166
167    let is_new = req.account_id.is_empty();
168    let account_id = if is_new { uuid::Uuid::new_v4().to_string() } else { owned_account_id(state, &def_id, &req)? };
169
170    // Step 1: store in keychain unconditionally.
171    {
172        let aid = account_id.clone();
173        let key = req.secret.clone();
174        tokio::task::spawn_blocking(move || crate::identity::secret_store::put(&aid, &key))
175            .await
176            .map_err(|e| format!("identity.account.upsert: keychain task: {e}"))?
177            .map_err(|e| format!("identity.account.upsert: keychain: {e}"))?;
178    }
179
180    // Step 1b: optional provider probe (validate controls this only).
181    let masked_tail = crate::identity::key_validator::masked_tail(&req.secret);
182    let (status, valid, error_msg) = if req.validate {
183        let outcome = crate::identity::key_validator::validate(&req.provider, &req.secret).await;
184        if outcome.valid {
185            ("valid".to_string(), true, None)
186        } else {
187            ("invalid".to_string(), false, outcome.error)
188        }
189    } else {
190        ("unknown".to_string(), false, None)
191    };
192
193    let account = account_to_store(state, &req, &account_id, &masked_tail, &status);
194    store_account(state, &account, is_new).await?;
195    link_account(state, &def_id, (&account_id, valid), &req.provider, is_new).await?;
196    announce_account(state, &req.agent_id, &account_id, valid);
197
198    Ok(IdentityAccountUpsertResult {
199        account_id,
200        provider: req.provider,
201        name: req.name,
202        status,
203        masked_tail,
204        valid,
205        error: error_msg,
206    })
207}
208
209/// Ownership check: the supplied account_id must already be
210/// linked to the calling agent, so callers can't overwrite
211/// another agent's credentials by guessing a UUID.
212fn owned_account_id(state: &AppState, def_id: &str, req: &IdentityAccountUpsertReq) -> Result<String, String> {
213    let links = state
214        .identity_store
215        .agent_identity_list_for_agent(def_id)
216        .map_err(|e| format!("identity.account.upsert: {e}"))?;
217    if !links.iter().any(|l| l.account_id == req.account_id) {
218        return Err("FORBIDDEN: account not linked to this agent".to_string());
219    }
220    Ok(req.account_id.clone())
221}
222
223/// The account row to write: a new one, or the existing one with its creation time and context kept.
224fn account_to_store(
225    state: &AppState,
226    req: &IdentityAccountUpsertReq,
227    account_id: &str,
228    masked_tail: &str,
229    status: &str,
230) -> IdentityAccount {
231    let now = agentmux_common::time::now_ms();
232    let existing = state.id_store.identity_get(account_id).ok().flatten();
233    let created_at = existing.as_ref().map(|a| a.created_at).filter(|&c| c != 0).unwrap_or(now);
234
235    let mut context = json!({ "masked_tail": masked_tail });
236    if let serde_json::Value::Object(ref mut m) = context {
237        if let Some(existing_ctx) = existing.as_ref().map(|a| &a.context) {
238            if let Some(obj) = existing_ctx.as_object() {
239                for (k, v) in obj {
240                    m.entry(k).or_insert_with(|| v.clone());
241                }
242            }
243        }
244    }
245
246    IdentityAccount {
247        id: account_id.to_string(),
248        name: req.name.clone(),
249        provider: req.provider.clone(),
250        kind: if req.kind.is_empty() { "api_key".to_string() } else { req.kind.clone() },
251        display_name: String::new(),
252        secret_ref: crate::backend::storage::identities::SecretRef::Keychain {
253            service: crate::identity::secret_store::SERVICE.to_string(),
254            account: crate::identity::secret_store::account_key(account_id),
255        },
256        context,
257        status: status.to_string(),
258        created_at,
259        updated_at: now,
260    }
261}
262
263/// Step 3 (upsert DB). Compensate on failure for new accounts.
264/// identity_upsert_with_mirror, not plain identity_upsert:
265/// without the mirror write, an account created/updated after the fix shipped still had
266/// no fallback entry and reproduced the reported bug on its own next channel switch.
267async fn store_account(state: &AppState, account: &IdentityAccount, is_new: bool) -> Result<(), String> {
268    if let Err(e) = state.id_store.identity_upsert_with_mirror(&state.identity_store, account) {
269        if is_new {
270            delete_secret(&account.id).await;
271        }
272        return Err(format!("identity.account.upsert: db: {e}"));
273    }
274    Ok(())
275}
276
277async fn delete_secret(account_id: &str) {
278    let aid = account_id.to_string();
279    let _ = tokio::task::spawn_blocking(move || crate::identity::secret_store::delete(&aid)).await;
280}
281
282/// Step 2/4: (re)point the agent's provider link at this account.
283/// agent_identity_link's own `ON CONFLICT(agent_id, provider) DO
284/// UPDATE` already overwrites whatever account_id was linked
285/// before, so no separate unlink is needed for the success path:
286/// an unlink that succeeds followed by a link that fails would permanently drop
287/// the agent's existing provider link with no compensation (the
288/// failure branch below only cleans up for is_new accounts).
289async fn link_account(state: &AppState, def_id: &str, (account_id, valid): (&str, bool), provider: &str, is_new: bool) -> Result<(), String> {
290    // Read before the link changes (see COMMAND_LINK_AGENT_IDENTITY):
291    // a pane left over from an earlier sign-in still carries that
292    // account's usage limit, which must not outlive the move.
293    let failed = crate::server::account_episodes::failed_panes(&state.mstore, &state.identity_store, def_id, provider);
294    if let Err(e) = state.identity_store.agent_identity_link(def_id, account_id, provider) {
295        // Only clean up for new accounts — on the update path the
296        // account still exists in the DB and may be linked to other providers,
297        // so deleting the keychain secret would destroy a valid credential.
298        // Delete the just-upserted db_accounts row too, not only the
299        // keychain secret: without it a failed link left an orphaned,
300        // unlinked account row behind.
301        if is_new {
302            let _ = state.id_store.identity_delete(account_id);
303            delete_secret(account_id).await;
304        }
305        return Err(format!("identity.account.upsert: link: {e}"));
306    }
307    // An agent whose last turn failed on the old login is told it is signed in only if this key passed its check.
308    crate::server::account_episodes::after_rebind_telling(&state.mstore, &state.event_bus, failed, account_id, valid);
309    Ok(())
310}
311
312/// Tell the UI and the watchers that the agent's account changed.
313fn announce_account(state: &AppState, agent_id: &str, account_id: &str, valid: bool) {
314    state.broker.publish_event::<crate::backend::mps_events::IdentityAccountsChanged>(&(), vec![], 0);
315    state.broker.publish_event_for::<crate::backend::mps_events::AgentIdentitiesChanged>(agent_id, &(), vec![], 0);
316    // A new key the provider accepted proves the account works (#2237).
317    if valid {
318        crate::server::account_episodes::after_sign_in(account_id);
319    }
320
321    // The subagent watcher can have resolved this agent's config dir before this binding landed and keep
322    // watching a stale one (`recheck_config_dir`); re-pointing is a no-op when nothing changed.
323    if let Some(watcher) = crate::backend::subagent_watcher::global() {
324        watcher.recheck_all_watched_agents();
325    }
326}
327
328fn register_identity_account_validate(engine: &Arc<WshRpcEngine>, state: &AppState) {
329    let state = state.clone();
330    engine.register_typed(COMMAND_IDENTITY_ACCOUNT_VALIDATE, move |req: IdentityAccountValidateReq, ctx| {
331        let state = state.clone();
332        async move { identity_account_validate(&state, &ctx, req).await }
333    });
334}
335
336/// `identity.account.validate`: probe a stored account, or a provider and secret the caller supplies.
337pub(crate) async fn identity_account_validate(
338    state: &AppState,
339    ctx: &RpcContext,
340    req: IdentityAccountValidateReq,
341) -> Result<IdentityAccountValidateResult, String> {
342    if !req.account_id.is_empty() {
343        // Stored-account path: S1 + ownership verification, then probe
344        // using the stored keychain secret (shared with the REST path).
345        check_s1(&state.mstore, ctx, &req.agent_id)?;
346        return identity_account_validate_stored_impl(state, &req.agent_id, &req.account_id).await.map_err(|e| e.to_string());
347    }
348    if !req.provider.is_empty() && !req.secret.is_empty() {
349        // Ad-hoc probe — caller supplies their own secret, nothing
350        // stored. WS-only; not exposed over REST/MCP (no inline secret).
351        let masked_tail = crate::identity::key_validator::masked_tail(&req.secret);
352        let outcome = crate::identity::key_validator::validate(&req.provider, &req.secret).await;
353        return Ok(IdentityAccountValidateResult::of(outcome, masked_tail));
354    }
355    Err("identity.account.validate: provide account_id or (provider + secret)".to_string())
356}
357
358fn register_identity_self_unlink(engine: &Arc<WshRpcEngine>, state: &AppState) {
359    let state = state.clone();
360    engine.register_typed(COMMAND_IDENTITY_SELF_UNLINK, move |req: IdentitySelfUnlinkReq, ctx| {
361        let state = state.clone();
362        async move { identity_self_unlink(&state, &ctx, req) }
363    });
364}
365
366/// `identity.self.unlink`: drop the agent's link to its account for one provider.
367pub(crate) fn identity_self_unlink(
368    state: &AppState,
369    ctx: &RpcContext,
370    req: IdentitySelfUnlinkReq,
371) -> Result<IdentitySelfUnlinkResult, String> {
372    let identity_store = &state.identity_store;
373    check_s1(&state.mstore, ctx, &req.agent_id)?;
374
375    // Link rows are keyed by definition id, not the S1 slug —
376    // unlinking by slug always matched zero rows (silent no-op).
377    let def_id = resolve_agent_definition_id(state, &req.agent_id)
378        .map_err(|e| format!("identity.self.unlink: {e}"))?;
379    let failed = crate::server::account_episodes::failed_panes(&state.mstore, identity_store, &def_id, &req.provider);
380    let unlinked = identity_store
381        .agent_identity_unlink(&def_id, &req.provider)
382        .map_err(|e| format!("identity.self.unlink: {e}"))?;
383    // info!, not debug!: the production filter is
384    // "agentmuxsrv=info,info" — debug lines never reach the log.
385    // Message prefix "identity.unlink:"
386    // is part of the `muxlog auth` vocabulary — keep it stable.
387    // `unlinked == false` (no link row matched) is logged too:
388    // a silent no-op unlink is exactly what an auth stress run
389    // needs to see. Both ids logged: link rows are keyed on
390    // def_id, not the S1 slug (the historical silent-no-op bug
391    // noted above) — a bad slug→def_id resolution is only
392    // visible if the log carries both.
393    tracing::info!(
394        agent_id = %req.agent_id,
395        def_id = %def_id,
396        provider = %req.provider,
397        unlinked,
398        "identity.unlink: self-service provider unlink (identity.self.unlink)"
399    );
400    if unlinked {
401        // No account left: whatever limit its panes carried belonged to the one it left.
402        crate::server::account_episodes::after_rebind(&state.mstore, &state.event_bus, failed, "");
403        state.broker.publish_event_for::<crate::backend::mps_events::AgentIdentitiesChanged>(&req.agent_id, &(), vec![], 0);
404    }
405    Ok(IdentitySelfUnlinkResult { unlinked })
406}
407
408pub(crate) async fn identity_self_accounts_impl<'o>(
409    state: &AppState,
410    owner: impl Into<SelfOwner<'o>>,
411) -> Result<IdentitySelfAccountsResult, ApiError> {
412    // Link rows are keyed by definition id, not the S1 slug callers
413    // authenticate with — see resolve_agent_definition_id. Identity M4c-2c:
414    // an attributed caller's is its own row's (`SelfOwner`).
415    let def_id = owner.into().owner_id(&state.mstore).map_err(|e| e.under("identity.self.accounts"))?;
416    let links = state.identity_store.agent_identity_list_for_agent(&def_id)
417        .map_err(|e| format!("identity.self.accounts: {e}"))?;
418    let mut accounts = Vec::new();
419    for link in &links {
420        // A malformed `secret_ref` on ONE linked account must not hide this
421        // agent's other, perfectly readable accounts — the same "one bad row
422        // hides everything" bug class `identity_list` was fixed for (#2419),
423        // just reachable through this separate per-agent lookup too. Skip and
424        // log rather than `?`-propagate.
425        // resolve_account (WITH the global-mirror fallback), not
426        // resolve_account_for_spawn: without the fallback a migrated/continuing
427        // account showed as "missing" here (#2632).
428        //
429        // CAVEAT (#2878): this is NO LONGER
430        // consistent with the spawn path. `inject.rs` now uses
431        // `resolve_account_for_spawn`, which deliberately has no fallback, so an
432        // oauth-class account resolvable ONLY via the mirror is listed here yet
433        // refused at spawn with `MissingCredentials` (an api-key-class one is
434        // silently skipped instead). That divergence is deliberate — a listing
435        // should describe what exists rather than silently hide it, and hiding
436        // it would reproduce exactly the "my account vanished" confusion #2632
437        // fixed — but it is a real UX gap: nothing in this payload tells the
438        // caller the account can't satisfy a spawn in THIS channel. Logged
439        // below so it is at least observable; surfacing it in the payload (and
440        // in Connectors) is tracked as follow-up, not silently assumed fine. See
441        // docs/analysis/ANALYSIS_PER_CHANNEL_AUTH_BYPASSES_2026_08_31.md §6.
442        match crate::identity::resolver::resolve_account(&state.id_store, &state.identity_store, &link.account_id) {
443            Ok(Some((acct, account_store))) => {
444                // Observability for the divergence documented above: this
445                // account exists only in the always-global mirror, so a spawn in
446                // this channel will not accept it.
447                if !std::sync::Arc::ptr_eq(&account_store, &state.id_store) {
448                    tracing::warn!(
449                        target: "identity",
450                        account_id = %acct.id,
451                        agent_id = %def_id,
452                        provider = %acct.provider,
453                        "identity.self.accounts: account resolved only via the global mirror; it will NOT satisfy a spawn in this channel (per-channel auth enforcement)"
454                    );
455                }
456                let masked_tail = acct.context.get("masked_tail")
457                    .and_then(|v| v.as_str()).unwrap_or("").to_string();
458                accounts.push(IdentitySelfAccount {
459                    account_id: acct.id, provider: acct.provider, name: acct.name,
460                    kind: acct.kind, status: acct.status, masked_tail,
461                    updated_at: acct.updated_at,
462                });
463            }
464            Ok(None) => {
465                // Link points at a since-deleted account — skip silently.
466            }
467            Err(e) => {
468                tracing::warn!(
469                    target: "identity",
470                    account_id = %link.account_id,
471                    agent_id = %def_id,
472                    error = %e,
473                    "identity.self.accounts: skipping unreadable linked account",
474                );
475            }
476        }
477    }
478    Ok(IdentitySelfAccountsResult { accounts })
479}
480
481/// Validate one of the agent's own linked accounts by probing the provider with
482/// the stored keychain secret. Ownership is verified (the account must be linked
483/// to `agent_id`) before the secret is read.
484pub(crate) async fn identity_account_validate_stored_impl<'o>(
485    state: &AppState,
486    owner: impl Into<SelfOwner<'o>>,
487    account_id: &str,
488) -> Result<IdentityAccountValidateResult, ApiError> {
489    // Link rows are keyed by definition id, not the S1 slug — without the
490    // resolution this ownership check always saw zero links and rejected.
491    // Identity M4c-2c: an attributed caller's is its own row's, so it can
492    // no longer live-probe a same-named agent's stored secret.
493    let def_id = owner.into().owner_id(&state.mstore).map_err(|e| e.under("identity.account.validate"))?;
494    let links = state.identity_store.agent_identity_list_for_agent(&def_id)
495        .map_err(|e| format!("identity.account.validate: {e}"))?;
496    if !links.iter().any(|l| l.account_id == account_id) {
497        return Err(ApiError::refused("FORBIDDEN: account not linked to this agent"));
498    }
499    // resolve_account (WITH the global-mirror fallback) — same reagentx P1
500    // review as identity_self_accounts_impl above.
501    //
502    // CAVEAT since 2026-08-31 (reagent P2 on PR #2878): "consistently with the
503    // spawn path" is no longer true — the spawn path dropped this fallback. What
504    // this RPC answers is narrower than it looks: it validates the CREDENTIAL
505    // (is the key live at the provider), not whether a spawn in this channel
506    // would accept the account. A cross-channel-only account can therefore come
507    // back `valid: true` and still be refused at spawn. Kept as-is because the
508    // credential-validity answer is genuinely correct and callers use it to
509    // check a key, not to predict a spawn — but do not read `valid` as
510    // "this agent can launch". See the note in identity_self_accounts_impl.
511    let (acct, _account_store) = crate::identity::resolver::resolve_account(&state.id_store, &state.identity_store, account_id)
512        .map_err(|e| format!("identity.account.validate: {e}"))?
513        .ok_or_else(|| ApiError::not_found(format!("identity.account.validate: account {account_id} not found")))?;
514    // An OAuth account is validated by its access token, refreshed first when
515    // it is near expiry; a grant the provider dropped answers "Reconnect
516    // needed" (and marks the account) rather than probing a dead token.
517    if acct.kind == "oauth" && matches!(acct.secret_ref, crate::backend::storage::identities::SecretRef::Keychain { .. }) {
518        use crate::identity::oauth_tokens::{access_token_for, KeychainSecrets, LiveHttp};
519        let token = match access_token_for(&LiveHttp, &KeychainSecrets, &state.id_store, &state.identity_store, &acct, Some(&state.id_store)).await {
520            Ok(t) => t,
521            Err(e) => return Ok(IdentityAccountValidateResult {
522                valid: false,
523                status: "invalid".to_string(),
524                masked_tail: String::new(),
525                error: Some(e),
526            }),
527        };
528        let tail = crate::identity::key_validator::masked_tail(&token);
529        let outcome = crate::identity::key_validator::validate(&acct.provider, &token).await;
530        return Ok(proven(account_id, IdentityAccountValidateResult::of(outcome, tail)));
531    }
532    // A CLI sign-in keeps its tokens in its own credentials file, with no stored key to check at the
533    // provider: say what the file reads instead of failing on the missing key (#47468).
534    if let crate::backend::storage::identities::SecretRef::OAuthConfigDir { dir } = &acct.secret_ref {
535        let provider = crate::backend::providers::resolve_provider_alias(&acct.provider);
536        let Some(probe) = crate::identity::resolver::probe_oauth_status(provider, dir, agentmux_common::time::now_ms()) else {
537            return Ok(IdentityAccountValidateResult {
538                valid: false,
539                status: acct.status.clone(),
540                masked_tail: String::new(),
541                error: Some("validate does not apply: this is a CLI sign-in with no stored key, and its credentials cannot be read here".to_string()),
542            });
543        };
544        use crate::identity::resolver::OAuthProbeStatus;
545        // Only an unexpired token proves the login: an expired access token is the very thing a pane
546        // was refused on, and a pass here clears its agents' signed-out state.
547        let valid = probe == OAuthProbeStatus::Valid;
548        let error = match probe {
549            OAuthProbeStatus::Valid => None,
550            OAuthProbeStatus::Expired => Some("this is a CLI sign-in with no stored key: its access token has expired and renews the next time the CLI uses it".to_string()),
551            OAuthProbeStatus::NeedsReauth => Some("this is a CLI sign-in with no stored key: its credentials file holds no token, so it needs a sign-in".to_string()),
552        };
553        let result = IdentityAccountValidateResult { valid, status: probe.as_str().to_string(), masked_tail: String::new(), error };
554        // Only Claude's probe reads the token's expiry; the others call a refresh token or key valid
555        // whatever its age, which does not prove a pane's refused login works.
556        if provider != "claude" {
557            return Ok(result);
558        }
559        return Ok(proven(account_id, result));
560    }
561    let (aid, secret_ref, vault) = (account_id.to_string(), acct.secret_ref.clone(), state.identity_store.clone());
562    let plaintext = tokio::task::spawn_blocking(move || match &secret_ref {
563        crate::backend::storage::identities::SecretRef::Vault { .. } => crate::backend::vault::account_key::read(&vault, &aid, &secret_ref),
564        _ => crate::identity::secret_store::get(&aid),
565    })
566    .await.map_err(|e| format!("identity.account.validate: key task: {e}"))?
567    .map_err(|e| format!("identity.account.validate: key: {e}"))?;
568    let tail = crate::identity::key_validator::masked_tail(&plaintext);
569    let outcome = crate::identity::key_validator::validate(&acct.provider, &plaintext).await;
570    Ok(proven(account_id, IdentityAccountValidateResult::of(outcome, tail)))
571}
572
573/// A validate that passed proves the account works, so its agents stop being
574/// signed out (#2237).
575fn proven(account_id: &str, result: IdentityAccountValidateResult) -> IdentityAccountValidateResult {
576    if result.valid {
577        crate::server::account_episodes::after_sign_in(account_id);
578    }
579    result
580}
581
582#[cfg(test)]
583mod wire_tests {
584    use super::*;
585
586    /// Each response serializes as the `json!` it replaced did: same keys, `error` null when there is none.
587    #[test]
588    fn identity_responses_serialize_as_before() {
589        let account = IdentitySelfAccount {
590            account_id: "a1".into(),
591            provider: "claude".into(),
592            name: "Work".into(),
593            kind: "api_key".into(),
594            status: "ok".into(),
595            masked_tail: "…wxyz".into(),
596            updated_at: 7,
597        };
598        assert_eq!(
599            serde_json::to_value(IdentitySelfAccountsResult { accounts: vec![account] }).unwrap(),
600            json!({ "accounts": [{ "account_id": "a1", "provider": "claude", "name": "Work", "kind": "api_key", "status": "ok", "masked_tail": "…wxyz", "updated_at": 7 }] })
601        );
602        let upsert = IdentityAccountUpsertResult {
603            account_id: "a1".into(),
604            provider: "claude".into(),
605            name: "Work".into(),
606            status: "unknown".into(),
607            masked_tail: "…wxyz".into(),
608            valid: false,
609            error: None,
610        };
611        assert_eq!(
612            serde_json::to_value(upsert).unwrap(),
613            json!({ "account_id": "a1", "provider": "claude", "name": "Work", "status": "unknown", "masked_tail": "…wxyz", "valid": false, "error": null })
614        );
615        let outcome = crate::identity::key_validator::ValidationOutcome {
616            valid: false,
617            metadata: json!({}),
618            masked_tail: String::new(),
619            error: Some("401".into()),
620        };
621        assert_eq!(
622            serde_json::to_value(IdentityAccountValidateResult::of(outcome, "…wxyz".into())).unwrap(),
623            json!({ "valid": false, "status": "invalid", "masked_tail": "…wxyz", "error": "401" })
624        );
625        assert_eq!(serde_json::to_value(IdentitySelfUnlinkResult { unlinked: true }).unwrap(), json!({ "unlinked": true }));
626    }
627}
628
629#[cfg(test)]
630mod handler_tests {
631    use super::*;
632    use crate::server::tests::test_state;
633
634    fn caller(slug: &str) -> RpcContext {
635        RpcContext { agent_id: slug.into(), ..Default::default() }
636    }
637
638    fn upsert_req(agent: &str, account_id: &str, secret: &str) -> IdentityAccountUpsertReq {
639        IdentityAccountUpsertReq {
640            agent_id: agent.into(),
641            account_id: account_id.into(),
642            name: "Work".into(),
643            provider: "claude".into(),
644            kind: String::new(),
645            secret: secret.into(),
646            validate: false,
647        }
648    }
649
650    fn state_with_agent(slug: &str) -> AppState {
651        let state = test_state();
652        let mut def = crate::backend::storage::agents::test_agent_def(&format!("uid-{slug}"), slug, "claude", "agent", 1, "");
653        def.slug = slug.to_string();
654        state.mstore.agent_def_insert(&mut def).unwrap();
655        state
656    }
657
658    #[tokio::test]
659    async fn an_unauthenticated_connection_cannot_store_or_unlink_an_account() {
660        let state = state_with_agent("idagent");
661        let anonymous = RpcContext::default();
662        let err = identity_account_upsert(&state, &anonymous, upsert_req("idagent", "", "sk-secret")).await.err().unwrap();
663        assert!(err.starts_with("FORBIDDEN"), "{err}");
664        let err = identity_self_unlink(&state, &anonymous, IdentitySelfUnlinkReq { agent_id: "idagent".into(), provider: "claude".into() })
665            .err()
666            .unwrap();
667        assert!(err.starts_with("FORBIDDEN"), "{err}");
668    }
669
670    #[tokio::test]
671    async fn an_agent_cannot_act_for_another_agents_accounts() {
672        let state = state_with_agent("idagent");
673        let err = identity_account_upsert(&state, &caller("someone-else"), upsert_req("idagent", "", "sk-secret")).await.err().unwrap();
674        assert_eq!(err, "FORBIDDEN: agent_id mismatch");
675    }
676
677    #[tokio::test]
678    async fn an_empty_secret_is_refused_before_anything_is_stored() {
679        let state = state_with_agent("idagent");
680        let err = identity_account_upsert(&state, &caller("idagent"), upsert_req("idagent", "", "")).await.err().unwrap();
681        assert_eq!(err, "identity.account.upsert: secret must not be empty");
682    }
683
684    #[tokio::test]
685    async fn an_account_that_is_not_linked_to_the_agent_cannot_be_overwritten_by_guessing_its_id() {
686        let state = state_with_agent("idagent");
687        let err = identity_account_upsert(&state, &caller("idagent"), upsert_req("idagent", "guessed-uuid", "sk-secret")).await.err().unwrap();
688        assert_eq!(err, "FORBIDDEN: account not linked to this agent");
689    }
690
691    #[tokio::test]
692    async fn validating_needs_an_account_or_a_provider_with_a_secret() {
693        let state = state_with_agent("idagent");
694        let req = |provider: &str, secret: &str| IdentityAccountValidateReq {
695            agent_id: "idagent".into(),
696            account_id: String::new(),
697            provider: provider.into(),
698            secret: secret.into(),
699        };
700        for (provider, secret) in [("", ""), ("claude", ""), ("", "sk-x")] {
701            let err = identity_account_validate(&state, &caller("idagent"), req(provider, secret)).await.err().unwrap();
702            assert_eq!(err, "identity.account.validate: provide account_id or (provider + secret)");
703        }
704    }
705
706    #[tokio::test]
707    async fn unlinking_a_provider_the_agent_has_no_account_for_changes_nothing() {
708        let state = state_with_agent("idagent");
709        let result = identity_self_unlink(&state, &caller("idagent"), IdentitySelfUnlinkReq { agent_id: "idagent".into(), provider: "claude".into() }).unwrap();
710        assert!(!result.unlinked);
711    }
712}