Skip to main content

agentmux_srv/server/
actor.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Whether the actor a request names is the agent that sent it — identity
5//! M4a-2 (`docs/specs/SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md`
6//! §6.5.3, §6.5.6).
7//!
8//! An actor site is a handler whose request says who is acting: a memory
9//! owner, a global-memory writer, a work claimer or creator, an inject or bus
10//! sender, a cron creator, a UI-automation signer (§6.5.2 item 4). When the
11//! request is [`Caller::Agent`], the named actor is checked against that
12//! UID's own row, and one of these is counted per site:
13//!
14//! - `m4.actor_mismatch.<site>` — the name is none of the row's {slug,
15//!   display name, `instance_name`}, matched as the M3 resolver matches
16//!   (`Store::agents_matching_name`): slug exactly, the others ASCII
17//!   case-insensitively. A name that would not select the caller's row.
18//! - `m4.actor_ambiguous.<site>` — the name selects the caller's row, but not
19//!   by its slug, and also selects another row — any row, a template
20//!   included: the colliding-name case, in which a slug-keyed consumer
21//!   (memory) resolves to the *other* agent, and the template-stub case of
22//!   #3573.
23//! - `m4.actor_absent.<site>` — an attributed request that names no actor.
24//! - `m4.actor_unchecked.<site>` — the caller's row could not be read.
25//!
26//! **Never refused, never awaited, and nothing is written:** the check runs
27//! detached on the blocking pool; the handler does not await it, though it
28//! contends for the store's connection lock like any store read (§7); M4c
29//! dual-writes the UID. This only measures how often the name and the token
30//! disagree before anything relies on the token. Unattributed requests are not
31//! checked — there is no row to compare with, and most are the UI (§6.5.1).
32
33use 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        /// Where the actor name came from — the `<site>` in the counters.
53        #[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
107/// Whether `actor` would select `row` by name (see the module doc).
108pub(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
116/// What to count for `actor` against the caller's `row`; `None` when the
117/// name is the caller's own. `rows_named` lists every row the name selects,
118/// templates included (`Store::rows_answering_to`); it is asked only when
119/// the name selects the caller's row other than by its slug.
120pub(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
139/// Identity M4d-4: whether `uid`'s own row has `name` as its slug, exactly
140/// (spec §6.5.10 rule ii: never its display or instance name), so a request
141/// carrying `uid`'s token under `name` is that agent by its token.
142pub(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
146/// A caller its token names that sent no source (`muxsh agent send` in an
147/// agent's shell) is that agent: the source becomes its slug, so tier 4 can
148/// relay it and srv can sign it (SPEC_WAN_JEKT_SIGNED_BY_SRV_2026_10_14.md
149/// §3.1 rule 2). A source the caller did send is kept, and is signed only if
150/// it is the token's own (`wan_signer`).
151pub(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
162/// The agent srv may sign a WAN jekt as: its `source_agent`, when the
163/// request's own caller (`caller_uid`, from its token or a cron job's
164/// creator; never anything a hop carries) owns that name (`uid_owns_name`,
165/// §3.1 rules 1 and 2). The name is compared ignoring case, as the keys are
166/// stored: an agent sends as `QTest`, its slug is `qtest`.
167pub(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
176/// Whether `uid`'s row is the one agent this instance knows by `name`: its
177/// slug is `name` ignoring case, and no other row's slug folds to `name`.
178/// Every per-name key (host HMAC, LAN, WAN) is stored under the folded name,
179/// so a second row differing only in case (`Victim` beside `victim`) would
180/// hold the first one's keys; for such a name nobody is its owner.
181pub(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
190/// Identity M4d-4: whether a host-tier jekt is from the agent it claims by
191/// its token (`audit_source_uid` is the request's Caller). Far-side receivers
192/// have no Caller and keep checking the signature, which is still sent.
193pub(crate) fn jekt_sender_by_token(store: &Store, req: &crate::backend::reactive::InjectionRequest, claimed: &str) -> bool {
194    // Rule ii keeps the slug exact here; `uid_owns_name` adds that no other
195    // row folds to it, so a case-only alias can't claim the shared key.
196    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
202/// Identity M4d-4: the pane of a caller whose token names it under its own
203/// slug, from its UID's registration, with no key to check. `None` (today's
204/// name path) for anyone else, or before the UID registers.
205pub(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
213/// Count `actor` against the caller's row at `site`. A no-op for an
214/// Unattributed caller. Never fails and is never awaited: the store reads
215/// run detached on the blocking pool (inline under test, so tests can read
216/// the counters right after the request).
217pub(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
238/// [`check_actor`] that refuses: a request whose token names an agent may
239/// claim only that agent as its sender. `Ok` for an Unattributed caller (no
240/// token to compare with: the UI, `muxsh`, a peer srv), for a request that
241/// names no actor, and when the caller's row can't be read. The error is the
242/// handler's answer.
243pub(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
262/// What a route that acts for an agent says to a request with no token of this srv's.
263const NO_TOKEN: &str = "FORBIDDEN: this acts for an agent, so the request must carry that agent's token (AGENTMUX_AGENT_TOKEN)";
264/// What it says when the token is another agent's, or the name is one more than one agent answers to.
265const 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
267/// Like [`require_actor`], but for a route that acts for an agent and has no
268/// meaning without one: the request must carry the token of the agent it
269/// names. A request with no token (or one this srv didn't mint) is refused
270/// instead of being taken at its word, and so is one whose token names another
271/// agent.
272pub(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
289/// A WebSocket write to one agent's transcript or session state. A connection
290/// that registered as an agent (with its token) may write only its own agent's;
291/// any other connection must be the AgentMux window, proven by the host.
292/// Holding the instance auth key proves nothing, because every agent holds it.
293/// `target` is the agent's definition id or its slug; `what` completes
294/// "FORBIDDEN: …" when a connection that isn't the window is refused.
295pub(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
308/// [`require_own_transcript`] for a call that names a pane's block instead of an agent: the
309/// archive or restore of that block's transcript. An agent's connection may act only on the block
310/// its own agent is running on (a block with no running agent is the window's alone); any other
311/// connection must be the AgentMux window, proven by the host.
312pub(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    // Who runs on a pane comes from the launch record (`last_block_id`), never from the block's `agentId`
317    // meta, which any connection can write: `instance_get_by_block_id` only lets that meta choose between
318    // rows already recorded for this block.
319    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
331/// For a route that records who acted: the agent the request's token names, as
332/// `(slug, uid)`. `claimed` is the name the request gives for itself, and an
333/// empty one leaves the token to decide alone. Refused without a token, and
334/// when `claimed` is not a name only that agent answers to, so what is recorded
335/// is what the server proved and never a body field.
336pub(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
364/// The slug of the agent behind `uid` when `actor` is a name only that agent
365/// answers to: its slug, a display or instance name no other agent shares, or
366/// a name it was renamed from. A name another row also answers to, or a row
367/// that can't be read, proves nothing (unlike [`names_the_caller`], which
368/// gives them the benefit of the doubt).
369pub(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
380/// For a route that acts for the agent its token names (its memory, accounts,
381/// presets): the request must carry a token this srv minted. Without one the
382/// route has no one to act for, and a body's `agent_id` is only a claim, so it
383/// is refused instead of being taken at its word.
384pub(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
392/// An agent acts on its own panes only: a request that carries an agent's token
393/// is refused when the pane (or agent) it acts on belongs to another. A request
394/// with no token (the window, a peer srv) is not compared, nor is a target that
395/// has no agent.
396pub(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
403/// Whether `actor` is a name the agent behind `uid` answers to: its slug,
404/// display or instance name, or one it was renamed from (a running agent keeps
405/// sending under the name its environment held at launch). A name that also
406/// selects another row, or a row that can't be read, is not held against it.
407pub(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
435/// A work claim also carries the claimer's UID (`agent_uid`, identity M1a).
436/// A carried UID that is not the token's is counted on its own, since it is
437/// the UID — not the name — that M3 writes to `claimed_by_uid`.
438pub(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    /// SPEC_WAN_JEKT_SIGNED_BY_SRV_2026_10_14.md §3.1: who srv signs as.
453    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            // A source the caller sent is kept, even another agent's.
485            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            // No token, nothing filled: a terminal's muxsh stays sourceless.
489            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            // SendMessage sends AGENTMUX_AGENT_ID, which keeps the name's capitals.
503            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            // A hop that set audit_source_uid (a verified channel v2 hop) is
509            // still not this request's caller.
510            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            // Rows created before slugs collided case-insensitively: both
518            // would hold the same folded keys, so neither is signed for.
519            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        /// Two rows whose names differ only in case share the folded keys, so
534        /// neither gets them in its `.mcp.json`.
535        #[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        // Slug is exact, as in the M3 resolver.
595        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    /// The colliding-names fixture: the second agent ("AGENTY", agenty-2)
619    /// sends the first one's slug `agenty`. It matches the second agent's
620    /// display name, so it is no mismatch — but it selects the first agent
621    /// too, and a slug-keyed consumer resolves it there (M4a-2 review P1).
622    #[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        // "AGENTY" selects both rows by display name, so it is ambiguous too.
631        assert_eq!(
632            classify(&second, "AGENTY", only(vec![first.clone(), second.clone()])),
633            Some(Outcome::Ambiguous)
634        );
635        // A display name no other row holds is the caller's own.
636        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}