From f2fe6c98751e6c5ab123c632c984eb67ddaa4cb8 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sun, 15 Nov 2026 18:38:29 -0600 Subject: [PATCH] feat(fleet-proxy): Cloudflare-primary/Tailscale-fallback sandbox<->laptop transport (code#10356) --- pkgs/fleet/Cargo.lock | 61 ++ pkgs/fleet/crates/fleet-config/src/lib.rs | 42 + .../fleet/crates/fleet-proxy-proto/src/lib.rs | 31 +- pkgs/fleet/crates/fleet-proxy/Cargo.toml | 20 +- pkgs/fleet/crates/fleet-proxy/src/client.rs | 3 + pkgs/fleet/crates/fleet-proxy/src/files.rs | 4 + pkgs/fleet/crates/fleet-proxy/src/http.rs | 78 +- pkgs/fleet/crates/fleet-proxy/src/lib.rs | 7 +- .../crates/fleet-proxy/src/raw_splice.rs | 1 + pkgs/fleet/crates/fleet-proxy/src/serve.rs | 749 ++++++++++++++---- pkgs/fleet/crates/fleet-proxy/src/tunnel.rs | 246 ++++++ pkgs/fleet/crates/fleet-secrets/src/lib.rs | 19 +- 12 files changed, 1111 insertions(+), 150 deletions(-) diff --git a/pkgs/fleet/Cargo.lock b/pkgs/fleet/Cargo.lock index 4e21453678..b6de34d22f 100644 --- a/pkgs/fleet/Cargo.lock +++ b/pkgs/fleet/Cargo.lock @@ -77,6 +77,29 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + [[package]] name = "base64" version = "0.13.1" @@ -175,6 +198,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -207,6 +232,15 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + [[package]] name = "combine" version = "4.6.9" @@ -456,6 +490,12 @@ dependencies = [ "litrs", ] +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "either" version = "1.19.0" @@ -577,8 +617,11 @@ dependencies = [ "fleet-registry", "libc", "proptest", + "rustls", + "rustls-native-certs", "serde", "serde_json", + "webpki-roots", ] [[package]] @@ -658,6 +701,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "generic-array" version = "0.14.7" @@ -933,6 +982,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "libc" version = "0.2.191" @@ -1475,6 +1534,7 @@ version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ + "aws-lc-rs", "log", "once_cell", "ring", @@ -1538,6 +1598,7 @@ version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ + "aws-lc-rs", "ring", "rustls-pki-types", "untrusted", diff --git a/pkgs/fleet/crates/fleet-config/src/lib.rs b/pkgs/fleet/crates/fleet-config/src/lib.rs index 8e033031dd..8381da76fc 100644 --- a/pkgs/fleet/crates/fleet-config/src/lib.rs +++ b/pkgs/fleet/crates/fleet-config/src/lib.rs @@ -46,6 +46,20 @@ pub const DEFAULT_TARGET_HOST: &str = "100.99.113.103"; /// `HTTPS_PROXY` — fixed by the tunnel setup, as in /// laptop-proxy-connect.py (the URL's own port is not used). pub const DEFAULT_EGRESS_PROXY_PORT: u16 = 3130; +/// The named Cloudflare tunnel hostname the broker's Cloudflare +/// leg dials for the laptop-agent daemon (code#10356, Drew's +/// 2026-11-15 transport ruling): the tunnel's ingress lands on +/// the daemon's own listener from the laptop side, so the daemon +/// is untouched and its token auth is preserved end to end. +pub const DEFAULT_CF_HOST: &str = "sandbox-link.security.cab"; +/// The Cloudflare Access service-token file for the tunnel +/// (home-relative, like [`DEFAULT_BROKER_TOKEN_FILE`]): a JSON +/// object with `client_id` / `client_secret`, mode 600, read by +/// the broker per request and sent only as `CF-Access-*` headers +/// — never stored, never logged. The file's EXISTENCE is what +/// puts the Cloudflare leg in play (the Python broker's rule); +/// no file, no leg, the tailnet path carries everything. +pub const DEFAULT_CF_ACCESS_FILE: &str = "tools/laptop-agent-cf-access.json"; /// Default listen address for the CONNECT-UDP endpoint /// (RFC 9298 spike, #6109) when `[proxy] connect_udp` enables @@ -345,6 +359,16 @@ pub struct ProxyConfig { /// [`DEFAULT_EGRESS_PROXY_PORT`]). `0` is rejected at load /// (#6412): port 0 cannot be dialled. pub egress_proxy_port: Option, + /// Hostname of the named Cloudflare tunnel the broker's + /// Cloudflare leg dials for the laptop-agent daemon (default + /// [`DEFAULT_CF_HOST`]; code#10356). Blank is rejected at load + /// (#6405's rule, same as `target_host`). + pub cf_host: Option, + /// Cloudflare Access service-token file for the tunnel, + /// home-relative (default [`DEFAULT_CF_ACCESS_FILE`]). The + /// broker reads it per request; its existence enables the + /// Cloudflare leg for the daemon port. + pub cf_access_file: Option, /// Dial the target directly instead of through a CONNECT tunnel /// (a broker running on the target host itself; also the /// hermetic-test mode). Default false — today's topology. @@ -731,6 +755,8 @@ impl Config { for (value, field) in [ (&self.proxy.broker_socket, "[proxy] broker_socket"), (&self.proxy.target_host, "[proxy] target_host"), + (&self.proxy.cf_host, "[proxy] cf_host"), + (&self.proxy.cf_access_file, "[proxy] cf_access_file"), (&self.proxy.connect_udp_listen, "[proxy] connect_udp_listen"), (&self.secrets.token_file, "[secrets] token_file"), (&self.dispatch.url, "[dispatch] url"), @@ -1134,6 +1160,22 @@ impl Config { .unwrap_or(DEFAULT_EGRESS_PROXY_PORT) } + /// The named Cloudflare tunnel hostname for the broker's + /// Cloudflare leg (see [`DEFAULT_CF_HOST`]). + pub fn cf_host(&self) -> &str { + self.proxy.cf_host.as_deref().unwrap_or(DEFAULT_CF_HOST) + } + + /// The Cloudflare Access service-token file (see + /// [`DEFAULT_CF_ACCESS_FILE`]), resolved under $HOME like the + /// other token files. + pub fn cf_access_file(&self) -> PathBuf { + match &self.proxy.cf_access_file { + Some(raw) => resolve_under_home(raw), + None => resolve_under_home(DEFAULT_CF_ACCESS_FILE), + } + } + /// Whether the broker dials the target directly (no CONNECT). pub fn proxy_direct(&self) -> bool { self.proxy.direct.unwrap_or(false) diff --git a/pkgs/fleet/crates/fleet-proxy-proto/src/lib.rs b/pkgs/fleet/crates/fleet-proxy-proto/src/lib.rs index 8838c533fe..84262af74f 100644 --- a/pkgs/fleet/crates/fleet-proxy-proto/src/lib.rs +++ b/pkgs/fleet/crates/fleet-proxy-proto/src/lib.rs @@ -141,6 +141,17 @@ pub struct ServiceInfo { /// names the file whose contents the broker sends as `X-Agent-Token` /// for that request — the file is read by the broker per request; the /// token itself never appears in the frame beyond that name. +/// +/// The 2026-11-15 transport fields (code#10356) ride the legacy +/// dialect the Python clients already speak: `trip` is the caller's +/// per-request id (the broker forwards it to the service as the +/// `X-Trip-Id` header, joining the trip logs), `transport` is the +/// caller's transport preference (`auto` | `cf` | `ts` — the broker +/// owns the actual selection and reports the outcome on the +/// response), and `cf_ok` is the caller's verdict that the request +/// may ride the Cloudflare leg (the broker computes the same verdict +/// from the body when the field is absent). All three are optional +/// and additive: pre-field frames parse exactly as before. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Request { pub method: String, @@ -151,14 +162,25 @@ pub struct Request { pub port: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub token_file: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub trip: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub transport: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cf_ok: Option, } /// A response frame: `{status, body}` — the HTTP status and parsed -/// JSON body of the routed service's reply. +/// JSON body of the routed service's reply. `transport` (2026-11-15, +/// code#10356) names the transport leg the broker actually used +/// (`cf` | `ts`), so a caller's trip record can prove which path a +/// request rode; absent when the broker predates the field. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Response { pub status: u16, pub body: serde_json::Value, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub transport: Option, } /// Frame-level errors. None of these ever carry payload contents — @@ -329,12 +351,18 @@ mod tests { body: None, port: None, token_file: None, + trip: None, + transport: None, + cf_ok: None, }; let frame = serde_json::to_value(&req).unwrap(); assert_eq!(frame["method"], "GET"); assert!(frame.get("body").is_none()); assert!(frame.get("port").is_none()); assert!(frame.get("token_file").is_none()); + assert!(frame.get("trip").is_none()); + assert!(frame.get("transport").is_none()); + assert!(frame.get("cf_ok").is_none()); assert_eq!(roundtrip(&req), req); } @@ -355,6 +383,7 @@ mod tests { let resp = Response { status: 200, body: serde_json::json!({"ok": true}), + transport: None, }; assert_eq!(roundtrip(&resp), resp); } diff --git a/pkgs/fleet/crates/fleet-proxy/Cargo.toml b/pkgs/fleet/crates/fleet-proxy/Cargo.toml index 34932ea904..8b22bfaa61 100644 --- a/pkgs/fleet/crates/fleet-proxy/Cargo.toml +++ b/pkgs/fleet/crates/fleet-proxy/Cargo.toml @@ -31,9 +31,25 @@ required-features = ["serve"] [features] # The broker half. The connect variant compiles this crate without # it: a dropped-on-a-box artifact carries the client and nothing -# else (§2's mechanical-incapability rule). +# else (§2's mechanical-incapability rule). The TLS stack for the +# broker's Cloudflare leg (code#10356) rides this feature for the +# same reason: rustls + two root stores is exactly the weight the +# size-gated connect artifact must not grow. default = ["serve"] -serve = [] +serve = ["dep:rustls", "dep:webpki-roots", "dep:rustls-native-certs"] + +[dependencies.rustls] +version = "0.23" +features = ["ring"] +optional = true + +[dependencies.webpki-roots] +version = "1" +optional = true + +[dependencies.rustls-native-certs] +version = "0.8" +optional = true [dev-dependencies] # Property-based tests for the fleet-udp-forward parser invariants diff --git a/pkgs/fleet/crates/fleet-proxy/src/client.rs b/pkgs/fleet/crates/fleet-proxy/src/client.rs index 2a18bd440c..d056115d37 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/client.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/client.rs @@ -460,6 +460,9 @@ pub fn run_connect( body: req.body.clone(), port: req.service_port, token_file: req.token_file.clone(), + trip: None, + transport: None, + cf_ok: None, }; // A legacy broker already spent its first reply eating the // hello; the round-trip proceeds identically from here. diff --git a/pkgs/fleet/crates/fleet-proxy/src/files.rs b/pkgs/fleet/crates/fleet-proxy/src/files.rs index e1cd81798a..c29e2b570d 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/files.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/files.rs @@ -344,6 +344,9 @@ impl FilesTransport for BrokerFilesTransport { body: Some(body), port: Some(self.port), token_file: Some(self.token_file.to_string_lossy().into_owned()), + trip: None, + transport: None, + cf_ok: None, }; let mut stream = UnixStream::connect(&self.socket).map_err(|e| { ClientError::Transport(format!("broker socket {}: {e}", self.socket.display())) @@ -1517,6 +1520,7 @@ mod tests { let response = Response { status, body: reply, + transport: None, }; if fleet_proxy_proto::write_frame(&mut stream, &response).is_err() { return; diff --git a/pkgs/fleet/crates/fleet-proxy/src/http.rs b/pkgs/fleet/crates/fleet-proxy/src/http.rs index c769104acb..f172a13ad3 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/http.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/http.rs @@ -142,13 +142,37 @@ pub(crate) fn valid_path(path: &str) -> bool { path.starts_with('/') && path.bytes().all(|b| b > 0x20 && b != 0x7f) } -/// The byte stream under an [`HttpConn`]: a TCP tunnel stream, or -/// a colocated service's Unix socket (#6219). Both are plain -/// Read+Write byte streams once connected; the HTTP exchange does -/// not care which it rides. +/// Whether `name` is a valid header field name: the method-token +/// rule (RFC 9110 `token`) — the extra headers the broker adds +/// (code#10356) are interpolated into the head, so their names +/// get the same #5750 treatment as the method. +pub(crate) fn valid_header_name(name: &str) -> bool { + valid_method(name) +} + +/// Whether `value` may appear as a header field value: no CR, LF, +/// or other control bytes and no DEL — a value carrying one would +/// forge the headers after it (#5750). The Access ids and trip +/// ids the broker sends are plain tokens; anything else is a bug +/// or an attack, and the request is refused before it is written. +pub(crate) fn valid_header_value(value: &str) -> bool { + value.bytes().all(|b| b >= 0x20 && b != 0x7f) +} + +/// The byte stream under an [`HttpConn`]: a TCP tunnel stream, a +/// colocated service's Unix socket (#6219), or TLS to the +/// Cloudflare edge for the broker's Cloudflare leg (code#10356, +/// serve-gated like the leg itself). All are plain Read+Write +/// byte streams once connected; the HTTP exchange does not care +/// which it rides. The TLS variant's clone is a second handle on +/// the one shared session (see +/// [`crate::tunnel::SharedTlsStream`]); the others clone the +/// socket itself. pub enum ConnStream { Tcp(TcpStream), Unix(UnixStream), + #[cfg(feature = "serve")] + Tls(crate::tunnel::SharedTlsStream), } impl ConnStream { @@ -156,6 +180,8 @@ impl ConnStream { Ok(match self { ConnStream::Tcp(s) => ConnStream::Tcp(s.try_clone()?), ConnStream::Unix(s) => ConnStream::Unix(s.try_clone()?), + #[cfg(feature = "serve")] + ConnStream::Tls(s) => ConnStream::Tls(s.try_clone()?), }) } } @@ -165,6 +191,8 @@ impl Read for ConnStream { match self { ConnStream::Tcp(s) => s.read(buf), ConnStream::Unix(s) => s.read(buf), + #[cfg(feature = "serve")] + ConnStream::Tls(s) => s.read(buf), } } } @@ -174,12 +202,16 @@ impl Write for ConnStream { match self { ConnStream::Tcp(s) => s.write(buf), ConnStream::Unix(s) => s.write(buf), + #[cfg(feature = "serve")] + ConnStream::Tls(s) => s.write(buf), } } fn flush(&mut self) -> std::io::Result<()> { match self { ConnStream::Tcp(s) => s.flush(), ConnStream::Unix(s) => s.flush(), + #[cfg(feature = "serve")] + ConnStream::Tls(s) => s.flush(), } } } @@ -204,6 +236,14 @@ impl HttpConn { Self::from_stream(ConnStream::Unix(stream)) } + /// An HTTP connection over a TLS stream to the Cloudflare + /// edge (code#10356): the same exchange, encrypted to the + /// tunnel hostname instead of tunnelled to the tailnet host. + #[cfg(feature = "serve")] + pub fn from_tls(stream: crate::tunnel::SharedTlsStream) -> std::io::Result { + Self::from_stream(ConnStream::Tls(stream)) + } + fn from_stream(stream: ConnStream) -> std::io::Result { let writer = stream.try_clone()?; Ok(HttpConn { @@ -258,6 +298,25 @@ impl HttpConn { host_header: &str, token: &str, body: Option<&[u8]>, + ) -> Result<(u16, Vec), HttpError> { + self.request_with_extra_headers(method, path, host_header, token, body, &[]) + } + + /// [`HttpConn::request`] with extra headers interpolated into + /// the head — the Cloudflare leg's `CF-Access-*` pair and the + /// caller's `X-Trip-Id` (code#10356). Header names and values + /// are validated with the same CRLF rule as the method and + /// path: a control character in either is an injection onto + /// this pooled connection (#5750's class) and is rejected + /// before a byte is written. + pub fn request_with_extra_headers( + &mut self, + method: &str, + path: &str, + host_header: &str, + token: &str, + body: Option<&[u8]>, + extra_headers: &[(String, String)], ) -> Result<(u16, Vec), HttpError> { // The method and path are interpolated into the request // line below: a control character in either is a CRLF @@ -271,6 +330,14 @@ impl HttpConn { "invalid request method or path (method {method:?})" ))); } + for (name, value) in extra_headers { + if !valid_header_name(name) || !valid_header_value(value) { + self.reusable = false; + return Err(HttpError::Malformed(format!( + "invalid extra header (name {name:?})" + ))); + } + } let mut head = format!( "{method} {path} HTTP/1.1\r\n\ Host: {host_header}\r\n\ @@ -278,6 +345,9 @@ impl HttpConn { Content-Type: application/json\r\n\ Accept-Encoding: identity\r\n" ); + for (name, value) in extra_headers { + head.push_str(&format!("{name}: {value}\r\n")); + } if let Some(b) = body { head.push_str(&format!("Content-Length: {}\r\n", b.len())); } diff --git a/pkgs/fleet/crates/fleet-proxy/src/lib.rs b/pkgs/fleet/crates/fleet-proxy/src/lib.rs index 7e78704138..0bfbce5653 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/lib.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/lib.rs @@ -10,7 +10,12 @@ //! tunnels to the laptop's services, so a client call skips the //! ~1.8 s tunnel handshake. Auto-started by clients when the //! socket is missing; exits after an idle hour (client requests -//! only — keepalive never resets the timer). +//! only — keepalive never resets the timer). Its tunnels ride +//! two reaches (code#10356): TLS to the named Cloudflare +//! tunnel's edge as primary for the laptop-agent daemon, the +//! tailnet CONNECT as automatic fallback — the sandbox↔laptop +//! transport lives in this binary, per Drew's 2026-11-15 +//! ruling. //! * **connect / init** — the client: ensure the broker, speak the //! hello (fleet-proxy-proto), regenerate the PATH shim dir from //! the negotiated services map, and the stdio relay that SSH's diff --git a/pkgs/fleet/crates/fleet-proxy/src/raw_splice.rs b/pkgs/fleet/crates/fleet-proxy/src/raw_splice.rs index ab2b67ac56..9c25637c26 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/raw_splice.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/raw_splice.rs @@ -119,6 +119,7 @@ mod tests { Response { status: 502, body: serde_json::json!({"error":"legacy"}), + transport: None, } )))); assert!(!supports_raw_splice(&fleet_response( diff --git a/pkgs/fleet/crates/fleet-proxy/src/serve.rs b/pkgs/fleet/crates/fleet-proxy/src/serve.rs index 38d59771da..82ad843af4 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/serve.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/serve.rs @@ -21,6 +21,19 @@ //! from the first frame, the Python clients) or negotiate the //! hello first (proto 1, fleet clients) — decided per connection //! by peeking at the first frame, never by configuration. +//! * Two reaches carry tunnels to the laptop (code#10356, Drew's +//! 2026-11-15 ruling that sandbox↔laptop transport lives in +//! this binary): the Cloudflare leg — TLS through the platform +//! egress proxy to the named tunnel's edge hostname, Access +//! service-token headers riding the HTTP request — is PRIMARY +//! for the laptop-agent daemon port when its Access file +//! exists, and the tailnet leg (CONNECT through the session +//! proxy to the tailnet host) is the automatic fallback, on +//! connection failure and on a Cloudflare edge error status +//! (502/503/530) alike. The attempt plan is the Python broker's +//! exactly (see [`attempt_plan`]); pools and recovery gates key +//! on (port, transport) so the legs' warmth and failure state +//! never share a bucket. //! //! The broker persists nothing: routing table from config, //! tunnels in memory, tokens in their files. @@ -42,7 +55,10 @@ use fleet_proxy_proto::{ }; use crate::http::{HttpConn, HttpError}; -use crate::tunnel::{Egress, connect_raw_tunnel, connect_tunnel, egress_from_env}; +use crate::tunnel::{ + Egress, connect_cf_tunnel, connect_raw_tunnel, connect_tunnel, egress_from_env, + egress_from_env_url_port, +}; /// Keepalive cadence (the Python's KEEPALIVE_S). const KEEPALIVE_S: u64 = 180; @@ -117,11 +133,47 @@ fn pool_size() -> usize { .unwrap_or(DEFAULT_POOL_SIZE) } +/// Which reach carries a tunnel (code#10356): the Cloudflare +/// leg (TLS to the named tunnel's edge hostname through the +/// platform egress proxy) or the tailnet leg (CONNECT through +/// the session proxy to the tailnet host). Pools and recovery +/// gates key on the pair (port, transport): the legs fail +/// independently, so their warmth and their recovery state +/// must never share a bucket. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum Transport { + Cf, + Ts, +} + +impl Transport { + /// The wire name, stamped on response frames and spoken by + /// request frames' `transport` preference. + fn as_str(&self) -> &'static str { + match self { + Transport::Cf => "cf", + Transport::Ts => "ts", + } + } +} + +/// Where one attempt's connection comes from: the (port, +/// transport) idle pool, or a fresh open. The Python broker's +/// attempt plan names both sources. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Source { + Pool, + Fresh, +} + +/// The pool key: one laptop service on one transport leg. +type PoolKey = (u16, Transport); + /// The per-port tunnel pools: an idle cache plus a live count -/// (idle + checked out) per port, behind one mutex that is -/// never held during network I/O — the same lock discipline -/// the pre-fix pool had (checkout/open/put all release it -/// before touching a socket). +/// (idle + checked out) per (port, transport), behind one +/// mutex that is never held during network I/O — the same +/// lock discipline the pre-fix pool had (checkout/open/put +/// all release it before touching a socket). struct TunnelPool { state: Mutex, /// Signalled whenever a tunnel returns or a live slot @@ -134,8 +186,8 @@ struct TunnelPool { #[derive(Default)] struct PoolState { - idle: HashMap>, - live: HashMap, + idle: HashMap>, + live: HashMap, } /// What a checkout decided: reuse this tunnel, or open a new @@ -159,20 +211,20 @@ impl TunnelPool { self.size } - fn live_of(state: &PoolState, port: u16) -> usize { - state.live.get(&port).copied().unwrap_or(0) + fn live_of(state: &PoolState, key: PoolKey) -> usize { + state.live.get(&key).copied().unwrap_or(0) } - fn reserve(state: &mut PoolState, port: u16) { - *state.live.entry(port).or_insert(0) += 1; + fn reserve(state: &mut PoolState, key: PoolKey) { + *state.live.entry(key).or_insert(0) += 1; } - fn unreserve(&self, state: &mut PoolState, port: u16) { - let live = TunnelPool::live_of(state, port); + fn unreserve(&self, state: &mut PoolState, key: PoolKey) { + let live = TunnelPool::live_of(state, key); if live <= 1 { - state.live.remove(&port); + state.live.remove(&key); } else { - state.live.insert(port, live - 1); + state.live.insert(key, live - 1); } self.returned.notify_all(); } @@ -191,20 +243,20 @@ impl TunnelPool { /// hard-fail because of the pool; the wait only ever /// trades a probable ~100–300 ms return against a /// certain seconds-long tunnel establishment. - fn checkout(&self, port: u16) -> Checkout { + fn checkout(&self, key: PoolKey) -> Checkout { let deadline = Instant::now() + POOL_WAIT_BUDGET; let mut state = self.state.lock().unwrap(); loop { - if let Some(conn) = state.idle.get_mut(&port).and_then(|pool| pool.pop()) { + if let Some(conn) = state.idle.get_mut(&key).and_then(|pool| pool.pop()) { return Checkout::Idle(conn); } - if TunnelPool::live_of(&state, port) < self.size { - TunnelPool::reserve(&mut state, port); + if TunnelPool::live_of(&state, key) < self.size { + TunnelPool::reserve(&mut state, key); return Checkout::Grow; } let remaining = deadline.saturating_duration_since(Instant::now()); if remaining.is_zero() { - TunnelPool::reserve(&mut state, port); + TunnelPool::reserve(&mut state, key); return Checkout::Grow; } let (guard, _) = self.returned.wait_timeout(state, remaining).unwrap(); @@ -216,32 +268,32 @@ impl TunnelPool { /// fresh connection. No idle pop (the retry contract is a /// *fresh* tunnel), no wait (the request is already on its /// second attempt); accounting only. - fn reserve_fresh(&self, port: u16) { + fn reserve_fresh(&self, key: PoolKey) { let mut state = self.state.lock().unwrap(); - TunnelPool::reserve(&mut state, port); + TunnelPool::reserve(&mut state, key); } /// A reserved slot whose tunnel never opened: hand it back. - fn release(&self, port: u16) { + fn release(&self, key: PoolKey) { let mut state = self.state.lock().unwrap(); - self.unreserve(&mut state, port); + self.unreserve(&mut state, key); } /// Return a tunnel after use. Retained as idle when it is - /// reusable and the port's idle vec has room; otherwise it + /// reusable and the key's idle vec has room; otherwise it /// stops counting as live and is dropped — after the lock /// is released, like every other socket touch in the pool. /// Every return wakes waiters (a retained tunnel is /// immediately checkout-able; a dropped one frees live /// headroom). - fn put(&self, port: u16, conn: HttpConn) { + fn put(&self, key: PoolKey, conn: HttpConn) { let mut state = self.state.lock().unwrap(); - if conn.reusable() && state.idle.get(&port).map_or(0, |p| p.len()) < self.size { - state.idle.entry(port).or_default().push(conn); + if conn.reusable() && state.idle.get(&key).map_or(0, |p| p.len()) < self.size { + state.idle.entry(key).or_default().push(conn); self.returned.notify_all(); return; } - self.unreserve(&mut state, port); + self.unreserve(&mut state, key); drop(state); drop(conn); } @@ -249,23 +301,23 @@ impl TunnelPool { /// A checked-out tunnel died in use and will never be /// returned: it stops counting as live, and waiters wake /// (headroom appeared). - fn discard(&self, port: u16) { + fn discard(&self, key: PoolKey) { let mut state = self.state.lock().unwrap(); - self.unreserve(&mut state, port); + self.unreserve(&mut state, key); } #[cfg(test)] - fn live_count(&self, port: u16) -> usize { - TunnelPool::live_of(&self.state.lock().unwrap(), port) + fn live_count(&self, key: PoolKey) -> usize { + TunnelPool::live_of(&self.state.lock().unwrap(), key) } #[cfg(test)] - fn idle_count(&self, port: u16) -> usize { + fn idle_count(&self, key: PoolKey) -> usize { self.state .lock() .unwrap() .idle - .get(&port) + .get(&key) .map_or(0, |p| p.len()) } } @@ -369,7 +421,7 @@ fn record(entry: &mut GateState, recovery_generation: Option, error: Option /// so an opener's immediate retry can never steal or overwrite /// the failure its cohort observed. struct RecoveryGate { - state: Mutex>, + state: Mutex>, finished: Condvar, } @@ -381,12 +433,16 @@ impl RecoveryGate { } } - fn run(&self, port: u16, attempt: impl FnOnce() -> Result) -> Result { + fn run( + &self, + key: PoolKey, + attempt: impl FnOnce() -> Result, + ) -> Result { let deadline = Instant::now() + RECOVERY_WAIT; let mut waiting_on: Option = None; let recovery_generation = loop { let mut state = self.state.lock().unwrap(); - let entry = state.entry(port).or_default(); + let entry = state.entry(key).or_default(); match decide(entry, waiting_on) { Decision::ShareFailure(err) => return Err(err), Decision::ProceedAfterRecovery => break None, @@ -397,7 +453,9 @@ impl RecoveryGate { let left = deadline.saturating_duration_since(Instant::now()); if left.is_zero() { return Err(format!( - "tunnel recovery for port {port} still in flight; failing fast" + "tunnel recovery for port {} via {} still in flight; failing fast", + key.0, + key.1.as_str() )); } let (guard, _) = self.finished.wait_timeout(state, left).unwrap(); @@ -408,7 +466,7 @@ impl RecoveryGate { }; let got = attempt(); let mut state = self.state.lock().unwrap(); - let entry = state.entry(port).or_default(); + let entry = state.entry(key).or_default(); record(entry, recovery_generation, got.as_ref().err()); if recovery_generation.is_some() { self.finished.notify_all(); @@ -459,6 +517,12 @@ fn startup_line(pool_size: usize, socket_path: &std::path::Path) -> String { struct Broker { config: Config, egress: Option, + /// The Cloudflare leg's egress: the same proxy as `egress`, + /// dialled at the proxy URL's own port (see + /// [`crate::tunnel::egress_from_env_url_port`]). Parsed at + /// startup like `egress`; None only when the env is missing, + /// in which case the leg fails per-request until it appears. + cf_egress: Option, pool: TunnelPool, /// Single-flight gate for tunnel opens (recovery stampedes). recovery: RecoveryGate, @@ -483,14 +547,32 @@ impl Broker { Ok(stream) } - fn open_conn(&self, port: u16) -> Result { + fn open_conn(&self, port: u16, transport: Transport) -> Result { // Tunnel opens pass through the recovery gate: ungated // while healthy, single-flight once an open has failed — // see [`RecoveryGate`]. - self.recovery.run(port, || self.open_conn_raw(port)) - } - - fn open_conn_raw(&self, port: u16) -> Result { + self.recovery + .run((port, transport), || self.open_conn_raw(port, transport)) + } + + fn open_conn_raw(&self, port: u16, transport: Transport) -> Result { + if transport == Transport::Cf { + // The Cloudflare leg (code#10356): TLS to the named + // tunnel's edge hostname through the platform egress + // proxy. It never takes the colocated direct path — + // direct mode is a same-box arrangement, and the leg + // exists exactly for the cross-box case (the attempt + // plan never offers it in direct mode anyway). + let egress = self + .cf_egress + .as_ref() + .ok_or_else(|| "HTTPS_PROXY must be set (runtime proxy env)".to_string())?; + let cf_host = self.config.cf_host(); + let stream = connect_cf_tunnel(egress, cf_host) + .map_err(|e| format!("cloudflare tunnel to {cf_host}:443: {e}"))?; + return HttpConn::from_tls(stream) + .map_err(|e| format!("cloudflare tunnel to {cf_host}:443: {e}")); + } let target = self.config.target_host(); if self.config.proxy_direct() { // Colocated direct mode (#6219): when the service on @@ -536,13 +618,14 @@ impl Broker { /// grow (see [`TunnelPool::checkout`] for the overflow /// policy); a grow reservation is handed back if the open /// fails so the live count never leaks. - fn pool_get(&self, port: u16) -> Result { - match self.pool.checkout(port) { + fn pool_get(&self, port: u16, transport: Transport) -> Result { + let key = (port, transport); + match self.pool.checkout(key) { Checkout::Idle(conn) => Ok(conn), - Checkout::Grow => match self.open_conn(port) { + Checkout::Grow => match self.open_conn(port, transport) { Ok(conn) => Ok(conn), Err(e) => { - self.pool.release(port); + self.pool.release(key); Err(e) } }, @@ -552,26 +635,49 @@ impl Broker { /// The retry path's fresh tunnel: reserved in the live /// count, opened immediately (no idle pop, no wait — the /// request is already on its second attempt). - fn pool_fresh(&self, port: u16) -> Result { - self.pool.reserve_fresh(port); - match self.open_conn(port) { + fn pool_fresh(&self, port: u16, transport: Transport) -> Result { + let key = (port, transport); + self.pool.reserve_fresh(key); + match self.open_conn(port, transport) { Ok(conn) => Ok(conn), Err(e) => { - self.pool.release(port); + self.pool.release(key); Err(e) } } } - fn pool_put(&self, port: u16, conn: HttpConn) { - self.pool.put(port, conn); - } - - /// One routed request, Python semantics: pooled connection - /// first, one retry on a fresh connection on any failure. - /// `client` distinguishes real client traffic (resets the idle - /// timer) from the broker's own keepalive (never does). - fn do_request(&self, req: &Request, client: bool) -> Result<(u16, serde_json::Value), String> { + fn pool_put(&self, port: u16, transport: Transport, conn: HttpConn) { + self.pool.put((port, transport), conn); + } + + /// Whether the Cloudflare leg can be attempted at all: the + /// egress env parsed at startup AND the Access file exists. + /// The file's existence is the enable (the Python broker's + /// rule) and is checked per request — dropping the file in, + /// or removing it, takes effect without a broker restart. + fn cf_available(&self) -> bool { + self.cf_egress.is_some() && self.config.cf_access_file().exists() + } + + /// One routed request: the request's attempt plan (see + /// [`attempt_plan`]) executed in order — pooled Cloudflare, + /// fresh Cloudflare, fresh tailnet when the leg is in play; + /// pooled tailnet, fresh tailnet otherwise. A Cloudflare + /// edge error status (502/503/530 — the edge answering for a + /// tunnel that is down) is not the service's reply: the + /// connection is dropped and the plan falls to the next leg. + /// Returns the status, the parsed body, and the transport + /// that actually served, which the caller stamps on the + /// response frame so a client's trip record proves which leg + /// a request rode. `client` distinguishes real client + /// traffic (resets the idle timer) from the broker's own + /// keepalive (never does). + fn do_request( + &self, + req: &Request, + client: bool, + ) -> Result<(u16, serde_json::Value, Transport), String> { if client { self.last_used.store(now_secs(), Ordering::Relaxed); } @@ -587,13 +693,31 @@ impl Broker { Some(body) => Some(serde_json::to_vec(body).map_err(|e| e.to_string())?), None => None, }; - let host_header = format!("{}:{}", self.config.target_host(), port); + let pref = req.transport.as_deref().unwrap_or("auto"); + let cf_ok = req.cf_ok.unwrap_or_else(|| cf_request_ok(req)); + let plan = attempt_plan( + port, + pref, + cf_ok, + self.cf_available(), + self.config.proxy_direct(), + ); + // The Access headers are read once per request (the file + // is the rotation surface) and ride Cloudflare attempts + // only. The trip id, when the frame carries one, rides + // every attempt — the daemon logs it per request, joining + // the client's trip record to the daemon's own log. + let cf_headers = if plan.iter().any(|(t, _)| *t == Transport::Cf) { + read_cf_access_headers(&self.config.cf_access_file()) + } else { + Vec::new() + }; let mut last_err: Option = None; - for attempt in 0..2 { - let mut conn = match if attempt == 0 { - self.pool_get(port) - } else { - self.pool_fresh(port) + for (transport, source) in &plan { + let key = (port, *transport); + let mut conn = match match source { + Source::Pool => self.pool_get(port, *transport), + Source::Fresh => self.pool_fresh(port, *transport), } { Ok(c) => c, Err(e) => { @@ -601,18 +725,43 @@ impl Broker { continue; } }; - match conn.request( + let host_header = match transport { + Transport::Cf => self.config.cf_host().to_string(), + Transport::Ts => format!("{}:{}", self.config.target_host(), port), + }; + let mut headers: Vec<(String, String)> = Vec::new(); + if let Some(trip) = &req.trip { + headers.push(("X-Trip-Id".to_string(), trip.clone())); + } + if *transport == Transport::Cf { + headers.extend(cf_headers.iter().cloned()); + } + match conn.request_with_extra_headers( &req.method, &req.path, &host_header, token, payload.as_deref(), + &headers, ) { Ok((status, data)) => { - self.pool_put(port, conn); + if *transport == Transport::Cf && CF_EDGE_STATUSES.contains(&status) { + // The edge answered for a dead tunnel: + // not the service's reply. Drop the + // connection and fall to the next leg, + // exactly as the Python broker does. + eprintln!( + "fleet proxy serve: cloudflare edge status {status} for {} {}; falling to next leg", + req.method, req.path + ); + self.pool.discard(key); + last_err = Some(format!("cloudflare edge status {status}")); + continue; + } + self.pool_put(port, *transport, conn); let body = serde_json::from_slice(&data) .map_err(|e| format!("service on port {port} answered non-JSON: {e}"))?; - return Ok((status, body)); + return Ok((status, body, *transport)); } Err(e) => { last_err = Some(match e { @@ -622,7 +771,7 @@ impl Broker { // conn drops: never re-pooled after an error, // and it stops counting against the pool's // live level. - self.pool.discard(port); + self.pool.discard(key); } } } @@ -646,6 +795,102 @@ impl Broker { } } +/// HTTP statuses that mean the Cloudflare EDGE answered, not +/// the service: the tunnel is down, or the edge cannot reach it. +/// The Python broker's set — the connection is dropped and the +/// plan falls to the next leg. +const CF_EDGE_STATUSES: [u16; 3] = [502, 503, 530]; + +/// The attempt plan for one request, the Python broker's plan +/// exactly (code#10356). The Cloudflare leg is in play only for +/// the laptop-agent daemon port, only when the caller's +/// per-request verdict allows the request to ride it (`cf_ok`), +/// the transport preference is `auto` or `cf`, the Access file +/// exists (`cf_available`), and the broker is not in colocated +/// direct mode (same-box there; the leg exists for the +/// cross-box case). In play, the plan is pooled-CF, fresh-CF, +/// and — under `auto` only — fresh tailnet. Every other case is +/// the historical plan: pooled tailnet, fresh tailnet. A `cf` +/// preference with the leg out of play degrades to the tailnet +/// plan: the preference is a preference, never a hard failure +/// (the Python's rule). +fn attempt_plan( + port: u16, + pref: &str, + cf_ok: bool, + cf_available: bool, + direct: bool, +) -> Vec<(Transport, Source)> { + let cf_in_play = !direct + && port == fleet_config::PORT_LAPTOP_AGENT + && cf_ok + && cf_available + && (pref == "auto" || pref == "cf"); + if cf_in_play { + let mut plan = vec![ + (Transport::Cf, Source::Pool), + (Transport::Cf, Source::Fresh), + ]; + if pref == "auto" { + plan.push((Transport::Ts, Source::Fresh)); + } + plan + } else { + vec![ + (Transport::Ts, Source::Pool), + (Transport::Ts, Source::Fresh), + ] + } +} + +/// The broker's own verdict on whether a request may ride the +/// Cloudflare leg, used when the frame carries no `cf_ok`: the +/// edge's response window makes a long /exec unsuitable — the +/// Python client's 660 s safety valve, computed from the same +/// body field. A frame that DOES carry `cf_ok` is honored +/// verbatim (the client computes the same rule, plus its own +/// knowledge of the request). +fn cf_request_ok(req: &Request) -> bool { + if req.path == "/exec" { + if let Some(timeout_s) = req + .body + .as_ref() + .and_then(|b| b.get("timeout_s")) + .and_then(|v| v.as_f64()) + { + if timeout_s > 660.0 { + return false; + } + } + } + true +} + +/// The Cloudflare Access service-token headers for one request, +/// read fresh from the Access file (rotation without a restart; +/// the values are never stored on the broker and never logged). +/// Any failure — missing file, bad JSON, missing fields — yields +/// no headers, the Python's rule: the request still rides the +/// leg and the edge's 403 is the service-visible answer. +fn read_cf_access_headers(path: &Path) -> Vec<(String, String)> { + let Ok(text) = std::fs::read_to_string(path) else { + return Vec::new(); + }; + let Ok(value) = serde_json::from_str::(&text) else { + return Vec::new(); + }; + let (Some(id), Some(secret)) = ( + value.get("client_id").and_then(|v| v.as_str()), + value.get("client_secret").and_then(|v| v.as_str()), + ) else { + return Vec::new(); + }; + vec![ + ("CF-Access-Client-Id".to_string(), id.to_string()), + ("CF-Access-Client-Secret".to_string(), secret.to_string()), + ] +} + /// Handle one request frame value; always answers a response frame /// value (errors ride the Python's `{status: 502, body:{error}}` /// shape — consumers branch on status, not on text). @@ -656,15 +901,22 @@ fn handle_request(broker: &Broker, frame: &serde_json::Value) -> serde_json::Val return serde_json::to_value(Response { status: 502, body: serde_json::json!({ "error": format!("broker: {why}") }), + transport: None, }) .unwrap(); } }; match broker.do_request(&req, true) { - Ok((status, body)) => serde_json::to_value(Response { status, body }).unwrap(), + Ok((status, body, transport)) => serde_json::to_value(Response { + status, + body, + transport: Some(transport.as_str().to_string()), + }) + .unwrap(), Err(why) => serde_json::to_value(Response { status: 502, body: serde_json::json!({ "error": format!("broker: {why}") }), + transport: None, }) .unwrap(), } @@ -704,9 +956,38 @@ fn parse_request(frame: &serde_json::Value) -> Result { } let body = frame.get("body").filter(|b| !b.is_null()).cloned(); let port = parse_port(frame)?; - let token_file = match frame.get("token_file") { + let token_file = parse_opt_string(frame, "token_file")?; + // The transport fields (code#10356) ride the same strict + // boundary: a present-but-misshapen value is refused, never + // silently reinterpreted — a `transport` that is not a string + // must not quietly become the default preference. + let trip = parse_opt_string(frame, "trip")?; + let transport = parse_opt_string(frame, "transport")?; + let cf_ok = match frame.get("cf_ok") { None | Some(serde_json::Value::Null) => None, - Some(serde_json::Value::String(path)) => Some(path.clone()), + Some(serde_json::Value::Bool(b)) => Some(*b), + Some(_) => return Err("request \"cf_ok\" must be a boolean or null".to_string()), + }; + Ok(Request { + method, + path, + body, + port, + token_file, + trip, + transport, + cf_ok, + }) +} + +/// An optional string frame field (`token_file`, and the +/// code#10356 `trip` / `transport` fields): absent or null is +/// None; a string is taken verbatim; anything else is refused +/// with the shape named — the #6516 strict-boundary rule. +fn parse_opt_string(frame: &serde_json::Value, field: &str) -> Result, String> { + match frame.get(field) { + None | Some(serde_json::Value::Null) => Ok(None), + Some(serde_json::Value::String(s)) => Ok(Some(s.clone())), Some(value) => { let shape = match value { serde_json::Value::Bool(_) => "boolean", @@ -716,18 +997,11 @@ fn parse_request(frame: &serde_json::Value) -> Result { serde_json::Value::Null => "null", serde_json::Value::String(_) => "string", }; - return Err(format!( - "request \"token_file\" must be a string or null, got {shape}" - )); + Err(format!( + "request \"{field}\" must be a string or null, got {shape}" + )) } - }; - Ok(Request { - method, - path, - body, - port, - token_file, - }) + } } /// The frame's `port`, strictly. Absent -- or null, mirroring how @@ -782,6 +1056,7 @@ fn serve_session(broker: &Broker, mut stream: UnixStream) { &serde_json::to_value(Response { status: 502, body: serde_json::json!({ "error": "broker: malformed hello" }), + transport: None, }) .unwrap(), ); @@ -829,6 +1104,7 @@ fn serve_session(broker: &Broker, mut stream: UnixStream) { body: serde_json::json!({ "error": "broker: first frame is neither hello nor request" }), + transport: None, }) .unwrap(), ); @@ -918,6 +1194,9 @@ fn keepalive_loop(broker: Arc, idle_exit: bool) { body: None, port: Some(fleet_config::PORT_LAPTOP_AGENT), token_file: None, + trip: None, + transport: None, + cf_ok: None, }; let mut last_health = now_secs(); loop { @@ -1059,24 +1338,51 @@ fn run_inner(config: &Config, idle_exit: bool) -> i32 { } } }; + let cf_egress = if config.proxy_direct() { + None + } else { + match egress_from_env_url_port() { + Ok(e) => Some(e), + Err(why) => { + eprintln!("fleet proxy serve: {why} (cloudflare leg will fail until it is set)"); + None + } + } + }; let broker = Arc::new(Broker { config: config.clone(), egress, + cf_egress, pool: TunnelPool::new(size), recovery: RecoveryGate::new(), last_used: AtomicU64::new(now_secs()), }); // Preconnect: warm the laptop-agent pool through the same // checkout accounting as requests, best effort (the Python - // does the same in a daemon thread). + // does the same in a daemon thread). The warmth goes to the + // pool the first requests will draw from: the Cloudflare + // pool when the leg is in play, switching to tailnet warmth + // if a Cloudflare open fails (the Python preconnect's rule); + // the tailnet pool otherwise, as before. { let broker = Arc::clone(&broker); std::thread::spawn(move || { + let port = fleet_config::PORT_LAPTOP_AGENT; + let mut transport = if broker.cf_available() { + Transport::Cf + } else { + Transport::Ts + }; for _ in 0..broker.pool.size() { - if let Ok(conn) = broker.pool_get(fleet_config::PORT_LAPTOP_AGENT) { - broker.pool_put(fleet_config::PORT_LAPTOP_AGENT, conn); - } else { - break; + match broker.pool_get(port, transport) { + Ok(conn) => broker.pool_put(port, transport, conn), + Err(_) => { + if transport == Transport::Cf { + transport = Transport::Ts; + continue; + } + break; + } } } }); @@ -1163,6 +1469,12 @@ mod tests { const PORT: u16 = 4799; + /// The pool/gate key the pre-transport tests exercise: the + /// daemon port on the tailnet leg. The Cloudflare leg's own + /// key separation is covered by + /// `pool_keys_separate_the_transports`. + const KEY: PoolKey = (PORT, Transport::Ts); + #[test] fn parse_request_validates_token_file_shape() { let mut absent = serde_json::json!({"method": "GET", "path": "/health"}); @@ -1233,29 +1545,186 @@ mod tests { }); } + #[test] + fn attempt_plan_puts_cloudflare_first_when_the_leg_is_in_play() { + // Daemon port, auto, suitable request, Access file + // present: pooled CF, fresh CF, fresh tailnet. + assert_eq!( + attempt_plan(PORT, "auto", true, true, false), + vec![ + (Transport::Cf, Source::Pool), + (Transport::Cf, Source::Fresh), + (Transport::Ts, Source::Fresh), + ] + ); + // cf pinned: no tailnet leg at all. + assert_eq!( + attempt_plan(PORT, "cf", true, true, false), + vec![ + (Transport::Cf, Source::Pool), + (Transport::Cf, Source::Fresh), + ] + ); + } + + #[test] + fn attempt_plan_degrades_to_the_tailnet_plan() { + let ts_plan = vec![ + (Transport::Ts, Source::Pool), + (Transport::Ts, Source::Fresh), + ]; + // ts pinned. + assert_eq!(attempt_plan(PORT, "ts", true, true, false), ts_plan); + // No Access file: the leg is not in play, even for cf. + assert_eq!(attempt_plan(PORT, "cf", true, false, false), ts_plan); + assert_eq!(attempt_plan(PORT, "auto", true, false, false), ts_plan); + // The request may not ride the edge (long /exec). + assert_eq!(attempt_plan(PORT, "auto", false, true, false), ts_plan); + // Other ports never take the leg. + assert_eq!( + attempt_plan(fleet_config::PORT_SECRETS_BROKER, "auto", true, true, false), + ts_plan + ); + // Colocated direct mode never takes the leg. + assert_eq!(attempt_plan(PORT, "auto", true, true, true), ts_plan); + // An unrecognized preference is not auto/cf: tailnet. + assert_eq!(attempt_plan(PORT, "warp", true, true, false), ts_plan); + } + + #[test] + fn pool_keys_separate_the_transports() { + // The legs' warmth must not share a bucket: a tunnel + // pooled under the Cloudflare key is invisible to a + // tailnet checkout for the same port, and the live + // counts are independent. + let pool = TunnelPool::new(2); + let cf_key = (PORT, Transport::Cf); + assert!(matches!(pool.checkout(cf_key), Checkout::Grow)); + pool.put(cf_key, dummy_conn()); + assert_eq!(pool.idle_count(cf_key), 1); + assert_eq!(pool.idle_count(KEY), 0); + assert!(matches!(pool.checkout(KEY), Checkout::Grow)); + assert_eq!(pool.live_count(KEY), 1); + assert_eq!(pool.live_count(cf_key), 1); + } + + #[test] + fn parse_request_reads_the_transport_fields() { + let frame = serde_json::json!({ + "method": "POST", + "path": "/exec", + "trip": "t-123", + "transport": "cf", + "cf_ok": false, + }); + let req = parse_request(&frame).unwrap(); + assert_eq!(req.trip.as_deref(), Some("t-123")); + assert_eq!(req.transport.as_deref(), Some("cf")); + assert_eq!(req.cf_ok, Some(false)); + + // Absent fields stay absent (pre-field frames parse + // exactly as before). + let bare = serde_json::json!({"method": "GET", "path": "/health"}); + let req = parse_request(&bare).unwrap(); + assert!(req.trip.is_none() && req.transport.is_none() && req.cf_ok.is_none()); + + // Misshapen fields are refused at the boundary. + let bad = serde_json::json!({"method": "GET", "path": "/health", "transport": 3}); + assert!(parse_request(&bad).unwrap_err().contains("transport")); + let bad = serde_json::json!({"method": "GET", "path": "/health", "cf_ok": "yes"}); + assert!(parse_request(&bad).unwrap_err().contains("cf_ok")); + } + + #[test] + fn cf_request_ok_applies_the_exec_safety_valve() { + let mk = |path: &str, body: serde_json::Value| Request { + method: "POST".to_string(), + path: path.to_string(), + body: Some(body), + port: None, + token_file: None, + trip: None, + transport: None, + cf_ok: None, + }; + // A long /exec may not ride the edge. + assert!(!cf_request_ok(&mk( + "/exec", + serde_json::json!({"timeout_s": 3600}) + ))); + assert!(cf_request_ok(&mk( + "/exec", + serde_json::json!({"timeout_s": 600}) + ))); + assert!(cf_request_ok(&mk( + "/exec", + serde_json::json!({"timeout_s": 660}) + ))); + // No timeout named: the daemon's own default applies, + // which is inside the valve. + assert!(cf_request_ok(&mk("/exec", serde_json::json!({})))); + // Other paths are unaffected by a timeout-shaped field. + assert!(cf_request_ok(&mk( + "/run", + serde_json::json!({"timeout_s": 3600}) + ))); + } + + #[test] + fn cf_access_headers_read_the_file_and_fail_closed_to_none() { + let dir = std::env::temp_dir().join(format!("fleet-cf-access-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("access.json"); + // Missing file: no headers (the request still rides the + // leg; the edge's 403 is the visible answer). + assert!(read_cf_access_headers(&path).is_empty()); + std::fs::write( + &path, + r#"{"client_id": "id-1", "client_secret": "secret-1"}"#, + ) + .unwrap(); + assert_eq!( + read_cf_access_headers(&path), + vec![ + ("CF-Access-Client-Id".to_string(), "id-1".to_string()), + ( + "CF-Access-Client-Secret".to_string(), + "secret-1".to_string() + ), + ] + ); + // Bad JSON / missing fields: no headers, never a panic. + std::fs::write(&path, "not json").unwrap(); + assert!(read_cf_access_headers(&path).is_empty()); + std::fs::write(&path, r#"{"client_id": "id-1"}"#).unwrap(); + assert!(read_cf_access_headers(&path).is_empty()); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn checkout_grows_below_ceiling_then_reuses_idle() { let pool = TunnelPool::new(2); - assert!(matches!(pool.checkout(PORT), Checkout::Grow)); - assert_eq!(pool.live_count(PORT), 1); - pool.put(PORT, dummy_conn()); - assert_eq!(pool.idle_count(PORT), 1); - assert!(matches!(pool.checkout(PORT), Checkout::Idle(_))); + assert!(matches!(pool.checkout(KEY), Checkout::Grow)); + assert_eq!(pool.live_count(KEY), 1); + pool.put(KEY, dummy_conn()); + assert_eq!(pool.idle_count(KEY), 1); + assert!(matches!(pool.checkout(KEY), Checkout::Idle(_))); // Checking out an idle tunnel does not change the // live count: the tunnel existed all along. - assert_eq!(pool.live_count(PORT), 1); - assert_eq!(pool.idle_count(PORT), 0); + assert_eq!(pool.live_count(KEY), 1); + assert_eq!(pool.idle_count(KEY), 0); } #[test] fn waiter_is_woken_by_put_and_gets_the_returned_tunnel() { let pool = Arc::new(TunnelPool::new(1)); // Occupy the only live slot. - assert!(matches!(pool.checkout(PORT), Checkout::Grow)); + assert!(matches!(pool.checkout(KEY), Checkout::Grow)); let (tx, rx) = mpsc::channel(); let waiter_pool = Arc::clone(&pool); let waiter = std::thread::spawn(move || { - let got = waiter_pool.checkout(PORT); + let got = waiter_pool.checkout(KEY); tx.send(matches!(got, Checkout::Idle(_))).unwrap(); }); // At the ceiling with nothing idle, the waiter must @@ -1266,21 +1735,21 @@ mod tests { other => panic!("waiter returned before any put: {other:?}"), } // Return a tunnel: the waiter wakes and reuses it. - pool.put(PORT, dummy_conn()); + pool.put(KEY, dummy_conn()); match rx.recv_timeout(Duration::from_secs(5)) { Ok(true) => {} other => panic!("waiter did not get the returned tunnel: {other:?}"), } waiter.join().unwrap(); - assert_eq!(pool.live_count(PORT), 1); + assert_eq!(pool.live_count(KEY), 1); } #[test] fn waiter_times_out_and_grows_anyway() { let pool = TunnelPool::new(1); - assert!(matches!(pool.checkout(PORT), Checkout::Grow)); + assert!(matches!(pool.checkout(KEY), Checkout::Grow)); let t0 = Instant::now(); - let got = pool.checkout(PORT); + let got = pool.checkout(KEY); let elapsed = t0.elapsed(); // Nobody returns anything: after the bounded wait the // checkout grows past the ceiling rather than failing. @@ -1290,46 +1759,46 @@ mod tests { "waited only {elapsed:?} of the {POOL_WAIT_BUDGET:?} budget" ); assert!(elapsed < Duration::from_secs(5), "waited {elapsed:?}"); - assert_eq!(pool.live_count(PORT), 2); + assert_eq!(pool.live_count(KEY), 2); } #[test] fn release_and_discard_keep_the_live_count_honest() { let pool = TunnelPool::new(2); - assert!(matches!(pool.checkout(PORT), Checkout::Grow)); - assert_eq!(pool.live_count(PORT), 1); - pool.release(PORT); // the open failed: reservation back - assert_eq!(pool.live_count(PORT), 0); + assert!(matches!(pool.checkout(KEY), Checkout::Grow)); + assert_eq!(pool.live_count(KEY), 1); + pool.release(KEY); // the open failed: reservation back + assert_eq!(pool.live_count(KEY), 0); - assert!(matches!(pool.checkout(PORT), Checkout::Grow)); - pool.put(PORT, dummy_conn()); - assert!(matches!(pool.checkout(PORT), Checkout::Idle(_))); - pool.discard(PORT); // the checked-out tunnel died in use - assert_eq!(pool.live_count(PORT), 0); - assert_eq!(pool.idle_count(PORT), 0); + assert!(matches!(pool.checkout(KEY), Checkout::Grow)); + pool.put(KEY, dummy_conn()); + assert!(matches!(pool.checkout(KEY), Checkout::Idle(_))); + pool.discard(KEY); // the checked-out tunnel died in use + assert_eq!(pool.live_count(KEY), 0); + assert_eq!(pool.idle_count(KEY), 0); } #[test] fn put_drops_when_idle_is_full_or_conn_not_reusable() { let pool = TunnelPool::new(1); - pool.reserve_fresh(PORT); - pool.put(PORT, dummy_conn()); // retained: idle 1, live 1 - assert_eq!(pool.idle_count(PORT), 1); - assert_eq!(pool.live_count(PORT), 1); + pool.reserve_fresh(KEY); + pool.put(KEY, dummy_conn()); // retained: idle 1, live 1 + assert_eq!(pool.idle_count(KEY), 1); + assert_eq!(pool.live_count(KEY), 1); - pool.reserve_fresh(PORT); // live 2 (retry path counts too) - pool.put(PORT, dummy_conn()); // idle full: dropped, live 1 - assert_eq!(pool.idle_count(PORT), 1); - assert_eq!(pool.live_count(PORT), 1); + pool.reserve_fresh(KEY); // live 2 (retry path counts too) + pool.put(KEY, dummy_conn()); // idle full: dropped, live 1 + assert_eq!(pool.idle_count(KEY), 1); + assert_eq!(pool.live_count(KEY), 1); - assert!(matches!(pool.checkout(PORT), Checkout::Idle(_))); - pool.discard(PORT); - assert_eq!(pool.live_count(PORT), 0); + assert!(matches!(pool.checkout(KEY), Checkout::Idle(_))); + pool.discard(KEY); + assert_eq!(pool.live_count(KEY), 0); - pool.reserve_fresh(PORT); - pool.put(PORT, close_conn()); // not reusable: never pooled - assert_eq!(pool.idle_count(PORT), 0); - assert_eq!(pool.live_count(PORT), 0); + pool.reserve_fresh(KEY); + pool.put(KEY, close_conn()); // not reusable: never pooled + assert_eq!(pool.idle_count(KEY), 0); + assert_eq!(pool.live_count(KEY), 0); } #[test] @@ -1346,7 +1815,7 @@ mod tests { Err::<(), String>("tunnel to laptop:4799: refused".to_string()) }; // Prime: a normal-mode failure arms single-flight recovery. - let priming = gate.run(PORT, || attempt(&attempts)); + let priming = gate.run(KEY, || attempt(&attempts)); assert!(priming.is_err()); assert_eq!(attempts.load(Ordering::Relaxed), 1); let mut handles = Vec::new(); @@ -1354,7 +1823,7 @@ mod tests { let gate = Arc::clone(&gate); let attempts = Arc::clone(&attempts); handles.push(std::thread::spawn(move || { - gate.run(PORT, || attempt(&attempts)) + gate.run(KEY, || attempt(&attempts)) })); } for h in handles { @@ -1381,7 +1850,7 @@ mod tests { let in_flight = Arc::clone(&in_flight); let peak = Arc::clone(&peak); handles.push(std::thread::spawn(move || { - gate.run(PORT, || { + gate.run(KEY, || { let now = in_flight.fetch_add(1, Ordering::Relaxed) + 1; peak.fetch_max(now, Ordering::Relaxed); std::thread::sleep(Duration::from_millis(100)); @@ -1414,21 +1883,21 @@ mod tests { std::thread::sleep(Duration::from_millis(ms)); Err::<(), String>(format!("failure-{k}")) }; - assert_eq!(gate.run(PORT, || mk(&n, 0)).unwrap_err(), "failure-1"); + assert_eq!(gate.run(KEY, || mk(&n, 0)).unwrap_err(), "failure-1"); // Leader: recovery attempt #2 (slow fail), then an // immediate retry = attempt #3 (even slower fail). let leader = { let gate = Arc::clone(&gate); let n = Arc::clone(&n); std::thread::spawn(move || { - let first = gate.run(PORT, || mk(&n, 200)); - let second = gate.run(PORT, || mk(&n, 600)); + let first = gate.run(KEY, || mk(&n, 200)); + let second = gate.run(KEY, || mk(&n, 600)); (first, second) }) }; // Waiter arrives while attempt #2 is in flight. std::thread::sleep(Duration::from_millis(50)); - let waited = gate.run(PORT, || mk(&n, 0)); + let waited = gate.run(KEY, || mk(&n, 0)); // The waiter shares attempt #2's verdict — it neither // waits for nor reports attempt #3's. assert_eq!(waited.unwrap_err(), "failure-2"); @@ -1442,13 +1911,13 @@ mod tests { // After a recovery succeeds, opens are concurrent again. let gate = Arc::new(RecoveryGate::new()); assert!( - gate.run(PORT, || Err::<(), String>("dead".to_string())) + gate.run(KEY, || Err::<(), String>("dead".to_string())) .is_err() ); - assert!(gate.run(PORT, || Ok::<(), String>(())).is_ok()); + assert!(gate.run(KEY, || Ok::<(), String>(())).is_ok()); // needs_recovery cleared: a later failure is a fresh // normal-mode failure, and the gate re-arms only then. - assert!(gate.run(PORT, || Ok::<(), String>(())).is_ok()); + assert!(gate.run(KEY, || Ok::<(), String>(())).is_ok()); } // Model-based property test for the RecoveryGate decision diff --git a/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs b/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs index 200d8297c0..fe9a82f861 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs @@ -178,6 +178,46 @@ pub fn egress_from_env(proxy_port: u16) -> Result { egress_from_url(&raw, proxy_port) } +/// The egress endpoint for the Cloudflare leg (code#10356): the +/// same proxy, but dialled at the URL's OWN port — the internet +/// egress port (3128 in the runtime shape), NOT the tailnet +/// tunnel port [`egress_from_env`] substitutes. The asymmetry is +/// the runtime's, exactly as the Python client's two socket +/// builders encoded it before the leg moved into fleet: the +/// tailnet CONNECT goes to the session proxy on the configured +/// port; the Cloudflare CONNECT goes to the platform egress at +/// the port the proxy URL itself names. +pub fn egress_from_env_url_port() -> Result { + let raw = std::env::var("HTTPS_PROXY") + .map_err(|_| "HTTPS_PROXY must be set (runtime proxy env)".to_string())?; + egress_from_url_url_port(&raw) +} + +/// [`egress_from_env_url_port`] with the URL supplied (tests). +pub fn egress_from_url_url_port(raw: &str) -> Result { + egress_from_url(raw, url_port(raw).unwrap_or(3128)) +} + +/// The port named by a proxy URL, if it names one. Mirrors the +/// authority parsing in [`egress_from_url`]: userinfo ends at the +/// last '@'; a bracketed v6 literal's port follows the bracket. +fn url_port(raw: &str) -> Option { + let after_scheme = raw.split_once("://").map(|(_, rest)| rest).unwrap_or(raw); + let authority = after_scheme + .split(['/', '?', '#']) + .next() + .unwrap_or(after_scheme); + let hostport = match authority.rfind('@') { + Some(at) => &authority[at + 1..], + None => authority, + }; + if let Some(rest) = hostport.strip_prefix('[') { + let (_, after) = rest.split_once(']')?; + return after.strip_prefix(':')?.parse().ok(); + } + hostport.rsplit_once(':')?.1.parse().ok() +} + /// [`egress_from_env`] with the URL supplied (tests, diagnostics). pub fn egress_from_url(raw: &str, proxy_port: u16) -> Result { let after_scheme = raw.split_once("://").map(|(_, rest)| rest).unwrap_or(raw); @@ -339,6 +379,138 @@ fn tune(stream: &TcpStream, http_timeouts: bool) { stream.set_nodelay(true).ok(); } +// --------------------------------------------------------------------------- +// The Cloudflare leg (code#10356): TLS to the named tunnel's edge +// hostname, through the egress proxy. Serve-gated: the connect +// variants must not grow a TLS stack (the D7 size gate), and only +// the broker speaks to the edge. The daemon end of the tunnel is +// untouched — cloudflared on the laptop terminates the tunnel and +// dials the daemon's own listener, so the daemon's token auth is +// preserved end to end; the Access headers ride the HTTP layer +// (http.rs), not this one. +// --------------------------------------------------------------------------- + +/// Setup budget for the Cloudflare leg: the CONNECT through the +/// egress proxy plus the TLS handshake to the edge. The edge is +/// an internet endpoint, not the local tailnet proxy, so the 2 s +/// transport deadline is too tight; the Python client's cf_socket +/// allowed the establishment 60 s — 15 s keeps the same order of +/// bound. Once established, the stream carries the standard HTTP +/// timeouts, like every other tunnel. +#[cfg(feature = "serve")] +pub const CF_SETUP_DEADLINE: Duration = Duration::from_secs(15); + +/// A TLS stream to the Cloudflare edge, shared between an HTTP +/// connection's reader and writer halves. A rustls session is +/// stateful in both directions over one socket, so unlike a plain +/// `TcpStream` the halves cannot be independent socket clones: +/// they are two handles on one session behind a mutex. The broker +/// uses a pooled connection from one thread at a time (checkout +/// is exclusive) and every lock is held only for a single read or +/// write call, so the mutex never serializes real work. +#[cfg(feature = "serve")] +#[derive(Clone)] +pub struct SharedTlsStream { + inner: + std::sync::Arc>>, +} + +#[cfg(feature = "serve")] +impl SharedTlsStream { + /// The other half of the same session (see the type docs). + pub fn try_clone(&self) -> std::io::Result { + Ok(self.clone()) + } +} + +#[cfg(feature = "serve")] +impl Read for SharedTlsStream { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + self.inner.lock().unwrap().read(buf) + } +} + +#[cfg(feature = "serve")] +impl Write for SharedTlsStream { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.inner.lock().unwrap().write(buf) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.inner.lock().unwrap().flush() + } +} + +/// The TLS client configuration for the edge, built once. Roots: +/// the public webpki set PLUS the platform store — hosts behind +/// the sandbox's TLS-intercepting egress proxy present the +/// proxy's CA, which only the platform store carries (the fleet +/// gh leg learned this the hard way; see crates/fleet/src/gh.rs), +/// while the edge's real certificate chains to the public set. +/// Carrying both keeps the leg working whether or not the proxy +/// intercepts this host. Platform-store load errors are not +/// fatal: the webpki roots still anchor the uninterrupted case. +/// The crypto provider is pinned to ring explicitly, so building +/// the config never depends on a process-level provider another +/// part of the binary happened to install. +#[cfg(feature = "serve")] +fn cf_tls_config() -> &'static std::sync::Arc { + static CONFIG: std::sync::OnceLock> = + std::sync::OnceLock::new(); + CONFIG.get_or_init(|| { + let mut roots = rustls::RootCertStore::empty(); + roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); + for cert in rustls_native_certs::load_native_certs().certs { + let _ = roots.add(cert); + } + let config = rustls::ClientConfig::builder_with_provider( + rustls::crypto::ring::default_provider().into(), + ) + .with_safe_default_protocol_versions() + .expect("rustls safe default protocol versions") + .with_root_certificates(roots) + .with_no_client_auth(); + std::sync::Arc::new(config) + }) +} + +/// Open the Cloudflare leg: a TLS stream to `cf_host:443` through +/// the egress proxy (a CONNECT at the egress URL's own port — +/// see [`egress_from_env_url_port`]), with the handshake completed +/// eagerly so an establishment failure surfaces at open time. The +/// pool's accounting relies on that contract, the same reason the +/// Python broker connected eagerly. +#[cfg(feature = "serve")] +pub fn connect_cf_tunnel(egress: &Egress, cf_host: &str) -> std::io::Result { + let start = Instant::now(); + let tcp = connect_tunnel_with_deadline(Some(egress), cf_host, 443, CF_SETUP_DEADLINE)?; + // The CONNECT applied the HTTP timeouts; the handshake gets + // only what is left of the setup budget. + let left = remaining(CF_SETUP_DEADLINE, start) + .ok_or_else(|| deadline_exceeded("TLS handshake", CF_SETUP_DEADLINE))?; + tcp.set_read_timeout(Some(left))?; + tcp.set_write_timeout(Some(left))?; + let server_name = + rustls::pki_types::ServerName::try_from(cf_host.to_string()).map_err(|e| { + std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("bad CF host name: {e}"), + ) + })?; + let conn = rustls::ClientConnection::new(cf_tls_config().clone(), server_name) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e.to_string()))?; + let mut stream = rustls::StreamOwned::new(conn, tcp); + while stream.conn.is_handshaking() { + stream.conn.complete_io(&mut stream.sock)?; + } + // Established: the standard HTTP timeouts apply from here. + stream.sock.set_read_timeout(Some(TUNNEL_READ_TIMEOUT))?; + stream.sock.set_write_timeout(Some(TUNNEL_WRITE_TIMEOUT))?; + Ok(SharedTlsStream { + inner: std::sync::Arc::new(std::sync::Mutex::new(stream)), + }) +} + #[cfg(test)] mod tests { use super::*; @@ -482,4 +654,78 @@ mod tests { assert_eq!(stream.read_timeout().unwrap(), None); assert_eq!(stream.write_timeout().unwrap(), None); } + + #[test] + fn url_port_reads_the_urls_own_port() { + // The Cloudflare leg dials the egress proxy at the port + // the URL itself names (code#10356) — the one place the + // URL's port is used instead of the configured tunnel + // port. + assert_eq!(url_port("http://user:pass@198.19.0.1:3128"), Some(3128)); + assert_eq!(url_port("http://user:pass@198.19.0.1:3130/"), Some(3130)); + assert_eq!(url_port("http://[2001:db8::1]:3128"), Some(3128)); + assert_eq!(url_port("http://user:pass@198.19.0.1"), None); + assert_eq!(url_port("http://user:pass@198.19.0.1:notaport"), None); + } + + #[test] + fn cf_egress_uses_the_url_port_not_the_tunnel_port() { + let egress = egress_from_url_url_port("http://u:p@proxy.invalid:3128").unwrap(); + assert_eq!(egress.host, "proxy.invalid"); + assert_eq!(egress.port, 3128); + // No port in the URL: the runtime's internet egress port. + let egress = egress_from_url_url_port("http://u:p@proxy.invalid").unwrap(); + assert_eq!(egress.port, 3128); + // The tailnet construction is untouched by the split: + // the configured port still wins there. + let egress = egress_from_url("http://u:p@proxy.invalid:3128", 3130).unwrap(); + assert_eq!(egress.port, 3130); + } + + #[cfg(feature = "serve")] + #[test] + fn cf_tunnel_speaks_tls_after_the_connect() { + // Fault-injection shape: a fake egress proxy that answers + // the CONNECT 200 and records the first byte that follows. + // A correct Cloudflare leg sends a TLS ClientHello next + // (0x16, the handshake record type) addressed to the + // tunnel hostname — never plaintext HTTP. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let proxy = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut request = Vec::new(); + let mut byte = [0u8; 1]; + while !request.ends_with(b"\r\n\r\n") { + stream.read_exact(&mut byte).unwrap(); + request.push(byte[0]); + } + stream + .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n") + .unwrap(); + let mut first = [0u8; 1]; + stream.read_exact(&mut first).unwrap(); + (String::from_utf8_lossy(&request).into_owned(), first[0]) + }); + let egress = Egress { + host: "127.0.0.1".to_string(), + port: addr.port(), + authorization: "Basic dTpw".to_string(), + }; + // The handshake cannot complete against the fake proxy + // (nothing answers the ClientHello, and the name would not + // verify anyway) — the open must FAIL, having first sent + // the CONNECT for the tunnel host and a ClientHello. + let got = connect_cf_tunnel(&egress, "sandbox-link.security.cab"); + assert!(got.is_err(), "no real edge, no tunnel"); + let (request, first) = proxy.join().unwrap(); + assert!( + request.starts_with("CONNECT sandbox-link.security.cab:443 "), + "CONNECT must target the tunnel host at 443: {request:?}" + ); + assert_eq!( + first, 0x16, + "first post-CONNECT byte must be a TLS handshake record" + ); + } } diff --git a/pkgs/fleet/crates/fleet-secrets/src/lib.rs b/pkgs/fleet/crates/fleet-secrets/src/lib.rs index ce3bf0f376..26fa09fc59 100644 --- a/pkgs/fleet/crates/fleet-secrets/src/lib.rs +++ b/pkgs/fleet/crates/fleet-secrets/src/lib.rs @@ -235,6 +235,9 @@ impl BrokerSource { body: None, port: Some(fleet_config::PORT_SECRETS_BROKER), token_file: Some(self.token_file.to_string_lossy().into_owned()), + trip: None, + transport: None, + cf_ok: None, }; let mut stream = self.connect(name)?; self.exchange(&mut stream, &request, name) @@ -935,6 +938,7 @@ mod tests { let resp = Response { status: 200, body: serde_json::json!({"names": ["a.name", "b.name"]}), + transport: None, }; fleet_proxy_proto::write_frame(&mut stream, &resp).unwrap(); }); @@ -965,7 +969,11 @@ mod tests { let (mut stream, _) = listener.accept().unwrap(); let req: Request = fleet_proxy_proto::read_typed(&mut stream).unwrap(); assert_eq!(req.path, "/secret/wanted.name"); - let resp = Response { status: 200, body }; + let resp = Response { + status: 200, + body, + transport: None, + }; fleet_proxy_proto::write_frame(&mut stream, &resp).unwrap(); }); let source = BrokerSource { @@ -1013,7 +1021,11 @@ mod tests { assert_eq!(req.path, "/secret/wanted.name"); assert_eq!(req.port, Some(fleet_config::PORT_SECRETS_BROKER)); assert_eq!(req.token_file.as_deref(), Some("/nonexistent/token")); - let resp = Response { status, body }; + let resp = Response { + status, + body, + transport: None, + }; fleet_proxy_proto::write_frame(&mut server, &resp).unwrap(); }); let source = BrokerSource { @@ -1034,6 +1046,9 @@ mod tests { body: None, port: Some(fleet_config::PORT_SECRETS_BROKER), token_file: Some("/nonexistent/token".to_string()), + trip: None, + transport: None, + cf_ok: None, }; let resp = source .exchange(&mut client, &request, "wanted.name")