Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/swarm-logs-auth/src/main.rs

728 lines
26 KiB
Rust

//! The log and metrics stores' gateway `auth_request` responder for agents.
//!
//! nginx sends it the `/select/logsql/` requests (`swarm-victorialogs.nix`)
//! and the metrics read API requests (`swarm-victoriametrics.nix`, as
//! `swarm-metrics-agent-auth`) whose `Authorization` is
//! `Bearer swarm-agent.<agent>.<secret>`, and only those: Grafana's bearer
//! goes to `swarm-metrics-auth`, and every other request to authelia.
//! `--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 grant is absent or lacks the permission. A store that
//! cannot answer, for the secret or the grant, is 503 and grants nothing. The
//! gateway hands the 503 on to the caller; `auth_request` itself turns any
//! status but 2xx, 401 and 403 into a 500.
//!
//! The permission is read from the leaf swarm-controller mirrors
//! (`swarm_secret_client::observability`), because this responder has no queue
//! access.
//!
//! 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.
//!
//! 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
//! stops verifying, or a permission that is revoked, is still honoured for up
//! to that long. Only an allow is remembered; a denial is looked up again.
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};
use anyhow::Context as _;
use axum::extract::State;
use axum::http::{HeaderMap, StatusCode, header};
use clap::{Parser, ValueEnum};
use swarm_agent_verify::agent_token::parse_agent_token;
use swarm_agent_verify::{CredentialSource, Verdict};
use swarm_secret_client::observability::{Grant, grant_path};
use verdicts::Verdicts;
/// How long one store lookup may take before the request is denied. Well
/// under nginx's 60s `proxy_read_timeout`, so a slow store answers 503
/// rather than a gateway timeout.
const LOOKUP_TIMEOUT: Duration = Duration::from_secs(5);
/// Most grants held at once. One live secret per agent, so this is a bound on
/// memory, not a size a swarm is expected to reach.
const VERDICT_CAP: usize = 4096;
#[derive(Parser)]
#[command(about = "auth_request responder: checks an agent's queue secret against the store")]
struct Args {
/// Unix socket to serve on.
#[arg(long)]
socket: PathBuf,
/// 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)]
health_addr: Option<std::net::SocketAddr>,
/// Cert-auth role this responder logs in to the store as.
#[arg(long, default_value = "swarm-logs-auth")]
store_cert_role: String,
/// Which store this instance guards, and so which permission it checks.
#[arg(long, value_enum)]
surface: Surface,
/// Seconds a verified bearer is granted again without a store lookup;
/// 0 looks up every request.
#[arg(long, default_value_t = 60)]
verdict_ttl: u64,
}
/// The store a gateway fronts.
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum Surface {
/// The log store, behind the `logs` permission.
Logs,
/// The metrics store, behind the `metrics` permission.
Metrics,
}
impl Surface {
fn allowed_by(self, grant: Grant) -> bool {
match self {
Self::Logs => grant.logs,
Self::Metrics => grant.metrics,
}
}
}
/// Where an agent's mirrored [`Grant`] comes from.
trait GrantSource {
/// The grant mirrored for `agent`, `None` when nothing is stored, or an
/// error when the store could not answer.
fn grant(&self, agent: &str) -> impl Future<Output = anyhow::Result<Option<Grant>>> + Send;
}
/// Where a request's store connection comes from: logged in once, then used
/// for both reads, the agent's credential and its grant.
trait Connector {
type Conn: CredentialSource + GrantSource;
/// Logs in to the store.
fn connect(&self) -> impl Future<Output = anyhow::Result<Self::Conn>> + Send;
}
impl Connector for swarm_agent_verify::Store {
type Conn = swarm_agent_verify::Connection;
async fn connect(&self) -> anyhow::Result<Self::Conn> {
swarm_agent_verify::Store::connect(self).await
}
}
impl GrantSource for swarm_agent_verify::Connection {
async fn grant(&self, agent: &str) -> anyhow::Result<Option<Grant>> {
self.read_optional(&grant_path(agent)?).await
}
}
struct Responder<S> {
source: S,
surface: Surface,
/// How long one store lookup may take before the request is denied.
lookup_timeout: Duration,
verdicts: Mutex<Verdicts>,
}
/// The answer for one subrequest's `Authorization` header, at `now`.
async fn decide(
responder: &Responder<impl Connector>,
authorization: Option<&str>,
now: Instant,
) -> StatusCode {
let Some(bearer) = authorization.and_then(|v| v.strip_prefix("Bearer ")) else {
tracing::warn!("no bearer token; denying");
return StatusCode::UNAUTHORIZED;
};
let token = match parse_agent_token(bearer) {
Some(Ok(token)) => token,
Some(Err(e)) => {
tracing::warn!(error = %e, "malformed agent token; denying");
return StatusCode::UNAUTHORIZED;
}
None => {
tracing::warn!("not an agent token; denying");
return StatusCode::UNAUTHORIZED;
}
};
if lock(&responder.verdicts).granted(bearer, now) {
tracing::debug!(agent = token.agent, "verified recently");
return StatusCode::OK;
}
// One login for both reads: the credential and the grant. A login that
// fails or is too slow is the store not answering, not a refusal.
let conn =
match tokio::time::timeout(responder.lookup_timeout, responder.source.connect()).await {
Ok(Ok(conn)) => conn,
Ok(Err(e)) => {
tracing::warn!(
agent = token.agent,
error = format!("{e:#}"),
"store login failed; denying"
);
return StatusCode::SERVICE_UNAVAILABLE;
}
Err(_) => {
tracing::warn!(agent = token.agent, "store login timed out; denying");
return StatusCode::SERVICE_UNAVAILABLE;
}
};
match swarm_agent_verify::check(&conn, &token, responder.lookup_timeout).await {
Verdict::Verified => {}
Verdict::Denied => return StatusCode::UNAUTHORIZED,
Verdict::Unavailable => return StatusCode::SERVICE_UNAVAILABLE,
}
match holds_permission(responder, &conn, token.agent).await {
Held::Yes => {}
Held::No => return StatusCode::FORBIDDEN,
Held::Unavailable => return StatusCode::SERVICE_UNAVAILABLE,
}
tracing::info!(agent = token.agent, surface = ?responder.surface, "verified");
lock(&responder.verdicts).grant(bearer, now);
StatusCode::OK
}
/// Whether an agent holds the permission for the surface.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Held {
Yes,
/// The store answered: the grant is absent, or lacks the permission.
No,
/// The grant could not be read or the read was too slow. Not held, but not
/// known to be missing either.
Unavailable,
}
/// Whether `agent` holds the permission for the surface.
async fn holds_permission<S>(
responder: &Responder<S>,
conn: &impl GrantSource,
agent: &str,
) -> Held {
let grant = match tokio::time::timeout(responder.lookup_timeout, conn.grant(agent)).await {
Ok(Ok(Some(grant))) => grant,
Ok(Ok(None)) => {
tracing::warn!(
agent,
"no permission grant is mirrored for this agent; denying"
);
return Held::No;
}
Ok(Err(e)) => {
tracing::warn!(
agent,
error = format!("{e:#}"),
"grant lookup failed; denying"
);
return Held::Unavailable;
}
Err(_) => {
tracing::warn!(agent, "grant lookup timed out; denying");
return Held::Unavailable;
}
};
if responder.surface.allowed_by(grant) {
Held::Yes
} else {
tracing::info!(agent, surface = ?responder.surface, "agent lacks the permission; denying");
Held::No
}
}
/// The cache holds no invariant a panicking holder could break mid-way, so a
/// poisoned lock is used as is.
fn lock(verdicts: &Mutex<Verdicts>) -> std::sync::MutexGuard<'_, Verdicts> {
verdicts
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
async fn handle(
State(responder): State<Arc<Responder<swarm_agent_verify::Store>>>,
headers: HeaderMap,
) -> StatusCode {
let authorization = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok());
decide(&responder, authorization, Instant::now()).await
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let stop = swarm_secret_client::shutdown_signal();
swarm_secret_client::install_crypto_provider();
hive_log::init();
let args = Args::parse();
let health = swarm_secret_client::health::Health::start(
swarm_secret_client::health::STALE_AFTER,
args.health_addr,
"SWARM_LOGS_AUTH_HEALTH_ADDR",
stop.clone(),
)
.await
.context("starting the health listener")?;
health.beat_on_runtime();
let settings = swarm_secret_client::client::Settings::from_env()
.context("reading the secret store's address and this responder's identity")?;
let responder = Arc::new(Responder {
source: swarm_agent_verify::Store::new(settings, args.store_cert_role),
surface: args.surface,
lookup_timeout: LOOKUP_TIMEOUT,
verdicts: Mutex::new(Verdicts::new(
Duration::from_secs(args.verdict_ttl),
VERDICT_CAP,
)),
});
// `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(&args.socket)
&& e.kind() != std::io::ErrorKind::NotFound
{
return Err(e)
.with_context(|| format!("clearing stale socket at {}", args.socket.display()));
}
let listener = tokio::net::UnixListener::bind(&args.socket)
.with_context(|| format!("binding {}", args.socket.display()))?;
// nginx is another user and `connect(2)` needs write. The directory is
// the access control, not this mode.
std::fs::set_permissions(&args.socket, std::fs::Permissions::from_mode(0o666))
.with_context(|| format!("chmod {}", args.socket.display()))?;
tracing::info!(socket = %args.socket.display(), "swarm-logs-auth listening");
// Ready means the store answers: with it down every request is a 503.
let probe = Arc::clone(&responder);
health.ready_while_checked(move || {
let probe = Arc::clone(&probe);
async move { probe.source.check_login().await }
});
let app = axum::Router::new().fallback(handle).with_state(responder);
serve(listener, app, stop).await
}
/// Answers on `listener` until `stop` resolves, then lets the requests in hand
/// finish, for at most the drain, and returns.
async fn serve(
listener: tokio::net::UnixListener,
app: axum::Router,
stop: impl Future<Output = ()> + Clone + Send + 'static,
) -> anyhow::Result<()> {
let serving = axum::serve(listener, app).with_graceful_shutdown(stop.clone());
swarm_secret_client::serve_bounded(stop, serving.into_future())
.await
.transpose()
.context("serving")?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use futures_util::FutureExt as _;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use swarm_secret_client::queue::AgentCredential;
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
/// What the mirrored grant leaf answers.
#[derive(Clone, Copy)]
enum Leaf {
Holds(Grant),
Absent,
Unreadable,
/// Accepts the read and never answers.
Hangs,
}
/// What the credential read answers, while atlas's credential is stored.
#[derive(Clone, Copy)]
enum Queue {
Answers,
Unreadable,
/// Accepts the read and never answers.
Hangs,
}
/// A store holding atlas's credential until `revoke` and her grant leaf,
/// counting lookups of each.
struct Atlas {
lookups: AtomicUsize,
revoked: AtomicBool,
queue: Mutex<Queue>,
leaf: Mutex<Leaf>,
grant_lookups: AtomicUsize,
/// Store logins, one per `connect`.
logins: AtomicUsize,
/// Whether a login is refused.
login_fails: AtomicBool,
}
impl Atlas {
fn with(leaf: Leaf) -> Self {
Self {
lookups: AtomicUsize::new(0),
revoked: AtomicBool::new(false),
queue: Mutex::new(Queue::Answers),
leaf: Mutex::new(leaf),
grant_lookups: AtomicUsize::new(0),
logins: AtomicUsize::new(0),
login_fails: AtomicBool::new(false),
}
}
/// Atlas holds `logs` and `metrics`, and the credential read is `queue`.
fn with_queue(queue: Queue) -> Self {
let store = Self::both();
*store.queue.lock().unwrap() = queue;
store
}
/// Atlas holds `logs` and `metrics`.
fn both() -> Self {
Self::with(Leaf::Holds(Grant {
logs: true,
metrics: true,
}))
}
fn revoke(&self) {
self.revoked.store(true, Ordering::SeqCst);
}
fn set_leaf(&self, leaf: Leaf) {
*self.leaf.lock().unwrap() = leaf;
}
fn lookups(&self) -> usize {
self.lookups.load(Ordering::SeqCst)
}
}
impl CredentialSource for &Atlas {
async fn lookup(&self, agent: &str) -> anyhow::Result<Option<AgentCredential>> {
self.lookups.fetch_add(1, Ordering::SeqCst);
let queue = *self.queue.lock().unwrap();
match queue {
Queue::Answers => {}
Queue::Unreadable => anyhow::bail!("store unreachable"),
Queue::Hangs => std::future::pending().await,
}
Ok(
(agent == "atlas" && !self.revoked.load(Ordering::SeqCst)).then(|| {
AgentCredential {
value: "Ab9_-zSECRET".to_owned(),
agent: "atlas".to_owned(),
minted_at: None,
}
}),
)
}
}
impl Connector for &Atlas {
type Conn = Self;
async fn connect(&self) -> anyhow::Result<Self> {
self.logins.fetch_add(1, Ordering::SeqCst);
if self.login_fails.load(Ordering::SeqCst) {
anyhow::bail!("store refused the certificate");
}
Ok(*self)
}
}
impl GrantSource for &Atlas {
async fn grant(&self, agent: &str) -> anyhow::Result<Option<Grant>> {
self.grant_lookups.fetch_add(1, Ordering::SeqCst);
let leaf = *self.leaf.lock().unwrap();
match (agent, leaf) {
("atlas", Leaf::Holds(grant)) => Ok(Some(grant)),
("atlas", Leaf::Unreadable) => anyhow::bail!("store unreachable"),
("atlas", Leaf::Hangs) => std::future::pending().await,
_ => Ok(None),
}
}
}
const TTL: Duration = Duration::from_mins(1);
const GOOD: &str = "Bearer swarm-agent.atlas.Ab9_-zSECRET";
const WRONG: &str = "Bearer swarm-agent.atlas.Ab9_-zSECREX";
fn responder(store: &Atlas, surface: Surface) -> Responder<&Atlas> {
Responder {
source: store,
surface,
lookup_timeout: Duration::from_millis(100),
verdicts: Mutex::new(Verdicts::new(TTL, 16)),
}
}
#[tokio::test]
async fn the_stored_secret_with_the_grant_is_200() {
let store = Atlas::both();
for surface in [Surface::Logs, Surface::Metrics] {
assert_eq!(
decide(&responder(&store, surface), Some(GOOD), Instant::now()).await,
StatusCode::OK,
"{surface:?}"
);
}
}
/// Each surface checks its own permission: a `logs` grant opens the log
/// store and not the metrics store, and the reverse.
#[tokio::test]
async fn each_surface_needs_its_own_permission() {
async fn at(store: &Atlas, surface: Surface) -> StatusCode {
decide(&responder(store, surface), Some(GOOD), Instant::now()).await
}
let logs_only = Atlas::with(Leaf::Holds(Grant {
logs: true,
metrics: false,
}));
let metrics_only = Atlas::with(Leaf::Holds(Grant {
logs: false,
metrics: true,
}));
assert_eq!(at(&logs_only, Surface::Logs).await, StatusCode::OK);
assert_eq!(
at(&logs_only, Surface::Metrics).await,
StatusCode::FORBIDDEN
);
assert_eq!(at(&metrics_only, Surface::Metrics).await, StatusCode::OK);
assert_eq!(
at(&metrics_only, Surface::Logs).await,
StatusCode::FORBIDDEN
);
}
/// No grant and an empty grant are a definite refusal.
#[tokio::test]
async fn without_a_grant_the_answer_is_403() {
for leaf in [Leaf::Absent, Leaf::Holds(Grant::default())] {
let store = Atlas::with(leaf);
assert_eq!(
decide(
&responder(&store, Surface::Logs),
Some(GOOD),
Instant::now()
)
.await,
StatusCode::FORBIDDEN
);
}
}
/// A grant the store fails or is too slow to read is not a refusal: 503,
/// and nothing is granted or remembered.
#[tokio::test]
async fn a_grant_that_cannot_be_read_is_503() {
for leaf in [Leaf::Unreadable, Leaf::Hangs] {
let store = Atlas::with(leaf);
let r = responder(&store, Surface::Logs);
assert_eq!(
decide(&r, Some(GOOD), Instant::now()).await,
StatusCode::SERVICE_UNAVAILABLE
);
store.set_leaf(Leaf::Absent);
assert_eq!(
decide(&r, Some(GOOD), Instant::now()).await,
StatusCode::FORBIDDEN,
"the outage was remembered"
);
}
}
/// A credential read that fails or is too slow is 503, not the 401 of a
/// secret that does not match.
#[tokio::test]
async fn a_credential_that_cannot_be_read_is_503() {
for queue in [Queue::Unreadable, Queue::Hangs] {
let store = Atlas::with_queue(queue);
assert_eq!(
decide(
&responder(&store, Surface::Logs),
Some(GOOD),
Instant::now()
)
.await,
StatusCode::SERVICE_UNAVAILABLE
);
assert_eq!(store.grant_lookups.load(Ordering::SeqCst), 0);
}
}
#[tokio::test]
async fn everything_else_is_401() {
let store = Atlas::both();
let r = responder(&store, Surface::Logs);
for authorization in [
None,
Some("swarm-agent.atlas.Ab9_-zSECRET"),
Some("Basic swarm-agent.atlas.Ab9_-zSECRET"),
Some(WRONG),
Some("Bearer swarm-agent.argus.Ab9_-zSECRET"),
Some("Bearer swarm-agent.atlas"),
Some("Bearer authelia_at_abc.def"),
] {
assert_eq!(
decide(&r, authorization, Instant::now()).await,
StatusCode::UNAUTHORIZED,
"{authorization:?}"
);
}
// A wrong secret is refused before the grant is read.
assert_eq!(store.grant_lookups.load(Ordering::SeqCst), 0);
}
/// A request that is not remembered logs in to the store once, and both
/// of its reads (the credential, the grant) go through that login: the
/// store's login is the costly part, and a second one per request doubles
/// the cost of every cold bearer. The remembered one logs in no more.
#[tokio::test]
async fn an_uncached_request_logs_in_once_for_both_reads() {
let store = Atlas::both();
let r = responder(&store, Surface::Logs);
let t0 = Instant::now();
assert_eq!(decide(&r, Some(GOOD), t0).await, StatusCode::OK);
assert_eq!(store.logins.load(Ordering::SeqCst), 1);
assert_eq!(store.lookups(), 1);
assert_eq!(store.grant_lookups.load(Ordering::SeqCst), 1);
assert_eq!(decide(&r, Some(GOOD), t0).await, StatusCode::OK);
assert_eq!(store.logins.load(Ordering::SeqCst), 1, "remembered");
}
/// A store that refuses the login answers nothing: the request is 503, and
/// neither read is tried.
#[tokio::test]
async fn a_refused_login_is_503_and_reads_nothing() {
let store = Atlas::both();
store.login_fails.store(true, Ordering::SeqCst);
let r = responder(&store, Surface::Logs);
assert_eq!(
decide(&r, Some(GOOD), Instant::now()).await,
StatusCode::SERVICE_UNAVAILABLE
);
assert_eq!(store.logins.load(Ordering::SeqCst), 1);
assert_eq!(store.lookups(), 0);
assert_eq!(store.grant_lookups.load(Ordering::SeqCst), 0);
}
/// An allow is reused within the TTL — a revocation the store already
/// holds, of the secret or of the permission, goes unseen — and checked
/// against the store again after it.
#[tokio::test]
async fn an_allow_spares_the_store_until_the_ttl() {
let store = Atlas::both();
let r = responder(&store, Surface::Logs);
let t0 = Instant::now();
assert_eq!(decide(&r, Some(GOOD), t0).await, StatusCode::OK);
store.revoke();
store.set_leaf(Leaf::Holds(Grant::default()));
let within = t0 + Duration::from_secs(59);
assert_eq!(decide(&r, Some(GOOD), within).await, StatusCode::OK);
assert_eq!(store.lookups(), 1);
assert_eq!(
decide(&r, Some(GOOD), t0 + TTL).await,
StatusCode::UNAUTHORIZED
);
assert_eq!(store.lookups(), 2);
}
/// A revoked permission is denied once the allow expires; a denial is not
/// remembered, so a permission granted later is honoured at once.
#[tokio::test]
async fn a_revoked_or_added_permission_takes_effect_by_the_ttl() {
let store = Atlas::both();
let r = responder(&store, Surface::Logs);
let t0 = Instant::now();
assert_eq!(decide(&r, Some(GOOD), t0).await, StatusCode::OK);
store.set_leaf(Leaf::Holds(Grant::default()));
assert_eq!(
decide(&r, Some(GOOD), t0 + TTL).await,
StatusCode::FORBIDDEN
);
assert_eq!(
decide(&r, Some(GOOD), t0 + TTL).await,
StatusCode::FORBIDDEN
);
store.set_leaf(Leaf::Holds(Grant {
logs: true,
metrics: false,
}));
assert_eq!(decide(&r, Some(GOOD), t0 + TTL).await, StatusCode::OK);
}
#[tokio::test]
async fn a_denial_is_looked_up_every_time() {
let store = Atlas::both();
let r = responder(&store, Surface::Logs);
let t0 = Instant::now();
for _ in 0..3 {
assert_eq!(decide(&r, Some(WRONG), t0).await, StatusCode::UNAUTHORIZED);
}
assert_eq!(store.lookups(), 3);
}
/// A request that is being answered when the stop arrives is still
/// answered, and `serve` returns only afterwards.
#[tokio::test]
async fn a_request_in_flight_at_the_stop_is_answered_before_serve_returns() {
let started = Arc::new(tokio::sync::Notify::new());
let release = Arc::new(tokio::sync::Notify::new());
let app = {
let (started, release) = (Arc::clone(&started), Arc::clone(&release));
axum::Router::new().fallback(move || {
let (started, release) = (Arc::clone(&started), Arc::clone(&release));
async move {
started.notify_one();
release.notified().await;
"answered"
}
})
};
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 (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();
let stop = async move {
let _ = stop_rx.await;
}
.shared();
let mut serving = tokio::spawn(serve(listener, app, stop));
let mut conn = tokio::net::UnixStream::connect(&socket)
.await
.expect("connect");
conn.write_all(b"GET / HTTP/1.1\r\nhost: x\r\nconnection: close\r\n\r\n")
.await
.expect("send");
started.notified().await;
stop_tx.send(()).expect("stop");
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(
!serving.is_finished(),
"serve returned with a request in flight"
);
release.notify_one();
let mut reply = String::new();
conn.read_to_string(&mut reply).await.expect("reply");
assert!(reply.starts_with("HTTP/1.1 200"), "{reply}");
assert!(reply.ends_with("answered"), "{reply}");
let finished = tokio::time::timeout(Duration::from_secs(5), &mut serving)
.await
.expect("serve returns once the request is answered");
finished.expect("task").expect("serve is Ok");
let _ = std::fs::remove_file(&socket);
}
}