use std::collections::HashSet;
#[derive(Clone)]
#[non_exhaustive]
pub struct Permissions {
pub read_only: bool,
pub allowed_commands: Option<HashSet<String>>,
pub sensitive_commands: HashSet<String>,
pub confirmation_token: Option<String>,
}
impl std::fmt::Debug for Permissions {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Permissions")
.field("read_only", &self.read_only)
.field("allowed_commands", &self.allowed_commands)
.field("sensitive_commands", &self.sensitive_commands)
.field(
"confirmation_token",
&self.confirmation_token.as_ref().map(|_| "[redacted]"),
)
.finish()
}
}
impl Default for Permissions {
fn default() -> Self {
Self {
read_only: true,
allowed_commands: None,
sensitive_commands: HashSet::new(),
confirmation_token: None,
}
}
}
impl Permissions {
pub fn read_write() -> Self {
Self {
read_only: false,
..Self::default()
}
}
pub fn allow_commands<I, S>(mut self, commands: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.allowed_commands = Some(commands.into_iter().map(Into::into).collect());
self
}
pub fn confirm<I, S>(mut self, commands: I, token: impl Into<String>) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.sensitive_commands.extend(commands.into_iter().map(Into::into));
self.confirmation_token = Some(token.into());
self
}
pub fn require_confirmation<I, S>(mut self, commands: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.sensitive_commands.extend(commands.into_iter().map(Into::into));
self.confirmation_token = None;
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debug_does_not_print_the_confirmation_token() {
let permissions = Permissions::read_write().confirm(["delete"], "super-secret");
let text = format!("{permissions:?}");
assert!(!text.contains("super-secret"), "{text}");
assert!(text.contains("redacted"), "{text}");
}
}