swarmctl bao init: save bao's raw output before parsing, and accept null key lists
This commit is contained in:
parent
479cdd6efb
commit
870a0a6697
10 changed files with 395 additions and 73 deletions
|
|
@ -96,9 +96,20 @@ swarmctl bao init
|
|||
```
|
||||
|
||||
It prints the unseal (or, under the default `pkcs11` seal, recovery) keys
|
||||
and the root token **once**, and stores none of them: not in a file, and the root token is
|
||||
never in a process's argument list (so not in `ps`). Record them off this host before you do
|
||||
anything else. It refuses an initialised store, and works
|
||||
and the root token **once**. Record them off this host before you do
|
||||
anything else.
|
||||
|
||||
Before it parses what `bao operator init` printed, it saves that raw output to
|
||||
`bao-init.json` in swarmctl's state directory: `$XDG_STATE_HOME/swarmctl`, else
|
||||
`~/.local/state/swarmctl` (`/root/.local/state/swarmctl` as root). The file is mode 0600
|
||||
in a 0700 directory. If the output isn't what swarmctl expects, it prints the
|
||||
raw output and the file's path, and exits non-zero. The store holds keys
|
||||
then, so keep the output and don't run `bao operator init` again. Once you
|
||||
have recorded the keys, delete the file with `shred -u`; until you do, a
|
||||
second `swarmctl bao init` refuses to run. The root token is never in a
|
||||
process's argument list (so not in `ps`).
|
||||
|
||||
`swarmctl bao init` refuses an initialised store, and works
|
||||
from any host that can reach the store and has `bao` on `PATH`; the
|
||||
wrapper installed on the store host already knows the store's address and CA, and
|
||||
presents a client certificate: the hive's own where a hive runs on that host, else
|
||||
|
|
|
|||
|
|
@ -649,7 +649,7 @@ The forge creates a human's account on their first SSO login, and this fails unt
|
|||
|
||||
Walk through the first-run setup, interactively.
|
||||
|
||||
Run it as root, in a terminal. It checks `docs/1-getting-started/setup.md` first, so a rerun continues at the first open step, then takes the open steps one at a time. It prompts for what a step needs, shows a running action as one live line, and prints anything to record in colour under a ⚠️ warning, such as the secret store's keys and root token. It prints those once and stores none of them. A step that needs a service this host doesn't run names the deploy option to enable and the host to run `swarmctl setup` on. A step without a verb yet prints its command and waits until you confirm you ran it.
|
||||
Run it as root, in a terminal. It checks `docs/1-getting-started/setup.md` first, so a rerun continues at the first open step, then takes the open steps one at a time. It prompts for what a step needs, shows a running action as one live line, and prints anything to record in colour under a ⚠️ warning, such as the secret store's keys and root token. It prints those once; `bao init` also saves the raw output in a 0600 file, whose path it prints. A step that needs a service this host doesn't run names the deploy option to enable and the host to run `swarmctl setup` on. A step without a verb yet prints its command and waits until you confirm you ran it.
|
||||
|
||||
For scripts, use `setup status` and the individual verbs.
|
||||
|
||||
|
|
@ -690,7 +690,7 @@ Exits 0 when every step it can see has finished, and 1 otherwise, including when
|
|||
|
||||
Initialise the swarm's secret store and bootstrap its granter.
|
||||
|
||||
Runs the `bao` CLI against the store over HTTPS, so the store need not run on this host. The root token never reaches a file, an argument list or an environment variable of this process.
|
||||
Runs the `bao` CLI against the store over HTTPS, so the store need not run on this host. The root token never reaches an argument list or an environment variable of this process; `init` saves `bao`'s raw output, which holds it, to one 0600 file.
|
||||
|
||||
**Usage:** `swarmctl bao <COMMAND>`
|
||||
|
||||
|
|
@ -705,7 +705,7 @@ Runs the `bao` CLI against the store over HTTPS, so the store need not run on th
|
|||
|
||||
Initialise the store, printing its keys and the root token once.
|
||||
|
||||
Prints the unseal or recovery keys and the root token to stdout, once, and stores none of them: record them off this host before doing anything else. Refuses an initialised store.
|
||||
Prints the unseal or recovery keys and the root token to stdout, once: record them off this host before doing anything else. Before parsing, it saves `bao`'s raw output to `bao-init.json` in `$XDG_STATE_HOME/swarmctl` (else `~/.local/state/swarmctl`), mode 0600; on output it can't parse it prints the raw output and that path and exits non-zero. Delete the file with `shred -u` once you have recorded the keys. Refuses an initialised store, and refuses to run while the file exists.
|
||||
|
||||
**Usage:** `swarmctl bao init [OPTIONS]`
|
||||
|
||||
|
|
|
|||
|
|
@ -131,6 +131,7 @@ pieces fit, and the reasoning behind them, is in [`credentials.md`](../../2-hand
|
|||
| Grafana's metrics bearer | `swarm-bao-grafana-metrics-bearer.service` creates it in the swarm secret store at `swarm/services/<grafana client id>/metrics/bearer` when the store holds none, then copies it out, **on every host that runs Grafana**. Same grant as the admin password, create without update. To rotate, run `bao kv metadata delete secret/swarm/services/<grafana client id>/metrics/bearer` with a token that may, then `systemctl restart swarm-bao-grafana-metrics-bearer` | `/run/swarm-grafana-secrets/metrics-bearer` on the host's tmpfs, bind-mounted read-only into the `swarm-grafana` container, holding `Bearer <value>`: the metrics datasource's `Authorization` header. The logs datasource sends the same header. `swarm-metrics-auth` on the metrics store's host, and a second instance on the log store's host (`swarm-logs-grafana-auth`), read the stored value themselves, each under its own leaf | same unit, same path. The unit restarts Grafana when the file changes |
|
||||
| Grafana's datasource encryption key | `swarm-bao-grafana-secret-key.service` stores it in the swarm secret store at `swarm/services/<grafana client id>/secret-key` when the store holds none, then copies it out, **on every host that runs Grafana**. It stores the key an earlier release generated at `/var/lib/grafana-secret/secret_key` in the container, so the key doesn't change, and mints a new one only on a host with no such file. Same grant as the admin password, create without update. The earlier file stays on disk, unused once the store holds the key. A store that's down or doesn't grant the leaf fails the unit, and Grafana doesn't start | `/run/swarm-grafana-secrets/secret-key` on the host's tmpfs, bind-mounted read-only into the `swarm-grafana` container: `security.secret_key` | same unit, same path. Grafana doesn't start until the file exists. Changing the key leaves Grafana unable to read the datasource secrets it stored, so never delete the store path to rotate it |
|
||||
| the swarm controller's webhook secret | `swarm-controller` stores it in the swarm secret store at `swarm/controller/swarm-controller/forge/webhook-secret` when the store holds none: the value of `webhook-secret` in its state directory, or a new one when there is no such file. The state directory file stays on disk and is the fallback while the store is unreachable or its policy doesn't grant the path yet | the swarm secret store; the controller holds it in memory and registers the same value with the forge's hooks | nothing to place: the controller's store leaf already exists. A store that stays unreachable on a start with no state directory file leaves the webhook endpoint answering 503 until the store answers: the controller re-reads it in the background, at most five minutes apart, and registers the forge hooks once it has the secret |
|
||||
| the secret store's unseal or recovery keys and root token, as `bao operator init -format=json` printed them | `bao operator init`, run once by `swarmctl bao init` (or `swarmctl setup`) on the host where the operator runs it | `bao-init.json` in swarmctl's state directory (`$XDG_STATE_HOME/swarmctl`, else `~/.local/state/swarmctl`, so `/root/.local/state/swarmctl` for root): file mode 0600 in a 0700 directory, written before swarmctl parses the output, so a parse failure leaves the keys on disk. Nothing reads it. The operator records the keys off the host, then runs `shred -u` on it; while it exists `swarmctl bao init` refuses to run | nothing: the file is on the host that ran `swarmctl bao init`, and no other host needs it |
|
||||
| the metrics store responder's own store leaf (cert + key) | `signLeaf` in `glue-bao-tls.nix` (`swarm-bao-pki.service`), on the host that runs the secret store, once, subject `deploy.bao.metricsAuthCommonName`. `swarm-bao-metrics-auth-policy.service` writes the `swarm-metrics-auth` role and its read grants on the bearer leaf and on the metrics store forwarder's client secret, nothing else | `/var/lib/swarm-bao-pki/metrics-auth.pem` and `metrics-auth-key.pem` on the store's host, handed to `swarm-metrics-auth` through `LoadCredential` (paths in argv, never values) and read by path by `swarm-victoriametrics-forwarder-oidc` | **the operator** places a leaf with that subject on the metrics store's host and names it in `deploy.victoriametrics.authBaoClientCertFile` / `authBaoClientKeyFile`; evaluation fails naming both until then. If the store is on another host, deploy that host first: the role must exist before the responder's login succeeds, and until it does the gateway refuses every Grafana query (fail closed) |
|
||||
| the secret publisher's store leaf (cert + key) | `signLeaf` in `glue-bao-tls.nix` (`swarm-bao-pki.service`), on the host that runs the secret store, once, subject `deploy.bao.secretPublisherCommonName`. `swarm-bao-secret-publisher-policy.service` writes the `swarm-secret-publisher` role: create and update under `swarm/hives/*`, `swarm/services/*` and the controller's client, and read on the `oidc/client` leaves it mints, the controller's client and authelia's five keys alone | `/var/lib/swarm-bao-pki/secret-publisher.pem` and `secret-publisher-key.pem` on the host, handed into authelia's container as nspawn system credentials, which `authelia-swarm-secrets`, `swarm-authelia-bridge` and the forwarder's `swarm-journal-forwarder-oidc` load with `LoadCredential`. nspawn won't start authelia's container while a named file is missing | **the operator** copies the leaf to authelia's host, beside the hive's own store leaf, where `glue-secret-publisher-bao-identity.nix` looks, or names it in `deploy.swarm-secret-publisher.baoClientCertFile` / `baoClientKeyFile` |
|
||||
| the operator's store leaf (cert + key) | `signLeaf` in `glue-bao-tls.nix` (`swarm-bao-pki.service`), on every host that runs the secret store, once, subject `deploy.bao.operatorCommonName`. No cert-auth role accepts that subject, so the leaf opens the TLS handshake and logs in to nothing | `/var/lib/swarm-bao-pki/operator.pem` and `operator-key.pem` on the host, `0600` root; the host's `bao` wrapper presents it when the host runs no hive, via `deploy.bao.operatorClientCertFile` / `operatorClientKeyFile`. A store host from before this leaf has no file until `swarm-bao-pki` next runs, and its wrapper sets no client certificate | nothing to place: the leaf is for the shell on the store's host and is never copied to another host |
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
# docs/1-getting-started/setup.md until the agents are deployed and need a login.
|
||||
#
|
||||
# Steps of setup.md, as the script runs them:
|
||||
# 1 secret store `bao operator init`, the granter bootstrap with the root
|
||||
# 1 secret store `swarmctl bao init`, the granter bootstrap with the root
|
||||
# token, then the policy units reset and restarted.
|
||||
# 4 unseal `bao operator unseal` (`deploy.bao.seal` is "shamir"; pkcs11
|
||||
# needs a TPM). A pkcs11 store unseals itself at init, so here
|
||||
|
|
|
|||
|
|
@ -9,7 +9,8 @@ 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"]
|
||||
INIT = "/root/bao-init.json"
|
||||
# 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.
|
||||
|
|
@ -114,16 +115,36 @@ with subtest("the agents' toplevels are in the store, and the daemon builds noth
|
|||
)
|
||||
|
||||
# setup.md step 1: the secret store.
|
||||
with subtest("step 1: bao operator init"):
|
||||
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"umask 077 && bao operator init -key-shares=1 -key-threshold=1 -format=json > {INIT}"
|
||||
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
|
||||
|
||||
with subtest("step 4: bao operator unseal, with the shamir seal"):
|
||||
machine.succeed(f"bao operator unseal \"$(jq -r '.unseal_keys_b64[0]' {INIT})\"")
|
||||
|
||||
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"):
|
||||
|
|
@ -168,9 +189,7 @@ with subtest("step 1: the policy units that waited for the granter are restarted
|
|||
machine.wait_until_succeeds(
|
||||
'[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=600
|
||||
)
|
||||
machine.succeed(
|
||||
f"bao operator unseal \"$(jq -r '.unseal_keys_b64[0]' {INIT})\""
|
||||
)
|
||||
unseal()
|
||||
settle(POLICY_UNITS_ACTIVE, 1200, "swarm-bao-*-policy")
|
||||
machine.succeed(
|
||||
"journalctl -u swarm-bao-controller-policy --no-pager "
|
||||
|
|
|
|||
|
|
@ -75,9 +75,11 @@ These run the `bao` CLI, so they reach the store over HTTPS wherever it runs;
|
|||
the CLI's own `BAO_ADDR`, `BAO_CACERT` and `BAO_CLIENT_*` say where. The root
|
||||
token is handed to each `bao` child in its own `BAO_TOKEN` environment, which
|
||||
is readable only by root through `/proc`; it is never in an argument list,
|
||||
this process's environment or a file, and error text from `bao` has it
|
||||
replaced before it is shown. `init` prints the keys and the token to stdout
|
||||
once and keeps none; `grant-bootstrap` reads the token from a hidden prompt,
|
||||
this process's environment or an error message, and error text from `bao` has
|
||||
it replaced before it is shown. `init` prints the keys and the token to stdout
|
||||
once, and saves `bao`'s raw output to a 0600 file first (see
|
||||
`docs/1-getting-started/setup.md`), so that a parse failure leaves the keys on
|
||||
disk; `grant-bootstrap` reads the token from a hidden prompt,
|
||||
or from stdin when that is not a terminal. Both wipe the strings from memory
|
||||
when done, on a best-effort basis: the JSON parser and the pipe buffers touch
|
||||
the heap on the way.
|
||||
|
|
|
|||
|
|
@ -7,23 +7,24 @@
|
|||
//! two steps (the token file and the unit restart) are local: they act on the
|
||||
//! host that runs `swarm-bao-granter-role`.
|
||||
//!
|
||||
//! The root token is handled so that it exists in exactly three places: the
|
||||
//! operator's terminal, this process's memory, and the `BAO_TOKEN`
|
||||
//! environment of one `bao` child at a time. It is never in a child's
|
||||
//! argument list (visible to every user through `ps`), never in this
|
||||
//! process's own environment, never in a file, and never in an error
|
||||
//! message. The child's environment is readable only by root through
|
||||
//! `/proc/<pid>/environ`.
|
||||
//! The root token is handled so that it exists in four places: the
|
||||
//! operator's terminal, this process's memory, the `BAO_TOKEN` environment of
|
||||
//! one `bao` child at a time, and the one 0600 file `init` saves `bao`'s raw
|
||||
//! init output to (see [`init_file`]). It is never in a child's argument list
|
||||
//! (visible to every user through `ps`), never in this process's own
|
||||
//! environment, and never in an error message. The child's environment is
|
||||
//! readable only by root through `/proc/<pid>/environ`.
|
||||
|
||||
use std::fs;
|
||||
use std::io::{self, IsTerminal as _, Write as _};
|
||||
use std::path::PathBuf;
|
||||
use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::Args;
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use zeroize::{Zeroize as _, Zeroizing};
|
||||
|
||||
use crate::path_from;
|
||||
|
|
@ -89,6 +90,8 @@ struct Tools {
|
|||
bao: PathBuf,
|
||||
systemctl: PathBuf,
|
||||
unseal_wait: Duration,
|
||||
/// Where `init` saves `bao`'s raw output; [`init_file`] when `None`.
|
||||
init_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl ToolArgs {
|
||||
|
|
@ -97,6 +100,7 @@ impl ToolArgs {
|
|||
bao: self.bao_bin.unwrap_or_else(|| PathBuf::from("bao")),
|
||||
systemctl: PathBuf::from("systemctl"),
|
||||
unseal_wait: UNSEAL_WAIT,
|
||||
init_file: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -179,7 +183,7 @@ impl Bao {
|
|||
|
||||
/// `swarmctl bao init`, minus delivering the secrets.
|
||||
pub(crate) fn init(&self) -> Result<Created> {
|
||||
create_store(&self.tools)
|
||||
create_store(&self.tools, &mut io::stderr().lock())
|
||||
}
|
||||
|
||||
pub(crate) fn wait_unsealed(&self) -> Result<()> {
|
||||
|
|
@ -199,19 +203,28 @@ impl Bao {
|
|||
}
|
||||
|
||||
/// What `bao operator init -format=json` prints, minus the fields not shown.
|
||||
/// Fields it does not name are ignored.
|
||||
///
|
||||
/// A seal that has no keys of one kind prints that field as `null` (a shamir
|
||||
/// seal prints `"recovery_keys_b64": null`), so a missing field and `null`
|
||||
/// both mean no keys.
|
||||
///
|
||||
/// Wiped on drop. The JSON parser and the child's output buffer pass through
|
||||
/// the heap on the way here, so this narrows how long the secrets sit in
|
||||
/// memory; it cannot make it zero.
|
||||
#[derive(Deserialize)]
|
||||
struct InitOutput {
|
||||
#[serde(default)]
|
||||
#[serde(default, deserialize_with = "null_as_empty")]
|
||||
unseal_keys_b64: Vec<String>,
|
||||
#[serde(default)]
|
||||
#[serde(default, deserialize_with = "null_as_empty")]
|
||||
recovery_keys_b64: Vec<String>,
|
||||
root_token: String,
|
||||
}
|
||||
|
||||
fn null_as_empty<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
|
||||
Ok(Option::<Vec<String>>::deserialize(d)?.unwrap_or_default())
|
||||
}
|
||||
|
||||
impl Drop for InitOutput {
|
||||
fn drop(&mut self) {
|
||||
self.unseal_keys_b64.zeroize();
|
||||
|
|
@ -230,24 +243,21 @@ fn initialise(
|
|||
out: &mut impl io::Write,
|
||||
fallback: &mut impl io::Write,
|
||||
) -> Result<Zeroizing<String>> {
|
||||
let created = create_store(tools)?;
|
||||
eprintln!(
|
||||
"Record the keys and the root token below off this host now: swarmctl keeps none of \
|
||||
them and cannot show them again."
|
||||
);
|
||||
let created = create_store(tools, fallback)?;
|
||||
eprintln!("{}", created.notice());
|
||||
if let Err(stdout_err) = write_secrets(out, &created.parsed) {
|
||||
let delivered = write_secrets(fallback, &created.parsed);
|
||||
let saved = created.saved_to.display();
|
||||
return Err(match delivered {
|
||||
Ok(()) => anyhow::anyhow!(
|
||||
"the store is now initialised, but its keys and root token could not be written \
|
||||
to stdout ({stdout_err}); they were written to stderr instead, once: record \
|
||||
them now"
|
||||
to stdout ({stdout_err}); they were written to stderr instead, once, and are \
|
||||
saved in {saved}: record them now"
|
||||
),
|
||||
Err(stderr_err) => anyhow::anyhow!(
|
||||
"the store is now initialised, but its keys and root token could not be \
|
||||
written to stdout ({stdout_err}) or to stderr ({stderr_err}) and are lost; \
|
||||
see OpenBao's `operator rekey` and `operator generate-root` documentation \
|
||||
for what a remaining key holder can recover"
|
||||
written to stdout ({stdout_err}) or to stderr ({stderr_err}); they are saved \
|
||||
in {saved}: record them now"
|
||||
),
|
||||
});
|
||||
}
|
||||
|
|
@ -258,9 +268,26 @@ fn initialise(
|
|||
/// and root token. Wiped on drop, through [`InitOutput`].
|
||||
pub(crate) struct Created {
|
||||
parsed: InitOutput,
|
||||
/// The file holding `bao`'s raw init output, mode 0600.
|
||||
saved_to: PathBuf,
|
||||
}
|
||||
|
||||
impl Created {
|
||||
/// Where the raw output was saved, for the operator to read.
|
||||
pub(crate) fn saved_to(&self) -> &Path {
|
||||
&self.saved_to
|
||||
}
|
||||
|
||||
/// What to tell the operator about the keys and the saved file.
|
||||
fn notice(&self) -> String {
|
||||
let path = self.saved_to.display();
|
||||
format!(
|
||||
"Record the keys and the root token below off this host now. `bao`'s raw init output \
|
||||
is also saved in {path} (readable by its owner only); delete it with `shred -u \
|
||||
{path}` once you have recorded them."
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn root_token(&self) -> Zeroizing<String> {
|
||||
Zeroizing::new(self.parsed.root_token.clone())
|
||||
}
|
||||
|
|
@ -276,10 +303,74 @@ impl Created {
|
|||
}
|
||||
}
|
||||
|
||||
/// Where `bao`'s raw init output is saved: `bao-init.json` in swarmctl's state
|
||||
/// directory, `$XDG_STATE_HOME/swarmctl` or else `~/.local/state/swarmctl`
|
||||
/// (`/root/.local/state/swarmctl` for root). The directory is mode 0700 and the
|
||||
/// file mode 0600.
|
||||
fn init_file() -> Result<PathBuf> {
|
||||
Ok(crate::remote::state_dir()?.join("bao-init.json"))
|
||||
}
|
||||
|
||||
/// Creates the file for the raw init output, refusing one that exists: it
|
||||
/// holds the keys of an earlier init that the operator has not recorded.
|
||||
fn create_init_file(path: &Path) -> Result<fs::File> {
|
||||
if let Some(dir) = path.parent() {
|
||||
fs::DirBuilder::new()
|
||||
.recursive(true)
|
||||
.mode(0o700)
|
||||
.create(dir)
|
||||
.with_context(|| format!("creating {}", dir.display()))?;
|
||||
}
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
.map_err(|e| match e.kind() {
|
||||
io::ErrorKind::AlreadyExists => anyhow::anyhow!(
|
||||
"{} exists: it holds the output of an earlier `bao operator init`. Record what is \
|
||||
in it, run `shred -u {}`, and run this again",
|
||||
path.display(),
|
||||
path.display()
|
||||
),
|
||||
_ => anyhow::anyhow!("creating {}: {e}", path.display()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Prints `raw` to `diag` and builds the error that sends the operator to the
|
||||
/// copy in `saved_to`. For when the store is initialised and its output
|
||||
/// cannot be used.
|
||||
fn keep_raw(
|
||||
diag: &mut impl io::Write,
|
||||
raw: &[u8],
|
||||
saved_to: &Path,
|
||||
problem: &str,
|
||||
saved: bool,
|
||||
) -> anyhow::Error {
|
||||
let _ = writeln!(
|
||||
diag,
|
||||
"The store is initialised. This is `bao operator init`'s output, which holds its keys \
|
||||
and root token; keep it:"
|
||||
);
|
||||
let _ = diag.write_all(raw);
|
||||
let _ = writeln!(diag);
|
||||
let _ = diag.flush();
|
||||
let where_ = if saved {
|
||||
format!("it is also saved in {}", saved_to.display())
|
||||
} else {
|
||||
"it could not be saved to disk".to_owned()
|
||||
};
|
||||
anyhow::anyhow!(
|
||||
"{problem}. The store is initialised and its keys are not lost: the output is printed \
|
||||
above, and {where_}. Keep it, and do not run `bao operator init` again"
|
||||
)
|
||||
}
|
||||
|
||||
/// Runs `bao operator init` against a store that is not initialised yet and
|
||||
/// reads what it printed. Prints nothing: delivering the secrets is the
|
||||
/// caller's.
|
||||
fn create_store(tools: &Tools) -> Result<Created> {
|
||||
/// reads what it printed. The raw output goes to the init file before it is
|
||||
/// parsed, and to `diag` if it cannot be used. Prints nothing else:
|
||||
/// delivering the secrets is the caller's.
|
||||
fn create_store(tools: &Tools, diag: &mut impl io::Write) -> Result<Created> {
|
||||
let status = run(&mut tools.bao_cmd(&["operator", "init", "-status"]))?;
|
||||
match status.status.code() {
|
||||
Some(0) => bail!(
|
||||
|
|
@ -293,23 +384,69 @@ fn create_store(tools: &Tools) -> Result<Created> {
|
|||
),
|
||||
}
|
||||
|
||||
let created = run(&mut tools.bao_cmd(&["operator", "init", "-format=json"]))?;
|
||||
// Created before init runs, so a path that cannot be written is found
|
||||
// while the store can still be initialised.
|
||||
let saved_to = match &tools.init_file {
|
||||
Some(path) => path.clone(),
|
||||
None => init_file()?,
|
||||
};
|
||||
let mut file = create_init_file(&saved_to)?;
|
||||
|
||||
let created = match run(&mut tools.bao_cmd(&["operator", "init", "-format=json"])) {
|
||||
Ok(created) if created.status.success() => created,
|
||||
Ok(created) => {
|
||||
let _ = fs::remove_file(&saved_to);
|
||||
bail!(
|
||||
"`bao operator init` failed: {}",
|
||||
failure_text(&created.stderr, &[])
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = fs::remove_file(&saved_to);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let raw = Zeroizing::new(created.stdout);
|
||||
if !created.status.success() {
|
||||
bail!(
|
||||
"`bao operator init` failed: {}",
|
||||
failure_text(&created.stderr, &[])
|
||||
);
|
||||
let saved = file.write_all(&raw).and_then(|()| file.sync_all());
|
||||
if let Err(e) = saved {
|
||||
return Err(keep_raw(
|
||||
diag,
|
||||
&raw,
|
||||
&saved_to,
|
||||
&format!("could not save the output to {}: {e}", saved_to.display()),
|
||||
false,
|
||||
));
|
||||
}
|
||||
// The parser's own error can quote the value it choked on, so none of it
|
||||
// is passed on.
|
||||
let parsed: InitOutput = serde_json::from_slice(&raw).map_err(|_| {
|
||||
anyhow::anyhow!("`bao operator init` printed output that is not the expected JSON")
|
||||
})?;
|
||||
drop(file);
|
||||
|
||||
// The parser's error can quote the value it choked on, so only its position
|
||||
// goes into the message.
|
||||
let parsed: InitOutput = match serde_json::from_slice(&raw) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(e) => {
|
||||
return Err(keep_raw(
|
||||
diag,
|
||||
&raw,
|
||||
&saved_to,
|
||||
&format!(
|
||||
"`bao operator init` printed output that is not the expected JSON (line {}, column {})",
|
||||
e.line(),
|
||||
e.column()
|
||||
),
|
||||
true,
|
||||
));
|
||||
}
|
||||
};
|
||||
if parsed.unseal_keys_b64.is_empty() && parsed.recovery_keys_b64.is_empty() {
|
||||
bail!("`bao operator init` printed no unseal or recovery keys");
|
||||
return Err(keep_raw(
|
||||
diag,
|
||||
&raw,
|
||||
&saved_to,
|
||||
"`bao operator init` printed no unseal or recovery keys",
|
||||
true,
|
||||
));
|
||||
}
|
||||
Ok(Created { parsed })
|
||||
Ok(Created { parsed, saved_to })
|
||||
}
|
||||
|
||||
fn write_secrets(out: &mut impl io::Write, parsed: &InitOutput) -> io::Result<()> {
|
||||
|
|
@ -595,7 +732,9 @@ echo "ARGV $(basename "$0") $*" >> "$D/log"
|
|||
echo "ENV BAO_TOKEN=${BAO_TOKEN-}" >> "$D/log"
|
||||
case "$(basename "$0") $1 $2 $3" in
|
||||
"bao operator init -status") exit "$(cat "$D/init_status")" ;;
|
||||
"bao operator init -format=json") cat "$D/init.json"; exit 0 ;;
|
||||
"bao operator init -format=json")
|
||||
if [ -e "$D/init_fails" ]; then echo "boom" >&2; exit 1; fi
|
||||
cat "$D/init.json"; exit 0 ;;
|
||||
"bao status "*) exit "$(cat "$D/seal_status")" ;;
|
||||
"bao policy list"*)
|
||||
if [ -e "$D/list_fails" ]; then echo "permission denied for token $BAO_TOKEN" >&2; exit 2; fi
|
||||
|
|
@ -629,6 +768,7 @@ exit 9
|
|||
bao: dir.join("bao"),
|
||||
systemctl: dir.join("systemctl"),
|
||||
unseal_wait: Duration::ZERO,
|
||||
init_file: Some(dir.join("saved").join("bao-init.json")),
|
||||
},
|
||||
paths: GrantPaths {
|
||||
token_file: dir.join("grant.token"),
|
||||
|
|
@ -646,6 +786,10 @@ exit 9
|
|||
fixture
|
||||
}
|
||||
|
||||
fn saved(&self) -> PathBuf {
|
||||
self.tools.init_file.clone().expect("fixture sets it")
|
||||
}
|
||||
|
||||
fn set(&self, name: &str, body: &str) {
|
||||
fs::write(self.dir.join(name), body).expect("write fixture file");
|
||||
}
|
||||
|
|
@ -739,22 +883,148 @@ exit 9
|
|||
assert!(!f.log().contains("-format=json"), "{}", f.log());
|
||||
}
|
||||
|
||||
/// `bao operator init -format=json` as bao 2.6.6 prints it under a shamir
|
||||
/// seal: the same fields in the same order, with `null` for the recovery
|
||||
/// keys. The values are made up.
|
||||
const BAO_2_6_6_SHAMIR: &str = r#"{
|
||||
"unseal_keys_b64": [
|
||||
"UK1b64",
|
||||
"UK2b64"
|
||||
],
|
||||
"unseal_keys_hex": [
|
||||
"01aa",
|
||||
"02bb"
|
||||
],
|
||||
"unseal_shares": 2,
|
||||
"unseal_threshold": 1,
|
||||
"recovery_keys_b64": null,
|
||||
"recovery_keys_hex": null,
|
||||
"recovery_keys_shares": 0,
|
||||
"recovery_keys_threshold": 0,
|
||||
"root_token": "hvs.ROOTTOKEN"
|
||||
}
|
||||
"#;
|
||||
|
||||
/// `InitOutput` with a plain `Vec` per field, which rejects `null`: the control for the 2.6.6 reply.
|
||||
#[derive(Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
struct StrictInitOutput {
|
||||
#[serde(default)]
|
||||
unseal_keys_b64: Vec<String>,
|
||||
#[serde(default)]
|
||||
recovery_keys_b64: Vec<String>,
|
||||
root_token: String,
|
||||
}
|
||||
|
||||
fn mode_of(path: &Path) -> u32 {
|
||||
fs::metadata(path).expect("stat").permissions().mode() & 0o7777
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_init_reply_does_not_leak_its_contents() {
|
||||
let f = Fixture::new("init-garbled");
|
||||
fn init_reads_bao_2_6_6_output_and_saves_it_unchanged() {
|
||||
let f = Fixture::new("init-2-6-6");
|
||||
f.set("init.json", BAO_2_6_6_SHAMIR);
|
||||
// Control: the parser as it was refuses this output.
|
||||
let old = serde_json::from_str::<StrictInitOutput>(BAO_2_6_6_SHAMIR)
|
||||
.err()
|
||||
.expect("the old parser rejects null");
|
||||
assert!(old.to_string().contains("null"), "{old}");
|
||||
|
||||
let mut out = Vec::new();
|
||||
let token = initialise(&f.tools, &mut out, &mut Vec::new()).expect("init succeeds");
|
||||
let out = String::from_utf8(out).expect("utf8");
|
||||
assert_eq!(&*token, ROOT);
|
||||
assert_eq!(
|
||||
out,
|
||||
"Unseal key 1: UK1b64\nUnseal key 2: UK2b64\nInitial root token: hvs.ROOTTOKEN\n"
|
||||
);
|
||||
|
||||
let saved = f.saved();
|
||||
assert_eq!(fs::read_to_string(&saved).expect("read"), BAO_2_6_6_SHAMIR);
|
||||
assert_eq!(mode_of(&saved), 0o600);
|
||||
assert_eq!(mode_of(saved.parent().expect("dir")), 0o700);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_reads_an_auto_unseal_reply_with_null_unseal_keys() {
|
||||
let f = Fixture::new("init-null-unseal");
|
||||
f.set(
|
||||
"init.json",
|
||||
r#"{"unseal_keys_b64":"hvs.LEAKED","root_token":"x"}"#,
|
||||
r#"{"unseal_keys_b64":null,"recovery_keys_b64":["RK1"],"future_field":{"a":1},"root_token":"hvs.ROOTTOKEN"}"#,
|
||||
);
|
||||
let mut out = Vec::new();
|
||||
initialise(&f.tools, &mut out, &mut Vec::new()).expect("init succeeds");
|
||||
assert_eq!(
|
||||
String::from_utf8(out).expect("utf8"),
|
||||
"Recovery key 1: RK1\nInitial root token: hvs.ROOTTOKEN\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_init_reply_is_saved_and_printed_but_not_put_in_the_error() {
|
||||
let f = Fixture::new("init-garbled");
|
||||
let garbage = r#"{"unseal_keys_b64":"hvs.LEAKED","root_token":"x"}"#;
|
||||
f.set("init.json", garbage);
|
||||
// Control: the parser's own error does quote the value.
|
||||
let raw = fs::read(f.dir.join("init.json")).expect("read");
|
||||
let parser = serde_json::from_slice::<InitOutput>(&raw)
|
||||
let parser = serde_json::from_str::<InitOutput>(garbage)
|
||||
.err()
|
||||
.expect("rejects");
|
||||
assert!(parser.to_string().contains("hvs.LEAKED"), "{parser}");
|
||||
|
||||
let mut out = Vec::new();
|
||||
let mut diag = Vec::new();
|
||||
let err = initialise(&f.tools, &mut out, &mut diag).expect_err("must fail");
|
||||
let msg = format!("{err:#}");
|
||||
assert!(!msg.contains("hvs.LEAKED"), "{msg}");
|
||||
let saved = f.saved();
|
||||
assert!(msg.contains(&saved.display().to_string()), "{msg}");
|
||||
assert!(msg.contains("not the expected JSON"), "{msg}");
|
||||
assert!(out.is_empty(), "nothing goes to stdout");
|
||||
let diag = String::from_utf8(diag).expect("utf8");
|
||||
assert!(diag.contains(garbage), "{diag}");
|
||||
assert_eq!(fs::read_to_string(&saved).expect("read"), garbage);
|
||||
assert_eq!(mode_of(&saved), 0o600);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reply_without_keys_is_saved_and_printed() {
|
||||
let f = Fixture::new("init-no-keys");
|
||||
let reply =
|
||||
r#"{"unseal_keys_b64":null,"recovery_keys_b64":null,"root_token":"hvs.ROOTTOKEN"}"#;
|
||||
f.set("init.json", reply);
|
||||
let mut diag = Vec::new();
|
||||
let err = initialise(&f.tools, &mut Vec::new(), &mut diag).expect_err("must fail");
|
||||
assert!(
|
||||
format!("{err:#}").contains("no unseal or recovery keys"),
|
||||
"{err:#}"
|
||||
);
|
||||
assert!(String::from_utf8(diag).expect("utf8").contains(reply));
|
||||
assert_eq!(fs::read_to_string(f.saved()).expect("read"), reply);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_leaves_no_file_when_bao_init_fails() {
|
||||
let f = Fixture::new("init-fails");
|
||||
f.set("init_fails", "");
|
||||
let err = initialise(&f.tools, &mut Vec::new(), &mut Vec::new()).expect_err("must fail");
|
||||
assert!(!format!("{err:#}").contains("hvs.LEAKED"), "{err:#}");
|
||||
assert!(format!("{err:#}").contains("boom"), "{err:#}");
|
||||
assert!(!f.saved().exists(), "an empty keys file would mislead");
|
||||
// Control: the log shows init was attempted.
|
||||
assert!(f.log().contains("-format=json"), "{}", f.log());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_refuses_to_run_over_an_unrecorded_keys_file() {
|
||||
let f = Fixture::new("init-file-exists");
|
||||
fs::create_dir_all(f.saved().parent().expect("dir")).expect("dir");
|
||||
fs::write(f.saved(), "EARLIER").expect("write");
|
||||
let err = initialise(&f.tools, &mut Vec::new(), &mut Vec::new()).expect_err("must refuse");
|
||||
assert!(
|
||||
format!("{err:#}").contains("earlier `bao operator init`"),
|
||||
"{err:#}"
|
||||
);
|
||||
assert!(!f.log().contains("-format=json"), "init ran: {}", f.log());
|
||||
assert_eq!(fs::read_to_string(f.saved()).expect("read"), "EARLIER");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -823,14 +1093,18 @@ exit 9
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn keys_that_neither_stdout_nor_stderr_accept_are_reported_lost() {
|
||||
fn keys_that_neither_stdout_nor_stderr_accept_are_pointed_to_in_the_saved_file() {
|
||||
let f = Fixture::new("both-fail");
|
||||
let err = initialise(&f.tools, &mut Broken, &mut Broken).expect_err("must fail");
|
||||
let text = format!("{err:#}");
|
||||
assert!(text.contains("now initialised"), "{text}");
|
||||
assert!(text.contains("are lost"), "{text}");
|
||||
assert!(text.contains("rekey"), "{text}");
|
||||
assert!(
|
||||
text.contains(&format!("saved in {}", f.saved().display())),
|
||||
"{text}"
|
||||
);
|
||||
assert!(!text.contains(ROOT), "{text}");
|
||||
let saved = fs::read_to_string(f.saved()).expect("read");
|
||||
assert!(saved.contains(ROOT), "the file holds the token: {saved}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1025,6 +1299,7 @@ exit 9
|
|||
bao: f.dir.join("absent"),
|
||||
systemctl: f.tools.systemctl.clone(),
|
||||
unseal_wait: Duration::ZERO,
|
||||
init_file: None,
|
||||
};
|
||||
let err = grant_bootstrap_with(&tools, &f.paths, ROOT).expect_err("must fail");
|
||||
let text = format!("{err:#}");
|
||||
|
|
|
|||
|
|
@ -256,6 +256,8 @@ pub(crate) trait Ui {
|
|||
pub(crate) struct Initialised {
|
||||
/// Each key and the root token on a labelled line.
|
||||
pub(crate) text: Zeroizing<String>,
|
||||
/// The file holding `bao`'s raw init output.
|
||||
pub(crate) saved_to: String,
|
||||
pub(crate) root_token: Zeroizing<String>,
|
||||
}
|
||||
|
||||
|
|
@ -615,9 +617,13 @@ fn init(ui: &mut impl Ui, actions: &mut impl Actions, session: &mut Session) ->
|
|||
Tone::Warn,
|
||||
"⚠️ The unseal or recovery keys and the root token follow.",
|
||||
);
|
||||
ui.say(Tone::Warn, "⚠️ They are shown once.");
|
||||
ui.say(
|
||||
Tone::Warn,
|
||||
"⚠️ They are shown once. swarmctl stores none of them and cannot show them again.",
|
||||
&format!(
|
||||
"⚠️ bao's raw init output is also saved in {}, readable by its owner only. Delete it with `shred -u` once you have recorded the keys.",
|
||||
initialised.saved_to
|
||||
),
|
||||
);
|
||||
ui.say(
|
||||
Tone::Warn,
|
||||
|
|
@ -902,6 +908,7 @@ mod tests {
|
|||
"Recovery key 1: RK1\nInitial root token: hvs.ROOT\n".to_owned(),
|
||||
),
|
||||
root_token: Zeroizing::new("hvs.ROOT".to_owned()),
|
||||
saved_to: "/root/bao-init.json".to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -238,7 +238,8 @@ enum Verb {
|
|||
/// steps one at a time. It prompts for what a step needs, shows a running
|
||||
/// action as one live line, and prints anything to record in colour under a
|
||||
/// ⚠️ warning, such as the secret store's keys and root token. It prints those
|
||||
/// once and stores none of them. A step that needs a service this host
|
||||
/// once; `bao init` also saves the raw output in a 0600 file, whose path it
|
||||
/// prints. A step that needs a service this host
|
||||
/// doesn't run names the deploy option to enable and the host to run
|
||||
/// `swarmctl setup` on. A step without a verb yet prints its command and
|
||||
/// waits until you confirm you ran it.
|
||||
|
|
@ -248,8 +249,9 @@ enum Verb {
|
|||
/// Initialise the swarm's secret store and bootstrap its granter.
|
||||
///
|
||||
/// Runs the `bao` CLI against the store over HTTPS, so the store need
|
||||
/// not run on this host. The root token never reaches a file, an
|
||||
/// argument list or an environment variable of this process.
|
||||
/// not run on this host. The root token never reaches an argument list or an
|
||||
/// environment variable of this process; `init` saves `bao`'s raw output,
|
||||
/// which holds it, to one 0600 file.
|
||||
Bao {
|
||||
#[command(subcommand)]
|
||||
command: BaoVerb,
|
||||
|
|
@ -338,9 +340,13 @@ struct SetupStatusArgs {
|
|||
enum BaoVerb {
|
||||
/// Initialise the store, printing its keys and the root token once.
|
||||
///
|
||||
/// Prints the unseal or recovery keys and the root token to stdout, once,
|
||||
/// and stores none of them: record them off this host before doing
|
||||
/// anything else. Refuses an initialised store.
|
||||
/// Prints the unseal or recovery keys and the root token to stdout, once:
|
||||
/// record them off this host before doing anything else. Before parsing, it
|
||||
/// saves `bao`'s raw output to `bao-init.json` in `$XDG_STATE_HOME/swarmctl`
|
||||
/// (else `~/.local/state/swarmctl`), mode 0600; on output it can't parse it
|
||||
/// prints the raw output and that path and exits non-zero. Delete the file
|
||||
/// with `shred -u` once you have recorded the keys. Refuses an initialised store,
|
||||
/// and refuses to run while the file exists.
|
||||
Init(bao::InitArgs),
|
||||
/// Bootstrap the granter: the one-time step that lets `swarm-bao-granter-role`
|
||||
/// write every `swarm-*` policy and role.
|
||||
|
|
|
|||
|
|
@ -277,6 +277,7 @@ impl Actions for Live {
|
|||
let created = self.bao.init()?;
|
||||
Ok(Initialised {
|
||||
text: created.rendered()?,
|
||||
saved_to: created.saved_to().display().to_string(),
|
||||
root_token: created.root_token(),
|
||||
})
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue