1use super::*;
2use crate::server::api_error::ApiError;
3
4#[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#[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#[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#[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#[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#[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#[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#[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#[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
148pub(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 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 {
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 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
209fn 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
223fn 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
263async 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
282async fn link_account(state: &AppState, def_id: &str, (account_id, valid): (&str, bool), provider: &str, is_new: bool) -> Result<(), String> {
290 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 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 crate::server::account_episodes::after_rebind_telling(&state.mstore, &state.event_bus, failed, account_id, valid);
309 Ok(())
310}
311
312fn 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 if valid {
318 crate::server::account_episodes::after_sign_in(account_id);
319 }
320
321 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
336pub(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 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 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
366pub(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 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 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 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 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 match crate::identity::resolver::resolve_account(&state.id_store, &state.identity_store, &link.account_id) {
443 Ok(Some((acct, account_store))) => {
444 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 }
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
481pub(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 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 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 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 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 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 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
573fn 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 #[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}