Skip to main content

agentmux_srv_core/backend/lan/
firewall.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Would the OS firewall let LAN peers reach us? Pure rule logic, no OS calls.
5//!
6//! SPEC_LAN_FIREWALL_SETUP_2026_10_01.md 4.2 and 4.3. On 2026-09-30 narko had LAN
7//! enabled, started its listeners, registered its mDNS service, logged no
8//! warning, and never saw a peer, because Windows Defender Firewall had no
9//! inbound allow rule for the active Private profile (and 606 stale per-path
10//! rules, none of them for the running binary). Nothing in AgentMux could say so.
11//!
12//! This module decides, from a snapshot of the firewall rules and the adapters'
13//! network categories, whether each interface is covered, and what the status
14//! bar should say. Reading the snapshot is OS-specific and lives elsewhere
15//! (`lan/firewall_windows.rs`); keeping the decision pure means the cases that
16//! actually bit us are unit tests that run on every platform.
17//!
18//! Windows semantics encoded here:
19//! - Inbound traffic is blocked unless a matching enabled **allow** rule exists,
20//!   and an enabled matching **block** rule beats any allow.
21//! - A rule applies per network **profile** (Domain, Private, Public), and each
22//!   adapter's connection has its own category.
23//! - A rule naming a program matches that exact path. The sidecar's file name
24//!   embeds its version (`agentmux-srv-0.59.1-windows.x64.exe`) and portable and
25//!   dev builds sit at a new path every time, so a per-program rule stops
26//!   matching on every update (spec R7). A **port** rule does not.
27
28// Only Windows reads its firewall so far (`lan/firewall_windows.rs`; macOS and
29// Linux are later PRs of the spec): elsewhere only the tests build rules.
30#![cfg_attr(not(windows), allow(dead_code))]
31
32use std::net::Ipv4Addr;
33
34/// `NET_FW_PROFILE2_*` bits.
35pub const PROFILE_DOMAIN: u32 = 1;
36pub const PROFILE_PRIVATE: u32 = 2;
37pub const PROFILE_PUBLIC: u32 = 4;
38
39/// A network's category, as `INetworkListManager` reports it.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum Category {
42    Public,
43    Private,
44    Domain,
45}
46
47impl Category {
48    pub fn bit(self) -> u32 {
49        match self {
50            Category::Domain => PROFILE_DOMAIN,
51            Category::Private => PROFILE_PRIVATE,
52            Category::Public => PROFILE_PUBLIC,
53        }
54    }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Proto {
59    Tcp,
60    Udp,
61    Any,
62    /// ICMP and anything else: never covers a TCP or UDP need.
63    Other,
64}
65
66impl Proto {
67    /// `NET_FW_IP_PROTOCOL_*`: TCP 6, UDP 17, ANY 256.
68    pub fn from_win(n: i32) -> Proto {
69        match n {
70            6 => Proto::Tcp,
71            17 => Proto::Udp,
72            256 => Proto::Any,
73            _ => Proto::Other,
74        }
75    }
76
77    fn covers(self, want: Proto) -> bool {
78        match self {
79            Proto::Any => matches!(want, Proto::Tcp | Proto::Udp),
80            Proto::Other => false,
81            p => p == want,
82        }
83    }
84}
85
86/// A rule's `LocalPorts`. Anything we cannot read exactly is `Unparseable` and
87/// matches nothing: claiming coverage we cannot prove is the worse error.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub enum PortSpec {
90    Any,
91    Ranges(Vec<(u16, u16)>),
92    Unparseable,
93}
94
95impl PortSpec {
96    /// `""` and `"*"` are any port; otherwise a comma list of ports and
97    /// `low-high` ranges. Windows also allows keywords (`RPC`, `IPHTTPS`,
98    /// `Teredo`, ...): those are `Unparseable`.
99    pub fn parse(spec: &str) -> PortSpec {
100        let spec = spec.trim();
101        if spec.is_empty() || spec == "*" {
102            return PortSpec::Any;
103        }
104        let mut ranges = Vec::new();
105        for part in spec.split(',') {
106            let part = part.trim();
107            let (lo, hi) = match part.split_once('-') {
108                Some((a, b)) => (a.trim().parse::<u16>(), b.trim().parse::<u16>()),
109                None => {
110                    let p = part.parse::<u16>();
111                    (p.clone(), p)
112                }
113            };
114            match (lo, hi) {
115                (Ok(lo), Ok(hi)) if lo <= hi => ranges.push((lo, hi)),
116                _ => return PortSpec::Unparseable,
117            }
118        }
119        PortSpec::Ranges(ranges)
120    }
121
122    pub fn contains(&self, port: u16) -> bool {
123        match self {
124            PortSpec::Any => true,
125            PortSpec::Ranges(r) => r.iter().any(|&(lo, hi)| (lo..=hi).contains(&port)),
126            PortSpec::Unparseable => false,
127        }
128    }
129}
130
131/// A rule's `RemoteAddresses`, reduced to the one question that matters here:
132/// does it reach LAN peers in general?
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum Remote {
135    /// `*` or empty.
136    Any,
137    /// `LocalSubnet`: the peers' subnet. Covers a LAN peer.
138    LocalSubnet,
139    /// A specific list, `Internet`, `DNS`, ...: does not cover peers in general.
140    Other,
141}
142
143impl Remote {
144    pub fn parse(spec: &str) -> Remote {
145        let spec = spec.trim();
146        if spec.is_empty() || spec == "*" {
147            Remote::Any
148        } else if spec.eq_ignore_ascii_case("LocalSubnet") {
149            Remote::LocalSubnet
150        } else {
151            Remote::Other
152        }
153    }
154
155    fn reaches_lan_peers(self) -> bool {
156        matches!(self, Remote::Any | Remote::LocalSubnet)
157    }
158}
159
160/// A rule's `LocalAddresses`: which of OUR addresses it applies to. A rule
161/// limited to one local IP must only count for the adapter that owns it (Codex P2
162/// on #4151); treating it as "every adapter in the profile" could make an
163/// uncovered adapter look covered, or turn an address-scoped block into a false
164/// global block.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub enum LocalScope {
167    /// `*`, empty or `LocalSubnet`: every address we have.
168    Any,
169    /// Explicit IPv4 addresses, subnets and ranges, as inclusive `(low, high)`.
170    /// Empty when the list names only IPv6 addresses (it matches no IPv4 adapter).
171    Addrs(Vec<(Ipv4Addr, Ipv4Addr)>),
172    /// Windows keywords we cannot resolve here (`DHCP`, `DNS`, `Defaultgateway`,
173    /// `WINS`, ...). Matches nothing, like every spec we cannot read exactly.
174    Unparseable,
175}
176
177impl LocalScope {
178    pub fn parse(spec: &str) -> LocalScope {
179        let spec = spec.trim();
180        if spec.is_empty() || spec == "*" {
181            return LocalScope::Any;
182        }
183        let mut out = Vec::new();
184        for part in spec.split(',') {
185            let part = part.trim();
186            if part == "*" || part.eq_ignore_ascii_case("LocalSubnet") {
187                return LocalScope::Any;
188            }
189            if part.contains(':') {
190                continue; // IPv6: cannot match an IPv4 adapter
191            }
192            match Self::parse_v4(part) {
193                Some(r) => out.push(r),
194                None => return LocalScope::Unparseable,
195            }
196        }
197        LocalScope::Addrs(out)
198    }
199
200    fn parse_v4(part: &str) -> Option<(Ipv4Addr, Ipv4Addr)> {
201        if let Some((a, b)) = part.split_once('-') {
202            let (lo, hi) = (a.trim().parse::<Ipv4Addr>().ok()?, b.trim().parse::<Ipv4Addr>().ok()?);
203            return (u32::from(lo) <= u32::from(hi)).then_some((lo, hi));
204        }
205        if let Some((a, m)) = part.split_once('/') {
206            let ip = u32::from(a.trim().parse::<Ipv4Addr>().ok()?);
207            let m = m.trim();
208            // `/24` or `/255.255.255.0`
209            let mask = match m.parse::<u32>() {
210                Ok(len) if len <= 32 => if len == 0 { 0 } else { u32::MAX << (32 - len) },
211                _ => u32::from(m.parse::<Ipv4Addr>().ok()?),
212            };
213            return Some((Ipv4Addr::from(ip & mask), Ipv4Addr::from(ip | !mask)));
214        }
215        let ip = part.parse::<Ipv4Addr>().ok()?;
216        Some((ip, ip))
217    }
218
219    /// Does the rule apply to any of these adapter addresses?
220    pub fn applies_to(&self, ips: &[Ipv4Addr]) -> bool {
221        match self {
222            LocalScope::Any => true,
223            LocalScope::Unparseable => false,
224            LocalScope::Addrs(ranges) => ips.iter().any(|ip| {
225                let n = u32::from(*ip);
226                ranges.iter().any(|&(lo, hi)| u32::from(lo) <= n && n <= u32::from(hi))
227            }),
228        }
229    }
230}
231
232/// One firewall rule, with the fields that decide whether it affects us.
233#[derive(Debug, Clone)]
234pub struct FwRule {
235    #[cfg(any(test, feature = "test-support"))]
236    pub name: String,
237    pub enabled: bool,
238    pub inbound: bool,
239    pub allow: bool,
240    /// `NET_FW_PROFILE2_*` bitmask; Windows uses `0x7FFFFFFF` for "all".
241    pub profiles: u32,
242    /// The program the rule is bound to, `None` for any program.
243    pub program: Option<String>,
244    pub proto: Proto,
245    pub local_ports: PortSpec,
246    pub remote: Remote,
247    /// Which of our own addresses the rule applies to.
248    pub local_addresses: LocalScope,
249    /// Restricted to particular adapters or interface types. Such a rule may not
250    /// cover the adapter we care about, so it is skipped rather than assumed.
251    pub interface_scoped: bool,
252    /// Bound to something other than a program path: a Windows service, a Store
253    /// app package (`LocalAppPackageId`), particular users or machines, or secure
254    /// (authenticated) traffic only. Such a rule has an empty program path and
255    /// looks like "any program", which it is not. Found on narko, 2026-10-01: 25
256    /// Store-app rules ("Solitaire", "Microsoft Store", ...) made coverage look
257    /// complete for a binary no rule named. Skipped, never assumed to apply.
258    pub restricted: bool,
259}
260
261/// Compare two Windows paths: case-insensitive, `/` equals `\`, the `\\?\`
262/// prefix ignored. Rules that use environment variables (`%SystemRoot%`) do not
263/// match: coverage is only claimed when it can be shown.
264pub fn same_path(a: &str, b: &str) -> bool {
265    fn norm(p: &str) -> String {
266        p.trim()
267            .trim_start_matches(r"\\?\")
268            .replace('/', "\\")
269            .to_lowercase()
270    }
271    let (a, b) = (norm(a), norm(b));
272    !a.is_empty() && a == b
273}
274
275/// Something the running srv must be reachable on from the LAN.
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub struct Need {
278    pub proto: Proto,
279    pub port: u16,
280}
281
282/// The inbound traffic a LAN peer needs: our web and ws ports (TCP), the mDNS
283/// port (UDP 5353) and the UDP broadcast-probe responder that mobile clients
284/// use when mDNS is filtered (`discovery::UDP_DISCOVERY_PORT`, spec 4.1 puts
285/// it in the same rule as 5353; #4151). While a viewer listener is up
286/// (`viewer_port`), the port a paired phone or computer connects to is a need too:
287/// it is TCP, and it is the one the other machine is dropped on when no rule names it.
288pub fn lan_needs(web_port: u16, ws_port: u16, viewer_port: Option<u16>) -> Vec<Need> {
289    let mut needs = vec![
290        Need { proto: Proto::Tcp, port: web_port },
291        Need { proto: Proto::Tcp, port: ws_port },
292        Need { proto: Proto::Udp, port: 5353 },
293        Need { proto: Proto::Udp, port: super::discovery::UDP_DISCOVERY_PORT },
294        Need { proto: Proto::Udp, port: super::discovery::DESKTOP_DISCOVERY_PORT },
295    ];
296    // The viewer shares the web port when it is the only listener there; one need per port.
297    needs.extend(viewer_port.filter(|p| *p != web_port && *p != ws_port).map(|port| Need { proto: Proto::Tcp, port }));
298    needs
299}
300
301/// Does a rule apply to `need` on this adapter? Three answers, not two.
302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303enum Applies {
304    /// Every field says it does.
305    Yes,
306    /// Every field we CAN evaluate says it does, but one we cannot (an interface
307    /// scope, a service, package or user restriction, a port or local-address spec
308    /// we could not read exactly) leaves it open.
309    Maybe,
310    /// Something we can evaluate says it does not.
311    No,
312}
313
314fn applies_to(rule: &FwRule, exe: &str, need: Need, category: Category, local_ips: &[Ipv4Addr]) -> Applies {
315    // Fields that settle the question either way.
316    if !rule.enabled
317        || !rule.inbound
318        || rule.profiles & category.bit() == 0
319        || !rule.proto.covers(need.proto)
320        || !rule.remote.reaches_lan_peers()
321        || rule.program.as_deref().is_some_and(|p| !same_path(p, exe))
322    {
323        return Applies::No;
324    }
325    let mut uncertain = rule.interface_scoped || rule.restricted;
326    match &rule.local_ports {
327        PortSpec::Any => {}
328        PortSpec::Ranges(_) if rule.local_ports.contains(need.port) => {}
329        PortSpec::Ranges(_) => return Applies::No,
330        PortSpec::Unparseable => uncertain = true,
331    }
332    match &rule.local_addresses {
333        LocalScope::Any => {}
334        LocalScope::Addrs(_) if rule.local_addresses.applies_to(local_ips) => {}
335        LocalScope::Addrs(_) => return Applies::No,
336        LocalScope::Unparseable => uncertain = true,
337    }
338    if uncertain {
339        Applies::Maybe
340    } else {
341        Applies::Yes
342    }
343}
344
345/// An ALLOW counts only when every field is evaluable and says yes: counting one
346/// we cannot evaluate would claim coverage we cannot prove. A BLOCK is the
347/// opposite case, handled in `coverage_with`: skipping one we cannot evaluate
348/// would lean toward `Covered`, the very direction the unreadable-means-unknown
349/// rule forbids (ReAgent on #4151).
350fn rule_applies(rule: &FwRule, exe: &str, need: Need, category: Category, local_ips: &[Ipv4Addr]) -> bool {
351    applies_to(rule, exe, need, category, local_ips) == Applies::Yes
352}
353
354/// The rules that decide `need` for `category`, allow or block. For diagnostics
355/// and tests: it is the same predicate `coverage` uses.
356#[cfg(test)]
357pub fn matching_rules<'a>(
358    rules: &'a [FwRule],
359    exe: &str,
360    need: Need,
361    category: Category,
362    local_ips: &[Ipv4Addr],
363    allow: bool,
364) -> Vec<&'a FwRule> {
365    rules
366        .iter()
367        .filter(|r| r.allow == allow && rule_applies(r, exe, need, category, local_ips))
368        .collect()
369}
370
371/// One profile's own switches, which decide whether any rule is needed at all
372/// (ReAgent P1 on #4151: judging from rules alone reported `needs-setup` on a
373/// profile whose firewall is off, or whose default inbound action is Allow).
374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
375pub struct ProfileSettings {
376    /// The firewall is on for this profile. Off filters nothing, so nothing is
377    /// blocked, block rules included.
378    pub enabled: bool,
379    /// "Block all incoming connections": overrides every allow rule.
380    pub block_all_inbound: bool,
381    /// The default for inbound traffic no rule matches is Allow (Windows' own
382    /// default is Block). Then no allow rule is needed; a matching block still wins.
383    pub default_inbound_allow: bool,
384}
385
386impl Default for ProfileSettings {
387    /// Windows' defaults: firewall on, default inbound Block.
388    fn default() -> Self {
389        ProfileSettings { enabled: true, block_all_inbound: false, default_inbound_allow: false }
390    }
391}
392
393#[derive(Debug, Clone, Copy, Default)]
394pub struct Profiles {
395    pub domain: ProfileSettings,
396    pub private: ProfileSettings,
397    pub public: ProfileSettings,
398}
399
400impl Profiles {
401    pub fn get(&self, c: Category) -> ProfileSettings {
402        match c {
403            Category::Domain => self.domain,
404            Category::Private => self.private,
405            Category::Public => self.public,
406        }
407    }
408}
409
410#[derive(Debug, Clone, Copy, PartialEq, Eq)]
411pub enum Coverage {
412    /// Every need is allowed and none is blocked.
413    Covered,
414    /// An enabled inbound block rule matches at least one need.
415    Blocked,
416    /// No block, but at least one need has no allow rule.
417    Missing,
418    /// Every need is allowed, and no block is certain, but a block rule that might
419    /// apply could not be ruled out (scoped to an interface type, bound to a
420    /// service or user, or with a port or address spec we could not read). Coverage
421    /// cannot be proven.
422    Uncertain,
423}
424
425/// [`coverage_with`] under Windows' default profile settings, for an adapter
426/// whose addresses are unknown (only rules open to every local address match).
427#[cfg(test)]
428pub fn coverage(rules: &[FwRule], exe: &str, needs: &[Need], category: Category) -> Coverage {
429    coverage_with(rules, exe, needs, category, ProfileSettings::default(), &[])
430}
431
432/// Does `category`'s profile let LAN peers reach `exe` on every need?
433///
434/// Order, as Windows applies it: a profile with the firewall off filters nothing;
435/// "block all incoming" beats every allow; a matching block rule beats any allow;
436/// then, with a default inbound action of Allow, nothing more is needed;
437/// otherwise every need must have a matching allow rule.
438pub fn coverage_with(
439    rules: &[FwRule],
440    exe: &str,
441    needs: &[Need],
442    category: Category,
443    settings: ProfileSettings,
444    local_ips: &[Ipv4Addr],
445) -> Coverage {
446    if !settings.enabled {
447        return Coverage::Covered;
448    }
449    if settings.block_all_inbound {
450        return Coverage::Blocked;
451    }
452    let applies = |allow: bool, need: Need| {
453        rules
454            .iter()
455            .any(|r| r.allow == allow && rule_applies(r, exe, need, category, local_ips))
456    };
457    if needs.iter().any(|&n| applies(false, n)) {
458        return Coverage::Blocked;
459    }
460    // A block we cannot rule out, next to an allow we can see.
461    let maybe_blocked = needs.iter().any(|&n| {
462        rules
463            .iter()
464            .any(|r| !r.allow && applies_to(r, exe, n, category, local_ips) == Applies::Maybe)
465    });
466    if settings.default_inbound_allow || needs.iter().all(|&n| applies(true, n)) {
467        if maybe_blocked {
468            Coverage::Uncertain
469        } else {
470            Coverage::Covered
471        }
472    } else {
473        Coverage::Missing
474    }
475}
476
477/// A network adapter and the category of the network it is connected to.
478#[derive(Debug, Clone)]
479pub struct Adapter {
480    /// The adapter GUID (`if_addrs::Interface::adapter_name` on Windows).
481    #[cfg(any(test, feature = "test-support"))]
482    pub id: String,
483    pub name: String,
484    pub ipv4: Vec<Ipv4Addr>,
485    /// `None` when Windows could not say (no profile yet, or the lookup failed).
486    pub category: Option<Category>,
487}
488
489#[derive(Debug, Clone, Copy, PartialEq, Eq)]
490pub enum AdapterState {
491    Covered,
492    NeedsSetup,
493    Blocked,
494    /// A Public network with no allow rule: not set up on purpose. Opening it
495    /// needs the user's consent for that network (spec 4.4), unlike Private.
496    PublicNotTrusted,
497    /// Category unknown: no claim either way.
498    Unknown,
499}
500
501#[cfg(test)]
502pub fn adapter_state(rules: &[FwRule], exe: &str, needs: &[Need], adapter: &Adapter) -> AdapterState {
503    adapter_state_with(rules, exe, needs, adapter, Profiles::default())
504}
505
506pub fn adapter_state_with(
507    rules: &[FwRule],
508    exe: &str,
509    needs: &[Need],
510    adapter: &Adapter,
511    profiles: Profiles,
512) -> AdapterState {
513    let Some(category) = adapter.category else {
514        return AdapterState::Unknown;
515    };
516    match coverage_with(rules, exe, needs, category, profiles.get(category), &adapter.ipv4) {
517        Coverage::Covered => AdapterState::Covered,
518        Coverage::Blocked => AdapterState::Blocked,
519        Coverage::Missing if category == Category::Public => AdapterState::PublicNotTrusted,
520        Coverage::Missing => AdapterState::NeedsSetup,
521        // Cannot prove it either way: no claim, like an unknown category.
522        Coverage::Uncertain => AdapterState::Unknown,
523    }
524}
525
526/// What the status bar shows about the firewall (spec 4.3).
527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
528pub enum FirewallStatus {
529    /// At least one adapter is covered: LAN can work.
530    Ok,
531    NeedsSetup,
532    Blocked,
533    PublicNetwork,
534    /// An administrator's policy makes local rules ineffective: a setup helper
535    /// cannot fix it.
536    Managed,
537    /// Nothing can be said (no adapters, or categories unknown).
538    Unknown,
539}
540
541impl FirewallStatus {
542    pub fn wire(self) -> &'static str {
543        match self {
544            FirewallStatus::Ok => "ok",
545            FirewallStatus::NeedsSetup => "needs-setup",
546            FirewallStatus::Blocked => "blocked",
547            FirewallStatus::PublicNetwork => "public-network",
548            FirewallStatus::Managed => "managed",
549            FirewallStatus::Unknown => "unknown",
550        }
551    }
552}
553
554/// The overall status from every adapter. One covered adapter is enough for
555/// "ok": a host also has virtual adapters (VMware, WSL, Hyper-V) that are
556/// rightly uncovered, and they must not flag a machine whose real LAN works.
557/// Otherwise the most actionable problem wins: a block, then a managed policy
558/// (no helper can help), then missing rules, then an untrusted Public network.
559pub fn overall(states: &[AdapterState], local_rules_ignored: bool) -> FirewallStatus {
560    let any = |s: AdapterState| states.iter().any(|&x| x == s);
561    if any(AdapterState::Covered) {
562        FirewallStatus::Ok
563    } else if any(AdapterState::Blocked) {
564        FirewallStatus::Blocked
565    } else if local_rules_ignored && (any(AdapterState::NeedsSetup) || any(AdapterState::PublicNotTrusted)) {
566        FirewallStatus::Managed
567    } else if any(AdapterState::NeedsSetup) {
568        FirewallStatus::NeedsSetup
569    } else if any(AdapterState::PublicNotTrusted) {
570        FirewallStatus::PublicNetwork
571    } else {
572        FirewallStatus::Unknown
573    }
574}
575
576/// Everything read from the OS in one go.
577#[derive(Debug, Clone, Default)]
578pub struct Snapshot {
579    pub rules: Vec<FwRule>,
580    pub adapters: Vec<Adapter>,
581    /// Group policy stops locally created rules from applying.
582    pub local_rules_ignored: bool,
583    /// Each profile's own on/off, block-all and default-inbound settings.
584    pub profiles: Profiles,
585    /// Rules that could not be read. One of them may be the block or the allow
586    /// that decides the verdict, so while any exist coverage cannot be proven.
587    pub unreadable_rules: u32,
588}
589
590#[derive(Debug, Clone)]
591pub struct Report {
592    pub status: FirewallStatus,
593    pub per_adapter: Vec<(Adapter, AdapterState)>,
594}
595
596pub fn report(snapshot: &Snapshot, exe: &str, needs: &[Need]) -> Report {
597    let per_adapter: Vec<(Adapter, AdapterState)> = snapshot
598        .adapters
599        .iter()
600        .map(|a| (a.clone(), adapter_state_with(&snapshot.rules, exe, needs, a, snapshot.profiles)))
601        .collect();
602    let states: Vec<AdapterState> = per_adapter.iter().map(|(_, s)| *s).collect();
603    let mut status = overall(&states, snapshot.local_rules_ignored);
604    // Never claim coverage that cannot be proven (Codex P2 on #4151): with an
605    // unreadable rule there may be a block we did not see, so `ok` becomes
606    // `unknown`. The problem verdicts stand: they are warnings, and a rule we
607    // could not read does not make a missing allow less missing.
608    if status == FirewallStatus::Ok && snapshot.unreadable_rules > 0 {
609        status = FirewallStatus::Unknown;
610    }
611    Report { status, per_adapter }
612}
613
614/// Whether this status goes to the windows on this tick. A standing problem is
615/// re-sent every tick so a window opened later, or a reconnected WebSocket,
616/// learns of it: the frontend only learns from events and cannot ask (the same
617/// lesson as `mdns_health::should_publish`, #4148). `Ok` and
618/// `Unknown` go out only on change.
619pub fn should_publish(status: FirewallStatus, changed: bool) -> bool {
620    match status {
621        FirewallStatus::Ok | FirewallStatus::Unknown => changed,
622        FirewallStatus::NeedsSetup
623        | FirewallStatus::Blocked
624        | FirewallStatus::PublicNetwork
625        | FirewallStatus::Managed => true,
626    }
627}
628
629fn category_wire(c: Option<Category>) -> &'static str {
630    match c {
631        Some(Category::Public) => "public",
632        Some(Category::Private) => "private",
633        Some(Category::Domain) => "domain",
634        None => "unknown",
635    }
636}
637
638fn state_wire(s: AdapterState) -> &'static str {
639    match s {
640        AdapterState::Covered => "covered",
641        AdapterState::NeedsSetup => "needs-setup",
642        AdapterState::Blocked => "blocked",
643        AdapterState::PublicNotTrusted => "public-not-trusted",
644        AdapterState::Unknown => "unknown",
645    }
646}
647
648/// The `laninstances:firewall` event body.
649pub fn payload(
650    status: FirewallStatus,
651    per_adapter: &[(Adapter, AdapterState)],
652    local_rules_ignored: bool,
653) -> LanFirewall {
654    LanFirewall {
655        status: status.wire().to_string(),
656        local_rules_ignored,
657        adapters: per_adapter
658            .iter()
659            .map(|(a, s)| LanFirewallAdapter {
660                name: a.name.clone(),
661                category: category_wire(a.category).to_string(),
662                state: state_wire(*s).to_string(),
663            })
664            .collect(),
665    }
666}
667
668/// `laninstances:firewall`: what the OS firewall would do to LAN peers reaching this machine.
669#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
670#[ts(export, export_to = "../../../frontend/types/rpc/")]
671pub struct LanFirewall {
672    #[ts(type = r#""ok" | "needs-setup" | "blocked" | "public-network" | "managed" | "unknown" | "off""#)]
673    pub status: String,
674    /// Per adapter: its network category and whether a rule covers it.
675    pub adapters: Vec<LanFirewallAdapter>,
676    /// Group policy makes locally created rules ineffective.
677    #[serde(rename = "localRulesIgnored")]
678    #[ts(rename = "localRulesIgnored")]
679    pub local_rules_ignored: bool,
680}
681
682impl LanFirewall {
683    /// No verdict to show: LAN went off, or the firewall couldn't be read.
684    fn bare(status: &str) -> Self {
685        LanFirewall { status: status.to_string(), adapters: Vec::new(), local_rules_ignored: false }
686    }
687}
688
689/// One adapter in a `LanFirewall` verdict.
690#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
691#[ts(export, export_to = "../../../frontend/types/rpc/")]
692pub struct LanFirewallAdapter {
693    pub name: String,
694    #[ts(type = r#""public" | "private" | "domain" | "unknown""#)]
695    pub category: String,
696    #[ts(type = r#""covered" | "needs-setup" | "blocked" | "public-not-trusted" | "unknown""#)]
697    pub state: String,
698}
699
700/// How often the firewall is read while LAN discovery is wanted. A read is cheap
701/// (about 60 ms for 1,300 rules on narko) and a changed rule or network should
702/// show promptly.
703const WATCH_TICK: std::time::Duration = std::time::Duration::from_secs(30);
704
705/// Woken when the person has just run the setup, so the verdict follows at once and not at the next tick.
706static READ_NOW: tokio::sync::Notify = tokio::sync::Notify::const_new();
707
708/// Ask the watcher to read the firewall again now.
709pub fn read_again_now() {
710    READ_NOW.notify_one();
711}
712
713/// Watch the OS firewall while LAN discovery is wanted and tell the windows what
714/// it found, via `laninstances:firewall`. Only Windows can read its firewall
715/// today (macOS and Linux are later PRs): elsewhere this does nothing, so the
716/// status bar simply has no firewall verdict.
717///
718/// Read-only. It changes no rule and gates nothing: the indicator tells the
719/// truth first (spec 4.3); acting on it is a later step.
720pub fn spawn_watcher(
721    lan: std::sync::Arc<super::discovery::LanDiscoveryController>,
722    web_port: u16,
723    ws_port: u16,
724    event_bus: std::sync::Arc<crate::backend::eventbus::EventBus>,
725) {
726    if !cfg!(windows) {
727        return;
728    }
729    tokio::spawn(async move {
730        let mut last: Option<String> = None;
731        let mut tick = tokio::time::interval(WATCH_TICK);
732        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
733        loop {
734            tokio::select! {
735                _ = tick.tick() => {}
736                _ = READ_NOW.notified() => {}
737            }
738            if !lan.is_wanted() {
739                // LAN went off: clear whatever the indicator was showing.
740                if last.as_deref().is_some_and(|s| s != "off") {
741                    event_bus.broadcast_event(&crate::backend::eventbus::EventBus::typed_ws_event::<crate::backend::mps_events::LanInstancesFirewall>(&LanFirewall::bare("off"), String::new()));
742                    last = Some("off".to_string());
743                }
744                continue;
745            }
746            let exe = match std::env::current_exe() {
747                Ok(p) => p.to_string_lossy().to_string(),
748                Err(e) => {
749                    tracing::warn!("firewall check: cannot find our own executable: {e}");
750                    continue;
751                }
752            };
753            let snapshot = match tokio::task::spawn_blocking(read_snapshot).await {
754                Ok(Ok(s)) => s,
755                Ok(Err(e)) => {
756                    // "Unknown" is a fact worth one line, and one event, not one per
757                    // tick. The event matters: without it a needs-setup or blocked
758                    // sent earlier would stay on the status bar while the backend
759                    // no longer knows (ReAgent P2 on #4151).
760                    if last.as_deref() != Some("unknown") {
761                        tracing::warn!("could not read the OS firewall, so no verdict: {e}");
762                        event_bus.broadcast_event(&crate::backend::eventbus::EventBus::typed_ws_event::<crate::backend::mps_events::LanInstancesFirewall>(&LanFirewall::bare("unknown"), String::new()));
763                        last = Some("unknown".to_string());
764                    }
765                    continue;
766                }
767                Err(e) => {
768                    tracing::warn!("firewall reader task failed: {e}");
769                    continue;
770                }
771            };
772            // The viewer's port is read every tick: it comes and goes with the viewer listener.
773            let report = report(&snapshot, &exe, &lan_needs(web_port, ws_port, super::super::viewer::advertised_viewer_port()));
774            let wire = report.status.wire().to_string();
775            let changed = last.as_deref() != Some(wire.as_str());
776            if changed && report.status != FirewallStatus::Ok {
777                tracing::warn!(
778                    status = %wire,
779                    adapters = ?report.per_adapter.iter().map(|(a, s)| (a.name.clone(), *s)).collect::<Vec<_>>(),
780                    "OS firewall may keep other machines from reaching this one"
781                );
782            }
783            if should_publish(report.status, changed) {
784                let verdict = payload(report.status, &report.per_adapter, snapshot.local_rules_ignored);
785                event_bus.broadcast_event(&crate::backend::eventbus::EventBus::typed_ws_event::<crate::backend::mps_events::LanInstancesFirewall>(&verdict, String::new()));
786            }
787            last = Some(wire);
788        }
789    });
790}
791
792/// Read the OS firewall and the adapters' network categories. Windows only for
793/// now (macOS is PR C, Linux PR D of the spec's delivery plan); elsewhere it is an
794/// `Err`, which callers must treat as "unknown", never as "covered".
795#[cfg(windows)]
796pub use super::firewall_windows::read_snapshot;
797
798#[cfg(not(windows))]
799pub fn read_snapshot() -> Result<Snapshot, String> {
800    Err("firewall inspection is only implemented on Windows".to_string())
801}
802
803#[cfg(test)]
804mod tests {
805    use super::*;
806
807    const ALL: u32 = 0x7FFF_FFFF;
808    const EXE: &str = r"C:\Users\user\Desktop\agentmux-0.59.1\runtime\agentmux-srv-0.59.1-windows.x64.exe";
809    const OLD_EXE: &str = r"C:\Users\user\Desktop\agentmux-0.58.2\runtime\agentmux-srv-0.58.2-windows.x64.exe";
810
811    fn needs() -> Vec<Need> {
812        lan_needs(29700, 29701, None)
813    }
814
815    fn rule(name: &str) -> FwRule {
816        FwRule {
817            name: name.to_string(),
818            enabled: true,
819            inbound: true,
820            allow: true,
821            profiles: PROFILE_PRIVATE,
822            program: None,
823            proto: Proto::Any,
824            local_ports: PortSpec::Any,
825            remote: Remote::Any,
826            local_addresses: LocalScope::Any,
827            interface_scoped: false,
828            restricted: false,
829        }
830    }
831
832    fn program_rule(exe: &str, proto: Proto, profiles: u32, allow: bool) -> FwRule {
833        FwRule {
834            program: Some(exe.to_string()),
835            proto,
836            profiles,
837            allow,
838            ..rule("agentmux-srv")
839        }
840    }
841
842    fn adapter(name: &str, cat: Option<Category>) -> Adapter {
843        Adapter {
844            id: format!("{{{name}}}"),
845            name: name.to_string(),
846            ipv4: vec!["192.168.1.26".parse().unwrap()],
847            category: cat,
848        }
849    }
850
851    // ---- parsers
852
853    #[test]
854    fn port_specs_parse_the_forms_windows_uses() {
855        assert_eq!(PortSpec::parse(""), PortSpec::Any);
856        assert_eq!(PortSpec::parse("*"), PortSpec::Any);
857        let p = PortSpec::parse("5353, 29700-29799");
858        assert!(p.contains(5353) && p.contains(29700) && p.contains(29799) && p.contains(29750));
859        assert!(!p.contains(29800) && !p.contains(5354) && !p.contains(29699));
860    }
861
862    #[test]
863    fn port_keywords_and_junk_never_match() {
864        for bad in ["RPC", "IPHTTPS", "Teredo", "80-", "-80", "70000", "90-80", "1,,2", "a-b"] {
865            let p = PortSpec::parse(bad);
866            assert_eq!(p, PortSpec::Unparseable, "{bad}");
867            assert!(!p.contains(80));
868        }
869    }
870
871    #[test]
872    fn remote_addresses_reduce_to_whether_lan_peers_are_reached() {
873        assert!(Remote::parse("").reaches_lan_peers());
874        assert!(Remote::parse("*").reaches_lan_peers());
875        assert!(Remote::parse("LocalSubnet").reaches_lan_peers());
876        assert!(Remote::parse("localsubnet").reaches_lan_peers());
877        assert!(!Remote::parse("192.168.1.5").reaches_lan_peers());
878        assert!(!Remote::parse("Internet").reaches_lan_peers());
879        assert!(!Remote::parse("LocalSubnet,10.0.0.1").reaches_lan_peers());
880    }
881
882    #[test]
883    fn protocols_from_the_windows_numbers() {
884        assert_eq!(Proto::from_win(6), Proto::Tcp);
885        assert_eq!(Proto::from_win(17), Proto::Udp);
886        assert_eq!(Proto::from_win(256), Proto::Any);
887        assert_eq!(Proto::from_win(1), Proto::Other);
888        assert!(!Proto::Other.covers(Proto::Tcp));
889        assert!(Proto::Any.covers(Proto::Udp));
890    }
891
892    #[test]
893    fn paths_compare_the_way_windows_does() {
894        assert!(same_path(r"C:\A\B.exe", r"c:\a\b.EXE"));
895        assert!(same_path("C:/A/B.exe", r"C:\A\B.exe"));
896        assert!(same_path(r"\\?\C:\A\B.exe", r"C:\A\B.exe"));
897        assert!(!same_path(r"C:\A\B.exe", r"C:\A\C.exe"));
898        assert!(!same_path("", ""));
899        assert!(!same_path(r"%SystemRoot%\x.exe", r"C:\Windows\x.exe"), "env vars are not expanded");
900    }
901
902    // ---- coverage: the cases that actually happened
903
904    /// narko, 2026-09-30: 606 per-program rules, none for the running binary,
905    /// nothing for the Private profile. LAN was on, nothing warned, no peer
906    /// was ever seen.
907    #[test]
908    fn narko_with_only_stale_per_path_rules_needs_setup() {
909        let mut rules: Vec<FwRule> = (0..606)
910            .map(|i| program_rule(&format!(r"C:\old\{i}\agentmux-srv.exe"), Proto::Any, ALL, true))
911            .collect();
912        rules.push(program_rule(OLD_EXE, Proto::Any, ALL, true));
913        assert_eq!(coverage(&rules, EXE, &needs(), Category::Private), Coverage::Missing);
914        let a = adapter("Ethernet", Some(Category::Private));
915        assert_eq!(adapter_state(&rules, EXE, &needs(), &a), AdapterState::NeedsSetup);
916    }
917
918    /// Area54: Private allow rules for the CURRENT binary, among 400 stale ones.
919    #[test]
920    fn area54_with_rules_for_the_current_binary_is_covered() {
921        let mut rules: Vec<FwRule> = (0..390)
922            .map(|i| program_rule(&format!(r"C:\old\{i}\agentmux-srv.exe"), Proto::Any, ALL, true))
923            .collect();
924        rules.push(program_rule(EXE, Proto::Tcp, PROFILE_PRIVATE, true));
925        rules.push(program_rule(EXE, Proto::Udp, PROFILE_PRIVATE, true));
926        // The Public blocks that Windows adds when a prompt is cancelled.
927        rules.push(program_rule(EXE, Proto::Tcp, PROFILE_PUBLIC, false));
928        rules.push(program_rule(EXE, Proto::Udp, PROFILE_PUBLIC, false));
929        assert_eq!(coverage(&rules, EXE, &needs(), Category::Private), Coverage::Covered);
930        assert_eq!(coverage(&rules, EXE, &needs(), Category::Public), Coverage::Blocked);
931    }
932
933    #[test]
934    fn a_program_rule_for_another_path_does_not_cover_this_binary() {
935        // Spec R7: the version is in the file name, so every update changes the path.
936        let rules = vec![program_rule(OLD_EXE, Proto::Any, ALL, true)];
937        assert_eq!(coverage(&rules, EXE, &needs(), Category::Private), Coverage::Missing);
938    }
939
940    #[test]
941    fn port_rules_survive_updates_and_new_paths() {
942        let tcp = FwRule {
943            proto: Proto::Tcp,
944            local_ports: PortSpec::parse("29700-29799"),
945            remote: Remote::LocalSubnet,
946            ..rule("AgentMux LAN (TCP)")
947        };
948        let udp = FwRule {
949            proto: Proto::Udp,
950            local_ports: PortSpec::parse("5353,29700,47891"),
951            remote: Remote::LocalSubnet,
952            ..rule("AgentMux LAN (UDP)")
953        };
954        let rules = vec![tcp, udp];
955        for exe in [EXE, OLD_EXE, r"D:\portable\anything.exe"] {
956            assert_eq!(coverage(&rules, exe, &needs(), Category::Private), Coverage::Covered, "{exe}");
957        }
958    }
959
960    #[test]
961    fn srv_ports_outside_the_rule_range_are_not_covered() {
962        // The OS-chosen fallback port when the fixed range is exhausted.
963        let tcp = FwRule { proto: Proto::Tcp, local_ports: PortSpec::parse("29700-29799"), ..rule("t") };
964        let udp = FwRule { proto: Proto::Udp, local_ports: PortSpec::parse("5353"), ..rule("u") };
965        let outside = lan_needs(51234, 51235, None);
966        assert_eq!(coverage(&[tcp, udp], EXE, &outside, Category::Private), Coverage::Missing);
967    }
968
969    #[test]
970    fn the_viewer_port_is_a_need_of_its_own_only_when_it_is_up_and_not_already_one() {
971        let tcp_ports = |needs: &[Need]| needs.iter().filter(|n| n.proto == Proto::Tcp).map(|n| n.port).collect::<Vec<_>>();
972        assert_eq!(tcp_ports(&lan_needs(29700, 29701, None)), vec![29700, 29701]);
973        assert_eq!(tcp_ports(&lan_needs(29700, 29701, Some(29702))), vec![29700, 29701, 29702]);
974        // One need per port: a viewer that shares the web or ws port adds nothing.
975        assert_eq!(tcp_ports(&lan_needs(29700, 29701, Some(29701))), vec![29700, 29701]);
976    }
977
978    #[test]
979    fn a_rule_that_names_the_web_and_ws_ports_but_not_the_viewer_port_is_not_enough() {
980        // The viewer listens on a LAN address, no rule names its port, and a paired computer's connect is dropped
981        // while the check says everything is fine.
982        let tcp = FwRule { proto: Proto::Tcp, local_ports: PortSpec::parse("29700-29701"), ..rule("t") };
983        let udp = FwRule { proto: Proto::Udp, local_ports: PortSpec::parse("5353,29700,47891"), ..rule("u") };
984        let rules = vec![tcp, udp];
985        assert_eq!(coverage(&rules, EXE, &lan_needs(29700, 29701, None), Category::Private), Coverage::Covered);
986        assert_eq!(coverage(&rules, EXE, &lan_needs(29700, 29701, Some(29705)), Category::Private), Coverage::Missing);
987    }
988
989    #[test]
990    fn the_spec_port_rule_covers_a_viewer_port_in_the_range_and_not_one_outside_it() {
991        let tcp = FwRule { proto: Proto::Tcp, local_ports: PortSpec::parse("29700-29799"), remote: Remote::LocalSubnet, ..rule("AgentMux LAN (TCP)") };
992        let udp = FwRule { proto: Proto::Udp, local_ports: PortSpec::parse("5353,29700,47891"), remote: Remote::LocalSubnet, ..rule("AgentMux LAN (UDP)") };
993        let rules = vec![tcp, udp];
994        assert_eq!(coverage(&rules, EXE, &lan_needs(29700, 29701, Some(29705)), Category::Private), Coverage::Covered);
995        assert_eq!(coverage(&rules, EXE, &lan_needs(29700, 29701, Some(51234)), Category::Private), Coverage::Missing);
996    }
997
998    // ---- what must not count
999
1000    #[test]
1001    fn disabled_outbound_interface_scoped_and_remote_limited_rules_do_not_count() {
1002        let base = program_rule(EXE, Proto::Any, PROFILE_PRIVATE, true);
1003        for broken in [
1004            FwRule { enabled: false, ..base.clone() },
1005            FwRule { inbound: false, ..base.clone() },
1006            FwRule { interface_scoped: true, ..base.clone() },
1007            // A Store-app or service rule looks like "any program" but is not.
1008            FwRule { restricted: true, program: None, ..base.clone() },
1009            FwRule { remote: Remote::Other, ..base.clone() },
1010            FwRule { proto: Proto::Other, ..base.clone() },
1011            FwRule { local_ports: PortSpec::Unparseable, ..base.clone() },
1012        ] {
1013            assert_eq!(coverage(&[broken.clone()], EXE, &needs(), Category::Private), Coverage::Missing, "{broken:?}");
1014        }
1015    }
1016
1017    #[test]
1018    fn a_rule_for_another_profile_does_not_cover_this_one() {
1019        let rules = vec![program_rule(EXE, Proto::Any, PROFILE_PUBLIC | PROFILE_DOMAIN, true)];
1020        assert_eq!(coverage(&rules, EXE, &needs(), Category::Private), Coverage::Missing);
1021        assert_eq!(coverage(&rules, EXE, &needs(), Category::Domain), Coverage::Covered);
1022    }
1023
1024    #[test]
1025    fn a_block_beats_an_allow_as_in_windows() {
1026        let rules = vec![
1027            program_rule(EXE, Proto::Any, ALL, true),
1028            program_rule(EXE, Proto::Tcp, PROFILE_PRIVATE, false),
1029        ];
1030        assert_eq!(coverage(&rules, EXE, &needs(), Category::Private), Coverage::Blocked);
1031        // The other profiles are untouched by it.
1032        assert_eq!(coverage(&rules, EXE, &needs(), Category::Domain), Coverage::Covered);
1033    }
1034
1035    #[test]
1036    fn a_block_for_a_different_program_does_not_block_us() {
1037        let rules = vec![
1038            program_rule(EXE, Proto::Any, ALL, true),
1039            program_rule(OLD_EXE, Proto::Any, ALL, false),
1040        ];
1041        assert_eq!(coverage(&rules, EXE, &needs(), Category::Private), Coverage::Covered);
1042    }
1043
1044    #[test]
1045    fn tcp_alone_is_not_enough_mdns_needs_udp_too() {
1046        let rules = vec![program_rule(EXE, Proto::Tcp, PROFILE_PRIVATE, true)];
1047        assert_eq!(coverage(&rules, EXE, &needs(), Category::Private), Coverage::Missing);
1048    }
1049
1050    // ---- per adapter and overall
1051
1052    #[test]
1053    fn a_public_adapter_with_no_rule_is_not_trusted_rather_than_needs_setup() {
1054        let rules = vec![program_rule(EXE, Proto::Any, PROFILE_PRIVATE, true)];
1055        let public = adapter("Wi-Fi", Some(Category::Public));
1056        assert_eq!(adapter_state(&rules, EXE, &needs(), &public), AdapterState::PublicNotTrusted);
1057        let private = adapter("Ethernet", Some(Category::Private));
1058        assert_eq!(adapter_state(&rules, EXE, &needs(), &private), AdapterState::Covered);
1059    }
1060
1061    #[test]
1062    fn an_adapter_with_an_unknown_category_makes_no_claim() {
1063        let rules = vec![program_rule(EXE, Proto::Any, ALL, true)];
1064        assert_eq!(adapter_state(&rules, EXE, &needs(), &adapter("x", None)), AdapterState::Unknown);
1065    }
1066
1067    #[test]
1068    fn one_covered_adapter_is_enough_virtual_adapters_do_not_flag_a_working_lan() {
1069        use AdapterState::*;
1070        assert_eq!(overall(&[Covered, PublicNotTrusted, NeedsSetup, Blocked], false), FirewallStatus::Ok);
1071    }
1072
1073    #[test]
1074    fn overall_priority_is_block_then_managed_then_setup_then_public() {
1075        use AdapterState::*;
1076        assert_eq!(overall(&[NeedsSetup, Blocked], false), FirewallStatus::Blocked);
1077        assert_eq!(overall(&[NeedsSetup], true), FirewallStatus::Managed);
1078        assert_eq!(overall(&[PublicNotTrusted], true), FirewallStatus::Managed);
1079        assert_eq!(overall(&[PublicNotTrusted, NeedsSetup], false), FirewallStatus::NeedsSetup);
1080        assert_eq!(overall(&[PublicNotTrusted], false), FirewallStatus::PublicNetwork);
1081        assert_eq!(overall(&[Unknown, Unknown], false), FirewallStatus::Unknown);
1082        assert_eq!(overall(&[], false), FirewallStatus::Unknown);
1083    }
1084
1085    #[test]
1086    fn a_managed_policy_does_not_hide_a_working_lan() {
1087        assert_eq!(overall(&[AdapterState::Covered], true), FirewallStatus::Ok);
1088    }
1089
1090    #[test]
1091    fn the_report_ties_the_snapshot_together() {
1092        let snap = Snapshot {
1093            rules: vec![program_rule(EXE, Proto::Any, PROFILE_PRIVATE, true)],
1094            adapters: vec![
1095                adapter("Ethernet", Some(Category::Private)),
1096                adapter("vEthernet (Default Switch)", Some(Category::Public)),
1097            ],
1098            local_rules_ignored: false,
1099            profiles: Profiles::default(),
1100            unreadable_rules: 0,
1101        };
1102        let r = report(&snap, EXE, &needs());
1103        assert_eq!(r.status, FirewallStatus::Ok);
1104        assert_eq!(r.per_adapter[0].1, AdapterState::Covered);
1105        assert_eq!(r.per_adapter[1].1, AdapterState::PublicNotTrusted);
1106
1107        let none = Snapshot { rules: vec![], ..snap };
1108        assert_eq!(report(&none, EXE, &needs()).status, FirewallStatus::NeedsSetup);
1109    }
1110
1111    #[test]
1112    fn a_standing_problem_is_resent_every_tick_ok_and_unknown_only_on_change() {
1113        for problem in [
1114            FirewallStatus::NeedsSetup,
1115            FirewallStatus::Blocked,
1116            FirewallStatus::PublicNetwork,
1117            FirewallStatus::Managed,
1118        ] {
1119            assert!(should_publish(problem, false), "{problem:?}: a late window must learn of it");
1120        }
1121        for quiet in [FirewallStatus::Ok, FirewallStatus::Unknown] {
1122            assert!(!should_publish(quiet, false));
1123            assert!(should_publish(quiet, true), "{quiet:?}: a change must clear an earlier warning");
1124        }
1125    }
1126
1127    #[test]
1128    fn the_event_payload_is_the_frontend_contract() {
1129        let a = adapter("Ethernet", Some(Category::Private));
1130        let v = serde_json::to_value(payload(FirewallStatus::NeedsSetup, &[(a, AdapterState::NeedsSetup)], false)).unwrap();
1131        assert_eq!(v["status"], "needs-setup");
1132        assert_eq!(v["localRulesIgnored"], false);
1133        assert_eq!(v["adapters"][0]["name"], "Ethernet");
1134        assert_eq!(v["adapters"][0]["category"], "private");
1135        assert_eq!(v["adapters"][0]["state"], "needs-setup");
1136    }
1137
1138    #[test]
1139    fn a_rule_bound_to_a_service_or_store_app_is_not_an_any_program_rule() {
1140        // Found on narko: 25 Store-app rules have an empty program path.
1141        let store = FwRule { restricted: true, program: None, ..rule("Microsoft Store") };
1142        let rules = vec![store];
1143        assert_eq!(coverage(&rules, EXE, &needs(), Category::Private), Coverage::Missing);
1144    }
1145
1146    // ReAgent P1 on #4151: the profile's own switches decide whether any rule is needed.
1147    #[test]
1148    fn a_profile_with_the_firewall_off_needs_no_rule_and_blocks_nothing() {
1149        let off = ProfileSettings { enabled: false, ..ProfileSettings::default() };
1150        assert_eq!(coverage_with(&[], EXE, &needs(), Category::Private, off, &[]), Coverage::Covered);
1151        // Block rules are not enforced either when the firewall is off.
1152        let blocked = vec![program_rule(EXE, Proto::Any, ALL, false)];
1153        assert_eq!(coverage_with(&blocked, EXE, &needs(), Category::Private, off, &[]), Coverage::Covered);
1154    }
1155
1156    #[test]
1157    fn a_default_inbound_allow_needs_no_allow_rule_but_a_block_still_wins() {
1158        let open = ProfileSettings { default_inbound_allow: true, ..ProfileSettings::default() };
1159        assert_eq!(coverage_with(&[], EXE, &needs(), Category::Private, open, &[]), Coverage::Covered);
1160        let blocked = vec![program_rule(EXE, Proto::Tcp, PROFILE_PRIVATE, false)];
1161        assert_eq!(coverage_with(&blocked, EXE, &needs(), Category::Private, open, &[]), Coverage::Blocked);
1162    }
1163
1164    #[test]
1165    fn block_all_incoming_beats_every_allow_rule() {
1166        let all = ProfileSettings { block_all_inbound: true, ..ProfileSettings::default() };
1167        let rules = vec![program_rule(EXE, Proto::Any, ALL, true)];
1168        assert_eq!(coverage_with(&rules, EXE, &needs(), Category::Private, all, &[]), Coverage::Blocked);
1169    }
1170
1171    #[test]
1172    fn settings_are_per_profile_in_the_report() {
1173        let profiles = Profiles {
1174            private: ProfileSettings { enabled: false, ..ProfileSettings::default() },
1175            ..Profiles::default()
1176        };
1177        let snap = Snapshot {
1178            rules: vec![],
1179            adapters: vec![
1180                adapter("Ethernet", Some(Category::Private)),
1181                adapter("Wi-Fi", Some(Category::Public)),
1182            ],
1183            local_rules_ignored: false,
1184            profiles,
1185            unreadable_rules: 0,
1186        };
1187        let r = report(&snap, EXE, &needs());
1188        assert_eq!(r.per_adapter[0].1, AdapterState::Covered, "Private firewall is off");
1189        assert_eq!(r.per_adapter[1].1, AdapterState::PublicNotTrusted, "Public still defaults to block");
1190        assert_eq!(r.status, FirewallStatus::Ok);
1191    }
1192
1193    // Codex P2 on #4151: the UDP broadcast responder is a need too.
1194    #[test]
1195    fn the_udp_broadcast_responder_port_is_a_need() {
1196        let port = crate::backend::lan::discovery::UDP_DISCOVERY_PORT;
1197        assert!(needs().iter().any(|n| n.proto == Proto::Udp && n.port == port));
1198        // TCP plus mDNS but not the responder port: not covered.
1199        let tcp = FwRule { proto: Proto::Tcp, local_ports: PortSpec::parse("29700-29799"), ..rule("t") };
1200        let mdns = FwRule { proto: Proto::Udp, local_ports: PortSpec::parse("5353"), ..rule("u") };
1201        assert_eq!(coverage(&[tcp.clone(), mdns], EXE, &needs(), Category::Private), Coverage::Missing);
1202        // The desktop discovery port is a need too: a rule that names mDNS and the
1203        // mobile port but not it leaves peers unable to find us when mDNS is down.
1204        let no_desktop = FwRule { proto: Proto::Udp, local_ports: PortSpec::parse("5353,47891"), ..rule("u") };
1205        assert_eq!(coverage(&[tcp.clone(), no_desktop], EXE, &needs(), Category::Private), Coverage::Missing);
1206        let both = FwRule { proto: Proto::Udp, local_ports: PortSpec::parse("5353,29700,47891"), ..rule("u") };
1207        assert_eq!(coverage(&[tcp, both], EXE, &needs(), Category::Private), Coverage::Covered);
1208    }
1209
1210    // Codex P2 on #4151: a rule limited to one local IP counts only for its adapter.
1211    #[test]
1212    fn local_address_scopes_parse_the_forms_windows_uses() {
1213        assert_eq!(LocalScope::parse(""), LocalScope::Any);
1214        assert_eq!(LocalScope::parse("*"), LocalScope::Any);
1215        assert_eq!(LocalScope::parse("LocalSubnet"), LocalScope::Any);
1216        let ip = |s: &str| s.parse::<Ipv4Addr>().unwrap();
1217        let one = LocalScope::parse("192.168.1.26");
1218        assert!(one.applies_to(&[ip("192.168.1.26")]) && !one.applies_to(&[ip("192.168.1.27")]));
1219        let net = LocalScope::parse("192.168.1.0/24, 10.0.0.5");
1220        assert!(net.applies_to(&[ip("192.168.1.200")]) && net.applies_to(&[ip("10.0.0.5")]));
1221        assert!(!net.applies_to(&[ip("192.168.2.1")]));
1222        let masked = LocalScope::parse("172.17.16.0/255.255.255.0");
1223        assert!(masked.applies_to(&[ip("172.17.16.1")]) && !masked.applies_to(&[ip("172.17.17.1")]));
1224        let range = LocalScope::parse("192.168.1.10-192.168.1.20");
1225        assert!(range.applies_to(&[ip("192.168.1.15")]) && !range.applies_to(&[ip("192.168.1.21")]));
1226        // Keywords and junk match nothing; an IPv6-only list matches no IPv4 adapter.
1227        for bad in ["DHCP", "Defaultgateway", "192.168.1", "1.2.3.4/33", "9-1", "10.0.0.1-bad"] {
1228            assert_eq!(LocalScope::parse(bad), LocalScope::Unparseable, "{bad}");
1229        }
1230        assert!(!LocalScope::parse("fe80::1").applies_to(&[ip("192.168.1.26")]));
1231        // The adapter's own addresses decide, any one is enough.
1232        assert!(one.applies_to(&[ip("10.9.9.9"), ip("192.168.1.26")]));
1233        assert!(!one.applies_to(&[]));
1234    }
1235
1236    #[test]
1237    fn an_address_scoped_allow_covers_only_the_adapter_that_owns_the_address() {
1238        let scoped = |name: &str| FwRule {
1239            local_addresses: LocalScope::parse("192.168.1.26"),
1240            program: Some(EXE.to_string()),
1241            ..rule(name)
1242        };
1243        let rules = vec![scoped("a")];
1244        let owner = adapter("Ethernet", Some(Category::Private)); // 192.168.1.26
1245        let other = Adapter { ipv4: vec!["10.0.0.5".parse().unwrap()], ..adapter("Wi-Fi", Some(Category::Private)) };
1246        assert_eq!(adapter_state(&rules, EXE, &needs(), &owner), AdapterState::Covered);
1247        assert_eq!(adapter_state(&rules, EXE, &needs(), &other), AdapterState::NeedsSetup);
1248    }
1249
1250    #[test]
1251    fn an_address_scoped_block_does_not_block_other_adapters() {
1252        let allow = program_rule(EXE, Proto::Any, ALL, true);
1253        let block = FwRule { local_addresses: LocalScope::parse("10.0.0.5"), ..program_rule(EXE, Proto::Any, ALL, false) };
1254        let rules = vec![allow, block];
1255        let ethernet = adapter("Ethernet", Some(Category::Private)); // 192.168.1.26
1256        let wifi = Adapter { ipv4: vec!["10.0.0.5".parse().unwrap()], ..adapter("Wi-Fi", Some(Category::Private)) };
1257        assert_eq!(adapter_state(&rules, EXE, &needs(), &ethernet), AdapterState::Covered);
1258        assert_eq!(adapter_state(&rules, EXE, &needs(), &wifi), AdapterState::Blocked);
1259    }
1260
1261    // Codex P2 on #4151: an unreadable rule may be the block that decides the verdict.
1262    #[test]
1263    fn an_unreadable_rule_stops_the_snapshot_from_claiming_ok() {
1264        let snap = Snapshot {
1265            rules: vec![program_rule(EXE, Proto::Any, PROFILE_PRIVATE, true)],
1266            adapters: vec![adapter("Ethernet", Some(Category::Private))],
1267            local_rules_ignored: false,
1268            profiles: Profiles::default(),
1269            unreadable_rules: 0,
1270        };
1271        assert_eq!(report(&snap, EXE, &needs()).status, FirewallStatus::Ok);
1272
1273        let hidden = Snapshot { unreadable_rules: 1, ..snap.clone() };
1274        let r = report(&hidden, EXE, &needs());
1275        assert_eq!(r.status, FirewallStatus::Unknown, "coverage cannot be proven");
1276        assert_eq!(r.per_adapter[0].1, AdapterState::Covered, "the adapter-level reading is unchanged");
1277
1278        // A missing allow stays a warning: an unreadable rule does not make it less missing.
1279        let none = Snapshot { rules: vec![], unreadable_rules: 3, ..snap };
1280        assert_eq!(report(&none, EXE, &needs()).status, FirewallStatus::NeedsSetup);
1281    }
1282
1283    // ReAgent on #4151: skipping a block we cannot evaluate leans toward Covered.
1284    #[test]
1285    fn a_block_that_might_apply_cannot_be_skipped_toward_covered() {
1286        let allow = program_rule(EXE, Proto::Any, ALL, true);
1287        let block = || program_rule(EXE, Proto::Any, ALL, false);
1288        let cases = [
1289            // The review's example: a Block limited to the Wireless interface type,
1290            // next to an any-interface Allow, while Windows blocks that adapter.
1291            ("interface-scoped", FwRule { interface_scoped: true, ..block() }),
1292            ("restricted", FwRule { restricted: true, ..block() }),
1293            ("unparseable ports", FwRule { local_ports: PortSpec::Unparseable, ..block() }),
1294            ("unparseable local addresses", FwRule { local_addresses: LocalScope::Unparseable, ..block() }),
1295        ];
1296        for (label, b) in cases {
1297            let rules = vec![allow.clone(), b];
1298            assert_eq!(coverage(&rules, EXE, &needs(), Category::Private), Coverage::Uncertain, "{label}");
1299            let a = adapter("Ethernet", Some(Category::Private));
1300            assert_eq!(adapter_state(&rules, EXE, &needs(), &a), AdapterState::Unknown, "{label}");
1301        }
1302        let snap = Snapshot {
1303            rules: vec![allow.clone(), FwRule { interface_scoped: true, ..block() }],
1304            adapters: vec![adapter("Ethernet", Some(Category::Private))],
1305            ..Snapshot::default()
1306        };
1307        assert_eq!(report(&snap, EXE, &needs()).status, FirewallStatus::Unknown);
1308    }
1309
1310    #[test]
1311    fn a_block_that_cannot_apply_is_still_ignored() {
1312        let allow = program_rule(EXE, Proto::Any, ALL, true);
1313        for no in [
1314            FwRule { enabled: false, ..program_rule(EXE, Proto::Any, ALL, false) },
1315            FwRule { inbound: false, ..program_rule(EXE, Proto::Any, ALL, false) },
1316            program_rule(OLD_EXE, Proto::Any, ALL, false),
1317            program_rule(EXE, Proto::Any, PROFILE_PUBLIC, false),
1318            FwRule { proto: Proto::Other, ..program_rule(EXE, Proto::Any, ALL, false) },
1319            // A block for specific remote addresses does not block LAN peers in general.
1320            FwRule { remote: Remote::Other, ..program_rule(EXE, Proto::Any, ALL, false) },
1321            // Ports that exclude ours are settled, not uncertain.
1322            FwRule { local_ports: PortSpec::parse("80"), ..program_rule(EXE, Proto::Any, ALL, false) },
1323            FwRule { local_addresses: LocalScope::parse("10.9.9.9"), ..program_rule(EXE, Proto::Any, ALL, false) },
1324        ] {
1325            let rules = vec![allow.clone(), no.clone()];
1326            assert_eq!(coverage(&rules, EXE, &needs(), Category::Private), Coverage::Covered, "{no:?}");
1327        }
1328    }
1329
1330    #[test]
1331    fn an_uncertain_block_does_not_make_a_missing_allow_less_missing() {
1332        let uncertain = FwRule { interface_scoped: true, ..program_rule(EXE, Proto::Any, ALL, false) };
1333        assert_eq!(coverage(&[uncertain], EXE, &needs(), Category::Private), Coverage::Missing);
1334    }
1335
1336    #[test]
1337    fn a_certain_block_still_wins_over_an_uncertain_one() {
1338        let rules = vec![
1339            program_rule(EXE, Proto::Any, ALL, true),
1340            FwRule { interface_scoped: true, ..program_rule(EXE, Proto::Any, ALL, false) },
1341            program_rule(EXE, Proto::Tcp, PROFILE_PRIVATE, false),
1342        ];
1343        assert_eq!(coverage(&rules, EXE, &needs(), Category::Private), Coverage::Blocked);
1344    }
1345
1346    #[test]
1347    fn wire_names_are_the_frontend_contract() {
1348        assert_eq!(FirewallStatus::Ok.wire(), "ok");
1349        assert_eq!(FirewallStatus::NeedsSetup.wire(), "needs-setup");
1350        assert_eq!(FirewallStatus::Blocked.wire(), "blocked");
1351        assert_eq!(FirewallStatus::PublicNetwork.wire(), "public-network");
1352        assert_eq!(FirewallStatus::Managed.wire(), "managed");
1353        assert_eq!(FirewallStatus::Unknown.wire(), "unknown");
1354    }
1355}