diff --git a/crates/minimal-tui/src/render.rs b/crates/minimal-tui/src/render.rs index 333287e90c..7b603678c2 100644 --- a/crates/minimal-tui/src/render.rs +++ b/crates/minimal-tui/src/render.rs @@ -517,6 +517,7 @@ fn policy_lines(model: &Model, key: &SessionKey) -> Vec> { .join(", ") ))), } + policy_list(&mut lines, "deny subnets", &egress.deny_subnets); } } lines.push(Line::styled( diff --git a/crates/minimal-tui/tests/snapshots.rs b/crates/minimal-tui/tests/snapshots.rs index 2c2051cc6a..50be77bbd4 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!["10.0.0.0/24".to_string()]), }), Some(sessions::IngressPolicy { port_mappings: vec![sessions::PortMapping { @@ -229,6 +230,41 @@ fn detail_pane_with_policy() { insta::assert_snapshot!(render(&mut model)); } +/// The policy section renders the `deny_subnets` field as part of the +/// effective egress rules. +#[test] +fn policy_lines_show_deny_subnets() { + let mut model = fixed_model(vec![provider( + "host", + vec![entry(1, Some("api-staging"), "/src/api")], + )]); + let key = SessionKey { + provider: "host".to_string(), + id: id(1), + }; + model.details.insert( + key, + Detail { + record: Some(record(Some("api-staging"), NetworkMode::OwnIp)), + policy: Some(sessions::SessionPolicy::new( + Some(sessions::EgressPolicy { + allow_subnets: None, + allow_dns_hosts: None, + allow_protocols: None, + deny_subnets: Some(vec!["192.168.1.0/24".to_string()]), + }), + None, + )), + }, + ); + model.cursor = 1; + let rendered = render(&mut model); + assert!( + rendered.contains("deny subnets 192.168.1.0/24"), + "deny_subnets must appear in the policy section:\n{rendered}" + ); +} + /// Git info from the list RPC renders: the branch in the sidebar row /// (TestBackend text — the glyph is what matters) and the repo root, /// tagged as a worktree, in the detail Info section. 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..917557526f 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 10.0.0.0/24 │" "│ ││ 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/cmd/session.rs b/crates/minimal/src/cmd/session.rs index 2c1279580d..b5eb5f5bd9 100644 --- a/crates/minimal/src/cmd/session.rs +++ b/crates/minimal/src/cmd/session.rs @@ -839,13 +839,29 @@ 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 policy for a session as JSON. pub async fn cmd_session_policy( global: &GlobalArgs, args: PolicyArgs, ) -> Result<(), anyhow::Error> { ensure_daemon(global)?; + let mut out = tokio::io::stdout(); + format_session_policy(&mut out, &args, global).await?; + Ok(()) +} +/// Fetch a session's effective networking policy from the daemon and write it +/// as JSON to `out`. Split from [`cmd_session_policy`] so tests can verify the +/// emitted JSON without capturing the process stdout. +pub async fn format_session_policy( + out: &mut W, + args: &PolicyArgs, + global: &GlobalArgs, +) -> Result<(), anyhow::Error> +where + W: tokio::io::AsyncWrite + Unpin, +{ let mut client = connect_daemon(global).await?; use minimald_rpc::{GetSessionPolicy, GetSessionPolicyRequest}; @@ -860,7 +876,8 @@ pub async fn cmd_session_policy( minimald_rpc::Errorable::Ok(policy) => { let json = serde_json_lenient::to_string(&policy).context("Failed to serialize policy")?; - println!("{json}"); + out.write_all(json.as_bytes()).await?; + out.write_all(b"\n").await?; Ok(()) } minimald_rpc::Errorable::Err { error } => { diff --git a/crates/minimal/src/main.rs b/crates/minimal/src/main.rs index a5dc205fe0..e11d68ff4b 100644 --- a/crates/minimal/src/main.rs +++ b/crates/minimal/src/main.rs @@ -127,10 +127,11 @@ impl std::io::Write for DashLog { /// Whether the command's stdout is a data contract that tracing must not /// pollute, so its logs go to stderr instead. The `completions` handlers emit a /// shell shim on stdout, `session exec` carries only the exec'd -/// command's output, and `task run` / `session run` stream the task's stdout — -/// a log line in any of them would be read as content. A bare `min` (no subcommand) is -/// one too: its non-TTY twin promises an empty stdout to pipelines, and its -/// interactive activate path prints only the session id there. +/// command's output, `task run` / `session run` stream the task's stdout, and +/// `session policy` emits JSON on stdout — a log line in any of them would be +/// read as content. A bare `min` (no subcommand) is one too: its non-TTY twin +/// promises pipelines an empty stdout, and its interactive activate path prints +/// only the session id there. fn stdout_is_data_contract(command: &Option) -> bool { matches!( command, @@ -139,7 +140,8 @@ fn stdout_is_data_contract(command: &Option) -> bool { | minimal::Command::Completions(_) | minimal::Command::Session(minimal::SessionArgs { command: minimal::SessionCommand::Exec(ExecArgs { .. }) - | minimal::SessionCommand::Run(_), + | minimal::SessionCommand::Run(_) + | minimal::SessionCommand::Policy(_), }) | minimal::Command::Task(minimal::TaskArgs { command: minimal::TaskCommand::Run(_), @@ -186,4 +188,16 @@ mod tests { })); assert!(stdout_is_data_contract(&cmd)); } + + /// `min session policy` emits JSON on stdout, so tracing must route to + /// stderr to keep the output parseable. + #[test] + fn session_policy_is_a_stdout_contract() { + let cmd = Some(Command::Session(minimal::SessionArgs { + command: minimal::SessionCommand::Policy(minimal::PolicyArgs { + session: "web".to_string(), + }), + })); + assert!(stdout_is_data_contract(&cmd)); + } } diff --git a/crates/minimal/tests/cli.rs b/crates/minimal/tests/cli.rs index 39f2125d98..97d563cf56 100644 --- a/crates/minimal/tests/cli.rs +++ b/crates/minimal/tests/cli.rs @@ -781,8 +781,142 @@ async fn session_policy_succeeds() { .unwrap(); } +/// NET-061: `min session policy` prints the effective egress rules, including +/// all four fields, for both own-address and host-address boxes. +#[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![minimald_rpc::IpProto::Tcp]), + deny_subnets: Some(vec!["10.0.0.0/24".to_string()]), + }; + + for (name, network) in [ + ("own-ip-policy-cli", sessions::NetworkMode::OwnIp), + ("host-ip-policy-cli", sessions::NetworkMode::HostNet), + ] { + let session_id = + create_session_with_policy(&daemon, name, network, Some(egress.clone())).await; + + let args = daemon.global_args(); + let json = run_session_policy(&args, session_id).await; + let parsed: serde_json_lenient::Value = serde_json_lenient::from_str(&json) + .unwrap_or_else(|_| panic!("policy output must be valid JSON: {json}")); + let egress_json = parsed + .get("egress") + .unwrap_or_else(|| panic!("policy output must contain egress: {json}")); + assert_eq!( + egress_json.get("allow_subnets").and_then(|v| v.as_array()), + Some(&vec![serde_json_lenient::json!("10.0.0.0/8")]), + "allow_subnets must round-trip for {network:?}" + ); + assert_eq!( + egress_json + .get("allow_dns_hosts") + .and_then(|v| v.as_array()), + Some(&vec![serde_json_lenient::json!("github.com")]), + "allow_dns_hosts must round-trip for {network:?}" + ); + assert_eq!( + egress_json + .get("allow_protocols") + .and_then(|v| v.as_array()), + Some(&vec![serde_json_lenient::json!("tcp")]), + "allow_protocols must round-trip for {network:?}" + ); + assert_eq!( + egress_json.get("deny_subnets").and_then(|v| v.as_array()), + Some(&vec![serde_json_lenient::json!("10.0.0.0/24")]), + "deny_subnets must round-trip for {network:?}" + ); + } +} + +async fn run_session_policy(args: &GlobalArgs, session_id: SessionId) -> String { + let mut buf = Vec::new(); + minimal::format_session_policy( + &mut buf, + &minimal::PolicyArgs { + session: session_id.to_string(), + }, + args, + ) + .await + .unwrap(); + String::from_utf8(buf).unwrap() +} + // --- helpers --- +/// Like [`create_session_at`], but sets an explicit network mode and policy. +async fn create_session_with_policy( + daemon: &common::TestDaemon, + name: &str, + network: sessions::NetworkMode, + egress: Option, +) -> SessionId { + let mut client = daemon.server.connect().await; + let project_path = paths::HostAbsPath::try_new( + camino::Utf8PathBuf::from_path_buf(std::env::current_dir().unwrap()).unwrap(), + ) + .unwrap(); + + let policy = sessions::SessionPolicy { + egress, + ingress: None, + }; + let config = minimald_rpc::SessionConfig { + name: Some(name.to_string()), + project_path, + network, + policy, + hooks_enabled: true, + attrs: Default::default(), + }; + + use minimald_rpc::{ + ConfigureLoadout, ConfigureLoadoutRequest, CreateSession, CreateSessionRequest, + FinalizeSession, FinalizeSessionRequest, + }; + let id = match client + .call::(&CreateSessionRequest { + config, + must_match_version: None, + }) + .await + { + minimald_rpc::Errorable::Ok(r) => r.id, + minimald_rpc::Errorable::Err { error } => { + panic!("CreateSession failed: {error}") + } + }; + match client + .call::(&ConfigureLoadoutRequest { + session_id: id, + contribution: Default::default(), + }) + .await + { + minimald_rpc::Errorable::Ok(r) => unwrap_ready(r), + minimald_rpc::Errorable::Err { error } => { + panic!("ConfigureLoadout failed: {error}") + } + } + match client + .call::(&FinalizeSessionRequest { session_id: id }) + .await + { + minimald_rpc::Errorable::Ok(_) => {} + minimald_rpc::Errorable::Err { error } => { + panic!("FinalizeSession failed: {error}") + } + } + id +} + /// Creates a session whose workspace mfile declares a `[session.vars]` /// entry, which the daemon must route back to the client for gating — so /// configuring its loadout returns `Pending` and the session actor parks in diff --git a/crates/minimald/src/rpc.rs b/crates/minimald/src/rpc.rs index 778de564ec..f79a25d2f5 100644 --- a/crates/minimald/src/rpc.rs +++ b/crates/minimald/src/rpc.rs @@ -2736,8 +2736,9 @@ mod tests { let egress = EgressPolicy { allow_subnets: Some(vec!["10.0.0.0/8".to_string()]), - allow_dns_hosts: None, - allow_protocols: None, + allow_dns_hosts: Some(vec!["github.com".to_string()]), + allow_protocols: Some(vec![minimald_rpc::IpProto::Tcp]), + deny_subnets: Some(vec!["10.0.0.0/24".to_string()]), }; let created_id = client .call::(&CreateSessionRequest { @@ -2765,6 +2766,52 @@ mod tests { assert_eq!(policy.ingress, None); } + /// NET-061/NET-120: GetSessionPolicy returns the effective egress rules, + /// including all four fields, for both own-address and host-address boxes. + #[tokio::test] + async fn get_session_policy_returns_effective_egress() { + let server = TestServer::new().await; + let mut client = server.connect().await; + + let egress = 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![minimald_rpc::IpProto::Tcp]), + deny_subnets: Some(vec!["10.0.0.0/24".to_string()]), + }; + + for (name, network) in [ + ("own-ip-policy", NetworkMode::OwnIp), + ("host-ip-policy", NetworkMode::HostNet), + ] { + let created_id = client + .call::(&CreateSessionRequest { + config: minimald_rpc::SessionConfig { + name: Some(name.to_string()), + project_path: HostAbsPath::try_new("/uwu").unwrap(), + network, + policy: SessionPolicy::new(Some(egress.clone()), None), + hooks_enabled: true, + attrs: Default::default(), + }, + must_match_version: None, + }) + .await + .unwrap() + .id; + + let policy = client + .call::(&GetSessionPolicyRequest::Id(created_id)) + .await + .unwrap(); + assert_eq!( + policy.egress, + Some(egress.clone()), + "effective egress must round-trip for {network:?}" + ); + } + } + /// `ListSessions` answers each session's git context: branch and /// toplevel for a plain repo, the worktree flag for a linked /// worktree, and `None` for a non-repo project. Follows @@ -2933,19 +2980,20 @@ 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 `NoNet` PTask is rejected at + // declaration time, so an egress-declared `none` box is never stored. 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(), @@ -2956,13 +3004,42 @@ 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 PTask, not NoNet".to_string() } ); - // The rejected session left nothing behind in the store. + // NET-120: a host-address (HostNet) box now accepts an egress section, + // so this create succeeds rather than errors. + let hostnet_egress = EgressPolicy { + allow_subnets: Some(vec!["10.0.0.0/8".to_string()]), + allow_dns_hosts: None, + allow_protocols: None, + deny_subnets: None, + }; + let hostnet_id = client + .call::(&CreateSessionRequest { + config: minimald_rpc::SessionConfig { + name: Some("hostnet-policy".to_string()), + project_path: HostAbsPath::try_new("/uwu").unwrap(), + network: NetworkMode::HostNet, + policy: SessionPolicy::new(Some(hostnet_egress.clone()), None), + hooks_enabled: true, + attrs: Default::default(), + }, + must_match_version: None, + }) + .await + .unwrap() + .id; + let mngr = server.state.sessions_manager().await; - assert!(mngr.list().await.unwrap().is_empty()); + assert_eq!(mngr.list().await.unwrap().len(), 1); + + let policy = client + .call::(&GetSessionPolicyRequest::Id(hostnet_id)) + .await + .unwrap(); + assert_eq!(policy.egress, Some(hostnet_egress)); } #[tokio::test] diff --git a/crates/minimald/src/sessions.rs b/crates/minimald/src/sessions.rs index d483f0e438..c1e63ed620 100644 --- a/crates/minimald/src/sessions.rs +++ b/crates/minimald/src/sessions.rs @@ -86,6 +86,25 @@ fn build_record( Ok(record) } +fn log_egress_rule_counts(policy: &sessions::SessionPolicy) { + let (allow_subnets, allow_protocols, allow_dns_hosts, deny_subnets) = match &policy.egress { + Some(egress) => ( + egress.allow_subnets.as_ref().map_or(0, Vec::len), + egress.allow_protocols.as_ref().map_or(0, Vec::len), + egress.allow_dns_hosts.as_ref().map_or(0, Vec::len), + egress.deny_subnets.as_ref().map_or(0, Vec::len), + ), + None => (0, 0, 0, 0), + }; + tracing::info!( + allow_subnets, + allow_protocols, + allow_dns_hosts, + deny_subnets, + "session egress rules parsed" + ); +} + /// Encapsulates the return channel for messages back from the actor. #[derive(Debug)] pub(crate) struct Responder(oneshot::Sender>); @@ -404,6 +423,7 @@ impl Manager { // Allocate the record up front: `store.create` assigns the id and // catches a name collision (`AlreadyExists`) before any actor exists. let record = build_record(config, username, sessions::SessionStatus::Pending)?; + log_egress_rule_counts(&record.policy); let handle = self.store.create(record).await?; let session_id = *handle.id(); diff --git a/crates/sessions/src/lib.rs b/crates/sessions/src/lib.rs index 0feb254468..6011543077 100644 --- a/crates/sessions/src/lib.rs +++ b/crates/sessions/src/lib.rs @@ -78,7 +78,8 @@ pub struct PortMapping { pub proto: IpProto, } -/// Effective egress policy for an `OwnIp` `PTask`. +/// Effective egress policy for a `PTask` with network policy (`OwnIp` or +/// `HostNet`). /// /// Each field is `None` to mean allow-all for that dimension. Absent `egress` /// config on a session is equivalent to all-`None` (allow-all). @@ -90,11 +91,16 @@ pub struct EgressPolicy { pub allow_dns_hosts: Option>, /// Allowed IP protocols; `None` means allow all protocols. pub allow_protocols: Option>, + /// Denied destination CIDR prefixes; applied after the allow lists and the + /// node-plane baseline set. `None` means no extra denies beyond the + /// infrastructure deny set. + pub deny_subnets: Option>, } impl EgressPolicy { - /// Returns the first `allow_subnets` entry that is not a syntactically valid - /// CIDR prefix, or `None` when every entry parses (or none are configured). + /// Returns the first subnet entry (allow or deny) that is not a + /// syntactically valid CIDR prefix, or `None` when every entry parses (or + /// none are configured). /// /// Used at launch to name a misconfigured destination subnet where it can be /// fixed — by [`Record::validate_policy`] for per-`PTask` egress and by @@ -104,9 +110,9 @@ impl EgressPolicy { #[must_use] pub fn first_invalid_subnet(&self) -> Option<&str> { self.allow_subnets - .as_deref() - .into_iter() - .flatten() + .iter() + .chain(self.deny_subnets.iter()) + .flat_map(std::vec::Vec::as_slice) .map(String::as_str) .find(|cidr| !is_valid_cidr(cidr)) } @@ -169,7 +175,8 @@ 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`]. + /// An egress policy was set on a `PTask` that has no network policy + /// surface ([`NetworkMode::NoNet`]). #[error("egress policy is only valid for an own-IP PTask, not {mode:?}")] EgressRequiresOwnIp { mode: NetworkMode }, /// An ingress policy was set on a `PTask` that is not [`NetworkMode::OwnIp`]. @@ -400,21 +407,21 @@ 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: `NoNet` has no network, `HostNet` can carry an egress + /// declaration but not ingress port forwarding, and `OwnIp` can carry both. + /// 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 + /// on a `NoNet` `PTask`, or [`PolicyError::IngressRequiresOwnIp`] when a + /// non-empty ingress policy is set on a non-`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, + /// 1024. For an `OwnIp` or `HostNet` `PTask`, returns + /// [`PolicyError::InvalidSubnet`] when an egress `allow_subnets` entry is not + /// a valid CIDR prefix. For an `OwnIp` `PTask`, returns /// [`PolicyError::InvalidDynamicRange`] when the ingress /// `dynamic_allowed_range` lower bound exceeds its upper bound, or /// [`PolicyError::PrivilegedDynamicRange`] when that lower bound is a @@ -446,54 +453,73 @@ 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 + // Egress syntax is checked for any networked PTask so misconfigs are + // named at launch rather than surfacing opaquely when the enforcement + // layer parses them. Ingress port forwarding is only valid on OwnIp; + // HostNet shares its node's address, so static mappings and dynamic + // ranges there are rejected rather than colliding on the shared address. + if matches!(self.network, NetworkMode::OwnIp | NetworkMode::HostNet) + && let Some(bad) = self .policy .egress .as_ref() .and_then(EgressPolicy::first_invalid_subnet) - { - return Err(PolicyError::InvalidSubnet { - cidr: bad.to_owned(), - }); + { + return Err(PolicyError::InvalidSubnet { + cidr: bad.to_owned(), + }); + } + + match 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 the static-mapping privileged-port check enforces. + // Reject either at launch rather than letting a misconfig persist + // on the Record until #553's dynamic port-mapping layer consumes + // it. + if let Some((lo, hi)) = self + .policy + .ingress + .as_ref() + .and_then(|ingress| ingress.dynamic_allowed_range) + { + if lo > hi { + return Err(PolicyError::InvalidDynamicRange { lo, hi }); + } + if lo < 1024 { + return Err(PolicyError::PrivilegedDynamicRange { lo }); + } + } + Ok(()) } - // 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 - // the static-mapping privileged-port check enforces. Reject either at - // launch rather than letting a misconfig persist on the Record until - // #553's dynamic port-mapping layer consumes it. - if let Some((lo, hi)) = self - .policy - .ingress - .as_ref() - .and_then(|ingress| ingress.dynamic_allowed_range) - { - if lo > hi { - return Err(PolicyError::InvalidDynamicRange { lo, hi }); + NetworkMode::HostNet => { + if self + .policy + .ingress + .as_ref() + .is_some_and(|ingress| !ingress.is_empty()) + { + return Err(PolicyError::IngressRequiresOwnIp { mode: self.network }); + } + Ok(()) + } + NetworkMode::NoNet => { + if self.policy.egress.is_some() { + return Err(PolicyError::EgressRequiresOwnIp { mode: self.network }); } - if lo < 1024 { - return Err(PolicyError::PrivilegedDynamicRange { lo }); + if self + .policy + .ingress + .as_ref() + .is_some_and(|ingress| !ingress.is_empty()) + { + return Err(PolicyError::IngressRequiresOwnIp { mode: self.network }); } + Ok(()) } - return Ok(()); - } - if self.policy.egress.is_some() { - return Err(PolicyError::EgressRequiresOwnIp { mode: self.network }); } - if self - .policy - .ingress - .as_ref() - .is_some_and(|ingress| !ingress.is_empty()) - { - return Err(PolicyError::IngressRequiresOwnIp { mode: self.network }); - } - Ok(()) } } @@ -550,22 +576,48 @@ 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 now valid for a host-address (HostNet) + // PTask, so the host-side classifier can enforce the box's own + // declaration. let record = record_with( NetworkMode::HostNet, SessionPolicy::new(Some(EgressPolicy::default()), None), ); + assert!(record.validate_policy().is_ok()); + } + + #[test] + fn egress_on_host_ip_box_with_deny_subnets_is_accepted() { + let egress = EgressPolicy { + allow_subnets: Some(vec!["10.0.0.0/8".into()]), + allow_dns_hosts: Some(vec!["github.com".into()]), + allow_protocols: Some(vec![IpProto::Tcp]), + deny_subnets: Some(vec!["10.0.0.0/24".into()]), + }; + let record = record_with(NetworkMode::HostNet, SessionPolicy::new(Some(egress), None)); + assert!(record.validate_policy().is_ok()); + } + + #[test] + fn egress_on_host_ip_box_rejects_invalid_deny_subnet() { + let egress = EgressPolicy { + deny_subnets: Some(vec!["not-a-cidr".into()]), + ..EgressPolicy::default() + }; + let record = record_with(NetworkMode::HostNet, SessionPolicy::new(Some(egress), None)); assert_eq!( record.validate_policy(), - Err(PolicyError::EgressRequiresOwnIp { - mode: NetworkMode::HostNet + Err(PolicyError::InvalidSubnet { + cidr: "not-a-cidr".into() }) ); } #[test] - fn egress_on_no_net_is_rejected() { + fn egress_on_none_box_is_validation_error() { + // NET-065: a `none` (NoNet) PTask has no network, so an egress section + // is a validation error rather than silently ignored. let record = record_with( NetworkMode::NoNet, SessionPolicy::new(Some(EgressPolicy::default()), None), @@ -848,6 +900,32 @@ mod tests { assert_eq!(SessionStatus::default(), SessionStatus::Active); } + /// NET-060: a box spec carrying all four egress fields deserializes into + /// `EgressPolicy` and round-trips through serde. + #[test] + fn spec_accepts_egress_fields() { + let json = serde_json_lenient::json!({ + "egress": { + "allow_subnets": ["10.0.0.0/8"], + "allow_protocols": ["tcp", "udp"], + "allow_dns_hosts": ["github.com"], + "deny_subnets": ["10.0.0.0/24"], + } + }); + let policy: SessionPolicy = serde_json_lenient::from_value(json).unwrap(); + let egress = policy.egress.as_ref().expect("egress present"); + assert_eq!(egress.allow_subnets, Some(vec!["10.0.0.0/8".into()])); + assert_eq!( + egress.allow_protocols, + Some(vec![IpProto::Tcp, IpProto::Udp]) + ); + assert_eq!(egress.allow_dns_hosts, Some(vec!["github.com".into()])); + assert_eq!(egress.deny_subnets, Some(vec!["10.0.0.0/24".into()])); + + let round = serde_json_lenient::to_value(policy).unwrap(); + assert!(round.get("egress").unwrap().get("deny_subnets").is_some()); + } + /// Records persisted before the `Draft` → `Pending` rename used /// the string `"draft"`. The serde alias keeps those records /// readable; regression guard for accidentally dropping the diff --git a/crates/sessions/src/store.rs b/crates/sessions/src/store.rs index aa59cbe45c..17a9b89178 100644 --- a/crates/sessions/src/store.rs +++ b/crates/sessions/src/store.rs @@ -1109,6 +1109,7 @@ mod tests { allow_subnets: Some(vec!["10.0.0.0/8".to_string()]), allow_dns_hosts: None, allow_protocols: None, + deny_subnets: None, }), None, ), diff --git a/crates/switch/src/lib.rs b/crates/switch/src/lib.rs index ed41d72a32..0981368cc0 100644 --- a/crates/switch/src/lib.rs +++ b/crates/switch/src/lib.rs @@ -35,6 +35,28 @@ pub const DEFAULT_SUBNET: SwitchSubnet = SwitchSubnet { prefix: 16, }; +/// Host enrollment state with the network plan it determines. +/// +/// An unenrolled local host has no identity-plane policy feed; it falls back to +/// the built-in default plan (NET-102). The enrolled variant is intentionally +/// absent until the identity-plane work introduces it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Enrollment { + /// The host has not enrolled with an identity plane; it self-allocates + /// from the built-in default plan. + Unenrolled, +} + +impl Enrollment { + /// Returns the switch subnet this enrollment uses for box addresses. + #[must_use] + pub fn switch_subnet(self) -> SwitchSubnet { + match self { + Self::Unenrolled => DEFAULT_SUBNET, + } + } +} + /// Filename the switch binary is installed under, in both the user-local `bin/` /// prefix and the system-wide path below. /// @@ -319,6 +341,13 @@ pub fn render_gvproxy_config(subnet: SwitchSubnet, leases: &[(Ipv4Addr, MacAddr) mod tests { use super::*; + #[test] + fn unenrolled_self_allocates_default_plan() { + // NET-102: an unenrolled host self-allocates from the built-in default + // plan rather than asking an identity plane for a network assignment. + assert_eq!(Enrollment::Unenrolled.switch_subnet(), DEFAULT_SUBNET); + } + #[test] fn default_is_cgnat_slash16() { let net = SwitchSubnet::default();