Watch
0
0
Fork
You've already forked hyperhive
0

Compare commits

..
9 changed files with 131 additions and 398 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::{Path, PathBuf}; use std::path::PathBuf;
const CAPABILITIES_FILE: &str = "capabilities.json"; const CAPABILITIES_FILE: &str = "capabilities.json";
@ -61,41 +61,50 @@ fn prune_unknown(map: &mut BTreeMap<String, Vec<String>>) -> bool {
dropped_any dropped_any
} }
/// Read the per-agent capability map. An absent file is the empty map — /// Read the per-agent capability map. Returns an empty map when the
/// callers treat a missing entry as "no extra capabilities". A file /// file is absent or unparsable — callers treat a missing entry as
/// that exists but can't be read or parsed is an error. Any entry that /// "no extra capabilities". Any entry that isn't a recognised
/// isn't a recognised [`Capability`] is dropped (with a `warn!`) from /// [`Capability`] is dropped (with a `warn!`) from what's returned —
/// what's returned — a stale or typo'd name is never honoured — but /// a stale or typo'd name is never honoured — but `read` itself never
/// `read` itself never writes. Unknown names stay on disk until the next /// writes; the on-disk file only gets repaired the next time something
/// write: `set_caps` always rewrites the file, `remove_agent` only when /// calls `write`/`set_caps` anyway.
/// the agent had an entry. #[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);
Ok(map) map
} }
/// Look up the configured capabilities for one agent in the file at /// Look up the configured capabilities for one agent. Returns an empty
/// `path` (normally [`capabilities_path`]). Returns an empty vec when /// vec when the agent has no entry.
/// the agent has no entry. Errors as [`read`] does. #[must_use]
pub fn caps_for(path: &Path, name: &str) -> std::io::Result<Vec<String>> { pub fn caps_for(name: &str) -> Vec<String> {
Ok(read_from(path)?.get(name).cloned().unwrap_or_default()) read().get(name).cloned().unwrap_or_default()
} }
/// Check whether an agent holds a specific capability, per the file at /// Check whether an agent holds a specific capability.
/// `path` (normally [`capabilities_path`]). Errors as [`read`] does. #[must_use]
pub fn has_cap( pub fn has_cap(name: &str, cap: hive_sh4re::permissions::Capability) -> bool {
path: &Path, caps_for(name)
name: &str,
cap: hive_sh4re::permissions::Capability,
) -> std::io::Result<bool> {
Ok(caps_for(path, 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
@ -128,30 +137,20 @@ 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). Fails without writing if the existing file can't be /// capabilities).
/// 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<()> {
set_caps_at(&capabilities_path(), name, caps) let mut current = read();
}
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);
super::write_map(path, &current) write(&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. Fails without /// don't accumulate. No-op if the agent has no entry.
/// 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<()> {
remove_agent_at(&capabilities_path(), name) let mut current = read();
}
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() {
super::write_map(path, &current)?; write(&current)?;
} }
Ok(()) Ok(())
} }
@ -160,54 +159,11 @@ fn remove_agent_at(path: &Path, name: &str) -> std::io::Result<()> {
mod tests { mod tests {
use super::*; use super::*;
// `read`/`set_caps`/`remove_agent` call `crate::paths::meta_root`, // `read`/`write`/`set_caps` 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`) against in-memory maps, and the file handling // `apply_known_caps`) directly against in-memory maps rather than
// through the path-taking `*_at` / `read_from` variants. // round-tripping through the real capabilities file.
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();
let err = set_caps_at(&path, "ruth", &["manage_root_agent".to_owned()])
.expect_err("a corrupt file must not be overwritten");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
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();
let err =
remove_agent_at(&path, "atlas").expect_err("a corrupt file must not be overwritten");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
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,91 +13,3 @@ 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::{Path, PathBuf}; use std::path::PathBuf;
use anyhow::Context as _; use anyhow::Context as _;
@ -33,18 +33,37 @@ 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. An absent file is the empty map — /// Read the per-agent tool-group map. Returns an empty map when the
/// callers treat a missing entry as "use role default". A file that /// file is absent or unparsable — callers treat a missing entry as
/// exists but can't be read or parsed is an error. /// "use role default".
pub fn read() -> std::io::Result<BTreeMap<String, Vec<String>>> { #[must_use]
super::read_map(&tool_groups_path()) pub fn read() -> BTreeMap<String, Vec<String>> {
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." Errors as [`read`] does. /// "use the harness role default."
pub fn groups_for(name: &str) -> std::io::Result<Vec<String>> { #[must_use]
Ok(read()?.get(name).cloned().unwrap_or_default()) pub fn groups_for(name: &str) -> Vec<String> {
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`.
@ -77,82 +96,25 @@ 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`, or if the /// Returns an error if any name is not in `ToolGroup::ALL`.
/// 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 = super::read_map(path)?; let mut current = read();
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());
} }
super::write_map(path, &current).with_context(|| format!("write tool-groups for {name}")) write(&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<()> {
remove_agent_at(&tool_groups_path(), name) let mut current = read();
}
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() {
super::write_map(path, &current)?; write(&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();
let err = set_groups_at(&path, "ruth", &["messaging".to_owned()])
.expect_err("a corrupt file must not be overwritten");
let kind = err
.downcast_ref::<std::io::Error>()
.map(std::io::Error::kind);
assert_eq!(kind, Some(std::io::ErrorKind::InvalidData));
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();
let err =
remove_agent_at(&path, "alice").expect_err("a corrupt file must not be overwritten");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
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,15 +643,7 @@ impl Coordinator {
.iter() .iter()
.map(|c| (<&str>::from(*c), c.description())) .map(|c| (<&str>::from(*c), c.description()))
.collect(); .collect();
// An empty snapshot would show every agent as having lost its let assignments = crate::capabilities::read();
// 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();
@ -678,13 +670,7 @@ impl Coordinator {
.iter() .iter()
.map(|g| (<&str>::from(*g), g.description())) .map(|g| (<&str>::from(*g), g.description()))
.collect(); .collect();
let assignments = match crate::tool_groups::read() { let assignments = 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,15 +42,12 @@ pub(super) struct ToolGroupsSnapshot {
#[utoipa::path( #[utoipa::path(
get, get,
path = "/api/tool-groups", path = "/api/tool-groups",
responses( responses((status = 200, description = "tool-group catalogue + assignments", body = ToolGroupsSnapshot)),
(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>,
) -> Result<axum::Json<ToolGroupsSnapshot>, ProblemDetails> { ) -> axum::Json<ToolGroupsSnapshot> {
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))
@ -59,7 +56,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().map_err(|e| unreadable(&e))?; let assignments = crate::tool_groups::read();
let roster = state let roster = state
.coord .coord
.containers_snapshot() .containers_snapshot()
@ -68,20 +65,13 @@ 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());
Ok(axum::Json(ToolGroupsSnapshot { 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
@ -208,22 +198,19 @@ pub(super) struct CapabilitiesSnapshot {
#[utoipa::path( #[utoipa::path(
get, get,
path = "/api/capabilities", path = "/api/capabilities",
responses( responses((status = 200, description = "capability catalogue + assignments", body = CapabilitiesSnapshot)),
(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>,
) -> Result<axum::Json<CapabilitiesSnapshot>, ProblemDetails> { ) -> axum::Json<CapabilitiesSnapshot> {
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().map_err(|e| unreadable(&e))?; let assignments = crate::capabilities::read();
let roster = state let roster = state
.coord .coord
.containers_snapshot() .containers_snapshot()
@ -232,13 +219,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, &[]);
Ok(axum::Json(CapabilitiesSnapshot { axum::Json(CapabilitiesSnapshot {
caps, caps,
descriptions, descriptions,
assignments, assignments,
agents, agents,
effective, effective,
})) })
} }
#[derive(Deserialize, ToSchema)] #[derive(Deserialize, ToSchema)]
@ -419,15 +406,12 @@ pub(super) struct StalePermsResponse {
#[utoipa::path( #[utoipa::path(
get, get,
path = "/api/permissions/stale", path = "/api/permissions/stale",
responses( responses((status = 200, description = "ghost agent names with stale permission entries", body = StalePermsResponse)),
(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>,
) -> Result<axum::Json<StalePermsResponse>, ProblemDetails> { ) -> axum::Json<StalePermsResponse> {
// 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
@ -448,8 +432,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().map_err(|e| unreadable(&e))?; let caps = crate::capabilities::read();
let tgs = crate::tool_groups::read().map_err(|e| unreadable(&e))?; let tgs = crate::tool_groups::read();
let mut ghost_names: Vec<String> = caps let mut ghost_names: Vec<String> = caps
.keys() .keys()
.chain(tgs.keys()) .chain(tgs.keys())
@ -459,7 +443,7 @@ pub(super) async fn get_stale_permissions(
.into_iter() .into_iter()
.collect(); .collect();
ghost_names.sort(); ghost_names.sort();
Ok(axum::Json(StalePermsResponse { stale: ghost_names })) 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

@ -135,24 +135,6 @@ fn bind_child_agent_dirs(child: &str, binds: &mut Vec<BindMount>) {
} }
} }
/// Whether `agent_name` holds `ManageRootAgent` per the capabilities file
/// at `caps_path`. An unreadable file denies: the error is logged and the
/// agent starts without the cross-agent mounts, so one corrupt file never
/// blocks any agent's start, spawn or swap.
fn holds_manage_root_agent(agent_name: &str, caps_path: &Path) -> bool {
crate::capabilities::has_cap(caps_path, agent_name, Capability::ManageRootAgent).unwrap_or_else(
|e| {
tracing::error!(
agent = %agent_name,
path = %caps_path.display(),
error = ?e,
"capabilities unreadable — no ManageRootAgent mounts"
);
false
},
)
}
/// Env var naming the host directory `swarm-bao-queue-agent.service` lands /// Env var naming the host directory `swarm-bao-queue-agent.service` lands
/// this hive's agent queue credential in. Set by the hive-c0re NixOS module /// this hive's agent queue credential in. Set by the hive-c0re NixOS module
/// from `deploy.hive-controller.queue.agentCredentialDir`; absent means this /// from `deploy.hive-controller.queue.agentCredentialDir`; absent means this
@ -357,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 holds_manage_root_agent(agent_name, &crate::capabilities::capabilities_path()) { 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
@ -426,7 +408,7 @@ async fn set_nspawn_flags(
mod tests { mod tests {
use super::{ use super::{
BindMount, QUEUE_CLIENT_ID_CREDENTIAL, QUEUE_SECRET_CREDENTIAL, bind_child_agent_dirs, BindMount, QUEUE_CLIENT_ID_CREDENTIAL, QUEUE_SECRET_CREDENTIAL, bind_child_agent_dirs,
holds_manage_root_agent, queue_agent_credentials, queue_agent_credentials,
}; };
fn child_binds() -> Vec<BindMount> { fn child_binds() -> Vec<BindMount> {
@ -542,23 +524,4 @@ mod tests {
] ]
); );
} }
#[test]
fn a_corrupt_capabilities_file_denies_without_failing() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("capabilities.json");
let truncated = "{\n \"ruth\": [\"manage_root_ag";
std::fs::write(&path, truncated).expect("seed");
assert!(!holds_manage_root_agent("ruth", &path));
assert_eq!(std::fs::read(&path).expect("read"), truncated.as_bytes());
}
#[test]
fn a_readable_grant_is_honoured() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("capabilities.json");
std::fs::write(&path, r#"{"ruth": ["manage_root_agent"]}"#).expect("seed");
assert!(holds_manage_root_agent("ruth", &path));
assert!(!holds_manage_root_agent("alice", &path));
}
} }

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],
) -> Result<String> { ) -> 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,
) -> Result<String> ) -> String
where where
F: Fn(&str) -> Vec<&'static str>, F: Fn(&str) -> Vec<&'static str>,
{ {
@ -1316,11 +1316,8 @@ where
nixosConfigurations = { nixosConfigurations = {
"#, "#,
); );
// Propagated, never read as empty: an agent with no tool-groups entry let tool_groups_map = crate::tool_groups::read();
// renders `toolGroups = null` and gets `AGENT_DEFAULT`, which fails let capabilities_map = crate::capabilities::read();
// open for any agent whose explicit entry is narrower.
let tool_groups_map = crate::tool_groups::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
@ -1373,7 +1370,7 @@ where
); );
} }
out.push_str(" };\n };\n}\n"); out.push_str(" };\n };\n}\n");
Ok(out) 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
@ -1674,8 +1671,7 @@ 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!(
@ -1722,8 +1718,7 @@ 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}"
@ -1742,8 +1737,7 @@ 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`, \
@ -1784,8 +1778,7 @@ 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\";"
@ -1814,8 +1807,7 @@ 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}"
@ -1836,8 +1828,7 @@ 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}"
@ -1873,8 +1864,7 @@ 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\""),
@ -1904,8 +1894,7 @@ 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
@ -1943,8 +1932,7 @@ 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");
} }
@ -2122,8 +2110,7 @@ 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");
@ -2160,8 +2147,7 @@ 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()
@ -2207,7 +2193,6 @@ 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
@ -2301,7 +2286,6 @@ 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");
@ -2377,7 +2361,6 @@ 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");
@ -2420,8 +2403,7 @@ 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,14 +598,15 @@ 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> {
match crate::tool_groups::groups_for(agent) { if crate::tool_groups::groups_for(agent)
Ok(groups) if groups.iter().any(|g| g == group) => None, .iter()
Ok(_) => Some(Response::Err { .any(|g| g == group)
{
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}"),
}),
} }
} }
@ -698,7 +699,6 @@ 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,23 +212,11 @@ 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. An unreadable file is logged and left alone: ruth has /// to the default.
/// already been spawned, and seeding stays best-effort like the write
/// below.
fn seed_manager_tool_groups() { fn seed_manager_tool_groups() {
match tool_groups::groups_for(MANAGER_NAME) { if !tool_groups::groups_for(MANAGER_NAME).is_empty() {
Ok(groups) if groups.is_empty() => {} tracing::debug!("manager tool groups already set — leaving as-is");
Ok(_) => { return;
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()
@ -275,7 +263,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`, which /// `meta::commit_capabilities` → `capabilities::set_caps` → `write`, 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