Watch
0
0
Fork
You've already forked hyperhive
0

swarmctl bao init: save bao's raw output before parsing, and accept null key lists

This commit is contained in:
atlas 2026-11-24 15:35:57 +01:00
commit 870a0a6697
5 changed files with 395 additions and 73 deletions

View file

@ -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.

View file

@ -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:#}");

View file

@ -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(),
})
}

View file

@ -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.

View file

@ -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(),
})
}