feat(#3089): add swarmctl and a user-add verb for the swarm's SSO
The swarm-authelia module states that its users database is written by swarm-controller, but nothing ever granted the means. This adds the tool that does it. swarmctl runs as root on the controller's host and acts directly. The rootless alternative was examined and does not work: relocating the users file into a directory the controller owns only turns a write problem into a read problem, because authelia must then reach across the same boundary in the other direction. Making that read work needs either a hand-pinned gid or world-readable password hashes. The user store is two files, one authoritative: users.json is canonical, users.yml is a rendered artifact. That split is what lets the crate work without a YAML parser -- the workspace has none, and adding one costs a crates.io fetch, a lock update and a vendor hash for a schema we fully control and only ever emit. Passwords are generated by authelia rather than passed to it: argv is world-readable, so a password on a command line is readable by any local process for the lifetime of the call. The three derived facts swarmctl needs about the authelia container -- machine, unit and the host-side users path -- become readOnly options on the authelia module rather than literals repeated at the call site.
This commit is contained in:
parent
3a69ad4256
commit
9e44efa01f
11 changed files with 995 additions and 1 deletions
313
swarmctl/src/users.rs
Normal file
313
swarmctl/src/users.rs
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
//! The swarm's SSO user store, and the authelia users database rendered
|
||||
//! from it.
|
||||
//!
|
||||
//! **Two files, and only one of them is authoritative.** `users.json` is
|
||||
//! ours and canonical; `users.yml` is a rendered artifact for authelia,
|
||||
//! written and never read back.
|
||||
//!
|
||||
//! That split is not a preference, it is what lets this crate exist
|
||||
//! without a YAML parser: the workspace has none, and adding one costs a
|
||||
//! crates.io fetch, a lock update and a vendor hash — for a schema we
|
||||
//! fully control and only ever emit. Rendering in one direction needs no
|
||||
//! parser at all.
|
||||
//!
|
||||
//! The tempting shortcut — *"JSON is a subset of YAML, so just write JSON
|
||||
//! into the `.yml` and read it back with `serde_json`"* — is rejected on
|
||||
//! purpose. authelia **refuses to start** on a users file it cannot
|
||||
//! parse, so it fronts the whole SSO provider's boot, and "go-yaml
|
||||
//! almost certainly accepts flow style" is not a claim worth betting that
|
||||
//! on without running it. Block style is what upstream's own examples
|
||||
//! show.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What the swarm-authelia module's first-boot unit writes into
|
||||
/// `users.yml` when there is no database yet.
|
||||
///
|
||||
/// Matched (after trimming) so a first `user add` can take the file over
|
||||
/// without a flag, while anything *else* already in place is treated as
|
||||
/// content somebody meant to be there. Overwriting a live SSO user
|
||||
/// database because a canonical store happened to be missing is the one
|
||||
/// unrecoverable mistake available here.
|
||||
pub const SEED_USERS_FILE: &str = "users: {}";
|
||||
|
||||
/// The canonical store, serialised as JSON.
|
||||
///
|
||||
/// `BTreeMap` rather than `HashMap` so the rendered YAML is stable
|
||||
/// between runs: a diffable artifact is worth more than the ordering
|
||||
/// being meaningless, and a random-order rewrite makes every change look
|
||||
/// like a whole-file change.
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
pub struct UserStore {
|
||||
pub users: BTreeMap<String, User>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct User {
|
||||
pub displayname: String,
|
||||
/// The argon2 **digest** (`$argon2id$v=19$...`), never a plaintext
|
||||
/// password. Nothing in this crate stores or logs a plaintext: the
|
||||
/// one that exists is printed to the operator once and dropped.
|
||||
pub password: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub email: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub groups: Vec<String>,
|
||||
}
|
||||
|
||||
/// Usernames are map **keys** in a YAML document, and they also reach
|
||||
/// logs, session cookies and access-control rules. Keeping them to a
|
||||
/// conservative ASCII set means the emitter never has to reason about a
|
||||
/// key that needs quoting, and an authelia-side surprise can't be
|
||||
/// something we handed it.
|
||||
///
|
||||
/// Deliberately tighter than authelia allows. Loosening later is a
|
||||
/// one-line change; discovering that a name broke an access-control rule
|
||||
/// in production is not.
|
||||
pub fn validate_username(name: &str) -> Result<()> {
|
||||
if name.is_empty() || name.len() > 64 {
|
||||
bail!("username must be 1..=64 characters, got {}", name.len());
|
||||
}
|
||||
if !name.starts_with(|c: char| c.is_ascii_alphanumeric()) {
|
||||
bail!("username must start with an ASCII letter or digit: {name:?}");
|
||||
}
|
||||
if let Some(bad) = name
|
||||
.chars()
|
||||
.find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')))
|
||||
{
|
||||
bail!("username may only contain [A-Za-z0-9._-], found {bad:?} in {name:?}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reject control characters in free text rather than escaping them.
|
||||
///
|
||||
/// The emitter below could encode them, but a display name or email
|
||||
/// carrying a control character is a bug or an injection attempt in every
|
||||
/// real case, and refusing is both simpler to reason about and impossible
|
||||
/// to get subtly wrong.
|
||||
fn reject_control_chars(field: &str, value: &str) -> Result<()> {
|
||||
if let Some(c) = value.chars().find(|c| c.is_control()) {
|
||||
bail!(
|
||||
"{field} contains control character U+{:04X}; refusing to write it",
|
||||
c as u32
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A double-quoted YAML scalar.
|
||||
///
|
||||
/// Everything is quoted, including values that would be fine bare: the
|
||||
/// argon2 digest alone contains `$`, `=`, `,` and `/`, and deciding
|
||||
/// per-value which of those need quoting is exactly the kind of judgement
|
||||
/// that is right until one day it isn't. Control characters are excluded
|
||||
/// upstream by [`reject_control_chars`], so `"` and `\` are the complete
|
||||
/// escape set.
|
||||
fn quote(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len() + 2);
|
||||
out.push('"');
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
/// Render the store as authelia's block-style YAML users database.
|
||||
///
|
||||
/// Fallible because it re-runs validation over every value it is about to
|
||||
/// emit. That is not belt-and-braces: it makes "no control character ever
|
||||
/// reaches the file" a property of the *only* path that writes it, rather
|
||||
/// than a rule the call sites have to remember.
|
||||
pub fn render_yaml(store: &UserStore) -> Result<String> {
|
||||
if store.users.is_empty() {
|
||||
return Ok(format!("{SEED_USERS_FILE}\n"));
|
||||
}
|
||||
|
||||
let mut out = String::from("users:\n");
|
||||
for (name, user) in &store.users {
|
||||
validate_username(name)?;
|
||||
reject_control_chars("displayname", &user.displayname)?;
|
||||
reject_control_chars("password digest", &user.password)?;
|
||||
|
||||
writeln!(out, " {name}:")?;
|
||||
writeln!(out, " displayname: {}", quote(&user.displayname))?;
|
||||
writeln!(out, " password: {}", quote(&user.password))?;
|
||||
if let Some(email) = &user.email {
|
||||
reject_control_chars("email", email)?;
|
||||
writeln!(out, " email: {}", quote(email))?;
|
||||
}
|
||||
if !user.groups.is_empty() {
|
||||
writeln!(out, " groups:")?;
|
||||
for group in &user.groups {
|
||||
reject_control_chars("group", group)?;
|
||||
writeln!(out, " - {}", quote(group))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Whether an existing `users.yml` is safe to take over when no canonical
|
||||
/// store exists yet — i.e. it is the untouched first-boot seed.
|
||||
///
|
||||
/// Empty counts: a zero-byte file holds no users to destroy, and authelia
|
||||
/// would refuse to start on it anyway, so treating it as untouched turns
|
||||
/// a dead deployment into a working one instead of demanding a flag.
|
||||
pub fn is_untouched_seed(contents: &str) -> bool {
|
||||
let trimmed = contents.trim();
|
||||
trimmed.is_empty() || trimmed == SEED_USERS_FILE
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn user(password: &str) -> User {
|
||||
User {
|
||||
displayname: "Test User".to_owned(),
|
||||
password: password.to_owned(),
|
||||
email: None,
|
||||
groups: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_store_renders_the_seed_document() {
|
||||
let out = render_yaml(&UserStore::default()).expect("empty store renders");
|
||||
assert_eq!(out, "users: {}\n");
|
||||
assert!(
|
||||
is_untouched_seed(&out),
|
||||
"the empty rendering must itself read as the seed, or removing the \
|
||||
last user would produce a file the next run refuses to take over"
|
||||
);
|
||||
}
|
||||
|
||||
/// The digest is the value most likely to break a naive emitter: it
|
||||
/// carries `$`, `=`, `,` and `/`, and `,` in particular terminates a
|
||||
/// YAML flow scalar.
|
||||
#[test]
|
||||
fn an_argon2_digest_survives_quoting() {
|
||||
let digest = "$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHQ$aGFzaA+/w==";
|
||||
let mut store = UserStore::default();
|
||||
store.users.insert("mara".to_owned(), user(digest));
|
||||
|
||||
let out = render_yaml(&store).expect("renders");
|
||||
assert!(
|
||||
out.contains(&format!("password: \"{digest}\"")),
|
||||
"digest must be emitted verbatim inside double quotes, got:\n{out}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quoting_escapes_backslash_and_quote() {
|
||||
assert_eq!(quote(r#"a"b\c"#), r#""a\"b\\c""#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optional_fields_are_omitted_rather_than_emitted_empty() {
|
||||
let mut store = UserStore::default();
|
||||
store.users.insert("mara".to_owned(), user("$argon2id$x"));
|
||||
|
||||
let out = render_yaml(&store).expect("renders");
|
||||
assert!(
|
||||
!out.contains("email"),
|
||||
"absent email must not appear:\n{out}"
|
||||
);
|
||||
assert!(
|
||||
!out.contains("groups"),
|
||||
"an empty group list must not appear:\n{out}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_render_as_a_block_sequence() {
|
||||
let mut u = user("$argon2id$x");
|
||||
u.email = Some("mara@example.com".to_owned());
|
||||
u.groups = vec!["admins".to_owned(), "operators".to_owned()];
|
||||
let mut store = UserStore::default();
|
||||
store.users.insert("mara".to_owned(), u);
|
||||
|
||||
let out = render_yaml(&store).expect("renders");
|
||||
assert_eq!(
|
||||
out,
|
||||
concat!(
|
||||
"users:\n",
|
||||
" mara:\n",
|
||||
" displayname: \"Test User\"\n",
|
||||
" password: \"$argon2id$x\"\n",
|
||||
" email: \"mara@example.com\"\n",
|
||||
" groups:\n",
|
||||
" - \"admins\"\n",
|
||||
" - \"operators\"\n",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/// Ordering is a property of the artifact, not an accident: an
|
||||
/// unordered rewrite makes every one-user change look like a
|
||||
/// whole-file change to anyone diffing it.
|
||||
#[test]
|
||||
fn users_render_in_a_stable_order() {
|
||||
let mut store = UserStore::default();
|
||||
for name in ["zoe", "atlas", "mara"] {
|
||||
store.users.insert(name.to_owned(), user("$argon2id$x"));
|
||||
}
|
||||
let out = render_yaml(&store).expect("renders");
|
||||
let order: Vec<&str> = out
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix(" ").and_then(|l| l.strip_suffix(':')))
|
||||
.collect();
|
||||
assert_eq!(order, ["atlas", "mara", "zoe"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_character_is_refused_not_escaped() {
|
||||
let mut u = user("$argon2id$x");
|
||||
u.displayname = "bad\nname".to_owned();
|
||||
let mut store = UserStore::default();
|
||||
store.users.insert("mara".to_owned(), u);
|
||||
|
||||
let err = render_yaml(&store).expect_err("a control character must not render");
|
||||
assert!(
|
||||
err.to_string().contains("control character"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usernames_outside_the_conservative_set_are_refused() {
|
||||
for bad in ["", "-leading", "has space", "quote\"d", "sla/sh", "üni"] {
|
||||
assert!(
|
||||
validate_username(bad).is_err(),
|
||||
"{bad:?} should have been rejected"
|
||||
);
|
||||
}
|
||||
for good in ["mara", "atlas", "svc-agent_1", "a.b"] {
|
||||
validate_username(good).unwrap_or_else(|e| panic!("{good:?} rejected: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The seed check gates an irreversible overwrite, so it has to be
|
||||
/// tolerant of trailing whitespace and intolerant of everything else.
|
||||
#[test]
|
||||
fn only_the_untouched_seed_reads_as_takeable() {
|
||||
assert!(is_untouched_seed("users: {}"));
|
||||
assert!(is_untouched_seed("users: {}\n"));
|
||||
assert!(!is_untouched_seed("users:\n mara:\n"));
|
||||
assert!(
|
||||
is_untouched_seed(""),
|
||||
"a zero-byte file has no users to lose, and authelia will not start \
|
||||
on it — refusing here would strand the deployment"
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue