1use std::collections::{HashMap, VecDeque};
23use std::sync::{Mutex, OnceLock};
24use std::time::{Duration, Instant};
25
26use agentmux_common::deeplinks::{self, AgentRule, LinkError, ParsedLink, Segment, Sensitivity, Value};
27use serde::Deserialize;
28
29use super::*;
30use crate::sagas::deeplink_open::{self, DeepLinkOutcome};
31
32pub(crate) const RATE_LIMIT: usize = 10;
34pub(crate) const RATE_WINDOW: Duration = Duration::from_secs(60);
35
36#[derive(Debug, Clone, Default, Deserialize)]
38pub(crate) struct OpenLinkRequest {
39 pub link: String,
40 #[serde(default)]
42 pub target: Option<String>,
43}
44
45#[derive(Debug, Clone, Default, PartialEq, Eq)]
47pub(crate) struct CallerFacts {
48 pub agent_id: String,
50 pub container: bool,
51 pub block_id: Option<String>,
52 pub tab_id: Option<String>,
53 pub window_id: Option<String>,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub(crate) struct Refusal {
59 pub code: &'static str,
60 pub text: String,
61 pub remedy: Option<String>,
62}
63
64pub(crate) fn refusal(code: &'static str, text: impl Into<String>, remedy: Option<String>) -> Refusal {
65 Refusal { code, text: text.into(), remedy }
66}
67
68impl From<LinkError> for Refusal {
69 fn from(e: LinkError) -> Self {
70 let code = if e == LinkError::NotYet { "not_yet" } else { "invalid_link" };
71 refusal(code, deeplinks::REGISTRY.reason(e.as_str()), None)
72 }
73}
74
75pub(crate) fn label_of(link: &ParsedLink) -> String {
77 let view = link.view.id;
78 match link.place {
79 None => view.to_string(),
80 Some(place) => {
81 let held = place.segments.iter().find_map(|s| match s {
82 Segment::Var(v) if v.kind == deeplinks::Kind::Enum => link.values.get(v.name).map(Value::to_string),
83 _ => None,
84 });
85 format!("{view} {} {}", deeplinks::REGISTRY.separator, held.unwrap_or_else(|| place.id.to_string()))
86 }
87 }
88}
89
90fn own_values<'a>(link: &'a ParsedLink) -> Vec<(&'static str, Option<&'a Value>)> {
92 let mut out = Vec::new();
93 if let Some(place) = link.place {
94 for s in place.segments {
95 if let Segment::Var(v) = s {
96 if v.agent_own {
97 out.push((v.name, link.values.get(v.name)));
98 }
99 }
100 }
101 for p in place.params {
102 if p.agent_own && p.only_with.is_none_or(|(var, allowed)| link.values.get(var).is_some_and(|h| allowed.contains(&h.to_string().as_str()))) {
103 out.push((p.name, link.params.get(p.name)));
104 }
105 }
106 }
107 out
108}
109
110pub(crate) fn check_rules(link: &mut ParsedLink, who: &CallerFacts) -> Result<(), Refusal> {
113 let view = link.view;
114 match view.agent {
115 AgentRule::No => return Err(refusal("not_allowed", format!("an agent can't open {}", view.id), None)),
116 AgentRule::Approved | AgentRule::Reveal => {
117 return Err(refusal("not_yet", deeplinks::REGISTRY.reason("not_yet"), None));
119 }
120 AgentRule::Own => {
121 let own_link = format!("agentmux://{}/agent/{}", view.id, who.agent_id);
122 match link.place.map(|p| p.id) {
123 Some("agent") => {}
124 _ => {
125 return Err(refusal(
126 "not_allowed",
127 format!("an agent may open only its own place of {}", view.id),
128 Some(own_link),
129 ))
130 }
131 }
132 }
133 AgentRule::Yes => {}
134 }
135 let mut fill: Vec<&'static str> = Vec::new();
136 for (name, held) in own_values(link) {
137 match held {
138 Some(v) if v.to_string() != who.agent_id => {
139 return Err(refusal(
140 "not_allowed",
141 format!("an agent may name only itself as {name}; another agent's is not opened for it"),
142 None,
143 ))
144 }
145 Some(_) => {}
146 None => {
147 if link.place.is_some_and(|p| p.params.iter().any(|x| x.name == name)) {
148 fill.push(name);
149 }
150 }
151 }
152 }
153 for name in fill {
154 link.params.insert(name.to_string(), Value::Text(who.agent_id.clone()));
155 }
156 if who.container && view.sensitivity == Sensitivity::Path {
157 return Err(refusal(
158 "not_allowed",
159 "a container agent opens its files with Pane open's view and path, which shows a copy of a file in its workspace",
160 None,
161 ));
162 }
163 Ok(())
164}
165
166pub(crate) fn canonical_path(path: &str, folder: bool) -> Result<String, Refusal> {
168 let bad = |why: &str| refusal("invalid_link", why.to_string(), None);
169 let real = std::fs::canonicalize(path).map_err(|_| bad("no such file or folder"))?;
170 let meta = std::fs::metadata(&real).map_err(|_| bad("no such file or folder"))?;
171 if folder && !meta.is_dir() {
172 return Err(bad("that is a file: open it with the Editor"));
173 }
174 if !folder && meta.is_dir() {
175 return Err(bad("that is a folder: open it with Files"));
176 }
177 let text = real.to_string_lossy().to_string();
178 let text = match text.strip_prefix(r"\\?\") {
179 Some(rest) if rest.starts_with(r"UNC\") => return Err(bad("a network path is not opened by a link")),
180 Some(rest) => rest.to_string(),
181 None => text,
182 };
183 let text = if cfg!(windows) { text.replace('\\', "/") } else { text };
184 if deeplinks::path_problem(&text).is_some() {
186 return Err(bad("the path is not an absolute local path a link may open"));
187 }
188 Ok(text)
189}
190
191fn check_path(link: &mut ParsedLink) -> Result<(), Refusal> {
193 if link.view.sensitivity != Sensitivity::Path {
194 return Ok(());
195 }
196 let Some(Value::Text(path)) = link.values.get("path").cloned() else { return Ok(()) };
197 let folder = link.view.id == "files";
198 let real = canonical_path(&path, folder)?;
199 link.values.insert("path".to_string(), Value::Text(real));
200 Ok(())
201}
202
203pub(crate) fn resolve_target(target: Option<&str>, who: &CallerFacts, pane_tab: impl Fn(&str) -> Option<String>) -> Result<(String, Option<String>), Refusal> {
206 let target = target.map(str::trim).filter(|t| !t.is_empty()).unwrap_or("beside");
207 let own_tab = who.tab_id.clone();
208 let note = |what: &str| Some(format!("{what} is not this agent's own tab, so it opened in the agent's own tab"));
209 match target.split_once(':').unwrap_or((target, "")) {
210 ("beside", "") => Ok(("beside".into(), None)),
211 ("new", "") => Ok(("new".into(), None)),
212 ("window", _) => Err(refusal("another_window", "an agent's open stays in its own window: naming a window is refused in this build", None)),
213 ("tab", tab) if !tab.is_empty() => Ok(("new".into(), if Some(tab.to_string()) == own_tab { None } else { note("that tab") })),
214 ("pane", block) if !block.is_empty() => {
215 if pane_tab(block).is_some_and(|t| Some(t) == own_tab) {
216 Ok((format!("pane:{block}"), None))
217 } else {
218 Ok(("beside".into(), note("that pane's tab")))
219 }
220 }
221 _ => Err(refusal("invalid_link", "target is beside, new, tab:<id>, pane:<id> or window:<id>", None)),
222 }
223}
224
225pub(crate) struct Limiter {
227 limit: usize,
228 seen: Mutex<HashMap<String, VecDeque<Instant>>>,
229}
230
231impl Limiter {
232 pub(crate) fn new(limit: usize) -> Self {
233 Limiter { limit, seen: Mutex::new(HashMap::new()) }
234 }
235
236 pub(crate) fn allow(&self, who: &str, now: Instant) -> Result<(), Duration> {
238 let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
239 let q = seen.entry(who.to_string()).or_default();
240 while q.front().is_some_and(|t| now.duration_since(*t) >= RATE_WINDOW) {
241 q.pop_front();
242 }
243 if q.len() >= self.limit {
244 let oldest = *q.front().expect("full");
245 return Err(RATE_WINDOW.saturating_sub(now.duration_since(oldest)));
246 }
247 q.push_back(now);
248 Ok(())
249 }
250}
251
252fn limiter() -> &'static Limiter {
253 static LIMITER: OnceLock<Limiter> = OnceLock::new();
254 LIMITER.get_or_init(|| Limiter::new(RATE_LIMIT))
255}
256
257pub(crate) fn check_place_rate(agent_id: &str) -> Result<(), String> {
260 limiter().allow(agent_id, Instant::now()).map_err(|wait| {
261 format!("RATE_LIMITED: an agent opens and places at most {RATE_LIMIT} panes a minute; the next one is allowed in {} s", wait.as_secs().max(1))
262 })
263}
264
265fn check_rate(agent_id: &str) -> Result<(), Refusal> {
266 limiter().allow(agent_id, Instant::now()).map_err(|wait| {
267 refusal(
268 "rate_limited",
269 format!("an agent opens at most {RATE_LIMIT} places a minute; the next one is allowed in {} s", wait.as_secs().max(1)),
270 None,
271 )
272 })
273}
274
275pub(crate) fn guard(req: &OpenLinkRequest, who: &CallerFacts, pane_tab: impl Fn(&str) -> Option<String>) -> Result<(ParsedLink, String, Option<String>), Refusal> {
277 let mut link = deeplinks::parse_link(req.link.trim())?;
278 check_rules(&mut link, who)?;
279 let (target, note) = resolve_target(req.target.as_deref(), who, pane_tab)?;
280 check_path(&mut link)?;
281 check_rate(&who.agent_id)?;
282 link.canonical = deeplinks::format_link(link.view, link.place, &link.values, &link.params, link.anchor.as_deref(), link.host.as_deref());
283 Ok((link, target, note))
284}
285
286fn record(state: &AppState, who: &CallerFacts, request_id: &str, link: &str, outcome: &DeepLinkOutcome) {
288 let ok = matches!(outcome.outcome.as_str(), "opened" | "reused" | "queued");
289 let why = outcome.reason.as_deref().map(|r| format!(": {r}")).unwrap_or_default();
290 state.reactive_handler.log_fleet_action_audit(
291 Some(&who.agent_id),
292 "",
293 outcome.block_id.as_deref().or(who.block_id.as_deref()).unwrap_or(""),
294 "pane.open_link",
295 ok,
296 (!ok).then_some(outcome.reason.as_deref().unwrap_or("refused")),
297 request_id,
298 Some(&format!("{} {link}{why}", outcome.outcome)),
299 );
300}
301
302fn facts_of(state: &AppState, uid: &str, container: bool) -> CallerFacts {
304 let agent_id = state.mstore.agent_names_by_id(uid).ok().flatten().map(|r| r.slug).filter(|s| !s.is_empty()).unwrap_or_else(|| uid.to_string());
305 let own = app_api::agent_block::find_agent_block_by_uid(&state.mstore, uid).ok().flatten();
306 let block_id = own.as_ref().map(|o| o.block.oid.clone());
307 let tab_id = own.and_then(|o| o.tab_id);
308 let window_id = tab_id.as_deref().and_then(|t| window_of_tab(state, t));
309 CallerFacts { agent_id, container, block_id, tab_id, window_id }
310}
311
312fn window_of_tab(state: &AppState, tab_id: &str) -> Option<String> {
313 use crate::backend::obj::{Window, Workspace};
314 let ws = state
315 .mstore
316 .get_all::<Workspace>()
317 .ok()?
318 .into_iter()
319 .find(|w| w.tabids.iter().chain(w.pinnedtabids.iter()).any(|t| t == tab_id))?;
320 state.mstore.get_all::<Window>().ok()?.into_iter().find(|w| w.workspaceid == ws.oid).map(|w| w.oid)
321}
322
323fn tab_of_block(state: &AppState, block_id: &str) -> Option<String> {
324 use crate::backend::obj::Tab;
325 state.mstore.get_all::<Tab>().ok()?.into_iter().find(|t| t.blockids.iter().any(|b| b == block_id)).map(|t| t.oid)
326}
327
328pub(super) async fn handle_pane_open_link(
331 State(state): State<AppState>,
332 grant: Option<axum::Extension<crate::backend::container::credential::ContainerGrant>>,
333 caller: Option<axum::Extension<super::caller::Caller>>,
334 Json(req): Json<OpenLinkRequest>,
335) -> impl IntoResponse {
336 let Some(uid) = caller.as_ref().and_then(|c| c.0.uid()).map(str::to_string) else {
337 return (StatusCode::FORBIDDEN, Json(json!({ "error": "a deep link is opened for an agent known by its token; a person clicks the link" }))).into_response();
338 };
339 let who = facts_of(&state, &uid, grant.is_some());
340 let request_id = uuid::Uuid::new_v4().to_string();
341 let decided = guard(&req, &who, |b| tab_of_block(&state, b));
342 let (link, target, note) = match decided {
343 Ok(x) => x,
344 Err(r) => {
345 let outcome = DeepLinkOutcome::refused(req.link.chars().take(120).collect::<String>().as_str(), r.code, &r.text, r.remedy);
346 record(&state, &who, &request_id, &req.link.chars().take(200).collect::<String>(), &outcome);
347 return (StatusCode::OK, Json(json!(outcome))).into_response();
348 }
349 };
350 let label = label_of(&link);
351 let event = crate::backend::mps_events::DeepLinkOpenEvent {
352 request_id: request_id.clone(),
353 link: link.canonical.clone(),
354 agent_id: who.agent_id.clone(),
355 source: None,
356 caller_block_id: who.block_id.clone(),
357 tab_id: who.tab_id.clone(),
358 window_id: who.window_id.clone(),
359 target,
360 expires_at_ms: agentmux_common::time::now_ms() + deeplink_open::KEEP_FOR.as_millis() as i64,
361 };
362 let late = {
363 let (state, who, rid, canonical) = (state.clone(), who.clone(), request_id.clone(), link.canonical.clone());
364 Box::new(move |o: &DeepLinkOutcome| record(&state, &who, &rid, &canonical, o))
365 };
366 let mut outcome = match deeplink_open::carry_out(&state, event, deeplink_open::WAIT_FOR, late).await {
367 Some(o) => o,
368 None => DeepLinkOutcome::queued(&label, "app_starting", "the window has not carried it out yet; it opens when it can"),
369 };
370 record(&state, &who, &request_id, &link.canonical, &outcome);
371 if let Some(n) = note {
372 outcome.remedy = Some(outcome.remedy.map(|r| format!("{n}. {r}")).unwrap_or(n));
373 }
374 let mut body = json!(outcome);
375 body["link"] = json!(link.canonical);
376 (StatusCode::OK, Json(body)).into_response()
377}
378
379#[cfg(test)]
380mod tests {
381 use super::*;
382
383 fn agent(id: &str) -> CallerFacts {
384 CallerFacts { agent_id: id.into(), container: false, block_id: Some("b-own".into()), tab_id: Some("t-own".into()), window_id: Some("w1".into()) }
385 }
386
387 fn parse(link: &str) -> ParsedLink {
388 deeplinks::parse_link(link).unwrap_or_else(|e| panic!("{link}: {}", e.as_str()))
389 }
390
391 fn rules(link: &str, who: &CallerFacts) -> Result<ParsedLink, Refusal> {
392 let mut l = parse(link);
393 check_rules(&mut l, who).map(|()| l)
394 }
395
396 #[test]
397 fn a_public_place_opens_for_any_agent() {
398 for link in ["agentmux://settings/recording", "agentmux://kanban/task/12", "agentmux://vault/api-keys", "agentmux://memory/global", "agentmux://help"] {
399 assert!(rules(link, &agent("a1")).is_ok(), "{link}");
400 }
401 }
402
403 #[test]
404 fn another_agents_personal_memory_is_refused_and_ones_own_opens() {
405 let e = rules("agentmux://memory/personal?agent=b2", &agent("a1")).unwrap_err();
406 assert_eq!(e.code, "not_allowed");
407 assert!(rules("agentmux://memory/personal?agent=a1", &agent("a1")).is_ok());
408 }
409
410 #[test]
411 fn personal_memory_without_an_agent_is_the_callers_own() {
412 let l = rules("agentmux://memory/personal", &agent("a1")).unwrap();
413 assert_eq!(l.params.get("agent"), Some(&Value::Text("a1".into())));
414 }
415
416 #[test]
417 fn the_audit_opens_only_at_the_callers_own_rows() {
418 assert!(rules("agentmux://audit/agent/a1", &agent("a1")).is_ok());
419 assert_eq!(rules("agentmux://audit/agent/b2", &agent("a1")).unwrap_err().code, "not_allowed");
420 for link in ["agentmux://audit", "agentmux://audit/message/m_1", "agentmux://audit/sound/s_1"] {
421 let e = rules(link, &agent("a1")).unwrap_err();
422 assert_eq!(e.code, "not_allowed", "{link}");
423 assert_eq!(e.remedy.as_deref(), Some("agentmux://audit/agent/a1"), "{link}: the refusal says what would work");
424 }
425 }
426
427 #[test]
428 fn a_container_agent_gets_no_path_destination() {
429 let mut who = agent("c1");
430 who.container = true;
431 for link in ["agentmux://editor/%2Fhome%2Fa.md", "agentmux://files/%2Fhome", "agentmux://media/%2Fhome%2Fa.png"] {
432 assert_eq!(rules(link, &who).unwrap_err().code, "not_allowed", "{link}");
433 }
434 assert!(rules("agentmux://settings", &who).is_ok(), "a public view opens for a container agent too");
435 }
436
437 #[test]
438 fn a_window_target_is_refused_and_another_tab_lands_in_the_callers_own() {
439 let who = agent("a1");
440 let no_panes = |_: &str| None;
441 assert_eq!(resolve_target(Some("window:w2"), &who, no_panes).unwrap_err().code, "another_window");
442 assert_eq!(resolve_target(None, &who, no_panes).unwrap(), ("beside".into(), None));
443 assert_eq!(resolve_target(Some("new"), &who, no_panes).unwrap(), ("new".into(), None));
444 let (t, note) = resolve_target(Some("tab:t-persons"), &who, no_panes).unwrap();
445 assert_eq!(t, "new");
446 assert!(note.unwrap().contains("own tab"));
447 assert_eq!(resolve_target(Some("tab:t-own"), &who, no_panes).unwrap(), ("new".into(), None));
448 let tabs = |b: &str| Some(if b == "b-mine" { "t-own".to_string() } else { "t-persons".to_string() });
449 assert_eq!(resolve_target(Some("pane:b-mine"), &who, tabs).unwrap(), ("pane:b-mine".into(), None));
450 let (t, note) = resolve_target(Some("pane:b-persons"), &who, tabs).unwrap();
451 assert_eq!(t, "beside", "a pane in the person's tab is never the target");
452 assert!(note.is_some());
453 assert_eq!(resolve_target(Some("over-there"), &who, no_panes).unwrap_err().code, "invalid_link");
454 }
455
456 #[test]
457 fn ten_opens_a_minute_and_the_eleventh_is_refused_until_the_window_moves() {
458 let l = Limiter::new(RATE_LIMIT);
459 let t0 = Instant::now();
460 for i in 0..RATE_LIMIT {
461 assert!(l.allow("a1", t0 + Duration::from_millis(i as u64)).is_ok());
462 }
463 let wait = l.allow("a1", t0 + Duration::from_secs(1)).unwrap_err();
464 assert!(wait <= RATE_WINDOW && wait > Duration::from_secs(50), "{wait:?}");
465 assert!(l.allow("b2", t0 + Duration::from_secs(1)).is_ok(), "each agent has its own");
466 assert!(l.allow("a1", t0 + RATE_WINDOW + Duration::from_millis(1)).is_ok(), "the window moved");
467 }
468
469 #[test]
470 fn a_link_the_parser_refuses_is_refused_with_its_reason() {
471 let who = agent("a1");
472 let req = |link: &str| OpenLinkRequest { link: link.into(), target: None };
473 let e = guard(&req("agentmux://settings?pane=b1"), &who, |_| None).unwrap_err();
474 assert_eq!(e.code, "invalid_link");
475 assert_eq!(e.text, deeplinks::REGISTRY.reason("unknown_param"));
476 assert_eq!(guard(&req("agentmux://agent/a1"), &who, |_| None).unwrap_err().code, "not_yet");
477 }
478
479 #[test]
480 fn a_path_is_opened_by_its_canonical_form_and_its_kind_is_checked() {
481 let dir = tempfile::tempdir().unwrap();
482 let file = dir.path().join("a.md");
483 std::fs::write(&file, "x").unwrap();
484 let sub = dir.path().join("sub");
485 std::fs::create_dir(&sub).unwrap();
486 let real = canonical_path(&sub.join("..").join("a.md").to_string_lossy(), false).unwrap();
489 assert!(real.ends_with("/a.md") || real.ends_with("\\a.md"), "{real}");
490 assert!(!real.contains(".."), "{real}");
491 assert!(!real.starts_with(r"\\?\"), "{real}");
492 assert_eq!(canonical_path(&file.to_string_lossy(), true).unwrap_err().text, "that is a file: open it with the Editor");
493 assert_eq!(canonical_path(&sub.to_string_lossy(), false).unwrap_err().text, "that is a folder: open it with Files");
494 assert_eq!(canonical_path(&dir.path().join("gone.md").to_string_lossy(), false).unwrap_err().text, "no such file or folder");
495 }
496
497 #[cfg(unix)]
498 #[test]
499 fn a_symbolic_link_opens_where_it_leads_not_where_it_is_written() {
500 let dir = tempfile::tempdir().unwrap();
501 let target = dir.path().join("real.md");
502 std::fs::write(&target, "x").unwrap();
503 let alias = dir.path().join("alias.md");
504 std::os::unix::fs::symlink(&target, &alias).unwrap();
505 let real = canonical_path(&alias.to_string_lossy(), false).unwrap();
506 assert!(real.ends_with("/real.md"), "{real}");
507 }
508
509 #[test]
510 fn the_label_names_the_view_and_the_place_by_id() {
511 assert_eq!(label_of(&parse("agentmux://settings/recording")), "settings › recording");
512 assert_eq!(label_of(&parse("agentmux://kanban/task/7")), "kanban › task");
513 assert_eq!(label_of(&parse("agentmux://help")), "help");
514 }
515}