Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/swarmctl/src/permissions.rs

156 lines
5.1 KiB
Rust

//! `swarmctl agent permissions` — the permissions the swarm grants one
//! agent, through swarm-controller's `/api/agents/{name}/permissions` routes.
//!
//! The agent applies its tool permissions at its next turn; the hive running
//! it restarts it, after its current turn, when `manage_root_agent` changes.
//! Unset leaves the agent on the default set; an empty list grants nothing.
//!
//! The body comes from `swarm-controller-api`, which the controller imports
//! too. A name that is not a permission fails before the request.
use anyhow::{Context as _, Result};
use hive_types::Permission;
use swarm_controller_api::permissions::Permissions;
use crate::agent::{parse_ident, send};
use crate::remote::Target;
fn runtime() -> Result<tokio::runtime::Runtime> {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.context("starting a tokio runtime for the controller request")
}
/// The agent's permissions path. The name is checked first, so it cannot
/// reshape the URI.
fn member(agent: &str) -> Result<String> {
let agent = parse_ident(agent, "agent name")?;
Ok(format!("/api/agents/{agent}/permissions"))
}
/// Run `swarmctl agent permissions get`.
pub(crate) fn get(target: &Target, agent: &str) -> Result<()> {
let uri = member(agent)?;
let stored: Permissions = runtime()?.block_on(send(
target,
hyper::Method::GET,
&uri,
None::<&()>,
"permissions-get",
))?;
print!("{}", render(&stored));
Ok(())
}
/// Run `swarmctl agent permissions set`: store the given permissions, which
/// replace the agent's record whole.
pub(crate) fn set(target: &Target, agent: &str, permissions: &[String]) -> Result<()> {
let uri = member(agent)?;
let wanted = with_permissions(permissions)?;
let stored: Permissions = runtime()?.block_on(send(
target,
hyper::Method::PUT,
&uri,
Some(&wanted),
"permissions-set",
))?;
print!("{}", render(&stored));
Ok(())
}
/// The record granting `permissions`. An empty name, as `--permissions ''`
/// gives, is dropped, so that spelling grants nothing.
fn with_permissions(permissions: &[String]) -> Result<Permissions> {
let granted = permissions
.iter()
.filter(|name| !name.is_empty())
.map(|name| parse_permission(name))
.collect::<Result<Vec<_>>>()?;
Ok(Permissions {
permissions: Some(granted),
})
}
/// The permission `name` spells, or an error listing the names that would
/// have been accepted.
fn parse_permission(name: &str) -> Result<Permission> {
Permission::ALL
.iter()
.copied()
.find(|p| <&str>::from(*p) == name)
.ok_or_else(|| {
let known: Vec<&str> = Permission::ALL.iter().map(|p| <&str>::from(*p)).collect();
anyhow::anyhow!(
"invalid permission {name:?}: expected one of {}",
known.join(", ")
)
})
}
/// Run `swarmctl agent permissions clear`.
pub(crate) fn clear(target: &Target, agent: &str) -> Result<()> {
let uri = member(agent)?;
runtime()?.block_on(send::<(), ()>(
target,
hyper::Method::DELETE,
&uri,
None,
"permissions-clear",
))?;
println!("cleared; {agent} goes back to the default");
Ok(())
}
fn render(p: &Permissions) -> String {
let caps = match p.permissions.as_deref() {
None => "(not set; the default)".to_owned(),
Some([]) => "(none)".to_owned(),
Some(perms) => perms
.iter()
.map(|p| <&str>::from(*p))
.collect::<Vec<_>>()
.join(", "),
};
format!("permissions: {caps}\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_tells_unset_from_none() {
let unset: Permissions = serde_json::from_str("{}").unwrap();
assert_eq!(render(&unset), "permissions: (not set; the default)\n");
let none: Permissions = serde_json::from_str(r#"{"permissions":[]}"#).unwrap();
assert_eq!(render(&none), "permissions: (none)\n");
let ruth: Permissions =
serde_json::from_str(r#"{"permissions":["manage_root_agent"]}"#).unwrap();
assert_eq!(render(&ruth), "permissions: manage_root_agent\n");
}
/// `--permissions ''` stores an empty list, not one empty name.
#[test]
fn an_empty_list_flag_grants_nothing() {
let set = with_permissions(&[String::new()]).unwrap();
assert_eq!(
serde_json::to_string(&set).unwrap(),
r#"{"permissions":[]}"#
);
}
/// A name that is not a permission fails locally and lists the valid ones.
#[test]
fn an_unknown_permission_is_refused() {
let err = with_permissions(&["messaging".to_owned(), "fly".to_owned()]).unwrap_err();
let text = err.to_string();
assert!(text.contains("invalid permission \"fly\""), "{text}");
assert!(text.contains("manage_root_agent"), "{text}");
let ok = with_permissions(&["web_tools".to_owned()]).unwrap();
assert_eq!(
serde_json::to_string(&ok).unwrap(),
r#"{"permissions":["web_tools"]}"#
);
}
}