swarm-archive-users and hive-archive-backup read "No value found" on
stderr to tell a prefix that holds nothing from an error. With
`kv list -format=json`, bao answers such a prefix with status 2, `{}` on
stdout and nothing on stderr, so on a swarm whose archive has no users
yet the unit failed every 30 seconds forever, and every switch reported
it.
store_list, in the shared store helper, prints the names as a JSON array
and `[]` for a prefix that holds nothing: failed, empty stderr, stdout
`{}`. It is not decided on status 2 alone, which a refused token, a
sealed store and an unreachable store end with as well (their error is on
stderr). The two scripts use it. The script test runs it against a stub
that answers as bao does, with controls for a refusal, a sealed store and
a warning beside an empty answer, and the archive VM test's stub no
longer prints the table format's message for a JSON list. full-setup
waits for the users file to be rendered on a fresh swarm.
Closes #6840
440 lines
19 KiB
Python
440 lines
19 KiB
Python
import json
|
|
import os
|
|
import shlex
|
|
|
|
API = "http://localhost"
|
|
SOCKET = os.environ["FULL_SETUP_SOCKET"]
|
|
FORGE = "https://" + os.environ["FULL_SETUP_FORGE_DOMAIN"]
|
|
HIVE = os.environ["FULL_SETUP_HIVE"]
|
|
TOPLEVELS = json.loads(os.environ["FULL_SETUP_TOPLEVELS"])
|
|
REPO = os.environ["FULL_SETUP_HYPERHIVE_REPO"]
|
|
CONTROL_NIX = os.environ["FULL_SETUP_CONTROL_NIX"]
|
|
# Where `swarmctl bao init` saves what `bao operator init` printed, for root.
|
|
INIT = "/root/.local/state/swarmctl/bao-init.json"
|
|
# The host's swarmctl defaults to the swarm's gateway, where each controller verb needs a
|
|
# `swarmctl login`, which a VM without a browser cannot do. An empty `SWARMCTL_SWARM` puts a
|
|
# verb on the controller socket.
|
|
VIA_SOCKET = "SWARMCTL_SWARM="
|
|
SWARM_URL = "https://" + os.environ["FULL_SETUP_SWARM_DOMAIN"]
|
|
FORGE_AUTH = "/root/forge-auth.header"
|
|
NIX = "nix --extra-experimental-features nix-command"
|
|
ARCHETYPE = {"source": "hyperhive", "name": "reviewer"}
|
|
POLICY_UNITS_ACTIVE = (
|
|
"for u in $(systemctl list-unit-files 'swarm-bao-*-policy.service' --no-legend | cut -d' ' -f1 | grep -v operator-viewer) "
|
|
"swarm-bao-agent-pki.service; do "
|
|
'[ "$(systemctl is-active $u)" = active ] || { echo "$u is not active"; exit 1; }; done'
|
|
)
|
|
|
|
|
|
def controller(method, path, body=None, check="--fail-with-body"):
|
|
data = (
|
|
f"-H 'Content-Type: application/json' -d {shlex.quote(json.dumps(body))}"
|
|
if body
|
|
else ""
|
|
)
|
|
return machine.succeed(
|
|
f"curl {check} --silent --unix-socket {SOCKET} -X {method} {API}{path} {data}"
|
|
)
|
|
|
|
|
|
def forge(method, path, body=None):
|
|
data = (
|
|
f"-H 'Content-Type: application/json' -d {shlex.quote(json.dumps(body))}"
|
|
if body
|
|
else ""
|
|
)
|
|
return machine.succeed(
|
|
f"curl --fail-with-body --silent --insecure -H @{FORGE_AUTH} "
|
|
f"-X {method} {FORGE}/api/v1{path} {data}"
|
|
)
|
|
|
|
|
|
def diagnose(unit=None, container=None):
|
|
# What a timed-out wait leaves behind: the failed units and the end of the
|
|
# journal of the units that were waited on.
|
|
where = f"--machine={container} " if container else ""
|
|
units = [unit] if isinstance(unit, str) else list(unit or [])
|
|
flags = " ".join(f"-u '{u}'" for u in units)
|
|
names = " ".join(f"'{u}'" for u in units)
|
|
for command in [
|
|
f"systemctl {where}--failed --no-legend --no-pager",
|
|
*(
|
|
[
|
|
f"systemctl {where}status {names} --no-pager -l",
|
|
f"journalctl {where}{flags} --no-pager -n 50 | tail -c 6000",
|
|
]
|
|
if units
|
|
else []
|
|
),
|
|
]:
|
|
print(f"--- {command}")
|
|
print(machine.execute(command)[1])
|
|
|
|
|
|
def settle(command, timeout, unit=None, container=None):
|
|
try:
|
|
machine.wait_until_succeeds(command, timeout=timeout)
|
|
except Exception:
|
|
diagnose(unit, container)
|
|
raise
|
|
|
|
|
|
def create_agent(body):
|
|
# The controller refuses a create until its dependencies answer (the
|
|
# archetype list comes from the builder's evaluation), so ask again.
|
|
for _ in range(60):
|
|
status, out = machine.execute(
|
|
f"curl --silent --unix-socket {SOCKET} -o /root/create.out -w '%{{http_code}}' "
|
|
f"-X POST {API}/api/agents -H 'Content-Type: application/json' -d {shlex.quote(json.dumps(body))}"
|
|
)
|
|
if out.strip().startswith("2"):
|
|
return
|
|
machine.sleep(10)
|
|
diagnose("swarm-controller")
|
|
# The queue refuses every client when its responder cannot answer. nats and
|
|
# the responder run in the container; the units that fetch its keys and
|
|
# certificate run on the host.
|
|
diagnose(["nats.service", "swarm-nats-auth.service"], "swarm-nats")
|
|
diagnose(["swarm-bao-nats-tls.service", "swarm-bao-nats-callout-xkey.service"])
|
|
raise Exception(
|
|
f"the controller refused to create {body['name']}: HTTP {out}: {machine.succeed('cat /root/create.out')}"
|
|
)
|
|
|
|
|
|
machine.start()
|
|
machine.wait_for_unit("multi-user.target")
|
|
|
|
with subtest("the agents' toplevels are in the store, and the daemon builds nothing"):
|
|
for toplevel in TOPLEVELS:
|
|
machine.succeed(f"{NIX} path-info {toplevel}")
|
|
# The control for the lookup: a path that is not there is not found.
|
|
machine.fail(f"{NIX} path-info /nix/store/00000000000000000000000000000000-absent")
|
|
# The control for the missing build: a derivation no store holds is refused.
|
|
machine.fail(
|
|
f"NIX_CONFIG='experimental-features = nix-command' nix build --no-link --impure -f {CONTROL_NIX}"
|
|
)
|
|
|
|
# setup.md step 1: the secret store.
|
|
with subtest("step 1: swarmctl bao init"):
|
|
machine.wait_until_succeeds(
|
|
'[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=600
|
|
)
|
|
machine.succeed("swarmctl bao init >/root/bao-init.out 2>/root/bao-init.err")
|
|
# The keys file is saved before swarmctl parses, at mode 0600, and holds what it printed.
|
|
machine.succeed(f'[ "$(stat -c %a {INIT})" = 600 ]')
|
|
machine.succeed(
|
|
f"jq -e '(.unseal_keys_b64 | length) == 5 and (.root_token | length) > 0' {INIT}"
|
|
)
|
|
machine.succeed(
|
|
f'grep -qxF "Initial root token: $(jq -r .root_token {INIT})" /root/bao-init.out'
|
|
)
|
|
machine.succeed(f"grep -qF {INIT} /root/bao-init.err")
|
|
# Control: an initialised store is refused, and the keys file is left as it was.
|
|
before = machine.succeed(f"sha256sum {INIT}")
|
|
machine.fail("swarmctl bao init")
|
|
assert machine.succeed(f"sha256sum {INIT}") == before
|
|
|
|
|
|
def unseal():
|
|
# swarmctl's init uses bao's default of 5 shares with a threshold of 3.
|
|
for i in range(3):
|
|
machine.succeed(
|
|
f"bao operator unseal \"$(jq -r '.unseal_keys_b64[{i}]' {INIT})\""
|
|
)
|
|
|
|
|
|
with subtest("step 4: bao operator unseal, with the shamir seal, from the saved keys"):
|
|
unseal()
|
|
machine.succeed("bao status")
|
|
|
|
with subtest("step 1: the granter bootstrap"):
|
|
machine.succeed(
|
|
"set -o pipefail; "
|
|
f'export BAO_TOKEN="$(jq -r .root_token {INIT})"; '
|
|
"bao policy write bao-bootstrap /etc/hyperhive/bao-bootstrap-policy.hcl; "
|
|
"bao token create -policy=bao-bootstrap -ttl=24h -orphan -display-name=bao-bootstrap -field=token "
|
|
"| install -D -m 0600 /dev/stdin /var/lib/swarm-bao-bootstrap/grant.token; "
|
|
"unset BAO_TOKEN; "
|
|
"systemctl restart swarm-bao-granter-role"
|
|
)
|
|
machine.wait_until_succeeds(
|
|
"journalctl -u swarm-bao-granter-role --no-pager | grep -F 'Uploaded policy: bao-granter'",
|
|
timeout=300,
|
|
)
|
|
|
|
with subtest("step 1: the policy units that waited for the granter are restarted"):
|
|
# Some of these units retry every 30 seconds until something outside
|
|
# them exists: the bao UI's viewer policy waits for authelia's secrets
|
|
# unit, in its container, to publish the UI's OIDC client secret, and
|
|
# that unit waits for the secret publisher's policy written here. So
|
|
# the units are started without waiting, and polled until all are active.
|
|
machine.succeed(
|
|
"systemctl reset-failed 'swarm-bao-*-policy.service' swarm-bao-agent-pki.service || true"
|
|
)
|
|
machine.succeed(
|
|
"systemctl restart --no-block 'swarm-bao-*-policy.service' swarm-bao-agent-pki.service"
|
|
)
|
|
machine.wait_until_succeeds(
|
|
'[ "$(systemctl is-active swarm-bao-agent-pki.service)" = active ]', timeout=600
|
|
)
|
|
# Under the shamir seal the PKI unit leaves a restart of the store to the
|
|
# operator when its listener's client CA changed, and says which command.
|
|
if (
|
|
machine.execute(
|
|
"journalctl -u swarm-bao-agent-pki --no-pager | grep -F 'restart openbao.service'"
|
|
)[0]
|
|
== 0
|
|
):
|
|
machine.succeed("systemctl --machine=swarm-bao restart openbao.service")
|
|
machine.wait_until_succeeds(
|
|
'[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=600
|
|
)
|
|
unseal()
|
|
settle(POLICY_UNITS_ACTIVE, 1200, "swarm-bao-*-policy")
|
|
machine.succeed(
|
|
"journalctl -u swarm-bao-controller-policy --no-pager "
|
|
"| grep -F 'Data written to: auth/cert/certs/swarm-controller'"
|
|
)
|
|
|
|
with subtest("authelia's mint has published the clients' secrets"):
|
|
# The operator viewer policy is left out of the poll above: it waits for
|
|
# the UI client's secret, which authelia's secrets unit publishes from
|
|
# its container once the store and the trust bundle it needs exist. The
|
|
# controller's client secret is published by the same unit, and the
|
|
# controller, the hive's store logins and the UI policy all wait for it.
|
|
settle(
|
|
f'BAO_TOKEN="$(jq -r .root_token {INIT})" bao kv get -field=value '
|
|
"secret/swarm/controller/swarm-controller/oidc/client >/dev/null",
|
|
1200,
|
|
"authelia-swarm-secrets",
|
|
"swarm-authelia",
|
|
)
|
|
settle(
|
|
'[ "$(systemctl is-active swarm-bao-operator-viewer-policy.service)" = active ]',
|
|
300,
|
|
"swarm-bao-operator-viewer-policy",
|
|
)
|
|
|
|
with subtest("the swarm collector's client secret reaches the host"):
|
|
# `swarm-bao-otel-oidc` reads the mint's path once the store answers, and the mint writes
|
|
# it a moment after that first read on a fresh swarm. The unit has to fail on "no value yet"
|
|
# and ask again every 30 s. One that finished would wait for its refresh timer, ten minutes
|
|
# on, so the wait is shorter than that.
|
|
settle(
|
|
"[ -s /run/swarm-otel-oidc/swarm-collector.secret ]",
|
|
300,
|
|
"swarm-bao-otel-oidc",
|
|
)
|
|
|
|
with subtest("the receiver-socket check is active once the collector has recovered"):
|
|
# The collector opens its sockets only after authelia answers, which on a fresh swarm is
|
|
# after the unseal. `swarm-otel-sockets` runs at activation, long before that, so its first
|
|
# attempt fails; `swarm-otel-sockets-recheck` has to start it again, or it stays failed (and
|
|
# the only red unit on the swarm) after ingest works. The timer fires each minute and an
|
|
# attempt takes up to 30 s, so the wait covers several rounds.
|
|
settle(
|
|
'[ "$(systemctl is-active swarm-otel-sockets.service)" = active ]',
|
|
600,
|
|
"swarm-otel-sockets",
|
|
"swarm-otel",
|
|
)
|
|
|
|
with subtest("the archive's users file is rendered while no agent has a user yet"):
|
|
# No agent has a user until the controller grants one, so `kv list` of the users prefix
|
|
# answers as bao answers an empty prefix: status 2, `{}` on stdout, nothing on stderr. The
|
|
# unit has to read that as "no users yet" and finish; one that reads it as an error fails
|
|
# every 30 s forever and every switch reports it.
|
|
settle(
|
|
"journalctl -u swarm-archive-users --no-pager | grep -q 'Finished render'",
|
|
600,
|
|
"swarm-archive-users",
|
|
)
|
|
|
|
with subtest("step 2: swarmctl user add"):
|
|
machine.wait_until_succeeds(
|
|
"swarmctl user add mara --display-name Mara --email mara@example.com --group admins "
|
|
">/root/user-add.out 2>&1",
|
|
timeout=900,
|
|
)
|
|
machine.succeed("[ -s /root/user-add.out ]")
|
|
machine.succeed("swarmctl user list | grep -w mara")
|
|
|
|
with subtest("the forge holds hyperhive/hyperhive at the fixture's commit"):
|
|
# The controller's forge token, from the store as the controller reads it.
|
|
# Minted and stored by `forgejo-swarm-controller-account` in the forge
|
|
# container, which waits for forgejo and for a login to the store.
|
|
settle(
|
|
f'BAO_TOKEN="$(jq -r .root_token {INIT})" bao kv get -field=value '
|
|
"secret/swarm/controller/swarm-controller/forge/token > /root/forge-token",
|
|
900,
|
|
["forgejo", "forgejo-swarm-controller-account", "forgejo-sso-source"],
|
|
"hive-forge",
|
|
)
|
|
machine.succeed(
|
|
f"umask 077 && printf 'Authorization: token %s\\n' \"$(cat /root/forge-token)\" > {FORGE_AUTH}"
|
|
)
|
|
# The token being published says nothing about the gateway's vhost for
|
|
# the forge, which the calls below go through.
|
|
machine.wait_until_succeeds(
|
|
f"curl --fail --silent --insecure -H @{FORGE_AUTH} {FORGE}/api/v1/user >/dev/null",
|
|
timeout=600,
|
|
)
|
|
status = machine.succeed(
|
|
f"curl --silent --insecure -o /dev/null -w '%{{http_code}}' -H @{FORGE_AUTH} {FORGE}/api/v1/orgs/hyperhive"
|
|
).strip()
|
|
if status != "200":
|
|
forge("POST", "/orgs", {"username": "hyperhive", "visibility": "public"})
|
|
forge(
|
|
"POST",
|
|
"/orgs/hyperhive/repos",
|
|
{"name": "hyperhive", "private": False, "default_branch": "main"},
|
|
)
|
|
machine.succeed(
|
|
f"cp -r {REPO}/repo.git /root/hyperhive.git && chmod -R u+w /root/hyperhive.git"
|
|
)
|
|
machine.succeed(
|
|
f'GIT_SSL_NO_VERIFY=1 git -C /root/hyperhive.git -c "http.extraHeader=$(cat {FORGE_AUTH})" '
|
|
f"push {FORGE}/hyperhive/hyperhive.git main"
|
|
)
|
|
pushed = machine.succeed(
|
|
f'GIT_SSL_NO_VERIFY=1 git -c "http.extraHeader=$(cat {FORGE_AUTH})" '
|
|
f"ls-remote {FORGE}/hyperhive/hyperhive.git refs/heads/main"
|
|
).split()[0]
|
|
assert pushed == machine.succeed(f"cat {REPO}/rev").strip(), pushed
|
|
|
|
with subtest(
|
|
"step 8: spawn, a reviewer-archetype agent, through the endpoint the swarm UI calls"
|
|
):
|
|
machine.wait_until_succeeds(
|
|
f"curl --fail --silent --unix-socket {SOCKET} {API}/api/permissions >/dev/null",
|
|
timeout=900,
|
|
)
|
|
# A custom root agent (ruth, as the UI creates her) is a follow-up, not covered yet.
|
|
create_agent({"name": "spawn", "hive": HIVE, "archetype": ARCHETYPE})
|
|
|
|
with subtest("step 9: the first agent"):
|
|
create_agent({"name": "iris", "hive": HIVE, "archetype": ARCHETYPE})
|
|
|
|
with subtest("internal/meta holds the flake the toplevels were built from"):
|
|
# The controller commits the flake after it accepts a create, so the file can exist
|
|
# holding only the earlier agents; wait for the last one created.
|
|
settle(
|
|
f"curl --fail --silent --insecure -H @{FORGE_AUTH} {FORGE}/api/v1/repos/internal/meta/raw/flake.nix "
|
|
">/root/meta-flake.nix && grep -qF 'iris = mkAgent' /root/meta-flake.nix",
|
|
1800,
|
|
"swarm-controller",
|
|
)
|
|
rev = machine.succeed(f"cat {REPO}/rev").strip()
|
|
settings = json.loads(os.environ["FULL_SETUP_META_SETTINGS"])
|
|
expected = (
|
|
open(os.environ["FULL_SETUP_META_TEMPLATE"])
|
|
.read()
|
|
.replace(
|
|
"@HYPERHIVE_URL@",
|
|
f"git+{settings['git_base']}/hyperhive/hyperhive.git?rev={rev}",
|
|
)
|
|
)
|
|
for name, value in settings["vars"].items():
|
|
expected = expected.replace(f"@{name}@", value)
|
|
committed = machine.succeed("cat /root/meta-flake.nix")
|
|
assert committed == expected, (
|
|
"the controller's flake differs from the one the toplevels came from:\n"
|
|
+ committed
|
|
)
|
|
|
|
with subtest("swarmctl setup status reports the steps done so far"):
|
|
# Step 9 names ruth, the root agent of the real setup; this test creates none, so the report
|
|
# ends on step 9 not done and the exit status is 1.
|
|
reported = [
|
|
"✅ 1 secret store initialised",
|
|
"✅ 2 secret store unsealed",
|
|
"✅ 3 granter bootstrapped",
|
|
"✅ 4 granting units active",
|
|
"✅ 5 store unsealed after the granting units",
|
|
"✅ 6 SSO account in the admins group",
|
|
"👉 9 ruth created and up",
|
|
"✅ 10 another agent [optional]",
|
|
]
|
|
for _ in range(60):
|
|
lines = machine.execute(f"{VIA_SOCKET} swarmctl setup status")[1].splitlines()
|
|
if all(any(line.startswith(prefix) for line in lines) for prefix in reported):
|
|
break
|
|
machine.sleep(10)
|
|
else:
|
|
raise Exception(
|
|
"swarmctl setup status did not report the steps done so far:\n"
|
|
+ "\n".join(lines)
|
|
)
|
|
assert machine.execute(f"{VIA_SOCKET} swarmctl setup status >/dev/null")[0] == 1
|
|
|
|
with subtest(
|
|
"the host's swarmctl reaches the controller through the gateway by default"
|
|
):
|
|
# No login exists in the VM, so a verb that names the controller stops at the login, and
|
|
# says which swarm it went to. Over the socket the same verb needs none.
|
|
status, out = machine.execute("swarmctl schedule list 2>&1")
|
|
assert status != 0 and f"not logged in to {SWARM_URL}" in out, (status, out)
|
|
machine.succeed(f"{VIA_SOCKET} swarmctl schedule list")
|
|
|
|
with subtest("swarmctl login discovers the swarm's SSO provider from the gateway"):
|
|
# The swarm's own CA signs the gateway's leaf. A VM has no browser, so the login runs to the
|
|
# point where it prints the authorization URL and waits for the answer, which the timeout ends.
|
|
# Reaching that URL takes the gateway's 401 challenge, its published metadata, and authelia
|
|
# accepting the pushed authorization request.
|
|
ca = "/var/lib/hive-tls/swarm-services-root.pem"
|
|
auth = f"https://auth.{SWARM_URL.removeprefix('https://')}"
|
|
challenge = machine.succeed(
|
|
f"curl --silent --cacert {ca} -D - -o /dev/null {SWARM_URL}/api/"
|
|
)
|
|
assert challenge.startswith("HTTP/") and " 401" in challenge.splitlines()[0], (
|
|
challenge
|
|
)
|
|
assert (
|
|
f'resource_metadata="{SWARM_URL}/.well-known/oauth-protected-resource/api/"'
|
|
in challenge
|
|
), challenge
|
|
metadata = machine.succeed(
|
|
f"curl --fail --silent --cacert {ca} {SWARM_URL}/.well-known/oauth-protected-resource/api/"
|
|
)
|
|
assert json.loads(metadata) == {
|
|
"resource": f"{SWARM_URL}/api/",
|
|
"authorization_servers": [auth],
|
|
}, metadata
|
|
status, out = machine.execute(
|
|
f"timeout 30 swarmctl --swarm {SWARM_URL} --ca-file {ca} login --callback-port 8765 2>&1"
|
|
)
|
|
assert status == 124, (status, out)
|
|
assert f"{auth}/api/oidc/authorization?client_id=swarmctl&request_uri=" in out, out
|
|
|
|
with subtest("the agents are deployed and need a login"):
|
|
settle(
|
|
f"curl --fail --silent --unix-socket {SOCKET} {API}/api/agents/status "
|
|
"| jq -e '[.[] | select(.hive == \""
|
|
+ HIVE
|
|
+ '" and .freshness == "fresh" and .needs_login == true)'
|
|
' | .name] | map(select(. == "iris" or . == "spawn")) | unique | length == 2\'',
|
|
2400,
|
|
["swarm-controller", "hive-c0re"],
|
|
)
|
|
|
|
with subtest(
|
|
"authelia's token endpoint never rate-limited a client while the swarm came up"
|
|
):
|
|
# Per source address, the limiter refuses once an address has been refused enough times, so
|
|
# one client POSTing without a usable secret locks every other client behind that address out.
|
|
# The control is a refusal this test causes from the host: the same journal query has to find it.
|
|
TOKEN_JOURNAL = (
|
|
"journalctl --machine=swarm-authelia -u authelia-swarm.service --no-pager -o cat "
|
|
'| grep -F \'"path":"/api/oidc/token"\''
|
|
)
|
|
machine.succeed(
|
|
"curl --silent --insecure -u nobody:wrong -d grant_type=client_credentials "
|
|
f"https://auth.{os.environ['FULL_SETUP_SWARM_DOMAIN']}/api/oidc/token"
|
|
)
|
|
machine.wait_until_succeeds(
|
|
f'{TOKEN_JOURNAL} | grep -F \'"remote_ip":"127.0.0.1"\''
|
|
)
|
|
limited = machine.execute(f"{TOKEN_JOURNAL} | grep -F 'Rate Limit Exceeded'")[1]
|
|
assert limited == "", (
|
|
"authelia rate-limited the token endpoint:\n" + limited[-3000:]
|
|
)
|