Skip to main content

agentmux_srv/server/
browser_allowlist.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sites an agent limited its browser pane to with
5//! `OpenBrowser({allowed_origins})`
6//! (docs/specs/SPEC_BROWSER_PANE_ALLOWED_ORIGINS_2026_10_09.md).
7//!
8//! One list per chain of panes: the pane `OpenBrowser` opened (the root) and
9//! every popup pane opened from it, or from those. Like the owner map, this
10//! is srv's own record, kept in memory and in a file across a restart
11//! (`browser_pane_records`): the block's `browser:allowed_origins`
12//! meta key mirrors it for the pane's header, and clients can't write it. The
13//! host keeps a copy of every member's list, pushed with the owned-pane set
14//! (`browser_host_sync`), and stops navigations off it.
15
16use std::collections::HashMap;
17use std::sync::{Mutex, OnceLock};
18
19use agentmux_common::allowed_origins;
20use axum::extract::State;
21use axum::http::StatusCode;
22use axum::response::IntoResponse;
23use axum::Json;
24use serde_json::{json, Value};
25
26use crate::server::ui_handlers as ui;
27use crate::server::AppState;
28
29/// Block meta key mirroring a pane's list, for its header.
30pub(crate) const ALLOWED_META_KEY: &str = "browser:allowed_origins";
31
32#[derive(Default)]
33struct Lists {
34    /// Panes a stopped navigation's report found to have no list: the host's
35    /// copy of one was behind (an early copy from the block's own meta, which
36    /// outlives srv's in-memory record across a restart). Pushed to the host
37    /// so it drops that copy; cleared when the pane is limited again or gone.
38    unlimited: std::collections::HashSet<String>,
39    /// Root pane → its chain's list (normal form, `allowed_origins::parse`).
40    lists: HashMap<String, Vec<String>>,
41    /// Every member pane, the root included → its root.
42    members: HashMap<String, String>,
43}
44
45fn lists() -> &'static Mutex<Lists> {
46    static L: OnceLock<Mutex<Lists>> = OnceLock::new();
47    L.get_or_init(Default::default)
48}
49
50fn lock() -> std::sync::MutexGuard<'static, Lists> {
51    lists().lock().unwrap_or_else(|p| p.into_inner())
52}
53
54/// Limit `root` (a pane `OpenBrowser` just opened) to `list`.
55pub(crate) fn set(root: &str, list: Vec<String>) {
56    let mut l = lock();
57    l.unlimited.remove(root);
58    l.lists.insert(root.to_string(), list);
59    l.members.insert(root.to_string(), root.to_string());
60    drop(l);
61    crate::server::browser_owner::changed().notify_one();
62}
63
64/// `pane`, a popup pane `opener` just opened, joins `opener`'s chain, if it
65/// has a list. Returns the list it now shares.
66pub(crate) fn join(pane: &str, opener: &str) -> Option<Vec<String>> {
67    let mut l = lock();
68    let root = l.members.get(opener)?.clone();
69    let list = l.lists.get(&root)?.clone();
70    l.members.insert(pane.to_string(), root);
71    drop(l);
72    crate::server::browser_owner::changed().notify_one();
73    Some(list)
74}
75
76/// Put back `pane`'s place in the chain of `root` and the chain's `list`, as `browser_pane_records`
77/// kept them across a restart. A chain that is already there keeps its list.
78pub(crate) fn restore(pane: &str, root: &str, list: Vec<String>) {
79    let mut l = lock();
80    l.lists.entry(root.to_string()).or_insert(list);
81    l.members.insert(pane.to_string(), root.to_string());
82    drop(l);
83    crate::server::browser_owner::changed().notify_one();
84}
85
86/// Every limited pane's chain root, and each chain's list, for `browser_pane_records`.
87pub(crate) fn chains() -> (std::collections::BTreeMap<String, String>, std::collections::BTreeMap<String, Vec<String>>) {
88    let l = lock();
89    (
90        l.members.iter().map(|(p, r)| (p.clone(), r.clone())).collect(),
91        l.lists.iter().map(|(r, list)| (r.clone(), list.clone())).collect(),
92    )
93}
94
95/// `pane`'s list, if its chain has one.
96pub(crate) fn list_for(pane: &str) -> Option<Vec<String>> {
97    let l = lock();
98    let root = l.members.get(pane)?;
99    l.lists.get(root).cloned()
100}
101
102/// Add `origin` to `pane`'s chain's list: the person allowed it. Returns the
103/// list after, and the chain's members, whose header shows it.
104pub(crate) fn allow(pane: &str, origin: &str) -> Option<(Vec<String>, Vec<String>)> {
105    let mut l = lock();
106    let root = l.members.get(pane)?.clone();
107    let list = l.lists.get_mut(&root)?;
108    if !list.iter().any(|o| o == origin) {
109        list.push(origin.to_string());
110    }
111    let list = list.clone();
112    let members = l.members.iter().filter(|(_, r)| **r == root).map(|(m, _)| m.clone()).collect();
113    drop(l);
114    crate::server::browser_owner::changed().notify_one();
115    Some((list, members))
116}
117
118/// `pane` was closed or taken over: it leaves its chain. The others keep the
119/// list, even when `pane` was the root: a popup pane can outlive its opener
120/// and still be the agent's, and must not lose its limit with it. The list
121/// goes when its last pane does. Returns whether `pane` had a list.
122pub(crate) fn drop_pane(pane: &str) -> bool {
123    let mut l = lock();
124    l.unlimited.remove(pane);
125    let Some(root) = l.members.remove(pane) else { return false };
126    if !l.members.values().any(|r| *r == root) {
127        l.lists.remove(&root);
128    }
129    drop(l);
130    crate::server::browser_owner::changed().notify_one();
131    true
132}
133
134/// `pane` leaves its chain for good, and any popup panes still in it keep the list it had: they stay one agent's, and a
135/// new list for `pane` (another agent took it over, `take_control`) must not change what they may reach. [`drop_pane`]
136/// leaves the list under the root's own name, which a new [`set`] on that pane would overwrite.
137pub(crate) fn leave_chain(pane: &str) {
138    let mut l = lock();
139    l.unlimited.remove(pane);
140    let old_root = l.members.remove(pane);
141    let rest: Vec<String> = match &old_root {
142        Some(root) => l.members.iter().filter(|(_, r)| *r == root).map(|(m, _)| m.clone()).collect(),
143        None => l.members.iter().filter(|(_, r)| *r == pane).map(|(m, _)| m.clone()).collect(),
144    };
145    let root = old_root.unwrap_or_else(|| pane.to_string());
146    if rest.is_empty() {
147        l.lists.remove(&root);
148    } else if root == pane {
149        // The chain is named after the pane: rename it, so the pane can start a list of its own.
150        if let Some(list) = l.lists.remove(&root) {
151            let renamed = format!("{pane}:{}", uuid::Uuid::new_v4());
152            for m in rest {
153                l.members.insert(m, renamed.clone());
154            }
155            l.lists.insert(renamed, list);
156        }
157    }
158    drop(l);
159    crate::server::browser_owner::changed().notify_one();
160}
161
162/// Record that `pane` has no list although the host holds one for it.
163fn confirm_unlimited(pane: &str) {
164    lock().unlimited.insert(pane.to_string());
165}
166
167/// The panes srv has found the host holds a stale list for.
168pub(crate) fn confirmed_unlimited() -> Vec<String> {
169    lock().unlimited.iter().cloned().collect()
170}
171
172/// Every member pane's list, for the host.
173pub(crate) fn snapshot() -> HashMap<String, Vec<String>> {
174    let l = lock();
175    l.members
176        .iter()
177        .filter_map(|(m, r)| l.lists.get(r).map(|list| (m.clone(), list.clone())))
178        .collect()
179}
180
181/// Write `list` (or nothing) to each of `panes`' headers.
182pub(crate) fn publish(state: &AppState, panes: &[String], list: Option<&[String]>) {
183    let value = list.map(|l| json!(l)).unwrap_or(Value::Null);
184    for pane in panes {
185        let mut meta = crate::backend::obj::MetaMapType::new();
186        meta.insert(ALLOWED_META_KEY.to_string(), value.clone());
187        if let Err(e) = crate::server::http_shell::broadcast_meta_update(state, pane, &meta) {
188            tracing::debug!(pane = %pane, error = %e, "[browser-allowlist] pane header not updated");
189        }
190    }
191}
192
193/// Check `OpenBrowser`'s `allowed_origins`: `None` when not given, the list
194/// in its normal form when it is, or why it can't be used.
195pub(crate) fn list_for_open(entries: Option<&[String]>, url: &str) -> Result<Option<Vec<String>>, String> {
196    let Some(entries) = entries else { return Ok(None) };
197    let list = allowed_origins::parse_list(entries).map_err(|e| format!("allowed_origins: {e}"))?;
198    if list.is_empty() {
199        return Err("allowed_origins is empty: leave it out, or list the sites the pane may go to".to_string());
200    }
201    if !allowed_origins::allows(&list, url) {
202        return Err(format!("url {url:?} isn't on allowed_origins ({})", list.join(", ")));
203    }
204    Ok(Some(list))
205}
206
207/// Mirror a new pane's list (if any) into the meta it's created with.
208pub(crate) fn mirror(meta: &mut crate::backend::obj::MetaMapType, list: Option<&[String]>) {
209    if let Some(list) = list {
210        meta.insert(ALLOWED_META_KEY.to_string(), json!(list));
211    }
212}
213
214/// Limit `pane`, which `OpenBrowser` just opened, to `list` if one was given,
215/// and send it to the host at once, not on the next sync: the host must have
216/// it before the pane's first navigation can leave it.
217pub(crate) async fn limit_new_pane(state: &AppState, pane: &str, list: Option<Vec<String>>) {
218    if let Some(list) = list {
219        set(pane, list);
220        crate::server::browser_host_sync::push(state).await;
221    }
222}
223
224/// Why a popup pane to `url` from `opener` isn't opened, if it isn't: the
225/// host asks before offering one off the opener's list, and this checks again
226/// from srv's own record.
227pub(crate) fn refuse_popup(opener: &str, url: &str) -> Option<&'static str> {
228    list_for(opener)
229        .is_some_and(|l| !allowed_origins::allows(&l, url))
230        .then_some("it isn't on the sites the pane that opened it is limited to")
231}
232
233/// `pane`, a popup pane that `join`ed its opener's chain (`list`) as soon as
234/// it opened, once its ownership is settled: with an owner it shares the
235/// chain's limit, in its header and on the host; with none (the opener was
236/// taken over meanwhile) it leaves the chain. The host push waits until here,
237/// so nothing yields between opening the pane and settling who owns it.
238pub(crate) async fn settle_popup_pane(state: &AppState, pane: &str, list: Option<Vec<String>>, owned: bool) {
239    let Some(list) = list else { return };
240    if owned {
241        publish(state, &[pane.to_string()], Some(&list));
242    } else {
243        drop_pane(pane);
244        publish(state, &[pane.to_string()], None);
245    }
246    crate::server::browser_host_sync::push(state).await;
247}
248
249/// Why an agent's own `BrowserNavigate` of `pane` to `url` is refused, if it
250/// is: the pane is limited to some sites and `url` isn't on them (§3).
251pub(crate) fn refuse_agent_navigation(pane: &str, url: &str) -> Option<String> {
252    let list = list_for(pane)?;
253    (!allowed_origins::allows(&list, url)).then(|| {
254        format!(
255            "{url:?} isn't on the sites this pane is limited to ({}): open another pane with Browser's open action \
256             for it, or ask the user",
257            list.join(", ")
258        )
259    })
260}
261
262/// `POST /api/v1/host/browser_navigation` — the host stopped a navigation off
263/// a pane's site list (allowed-origins spec §4). Body `{pane, target, url,
264/// kind}`: `pane` is the pane the list belongs to, `target` the pane or popup
265/// window that was navigating, `kind` `navigate` (replayed on Allow) or
266/// `popup` (not: the person or agent clicks again). Only the host calls it.
267/// Answers at once, with how the attempt was settled (`settled`); a question
268/// runs on its own. The host shows its own notice for anything it doesn't
269/// recognise there, so a stopped navigation never ends in a blank pane.
270pub(crate) async fn handle_host_browser_navigation(
271    State(state): State<AppState>,
272    headers: axum::http::HeaderMap,
273    Json(body): Json<serde_json::Value>,
274) -> impl IntoResponse {
275    if !ui::from_host(&state, &headers).await {
276        return ui::err_response(StatusCode::FORBIDDEN, "only the AgentMux host can report a navigation".to_string());
277    }
278    let s = |k: &str| body.get(k).and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
279    let stopped = Stopped { pane: s("pane"), target: s("target"), url: s("url"), kind: s("kind") };
280    let settled = settle_stopped_navigation(&state, stopped.clone(), ASK_TIMEOUT).await;
281    let (outcome, reason) = settled.describe();
282    tracing::info!(
283        pane = %stopped.pane, target = %stopped.target, kind = %stopped.kind, outcome, reason = %reason,
284        "[browser-allowlist] stopped navigation"
285    );
286    let data = json!({ "asked": settled == Settled::Asking, "settled": outcome, "reason": reason });
287    (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
288}
289
290/// A navigation the host stopped: in `pane`'s chain, by `target`, to `url`,
291/// a `navigate` or a `popup`.
292#[derive(Clone)]
293struct Stopped {
294    pane: String,
295    target: String,
296    url: String,
297    kind: String,
298}
299
300/// How a stopped navigation ended (RCA §7.1). Each one loads, asks, or
301/// shows why: none leaves the pane where the cancel left it.
302#[derive(Debug, PartialEq)]
303enum Settled {
304    /// It may go after all, and is loaded again.
305    Replayed(&'static str),
306    /// The person is being asked.
307    Asking,
308    /// A question about another address is up: that banner speaks for this.
309    Busy,
310    /// Nobody is asked; the pane's notice says why it stopped.
311    Notice(String),
312    /// Not even a notice could be shown: the host shows its own.
313    Unshown(String),
314}
315
316impl Settled {
317    /// The outcome's name, for the host and the log, and why.
318    fn describe(&self) -> (&'static str, String) {
319        match self {
320            Settled::Replayed(why) => ("replayed", why.to_string()),
321            Settled::Asking => ("asking", String::new()),
322            Settled::Busy => ("busy", "the pane is already asking about another address".to_string()),
323            Settled::Notice(why) => ("notice", why.clone()),
324            Settled::Unshown(why) => ("unshown", why.clone()),
325        }
326    }
327}
328
329/// Where a stopped navigation goes, decided in one place, so every branch
330/// replays, asks, or shows a notice. A question waits up to `timeout`.
331async fn settle_stopped_navigation(state: &AppState, stopped: Stopped, timeout: std::time::Duration) -> Settled {
332    use crate::server::browser_attention::{self, AskError, Kind};
333    let list = list_for(&stopped.pane).or_else(|| opener_list(state, &stopped.pane));
334    let Some(list) = list else {
335        // Taken over or closed since, or srv restarted and lost its record
336        // while the block still carries the list: the host's copy was behind.
337        // The push says so, so the host drops its copy before the replay, and
338        // the header's stale list goes with it.
339        confirm_unlimited(&stopped.pane);
340        publish(state, std::slice::from_ref(&stopped.pane), None);
341        push_then_replay(state, &stopped).await;
342        return Settled::Replayed("the pane isn't limited to any sites");
343    };
344    if allowed_origins::allows(&list, &stopped.url) {
345        // Allowed already (the host's copy was behind).
346        push_then_replay(state, &stopped).await;
347        return Settled::Replayed("it is on the pane's sites");
348    }
349    let is_frame = stopped.kind == "frame";
350    let Some(origin) = allowed_origins::target_origin(&stopped.url) else {
351        // A frame's site is a question about what the agent may act on; nothing
352        // was stopped, so there is no navigation notice to show.
353        if is_frame {
354            return Settled::Notice("it isn't a web address".to_string());
355        }
356        return show_notice(state, &stopped, None, "It isn't a web address.");
357    };
358    if is_frame {
359        return ask_about_frame(state, &stopped, &list, &origin);
360    }
361    let agent = crate::server::browser_owner::owner_of(&stopped.pane).unwrap_or_default();
362    let payload = json!({
363        "url": stopped.url, "origin": origin, "window": window_of(&stopped), "popup": stopped.kind == "popup",
364    });
365    // A hand-off or approval up doesn't stop this: the question goes over it.
366    match browser_attention::raise(state, &stopped.pane, &agent, Kind::Navigation, payload) {
367        Ok(raised) => {
368            let st = state.clone();
369            tokio::spawn(async move {
370                let (answer, waiting) = raised.answer(Some(timeout)).await;
371                let outcome = match answer {
372                    browser_attention::Answer::Yes | browser_attention::Answer::YesAlways | browser_attention::Answer::YesAsking => allow_and_load(&st, &stopped, &origin).await,
373                    // Taken over: it isn't limited any more, so it goes on.
374                    _ if list_for(&stopped.pane).is_none() => {
375                        let open = st.mstore.get::<crate::backend::obj::Block>(&stopped.pane).ok().flatten().is_some();
376                        if !open {
377                            "dropped: the pane was closed".to_string()
378                        } else {
379                            push_then_replay(&st, &stopped).await;
380                            "replayed: the pane isn't limited any more".to_string()
381                        }
382                    }
383                    // Shown before the question comes down, so the banner goes
384                    // straight to it.
385                    browser_attention::Answer::Cancelled => notice_outcome(&st, &stopped, &origin, "You blocked it."),
386                    browser_attention::Answer::TimedOut => {
387                        notice_outcome(&st, &stopped, &origin, "Nobody answered within 10 minutes.")
388                    }
389                };
390                tracing::info!(pane = %stopped.pane, origin = %origin, answer = ?answer, outcome = %outcome, "[browser-allowlist] question answered");
391                // The pane stays locked until the load is on its way. Then the
392                // host hears the question is over, and reports this pane's
393                // attempts again.
394                drop(waiting);
395                crate::server::browser_host_sync::push(&st).await;
396            });
397            Settled::Asking
398        }
399        Err(AskError::Busy { .. }) => Settled::Busy,
400        Err(e @ AskError::NotShown(_)) => {
401            tracing::warn!(pane = %stopped.pane, error = %e, "[browser-allowlist] couldn't ask");
402            show_notice(state, &stopped, Some(&origin), "AgentMux couldn't ask you about it.")
403        }
404    }
405}
406
407/// The site each pane's frame notice is showing now, if it has one.
408fn frame_notices() -> &'static Mutex<HashMap<String, String>> {
409    static N: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
410    N.get_or_init(Default::default)
411}
412
413/// What taking a pane's frame-notice slot came to.
414#[derive(Debug, PartialEq, Eq)]
415enum FrameSlot {
416    /// The slot was free and now holds this site.
417    Reserved,
418    /// This site's notice is up already.
419    Showing,
420    /// Another site's notice is up.
421    Busy,
422}
423
424/// Take `pane`'s slot for `origin`, in the same step as the check.
425fn reserve_frame_slot(map: &mut HashMap<String, String>, pane: &str, origin: &str) -> FrameSlot {
426    match map.get(pane) {
427        Some(up) if up == origin => FrameSlot::Showing,
428        Some(_) => FrameSlot::Busy,
429        None => {
430            map.insert(pane.to_string(), origin.to_string());
431            FrameSlot::Reserved
432        }
433    }
434}
435
436/// Free `pane`'s slot, only if it still holds `origin`: a notice that was
437/// replaced mustn't free the slot of the one that replaced it.
438fn release_frame_slot(map: &mut HashMap<String, String>, pane: &str, origin: &str) {
439    if map.get(pane).is_some_and(|up| up == origin) {
440        map.remove(pane);
441    }
442}
443
444/// A snapshot found a frame from `origin`, a site off the pane's `list`
445/// (forms-in-frames spec §5.3): tell the person in the pane's banner, with
446/// Allow. It is a notice, not a question about a navigation, because nothing
447/// is stopped and the agent's tools on the pane must not pause for an
448/// incidental frame; the frame stays unactable until Allow, and the agent
449/// takes a new snapshot after. Allow adds the site and loads nothing.
450fn ask_about_frame(state: &AppState, stopped: &Stopped, list: &[String], origin: &str) -> Settled {
451    use crate::server::browser_attention::{self, Answer, AskError, Kind};
452    // One frame notice per pane at a time: a second site's would replace the
453    // first's, which the host then counts as asked and never raises again. Busy
454    // makes the host forget the second site until a later snapshot. The slot is
455    // taken before the notice is raised, so two reports at once can't both pass.
456    match reserve_frame_slot(&mut frame_notices().lock().unwrap_or_else(|p| p.into_inner()), &stopped.pane, origin) {
457        FrameSlot::Reserved => {}
458        FrameSlot::Showing => return Settled::Notice("it is being shown already".to_string()),
459        FrameSlot::Busy => return Settled::Busy,
460    }
461    let payload = json!({
462        "url": origin, "origin": origin, "sites": list, "why": "", "allow": true, "frame": true, "popup": false, "window": null,
463    });
464    match browser_attention::raise(state, &stopped.pane, "", Kind::Notice, payload) {
465        Ok(raised) => {
466            let (st, stopped, origin) = (state.clone(), stopped.clone(), origin.to_string());
467            tokio::spawn(async move {
468                // Dismissed, replaced by another banner or the pane closed all read as Cancelled.
469                let (answer, waiting) = raised.answer(None).await;
470                release_frame_slot(&mut frame_notices().lock().unwrap_or_else(|p| p.into_inner()), &stopped.pane, &origin);
471                if matches!(answer, Answer::Yes | Answer::YesAlways | Answer::YesAsking) {
472                    let outcome = allow_and_load(&st, &stopped, &origin).await;
473                    tracing::info!(pane = %stopped.pane, origin = %origin, outcome = %outcome, "[browser-allowlist] a frame's site allowed from the banner");
474                }
475                drop(waiting);
476            });
477            Settled::Notice("the person is told about the frame's site; the agent isn't paused".to_string())
478        }
479        Err(e) => {
480            release_frame_slot(&mut frame_notices().lock().unwrap_or_else(|p| p.into_inner()), &stopped.pane, origin);
481            if matches!(e, AskError::Busy { .. }) {
482                return Settled::Busy;
483            }
484            tracing::warn!(pane = %stopped.pane, error = %e, "[browser-allowlist] couldn't tell the person about a frame's site");
485            Settled::Unshown(e.to_string())
486        }
487    }
488}
489
490/// How long the person has to answer a question about a navigation.
491const ASK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10 * 60);
492
493/// The popup window `stopped` was in, by its address, if it was in one.
494fn window_of(stopped: &Stopped) -> Option<String> {
495    crate::server::browser_popup::is_window_id(&stopped.target)
496        .then(|| crate::server::browser_popup::window(&stopped.target).map(|w| w.url))
497        .flatten()
498}
499
500/// The log line's outcome for a notice shown after a question.
501fn notice_outcome(state: &AppState, stopped: &Stopped, origin: &str, why: &str) -> String {
502    let (outcome, why) = show_notice(state, stopped, Some(origin), why).describe();
503    format!("{outcome}: {why}")
504}
505
506/// Show in the pane why `stopped` didn't load (RCA §6.2), with Back, and
507/// Allow while its site (`origin`) can still be added. Allow adds it and
508/// loads the address; Back and Dismiss only take the notice down.
509fn show_notice(state: &AppState, stopped: &Stopped, origin: Option<&str>, why: &str) -> Settled {
510    use crate::server::browser_attention::{self, Answer, Kind};
511    let sites = list_for(&stopped.pane).or_else(|| opener_list(state, &stopped.pane)).unwrap_or_default();
512    let allow = origin.filter(|_| !sites.is_empty()).map(str::to_string);
513    let payload = json!({
514        "url": stopped.url, "origin": origin.unwrap_or(""), "sites": sites, "why": why, "allow": allow.is_some(),
515        "popup": stopped.kind == "popup", "window": window_of(stopped),
516    });
517    match browser_attention::raise(state, &stopped.pane, "", Kind::Notice, payload) {
518        Ok(raised) => {
519            let (st, stopped) = (state.clone(), stopped.clone());
520            tokio::spawn(async move {
521                let (answer, waiting) = raised.answer(None).await;
522                if let (Answer::Yes | Answer::YesAlways | Answer::YesAsking, Some(origin)) = (answer, allow) {
523                    let outcome = allow_and_load(&st, &stopped, &origin).await;
524                    tracing::info!(pane = %stopped.pane, origin = %origin, outcome = %outcome, "[browser-allowlist] allowed from the notice");
525                }
526                drop(waiting);
527            });
528            Settled::Notice(why.to_string())
529        }
530        Err(e) => {
531            tracing::warn!(pane = %stopped.pane, error = %e, "[browser-allowlist] couldn't show why a navigation stopped");
532            Settled::Unshown(format!("{why} ({e})"))
533        }
534    }
535}
536
537/// The person allowed `origin`: add it to the chain's list, show the longer
538/// list, and load the stopped address.
539async fn allow_and_load(state: &AppState, stopped: &Stopped, origin: &str) -> String {
540    match allow(&stopped.pane, origin) {
541        Some((list, members)) => {
542            publish(state, &members, Some(&list));
543            push_then_replay(state, stopped).await;
544            "allowed by the user".to_string()
545        }
546        // Taken over or closed meanwhile: no list is left to add to.
547        None => {
548            push_then_replay(state, stopped).await;
549            "replayed: the pane isn't limited any more".to_string()
550        }
551    }
552}
553
554/// Send the host the current lists, then load what it stopped, if it was a
555/// navigation (a popup is clicked again).
556async fn push_then_replay(state: &AppState, stopped: &Stopped) {
557    crate::server::browser_host_sync::push(state).await;
558    if stopped.kind == "navigate" {
559        replay_navigation(state, &stopped.target, &stopped.url).await;
560    }
561}
562
563/// The site list of the pane `pane` was opened from as a popup, from srv's
564/// own records (`browser:popup_of`, which only srv writes). Covers the moment
565/// between a popup pane opening and joining its chain: a navigation the host
566/// stopped then is still asked about, not replayed.
567fn opener_list(state: &AppState, pane: &str) -> Option<Vec<String>> {
568    let block = state.mstore.get::<crate::backend::obj::Block>(pane).ok().flatten()?;
569    let opener = block.meta.get(crate::server::browser_popup::POPUP_OF_META_KEY)?.as_str()?;
570    list_for(opener)
571}
572
573/// Load `url` in `target` (a pane or popup window), as the navigation the
574/// host stopped would have. A plain load: a form's data isn't sent again.
575async fn replay_navigation(state: &AppState, target: &str, url: &str) {
576    let Ok(host) = ui::get_host_ipc(state).await else { return };
577    if ui::proxy_ack(state, &host, "navigate", json!({ "block_id": target, "url": url })).await.is_err() {
578        tracing::warn!(target = %target, "[browser-allowlist] couldn't load the allowed address");
579    }
580}
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585
586    /// A pane that leaves its chain takes nothing with it, and a new list for it changes no popup of the old chain.
587    #[test]
588    fn a_pane_that_leaves_its_chain_can_start_a_list_without_changing_the_popups() {
589        let (a, b) = (vec!["https://a.example".to_string()], vec!["https://b.example".to_string(), "https://c.example".to_string()]);
590        set("chain-root-1", a.clone());
591        join("chain-popup-1", "chain-root-1").unwrap();
592        leave_chain("chain-root-1");
593        assert_eq!(list_for("chain-root-1"), None, "the pane itself is out");
594        assert_eq!(list_for("chain-popup-1"), Some(a.clone()), "the popup keeps the list");
595        set("chain-root-1", b.clone());
596        assert_eq!(list_for("chain-root-1"), Some(b), "the pane has its new list");
597        assert_eq!(list_for("chain-popup-1"), Some(a.clone()), "the popup's is not widened");
598
599        // A popup leaves: the chain stays; the last one out takes the list with it.
600        set("chain-root-2", a.clone());
601        join("chain-popup-2", "chain-root-2").unwrap();
602        leave_chain("chain-popup-2");
603        assert_eq!(list_for("chain-popup-2"), None);
604        assert_eq!(list_for("chain-root-2"), Some(a));
605        leave_chain("chain-root-2");
606        assert_eq!(list_for("chain-root-2"), None);
607        assert!(!lock().lists.contains_key("chain-root-2"), "no list left behind");
608        leave_chain("chain-never-seen");
609        for p in ["chain-root-1", "chain-popup-1"] {
610            drop_pane(p);
611        }
612    }
613
614    #[test]
615    fn a_pane_found_unlimited_is_pushed_until_it_is_limited_again_or_gone() {
616        confirm_unlimited("unlimited-test-a");
617        confirm_unlimited("unlimited-test-b");
618        assert!(confirmed_unlimited().contains(&"unlimited-test-a".to_string()));
619        set("unlimited-test-a", vec!["https://example.com".to_string()]);
620        assert!(!confirmed_unlimited().contains(&"unlimited-test-a".to_string()));
621        drop_pane("unlimited-test-b");
622        assert!(!confirmed_unlimited().contains(&"unlimited-test-b".to_string()));
623        drop_pane("unlimited-test-a");
624    }
625
626    // RCA §6.2: a question about a stopped navigation that nobody answers
627    // ends in a notice saying so, not in a blank pane.
628    #[tokio::test]
629    async fn a_question_nobody_answers_ends_in_a_notice() {
630        use crate::server::browser_attention::tests::{banner, browser_block};
631        let state = crate::server::tests::test_state();
632        let pane = uuid::Uuid::new_v4().to_string();
633        browser_block(&state, &pane);
634        set(&pane, vec!["https://github.com".into()]);
635        let stopped = Stopped {
636            pane: pane.clone(),
637            target: pane.clone(),
638            url: "https://accounts.google.com/o/oauth2".into(),
639            kind: "navigate".into(),
640        };
641        let settled = settle_stopped_navigation(&state, stopped, std::time::Duration::from_millis(100)).await;
642        assert_eq!(settled, Settled::Asking);
643        assert_eq!(banner(&state, &pane)["kind"], "navigation");
644        let mut shown = Value::Null;
645        for _ in 0..200 {
646            shown = banner(&state, &pane);
647            if shown["kind"] == "notice" {
648                break;
649            }
650            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
651        }
652        assert_eq!(shown["kind"], "notice", "{shown}");
653        assert_eq!(shown["why"], "Nobody answered within 10 minutes.");
654        assert_eq!(shown["origin"], "https://accounts.google.com");
655        assert_eq!(shown["allow"], true);
656        // The question is gone; only the notice, which holds nothing, is left.
657        for _ in 0..200 {
658            if crate::server::browser_attention::waiting_on_user(&pane).is_none() {
659                break;
660            }
661            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
662        }
663        assert_eq!(crate::server::browser_attention::waiting_on_user(&pane), None);
664        assert_eq!(banner(&state, &pane)["kind"], "notice");
665        crate::server::browser_attention::cancel_for(&pane);
666        drop_pane(&pane);
667    }
668
669    #[test]
670    fn a_chain_shares_one_list_and_keeps_it_past_its_root() {
671        set("al-root", vec!["https://a.example".into()]);
672        assert_eq!(join("al-popup", "al-root").unwrap(), vec!["https://a.example"]);
673        assert_eq!(join("al-popup2", "al-popup").unwrap(), vec!["https://a.example"]);
674        // Allowing on any member adds to the whole chain.
675        let (list, mut members) = allow("al-popup2", "https://b.example").unwrap();
676        members.sort();
677        assert_eq!(list, vec!["https://a.example", "https://b.example"]);
678        assert_eq!(members, vec!["al-popup", "al-popup2", "al-root"]);
679        assert_eq!(list_for("al-root").unwrap().len(), 2);
680        // A member leaving keeps the rest.
681        assert!(drop_pane("al-popup"));
682        assert!(list_for("al-popup").is_none() && list_for("al-popup2").is_some());
683        // The root leaving too: a popup pane that outlives it stays limited.
684        assert!(drop_pane("al-root"));
685        assert!(list_for("al-root").is_none());
686        assert_eq!(list_for("al-popup2").unwrap().len(), 2);
687        // A popup of that popup still joins the same list.
688        assert_eq!(join("al-popup3", "al-popup2").unwrap().len(), 2);
689        // The list goes with its last pane.
690        assert!(drop_pane("al-popup2") && drop_pane("al-popup3"));
691        assert!(!snapshot().keys().any(|k| k.starts_with("al-")));
692        assert!(!lock().lists.contains_key("al-root"));
693    }
694
695    #[test]
696    fn a_frame_notice_slot_is_taken_with_the_check_and_freed_only_by_its_owner() {
697        let mut map = HashMap::new();
698        assert_eq!(reserve_frame_slot(&mut map, "p", "https://a.example"), FrameSlot::Reserved);
699        assert_eq!(reserve_frame_slot(&mut map, "p", "https://a.example"), FrameSlot::Showing);
700        assert_eq!(reserve_frame_slot(&mut map, "p", "https://b.example"), FrameSlot::Busy, "a second site finds the slot taken");
701        assert_eq!(reserve_frame_slot(&mut map, "q", "https://b.example"), FrameSlot::Reserved, "another pane has its own slot");
702        // A notice that was replaced frees nothing of the one that took over.
703        release_frame_slot(&mut map, "p", "https://b.example");
704        assert_eq!(map.get("p").map(String::as_str), Some("https://a.example"));
705        release_frame_slot(&mut map, "p", "https://a.example");
706        assert!(!map.contains_key("p"));
707        assert_eq!(reserve_frame_slot(&mut map, "p", "https://b.example"), FrameSlot::Reserved, "free again");
708        release_frame_slot(&mut map, "never", "https://a.example");
709    }
710
711    #[test]
712    fn a_pane_without_a_list_has_nothing_to_join_or_allow() {
713        assert!(join("al-x-popup", "al-x-unlisted").is_none());
714        assert!(allow("al-x-unlisted", "https://b.example").is_none());
715        assert!(!drop_pane("al-x-unlisted"));
716    }
717
718    #[test]
719    fn the_snapshot_lists_every_member() {
720        set("als-root", vec!["https://a.example".into()]);
721        join("als-popup", "als-root");
722        let snap = snapshot();
723        assert_eq!(snap.get("als-root"), Some(&vec!["https://a.example".to_string()]));
724        assert_eq!(snap.get("als-popup"), Some(&vec!["https://a.example".to_string()]));
725        drop_pane("als-root");
726        drop_pane("als-popup");
727    }
728}