hive-c0re: fail on an unparseable permission file, write it atomically

tool_groups::read and capabilities::read returned an empty map when
their file existed but didn't parse. Every set_*/remove_agent is a
read-modify-write, and write() rewrote the file in place, so a crash or
ENOSPC mid-write left a truncated file, and the next write (e.g. the
manager-spawn seed of ruth's tool groups) replaced it with a map holding
only one agent. The scheduling and approval gates then denied every
other agent, recoverable only from meta git history.

- Both registries now read through agent_config::read_map: a missing
  file is still the empty map, any other read failure or a parse
  failure is an io::Error. set_groups / set_caps / remove_agent fail
  without writing.
- Writes go through agent_config::write_map: temp file in the same
  directory, fsync, rename, fsync the directory. hive-c0re had no
  shared atomic-write helper (the existing tmp+rename sites are inline
  and don't fsync).
- Callers of read / groups_for / has_cap now handle the error:
  * dashboard GET /api/tool-groups, /api/capabilities,
    /api/permissions/stale return 500 instead of an empty table;
  * the SSE permission snapshots are skipped with a warn;
  * render_flake returns Result, so sync_agents fails instead of
    rendering every agent without its tool groups / capabilities;
  * set_nspawn_flags propagates has_cap's error;
  * the socket tool-group gates deny with the read error as message;
  * seed_manager_tool_groups logs and does not seed.
- capabilities::write had no callers left once set_caps writes through
  write_map, and is removed.

Closes #4719
This commit is contained in:
atlas 2026-09-26 02:17:54 +02:00 • committed by mara
commit e0b08fe362
9 changed files with 341 additions and 129 deletions

View file

@ -22,7 +22,7 @@
use hive_sh4re::permissions::Capability; use hive_sh4re::permissions::Capability;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::path::PathBuf; use std::path::{Path, PathBuf};
const CAPABILITIES_FILE: &str = "capabilities.json"; const CAPABILITIES_FILE: &str = "capabilities.json";
@ -61,50 +61,35 @@ fn prune_unknown(map: &mut BTreeMap<String, Vec<String>>) -> bool {
dropped_any dropped_any
} }
/// Read the per-agent capability map. Returns an empty map when the /// Read the per-agent capability map. An absent file is the empty map —
/// file is absent or unparsable — callers treat a missing entry as /// callers treat a missing entry as "no extra capabilities". A file
/// "no extra capabilities". Any entry that isn't a recognised /// that exists but can't be read or parsed is an error. Any entry that
/// [`Capability`] is dropped (with a `warn!`) from what's returned — /// isn't a recognised [`Capability`] is dropped (with a `warn!`) from
/// a stale or typo'd name is never honoured — but `read` itself never /// what's returned — a stale or typo'd name is never honoured — but
/// writes; the on-disk file only gets repaired the next time something /// `read` itself never writes; the on-disk file only gets repaired the
/// calls `write`/`set_caps` anyway. /// next time something calls `set_caps`/`remove_agent` anyway.
#[must_use] pub fn read() -> std::io::Result<BTreeMap<String, Vec<String>>> {
pub fn read() -> BTreeMap<String, Vec<String>> { read_from(&capabilities_path())
let path = capabilities_path(); }
let Ok(raw) = std::fs::read_to_string(&path) else {
return BTreeMap::new(); fn read_from(path: &Path) -> std::io::Result<BTreeMap<String, Vec<String>>> {
}; let mut map = super::read_map(path)?;
let mut map: BTreeMap<String, Vec<String>> = serde_json::from_str(&raw).unwrap_or_default();
prune_unknown(&mut map); prune_unknown(&mut map);
map Ok(map)
} }
/// Look up the configured capabilities for one agent. Returns an empty /// Look up the configured capabilities for one agent. Returns an empty
/// vec when the agent has no entry. /// vec when the agent has no entry. Errors as [`read`] does.
#[must_use] pub fn caps_for(name: &str) -> std::io::Result<Vec<String>> {
pub fn caps_for(name: &str) -> Vec<String> { Ok(read()?.get(name).cloned().unwrap_or_default())
read().get(name).cloned().unwrap_or_default()
} }
/// Check whether an agent holds a specific capability. /// Check whether an agent holds a specific capability. Errors as
#[must_use] /// [`read`] does.
pub fn has_cap(name: &str, cap: hive_sh4re::permissions::Capability) -> bool { pub fn has_cap(name: &str, cap: hive_sh4re::permissions::Capability) -> std::io::Result<bool> {
caps_for(name) Ok(caps_for(name)?
.iter() .iter()
.any(|s| s.eq_ignore_ascii_case(<&str>::from(cap))) .any(|s| s.eq_ignore_ascii_case(<&str>::from(cap))))
}
/// Persist the full capability map. Sorted JSON output keeps diffs
/// minimal. Best-effort — returns `io::Error` so callers decide
/// whether to abort or log.
pub fn write(map: &BTreeMap<String, Vec<String>>) -> std::io::Result<()> {
let path = capabilities_path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let text = serde_json::to_string_pretty(map)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
std::fs::write(&path, format!("{text}\n"))
} }
/// Filter `caps` down to recognised [`Capability`] names (warning per /// Filter `caps` down to recognised [`Capability`] names (warning per
@ -137,20 +122,30 @@ fn apply_known_caps(current: &mut BTreeMap<String, Vec<String>>, name: &str, cap
/// rather than written — an unknown grant should never look like it /// rather than written — an unknown grant should never look like it
/// took effect. An empty `caps` vec, or one that becomes empty after /// took effect. An empty `caps` vec, or one that becomes empty after
/// dropping unknown names, removes the entry (agent has no /// dropping unknown names, removes the entry (agent has no
/// capabilities). /// capabilities). Fails without writing if the existing file can't be
/// read or parsed.
pub fn set_caps(name: &str, caps: &[String]) -> std::io::Result<()> { pub fn set_caps(name: &str, caps: &[String]) -> std::io::Result<()> {
let mut current = read(); set_caps_at(&capabilities_path(), name, caps)
}
fn set_caps_at(path: &Path, name: &str, caps: &[String]) -> std::io::Result<()> {
let mut current = read_from(path)?;
apply_known_caps(&mut current, name, caps); apply_known_caps(&mut current, name, caps);
write(&current) super::write_map(path, &current)
} }
/// Remove an agent from the capability map entirely. Called by /// Remove an agent from the capability map entirely. Called by
/// `meta::sync_agents` when an agent is deprovisioned so stale entries /// `meta::sync_agents` when an agent is deprovisioned so stale entries
/// don't accumulate. No-op if the agent has no entry. /// don't accumulate. No-op if the agent has no entry. Fails without
/// writing if the existing file can't be read or parsed.
pub fn remove_agent(name: &str) -> std::io::Result<()> { pub fn remove_agent(name: &str) -> std::io::Result<()> {
let mut current = read(); remove_agent_at(&capabilities_path(), name)
}
fn remove_agent_at(path: &Path, name: &str) -> std::io::Result<()> {
let mut current = read_from(path)?;
if current.remove(name).is_some() { if current.remove(name).is_some() {
write(&current)?; super::write_map(path, &current)?;
} }
Ok(()) Ok(())
} }
@ -159,11 +154,51 @@ pub fn remove_agent(name: &str) -> std::io::Result<()> {
mod tests { mod tests {
use super::*; use super::*;
// `read`/`write`/`set_caps` shell out to `crate::paths::meta_root`, // `read`/`set_caps`/`remove_agent` shell out to `crate::paths::meta_root`,
// which is hardcoded to `/var/lib/hyperhive` (no test override) — so // which is hardcoded to `/var/lib/hyperhive` (no test override) — so
// these tests pin the pure decision logic (`prune_unknown`, // these tests pin the pure decision logic (`prune_unknown`,
// `apply_known_caps`) directly against in-memory maps rather than // `apply_known_caps`) against in-memory maps, and the file handling
// round-tripping through the real capabilities file. // through the path-taking `*_at` / `read_from` variants.
const TRUNCATED: &str = "{\n \"atlas\": [\"manage_root_ag";
fn corrupt_file() -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(CAPABILITIES_FILE);
std::fs::write(&path, TRUNCATED).expect("seed");
(dir, path)
}
#[test]
fn read_of_a_corrupt_file_is_an_error() {
let (_dir, path) = corrupt_file();
read_from(&path).expect_err("truncated JSON must not read as a map");
}
#[test]
fn set_caps_leaves_a_corrupt_file_untouched() {
let (_dir, path) = corrupt_file();
set_caps_at(&path, "ruth", &["manage_root_agent".to_owned()])
.expect_err("a corrupt file must not be overwritten");
assert_eq!(std::fs::read(&path).expect("read"), TRUNCATED.as_bytes());
}
#[test]
fn remove_agent_leaves_a_corrupt_file_untouched() {
let (_dir, path) = corrupt_file();
remove_agent_at(&path, "atlas").expect_err("a corrupt file must not be overwritten");
assert_eq!(std::fs::read(&path).expect("read"), TRUNCATED.as_bytes());
}
#[test]
fn set_caps_round_trips_through_a_missing_file() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(CAPABILITIES_FILE);
assert!(read_from(&path).expect("missing file is empty").is_empty());
set_caps_at(&path, "ruth", &["manage_root_agent".to_owned()]).expect("set");
let map = read_from(&path).expect("read");
assert_eq!(map["ruth"], vec!["manage_root_agent".to_owned()]);
}
#[test] #[test]
fn prune_unknown_keeps_known_name() { fn prune_unknown_keeps_known_name() {

View file

@ -13,3 +13,91 @@ pub mod limits;
pub mod resource_limits; pub mod resource_limits;
pub mod tool_groups; pub mod tool_groups;
pub mod topology; pub mod topology;
use std::collections::BTreeMap;
use std::io::{self, Write as _};
use std::path::Path;
/// Read a per-agent `name → [string]` JSON map. A missing file is the
/// empty map; any other read failure, or content that doesn't parse, is
/// an error, so a read-modify-write can't write back a map that has lost
/// every other agent's entry.
fn read_map(path: &Path) -> io::Result<BTreeMap<String, Vec<String>>> {
let raw = match std::fs::read_to_string(path) {
Ok(raw) => raw,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
Err(e) => {
return Err(io::Error::new(
e.kind(),
format!("read {}: {e}", path.display()),
));
}
};
serde_json::from_str(&raw).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("parse {}: {e}", path.display()),
)
})
}
/// Serialise `map` as pretty JSON and replace `path` with it atomically:
/// a temp file in the same directory (`rename(2)` is only atomic within a
/// filesystem), fsynced, renamed over `path`, then the directory fsynced
/// so the rename itself survives a crash. A reader sees the old file or
/// the new one, never a truncated one.
fn write_map(path: &Path, map: &BTreeMap<String, Vec<String>>) -> io::Result<()> {
let text = serde_json::to_string_pretty(map)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let (Some(dir), Some(name)) = (path.parent(), path.file_name()) else {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("{} has no parent directory or file name", path.display()),
));
};
std::fs::create_dir_all(dir)?;
let tmp = dir.join(format!(".{}.tmp", name.to_string_lossy()));
let mut file = std::fs::File::create(&tmp)?;
file.write_all(format!("{text}\n").as_bytes())?;
file.sync_all()?;
drop(file);
std::fs::rename(&tmp, path)?;
std::fs::File::open(dir)?.sync_all()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn write_map_round_trips_and_leaves_no_temp_file() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("map.json");
let map = BTreeMap::from([("alice".to_owned(), vec!["messaging".to_owned()])]);
write_map(&path, &map).expect("first write");
let replaced = BTreeMap::from([("bob".to_owned(), vec!["inbox".to_owned()])]);
write_map(&path, &replaced).expect("replacing write");
assert_eq!(read_map(&path).expect("read"), replaced);
let entries: Vec<_> = std::fs::read_dir(dir.path())
.expect("read_dir")
.map(|e| e.expect("entry").file_name())
.collect();
assert_eq!(entries, vec![std::ffi::OsString::from("map.json")]);
}
#[test]
fn read_map_of_a_missing_file_is_empty() {
let dir = tempfile::tempdir().expect("tempdir");
let map = read_map(&dir.path().join("absent.json")).expect("missing file is not an error");
assert!(map.is_empty());
}
#[test]
fn read_map_of_a_truncated_file_is_an_error() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("map.json");
std::fs::write(&path, "{\n \"alice\": [\"messag").expect("seed");
let err = read_map(&path).expect_err("truncated JSON must not read as a map");
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
}

