1use std::collections::BTreeMap;
15use std::sync::{Arc, Mutex};
16use std::time::Duration;
17
18use axum::extract::State;
19use axum::http::StatusCode;
20use axum::response::IntoResponse;
21use axum::Json;
22use serde_json::{json, Value};
23
24use crate::backend::mps::Broker;
25use crate::backend::storage::store::Store;
26use crate::backend::user_attention::Asking;
27use crate::server::browser_dialog::record;
28use crate::server::ui_handlers::{banner_for, err_response, from_host};
29use crate::server::AppState;
30use agentmux_common::time::now_ms;
31
32const DEVICE_AUDIO_CAPTURE: u32 = 1;
34const DEVICE_VIDEO_CAPTURE: u32 = 2;
35const PROMPT_GEOLOCATION: u32 = 256;
37const PROMPT_NOTIFICATIONS: u32 = 32768;
38const GRANT_MS: i64 = 30 * 60 * 1000;
40const MAX_KEPT: usize = 64;
42
43struct Ask {
45 request_id: String,
46 uid: String,
47 agent: String,
48 target: String,
49 site: String,
50 kinds: Vec<&'static str>,
51}
52
53struct Grant {
54 agent: String,
55 target: String,
56 site: String,
57 kinds: Vec<&'static str>,
58 until_ms: i64,
59 audited: bool,
61}
62
63static ASKS: Mutex<Vec<Ask>> = Mutex::new(Vec::new());
64static GRANTS: Mutex<Vec<Grant>> = Mutex::new(Vec::new());
65
66fn asks() -> std::sync::MutexGuard<'static, Vec<Ask>> {
67 ASKS.lock().unwrap_or_else(|e| e.into_inner())
68}
69
70fn grants() -> std::sync::MutexGuard<'static, Vec<Grant>> {
71 GRANTS.lock().unwrap_or_else(|e| e.into_inner())
72}
73
74fn kinds_of(requested: u32, prompt: bool) -> Result<Vec<&'static str>, &'static str> {
77 let (table, refusal): (&[(u32, &'static str)], &str) = if prompt {
78 (
79 &[(PROMPT_GEOLOCATION, "location"), (PROMPT_NOTIFICATIONS, "notifications")],
80 "the page asked for a permission an agent's pane is never given",
81 )
82 } else {
83 (
84 &[(DEVICE_VIDEO_CAPTURE, "camera"), (DEVICE_AUDIO_CAPTURE, "microphone")],
85 "the page asked to capture the screen or the computer's sound, which an agent's pane is never allowed",
86 )
87 };
88 if requested & !table.iter().fold(0, |all, (bit, _)| all | bit) != 0 {
89 return Err(refusal);
90 }
91 let kinds: Vec<&'static str> = table.iter().filter(|(bit, _)| requested & bit != 0).map(|(_, name)| *name).collect();
92 if kinds.is_empty() {
93 return Err("the page asked for nothing AgentMux can name");
94 }
95 Ok(kinds)
96}
97
98fn what_of(kinds: &[&str]) -> String {
100 let named: Vec<&str> = kinds
101 .iter()
102 .map(|k| match *k {
103 "camera" => "the camera",
104 "microphone" => "the microphone",
105 "location" => "the computer's location",
106 _ => "notifications",
107 })
108 .collect();
109 named.join(" and ")
110}
111
112fn covers(g: &Grant, agent: &str, target: &str, site: &str, kinds: &[&str], now: i64) -> bool {
113 g.until_ms > now && g.agent == agent && g.target == target && g.site == site && kinds.iter().all(|k| g.kinds.contains(k))
114}
115
116fn is_granted(agent: &str, target: &str, site: &str, kinds: &[&str], now: i64) -> bool {
117 grants().iter().any(|g| covers(g, agent, target, site, kinds, now))
118}
119
120fn first_use_of_grant(agent: &str, target: &str, site: &str, kinds: &[&str], now: i64) -> bool {
123 match grants().iter_mut().find(|g| covers(g, agent, target, site, kinds, now)) {
124 Some(g) if !g.audited => {
125 g.audited = true;
126 true
127 }
128 _ => false,
129 }
130}
131
132fn audit_standing_allow(state: &AppState, agent: &str, site: &str, kinds: &[&str], message: &str, lasting: bool) {
137 let mut facts = facts_for(agent, site, kinds);
138 if lasting {
139 facts.insert("answer".to_string(), format!("allow {} for {site} (a standing permission from Settings)", what_of(kinds)));
140 }
141 state.reactive_handler.log_sensitive_op_audit(
142 Some(agent),
143 agent,
144 "os_prompt_answer.standing",
145 true,
146 None,
147 &uuid::Uuid::new_v4().to_string(),
148 Some(message),
149 facts.get("prompt").map(String::as_str),
150 facts.get("answer").map(String::as_str),
151 facts.get("level").map(String::as_str),
152 true,
153 );
154}
155
156fn open_ask(agent: &str, target: &str, site: &str, kinds: &[&str]) -> Option<String> {
158 asks()
159 .iter()
160 .filter(|a| a.agent == agent && a.target == target && a.site == site && a.kinds == kinds)
161 .map(|a| a.request_id.clone())
162 .find(|id| crate::backend::sensitive_requests::registry().get(id).is_some_and(|r| r.status.is_open()))
163}
164
165fn remember(ask: Ask) {
166 let mut a = asks();
167 a.retain(|x| crate::backend::sensitive_requests::registry().get(&x.request_id).is_some_and(|r| r.status.is_open()));
169 if a.len() >= MAX_KEPT {
170 a.remove(0);
171 }
172 a.push(ask);
173}
174
175const COUNTDOWN_POLL: Duration = Duration::from_millis(500);
178const COUNTDOWN_WAIT: Duration = Duration::from_secs(30 * 60);
179
180fn announce_countdown(state: &AppState, request_id: String, target: String, text: String) {
185 announce_countdown_with(state.broker.clone(), state.mstore.clone(), request_id, target, text, COUNTDOWN_POLL);
186}
187
188fn announce_countdown_with(broker: Arc<Broker>, store: Arc<Store>, request_id: String, target: String, text: String, poll: Duration) {
189 use crate::backend::sensitive_requests::{registry, Status};
190 tokio::spawn(async move {
191 let started = std::time::Instant::now();
192 let mut asking = None;
193 while started.elapsed() < COUNTDOWN_WAIT {
194 match registry().get(&request_id).map(|r| r.status) {
195 Some(Status::Pending) if asking.is_none() => asking = Some(Asking::start(&broker, &store, &target, "browser", &text)),
196 Some(Status::Asked | Status::Pending) => {}
197 _ => break,
198 }
199 tokio::time::sleep(poll).await;
200 }
201 });
202}
203
204fn facts_for(agent: &str, site: &str, kinds: &[&str]) -> BTreeMap<String, String> {
206 let what = what_of(kinds);
207 BTreeMap::from([
208 ("agent".to_string(), agent.to_string()),
209 ("app".to_string(), "Browser".to_string()),
210 ("window".to_string(), site.to_string()),
211 ("prompt".to_string(), format!("{site} wants to use {what}")),
212 ("answer".to_string(), format!("allow {what} for {site} for 30 minutes")),
213 ("level".to_string(), "medium".to_string()),
214 ("reason".to_string(), "the page asked while the agent was driving this pane".to_string()),
215 ])
216}
217
218fn asked_reason(site: &str, what: &str) -> String {
220 format!(
221 "{site} asked to use {what}. AgentMux denied it for now and filed it as a sensitive operation: the super agent \
222 reviews it and the person can veto its countdown. An [AgentMux] note brings the answer; then ask the page again"
223 )
224}
225
226pub(crate) async fn handle_host_browser_permission(
231 State(state): State<AppState>,
232 headers: axum::http::HeaderMap,
233 Json(body): Json<Value>,
234) -> impl IntoResponse {
235 if !from_host(&state, &headers).await {
236 return err_response(StatusCode::FORBIDDEN, "only the AgentMux host can report a page's permission request".to_string());
237 }
238 let s = |k: &str| body.get(k).and_then(Value::as_str).unwrap_or("").trim().to_string();
239 let target = s("target");
240 let requested = body.get("requested").and_then(Value::as_u64).unwrap_or(0) as u32;
241 let (banner_at, _window) = banner_for(&target);
242 let agent = crate::server::browser_owner::owner_of(&banner_at).unwrap_or_default();
243 let answered = |decision: &str| (StatusCode::OK, Json(json!({ "ok": true, "data": { "decision": decision } }))).into_response();
244 let origin = s("origin");
245 let site = agentmux_common::allowed_origins::target_origin(&origin).unwrap_or(origin);
246 let kinds = match kinds_of(requested, body.get("prompt").and_then(Value::as_bool).unwrap_or(false)) {
247 Ok(k) => k,
248 Err(why) => {
249 record(&agent, &target, "permission", &format!("{site} asked for a permission"), "denied", why);
250 return answered("deny");
251 }
252 };
253 let what = what_of(&kinds);
254 let message = format!("{site} asked to use {what}");
255 if agent.is_empty() || site.is_empty() {
256 return answered("deny");
257 }
258 if super::browser_site_permissions::allowed(&agent, &site, &kinds) {
259 record(&agent, &target, "permission", &message, "allowed", "you allowed it on this site in Settings");
260 if super::browser_site_permissions::first_use(&agent, &target, &site, &kinds) {
261 audit_standing_allow(&state, &agent, &site, &kinds, &message, true);
262 }
263 return answered("allow");
264 }
265 if is_granted(&agent, &target, &site, &kinds, now_ms()) {
266 record(&agent, &target, "permission", &message, "allowed", "the person's countdown for this site ended without a veto");
267 if first_use_of_grant(&agent, &target, &site, &kinds, now_ms()) {
268 audit_standing_allow(&state, &agent, &site, &kinds, &message, false);
269 }
270 return answered("allow");
271 }
272 if open_ask(&agent, &target, &site, &kinds).is_some() {
273 record(&agent, &target, "permission", &message, "denied", "it is already asked for; the answer comes as an [AgentMux] note");
274 return answered("deny");
275 }
276 let uid = crate::backend::reactive::get_global_handler().get_agent(&agent).and_then(|r| r.uid).unwrap_or_default();
277 if uid.is_empty() {
278 record(&agent, &target, "permission", &message, "denied", "this agent has no token to ask with");
279 return answered("deny");
280 }
281 let facts = facts_for(&agent, &site, &kinds);
282 let reason = format!("let {site} use {what} in the pane {agent} is driving");
283 match crate::server::sensitive_handlers::file_request(&state, &uid, &agent, "os_prompt_answer", &facts, &reason).await {
284 Ok(filed) => {
285 let request_id = filed["id"].as_str().unwrap_or_default().to_string();
286 announce_countdown(&state, request_id.clone(), target.clone(), format!("{agent} needs you: {site} wants to use {what}"));
287 remember(Ask { request_id, uid, agent: agent.clone(), target: target.clone(), site: site.clone(), kinds });
288 record(&agent, &target, "permission", &message, "denied for now", &asked_reason(&site, &what));
289 }
290 Err(e) => record(&agent, &target, "permission", &message, "denied", &format!("couldn't ask: {e}")),
291 }
292 answered("deny")
293}
294
295pub(crate) fn grant_after_countdown(_state: &AppState, request_id: &str) -> Result<(), String> {
298 let mine: Vec<Ask> = {
300 let mut a = asks();
301 let (mine, rest): (Vec<Ask>, Vec<Ask>) = std::mem::take(&mut *a).into_iter().partition(|x| x.request_id == request_id);
302 *a = rest;
303 mine
304 };
305 if mine.is_empty() {
306 return Err("the permission this request was for is no longer known; ask the page again".to_string());
307 }
308 let request = crate::backend::sensitive_requests::registry().get(request_id);
309 let askers = request.as_ref().map(|r| r.askers()).unwrap_or_default();
310 let until_ms = now_ms() + GRANT_MS;
311 let mut any = false;
312 for a in mine.into_iter().filter(|a| askers.contains(&a.uid.as_str())) {
313 let mut g = grants();
314 g.retain(|x| x.until_ms > now_ms());
315 if g.len() >= MAX_KEPT {
316 g.remove(0);
317 }
318 g.push(Grant { agent: a.agent, target: a.target, site: a.site, kinds: a.kinds, until_ms, audited: false });
319 any = true;
320 }
321 if any {
322 Ok(())
323 } else {
324 Err("everyone who asked has withdrawn".to_string())
325 }
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331
332 #[test]
333 fn a_camera_or_microphone_is_named_and_anything_else_is_refused() {
334 assert_eq!(kinds_of(DEVICE_VIDEO_CAPTURE, false), Ok(vec!["camera"]));
335 assert_eq!(kinds_of(DEVICE_AUDIO_CAPTURE | DEVICE_VIDEO_CAPTURE, false), Ok(vec!["camera", "microphone"]));
336 assert!(kinds_of(4, false).unwrap_err().contains("screen"));
337 assert!(kinds_of(DEVICE_VIDEO_CAPTURE | 8, false).is_err(), "a screen share with the camera is still a screen share");
338 assert!(kinds_of(0, false).is_err());
339 }
340
341 #[test]
342 fn a_location_or_notification_prompt_is_named_and_the_media_bits_are_not_its_bits() {
343 assert_eq!(kinds_of(PROMPT_GEOLOCATION, true), Ok(vec!["location"]));
344 assert_eq!(kinds_of(PROMPT_GEOLOCATION | PROMPT_NOTIFICATIONS, true), Ok(vec!["location", "notifications"]));
345 assert!(kinds_of(1, true).is_err(), "bit 1 is a camera in a media request, nothing in a prompt");
346 assert!(kinds_of(PROMPT_NOTIFICATIONS | (1 << 14), true).is_err(), "something else with it is refused");
347 assert!(kinds_of(PROMPT_GEOLOCATION, false).is_err(), "a prompt's bits are not a media request's");
348 assert_eq!(what_of(&["camera", "microphone"]), "the camera and the microphone");
349 assert_eq!(what_of(&["location"]), "the computer's location");
350 assert_eq!(what_of(&["notifications"]), "notifications");
351 }
352
353 #[test]
354 fn the_facts_fit_the_operation_and_say_who_wrote_what() {
355 let spec = crate::backend::sensitive_ops::spec("os_prompt_answer").unwrap();
356 let facts = facts_for("posa", "https://meet.example", &["camera", "microphone"]);
357 let checked = spec.check_facts(&facts).unwrap();
358 assert_eq!(checked["app"], "Browser");
359 assert_eq!(checked["level"], "medium");
360 assert!(checked["prompt"].contains("https://meet.example") && checked["answer"].contains("the camera and the microphone"));
361 let summary = spec.summary(&checked);
362 assert!(summary.starts_with("answer a prompt for an agent (") && summary.contains("meet.example"), "{summary}");
363 }
364
365 #[test]
366 fn a_grant_covers_its_agent_pane_site_and_kinds_until_it_runs_out() {
367 let g = Grant { agent: "a".into(), target: "p".into(), site: "https://s".into(), kinds: vec!["camera", "microphone"], until_ms: 1000, audited: false };
368 assert!(covers(&g, "a", "p", "https://s", &["camera"], 999));
369 assert!(covers(&g, "a", "p", "https://s", &["camera", "microphone"], 999));
370 assert!(!covers(&g, "a", "p", "https://s", &["camera"], 1000), "expired");
371 assert!(!covers(&g, "b", "p", "https://s", &["camera"], 10), "another agent");
372 assert!(!covers(&g, "a", "q", "https://s", &["camera"], 10), "another pane");
373 assert!(!covers(&g, "a", "p", "https://other", &["camera"], 10), "another site");
374 let cam = Grant { kinds: vec!["camera"], ..g };
375 assert!(!covers(&cam, "a", "p", "https://s", &["camera", "microphone"], 10), "a camera grant is not a microphone grant");
376 }
377
378 #[tokio::test]
379 async fn the_countdown_ending_grants_only_what_was_asked_and_only_once() {
380 let state = crate::server::tests::test_state();
381 let uid = format!("u-bp-{}", uuid::Uuid::new_v4().simple());
382 let site = format!("https://{}.example", uuid::Uuid::new_v4().simple());
383 let facts = facts_for("bp-agent", &site, &["camera"]);
384 let id = crate::backend::sensitive_requests::registry().request(&uid, "bp-agent", "os_prompt_answer", &facts, "", now_ms()).unwrap().id;
385 remember(Ask { request_id: id.clone(), uid: uid.clone(), agent: "bp-agent".into(), target: "pane-1".into(), site: site.clone(), kinds: vec!["camera"] });
386 assert!(open_ask("bp-agent", "pane-1", &site, &["camera"]).is_some());
387 assert!(!is_granted("bp-agent", "pane-1", &site, &["camera"], now_ms()), "nothing is allowed before the countdown ends");
388 grant_after_countdown(&state, &id).unwrap();
389 assert!(is_granted("bp-agent", "pane-1", &site, &["camera"], now_ms()));
390 assert!(!is_granted("bp-agent", "pane-1", &site, &["microphone"], now_ms()), "the microphone was not asked for");
391 assert!(grant_after_countdown(&state, &id).is_err(), "a second run finds nothing to grant");
392 }
393
394 #[tokio::test]
395 async fn the_countdown_is_announced_in_its_pane_for_its_length_only() {
396 use crate::backend::sensitive_requests::{registry, Status};
397 let state = crate::server::tests::test_state();
398 let uid = format!("u-bp-{}", uuid::Uuid::new_v4().simple());
399 let site = format!("https://{}.example", uuid::Uuid::new_v4().simple());
400 let pane = format!("pane-{}", uuid::Uuid::new_v4().simple());
401 let facts = facts_for("bp-agent", &site, &["camera"]);
402 let id = registry().request(&uid, "bp-agent", "os_prompt_answer", &facts, "", now_ms()).unwrap().id;
403 let mine = |pane: &str| crate::backend::user_attention::open_requests().into_iter().filter(|a| a.block_id == pane && a.kind == "browser").count();
404 announce_countdown_with(state.broker.clone(), state.mstore.clone(), id.clone(), pane.clone(), "bp-agent needs you".into(), Duration::from_millis(10));
405 tokio::time::sleep(Duration::from_millis(80)).await;
406 assert_eq!(mine(&pane), 0, "the super agent is still reviewing: not the person's to answer");
407 registry().approve(&id, "super", now_ms()).unwrap();
408 tokio::time::sleep(Duration::from_millis(80)).await;
409 assert_eq!(mine(&pane), 1, "announced while the countdown runs");
410 registry().finish(&id, Status::Vetoed, now_ms()).unwrap();
411 tokio::time::sleep(Duration::from_millis(80)).await;
412 assert_eq!(mine(&pane), 0, "ended with the countdown");
413 }
414
415 #[tokio::test]
416 async fn a_standing_grant_writes_one_audit_row_flagged_standing() {
417 let state = crate::server::tests::test_state();
418 let agent = format!("bp-agent-{}", uuid::Uuid::new_v4().simple());
421 audit_standing_allow(&state, &agent, "https://standing.example", &["camera", "microphone"], "https://standing.example asked to use the camera and the microphone", false);
422 let mine: Vec<_> = state.reactive_handler.get_audit_log(200).into_iter().filter(|r| r.target_agent == agent).collect();
423 assert_eq!(mine.len(), 1, "exactly one row");
424 let row = &mine[0];
425 assert_eq!(row.standing, Some(true));
426 assert!(row.prompt.as_deref().unwrap().contains("standing.example"));
427 assert!(row.answer.as_deref().unwrap().contains("camera") && row.answer.as_deref().unwrap().contains("microphone"));
428 assert_eq!(row.level.as_deref(), Some("medium"));
429 assert!(row.answer.as_deref().unwrap().ends_with("for 30 minutes"));
430 }
431
432 #[tokio::test]
433 async fn a_settings_row_is_audited_without_a_30_minute_duration() {
434 let state = crate::server::tests::test_state();
435 let agent = format!("bp-agent-{}", uuid::Uuid::new_v4().simple());
436 audit_standing_allow(&state, &agent, "https://lasting.example", &["camera"], "https://lasting.example asked to use the camera", true);
437 let mine: Vec<_> = state.reactive_handler.get_audit_log(200).into_iter().filter(|r| r.target_agent == agent).collect();
438 assert_eq!(mine.len(), 1);
439 let answer = mine[0].answer.as_deref().unwrap();
440 assert!(answer.contains("a standing permission from Settings") && !answer.contains("30 minutes"), "{answer}");
441 assert_eq!(mine[0].standing, Some(true));
442 }
443
444 #[test]
445 fn a_page_asking_again_during_a_grant_is_audited_once() {
446 let site = format!("https://{}.example", uuid::Uuid::new_v4().simple());
447 grants().push(Grant { agent: "bp-agent-3".into(), target: "pane-9".into(), site: site.clone(), kinds: vec!["camera"], until_ms: now_ms() + GRANT_MS, audited: false });
448 assert!(first_use_of_grant("bp-agent-3", "pane-9", &site, &["camera"], now_ms()), "the first use is audited");
449 for _ in 0..5 {
450 assert!(!first_use_of_grant("bp-agent-3", "pane-9", &site, &["camera"], now_ms()), "a repeat ask adds no row");
451 }
452 assert!(!first_use_of_grant("bp-agent-3", "pane-9", &site, &["microphone"], now_ms()), "an uncovered ask is not a use");
453 }
454}