From d5f5ee21be51328acb539515ed76eda8194313ef Mon Sep 17 00:00:00 2001 From: maia Date: Mon, 30 Nov 2026 15:35:37 +0100 Subject: [PATCH] swarm-nats-auth: refuse a service client id that fits a hive or a second role --- docs/4-implementation/swarm/credentials.md | 10 ++ nix/host-modules/lib/client-id-clash.nix | 21 ++++ nix/host-modules/swarm-nats.nix | 34 ++++++ nix/module-eval/nats-authelia.nix | 55 +++++++++ swarm-nats-auth/src/main.rs | 27 ++++- swarm-nats-auth/src/policy.rs | 128 +++++++++++++++++++++ 6 files changed, 274 insertions(+), 1 deletion(-) create mode 100644 nix/host-modules/lib/client-id-clash.nix diff --git a/docs/4-implementation/swarm/credentials.md b/docs/4-implementation/swarm/credentials.md index 24844404b..1e856a29b 100644 --- a/docs/4-implementation/swarm/credentials.md +++ b/docs/4-implementation/swarm/credentials.md @@ -161,6 +161,16 @@ The signature and the sender key stay unchecked on purpose, for three reasons. The guard is the module-eval case `the callout account has exactly one member and no system account is configured` in `nix/module-eval/nats-authelia.nix`. An extra member of `AUTH` could subscribe to the subject and read every client's token, which no signature check would stop. Revisit this decision if that case changes: when `AUTH` gains a member, or the server gets a system account. +## Which role a queue client id gets + +The responder gives a client id the first role it fits: a hive if the id starts +with `--hive-client-prefix`, then the controller's reader role, then the review +classifier, builder, claude login, notify router and speech-to-text roles. An id +under two of them gets only the first one's grant, so the responder refuses to +start when a service role's id starts with the hive prefix or appears under two +roles, and the message names both. The module says the same at evaluation, with +an assertion naming the six ids, so a clash fails the build before a deploy. + ## Per-principal identities Bao matches a cert-auth role on the certificate's subject, so a certificate is an diff --git a/nix/host-modules/lib/client-id-clash.nix b/nix/host-modules/lib/client-id-clash.nix new file mode 100644 index 000000000..977393011 --- /dev/null +++ b/nix/host-modules/lib/client-id-clash.nix @@ -0,0 +1,21 @@ +# Whether a set of queue client ids would give one id the wrong grant. +# +# The queue's auth-callout responder matches a client id against the hive +# prefix first, then against each service role in turn, and the first match +# wins. So an id listed under two roles, or one under the hive prefix, silently +# gets another role's grant. The responder refuses to start on the same +# overlap (`Policy::checked`); `swarm-nats.nix` asserts it at evaluation. +# +# Pure function of the ids and the prefix, so a module-eval case can feed it +# a clash: the ids are read-only options, which no host config can set. +{ lib }: +{ + ids, + hivePrefix, +}: +let + # An id equal to the prefix alone names no hive (nothing follows it), as in + # the responder's own matcher. + underPrefix = id: lib.hasPrefix hivePrefix id && id != hivePrefix; +in +lib.length (lib.unique ids) != lib.length ids || lib.any underPrefix ids diff --git a/nix/host-modules/swarm-nats.nix b/nix/host-modules/swarm-nats.nix index 653782c88..f0f38e038 100644 --- a/nix/host-modules/swarm-nats.nix +++ b/nix/host-modules/swarm-nats.nix @@ -15,6 +15,19 @@ let # everywhere, not whether the daemon happens to be enabled here. controllerCfg = config.services.hyperhive.swarm.controller; + clientIdClash = import ./lib/client-id-clash.nix { inherit lib; }; + + # The client ids the responder grants a service role, in the order of its + # `--reader-client` and `--*-client` flags below. + serviceClientIds = [ + controllerCfg.queueClientId + config.services.hyperhive.swarm.review-classifier.clientId + config.services.hyperhive.swarm.builder.clientId + config.services.hyperhive.swarm.claude-login.clientId + config.services.hyperhive.swarm.notify-router.clientId + config.services.hyperhive.swarm.stt.clientId + ]; + # The account the callout responder authenticates as, and the account # authorized clients are placed in. Two accounts rather than one: an # account is NATS' isolation boundary, so a responder that shares an @@ -654,6 +667,27 @@ in }; assertions = [ + { + # The responder matches a client id against the hive prefix first and + # takes the first role that fits, so an id under two roles, or under + # the hive prefix, silently gets the wrong grant. The responder + # refuses to start on the same overlap; this says so at evaluation. + assertion = + !(clientIdClash { + ids = serviceClientIds; + hivePrefix = autheliaCfg.hiveClientPrefix; + }); + message = '' + The queue's service client ids overlap: ${lib.concatStringsSep ", " serviceClientIds}. + + services.hyperhive.swarm.{controller.queueClientId, + review-classifier,builder,claude-login,notify-router,stt}.clientId + must differ from each other, and none may start with + services.hyperhive.swarm.authelia.hiveClientPrefix + ("${autheliaCfg.hiveClientPrefix}"): a client id that fits two roles gets the + first one's grant, and one under the prefix gets a hive's. + ''; + } { # The callout xkey and the responder's OIDC client secret are read # from the store under this identity; without either the server or diff --git a/nix/module-eval/nats-authelia.nix b/nix/module-eval/nats-authelia.nix index 9d29c51c3..6512212ce 100644 --- a/nix/module-eval/nats-authelia.nix +++ b/nix/module-eval/nats-authelia.nix @@ -61,6 +61,13 @@ let deploy.bao.clientKeyFile = "/etc/pki/h1-key.pem"; }; + # The queue module's assertion that no service client id is shared or under + # the hive prefix. Every one of those ids is a read-only option, so no host + # config can break it: what it guards is an edit to one of the module's own + # defaults. + clientIdsAssertion = + m: lib.findFirst (a: lib.hasInfix "service client ids overlap" a.message) null m.assertions; + responderOf = h: h.containers.swarm-nats.config.systemd.services.swarm-nats-auth; refusedWithoutIdentity = @@ -527,6 +534,54 @@ let lib.hasSuffix "s" timeout && lib.hasInfix " --server-auth-timeout-secs ${lib.removeSuffix "s" timeout} " exec; } + { + # The condition itself, on literal ids: the real ids are read-only, so no + # host can feed it a clash. Each clash must be refused and each near miss + # allowed, so dropping either half of the condition, or inverting one, + # fails a line here. + name = "the client id clash check refuses a shared id and one under the hive prefix"; + ok = + let + clash = + ids: + (import ../host-modules/lib/client-id-clash.nix { inherit lib; }) { + inherit ids; + hivePrefix = "hive-"; + }; + in + clash [ + "a" + "b" + "a" + ] + && clash [ + "swarm-a" + "hive-b" + ] + && clash [ + "hive-" + "hive-x" + ] + && !(clash [ + "swarm-a" + "swarm-b" + ]) + && !(clash [ + "hive-" + "swarm-b" + ]) + && !(clash [ ]); + } + { + # The control: the real ids, which no host config can change, pass it. A + # missing assertion would pass anything, so it must be there. + name = "the queue's service client ids are distinct and outside the hive prefix"; + ok = + let + a = clientIdsAssertion natsWithStoreIdentity; + in + a != null && a.assertion; + } { # The responder takes no agent-client suffix: no such client is minted. # `--hive-client-prefix` is the control that the lookup finds a flag the diff --git a/swarm-nats-auth/src/main.rs b/swarm-nats-auth/src/main.rs index 816eb85a8..436ddf244 100644 --- a/swarm-nats-auth/src/main.rs +++ b/swarm-nats-auth/src/main.rs @@ -245,7 +245,8 @@ async fn serve(args: Args, stop: swarm_secret_client::Shutdown) -> anyhow::Resul .with_builders(args.builder_clients.clone()) .with_claude_logins(args.claude_login_clients.clone()) .with_notify_routers(args.notify_router_clients.clone()) - .with_stts(args.stt_clients.clone()); + .with_stts(args.stt_clients.clone()) + .checked()?; let health = swarm_secret_client::health::Health::start( swarm_secret_client::health::STALE_AFTER, args.health_addr, @@ -1118,6 +1119,30 @@ mod tests { ); } + /// A service client id under the hive prefix ends `serve` while it reads + /// the policy, before it opens a listener or reaches the store; nothing + /// ahead of that check fails in this test, so the error is the check's. + #[tokio::test] + async fn a_service_client_under_the_hive_prefix_stops_serve_at_the_policy() { + let args = responder([ + "swarm-nats-auth", + "--introspection-url", + "https://auth.example/api/oidc/introspection", + "--server-auth-timeout-secs", + "2", + "--builder-client", + "hive-builder", + ]) + .expect("the flags parse"); + let stop: swarm_secret_client::Shutdown = + futures_util::FutureExt::shared(futures_util::FutureExt::boxed(std::future::pending())); + let err = serve(args, stop).await.expect_err("an overlapping policy"); + assert!( + format!("{err:#}").contains("--hive-client-prefix"), + "stopped for another reason: {err:#}" + ); + } + #[test] fn the_verb_does_not_take_the_responders_flags() { Cli::try_parse_from([ diff --git a/swarm-nats-auth/src/policy.rs b/swarm-nats-auth/src/policy.rs index 8b639380b..566240af4 100644 --- a/swarm-nats-auth/src/policy.rs +++ b/swarm-nats-auth/src/policy.rs @@ -158,6 +158,47 @@ impl Policy { self } + /// Refuses a configuration in which one client id fits two roles, or a + /// service role and the hive prefix. + /// + /// [`Self::permissions`] gives an id the first role it fits, hives first, + /// so an id under the hive prefix (`--builder-client hive-builder`) would + /// get a hive's grant, and one listed under two roles the earlier role's. + /// Hive names are guarded where the roster is read; service client ids + /// are not, so the check is here, once every role is set. + /// + /// # Errors + /// When a client id of a service role starts with the hive prefix, or is + /// listed under two roles; the message names both. + pub fn checked(self) -> anyhow::Result { + let roles: [(&str, &[String]); 6] = [ + ("--reader-client", &self.readers), + ("--review-classifier-client", &self.review_classifiers), + ("--builder-client", &self.builders), + ("--claude-login-client", &self.claude_logins), + ("--notify-router-client", &self.notify_routers), + ("--stt-client", &self.stts), + ]; + for (at, (flag, ids)) in roles.iter().enumerate() { + for id in *ids { + if self.hive_name(id).is_some() { + anyhow::bail!( + "{flag} {id:?} starts with --hive-client-prefix {:?}: it would get a \ + hive's grant, not the {flag} one", + self.hive_prefix + ); + } + if let Some((other, _)) = roles[at + 1..].iter().find(|(_, o)| o.contains(id)) { + anyhow::bail!( + "client id {id:?} is given to both {flag} and {other}: it would get \ + only the first one's grant" + ); + } + } + } + Ok(self) + } + /// The permissions for an agent whose own credential was verified, or /// `None` when none are configured. /// @@ -2830,4 +2871,91 @@ mod tests { .any(|g| covers(g, &direct_get_subject())) ); } + /// A policy with every service role set, `id` under each in turn by + /// `with`: one role per call, the rest as the module's defaults. + fn with_role_id(flag: &str, id: &str) -> Policy { + let one = || vec![id.to_owned()]; + let p = with_router(); + match flag { + "--reader-client" => Policy::new( + "hive-".to_owned(), + "hive-status".to_owned(), + one(), + Vec::new(), + ) + .expect("valid"), + "--review-classifier-client" => p.with_review_classifiers(one()), + "--builder-client" => p.with_builders(one()), + "--claude-login-client" => p.with_claude_logins(one()), + "--notify-router-client" => p.with_notify_routers(one()), + "--stt-client" => p.with_stts(one()), + other => panic!("no role {other}"), + } + } + + const ROLE_FLAGS: [&str; 6] = [ + "--reader-client", + "--review-classifier-client", + "--builder-client", + "--claude-login-client", + "--notify-router-client", + "--stt-client", + ]; + + /// The control for the two refusals below: the roles as the module sets + /// them, each with its own id, overlap nowhere. + #[test] + fn roles_with_distinct_ids_outside_the_hive_prefix_pass_the_check() { + with_router() + .with_stts(vec![STT.to_owned()]) + .checked() + .expect("no overlap"); + // The prefix alone is not a hive: nothing follows it. + with_role_id("--builder-client", "hive-") + .checked() + .expect("an id equal to the prefix names no hive"); + } + + /// An id under the hive prefix would be matched as a hive first, whatever + /// role it was configured for. + #[test] + fn a_service_client_under_the_hive_prefix_is_refused_naming_its_role() { + for flag in ROLE_FLAGS { + let err = with_role_id(flag, "hive-builder") + .checked() + .expect_err("a hive's id is not a service's"); + let message = err.to_string(); + assert!(message.contains(flag), "{flag}: {message}"); + assert!( + message.contains("--hive-client-prefix"), + "{flag}: {message}" + ); + } + } + + /// An id under two roles gets the earlier role's grant only; the message + /// names both, for every pair. + #[test] + fn a_client_id_given_to_two_roles_is_refused_naming_both() { + for (at, first) in ROLE_FLAGS.iter().enumerate() { + for second in &ROLE_FLAGS[at + 1..] { + let p = with_role_id(first, "swarm-shared"); + let p = match *second { + "--review-classifier-client" => { + p.with_review_classifiers(vec!["swarm-shared".into()]) + } + "--builder-client" => p.with_builders(vec!["swarm-shared".into()]), + "--claude-login-client" => p.with_claude_logins(vec!["swarm-shared".into()]), + "--notify-router-client" => p.with_notify_routers(vec!["swarm-shared".into()]), + "--stt-client" => p.with_stts(vec!["swarm-shared".into()]), + other => panic!("no role {other}"), + }; + let message = p.checked().expect_err("an id on two roles").to_string(); + assert!( + message.contains(first) && message.contains(second), + "{first} and {second}: {message}" + ); + } + } + } }