diff --git a/crates/minimal/src/cmd/boxes/create.rs b/crates/minimal/src/cmd/boxes/create.rs index d7a29de064..42ac5fd1fc 100644 --- a/crates/minimal/src/cmd/boxes/create.rs +++ b/crates/minimal/src/cmd/boxes/create.rs @@ -349,6 +349,19 @@ fn refuse_unhonourable_grants( Ok(plan.warnings) } +/// Whether the activation holds the box's name on the VM host daemon once +/// the box is active. A `host_ip` box holds it for the zone (NET-128). A +/// `none` box holds it so the host can name the box by its id when the +/// in-VM daemon reports an expose decision (NET-046). An own-address box +/// has a row, and a native host has no VM host daemon. +pub(crate) fn holds_name_with_vm_host(kind: paths::HostKind, network: boxes::NetworkMode) -> bool { + kind == paths::HostKind::Minvmd + && matches!( + network, + boxes::NetworkMode::HostNet | boxes::NetworkMode::NoNet + ) +} + /// Whether a box with `network` on a host of `kind` has its lookups go /// through a switch that steers the credential module's names (BEP-017, /// BEP-062). This is a host fact and does not read the steering. On the VM @@ -2635,8 +2648,7 @@ pub(crate) async fn activate_box( // A kept session is active: it gets the `host_ip` name hold // an activation that succeeded makes below. if outcome == CleanupOutcome::Kept - && kind == paths::HostKind::Minvmd - && request.config.network == boxes::NetworkMode::HostNet + && holds_name_with_vm_host(kind, request.config.network) && let Some(name) = box_name.as_deref() { hold_box_name_with_vm_host(control_sock.clone(), name, Some(id), true).await; @@ -2689,10 +2701,19 @@ pub(crate) async fn activate_box( // attaches to or execs into is dropped once the daemon's reconfirm // bound passes, and the name answers NXDOMAIN until the session's // next attach or exec. + // + // A `none` box on a VM host takes the same hold (NET-046): it has no + // switch row, so the hold is the host's one record of its box id, and + // the in-VM daemon's expose decision report names the box by that id. + // Its name answers NODATA, as a `host_ip` box's does while it is not + // resident. `min session destroy` and the dashboard's destroy release + // it, `min session rename` moves it, and an attach or exec re-holds it + // after a VM host daemon restart, because `holds_name` (vm_host.rs) is + // true for a `none` box as for a `host_ip` box. An unnamed `none` box + // holds nothing, and the host refuses its report. ActivationStep::HoldName .run(async { - if kind == paths::HostKind::Minvmd - && request.config.network == boxes::NetworkMode::HostNet + if holds_name_with_vm_host(kind, request.config.network) && let Some(name) = box_name.as_deref() { hold_box_name_with_vm_host(control_sock.clone(), name, Some(id), true).await; @@ -3800,6 +3821,30 @@ mod tests { assert_eq!(refused.exit_code(), 3); } + /// NET-046: a `none` box on a VM host holds its name with the host, as + /// a `host_ip` box does, so the host can name it by its box id. + #[test] + fn none_box_holds_its_name_with_the_vm_host() { + use boxes::NetworkMode; + use paths::HostKind; + assert!(holds_name_with_vm_host( + HostKind::Minvmd, + NetworkMode::NoNet + )); + assert!(holds_name_with_vm_host( + HostKind::Minvmd, + NetworkMode::HostNet + )); + assert!(!holds_name_with_vm_host( + HostKind::Minvmd, + NetworkMode::OwnIp + )); + assert!(!holds_name_with_vm_host( + HostKind::Minimald, + NetworkMode::NoNet + )); + } + /// BEP-017, BEP-062, BEP-080: a GitHub grant box with `dns` steering, /// declared or by default, or with `both`, is created where the VM /// host's switch resolves its names, and `min box spec` shows it. On a diff --git a/crates/minimal/src/cmd/boxes/vm_host.rs b/crates/minimal/src/cmd/boxes/vm_host.rs index 95e8f810dc..f9718a129c 100644 --- a/crates/minimal/src/cmd/boxes/vm_host.rs +++ b/crates/minimal/src/cmd/boxes/vm_host.rs @@ -311,10 +311,12 @@ pub(crate) async fn release_held_name_after_attach( /// a persisted registry failed to carry, its write a warn line — may be /// gone by the time the attach lands; the re-hold is idempotent, so it /// remakes the hold and the name answers NODATA through the attach -/// either way. Only a named `host_ip` session without a box row needs -/// it: a box that registered a row owns its name through the row, which -/// `resume_box_row` re-sends, and a `none` or `own_ip` session holds -/// nothing. +/// either way. Only a named `host_ip` or `none` session without a box +/// row needs it: a box that registered a row owns its name through the +/// row, which `resume_box_row` re-sends, and an `own_ip` session holds +/// nothing. A `none` box's hold is the host's record of its box id, so a +/// hold lost to a restart leaves the host refusing its expose decision +/// reports (NET-046). Only a `host_ip` box has egress to re-admit. /// /// The record was read before the hold, so a destroy another client /// issues in between can release the session's holds first and leave @@ -347,7 +349,8 @@ pub(crate) async fn rehold_held_name_before_attach( let Some(record) = record else { return; }; - if record.network != boxes::NetworkMode::HostNet { + let host_net = record.network == boxes::NetworkMode::HostNet; + if !host_net && !holds_name(record) { return; } // The box's egress, re-admitted before the attach or the exec for the @@ -360,13 +363,15 @@ pub(crate) async fn rehold_held_name_before_attach( // The session is looked up again once the admit is made, and a session // gone by then has its rules retired, as the name re-hold below undoes // its hold. A destroy that lands after that lookup retires them itself. - if host_ip_box_with_vm_host( - control_sock_beside(sock), - id, - record.policy.egress.clone(), - true, - ) - .await + // A `none` box has no egress to admit, so only its name is re-held. + if host_net + && host_ip_box_with_vm_host( + control_sock_beside(sock), + id, + record.policy.egress.clone(), + true, + ) + .await { match attached_box_record(sock, id).await { Ok(None) => { @@ -413,8 +418,8 @@ pub(crate) async fn rehold_held_name_before_attach( /// The undo of a re-hold made for session `id`, found gone since, from the /// lookup of its name (`by_name`): the session to send the verb for and -/// whether the verb is a hold. A live `host_ip` session without a row that -/// answers to the name now is handed the hold back; no such session, and +/// whether the verb is a hold. A live session that holds its name +/// ([`holds_name`]) and answers to the name now is handed the hold back; no such session, and /// the hold is released by `id`. A lookup that failed tells neither, so /// nothing is undone (`None`): a release there could take the name from a /// live session, and a hold left standing blocks nothing. @@ -422,20 +427,23 @@ fn rehold_undo( id: boxes::SessionId, by_name: anyhow::Result>, ) -> Option<(boxes::SessionId, bool)> { - let taken_over_by = by_name.ok()?.filter(|other| { - other.id != id - && other.network == boxes::NetworkMode::HostNet - && other.box_addresses.is_none() - }); + let taken_over_by = by_name + .ok()? + .filter(|other| other.id != id && holds_name(other)); Some(taken_over_by.map_or((id, false), |other| (other.id, true))) } /// Whether this box holds its name at the VM host instead of registering /// an address there. A `host_ip` box uses the host's own address, so the /// host only reserves the name for it (a lookup returns no address), and -/// the record carries no `box_addresses`. +/// the record carries no `box_addresses`. A `none` box holds its name too +/// (NET-046): the hold is the host's one record of its box id, which the +/// in-VM daemon's expose decision report names. pub(crate) fn holds_name(record: &boxes::Record) -> bool { - record.network == boxes::NetworkMode::HostNet && record.box_addresses.is_none() + matches!( + record.network, + boxes::NetworkMode::HostNet | boxes::NetworkMode::NoNet + ) && record.box_addresses.is_none() } /// Withdraws a box's host row (T66) on the VM host daemon beside `sock`, @@ -2152,6 +2160,52 @@ mod tests { assert_eq!(request.session_id, Some(id)); } + /// NET-046: a named `none` box's hold is the VM host's record of its + /// box id, so an attach or exec re-holds it after a VM host daemon + /// restart, as a `host_ip` box's is. A `none` box has no egress, so + /// nothing is re-admitted for it. + #[tokio::test] + async fn an_attach_reholds_a_none_box_name_and_admits_no_egress() { + let dir = tempfile::TempDir::new().unwrap(); + let ssh_sock = dir.path().join("ssh.sock"); + let (requests, residency) = fake_vm_host_with_residency( + dir.path().join(minvmd::control::CONTROL_SOCK_FILE), + r#"{"name":"web","held":false}"#.to_string(), + ) + .await; + let server = minimald::test_harness::TestServer::new().await; + server.listen_on_uds(&ssh_sock).await; + let project = tempfile::TempDir::new().unwrap(); + let mut daemon = server.connect().await; + let id = minimald::test_harness::create_configured_session( + &mut daemon, + "web", + project.path().to_str().unwrap(), + ) + .await; + let mut record = attached_box_record(&ssh_sock, id) + .await + .expect("the lookup does not fail") + .expect("the session's record is read"); + record.network = boxes::NetworkMode::NoNet; + assert!(record.box_addresses.is_none()); + + rehold_held_name_before_attach(paths::HostKind::Minvmd, &ssh_sock, id, Some(&record)).await; + let seen = requests.lock().unwrap(); + assert_eq!(seen.len(), 1, "one hold, one request"); + let minimald_rpc::BoxControlRequest::HoldBoxName(request) = + serde_json_lenient::from_str(&seen[0]).expect("the request is the wire type") + else { + panic!("the re-hold is carried by the hold verb"); + }; + assert_eq!(request.name, "web"); + assert_eq!(request.session_id, Some(id)); + assert!( + residency.lock().unwrap().is_empty(), + "a `none` box has no egress to re-admit" + ); + } + /// A stand-in VM host daemon at `control_sock` that answers `host_ip` /// retires, and drops the first `unanswered` of them unanswered: their /// connection closes, so the exchange fails. Returns the count of diff --git a/crates/minimal/src/tests.rs b/crates/minimal/src/tests.rs index 468edcfe13..c1efc2473d 100644 --- a/crates/minimal/src/tests.rs +++ b/crates/minimal/src/tests.rs @@ -6831,3 +6831,63 @@ async fn box_first_slice_list_show_stop_rm_end_to_end() { assert_eq!(spans, ran, "{span} spans\n{transcript}\n{log}"); } } + +/// A session record carrying `mode` and `box_addresses`, with everything +/// else at its default. +fn hold_record( + mode: boxes::NetworkMode, + box_addresses: Option, +) -> boxes::Record { + boxes::Record { + id: boxes::SessionId::nil(), + name: Some("web".to_string()), + username: None, + project_path: paths::HostAbsPath::try_new("/tmp/project").unwrap(), + network: mode, + policy: boxes::BoxPolicy::default(), + task_addresses: Vec::new(), + box_addresses, + status: boxes::BoxState::Active, + reason: None, + exit_code: None, + signal: None, + hooks_enabled: true, + host_ip_enforcement: None, + box_id: None, + host_row_bound: false, + bound_ports: std::collections::BTreeSet::new(), + ends_with_run: false, + sealed_deliveries: Vec::new(), + root_certificate: None, + box_type: None, + parent: None, + project_root: None, + attrs: Default::default(), + } +} + +/// NET-046: a named `none` box holds its name on the VM host, so the +/// paths that release or move a hold treat it as a `host_ip` box. The +/// dashboard's destroy (`dash/rpc.rs`) releases a hold only for a record +/// `holds_name` accepts, and `min session rename` and the dashboard's +/// rename move a hold only for such a record. An own-address box owns +/// its name through its row, and holds nothing. +#[test] +fn none_box_hold_is_released_by_destroy_and_moved_by_rename() { + assert!( + crate::holds_name(&hold_record(boxes::NetworkMode::NoNet, None)), + "the dashboard's destroy releases a `none` box's hold, and a rename moves it" + ); + assert!( + crate::holds_name(&hold_record(boxes::NetworkMode::HostNet, None)), + "a `host_ip` box's hold is released and moved as before" + ); + let row = boxes::BoxAddresses { + switch_address: std::net::Ipv4Addr::new(10, 0, 0, 2), + loopback_address: std::net::Ipv4Addr::new(127, 0, 0, 2), + }; + assert!( + !crate::holds_name(&hold_record(boxes::NetworkMode::NoNet, Some(row))), + "a box with a row owns its name through the row" + ); +} diff --git a/crates/minimald-rpc/src/lib.rs b/crates/minimald-rpc/src/lib.rs index cfb1af7534..ffb35ab48a 100644 --- a/crates/minimald-rpc/src/lib.rs +++ b/crates/minimald-rpc/src/lib.rs @@ -1114,12 +1114,23 @@ pub enum ExposeDecisionOutcome { /// /// Fixed and size-bounded like the port reports: the row key, the port, and /// three closed enums. The box is named by the host from the row at -/// `switch_address`, never by a string the guest sends. A report keyed at -/// no row is refused and leaves no record. +/// `switch_address`, never by a string the guest sends. A box with no +/// switch has no row key, so its report carries its box id instead, and +/// the host names the box from what it holds under that id. A report keyed +/// at no box the host holds is refused and leaves no record. +/// +/// Both keys are serde-defaulted, so an older guest's report, which always +/// carries a switch address and never a box id, still reads. #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] pub struct ExposeDecisionReport { - /// The switch address of the row the decision is about. - pub switch_address: std::net::Ipv4Addr, + /// The switch address of the row the decision is about. `None` for a + /// box with no switch, which [`Self::box_id`] names instead. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub switch_address: Option, + /// The box the decision is about, by its id. The host reads it only + /// when the report carries no switch address. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub box_id: Option, /// The port the box asked to publish. pub port: u16, /// The decision the box's `dynamic_ingress` setting made. diff --git a/crates/minimald/src/audit.rs b/crates/minimald/src/audit.rs index f898c29880..45e4b9f3c0 100644 --- a/crates/minimald/src/audit.rs +++ b/crates/minimald/src/audit.rs @@ -148,7 +148,7 @@ pub(crate) fn rotated_path(state_dir: &Path) -> PathBuf { /// failure the caller fails closed on. The daemon's own log, which the /// diagnostic bundle ships beside this file's tail, carries the failure /// either way. -pub(crate) async fn append(state_dir: &Path, record: &DecisionRecord) { +pub(crate) async fn append(state_dir: &Path, record: &DecisionRecord, host: &HostReportKey) { if let Err(e) = try_append_capped(state_dir, record, MAX_LOG_BYTES).await { tracing::warn!( box = %record.box_name, @@ -160,18 +160,34 @@ pub(crate) async fn append(state_dir: &Path, record: &DecisionRecord) { // A refusal goes to the host whether or not the local line landed: the // host's copy is the one a box cannot reach, and it names a refusal // that stands either way. - report_to_host(record); + report_to_host(record, host); +} + +/// How the VM host daemon finds the box a decision is about, when the box has +/// no audit route by switch address (NET-046). The host names a box with no +/// switch by its id, and the report goes over the box's own control channel. +/// Not written to the local log: the record names the box already. +#[derive(Debug, Clone, Default)] +pub(crate) struct HostReportKey { + /// The box's id, which the report carries when no route names the box. + pub(crate) box_id: Option, + /// The box's switch control channel. Its VM host door carries a report + /// keyed by box id. A native channel has no door, so nothing is sent. + #[cfg(target_os = "linux")] + pub(crate) control: Option, } /// Reports `record` to the VM host daemon, which keeps its own copy of the /// decision outside the VM (NET-046). Best-effort and in the background: /// the local record is the decision's own, and a host that cannot be /// reached never changes it. A daemon with no VM host behind the box sends -/// nothing. -fn report_to_host(record: &DecisionRecord) { +/// nothing. A box with no switch is named by the box id in `host`. +fn report_to_host(record: &DecisionRecord, host: &HostReportKey) { #[cfg(target_os = "linux")] crate::net::listeners::report_expose_decision( &record.box_name, + host.box_id, + host.control.as_ref(), record.port, record.decision, match record.decided_by { @@ -186,7 +202,7 @@ fn report_to_host(record: &DecisionRecord) { }, ); #[cfg(not(target_os = "linux"))] - let _ = record; + let _ = (record, host); } /// Appends one decision to the log (NET-046), rotating it first when the @@ -198,9 +214,13 @@ fn report_to_host(record: &DecisionRecord) { /// A record that landed is also reported to the VM host daemon, in the /// background. One that did not land is not: the caller withdraws the /// allow it names, and records that withdrawal through [`append`]. -pub(crate) async fn try_append(state_dir: &Path, record: &DecisionRecord) -> std::io::Result<()> { +pub(crate) async fn try_append( + state_dir: &Path, + record: &DecisionRecord, + host: &HostReportKey, +) -> std::io::Result<()> { try_append_capped(state_dir, record, MAX_LOG_BYTES).await?; - report_to_host(record); + report_to_host(record, host); Ok(()) } @@ -404,6 +424,7 @@ mod tests { outcome: DecisionOutcome::Published, reason: None, }, + &HostReportKey::default(), ) .await; append( @@ -417,6 +438,7 @@ mod tests { outcome: DecisionOutcome::Refused, reason: Some("dynamic ingress is denied for this box".to_string()), }, + &HostReportKey::default(), ) .await; @@ -482,7 +504,7 @@ mod tests { std::fs::write(&planted, "planted\n").unwrap(); std::os::unix::fs::symlink(&planted, log_path(state_dir)).unwrap(); - append(state_dir, &record).await; + append(state_dir, &record, &HostReportKey::default()).await; assert_eq!( std::fs::read_to_string(&planted).unwrap(), @@ -516,7 +538,7 @@ mod tests { std::fs::create_dir_all(&planted_dir).unwrap(); std::os::unix::fs::symlink(&planted_dir, state_dir.join("audit")).unwrap(); - append(state_dir, &record).await; + append(state_dir, &record, &HostReportKey::default()).await; assert!( !planted_dir.join("decisions.log").exists(), @@ -634,7 +656,7 @@ mod tests { std::fs::create_dir_all(&planted_dir).unwrap(); std::os::unix::fs::symlink(&planted_dir, state_dir.join("audit")).unwrap(); - let error = try_append(state_dir, &record_for(3000)) + let error = try_append(state_dir, &record_for(3000), &HostReportKey::default()) .await .expect_err("a symlinked audit directory refuses the append"); assert!( diff --git a/crates/minimald/src/box_actor/ports.rs b/crates/minimald/src/box_actor/ports.rs index deec07bb13..3b629c93d8 100644 --- a/crates/minimald/src/box_actor/ports.rs +++ b/crates/minimald/src/box_actor/ports.rs @@ -615,6 +615,35 @@ impl BoxActor { .as_utf8_path() .as_std_path() .to_path_buf(); + // How the VM host names this box when its copy of the record + // arrives (NET-046). A box with a switch address reports only by the + // route its listen watcher registered. A box with no switch address + // has no such route, so its report carries the box id and goes over + // this box's control channel. When the box record cannot be read, + // the switch address this box reported decides, so a box with no + // switch still reports by id. + let no_switch = match self.record.record().await { + Ok(record) => record.box_addresses.is_none(), + Err(error) => { + let no_switch = self.reported_switch_address.is_none(); + tracing::debug!( + name = %box_name, + port, + %error, + no_switch, + "the box record could not be read; the reported switch address decides the host report key" + ); + no_switch + } + }; + let host_key = if no_switch { + crate::audit::HostReportKey { + box_id: Some(*self.record.id()), + control: Some(self.switch_control().await), + } + } else { + crate::audit::HostReportKey::default() + }; // An allow that stands is recorded before anything else is said // about it, and only a recorded one is answered as published // (NET-046): an allow whose record cannot be written is withdrawn and @@ -631,7 +660,7 @@ impl BoxActor { outcome: crate::audit::DecisionOutcome::Published, reason: None, }; - match crate::audit::try_append(&state_dir, &record).await { + match crate::audit::try_append(&state_dir, &record, &host_key).await { Ok(()) => { // The record is written, so the box's relay gate // admits the port now, before the caller hears the @@ -812,6 +841,7 @@ impl BoxActor { outcome: audited, reason, }, + &host_key, ) .await; } diff --git a/crates/minimald/src/box_runtime/tests.rs b/crates/minimald/src/box_runtime/tests.rs index a68e5b127d..9ba307570f 100644 --- a/crates/minimald/src/box_runtime/tests.rs +++ b/crates/minimald/src/box_runtime/tests.rs @@ -5779,14 +5779,16 @@ async fn expose_unenrolled_decision_audited() { host_reports, vec![ minimald_rpc::ExposeDecisionReport { - switch_address: web_row, + switch_address: Some(web_row), + box_id: None, port: 3000, decision: boxes::DynamicIngress::Allow, decided_by: minimald_rpc::ExposeDecidedBy::BoxPolicy, outcome: minimald_rpc::ExposeDecisionOutcome::Published, }, minimald_rpc::ExposeDecisionReport { - switch_address: db_row, + switch_address: Some(db_row), + box_id: None, port: 3000, decision: boxes::DynamicIngress::Deny, decided_by: minimald_rpc::ExposeDecidedBy::BoxPolicy, @@ -8241,3 +8243,108 @@ async fn box_output_logged_from_start_complete_after_disconnect() { handle.kill(true).await.expect("kill should reach the host"); let _ = tokio::time::timeout(Duration::from_secs(10), task).await; } + +/// NET-046: a box with no switch address, on a VM host, asks to publish a +/// port, is refused, and the VM host daemon still hears the decision. On a +/// microVM the box with no switch is a `none` box: an `own_ip` box with no +/// handed addresses is refused at create. No audit route names a box with no +/// switch, so the report carries the box's id in place of a switch address, +/// over the box's own control channel. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn no_switch_box_reports_expose_decision_by_id() { + use crate::test_harness::unwrap_ready; + use minimald_rpc::{ + ConfigureLoadout, ConfigureLoadoutRequest, CreateSession, Errorable, FinalizeSession, + FinalizeSessionRequest, + }; + let server = TestServer::new().await; + let mut client = server.connect().await; + // A `none` box that declares no `dynamic_ingress`: the deny-all default + // decides its request. + let request = minimald_rpc::CreateSessionRequest::new( + "web", + paths::HostAbsPath::try_new("/uwu").unwrap(), + boxes::NetworkMode::NoNet, + boxes::BoxPolicy { + egress: None, + ingress: None, + credentialed_upstream: None, + quic443: None, + }, + ); + assert!(request.config.box_addresses.is_none()); + let id = client.call::(&request).await.unwrap().id; + unwrap_ready( + client + .call::(&ConfigureLoadoutRequest { + session_id: id, + contribution: Default::default(), + }) + .await + .unwrap(), + ); + match client + .call::(&FinalizeSessionRequest { + session_id: id, + report_shared_port_collisions: false, + }) + .await + { + Errorable::Ok(_) => {} + Errorable::Err { error } => panic!("FinalizeSession failed: {error}"), + } + let handle = server + .state + .sessions_manager() + .await + .get_session(crate::box_manager::BoxKeyPredicate::Id(id)) + .await + .unwrap() + .expect("the web box should resolve"); + let sock = handle + .net_switch() + .await + .unwrap() + .lock() + .await + .control_socket(); + // The switch's control channel is VM-shaped: its door is the stand-in. + let door_sock = sock.with_file_name("no-switch-door.sock"); + let (door, mut reports, replies) = fake_report_door(&door_sock).await; + crate::net::listeners::seed_vm_report_door_for_tests(&sock, &door_sock); + + match handle.expose_dynamic(3000).await { + Err(crate::net::policy::ExposeFailure::Refused( + crate::net::policy::ExposeRefusal::DeniedByPolicy, + )) => {} + other => panic!("a box that declares no dynamic ingress is refused: {other:?}"), + } + + let report = tokio::time::timeout(Duration::from_secs(10), reports.recv()) + .await + .expect("the refusal is reported to the VM host daemon") + .expect("the report door stand-in lives"); + replies + .send(minimald_rpc::BoxControlReply::Audited { audited: true }) + .expect("the report door stand-in lives"); + door.abort(); + crate::net::listeners::clear_vm_report_door_for_tests(&sock); + assert_eq!( + report, + minimald_rpc::BoxControlRequest::ReportExposeDecision(minimald_rpc::ExposeDecisionReport { + switch_address: None, + box_id: Some(id), + port: 3000, + decision: boxes::DynamicIngress::Deny, + decided_by: minimald_rpc::ExposeDecidedBy::BoxPolicy, + outcome: minimald_rpc::ExposeDecisionOutcome::Refused, + }), + "a box with no switch is named to the host by its id" + ); + + // The local record lands as it always did. + let records = audit_records(&server.state.minimal_state_dir().await).await; + assert_eq!(records.len(), 1, "one request is one decision: {records:?}"); + assert_eq!(records[0]["box"], "web"); + assert_eq!(records[0]["outcome"], "refused"); +} diff --git a/crates/minimald/src/net/listeners.rs b/crates/minimald/src/net/listeners.rs index 145eb1f2b1..510216134c 100644 --- a/crates/minimald/src/net/listeners.rs +++ b/crates/minimald/src/net/listeners.rs @@ -877,10 +877,15 @@ fn send_host_audit(channel: BoxReportChannel, request: minimald_rpc::BoxControlR } /// Reports one dynamic ingress decision to the VM host daemon (NET-046), so -/// the host keeps its own copy outside the VM. Nothing is sent for a box -/// with no audit route: a native host, or a box with no switch. +/// the host keeps its own copy outside the VM. A box with an audit route is +/// named by its switch address. A box with no route, such as a box with no +/// switch, is named by `box_id`, and the report goes over the VM host door +/// of its `control` channel. Nothing is sent on a native host, or when +/// neither key is known. pub(crate) fn report_expose_decision( box_name: &str, + box_id: Option, + control: Option<&ControlChannel>, port: u16, decision: boxes::DynamicIngress, decided_by: minimald_rpc::ExposeDecidedBy, @@ -892,13 +897,23 @@ pub(crate) fn report_expose_decision( .iter() .find(|(_, route)| route.box_name == box_name) .map(|(switch_address, route)| (*switch_address, route.channel.clone())); - let Some((switch_address, channel)) = route else { - return; + let (switch_address, box_id, channel) = match route { + Some((switch_address, channel)) => (Some(switch_address), None, channel), + None => { + let Some(box_id) = box_id else { + return; + }; + let Some(channel) = control.and_then(box_report_channel) else { + return; + }; + (None, Some(box_id), channel) + } }; send_host_audit( channel, minimald_rpc::BoxControlRequest::ReportExposeDecision(minimald_rpc::ExposeDecisionReport { switch_address, + box_id, port, decision, decided_by, @@ -2293,6 +2308,7 @@ impl WatchState { crate::audit::DecisionOutcome::Published, None, ), + &crate::audit::HostReportKey::default(), ) .await { @@ -2548,6 +2564,7 @@ impl WatchState { crate::audit::DecisionOutcome::Published, None, ), + &crate::audit::HostReportKey::default(), ) .await { @@ -2765,6 +2782,9 @@ impl WatchState { crate::audit::append( &self.plan.state_dir, &self.listen_record(port, outcome, reason), + // A watched box reports through the route its watcher + // registered by switch address, so it needs no box id. + &crate::audit::HostReportKey::default(), ) .await; } diff --git a/crates/minvmd/src/control.rs b/crates/minvmd/src/control.rs index 73b79c1f72..6635d09f7a 100644 --- a/crates/minvmd/src/control.rs +++ b/crates/minvmd/src/control.rs @@ -1067,7 +1067,7 @@ fn serve_request( // The box is gone: its audit window ends, and the count of // the records it suppressed lands now. if matches!(reply, BoxControlReply::Addresses(_)) { - flush_guest_audit(audit_path, &name, switch_address); + flush_guest_audit(audit_path, &name, GuestAuditKey::Switch(switch_address)); } reply }); @@ -1125,7 +1125,15 @@ fn serve_request( write_reply(stream, &reply) } (BoxControlRequest::ReleaseBoxName(request), ControlDoor::Host) => { - let reply = order.apply(|| release_box_name(boxes, &request.name, request.session_id)); + let reply = order.apply(|| { + let reply = release_box_name(boxes, &request.name, request.session_id); + // A box with no switch ends with its hold: its audit window, + // filed by its box id, ends here too (NET-046). + if let Some(session_id) = request.session_id { + flush_guest_audit(audit_path, &request.name, GuestAuditKey::Box(session_id)); + } + reply + }); write_reply(stream, &reply) } // A `host_ip` box's policy changes no zone table, so it takes no @@ -1147,7 +1155,18 @@ fn serve_request( ) } (BoxControlRequest::RetireHostIpBox(request), ControlDoor::Host) => { + // Name the box before it leaves the resident set, for the + // suppressed-count line its audit window can still owe. + let box_name = no_switch_box_name(boxes, request.session_id) + .unwrap_or_else(|| request.session_id.to_string()); boxes.retire_host_ip_box(request.session_id); + // A host-address box has no switch: its audit window, filed by + // its box id, ends with it (NET-046). + flush_guest_audit( + audit_path, + &box_name, + GuestAuditKey::Box(request.session_id), + ); write_reply( stream, &BoxControlReply::HostIpBox { @@ -2460,11 +2479,41 @@ struct GuestAuditWindow { flows: HashSet, } -/// The audit windows, by the audit log they write to and the box's row -/// key. The log is part of the key so that two doors in one process (the -/// tests) never share a cap. +/// The key one box's audit window is filed under: the row's switch +/// address, or the box id for a box with no switch. Every box with no switch +/// shares the node's own address, so that address is never a key: one such +/// box would spend the cap of all of them (NET-046). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum GuestAuditKey { + /// A box with a row, by the row's switch address. + Switch(Ipv4Addr), + /// A box with no switch, by its box id. + Box(minimald_rpc::BoxId), +} + +impl GuestAuditKey { + /// The switch address, for a box with a row. + fn switch_address(self) -> Option { + match self { + Self::Switch(switch_address) => Some(switch_address), + Self::Box(_) => None, + } + } + + /// The box id, for a box with no switch. + fn box_id(self) -> Option { + match self { + Self::Switch(_) => None, + Self::Box(box_id) => Some(box_id), + } + } +} + +/// The audit windows, by the audit log they write to and the box's key. The +/// log is part of the key so that two doors in one process (the tests) +/// never share a cap. static GUEST_AUDIT_WINDOWS: std::sync::LazyLock< - std::sync::Mutex>, + std::sync::Mutex>, > = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); /// What the per-box cap says about one report. @@ -2485,14 +2534,14 @@ enum GuestAuditAdmission { /// expose decision, each of which is its own record). fn admit_guest_audit( audit_path: &Path, - switch_address: Ipv4Addr, + key: GuestAuditKey, flow: Option, now: std::time::Instant, ) -> GuestAuditAdmission { let mut windows = GUEST_AUDIT_WINDOWS .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - let key = (audit_path.to_path_buf(), switch_address); + let key = (audit_path.to_path_buf(), key); if windows.len() >= GUEST_AUDIT_TRACKED && !windows.contains_key(&key) { windows.retain(|_, window| { now.duration_since(window.opened) < GUEST_AUDIT_WINDOW || window.suppressed > 0 @@ -2555,11 +2604,17 @@ struct ExposeDecisionAudit { /// Who asserted this record: always `guest`. The in-VM daemon reported /// it, and the host did not observe it. reported_by: &'static str, - /// The box the decision was about, from the row. + /// The box the decision was about, from the row, or from what the + /// host holds under the box id for a box with no switch. #[serde(rename = "box")] box_name: String, - /// The row key the report named. - switch_address: Ipv4Addr, + /// The row key the report named; absent for a box with no switch. + #[serde(skip_serializing_if = "Option::is_none")] + switch_address: Option, + /// The box id the report named a box with no switch by; absent when + /// the row key named the box. + #[serde(skip_serializing_if = "Option::is_none")] + box_id: Option, /// The port the box asked to publish. port: u16, /// The decision the box's `dynamic_ingress` setting made. @@ -2605,26 +2660,27 @@ struct SuppressedAudit { /// The box whose records were suppressed. #[serde(rename = "box")] box_name: String, - /// The box's row key. - switch_address: Ipv4Addr, + /// The box's row key; absent for a box with no switch. + #[serde(skip_serializing_if = "Option::is_none")] + switch_address: Option, + /// The box id, for a box with no switch; absent when the row key names + /// the box. + #[serde(skip_serializing_if = "Option::is_none")] + box_id: Option, /// How many records the cap suppressed in the window that ended. suppressed: u64, } /// Writes the line that counts `suppressed` records for the box, when /// there are any. -fn append_suppressed_audit( - audit_path: &Path, - box_name: &str, - switch_address: Ipv4Addr, - suppressed: u64, -) { +fn append_suppressed_audit(audit_path: &Path, box_name: &str, key: GuestAuditKey, suppressed: u64) { if suppressed == 0 { return; } tracing::warn!( box = %box_name, - %switch_address, + switch_address = ?key.switch_address(), + box_id = ?key.box_id(), suppressed, "the box's audit reports passed the host's cap; records were suppressed" ); @@ -2634,7 +2690,8 @@ fn append_suppressed_audit( ts: unix_now_secs(), event: "audit_suppressed", box_name: box_name.to_string(), - switch_address, + switch_address: key.switch_address(), + box_id: key.box_id().map(|box_id| box_id.simple()), suppressed, }, ); @@ -2645,29 +2702,32 @@ fn append_suppressed_audit( fn take_guest_audit( audit_path: &Path, box_name: &str, - switch_address: Ipv4Addr, + key: GuestAuditKey, admission: &GuestAuditAdmission, ) -> bool { match admission { GuestAuditAdmission::Write { suppressed } => { - append_suppressed_audit(audit_path, box_name, switch_address, *suppressed); + append_suppressed_audit(audit_path, box_name, key, *suppressed); true } GuestAuditAdmission::Repeat | GuestAuditAdmission::Suppressed => false, } } -/// Ends a withdrawn box's audit window. The window is forgotten, so a later -/// box at the same address starts a fresh one. The count of the records it -/// suppressed is written now: a box that stops reporting opens no later -/// window, so without this flush that count is never written. -fn flush_guest_audit(audit_path: &Path, box_name: &str, switch_address: Ipv4Addr) { +/// Ends a box's audit window when the box is gone: a withdrawn row, by its +/// switch address, or a box with no switch, by its box id. The window is +/// forgotten, so a later box under the same key starts a fresh one. The +/// count of the records it suppressed is written now: a box that stops +/// reporting opens no later window, so without this flush that count is +/// never written, and the window, which the trim keeps while it holds a +/// count, stays in the table. +fn flush_guest_audit(audit_path: &Path, box_name: &str, key: GuestAuditKey) { let window = GUEST_AUDIT_WINDOWS .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) - .remove(&(audit_path.to_path_buf(), switch_address)); + .remove(&(audit_path.to_path_buf(), key)); if let Some(window) = window { - append_suppressed_audit(audit_path, box_name, switch_address, window.suppressed); + append_suppressed_audit(audit_path, box_name, key, window.suppressed); } } @@ -2682,37 +2742,73 @@ fn clamp_guest_text(text: &str) -> String { } /// Serves the in-VM daemon's expose decision report (NET-046): one record -/// in the host's audit log, the box named from the row at the report's -/// switch address. A report at no row is refused and writes nothing. +/// in the host's audit log. The box is named from the row at the report's +/// switch address, or, for a box with no switch, from what the host holds +/// under the report's box id ([`no_switch_box_name`]). A report that names +/// no box the host holds is refused and writes nothing. fn audit_expose_decision( boxes: &BoxRegistry, audit_path: &Path, request: &minimald_rpc::ExposeDecisionReport, ) -> BoxControlReply { - let Some(record) = boxes.table().by_source(request.switch_address.octets()) else { - tracing::debug!( - switch_address = %request.switch_address, - "refused an expose decision report at an address no row holds" - ); - return BoxControlReply::Error { - error: format!("no box is registered at {}", request.switch_address), - }; + // The key the per-box cap is filed under: the row's switch address, or + // the box id for a box with no switch. Boxes with no switch all share + // the node's own address, so that address cannot keep their caps apart. + let (box_name, cap_key, box_id) = match (request.switch_address, request.box_id) { + (Some(switch_address), _) => { + let Some(record) = boxes.table().by_source(switch_address.octets()) else { + tracing::debug!( + %switch_address, + "refused an expose decision report at an address no row holds" + ); + return BoxControlReply::Error { + error: format!("no box is registered at {switch_address}"), + }; + }; + tracing::debug!( + box = %record.name(), + %switch_address, + key = "switch_address", + "found the expose decision report's box by its switch address" + ); + ( + record.name().to_string(), + GuestAuditKey::Switch(switch_address), + None, + ) + } + (None, Some(box_id)) => { + let Some(box_name) = no_switch_box_name(boxes, box_id) else { + tracing::debug!( + %box_id, + "refused an expose decision report for a box id the host holds nothing for" + ); + return BoxControlReply::Error { + error: format!("no box with id {box_id} is known to the VM host"), + }; + }; + tracing::debug!( + box = %box_name, + %box_id, + key = "box_id", + "found the expose decision report's box by its box id" + ); + (box_name, GuestAuditKey::Box(box_id), Some(box_id)) + } + (None, None) => { + tracing::debug!("refused an expose decision report that names no box"); + return BoxControlReply::Error { + error: "the expose decision report names no box".to_string(), + }; + } }; - let admission = admit_guest_audit( - audit_path, - request.switch_address, - None, - std::time::Instant::now(), - ); - let audited = take_guest_audit( - audit_path, - record.name(), - request.switch_address, - &admission, - ); + let admission = admit_guest_audit(audit_path, cap_key, None, std::time::Instant::now()); + let audited = take_guest_audit(audit_path, &box_name, cap_key, &admission); if audited { tracing::info!( - box = %record.name(), + box = %box_name, + switch_address = ?request.switch_address, + box_id = ?box_id, port = request.port, decision = ?request.decision, decided_by = ?request.decided_by, @@ -2726,8 +2822,11 @@ fn audit_expose_decision( ts: unix_now_secs(), event: "expose_decision", reported_by: "guest", - box_name: record.name().to_string(), + box_name, switch_address: request.switch_address, + // The 32 lowercase hex form every audit record spells a box + // id in ([`AskAudit::with_facts`]). + box_id: box_id.map(|box_id| box_id.simple()), port: request.port, decision: request.decision, decided_by: request.decided_by, @@ -2738,6 +2837,34 @@ fn audit_expose_decision( BoxControlReply::Audited { audited } } +/// The name of the box a report with no switch address names by `box_id` +/// (NET-046): a row filed under the id, a name held for it (a named +/// `host_ip` box), or a resident `host_ip` box, which has no name the host +/// holds and is named by its id. `None` when the host holds nothing under +/// the id. +fn no_switch_box_name(boxes: &BoxRegistry, box_id: minimald_rpc::BoxId) -> Option { + let table = boxes.table(); + if let Some(record) = table + .rows() + .into_iter() + .find(|record| record.box_id() == box_id.to_bytes()) + { + return Some(record.name().to_string()); + } + if let Some((name, _)) = boxes + .held_name_owners() + .into_iter() + .find(|(_, owner)| *owner == Some(box_id)) + { + return Some(name); + } + table + .host_ip_boxes() + .iter() + .any(|rules| rules.session_id() == box_id) + .then(|| box_id.to_string()) +} + /// Serves the in-VM daemon's refused egress report: one record per refused /// flow in the host's audit log, under the box's cap, the box named from /// the row at the report's switch address. A repeat of a flow already @@ -2764,14 +2891,14 @@ fn audit_refused_egress( let flow = format!("{destination}/{proto}/{rule}"); let admission = admit_guest_audit( audit_path, - request.switch_address, + GuestAuditKey::Switch(request.switch_address), Some(flow), std::time::Instant::now(), ); let audited = take_guest_audit( audit_path, record.name(), - request.switch_address, + GuestAuditKey::Switch(request.switch_address), &admission, ); if audited { @@ -3590,6 +3717,21 @@ fn record_ask_answer( dismissed = ended.dismissed, "recorded the attached client's answer to a pending ask; the first answer wins" ); + // A yes admits the port into the row (NET-045), so it gets the + // same admission record an allow-decided expose does (NET-046). + if let minimald_rpc::AskAdmitOutcome::Admitted { port, proto, .. } = ended.outcome { + append_audit_line( + audit_path, + &AdmittedPortAudit { + ts: unix_now_secs(), + box_name: ended.facts.name.clone(), + switch_address: ended.facts.switch_address, + port, + proto, + source: PortReportSource::Ask, + }, + ); + } if let Some(offered) = &ended.offered_next { log_and_audit_offer(audit_path, offered); } @@ -6850,10 +6992,10 @@ mod tests { ); } let box_id = format!(r#""box_id":"{}""#, web.box_id.simple()); - for line in audit - .lines() - .filter(|line| !line.contains("refused_unknown_id")) - { + // The yes also writes an admission record, which is not an ask line. + for line in audit.lines().filter(|line| { + line.contains(r#""event":"ask""#) && !line.contains("refused_unknown_id") + }) { assert!( line.contains(&box_id) && line.contains(r#""proto":"tcp""#), "each ask line names the box id and the protocol: {line}" @@ -7931,7 +8073,8 @@ mod tests { let reply = control( &guest, &BoxControlRequest::ReportExposeDecision(minimald_rpc::ExposeDecisionReport { - switch_address: web.switch_address, + switch_address: Some(web.switch_address), + box_id: None, port, decision, decided_by: minimald_rpc::ExposeDecidedBy::BoxPolicy, @@ -7944,7 +8087,8 @@ mod tests { let stray = control( &guest, &BoxControlRequest::ReportExposeDecision(minimald_rpc::ExposeDecisionReport { - switch_address: Ipv4Addr::new(192, 0, 2, 1), + switch_address: Some(Ipv4Addr::new(192, 0, 2, 1)), + box_id: None, port: 3000, decision: boxes::DynamicIngress::Allow, decided_by: minimald_rpc::ExposeDecidedBy::BoxPolicy, @@ -7960,7 +8104,8 @@ mod tests { let wrong_door = control( &sock_path, &BoxControlRequest::ReportExposeDecision(minimald_rpc::ExposeDecisionReport { - switch_address: web.switch_address, + switch_address: Some(web.switch_address), + box_id: None, port: 3001, decision: boxes::DynamicIngress::Allow, decided_by: minimald_rpc::ExposeDecidedBy::BoxPolicy, @@ -7987,6 +8132,271 @@ mod tests { assert_eq!(records[1]["outcome"], "published"); } + /// NET-046 for a box with no switch: its report carries its box id in + /// place of a row key, and the host names the box from what it holds + /// under that id. A `none` box is named by the name `min` holds for it + /// at create, over the host's door, and a resident `host_ip` box with no + /// held name is named by its id. A report + /// for an id the host holds nothing for, or one that names no box, is + /// refused and writes nothing. An older guest's report, which always + /// carries a switch address and never a box id, still reads. + #[test] + fn expose_decision_recorded_for_no_switch_box() { + let dir = tempfile::TempDir::new().expect("temp dir"); + let (sock_path, _server, registry, _answerer, _proxy_publish) = + spawn_server(dir.path()).expect("server binds"); + let guest = sock_path.with_file_name(GUEST_CONTROL_SOCK_FILE); + let named = + boxes::SessionId::parse_str("00000000-0000-4000-8000-0000000000a1").expect("a box id"); + let unnamed = + boxes::SessionId::parse_str("00000000-0000-4000-8000-0000000000a2").expect("a box id"); + let unknown = + boxes::SessionId::parse_str("00000000-0000-4000-8000-0000000000a3").expect("a box id"); + // `named` is a `none` box: `min` holds its name at create, over the + // host's door, and that hold is all the host holds for it. + assert_eq!( + control( + &sock_path, + &BoxControlRequest::HoldBoxName(HoldBoxNameRequest { + name: "api".to_string(), + session_id: Some(named), + }), + ) + .expect("the hold is answered"), + BoxControlReply::NameHeld { + name: "api".to_string(), + held: true, + } + ); + assert!(registry.admit_host_ip_box(unnamed, None)); + + let report = |box_id: Option, port: u16| { + control( + &guest, + &BoxControlRequest::ReportExposeDecision(minimald_rpc::ExposeDecisionReport { + switch_address: None, + box_id, + port, + // An `ask` box with nobody attached, refused closed. + decision: boxes::DynamicIngress::Ask, + decided_by: minimald_rpc::ExposeDecidedBy::Daemon, + outcome: minimald_rpc::ExposeDecisionOutcome::Refused, + }), + ) + .expect("the report is answered") + }; + assert_eq!( + report(Some(named), 4000), + BoxControlReply::Audited { audited: true } + ); + assert_eq!( + report(Some(unnamed), 4001), + BoxControlReply::Audited { audited: true } + ); + let stray = report(Some(unknown), 4002); + assert!( + matches!(stray, BoxControlReply::Error { .. }), + "a report for an id the host holds nothing for is refused: {stray:?}" + ); + let keyless = report(None, 4003); + assert!( + matches!(keyless, BoxControlReply::Error { .. }), + "a report that names no box is refused: {keyless:?}" + ); + + let records: Vec<_> = host_audit_records(&guest) + .into_iter() + .filter(|record| record["event"] == "expose_decision") + .collect(); + assert_eq!(records.len(), 2, "one record per known box: {records:?}"); + assert_eq!(records[0]["box"], "api"); + assert_eq!(records[0]["box_id"], named.simple()); + assert_eq!(records[0]["port"], 4000); + assert_eq!(records[0]["decision"], "ask"); + assert_eq!(records[0]["decided_by"], "daemon"); + assert_eq!(records[0]["outcome"], "refused"); + assert_eq!(records[0]["reported_by"], "guest"); + assert!( + records[0].get("switch_address").is_none(), + "a box with no switch has no row key to record: {records:?}" + ); + assert_eq!(records[1]["box"], unnamed.to_string()); + assert_eq!(records[1]["box_id"], unnamed.simple()); + assert_eq!(records[1]["port"], 4001); + + // Each box with no switch has its own cap window: one box that + // passes its cap never suppresses the record of another. The box + // wrote one record above, so this fills the rest of its cap. + for port in 1..(GUEST_AUDIT_RECORDS_PER_WINDOW as u16) { + report(Some(named), 5000 + port); + } + assert_eq!( + report(Some(named), 6000), + BoxControlReply::Audited { audited: false }, + "the flooding box passed its own cap" + ); + assert_eq!( + report(Some(unnamed), 6001), + BoxControlReply::Audited { audited: true }, + "another box with no switch still gets its record" + ); + + // The count line for a box with no switch names its box id. + let audit_path = audit_log_path(&guest); + let later = std::time::Instant::now() + GUEST_AUDIT_WINDOW; + let admission = admit_guest_audit(&audit_path, GuestAuditKey::Box(named), None, later); + assert_eq!(admission, GuestAuditAdmission::Write { suppressed: 1 }); + assert!(take_guest_audit( + &audit_path, + "api", + GuestAuditKey::Box(named), + &admission + )); + let suppressed: Vec<_> = host_audit_records(&guest) + .into_iter() + .filter(|record| record["event"] == "audit_suppressed") + .collect(); + assert_eq!(suppressed.len(), 1, "one count line: {suppressed:?}"); + assert_eq!(suppressed[0]["box"], "api"); + assert_eq!(suppressed[0]["box_id"], named.simple()); + assert!( + suppressed[0].get("switch_address").is_none(), + "a box with no switch has no row key to record: {suppressed:?}" + ); + + // A box with no switch that ends writes the count its window still + // holds, and its window leaves the table. A host-address box ends + // when it retires, and a named one also when its hold is released. + let window_held = |box_id| { + GUEST_AUDIT_WINDOWS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .contains_key(&(audit_path.clone(), GuestAuditKey::Box(box_id))) + }; + let suppressed_for = |box_id: boxes::SessionId| { + host_audit_records(&guest) + .into_iter() + .filter(|record| { + record["event"] == "audit_suppressed" && record["box_id"] == box_id.simple() + }) + .collect::>() + }; + // The unnamed box wrote two records: fill the rest of its cap, and + // pass it once. + for port in 2..=(GUEST_AUDIT_RECORDS_PER_WINDOW as u16) { + report(Some(unnamed), 7000 + port); + } + assert!(window_held(unnamed)); + assert!(suppressed_for(unnamed).is_empty()); + control( + &sock_path, + &BoxControlRequest::RetireHostIpBox(minimald_rpc::RetireHostIpBoxRequest { + session_id: unnamed, + }), + ) + .expect("the retire is answered"); + let flushed = suppressed_for(unnamed); + assert_eq!(flushed.len(), 1, "the retire writes the count: {flushed:?}"); + assert_eq!(flushed[0]["box"], unnamed.to_string()); + assert_eq!(flushed[0]["suppressed"], 1); + assert!(!window_held(unnamed), "the retired box's window is gone"); + + // The named box's new window holds one record: fill its cap, and + // pass it once. + for port in 1..=(GUEST_AUDIT_RECORDS_PER_WINDOW as u16) { + report(Some(named), 8000 + port); + } + control( + &sock_path, + &BoxControlRequest::ReleaseBoxName(HoldBoxNameRequest { + name: "api".to_string(), + session_id: Some(named), + }), + ) + .expect("the release is answered"); + let flushed = suppressed_for(named); + assert_eq!( + flushed.len(), + 2, + "the release writes the count: {flushed:?}" + ); + assert_eq!(flushed[1]["box"], "api"); + assert_eq!(flushed[1]["suppressed"], 1); + assert!(!window_held(named), "the released box's window is gone"); + + // An older guest's report: a switch address, and no box id. + let old = parse_request( + r#"{"verb":"report_expose_decision","switch_address":"100.64.128.9","port":3000,"decision":"allow","decided_by":"box-policy","outcome":"published"}"#, + ) + .expect("an older guest's report still reads"); + let BoxControlRequest::ReportExposeDecision(old) = old else { + panic!("the line is an expose decision report"); + }; + assert_eq!(old.switch_address, Some(Ipv4Addr::new(100, 64, 128, 9))); + assert_eq!(old.box_id, None); + } + + /// NET-046 under `ask`: an attached client's yes admits the port, and + /// the host's audit log gets the same admission record an + /// allow-decided expose writes, its source `ask`. A no admits nothing + /// and writes no admission record. + #[test] + fn ask_yes_writes_admission_line() { + let host = AskHost::start(); + let web = host.register_ask_box("web"); + let mut client = attach_client(&host, &web); + + let mut guest = guest_ask(&host, &web, ASK_PORT); + let offer = expect_offer(&mut client); + assert_eq!( + host.answer(offer.ask_id, AskAnswer::Yes), + BoxControlReply::AskAnswerRecorded { + ask_id: offer.ask_id, + recorded: true + } + ); + assert!(matches!( + expect_outcome(&mut guest), + AskAdmitOutcome::Admitted { .. } + )); + assert!(matches!( + client.next(), + BoxControlReply::PendingAskDismissed { .. } + )); + + let mut refused_guest = guest_ask(&host, &web, ASK_PORT + 1); + let offer = expect_offer(&mut client); + assert_eq!( + host.answer(offer.ask_id, AskAnswer::No), + BoxControlReply::AskAnswerRecorded { + ask_id: offer.ask_id, + recorded: true + } + ); + assert_eq!( + refused(expect_outcome(&mut refused_guest)), + AskRefused::Denied + ); + + let admissions: Vec<_> = host_audit_records(&host.guest) + .into_iter() + .filter(|record| record.get("source").is_some()) + .collect(); + assert_eq!( + admissions.len(), + 1, + "a yes writes one admission record and a no writes none: {admissions:?}" + ); + assert_eq!(admissions[0]["box"], "web"); + assert_eq!(admissions[0]["port"], ASK_PORT); + assert_eq!(admissions[0]["proto"], "tcp"); + assert_eq!(admissions[0]["source"], "ask"); + assert_eq!( + admissions[0]["switch_address"], + web.switch_address.to_string() + ); + } + /// A refused own-address egress flow the in-VM daemon reports lands in /// the host's audit log: one record per refused flow, never per frame, so /// a repeat of the same flow writes nothing more. The records a box @@ -8063,7 +8473,8 @@ mod tests { let expose = control( &guest, &BoxControlRequest::ReportExposeDecision(minimald_rpc::ExposeDecisionReport { - switch_address: web.switch_address, + switch_address: Some(web.switch_address), + box_id: None, port: 4000, decision: boxes::DynamicIngress::Deny, decided_by: minimald_rpc::ExposeDecidedBy::BoxPolicy, @@ -8089,7 +8500,7 @@ mod tests { let later = std::time::Instant::now() + GUEST_AUDIT_WINDOW; let admission = admit_guest_audit( &audit_path, - web.switch_address, + GuestAuditKey::Switch(web.switch_address), Some("later".to_string()), later, ); @@ -8097,7 +8508,7 @@ mod tests { assert!(take_guest_audit( &audit_path, "web", - web.switch_address, + GuestAuditKey::Switch(web.switch_address), &admission )); let suppressed: Vec<_> = host_audit_records(&guest)