hyperhive/hivectl/src/wg.rs
atlas f108c72f25 hivectl: say which of the three socket failures actually happened
`hivectl open forge` on a host where the daemon is fine and the socket is
fine printed "could not reach the hive-c0re daemon for URLs — is hive-c0re
running?". It was running. The operator was not in `hive-admin` in that
shell, and the connect got EACCES.

The message was a guess, not a diagnosis, because `query_hive_urls`
returned `Option` and threw the cause away with `.ok()`. Three different
failures — not in the group, no socket at all, nobody listening — all
arrived as the same sentence, and only one of the three is fixed by
looking at the daemon.

Classify the connect error in `client::request`, which every
daemon-assisted verb goes through, and keep the io error as the anyhow
cause so the output reads fix-first. EACCES names `hive-admin`,
`services.hyperhive.adminUsers`, and — the part that actually bites — the
re-login, since secondary group membership is only applied at login, so a
shell opened before the grant still cannot connect. ENOENT and
ECONNREFUSED point at the units instead.

Then stop discarding it: `query_hive_urls` returns `Result<Option<_>>`,
`open` and `require_hive_domain` propagate, and `daemon_request` drops its
own "connect to daemon socket" context, which only buried the actionable
line under a vaguer one. `wg init`'s domain lookup stays best-effort by
an explicit `.ok().flatten()` rather than by accident.

Same footgun `agent_exists` was already fixed for: a permission error
collapsed into a value that reads as a different, wrong story.
2026-07-26 17:35:44 +02:00

208 lines
8.7 KiB
Rust