View file

@ -22,7 +22,7 @@
//! that the operator uses to grant/revoke tool groups per agent. //! that the operator uses to grant/revoke tool groups per agent.
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::path::PathBuf; use std::path::{Path, PathBuf};
use anyhow::Context as _; use anyhow::Context as _;
@ -33,37 +33,18 @@ pub fn tool_groups_path() -> PathBuf {
crate::paths::meta_root().join(TOOL_GROUPS_FILE) crate::paths::meta_root().join(TOOL_GROUPS_FILE)
} }
/// Read the per-agent tool-group map. Returns an empty map when the /// Read the per-agent tool-group map. An absent file is the empty map —
/// file is absent or unparsable — callers treat a missing entry as /// callers treat a missing entry as "use role default". A file that
/// "use role default". /// exists but can't be read or parsed is an error.
#[must_use] pub fn read() -> std::io::Result<BTreeMap<String, Vec<String>>> {
pub fn read() -> BTreeMap<String, Vec<String>> { super::read_map(&tool_groups_path())
let path = tool_groups_path();
let Ok(raw) = std::fs::read_to_string(&path) else {
return BTreeMap::new();
};
serde_json::from_str(&raw).unwrap_or_default()
} }
/// Look up the configured tool groups for one agent. Returns an empty /// Look up the configured tool groups for one agent. Returns an empty
/// vec when the agent has no entry — callers should treat this as /// vec when the agent has no entry — callers should treat this as
/// "use the harness role default." /// "use the harness role default." Errors as [`read`] does.
#[must_use] pub fn groups_for(name: &str) -> std::io::Result<Vec<String>> {
pub fn groups_for(name: &str) -> Vec<String> { Ok(read()?.get(name).cloned().unwrap_or_default())
read().get(name).cloned().unwrap_or_default()
}
/// Persist the full tool-groups map. Sorted JSON output keeps diffs
/// minimal. Use `set_groups` (or `remove_agent`) from outside this
/// module — they go through the validated write path.
fn write(map: &BTreeMap<String, Vec<String>>) -> std::io::Result<()> {
let path = tool_groups_path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let text = serde_json::to_string_pretty(map)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
std::fs::write(&path, format!("{text}\n"))
} }
/// Validate a slice of group name strings against `ToolGroup::ALL`. /// Validate a slice of group name strings against `ToolGroup::ALL`.
@ -96,25 +77,76 @@ pub fn validate_groups(groups: &[String]) -> anyhow::Result<()> {
/// Set the tool groups for one agent and persist the map. An empty /// Set the tool groups for one agent and persist the map. An empty
/// `groups` vec removes the entry (agent reverts to role default). /// `groups` vec removes the entry (agent reverts to role default).
/// Returns an error if any name is not in `ToolGroup::ALL`. /// Returns an error if any name is not in `ToolGroup::ALL`, or if the
/// existing file can't be read or parsed — the file is then left
/// untouched.
pub fn set_groups(name: &str, groups: &[String]) -> anyhow::Result<()> { pub fn set_groups(name: &str, groups: &[String]) -> anyhow::Result<()> {
set_groups_at(&tool_groups_path(), name, groups)
}
fn set_groups_at(path: &Path, name: &str, groups: &[String]) -> anyhow::Result<()> {
if !groups.is_empty() { if !groups.is_empty() {
validate_groups(groups)?; validate_groups(groups)?;
} }
let mut current = read(); let mut current = super::read_map(path)?;
if groups.is_empty() { if groups.is_empty() {
current.remove(name); current.remove(name);
} else { } else {
current.insert(name.to_owned(), groups.to_vec()); current.insert(name.to_owned(), groups.to_vec());
} }
write(&current).with_context(|| format!("write tool-groups for {name}")) super::write_map(path, &current).with_context(|| format!("write tool-groups for {name}"))
} }
/// Drop the entry for an agent that is being destroyed. Idempotent. /// Drop the entry for an agent that is being destroyed. Idempotent.
/// Fails without writing if the existing file can't be read or parsed.
pub fn remove_agent(name: &str) -> std::io::Result<()> { pub fn remove_agent(name: &str) -> std::io::Result<()> {
let mut current = read(); remove_agent_at(&tool_groups_path(), name)
}
fn remove_agent_at(path: &Path, name: &str) -> std::io::Result<()> {
let mut current = super::read_map(path)?;
if current.remove(name).is_some() { if current.remove(name).is_some() {
write(&current)?; super::write_map(path, &current)?;
} }
Ok(()) Ok(())
} }
#[cfg(test)]
mod tests {
use super::*;
const TRUNCATED: &str = "{\n \"alice\": [\"messaging\", \"meta\"],\n \"bob\": [\"mess";
fn corrupt_file() -> (tempfile::TempDir, PathBuf) {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(TOOL_GROUPS_FILE);
std::fs::write(&path, TRUNCATED).expect("seed");
(dir, path)
}
#[test]
fn set_groups_leaves_a_corrupt_file_untouched() {
let (_dir, path) = corrupt_file();
set_groups_at(&path, "ruth", &["messaging".to_owned()])
.expect_err("a corrupt file must not be overwritten");
assert_eq!(std::fs::read(&path).expect("read"), TRUNCATED.as_bytes());
}
#[test]
fn remove_agent_leaves_a_corrupt_file_untouched() {
let (_dir, path) = corrupt_file();
remove_agent_at(&path, "alice").expect_err("a corrupt file must not be overwritten");
assert_eq!(std::fs::read(&path).expect("read"), TRUNCATED.as_bytes());
}
#[test]
fn set_groups_keeps_other_agents_entries() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(TOOL_GROUPS_FILE);
set_groups_at(&path, "alice", &["inbox".to_owned()]).expect("set on missing file");
set_groups_at(&path, "ruth", &["messaging".to_owned()]).expect("set");
let map = crate::agent_config::read_map(&path).expect("read");
assert_eq!(map["alice"], vec!["inbox".to_owned()]);
assert_eq!(map["ruth"], vec!["messaging".to_owned()]);
}
}

