diff --git a/docs/4-implementation/swarm/readiness.md b/docs/4-implementation/swarm/readiness.md index 6b4f9ebd9..a269ef743 100644 --- a/docs/4-implementation/swarm/readiness.md +++ b/docs/4-implementation/swarm/readiness.md @@ -24,7 +24,7 @@ ends when the last clone of the check drops. | ----------------------- | ------------------------------------------------------------------------------------- | | `swarm-logs-auth` | a login to the store under its own certificate | | `swarm-metrics-auth` | the read of the stored bearer, the lookup it makes anyway | -| `swarm-authelia-bridge` | the users file loads (the bridge has no secret store) | +| `swarm-authelia-bridge` | the users file loads and renders again (no secret store) | | `swarm-controller` | a login to the store; the probe reads the queue connection live, since it's in memory | The controller starts its check once, when it starts serving diff --git a/docs/4-implementation/swarm/sso.md b/docs/4-implementation/swarm/sso.md index fb9ac5cf3..37e4b3322 100644 --- a/docs/4-implementation/swarm/sso.md +++ b/docs/4-implementation/swarm/sso.md @@ -231,6 +231,8 @@ publishes it as It answers only swarm-controller's OIDC client (`swarm.controller.queueClientId`) and refuses every other token `403`. +A write checks the name it creates or changes, not the whole file. A name someone added by hand with characters outside the roster's set stays in the file, and each write logs a warning naming it. The bridge counts as not ready only while the file holds a value it can't write back, such as a control character. + On first boot this module seeds the users database with a placeholder subject marked `disabled`, so authelia has a non-empty store to start against before any real account exists (`swarm-authelia.nix:873`). Authelia's session, storage and other keys live in the swarm secret store; the container copies them into place at start, seeded from the files an earlier release generated there, and generates them itself only where it has no store identity. Nothing rotates them automatically; replacing one invalidates data already written (sessions, the encrypted store), so that's an operator action. diff --git a/swarm-authelia-bridge/src/main.rs b/swarm-authelia-bridge/src/main.rs index df0b86219..dc7e2050c 100644 --- a/swarm-authelia-bridge/src/main.rs +++ b/swarm-authelia-bridge/src/main.rs @@ -128,11 +128,15 @@ async fn main() -> Result<()> { let listener = bind_socket(&socket)?; tracing::info!(socket = %socket.display(), "swarm-authelia-bridge listening"); - // Ready means the users file loads: without it every request fails. + // Ready means the users file loads and renders: without it every request fails. let users_file = state.config.users_file.clone(); health.ready_while_checked(move || { let users_file = users_file.clone(); - async move { store::load_store(&users_file).map(drop) } + async move { + // Writable, not just parseable: a user the bridge cannot render + // makes every request fail. + store::check_writable(&store::load_store(&users_file)?) + } }); serve(listener, app, stop).await } @@ -848,6 +852,52 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// One hand-added user outside the username charset must not stop an + /// agent being created: the request writes its own name and leaves the + /// human's entry as it found it. + #[tokio::test] + async fn a_hand_added_user_outside_the_charset_does_not_block_a_create() { + let mut config = config_with_one_operator(); + let dir = config.users_file.parent().unwrap().to_owned(); + let authelia = dir.join("authelia"); + write_executable( + &authelia, + "#!/bin/sh\nprintf 'Random Password: pw\\nDigest: $argon2id$x\\n'\n", + ); + config.authelia_bin = authelia; + let mut users = crate::store::load_store(&config.users_file).unwrap(); + users.users.insert( + "first.last@corp".to_owned(), + crate::store::User { + displayname: "first last".to_owned(), + password: "$argon2id$human".to_owned(), + email: None, + groups: vec!["admins".to_owned()], + extra: std::collections::BTreeMap::new(), + }, + ); + std::fs::write( + &config.users_file, + crate::store::render_yaml(&users).unwrap(), + ) + .unwrap(); + let write_lock = tokio::sync::Mutex::new(()); + + handle(&config, &write_lock, "atlas".to_owned()) + .await + .expect("the create goes through"); + + let after = crate::store::load_store(&config.users_file).unwrap(); + assert!(after.users.contains_key("atlas")); + assert_eq!(after.users["first.last@corp"].groups, ["admins"]); + assert_eq!(after.users["first.last@corp"].password, "$argon2id$human"); + // The name this request writes is still held to the charset. + handle(&config, &write_lock, "has space".to_owned()) + .await + .expect_err("the written name is validated"); + let _ = std::fs::remove_dir_all(&dir); + } + /// `handle` waits for the `flock` `swarmctl` takes, not only for the /// in-process lock: it is held here while `handle` runs with a lock of /// its own that nothing contends. diff --git a/swarm-authelia-bridge/src/store.rs b/swarm-authelia-bridge/src/store.rs index 1d94bf405..a6972e2e3 100644 --- a/swarm-authelia-bridge/src/store.rs +++ b/swarm-authelia-bridge/src/store.rs @@ -199,9 +199,15 @@ pub fn render_yaml(store: &UserStore) -> Result { /// Everything [`render_yaml`] refuses to write. Separate so the rule can be /// tested directly, and so a second writer can call it without going /// through serialisation. +/// +/// The username charset is **not** checked here: [`validate_username`] gates +/// the one name a request writes (`handle`), not every name in the file. The +/// file holds humans this bridge did not create, and authelia accepts names +/// the charset refuses (`first.last@corp`), so checking them all would make +/// one hand-added user refuse every later write. [`warn_outside_charset`] +/// names them instead. Same reason as [`reject_reserved_name`]. fn validate(store: &UserStore) -> Result<()> { - for (name, user) in &store.users { - validate_username(name)?; + for user in store.users.values() { reject_control_chars("displayname", &user.displayname)?; reject_control_chars("password digest", &user.password)?; if let Some(email) = &user.email { @@ -214,6 +220,40 @@ fn validate(store: &UserStore) -> Result<()> { Ok(()) } +/// Whether [`render_yaml`] would write `store`: the same check, without +/// serialising, for a readiness probe. A user it fails on (a control +/// character in a value) makes every write fail, so a bridge holding one is +/// not ready. +/// +/// # Errors +/// When a value in the store has a control character. +pub fn check_writable(store: &UserStore) -> Result<()> { + validate(store) +} + +/// The names in `store` that [`validate_username`] refuses: users added by +/// hand (a human with an `@` in the name, say), which a write passes through +/// unchanged. +pub fn names_outside_charset(store: &UserStore) -> Vec<&str> { + store + .users + .keys() + .map(String::as_str) + .filter(|name| validate_username(name).is_err()) + .collect() +} + +/// Log, at `warn`, each user [`names_outside_charset`] finds, so an operator +/// sees that the file holds a name the bridge would not have written. +fn warn_outside_charset(store: &UserStore) { + for name in names_outside_charset(store) { + tracing::warn!( + user = %name, + "the users file holds a name outside the bridge's charset; leaving it as it is" + ); + } +} + /// Load the users database, or start empty when it does not exist yet. /// /// ⚠️ **There is deliberately no overwrite guard here any more.** The old @@ -249,6 +289,7 @@ pub fn publish(users_file: &Path, store: &mut UserStore) -> Result<()> { // writes — the old version wrote the JSON store first so a crash // between them left something to repair from. That whole failure mode // belonged to having two files. + warn_outside_charset(store); let rendered = render_yaml(store)?; write_atomic(users_file, &rendered) } @@ -620,6 +661,44 @@ some_future_top_level_key: 7 } } + /// A user added by hand with a name the charset refuses (`@`) must not + /// block a write of someone else: it is written back as it was, and named + /// in the check, which is a note and not a refusal. + #[test] + fn a_hand_added_name_outside_the_charset_passes_through_a_write() { + let dir = tempdir(); + let users_file = dir.join("users.yml"); + let mut store = UserStore::default(); + store + .users + .insert("first.last@corp".to_owned(), operator("$argon2id$human")); + store + .users + .insert("atlas".to_owned(), agent("$argon2id$agent")); + + assert_eq!(names_outside_charset(&store), ["first.last@corp"]); + check_writable(&store).expect("a charset-odd name does not make the file unwritable"); + publish(&users_file, &mut store).expect("the write goes through"); + + let back = load_store(&users_file).expect("reloads"); + assert_eq!(back.users["first.last@corp"].password, "$argon2id$human"); + assert_eq!(back.users["first.last@corp"].groups, ["admins"]); + assert_eq!(agent_names(&back), ["atlas"]); + fs::remove_dir_all(&dir).ok(); + } + + /// What does make the file unwritable is a control character in a value, + /// of any user: readiness has to say so, since every write would fail. + #[test] + fn a_user_the_bridge_cannot_render_makes_the_file_unwritable() { + let mut bad = operator("$argon2id$x"); + bad.displayname = "bad\nname".to_owned(); + let mut store = UserStore::default(); + store.users.insert("first.last@corp".to_owned(), bad); + let err = check_writable(&store).expect_err("must refuse"); + assert!(err.to_string().contains("control character"), "{err}"); + } + #[test] fn a_control_character_is_refused_not_escaped() { let mut u = user("$argon2id$x");