//! `swarm-authelia-bridge` — the only thing allowed to write //! `swarm-authelia`'s users database. //! //! Runs **inside the `swarm-authelia` container**, as //! `User = "authelia-swarm";` (the literal name //! `swarm-authelia.nix`'s `unitName` already derives) — the same user //! authelia's own instance runs as, and therefore the file's actual //! owner. That is the whole answer to "how does an unprivileged //! `swarm-controller` write a file it doesn't own": it doesn't — this //! process does, sidestepping the uid boundary instead of bridging it //! with root/`CAP_CHOWN`/a shared group (all examined and rejected — see //! `swarmctl/README.md`'s own identical analysis of this same file). //! //! Network-facing, not unix-socket-only: `swarm-authelia`'s container //! shares the host netns (`privateNetwork = false`, same as `hive-forge`/ //! `hive-matrix`), so one listener serves a co-located `swarm-controller` //! (loopback) and a split-host one (bind wider, firewall it) with the //! same code path — no separate transport for the cross-host case. //! Bearer-authenticated via authelia's own OIDC token introspection (RFC //! 7662) against `swarm-controller`'s **existing** machine-client //! identity (already minted for the queue connection) — no new //! credential to mint or deliver, and always local/fast to verify since //! this process runs right next to the authelia it asks. //! //! One endpoint, `POST /requests`, body = //! [`swarm_authelia_bridge_sock::BridgeRequest`] verbatim — one variant //! today (`EnsureAgentIdentity`, idempotently ensure an agent exists as //! an authelia subject). Not a wholesale-replace-the-file API — this //! process owns rendering `users.yml` internally; see `store` module. mod introspect; mod store; use std::sync::Arc; use anyhow::{Context, Result, bail}; use axum::extract::State; use axum::http::{HeaderMap, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::routing::post; use axum::{Json, Router}; use swarm_authelia_bridge_sock::{BridgeRequest, BridgeResponse}; /// Where the introspecting bearer token is authenticated *to* — this /// bridge's own authelia machine client, distinct from /// `swarm-controller`'s (the token being checked). Set by the nix module /// that provisions this bridge's own client alongside authelia. struct Config { bind: String, users_file: std::path::PathBuf, authelia_bin: std::path::PathBuf, introspection_url: String, client_id: String, client_secret: String, } impl Config { fn from_env() -> Result { Ok(Self { bind: env_var("SWARM_AUTHELIA_BRIDGE_BIND")?, users_file: env_var("SWARM_AUTHELIA_BRIDGE_USERS_FILE")?.into(), authelia_bin: env_var("SWARM_AUTHELIA_BRIDGE_AUTHELIA_BIN")?.into(), introspection_url: env_var("SWARM_AUTHELIA_BRIDGE_INTROSPECTION_URL")?, client_id: env_var("SWARM_AUTHELIA_BRIDGE_CLIENT_ID")?, client_secret: read_secret_file(&env_var("SWARM_AUTHELIA_BRIDGE_CLIENT_SECRET_FILE")?)?, }) } } fn env_var(name: &str) -> Result { std::env::var(name).with_context(|| format!("{name} is unset")) } fn read_secret_file(path: &str) -> Result { let raw = std::fs::read_to_string(path).with_context(|| format!("reading secret file {path}"))?; let trimmed = raw.trim(); if trimmed.is_empty() { bail!("secret file {path} is empty"); } Ok(trimmed.to_owned()) } struct AppState { config: Config, http: reqwest::Client, /// Serializes `handle`'s load → insert → publish sequence. Without this, /// two `EnsureAgentIdentity` requests landing close together (real: the /// controller's job worker claims and spawns nodes without waiting for /// each to finish, and `SwarmResourceKind` declares no resource dep /// between two `CreateIdentity` jobs, so they run concurrently) both /// `load_store` the same snapshot, both insert their own agent, and /// whichever `publish`es second silently drops the first agent's entry — /// the store is a plain file, not a database with its own concurrency /// control. `tokio::sync::Mutex`, not `std`'s: held across the `.await`s /// in `generate_password` and `publish`. write_lock: tokio::sync::Mutex<()>, } #[tokio::main] async fn main() -> Result<()> { tracing_subscriber::fmt() .with_env_filter( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), ) .init(); let config = Config::from_env()?; let bind = config.bind.clone(); let state = Arc::new(AppState { config, http: reqwest::Client::new(), write_lock: tokio::sync::Mutex::new(()), }); let app = Router::new() .route("/requests", post(handle_request)) .with_state(state); let listener = tokio::net::TcpListener::bind(&bind) .await .with_context(|| format!("binding {bind}"))?; tracing::info!(%bind, "swarm-authelia-bridge listening"); axum::serve(listener, app) .await .context("serving swarm-authelia-bridge") } /// The single endpoint — body is the wire-crate's [`BridgeRequest`] /// verbatim (JSON), not a per-operation REST route. One variant today, /// but this is what keeps a second operation from needing a new route + /// a new extractor shape: it just becomes a new match arm below. async fn handle_request( State(state): State>, headers: HeaderMap, Json(req): Json, ) -> Response { if let Err(resp) = authorize(&state, &headers).await { return resp; } let BridgeRequest::EnsureAgentIdentity { name } = req; match handle(&state, name).await { Ok(body) => (StatusCode::OK, Json(body)).into_response(), Err(e) => { let detail = format!("{e:#}"); tracing::warn!(error = %detail, "ensure_identity failed"); ( StatusCode::INTERNAL_SERVER_ERROR, Json(BridgeResponse::Error { message: detail }), ) .into_response() } } } /// Extract + introspect the bearer token. `Err` carries the response to /// return outright — kept separate from `handle`'s error path, which is /// "the op itself failed," a different case from "the caller was never let /// in." /// /// Anything short of an active token is refused; **which status** depends /// on whose credential failed, see [`Refusal`]. async fn authorize(state: &AppState, headers: &HeaderMap) -> Result<(), Response> { let Some(auth) = headers.get(axum::http::header::AUTHORIZATION) else { return Err(refuse(Refusal::Caller)); }; let Ok(auth) = auth.to_str() else { return Err(refuse(Refusal::Caller)); }; let Some(token) = auth.strip_prefix("Bearer ") else { return Err(refuse(Refusal::Caller)); }; let verdict = introspect::introspect( &state.http, &state.config.introspection_url, &state.config.client_id, &state.config.client_secret, token, ) .await; classify(verdict).map_err(refuse) } /// The admission decision, and the only place that makes it. /// /// Fail-closed: `Ok(())` is reachable from exactly one variant. Split out /// of [`authorize`] so the rule is testable without an authelia — and it is /// the *real* rule, not a restatement of it, because this is the function /// the request path calls. fn classify(verdict: introspect::Verdict) -> Result<(), Refusal> { match verdict { introspect::Verdict::Active => Ok(()), introspect::Verdict::Inactive => Err(Refusal::Caller), introspect::Verdict::Unavailable => Err(Refusal::Bridge), } } /// Whose credential was at fault when a request was refused. /// /// The distinction is the whole point: these used to be one 401, so a /// caller whose token was fine was told its token was invalid whenever /// *this bridge* could not authenticate itself to authelia. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Refusal { /// No token, an unusable header, or a token authelia rejected. Caller, /// This bridge could not get an answer out of authelia at all, so the /// request was never evaluated. Bridge, } impl Refusal { /// `401` for the caller; `503` for us. /// /// 401 would be wrong for [`Refusal::Bridge`] under RFC 7235 — nothing /// about the caller's credential was determined — and it is also the /// least useful thing to say, because a client that believes its token /// is bad will go and mint a new one, which cannot help. /// /// 503 rather than 500 because the overwhelmingly common cause is /// transient by construction: this bridge's own secret is minted on /// authelia's first boot and delivered by a separate unit, so the /// window where it is absent closes on its own. A client retrying is /// doing the right thing. fn status(self) -> StatusCode { match self { Refusal::Caller => StatusCode::UNAUTHORIZED, Refusal::Bridge => StatusCode::SERVICE_UNAVAILABLE, } } /// Deliberately coarse for [`Refusal::Caller`]: an unauthenticated /// caller learns that it was refused, never which of the four ways. /// The `Bridge` message says only that validation could not happen — /// no status code, no upstream detail, nothing about the secret. The /// discriminating detail is in this bridge's journal, where it belongs. fn message(self) -> &'static str { match self { Refusal::Caller => "missing or invalid bearer token", Refusal::Bridge => "cannot validate credentials", } } } fn refuse(refusal: Refusal) -> Response { ( refusal.status(), Json(BridgeResponse::Error { message: refusal.message().to_owned(), }), ) .into_response() } async fn handle(state: &AppState, name: String) -> Result { store::validate_username(&name)?; // After the charset check and before anything touches the store: a // reserved name is refused on its own terms, not as a side effect of a // collision with whatever happens to be in the file today. store::reject_reserved_name(&name)?; let cfg = &state.config; // Held across the whole load → insert → publish sequence, not just the // write — two concurrent `EnsureAgentIdentity` calls must not both read // the same on-disk snapshot before either publishes. See the field's // doc comment on `AppState::write_lock` for why this is reachable in // practice, not just theoretically. let _write_guard = state.write_lock.lock().await; let mut user_store = store::load_store(&cfg.users_file)?; if user_store.users.contains_key(&name) { return Ok(BridgeResponse::AlreadyExists); } let generated = generate_password(&cfg.authelia_bin).await?; user_store.users.insert( name.clone(), store::User { displayname: name.clone(), password: generated, email: None, groups: Vec::new(), extra: std::collections::BTreeMap::new(), }, ); store::publish(&cfg.users_file, &mut user_store)?; tracing::info!(agent = %name, "created authelia identity"); Ok(BridgeResponse::Created) } /// Mint a password digest via the **configured** authelia — the argon2 /// parameters baked into a hash have to match the verifier's, same /// reasoning `swarmctl::generate_password` documents (this is /// deliberately a fresh async port of that function, not a shared one — /// `swarmctl` is a separate binary crate with no lib target). /// /// `--random`, not `--password `: `/proc//cmdline` is /// world-readable, so a password on argv would be readable by any local /// process for the call's lifetime. Only the digest is kept — the /// plaintext is generated and immediately discarded, since nothing reads /// it back today (still an open question what an agent's login actually /// uses this for). async fn generate_password(bin: &std::path::Path) -> Result { let out = tokio::process::Command::new(bin) .args(["crypto", "hash", "generate", "argon2", "--random"]) .output() .await .with_context(|| format!("running {}", bin.display()))?; if !out.status.success() { bail!( "{} failed ({}): {}", bin.display(), out.status, String::from_utf8_lossy(&out.stderr).trim() ); } let stdout = String::from_utf8(out.stdout).context("authelia printed non-UTF-8 output")?; stdout .lines() .find_map(|line| line.trim().strip_prefix("Digest:")) .map(|v| v.trim().to_owned()) .filter(|v| !v.is_empty()) .with_context(|| { format!( "could not parse {}'s output: missing 'Digest:'", bin.display() ) }) } #[cfg(test)] mod tests { use super::{Refusal, StatusCode, classify, introspect::Verdict}; /// Fail-closed, asserted per variant rather than as one negation: /// splitting blame out of a single denial is exactly the change that /// could have widened admission, so each refusing variant is named on /// its own line. #[test] fn only_an_active_token_is_admitted() { assert_eq!(classify(Verdict::Active), Ok(())); assert_eq!( classify(Verdict::Inactive), Err(Refusal::Caller), "authelia evaluated the token and said no" ); assert_eq!( classify(Verdict::Unavailable), Err(Refusal::Bridge), "a bridge that cannot ask must not admit — this variant reports a \ different fault, it is not a softer denial" ); } /// The whole point of the split, asserted on the value rather than /// on message text — the previous code picked its status by matching on /// a log message's wording, which is what let the two collapse. #[test] fn a_refusal_names_whose_credential_failed() { assert_eq!( Refusal::Caller.status(), StatusCode::UNAUTHORIZED, "the caller's token is the problem; retrying with the same one will not help" ); assert_eq!( Refusal::Bridge.status(), StatusCode::SERVICE_UNAVAILABLE, "the request was never evaluated — 401 here accuses the caller of our fault" ); assert_ne!( Refusal::Caller.status(), Refusal::Bridge.status(), "collapsing these back into one status is the bug this exists to prevent" ); } /// No response body may leak which of the four caller-side causes /// applied, nor anything about this bridge's own credential. #[test] fn refusal_messages_say_nothing_useful_to_an_attacker() { for refusal in [Refusal::Caller, Refusal::Bridge] { let message = refusal.message(); for leak in ["secret", "client_id", "authelia", "http", "status"] { assert!( !message.to_ascii_lowercase().contains(leak), "{refusal:?} message leaks {leak:?}: {message:?}" ); } } } }