Watch
0
0
Fork
You've already forked hyperhive
0

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

@ -13,3 +13,91 @@ pub mod limits;
pub mod resource_limits;
pub mod tool_groups;
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);
}
}