diff --git a/crates/minimal-tui/src/render.rs b/crates/minimal-tui/src/render.rs index 333287e90c..aca319b954 100644 --- a/crates/minimal-tui/src/render.rs +++ b/crates/minimal-tui/src/render.rs @@ -483,11 +483,14 @@ fn render_policy(model: &Model, key: &SessionKey, frame: &mut Frame, area: Rect) fn policy_lines(model: &Model, key: &SessionKey) -> Vec> { let detail = model.details.get(key); let record = detail.and_then(|d| d.record.as_ref()); + let network = record.map(|r| r.network); let mut lines: Vec = Vec::new(); - if record.is_some() && record.map(|r| r.network) != Some(sessions::NetworkMode::OwnIp) { + if network == Some(sessions::NetworkMode::NoNet) { + // A none box has no network, so it can carry no egress or ingress + // declaration at all — nothing here would describe anything real. lines.push(Line::styled( - "No network policy (HostNet/NoNet)", + "No network policy (NoNet)", Style::default().fg(Color::Gray), )); } else { @@ -517,28 +520,43 @@ fn policy_lines(model: &Model, key: &SessionKey) -> Vec> { .join(", ") ))), } + // The denied ranges are subtractive — carved out of + // what the allow fields admit — so unlike the allow + // fields an unset row means "nothing denied", not + // "allow all". + match &egress.deny_subnets { + None => lines.push(Line::raw(" deny subnets (none)")), + Some(subnets) => lines + .push(Line::raw(format!(" deny subnets {}", subnets.join(", ")))), + } } } - lines.push(Line::styled( - "ingress", - Style::default().add_modifier(Modifier::BOLD), - )); - match &policy.ingress { - None => lines.push(Line::raw(" deny all")), - Some(ingress) => { - if ingress.port_mappings.is_empty() - && ingress.dynamic_allowed_range.is_none() - { - lines.push(Line::raw(" deny all")); - } - for mapping in &ingress.port_mappings { - lines.push(Line::raw(format!( - " {} :{} → :{}", - mapping.proto, mapping.external_port, mapping.internal_port - ))); - } - if let Some((lo, hi)) = ingress.dynamic_allowed_range { - lines.push(Line::raw(format!(" dynamic ports {lo}–{hi}"))); + // Ingress is an own-address surface: the switch's static + // forwarder is the only per-session ingress minimald applies, + // and a host-address box shares its host's namespace, so + // there is no per-session ingress policy to show for it. + if network != Some(sessions::NetworkMode::HostNet) { + lines.push(Line::styled( + "ingress", + Style::default().add_modifier(Modifier::BOLD), + )); + match &policy.ingress { + None => lines.push(Line::raw(" deny all")), + Some(ingress) => { + if ingress.port_mappings.is_empty() + && ingress.dynamic_allowed_range.is_none() + { + lines.push(Line::raw(" deny all")); + } + for mapping in &ingress.port_mappings { + lines.push(Line::raw(format!( + " {} :{} → :{}", + mapping.proto, mapping.external_port, mapping.internal_port + ))); + } + if let Some((lo, hi)) = ingress.dynamic_allowed_range { + lines.push(Line::raw(format!(" dynamic ports {lo}–{hi}"))); + } } } } diff --git a/crates/minimal-tui/tests/snapshots.rs b/crates/minimal-tui/tests/snapshots.rs index 2c2051cc6a..6d650258d9 100644 --- a/crates/minimal-tui/tests/snapshots.rs +++ b/crates/minimal-tui/tests/snapshots.rs @@ -212,6 +212,7 @@ fn detail_pane_with_policy() { allow_subnets: Some(vec!["10.0.0.0/8".to_string()]), allow_dns_hosts: None, allow_protocols: None, + deny_subnets: Some(vec!["192.168.0.0/16".to_string()]), }), Some(sessions::IngressPolicy { port_mappings: vec![sessions::PortMapping { diff --git a/crates/minimal-tui/tests/snapshots/snapshots__detail_pane_with_policy.snap b/crates/minimal-tui/tests/snapshots/snapshots__detail_pane_with_policy.snap index 5084e3f878..98597679b2 100644 --- a/crates/minimal-tui/tests/snapshots/snapshots__detail_pane_with_policy.snap +++ b/crates/minimal-tui/tests/snapshots/snapshots__detail_pane_with_policy.snap @@ -1,5 +1,6 @@ --- source: crates/minimal-tui/tests/snapshots.rs +assertion_line: 230 expression: render(&mut model) --- "┌──────────────────────────────┐┌ api-staging · 00000000 ──────────────────────────────────────────┐" @@ -12,6 +13,7 @@ expression: render(&mut model) "│ ││ subnets 10.0.0.0/8 │" "│ ││ dns hosts allow all │" "│ ││ protocols allow all │" +"│ ││ deny subnets 192.168.0.0/16 │" "│ ││ ingress │" "│ ││ tcp :8080 → :80 │" "│ ││ ─ Preview (live screen snapshot) ─────────────────────────────── │" @@ -29,6 +31,5 @@ expression: render(&mut model) "│ ││ │" "│ ││ │" "│ ││ │" -"│ ││ │" "└──────────────────────────────┘└──────────────────────────────────────────────────────────────────┘" " ↑↓ move · / filter · enter attach · d destroy · r rename · n new · q quit " diff --git a/crates/minimal/src/cli.rs b/crates/minimal/src/cli.rs index 4472ec7318..7a8e338089 100644 --- a/crates/minimal/src/cli.rs +++ b/crates/minimal/src/cli.rs @@ -462,6 +462,26 @@ pub struct ActivateArgs { /// tcp). Repeatable. Requires `--network own_ip`. #[arg(long = "ingress", value_name = "EXT:INT[/PROTO]")] pub ingress: Vec, + /// Allowed destination subnets in CIDR form (`egress.allow_subnets`), + /// e.g. `10.0.0.0/8`. Repeatable; unset means allow-all subnets. Valid on + /// an own-address (`--network own_ip`) or host-address + /// (`--network host_ip`) box; a none box rejects the whole egress + /// declaration. + #[arg(long = "allow-subnets", value_name = "CIDR")] + pub allow_subnets: Vec, + /// Allowed destination DNS hostnames (`egress.allow_dns_hosts`), e.g. + /// `github.com`. Repeatable; unset means allow-all hosts. + #[arg(long = "allow-dns-hosts", value_name = "HOST")] + pub allow_dns_hosts: Vec, + /// Allowed outbound transport protocols (`egress.allow_protocols`): + /// tcp, udp, or icmp. Repeatable; unset means allow all protocols. + #[arg(long = "allow-protocols", value_name = "PROTO")] + pub allow_protocols: Vec, + /// Denied destination subnets in CIDR form (`egress.deny_subnets`), + /// subtracted from the allowed set. Repeatable; unset means nothing is + /// denied. + #[arg(long = "deny-subnets", value_name = "CIDR")] + pub deny_subnets: Vec, /// Apply the named loadout from `/minimal/loadouts/.toml`. /// Repeatable. If any `--loadout` is specified, defaults from /// `[loadouts].default_loadouts` in the client config are ignored. @@ -610,6 +630,21 @@ pub(crate) fn parse_ingress_proto(proto: &str) -> Result` spec into an [`sessions::IpProto`]. +/// Egress rules name any transport the policy type carries, so unlike the +/// ingress parser (whose vocabulary is gvproxy's static forwarder's), icmp is +/// accepted here. +pub(crate) fn parse_egress_proto(proto: &str) -> Result { + match proto.to_ascii_lowercase().as_str() { + "tcp" => Ok(sessions::IpProto::Tcp), + "udp" => Ok(sessions::IpProto::Udp), + "icmp" => Ok(sessions::IpProto::Icmp), + other => Err(anyhow::anyhow!( + "egress: unsupported protocol '{other}' (use tcp, udp, or icmp)" + )), + } +} + #[derive(Debug, Args)] pub struct AttachArgs { /// Session identifier (UUID or session name). When omitted, `min session attach` diff --git a/crates/minimal/src/cmd/list.rs b/crates/minimal/src/cmd/list.rs index 4c2d537822..d5e0ceae1d 100644 --- a/crates/minimal/src/cmd/list.rs +++ b/crates/minimal/src/cmd/list.rs @@ -65,6 +65,10 @@ pub(crate) fn bare_activate_args() -> ActivateArgs { sync: None, network: CliNetworkMode::HostNet, ingress: Vec::new(), + allow_subnets: Vec::new(), + allow_dns_hosts: Vec::new(), + allow_protocols: Vec::new(), + deny_subnets: Vec::new(), loadout: Vec::new(), no_loadouts: false, no_hooks: false, diff --git a/crates/minimal/src/cmd/session.rs b/crates/minimal/src/cmd/session.rs index 30019339d5..5084e781ab 100644 --- a/crates/minimal/src/cmd/session.rs +++ b/crates/minimal/src/cmd/session.rs @@ -59,8 +59,25 @@ pub(crate) async fn activate_session( let mapping = parse_ingress_mapping(spec)?; port_mappings.push(mapping); } + let mut allow_protocols = Vec::with_capacity(args.allow_protocols.len()); + for spec in &args.allow_protocols { + allow_protocols.push(parse_egress_proto(spec)?); + } + // Any egress flag makes the declaration; a field with no values stays + // `None` — its allow-all/none-denied default — so `--deny-subnets` alone + // records an allow-all policy that denies one range. + let has_egress = !args.allow_subnets.is_empty() + || !allow_protocols.is_empty() + || !args.allow_dns_hosts.is_empty() + || !args.deny_subnets.is_empty(); + let egress = has_egress.then_some(sessions::EgressPolicy { + allow_subnets: (!args.allow_subnets.is_empty()).then(|| args.allow_subnets.clone()), + allow_dns_hosts: (!args.allow_dns_hosts.is_empty()).then(|| args.allow_dns_hosts.clone()), + allow_protocols: (!allow_protocols.is_empty()).then_some(allow_protocols), + deny_subnets: (!args.deny_subnets.is_empty()).then(|| args.deny_subnets.clone()), + }); let policy = sessions::SessionPolicy { - egress: None, + egress, ingress: (!port_mappings.is_empty()).then_some(sessions::IngressPolicy { port_mappings, dynamic_allowed_range: None, @@ -747,6 +764,10 @@ pub(crate) async fn activate_new_for_attach(global: &GlobalArgs) -> Result<(), a sync: None, network: CliNetworkMode::HostNet, ingress: Vec::new(), + allow_subnets: Vec::new(), + allow_dns_hosts: Vec::new(), + allow_protocols: Vec::new(), + deny_subnets: Vec::new(), loadout: Vec::new(), no_loadouts: false, no_hooks: false, @@ -857,7 +878,7 @@ pub(crate) fn exit_code_of(status: std::process::ExitStatus) -> i32 { .unwrap_or(1) } -/// Print the effective networking policy for a session as JSON. +/// Print the effective networking rules for a session. pub async fn cmd_session_policy( global: &GlobalArgs, args: PolicyArgs, @@ -866,6 +887,12 @@ pub async fn cmd_session_policy( let mut client = connect_daemon(global).await?; + // The policy reply carries only the rules, but the ingress block is + // suppressed for host-address sessions (see [`format_policy`]), so the + // command also resolves the record the policy rides on for its network + // mode. + let record = resolve_session(&mut client, &args.session).await?; + use minimald_rpc::{GetSessionPolicy, GetSessionPolicyRequest}; let lookup: GetSessionPolicyRequest = SessionLookup::parse(&args.session).into(); @@ -876,9 +903,9 @@ pub async fn cmd_session_policy( match resp { minimald_rpc::Errorable::Ok(policy) => { - let json = - serde_json_lenient::to_string(&policy).context("Failed to serialize policy")?; - println!("{json}"); + let mut out = std::io::stdout(); + format_policy(&mut out, &policy, record.network)?; + out.flush().context("Failed to write policy")?; Ok(()) } minimald_rpc::Errorable::Err { error } => { @@ -887,6 +914,98 @@ pub async fn cmd_session_policy( } } +/// Render a session policy as its effective rules: each egress dimension +/// resolved to its list or its default (`allow all`; `deny subnets` reads +/// `(none)` when nothing is denied), the ingress mappings spelled out. +/// `network` is the session's network mode, and the modes without a surface +/// to describe are held to the TUI's detail pane: a none box has no network +/// at all, so it prints the pane's one-line note in place of both blocks +/// (`allow all` egress would claim a reach a box with no network does not +/// have), and a host-address session shares its host's namespace, so it has +/// no per-session ingress policy to show and the block is omitted entirely. +/// Shared by `min session policy`'s printer and the integration +/// test that pins the rendering (NET-061). +pub fn format_policy( + out: &mut impl std::io::Write, + policy: &sessions::SessionPolicy, + network: sessions::NetworkMode, +) -> Result<(), anyhow::Error> { + // A none box has no network, so it can carry no egress or ingress + // declaration at all — nothing the blocks print would describe anything + // real (the same case the TUI's detail pane replaces with this note). + if network == sessions::NetworkMode::NoNet { + writeln!(out, "No network policy (NoNet)")?; + return Ok(()); + } + writeln!(out, "egress")?; + match &policy.egress { + None => writeln!(out, " allow all")?, + Some(egress) => { + write_rules(out, "subnets", egress.allow_subnets.as_ref(), "allow all")?; + write_rules( + out, + "dns hosts", + egress.allow_dns_hosts.as_ref(), + "allow all", + )?; + match &egress.allow_protocols { + None => writeln!(out, " protocols allow all")?, + Some(protos) => writeln!( + out, + " protocols {}", + protos + .iter() + .map(|p| p.to_string()) + .collect::>() + .join(", ") + )?, + } + write_rules(out, "deny subnets", egress.deny_subnets.as_ref(), "(none)")?; + } + } + // Ingress is an own-address surface: the switch's static forwarder is the + // only per-session ingress minimald applies, and a host-address box + // shares its host's namespace, so there is no per-session ingress policy + // to show for it — "deny all" there would claim a deny-rule exists. + if network != sessions::NetworkMode::HostNet { + writeln!(out, "ingress")?; + match &policy.ingress { + None => writeln!(out, " deny all")?, + Some(ingress) => { + if ingress.port_mappings.is_empty() && ingress.dynamic_allowed_range.is_none() { + writeln!(out, " deny all")?; + } + for mapping in &ingress.port_mappings { + writeln!( + out, + " {} :{} → :{}", + mapping.proto, mapping.external_port, mapping.internal_port + )?; + } + if let Some((lo, hi)) = ingress.dynamic_allowed_range { + writeln!(out, " dynamic ports {lo}–{hi}")?; + } + } + } + } + Ok(()) +} + +/// One egress rule row: the CIDR or hostname list, or the default the policy +/// resolves to when the dimension is unset. +fn write_rules( + out: &mut impl std::io::Write, + label: &str, + rules: Option<&Vec>, + default: &str, +) -> Result<(), anyhow::Error> { + match rules { + None => writeln!(out, " {label} {default}")?, + Some(rules) => writeln!(out, " {label} {}", rules.join(", "))?, + } + Ok(()) +} + /// Register a session as an SSH remote in Zed's `settings.json`. /// /// Zed drives its own `ssh` for remote projects, so the entry has to carry the diff --git a/crates/minimal/tests/cli.rs b/crates/minimal/tests/cli.rs index 45ca89224c..32ed109b4b 100644 --- a/crates/minimal/tests/cli.rs +++ b/crates/minimal/tests/cli.rs @@ -271,6 +271,10 @@ async fn activate_creates_session() { sync: Some(SyncMode::Tarball), network: CliNetworkMode::NoNet, ingress: vec![], + allow_subnets: vec![], + allow_dns_hosts: vec![], + allow_protocols: vec![], + deny_subnets: vec![], loadout: vec![], no_loadouts: false, no_hooks: false, @@ -314,6 +318,10 @@ async fn activate_uploads_project_files() { sync: Some(SyncMode::Tarball), network: CliNetworkMode::NoNet, ingress: vec![], + allow_subnets: vec![], + allow_dns_hosts: vec![], + allow_protocols: vec![], + deny_subnets: vec![], loadout: vec![], no_loadouts: false, no_hooks: false, @@ -396,6 +404,10 @@ async fn activate_uses_repo_dir_when_no_positional_path() { sync: Some(SyncMode::Tarball), network: CliNetworkMode::NoNet, ingress: vec![], + allow_subnets: vec![], + allow_dns_hosts: vec![], + allow_protocols: vec![], + deny_subnets: vec![], loadout: vec![], no_loadouts: false, no_hooks: false, @@ -781,6 +793,126 @@ async fn session_policy_succeeds() { .unwrap(); } +/// `min session policy` shows the effective egress rules (NET-061): the four +/// egress fields the session was activated with, each unset dimension +/// resolved to its default instead of a bare `null`. The policy is stored +/// through the daemon and fetched the way the command fetches it; +/// `format_policy` is the rendering the command prints. The same egress on a +/// host-address box is still shown, but with no ingress block, and a none +/// box shows no blocks at all — just the note the TUI shows in their place. +#[tokio::test] +async fn policy_shows_effective_egress() { + let (daemon, args) = setup().await; + let egress = sessions::EgressPolicy { + allow_subnets: Some(vec!["10.0.0.0/8".to_string()]), + allow_dns_hosts: Some(vec!["github.com".to_string()]), + allow_protocols: Some(vec![sessions::IpProto::Tcp]), + deny_subnets: Some(vec!["169.254.169.254/32".to_string()]), + }; + let session_id = create_session_with_policy( + &daemon, + "egress-policy", + sessions::NetworkMode::OwnIp, + sessions::SessionPolicy::new(Some(egress.clone()), None), + ) + .await; + + let mut client = connect_daemon(&args).await.unwrap(); + use minimald_rpc::{GetSessionPolicy, GetSessionPolicyRequest}; + let resp = client + .oneshot_rpc::(GetSessionPolicyRequest::Id(session_id)) + .await + .unwrap(); + let policy = match resp { + minimald_rpc::Errorable::Ok(policy) => policy, + minimald_rpc::Errorable::Err { error } => panic!("GetSessionPolicy failed: {error}"), + }; + assert_eq!( + policy.egress, + Some(egress.clone()), + "the stored egress must survive the record round trip" + ); + + let mut out = Vec::new(); + format_policy(&mut out, &policy, sessions::NetworkMode::OwnIp).unwrap(); + let text = String::from_utf8(out).unwrap(); + assert!( + text.contains("subnets 10.0.0.0/8"), + "allowed subnets missing:\n{text}" + ); + assert!( + text.contains("dns hosts github.com"), + "allowed hosts missing:\n{text}" + ); + assert!( + text.contains("protocols tcp"), + "allowed protocols missing:\n{text}" + ); + assert!( + text.contains("deny subnets 169.254.169.254/32"), + "denied subnets missing:\n{text}" + ); + + // The same egress is accepted on a host-address box (NET-120), but the + // ingress block is suppressed there: a host-address session shares its + // host's namespace, so minimald applies no per-session ingress to it and + // a `deny all` row would claim a deny-rule that does not exist. The TUI's + // detail pane suppresses the block for the same reason. + let host_id = create_session_with_policy( + &daemon, + "egress-policy-host", + sessions::NetworkMode::HostNet, + sessions::SessionPolicy::new(Some(egress.clone()), None), + ) + .await; + let resp = client + .oneshot_rpc::(GetSessionPolicyRequest::Id(host_id)) + .await + .unwrap(); + let policy = match resp { + minimald_rpc::Errorable::Ok(policy) => policy, + minimald_rpc::Errorable::Err { error } => panic!("GetSessionPolicy failed: {error}"), + }; + let mut out = Vec::new(); + format_policy(&mut out, &policy, sessions::NetworkMode::HostNet).unwrap(); + let text = String::from_utf8(out).unwrap(); + assert!( + text.contains("subnets 10.0.0.0/8"), + "the host-address egress rules are still shown:\n{text}" + ); + assert!( + !text.contains("ingress"), + "a host-address session has no per-session ingress policy to show:\n{text}" + ); + + // A none box has no network, so it can carry no egress or ingress + // declaration at all — the whole policy is replaced by the one-line + // note the TUI's detail pane shows, since `egress / allow all` there + // would claim a reach a box with no network does not have. + let none_id = create_session_with_policy( + &daemon, + "egress-policy-none", + sessions::NetworkMode::NoNet, + sessions::SessionPolicy::default(), + ) + .await; + let resp = client + .oneshot_rpc::(GetSessionPolicyRequest::Id(none_id)) + .await + .unwrap(); + let policy = match resp { + minimald_rpc::Errorable::Ok(policy) => policy, + minimald_rpc::Errorable::Err { error } => panic!("GetSessionPolicy failed: {error}"), + }; + let mut out = Vec::new(); + format_policy(&mut out, &policy, sessions::NetworkMode::NoNet).unwrap(); + let text = String::from_utf8(out).unwrap(); + assert_eq!( + text, "No network policy (NoNet)\n", + "a none session prints the note in place of both blocks:\n{text}" + ); +} + // --- hostname routing warning (NET-020/NET-021/NET-022) --- // // The startup retry lives in `minimald::server` behind the Linux gate with the @@ -1021,14 +1153,33 @@ async fn create_session_at( daemon: &common::TestDaemon, name: &str, project_path: paths::HostAbsPath, +) -> SessionId { + create_session_with( + daemon, + name, + project_path, + sessions::NetworkMode::NoNet, + sessions::SessionPolicy::default(), + ) + .await +} + +/// Like [`create_session`] but with the network mode and policy the caller +/// chooses, so a test can store a policy the CLI surfaces must render. +async fn create_session_with( + daemon: &common::TestDaemon, + name: &str, + project_path: paths::HostAbsPath, + network: sessions::NetworkMode, + policy: sessions::SessionPolicy, ) -> SessionId { let mut client = daemon.server.connect().await; let config = minimald_rpc::SessionConfig { name: Some(name.to_string()), project_path, - network: sessions::NetworkMode::NoNet, - policy: Default::default(), + network, + policy, hooks_enabled: true, attrs: Default::default(), }; @@ -1075,3 +1226,17 @@ async fn create_session_at( } id } + +/// Like [`create_session`] but with the network mode and policy the caller +/// chooses. +async fn create_session_with_policy( + daemon: &common::TestDaemon, + name: &str, + network: sessions::NetworkMode, + policy: sessions::SessionPolicy, +) -> SessionId { + let project_path = + camino::Utf8PathBuf::from_path_buf(std::env::current_dir().unwrap()).unwrap(); + let abs_path = paths::HostAbsPath::try_new(project_path).unwrap(); + create_session_with(daemon, name, abs_path, network, policy).await +} diff --git a/crates/minimald/src/rpc.rs b/crates/minimald/src/rpc.rs index c3756ca5b6..5a77e44b63 100644 --- a/crates/minimald/src/rpc.rs +++ b/crates/minimald/src/rpc.rs @@ -208,6 +208,38 @@ async fn serve_get_session_record( /// anonymous session, and an absent field reads like a logging bug. const ANONYMOUS_SESSION: &str = ""; +/// The egress rule counts a session config parses to, one per egress field. +/// Logged beside the record the daemon stores at session start, they are the +/// diagnostic for what a session actually activated with: a count of `0` +/// means the field — or the whole `egress` section — carries no rules. +#[derive(Debug, Clone, Copy)] +struct EgressRuleCounts { + allow_subnets: usize, + allow_protocols: usize, + allow_dns_hosts: usize, + deny_subnets: usize, +} + +impl EgressRuleCounts { + fn of(policy: &minimald_rpc::SessionPolicy) -> Self { + let egress = policy.egress.as_ref(); + Self { + allow_subnets: egress + .and_then(|e| e.allow_subnets.as_ref()) + .map_or(0, Vec::len), + allow_protocols: egress + .and_then(|e| e.allow_protocols.as_ref()) + .map_or(0, Vec::len), + allow_dns_hosts: egress + .and_then(|e| e.allow_dns_hosts.as_ref()) + .map_or(0, Vec::len), + deny_subnets: egress + .and_then(|e| e.deny_subnets.as_ref()) + .map_or(0, Vec::len), + } + } +} + /// `CreateSession`: allocates the session's record and brings its actor /// up, replying with the assigned id. The loadout is composed separately, /// by the `ConfigureLoadout` that follows. @@ -236,6 +268,10 @@ async fn serve_create_session( // manager: the success record below needs it, and the reply // carries only the assigned id. let session_name = req.config.name.clone(); + // Read the egress rule counts off the config for the same reason: + // the manager consumes it, and the stored record's egress is what + // the counts below report beside the "session created" line. + let egress_counts = EgressRuleCounts::of(&req.config.policy); Ok(match mngr.create_session(req.config, ssh_username).await { Ok(id) => { @@ -247,6 +283,10 @@ async fn serve_create_session( tracing::info!( session_id = %id, session_name = session_name.as_deref().unwrap_or(ANONYMOUS_SESSION), + egress_allow_subnets = egress_counts.allow_subnets, + egress_allow_protocols = egress_counts.allow_protocols, + egress_allow_dns_hosts = egress_counts.allow_dns_hosts, + egress_deny_subnets = egress_counts.deny_subnets, "session created" ); Errorable::Ok(minimald_rpc::CreateSessionResponse { @@ -2687,6 +2727,7 @@ mod tests { allow_subnets: Some(vec!["10.0.0.0/8".to_string()]), allow_dns_hosts: None, allow_protocols: None, + deny_subnets: Some(vec!["192.168.0.0/16".to_string()]), }; let created_id = client .call::(&CreateSessionRequest { @@ -2788,19 +2829,22 @@ mod tests { let server = TestServer::new().await; let mut client = server.connect().await; - // R2.1: an egress policy on a non-`OwnIp` PTask is rejected at - // declaration time, so the invalid session is never stored. + // NET-065: an egress policy on a none (`NoNet`) box is rejected at + // declaration time, so the invalid session is never stored. Egress on + // a host-address box is accepted (NET-120), so `NoNet` is the only + // mode that still refuses it. let egress = EgressPolicy { allow_subnets: Some(vec!["10.0.0.0/8".to_string()]), allow_dns_hosts: None, allow_protocols: None, + deny_subnets: None, }; let resp = client .call::(&CreateSessionRequest { config: minimald_rpc::SessionConfig { name: Some("bad-policy".to_string()), project_path: HostAbsPath::try_new("/uwu").unwrap(), - network: NetworkMode::HostNet, + network: NetworkMode::NoNet, policy: SessionPolicy::new(Some(egress), None), hooks_enabled: true, attrs: Default::default(), @@ -2811,7 +2855,8 @@ mod tests { assert_eq!( resp, Errorable::Err { - error: "egress policy is only valid for an own-IP PTask, not HostNet".to_string() + error: "egress policy is only valid for an own-IP or host-address PTask, not NoNet" + .to_string() } ); diff --git a/crates/sessions/src/lib.rs b/crates/sessions/src/lib.rs index 0feb254468..2fc303ac13 100644 --- a/crates/sessions/src/lib.rs +++ b/crates/sessions/src/lib.rs @@ -78,10 +78,13 @@ pub struct PortMapping { pub proto: IpProto, } -/// Effective egress policy for an `OwnIp` `PTask`. +/// Effective egress policy for a session. /// -/// Each field is `None` to mean allow-all for that dimension. Absent `egress` -/// config on a session is equivalent to all-`None` (allow-all). +/// Each `allow_*` field is `None` to mean allow-all for that dimension, and +/// `deny_subnets` is `None` to mean nothing is denied. Absent `egress` config +/// on a session is equivalent to all-`None` (allow-all). A `deny_subnets` +/// entry is subtractive: it carves a range out of what the `allow_*` fields +/// admit, so a rule set is effective only where it is not also denied. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] pub struct EgressPolicy { /// Allowed destination CIDR prefixes; `None` means allow-all subnets. @@ -90,6 +93,9 @@ pub struct EgressPolicy { pub allow_dns_hosts: Option>, /// Allowed IP protocols; `None` means allow all protocols. pub allow_protocols: Option>, + /// Denied destination CIDR prefixes, subtracted from the allowed set; + /// `None` means nothing is denied. + pub deny_subnets: Option>, } impl EgressPolicy { @@ -103,13 +109,27 @@ impl EgressPolicy { /// layer parses it. #[must_use] pub fn first_invalid_subnet(&self) -> Option<&str> { - self.allow_subnets - .as_deref() - .into_iter() - .flatten() - .map(String::as_str) - .find(|cidr| !is_valid_cidr(cidr)) + first_invalid_cidr(self.allow_subnets.as_ref()) } + + /// [`Self::first_invalid_subnet`] for `deny_subnets`, so a denied range is + /// held to the same syntactic check as an allowed one: both are parsed by + /// #553's egress-enforcement layer, so both are named at launch when they + /// do not parse. + #[must_use] + pub fn first_invalid_deny_subnet(&self) -> Option<&str> { + first_invalid_cidr(self.deny_subnets.as_ref()) + } +} + +/// The first entry of an optional CIDR list that is not a syntactically valid +/// prefix, or `None` when every entry parses (or the list is unset/empty). +fn first_invalid_cidr(entries: Option<&Vec>) -> Option<&str> { + entries + .into_iter() + .flatten() + .map(String::as_str) + .find(|cidr| !is_valid_cidr(cidr)) } /// Effective ingress policy for an `OwnIp` `PTask`. @@ -169,9 +189,12 @@ impl SessionPolicy { #[derive(Debug, thiserror::Error, PartialEq, Eq)] #[non_exhaustive] pub enum PolicyError { - /// An egress policy was set on a `PTask` that is not [`NetworkMode::OwnIp`]. - #[error("egress policy is only valid for an own-IP PTask, not {mode:?}")] - EgressRequiresOwnIp { mode: NetworkMode }, + /// An egress policy was set on a [`NetworkMode::NoNet`] `PTask`. An + /// own-address (`OwnIp`) and a host-address (`HostNet`) box both carry a + /// network their egress rules can bound; a none box has none, so there is + /// nothing to enforce the declaration on and it is rejected. + #[error("egress policy is only valid for an own-IP or host-address PTask, not {mode:?}")] + EgressRequiresNetwork { mode: NetworkMode }, /// An ingress policy was set on a `PTask` that is not [`NetworkMode::OwnIp`]. #[error("ingress policy is only valid for an own-IP PTask, not {mode:?}")] IngressRequiresOwnIp { mode: NetworkMode }, @@ -199,6 +222,11 @@ pub enum PolicyError { /// when #553's egress-enforcement layer parses it. #[error("egress allow_subnets entry {cidr:?} is not a valid CIDR prefix")] InvalidSubnet { cidr: String }, + /// An egress `deny_subnets` entry is not a syntactically valid CIDR prefix. + /// Held to the same launch-time check as an `allow_subnets` entry, since + /// both are parsed by #553's egress-enforcement layer. + #[error("egress deny_subnets entry {cidr:?} is not a valid CIDR prefix")] + InvalidDenySubnet { cidr: String }, /// An ingress `dynamic_allowed_range` was given with its lower bound above /// its upper bound (e.g. `(8443, 8000)`). The range is inclusive, so a /// reversed pair describes no ports; rejected at launch so the misconfig is @@ -400,24 +428,30 @@ pub struct Record { impl Record { /// Validates that this record's networking policy is compatible with its - /// network mode (R2.1/R2.3): egress and ingress are only meaningful for an - /// [`NetworkMode::OwnIp`] `PTask`, since `NoNet` has no network and `HostNet` - /// shares the host's, neither of which minimald can apply per-session - /// policy to. Returns an error naming the first incompatible section. + /// network mode (R2.1/R2.3, as amended for host-address egress): an egress + /// policy is accepted on an [`NetworkMode::OwnIp`] and on a + /// [`NetworkMode::HostNet`] `PTask` — both carry a network their egress + /// rules can bound (NET-120) — and rejected only on `NoNet`, which has no + /// network to enforce it on (NET-065). An ingress policy stays + /// `OwnIp`-only, since the switch's static forwarder is the only ingress + /// surface minimald can apply per-session. Returns an error naming the + /// first incompatible section. /// /// # Errors /// - /// Returns [`PolicyError::EgressRequiresOwnIp`] when an egress policy is set - /// on a non-`OwnIp` `PTask`, or [`PolicyError::IngressRequiresOwnIp`] when a - /// non-empty ingress policy is. Returns + /// Returns [`PolicyError::EgressRequiresNetwork`] when an egress policy is + /// set on a none (`NoNet`) `PTask`, or + /// [`PolicyError::IngressRequiresOwnIp`] when a non-empty ingress policy is + /// set on anything but an `OwnIp` `PTask`. Returns /// [`PolicyError::UnsupportedIngressProtocol`] for an ingress mapping whose /// transport gvproxy's forwarder cannot expose, or /// [`PolicyError::PrivilegedPort`] for one that publishes a host port below - /// 1024. For an `OwnIp` `PTask`, returns [`PolicyError::InvalidSubnet`] when - /// an egress `allow_subnets` entry is not a valid CIDR prefix, - /// [`PolicyError::InvalidDynamicRange`] when the ingress - /// `dynamic_allowed_range` lower bound exceeds its upper bound, or - /// [`PolicyError::PrivilegedDynamicRange`] when that lower bound is a + /// 1024. For a `PTask` that accepts egress, returns + /// [`PolicyError::InvalidSubnet`] when an egress `allow_subnets` entry is + /// not a valid CIDR prefix or [`PolicyError::InvalidDenySubnet`] when a + /// `deny_subnets` entry is not, [`PolicyError::InvalidDynamicRange`] when + /// the ingress `dynamic_allowed_range` lower bound exceeds its upper bound, + /// or [`PolicyError::PrivilegedDynamicRange`] when that lower bound is a /// privileged host port (< 1024). pub fn validate_policy(&self) -> Result<(), PolicyError> { // gvproxy's static forwarder only exposes TCP and UDP, so an ingress @@ -446,21 +480,49 @@ impl Record { }) { return Err(PolicyError::PrivilegedPort { external_port }); } - // For an OwnIp PTask egress/ingress are allowed; the only remaining - // check is that each egress allow_subnets entry is a syntactically valid - // CIDR prefix, so a misconfigured subnet is named at launch rather than - // surfacing opaquely when #553's enforcement layer parses it. - if self.network == NetworkMode::OwnIp { - if let Some(bad) = self + // A none box has no network: there is nothing to enforce an egress or + // ingress declaration on, so both are configuration errors (NET-065). + if self.network == NetworkMode::NoNet { + if self.policy.egress.is_some() { + return Err(PolicyError::EgressRequiresNetwork { mode: self.network }); + } + if self .policy - .egress + .ingress .as_ref() - .and_then(EgressPolicy::first_invalid_subnet) + .is_some_and(|ingress| !ingress.is_empty()) { - return Err(PolicyError::InvalidSubnet { - cidr: bad.to_owned(), - }); + return Err(PolicyError::IngressRequiresOwnIp { mode: self.network }); } + return Ok(()); + } + // An own-address and a host-address box both carry a network their + // egress rules can bound (NET-120 accepts the declaration on a + // host-address box), so the syntactic checks run for both: every + // allow and deny entry must be a valid CIDR prefix, so a misconfigured + // subnet is named at launch rather than surfacing opaquely when + // #553's enforcement layer parses it. + if let Some(bad) = self + .policy + .egress + .as_ref() + .and_then(EgressPolicy::first_invalid_subnet) + { + return Err(PolicyError::InvalidSubnet { + cidr: bad.to_owned(), + }); + } + if let Some(bad) = self + .policy + .egress + .as_ref() + .and_then(EgressPolicy::first_invalid_deny_subnet) + { + return Err(PolicyError::InvalidDenySubnet { + cidr: bad.to_owned(), + }); + } + if self.network == NetworkMode::OwnIp { // A reversed dynamic range (lo > hi) describes no ports under the // inclusive semantics, and a privileged lower bound (< 1024) names a // host port the rootless switch cannot publish — the same constraint @@ -482,9 +544,9 @@ impl Record { } return Ok(()); } - if self.policy.egress.is_some() { - return Err(PolicyError::EgressRequiresOwnIp { mode: self.network }); - } + // Host-address box: egress is accepted, but ingress still requires an + // own address — the switch's forwarder is the only per-session ingress + // surface, and a host-address box shares its host's namespace. if self .policy .ingress @@ -550,34 +612,60 @@ mod tests { } #[test] - fn egress_on_host_net_is_rejected() { - // R2.1: an egress section is only valid for an own-IP PTask. + fn egress_on_host_ip_box_accepted() { + // NET-120: an egress section is valid on a host-address box too — its + // declaration is enforced on the box's own cgroup — superseding the + // shipped R2.1 rule that rejected it there. let record = record_with( NetworkMode::HostNet, - SessionPolicy::new(Some(EgressPolicy::default()), None), - ); - assert_eq!( - record.validate_policy(), - Err(PolicyError::EgressRequiresOwnIp { - mode: NetworkMode::HostNet - }) + SessionPolicy::new( + Some(EgressPolicy { + allow_subnets: Some(vec!["10.0.0.0/8".into()]), + deny_subnets: Some(vec!["192.168.0.0/16".into()]), + ..EgressPolicy::default() + }), + None, + ), ); + assert!(record.validate_policy().is_ok()); } #[test] - fn egress_on_no_net_is_rejected() { + fn egress_on_none_box_is_validation_error() { + // NET-065: a none box has no network, so there is nothing to enforce + // an egress declaration on. It is the only mode that rejects egress. let record = record_with( NetworkMode::NoNet, SessionPolicy::new(Some(EgressPolicy::default()), None), ); assert_eq!( record.validate_policy(), - Err(PolicyError::EgressRequiresOwnIp { + Err(PolicyError::EgressRequiresNetwork { mode: NetworkMode::NoNet }) ); } + #[test] + fn spec_accepts_egress_fields() { + // NET-060: the box spec accepts all four egress fields — + // allow_subnets, allow_protocols, allow_dns_hosts and deny_subnets — + // on an own-address box and on a host-address box alike. + let egress = EgressPolicy { + allow_subnets: Some(vec!["10.0.0.0/8".into(), "fd00::/8".into()]), + allow_protocols: Some(vec![IpProto::Tcp, IpProto::Udp]), + allow_dns_hosts: Some(vec!["github.com".into()]), + deny_subnets: Some(vec!["169.254.169.254/32".into()]), + }; + for network in [NetworkMode::OwnIp, NetworkMode::HostNet] { + let record = record_with(network, SessionPolicy::new(Some(egress.clone()), None)); + assert!( + record.validate_policy().is_ok(), + "all four egress fields must validate on {network:?}" + ); + } + } + #[test] fn ingress_mappings_on_host_net_are_rejected() { let ingress = IngressPolicy { @@ -743,6 +831,51 @@ mod tests { assert!(record.validate_policy().is_ok()); } + #[test] + fn invalid_egress_deny_subnet_is_rejected() { + // A deny_subnets entry is held to the same syntactic check as an + // allow_subnets entry, and the check runs on a host-address box too — + // both modes accept egress, so both parse the same rules. + for network in [NetworkMode::OwnIp, NetworkMode::HostNet] { + let egress = EgressPolicy { + deny_subnets: Some(vec!["10.0.0.0/8".into(), "not-a-cidr".into()]), + ..EgressPolicy::default() + }; + let record = record_with(network, SessionPolicy::new(Some(egress), None)); + assert_eq!( + record.validate_policy(), + Err(PolicyError::InvalidDenySubnet { + cidr: "not-a-cidr".into() + }) + ); + } + } + + #[test] + fn egress_on_host_ip_box_rejects_ingress_mappings() { + // Egress is accepted on a host-address box; ingress still requires an + // own address, so a host-address record carrying both is rejected for + // the ingress half, not for the egress it is now allowed to declare. + let ingress = IngressPolicy { + port_mappings: vec![PortMapping { + external_port: 18080, + internal_port: 80, + proto: IpProto::Tcp, + }], + dynamic_allowed_range: None, + }; + let record = record_with( + NetworkMode::HostNet, + SessionPolicy::new(Some(EgressPolicy::default()), Some(ingress)), + ); + assert_eq!( + record.validate_policy(), + Err(PolicyError::IngressRequiresOwnIp { + mode: NetworkMode::HostNet + }) + ); + } + #[test] fn reversed_dynamic_range_is_rejected_on_own_ip() { // A dynamic_allowed_range whose lower bound exceeds its upper bound diff --git a/crates/sessions/src/store.rs b/crates/sessions/src/store.rs index aa59cbe45c..3892b76ad1 100644 --- a/crates/sessions/src/store.rs +++ b/crates/sessions/src/store.rs @@ -1102,13 +1102,15 @@ mod tests { // An OwnIp session carrying a non-default policy, so the round-trip // tests prove a configured policy — the live source for the // GetSessionPolicy RPC — survives a disk round-trip, not just the - // all-`None` default. + // all-`None` default. Every egress field is set, deny_subnets + // included, so a field dropped on write shows up as a diff. network: crate::NetworkMode::OwnIp, policy: crate::SessionPolicy::new( Some(crate::EgressPolicy { allow_subnets: Some(vec!["10.0.0.0/8".to_string()]), allow_dns_hosts: None, allow_protocols: None, + deny_subnets: Some(vec!["192.168.0.0/16".to_string()]), }), None, ), diff --git a/docs/reference/cli-min.md b/docs/reference/cli-min.md index 36d5f02ad5..ad00fc0206 100644 --- a/docs/reference/cli-min.md +++ b/docs/reference/cli-min.md @@ -100,6 +100,14 @@ the current directory). | `--no-hooks` | | Run none of the session's [lifecycle hooks](./loadouts.md#lifecycle_hooks---scripts-at-session-transition-points), from either the loadouts or the project's `minimal.toml`. Recorded on the session, so it applies to the later attach, detach, and destroy transitions too | | `--no-prompt` | | Fail instead of prompting when the daemon surfaces items user policy can't auto-decide; implied when stdin/stderr isn't a TTY | | `--attach` | | Automatically attach after creation | +| `--allow-subnets ` | | Destination subnet the box may reach, in CIDR form (e.g. `10.0.0.0/8`). Repeatable; unset means allow all. Valid on an own-address (`--network own_ip`) or host-address (`--network host_ip`) box; a `--network none` box rejects the whole egress declaration | +| `--allow-dns-hosts ` | | Destination DNS hostname the box may resolve and reach (e.g. `github.com`). Repeatable; unset means allow all | +| `--allow-protocols ` | | Outbound transport protocol the box may use: `tcp`, `udp`, or `icmp`. Repeatable; unset means allow all | +| `--deny-subnets ` | | Destination subnet the box may not reach, in CIDR form — subtracted from what the allow flags admit. Repeatable; unset means nothing is denied | + +Together the four `--allow-*`/`--deny-*` flags form the box's `egress` +declaration; naming any one of them stores it on the session, and `min +session policy` shows what the session ended up with. Activating a path that already has a session is allowed, but warns: `min` names the existing session and creates a second one anyway. With two sessions on one @@ -230,9 +238,36 @@ Renames an existing session. min session policy ``` -Prints the effective networking policy for `SESSION` (a UUID or session -name) as JSON — an object with `egress` and `ingress` fields, each null -when unset. Resolved from the daemon. +Prints the effective networking rules for `SESSION` (a UUID or session +name). Resolved from the daemon, which answers from the policy stored at +activation; each rule line shows what the session ended up with, not just +what was typed. + +The egress block resolves every dimension of the box's `egress` declaration +to its rule or its default: + +``` +egress + subnets 10.0.0.0/8 + dns hosts allow all + protocols tcp, udp + deny subnets 169.254.169.254/32 +``` + +`subnets`, `dns hosts`, and `protocols` each read `allow all` when the +matching flag was not given; `deny subnets` reads `(none)` when nothing is +denied. The ingress block lists the published port mappings the session's +`--ingress` flags declared (or `deny all` when none were), plus the dynamic +port range when one is configured: + +``` +ingress + tcp :8080 → :80 +``` + +A host-address (`--network host_ip`) session prints no ingress block at all: +it shares its host's network namespace, so minimald applies no per-session +ingress to it and there is no rule to state. ### `session hooks`