215 lines
7.2 KiB
Rust
215 lines
7.2 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],
|
|
unrestricted_internet: Option<bool>,
|
|
) -> Result<()> {
|
|
let uri = member(agent)?;
|
|
let wanted = with_permissions(permissions, unrestricted_internet)?;
|
|
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],
|
|
unrestricted_internet: Option<bool>,
|
|
) -> Result<Permissions> {
|
|
let granted = permissions
|
|
.iter()
|
|
.filter(|name| !name.is_empty())
|
|
.map(|name| parse_permission(name))
|
|
.collect::<Result<Vec<_>>>()?;
|
|
Ok(Permissions {
|
|
permissions: Some(granted),
|
|
unrestricted_internet,
|
|
internet_log: None,
|
|
})
|
|
}
|
|
|
|
/// 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(", "),
|
|
};
|
|
let internet = match (p.unrestricted_internet, p.internet_log) {
|
|
(None, _) => "(not set; unrestricted)",
|
|
(Some(true), _) => "unrestricted",
|
|
(Some(false), Some(true)) => "log (unlisted names are allowed and logged as would_deny)",
|
|
(Some(false), _) => "restricted",
|
|
};
|
|
format!("permissions: {caps}\nunrestricted_internet: {internet}\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)\nunrestricted_internet: (not set; unrestricted)\n"
|
|
);
|
|
let none: Permissions = serde_json::from_str(r#"{"permissions":[]}"#).unwrap();
|
|
assert_eq!(
|
|
render(&none),
|
|
"permissions: (none)\nunrestricted_internet: (not set; unrestricted)\n"
|
|
);
|
|
let ruth: Permissions =
|
|
serde_json::from_str(r#"{"permissions":["manage_root_agent"]}"#).unwrap();
|
|
assert_eq!(
|
|
render(&ruth),
|
|
"permissions: manage_root_agent\nunrestricted_internet: (not set; unrestricted)\n"
|
|
);
|
|
}
|
|
|
|
/// An explicit flag is shown and sent; left out it is not sent, so a `PUT`
|
|
/// keeps the stored one.
|
|
#[test]
|
|
fn the_internet_flag_is_sent_only_when_given() {
|
|
let off = with_permissions(&[], Some(false)).unwrap();
|
|
assert_eq!(
|
|
serde_json::to_string(&off).unwrap(),
|
|
r#"{"permissions":[],"unrestricted_internet":false}"#
|
|
);
|
|
assert_eq!(
|
|
render(&off),
|
|
"permissions: (none)\nunrestricted_internet: restricted\n"
|
|
);
|
|
let left_out = with_permissions(&[], None).unwrap();
|
|
assert!(
|
|
!serde_json::to_string(&left_out)
|
|
.unwrap()
|
|
.contains("internet")
|
|
);
|
|
}
|
|
|
|
/// `--permissions ''` stores an empty list, not one empty name.
|
|
#[test]
|
|
fn an_empty_list_flag_grants_nothing() {
|
|
let set = with_permissions(&[String::new()], None).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()], None).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()], None).unwrap();
|
|
assert_eq!(
|
|
serde_json::to_string(&ok).unwrap(),
|
|
r#"{"permissions":["web_tools"]}"#
|
|
);
|
|
}
|
|
|
|
/// A logging agent shows as such, not as plainly restricted.
|
|
#[test]
|
|
fn a_logging_agent_is_shown_as_logging() {
|
|
let log: Permissions =
|
|
serde_json::from_str(r#"{"unrestricted_internet":false,"internet_log":true}"#).unwrap();
|
|
assert!(render(&log).contains("unrestricted_internet: log ("));
|
|
let off: Permissions = serde_json::from_str(r#"{"unrestricted_internet":false}"#).unwrap();
|
|
assert!(
|
|
render(&off).ends_with("unrestricted_internet: restricted\n"),
|
|
"control"
|
|
);
|
|
}
|
|
}
|