1use crate::backend::rpc_types::RpcContext;
34use crate::backend::storage::agents::AgentNameMatch;
35use crate::backend::storage::error::StoreError;
36use crate::backend::storage::store::Store;
37
38use super::api_error::ApiError;
39use super::caller::Caller;
40use super::AppState;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub(crate) enum Outcome {
44 Mismatch,
45 Ambiguous,
46 Absent,
47 Unchecked,
48}
49
50macro_rules! actor_sites {
51 ($($site:ident => $name:literal,)*) => {
52 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
54 pub(crate) enum ActorSite {
55 $($site,)*
56 }
57
58 impl ActorSite {
59 pub(crate) fn counter(self, outcome: Outcome) -> &'static str {
60 match (self, outcome) {
61 $(
62 (ActorSite::$site, Outcome::Mismatch) => concat!("m4.actor_mismatch.", $name),
63 (ActorSite::$site, Outcome::Ambiguous) => concat!("m4.actor_ambiguous.", $name),
64 (ActorSite::$site, Outcome::Absent) => concat!("m4.actor_absent.", $name),
65 (ActorSite::$site, Outcome::Unchecked) => concat!("m4.actor_unchecked.", $name),
66 )*
67 }
68 }
69 }
70 };
71}
72
73actor_sites! {
74 MemoryList => "memory_list",
75 MemoryRead => "memory_read",
76 MemoryWrite => "memory_write",
77 MemoryHistory => "memory_history",
78 MemoryDiff => "memory_diff",
79 MemoryRevert => "memory_revert",
80 GlobalMemoryWrite => "globalmemory_write",
81 GlobalMemoryRevert => "globalmemory_revert",
82 GlobalMemoryRemove => "globalmemory_remove",
83 IdentityAccounts => "identity_accounts",
84 PresetGet => "preset_get",
85 IdentityValidate => "identity_validate",
86 IdentitySwitch => "identity_switch",
87 IdentityCheckLimits => "identity_check_limits",
88 IdentitySigninNotice => "identity_signin_notice",
89 RemoteOp => "remote_op",
90 SkillManage => "skill_manage",
91 HistorySearch => "history_search",
92 WorkEnqueue => "work_enqueue",
93 WorkClaim => "work_claim",
94 WorkHeartbeat => "work_heartbeat",
95 WorkComplete => "work_complete",
96 WorkRelease => "work_release",
97 CronCreate => "cron_create",
98 Inject => "inject",
99 BusRegister => "bus_register",
100 BusRead => "bus_read",
101 BusSend => "bus_send",
102 BusInject => "bus_inject",
103 BusBroadcast => "bus_broadcast",
104 UiAuth => "ui_auth",
105}
106
107pub(crate) fn names_the_row(row: &AgentNameMatch, actor: &str) -> bool {
109 let actor = actor.trim();
110 !actor.is_empty()
111 && (actor == row.slug
112 || actor.eq_ignore_ascii_case(&row.name)
113 || actor.eq_ignore_ascii_case(&row.instance_name))
114}
115
116pub(crate) fn classify(
121 row: &AgentNameMatch,
122 actor: &str,
123 rows_named: impl FnOnce(&str) -> Result<Vec<AgentNameMatch>, StoreError>,
124) -> Option<Outcome> {
125 let actor = actor.trim();
126 if actor == row.slug {
127 return None;
128 }
129 if !names_the_row(row, actor) {
130 return Some(Outcome::Mismatch);
131 }
132 match rows_named(actor) {
133 Ok(rows) if rows.iter().any(|r| r.id != row.id) => Some(Outcome::Ambiguous),
134 Ok(_) => None,
135 Err(_) => Some(Outcome::Unchecked),
136 }
137}
138
139pub(crate) fn uid_has_slug(store: &Store, uid: &str, name: &str) -> bool {
143 matches!(store.agent_names_by_id(uid), Ok(Some(row)) if !row.slug.is_empty() && row.slug == name)
144}
145
146pub(crate) fn source_from_token(store: &Store, caller_uid: &str, req: &mut crate::backend::reactive::InjectionRequest) {
152 if caller_uid.is_empty() || req.source_agent.as_deref().is_some_and(|s| !s.trim().is_empty()) {
153 return;
154 }
155 if let Ok(Some(row)) = store.agent_names_by_id(caller_uid) {
156 if !row.slug.is_empty() {
157 req.source_agent = Some(row.slug);
158 }
159 }
160}
161
162pub(crate) fn wan_signer<'a>(
168 store: &Store,
169 caller_uid: &str,
170 req: &'a crate::backend::reactive::InjectionRequest,
171) -> Option<&'a str> {
172 let source = req.source_agent.as_deref()?;
173 (!caller_uid.is_empty() && uid_owns_name(store, caller_uid, source)).then_some(source)
174}
175
176pub(crate) fn uid_owns_name(store: &Store, uid: &str, name: &str) -> bool {
182 let folded = name.trim().to_lowercase();
183 if folded.is_empty() {
184 return false;
185 }
186 let owns = matches!(store.agent_names_by_id(uid), Ok(Some(row)) if row.slug.trim().to_lowercase() == folded);
187 owns && matches!(store.agent_ids_for_slug_folded(&folded), Ok(ids) if ids.len() == 1 && ids[0] == uid)
188}
189
190pub(crate) fn jekt_sender_by_token(store: &Store, req: &crate::backend::reactive::InjectionRequest, claimed: &str) -> bool {
194 req.delivery_tier.as_deref() == Some("host")
197 && !req.audit_source_uid.is_empty()
198 && uid_has_slug(store, &req.audit_source_uid, claimed)
199 && uid_owns_name(store, &req.audit_source_uid, claimed)
200}
201
202pub(crate) fn own_pane_by_token(store: &Store, caller: Option<&Caller>, name: &str) -> Option<String> {
206 let uid = caller.and_then(Caller::uid)?;
207 if !uid_has_slug(store, uid, name) {
208 return None;
209 }
210 crate::backend::reactive::handler::get_global_handler().block_for_uid(uid)
211}
212
213pub(crate) fn check_actor(
218 state: &AppState,
219 caller: Option<&Caller>,
220 site: ActorSite,
221 actor: Option<&str>,
222) {
223 let Some(uid) = caller.and_then(Caller::uid) else {
224 return;
225 };
226 let Some(actor) = actor.map(str::trim).filter(|a| !a.is_empty()) else {
227 crate::backend::agent_resolve::record_uid_fallback(site.counter(Outcome::Absent));
228 return;
229 };
230 let (mstore, uid, actor) = (state.mstore.clone(), uid.to_string(), actor.to_string());
231 let run = move || count_against_row(&mstore, &uid, site, &actor);
232 #[cfg(not(test))]
233 drop(tokio::task::spawn_blocking(run));
234 #[cfg(test)]
235 run();
236}
237
238pub(crate) async fn require_actor(
244 state: &AppState,
245 caller: Option<&Caller>,
246 site: ActorSite,
247 actor: Option<&str>,
248) -> Result<(), String> {
249 check_actor(state, caller, site, actor);
250 let (Some(uid), Some(actor)) = (caller.and_then(Caller::uid), actor.map(str::trim).filter(|a| !a.is_empty())) else {
251 return Ok(());
252 };
253 let (mstore, uid, name) = (state.mstore.clone(), uid.to_string(), actor.to_string());
254 let own = tokio::task::spawn_blocking(move || names_the_caller(&mstore, &uid, &name)).await.unwrap_or(true);
255 if own {
256 Ok(())
257 } else {
258 Err("FORBIDDEN: the sender must be the agent this request's token names".to_string())
259 }
260}
261
262const NO_TOKEN: &str = "FORBIDDEN: this acts for an agent, so the request must carry that agent's token (AGENTMUX_AGENT_TOKEN)";
264const TOKEN_NAMES_ANOTHER: &str = "FORBIDDEN: the request's token must name the agent this acts for, by a name only that agent answers to";
266
267pub(crate) async fn require_token_naming(
273 state: &AppState,
274 caller: Option<&Caller>,
275 site: ActorSite,
276 actor: &str,
277) -> Result<(), String> {
278 check_actor(state, caller, site, Some(actor));
279 let Some(uid) = caller.and_then(Caller::uid) else {
280 return Err(NO_TOKEN.to_string());
281 };
282 let (mstore, uid, name) = (state.mstore.clone(), uid.to_string(), actor.trim().to_string());
283 match tokio::task::spawn_blocking(move || proven_slug(&mstore, &uid, &name)).await {
284 Ok(Some(_)) => Ok(()),
285 _ => Err(TOKEN_NAMES_ANOTHER.to_string()),
286 }
287}
288
289pub(crate) fn require_own_transcript(ctx: &RpcContext, store: &Store, target: &str, what: &str) -> Result<(), String> {
296 if ctx.agent_id.is_empty() {
297 return ctx.operator_only(&format!("{what} is written by its own agent or by the AgentMux window"));
298 }
299 let target = target.trim();
300 let slug = store.agent_def_get(target).ok().flatten().map_or_else(|| target.to_string(), |def| def.slug);
301 if slug.eq_ignore_ascii_case(&ctx.agent_id) {
302 Ok(())
303 } else {
304 Err(format!("FORBIDDEN: {what} is written by its own agent or by the AgentMux window, not by another agent"))
305 }
306}
307
308pub(crate) fn require_own_block_transcript(ctx: &RpcContext, store: &Store, block_id: &str, what: &str) -> Result<(), String> {
313 if ctx.agent_id.is_empty() {
314 return ctx.operator_only(&format!("{what} is written by its own agent or by the AgentMux window"));
315 }
316 let owner = store
320 .instance_get_by_block_id(block_id)
321 .ok()
322 .flatten()
323 .and_then(|inst| store.agent_def_get(&inst.id).ok().flatten())
324 .map(|def| def.slug);
325 match owner {
326 Some(slug) if slug.eq_ignore_ascii_case(&ctx.agent_id) => Ok(()),
327 _ => Err(format!("FORBIDDEN: {what} is written by its own agent or by the AgentMux window, not by another agent")),
328 }
329}
330
331pub(crate) async fn require_token_actor(
337 state: &AppState,
338 caller: Option<&Caller>,
339 site: ActorSite,
340 claimed: &str,
341) -> Result<(String, String), ApiError> {
342 check_actor(state, caller, site, Some(claimed));
343 let Some(uid) = caller.and_then(Caller::uid) else {
344 return Err(ApiError::refused(NO_TOKEN));
345 };
346 let (mstore, uid, claimed) = (state.mstore.clone(), uid.to_string(), claimed.trim().to_string());
347 let who = uid.clone();
348 let slug = tokio::task::spawn_blocking(move || {
349 if claimed.is_empty() {
350 mstore.agent_names_by_id(&who).ok().flatten().map(|row| row.slug)
351 } else {
352 proven_slug(&mstore, &who, &claimed)
353 }
354 })
355 .await
356 .ok()
357 .flatten();
358 match slug {
359 Some(slug) => Ok((slug, uid)),
360 None => Err(ApiError::refused(TOKEN_NAMES_ANOTHER)),
361 }
362}
363
364pub(crate) fn proven_slug(store: &Store, uid: &str, actor: &str) -> Option<String> {
370 let Ok(Some(row)) = store.agent_names_by_id(uid) else {
371 return None;
372 };
373 match classify(&row, actor, |name| store.rows_answering_to(name)) {
374 None => Some(row.slug),
375 Some(Outcome::Mismatch) => store.former_name_owner(actor).ok().flatten().filter(|owner| owner.uid == uid).map(|_| row.slug),
376 Some(_) => None,
377 }
378}
379
380pub(crate) fn require_token(state: &AppState, caller: Option<&Caller>, site: ActorSite, actor: &str) -> Result<(), ApiError> {
385 check_actor(state, caller, site, Some(actor));
386 match caller.and_then(Caller::uid) {
387 Some(_) => Ok(()),
388 None => Err(ApiError::refused(NO_TOKEN)),
389 }
390}
391
392pub(crate) fn own_agent_only(caller: Option<&Caller>, target_uid: Option<&str>) -> Result<(), String> {
397 match (caller.and_then(Caller::uid), target_uid) {
398 (Some(me), Some(target)) if me != target => Err("FORBIDDEN: an agent acts on its own panes only".to_string()),
399 _ => Ok(()),
400 }
401}
402
403pub(crate) fn names_the_caller(store: &Store, uid: &str, actor: &str) -> bool {
408 let Ok(Some(row)) = store.agent_names_by_id(uid) else {
409 return true;
410 };
411 match classify(&row, actor, |name| store.rows_answering_to(name)) {
412 Some(Outcome::Mismatch) => store.former_name_owner(actor).ok().flatten().is_some_and(|owner| owner.uid == uid),
413 _ => true,
414 }
415}
416
417fn count_against_row(store: &Store, uid: &str, site: ActorSite, actor: &str) {
418 let outcome = match store.agent_names_by_id(uid) {
419 Ok(Some(row)) => classify(&row, actor, |name| store.rows_answering_to(name)),
420 Ok(None) | Err(_) => Some(Outcome::Unchecked),
421 };
422 let Some(outcome) = outcome else {
423 return;
424 };
425 let counter = site.counter(outcome);
426 crate::backend::agent_resolve::record_uid_fallback(counter);
427 tracing::debug!(
428 counter,
429 caller_uid = uid,
430 actor = %actor.chars().take(128).collect::<String>(),
431 "identity M4a-2: the request's actor name is not plainly the calling agent's"
432 );
433}
434
435pub(crate) fn check_carried_uid(caller: Option<&Caller>, carried_uid: &str) {
439 let Some(uid) = caller.and_then(Caller::uid) else {
440 return;
441 };
442 let carried = carried_uid.trim();
443 if !carried.is_empty() && carried != uid {
444 crate::backend::agent_resolve::record_uid_fallback("m4.actor_uid_mismatch.work_claim");
445 }
446}
447
448#[cfg(test)]
449mod tests {
450 use super::*;
451
452 mod wan_signing {
454 use super::super::*;
455 use crate::backend::reactive::InjectionRequest;
456
457 fn store_with_camper() -> Store {
458 let store = Store::open_in_memory().unwrap();
459 let mut def = crate::backend::storage::agents::test_agent_def("uid-camper", "Camper", "claude", "agent", 1, "");
460 def.slug = "camper".into();
461 store.agent_def_insert(&mut def).unwrap();
462 store
463 }
464
465 fn req(source: Option<&str>, caller_uid: &str) -> InjectionRequest {
466 InjectionRequest {
467 target_agent: "agent2".into(),
468 message: "hi".into(),
469 source_agent: source.map(str::to_string),
470 audit_source_uid: caller_uid.into(),
471 ..Default::default()
472 }
473 }
474
475 #[test]
476 fn a_token_with_no_source_sends_as_its_own_slug() {
477 let store = store_with_camper();
478 let mut r = req(None, "uid-camper");
479 source_from_token(&store, "uid-camper", &mut r);
480 assert_eq!(r.source_agent.as_deref(), Some("camper"));
481 let mut blank = req(Some(" "), "uid-camper");
482 source_from_token(&store, "uid-camper", &mut blank);
483 assert_eq!(blank.source_agent.as_deref(), Some("camper"));
484 let mut other = req(Some("agent5"), "uid-camper");
486 source_from_token(&store, "uid-camper", &mut other);
487 assert_eq!(other.source_agent.as_deref(), Some("agent5"));
488 let mut anon = req(None, "");
490 source_from_token(&store, "", &mut anon);
491 assert_eq!(anon.source_agent, None);
492 let mut unknown = req(None, "uid-nobody");
493 source_from_token(&store, "uid-nobody", &mut unknown);
494 assert_eq!(unknown.source_agent, None);
495 }
496
497 #[test]
498 fn srv_signs_only_as_the_agent_the_token_names() {
499 let store = store_with_camper();
500 let sign = |source: Option<&str>, caller: &str| wan_signer(&store, caller, &req(source, caller)).map(str::to_string);
501 assert_eq!(sign(Some("camper"), "uid-camper").as_deref(), Some("camper"));
502 assert_eq!(sign(Some("Camper"), "uid-camper").as_deref(), Some("Camper"), "the slug, ignoring case");
504 assert_eq!(sign(Some("agent5"), "uid-camper"), None, "another agent's name");
505 assert_eq!(sign(Some("camper"), ""), None, "no caller: a forwarded hop, a script");
506 assert_eq!(sign(Some("camper"), "uid-nobody"), None);
507 assert_eq!(sign(None, "uid-camper"), None);
508 let mut hop = req(Some("camper"), "uid-camper");
511 hop.audit_source_uid = "uid-camper".into();
512 assert_eq!(wan_signer(&store, "", &hop), None);
513 }
514
515 #[test]
516 fn a_name_two_rows_fold_to_has_no_owner() {
517 let store = store_with_camper();
520 {
521 let conn = store.conn().lock().unwrap();
522 conn.execute_batch(
523 "INSERT INTO db_agents (id, name, slug, provider, created_at) VALUES ('uid-alias', 'Camper', 'Camper', 'claude', 0);",
524 )
525 .unwrap();
526 }
527 assert!(!uid_owns_name(&store, "uid-camper", "camper"));
528 assert!(!uid_owns_name(&store, "uid-alias", "Camper"));
529 assert_eq!(wan_signer(&store, "uid-alias", &req(Some("Camper"), "uid-alias")), None);
530 assert_eq!(wan_signer(&store, "uid-camper", &req(Some("camper"), "uid-camper")), None);
531 }
532
533 #[test]
536 fn inject_jekt_signing_keys_writes_none_when_two_rows_fold_to_the_name() {
537 let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
538 {
539 let conn = store.conn().lock().unwrap();
540 conn.execute_batch(
541 "INSERT INTO db_agents (id, name, slug, provider, created_at) VALUES ('a', 'victim', 'victim', 'claude', 0);
542 INSERT INTO db_agents (id, name, slug, provider, created_at) VALUES ('b', 'Victim', 'Victim', 'claude', 0);",
543 )
544 .unwrap();
545 }
546 let content = serde_json::to_string(&serde_json::json!({
547 "mcpServers": { "agentmux": { "env": { "AGENTMUX_AGENT_ID": "Victim", "AGENTMUX_LAN_KEY": "old" } } }
548 }))
549 .unwrap();
550 let rewritten = crate::backend::agent_config::inject_jekt_signing_keys_into_mcp_json(&content, &store, "Victim").expect("the old key removed");
551 let env = serde_json::from_str::<serde_json::Value>(&rewritten).unwrap()["mcpServers"]["agentmux"]["env"].clone();
552 assert!(env.get("AGENTMUX_JEKT_KEY").is_none() && env.get("AGENTMUX_LAN_KEY").is_none(), "{env}");
553 assert!(store.agent_jekt_key_load("victim").unwrap().is_none(), "nothing minted for the name");
554 }
555
556 #[test]
557 fn a_new_slug_differing_only_in_case_gets_a_suffix() {
558 let store = store_with_camper();
559 let mut def = crate::backend::storage::agents::test_agent_def("uid-v", "Camper", "claude", "agent", 1, "");
560 def.slug = "Camper".into();
561 store.agent_def_insert(&mut def).unwrap();
562 assert_eq!(def.slug, "Camper-2", "not a second owner of camper's keys");
563 assert!(uid_owns_name(&store, "uid-camper", "Camper"));
564 }
565 }
566
567 fn row(id: &str, name: &str, slug: &str, instance_name: &str) -> AgentNameMatch {
568 AgentNameMatch {
569 id: id.into(),
570 name: name.into(),
571 slug: slug.into(),
572 instance_name: instance_name.into(),
573 }
574 }
575
576 fn only(
577 rows: Vec<AgentNameMatch>,
578 ) -> impl FnOnce(&str) -> Result<Vec<AgentNameMatch>, StoreError> {
579 move |_| Ok(rows)
580 }
581
582 #[test]
583 fn a_name_the_row_answers_to_matches() {
584 let r = row("uid-y", "AgentY", "agenty", "Yardbird");
585 assert!(names_the_row(&r, "agenty"));
586 assert!(names_the_row(&r, " agenty "));
587 assert!(
588 names_the_row(&r, "AGENTY"),
589 "display name is case-insensitive"
590 );
591 assert!(names_the_row(&r, "yardbird"));
592 assert!(!names_the_row(&r, "agentz"));
593 assert!(!names_the_row(&r, ""));
594 let r = row("uid-y", "Why", "agenty", "");
596 assert!(!names_the_row(&r, "AGENTY"));
597 assert!(
598 !names_the_row(&r, ""),
599 "an empty instance name matches nothing"
600 );
601 }
602
603 #[test]
604 fn the_callers_own_slug_is_never_counted_and_asks_nothing() {
605 let r = row("uid-y2", "AGENTY", "agenty-2", "");
606 assert_eq!(classify(&r, "agenty-2", |_| panic!("not asked")), None);
607 }
608
609 #[test]
610 fn a_name_that_is_not_the_callers_is_a_mismatch() {
611 let r = row("uid-y2", "AGENTY", "agenty-2", "");
612 assert_eq!(
613 classify(&r, "agentz", |_| panic!("not asked")),
614 Some(Outcome::Mismatch)
615 );
616 }
617
618 #[test]
623 fn a_colliding_name_that_also_selects_another_row_is_ambiguous() {
624 let first = row("uid-y", "AgentY", "agenty", "");
625 let second = row("uid-y2", "AGENTY", "agenty-2", "");
626 assert_eq!(
627 classify(&second, "agenty", only(vec![first.clone(), second.clone()])),
628 Some(Outcome::Ambiguous)
629 );
630 assert_eq!(
632 classify(&second, "AGENTY", only(vec![first.clone(), second.clone()])),
633 Some(Outcome::Ambiguous)
634 );
635 let zed = row("uid-z", "Zed", "zed-2", "");
637 assert_eq!(classify(&zed, "zed", only(vec![zed.clone()])), None);
638 assert_eq!(
639 classify(&second, "agenty", |_| Err(StoreError::NotFound)),
640 Some(Outcome::Unchecked)
641 );
642 }
643}