1use std::collections::HashMap;
20use std::path::PathBuf;
21use std::sync::Arc;
22
23use crate::backend::providers::resolve_provider_alias;
24use crate::backend::storage::store::{IdentityAccount, SecretRef, Store};
25use crate::backend::storage::StoreError;
26use crate::backend::mps::Broker;
27
28use super::errors::{refusal_linked, SpawnGateError};
29use super::oauth_probe::{oauth_status, probe_oauth_status};
30use super::provider::{provider_class, ProviderClass};
31use super::secret::{resolve_account_secret, resolve_secret};
32
33pub fn inject_identity_env(
74 mstore: Arc<Store>,
75 id_store: Arc<Store>,
76 identity_store: Arc<Store>,
77 block_id: &str,
78 env_vars: &mut HashMap<String, String>,
79) -> Result<(), SpawnGateError> {
80 inject_identity_env_with_broker(mstore, id_store, identity_store, None, block_id, env_vars)
81}
82
83pub async fn inject_identity_env_async(
104 mstore: Arc<Store>,
105 id_store: Arc<Store>,
106 identity_store: Arc<Store>,
107 broker: Option<Arc<Broker>>,
108 block_id: String,
109 env_vars: HashMap<String, String>,
110 own_claude_endpoint: bool,
111) -> Result<HashMap<String, String>, SpawnGateError> {
112 match tokio::task::spawn_blocking(move || {
113 let mut env = env_vars;
114 inject_identity_env_for_spawn(mstore, id_store, identity_store, broker, &block_id, &mut env, own_claude_endpoint)
115 .map(|()| env)
116 })
117 .await
118 {
119 Ok(result) => result,
120 Err(e) => {
121 tracing::warn!(
128 target: "identity",
129 error = %e,
130 "identity.spawn.blocked: injection task join failed — failing closed"
131 );
132 Err(SpawnGateError::InjectionUnavailable { detail: e.to_string() })
133 }
134 }
135}
136
137struct IdentityBinding {
143 provider: String,
144 account_id: String,
145}
146
147pub(super) fn template_parent_id_if_seeded(mstore: &Store, parent_id: &str) -> String {
203 if parent_id.is_empty() {
204 return String::new();
205 }
206 match mstore.agent_def_get(parent_id) {
207 Ok(Some(parent)) if parent.is_seeded == 1 => parent_id.to_string(),
208 Ok(Some(_)) => String::new(), Ok(None) => String::new(),
210 Err(e) => {
211 tracing::warn!(
212 target: "identity",
213 "template-parent lookup failed for {}: {} — treating as no eligible template parent",
214 parent_id,
215 e,
216 );
217 String::new()
218 }
219 }
220}
221
222fn resolve_bindings_for_instance(
223 id_store: &Store,
224 instance: &crate::backend::storage::store::AgentInstance,
225 parent_template_id: &str,
226 broker: Option<&Arc<Broker>>,
227) -> Vec<IdentityBinding> {
228 let direct = id_store
229 .agent_identity_list_for_agent(&instance.definition_id)
230 .unwrap_or_else(|e| {
231 tracing::warn!(
232 target: "identity",
233 "direct-link lookup failed for definition {}: {}",
234 instance.definition_id,
235 e,
236 );
237 Vec::new()
238 });
239
240 if direct.is_empty() && !parent_template_id.is_empty() {
241 let from_template = id_store
242 .agent_identity_list_for_agent(parent_template_id)
243 .unwrap_or_else(|e| {
244 tracing::warn!(
245 target: "identity",
246 "template link fallback failed for template {}: {}",
247 parent_template_id,
248 e,
249 );
250 Vec::new()
251 });
252 if !from_template.is_empty() {
253 return from_template
254 .into_iter()
255 .map(|l| IdentityBinding { provider: l.provider, account_id: l.account_id })
256 .collect();
257 }
258 }
259
260 if direct.is_empty() {
261 tracing::warn!(
268 target: "identity",
269 "no direct account links for definition {} (identity {}) — \
270 nothing to inject.",
271 instance.definition_id,
272 instance.identity_id,
273 );
274 if let Some(b) = broker {
275 let event = crate::backend::mps_events::NoDirectLinksEvent {
276 definition_id: instance.definition_id.clone(),
277 identity_id: instance.identity_id.clone(),
278 };
279 b.publish_event::<crate::backend::mps_events::IdentityNoDirectLinks>(&event, vec![], 20);
285 }
286 }
287
288 direct
289 .into_iter()
290 .map(|l| IdentityBinding {
291 provider: l.provider,
292 account_id: l.account_id,
293 })
294 .collect()
295}
296
297pub fn resolve_account(
315 id_store: &Arc<Store>,
316 identity_store: &Arc<Store>,
317 account_id: &str,
318) -> Result<Option<(IdentityAccount, Arc<Store>)>, StoreError> {
319 if let Some(a) = id_store.identity_get(account_id)? {
320 return Ok(Some((a, id_store.clone())));
321 }
322 if let Some(a) = identity_store.identity_get(account_id)? {
323 return Ok(Some((a, identity_store.clone())));
324 }
325 Ok(None)
326}
327
328pub fn resolve_account_for_spawn(
357 id_store: &Arc<Store>,
358 account_id: &str,
359) -> Result<Option<(IdentityAccount, Arc<Store>)>, StoreError> {
360 Ok(id_store
361 .identity_get(account_id)?
362 .map(|a| (a, id_store.clone())))
363}
364
365pub fn resolve_bound_oauth_config_dir(
386 mstore: &Arc<Store>,
387 id_store: &Arc<Store>,
388 identity_store: &Arc<Store>,
389 block_id: &str,
390) -> Option<PathBuf> {
391 let instance = mstore.instance_get_active_for_block(block_id).ok().flatten()?;
392 bound_oauth_config_dir(mstore, id_store, identity_store, &instance)
393}
394
395pub fn resolve_bound_claude_config_dir_for_agent(
402 mstore: &Store,
403 id_store: &Arc<Store>,
404 identity_store: &Arc<Store>,
405 agent_id: &str,
406) -> Option<PathBuf> {
407 let instance = mstore.instance_get(agent_id).ok().flatten()?;
408 let def = mstore.agent_def_get(&instance.definition_id).ok().flatten()?;
409 let provider = id_store.resolve_effective_provider_id(&def);
410 if resolve_provider_alias(&provider) != "claude" {
411 return None;
412 }
413 let dir = bound_oauth_config_dir(mstore, id_store, identity_store, &instance)?;
414 let claude = crate::backend::providers::get_provider("claude")?;
415 if crate::backend::providers::is_provider_ambient_home_dir(claude, &dir.to_string_lossy()) {
416 return None;
417 }
418 Some(dir)
419}
420
421pub fn agent_has_identity_binding(mstore: &Store, identity_store: &Store, agent_id: &str) -> bool {
426 let direct = identity_store
427 .agent_identity_list_for_agent(agent_id)
428 .map(|l| !l.is_empty())
429 .unwrap_or(false);
430 if direct {
431 return true;
432 }
433 let Some(def) = mstore.agent_def_get(agent_id).ok().flatten() else {
434 return false;
435 };
436 let parent = template_parent_id_if_seeded(mstore, &def.parent_id);
437 !parent.is_empty()
438 && identity_store
439 .agent_identity_list_for_agent(&parent)
440 .map(|l| !l.is_empty())
441 .unwrap_or(false)
442}
443
444fn bound_oauth_config_dir(
445 mstore: &Store,
446 id_store: &Arc<Store>,
447 identity_store: &Arc<Store>,
448 instance: &crate::backend::storage::store::AgentInstance,
449) -> Option<PathBuf> {
450 let def = mstore.agent_def_get(&instance.definition_id).ok().flatten()?;
451 let effective_provider = id_store.resolve_effective_provider_id(&def);
452 let canonical_provider = resolve_provider_alias(&effective_provider).to_string();
453 if !matches!(provider_class(&canonical_provider), Some(ProviderClass::OAuth { .. })) {
454 return None;
455 }
456
457 let template_parent_id = template_parent_id_if_seeded(mstore, &def.parent_id);
458 let bindings = resolve_bindings_for_instance(identity_store, instance, &template_parent_id, None);
459 if let Some(dir) = steps::key_route_dir(&bindings, &canonical_provider) { return Some(dir); }
460 let binding = bindings.iter().find(|b| resolve_provider_alias(&b.provider) == canonical_provider)?;
461 let (account, _store) = resolve_account_for_spawn(id_store, &binding.account_id).ok().flatten()?;
466 match account.secret_ref {
467 SecretRef::OAuthConfigDir { dir } => Some(PathBuf::from(dir)),
468 _ => None,
469 }
470}
471
472pub fn block_agent_id(mstore: &Store, block_id: &str) -> Option<String> {
474 let block: crate::backend::obj::Block = mstore.get(block_id).ok().flatten()?;
475 crate::backend::obj::block_meta_agent_id(&block.meta)
476 .map(str::trim)
477 .filter(|s| !s.is_empty())
478 .map(str::to_string)
479}
480
481pub fn inject_identity_env_with_broker(
493 mstore: Arc<Store>,
494 id_store: Arc<Store>,
495 identity_store: Arc<Store>,
496 broker: Option<Arc<Broker>>,
497 block_id: &str,
498 env_vars: &mut HashMap<String, String>,
499) -> Result<(), SpawnGateError> {
500 inject_identity_env_for_spawn(mstore, id_store, identity_store, broker, block_id, env_vars, false)
501}
502
503pub fn inject_identity_env_for_spawn(
511 mstore: Arc<Store>,
512 id_store: Arc<Store>,
513 identity_store: Arc<Store>,
514 broker: Option<Arc<Broker>>,
515 block_id: &str,
516 env_vars: &mut HashMap<String, String>,
517 own_claude_endpoint: bool,
518) -> Result<(), SpawnGateError> {
519 let instance = match mstore.instance_get_active_for_block(block_id) {
521 Ok(Some(i)) => i,
522 Ok(None) => return steps::check_row_less_block(&mstore, block_id),
523 Err(e) => {
524 tracing::warn!(target: "identity", "instance lookup failed for block {}: {}", block_id, e);
525 return Ok(());
526 }
527 };
528
529 let on_route = steps::on_model_route(&mstore, &instance);
530
531 let (def_provider, parent_template_id) = steps::definition_provider(&mstore, &id_store, &instance);
533
534 let bindings = resolve_bindings_for_instance(&identity_store, &instance, &parent_template_id, broker.as_ref());
546
547 steps::note_blank_identity(&instance, block_id, &bindings, on_route);
549 let mut injector = steps::BindingInjector {
551 id_store: &id_store,
552 identity_store: &identity_store,
553 broker: broker.as_ref(),
554 instance: &instance, injected_oauth: std::collections::HashSet::new(), mstore: &mstore, def_provider: def_provider.as_deref(), own_endpoint: own_claude_endpoint,
555 };
556 for binding in &bindings {
557 injector.inject(binding, env_vars)?;
558 }
559
560 let brings_own_login = on_route || (own_claude_endpoint && def_provider.as_deref() == Some("claude"));
562 if !brings_own_login { steps::gate_unbound_provider(def_provider.clone(), &injector.injected_oauth, &bindings, &identity_store, &instance, &parent_template_id)?; }
563
564 steps::recheck_agent_not_deleted(&mstore, &instance)
566}
567
568#[path = "inject_steps.rs"]
569pub mod steps;
570
571#[cfg(test)]
572mod tests {
573 #[path = "../../inject_own_endpoint_tests.rs"]
574 pub mod own_endpoint;
575 #[path = "../../inject_key_route_tests.rs"]
576 pub mod key_route;
577 use super::*;
578 use super::super::oauth_probe::oauth_status;
579 use crate::backend::storage::store::{
580 AgentInstance, IdentityAccount, Bundle, SecretRef,
581 };
582
583 fn make_store() -> Arc<Store> {
584 Arc::new(Store::open_in_memory().unwrap())
585 }
586
587 fn store_with_def_registry(tmp: &tempfile::TempDir) -> Arc<Store> {
590 let store = make_store();
591 let defs = crate::registry::DefinitionStore::open(tmp.path().join("definitions")).unwrap();
592 store.set_def_registry(Arc::new(defs));
593 store
594 }
595
596 #[test]
600 fn a_block_naming_a_deleted_agent_is_refused() {
601 let tmp = tempfile::tempdir().unwrap();
602 let store = store_with_def_registry(&tmp);
603 let mut def = crate::backend::storage::agents::test_agent_def(
604 "agent-deleted-3577",
605 "Gone",
606 "claude",
607 "agent",
608 1,
609 "",
610 );
611 store.agent_def_insert(&mut def).unwrap();
612 assert!(
613 store
614 .shared_def_registry()
615 .unwrap()
616 .exists("agent-deleted-3577"),
617 "precondition: mirrored"
618 );
619 assert!(store.agent_def_delete("agent-deleted-3577").unwrap());
620 insert_block_for_agent(&store, "block-deleted-3577", "agent-deleted-3577");
621
622 let mut env = HashMap::new();
623 let res = inject_identity_env_with_broker(
624 store.clone(),
625 store.clone(),
626 store.clone(),
627 None,
628 "block-deleted-3577",
629 &mut env,
630 );
631 assert_eq!(
632 res,
633 Err(SpawnGateError::AgentDeleted {
634 agent_id: "agent-deleted-3577".to_string()
635 })
636 );
637 }
638
639 #[test]
645 fn a_row_less_block_not_naming_a_deleted_agent_is_not_refused() {
646 let tmp = tempfile::tempdir().unwrap();
647 let store = store_with_def_registry(&tmp);
648 let mut tpl = crate::backend::storage::agents::test_agent_def(
649 "claude", "Claude", "claude", "agent", 1, "",
650 );
651 tpl.is_seeded = 1;
652 store.agent_def_insert(&mut tpl).unwrap();
653 store
654 .shared_def_registry()
655 .unwrap()
656 .upsert(&crate::registry::DefinitionRecord {
657 schema_version: crate::registry::DEF_MAX_SUPPORTED_SCHEMA,
658 data: crate::registry::DefinitionRecordV1 {
659 id: "agent-elsewhere-3577".to_string(),
660 name: "Elsewhere".to_string(),
661 provider: "claude".to_string(),
662 ..Default::default()
663 },
664 })
665 .unwrap();
666 insert_block_for_agent(&store, "block-template-3577", "claude");
667 insert_block_for_agent(&store, "block-cross-3577", "agent-elsewhere-3577");
668 insert_block_for_agent(&store, "block-unknown-3577", "never-existed");
669 for block in [
670 "block-template-3577",
671 "block-cross-3577",
672 "block-unknown-3577",
673 ] {
674 let mut env = HashMap::new();
675 let res = inject_identity_env_with_broker(
676 store.clone(),
677 store.clone(),
678 store.clone(),
679 None,
680 block,
681 &mut env,
682 );
683 assert_eq!(res, Ok(()), "{block}");
684 }
685
686 let bare = make_store();
689 insert_block_for_agent(&bare, "block-bare-3577", "agent-deleted-anywhere");
690 let mut env = HashMap::new();
691 assert_eq!(
692 inject_identity_env_with_broker(
693 bare.clone(),
694 bare.clone(),
695 bare.clone(),
696 None,
697 "block-bare-3577",
698 &mut env
699 ),
700 Ok(())
701 );
702 }
703
704 fn make_account(
705 id: &str,
706 provider: &str,
707 secret_ref: SecretRef,
708 ) -> IdentityAccount {
709 IdentityAccount {
710 id: id.to_string(),
711 name: format!("{}-{}", provider, id),
712 provider: provider.to_string(),
713 kind: "pat".to_string(),
714 display_name: String::new(),
715 secret_ref,
716 context: serde_json::json!({}),
717 status: "unknown".to_string(),
718 created_at: 0,
719 updated_at: 0,
720 }
721 }
722
723 fn insert_block_for_agent(store: &Store, block_id: &str, agent_id: &str) {
729 use crate::backend::obj::{Block, MetaMapType};
730 let mut block = Block {
731 oid: block_id.to_string(),
732 parentoref: String::new(),
733 version: 0,
734 runtimeopts: None,
735 stickers: None,
736 meta: {
737 let mut m = MetaMapType::new();
738 m.insert("view".to_string(), serde_json::json!("agent"));
739 m.insert("agentId".to_string(), serde_json::json!(agent_id));
740 m
741 },
742 subblockids: None,
743 };
744 store.insert(&mut block).unwrap();
745 }
746
747 fn test_config_dir(name: &str) -> String {
757 std::env::temp_dir()
758 .join(format!("agentmux-inject-test-{}-{name}", std::process::id()))
759 .to_string_lossy()
760 .into_owned()
761 }
762
763 fn make_instance(block_id: &str, identity_id: &str) -> AgentInstance {
764 AgentInstance {
765 identity_id: identity_id.to_string(),
766 ..crate::backend::storage::agents::test_agent_instance(&format!("inst-{block_id}"), "def-1", block_id, 0)
767 }
768 }
769
770 #[cfg(debug_assertions)]
771 #[test]
772 fn inject_oauth_class_sets_config_dir_env_var() {
773 let store = make_store();
774
775 let mut def = crate::backend::storage::store::AgentDefinition {
776 slug: String::new(),
777 icon: "✦".to_string(),
778 ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
779 };
780 store.agent_def_insert(&mut def).unwrap();
781
782 let claude = make_account(
783 "acct-claude",
784 "claude",
785 SecretRef::OAuthConfigDir {
786 dir: test_config_dir("id-oauth"),
787 },
788 );
789 store.identity_upsert(&claude).unwrap();
790 store
791 .agent_identity_link("def-1", "acct-claude", "claude")
792 .unwrap();
793
794 insert_block_for_agent(&store, "block-oauth", "def-1");
795 let inst = make_instance("block-oauth", "id-oauth");
796 store.instance_create(&inst).unwrap();
797
798 let mut env: HashMap<String, String> = HashMap::new();
799 inject_identity_env(store.clone(), store.clone(), store, "block-oauth", &mut env).unwrap();
802
803 assert_eq!(
805 env.get("CLAUDE_CONFIG_DIR").cloned(),
806 Some(test_config_dir("id-oauth")),
807 );
808 assert!(env.get("ANTHROPIC_API_KEY").is_none());
811 }
812
813 #[cfg(debug_assertions)]
824 #[test]
825 fn inject_oauth_class_blocks_spawn_when_config_dir_is_the_ambient_home() {
826 let store = make_store();
827
828 let mut def = crate::backend::storage::store::AgentDefinition {
829 slug: String::new(),
830 icon: "✦".to_string(),
831 ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
832 };
833 store.agent_def_insert(&mut def).unwrap();
834
835 let ambient_claude_dir = crate::backend::base::get_home_dir()
836 .join(".claude")
837 .to_string_lossy()
838 .into_owned();
839 let claude = make_account(
840 "acct-ambient",
841 "claude",
842 SecretRef::OAuthConfigDir { dir: ambient_claude_dir.clone() },
843 );
844 store.identity_upsert(&claude).unwrap();
845 store
846 .agent_identity_link("def-1", "acct-ambient", "claude")
847 .unwrap();
848
849 insert_block_for_agent(&store, "block-ambient", "def-1");
850 let inst = make_instance("block-ambient", "id-ambient");
851 store.instance_create(&inst).unwrap();
852
853 let mut env: HashMap<String, String> = HashMap::new();
854 let err = inject_identity_env(store.clone(), store.clone(), store, "block-ambient", &mut env)
855 .expect_err("spawn must be refused when the bound account's config dir is the ambient home");
856
857 match err {
858 SpawnGateError::AmbientHomeDirNotAllowed { provider, dir } => {
859 assert_eq!(provider, "claude");
860 assert_eq!(dir, ambient_claude_dir);
861 }
862 other => panic!("expected AmbientHomeDirNotAllowed, got {other:?}"),
863 }
864 assert!(env.get("CLAUDE_CONFIG_DIR").is_none());
867 }
868
869 #[cfg(debug_assertions)]
880 #[test]
881 fn inject_oauth_class_blocks_spawn_when_claude_md_seed_fails() {
882 let store = make_store();
883
884 let mut def = crate::backend::storage::store::AgentDefinition {
885 slug: String::new(),
886 icon: "✦".to_string(),
887 ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
888 };
889 store.agent_def_insert(&mut def).unwrap();
890
891 let claude = make_account(
892 "acct-empty-dir",
893 "claude",
894 SecretRef::OAuthConfigDir { dir: String::new() },
895 );
896 store.identity_upsert(&claude).unwrap();
897 store
898 .agent_identity_link("def-1", "acct-empty-dir", "claude")
899 .unwrap();
900
901 insert_block_for_agent(&store, "block-empty-dir", "def-1");
902 let inst = make_instance("block-empty-dir", "id-empty-dir");
903 store.instance_create(&inst).unwrap();
904
905 let mut env: HashMap<String, String> = HashMap::new();
906 let err = inject_identity_env(store.clone(), store.clone(), store, "block-empty-dir", &mut env)
907 .expect_err("spawn must be refused when the CLAUDE.md isolation seed fails");
908
909 match err {
910 SpawnGateError::ClaudeMdSeedFailed { provider, dir, .. } => {
911 assert_eq!(provider, "claude");
912 assert_eq!(dir, "");
913 }
914 other => panic!("expected ClaudeMdSeedFailed, got {other:?}"),
915 }
916 assert!(env.get("CLAUDE_CONFIG_DIR").is_none());
919 }
920
921 #[cfg(debug_assertions)]
941 #[test]
942 fn inject_refuses_an_account_that_only_exists_in_the_global_mirror() {
943 let mstore = make_store();
944 let id_store = make_store();
947 let identity_store_tmp = tempfile::NamedTempFile::new().unwrap();
955 let identity_store = Arc::new(Store::open_identity_store(identity_store_tmp.path()).unwrap());
956
957 let mut def = crate::backend::storage::store::AgentDefinition {
958 slug: String::new(),
959 icon: "✦".to_string(),
960 ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
961 };
962 mstore.agent_def_insert(&mut def).unwrap();
963
964 let claude = make_account(
965 "acct-migrated",
966 "claude",
967 SecretRef::OAuthConfigDir {
968 dir: test_config_dir("id-migrated"),
969 },
970 );
971 identity_store.identity_upsert(&claude).unwrap();
972 identity_store
973 .agent_identity_link("def-1", "acct-migrated", "claude")
974 .unwrap();
975
976 insert_block_for_agent(&mstore, "block-continuing", "def-1");
977 let inst = make_instance("block-continuing", "id-continuing");
978 mstore.instance_create(&inst).unwrap();
979
980 let mut env: HashMap<String, String> = HashMap::new();
981 let res = inject_identity_env(mstore, id_store, identity_store, "block-continuing", &mut env);
982
983 assert!(
984 matches!(res, Err(SpawnGateError::MissingCredentials { .. })),
985 "an account that exists ONLY in the global mirror must NOT satisfy a spawn in \
986 this channel — that is the per-channel-isolation bypass; expected \
987 MissingCredentials, got {res:?}"
988 );
989 assert!(
990 env.get("CLAUDE_CONFIG_DIR").is_none(),
991 "nothing may be injected from a refused cross-channel account"
992 );
993 }
994
995 #[cfg(debug_assertions)]
1010 #[test]
1011 fn inject_refuses_a_mirror_written_account_after_a_channel_switch() {
1012 let mstore = make_store();
1013 let id_store = make_store();
1014 let identity_store_tmp = tempfile::NamedTempFile::new().unwrap();
1015 let identity_store = Arc::new(Store::open_identity_store(identity_store_tmp.path()).unwrap());
1016
1017 let mut def = crate::backend::storage::store::AgentDefinition {
1020 slug: String::new(),
1021 icon: "✦".to_string(),
1022 ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
1023 };
1024 mstore.agent_def_insert(&mut def).unwrap();
1025
1026 let claude = make_account(
1031 "acct-fresh",
1032 "claude",
1033 SecretRef::OAuthConfigDir {
1034 dir: test_config_dir("id-fresh"),
1035 },
1036 );
1037 id_store.identity_upsert_with_mirror(&identity_store, &claude).unwrap();
1038 identity_store
1039 .agent_identity_link("def-1", "acct-fresh", "claude")
1040 .unwrap();
1041
1042 insert_block_for_agent(&mstore, "block-fresh", "def-1");
1043 let inst = make_instance("block-fresh", "id-fresh");
1044 mstore.instance_create(&inst).unwrap();
1045
1046 let id_store_after_switch = make_store();
1050
1051 let mut env: HashMap<String, String> = HashMap::new();
1052 let res = inject_identity_env(mstore, id_store_after_switch, identity_store, "block-fresh", &mut env);
1053
1054 assert!(
1055 matches!(res, Err(SpawnGateError::MissingCredentials { .. })),
1056 "REVERSED 2026-08-31: a mirror row must no longer carry a spawn across a channel \
1057 switch, however it was written — dual-writing the mirror is not a substitute for \
1058 logging in on this channel; expected MissingCredentials, got {res:?}"
1059 );
1060 assert!(env.get("CLAUDE_CONFIG_DIR").is_none());
1061 }
1062
1063 #[cfg(debug_assertions)]
1069 #[test]
1070 fn inject_oauth_class_links_conversation_history_on_the_ordinary_spawn_path() {
1071 let _lock = crate::test_support::ISOLATED_AUTH_ENV_LOCK
1072 .lock()
1073 .unwrap_or_else(|e| e.into_inner());
1074 let tmp = tempfile::TempDir::new().unwrap();
1075 std::env::set_var("AGENTMUX_HOME_OVERRIDE", tmp.path());
1076 std::env::set_var("AGENTMUX_ISOLATED_AUTH", "1");
1077 let paths = agentmux_common::DataPaths::resolve(
1078 "0.0.0-test",
1079 &agentmux_common::RuntimeMode::Installed,
1080 )
1081 .unwrap();
1082 paths.ensure_dirs().unwrap();
1083 for (k, v) in paths.to_env_vars() {
1084 std::env::set_var(k, v);
1085 }
1086
1087 let isolated_dir = paths.instance_dir.join("identities").join("acct-claude").join("claude");
1092 std::fs::create_dir_all(isolated_dir.join("projects")).unwrap();
1093 std::fs::write(
1094 isolated_dir.join("projects").join("existing-session.jsonl"),
1095 b"pre-existing history",
1096 )
1097 .unwrap();
1098
1099 let store = make_store();
1100 let mut def = crate::backend::storage::store::AgentDefinition {
1101 slug: String::new(),
1102 icon: "✦".to_string(),
1103 ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
1104 };
1105 store.agent_def_insert(&mut def).unwrap();
1106
1107 let claude = make_account(
1108 "acct-claude",
1109 "claude",
1110 SecretRef::OAuthConfigDir { dir: isolated_dir.to_string_lossy().to_string() },
1111 );
1112 store.identity_upsert(&claude).unwrap();
1113 store.agent_identity_link("def-1", "acct-claude", "claude").unwrap();
1114 insert_block_for_agent(&store, "block-oauth-history", "def-1");
1115 let inst = make_instance("block-oauth-history", "id-oauth");
1116 store.instance_create(&inst).unwrap();
1117
1118 let mut env: HashMap<String, String> = HashMap::new();
1119 inject_identity_env(store.clone(), store.clone(), store, "block-oauth-history", &mut env).unwrap();
1120
1121 let global_history = paths.identity_history_dir("acct-claude", "claude", "projects");
1122 let via_link = std::fs::read(global_history.join("existing-session.jsonl"))
1123 .expect("pre-existing history must have been migrated to the global location by the spawn-time link");
1124 assert_eq!(via_link, b"pre-existing history");
1125
1126 std::env::remove_var("AGENTMUX_HOME_OVERRIDE");
1127 std::env::remove_var("AGENTMUX_ISOLATED_AUTH");
1128 for (k, _) in paths.to_env_vars() {
1129 std::env::remove_var(k);
1130 }
1131 }
1132
1133 #[cfg(debug_assertions)]
1134 #[test]
1135 fn inject_oauth_class_blocks_account_with_non_oauth_secret_ref() {
1136 let store = make_store();
1143
1144 let mut def = crate::backend::storage::store::AgentDefinition {
1145 slug: String::new(),
1146 icon: "✦".to_string(),
1147 ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
1148 };
1149 store.agent_def_insert(&mut def).unwrap();
1150
1151 let bad = make_account(
1152 "acct-bad",
1153 "claude",
1154 SecretRef::Env {
1155 env_var: "CLAUDE_TOKEN_NOT_A_DIR".to_string(),
1156 },
1157 );
1158 store.identity_upsert(&bad).unwrap();
1159 store
1160 .agent_identity_link("def-1", "acct-bad", "claude")
1161 .unwrap();
1162
1163 insert_block_for_agent(&store, "block-bad", "def-1");
1164 let inst = make_instance("block-bad", "id-bad");
1165 store.instance_create(&inst).unwrap();
1166
1167 let mut env: HashMap<String, String> = HashMap::new();
1168 let res = inject_identity_env(store.clone(), store.clone(), store, "block-bad", &mut env);
1169
1170 assert_eq!(
1172 res,
1173 Err(SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: true }),
1174 );
1175 assert!(env.get("CLAUDE_CONFIG_DIR").is_none());
1176 assert!(env.is_empty());
1177 }
1178
1179 #[cfg(debug_assertions)]
1180 #[test]
1181 fn inject_oauth_class_succeeds_when_the_only_binding_is_under_a_legacy_alias() {
1182 let store = make_store();
1194
1195 let mut def = crate::backend::storage::store::AgentDefinition {
1196 slug: String::new(),
1197 icon: "✦".to_string(),
1198 ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
1199 };
1200 store.agent_def_insert(&mut def).unwrap();
1201
1202 let claude = make_account(
1203 "acct-alias",
1204 "claude-code",
1205 SecretRef::OAuthConfigDir {
1206 dir: test_config_dir("id-alias"),
1207 },
1208 );
1209 store.identity_upsert(&claude).unwrap();
1210 store
1212 .agent_identity_link("def-1", "acct-alias", "claude-code")
1213 .unwrap();
1214
1215 insert_block_for_agent(&store, "block-alias", "def-1");
1216 let inst = make_instance("block-alias", "id-alias");
1217 store.instance_create(&inst).unwrap();
1218
1219 let mut env: HashMap<String, String> = HashMap::new();
1220 let res = inject_identity_env(store.clone(), store.clone(), store, "block-alias", &mut env);
1221
1222 assert!(res.is_ok(), "expected Ok, got {res:?}");
1223 assert_eq!(
1224 env.get("CLAUDE_CONFIG_DIR").cloned(),
1225 Some(test_config_dir("id-alias")),
1226 );
1227 }
1228
1229 fn gate_def(use_ambient_login: i64) -> crate::backend::storage::store::AgentDefinition {
1235 crate::backend::storage::store::AgentDefinition {
1236 slug: String::new(),
1237 icon: "✦".to_string(),
1238 use_ambient_login,
1239 ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
1240 }
1241 }
1242
1243 fn delete_account_row_keep_link(store: &Store, account_id: &str) {
1249 let conn = store.conn().lock().unwrap();
1250 conn.execute_batch(&format!(
1251 "PRAGMA foreign_keys=OFF;
1252 DELETE FROM db_accounts WHERE id = '{account_id}';
1253 PRAGMA foreign_keys=ON;"
1254 ))
1255 .unwrap();
1256 }
1257
1258 #[test]
1259 fn spawn_blocked_when_bound_oauth_account_missing_and_flag_false() {
1260 let store = make_store();
1263 let mut def = gate_def(0);
1264 store.agent_def_insert(&mut def).unwrap();
1265
1266 let claude = make_account(
1267 "acct-gone",
1268 "claude",
1269 SecretRef::OAuthConfigDir {
1270 dir: test_config_dir("id-x"),
1271 },
1272 );
1273 store.identity_upsert(&claude).unwrap();
1274 store
1275 .agent_identity_link("def-1", "acct-gone", "claude")
1276 .unwrap();
1277 delete_account_row_keep_link(&store, "acct-gone");
1281
1282 insert_block_for_agent(&store, "block-gate-1", "def-1");
1283 let inst = make_instance("block-gate-1", "id-x");
1284 store.instance_create(&inst).unwrap();
1285
1286 let mut env: HashMap<String, String> = HashMap::new();
1287 let res = inject_identity_env(store.clone(), store.clone(), store, "block-gate-1", &mut env);
1288
1289 assert_eq!(
1290 res,
1291 Err(SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: true }),
1292 );
1293 assert!(env.is_empty());
1295 let msg = res.unwrap_err().to_string();
1298 assert!(msg.contains("no credentials for claude"), "got: {msg}");
1299 assert!(msg.contains("Bind an account for this provider in Connectors → Accounts"), "got: {msg}");
1300 }
1301
1302 #[test]
1303 fn spawn_still_blocked_when_bound_oauth_account_missing_and_flag_true() {
1304 let store = make_store();
1311 let mut def = gate_def(1);
1312 store.agent_def_insert(&mut def).unwrap();
1313
1314 let claude = make_account(
1315 "acct-gone-2",
1316 "claude",
1317 SecretRef::OAuthConfigDir {
1318 dir: test_config_dir("id-y"),
1319 },
1320 );
1321 store.identity_upsert(&claude).unwrap();
1322 store
1323 .agent_identity_link("def-1", "acct-gone-2", "claude")
1324 .unwrap();
1325 delete_account_row_keep_link(&store, "acct-gone-2");
1326
1327 insert_block_for_agent(&store, "block-gate-2", "def-1");
1328 let inst = make_instance("block-gate-2", "id-y");
1329 store.instance_create(&inst).unwrap();
1330
1331 let mut env: HashMap<String, String> = HashMap::new();
1332 let res = inject_identity_env(store.clone(), store.clone(), store, "block-gate-2", &mut env);
1333
1334 assert_eq!(
1335 res,
1336 Err(SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: true }),
1337 );
1338 assert!(env.is_empty());
1339 }
1340
1341 #[test]
1342 fn spawn_blocked_when_oauth_def_provider_has_no_binding_and_flag_false() {
1343 let store = make_store();
1362 let mut def = gate_def(0);
1363 store.agent_def_insert(&mut def).unwrap();
1364
1365 insert_block_for_agent(&store, "block-gate-3", "def-1");
1366 let inst = make_instance("block-gate-3", "id-z");
1367 store.instance_create(&inst).unwrap();
1368
1369 let mut env: HashMap<String, String> = HashMap::new();
1370 let res = inject_identity_env(store.clone(), store.clone(), store, "block-gate-3", &mut env);
1371
1372 assert_eq!(
1373 res,
1374 Err(SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: false }),
1375 );
1376 assert!(env.is_empty());
1377 }
1378
1379 #[test]
1406 fn spawn_is_gated_for_a_template_launch_with_no_binding_where_it_used_to_be_invisible_to_the_gate() {
1407 let store = make_store();
1408 let mut tpl = gate_def(1); tpl.id = "tpl-ambient".to_string();
1410 tpl.is_seeded = 1;
1411 store.agent_def_insert(&mut tpl).unwrap();
1412
1413 let inst = crate::backend::storage::store::AgentInstance {
1417 identity_id: "id-ambient".to_string(),
1418 ..crate::backend::storage::agents::test_agent_instance("launch-ambient", "tpl-ambient", "block-gate-ambient", 0)
1419 };
1420 let canonical = store.instance_create(&inst).unwrap();
1421 assert_eq!(canonical.id, "launch-ambient", "sanity: a template launch creates its own row");
1422
1423 insert_block_for_agent(&store, "block-gate-ambient", "launch-ambient");
1424
1425 let mut env: HashMap<String, String> = HashMap::new();
1426 let res = inject_identity_env(store.clone(), store.clone(), store, "block-gate-ambient", &mut env);
1427
1428 assert_eq!(
1429 res,
1430 Err(SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: false }),
1431 "a template launch's zero-binding oauth-class provider must now reach Step 5's gate, not skip it",
1432 );
1433 assert!(env.is_empty());
1434 }
1435
1436 #[test]
1445 fn spawn_proceeds_when_a_template_launch_inherits_the_templates_own_identity_link() {
1446 let store = make_store();
1447 let mut tpl = gate_def(0);
1448 tpl.id = "tpl-bound".to_string();
1449 tpl.is_seeded = 1;
1450 store.agent_def_insert(&mut tpl).unwrap();
1451
1452 let claude = make_account(
1453 "acct-tpl",
1454 "claude",
1455 SecretRef::OAuthConfigDir { dir: test_config_dir("id-tpl-bound") },
1456 );
1457 store.identity_upsert(&claude).unwrap();
1458 store.agent_identity_link("tpl-bound", "acct-tpl", "claude").unwrap();
1461
1462 let inst = crate::backend::storage::store::AgentInstance {
1463 identity_id: "id-tpl-bound".to_string(),
1464 ..crate::backend::storage::agents::test_agent_instance("launch-bound", "tpl-bound", "block-gate-bound", 0)
1465 };
1466 let canonical = store.instance_create(&inst).unwrap();
1467 assert_eq!(canonical.id, "launch-bound", "sanity: a template launch creates its own row");
1468 assert!(store.agent_identity_list_for_agent("launch-bound").unwrap().is_empty());
1472
1473 insert_block_for_agent(&store, "block-gate-bound", "launch-bound");
1474
1475 let mut env: HashMap<String, String> = HashMap::new();
1476 let res = inject_identity_env(store.clone(), store.clone(), store, "block-gate-bound", &mut env);
1477
1478 assert_eq!(res, Ok(()), "a template's own real binding must still let its launches spawn");
1479 assert_eq!(
1480 env.get("CLAUDE_CONFIG_DIR").map(String::as_str),
1481 Some(test_config_dir("id-tpl-bound").as_str()),
1482 "the template's bound config dir must actually be injected, not just pass the gate",
1483 );
1484 }
1485
1486 #[test]
1499 fn a_fork_of_a_regular_agent_does_not_inherit_the_sources_identity_link() {
1500 let store = make_store();
1501 let mut source = gate_def(0);
1502 source.id = "agent-source".to_string();
1503 source.is_seeded = 0; store.agent_def_insert(&mut source).unwrap();
1505
1506 let claude = make_account(
1507 "acct-source",
1508 "claude",
1509 SecretRef::OAuthConfigDir { dir: test_config_dir("id-source-only") },
1510 );
1511 store.identity_upsert(&claude).unwrap();
1512 store.agent_identity_link("agent-source", "acct-source", "claude").unwrap();
1513
1514 let mut fork = gate_def(0);
1518 fork.id = "agent-fork".to_string();
1519 fork.is_seeded = 0;
1520 fork.parent_id = "agent-source".to_string();
1521 fork.accounts = String::new();
1522 store.agent_def_insert(&mut fork).unwrap();
1523
1524 let inst = crate::backend::storage::store::AgentInstance {
1525 identity_id: "id-fork".to_string(),
1526 ..crate::backend::storage::agents::test_agent_instance("agent-fork", "agent-fork", "block-gate-fork", 0)
1527 };
1528 let canonical = store.instance_create(&inst).unwrap();
1529 assert_eq!(canonical.id, "agent-fork", "sanity: a fork of a non-template agent folds into its own row");
1530 assert!(store.agent_identity_list_for_agent("agent-fork").unwrap().is_empty(), "sanity: the fork has no link of its own");
1531
1532 insert_block_for_agent(&store, "block-gate-fork", "agent-fork");
1533
1534 let mut env: HashMap<String, String> = HashMap::new();
1535 let res = inject_identity_env(store.clone(), store.clone(), store, "block-gate-fork", &mut env);
1536
1537 assert_eq!(
1538 res,
1539 Err(SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: false }),
1540 "a fork must NOT silently inherit and spawn on its source agent's credentials",
1541 );
1542 assert!(env.is_empty(), "nothing must be injected — especially not the source's config dir");
1543 }
1544
1545 #[test]
1546 fn inject_no_instance_does_nothing() {
1547 let store = make_store();
1548 let mut env: HashMap<String, String> = HashMap::new();
1549 inject_identity_env(store.clone(), store.clone(), store, "block-no-instance", &mut env).unwrap();
1550 assert!(env.is_empty());
1551 }
1552
1553 pub mod blank_identity;
1556
1557 #[cfg(debug_assertions)]
1558 #[test]
1559 fn inject_full_round_trip_plaintext_dev() {
1560 let store = make_store();
1561
1562 let mut def = crate::backend::storage::store::AgentDefinition {
1564 seat: None,
1565 conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
1566 id: "def-1".to_string(),
1567 slug: String::new(),
1568 name: "T".to_string(),
1569 icon: "✦".to_string(),
1570 provider: "openai".to_string(),
1578 description: String::new(),
1579 working_directory: String::new(),
1580 shell: String::new(),
1581 provider_flags: String::new(),
1582 auto_start: 0,
1583 restart_on_crash: 0,
1584 idle_timeout_minutes: 0,
1585 created_at: 0,
1586 agent_type: String::new(),
1587 environment: String::new(),
1588 agent_bus_id: String::new(),
1589 is_seeded: 0,
1590 accounts: String::new(),
1591 parent_id: String::new(),
1592 branch_label: String::new(),
1593 updated_at: 0,
1594 user_hidden: 0,
1595 container_image: String::new(),
1596 container_volumes: "[]".to_string(),
1597 container_name: String::new(),
1598 use_ambient_login: 0,
1599 model_vendor_base_url: String::new(),
1600 memory_id: String::new(),
1601 };
1602 store.agent_def_insert(&mut def).unwrap();
1603
1604 let github = make_account(
1606 "acct-gh",
1607 "github",
1608 SecretRef::PlaintextDev {
1609 plaintext_dev: r#"{"access_token":"gho_round_trip","refresh_token":null,"expires_at":0}"#.to_string(),
1610 },
1611 );
1612 store.identity_upsert(&github).unwrap();
1613 store
1614 .agent_identity_link("def-1", "acct-gh", "github")
1615 .unwrap();
1616
1617 let anthropic = make_account(
1619 "acct-anth",
1620 "anthropic",
1621 SecretRef::PlaintextDev {
1622 plaintext_dev: "sk-ant-round_trip".to_string(),
1623 },
1624 );
1625 store.identity_upsert(&anthropic).unwrap();
1626 store
1627 .agent_identity_link("def-1", "acct-anth", "anthropic")
1628 .unwrap();
1629
1630 insert_block_for_agent(&store, "block-1", "def-1");
1632 let inst = make_instance("block-1", "id-work");
1633 store.instance_create(&inst).unwrap();
1634
1635 let mut env: HashMap<String, String> = HashMap::new();
1636 inject_identity_env(store.clone(), store.clone(), store, "block-1", &mut env).unwrap();
1637
1638 assert_eq!(env.get("GITHUB_TOKEN").map(String::as_str), Some("gho_round_trip"));
1640 assert_eq!(env.get("GH_TOKEN").map(String::as_str), Some("gho_round_trip"));
1641 assert_eq!(
1643 env.get("ANTHROPIC_API_KEY").map(String::as_str),
1644 Some("sk-ant-round_trip"),
1645 );
1646 }
1647
1648 #[cfg(debug_assertions)]
1649 #[test]
1650 fn inject_via_direct_link_round_trip() {
1651 let store = make_store();
1654
1655 let mut def = crate::backend::storage::store::AgentDefinition {
1656 seat: None,
1657 conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
1658 id: "def-1".to_string(),
1659 slug: String::new(),
1660 name: "T".to_string(),
1661 icon: "✦".to_string(),
1662 provider: "openai".to_string(),
1665 description: String::new(),
1666 working_directory: String::new(),
1667 shell: String::new(),
1668 provider_flags: String::new(),
1669 auto_start: 0,
1670 restart_on_crash: 0,
1671 idle_timeout_minutes: 0,
1672 created_at: 0,
1673 agent_type: String::new(),
1674 environment: String::new(),
1675 agent_bus_id: String::new(),
1676 is_seeded: 0,
1677 accounts: String::new(),
1678 parent_id: String::new(),
1679 branch_label: String::new(),
1680 updated_at: 0,
1681 user_hidden: 0,
1682 container_image: String::new(),
1683 container_volumes: "[]".to_string(),
1684 container_name: String::new(),
1685 use_ambient_login: 0,
1686 model_vendor_base_url: String::new(),
1687 memory_id: String::new(),
1688 };
1689 store.agent_def_insert(&mut def).unwrap();
1690
1691 let github = make_account(
1692 "acct-gh",
1693 "github",
1694 SecretRef::PlaintextDev {
1695 plaintext_dev: "ghp_direct".to_string(),
1696 },
1697 );
1698 store.identity_upsert(&github).unwrap();
1699 store
1700 .agent_identity_link("def-1", "acct-gh", "github")
1701 .unwrap();
1702
1703 insert_block_for_agent(&store, "block-direct", "def-1");
1704 let inst = make_instance("block-direct", "id-direct");
1705 store.instance_create(&inst).unwrap();
1706
1707 let mut env: HashMap<String, String> = HashMap::new();
1708 inject_identity_env(store.clone(), store.clone(), store, "block-direct", &mut env).unwrap();
1709
1710 assert_eq!(env.get("GITHUB_TOKEN").map(String::as_str), Some("ghp_direct"));
1711 assert_eq!(env.get("GH_TOKEN").map(String::as_str), Some("ghp_direct"));
1712 }
1713
1714 #[cfg(debug_assertions)]
1715 #[test]
1716 fn inject_no_direct_links_injects_nothing() {
1717 let store = make_store();
1721
1722 let mut def = crate::backend::storage::store::AgentDefinition {
1723 seat: None,
1724 conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
1725 id: "def-1".to_string(),
1726 slug: String::new(),
1727 name: "T".to_string(),
1728 icon: "✦".to_string(),
1729 provider: "openai".to_string(),
1734 description: String::new(),
1735 working_directory: String::new(),
1736 shell: String::new(),
1737 provider_flags: String::new(),
1738 auto_start: 0,
1739 restart_on_crash: 0,
1740 idle_timeout_minutes: 0,
1741 created_at: 0,
1742 agent_type: String::new(),
1743 environment: String::new(),
1744 agent_bus_id: String::new(),
1745 is_seeded: 0,
1746 accounts: String::new(),
1747 parent_id: String::new(),
1748 branch_label: String::new(),
1749 updated_at: 0,
1750 user_hidden: 0,
1751 container_image: String::new(),
1752 container_volumes: "[]".to_string(),
1753 container_name: String::new(),
1754 use_ambient_login: 0,
1755 model_vendor_base_url: String::new(),
1756 memory_id: String::new(),
1757 };
1758 store.agent_def_insert(&mut def).unwrap();
1759
1760 let github = make_account(
1761 "acct-unlinked",
1762 "github",
1763 SecretRef::PlaintextDev {
1764 plaintext_dev: "ghp_unlinked".to_string(),
1765 },
1766 );
1767 store.identity_upsert(&github).unwrap();
1768
1769 insert_block_for_agent(&store, "block-unlinked", "def-1");
1770 let inst = make_instance("block-unlinked", "id-unused");
1771 store.instance_create(&inst).unwrap();
1772
1773 let mut env: HashMap<String, String> = HashMap::new();
1774 inject_identity_env(store.clone(), store.clone(), store, "block-unlinked", &mut env).unwrap();
1775
1776 assert!(env.get("GITHUB_TOKEN").is_none());
1779 assert!(env.is_empty());
1780 }
1781
1782 #[cfg(debug_assertions)]
1783 #[test]
1784 fn inject_no_direct_links_publishes_event() {
1785 let store = make_store();
1790
1791 let mut def = crate::backend::storage::store::AgentDefinition {
1792 seat: None,
1793 conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
1794 id: "def-1".to_string(),
1795 slug: String::new(),
1796 name: "T".to_string(),
1797 icon: "✦".to_string(),
1798 provider: "openai".to_string(),
1801 description: String::new(),
1802 working_directory: String::new(),
1803 shell: String::new(),
1804 provider_flags: String::new(),
1805 auto_start: 0,
1806 restart_on_crash: 0,
1807 idle_timeout_minutes: 0,
1808 created_at: 0,
1809 agent_type: String::new(),
1810 environment: String::new(),
1811 agent_bus_id: String::new(),
1812 is_seeded: 0,
1813 accounts: String::new(),
1814 parent_id: String::new(),
1815 branch_label: String::new(),
1816 updated_at: 0,
1817 user_hidden: 0,
1818 container_image: String::new(),
1819 container_volumes: "[]".to_string(),
1820 container_name: String::new(),
1821 use_ambient_login: 0,
1822 model_vendor_base_url: String::new(),
1823 memory_id: String::new(),
1824 };
1825 store.agent_def_insert(&mut def).unwrap();
1826
1827 let github = make_account(
1828 "acct-unlinked-2",
1829 "github",
1830 SecretRef::PlaintextDev {
1831 plaintext_dev: "ghp_unlinked_2".to_string(),
1832 },
1833 );
1834 store.identity_upsert(&github).unwrap();
1835
1836 insert_block_for_agent(&store, "block-unlinked-2", "def-1");
1837 let inst = make_instance("block-unlinked-2", "id-unused-2");
1838 store.instance_create(&inst).unwrap();
1839
1840 let broker = Arc::new(Broker::new());
1841 let mut env: HashMap<String, String> = HashMap::new();
1842 inject_identity_env_with_broker(
1843 store.clone(),
1844 store.clone(),
1845 store,
1846 Some(broker.clone()),
1847 "block-unlinked-2",
1848 &mut env,
1849 )
1850 .unwrap();
1851
1852 let history = broker.read_event_history("identity:no-direct-links", "", 10);
1856 let event = history.last().expect("expected identity:no-direct-links event");
1857 assert_eq!(
1858 event.data.as_ref().and_then(|d| d.get("definition_id")).and_then(|v| v.as_str()),
1859 Some("def-1"),
1860 );
1861 }
1862
1863 #[cfg(debug_assertions)]
1864 #[test]
1865 fn inject_partial_success_skips_failed_bindings() {
1866 let store = make_store();
1867
1868 let mut def = crate::backend::storage::store::AgentDefinition {
1869 seat: None,
1870 conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
1871 id: "def-1".to_string(),
1872 slug: String::new(),
1873 name: "T".to_string(),
1874 icon: "✦".to_string(),
1875 provider: "openai".to_string(),
1879 description: String::new(),
1880 working_directory: String::new(),
1881 shell: String::new(),
1882 provider_flags: String::new(),
1883 auto_start: 0,
1884 restart_on_crash: 0,
1885 idle_timeout_minutes: 0,
1886 created_at: 0,
1887 agent_type: String::new(),
1888 environment: String::new(),
1889 agent_bus_id: String::new(),
1890 is_seeded: 0,
1891 accounts: String::new(),
1892 parent_id: String::new(),
1893 branch_label: String::new(),
1894 updated_at: 0,
1895 user_hidden: 0,
1896 container_image: String::new(),
1897 container_volumes: "[]".to_string(),
1898 container_name: String::new(),
1899 use_ambient_login: 0,
1900 model_vendor_base_url: String::new(),
1901 memory_id: String::new(),
1902 };
1903 store.agent_def_insert(&mut def).unwrap();
1904
1905 let good = make_account(
1907 "acct-good",
1908 "github",
1909 SecretRef::PlaintextDev {
1910 plaintext_dev: "ghp_good".to_string(),
1911 },
1912 );
1913 store.identity_upsert(&good).unwrap();
1914 store
1915 .agent_identity_link("def-1", "acct-good", "github")
1916 .unwrap();
1917
1918 let bad = make_account(
1920 "acct-bad",
1921 "anthropic",
1922 SecretRef::Env {
1923 env_var: "AGENTMUX_TEST_DEFINITELY_NOT_SET_4242".to_string(),
1924 },
1925 );
1926 store.identity_upsert(&bad).unwrap();
1927 store
1928 .agent_identity_link("def-1", "acct-bad", "anthropic")
1929 .unwrap();
1930
1931 insert_block_for_agent(&store, "block-mixed", "def-1");
1932 let inst = make_instance("block-mixed", "id-mixed");
1933 store.instance_create(&inst).unwrap();
1934
1935 let mut env: HashMap<String, String> = HashMap::new();
1936 inject_identity_env(store.clone(), store.clone(), store, "block-mixed", &mut env).unwrap();
1937
1938 assert_eq!(env.get("GITHUB_TOKEN").map(String::as_str), Some("ghp_good"));
1940 assert_eq!(env.get("GH_TOKEN").map(String::as_str), Some("ghp_good"));
1941 assert!(env.get("ANTHROPIC_API_KEY").is_none());
1943 }
1944
1945 #[cfg(debug_assertions)]
1946 #[test]
1947 fn inject_unknown_provider_is_skipped() {
1948 let store = make_store();
1949
1950 let mut def = crate::backend::storage::store::AgentDefinition {
1951 seat: None,
1952 conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
1953 id: "def-1".to_string(),
1954 slug: String::new(),
1955 name: "T".to_string(),
1956 icon: "✦".to_string(),
1957 provider: "openai".to_string(),
1960 description: String::new(),
1961 working_directory: String::new(),
1962 shell: String::new(),
1963 provider_flags: String::new(),
1964 auto_start: 0,
1965 restart_on_crash: 0,
1966 idle_timeout_minutes: 0,
1967 created_at: 0,
1968 agent_type: String::new(),
1969 environment: String::new(),
1970 agent_bus_id: String::new(),
1971 is_seeded: 0,
1972 accounts: String::new(),
1973 parent_id: String::new(),
1974 branch_label: String::new(),
1975 updated_at: 0,
1976 user_hidden: 0,
1977 container_image: String::new(),
1978 container_volumes: "[]".to_string(),
1979 container_name: String::new(),
1980 use_ambient_login: 0,
1981 model_vendor_base_url: String::new(),
1982 memory_id: String::new(),
1983 };
1984 store.agent_def_insert(&mut def).unwrap();
1985
1986 let custom = make_account(
1987 "acct-custom",
1988 "custom",
1989 SecretRef::PlaintextDev {
1990 plaintext_dev: "ignored".to_string(),
1991 },
1992 );
1993 store.identity_upsert(&custom).unwrap();
1994 store
1995 .agent_identity_link("def-1", "acct-custom", "custom")
1996 .unwrap();
1997
1998 insert_block_for_agent(&store, "block-future", "def-1");
1999 let inst = make_instance("block-future", "id-future");
2000 store.instance_create(&inst).unwrap();
2001
2002 let mut env: HashMap<String, String> = HashMap::new();
2003 inject_identity_env(store.clone(), store.clone(), store, "block-future", &mut env).unwrap();
2004 assert!(env.is_empty());
2006 }
2007
2008 fn write_claude_creds(
2017 dir: &std::path::Path,
2018 expires_ms: i64,
2019 with_refresh: bool,
2020 ) {
2021 std::fs::create_dir_all(dir).unwrap();
2022 let body = serde_json::json!({
2023 "claudeAiOauth": {
2024 "accessToken": "test-access",
2025 "refreshToken": if with_refresh { "test-refresh" } else { "" },
2026 "expiresAt": expires_ms,
2027 }
2028 });
2029 std::fs::write(
2030 dir.join(".credentials.json"),
2031 serde_json::to_string(&body).unwrap(),
2032 )
2033 .unwrap();
2034 }
2035
2036 #[cfg(debug_assertions)]
2037 #[test]
2038 fn inject_oauth_class_probes_and_flips_status_to_needs_reauth() {
2039 let store = make_store();
2052
2053 let mut def = crate::backend::storage::store::AgentDefinition {
2054 slug: String::new(),
2055 icon: "✦".to_string(),
2056 ..crate::backend::storage::agents::test_agent_def("def-1", "T", "codex", "", 0, "")
2057 };
2058 store.agent_def_insert(&mut def).unwrap();
2059
2060 let tmp = tempfile::tempdir().unwrap();
2063 let bundle_dir = tmp.path().to_str().unwrap().to_string();
2064
2065 let codex_acct = IdentityAccount {
2066 id: "acct-codex".to_string(),
2067 name: "codex-acct-codex".to_string(),
2068 provider: "codex".to_string(),
2069 kind: "oauth".to_string(),
2070 display_name: String::new(),
2071 secret_ref: SecretRef::OAuthConfigDir { dir: bundle_dir },
2072 context: serde_json::json!({}),
2073 status: oauth_status::VALID.to_string(),
2076 created_at: 0,
2077 updated_at: 0,
2078 };
2079 store.identity_upsert(&codex_acct).unwrap();
2080 store
2081 .agent_identity_link("def-1", "acct-codex", "codex")
2082 .unwrap();
2083
2084 insert_block_for_agent(&store, "block-probe", "def-1");
2085 let inst = make_instance("block-probe", "id-probe");
2086 store.instance_create(&inst).unwrap();
2087
2088 let mut env: HashMap<String, String> = HashMap::new();
2089 inject_identity_env(store.clone(), store.clone(), store.clone(), "block-probe", &mut env).unwrap();
2090
2091 assert!(env.get("CODEX_HOME").is_some());
2095
2096 let after = store.identity_get("acct-codex").unwrap().unwrap();
2098 assert_eq!(after.status, oauth_status::NEEDS_REAUTH);
2099 }
2100
2101 #[cfg(target_os = "macos")]
2102 #[cfg(debug_assertions)]
2103 #[test]
2104 fn inject_oauth_class_self_heals_stale_needs_reauth_for_claude_on_macos() {
2105 let store = make_store();
2113
2114 let mut def = gate_def(0);
2116 store.agent_def_insert(&mut def).unwrap();
2117
2118 let tmp = tempfile::tempdir().unwrap();
2122 let bundle_dir = tmp.path().to_str().unwrap().to_string();
2123
2124 let stale = IdentityAccount {
2125 id: "acct-stale".to_string(),
2126 name: "claude-acct-stale".to_string(),
2127 provider: "claude".to_string(),
2128 kind: "oauth".to_string(),
2129 display_name: String::new(),
2130 secret_ref: SecretRef::OAuthConfigDir { dir: bundle_dir },
2131 context: serde_json::json!({}),
2132 status: oauth_status::NEEDS_REAUTH.to_string(),
2133 created_at: 0,
2134 updated_at: 0,
2135 };
2136 store.identity_upsert(&stale).unwrap();
2137 store
2138 .agent_identity_link("def-1", "acct-stale", "claude")
2139 .unwrap();
2140
2141 insert_block_for_agent(&store, "block-self-heal", "def-1");
2142 let inst = make_instance("block-self-heal", "id-self-heal");
2143 store.instance_create(&inst).unwrap();
2144
2145 let mut env: HashMap<String, String> = HashMap::new();
2146 inject_identity_env(store.clone(), store.clone(), store.clone(), "block-self-heal", &mut env).unwrap();
2147
2148 let after = store.identity_get("acct-stale").unwrap().unwrap();
2149 assert_eq!(
2150 after.status, "unknown",
2151 "a stale pre-carve-out needs_reauth must self-heal to unknown, not stay stuck"
2152 );
2153 }
2154
2155 #[cfg(debug_assertions)]
2156 #[test]
2157 fn inject_oauth_class_probe_canonicalizes_a_legacy_alias_binding() {
2158 let store = make_store();
2174
2175 let mut def = crate::backend::storage::store::AgentDefinition {
2176 slug: String::new(),
2177 icon: "✦".to_string(),
2178 ..crate::backend::storage::agents::test_agent_def("def-1", "T", "codex", "", 0, "")
2179 };
2180 store.agent_def_insert(&mut def).unwrap();
2181
2182 let tmp = tempfile::tempdir().unwrap();
2183 let bundle_dir = tmp.path().to_str().unwrap().to_string();
2184
2185 let codex_acct = IdentityAccount {
2186 id: "acct-alias".to_string(),
2187 name: "codex-cli-acct-alias".to_string(),
2188 provider: "codex-cli".to_string(),
2189 kind: "oauth".to_string(),
2190 display_name: String::new(),
2191 secret_ref: SecretRef::OAuthConfigDir { dir: bundle_dir },
2192 context: serde_json::json!({}),
2193 status: oauth_status::VALID.to_string(),
2194 created_at: 0,
2195 updated_at: 0,
2196 };
2197 store.identity_upsert(&codex_acct).unwrap();
2198 store
2200 .agent_identity_link("def-1", "acct-alias", "codex-cli")
2201 .unwrap();
2202
2203 insert_block_for_agent(&store, "block-probe-alias", "def-1");
2204 let inst = make_instance("block-probe-alias", "id-probe-alias");
2205 store.instance_create(&inst).unwrap();
2206
2207 let mut env: HashMap<String, String> = HashMap::new();
2208 inject_identity_env(store.clone(), store.clone(), store.clone(), "block-probe-alias", &mut env).unwrap();
2209
2210 assert!(env.get("CODEX_HOME").is_some());
2211 let after = store.identity_get("acct-alias").unwrap().unwrap();
2215 assert_eq!(after.status, oauth_status::NEEDS_REAUTH);
2216 }
2217
2218 #[cfg(debug_assertions)]
2219 #[test]
2220 fn inject_oauth_class_probe_preserves_status_when_valid() {
2221 let store = make_store();
2226
2227 let mut def = crate::backend::storage::store::AgentDefinition {
2228 slug: String::new(),
2229 icon: "✦".to_string(),
2230 ..crate::backend::storage::agents::test_agent_def("def-1", "T", "claude", "", 0, "")
2231 };
2232 store.agent_def_insert(&mut def).unwrap();
2233
2234 let tmp = tempfile::tempdir().unwrap();
2235 let now_ms = agentmux_common::time::now_ms();
2236 write_claude_creds(tmp.path(), now_ms + 3_600_000, true);
2237
2238 let claude = IdentityAccount {
2239 id: "acct-ok".to_string(),
2240 name: "claude-acct-ok".to_string(),
2241 provider: "claude".to_string(),
2242 kind: "oauth".to_string(),
2243 display_name: String::new(),
2244 secret_ref: SecretRef::OAuthConfigDir {
2245 dir: tmp.path().to_str().unwrap().to_string(),
2246 },
2247 context: serde_json::json!({}),
2248 status: oauth_status::VALID.to_string(),
2249 created_at: 0,
2250 updated_at: 0,
2251 };
2252 store.identity_upsert(&claude).unwrap();
2253 store
2254 .agent_identity_link("def-1", "acct-ok", "claude")
2255 .unwrap();
2256
2257 insert_block_for_agent(&store, "block-ok", "def-1");
2258 let inst = make_instance("block-ok", "id-ok");
2259 store.instance_create(&inst).unwrap();
2260
2261 let mut env: HashMap<String, String> = HashMap::new();
2262 inject_identity_env(store.clone(), store.clone(), store.clone(), "block-ok", &mut env).unwrap();
2263
2264 let after = store.identity_get("acct-ok").unwrap().unwrap();
2265 assert_eq!(after.status, oauth_status::VALID);
2266 assert_eq!(after.updated_at, 0);
2269 }
2270
2271 #[test]
2291 fn spawn_gate_checks_the_agents_own_provider_not_its_bundles() {
2292 let mstore = make_store();
2293 let id_store_tmp = tempfile::NamedTempFile::new().unwrap();
2302 let id_store = Arc::new(Store::open_shared(id_store_tmp.path()).unwrap());
2303 let identity_store_tmp = tempfile::NamedTempFile::new().unwrap();
2308 let identity_store = Arc::new(Store::open_identity_store(identity_store_tmp.path()).unwrap());
2309
2310 let mut def = crate::backend::storage::store::AgentDefinition {
2311 seat: None,
2312 conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
2313 id: "def-1".to_string(),
2314 slug: String::new(),
2315 name: "T".to_string(),
2316 icon: "✦".to_string(),
2317 provider: "codex".to_string(),
2319 description: String::new(),
2320 working_directory: String::new(),
2321 shell: String::new(),
2322 provider_flags: String::new(),
2323 auto_start: 0,
2324 restart_on_crash: 0,
2325 idle_timeout_minutes: 0,
2326 created_at: 0,
2327 agent_type: String::new(),
2328 environment: String::new(),
2329 agent_bus_id: String::new(),
2330 is_seeded: 0,
2331 accounts: String::new(),
2332 parent_id: String::new(),
2333 branch_label: String::new(),
2334 updated_at: 0,
2335 user_hidden: 0,
2336 container_image: String::new(),
2337 container_volumes: "[]".to_string(),
2338 container_name: String::new(),
2339 use_ambient_login: 0,
2340 model_vendor_base_url: String::new(),
2341 memory_id: "bundle-1".to_string(),
2343 };
2344 mstore.agent_def_insert(&mut def).unwrap();
2345
2346 let bundle = Bundle {
2347 id: "bundle-1".to_string(),
2348 name: "Drift Test Bundle".to_string(),
2349 description: String::new(),
2350 is_blank: false,
2351 is_global: false,
2352 provider: "claude".to_string(),
2353 model: "anthropic".to_string(),
2354 instructions: String::new(),
2355 instructions_by_provider: "{}".to_string(),
2356 context_files: "[]".to_string(),
2357 mcp_servers: "[]".to_string(),
2358 skills: "[]".to_string(),
2359 sort_order: 0,
2360 created_at: 0,
2361 updated_at: 0,
2362 is_system: false,
2363 };
2364 id_store.bundle_upsert(&bundle).unwrap();
2365
2366 let claude = make_account(
2367 "acct-drift",
2368 "claude",
2369 SecretRef::OAuthConfigDir {
2370 dir: test_config_dir("id-drift"),
2371 },
2372 );
2373 id_store.identity_upsert_with_mirror(&identity_store, &claude).unwrap();
2374 identity_store
2375 .agent_identity_link("def-1", "acct-drift", "claude")
2376 .unwrap();
2377
2378 insert_block_for_agent(&mstore, "block-drift", "def-1");
2379 let inst = make_instance("block-drift", "id-drift");
2380 mstore.instance_create(&inst).unwrap();
2381
2382 let mut env: HashMap<String, String> = HashMap::new();
2383 let res = inject_identity_env(mstore, id_store, identity_store, "block-drift", &mut env);
2384
2385 assert!(
2388 matches!(&res, Err(SpawnGateError::MissingCredentials { provider, .. }) if provider == "codex"),
2389 "the agent owns its harness; the bundle's provider is a hint (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1): {res:?}"
2390 );
2391 }
2392
2393 fn make_agent_def_with_provider(id: &str, provider: &str) -> crate::backend::storage::store::AgentDefinition {
2394 crate::backend::storage::store::AgentDefinition {
2395 slug: String::new(),
2396 icon: "✦".to_string(),
2397 ..crate::backend::storage::agents::test_agent_def(id, "T", provider, "", 0, "")
2398 }
2399 }
2400
2401 #[cfg(debug_assertions)]
2403 #[test]
2404 fn resolve_bound_oauth_config_dir_resolves_the_identity_bound_dir() {
2405 let store = make_store();
2406 let mut def = make_agent_def_with_provider("def-1", "claude");
2407 store.agent_def_insert(&mut def).unwrap();
2408
2409 let claude = make_account(
2410 "acct-claude",
2411 "claude",
2412 SecretRef::OAuthConfigDir {
2413 dir: test_config_dir("id-bound"),
2414 },
2415 );
2416 store.identity_upsert(&claude).unwrap();
2417 store.agent_identity_link("def-1", "acct-claude", "claude").unwrap();
2418
2419 insert_block_for_agent(&store, "block-bound", "def-1");
2420 let inst = make_instance("block-bound", "id-bound");
2421 store.instance_create(&inst).unwrap();
2422
2423 let resolved = resolve_bound_oauth_config_dir(&store, &store, &store, "block-bound");
2424 assert_eq!(
2425 resolved,
2426 Some(std::path::PathBuf::from(test_config_dir("id-bound"))),
2427 );
2428 }
2429
2430 #[cfg(debug_assertions)]
2431 #[test]
2432 fn resolve_bound_oauth_config_dir_none_when_no_instance_for_block() {
2433 let store = make_store();
2434 let resolved = resolve_bound_oauth_config_dir(&store, &store, &store, "no-such-block");
2435 assert_eq!(resolved, None);
2436 }
2437
2438 #[cfg(debug_assertions)]
2439 #[test]
2440 fn resolve_bound_oauth_config_dir_none_for_api_key_class_provider() {
2441 let store = make_store();
2442 let mut def = make_agent_def_with_provider("def-1", "github");
2444 store.agent_def_insert(&mut def).unwrap();
2445
2446 let github = make_account(
2447 "acct-gh",
2448 "github",
2449 SecretRef::PlaintextDev { plaintext_dev: "ghp_x".to_string() },
2450 );
2451 store.identity_upsert(&github).unwrap();
2452 store.agent_identity_link("def-1", "acct-gh", "github").unwrap();
2453
2454 insert_block_for_agent(&store, "block-gh", "def-1");
2455 let inst = make_instance("block-gh", "id-gh");
2456 store.instance_create(&inst).unwrap();
2457
2458 let resolved = resolve_bound_oauth_config_dir(&store, &store, &store, "block-gh");
2459 assert_eq!(resolved, None);
2460 }
2461
2462 #[cfg(debug_assertions)]
2463 #[test]
2464 fn resolve_bound_oauth_config_dir_none_when_oauth_provider_has_no_binding() {
2465 let store = make_store();
2466 let mut def = make_agent_def_with_provider("def-1", "claude");
2467 store.agent_def_insert(&mut def).unwrap();
2468 insert_block_for_agent(&store, "block-unbound", "def-1");
2471 let inst = make_instance("block-unbound", "");
2472 store.instance_create(&inst).unwrap();
2473
2474 let resolved = resolve_bound_oauth_config_dir(&store, &store, &store, "block-unbound");
2475 assert_eq!(resolved, None, "ambient/unbound agents must fall through, not error");
2476 }
2477
2478 #[cfg(debug_assertions)]
2484 #[test]
2485 fn resolve_bound_oauth_config_dir_does_not_mutate_account_status() {
2486 let store = make_store();
2487 let mut def = make_agent_def_with_provider("def-1", "claude");
2488 store.agent_def_insert(&mut def).unwrap();
2489
2490 let claude = make_account(
2491 "acct-claude",
2492 "claude",
2493 SecretRef::OAuthConfigDir { dir: "/nonexistent/dir/for/probe".to_string() },
2494 );
2495 store.identity_upsert(&claude).unwrap();
2496 store.agent_identity_link("def-1", "acct-claude", "claude").unwrap();
2497
2498 insert_block_for_agent(&store, "block-status", "def-1");
2499 let inst = make_instance("block-status", "id-status");
2500 store.instance_create(&inst).unwrap();
2501
2502 let _ = resolve_bound_oauth_config_dir(&store, &store, &store, "block-status");
2503
2504 let reread = store.identity_get("acct-claude").unwrap().unwrap();
2505 assert_eq!(reread.status, "unknown", "status must be untouched — no probe/upsert side effect");
2506 }
2507}