diff --git a/AGENTS.md b/AGENTS.md index 7433a34f89..fbaf57aed1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -148,10 +148,10 @@ Verified against the current tree; sources in parentheses. resolutions. The fetch scripts warn explicitly: do not run it as part of artifact fetching (`scripts/fetch-libkrun.sh`). - **Initramfs features come from the `FEATURES` env.** - `scripts/build-initramfs.sh` compiles the guest `minimald` with - `FEATURES` (empty by default; the justfile passes `networking-proxy`). - Calling the script directly yields a guest daemon without networking - features; with a prebuilt `MINIMALD_BIN`, `TARGET`/`FEATURES` are ignored. + `scripts/build-initramfs.sh` still honours `FEATURES` when it compiles the + guest `minimald`, but the justfile passes none, so every guest daemon the + recipes ship carries the default feature set; with a prebuilt + `MINIMALD_BIN`, `TARGET`/`FEATURES` are ignored. - **macOS `--output` must stay under the repo.** On macOS the `minimal` shim runs the CLI inside a VM and only syncs the project dir back to the host, so `materialize --output` paths outside the repo tree are not visible to diff --git a/Cargo.lock b/Cargo.lock index 9cd49d0e4f..bb3a2804a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -216,45 +216,6 @@ dependencies = [ "term", ] -[[package]] -name = "asn1-rs" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" -dependencies = [ - "asn1-rs-derive", - "asn1-rs-impl", - "displaydoc", - "nom", - "num-traits", - "rusticata-macros", - "thiserror 2.0.20", - "time", -] - -[[package]] -name = "asn1-rs-derive" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", - "synstructure", -] - -[[package]] -name = "asn1-rs-impl" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "async-compression" version = "0.4.48" @@ -500,9 +461,6 @@ name = "bit-vec" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" -dependencies = [ - "serde", -] [[package]] name = "bitflags" @@ -1608,20 +1566,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "der-parser" -version = "10.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" -dependencies = [ - "asn1-rs", - "displaydoc", - "nom", - "num-bigint 0.4.8", - "num-traits", - "rusticata-macros", -] - [[package]] name = "deranged" version = "0.5.8" @@ -4147,10 +4091,8 @@ dependencies = [ "paths", "proptest", "rand_core 0.6.4", - "rcgen", "russh", "russh-sftp", - "rustls", "sandbox2", "serde", "serde_json_lenient", @@ -4163,7 +4105,6 @@ dependencies = [ "tempfile", "thiserror 2.0.20", "tokio", - "tokio-rustls", "tokio-util", "tokio-vsock", "tracing", @@ -4739,15 +4680,6 @@ dependencies = [ "thiserror 2.0.20", ] -[[package]] -name = "oid-registry" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" -dependencies = [ - "asn1-rs", -] - [[package]] name = "once_cell" version = "1.21.4" @@ -5112,16 +5044,6 @@ dependencies = [ "hmac 0.13.0", ] -[[package]] -name = "pem" -version = "4.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" -dependencies = [ - "base64 0.23.1", - "serde_core", -] - [[package]] name = "pem-rfc7468" version = "1.0.0" @@ -5958,20 +5880,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "rcgen" -version = "0.14.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" -dependencies = [ - "pem", - "ring", - "rustls-pki-types", - "time", - "x509-parser", - "yasna", -] - [[package]] name = "redox_syscall" version = "0.5.18" @@ -6309,15 +6217,6 @@ dependencies = [ "semver", ] -[[package]] -name = "rusticata-macros" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" -dependencies = [ - "nom", -] - [[package]] name = "rustix" version = "1.1.4" @@ -6340,7 +6239,6 @@ dependencies = [ "aws-lc-rs", "log", "once_cell", - "ring", "rustls-pki-types", "rustls-webpki", "subtle", @@ -8831,24 +8729,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "x509-parser" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" -dependencies = [ - "asn1-rs", - "data-encoding", - "der-parser", - "lazy_static", - "nom", - "oid-registry", - "ring", - "rusticata-macros", - "thiserror 2.0.20", - "time", -] - [[package]] name = "xattr" version = "1.6.1" @@ -8871,16 +8751,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" -[[package]] -name = "yasna" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" -dependencies = [ - "bit-vec 0.9.1", - "time", -] - [[package]] name = "yoke" version = "0.8.3" diff --git a/Cargo.toml b/Cargo.toml index 1ce507bb6d..001467166b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -148,10 +148,7 @@ rand = "0.10" rand_core = { version = "0.6", features = ["getrandom"] } rayon = "1.12" ratatui = "0.30" -rcgen = { version = "0.14", default-features = false, features = ["crypto", "pem", "ring"] } regex = "1" # keep in sync with nickel-lang-core -rustls = { version = "0.23", default-features = false, features = ["ring", "logging", "std"] } -tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "logging"] } reqwest = { version = "0.13.4", features = ["stream"], default-features = false } # keep in sync with google-cloud-gax rustc-hash = "2.1.3" serde = { version = "1.0", features = ["derive", "rc"] } # Keep within the same minor version as nickel-lang-core diff --git a/crates/minimal/Cargo.toml b/crates/minimal/Cargo.toml index 671d087488..251576fb0e 100644 --- a/crates/minimal/Cargo.toml +++ b/crates/minimal/Cargo.toml @@ -17,9 +17,9 @@ name = "min" path = "src/main.rs" [features] -# Off by default: gates the `mesh` and `ssh-forward` CLI subcommands. WireGuard -# mesh (UC7 / UC2b-A) and the SSH port-forward fallback are deferred for now; the -# daemon-side `direct-tcpip` handler is behind minimald's `ssh-forward` feature. +# Off by default: gates the `mesh` CLI subcommand. WireGuard mesh (UC7 / UC2b-A) +# is deferred for now; the daemon-side `direct-tcpip` handler needs no feature +# and is served in every build. remote-access = [] [dependencies] diff --git a/crates/minimal/src/cmd/list.rs b/crates/minimal/src/cmd/list.rs index d5e0ceae1d..59decfef43 100644 --- a/crates/minimal/src/cmd/list.rs +++ b/crates/minimal/src/cmd/list.rs @@ -309,7 +309,6 @@ pub async fn cmd_ls(global: &GlobalArgs, args: LsArgs) -> Result<(), anyhow::Err // is exactly what will go on using hostnames that no longer resolve — and // stdout stays clean for the parser either way. warn_if_hostname_routing_down(resp.hostname_routing_unavailable.as_deref(), "min ls"); - warn_if_mtls_proxy_down(resp.mtls_proxy_unavailable.as_deref()); format_ls(&mut std::io::stdout(), &args, &resp)?; Ok(()) } @@ -351,17 +350,6 @@ pub(crate) fn warn_if_hostname_routing_down(reason: Option<&str>, command: &str) } } -/// Tells the user the mTLS reverse proxy is not serving, and why. -/// -/// Kept separate from [`warn_if_hostname_routing_down`] so the two faults read -/// as what they are: hostnames failing to resolve and TLS termination being -/// absent are different problems with different fixes. -pub(crate) fn warn_if_mtls_proxy_down(reason: Option<&str>) { - if let Some(reason) = reason { - eprintln!("warning: the mTLS reverse proxy is not serving: {reason}"); - } -} - /// Format the session list for the given output mode. Split from /// [`cmd_ls`] so integration tests can capture output into a buffer /// instead of stdout. diff --git a/crates/minimal/src/cmd/session.rs b/crates/minimal/src/cmd/session.rs index 5084e781ab..cf12987b6e 100644 --- a/crates/minimal/src/cmd/session.rs +++ b/crates/minimal/src/cmd/session.rs @@ -279,7 +279,6 @@ pub(crate) async fn activate_session( created.hostname_routing_unavailable.as_deref(), "min session activate", ); - warn_if_mtls_proxy_down(created.mtls_proxy_unavailable.as_deref()); let id = created.id; // From here the session exists on the daemon in an unfinalized state. diff --git a/crates/minimal/tests/cli.rs b/crates/minimal/tests/cli.rs index 32ed109b4b..e9d3553f14 100644 --- a/crates/minimal/tests/cli.rs +++ b/crates/minimal/tests/cli.rs @@ -44,7 +44,6 @@ fn ls_shows_shared_resource_pool() { let resp = ListSessionsResponse { daemon_version: None, hostname_routing_unavailable: None, - mtls_proxy_unavailable: None, resource_pool: Some(ResourcePool { cpu_cores: 8, memory_bytes: 16 * 1024 * 1024 * 1024, @@ -81,7 +80,6 @@ fn ls_table_exposes_project_path_and_status() { let resp = ListSessionsResponse { daemon_version: None, hostname_routing_unavailable: None, - mtls_proxy_unavailable: None, resource_pool: None, sessions: vec![minimald_rpc::ListSessionsEntry { id: SessionId::nil(), @@ -1092,6 +1090,134 @@ async fn ls_warning_clears_on_recovery() { ); } +// --- retired surfaces (NET-109 / NET-110) --- + +/// No build of the daemon carries the retired mTLS reverse proxy, its +/// client-certificate RPC, or the `ssh-forward` feature that compiled +/// `direct-tcpip` out (NET-109, NET-110). A client crate cannot reach the +/// daemon's build flags from here, so assert on its sources and manifests — +/// the same source-scan approach `minimal`'s own `login_mints_no_certificate` +/// uses to prove a verb dropped a surface. +#[test] +fn retired_surfaces_absent() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .ancestors() + .nth(2) + .expect("crates/minimal sits two levels below the workspace root"); + + let source = |rel: &str| { + std::fs::read_to_string(root.join(rel)) + .unwrap_or_else(|e| panic!("readable source {rel}: {e}")) + }; + + let retired_surfaces: &[(&str, &[&str])] = &[ + // The proxy serves plain HTTP only: no TLS port, no certificate + // authority, no TLS-terminating serve loop, no TLS deps. + ( + "crates/minimald/src/net/proxy.rs", + &[ + "HTTPS_PROXY_PORT", + "CertAuthority", + "serve_https", + "tokio_rustls", + "networking-proxy", + ], + ), + // The daemon opens one routing listener and keeps no proxy state. + ( + "crates/minimald/src/server.rs", + &["mtls", "7655", "cert_authority", "networking-proxy"], + ), + // No client-certificate RPC handler or dispatch arm, and no + // mTLS field on the replies. + ( + "crates/minimald/src/rpc.rs", + &[ + "IssueClientCert", + "mtls_proxy_unavailable", + "networking-proxy", + ], + ), + // No crypto-provider install for the removed feature, and no + // second-proxy comment in the startup path. + ("crates/minimald/src/main.rs", &["networking-proxy", "7655"]), + // direct-tcpip is served in every build: neither the handler nor + // the relay is behind a feature gate anymore. + ( + "crates/minimald/src/connection.rs", + &[ + "feature = \"ssh-forward\"", + "feature = \"networking-proxy\"", + ], + ), + // Both features and their optional TLS deps are gone from the + // manifest, so no build can turn them back on. + ( + "crates/minimald/Cargo.toml", + &[ + "networking-proxy", + "ssh-forward", + "rcgen", + "rustls", + "tokio-rustls", + ], + ), + // The wire contract carries no client-certificate types and no + // mTLS-unavailable fields. + ( + "crates/minimald-rpc/src/lib.rs", + &["IssueClientCert", "mtls_proxy_unavailable"], + ), + // The workspace drops the certificate generator only minimald used. + ("Cargo.toml", &["rcgen"]), + // Nothing passes a removed feature to the daemon builds. + ("justfile", &["networking-proxy", "{{features}}"]), + ]; + for (rel, retired) in retired_surfaces.iter().copied() { + let text = source(rel); + for &token in retired { + assert!( + !text.contains(token), + "{rel} still names the retired surface `{token}` (NET-109)" + ); + } + } +} + +/// The daemon's `ListSessions` reply no longer carries the mTLS field, and a +/// reply without it decodes: `min ls` keeps reading the list, and never +/// prints an mTLS warning again (NET-109). A reply from an older daemon that +/// still sends the field decodes too — an unknown field is skipped, so the +/// version skew never breaks the list. +#[test] +fn session_list_decodes_without_mtls_field() { + let resp = ListSessionsResponse { + daemon_version: Some("test".to_string()), + hostname_routing_unavailable: None, + resource_pool: None, + sessions: vec![], + }; + + // The reply this build's daemon sends carries no mtls field. + let json = serde_json_lenient::to_string(&resp).unwrap(); + assert!( + !json.contains("mtls_proxy_unavailable"), + "the serialized reply must not carry the retired field: {json}" + ); + + // And it decodes back through the client's own type. + let decoded: ListSessionsResponse = serde_json_lenient::from_str(&json).unwrap(); + assert_eq!(decoded.daemon_version.as_deref(), Some("test")); + assert!(decoded.sessions.is_empty()); + + // An older daemon's reply, still carrying the field, decodes as well: + // the extra field is ignored rather than fatal. + let older = r#"{"daemon_version":"old","mtls_proxy_unavailable":"still here","sessions":[]}"#; + let from_older: ListSessionsResponse = serde_json_lenient::from_str(older).unwrap(); + assert_eq!(from_older.daemon_version.as_deref(), Some("old")); + assert!(from_older.sessions.is_empty()); +} + // --- helpers --- /// Creates a session whose workspace mfile declares a `[session.vars]` diff --git a/crates/minimald-rpc/src/lib.rs b/crates/minimald-rpc/src/lib.rs index 524d8b518f..76fc913a8e 100644 --- a/crates/minimald-rpc/src/lib.rs +++ b/crates/minimald-rpc/src/lib.rs @@ -245,18 +245,6 @@ pub struct ListSessionsResponse { /// daemon log, and the user is at a terminal watching curl fail. #[serde(default, skip_serializing_if = "Option::is_none")] pub hostname_routing_unavailable: Option, - /// Why the mTLS reverse proxy (`:7655`) is not serving, when it is not. - /// - /// Separate from [`Self::hostname_routing_unavailable`] because they are - /// different services with different consumers: losing `:7654` costs every - /// session its hostname, losing `:7655` costs whatever terminates TLS - /// against it. Reporting them through one field would tell a user their - /// hostnames are broken when they are not. - /// - /// Always `None` from a daemon built without the `networking-proxy` - /// feature, which is the default — there is no proxy to be unavailable. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub mtls_proxy_unavailable: Option, } impl OneshotSshRpc for ListSessions { @@ -446,15 +434,6 @@ pub struct CreateSessionResponse { /// looking healthy either way. #[serde(default, skip_serializing_if = "Option::is_none")] pub hostname_routing_unavailable: Option, - /// Why the mTLS reverse proxy is not serving, when it is not — see - /// [`ListSessionsResponse::mtls_proxy_unavailable`]. - /// - /// Here for the same reason as the field above it: both proxies are - /// daemon-wide rather than session-scoped, so the thing that decides - /// whether activation should mention them is whether the person - /// activating is about to depend on one, and that is not ours to know. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub mtls_proxy_unavailable: Option, } impl OneshotSshRpc for CreateSession { @@ -846,43 +825,6 @@ impl OneshotSshRpc for DynamicPortMap { type Response = Errorable; } -// --------------------------------------------------------------------------- -// mTLS client certificate issuance (R4.4 / `minimal login`). -// --------------------------------------------------------------------------- - -/// An RPC that signs and returns a fresh client certificate for use with the -/// HTTPS reverse proxy's mTLS authentication (R4.4). The caller supplies a -/// subject common name; the daemon generates a key pair, signs the certificate -/// with its internal CA, and returns PEM-encoded certificate and private key. -/// The CA certificate PEM is also returned so the client can add it to -/// its trust store. -pub struct IssueClientCert; - -/// Request for the [`IssueClientCert`] RPC. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct IssueClientCertRequest { - /// Subject common name for the client certificate (e.g. the OS username). - pub subject_cn: String, -} - -/// Response for the [`IssueClientCert`] RPC. -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct IssueClientCertResponse { - /// PEM-encoded client certificate signed by the daemon's CA. - pub cert_pem: String, - /// PEM-encoded PKCS#8 private key matching the certificate. - pub key_pem: String, - /// PEM-encoded CA certificate, so the client can trust the HTTPS proxy's - /// server certificate. - pub ca_cert_pem: String, -} - -impl OneshotSshRpc for IssueClientCert { - const NAME: &'static str = constcat::concat!(RPC_SUBSYSTEM_PREFIX, "IssueClientCert"); - type Request<'a> = IssueClientCertRequest; - type Response = Errorable; -} - // --------------------------------------------------------------------------- // WireGuard mesh status (Unit 4: R4.6). // @@ -1448,7 +1390,6 @@ mod tests { id: SessionId::parse_str("00000000-0000-0000-0000-000000000001").unwrap(), daemon_version: Some("0.6.0".into()), hostname_routing_unavailable: None, - mtls_proxy_unavailable: None, }; assert_eq!(round_trip(&resp), resp); } @@ -1463,7 +1404,6 @@ mod tests { serde_json_lenient::from_str(r#"{"sessions":[],"daemon_version":"0.5.0"}"#) .expect("a pre-field ListSessions reply must still decode"); assert!(list.hostname_routing_unavailable.is_none()); - assert!(list.mtls_proxy_unavailable.is_none()); let create: Errorable = serde_json_lenient::from_str( r#"{"id":"00000000-0000-0000-0000-000000000001","daemon_version":"0.5.0"}"#, @@ -1472,7 +1412,6 @@ mod tests { match create { Errorable::Ok(c) => { assert!(c.hostname_routing_unavailable.is_none()); - assert!(c.mtls_proxy_unavailable.is_none()); } Errorable::Err { error } => panic!("expected Ok, got {error}"), } @@ -1486,7 +1425,6 @@ mod tests { let resp = ListSessionsResponse { daemon_version: Some("0.6.0".into()), hostname_routing_unavailable: None, - mtls_proxy_unavailable: None, resource_pool: None, sessions: vec![], }; @@ -1495,10 +1433,6 @@ mod tests { !json.contains("hostname_routing_unavailable"), "healthy reply should omit the field, got {json}" ); - assert!( - !json.contains("mtls_proxy_unavailable"), - "healthy reply should omit the mTLS field too, got {json}" - ); let down = ListSessionsResponse { hostname_routing_unavailable: Some("port 7654 is held".into()), diff --git a/crates/minimald/Cargo.toml b/crates/minimald/Cargo.toml index 35f016d1e0..2dd9a24229 100644 --- a/crates/minimald/Cargo.toml +++ b/crates/minimald/Cargo.toml @@ -7,17 +7,10 @@ publish.workspace = true license.workspace = true [features] -# Enables the B8 HTTPS reverse proxy with mTLS termination (R4.4–R4.7) in front -# of the shared B5 routing core. Requires the rustls/rcgen/tokio-rustls deps. -networking-proxy = ["dep:rcgen", "dep:rustls", "dep:tokio-rustls"] # WireGuard mesh peer and its CLI/RPC plumbing (Unit 4). Off by default so the # default `minimald` build pulls in no WireGuard code and pays no binary-size or # startup cost (R4.7); enable with `--features networking-wg`. networking-wg = ["dep:boringtun", "dep:base64", "dep:rand_core"] -# Enables the SSH `direct-tcpip` (LocalForward) handler for `minimal ssh-forward` -# (R4.8/R4.9). Off by default so port-forwarding is compiled out and every -# `direct-tcpip` channel is rejected fail-closed; deferred for now (finding #4). -ssh-forward = [] # Exposes the in-process test harness (TestServer/TestClient) so external # crates — notably `minimal`'s integration tests — can spin up a real # minimald server over an in-memory or UDS transport without a separate @@ -88,10 +81,6 @@ switch.workspace = true stdlib.workspace = true version.workspace = true -rcgen = { workspace = true, optional = true } -rustls = { workspace = true, optional = true } -tokio-rustls = { workspace = true, optional = true } - [dev-dependencies] # The two-namespace UC7 mesh integration test (`tests/mesh_uc7.rs`) drives a # tokio runtime and `setns(2)` directly. diff --git a/crates/minimald/src/connection.rs b/crates/minimald/src/connection.rs index 037a8b80b4..332e0e2fe5 100644 --- a/crates/minimald/src/connection.rs +++ b/crates/minimald/src/connection.rs @@ -6,17 +6,13 @@ use sessions::SessionId; use std::{ collections::BTreeMap, sync::{Arc, LazyLock}, + time::Duration, }; -// Used only by the `ssh-forward` direct-tcpip handler. -#[cfg(feature = "ssh-forward")] -use std::time::Duration; use tokio::{ io::{AsyncRead, AsyncWrite}, + net::TcpStream, sync::{Mutex, MutexGuard}, }; -// Used only by the `ssh-forward` direct-tcpip handler. -#[cfg(feature = "ssh-forward")] -use tokio::net::TcpStream; use crate::{ ChannelConfig, RequestedPty, exec, @@ -457,7 +453,9 @@ impl russh::server::Handler for ConnectionHandler { /// /// The connection attempt times out after 10 seconds; a failure rejects the /// channel so the SSH client receives a clean error rather than hanging. - #[cfg(feature = "ssh-forward")] + /// + /// Served in every build: the `ssh-forward` feature gate is retired + /// (NET-110), so a release build forwards ports too. async fn channel_open_direct_tcpip( &mut self, channel: RuChannel, @@ -577,36 +575,25 @@ impl russh::server::Handler for ConnectionHandler { reply.accept().await; + // One info line per served channel open (NET-110): the daemon log — + // and the diagnostics bundle's tail of it — names every direct-tcpip + // channel that relays, with the session it forwarded for and the box + // port it reached. + tracing::info!( + session_id = %session_id, + host = %host, + port, + "direct-tcpip channel open: relaying bytes to the box port" + ); + // Relay bytes bidirectionally: SSH channel ↔ upstream TCP. tokio::spawn(relay_streams(channel.into_stream(), upstream)); Ok(()) } - - /// With the `ssh-forward` feature disabled, port-forwarding is compiled out. - /// Reject every `direct-tcpip` channel so forwarding fails **closed**, rather - /// than relying on whatever russh's default handler does (finding #4 / the - /// user decision to disable ssh-forward for now). - #[cfg(not(feature = "ssh-forward"))] - async fn channel_open_direct_tcpip( - &mut self, - _channel: RuChannel, - _host_to_connect: &str, - _port_to_connect: u32, - _originator_address: &str, - _originator_port: u32, - reply: ChannelOpenHandle, - _session: &mut Session, - ) -> Result<(), Self::Error> { - reply - .reject(russh::ChannelOpenFailure::AdministrativelyProhibited) - .await; - Ok(()) - } } /// Relay bytes bidirectionally between two async streams, logging any relay error. -#[cfg(feature = "ssh-forward")] async fn relay_streams(mut a: A, mut b: B) where A: AsyncRead + AsyncWrite + Unpin, @@ -617,10 +604,7 @@ where } } -// The only test here exercises `relay_streams`, which is itself behind -// `ssh-forward`; gate the whole module so it (and its imports) compile out with -// the feature. -#[cfg(all(test, feature = "ssh-forward"))] +#[cfg(test)] mod tests { use super::*; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -642,4 +626,123 @@ mod tests { client.read_exact(&mut buf2).await.unwrap(); assert_eq!(&buf2, b"world"); } + + /// A `direct-tcpip` channel to a box port relays bytes in the default, + /// featureless build — the configuration a release build ships — because + /// nothing about the handler is behind a feature anymore (NET-110). The + /// open logs one info line naming the session it forwarded for and the + /// port it reached. + #[tokio::test] + async fn direct_tcpip_served_in_release() { + use russh::keys::PublicKeyOrCertificate; + use tokio::net::{TcpListener, UnixStream}; + + use crate::test_harness::{TestServer, captured_log, create_session_req}; + + // Install the capture subscriber before the open happens: the global + // subscriber must already exist when the info line is emitted. + let log = captured_log(); + + // The box port: a loopback listener echoing whatever it receives. + let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + let (mut sock, _) = listener.accept().await.unwrap(); + let mut buf = [0u8; 64]; + loop { + match sock.read(&mut buf).await { + Ok(0) | Err(_) => break, + Ok(n) => sock.write_all(&buf[..n]).await.unwrap(), + } + } + }); + + // The session the forward is scoped to: the SSH username carries its + // UUID, exactly as `ssh -l -L ...` does. + let server = TestServer::new().await; + let req = create_session_req("direct-tcpip", "/tmp"); + let session_id = server + .state + .sessions_manager() + .await + .create_session(req.config, None) + .await + .unwrap(); + + // `TestClient` keeps its russh handle private and this test needs the + // raw `channel_open_direct_tcpip`, so drive both halves of the + // connection the way `TestServer::connect` does. + struct ForwardHandler; + impl russh::client::Handler for ForwardHandler { + type Error = russh::Error; + async fn check_server_key( + &mut self, + _key: &PublicKeyOrCertificate, + ) -> Result { + Ok(true) + } + } + + let host_key = server.state.host_key().await.unwrap(); + let russh_config = Arc::new(russh::server::Config { + keys: vec![host_key], + auth_rejection_time_initial: Some(Duration::ZERO), + nodelay: true, + ..Default::default() + }); + let (server_side, client_side) = UnixStream::pair().unwrap(); + let server_setup = { + let state = server.state.clone(); + let russh_config = russh_config.clone(); + async move { + let (_conn, session_fut) = + Connection::from_stream(server_side, russh_config, state, true) + .await + .expect("handshake over the in-memory pair"); + tokio::spawn(session_fut); + } + }; + let client_setup = russh::client::connect_stream( + Arc::new(russh::client::Config::default()), + client_side, + ForwardHandler, + ); + let (_, handle) = tokio::join!(server_setup, client_setup); + let mut handle = handle.unwrap(); + let auth = handle + .authenticate_none(&session_id.to_string()) + .await + .unwrap(); + assert!(auth.success(), "auth_none should succeed on local UDS"); + + // The point of the test: the channel opens in a build with no + // features, and bytes relay through it to the box port and back. + let channel = handle + .channel_open_direct_tcpip("127.0.0.1", port.into(), "127.0.0.1", 0) + .await + .expect("direct-tcpip must open in the default (release) build"); + let mut channel = channel.into_stream(); + channel.write_all(b"ping").await.unwrap(); + let mut echoed = [0u8; 4]; + channel.read_exact(&mut echoed).await.unwrap(); + assert_eq!(&echoed, b"ping", "the box port must echo the relayed bytes"); + + // Observability (NET-110): the open's info line names the session and + // the box port it reached. + let logged = log.contents(); + let line = logged + .lines() + .find(|l| l.contains("direct-tcpip channel open")) + .unwrap_or_else(|| { + panic!("expected a direct-tcpip channel-open info line, got: {logged}") + }); + assert!( + line.contains(&format!("session_id={session_id}")), + "the open line must name the session, got: {line}" + ); + assert!( + line.contains(&format!("port={port}")), + "the open line must name the box port, got: {line}" + ); + } } diff --git a/crates/minimald/src/main.rs b/crates/minimald/src/main.rs index bfcb99c7bd..4268107595 100644 --- a/crates/minimald/src/main.rs +++ b/crates/minimald/src/main.rs @@ -427,16 +427,6 @@ fn lock_held(path: &std::path::Path) -> std::io::Result { } async fn async_main() -> Result<(), MainError> { - // With `networking-proxy` on, both the `ring` (workspace rustls) and the - // `aws-lc-rs` (google-cloud) providers are compiled in, so rustls cannot - // auto-pick one and panics ("no process-level CryptoProvider") the first time - // a config is built — e.g. when a session build reaches the remote-cache - // HTTPS client, off the proxy's own install path. Install ring explicitly - // here (idempotent; the proxy's later install no-ops). Without - // networking-proxy only one provider is present and rustls auto-installs it. - #[cfg(feature = "networking-proxy")] - let _ = rustls::crypto::ring::default_provider().install_default(); - // Use hardcoded configuration if we are the init process (`argv[0] == "/init"`), which // would indicate we are operating in a single-purpose micro-vm. // @@ -846,9 +836,9 @@ async fn async_main() -> Result<(), MainError> { if !cli.listen_args().unwrap().vsock { // standard path, listening on UDS socket. // - // The B5 host-side egress proxy (:7654) and B8 mTLS reverse proxy - // (:7655) are bound and served by `Server::run` for both DM2 (here) and - // DM1 (the vsock path below), so no separate startup bind happens here. + // The B5 host-side egress proxy (:7654) is bound and served by + // `Server::run` for both DM2 (here) and DM1 (the vsock path below), so + // no separate startup bind happens here. if let Err(e) = std::fs::remove_file(cli.listen_on()) && e.kind() != std::io::ErrorKind::NotFound diff --git a/crates/minimald/src/net/proxy.rs b/crates/minimald/src/net/proxy.rs index e1d3aee136..7f92b27e50 100644 --- a/crates/minimald/src/net/proxy.rs +++ b/crates/minimald/src/net/proxy.rs @@ -1,4 +1,4 @@ -//! The B5 host-side egress proxy and its shared routing core. +//! The host-side egress proxy and its shared routing core. //! //! Unit 3 (UC2a) resolves PTask `*.min.internal` hostnames **host-side**: the host //! resolver is never consulted, so the no-systemd sandbox (hakoniwa) and microVM @@ -13,11 +13,11 @@ //! for, the reason and the status sent (NET-001), so the daemon log — and the //! diagnostics bundle's tail of it — names every refused request. //! -//! [`Router`] is that routing core, factored so #502 (the B8 HTTPS/mTLS reverse -//! proxy) extends it by terminating TLS in front of the same `Host:`-header → -//! registry → target lookup rather than duplicating it. The host-side -//! `*.min.internal` decision supersedes spike #485's systemd-resolved finding -//! (spec Open Question 1). +//! The proxy serves plain HTTP only: the HTTPS/mTLS reverse proxy that once +//! terminated TLS in front of this routing core is retired (NET-109), so the +//! daemon opens no listener but [`EGRESS_PROXY_PORT`] and issues no +//! certificate. The host-side `*.min.internal` decision supersedes spike +//! #485's systemd-resolved finding (spec Open Question 1). use std::io; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; @@ -29,13 +29,11 @@ use tokio::net::{TcpListener, TcpStream}; use super::dns::HostnameRegistry; -/// Port the B5 host-side egress/DNS proxy listens on (TC3). Clients reach it -/// via `HTTP(S)_PROXY`. +/// Port the host-side egress/DNS proxy listens on (TC3). Clients reach it +/// via `HTTP(S)_PROXY`. The one routing listener the daemon opens: the +/// mTLS reverse proxy that once took the next port up is retired (NET-109). pub const EGRESS_PROXY_PORT: u16 = 7654; -/// Port the B8 mTLS reverse proxy listens on (TC7). -pub const HTTPS_PROXY_PORT: u16 = 7655; - /// Default address the egress proxy listens on: loopback, where every /// `*.min.internal` name is reachable. Clients reach it via `HTTP(S)_PROXY`. pub const DEFAULT_PROXY_ADDR: SocketAddr = @@ -59,8 +57,7 @@ const HEAD_READ_TIMEOUT: Duration = Duration::from_secs(30); /// on, or `None` if no live PTask owns it. The host resolver is never consulted. /// /// Factored as a trait so the routing core is decoupled from how the table is -/// shared (the sessions manager owns the live registry) and so #502 can drive -/// the same lookup behind TLS termination. +/// shared (the sessions manager owns the live registry). pub trait HostRoute: Send + Sync + 'static { /// Resolves a `Host:`-header host to the route its requests forward on. fn resolve_host(&self, host: &str) -> Option; @@ -90,8 +87,7 @@ impl HostRoute for std::sync::RwLock { } /// The shared routing core: maps an HTTP authority (`host` or `host:port`) to -/// the upstream socket address a request forwards to. #502 extends this by -/// terminating TLS/mTLS in front of the same lookup. +/// the upstream socket address a request forwards to. pub struct Router { table: Arc, } @@ -264,8 +260,8 @@ struct ParsedRequest<'a> { /// Handles one client connection over any byte stream: read its request head, /// route it by authority, then either return a gateway error or splice it to /// the upstream PTask. Generic over the client transport so the same routing -/// core serves both the plain egress proxy (`TcpStream`) and the TLS-terminated -/// HTTPS proxy (`TlsStream`) added by the `networking-proxy` feature. +/// core serves the egress proxy's `TcpStream` and any other byte stream a +/// caller hands it. /// /// Every refusal — a head that never arrives, an unparseable head, a host no /// live PTask owns, an upstream that will not accept the connection — is @@ -454,262 +450,6 @@ fn log_refusal(host: Option<&str>, reason: &str, status: &str) { } } -// --------------------------------------------------------------------------- -// TLS/mTLS termination extension (R4.4–R4.7, feature = "networking-proxy"). -// -// Wraps the shared `Router` with a rustls TLS layer that requires clients to -// present a certificate signed by the daemon's internal CA. A missing or -// invalid client certificate is rejected at the application layer with a -// `401 Unauthorized` response whose body is empty (no PTask hostname, IP, or -// any internal topology — R4.5). This keeps the TLS handshake itself from -// revealing topology: only well-authenticated clients learn where their -// requests routed. -// --------------------------------------------------------------------------- - -/// The daemon's self-signed certificate authority and the TLS server -/// certificate it issued. Manages the cryptographic material needed for the -/// HTTPS reverse proxy: signing new client certificates (for `minimal login`) -/// and terminating TLS for incoming connections. -#[cfg(feature = "networking-proxy")] -pub struct CertAuthority { - /// CA certificate in DER format; handed to clients by `minimal login` so - /// they can trust the daemon's server certificate. - pub ca_cert_der: rustls::pki_types::CertificateDer<'static>, - /// CA certificate in PEM format; returned by the `IssueClientCert` RPC - /// for use with `curl --cacert`. - pub ca_cert_pem: String, - /// Server certificate DER, presented to HTTPS clients during the - /// TLS handshake. - pub server_cert_der: rustls::pki_types::CertificateDer<'static>, - /// Raw PKCS#8 bytes of the server's private key. - server_key_bytes: Vec, - /// The CA issuer (parameters plus key pair), kept for signing server and - /// client certificates. - issuer: rcgen::Issuer<'static, rcgen::KeyPair>, -} - -#[cfg(feature = "networking-proxy")] -impl std::fmt::Debug for CertAuthority { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("CertAuthority") - .field("ca_cert_der_len", &self.ca_cert_der.len()) - .field("server_cert_der_len", &self.server_cert_der.len()) - .finish_non_exhaustive() - } -} - -#[cfg(feature = "networking-proxy")] -impl CertAuthority { - /// Generates a fresh self-signed CA and a server certificate signed by it. - /// - /// The CA is ECDSA P-256 / SHA-256. Both the CA and the server cert are - /// valid for the `localhost` SAN so a local curl can reach the proxy - /// without specifying an SNI override. - /// - /// # Errors - /// - /// Returns an `rcgen::Error` if key-pair or cert generation fails. - pub fn generate() -> Result { - // CA — unconstrained so it can sign any cert. - let ca_key = rcgen::KeyPair::generate()?; - let mut ca_params = rcgen::CertificateParams::default(); - ca_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); - ca_params - .distinguished_name - .push(rcgen::DnType::CommonName, "Minimal CA"); - let ca_cert = ca_params.self_signed(&ca_key)?; - let ca_cert_der = rustls::pki_types::CertificateDer::from(ca_cert.der().to_vec()); - let ca_cert_pem = ca_cert.pem(); - // Retain the CA as an issuer so it can sign server and client certs. - let issuer = rcgen::Issuer::new(ca_params, ca_key); - - // Server certificate signed by the CA. - let server_key = rcgen::KeyPair::generate()?; - let server_params = rcgen::CertificateParams::new(vec!["localhost".to_string()])?; - let server_cert = server_params.signed_by(&server_key, &issuer)?; - let server_cert_der = rustls::pki_types::CertificateDer::from(server_cert.der().to_vec()); - let server_key_bytes = server_key.serialize_der(); - - Ok(Self { - ca_cert_der, - ca_cert_pem, - server_cert_der, - server_key_bytes, - issuer, - }) - } - - /// Signs a new client certificate for the given subject common name, - /// returning the cert PEM and key PEM. The key pair is generated - /// server-side and handed to the client via `IssueClientCert` so the - /// client can authenticate to the HTTPS proxy without a separate CSR - /// exchange. - /// - /// Returns `(cert_pem, key_pem)`. - /// - /// # Errors - /// - /// Returns an `rcgen::Error` if key-pair or cert generation fails. - pub fn sign_client_cert(&self, subject_cn: &str) -> Result<(String, String), rcgen::Error> { - let client_key = rcgen::KeyPair::generate()?; - // The login username can be non-ASCII; rcgen parses SANs as DNS names - // and rejects those, which would break `minimal login`. The proxy - // authenticates on CA-signed cert presence (not the SAN/CN), so use a - // fixed ASCII SAN and carry the username in the subject CN instead. - let mut client_params = rcgen::CertificateParams::new(vec!["minimal-client".to_string()])?; - let mut client_dn = rcgen::DistinguishedName::new(); - client_dn.push(rcgen::DnType::CommonName, subject_cn); - client_params.distinguished_name = client_dn; - client_params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth]; - let client_cert = client_params.signed_by(&client_key, &self.issuer)?; - Ok((client_cert.pem(), client_key.serialize_pem())) - } - - /// Signs a new client certificate and also returns the cert in DER format - /// for in-process TLS use (e.g., test clients). Returns - /// `(cert_der, key_bytes, cert_pem, key_pem)`. - /// - /// # Errors - /// - /// Returns an `rcgen::Error` if key-pair or cert generation fails. - #[allow(dead_code)] - pub(crate) fn sign_client_cert_der( - &self, - subject_cn: &str, - ) -> Result<(rustls::pki_types::CertificateDer<'static>, Vec), rcgen::Error> { - let client_key = rcgen::KeyPair::generate()?; - // The login username can be non-ASCII; rcgen parses SANs as DNS names - // and rejects those, which would break `minimal login`. The proxy - // authenticates on CA-signed cert presence (not the SAN/CN), so use a - // fixed ASCII SAN and carry the username in the subject CN instead. - let mut client_params = rcgen::CertificateParams::new(vec!["minimal-client".to_string()])?; - let mut client_dn = rcgen::DistinguishedName::new(); - client_dn.push(rcgen::DnType::CommonName, subject_cn); - client_params.distinguished_name = client_dn; - client_params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth]; - let client_cert = client_params.signed_by(&client_key, &self.issuer)?; - let cert_der = rustls::pki_types::CertificateDer::from(client_cert.der().to_vec()); - let key_bytes = client_key.serialize_der(); - Ok((cert_der, key_bytes)) - } - - /// Builds a rustls `ServerConfig` for the HTTPS proxy. - /// - /// The verifier uses `allow_unauthenticated()` so a TLS handshake - /// succeeds even when no client certificate is presented — the - /// application layer then returns `401 Unauthorized`. A presented - /// certificate is validated against the CA trust store by rustls - /// before the handshake completes; an invalid certificate causes a - /// TLS-level failure (the client never gets an HTTP response). - /// - /// # Errors - /// - /// Returns an `io::Error` if the TLS configuration cannot be assembled - /// (malformed cert/key or unsupported crypto). - pub fn build_server_config(&self) -> io::Result> { - // Install ring as the process-default CryptoProvider if not already set. - let _ = rustls::crypto::ring::default_provider().install_default(); - - let mut root_store = rustls::RootCertStore::empty(); - root_store - .add(self.ca_cert_der.clone()) - .map_err(io::Error::other)?; - - let verifier = rustls::server::WebPkiClientVerifier::builder(Arc::new(root_store)) - .allow_unauthenticated() - .build() - .map_err(io::Error::other)?; - - let server_key = rustls::pki_types::PrivateKeyDer::Pkcs8( - rustls::pki_types::PrivatePkcs8KeyDer::from(self.server_key_bytes.clone()), - ); - - let config = rustls::ServerConfig::builder() - .with_client_cert_verifier(verifier) - .with_single_cert(vec![self.server_cert_der.clone()], server_key) - .map_err(io::Error::other)?; - - Ok(Arc::new(config)) - } -} - -/// Serves the HTTPS reverse proxy with mTLS on `listener`. Each accepted TCP -/// connection is TLS-terminated using `tls_config`, then routed via `router` -/// exactly as the plain proxy does — the shared routing core is reused -/// (scope-coordination comment on #502). -/// -/// A connection that arrives **without** a client certificate is answered with -/// `401 Unauthorized` and an empty body (no PTask hostname or IP — R4.5). The -/// rejection is logged as a `tracing::warn!` event with structured fields. -/// -/// A valid client certificate (signed by the daemon's CA) passes through to -/// the routing core. -/// -/// # Errors -/// -/// Returns the accept error if the listener fails. -#[cfg(feature = "networking-proxy")] -pub async fn serve_https( - listener: TcpListener, - router: Router, - tls_config: Arc, -) -> io::Result<()> { - let acceptor = tokio_rustls::TlsAcceptor::from(tls_config); - loop { - let (tcp_stream, peer) = listener.accept().await?; - let acceptor = acceptor.clone(); - let router = router.clone(); - tokio::spawn(async move { - let tls_stream = match acceptor.accept(tcp_stream).await { - Ok(s) => s, - Err(error) => { - tracing::debug!( - component = "https-proxy", - %peer, - %error, - "TLS handshake failed" - ); - return; - } - }; - - // Check whether the client presented a certificate. The verifier - // is configured with `allow_unauthenticated`, so a missing cert - // does NOT fail the TLS handshake — it fails here at the HTTP - // layer with a 401 that leaks no internal topology (R4.5). - let has_cert = tls_stream.get_ref().1.peer_certificates().is_some(); - - if !has_cert { - tracing::warn!( - component = "https-proxy", - %peer, - reason = "no-client-cert", - "mTLS authentication failed: no client certificate presented" - ); - let mut stream = tls_stream; - // Body is intentionally empty — no PTask name or IP (R4.5). - let _ = write_status(&mut stream, "401 Unauthorized").await; - // Shut down cleanly so the peer receives the TLS close_notify - // and the 401 response before the TCP connection closes. - // Without this, the OS sends a TCP RST that can race with the - // client still completing the TLS handshake, causing - // ConnectionReset instead of the clean 401. - let _ = stream.shutdown().await; - return; - } - - if let Err(error) = handle_connection_io(tls_stream, &router).await { - tracing::debug!( - component = "https-proxy", - %peer, - %error, - "HTTPS proxy connection closed with error" - ); - } - }); - } -} - #[cfg(test)] mod tests { use super::*; @@ -1183,23 +923,18 @@ mod tests { } // ----------------------------------------------------------------------- - // TLS / mTLS tests (feature = "networking-proxy"). - // These drive the full stack from TCP connection through TLS handshake to - // the HTTP routing core, asserting the mTLS auth-failure and auth-success - // contracts (R4.5, proof artifacts 2 and 3). + // The proxy is plain HTTP only (NET-109): the HTTPS/mTLS reverse proxy + // that once terminated TLS on the port above the egress proxy is retired, + // so the one listener routes plain HTTP and answers a TLS handshake with + // no TLS bytes at all — there is no certificate to present and no + // termination behind the port in any build. // ----------------------------------------------------------------------- - /// Proof artifact 2 (R4.5 auth-failure non-disclosure): a connection that - /// presents **no** client certificate is answered with `401 Unauthorized` - /// and an empty body — no PTask hostname, IP, or any internal topology. - #[cfg(feature = "networking-proxy")] + /// A plain `GET` routes through `serve` to its PTask, and a TLS + /// ClientHello to the same listener draws no response bytes: the proxy + /// serves HTTP only, so no client can negotiate TLS with it (NET-109). #[tokio::test] - async fn mtls_missing_cert_returns_401_with_no_topology() { - use tokio_rustls::TlsConnector; - - let ca = CertAuthority::generate().expect("CA generation must not fail"); - let tls_config = ca.build_server_config().expect("server config must build"); - + async fn proxy_serves_http_only() { let backend_port = spawn_backend().await; let mut reg = HostnameRegistry::new("dev", false); reg.register_host_net(SessionId::nil(), "mysvc"); @@ -1207,97 +942,41 @@ mod tests { let proxy = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); let proxy_addr = proxy.local_addr().unwrap(); - tokio::spawn(serve_https(proxy, router, tls_config)); - - // Build a TLS client that trusts the CA but presents no client cert. - let mut root_store = rustls::RootCertStore::empty(); - root_store.add(ca.ca_cert_der.clone()).unwrap(); - let client_config = rustls::ClientConfig::builder() - .with_root_certificates(root_store) - .with_no_client_auth(); - let connector = TlsConnector::from(Arc::new(client_config)); - - let tcp = TcpStream::connect(proxy_addr).await.unwrap(); - let mut tls = connector - .connect("localhost".try_into().unwrap(), tcp) - .await - .expect("TLS handshake must succeed for anonymous connection"); + tokio::spawn(serve(proxy, router)); + // HTTP: a plain request routes to the registered PTask and returns + // its response. + let mut client = TcpStream::connect(proxy_addr).await.unwrap(); let authority = format!("mysvc.min.internal:{backend_port}"); - tls.write_all(format!("GET / HTTP/1.1\r\nHost: {authority}\r\n\r\n").as_bytes()) + client + .write_all(format!("GET / HTTP/1.1\r\nHost: {authority}\r\n\r\n").as_bytes()) .await .unwrap(); let mut response = Vec::new(); - tls.read_to_end(&mut response).await.unwrap(); - + client.read_to_end(&mut response).await.unwrap(); let response_str = String::from_utf8_lossy(&response); assert!( - response_str.contains("401"), - "expected 401 Unauthorized for no-cert, got: {response_str}" - ); - // The 401 body must not reveal PTask hostnames or switch IPs (R4.5). - assert!( - !response_str.contains("min.internal"), - "response body must not contain a PTask hostname" - ); - assert!( - !response_str.contains("100.64"), - "response body must not contain a switch IP" - ); - } - - /// Proof artifact 3 (UC2b remote browser access): a connection that - /// presents a **valid** client certificate signed by the daemon CA is - /// routed to the target PTask and receives a `200 OK`. - #[cfg(feature = "networking-proxy")] - #[tokio::test] - async fn mtls_valid_cert_routes_to_backend() { - use tokio_rustls::TlsConnector; - - let ca = CertAuthority::generate().expect("CA generation must not fail"); - let tls_config = ca.build_server_config().expect("server config must build"); - let (client_cert_der, client_key_bytes) = ca - .sign_client_cert_der("test-client") - .expect("sign must succeed"); - - let backend_port = spawn_backend().await; - let mut reg = HostnameRegistry::new("dev", false); - reg.register_host_net(SessionId::nil(), "mysvc"); - let router = Router::new(Arc::new(reg)); - - let proxy = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); - let proxy_addr = proxy.local_addr().unwrap(); - tokio::spawn(serve_https(proxy, router, tls_config)); - - // Build a TLS client with a valid client certificate. - let mut root_store = rustls::RootCertStore::empty(); - root_store.add(ca.ca_cert_der.clone()).unwrap(); - let client_key = rustls::pki_types::PrivateKeyDer::Pkcs8( - rustls::pki_types::PrivatePkcs8KeyDer::from(client_key_bytes), + response_str.contains("200 OK"), + "expected the plain-HTTP request to route, got: {response_str}" ); - let client_config = rustls::ClientConfig::builder() - .with_root_certificates(root_store) - .with_client_auth_cert(vec![client_cert_der], client_key) - .expect("client auth config must build"); - let connector = TlsConnector::from(Arc::new(client_config)); - - let tcp = TcpStream::connect(proxy_addr).await.unwrap(); - let mut tls = connector - .connect("localhost".try_into().unwrap(), tcp) - .await - .expect("TLS handshake must succeed with valid client cert"); - let authority = format!("mysvc.min.internal:{backend_port}"); - tls.write_all(format!("GET / HTTP/1.1\r\nHost: {authority}\r\n\r\n").as_bytes()) + // No TLS: a ClientHello is just bytes that never end an HTTP head. + // Half-close the write side so `read_head` hits EOF, and nothing may + // come back — no ServerHello, no alert, not even a status line, + // because no build puts a TLS terminator behind the port. + let mut tls_client = TcpStream::connect(proxy_addr).await.unwrap(); + tls_client + .write_all(&[0x16, 0x03, 0x01, 0x00, 0x05, 0x01, 0x00, 0x00, 0x01, 0x00]) .await .unwrap(); - let mut response = Vec::new(); - tls.read_to_end(&mut response).await.unwrap(); - - let response_str = String::from_utf8_lossy(&response); + tls_client.shutdown().await.unwrap(); + let mut tls_response = Vec::new(); + tls_client.read_to_end(&mut tls_response).await.unwrap(); assert!( - response_str.contains("200 OK"), - "expected 200 OK from backend via authenticated mTLS proxy, got: {response_str}" + tls_response.is_empty(), + "the proxy must serve plain HTTP only; a TLS handshake must draw no \ + response bytes, got: {:?}", + String::from_utf8_lossy(&tls_response) ); } } diff --git a/crates/minimald/src/rpc.rs b/crates/minimald/src/rpc.rs index 5a77e44b63..ea0541980b 100644 --- a/crates/minimald/src/rpc.rs +++ b/crates/minimald/src/rpc.rs @@ -1,15 +1,13 @@ use futures::StreamExt as _; -#[cfg(feature = "networking-proxy")] -use minimald_rpc::IssueClientCertResponse; use minimald_rpc::{ AbortSession, AbortSessionResponse, CleanCacheRequest, CleanCacheUpdate, CreateSession, DestroySession, DestroySessionResponse, Errorable, FinalizeSession, FinalizeSessionResponse, GetMeshStatus, GetSessionPolicy, GetSessionPolicyRequest, GetSessionRecord, GetSessionRecordRequest, GetSessionRecordResponse, GetSessionScreen, GetVersion, - GetVersionResponse, IssueClientCert, IssueClientCertRequest, ListSessions, ListSessionsEntry, - ListSessionsResponse, OneshotSshRpc, RPC_SUBSYSTEM_PREFIX, RenameSession, - RenameSessionResponse, ResourcePool, SessionDelta, SessionDeltaRequest, SessionDeltaResponse, - Shutdown, ShutdownRequest, ShutdownResponse, SubmitVerdict, + GetVersionResponse, ListSessions, ListSessionsEntry, ListSessionsResponse, OneshotSshRpc, + RPC_SUBSYSTEM_PREFIX, RenameSession, RenameSessionResponse, ResourcePool, SessionDelta, + SessionDeltaRequest, SessionDeltaResponse, Shutdown, ShutdownRequest, ShutdownResponse, + SubmitVerdict, }; use russh::{ Channel as RuChannel, ChannelId, @@ -128,7 +126,6 @@ async fn serve_list_sessions( Ok(ListSessionsResponse { daemon_version: Some(OWN_VERSION.to_string()), hostname_routing_unavailable: s.proxy_unavailable().await, - mtls_proxy_unavailable: s.mtls_unavailable().await, resource_pool, // `git` is left `None`: the daemon cannot probe it — on // macOS it runs in the minvmd guest, where the host's @@ -293,7 +290,6 @@ async fn serve_create_session( id, daemon_version: Some(OWN_VERSION.to_string()), hostname_routing_unavailable: s.proxy_unavailable().await, - mtls_proxy_unavailable: s.mtls_unavailable().await, }) } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Errorable::Err { @@ -727,48 +723,6 @@ async fn serve_get_session_screen( .await } -/// Signs a fresh client certificate for the `minimal login` flow and returns -/// the cert PEM, key PEM, and CA cert PEM so the client can authenticate to -/// the HTTPS reverse proxy. Only compiled when the `networking-proxy` feature -/// is enabled. -#[cfg(feature = "networking-proxy")] -async fn serve_issue_client_cert( - s: ServerStateHandle, - c: RuChannel, -) -> Result<(), ConnectionError> { - IssueClientCert - .handle_channel(c, async |req: IssueClientCertRequest| { - let ca = s.cert_authority().await; - match ca.sign_client_cert(&req.subject_cn) { - Ok((cert_pem, key_pem)) => Ok(Errorable::Ok(IssueClientCertResponse { - cert_pem, - key_pem, - ca_cert_pem: ca.ca_cert_pem.clone(), - })), - Err(e) => Ok(Errorable::Err { - error: e.to_string(), - }), - } - }) - .await -} - -/// Replies to an `IssueClientCert` request with a readable error when the -/// `networking-proxy` feature is compiled out, so the client sees "feature not -/// enabled" instead of an opaque EOF/channel-close on the response stream. -#[cfg(not(feature = "networking-proxy"))] -async fn serve_issue_client_cert_unavailable(c: RuChannel) -> Result<(), ConnectionError> { - IssueClientCert - .handle_channel(c, async |_req: IssueClientCertRequest| { - Ok(Errorable::Err { - error: "minimald was built without the networking-proxy feature; \ - client certificate issuance is unavailable" - .to_string(), - }) - }) - .await -} - async fn serve_get_mesh_status( s: ServerStateHandle, c: RuChannel, @@ -1627,8 +1581,7 @@ pub async fn handle_ssh_rpc( | STREAM_WORKSPACE_PATCHES | STREAM_WORKSPACE_HOOK_SCRIPTS | minimald_rpc::DIAG_BUNDLE_SUBSYSTEM - | minimald_rpc::CLEAN_CACHE_SUBSYSTEM - | IssueClientCert::NAME => { + | minimald_rpc::CLEAN_CACHE_SUBSYSTEM => { let mut conn_lock = c.lock().await; let c_hnd = match conn_lock.take(id) { None => { @@ -1716,19 +1669,6 @@ pub async fn handle_ssh_rpc( serve!(crate::diag::serve_stream_diag_bundle(s, config, channel)) } minimald_rpc::CLEAN_CACHE_SUBSYSTEM => serve!(serve_clean_cache(s, channel)), - IssueClientCert::NAME => { - #[cfg(feature = "networking-proxy")] - serve!(serve_issue_client_cert(s, channel)); - #[cfg(not(feature = "networking-proxy"))] - { - tracing::warn!( - "IssueClientCert RPC called but the networking-proxy \ - feature is not enabled; replying with an error" - ); - drop(s); - serve!(serve_issue_client_cert_unavailable(channel)); - } - } _ => unreachable!(), }; @@ -2683,9 +2623,9 @@ mod tests { assert_eq!(created.daemon_version.as_deref(), Some(OWN_VERSION)); } - /// The two read RPCs the attach / exec / setup-zed / ssh-forward paths - /// gate on must report the daemon's build, or those paths have nothing to - /// assert against and would have to spend a `GetVersion` to find out. + /// The two read RPCs the attach / exec / setup-zed paths gate on must + /// report the daemon's build, or those paths have nothing to assert + /// against and would have to spend a `GetVersion` to find out. #[tokio::test] async fn the_read_rpcs_report_the_daemon_build() { let server = TestServer::new().await; diff --git a/crates/minimald/src/server.rs b/crates/minimald/src/server.rs index 3e0e1ad73e..fc8e4b973e 100644 --- a/crates/minimald/src/server.rs +++ b/crates/minimald/src/server.rs @@ -176,19 +176,6 @@ pub struct ServerState { /// macOS, which is the platform the failure was reported from. proxy_unavailable: Option, - /// Why the mTLS reverse proxy is not serving, if it is not. Kept apart - /// from [`Self::proxy_unavailable`] so a client is not told its hostnames - /// are broken when only TLS termination is. Never set without the - /// `networking-proxy` feature, where there is no such proxy to lose. - mtls_unavailable: Option, - - /// The daemon's TLS certificate authority, used by the HTTPS proxy and the - /// `IssueClientCert` RPC. Generated once on daemon startup and held for the - /// daemon's lifetime; clients must call `minimal login` again after a - /// restart. - #[cfg(feature = "networking-proxy")] - pub cert_authority: Arc, - /// The running WireGuard mesh peer, when one is configured (Unit 4). Only /// present under the `networking-wg` feature; the `GetMeshStatus` RPC reads /// it through [`ServerStateHandle::mesh_status`]. @@ -229,13 +216,6 @@ impl ServerState { .with_transport(transport), )); - // Generate the TLS CA once at daemon startup so the HTTPS proxy and the - // IssueClientCert RPC share the same trust anchor for the lifetime of - // this daemon process. - #[cfg(feature = "networking-proxy")] - let cert_authority = - Arc::new(crate::net::proxy::CertAuthority::generate().map_err(std::io::Error::other)?); - // Build a daemon-scoped mctx config from what the daemon // knows today (dirs). Additional flags (offline, stdlib // override, num-parallel-builds) will thread through from @@ -270,9 +250,6 @@ impl ServerState { log_release, host_key: None, proxy_unavailable: None, - mtls_unavailable: None, - #[cfg(feature = "networking-proxy")] - cert_authority, #[cfg(feature = "networking-wg")] mesh: None, }) @@ -343,24 +320,6 @@ impl ServerStateHandle { self.0.lock().await.proxy_unavailable = None; } - /// Records why the mTLS reverse proxy is not serving. - #[cfg_attr(not(feature = "networking-proxy"), expect(dead_code))] - pub(crate) async fn set_mtls_unavailable(&self, reason: String) { - self.0.lock().await.mtls_unavailable = Some(reason); - } - - /// Clears the mTLS unavailability note: the proxy's startup retry bound - /// and published it. - #[cfg_attr(not(feature = "networking-proxy"), expect(dead_code))] - pub(crate) async fn clear_mtls_unavailable(&self) { - self.0.lock().await.mtls_unavailable = None; - } - - /// Why the mTLS reverse proxy is not serving, or `None` if it is. - pub(crate) async fn mtls_unavailable(&self) -> Option { - self.0.lock().await.mtls_unavailable.clone() - } - /// Returns the daemon-scoped mctx state. pub(crate) async fn daemon_context(&self) -> Arc { Arc::clone(&self.0.lock().await.daemon_ctx) @@ -422,13 +381,6 @@ impl ServerStateHandle { self.0.lock().await.daemon_id.clone() } - /// Returns the daemon's TLS certificate authority (only with - /// `networking-proxy` feature). Used by the `IssueClientCert` RPC handler. - #[cfg(feature = "networking-proxy")] - pub async fn cert_authority(&self) -> Arc { - Arc::clone(&self.0.lock().await.cert_authority) - } - /// Builds the current WireGuard mesh status for the `GetMeshStatus` RPC /// (R4.6). On a build without the `networking-wg` feature, or with no mesh /// configured, this reports `configured = false`. @@ -544,10 +496,10 @@ impl Server { let in_microvm = config.in_microvm; let state = ServerStateHandle::new(config, log_release).await?; - // Start minimald's two host-side proxies (B5 egress :7654, B8 mTLS - // :7655) for the server's lifetime and, in a microVM (DM1), publish them - // on the macOS host loopback. minimald is Linux-only, and the PTask - // hostname registry they route against only exists on Linux. + // Start minimald's host-side egress proxy (B5, :7654) for the server's + // lifetime and, in a microVM (DM1), publish it on the macOS host + // loopback. minimald is Linux-only, and the PTask hostname registry it + // routes against only exists on Linux. #[cfg(target_os = "linux")] start_host_proxies(&state, in_microvm).await; @@ -755,9 +707,9 @@ async fn reap_unfinalized_sessions(state: &ServerStateHandle, ids: Vec<::session } } -/// Binds and serves minimald's host-side listeners — the egress and mTLS -/// proxies, and beside them the box-zone answerer — for the daemon's lifetime -/// and, in a microVM (DM1), publishes them on the macOS host loopback. +/// Binds and serves minimald's host-side listeners — the egress proxy, and +/// beside it the box-zone answerer — for the daemon's lifetime and, in a +/// microVM (DM1), publishes them on the macOS host loopback. /// /// The proxies route by `Host:` header through the sessions manager's shared /// PTask hostname registry; the answerer serves the same registry as DNS, @@ -822,40 +774,6 @@ async fn start_host_proxies(state: &ServerStateHandle, in_microvm: bool) { in_microvm, RetryBackoff::production(), )); - - // B8 mTLS reverse proxy (:7655), under the networking-proxy feature. - #[cfg(feature = "networking-proxy")] - { - // Three ways this ends with nothing serving on :7655, and all three - // were silent: the TLS config failing to build, the bind failing, and - // the publish failing. The daemon carries on in every case, so only a - // reported reason distinguishes "no mTLS proxy configured" from "the - // mTLS proxy is broken". A TLS config that cannot build is not - // retryable — the CA material does not change under the retry — so it - // is reported once, here, and only the bind and publish retry. - let https_addr = SocketAddr::new(bind_base, crate::net::proxy::HTTPS_PROXY_PORT); - match state.cert_authority().await.build_server_config() { - Ok(tls_config) => { - tokio::spawn(drive_proxy_until_serving( - state.clone(), - HostProxyStartup::Mtls { - addr: https_addr, - tls_config, - }, - RetryBackoff::production(), - )); - } - Err(error) => { - tracing::warn!(%error, "could not build TLS config for the mTLS reverse proxy"); - state - .set_mtls_unavailable(format!( - "the daemon could not build a TLS config for the mTLS reverse \ - proxy: {error}" - )) - .await; - } - } - } } /// The retry schedule a host-side proxy's startup uses while its bind (or, in @@ -899,20 +817,14 @@ impl RetryBackoff { } } -/// Which host-side proxy a startup retry drives. The two differ in what serves -/// a bound listener and which state note a failure lands on; the retry loop -/// itself is shared. +/// Which host-side proxy a startup retry drives. The one left differs only in +/// what serves a bound listener and which state note a failure lands on; the +/// retry loop itself is shared. #[cfg(target_os = "linux")] #[derive(Debug)] enum HostProxyStartup { /// The B5 egress/DNS proxy: plain HTTP routing through the shared router. Egress { addr: SocketAddr }, - /// The B8 mTLS reverse proxy: the same routing behind TLS termination. - #[cfg(feature = "networking-proxy")] - Mtls { - addr: SocketAddr, - tls_config: Arc, - }, } #[cfg(target_os = "linux")] @@ -921,8 +833,6 @@ impl HostProxyStartup { fn addr(&self) -> SocketAddr { match self { Self::Egress { addr } => *addr, - #[cfg(feature = "networking-proxy")] - Self::Mtls { addr, .. } => *addr, } } @@ -931,16 +841,12 @@ impl HostProxyStartup { fn component(&self) -> &'static str { match self { Self::Egress { .. } => "dns-proxy", - #[cfg(feature = "networking-proxy")] - Self::Mtls { .. } => "https-proxy", } } /// Spawns the serve loop for a bound listener. Runs for the daemon's /// lifetime; the startup retry never rebinds a bound-and-served listener. async fn spawn_serve(&self, state: &ServerStateHandle, listener: TcpListener) { - #[cfg(feature = "networking-proxy")] - use crate::net::proxy::serve_https; use crate::net::proxy::{Router, serve}; let router = Router::new(state.sessions_manager().await.hostnames()); @@ -952,15 +858,6 @@ impl HostProxyStartup { } }); } - #[cfg(feature = "networking-proxy")] - Self::Mtls { tls_config, .. } => { - let tls_config = Arc::clone(tls_config); - tokio::spawn(async move { - if let Err(error) = serve_https(listener, router, tls_config).await { - tracing::error!(%error, "mTLS proxy accept loop exited"); - } - }); - } } } @@ -969,8 +866,6 @@ impl HostProxyStartup { async fn record_unavailable(&self, state: &ServerStateHandle, report: String) { match self { Self::Egress { .. } => state.set_proxy_unavailable(report).await, - #[cfg(feature = "networking-proxy")] - Self::Mtls { .. } => state.set_mtls_unavailable(report).await, } } @@ -978,8 +873,6 @@ impl HostProxyStartup { async fn clear_unavailable(&self, state: &ServerStateHandle) { match self { Self::Egress { .. } => state.clear_proxy_unavailable().await, - #[cfg(feature = "networking-proxy")] - Self::Mtls { .. } => state.clear_mtls_unavailable().await, } } } diff --git a/justfile b/justfile index cb63c6c17e..14d7f889f3 100644 --- a/justfile +++ b/justfile @@ -15,8 +15,6 @@ krun-prefix := env('HOME') / ".krun" # Prefix for the STATIC libkrun the dev stack links (Linux). Built from the # vendored pin, not fetched; `just clean` removes it. krun-static := scratch / "libkrun-static" / musl-target -# Guest networking features baked into the initramfs (networking-wg deferred). -features := "networking-proxy" kernel := scratch / "vmlinuz" rootfs := scratch / "rootfs.img" initramfs := scratch / "initramfs.cpio" @@ -101,9 +99,9 @@ gvproxy: @mkdir -p {{scratch}} @[ -x {{gvproxy}} ] || scripts/fetch-gvproxy.sh {{gvproxy}} -# Cross-compile minimald → initramfs /init with the networking features. +# Cross-compile minimald → initramfs /init. initramfs: - FEATURES={{features}} scripts/build-initramfs.sh {{initramfs}} {{musl-target}} + scripts/build-initramfs.sh {{initramfs}} {{musl-target}} # Compiles the guest minimald here, then hands the binary to # scripts/build-initramfs.sh via MINIMALD_BIN (its prebuilt mode), so the script @@ -119,8 +117,7 @@ initramfs: # # Build minimald → initramfs /init using the cross toolchain on PATH (no container). initramfs-nodocker: - cargo zigbuild -p minimald --profile initramfs \ - --target {{musl-target}} --features {{features}} + cargo zigbuild -p minimald --profile initramfs --target {{musl-target}} MINIMALD_BIN="{{justfile_directory()}}/target/{{musl-target}}/initramfs/minimald" \ scripts/build-initramfs.sh {{initramfs}} {{musl-target}} @@ -147,10 +144,10 @@ minvmd-build: libkrun-static minimal-cli: cargo build -p minimal --locked -# Build a host-native (glibc) minimald with the networking features (for `just up`). +# Build a host-native (glibc) minimald (for `just up`). [linux] minimald-build: - cargo build -p minimald --features {{features}} --locked + cargo build -p minimald --locked # THE single build entrypoint for a shippable build: the four release binaries # for a target triple, built exactly the way release.yml's build jobs build diff --git a/scripts/build-initramfs.sh b/scripts/build-initramfs.sh index 0c3098ce68..522f81b106 100755 --- a/scripts/build-initramfs.sh +++ b/scripts/build-initramfs.sh @@ -17,8 +17,8 @@ # use `cross`. # # Set FEATURES to a comma-separated cargo feature list to compile the guest -# minimald with extra features (e.g. FEATURES=networking-proxy,networking-wg for -# the HTTPS reverse proxy and WireGuard mesh peer). Empty by default. +# minimald with extra features (e.g. FEATURES=networking-wg for the WireGuard +# mesh peer). Empty by default. # # Usage: scripts/build-initramfs.sh [rust-target] set -eu diff --git a/scripts/kernel-bump-review.sh b/scripts/kernel-bump-review.sh index 2b8bb8a215..47a86677db 100755 --- a/scripts/kernel-bump-review.sh +++ b/scripts/kernel-bump-review.sh @@ -47,9 +47,8 @@ # driver is never loaded on either side of our stack. # --wide includes it anyway as a cross-check, since a # vsock semantics change is often mirrored here. -# drivers/net/virtio_net.c guest egress (gvproxy) rides it, but it is behind -# the networking-proxy feature and off the control -# plane. --wide includes it. +# drivers/net/virtio_net.c guest egress (gvproxy) rides it, but it is off +# the control plane. --wide includes it. # fs/fuse/virtio_fs.c not used: the rootfs is a raw ext4 disk, not virtiofs. # arch/, mm/, sched/, … real, but any bump touches thousands of these lines; # including them is how a report becomes wallpaper.