Skip to main content

agentmux_srv/server/
browser_standing.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The person's standing grants: "this agent may do these things on this
5//! site, until I say otherwise"
6//! (docs/specs/SPEC_BROWSER_WEB_TERMINAL_TYPING_2026_10_23.md ยง3).
7//!
8//! A row names one agent and one site (with, for a preset, the frames of other
9//! sites that belong to it) and the powers it carries. It is a
10//! setting: it lives in a file in the config folder and survives restarts. A
11//! row grants nothing by itself. When its agent works on a pane showing a
12//! site the row names, [`activate_at`] makes a pane grant from it (the strip,
13//! Stop, Pause, Take over and the idle rule are the pane grant's), so the
14//! agent never has to ask again and the person's controls are the ones they
15//! already know.
16//!
17//! Only the person writes rows: through the Settings window
18//! (`app_api/browser_grants.rs`, which checks that), or by answering a
19//! request banner with "Always". No agent route reaches this module.
20
21use std::path::PathBuf;
22use std::sync::{Mutex, OnceLock};
23
24use serde::{Deserialize, Serialize};
25
26use crate::server::browser_bypass as bypass;
27use crate::server::browser_powers::{self, Power};
28use crate::server::AppState;
29
30/// The file the rows are kept in, in the config folder.
31const FILE_NAME: &str = "browser-standing-grants.json";
32
33/// Most rows kept: a list this long is a mistake, not a use.
34const MAX_ROWS: usize = 200;
35
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37pub(crate) struct Row {
38    pub id: String,
39    /// The agent's id (its slug), as `request_auto_approve` sees it.
40    pub agent: String,
41    /// The sites, in `allowed_origins` normal form: the one the person sees
42    /// first, then any whose frames belong to it (Cloud Shell's terminal runs
43    /// in a frame of another site than the page that shows it).
44    pub origins: Vec<String>,
45    /// The wire names of the powers, committing clicks always among them.
46    pub powers: Vec<String>,
47    /// Milliseconds since the Unix epoch.
48    pub granted_at_ms: i64,
49}
50
51impl Row {
52    /// The powers as the grant module knows them.
53    pub(crate) fn powers(&self) -> Vec<Power> {
54        browser_powers::parse(Some(&self.powers)).unwrap_or_else(|_| vec![Power::Clicks])
55    }
56}
57
58/// The rows, and where they are kept (None: nowhere, for tests).
59struct Store {
60    path: Option<PathBuf>,
61    rows: Vec<Row>,
62}
63
64impl Store {
65    fn open(path: PathBuf) -> Store {
66        let rows = match std::fs::read(&path) {
67            Ok(bytes) => serde_json::from_slice::<Vec<Row>>(&bytes).unwrap_or_else(|e| {
68                // A file nobody can read grants nothing: the person sees an empty list.
69                tracing::warn!(error = %e, "[browser-standing] the standing grants file is unreadable; none are in force");
70                Vec::new()
71            }),
72            Err(_) => Vec::new(),
73        };
74        Store { path: Some(path), rows }
75    }
76
77    /// Make `rows` the rows: written to the file first, and kept in memory only once that worked, so a
78    /// failed write leaves the person's view and the file the same.
79    fn commit(&mut self, rows: Vec<Row>) -> Result<(), String> {
80        write_rows(self.path.as_deref(), &rows)?;
81        self.rows = rows;
82        Ok(())
83    }
84}
85
86/// `rows` as the file at `path` (None: nowhere, for tests). The error says what failed, for the person.
87pub(crate) fn write_rows<T: Serialize>(path: Option<&std::path::Path>, rows: &[T]) -> Result<(), String> {
88    let Some(path) = path else { return Ok(()) };
89    let bytes = serde_json::to_vec_pretty(rows).map_err(|e| format!("couldn't encode the rows: {e}"))?;
90    write_atomic(path, &bytes).map_err(|e| format!("couldn't save {}: {e}; nothing was changed", path.display()))
91}
92
93/// Write `bytes` to `path` so a reader never sees half a file: a temp file in
94/// the same folder, flushed, then renamed over it.
95pub(crate) fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
96    use std::io::Write;
97    let parent = path.parent().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "no folder to write in"))?;
98    std::fs::create_dir_all(parent)?;
99    let mut tmp = tempfile::Builder::new().prefix(".standing-grants-").suffix(".json").tempfile_in(parent)?;
100    tmp.as_file_mut().write_all(bytes)?;
101    tmp.as_file_mut().sync_all()?;
102    tmp.persist(path).map_err(|e| e.error)?;
103    Ok(())
104}
105
106fn store() -> std::sync::MutexGuard<'static, Store> {
107    static S: OnceLock<Mutex<Store>> = OnceLock::new();
108    S.get_or_init(|| Mutex::new(Store::open(crate::backend::base::get_mux_config_dir().join(FILE_NAME))))
109        .lock()
110        .unwrap_or_else(|p| p.into_inner())
111}
112
113/// The row of `rows` that lets `agent` work on `url`, if one does. A page with
114/// no web origin (`about:blank`, `data:`) is never covered.
115fn find<'a>(rows: &'a [Row], agent: &str, url: &str) -> Option<&'a Row> {
116    agentmux_common::allowed_origins::target_origin(url)?;
117    rows.iter()
118        .find(|r| r.agent.eq_ignore_ascii_case(agent) && agentmux_common::allowed_origins::allows(&r.origins, url))
119}
120
121/// Add or replace the row for `agent` on `sites` (the first names the row).
122/// A wildcard (`*.example.com`) is only for a preset or a banner the person
123/// answered (`wildcard_ok`): a row the person types in names one site.
124fn upsert_in(
125    rows: &mut Vec<Row>,
126    agent: &str,
127    sites: &[String],
128    powers: &[String],
129    wildcard_ok: bool,
130    now_ms: i64,
131) -> Result<Row, String> {
132    let agent = agent.trim().to_ascii_lowercase();
133    if agent.is_empty() {
134        return Err("name the agent".to_string());
135    }
136    if sites.is_empty() {
137        return Err("name the site".to_string());
138    }
139    let origins = agentmux_common::allowed_origins::parse_list(sites)?;
140    if !wildcard_ok {
141        if let Some(wild) = origins.iter().find(|o| o.contains("://*.")) {
142            return Err(format!("{wild:?} names every subdomain: a standing grant names one site (https://shell.example.com)"));
143        }
144    }
145    let powers: Vec<String> = browser_powers::names(&browser_powers::parse(Some(powers))?).iter().map(|n| n.to_string()).collect();
146    if let Some(row) = rows.iter_mut().find(|r| r.agent == agent && r.origins.first() == origins.first()) {
147        row.origins = origins;
148        row.powers = powers;
149        return Ok(row.clone());
150    }
151    if rows.len() >= MAX_ROWS {
152        return Err(format!("there are already {MAX_ROWS} standing grants: revoke some first"));
153    }
154    let row = Row { id: uuid::Uuid::new_v4().to_string(), agent, origins, powers, granted_at_ms: now_ms };
155    rows.push(row.clone());
156    Ok(row)
157}
158
159/// A console the person can switch on for an agent with one click.
160pub(crate) struct Preset {
161    pub id: &'static str,
162    pub label: &'static str,
163    /// The page's site first, then the sites whose frames belong to it.
164    pub sites: &'static [&'static str],
165    /// What the person is told beside it.
166    pub note: &'static str,
167}
168
169/// The presets. The sites are the ones the console's own documentation names;
170/// each is to be checked against the real console in a signed-in run (the spec's
171/// Phase 0 live check), and AWS CloudShell and GitHub Codespaces wait for that
172/// check, because their hostnames vary by region and by codespace.
173pub(crate) const PRESETS: [Preset; 2] = [
174    Preset {
175        id: "google-cloud-shell",
176        label: "Google Cloud Shell",
177        sites: &["https://shell.cloud.google.com", "https://ssh.cloud.google.com"],
178        note: "Not yet checked against a signed-in Cloud Shell: if the terminal doesn't work, tell the person who set it up.",
179    },
180    Preset {
181        id: "azure-cloud-shell",
182        label: "Azure Cloud Shell",
183        sites: &["https://shell.azure.com"],
184        note: "Not yet checked against a signed-in Cloud Shell: if the terminal doesn't work, tell the person who set it up.",
185    },
186];
187
188/// Turn a preset on for `agent` with the terminal power (a preset is for
189/// consoles).
190pub(crate) fn enable_preset(state: &AppState, preset: &str, agent: &str) -> Result<Row, String> {
191    let p = PRESETS.iter().find(|p| p.id == preset).ok_or_else(|| format!("unknown preset {preset:?}"))?;
192    let sites: Vec<String> = p.sites.iter().map(|s| s.to_string()).collect();
193    upsert(state, agent, &sites, &["terminal".to_string()], true)
194}
195
196/// Every row, oldest first.
197pub(crate) fn list() -> Vec<Row> {
198    store().rows.clone()
199}
200
201/// Add a row, or change the powers of the one for this agent and site. The
202/// caller has checked that the person is the one asking. A changed row ends the
203/// pane grants made from it, which are made again from the new row on the
204/// agent's next call.
205pub(crate) fn upsert(state: &AppState, agent: &str, sites: &[String], powers: &[String], wildcard_ok: bool) -> Result<Row, String> {
206    let (row, existed) = {
207        let mut s = store();
208        let mut next = s.rows.clone();
209        let had: Vec<String> = next.iter().map(|r| r.id.clone()).collect();
210        let row = upsert_in(&mut next, agent, sites, powers, wildcard_ok, chrono::Utc::now().timestamp_millis())?;
211        s.commit(next)?;
212        let existed = had.contains(&row.id);
213        (row, existed)
214    };
215    // A row that already existed may have held grants with other powers.
216    if existed {
217        bypass::end_standing(state, &row.id, "you changed what it may do");
218    }
219    tracing::info!(agent = %row.agent, origins = ?row.origins, powers = ?row.powers, "[browser-standing] a standing grant was set");
220    state.broker.publish_event::<crate::backend::mps_events::BrowserGrantsChanged>(&(), vec![], 0);
221    Ok(row)
222}
223
224/// The person's "Always" on a request banner: a row for `agent` on the sites
225/// the banner named, with `powers` added to whatever it already carried (a
226/// banner that shows fewer powers than a row has never narrows the row).
227pub(crate) fn add_powers(state: &AppState, agent: &str, sites: &[String], powers: &[String]) -> Result<Row, String> {
228    let origins = agentmux_common::allowed_origins::parse_list(sites)?;
229    let mut all: Vec<String> = store()
230        .rows
231        .iter()
232        .find(|r| r.agent.eq_ignore_ascii_case(agent.trim()) && r.origins.first() == origins.first())
233        .map(|r| r.powers.clone())
234        .unwrap_or_default();
235    all.extend(powers.iter().cloned());
236    upsert(state, agent, sites, &all, true)
237}
238
239/// Change the powers of row `id`.
240pub(crate) fn set_powers(state: &AppState, id: &str, powers: &[String]) -> Result<Row, String> {
241    let powers: Vec<String> = browser_powers::names(&browser_powers::parse(Some(powers))?).iter().map(|n| n.to_string()).collect();
242    let row = {
243        let mut s = store();
244        let mut next = s.rows.clone();
245        let row = next.iter_mut().find(|r| r.id == id).ok_or_else(|| "that standing grant is gone".to_string())?;
246        row.powers = powers;
247        let row = row.clone();
248        s.commit(next)?;
249        row
250    };
251    bypass::end_standing(state, &row.id, "you changed what it may do");
252    state.broker.publish_event::<crate::backend::mps_events::BrowserGrantsChanged>(&(), vec![], 0);
253    Ok(row)
254}
255
256/// Remove row `id` and end the pane grants made from it, at once: an
257/// in-flight call ends and the strip comes down. Returns whether the row was
258/// there; an error when the file could not be written, in which case the row stays (it would be back
259/// after a restart anyway).
260pub(crate) fn revoke(state: &AppState, id: &str) -> Result<bool, String> {
261    let removed = {
262        let mut s = store();
263        let mut next = s.rows.clone();
264        next.retain(|r| r.id != id);
265        let gone = next.len() != s.rows.len();
266        if gone {
267            s.commit(next)?;
268        }
269        gone
270    };
271    if removed {
272        bypass::end_standing(state, id, "you revoked it");
273        state.broker.publish_event::<crate::backend::mps_events::BrowserGrantsChanged>(&(), vec![], 0);
274        tracing::info!(row = %id, "[browser-standing] a standing grant was revoked");
275    }
276    Ok(removed)
277}
278
279/// Panes whose standing grant the person ended with Stop. A standing row
280/// would make the grant again on the agent's next call, so Stop would end
281/// only the call in flight: until the person turns auto-approve on again or
282/// answers the agent's request, the pane's calls ask as they did before.
283fn stopped() -> std::sync::MutexGuard<'static, std::collections::HashSet<String>> {
284    static S: OnceLock<Mutex<std::collections::HashSet<String>>> = OnceLock::new();
285    S.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner())
286}
287
288/// The person pressed Stop on `pane`'s grant: if it is a standing one, hold
289/// off making it again. Returns whether it was a standing one.
290pub(crate) fn stop_by_person(state: &AppState, pane: &str) -> bool {
291    let standing = bypass::is_standing(pane);
292    if standing {
293        stopped().insert(pane.to_string());
294    }
295    bypass::end(state, pane, "the user turned it off", false, crate::server::browser_actions::How::ByUser);
296    standing
297}
298
299/// The person turned auto-approve on again, or answered the agent's request:
300/// a standing row may make `pane`'s grant again.
301pub(crate) fn resume(pane: &str) {
302    stopped().remove(pane);
303}
304
305/// The pane grant for `agent` on `pane`, made from a standing row that names
306/// the site `url` (the address the host read from the page itself). None: no
307/// row says so, or the person stopped the grant on this pane and hasn't
308/// turned it on again. A grant `agent` already holds there is not replaced.
309pub(crate) fn activate_at(state: &AppState, pane: &str, agent: &str, url: &str) -> Option<bypass::Grant> {
310    if let Some(g) = bypass::active_for(pane, agent) {
311        return Some(g);
312    }
313    if stopped().contains(pane) {
314        return None;
315    }
316    // The grant is made with the store locked: a revoke that lands after the
317    // row was read waits here, then ends the grant it finds.
318    let s = store();
319    let row = find(&s.rows, agent, url)?;
320    Some(bypass::grant_standing(state, pane, agent, row.origins.clone(), row.powers(), &row.id))
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    fn sites(v: &[&str]) -> Vec<String> {
328        v.iter().map(|s| s.to_string()).collect()
329    }
330
331    fn rows() -> Vec<Row> {
332        let mut r = Vec::new();
333        upsert_in(&mut r, "Naki-2", &sites(&["shell.cloud.google.com"]), &["terminal".to_string()], false, 1).unwrap();
334        r
335    }
336
337    #[test]
338    fn a_row_covers_its_agent_on_its_site_only() {
339        let r = rows();
340        assert_eq!(r[0].origins, vec!["https://shell.cloud.google.com"]);
341        assert_eq!(r[0].agent, "naki-2");
342        assert!(find(&r, "naki-2", "https://shell.cloud.google.com/?x=1").is_some());
343        assert!(find(&r, "NAKI-2", "https://shell.cloud.google.com/").is_some());
344        // Another agent, another site, another scheme, another port, no web origin at all.
345        assert!(find(&r, "agent1", "https://shell.cloud.google.com/").is_none());
346        assert!(find(&r, "naki-2", "https://evil.example.com/").is_none());
347        assert!(find(&r, "naki-2", "http://shell.cloud.google.com/").is_none());
348        assert!(find(&r, "naki-2", "https://shell.cloud.google.com:8443/").is_none());
349        assert!(find(&r, "naki-2", "about:blank").is_none());
350        assert!(find(&r, "naki-2", "data:text/html,hi").is_none());
351    }
352
353    #[test]
354    fn clicks_are_always_a_power_of_a_row_and_an_unknown_power_is_refused() {
355        let r = rows();
356        assert_eq!(r[0].powers, vec!["clicks", "terminal"]);
357        assert_eq!(r[0].powers(), vec![Power::Clicks, Power::Terminal]);
358        let mut v = Vec::new();
359        assert!(upsert_in(&mut v, "a", &sites(&["example.com"]), &["root".to_string()], false, 1).is_err());
360    }
361
362    #[test]
363    fn a_typed_row_names_one_site_and_only_a_preset_or_a_banner_may_use_a_wildcard() {
364        let mut v = Vec::new();
365        assert!(upsert_in(&mut v, "a", &sites(&["*.github.dev"]), &[], false, 1).is_err());
366        let row = upsert_in(&mut v, "a", &sites(&["*.github.dev"]), &[], true, 1).unwrap();
367        assert_eq!(row.origins, vec!["https://*.github.dev"]);
368        assert!(upsert_in(&mut v, "", &sites(&["example.com"]), &[], false, 1).is_err());
369        assert!(upsert_in(&mut v, "a", &sites(&["not a site"]), &[], false, 1).is_err());
370        assert!(upsert_in(&mut v, "a", &[], &[], false, 1).is_err());
371    }
372
373    #[test]
374    fn a_row_with_frames_covers_the_page_and_the_frame_but_nothing_else() {
375        let mut v = Vec::new();
376        upsert_in(&mut v, "a", &sites(&["shell.example.com", "ssh.example.com"]), &["terminal".to_string()], false, 1).unwrap();
377        assert!(find(&v, "a", "https://shell.example.com/").is_some());
378        assert!(find(&v, "a", "https://ssh.example.com/proxy").is_some());
379        assert!(find(&v, "a", "https://www.example.com/").is_none());
380    }
381
382    #[test]
383    fn setting_a_row_again_replaces_its_powers_instead_of_adding_one() {
384        let mut v = rows();
385        let first = v[0].id.clone();
386        let again = upsert_in(&mut v, "naki-2", &sites(&["https://shell.cloud.google.com"]), &[], false, 9).unwrap();
387        assert_eq!(v.len(), 1);
388        assert_eq!(again.id, first);
389        assert_eq!(again.powers, vec!["clicks"]);
390        assert_eq!(again.granted_at_ms, 1, "the day it was first granted is kept");
391    }
392
393    #[test]
394    fn every_preset_is_a_set_of_sites_a_row_accepts() {
395        let mut v = Vec::new();
396        for p in PRESETS {
397            let sites: Vec<String> = p.sites.iter().map(|s| s.to_string()).collect();
398            let row = upsert_in(&mut v, "naki-2", &sites, &["terminal".to_string()], true, 1).unwrap();
399            assert_eq!(row.origins.len(), p.sites.len(), "{}", p.id);
400            assert!(!p.note.is_empty() && !p.label.is_empty());
401        }
402    }
403
404    #[test]
405    fn the_list_is_capped() {
406        let mut v = Vec::new();
407        for i in 0..MAX_ROWS {
408            upsert_in(&mut v, "a", &sites(&[&format!("site{i}.example.com")]), &[], false, 1).unwrap();
409        }
410        assert!(upsert_in(&mut v, "a", &sites(&["one-more.example.com"]), &[], false, 1).is_err());
411    }
412
413    #[test]
414    fn a_row_the_file_could_not_record_is_not_kept() {
415        let dir = tempfile::tempdir().unwrap();
416        // A folder that cannot be made: its parent is a file.
417        let blocker = dir.path().join("blocker");
418        std::fs::write(&blocker, b"x").unwrap();
419        let mut s = Store { path: Some(blocker.join(FILE_NAME)), rows: rows() };
420        let kept = s.rows.clone();
421        let err = s.commit(Vec::new()).unwrap_err();
422        assert!(err.contains("couldn't save") && err.contains("nothing was changed"), "{err}");
423        assert_eq!(s.rows, kept, "the revoke that could not be written did not happen in memory either");
424    }
425
426    #[test]
427    fn rows_survive_a_restart_and_an_unreadable_file_grants_nothing() {
428        let dir = tempfile::tempdir().unwrap();
429        let path = dir.path().join(FILE_NAME);
430        let mut s = Store { path: Some(path.clone()), rows: Vec::new() };
431        s.commit(rows()).unwrap();
432        let reopened = Store::open(path.clone());
433        assert_eq!(reopened.rows, s.rows);
434        s.rows.clear();
435        std::fs::write(&path, b"{ not json").unwrap();
436        assert!(Store::open(path).rows.is_empty());
437    }
438
439    /// The process-wide store, with no file behind it, holding one row for `agent` on `site`.
440    fn row_in_store(agent: &str, site: &str) -> String {
441        let mut s = store();
442        s.path = None;
443        upsert_in(&mut s.rows, agent, &sites(&[site]), &["terminal".to_string()], false, 1).unwrap().id
444    }
445
446    #[tokio::test]
447    async fn a_row_that_asks_for_each_line_makes_a_grant_that_asks() {
448        let state = crate::server::tests::test_state();
449        let (agent, url, pane) = ("ask-row-agent", "https://ask-row.example.com/x", "ask-row-pane");
450        let id = {
451            let mut s = store();
452            s.path = None;
453            upsert_in(&mut s.rows, agent, &sites(&["ask-row.example.com"]), &["terminal_ask".to_string()], false, 1).unwrap().id
454        };
455        let g = activate_at(&state, pane, agent, url).unwrap();
456        assert!(g.asks_each_line() && g.allows_terminal());
457        revoke(&state, &id);
458    }
459
460    #[tokio::test]
461    async fn stop_holds_off_the_standing_grant_until_the_person_turns_it_on_again() {
462        let state = crate::server::tests::test_state();
463        let (agent, url, pane) = ("stop-test-agent", "https://stop-test.example.com/x", "stop-test-pane");
464        let id = row_in_store(agent, "stop-test.example.com");
465        assert!(activate_at(&state, pane, agent, url).is_some());
466        assert!(bypass::is_standing(pane));
467        // Stop ends it, and the agent's next call doesn't make it again.
468        assert!(stop_by_person(&state, pane));
469        assert!(bypass::active_for(pane, agent).is_none());
470        assert!(activate_at(&state, pane, agent, url).is_none());
471        // The person turns it on again (or answers the agent's request).
472        resume(pane);
473        assert!(activate_at(&state, pane, agent, url).is_some());
474        // Revoke ends the grant, and nothing makes it again.
475        assert!(revoke(&state, &id).unwrap());
476        assert!(bypass::active_for(pane, agent).is_none());
477        assert!(activate_at(&state, pane, agent, url).is_none());
478    }
479
480    #[tokio::test]
481    async fn stop_on_a_grant_the_person_made_by_hand_holds_nothing_off() {
482        let state = crate::server::tests::test_state();
483        let (agent, pane) = ("stop-hand-agent", "stop-hand-pane");
484        let id = row_in_store(agent, "stop-hand.example.com");
485        bypass::grant(&state, pane, agent, vec!["https://stop-hand.example.com".to_string()], vec![Power::Clicks], 15, crate::server::browser_actions::How::ByUser);
486        assert!(!stop_by_person(&state, pane));
487        assert!(activate_at(&state, pane, agent, "https://stop-hand.example.com/").is_some());
488        revoke(&state, &id);
489    }
490}