//! Minimal privileged helper for hive-c0re. //! //! Runs as root. Exposes a narrow unix socket at `/run/hive/priv.sock` //! that accepts `PrivRequest` JSON lines and executes only the //! operations that genuinely require root. All coordination logic, //! broker, HTTP, and scheduling stay in the unprivileged hive-c0re //! process. //! //! **Security model**: every request is validated against a strict //! container-name allowlist before any filesystem or process operation. //! Only containers whose names match the hive convention (`h-*`, //! the manager container, or known sibling service containers) are //! accepted. Every variant maps to a single known operation — no //! arbitrary command pass-through. //! //! **Socket activation**: when systemd passes the listener socket via //! `LISTEN_FDS=1` + `LISTEN_PID=`, the inherited fd 3 is used //! instead of binding a fresh socket. use std::path::{Path, PathBuf}; use anyhow::{Context as _, Result, bail}; use hive_priv_sock::{ AGENT_PREFIX, AGENT_RUNTIME_ROOT, AGENT_STATE_ROOT, BindMount, CredentialMount, InfraAction, InfraContainer, JournalQuery, META_DIR, MIGRATE_STAGING_ROOT, NetworkIsolation, PAUSED_MARKER_FILE, PRIV_SOCK, PrivEvent, PrivRequest, PrivResponse, PrivStream, PrivStreamLine, SIBLING_CONTAINERS, }; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::net::unix::OwnedWriteHalf; use tokio::net::{UnixListener, UnixStream}; use tokio::process::Command; /// Root of the per-agent unix-socket dirs on the host. const SOCKET_DIR_ROOT: &str = "/run/hive-agent"; #[tokio::main] async fn main() -> Result<()> { tracing_subscriber::fmt() .with_env_filter( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), ) .init(); let listener = socket_listener()?; tracing::info!("hive-priv listening"); loop { match listener.accept().await { Ok((stream, _)) => { tokio::spawn(handle(stream)); } Err(e) => { tracing::error!(error = %e, "accept failed"); } } } } fn socket_listener() -> Result { // hive-priv is ALWAYS socket-activated by the `hive-priv.socket` unit // (fd 3 via LISTEN_FDS). There is intentionally no self-bind fallback, // so dev and prod take the same path; see docs/boundary.md. let listen_fds: Option = std::env::var("LISTEN_FDS") .ok() .and_then(|s| s.parse().ok()); let listen_pid: Option = std::env::var("LISTEN_PID") .ok() .and_then(|s| s.parse().ok()); let activated = matches!(listen_fds, Some(n) if n >= 1) && listen_pid == Some(std::process::id()); if !activated { bail!( "hive-priv requires systemd socket activation (expected LISTEN_FDS>=1 + \ LISTEN_PID= for {PRIV_SOCK}); run it via the hive-priv.socket unit, \ not directly" ); } // SAFETY: systemd has passed us a ready UnixListener on fd 3. let std_listener = unsafe { use std::os::unix::io::FromRawFd; std::os::unix::net::UnixListener::from_raw_fd(3) }; std_listener .set_nonblocking(true) .context("set socket non-blocking")?; let listener = tokio::net::UnixListener::from_std(std_listener).context("wrap systemd socket")?; tracing::info!("using systemd-activated socket"); Ok(listener) } async fn handle(stream: UnixStream) { let (reader, mut writer) = stream.into_split(); let mut lines = BufReader::new(reader).lines(); while let Ok(Some(line)) = lines.next_line().await { let resp = dispatch(&line, &mut writer).await; // Write the terminal PrivResponse as a PrivEvent::Done. Wire-identical // to a bare PrivResponse (untagged), so old hive-c0re callers that // deserialise directly to PrivResponse continue to work. let event = PrivEvent::Done(resp); let mut json = serde_json::to_string(&event).unwrap_or_else(|e| { format!("{{\"ok\":false,\"stdout\":\"\",\"stderr\":\"\",\"error\":\"serialise failed: {e}\"}}") }); json.push('\n'); if let Err(e) = writer.write_all(json.as_bytes()).await { tracing::warn!(error = %e, "write response failed"); break; } } } async fn dispatch(line: &str, writer: &mut OwnedWriteHalf) -> PrivResponse { match serde_json::from_str::(line) { Ok(req) => match exec(req, writer).await { Ok((stdout, stderr)) => PrivResponse { ok: true, stdout, stderr, error: None, }, Err(e) => PrivResponse { ok: false, stdout: String::new(), stderr: String::new(), error: Some(format!("{e:#}")), }, }, Err(e) => PrivResponse { ok: false, stdout: String::new(), stderr: String::new(), error: Some(format!("parse request: {e}")), }, } } /// Write one `PrivEvent::Line` to the client. Best-effort: a write /// failure is logged but doesn't abort the running subprocess. async fn write_line_event(writer: &mut OwnedWriteHalf, stream: PrivStream, data: &str) { let event = PrivEvent::Line(PrivStreamLine { stream, data: data.to_owned(), }); if let Ok(mut json) = serde_json::to_string(&event) { json.push('\n'); if let Err(e) = writer.write_all(json.as_bytes()).await { tracing::warn!(error = %e, "write_line_event: write failed"); } } } /// Execute a validated `PrivRequest`. Returns `(stdout, stderr)` on success. /// For streaming ops (`CreateContainer`/`UpdateContainer` with `stream: true`) /// output lines are forwarded to `writer` as `PrivEvent::Line` messages and /// the returned strings are empty. // One match arm per priv op — a flat 1:1 dispatch table. The length tracks // the op count, not complexity; splitting it would just scatter the mapping. #[allow(clippy::too_many_lines)] async fn exec(req: PrivRequest, writer: &mut OwnedWriteHalf) -> Result<(String, String)> { match req { PrivRequest::StartContainer { ref name } => { validate_container_name(name)?; let machine = container_system_name(name); // Clear any start-limit lockout left by earlier failures so a // now-correct start isn't blocked. nixos-container start does not // do this itself. Best-effort: if the unit doesn't exist yet // (first-time create) reset-failed is a no-op and we proceed. let _ = Command::new("systemctl") .args(["reset-failed", &format!("container@{machine}.service")]) .status() .await; container_run(&["start", &machine]).await } PrivRequest::StopContainer { ref name } => { validate_container_name(name)?; stop_and_release(&container_system_name(name)).await } PrivRequest::KillContainer { ref name } => { validate_container_name(name)?; // nixos-container has no kill verb. Use machinectl to send SIGKILL // to all processes in the container — the right semantics for a // forced shutdown after a graceful stop has already been attempted. let machine = container_system_name(name); machinectl_run(&["kill", &machine, "--signal=SIGKILL"]).await } PrivRequest::UpdateContainer { ref name, stream } => { container_flake_action("update", name, stream, writer).await } PrivRequest::CreateContainer { ref name, stream } => { container_flake_action("create", name, stream, writer).await } PrivRequest::DestroyContainer { ref name } => { validate_container_name(name)?; container_run(&["destroy", &container_system_name(name)]).await } PrivRequest::ListContainers => container_run(&["list"]).await, PrivRequest::ReadContainerJournal { ref container, ref query, } => { validate_container_system_name(container)?; read_container_journal(container, query).await } PrivRequest::WriteNspawnFlags { ref container, ref binds, ref isolation, ref load_credentials, } => handle_write_nspawn_flags(container, binds, isolation.as_ref(), load_credentials), PrivRequest::WriteResourceLimits { ref container, ref memory_max, ref cpu_quota, cpu_weight, io_weight, } => write_resource_limits(container, memory_max, cpu_quota, cpu_weight, io_weight), PrivRequest::RemoveServiceDropin { ref container } => remove_service_dropin(container), PrivRequest::DaemonReload => daemon_reload().await, PrivRequest::ReloadGatewayNginx => sync_gateway_nginx().await, PrivRequest::ChownSocketDir { ref agent_name, uid, gid, } => chown_socket_dir(agent_name, uid, gid), PrivRequest::ChmodSocketDir { ref agent_name, mode, } => chmod_socket_dir(agent_name, mode), PrivRequest::RunForgeAdmin { ref args } => { for arg in args { validate_forge_admin_arg(arg)?; } run_forge_admin(args).await } PrivRequest::SetAgentPaused { ref agent_name, paused, } => { validate_agent_name(agent_name)?; set_agent_paused(agent_name, paused) } PrivRequest::WriteAgentForgeToken { ref agent_name, ref token, } => { validate_agent_name(agent_name)?; write_agent_state_file(agent_name, "forge-token", &format!("{token}\n")) } PrivRequest::WriteAgentMatrixToken { ref agent_name, ref token, ref account, ref homeserver, } => { validate_agent_name(agent_name)?; // Build the token filename. `None` → the hive account's // `matrix-token`; `Some(a)` → `matrix-token-`. The account // suffix MUST be validated as a plain identifier (no `/`, `.`, // `..`) before it goes into the filename, or a crafted account // could traverse out of the state dir — `write_agent_state_file` // trusts its `filename` argument. let filename = match account { None => "matrix-token".to_owned(), Some(a) => { validate_name_chars(a)?; format!("matrix-token-{a}") } }; let res = write_agent_state_file(agent_name, &filename, &format!("{token}\n"))?; // For an extra account, persist its homeserver in a sidecar // (`matrix-account-.json`) so the daemon can auto-discover the // account without a static `matrixAccounts` config entry. Only // when both `account` and `homeserver` are present; the account // suffix is already validated above. if let (Some(a), Some(hs)) = (account, homeserver) { let meta = serde_json::json!({ "homeserver": hs }).to_string(); write_agent_state_file(agent_name, &format!("matrix-account-{a}.json"), &meta)?; } Ok(res) } PrivRequest::WriteAgentGithubToken { ref agent_name, ref token, } => { validate_agent_name(agent_name)?; write_agent_state_file(agent_name, "github-token", &format!("{token}\n")) } PrivRequest::WriteAgentExtraForgeAccount { ref agent_name, ref label, ref base_url, ref token, } => { validate_agent_name(agent_name)?; validate_name_chars(label)?; let res = write_agent_state_file( agent_name, &format!("forge-{label}-token"), &format!("{token}\n"), )?; // Sidecar carries the base URL — there's no host-side nix config // for extra forges, so this is the only place it's persisted. let meta = serde_json::json!({ "base_url": base_url }).to_string(); write_agent_state_file(agent_name, &format!("forge-{label}.json"), &meta)?; Ok(res) } PrivRequest::DeleteAgentExtraForgeAccount { ref agent_name, ref label, } => { validate_agent_name(agent_name)?; validate_name_chars(label)?; delete_agent_state_file(agent_name, &format!("forge-{label}-token"))?; delete_agent_state_file(agent_name, &format!("forge-{label}.json")) } PrivRequest::RestartMatrixDaemon { ref agent_name } => { restart_matrix_daemon(agent_name).await } PrivRequest::RegisterCiRunner { ref token } => register_ci_runner(token).await, PrivRequest::ControlInfraContainer { container, action } => { control_infra_container(container, action).await } PrivRequest::EnsureAgentSubvolume { ref agent_name } => { validate_agent_name(agent_name)?; ensure_agent_subvolume(agent_name).await } PrivRequest::DeleteAgentSubvolume { ref agent_name } => { validate_agent_name(agent_name)?; delete_agent_subvolume(agent_name).await } PrivRequest::EnsureBtrfsQuota => ensure_btrfs_quota().await, PrivRequest::ReadSubvolumeUsage { ref agent_name } => { validate_agent_name(agent_name)?; read_subvolume_usage(agent_name).await } PrivRequest::SetSubvolumeQuota { ref agent_name, limit_bytes, } => { validate_agent_name(agent_name)?; set_subvolume_quota(agent_name, limit_bytes).await } PrivRequest::UpgradeAgentSubvolume { ref agent_name } => { validate_agent_name(agent_name)?; upgrade_agent_subvolume(agent_name).await } PrivRequest::SnapshotAgentSubvolume { ref agent_name, ref snapshot_name, } => { validate_agent_name(agent_name)?; validate_snapshot_name(snapshot_name)?; snapshot_agent_subvolume(agent_name, snapshot_name).await } PrivRequest::DeleteAgentSnapshot { ref agent_name, ref snapshot_name, } => { validate_agent_name(agent_name)?; validate_snapshot_name(snapshot_name)?; delete_agent_snapshot(agent_name, snapshot_name).await } PrivRequest::SendAgentSnapshotToFile { ref agent_name, ref snapshot_name, ref parent_snapshot_name, ref dest_file_name, } => { validate_agent_name(agent_name)?; validate_snapshot_name(snapshot_name)?; if let Some(parent) = parent_snapshot_name { validate_snapshot_name(parent)?; } validate_credential_name(dest_file_name)?; send_agent_snapshot_to_file( agent_name, snapshot_name, parent_snapshot_name.as_deref(), dest_file_name, ) .await } PrivRequest::SyncAgentTmpfiles { ref agents } => sync_agent_tmpfiles(agents).await, } } /// Shared body for `CreateContainer` / `UpdateContainer`: validate the /// name, build the `nixos-container … --flake ` argv, and /// run it (streaming line events to `writer` when `stream` is set). async fn container_flake_action( verb: &str, name: &str, stream: bool, writer: &mut OwnedWriteHalf, ) -> Result<(String, String)> { validate_container_name(name)?; let flake_ref = agent_flake_ref(name); let args = [verb, &container_system_name(name), "--flake", &flake_ref]; if stream { container_run_streaming(&args, writer).await } else { container_run(&args).await } } /// `WriteNspawnFlags` — validate the container + every bind path + every /// credential entry, then write the container's nspawn flag overrides. fn handle_write_nspawn_flags( container: &str, binds: &[BindMount], isolation: Option<&NetworkIsolation>, load_credentials: &[CredentialMount], ) -> Result<(String, String)> { validate_container_system_name(container)?; for bind in binds { validate_bind_path(&bind.host_path)?; validate_bind_path(&bind.container_path)?; } for cred in load_credentials { validate_credential_name(&cred.name)?; // Same path rules as binds (absolute, no colon/newline/quote/null): // the colon ban is essential since `--load-credential=name:path` // uses `:` as the name/path separator. validate_bind_path(&cred.host_path)?; } write_nspawn_flags(container, binds, isolation, load_credentials)?; Ok((String::new(), String::new())) } /// A btrfs snapshot label must start with `hive-` — this doubles as an /// allow-list: only names hivectl itself constructs (or an operator who /// knows the convention) can reach the `btrfs subvolume snapshot`/`delete` /// shellouts, so an arbitrary caller can't use the snapshot ops to probe or /// churn unrelated paths under `AGENT_STATE_ROOT`. Beyond the prefix, the /// same charset restriction as [`validate_credential_name`] applies (it's /// interpolated straight into a filesystem path). fn validate_snapshot_name(name: &str) -> Result<()> { if !name.starts_with("hive-") { bail!("invalid snapshot label {name:?}: must start with \"hive-\""); } validate_credential_name(name) } /// A systemd credential id must be a short token — restrict to /// `[A-Za-z0-9_-]` (no `.`) so it can't inject extra `--load-credential` /// argv or break the `name:path` shape. `.` is deliberately excluded, not /// just a bare `..`: this name gets interpolated into filesystem paths /// (snapshot labels) and there's no legitimate need for a dot in either a /// systemd credential id or a `hive-`-prefixed snapshot label — we're /// defining this token format from scratch, so keep it maximally strict /// rather than allow-then-patch each traversal-adjacent character /// (mara: "we are making up the rules here, lets go strict"). fn validate_credential_name(name: &str) -> Result<()> { if name.is_empty() || !name .bytes() .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-')) { bail!("invalid credential name {name:?}: must be non-empty [A-Za-z0-9_-]"); } Ok(()) } /// `RemoveServiceDropin` — remove the container service's drop-in dir /// if present (idempotent). fn remove_service_dropin(container: &str) -> Result<(String, String)> { validate_container_system_name(container)?; let dir = format!("/run/systemd/system/container@{container}.service.d"); if Path::new(&dir).exists() { std::fs::remove_dir_all(&dir).with_context(|| format!("remove {dir}"))?; } Ok((String::new(), String::new())) } /// `ChownSocketDir` — chown the agent's host socket dir to its /// container uid/gid. fn chown_socket_dir(agent_name: &str, uid: u32, gid: u32) -> Result<(String, String)> { validate_agent_name(agent_name)?; let path = socket_dir_path(agent_name); std::os::unix::fs::chown(&path, Some(uid), Some(gid)) .with_context(|| format!("chown {} to {uid}:{gid}", path.display()))?; Ok((String::new(), String::new())) } /// `ChmodSocketDir` — set the mode on the agent's host socket dir. fn chmod_socket_dir(agent_name: &str, mode: u32) -> Result<(String, String)> { use std::os::unix::fs::PermissionsExt as _; validate_agent_name(agent_name)?; let path = socket_dir_path(agent_name); std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)) .with_context(|| format!("chmod {:o} {}", mode, path.display()))?; Ok((String::new(), String::new())) } /// `WriteResourceLimits` — drop the systemd resource settings into the /// container service's drop-in dir, together with a /// `ConditionPathIsDirectory=` guard on the agent's MCP runtime dir. /// /// Two different kinds of setting land in the same file. `MemoryMax=` / /// `CPUQuota=` are hard caps that throttle even on an idle host; /// `CPUWeight=` / `IOWeight=` are cgroup v2 relative shares that only /// decide who yields *under contention*. A zero weight means "not /// configured" (`None`) and omits the line, so a hive-c0re built before the /// weights existed keeps producing the old two-line drop-in. /// /// The condition causes systemd to *skip* (not *fail*) the unit when the /// bind-mount source dir is absent — result is `condition`, which does not /// increment the start-limit counter. This is belt-and-braces on top of /// the tmpfiles.d entries written by `SyncAgentTmpfiles`: in the unlikely /// event the dir is missing at start time, the unit idles rather than /// restart-looping into `start-limit-hit`. fn write_resource_limits( container: &str, memory_max: &str, cpu_quota: &str, cpu_weight: Option, io_weight: Option, ) -> Result<(String, String)> { validate_container_system_name(container)?; // Derive the logical agent name (strip h- prefix) to form the runtime // dir path. Falls back to the full container name for infra containers // that don't use the h- prefix. let logical = container.strip_prefix(AGENT_PREFIX).unwrap_or(container); let runtime_dir = format!("{AGENT_RUNTIME_ROOT}/{logical}"); let dir = format!("/run/systemd/system/container@{container}.service.d"); std::fs::create_dir_all(&dir).with_context(|| format!("create {dir}"))?; let path = format!("{dir}/hyperhive-limits.conf"); let content = limits_dropin_body(&runtime_dir, memory_max, cpu_quota, cpu_weight, io_weight); std::fs::write(&path, content).with_context(|| format!("write {path}"))?; Ok((String::new(), String::new())) } /// Render the body of `hyperhive-limits.conf`. /// /// `[Unit]`: the condition is checked at start time — it skips (not fails) /// the unit when the MCP socket dir is absent, avoiding restart loops. /// `[Service]`: the hard caps first, then the relative weights. A weight of /// `None` means "not configured" and omits its line entirely, so a request /// from a hive-c0re built before the weights existed — or one whose nix /// option is `null` — reproduces the old two-setting drop-in byte for byte. fn limits_dropin_body( runtime_dir: &str, memory_max: &str, cpu_quota: &str, cpu_weight: Option, io_weight: Option, ) -> String { // Built as two possibly-empty lines rather than pushed onto the // string: `format!` appended to a `String` trips clippy::pedantic's // `format_push_string`, and a `write!` would need an unwrap. let cpu_weight_line = cpu_weight.map_or_else(String::new, |w| format!("CPUWeight={w}\n")); let io_weight_line = io_weight.map_or_else(String::new, |w| format!("IOWeight={w}\n")); format!( "[Unit]\n\ ConditionPathIsDirectory={runtime_dir}\n\ \n\ [Service]\n\ MemoryMax={memory_max}\n\ CPUQuota={cpu_quota}\n\ {cpu_weight_line}{io_weight_line}" ) } /// `DaemonReload` — `systemctl daemon-reload` on the host. async fn daemon_reload() -> Result<(String, String)> { let out = Command::new("systemctl") .arg("daemon-reload") .output() .await .context("invoke systemctl daemon-reload")?; if !out.status.success() { bail!( "systemctl daemon-reload failed ({}): {}", out.status, String::from_utf8_lossy(&out.stderr).trim() ); } Ok((String::new(), String::new())) } /// `RestartMatrixDaemon` — restart the matrix daemon unit inside the /// agent's container. async fn restart_matrix_daemon(agent_name: &str) -> Result<(String, String)> { validate_agent_name(agent_name)?; let machine = format!("--machine=h-{agent_name}"); let unit = "hive-matrix-daemon.service"; let out = Command::new("systemctl") .args([&machine, "restart", unit]) .output() .await .with_context(|| format!("systemctl restart {unit} in container h-{agent_name}"))?; if !out.status.success() { bail!( "systemctl restart {unit} in h-{agent_name} exited {}: {}", out.status, String::from_utf8_lossy(&out.stderr).trim() ); } Ok(( String::from_utf8_lossy(&out.stdout).into_owned(), String::from_utf8_lossy(&out.stderr).into_owned(), )) } /// `RegisterCiRunner` — write the runner registration token to the host-side /// `/run/hive-ci/runner-token` env-file, then restart the in-container runner /// so it re-registers. The forge admin token never enters the container; only /// the registration token c0re passes here is written, and it lands on a host /// path bind-mounted read-only into hive-ci. async fn register_ci_runner(token: &str) -> Result<(String, String)> { use std::os::unix::fs::PermissionsExt as _; // Reject anything that could corrupt the `KEY=VALUE` env-file or smuggle a // second line — a forge registration token is an opaque single-line string. if token.is_empty() || token.contains(['\n', '\r', '\0']) { bail!("ci runner registration token empty or contains control characters"); } let token_path = "/run/hive-ci/runner-token"; // In-place truncate+write of the existing inode (mirrors the prefetch's // `echo > $FILE`), NOT a temp+rename: nspawn pins this file's inode into // hive-ci at container start, so a rename would leave the running runner // reading the old content. Format + perms match the tmpfiles seed and the // prefetch: `TOKEN=`, mode 0600, root-owned. std::fs::write(token_path, format!("TOKEN={token}\n")) .with_context(|| format!("write {token_path}"))?; std::fs::set_permissions(token_path, std::fs::Permissions::from_mode(0o600)) .with_context(|| format!("chmod {token_path}"))?; // Restart the in-container runner so it reads the new token and registers. let out = Command::new("systemctl") .args(["--machine=hive-ci", "restart", "gitea-runner-hive.service"]) .output() .await .context("systemctl restart gitea-runner-hive.service in hive-ci")?; if !out.status.success() { bail!( "systemctl restart gitea-runner-hive.service in hive-ci exited {}: {}", out.status, String::from_utf8_lossy(&out.stderr).trim() ); } Ok(( String::from_utf8_lossy(&out.stdout).into_owned(), String::from_utf8_lossy(&out.stderr).into_owned(), )) } /// `ControlInfraContainer` — start/stop/restart a hive infrastructure /// container via `systemctl container@.service`. The /// [`InfraContainer`] enum is the allowlist: serde already rejected any /// unknown / unsafe name (hive-c0re has no variant, so a stop can't sever /// the daemon socket) at deserialisation, so no root-side `.contains()` /// check is needed here. Serves both the hive-wide `hivectl stop`/`start` /// flow and an `infra_admin` agent's `restart` (action = Restart). async fn control_infra_container( container: InfraContainer, action: InfraAction, ) -> Result<(String, String)> { let verb = action.systemctl_verb(); let unit = format!("container@{}.service", container.unit_name()); let out = Command::new("systemctl") .args([verb, &unit]) .output() .await .with_context(|| format!("systemctl {verb} {unit}"))?; if !out.status.success() { bail!( "systemctl {verb} {unit} exited {}: {}", out.status, String::from_utf8_lossy(&out.stderr).trim() ); } tracing::info!(target: "infra-control", "{verb} {unit}"); Ok(( String::from_utf8_lossy(&out.stdout).into_owned(), String::from_utf8_lossy(&out.stderr).into_owned(), )) } /// Create/overwrite `dir/filename` at 0600 without following a symlink at the /// leaf, returning the open fd for the caller to `fchown`. `filename` must be a /// single plain component (no `/`, `.`, `..`) — the leaf sits in an /// agent-writable dir, so `O_NOFOLLOW` refuses a planted symlink (`ELOOP`) /// instead of letting this root-privileged write/chmod be redirected at another /// file; `O_WRONLY` refuses a directory leaf (`EISDIR`); `O_TRUNC` keeps the /// overwrite semantics for an existing regular file. `.mode(0o600)` sets the /// create mode; the explicit `fchmod` after (on the fd, not a re-resolved path) /// tightens an already-existing file and dodges umask. The returned fd is the /// exact inode the write hit, so the caller's `fchown` is TOCTOU-immune. fn write_state_file_nofollow(dir: &Path, filename: &str, content: &str) -> Result { use std::io::Write as _; use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _}; if filename.is_empty() || filename == "." || filename == ".." || filename.contains('/') { bail!("write_state_file_nofollow: refusing non-plain filename {filename:?}"); } let path = dir.join(filename); let mut file = std::fs::OpenOptions::new() .write(true) .create(true) .truncate(true) .mode(0o600) .custom_flags(libc::O_NOFOLLOW) .open(&path) .with_context(|| format!("open (no-follow) {}", path.display()))?; file.write_all(content.as_bytes()) .with_context(|| format!("write {}", path.display()))?; file.set_permissions(std::fs::Permissions::from_mode(0o600)) .with_context(|| format!("chmod 600 {}", path.display()))?; Ok(file) } /// Shared helper for `WriteAgentForgeToken` and `WriteAgentMatrixToken`. /// Writes `content` to `AGENT_STATE_ROOT//state/`, /// chowns to the agent user (derived from the state dir's existing owner), /// and chmods 0600. Running as root (hive-priv), so this succeeds /// regardless of the file's prior owner/permissions. fn write_agent_state_file( agent_name: &str, filename: &str, content: &str, ) -> Result<(String, String)> { let state_dir = PathBuf::from(AGENT_STATE_ROOT) .join(agent_name) .join("state"); write_agent_dir_file(agent_name, &state_dir, filename, content) } /// Create or remove an agent's pause marker under its harness dir. The /// marker is written empty and chowned to the harness dir's owner (the /// agent), matching how the harness itself would have created it. /// /// Both directions are idempotent: re-pausing truncates the existing empty /// marker rather than failing, and a `NotFound` on removal is the /// already-resumed case, not an error. fn set_agent_paused(agent_name: &str, paused: bool) -> Result<(String, String)> { let harness_dir = PathBuf::from(AGENT_STATE_ROOT) .join(agent_name) .join("harness"); if paused { return write_agent_dir_file(agent_name, &harness_dir, PAUSED_MARKER_FILE, ""); } remove_marker_in(&harness_dir, PAUSED_MARKER_FILE)?; tracing::info!(agent = %agent_name, "cleared pause marker"); Ok((String::new(), String::new())) } /// Unlink `dir/filename`, treating "already gone" as success. /// /// `remove_file` unlinks the leaf itself and never follows a symlink, so an /// agent-planted link at the marker path cannot redirect this root unlink /// at another file — the same threat `write_state_file_nofollow` closes on /// the create side. fn remove_marker_in(dir: &Path, filename: &str) -> Result<()> { let path = dir.join(filename); match std::fs::remove_file(&path) { Ok(()) => Ok(()), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(e) => Err(e).with_context(|| format!("remove {}", path.display())), } } /// Write `content` to `dir/filename` as root, chowning the result to `dir`'s /// owner so the agent process can read it back. Shared by the credential /// writes (which target `state/`) and the pause marker (which targets /// `harness/`) — both write into a directory owned by the agent, which is /// precisely why they need hive-priv at all. fn write_agent_dir_file( agent_name: &str, dir: &Path, filename: &str, content: &str, ) -> Result<(String, String)> { use std::os::fd::AsRawFd as _; use std::os::unix::fs::MetadataExt as _; let state_dir = dir.to_path_buf(); // NOTE: `create_dir_all` is normally a no-op — lifecycle creates and chowns // the state dir during spawn. On the rare edge where the dir doesn't exist // yet (container being provisioned for the first time), the newly created dir // is root:root. The `stat state_dir` chown below will then see uid=0 and // leave the file root-owned (0600). The agent won't be able to read it until // its lifecycle completes. If that happens, a `systemctl restart hive-c0re` // after provisioning will re-mint and re-write the token correctly. std::fs::create_dir_all(&state_dir) .with_context(|| format!("create state dir {}", state_dir.display()))?; // Security-critical: refuses a symlink the (state/-owning) agent may have // planted at the leaf, so this root-privileged create/write/chmod/chown // can't be redirected at an arbitrary file. See `write_state_file_nofollow`. let path = state_dir.join(filename); let file = write_state_file_nofollow(&state_dir, filename, content)?; // Chown to the state dir's owner so the agent process can read the file. // fchown on the same fd — TOCTOU-immune (the inode the write hit, never a // swapped path). If stat fails (e.g. dir just created, owner is root), the // file stays root-owned and 0600 — still unreadable by others, just not // agent-readable. Log a warning so operators can diagnose. match std::fs::metadata(&state_dir) { Ok(meta) => { // SAFETY: `file` is an open, owned fd live for the whole call; // `fchown` only mutates that inode's uid/gid. let rc = unsafe { libc::fchown(file.as_raw_fd(), meta.uid(), meta.gid()) }; if rc != 0 { let e = std::io::Error::last_os_error(); tracing::warn!( agent = %agent_name, path = %path.display(), error = %e, "write_agent_state_file: fchown failed" ); } } Err(e) => { tracing::warn!( agent = %agent_name, error = %e, "write_agent_state_file: stat state_dir failed, leaving file root-owned" ); } } tracing::info!( agent = %agent_name, dir = %state_dir.display(), file = %filename, "wrote agent file" ); Ok((String::new(), String::new())) } /// Remove `AGENT_STATE_ROOT//state/` if present. /// Idempotent revoke counterpart to [`write_agent_state_file`] — a /// missing file is success, not an error. `filename` must be a single /// plain component (no `/`, `.`, `..`); callers pass a pre-validated /// label into a fixed `forge-