# 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; }; # The swarm appservice token's leaf, the nix half of # `swarm_secret_client::matrix::swarm_appservice_token_path`. Under # `controller/`, the one kind no hive's policy reads: its sender is the # homeserver's admin. swarmAppserviceTokenLeaf = "swarm/controller/swarm-controller/matrix/appservice-token"; # The swarm appservice registration's leaf, the nix half of # `swarm_secret_client::matrix::swarm_appservice_registration_path`. Only # matrix-ctl reaches it; the controller reads the token above, not this. swarmAppserviceRegistrationLeaf = "swarm/controller/swarm-controller/matrix/appservice-registration"; # The controller's own OIDC client secret, the nix half of # `swarm_secret_client::queue::controller_client_path`. Authelia's mint writes # it; the controller reads it and holds no other copy. controllerClientLeaf = "swarm/controller/swarm-controller/oidc/client"; # The controller's own forge token, the nix half of # `swarm_secret_client::forge::controller_token_path`. The forge's host writes # it; the controller reads it and holds no other copy. controllerForgeTokenLeaf = "swarm/controller/swarm-controller/forge/token"; # The controller's Viewer token for Grafana's API, the nix half of # `swarm_secret_client::grafana::controller_token_path`. Grafana's host # writes it; the controller reads it and holds no other copy. controllerGrafanaTokenLeaf = "swarm/controller/swarm-controller/grafana/token"; # The HMAC secret of the swarm-wide forge webhooks, the nix half of # `swarm_secret_client::forge::controller_webhook_secret_path`. The controller # creates it, seeded from its old state-directory file, and reads it; `create` # without `update`, so the first value stored is the one every start reads. controllerWebhookSecretLeaf = "swarm/controller/swarm-controller/forge/webhook-secret"; # The forge's runner registration token, the nix half of # `swarm_secret_client::ci::registration_token_path`. The controller writes # it and cannot read it back (`forge::runner_token` keeps the value it last # wrote in memory); the CI runner's fetch unit is its one reader. ciRunnerTokenLeaf = "swarm/services/ci-runner/registration-token"; # The review classifier's forge token, the nix half of # `swarm_secret_client::review_classifier::forge_token_path`. The controller # mints it, reads it back before deciding whether to re-mint, and posts the # classifier's reviews with it; no other principal's policy reaches it. classifierForgeTokenLeaf = "swarm/services/review-classifier/forge/token"; # 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 CI run poller's forge token, the nix half of # `swarm_secret_client::ci_metrics::forge_token_path`. The controller mints it # and reads it back before deciding whether to re-mint; the poller reads it # to list runs. ciMetricsForgeTokenLeaf = "swarm/services/ci-metrics/forge/token"; readStanza = path: '' path "${path}" { capabilities = ["read"] } ''; listStanza = path: '' path "${path}" { capabilities = ["list"] } ''; # The callout's keys, the nix half of `swarm-nats-auth`'s `xkey::SEED_PATH` # and `xkey::PUBLIC_PATH`, and of the `seed_path` and `public_path` of # `nkey::ISSUER` and `nkey::USER`. All are readable by the `swarm-nats-auth` # role alone: `swarm/public/` marks the halves that are no secret, and no # policy opens them to every token. xkeySeedLeaf = "swarm/services/swarm-nats/callout/xkey-seed"; xkeyPublicLeaf = "swarm/public/swarm-nats/callout-xkey"; issuerSeedLeaf = "swarm/services/swarm-nats/callout/issuer-seed"; issuerPublicLeaf = "swarm/public/swarm-nats/callout-issuer"; userSeedLeaf = "swarm/services/swarm-nats/callout/user-seed"; userPublicLeaf = "swarm/public/swarm-nats/callout-user"; # Grafana's admin password, which only Grafana's leaf creates. The nix half # of `adminPasswordStorePath` in ../swarm-grafana.nix. grafanaAdminLeaf = "swarm/services/${hyperhiveCfg.swarm.grafana.oidc.clientId}/admin/password"; # The bearer Grafana's datasources present at the metrics and log stores. # Grafana's leaf creates it, the stores' responders read it. The nix half of # `metricsBearerStorePath` in ../swarm-grafana.nix and of `--store-path` in # ../swarm-victoriametrics.nix and ../swarm-victorialogs.nix. grafanaMetricsBearerLeaf = "swarm/services/${hyperhiveCfg.swarm.grafana.oidc.clientId}/metrics/bearer"; # Grafana's datasource-encryption key, which only Grafana's leaf creates. The # nix half of `secretKeyStorePath` in ../swarm-grafana.nix. grafanaSecretKeyLeaf = "swarm/services/${hyperhiveCfg.swarm.grafana.oidc.clientId}/secret-key"; # authelia's jwt, session, storage-encryption, OIDC HMAC and OIDC issuer keys, # which only `authelia-swarm-secrets` in authelia's container creates and reads. # The nix half of `keyLeaf` in ../swarm-authelia.nix. `create` without # `update`, so a stored key is never replaced: the storage-encryption key # encrypts authelia's database and the issuer key signs every id token. autheliaKeyLeaves = map (name: "swarm/services/${autheliaCfg.machine}/keys/${name}") [ "jwt" "session" "storage-encryption" "oidc-hmac" "oidc-issuer" ]; createStanza = path: '' path "${path}" { capabilities = ["create", "read"] } ''; in { inherit atticCacheLeaf atticFactLeaves atticJwtLeaf atticPublicKeyLeaf atticPullTokenLeaf atticPushTokenLeaf atticUrlLeaf autheliaCfg autheliaKeyLeaves baoCli baoStoreUp baoUiClientLeaf builderForgeTokenLeaf caTrust certRoleTokenTtl ciMetricsForgeTokenLeaf ciRunnerTokenLeaf classifierAcpKeyLeaf classifierApiKeyLeaf classifierForgeTokenLeaf controllerClientLeaf controllerForgeTokenLeaf controllerGrafanaTokenLeaf controllerWebhookSecretLeaf createStanza credentialMountPath grafanaAdminLeaf grafanaMetricsBearerLeaf grafanaSecretKeyLeaf granterAfter granterCn granterEnv granterLogin granterPolicyName granterPolicyUnit granterSetupSteps haveBootstrapToken haveGranter haveServerTls issuerPublicLeaf issuerSeedLeaf listStanza readStanza swarmAppserviceRegistrationLeaf swarmAppserviceTokenLeaf tlsDir userPublicLeaf userSeedLeaf xkeyPublicLeaf xkeySeedLeaf ; }