//! `hivectl wg` / `peer-config` — WireGuard mesh helpers: generate this
//! hive's key + the nix snippets to enable the mesh, add a peer, print the
//! block a peer pastes to federate with us, and show the live interface.
use std::path::Path;
use anyhow::{Context as _, Result, bail};
use crate::util::query_hive_urls;
/// Host path of this hive's WireGuard private key (matches the
/// `privateKeyFile` example in the swarm.wireguard nix options).
const WG_KEY_PATH: &str = "/etc/wireguard/hive.key";
/// The mesh interface name hive-c0re's nix module brings up.
const WG_INTERFACE: &str = "wg-hive";
/// Host path of this hive's self-signed CA cert (matches the
/// `services.hyperhive.tls.stateDir` default in hive-tls.nix). Its
/// existence means the gateway serves a self-signed, hive-CA-signed leaf,
/// so a federating peer needs this CA via `swarm.peers.<d>.caCert`. Absent
/// = ACME / operator cert (trusted by the default CA bundle, no `caCert`).
const HIVE_TLS_CA_PATH: &str = "/var/lib/hive-tls/ca.pem";
/// Best-effort query for this hive's domain from the running daemon
/// (`HostRequest::Urls`, which reads `HYPERHIVE_HIVE_DOMAIN` from c0re's
/// service env). `None` when the daemon is unreachable or the domain is
/// unset — for the callers that treat both as "skip the optional block".
/// Use [`require_hive_domain`] where the distinction matters: it keeps the
/// connect error (and its hint) instead of flattening it away.
async fn query_hive_domain(socket: &Path) -> Option<String> {
query_hive_urls(socket).await.ok().flatten()?.domain
}
/// Require this hive's domain from the daemon for snippet generation.
/// Errors with a clear hint when it can't be resolved, so `peer-config`
/// never silently emits a wrong key. An unreachable daemon propagates its
/// own (classified) connect error; only a *reachable* daemon with no domain
/// gets the config hint.
pub(crate) async fn require_hive_domain(socket: &Path) -> Result<String> {
query_hive_urls(socket)
.await
.context("could not determine this hive's domain from the daemon")?
.and_then(|u| u.domain)
.context("the daemon reported no domain — set `services.hyperhive.domain`")
}
/// `wg init` — generate (if absent) the hive's WireGuard key, print its
/// public key + the nix snippet to enable the mesh, then (best-effort)
/// the `peer-config` block peers paste to federate with this hive, so a
/// fresh setup is one command. The domain comes from the daemon; if it
/// can't be resolved, the peer block is skipped (init still succeeds —
/// its core job is enabling the mesh locally).
pub(crate) async fn wg_init(socket: &Path, address: Option<&str>) -> Result<()> {
use std::os::unix::fs::PermissionsExt as _;
let key_path = Path::new(WG_KEY_PATH);
if key_path.exists() {
println!(
"WireGuard private key already present at {WG_KEY_PATH} — reusing (not regenerating)."
);
} else {
if let Some(parent) = key_path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("create {}", parent.display()))?;
std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)).ok();
}
let out = std::process::Command::new("wg")
.arg("genkey")
.output()
.context("run `wg genkey` (is wireguard-tools installed?)")?;
if !out.status.success() {
bail!(
"wg genkey failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
}
std::fs::write(key_path, &out.stdout)
.with_context(|| format!("write {}", key_path.display()))?;
std::fs::set_permissions(key_path, std::fs::Permissions::from_mode(0o400))
.with_context(|| format!("chmod 400 {}", key_path.display()))?;
println!("Generated WireGuard private key at {WG_KEY_PATH} (0400).");
}
let privkey =
std::fs::read(key_path).with_context(|| format!("read {}", key_path.display()))?;
let pubkey = wg_pubkey(&privkey)?;
let addr = address.unwrap_or("<MESH_ADDRESS e.g. 10.42.0.1/32>");
println!("\nPublic key (share this with peer hives — they pass it to `hivectl wg peer`):");
println!(" {pubkey}");
println!("\nAdd to this hive's NixOS config:");
println!(" services.hyperhive.swarm.wireguard = {{");
println!(" enable = true;");
println!(" privateKeyFile = \"{WG_KEY_PATH}\";");
println!(" address = \"{addr}\";");
println!(" # listenPort = 51820; # default");
println!(" }};");
// Also print the block a peer pastes to federate with us (CA + this
// mesh key) — one-stop setup. Domain comes from the daemon;
// best-effort, so init still succeeds when it can't be resolved.
if let Some(d) = query_hive_domain(socket).await {
println!();
peer_config(&d, address, None);
}
Ok(())
}
/// Derive a WireGuard public key from a private key by piping it through
/// `wg pubkey`.
fn wg_pubkey(privkey: &[u8]) -> Result<String> {
use std::io::Write as _;
use std::process::{Command, Stdio};
let mut child = Command::new("wg")
.arg("pubkey")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.context("run `wg pubkey` (is wireguard-tools installed?)")?;
child
.stdin
.take()
.context("wg pubkey: stdin unavailable")?
.write_all(privkey)
.context("write private key to `wg pubkey`")?;
let out = child.wait_with_output().context("wait for `wg pubkey`")?;
if !out.status.success() {
bail!(
"wg pubkey failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
}
/// `wg peer` — print the nix snippet to add a peer hive to the mesh.
/// Pure output (no fallible work), so it returns `()`; the dispatch arm
/// wraps it in `Ok` to match the sibling verbs.
pub(crate) fn wg_peer(domain: &str, pubkey: &str, address: &str, endpoint: Option<&str>) {
println!("Add to this hive's NixOS config:");
println!(" services.hyperhive.swarm.peers.\"{domain}\" = {{");
println!(" wireguardPublicKey = \"{pubkey}\";");
println!(" wireguardAddress = \"{address}\";");
if let Some(ep) = endpoint {
println!(" wireguardEndpoint = \"{ep}\";");
}
println!(" }};");
}
/// `peer-config` — print the `swarm.peers."<domain>"` block a peer
/// operator pastes to federate with THIS hive, plus a `cp` line for the
/// CA when this hive is self-signed. Reads local state only (the TLS CA
/// cert presence + the wg key); prints, never mutates.
pub(crate) fn peer_config(domain: &str, wg_address: Option<&str>, wg_endpoint: Option<&str>) {
let self_signed = Path::new(HIVE_TLS_CA_PATH).exists();
// CA filename derived from the first DNS label so multiple peers'
// certs don't collide in the operator's config dir.
let ca_file = format!("{}-ca.pem", domain.split('.').next().unwrap_or("peer"));
// WireGuard public key, when this hive has a mesh key. Best-effort:
// a missing key or absent `wg` binary just omits the mesh lines.
let wg_pub = std::fs::read(WG_KEY_PATH)
.ok()
.and_then(|k| wg_pubkey(&k).ok());
if self_signed {
println!("# 1. copy this hive's CA cert next to the peer's config:");
println!("cp {HIVE_TLS_CA_PATH} ./{ca_file}");
println!();
println!("# 2. paste into the peer hive's NixOS config:");
} else {
println!("# paste into the peer hive's NixOS config:");
}
println!("services.hyperhive.swarm.peers.\"{domain}\" = {{");
if self_signed {
println!(" caCert = ./{ca_file};");
}
if let Some(pk) = &wg_pub {
println!(" wireguardPublicKey = \"{pk}\";");
}
if let Some(addr) = wg_address {
println!(" wireguardAddress = \"{addr}\";");
}
if let Some(ep) = wg_endpoint {
println!(" wireguardEndpoint = \"{ep}\";");
}
println!("}};");
if !self_signed {
println!(
"# (this hive's cert chains to a public CA — no `caCert` needed; \
it's trusted by the default bundle.)"
);
}
}
/// `wg status` — show the live mesh interface (`wg show wg-hive`),
/// inheriting stdout so the operator sees it directly.
pub(crate) fn wg_status() -> Result<()> {
let status = std::process::Command::new("wg")
.args(["show", WG_INTERFACE])
.status()
.context("run `wg show` (is wireguard-tools installed?)")?;
if !status.success() {
bail!(
"`wg show {WG_INTERFACE}` failed — is the mesh enabled + up? \
(services.hyperhive.swarm.wireguard.enable = true, then deploy)"
);
}
Ok(())
}