use crate::error::{Result, VaultError};
use crate::scope::{Environment, Scope};
use crate::secret::SecretMeta;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::RwLock;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Caller {
pub identity: String,
pub environment: Environment,
}
impl Caller {
pub fn new(identity: impl Into<String>, environment: Environment) -> Self {
Caller { identity: identity.into(), environment }
}
pub fn live(identity: impl Into<String>) -> Self {
Caller::new(identity, Environment::Live)
}
pub fn test(identity: impl Into<String>) -> Self {
Caller::new(identity, Environment::Test)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Action {
List,
ReadMeta,
Create,
Rotate,
Delete,
Use,
Reveal,
Grant,
Audit,
Backup,
}
impl Action {
pub const ALL: [Action; 10] = [
Action::List,
Action::ReadMeta,
Action::Create,
Action::Rotate,
Action::Delete,
Action::Use,
Action::Reveal,
Action::Grant,
Action::Audit,
Action::Backup,
];
pub fn as_str(self) -> &'static str {
match self {
Action::List => "list",
Action::ReadMeta => "read_meta",
Action::Create => "create",
Action::Rotate => "rotate",
Action::Delete => "delete",
Action::Use => "use",
Action::Reveal => "reveal",
Action::Grant => "grant",
Action::Audit => "audit",
Action::Backup => "backup",
}
}
pub fn parse(s: &str) -> Result<Self> {
let s = s.trim().to_ascii_lowercase().replace('-', "_");
Action::ALL.into_iter().find(|a| a.as_str() == s).ok_or_else(|| VaultError::invalid("action", format!("{s:?}")))
}
pub fn is_metadata_read(self) -> bool {
matches!(self, Action::List | Action::ReadMeta | Action::Audit)
}
}
impl fmt::Display for Action {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy)]
pub struct AccessRequest<'a> {
pub caller: &'a Caller,
pub action: Action,
pub scope: &'a Scope,
pub secret: Option<&'a SecretMeta>,
pub grantee: Option<&'a str>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
Allow,
Deny(String),
}
impl Decision {
pub fn deny(reason: impl Into<String>) -> Self {
Decision::Deny(reason.into())
}
}
pub trait Authorize: Send + Sync {
fn authorize(&self, request: &AccessRequest<'_>) -> Decision;
}
impl<F> Authorize for F
where
F: Fn(&AccessRequest<'_>) -> Decision + Send + Sync,
{
fn authorize(&self, request: &AccessRequest<'_>) -> Decision {
self(request)
}
}
#[derive(Default)]
struct RoleState {
roles: BTreeMap<String, BTreeSet<Action>>,
members: BTreeMap<String, BTreeSet<(Scope, String)>>,
}
#[derive(Default)]
pub struct RolePolicy {
state: RwLock<RoleState>,
}
impl fmt::Debug for RolePolicy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = self.read();
f.debug_struct("RolePolicy").field("roles", &s.roles).field("members", &s.members).finish()
}
}
impl RolePolicy {
pub fn new() -> Self {
Self::default()
}
pub fn with_example_roles() -> Self {
let p = RolePolicy::new();
let viewer = [Action::List, Action::ReadMeta];
p.define_role("viewer", &viewer);
p.define_role("trader", &[viewer[0], viewer[1], Action::Use]);
p.define_role("auditor", &[viewer[0], viewer[1], Action::Audit]);
p.define_role("admin", &Action::ALL);
p
}
fn read(&self) -> std::sync::RwLockReadGuard<'_, RoleState> {
self.state.read().unwrap_or_else(|e| e.into_inner())
}
fn write(&self) -> std::sync::RwLockWriteGuard<'_, RoleState> {
self.state.write().unwrap_or_else(|e| e.into_inner())
}
pub fn define_role(&self, name: &str, actions: &[Action]) {
self.write().roles.insert(name.to_string(), actions.iter().copied().collect());
}
pub fn remove_role(&self, name: &str) {
let mut s = self.write();
s.roles.remove(name);
for held in s.members.values_mut() {
held.retain(|(_, r)| r != name);
}
s.members.retain(|_, held| !held.is_empty());
}
pub fn assign(&self, identity: &str, scope: &Scope, role: &str) -> Result<()> {
let mut s = self.write();
if !s.roles.contains_key(role) {
return Err(VaultError::NotFound(format!("role {role:?}")));
}
s.members.entry(identity.to_string()).or_default().insert((scope.clone(), role.to_string()));
Ok(())
}
pub fn unassign(&self, identity: &str, scope: &Scope, role: &str) {
let mut s = self.write();
if let Some(held) = s.members.get_mut(identity) {
held.remove(&(scope.clone(), role.to_string()));
if held.is_empty() {
s.members.remove(identity);
}
}
}
pub fn roles_of(&self, identity: &str) -> Vec<(Scope, String)> {
self.read().members.get(identity).map(|h| h.iter().cloned().collect()).unwrap_or_default()
}
pub fn allows(&self, identity: &str, scope: &Scope, action: Action) -> bool {
let s = self.read();
s.members
.get(identity)
.is_some_and(|held| held.iter().any(|(on, role)| on.contains(scope) && s.roles.get(role).is_some_and(|acts| acts.contains(&action))))
}
}
impl Authorize for RolePolicy {
fn authorize(&self, r: &AccessRequest<'_>) -> Decision {
if self.allows(&r.caller.identity, r.scope, r.action) {
Decision::Allow
} else {
let scope = if r.scope.is_root() { "the root scope".to_string() } else { r.scope.to_string() };
Decision::deny(format!("no role allows {} on {scope}", r.action))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn actions_round_trip() {
for a in Action::ALL {
assert_eq!(Action::parse(a.as_str()).unwrap(), a);
assert_eq!(serde_json::to_string(&a).unwrap(), format!("\"{}\"", a.as_str()));
}
assert_eq!(Action::parse("read-meta").unwrap(), Action::ReadMeta);
assert!(Action::parse("steal").is_err());
}
#[test]
fn role_policy_scopes_and_changes() {
let p = RolePolicy::with_example_roles();
let t = Scope::new(["t1"]).unwrap();
let acct = t.child("a").unwrap();
let other = Scope::new(["t2"]).unwrap();
p.assign("v", &t, "viewer").unwrap();
p.assign("a", &Scope::root(), "admin").unwrap();
assert!(p.assign("x", &t, "nope").is_err());
assert!(p.allows("v", &acct, Action::List));
assert!(!p.allows("v", &acct, Action::Use));
assert!(!p.allows("v", &other, Action::List));
assert!(p.allows("a", &other, Action::Delete));
p.unassign("v", &t, "viewer");
assert!(!p.allows("v", &acct, Action::List));
p.remove_role("admin");
assert!(!p.allows("a", &other, Action::Delete));
assert!(p.roles_of("a").is_empty());
}
}