Skip to main content

agentmux_srv/server/
browser_site_permissions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The person's "always on this site" for a page's camera, microphone, location or notifications in a
5//! pane an agent drives (docs/reports/REPORT_AGENTS_AND_OS_PROMPTS_2026_11_07.md ยง4.5, medium level).
6//!
7//! A row names one agent, one site and the kinds it may use there. It is a setting: it lives in a file in
8//! the config folder, survives restarts, is listed in Settings and revoked there. It is not an Auto-approve
9//! grant (`browser_standing`): those lift the wait for committing clicks, and a camera must not bring that
10//! along, so these rows are a list of their own.
11//!
12//! Only the person writes rows: from the Settings window (`app_api/browser_grants.rs` checks that), or by
13//! answering "Always" on an agent's account prompt (`add_kind`). With
14//! a row, `browser_permission` allows the page's request at once, with no countdown, and writes one Audit
15//! row flagged `standing` for the first use in a pane.
16
17use std::collections::HashSet;
18use std::path::PathBuf;
19use std::sync::{Mutex, OnceLock};
20
21use serde::{Deserialize, Serialize};
22
23use crate::server::AppState;
24
25/// The file the rows are kept in, in the config folder.
26const FILE_NAME: &str = "browser-site-permissions.json";
27
28/// Most rows kept: a list this long is a mistake, not a use.
29const MAX_ROWS: usize = 200;
30
31/// What a row can carry: what a page may use (the words `browser_permission` names them in), and
32/// `accounts`, which is not the page's: the agent may make an account on the site with a password
33/// the Vault makes (`browser_account`), the person's "Always for this agent on this site".
34pub(crate) const KINDS: [&str; 5] = ["camera", "microphone", "location", "notifications", ACCOUNTS];
35
36/// The kind of "may make an account here".
37pub(crate) const ACCOUNTS: &str = "accounts";
38
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub(crate) struct Row {
41    pub id: String,
42    /// The agent's id (its slug), as the pane's owner is known.
43    pub agent: String,
44    /// The one site, in `allowed_origins` normal form (`https://meet.example.com`).
45    pub site: String,
46    pub kinds: Vec<String>,
47    /// Milliseconds since the Unix epoch.
48    pub granted_at_ms: i64,
49}
50
51/// The rows, and where they are kept (None: nowhere, for tests).
52struct Store {
53    path: Option<PathBuf>,
54    rows: Vec<Row>,
55}
56
57impl Store {
58    fn open(path: PathBuf) -> Store {
59        let rows = match std::fs::read(&path) {
60            Ok(bytes) => serde_json::from_slice::<Vec<Row>>(&bytes).unwrap_or_else(|e| {
61                // A file nobody can read allows nothing: the person sees an empty list.
62                tracing::warn!(error = %e, "[browser-site-permissions] the file is unreadable; none are in force");
63                Vec::new()
64            }),
65            Err(_) => Vec::new(),
66        };
67        Store { path: Some(path), rows }
68    }
69
70    /// Make `rows` the rows: written to the file first, and kept in memory only once that worked, so a
71    /// failed write leaves the person's view and the file the same.
72    fn commit(&mut self, rows: Vec<Row>) -> Result<(), String> {
73        crate::server::browser_standing::write_rows(self.path.as_deref(), &rows)?;
74        self.rows = rows;
75        Ok(())
76    }
77}
78
79fn store() -> std::sync::MutexGuard<'static, Store> {
80    static S: OnceLock<Mutex<Store>> = OnceLock::new();
81    // Tests that go through here keep the rows in memory, never in the real config folder.
82    #[cfg(test)]
83    let open = || Store { path: None, rows: Vec::new() };
84    #[cfg(not(test))]
85    let open = || Store::open(crate::backend::base::get_mux_config_dir().join(FILE_NAME));
86    S.get_or_init(|| Mutex::new(open())).lock().unwrap_or_else(|p| p.into_inner())
87}
88
89/// `kinds` checked: at least one, each a known kind, listed once in the fixed order.
90fn parse_kinds(asked: &[String]) -> Result<Vec<String>, String> {
91    if let Some(bad) = asked.iter().find(|k| !KINDS.iter().any(|known| known.eq_ignore_ascii_case(k.trim()))) {
92        return Err(format!("unknown permission {bad:?}: choose from {}", KINDS.join(", ")));
93    }
94    let kinds: Vec<String> = KINDS
95        .iter()
96        .filter(|known| asked.iter().any(|k| known.eq_ignore_ascii_case(k.trim())))
97        .map(|k| k.to_string())
98        .collect();
99    if kinds.is_empty() {
100        return Err("choose what the site may use".to_string());
101    }
102    Ok(kinds)
103}
104
105/// The one site, in normal form. A wildcard is refused: a row names one site.
106fn parse_site(site: &str) -> Result<String, String> {
107    let origins = agentmux_common::allowed_origins::parse_list(&[site.to_string()])?;
108    match origins.as_slice() {
109        [one] if !one.contains("://*.") => Ok(one.clone()),
110        [one] => Err(format!("{one:?} names every subdomain: name one site (https://meet.example.com)")),
111        _ => Err("name one site".to_string()),
112    }
113}
114
115/// Add the row for `agent` on `site`, or replace its kinds.
116fn upsert_in(rows: &mut Vec<Row>, agent: &str, site: &str, kinds: &[String], now_ms: i64) -> Result<Row, String> {
117    let agent = agent.trim().to_ascii_lowercase();
118    if agent.is_empty() {
119        return Err("name the agent".to_string());
120    }
121    let site = parse_site(site)?;
122    let kinds = parse_kinds(kinds)?;
123    if let Some(row) = rows.iter_mut().find(|r| r.agent == agent && r.site == site) {
124        row.kinds = kinds;
125        return Ok(row.clone());
126    }
127    if rows.len() >= MAX_ROWS {
128        return Err(format!("there are already {MAX_ROWS} site permissions: revoke some first"));
129    }
130    let row = Row { id: uuid::Uuid::new_v4().to_string(), agent, site, kinds, granted_at_ms: now_ms };
131    rows.push(row.clone());
132    Ok(row)
133}
134
135/// The row that lets `agent` use all of `kinds` on `site`, if one does.
136fn covering<'a>(rows: &'a [Row], agent: &str, site: &str, kinds: &[&str]) -> Option<&'a Row> {
137    rows.iter().find(|r| r.agent.eq_ignore_ascii_case(agent) && r.site == site && kinds.iter().all(|k| r.kinds.iter().any(|have| have == k)))
138}
139
140pub(crate) fn list() -> Vec<Row> {
141    store().rows.clone()
142}
143
144/// Add a row, or change the kinds of the one for this agent and site. The caller has checked that the
145/// person is the one asking.
146pub(crate) fn upsert(state: &AppState, agent: &str, site: &str, kinds: &[String]) -> Result<Row, String> {
147    let row = {
148        let mut s = store();
149        let mut next = s.rows.clone();
150        let row = upsert_in(&mut next, agent, site, kinds, chrono::Utc::now().timestamp_millis())?;
151        s.commit(next)?;
152        row
153    };
154    tracing::info!(agent = %row.agent, site = %row.site, kinds = ?row.kinds, "[browser-site-permissions] a site permission was set");
155    state.broker.publish_event::<crate::backend::mps_events::BrowserGrantsChanged>(&(), vec![], 0);
156    Ok(row)
157}
158
159/// The person's "Always" on an agent's account prompt: `kind` is added to the row for `agent` on `site`
160/// (made if there is none), keeping what the row already carries. The person answered in the Vault's own
161/// prompt, a window no agent's click reaches, so this is their write as much as one from Settings.
162pub(crate) fn add_kind(state: &AppState, agent: &str, site: &str, kind: &str) -> Result<Row, String> {
163    let site = parse_site(site)?;
164    let mut kinds: Vec<String> = list().into_iter().find(|r| r.agent.eq_ignore_ascii_case(agent.trim()) && r.site == site).map(|r| r.kinds).unwrap_or_default();
165    kinds.push(kind.to_string());
166    upsert(state, agent, &site, &kinds)
167}
168
169/// Whether the person has let `agent` make accounts on `site` (the origin the host found the sign-up form on).
170pub(crate) fn may_make_accounts(agent: &str, site: &str) -> bool {
171    parse_site(site).is_ok_and(|site| allowed(agent, &site, &[ACCOUNTS]))
172}
173
174/// Remove row `id`. Returns whether it was there; an error when the file could not be written, in which
175/// case the row stays (it would be back after a restart anyway). The next request from the page asks again.
176pub(crate) fn revoke(state: &AppState, id: &str) -> Result<bool, String> {
177    let removed = {
178        let mut s = store();
179        let mut next = s.rows.clone();
180        next.retain(|r| r.id != id);
181        let gone = next.len() != s.rows.len();
182        if gone {
183            s.commit(next)?;
184        }
185        gone
186    };
187    if removed {
188        state.broker.publish_event::<crate::backend::mps_events::BrowserGrantsChanged>(&(), vec![], 0);
189        tracing::info!(row = %id, "[browser-site-permissions] a site permission was revoked");
190    }
191    Ok(removed)
192}
193
194/// Whether the person has allowed `agent` all of `kinds` on `site` for good.
195pub(crate) fn allowed(agent: &str, site: &str, kinds: &[&str]) -> bool {
196    covering(&store().rows, agent, site, kinds).is_some()
197}
198
199/// Whether this is the first use of the permission in `target` since AgentMux started, which is the one
200/// that earns an Audit row: a page asking again adds none. Kept small: it forgets all when it fills.
201pub(crate) fn first_use(agent: &str, target: &str, site: &str, kinds: &[&str]) -> bool {
202    static SEEN: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
203    let mut seen = SEEN.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
204    if seen.len() >= 1024 {
205        seen.clear();
206    }
207    seen.insert(format!("{agent}|{target}|{site}|{}", kinds.join(",")))
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    fn kinds(k: &[&str]) -> Vec<String> {
215        k.iter().map(|s| s.to_string()).collect()
216    }
217
218    #[test]
219    fn a_row_covers_its_agent_on_its_site_for_the_kinds_it_carries_only() {
220        let mut rows = Vec::new();
221        upsert_in(&mut rows, "Posa", "https://meet.example.com", &kinds(&["microphone", "camera"]), 1).unwrap();
222        assert_eq!(rows[0].kinds, ["camera", "microphone"], "listed in the fixed order");
223        assert!(covering(&rows, "posa", "https://meet.example.com", &["camera"]).is_some());
224        assert!(covering(&rows, "posa", "https://meet.example.com", &["camera", "microphone"]).is_some());
225        assert!(covering(&rows, "posa", "https://meet.example.com", &["location"]).is_none(), "not carried");
226        assert!(covering(&rows, "lazo", "https://meet.example.com", &["camera"]).is_none(), "another agent");
227        assert!(covering(&rows, "posa", "https://other.example.com", &["camera"]).is_none(), "another site");
228        assert!(covering(&rows, "posa", "https://meet.example.com:8443", &["camera"]).is_none(), "another port is another site");
229    }
230
231    #[test]
232    fn accounts_is_a_kind_listed_last_and_never_stands_in_for_a_page_permission() {
233        let mut rows = Vec::new();
234        upsert_in(&mut rows, "posa", "https://meet.example.com", &kinds(&["accounts", "camera"]), 1).unwrap();
235        assert_eq!(rows[0].kinds, ["camera", "accounts"]);
236        let only = {
237            let mut r = Vec::new();
238            upsert_in(&mut r, "posa", "https://shop.example.com", &kinds(&["accounts"]), 1).unwrap();
239            r
240        };
241        assert!(covering(&only, "posa", "https://shop.example.com", &[ACCOUNTS]).is_some());
242        assert!(covering(&only, "posa", "https://shop.example.com", &["camera"]).is_none(), "an account grant brings no camera");
243    }
244
245    #[tokio::test]
246    async fn adding_accounts_keeps_the_page_permissions_the_row_already_had() {
247        let state = crate::server::tests::test_state();
248        let (agent, site) = (format!("kept-{}", uuid::Uuid::new_v4().simple()), "https://keep.example.com");
249        upsert(&state, &agent, site, &kinds(&["camera"])).unwrap();
250        let row = add_kind(&state, &agent, site, ACCOUNTS).unwrap();
251        assert_eq!(row.kinds, ["camera", "accounts"]);
252        assert_eq!(list().iter().filter(|r| r.agent == agent).count(), 1, "one row, not two");
253        assert!(may_make_accounts(&agent, "https://keep.example.com"));
254        assert!(!may_make_accounts(&agent, "https://keep.example.com:8443"), "another port is another site");
255        assert!(!may_make_accounts(&agent, "not a site"));
256    }
257
258    #[test]
259    fn setting_a_row_again_replaces_its_kinds_instead_of_adding_one() {
260        let mut rows = Vec::new();
261        let first = upsert_in(&mut rows, "posa", "https://meet.example.com", &kinds(&["camera"]), 1).unwrap();
262        let again = upsert_in(&mut rows, "posa", "https://meet.example.com", &kinds(&["notifications"]), 2).unwrap();
263        assert_eq!((rows.len(), first.id.clone()), (1, again.id));
264        assert_eq!(rows[0].kinds, ["notifications"]);
265    }
266
267    #[test]
268    fn an_unknown_kind_a_wildcard_and_an_empty_choice_are_refused() {
269        let mut rows = Vec::new();
270        let site = "https://meet.example.com";
271        assert!(upsert_in(&mut rows, "posa", site, &kinds(&["screen"]), 1).unwrap_err().contains("screen"));
272        assert!(upsert_in(&mut rows, "posa", site, &[], 1).is_err());
273        assert!(upsert_in(&mut rows, "posa", "https://*.example.com", &kinds(&["camera"]), 1).is_err(), "a row names one site");
274        assert!(upsert_in(&mut rows, " ", site, &kinds(&["camera"]), 1).is_err());
275        assert!(rows.is_empty());
276    }
277
278    #[test]
279    fn the_list_is_capped() {
280        let mut rows = Vec::new();
281        for i in 0..MAX_ROWS {
282            upsert_in(&mut rows, "posa", &format!("https://s{i}.example.com"), &kinds(&["camera"]), 1).unwrap();
283        }
284        assert!(upsert_in(&mut rows, "posa", "https://one-more.example.com", &kinds(&["camera"]), 1).is_err());
285        assert!(upsert_in(&mut rows, "posa", "https://s0.example.com", &kinds(&["location"]), 1).is_ok(), "changing a row is not adding one");
286    }
287
288    #[test]
289    fn rows_survive_a_restart_and_an_unreadable_file_allows_nothing() {
290        let dir = tempfile::tempdir().unwrap();
291        let path = dir.path().join(FILE_NAME);
292        let mut s = Store { path: Some(path.clone()), rows: Vec::new() };
293        let mut next = Vec::new();
294        upsert_in(&mut next, "posa", "https://meet.example.com", &kinds(&["camera"]), 1).unwrap();
295        s.commit(next).unwrap();
296        assert_eq!(Store::open(path.clone()).rows, s.rows);
297        std::fs::write(&path, b"{ not json").unwrap();
298        assert!(Store::open(path).rows.is_empty());
299    }
300
301    #[test]
302    fn a_change_the_file_could_not_record_does_not_happen_in_memory_either() {
303        let dir = tempfile::tempdir().unwrap();
304        // A folder that cannot be made: its parent is a file.
305        let blocker = dir.path().join("blocker");
306        std::fs::write(&blocker, b"x").unwrap();
307        let mut s = Store { path: Some(blocker.join(FILE_NAME)), rows: Vec::new() };
308        let mut one = Vec::new();
309        upsert_in(&mut one, "posa", "https://meet.example.com", &kinds(&["camera"]), 1).unwrap();
310        s.rows = one.clone();
311        let err = s.commit(Vec::new()).unwrap_err();
312        assert!(err.contains("couldn't save") && err.contains("nothing was changed"), "{err}");
313        assert_eq!(s.rows, one, "a revoke that could not be written leaves the row, as the file has it");
314    }
315
316    #[test]
317    fn only_the_first_use_in_a_pane_is_audited() {
318        let site = format!("https://{}.example", uuid::Uuid::new_v4().simple());
319        assert!(first_use("posa", "pane-1", &site, &["camera"]));
320        assert!(!first_use("posa", "pane-1", &site, &["camera"]));
321        assert!(first_use("posa", "pane-2", &site, &["camera"]), "another pane is another use");
322    }
323}