View file

@ -643,7 +643,15 @@ impl Coordinator {
.iter() .iter()
.map(|c| (<&str>::from(*c), c.description())) .map(|c| (<&str>::from(*c), c.description()))
.collect(); .collect();
let assignments = crate::capabilities::read(); // An empty snapshot would show every agent as having lost its
// capabilities; emit nothing and let the HTTP refetch report it.
let assignments = match crate::capabilities::read() {
Ok(map) => map,
Err(e) => {
tracing::warn!(error = ?e, "capabilities snapshot skipped");
return;
}
};
// Best-effort roster (sync path); on a contended cache miss we // Best-effort roster (sync path); on a contended cache miss we
// emit explicit keys only — the HTTP refetch fills the rest in. // emit explicit keys only — the HTTP refetch fills the rest in.
let roster = self.live_container_names_blocking().unwrap_or_default(); let roster = self.live_container_names_blocking().unwrap_or_default();
@ -670,7 +678,13 @@ impl Coordinator {
.iter() .iter()
.map(|g| (<&str>::from(*g), g.description())) .map(|g| (<&str>::from(*g), g.description()))
.collect(); .collect();
let assignments = crate::tool_groups::read(); let assignments = match crate::tool_groups::read() {
Ok(map) => map,
Err(e) => {
tracing::warn!(error = ?e, "tool-groups snapshot skipped");
return;
}
};
let roster = self.live_container_names_blocking().unwrap_or_default(); let roster = self.live_container_names_blocking().unwrap_or_default();
let (agents, effective) = crate::dashboard::permissions::roster_and_effective( let (agents, effective) = crate::dashboard::permissions::roster_and_effective(
roster, roster,

View file

@ -42,12 +42,15 @@ pub(super) struct ToolGroupsSnapshot {
#[utoipa::path( #[utoipa::path(
get, get,
path = "/api/tool-groups", path = "/api/tool-groups",
responses((status = 200, description = "tool-group catalogue + assignments", body = ToolGroupsSnapshot)), responses(
(status = 200, description = "tool-group catalogue + assignments", body = ToolGroupsSnapshot),
(status = 500, description = "tool-groups file unreadable"),
),
tag = "permissions" tag = "permissions"
)] )]
pub(super) async fn get_tool_groups( pub(super) async fn get_tool_groups(
State(state): State<AppState>, State(state): State<AppState>,
) -> axum::Json<ToolGroupsSnapshot> { ) -> Result<axum::Json<ToolGroupsSnapshot>, ProblemDetails> {
let groups = hive_sh4re::permissions::ToolGroup::ALL let groups = hive_sh4re::permissions::ToolGroup::ALL
.iter() .iter()
.map(|g| <&str>::from(*g)) .map(|g| <&str>::from(*g))
@ -56,7 +59,7 @@ pub(super) async fn get_tool_groups(
.iter() .iter()
.map(|g| (<&str>::from(*g), g.description())) .map(|g| (<&str>::from(*g), g.description()))
.collect(); .collect();
let assignments = crate::tool_groups::read(); let assignments = crate::tool_groups::read().map_err(|e| unreadable(&e))?;
let roster = state let roster = state
.coord .coord
.containers_snapshot() .containers_snapshot()
@ -65,13 +68,20 @@ pub(super) async fn get_tool_groups(
.map(|c| c.name); .map(|c| c.name);
let (agents, effective) = let (agents, effective) =
roster_and_effective(roster, &assignments, &tool_group_default_names()); roster_and_effective(roster, &assignments, &tool_group_default_names());
axum::Json(ToolGroupsSnapshot { Ok(axum::Json(ToolGroupsSnapshot {
groups, groups,
descriptions, descriptions,
assignments, assignments,
agents, agents,
effective, effective,
}) }))
}
/// A permission file that exists but can't be read or parsed. Surfaced
/// as a 500 rather than an empty table, which would read as "nobody has
/// any grants".
fn unreadable(e: &std::io::Error) -> ProblemDetails {
ProblemDetails::from_status_code(StatusCode::INTERNAL_SERVER_ERROR).with_detail(e.to_string())
} }
/// The role-default tool-group names the harness falls back to for an /// The role-default tool-group names the harness falls back to for an
@ -198,19 +208,22 @@ pub(super) struct CapabilitiesSnapshot {
#[utoipa::path( #[utoipa::path(
get, get,
path = "/api/capabilities", path = "/api/capabilities",
responses((status = 200, description = "capability catalogue + assignments", body = CapabilitiesSnapshot)), responses(
(status = 200, description = "capability catalogue + assignments", body = CapabilitiesSnapshot),
(status = 500, description = "capabilities file unreadable"),
),
tag = "permissions" tag = "permissions"
)] )]
pub(super) async fn get_capabilities( pub(super) async fn get_capabilities(
State(state): State<AppState>, State(state): State<AppState>,
) -> axum::Json<CapabilitiesSnapshot> { ) -> Result<axum::Json<CapabilitiesSnapshot>, ProblemDetails> {
use hive_sh4re::permissions::Capability; use hive_sh4re::permissions::Capability;
let caps = Capability::ALL.iter().map(|c| <&str>::from(*c)).collect(); let caps = Capability::ALL.iter().map(|c| <&str>::from(*c)).collect();
let descriptions = Capability::ALL let descriptions = Capability::ALL
.iter() .iter()
.map(|c| (<&str>::from(*c), c.description())) .map(|c| (<&str>::from(*c), c.description()))
.collect(); .collect();
let assignments = crate::capabilities::read(); let assignments = crate::capabilities::read().map_err(|e| unreadable(&e))?;
let roster = state let roster = state
.coord .coord
.containers_snapshot() .containers_snapshot()
@ -219,13 +232,13 @@ pub(super) async fn get_capabilities(
.map(|c| c.name); .map(|c| c.name);
// Capability default is "no extra caps" — empty default slice. // Capability default is "no extra caps" — empty default slice.
let (agents, effective) = roster_and_effective(roster, &assignments, &[]); let (agents, effective) = roster_and_effective(roster, &assignments, &[]);
axum::Json(CapabilitiesSnapshot { Ok(axum::Json(CapabilitiesSnapshot {
caps, caps,
descriptions, descriptions,
assignments, assignments,
agents, agents,
effective, effective,
}) }))
} }
#[derive(Deserialize, ToSchema)] #[derive(Deserialize, ToSchema)]
@ -406,12 +419,15 @@ pub(super) struct StalePermsResponse {
#[utoipa::path( #[utoipa::path(
get, get,
path = "/api/permissions/stale", path = "/api/permissions/stale",
responses((status = 200, description = "ghost agent names with stale permission entries", body = StalePermsResponse)), responses(
(status = 200, description = "ghost agent names with stale permission entries", body = StalePermsResponse),
(status = 500, description = "tool-groups/capabilities file unreadable"),
),
tag = "permissions" tag = "permissions"
)] )]
pub(super) async fn get_stale_permissions( pub(super) async fn get_stale_permissions(
State(state): State<AppState>, State(state): State<AppState>,
) -> axum::Json<StalePermsResponse> { ) -> Result<axum::Json<StalePermsResponse>, ProblemDetails> {
// Live container names — includes stopped-but-configured containers. // Live container names — includes stopped-but-configured containers.
let live: std::collections::HashSet<String> = state let live: std::collections::HashSet<String> = state
.coord .coord
@ -432,8 +448,8 @@ pub(super) async fn get_stale_permissions(
// Known = live roster ∪ kept-state names. // Known = live roster ∪ kept-state names.
let known: std::collections::HashSet<&String> = live.iter().chain(kept.iter()).collect(); let known: std::collections::HashSet<&String> = live.iter().chain(kept.iter()).collect();
// Explicit entries in either JSON file. // Explicit entries in either JSON file.
let caps = crate::capabilities::read(); let caps = crate::capabilities::read().map_err(|e| unreadable(&e))?;
let tgs = crate::tool_groups::read(); let tgs = crate::tool_groups::read().map_err(|e| unreadable(&e))?;
let mut ghost_names: Vec<String> = caps let mut ghost_names: Vec<String> = caps
.keys() .keys()
.chain(tgs.keys()) .chain(tgs.keys())
@ -443,7 +459,7 @@ pub(super) async fn get_stale_permissions(
.into_iter() .into_iter()
.collect(); .collect();
ghost_names.sort(); ghost_names.sort();
axum::Json(StalePermsResponse { stale: ghost_names }) Ok(axum::Json(StalePermsResponse { stale: ghost_names }))
} }
/// Clear all explicit permission entries for a named agent without /// Clear all explicit permission entries for a named agent without

View file

@ -339,7 +339,7 @@ async fn set_nspawn_flags(
// parent field took with it the unconditional grant every // parent field took with it the unconditional grant every
// agent used to get over its own direct children — so an agent with // agent used to get over its own direct children — so an agent with
// no capability now sees its own dirs and nothing else. // no capability now sees its own dirs and nothing else.
if crate::capabilities::has_cap(agent_name, Capability::ManageRootAgent) { if crate::capabilities::has_cap(agent_name, Capability::ManageRootAgent)? {
// Skipping self is a no-op, not a narrowing: `agent_notes_dir` is // Skipping self is a no-op, not a narrowing: `agent_notes_dir` is
// `agent_state_dir/state` and `config_bind_source` is shared, so // `agent_state_dir/state` and `config_bind_source` is shared, so
// binding the holder as its own virtual child reproduced the two // binding the holder as its own virtual child reproduced the two

View file

@ -102,7 +102,7 @@ pub async fn sync_agents(hive: &HiveEnv, agents: &[AgentSpec]) -> Result<()> {
&hive.context_window_tokens, &hive.context_window_tokens,
&hive.agent_memory_max, &hive.agent_memory_max,
agents, agents,
); )?;
let flake_path = dir.join("flake.nix"); let flake_path = dir.join("flake.nix");
let on_disk = std::fs::read_to_string(&flake_path).unwrap_or_default(); let on_disk = std::fs::read_to_string(&flake_path).unwrap_or_default();
let initial = !dir.join(".git").exists(); let initial = !dir.join(".git").exists();
@ -585,7 +585,7 @@ fn render_flake(
context_window_tokens: &std::collections::HashMap<String, u64>, context_window_tokens: &std::collections::HashMap<String, u64>,
hive_memory_max: &str, hive_memory_max: &str,
agents: &[AgentSpec], agents: &[AgentSpec],
) -> String { ) -> Result<String> {
render_flake_with_lookup( render_flake_with_lookup(
hyperhive_flake, hyperhive_flake,
docs_flake, docs_flake,
@ -1000,7 +1000,7 @@ fn render_flake_with_lookup<F>(
hive_memory_max: &str, hive_memory_max: &str,
agents: &[AgentSpec], agents: &[AgentSpec],
lookup: F, lookup: F,
) -> String ) -> Result<String>
where where
F: Fn(&str) -> Vec<&'static str>, F: Fn(&str) -> Vec<&'static str>,
{ {
@ -1316,8 +1316,8 @@ where
nixosConfigurations = { nixosConfigurations = {
"#, "#,
); );
let tool_groups_map = crate::tool_groups::read(); let tool_groups_map = crate::tool_groups::read()?;
let capabilities_map = crate::capabilities::read(); let capabilities_map = crate::capabilities::read()?;
let resource_limits_map = crate::resource_limits::read(); let resource_limits_map = crate::resource_limits::read();
for spec in agents { for spec in agents {
// Emit `toolGroups = "group1,group2"` when the operator has // Emit `toolGroups = "group1,group2"` when the operator has
@ -1370,7 +1370,7 @@ where
); );
} }
out.push_str(" };\n };\n}\n"); out.push_str(" };\n };\n}\n");
out Ok(out)
} }
/// Return the list of file names that are currently staged (index differs /// Return the list of file names that are currently staged (index differs
@ -1671,7 +1671,8 @@ mod tests {
&std::collections::HashMap::new(), &std::collections::HashMap::new(),
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
); )
.expect("render flake");
// nixpkgs is a top-level input with an explicit URL; hyperhive // nixpkgs is a top-level input with an explicit URL; hyperhive
// follows it. // follows it.
assert!( assert!(
@ -1718,7 +1719,8 @@ mod tests {
&std::collections::HashMap::new(), &std::collections::HashMap::new(),
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
); )
.expect("render flake");
assert!( assert!(
!out.contains("hyperhive-docs"), !out.contains("hyperhive-docs"),
"no docs input/source when docs_flake is empty:\n{out}" "no docs input/source when docs_flake is empty:\n{out}"
@ -1737,7 +1739,8 @@ mod tests {
&std::collections::HashMap::new(), &std::collections::HashMap::new(),
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
); )
.expect("render flake");
assert!( assert!(
out.contains(r#"networking.hostName = "h-${name}";"#), out.contains(r#"networking.hostName = "h-${name}";"#),
"an agent container with no hostname of its own is called `nixos`, \ "an agent container with no hostname of its own is called `nixos`, \
@ -1778,7 +1781,8 @@ mod tests {
&std::collections::HashMap::new(), &std::collections::HashMap::new(),
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
); )
.expect("render flake");
assert!( assert!(
out.contains( out.contains(
"services.hyperhive.agent.claudeCodePath = \"/nix/store/cccc-claude-code-2.1.220\";" "services.hyperhive.agent.claudeCodePath = \"/nix/store/cccc-claude-code-2.1.220\";"
@ -1807,7 +1811,8 @@ mod tests {
&std::collections::HashMap::new(), &std::collections::HashMap::new(),
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
); )
.expect("render flake");
assert!( assert!(
!out.contains("claudeCodePath"), !out.contains("claudeCodePath"),
"no claude assignment when unpinned:\n{out}" "no claude assignment when unpinned:\n{out}"
@ -1828,7 +1833,8 @@ mod tests {
&std::collections::HashMap::new(), &std::collections::HashMap::new(),
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
); )
.expect("render flake");
assert!( assert!(
out.contains("nixpkgs.follows = \"hyperhive/nixpkgs\""), out.contains("nixpkgs.follows = \"hyperhive/nixpkgs\""),
"expected fallback follows:\n{out}" "expected fallback follows:\n{out}"
@ -1864,7 +1870,8 @@ mod tests {
sample_spec("dmatrix", false, 9003), sample_spec("dmatrix", false, 9003),
], ],
lookup, lookup,
); )
.expect("render flake");
// bitburner declares nixpkgs → follows emitted. // bitburner declares nixpkgs → follows emitted.
assert!( assert!(
out.contains("agent-bitburner.inputs.nixpkgs.follows = \"nixpkgs\""), out.contains("agent-bitburner.inputs.nixpkgs.follows = \"nixpkgs\""),
@ -1894,7 +1901,8 @@ mod tests {
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
|_| Vec::new(), |_| Vec::new(),
); )
.expect("render flake");
// No agent-side follows when the lookup reports nothing // No agent-side follows when the lookup reports nothing
// declared — protects agents whose flake.lock can't be read // declared — protects agents whose flake.lock can't be read
// (missing / unparsable) from being broken by a follows on a // (missing / unparsable) from being broken by a follows on a
@ -1932,7 +1940,8 @@ mod tests {
&std::collections::HashMap::new(), &std::collections::HashMap::new(),
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
); )
.expect("render flake");
unsafe { unsafe {
std::env::remove_var("HIVE_FORGE_URL"); std::env::remove_var("HIVE_FORGE_URL");
} }
@ -2110,7 +2119,8 @@ mod tests {
&std::collections::HashMap::new(), &std::collections::HashMap::new(),
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
); )
.expect("render flake");
unsafe { unsafe {
std::env::remove_var("HIVE_FORGE_URL"); std::env::remove_var("HIVE_FORGE_URL");
std::env::remove_var("HIVE_MATRIX_URL"); std::env::remove_var("HIVE_MATRIX_URL");
@ -2147,7 +2157,8 @@ mod tests {
&std::collections::HashMap::new(), &std::collections::HashMap::new(),
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
); )
.expect("render flake");
let want = format!( let want = format!(
"agent-alice.url = \"git+file://{}\"", "agent-alice.url = \"git+file://{}\"",
crate::paths::applied_dir("alice").display() crate::paths::applied_dir("alice").display()
@ -2193,6 +2204,7 @@ mod tests {
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
) )
.expect("render flake")
}; };
// A leftover peer-CA file + the env var that used to name it. Both // A leftover peer-CA file + the env var that used to name it. Both
@ -2286,6 +2298,7 @@ mod tests {
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
) )
.expect("render flake")
}; };
unsafe { unsafe {
std::env::remove_var("HYPERHIVE_OTEL_EXTRA_RESOURCE_ATTRIBUTES"); std::env::remove_var("HYPERHIVE_OTEL_EXTRA_RESOURCE_ATTRIBUTES");
@ -2361,6 +2374,7 @@ mod tests {
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
) )
.expect("render flake")
}; };
unsafe { unsafe {
std::env::remove_var("HYPERHIVE_GITHUB_DISABLED"); std::env::remove_var("HYPERHIVE_GITHUB_DISABLED");
@ -2403,7 +2417,8 @@ mod tests {
&std::collections::HashMap::new(), &std::collections::HashMap::new(),
"4G", "4G",
&[sample_spec("alice", false, 9001)], &[sample_spec("alice", false, 9001)],
); )
.expect("render flake");
let want_bytes = 4u64 * 1024 * 1024 * 1024; let want_bytes = 4u64 * 1024 * 1024 * 1024;
assert!( assert!(
out.contains(&format!("memoryMaxBytes = {want_bytes};")), out.contains(&format!("memoryMaxBytes = {want_bytes};")),

View file

@ -598,15 +598,14 @@ async fn dispatch_orchestration(req: &Request, agent: &str, coord: &Arc<Coordina
/// these verbs without any positional/hardcoded privilege. `action` is the /// these verbs without any positional/hardcoded privilege. `action` is the
/// verb phrase for the message. /// verb phrase for the message.
fn require_group(agent: &str, group: &str, action: &str) -> Option<Response> { fn require_group(agent: &str, group: &str, action: &str) -> Option<Response> {
if crate::tool_groups::groups_for(agent) match crate::tool_groups::groups_for(agent) {
.iter() Ok(groups) if groups.iter().any(|g| g == group) => None,
.any(|g| g == group) Ok(_) => Some(Response::Err {
{
None
} else {
Some(Response::Err {
message: format!("agent `{agent}` cannot {action}: requires the `{group}` tool group"), message: format!("agent `{agent}` cannot {action}: requires the `{group}` tool group"),
}) }),
Err(e) => Some(Response::Err {
message: format!("agent `{agent}` cannot {action}: {e}"),
}),
} }
} }
@ -699,6 +698,7 @@ fn handle_cancel_loose_end(
fn check_can_cancel_approval(canceller: &str) -> Result<(), String> { fn check_can_cancel_approval(canceller: &str) -> Result<(), String> {
const APPROVALS_GROUP: &str = "approvals"; const APPROVALS_GROUP: &str = "approvals";
if crate::tool_groups::groups_for(canceller) if crate::tool_groups::groups_for(canceller)
.map_err(|e| format!("cancel_loose_end: {e}"))?
.iter() .iter()
.any(|g| g == APPROVALS_GROUP) .any(|g| g == APPROVALS_GROUP)
{ {

View file

@ -212,11 +212,23 @@ pub async fn ensure_root_agent(coord: &Arc<Coordinator>) -> Result<()> {
/// ///
/// Skips a name that already has an entry: a destroy+recreate under the /// Skips a name that already has an entry: a destroy+recreate under the
/// same name must not silently reset an operator's chosen group set back /// same name must not silently reset an operator's chosen group set back
/// to the default. /// to the default. An unreadable file is logged and left alone: ruth has
/// already been spawned, and seeding stays best-effort like the write
/// below.
fn seed_manager_tool_groups() { fn seed_manager_tool_groups() {
if !tool_groups::groups_for(MANAGER_NAME).is_empty() { match tool_groups::groups_for(MANAGER_NAME) {
tracing::debug!("manager tool groups already set — leaving as-is"); Ok(groups) if groups.is_empty() => {}
return; Ok(_) => {
tracing::debug!("manager tool groups already set — leaving as-is");
return;
}
Err(e) => {
tracing::warn!(
error = ?e,
"tool-groups file unreadable — not seeding ruth's tool groups"
);
return;
}
} }
let all_groups: Vec<String> = hive_sh4re::permissions::ToolGroup::MANAGER_DEFAULT let all_groups: Vec<String> = hive_sh4re::permissions::ToolGroup::MANAGER_DEFAULT
.iter() .iter()
@ -263,7 +275,7 @@ fn should_seed_manager_caps(store_written: bool) -> bool {
/// entry that has been emptied rather than tombstoning it, so "the manager /// entry that has been emptied rather than tombstoning it, so "the manager
/// has no entry" cannot tell a fresh hive apart from a deliberate revoke. /// has no entry" cannot tell a fresh hive apart from a deliberate revoke.
/// File existence can: every grant and revoke goes through /// File existence can: every grant and revoke goes through
/// `meta::commit_capabilities` → `capabilities::set_caps` → `write`, which /// `meta::commit_capabilities` → `capabilities::set_caps`, which
/// writes the file even when the result is an empty `{}`. So while the file /// writes the file even when the result is an empty `{}`. So while the file
/// is absent nobody has ever had a say, and once it exists this is inert /// is absent nobody has ever had a say, and once it exists this is inert
/// forever — including on the destroy+recreate path, matching /// forever — including on the destroy+recreate path, matching