Watch
0
0
Fork
You've already forked hyperhive
0

grant manage_root_agent by stored permission only, not by the name ruth

Permission::default_for and hive-sh4re's MANAGER_AGENT are gone: every
agent with no permissions key holds Permission::DEFAULT, ruth included.
The agent-name parameters that only fed default_for go with it
(permissions::effective, HiveCopy::before_read/after_read and their
callers).

swarm-controller seeds the grant ruth held by name: at start, a declared
ruth whose permissions are unset gets DEFAULT plus manage_root_agent
written into her key, once, logged. A set key is never touched. It is a
one-shot to delete once every swarm has passed it.

The swarm UI setup assistant opens the create form with
manage_root_agent checked, so a new ruth is created with the grant.
permissions_import no longer adds ruth to the import or splits her
default. Docs and help text no longer say ruth holds the grant by
default; swarmctl-cli.md regenerated.
This commit is contained in:
atlas 2026-10-16 23:10:05 +02:00 • committed by mara
commit 7b5400ecb8
26 changed files with 380 additions and 216 deletions

View file

@ -6,7 +6,7 @@
//! Format: agent name → the stored
//! [`swarm_queue_client::agent_permissions::AgentPermissions`]. An agent with
//! no entry, or an entry with `permissions` unset, holds
//! [`Permission::default_for`]; `"permissions": []` holds none.
//! [`Permission::DEFAULT`]; `"permissions": []` holds none.
//!
//! hive-c0re enforces one member, [`Permission::ManageRootAgent`]: read by
//! `lifecycle::host_config::set_nspawn_flags` on every container start, which
@ -40,12 +40,12 @@ pub fn write_at(path: &Path, stored: &Stored) -> std::io::Result<()> {
super::write_map(path, stored)
}
/// The permissions `agent` holds under `record`.
/// The permissions an agent holds under `record`.
#[must_use]
pub fn effective(agent: &str, record: Option<&AgentPermissions>) -> Vec<Permission> {
pub fn effective(record: Option<&AgentPermissions>) -> Vec<Permission> {
record
.and_then(|r| r.permissions.clone())
.unwrap_or_else(|| Permission::default_for(agent))
.unwrap_or_else(|| Permission::DEFAULT.to_vec())
}
/// Whether `agent` holds `perm` per the file at `path` (normally [`path`]).
@ -54,7 +54,7 @@ pub fn effective(agent: &str, record: Option<&AgentPermissions>) -> Vec<Permissi
///
/// As [`read_at`].
pub fn holds(path: &Path, agent: &str, perm: Permission) -> std::io::Result<bool> {
Ok(effective(agent, read_at(path)?.get(agent)).contains(&perm))
Ok(effective(read_at(path)?.get(agent)).contains(&perm))
}
/// Write `agent`'s [`HiveCopy`] into `runtime_dir`: its entry in the file at
@ -91,25 +91,41 @@ mod tests {
#[test]
fn unset_is_the_default_and_an_empty_list_is_none() {
assert!(effective("ruth", None).contains(&Permission::ManageRootAgent));
assert!(effective("ruth", Some(&record("{}"))).contains(&Permission::ManageRootAgent));
assert!(effective("ruth", Some(&record(r#"{"permissions":[]}"#))).is_empty());
assert_eq!(effective("atlas", None), Permission::DEFAULT.to_vec());
assert_eq!(effective(None), Permission::DEFAULT.to_vec());
assert_eq!(effective(Some(&record("{}"))), Permission::DEFAULT.to_vec());
assert!(effective(Some(&record(r#"{"permissions":[]}"#))).is_empty());
assert_eq!(
effective(
"atlas",
Some(&record(r#"{"permissions":["manage_root_agent"]}"#))
),
effective(Some(&record(r#"{"permissions":["manage_root_agent"]}"#))),
vec![Permission::ManageRootAgent]
);
}
/// No name holds more than the default without an entry: `ruth` with no
/// entry holds `DEFAULT`, and only an entry grants her `manage_root_agent`.
#[test]
fn a_missing_file_holds_the_defaults() {
fn ruth_with_no_entry_holds_the_default() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join(FILE);
assert!(holds(&path, "ruth", Permission::ManageRootAgent).expect("missing is empty"));
assert!(!holds(&path, "atlas", Permission::ManageRootAgent).expect("missing is empty"));
for agent in ["ruth", "atlas"] {
for perm in Permission::ALL {
assert_eq!(
holds(&path, agent, *perm).expect("missing is empty"),
Permission::DEFAULT.contains(perm),
"{agent} {perm:?}"
);
}
}
write_at(
&path,
&Stored::from([(
"ruth".to_owned(),
record(r#"{"permissions":["manage_root_agent"]}"#),
)]),
)
.expect("seed");
assert!(holds(&path, "ruth", Permission::ManageRootAgent).expect("read"));
assert!(!holds(&path, "atlas", Permission::ManageRootAgent).expect("read"));
}
/// With the queue down nothing is read, so the agent starts on the copy
@ -131,7 +147,7 @@ mod tests {
hand_at(&stored, true, "atlas", &runtime).expect("hand");
let copy = HiveCopy::read_at(&runtime.join(HIVE_COPY_FILE));
assert!(copy.import_pending);
assert_eq!(copy.before_read("atlas"), vec![Permission::WebTools]);
assert_eq!(copy.before_read(), vec![Permission::WebTools]);
hand_at(&stored, false, "iris", &runtime).expect("hand");
let copy = HiveCopy::read_at(&runtime.join(HIVE_COPY_FILE));

View file

@ -866,11 +866,10 @@ impl Coordinator {
/// --continue's session). Best-effort; broker errors are logged
/// but don't propagate.
pub fn kick_agent(&self, name: &str, reason: &str) {
// Sub-agents bind their state at /agents/<name>/state. The
// manager has both /state (legacy mount) and /agents
// bind-mounted, so /agents/<name>/state resolves there too —
// use that uniformly so the wake message has one canonical
// path that works everywhere.
// Every agent binds its state at /agents/<name>/state, and a
// `manage_root_agent` holder has all of /agents bind-mounted, so
// the path resolves there too — use that uniformly so the wake
// message has one canonical path that works everywhere.
let body = format!(
"{reason}\n\nYou were just (re)started by the operator. \
If you were mid-task, check `/agents/{name}/state/` for \

View file

@ -843,13 +843,13 @@ mod tests {
assert_eq!(std::fs::read(&path).expect("read"), truncated.as_bytes());
}
/// Unset is the default, which gives ruth the recovery mounts and nobody
/// else; a grant or an explicit empty list replaces it.
/// Unset is the default, which gives nobody the recovery mounts, `ruth`
/// included; only a grant does.
#[test]
fn the_swarm_grant_or_the_default_decides_the_recovery_mounts() {
fn the_swarm_grant_decides_the_recovery_mounts() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("swarm-agent-permissions.json");
assert!(holds_manage_root_agent("ruth", &path));
assert!(!holds_manage_root_agent("ruth", &path));
assert!(!holds_manage_root_agent("alice", &path));
std::fs::write(
&path,

View file

@ -11,10 +11,9 @@
//! only if it cannot be expressed as convergence, and expect to delete
//! it once every hive has passed it.
//! - **Create-time setup.** A thing that is true from birth is set where
//! the agent is created, not re-asserted each morning. Ruth's
//! permissions need neither: with no key in the swarm's
//! `agent-permissions` bucket she holds the code-constant default
//! (`Permission::default_for`).
//! the agent is created, not re-asserted each morning: ruth's
//! `manage_root_agent`, for one, is stored in the swarm's
//! `agent-permissions` bucket when the swarm UI creates her.
//!
//! Kill-switch: `HIVE_SKIP_META_MIGRATION=1`. Full sequence and phase
//! details: `docs/agent-lifecycle/config-changes.md::Startup migrations (older hosts)`.

View file

@ -1,10 +1,8 @@
//! Publishing lifecycle notices onto the swarm queue.
//!
//! Replaces the old `push_todo(MANAGER_AGENT, ...)` fallback the
//! lifecycle-notice call sites used to reach for when there was nobody
//! else to tell. Every hive is swarm-controlled now, so there is no case
//! left that needs a manager-agent recipient — this module has no such
//! fallback, on purpose, not by omission.
//! There is no fallback recipient agent: every hive is swarm-controlled,
//! so a notice always goes to the swarm queue, and no agent receives it by
//! name.
//!
//! **Why a stream and not the [`crate::swarm_status`] KV bucket shape**:
//! a status snapshot has a current value a late reader can always ask

View file

@ -54,27 +54,17 @@ fn parse(agent: &str, name: &str) -> Option<Permission> {
/// only unknown names, was the default groups. `lifecycle`/`forge` count as
/// known (they parsed) and are then dropped, so an entry of only those
/// held no tools and imports as none.
/// - capabilities: the entry's names. With the file present, `ruth` having no
/// entry means her grant was revoked: the file was created holding it, and
/// a revoke removed the entry. With no file, the default.
/// - capabilities: the entry's names; no entry, or no file, is none.
///
/// An agent whose list equals [`Permission::default_for`] is left out, so its
/// key stays unset and follows the default.
/// An agent whose list equals [`Permission::DEFAULT`] is left out, so its key
/// stays unset and follows the default.
fn grants(caps: Option<&FileMap>, groups: Option<&FileMap>) -> Grants {
let mut agents: BTreeSet<&str> = BTreeSet::new();
agents.extend(caps.iter().flat_map(|m| m.keys().map(String::as_str)));
agents.extend(groups.iter().flat_map(|m| m.keys().map(String::as_str)));
if caps.is_some() {
agents.insert(crate::lifecycle::MANAGER_NAME);
}
let default = Permission::DEFAULT;
let mut out = Grants::new();
for agent in agents {
let default = Permission::default_for(agent);
let tool_default: Vec<Permission> = default
.iter()
.copied()
.filter(|p| *p != Permission::ManageRootAgent)
.collect();
let tool_part = match groups.and_then(|m| m.get(agent)) {
Some(names)
if names.iter().any(|n| {
@ -84,19 +74,12 @@ fn grants(caps: Option<&FileMap>, groups: Option<&FileMap>) -> Grants {
{
names.iter().filter_map(|n| parse(agent, n)).collect()
}
_ => tool_default,
};
let cap_part: Vec<Permission> = match caps {
Some(m) => m
.get(agent)
.map(|names| names.iter().filter_map(|n| parse(agent, n)).collect())
.unwrap_or_default(),
None => default
.iter()
.copied()
.filter(|p| *p == Permission::ManageRootAgent)
.collect(),
_ => default.to_vec(),
};
let cap_part: Vec<Permission> = caps
.and_then(|m| m.get(agent))
.map(|names| names.iter().filter_map(|n| parse(agent, n)).collect())
.unwrap_or_default();
let mut list: Vec<Permission> = Vec::new();
for perm in tool_part.into_iter().chain(cap_part) {
if !list.contains(&perm) {
@ -275,24 +258,15 @@ mod tests {
"sock": ["lifecycle"]}"#,
);
let out = grants(Some(&caps), Some(&groups));
assert!(!out.contains_key("ruth"), "ruth's seed is her default");
assert_eq!(
out["ruth"],
vec![Messaging, Meta, Inbox, Execution, ManageRootAgent]
);
assert_eq!(out["atlas"], vec![Messaging, WebTools, ManageRootAgent]);
assert_eq!(out["iris"], vec![Messaging]);
assert_eq!(out["sock"], Vec::<Permission>::new());
}
/// Without a capabilities entry, ruth's existing file means a revoke; with
/// no capabilities file at all, her default stands.
#[test]
fn a_revoked_ruth_stays_revoked() {
let out = grants(Some(&file("{}")), None);
assert_eq!(out["ruth"], vec![Messaging, Meta, Inbox, Execution]);
let out = grants(None, Some(&file(r#"{"atlas": ["messaging"]}"#)));
assert!(!out.contains_key("ruth"));
assert_eq!(out["atlas"], vec![Messaging]);
}
/// The seed writes once, from the files, and never over a stored read.
#[test]
fn the_seed_copies_the_files_only_when_nothing_is_stored() {

View file

@ -155,7 +155,7 @@ async fn hand_all() {
/// Whether `agent` holds the one permission hive-c0re enforces under `stored`.
fn manages(agent: &str, stored: &Stored) -> bool {
permissions::effective(agent, stored.get(agent)).contains(&Permission::ManageRootAgent)
permissions::effective(stored.get(agent)).contains(&Permission::ManageRootAgent)
}
/// Restart each running agent in `changed` once its current turn is done, so
@ -216,7 +216,7 @@ mod tests {
assert!(changed.is_empty());
assert!(crate::permissions::read_at(&path).expect("read").is_empty());
assert!(
crate::permissions::holds(
!crate::permissions::holds(
&path,
"ruth",
hive_sh4re::permissions::Permission::ManageRootAgent
@ -225,33 +225,22 @@ mod tests {
);
}
/// Revoking ruth's default, and granting atlas, restarts both; clearing
/// them again restarts both back.
/// Granting `manage_root_agent` to agents on the default restarts them;
/// clearing it again restarts them back.
#[tokio::test]
async fn a_changed_manage_root_agent_asks_for_a_restart() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("p.json");
let changed = sync(&path, |agent| {
Ok(Read::Current(record(if agent == "ruth" {
r#"{"permissions":[]}"#
} else {
r#"{"permissions":["manage_root_agent"]}"#
})))
})
.await
.expect("read");
let granted = || {
Ok(Read::Current(record(
r#"{"permissions":["manage_root_agent"]}"#,
)))
};
let changed = sync(&path, |_| granted()).await.expect("read");
assert_eq!(changed, agents());
// The same answer again changes nothing.
let unchanged = sync(&path, |agent| {
Ok(Read::Current(record(if agent == "ruth" {
r#"{"permissions":[]}"#
} else {
r#"{"permissions":["manage_root_agent"]}"#
})))
})
.await
.expect("read");
let unchanged = sync(&path, |_| granted()).await.expect("read");
assert!(unchanged.is_empty());
let cleared = sync(&path, |_| Ok(Read::Current(AgentPermissions::default())))
@ -268,7 +257,7 @@ mod tests {
let path = dir.path().join("p.json");
let changed = sync(&path, |agent| {
Ok(Read::Current(if agent == "ruth" {
record(r#"{"permissions":["manage_root_agent"]}"#)
record(r#"{"permissions":["meta"]}"#)
} else {
record(r#"{"permissions":["messaging","web_tools"]}"#)
}))
@ -289,10 +278,16 @@ mod tests {
async fn a_failed_read_keeps_the_last_value() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("p.json");
let revoked = || Ok(Read::Current(record(r#"{"permissions":[]}"#)));
// atlas holds no manage_root_agent either way, so only ruth changes.
// atlas stays on the default, so only ruth changes.
let ruth_granted = |agent: &str| {
Ok(Read::Current(record(if agent == "ruth" {
r#"{"permissions":["manage_root_agent"]}"#
} else {
"{}"
})))
};
assert_eq!(
sync(&path, |_| revoked()).await.expect("read"),
sync(&path, ruth_granted).await.expect("read"),
vec!["ruth".to_owned()]
);
let before = std::fs::read(&path).expect("stored");