Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/nix/host-modules/lib/swarm-bao-shared.nix
maia 5dacfdb320 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
2026-11-23 21:54:32 +01:00

299 lines
12 KiB
Nix

# 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/<hive>/attic/<name>`
# (`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
;
}