Watch
0
0
Fork
You've already forked hyperhive
0

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.
This commit is contained in:
atlas 2026-11-27 09:26:29 +01:00 • committed by maia
commit ba0df0ec82
3 changed files with 60 additions and 172 deletions

View file

@ -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";

View file

@ -1,10 +1,9 @@
//! The log and metrics stores' gateway `auth_request` responder for agents.
//!
//! nginx sends it every `/select/logsql/` request (`swarm-victorialogs.nix`),
//! and every metrics read API request (`swarm-victoriametrics.nix`, as
//! `swarm-metrics-agent-auth`), whose `Authorization` is
//! `Bearer swarm-agent.<agent>.<secret>`. `--surface` says which store this
//! instance guards. It answers 200 when the secret is the one stored at
//! and every metrics read API request (`swarm-victoriametrics.nix`), whose
//! `Authorization` is `Bearer swarm-agent.<agent>.<secret>`. `--surface` says
//! which store this instance guards. It answers 200 when the secret is the one stored at
//! `swarm/agents/<agent>/queue` and the agent holds the permission for that
//! surface (`logs` or `metrics`), 401 when the secret does not verify, and 403
//! when it does but the permission is not held. A grant it cannot read is not
@ -16,10 +15,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
@ -29,8 +26,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};
@ -53,17 +48,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<PathBuf>,
/// TCP address to serve on, for a caller that is not on this host's filesystem.
#[arg(long)]
listen: Option<std::net::SocketAddr>,
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)]
@ -234,7 +223,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 401.
let probe = Arc::clone(&responder);
health.ready_while_checked(move || {
@ -243,59 +232,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<std::net::SocketAddr>,
) -> anyhow::Result<Bound> {
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<tokio::net::TcpListener> {
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<L>(
listener: L,
async fn serve(
listener: tokio::net::TcpListener,
app: axum::Router,
stop: impl Future<Output = ()> + 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
@ -560,10 +515,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;
@ -571,9 +526,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");
@ -595,7 +548,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, clap::Error> {
Args::try_parse_from(
@ -605,24 +557,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 {

View file

@ -7,11 +7,10 @@
//! status into a 500 for the caller. A store that does not answer is a 401
//! only until a value has been read; see below.
//!
//! 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
@ -30,8 +29,6 @@
//! both deny.
use std::future::Future;
use std::os::unix::fs::PermissionsExt as _;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
@ -62,17 +59,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<PathBuf>,
/// TCP address to serve on, for a caller that is not on this host's filesystem.
#[arg(long)]
listen: Option<std::net::SocketAddr>,
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)]
@ -320,7 +311,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 || {
@ -329,59 +320,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<std::net::SocketAddr>,
) -> anyhow::Result<Bound> {
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<tokio::net::TcpListener> {
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<L>(
listener: L,
async fn serve(
listener: tokio::net::TcpListener,
app: axum::Router,
stop: impl Future<Output = ()> + 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
@ -774,24 +731,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 {