From 0c8f82eb310a0ce1971bdb2146e05712c572db1e Mon Sep 17 00:00:00 2001 From: atlas Date: Fri, 27 Nov 2026 09:26:29 +0100 Subject: [PATCH] the responders drop the unix-socket listener nothing uses since WP4/WP5 swarm-logs-auth and swarm-metrics-auth serve the TCP address --listen names and nothing else. Every unit of theirs runs as a pod, and the VM test that ran them on a socket takes --listen. --- nix/vm-tests/k8s-swarm-images.nix | 19 +----- swarm-logs-auth/src/main.rs | 108 ++++++++---------------------- swarm-metrics-auth/src/main.rs | 98 +++++++-------------------- 3 files changed, 57 insertions(+), 168 deletions(-) diff --git a/nix/vm-tests/k8s-swarm-images.nix b/nix/vm-tests/k8s-swarm-images.nix index 6ebce197e..15945dd4f 100644 --- a/nix/vm-tests/k8s-swarm-images.nix +++ b/nix/vm-tests/k8s-swarm-images.nix @@ -56,7 +56,6 @@ let args ? [ ], env ? [ ], restartPolicy ? "Always", - socketDir ? false, }: { apiVersion = "v1"; @@ -77,20 +76,8 @@ let // lib.optionalAttrs (restartPolicy == "Always") { readinessProbe = probe "/readyz"; } - // lib.optionalAttrs socketDir { - volumeMounts = [ - { - name = "sock"; - mountPath = "/sock"; - } - ]; - } ) ]; - volumes = lib.optional socketDir { - name = "sock"; - emptyDir = { }; - }; }; }; @@ -98,22 +85,20 @@ let swarm-logs-auth = mkPod { name = "swarm-logs-auth"; args = [ - "--socket=/sock/s.sock" + "--listen=0.0.0.0:8081" "--surface=logs" "--health-addr=0.0.0.0:${toString healthPort}" ]; env = storeEnv; - socketDir = true; }; swarm-metrics-auth = mkPod { name = "swarm-metrics-auth"; args = [ - "--socket=/sock/s.sock" + "--listen=0.0.0.0:8081" "--store-path=swarm/stub" "--health-addr=0.0.0.0:${toString healthPort}" ]; env = storeEnv; - socketDir = true; }; swarm-notify-router = mkPod { name = "swarm-notify-router"; diff --git a/swarm-logs-auth/src/main.rs b/swarm-logs-auth/src/main.rs index 6ed7309db..3d64be0a3 100644 --- a/swarm-logs-auth/src/main.rs +++ b/swarm-logs-auth/src/main.rs @@ -20,10 +20,8 @@ //! //! It logs in to the store as the cert-auth role `--store-cert-role` names, //! whose policy reaches every agent's `queue` secret and grant leaf. It serves -//! a unix socket whose directory only the gateway's nginx may enter, or, with -//! `--listen`, a TCP address for a gateway that is not on this host's -//! filesystem. The address is not authenticated: whoever reaches it is the -//! gateway. +//! the TCP address `--listen` names, which is not authenticated: whoever +//! reaches it is the gateway, so the pod's `NetworkPolicy` admits only the node. //! //! A grant is remembered for `--verdict-ttl` seconds ([`verdicts`]), so an //! agent's queries within that window cost no store lookup, and a secret that @@ -33,8 +31,6 @@ mod verdicts; use std::future::Future; -use std::os::unix::fs::PermissionsExt as _; -use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -57,17 +53,11 @@ const LOOKUP_TIMEOUT: Duration = Duration::from_secs(5); const VERDICT_CAP: usize = 4096; #[derive(Parser)] -#[command( - about = "auth_request responder: checks an agent's queue secret against the store", - group(clap::ArgGroup::new("bind").required(true).args(["socket", "listen"])) -)] +#[command(about = "auth_request responder: checks an agent's queue secret against the store")] struct Args { - /// Unix socket to serve on. Exactly one of `--socket` and `--listen`. + /// TCP address to serve on. #[arg(long)] - socket: Option, - /// TCP address to serve on, for a caller that is not on this host's filesystem. - #[arg(long)] - listen: Option, + listen: std::net::SocketAddr, /// Address to serve `/healthz` and `/readyz` on. Nothing listens unless set; /// the environment variable `SWARM_LOGS_AUTH_HEALTH_ADDR` is read when the flag is absent. #[arg(long)] @@ -291,7 +281,7 @@ async fn main() -> anyhow::Result<()> { )), }); - let bound = bind(args.socket.as_deref(), args.listen).await?; + let listener = bind(args.listen).await?; // Ready means the store answers: with it down every request is a 503. let probe = Arc::clone(&responder); health.ready_while_checked(move || { @@ -300,59 +290,25 @@ async fn main() -> anyhow::Result<()> { }); let app = axum::Router::new().fallback(handle).with_state(responder); - match bound { - Bound::Unix(listener) => serve(listener, app, stop).await, - Bound::Tcp(listener) => serve(listener, app, stop).await, - } + serve(listener, app, stop).await } -/// What the responder answers on. -enum Bound { - Unix(tokio::net::UnixListener), - Tcp(tokio::net::TcpListener), -} - -/// Binds `listen` when given, else `socket`; `Args` requires one of the two. -async fn bind( - socket: Option<&std::path::Path>, - listen: Option, -) -> anyhow::Result { - if let Some(addr) = listen { - let listener = tokio::net::TcpListener::bind(addr) - .await - .with_context(|| format!("binding {addr}"))?; - tracing::info!(%addr, "swarm-logs-auth listening"); - return Ok(Bound::Tcp(listener)); - } - let socket = socket.context("neither --socket nor --listen is set")?; - // `RuntimeDirectoryPreserve=yes` can leave the previous run's socket; the - // directory is this unit's alone, so unlinking it is safe. - if let Err(e) = std::fs::remove_file(socket) - && e.kind() != std::io::ErrorKind::NotFound - { - return Err(e).with_context(|| format!("clearing stale socket at {}", socket.display())); - } - let listener = tokio::net::UnixListener::bind(socket) - .with_context(|| format!("binding {}", socket.display()))?; - // nginx is another user and `connect(2)` needs write. The directory is - // the access control, not this mode. - std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o666)) - .with_context(|| format!("chmod {}", socket.display()))?; - tracing::info!(socket = %socket.display(), "swarm-logs-auth listening"); - Ok(Bound::Unix(listener)) +/// Binds the address `--listen` names. +async fn bind(addr: std::net::SocketAddr) -> anyhow::Result { + let listener = tokio::net::TcpListener::bind(addr) + .await + .with_context(|| format!("binding {addr}"))?; + tracing::info!(%addr, "swarm-logs-auth listening"); + Ok(listener) } /// Answers on `listener` until `stop` resolves, then lets the requests in hand /// finish, for at most the drain, and returns. -async fn serve( - listener: L, +async fn serve( + listener: tokio::net::TcpListener, app: axum::Router, stop: impl Future + Clone + Send + 'static, -) -> anyhow::Result<()> -where - L: axum::serve::Listener, - L::Addr: std::fmt::Debug, -{ +) -> anyhow::Result<()> { let serving = axum::serve(listener, app).with_graceful_shutdown(stop.clone()); swarm_secret_client::serve_bounded(stop, serving.into_future()) .await @@ -726,10 +682,10 @@ mod tests { } }) }; - let socket = - std::env::temp_dir().join(format!("swarm-logs-auth-stop-{}.sock", std::process::id())); - let _ = std::fs::remove_file(&socket); - let listener = tokio::net::UnixListener::bind(&socket).expect("bind"); + let listener = bind("127.0.0.1:0".parse().expect("addr")) + .await + .expect("bind"); + let addr = listener.local_addr().expect("addr"); let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); let stop = async move { let _ = stop_rx.await; @@ -737,9 +693,7 @@ mod tests { .shared(); let mut serving = tokio::spawn(serve(listener, app, stop)); - let mut conn = tokio::net::UnixStream::connect(&socket) - .await - .expect("connect"); + let mut conn = tokio::net::TcpStream::connect(addr).await.expect("connect"); conn.write_all(b"GET / HTTP/1.1\r\nhost: x\r\nconnection: close\r\n\r\n") .await .expect("send"); @@ -761,7 +715,6 @@ mod tests { .await .expect("serve returns once the request is answered"); finished.expect("task").expect("serve is Ok"); - let _ = std::fs::remove_file(&socket); } fn args(extra: &[&str]) -> Result { Args::try_parse_from( @@ -771,24 +724,21 @@ mod tests { ) } - /// The socket and the TCP address are alternatives, and one is required. + /// `--listen` is required, and `--socket` is not an option. #[test] - fn exactly_one_of_socket_and_listen_is_required() { + fn listen_is_required_and_socket_is_not_an_option() { assert!(args(&[]).is_err()); + assert!(args(&["--socket", "/x"]).is_err()); assert!(args(&["--socket", "/x", "--listen", "127.0.0.1:1"]).is_err()); - assert!(args(&["--socket", "/x"]).is_ok()); assert!(args(&["--listen", "127.0.0.1:1"]).is_ok()); } - /// `--listen` answers over TCP, and `serve` returns once the stop arrives. + /// The listener answers over TCP, and `serve` returns once the stop arrives. #[tokio::test] - async fn listen_answers_over_tcp_and_stops() { - let Bound::Tcp(listener) = bind(None, Some("127.0.0.1:0".parse().expect("addr"))) + async fn the_listener_answers_over_tcp_and_stops() { + let listener = bind("127.0.0.1:0".parse().expect("addr")) .await - .expect("bind") - else { - panic!("--listen did not bind a TCP listener"); - }; + .expect("bind"); let addr = listener.local_addr().expect("addr"); let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); let stop = async move { diff --git a/swarm-metrics-auth/src/main.rs b/swarm-metrics-auth/src/main.rs index 655a186af..eef2514c6 100644 --- a/swarm-metrics-auth/src/main.rs +++ b/swarm-metrics-auth/src/main.rs @@ -9,11 +9,10 @@ //! store that does not answer is a 503 until a value has been read (see //! below), which the gateway hands on. //! -//! It reads the store under its own certificate, whose policy reaches that one -//! path. It serves a unix socket whose directory only the gateway's nginx may -//! enter, or, with `--listen`, a TCP address for a gateway that is not on this -//! host's filesystem. The address is not authenticated: whoever reaches it is the -//! gateway. +//! It reads the store under its own identity, whose policy reaches that one +//! path. It serves the TCP address `--listen` names, which is not authenticated: +//! whoever reaches it is the gateway, so the pod's `NetworkPolicy` admits only the +//! node. //! //! The stored value is kept for `--cache-ttl` seconds, and no request reaches //! the store within that window: a replaced bearer is refused, and the one it @@ -33,8 +32,6 @@ //! and a process that has not yet read the store has none: both answer 503. use std::future::Future; -use std::os::unix::fs::PermissionsExt as _; -use std::path::PathBuf; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -65,17 +62,11 @@ const LOOKUP_FAILURE_WINDOW: Duration = Duration::from_secs(3); const MAX_KEPT_AGE: Duration = Duration::from_hours(1); #[derive(Parser)] -#[command( - about = "auth_request responder: checks Grafana's metrics bearer against the store", - group(clap::ArgGroup::new("bind").required(true).args(["socket", "listen"])) -)] +#[command(about = "auth_request responder: checks Grafana's metrics bearer against the store")] struct Args { - /// Unix socket to serve on. Exactly one of `--socket` and `--listen`. + /// TCP address to serve on. #[arg(long)] - socket: Option, - /// TCP address to serve on, for a caller that is not on this host's filesystem. - #[arg(long)] - listen: Option, + listen: std::net::SocketAddr, /// Address to serve `/healthz` and `/readyz` on. Nothing listens unless set; /// the environment variable `SWARM_METRICS_AUTH_HEALTH_ADDR` is read when the flag is absent. #[arg(long)] @@ -345,7 +336,7 @@ async fn main() -> anyhow::Result<()> { cached: tokio::sync::Mutex::new(Cache::default()), }); - let bound = bind(args.socket.as_deref(), args.listen).await?; + let listener = bind(args.listen).await?; // Ready means the store answers: with it down the bearer can't be checked. let probe = Arc::clone(&responder); health.ready_while_checked(move || { @@ -354,59 +345,25 @@ async fn main() -> anyhow::Result<()> { }); let app = axum::Router::new().fallback(handle).with_state(responder); - match bound { - Bound::Unix(listener) => serve(listener, app, stop).await, - Bound::Tcp(listener) => serve(listener, app, stop).await, - } + serve(listener, app, stop).await } -/// What the responder answers on. -enum Bound { - Unix(tokio::net::UnixListener), - Tcp(tokio::net::TcpListener), -} - -/// Binds `listen` when given, else `socket`; `Args` requires one of the two. -async fn bind( - socket: Option<&std::path::Path>, - listen: Option, -) -> anyhow::Result { - if let Some(addr) = listen { - let listener = tokio::net::TcpListener::bind(addr) - .await - .with_context(|| format!("binding {addr}"))?; - tracing::info!(%addr, "swarm-metrics-auth listening"); - return Ok(Bound::Tcp(listener)); - } - let socket = socket.context("neither --socket nor --listen is set")?; - // `RuntimeDirectoryPreserve=yes` can leave the previous run's socket; the - // directory is this unit's alone, so unlinking it is safe. - if let Err(e) = std::fs::remove_file(socket) - && e.kind() != std::io::ErrorKind::NotFound - { - return Err(e).with_context(|| format!("clearing stale socket at {}", socket.display())); - } - let listener = tokio::net::UnixListener::bind(socket) - .with_context(|| format!("binding {}", socket.display()))?; - // nginx is another user and `connect(2)` needs write. The directory is - // the access control, not this mode. - std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o666)) - .with_context(|| format!("chmod {}", socket.display()))?; - tracing::info!(socket = %socket.display(), "swarm-metrics-auth listening"); - Ok(Bound::Unix(listener)) +/// Binds the address `--listen` names. +async fn bind(addr: std::net::SocketAddr) -> anyhow::Result { + let listener = tokio::net::TcpListener::bind(addr) + .await + .with_context(|| format!("binding {addr}"))?; + tracing::info!(%addr, "swarm-metrics-auth listening"); + Ok(listener) } /// Answers on `listener` until `stop` resolves, then lets the requests in hand /// finish, for at most the drain, and returns. -async fn serve( - listener: L, +async fn serve( + listener: tokio::net::TcpListener, app: axum::Router, stop: impl Future + Clone + Send + 'static, -) -> anyhow::Result<()> -where - L: axum::serve::Listener, - L::Addr: std::fmt::Debug, -{ +) -> anyhow::Result<()> { let serving = axum::serve(listener, app).with_graceful_shutdown(stop.clone()); swarm_secret_client::serve_bounded(stop, serving.into_future()) .await @@ -837,24 +794,21 @@ mod tests { ) } - /// The socket and the TCP address are alternatives, and one is required. + /// `--listen` is required, and `--socket` is not an option. #[test] - fn exactly_one_of_socket_and_listen_is_required() { + fn listen_is_required_and_socket_is_not_an_option() { assert!(args(&[]).is_err()); + assert!(args(&["--socket", "/x"]).is_err()); assert!(args(&["--socket", "/x", "--listen", "127.0.0.1:1"]).is_err()); - assert!(args(&["--socket", "/x"]).is_ok()); assert!(args(&["--listen", "127.0.0.1:1"]).is_ok()); } - /// `--listen` answers over TCP, and `serve` returns once the stop arrives. + /// The listener answers over TCP, and `serve` returns once the stop arrives. #[tokio::test] - async fn listen_answers_over_tcp_and_stops() { - let Bound::Tcp(listener) = bind(None, Some("127.0.0.1:0".parse().expect("addr"))) + async fn the_listener_answers_over_tcp_and_stops() { + let listener = bind("127.0.0.1:0".parse().expect("addr")) .await - .expect("bind") - else { - panic!("--listen did not bind a TCP listener"); - }; + .expect("bind"); let addr = listener.local_addr().expect("addr"); let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); let stop = async move {