From 5dacfdb320950b4f6da589f0d9d86abd0abf034d Mon Sep 17 00:00:00 2001 From: maia Date: Mon, 23 Nov 2026 21:16:46 +0100 Subject: [PATCH] swarm-bao: move the operator viewer login and the shared bindings out swarm-bao.nix held 5,146 lines in one module. Move two pieces out, with no change to what it renders: - lib/swarm-bao-shared.nix: the bindings more than one concern reads (the TLS directory, the granter's login and unit shape, the leaves several grants name, the CLI wrapper). swarm-bao.nix and the sibling modules import it and inherit what they use. - swarm-bao-operator-viewer.nix: the store's browser-UI login (the operator viewer policy, the oidc auth config and its role), gated as it was on the store and its server certificate. Refs #6820 --- nix/host-modules/default.nix | 1 + nix/host-modules/lib/swarm-bao-shared.nix | 299 ++++++++++++++ .../swarm-bao-operator-viewer.nix | 144 +++++++ nix/host-modules/swarm-bao.nix | 389 ++---------------- 4 files changed, 472 insertions(+), 361 deletions(-) create mode 100644 nix/host-modules/lib/swarm-bao-shared.nix create mode 100644 nix/host-modules/swarm-bao-operator-viewer.nix diff --git a/nix/host-modules/default.nix b/nix/host-modules/default.nix index b5ec31f96..1044c61ec 100644 --- a/nix/host-modules/default.nix +++ b/nix/host-modules/default.nix @@ -74,6 +74,7 @@ ./swarm-authelia.nix ./swarm-bao-service.nix ./swarm-bao.nix + ./swarm-bao-operator-viewer.nix ./swarm-builder.nix ./swarm-claude-login.nix ./swarm-notify-router.nix diff --git a/nix/host-modules/lib/swarm-bao-shared.nix b/nix/host-modules/lib/swarm-bao-shared.nix new file mode 100644 index 000000000..e6a286499 --- /dev/null +++ b/nix/host-modules/lib/swarm-bao-shared.nix @@ -0,0 +1,299 @@ +# The bindings of ../swarm-bao.nix that more than one concern of the store's +# host uses: where its TLS material lives, the granter's login and the unit +# shape every granting unit shares, the leaves several grants name, and the +# CLI wrapper. A module that writes some of the store's units imports this and +# inherits what it reads, so the unit is spelled once whichever file holds it. +{ + config, + lib, + pkgs, +}: +let + cfg = config.services.hyperhive.swarm.bao; + hyperhiveCfg = config.services.hyperhive; + deployCfg = hyperhiveCfg.deploy; + baoDeploy = deployCfg.bao; + + # The TLS material is its own small bind, on both sides of the boundary at + # the same path. Separate from `stateDir` because a HOST unit writes it and + # the container only reads it, and because systemd owns `stateDir` and moves + # it around; this directory is ours. + tlsDir = "/var/lib/swarm-bao-tls"; + + # Both or neither: a certificate without its key configures a listener that + # cannot start, and the failure would surface as openbao refusing to boot + # rather than as the missing setting it is. + haveServerTls = baoDeploy.serverCertFile != null && baoDeploy.serverKeyFile != null; + + # The credential that writes the granter's role below. A token and not a + # certificate: cert auth answers a *role*, so nothing can authenticate here + # until some role exists, and whatever creates the first one cannot itself + # use one. An operator places it — ../../../docs/1-getting-started/setup.md. + haveBootstrapToken = baoDeploy.bootstrapTokenFile != null; + + # The principal every `swarm-bao-*-policy` unit logs in as, so a new or + # changed `swarm-*` grant applies on deploy with no operator step. Policy and + # role share one name, outside both `swarm-*` and `hive-*`: neither the + # granter's globs nor the controller's reach the objects that constrain it. + granterPolicyName = "bao-granter"; + granterCn = baoDeploy.granterCommonName; + + # No CA means no login role can be written, so nothing could log in as the + # granter; the units that need it do not render. + haveGranter = + baoDeploy.granterClientCertFile != null + && baoDeploy.granterClientKeyFile != null + && baoDeploy.clientCaFile != null; + + # What a granting unit prints when the store refuses the granter: the + # one-time step, runnable as root on this host. + granterSetupSteps = [ + "swarmctl bao grant-bootstrap # does all of the following, and is also the re-apply after a policy change" + "# on a host without swarmctl, run these instead:" + "read -rs BAO_TOKEN && export BAO_TOKEN # the root token from 'bao operator init'" + "bao policy write bao-bootstrap /etc/hyperhive/bao-bootstrap-policy.hcl" + ] + ++ ( + if haveBootstrapToken then + [ + "bao token create -policy=bao-bootstrap -ttl=24h -orphan -display-name=bao-bootstrap -field=token | install -D -m 0600 /dev/stdin ${baoDeploy.bootstrapTokenFile}" + "unset BAO_TOKEN" + "systemctl restart swarm-bao-granter-role" + ] + else + [ + "# then set services.hyperhive.deploy.bao.bootstrapTokenFile on this host, deploy, and place a token there:" + "bao token create -policy=bao-bootstrap -ttl=24h -orphan -display-name=bao-bootstrap -field=token" + ] + ); + + # Exit 0 only on a reachable, unsealed store; its error, if any, is appended + # to `$err`. `status` needs no token, but the CLI resolves a token helper + # under `$HOME` before it asks, and systemd sets no `HOME` for a unit without + # `User=`: there it exits 1 on a healthy store. An empty home holds no helper + # config and no token. + baoStoreUp = ''HOME=/var/empty bao status >/dev/null 2>>"$err"''; + + # The login every granting unit starts with; ./granter-login.nix says + # which failures it reports as a missing role. + granterLogin = import ./granter-login.nix { + inherit + lib + granterCn + granterPolicyName + haveBootstrapToken + baoStoreUp + ; + setupSteps = granterSetupSteps; + }; + + # The granter's certificate for the granting units. The `baoCli` wrapper + # only defaults these, so the unit's environment wins. + granterEnv = { + BAO_CLIENT_CERT = baoDeploy.granterClientCertFile; + BAO_CLIENT_KEY = baoDeploy.granterClientKeyFile; + }; + + # `swarm-bao-pki` mints the granter's leaf; the granter's role is written by + # `swarm-bao-granter-role`, which normally skips, hence ordering only there. + # Each granting unit `Wants=` pki and never `Requires=` it: a refused or + # failed pki start fails a requirer's job with `dependency`, which no + # `Restart=` retries, while a leaf still missing fails `granterLogin` into + # the unit's own retry. + granterAfter = [ + "swarm-bao-pki.service" + "swarm-bao-granter-role.service" + ]; + + # The review classifier's Anthropic API key. The operator writes it through + # the UI's OIDC login, or the swarm UI's classifier settings, which the + # controller writes for them: `create` and `update` with no `read`, and a + # metadata `read` for whether one is set and when it changed. The classifier + # reads it on every run. + classifierApiKeyLeaf = "swarm/services/review-classifier/anthropic-api-key"; + + # The token the swarm builder pushes closures to the binary cache with, the nix + # half of `swarm_secret_client::builder::attic_push_token_path`. The builder + # reads it on every push. The operator writes it for an external cache; the + # in-swarm cache's host units create it. + atticPushTokenLeaf = "swarm/services/attic/push-token"; + + # The in-swarm cache's other two secrets, which its host units create: the + # key atticd signs tokens with, and the read-only token for the hives' pulls. + atticJwtLeaf = "swarm/services/attic/jwt-secret"; + atticPullTokenLeaf = "swarm/services/attic/pull-token"; + + # The cache's three public facts, beside the pull token: its address, its + # name, and the key its narinfo are signed with. The in-swarm cache's host + # unit creates them; for an external cache the operator writes them. + # `swarm-controller` reads all four and copies each to + # `swarm/hives//attic/` + # (`swarm_secret_client::attic::Leaf`). + atticUrlLeaf = "swarm/services/attic/url"; + atticCacheLeaf = "swarm/services/attic/cache"; + atticPublicKeyLeaf = "swarm/services/attic/public-key"; + atticFactLeaves = [ + atticPullTokenLeaf + atticUrlLeaf + atticCacheLeaf + atticPublicKeyLeaf + ]; + + # The review classifier's ACP provider key, the nix half of + # `swarm_secret_client::review_classifier::acp_provider_key_path`. Written + # and read like the API key above. + classifierAcpKeyLeaf = "swarm/services/review-classifier/acp-provider"; + + # The UI's OIDC client secret. Authelia's mint writes it; the granter reads it + # into the `oidc` auth method's config, which is the only copy bao uses. + baoUiClientLeaf = "swarm/services/${cfg.ui.oidc.clientId}/oidc/client"; + + # The KV v2 engine the controller writes agent credentials through. Named + # once because the grant above and the `secrets enable` in the bootstrap unit + # have to agree: a policy pointing at a mount nobody created is precisely the + # failure this pair exists to avoid. `swarm-secret-client` pins the same + # value on the reading side. + credentialMountPath = "secret"; + + # Lifetime of a token from a cert login, on every cert-auth role this file + # writes except the batch ones. The store keeps a lease per token until it + # expires; a login per operation at the mount default (32 days) leaves one + # lease each for a month. Every holder logs in, works and drops the token + # within two minutes (the controller's forge work is cut off at + # `FORGE_DEADLINE`). Rust-written roles take `CERT_ROLE_TOKEN_TTL`, which + # is the same value. + certRoleTokenTtl = "1h"; + + # A unit that logs in as the granter and runs `body`, ordered after the + # controller's unit. `after` and not `requires`: the controller's and the + # granter's units create the mounts these write into, but a failed oneshot + # still counts as finished, so ordering plus this unit's own retry is what + # converges. `body` follows the login with no separator. + granterPolicyUnit = + description: body: + lib.mkIf haveGranter { + inherit description; + after = [ + "container@${cfg.machine}.service" + "swarm-bao-controller-policy.service" + ] + ++ granterAfter; + wants = [ "swarm-bao-pki.service" ]; + wantedBy = [ "multi-user.target" ]; + path = [ + baoCli + pkgs.coreutils + ]; + environment = granterEnv; + # Same unseal wait as `swarm-bao-controller-policy`, for the reason stated + # there: under `seal = "shamir"` a human unseals by hand. + startLimitBurst = 2880; + startLimitIntervalSec = 90000; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + Restart = "on-failure"; + RestartSec = 30; + TimeoutStartSec = 60; + }; + script = '' + set -euo pipefail + + ${granterLogin} + '' + + body; + }; + + # The store's own CLI, on the host, with this deployment's coordinates already + # in the environment. Only the wrapper goes on `PATH` — `wrapProgram` renames + # the real binary, so there is no unwrapped `bao` to reach by accident and + # produce a connection that names no cause. + # + # `--set-default`, not `--set`: an operator pointing `BAO_ADDR` at another + # store must win. A wrapper that overrode an explicit environment would be the + # same class of surprise it exists to remove. + baoCli = + let + # The hive reader identity `glue-bao-tls` mints where a hive runs; a + # store host without a hive presents the operator leaf instead. Either + # satisfies the listeners' client-certificate requirement and neither + # supplies a token: a wrapper cannot conjure one. + identity = + if baoDeploy.clientCertFile != null && baoDeploy.clientKeyFile != null then + { + cert = baoDeploy.clientCertFile; + key = baoDeploy.clientKeyFile; + } + else if baoDeploy.operatorClientCertFile != null && baoDeploy.operatorClientKeyFile != null then + { + cert = baoDeploy.operatorClientCertFile; + key = baoDeploy.operatorClientKeyFile; + } + else + null; + wrapArgs = [ + "--set-default BAO_ADDR ${lib.escapeShellArg "https://${cfg.domain}:${toString cfg.port}"}" + ] + ++ lib.optional ( + baoDeploy.serverCaFile != null + ) "--set-default BAO_CACERT ${lib.escapeShellArg baoDeploy.serverCaFile}" + ++ lib.optionals (identity != null) [ + "--set-default BAO_CLIENT_CERT ${lib.escapeShellArg identity.cert}" + "--set-default BAO_CLIENT_KEY ${lib.escapeShellArg identity.key}" + ]; + in + pkgs.symlinkJoin { + name = "bao-hive"; + paths = [ baoDeploy.package ]; + nativeBuildInputs = [ pkgs.makeWrapper ]; + postBuild = '' + wrapProgram $out/bin/bao ${lib.concatStringsSep " " wrapArgs} + ''; + }; + + autheliaCfg = hyperhiveCfg.swarm.authelia; + + # Outbound TLS for that collector: it dials the swarm collector's gateway + # name and authelia's token endpoint, both leaves under the store's runtime + # pki root, which cannot be baked into a derivation. Same helper, same two + # halves and the same `SSL_CERT_FILE` consumption as ../swarm-otel.nix's own + # container — a Go process whose trust variable REPLACES the store, which is + # what the bundle (system CAs ++ our anchors) is for. + caTrust = import ./hive-ca-trust.nix { + inherit lib; + tlsCfg = deployCfg.hive-controller.tls; + gatewayCfg = hyperhiveCfg.gateway; + }; + +in +{ + inherit + atticCacheLeaf + atticFactLeaves + atticJwtLeaf + atticPublicKeyLeaf + atticPullTokenLeaf + atticPushTokenLeaf + atticUrlLeaf + autheliaCfg + baoCli + baoStoreUp + baoUiClientLeaf + caTrust + certRoleTokenTtl + classifierAcpKeyLeaf + classifierApiKeyLeaf + credentialMountPath + granterAfter + granterCn + granterEnv + granterLogin + granterPolicyName + granterPolicyUnit + granterSetupSteps + haveBootstrapToken + haveGranter + haveServerTls + tlsDir + ; +} diff --git a/nix/host-modules/swarm-bao-operator-viewer.nix b/nix/host-modules/swarm-bao-operator-viewer.nix new file mode 100644 index 000000000..6a9daddd8 --- /dev/null +++ b/nix/host-modules/swarm-bao-operator-viewer.nix @@ -0,0 +1,144 @@ +# The store's browser-UI login, written by the granter: the operator viewer +# policy, the `oidc` auth method's config and the role that hands authelia's +# `admins` that policy. Split out of ./swarm-bao.nix; the unit shape, the leaves +# and the mount names it shares with the other grants are in +# ./lib/swarm-bao-shared.nix. +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.services.hyperhive.swarm.bao; + deployCfg = config.services.hyperhive.deploy; + shared = import ./lib/swarm-bao-shared.nix { inherit config lib pkgs; }; + inherit (shared) + atticFactLeaves + atticPushTokenLeaf + autheliaCfg + baoUiClientLeaf + caTrust + classifierAcpKeyLeaf + classifierApiKeyLeaf + credentialMountPath + granterPolicyUnit + granterSetupSteps + haveServerTls + ; + + # What an OIDC login through the UI gets: the key tree and each key's KV + # metadata, and a write on the leaves the operator fills by hand. Never a + # value: KV v2 serves values under `data/`, and no `data/` stanza has a + # `read`. The UI needs no `sys/` grant on top: + # `sys/internal/ui/mounts` lists any mount the token holds a capability + # under, and the rest it calls is in the `default` policy. + # + # The cache's five leaves are where an external cache is configured, and + # where the operator replaces the in-swarm cache's tokens; its host units + # create them only while none is stored. `atticJwtLeaf` is left out: a new + # signing key invalidates both tokens. + operatorWritableLeaves = [ + classifierApiKeyLeaf + classifierAcpKeyLeaf + atticPushTokenLeaf + ] + ++ atticFactLeaves; + operatorViewerPolicyName = "swarm-operator-viewer"; + operatorViewerPolicyText = '' + path "${credentialMountPath}/metadata/*" { + capabilities = ["list", "read"] + } + '' + + lib.concatMapStrings (leaf: '' + path "${credentialMountPath}/data/${leaf}" { + capabilities = ["create", "update"] + } + '') operatorWritableLeaves; + + # authelia's operator group (`operatorGroup` in ./swarm-authelia.nix, the + # group its rule for the UI's vhost admits) → the viewer policy. authelia + # sends `groups` and `preferred_username` from its userinfo endpoint, and + # bao merges those into the ID token's claims before it checks + # `bound_claims`. + operatorViewerRole = builtins.toJSON { + role_type = "oidc"; + user_claim = "preferred_username"; + groups_claim = "groups"; + oidc_scopes = [ + "profile" + "groups" + ]; + bound_claims.groups = [ "admins" ]; + allowed_redirect_uris = [ cfg.ui.oidc.redirectUri ]; + token_policies = [ operatorViewerPolicyName ]; + token_ttl = "1h"; + token_max_ttl = "8h"; + }; + + # The `oidc` auth method's config, as `bao write` arguments. The client + # secret is `-`, read from stdin. On a self-signed gateway authelia's + # certificate chains to the host's anchor bundle; bao takes every + # certificate in `oidc_discovery_ca_pem`, not only the first. + operatorViewerOidcConfig = [ + "oidc_discovery_url=${toString autheliaCfg.url}" + "oidc_client_id=${cfg.ui.oidc.clientId}" + "oidc_client_secret=-" + "default_role=${operatorViewerPolicyName}" + ] + ++ lib.optional caTrust.useSelfSigned "oidc_discovery_ca_pem=@${deployCfg.hive-controller.tls.stateDir}/trust-bundle.pem"; +in +{ + config = lib.mkIf (deployCfg.bao.enable && haveServerTls) { + # The UI's OIDC login: the viewer policy, then the `oidc` auth method's + # config and the role that hands `admins` that policy. The mount itself, + # and the granter's grants on it, exist only once `swarm-bao-granter-role` + # has run with a bootstrap token that carries `sys/auth/oidc`. Until then + # this writes the policy and stops with exit 0: nothing is broken, the UI + # still takes a token, and a day of retries would change nothing. + # `swarm-bao-granter-role` restarts this unit each time it succeeds. + systemd.services.swarm-bao-operator-viewer-policy = granterPolicyUnit "write the bao UI's OIDC login: the operator viewer policy, the oidc config and its role" '' + + printf '%s' ${lib.escapeShellArg operatorViewerPolicyText} | + bao policy write ${lib.escapeShellArg operatorViewerPolicyName} - + + # Asks the granter's own token, through the `default` policy's + # `sys/capabilities-self`, rather than probing the mount: the granter + # holds no `sys/auth` to list mounts with. + caps="$(bao token capabilities auth/oidc/config)" + case "$caps" in + *update*) ;; + *) + echo "the granter may not configure auth/oidc yet (capabilities: $caps), so the UI's OIDC login stays off and token login is unchanged." >&2 + echo "one-time step, as root on this host (docs/1-getting-started/setup.md):" >&2 + ${lib.concatMapStringsSep "\n" (l: "echo ${lib.escapeShellArg " ${l}"} >&2") granterSetupSteps} + echo "swarm-bao-granter-role re-runs this unit once it succeeds." >&2 + exit 0 + ;; + esac + + # Stored by authelia's mint, in its container, which + # this boot does not wait on, so absence is retried. + if ! secret="$(bao kv get -field=value ${lib.escapeShellArg "${credentialMountPath}/${baoUiClientLeaf}"} 2>"$err")"; then + echo ${lib.escapeShellArg "the store did not return ${credentialMountPath}/${baoUiClientLeaf}: the UI's OIDC client secret is not published yet."} >&2 + cat "$err" >&2 + exit 1 + fi + if [ -z "$secret" ]; then + echo ${lib.escapeShellArg "the store returned an empty ${credentialMountPath}/${baoUiClientLeaf}."} >&2 + exit 1 + fi + + # bao fetches authelia's discovery document on this write, so an + # unreachable or untrusted authelia fails it and the unit retries. + printf '%s' "$secret" | + bao write auth/oidc/config ${ + lib.concatMapStringsSep " " lib.escapeShellArg operatorViewerOidcConfig + } + + # A JSON body on stdin, because `bound_claims` is a map. + printf '%s' ${lib.escapeShellArg operatorViewerRole} | + bao write auth/oidc/role/${lib.escapeShellArg operatorViewerPolicyName} - + ''; + }; +} diff --git a/nix/host-modules/swarm-bao.nix b/nix/host-modules/swarm-bao.nix index f976bde3f..29ea1e895 100644 --- a/nix/host-modules/swarm-bao.nix +++ b/nix/host-modules/swarm-bao.nix @@ -41,6 +41,34 @@ let baoDeploy = deployCfg.bao; networkCfg = hyperhiveCfg.network; + shared = import ./lib/swarm-bao-shared.nix { inherit config lib pkgs; }; + inherit (shared) + atticFactLeaves + atticJwtLeaf + atticPublicKeyLeaf + atticPushTokenLeaf + autheliaCfg + baoCli + baoStoreUp + baoUiClientLeaf + caTrust + certRoleTokenTtl + classifierAcpKeyLeaf + classifierApiKeyLeaf + credentialMountPath + granterAfter + granterCn + granterEnv + granterLogin + granterPolicyName + granterPolicyUnit + granterSetupSteps + haveBootstrapToken + haveGranter + haveServerTls + tlsDir + ; + # What this container's own collector stamps as `service.name` on every # log line and metric it forwards, and the value the shipped Grafana # dashboard's (`swarm-grafana/dashboards/bao.json`) panels all select on. @@ -74,12 +102,6 @@ let # `STATE_DIRECTORY` — the unit then dies before `bao` runs at all. stateDir = "/var/lib/openbao"; - # The TLS material is its own small bind, on both sides of the boundary at - # the same path. Separate from `stateDir` because a HOST unit writes it and - # the container only reads it, and because systemd owns `stateDir` and moves - # it around; this directory is ours. - tlsDir = "/var/lib/swarm-bao-tls"; - # Where the key surfaces for openbao to open. NOT `${tlsDir}/server-key.pem`: # that file is root-owned 0600 on the host, and the service runs as a # `DynamicUser`, so it cannot read the bind-mounted original. `LoadCredential` @@ -151,37 +173,12 @@ let serverCertSrc = baoDeploy.serverCertFile; serverKeySrc = baoDeploy.serverKeyFile; - # Both or neither: a certificate without its key configures a listener that - # cannot start, and the failure would surface as openbao refusing to boot - # rather than as the missing setting it is. - haveServerTls = baoDeploy.serverCertFile != null && baoDeploy.serverKeyFile != null; - - # The credential that writes the granter's role below. A token and not a - # certificate: cert auth answers a *role*, so nothing can authenticate here - # until some role exists, and whatever creates the first one cannot itself - # use one. An operator places it — ../../docs/1-getting-started/setup.md. - haveBootstrapToken = baoDeploy.bootstrapTokenFile != null; - # Bind the directory, never the file, for the reason `tokenStoreDir` gives # above: nothing creates a `hostPath`, so naming a file an operator has not # placed yet would stop the container from starting. bootstrapTokenDir = if haveBootstrapToken then builtins.dirOf baoDeploy.bootstrapTokenFile else null; - # The principal every `swarm-bao-*-policy` unit logs in as, so a new or - # changed `swarm-*` grant applies on deploy with no operator step. Policy and - # role share one name, outside both `swarm-*` and `hive-*`: neither the - # granter's globs nor the controller's reach the objects that constrain it. - granterPolicyName = "bao-granter"; - granterCn = baoDeploy.granterCommonName; - - # No CA means no login role can be written, so nothing could log in as the - # granter; the units that need it do not render. - haveGranter = - baoDeploy.granterClientCertFile != null - && baoDeploy.granterClientKeyFile != null - && baoDeploy.clientCaFile != null; - # ⚠️ ROOT-EQUIVALENT BY CONSTRUCTION. No ACL constrains the body of a policy, # so a principal that may write `swarm-*` policies and the roles attaching # them may grant itself anything. What bounds it is that every policy it @@ -303,48 +300,6 @@ let } ''; - # What a granting unit prints when the store refuses the granter: the - # one-time step, runnable as root on this host. - granterSetupSteps = [ - "swarmctl bao grant-bootstrap # does all of the following, and is also the re-apply after a policy change" - "# on a host without swarmctl, run these instead:" - "read -rs BAO_TOKEN && export BAO_TOKEN # the root token from 'bao operator init'" - "bao policy write bao-bootstrap /etc/hyperhive/bao-bootstrap-policy.hcl" - ] - ++ ( - if haveBootstrapToken then - [ - "bao token create -policy=bao-bootstrap -ttl=24h -orphan -display-name=bao-bootstrap -field=token | install -D -m 0600 /dev/stdin ${baoDeploy.bootstrapTokenFile}" - "unset BAO_TOKEN" - "systemctl restart swarm-bao-granter-role" - ] - else - [ - "# then set services.hyperhive.deploy.bao.bootstrapTokenFile on this host, deploy, and place a token there:" - "bao token create -policy=bao-bootstrap -ttl=24h -orphan -display-name=bao-bootstrap -field=token" - ] - ); - - # Exit 0 only on a reachable, unsealed store; its error, if any, is appended - # to `$err`. `status` needs no token, but the CLI resolves a token helper - # under `$HOME` before it asks, and systemd sets no `HOME` for a unit without - # `User=`: there it exits 1 on a healthy store. An empty home holds no helper - # config and no token. - baoStoreUp = ''HOME=/var/empty bao status >/dev/null 2>>"$err"''; - - # The login every granting unit starts with; ./lib/granter-login.nix says - # which failures it reports as a missing role. - granterLogin = import ./lib/granter-login.nix { - inherit - lib - granterCn - granterPolicyName - haveBootstrapToken - baoStoreUp - ; - setupSteps = granterSetupSteps; - }; - # The bootstrap token's first use, in `swarm-bao-granter-role`. bootstrapAuthList = import ./lib/bootstrap-auth-list.nix { inherit lib baoStoreUp; @@ -356,24 +311,6 @@ let setupSteps = granterSetupSteps; }; - # The granter's certificate for the granting units. The `baoCli` wrapper - # only defaults these, so the unit's environment wins. - granterEnv = { - BAO_CLIENT_CERT = baoDeploy.granterClientCertFile; - BAO_CLIENT_KEY = baoDeploy.granterClientKeyFile; - }; - - # `swarm-bao-pki` mints the granter's leaf; the granter's role is written by - # `swarm-bao-granter-role`, which normally skips, hence ordering only there. - # Each granting unit `Wants=` pki and never `Requires=` it: a refused or - # failed pki start fails a requirer's job with `dependency`, which no - # `Restart=` retries, while a leaf still missing fails `granterLogin` into - # the unit's own retry. - granterAfter = [ - "swarm-bao-pki.service" - "swarm-bao-granter-role.service" - ]; - # The name both ends must agree on: the cert-auth role below attaches this # policy by spelling it the same way, and is itself named after it. controllerPolicyName = "swarm-controller"; @@ -842,45 +779,12 @@ let # classifier's reviews with it; no other principal's policy reaches it. classifierForgeTokenLeaf = "swarm/services/review-classifier/forge/token"; - # The review classifier's Anthropic API key. The operator writes it through - # the UI's OIDC login, or the swarm UI's classifier settings, which the - # controller writes for them: `create` and `update` with no `read`, and a - # metadata `read` for whether one is set and when it changed. The classifier - # reads it on every run. - classifierApiKeyLeaf = "swarm/services/review-classifier/anthropic-api-key"; - # The swarm builder's forge token, the nix half of # `swarm_secret_client::builder::forge_token_path`. The controller mints it # and reads it back before deciding whether to re-mint; the builder reads it # to fetch config repos. builderForgeTokenLeaf = "swarm/services/builder/forge/token"; - # The token the swarm builder pushes closures to the binary cache with, the nix - # half of `swarm_secret_client::builder::attic_push_token_path`. The builder - # reads it on every push. The operator writes it for an external cache; the - # in-swarm cache's host units create it. - atticPushTokenLeaf = "swarm/services/attic/push-token"; - - # The in-swarm cache's other two secrets, which its host units create: the - # key atticd signs tokens with, and the read-only token for the hives' pulls. - atticJwtLeaf = "swarm/services/attic/jwt-secret"; - atticPullTokenLeaf = "swarm/services/attic/pull-token"; - - # The cache's three public facts, beside the pull token: its address, its - # name, and the key its narinfo are signed with. The in-swarm cache's host - # unit creates them; for an external cache the operator writes them. - # `swarm-controller` reads all four and copies each to - # `swarm/hives//attic/` - # (`swarm_secret_client::attic::Leaf`). - atticUrlLeaf = "swarm/services/attic/url"; - atticCacheLeaf = "swarm/services/attic/cache"; - atticPublicKeyLeaf = "swarm/services/attic/public-key"; - atticFactLeaves = [ - atticPullTokenLeaf - atticUrlLeaf - atticCacheLeaf - atticPublicKeyLeaf - ]; atticHiveFactNames = [ "pull-token" "url" @@ -894,83 +798,6 @@ let # to list runs. ciMetricsForgeTokenLeaf = "swarm/services/ci-metrics/forge/token"; - # The review classifier's ACP provider key, the nix half of - # `swarm_secret_client::review_classifier::acp_provider_key_path`. Written - # and read like the API key above. - classifierAcpKeyLeaf = "swarm/services/review-classifier/acp-provider"; - - # The UI's OIDC client secret. Authelia's mint writes it; the granter reads it - # into the `oidc` auth method's config, which is the only copy bao uses. - baoUiClientLeaf = "swarm/services/${cfg.ui.oidc.clientId}/oidc/client"; - - # What an OIDC login through the UI gets: the key tree and each key's KV - # metadata, and a write on the leaves the operator fills by hand. Never a - # value: KV v2 serves values under `data/`, and no `data/` stanza has a - # `read`. The UI needs no `sys/` grant on top: - # `sys/internal/ui/mounts` lists any mount the token holds a capability - # under, and the rest it calls is in the `default` policy. - # - # The cache's five leaves are where an external cache is configured, and - # where the operator replaces the in-swarm cache's tokens; its host units - # create them only while none is stored. `atticJwtLeaf` is left out: a new - # signing key invalidates both tokens. - operatorWritableLeaves = [ - classifierApiKeyLeaf - classifierAcpKeyLeaf - atticPushTokenLeaf - ] - ++ atticFactLeaves; - operatorViewerPolicyName = "swarm-operator-viewer"; - operatorViewerPolicyText = '' - path "${credentialMountPath}/metadata/*" { - capabilities = ["list", "read"] - } - '' - + lib.concatMapStrings (leaf: '' - path "${credentialMountPath}/data/${leaf}" { - capabilities = ["create", "update"] - } - '') operatorWritableLeaves; - - # authelia's operator group (`operatorGroup` in ./swarm-authelia.nix, the - # group its rule for the UI's vhost admits) → the viewer policy. authelia - # sends `groups` and `preferred_username` from its userinfo endpoint, and - # bao merges those into the ID token's claims before it checks - # `bound_claims`. - operatorViewerRole = builtins.toJSON { - role_type = "oidc"; - user_claim = "preferred_username"; - groups_claim = "groups"; - oidc_scopes = [ - "profile" - "groups" - ]; - bound_claims.groups = [ "admins" ]; - allowed_redirect_uris = [ cfg.ui.oidc.redirectUri ]; - token_policies = [ operatorViewerPolicyName ]; - token_ttl = "1h"; - token_max_ttl = "8h"; - }; - - # The `oidc` auth method's config, as `bao write` arguments. The client - # secret is `-`, read from stdin. On a self-signed gateway authelia's - # certificate chains to the host's anchor bundle; bao takes every - # certificate in `oidc_discovery_ca_pem`, not only the first. - operatorViewerOidcConfig = [ - "oidc_discovery_url=${toString autheliaCfg.url}" - "oidc_client_id=${cfg.ui.oidc.clientId}" - "oidc_client_secret=-" - "default_role=${operatorViewerPolicyName}" - ] - ++ lib.optional caTrust.useSelfSigned "oidc_discovery_ca_pem=@${deployCfg.hive-controller.tls.stateDir}/trust-bundle.pem"; - - # The KV v2 engine the controller writes agent credentials through. Named - # once because the grant above and the `secrets enable` in the bootstrap unit - # have to agree: a policy pointing at a mount nobody created is precisely the - # failure this pair exists to avoid. `swarm-secret-client` pins the same - # value on the reading side. - credentialMountPath = "secret"; - # The PKI engine the swarm's *service* certificates are to be issued from, # named once for the same reason `credentialMountPath` is: the role below, # the grant that points at `pki/issue/`, and the `secrets enable` in the @@ -1216,15 +1043,6 @@ let max_ttl = "${toString sshAgent.certMaxTtlMinutes}m"; }; - # Lifetime of a token from a cert login, on every cert-auth role this file - # writes except the batch ones. The store keeps a lease per token until it - # expires; a login per operation at the mount default (32 days) leaves one - # lease each for a month. Every holder logs in, works and drops the token - # within two minutes (the controller's forge work is cut off at - # `FORGE_DEADLINE`). Rust-written roles take `CERT_ROLE_TOKEN_TTL`, which - # is the same value. - certRoleTokenTtl = "1h"; - # The agent CA's certificate, cached on this host by `swarm-bao-agent-pki`, # so `swarm-bao-certs` can compose the listener's bundle before the store # is up. Public material. @@ -1676,46 +1494,6 @@ let display_name=${lib.escapeShellArg obj.cn}${ttlArgs} ''; - # A unit that logs in as the granter and runs `body`, ordered after the - # controller's unit. `after` and not `requires`: the controller's and the - # granter's units create the mounts these write into, but a failed oneshot - # still counts as finished, so ordering plus this unit's own retry is what - # converges. `body` follows the login with no separator. - granterPolicyUnit = - description: body: - lib.mkIf haveGranter { - inherit description; - after = [ - "container@${cfg.machine}.service" - "swarm-bao-controller-policy.service" - ] - ++ granterAfter; - wants = [ "swarm-bao-pki.service" ]; - wantedBy = [ "multi-user.target" ]; - path = [ - baoCli - pkgs.coreutils - ]; - environment = granterEnv; - # Same unseal wait as `swarm-bao-controller-policy`, for the reason stated - # there: under `seal = "shamir"` a human unseals by hand. - startLimitBurst = 2880; - startLimitIntervalSec = 90000; - serviceConfig = { - Type = "oneshot"; - RemainAfterExit = true; - Restart = "on-failure"; - RestartSec = 30; - TimeoutStartSec = 60; - }; - script = '' - set -euo pipefail - - ${granterLogin} - '' - + body; - }; - # One unit per PRINCIPAL, not one unit for all of them: these names are # operator-facing strings, the same reason `swarm-bao-secret-publisher-policy` # below gives for not being more script inside the controller's unit. A @@ -1743,53 +1521,6 @@ let clientCaPath = "${tlsDir}/client-ca.pem"; - # The store's own CLI, on the host, with this deployment's coordinates already - # in the environment. Only the wrapper goes on `PATH` — `wrapProgram` renames - # the real binary, so there is no unwrapped `bao` to reach by accident and - # produce a connection that names no cause. - # - # `--set-default`, not `--set`: an operator pointing `BAO_ADDR` at another - # store must win. A wrapper that overrode an explicit environment would be the - # same class of surprise it exists to remove. - baoCli = - let - # The hive reader identity `glue-bao-tls` mints where a hive runs; a - # store host without a hive presents the operator leaf instead. Either - # satisfies the listeners' client-certificate requirement and neither - # supplies a token: a wrapper cannot conjure one. - identity = - if baoDeploy.clientCertFile != null && baoDeploy.clientKeyFile != null then - { - cert = baoDeploy.clientCertFile; - key = baoDeploy.clientKeyFile; - } - else if baoDeploy.operatorClientCertFile != null && baoDeploy.operatorClientKeyFile != null then - { - cert = baoDeploy.operatorClientCertFile; - key = baoDeploy.operatorClientKeyFile; - } - else - null; - wrapArgs = [ - "--set-default BAO_ADDR ${lib.escapeShellArg "https://${cfg.domain}:${toString cfg.port}"}" - ] - ++ lib.optional ( - baoDeploy.serverCaFile != null - ) "--set-default BAO_CACERT ${lib.escapeShellArg baoDeploy.serverCaFile}" - ++ lib.optionals (identity != null) [ - "--set-default BAO_CLIENT_CERT ${lib.escapeShellArg identity.cert}" - "--set-default BAO_CLIENT_KEY ${lib.escapeShellArg identity.key}" - ]; - in - pkgs.symlinkJoin { - name = "bao-hive"; - paths = [ baoDeploy.package ]; - nativeBuildInputs = [ pkgs.makeWrapper ]; - postBuild = '' - wrapProgram $out/bin/bao ${lib.concatStringsSep " " wrapArgs} - ''; - }; - extraListeners = lib.listToAttrs ( lib.imap1 ( i: addr: @@ -1981,22 +1712,9 @@ let # exporter that names it, and `service.extensions`, where an omission makes # it inert rather than an error. forwarderAuthName = "oauth2client/${swarmOtelCfg.storeProducerName}"; - autheliaCfg = hyperhiveCfg.swarm.authelia; rootfsCheck = import ./lib/container-rootfs-check.nix { inherit config; }; - # Outbound TLS for that collector: it dials the swarm collector's gateway - # name and authelia's token endpoint, both leaves under the store's runtime - # pki root, which cannot be baked into a derivation. Same helper, same two - # halves and the same `SSL_CERT_FILE` consumption as ./swarm-otel.nix's own - # container — a Go process whose trust variable REPLACES the store, which is - # what the bundle (system CAs ++ our anchors) is for. - caTrust = import ./lib/hive-ca-trust.nix { - inherit lib; - tlsCfg = deployCfg.hive-controller.tls; - gatewayCfg = hyperhiveCfg.gateway; - }; - swarmOtelCfg = hyperhiveCfg.swarm.otel; # Non-zero is what SERVES the endpoint at all — the switch is a duration, not @@ -4523,57 +4241,6 @@ in ); }; - # The UI's OIDC login: the viewer policy, then the `oidc` auth method's - # config and the role that hands `admins` that policy. The mount itself, - # and the granter's grants on it, exist only once `swarm-bao-granter-role` - # has run with a bootstrap token that carries `sys/auth/oidc`. Until then - # this writes the policy and stops with exit 0: nothing is broken, the UI - # still takes a token, and a day of retries would change nothing. - # `swarm-bao-granter-role` restarts this unit each time it succeeds. - systemd.services.swarm-bao-operator-viewer-policy = granterPolicyUnit "write the bao UI's OIDC login: the operator viewer policy, the oidc config and its role" '' - - printf '%s' ${lib.escapeShellArg operatorViewerPolicyText} | - bao policy write ${lib.escapeShellArg operatorViewerPolicyName} - - - # Asks the granter's own token, through the `default` policy's - # `sys/capabilities-self`, rather than probing the mount: the granter - # holds no `sys/auth` to list mounts with. - caps="$(bao token capabilities auth/oidc/config)" - case "$caps" in - *update*) ;; - *) - echo "the granter may not configure auth/oidc yet (capabilities: $caps), so the UI's OIDC login stays off and token login is unchanged." >&2 - echo "one-time step, as root on this host (docs/1-getting-started/setup.md):" >&2 - ${lib.concatMapStringsSep "\n" (l: "echo ${lib.escapeShellArg " ${l}"} >&2") granterSetupSteps} - echo "swarm-bao-granter-role re-runs this unit once it succeeds." >&2 - exit 0 - ;; - esac - - # Stored by authelia's mint, in its container, which - # this boot does not wait on, so absence is retried. - if ! secret="$(bao kv get -field=value ${lib.escapeShellArg "${credentialMountPath}/${baoUiClientLeaf}"} 2>"$err")"; then - echo ${lib.escapeShellArg "the store did not return ${credentialMountPath}/${baoUiClientLeaf}: the UI's OIDC client secret is not published yet."} >&2 - cat "$err" >&2 - exit 1 - fi - if [ -z "$secret" ]; then - echo ${lib.escapeShellArg "the store returned an empty ${credentialMountPath}/${baoUiClientLeaf}."} >&2 - exit 1 - fi - - # bao fetches authelia's discovery document on this write, so an - # unreachable or untrusted authelia fails it and the unit retries. - printf '%s' "$secret" | - bao write auth/oidc/config ${ - lib.concatMapStringsSep " " lib.escapeShellArg operatorViewerOidcConfig - } - - # A JSON body on stdin, because `bound_claims` is a map. - printf '%s' ${lib.escapeShellArg operatorViewerRole} | - bao write auth/oidc/role/${lib.escapeShellArg operatorViewerPolicyName} - - ''; - # The CA bind source is written at runtime by a host unit, so the # container has to start after it — otherwise nspawn sets up a mount # over a file that does not exist yet.