use crate::{SecurityError, TokenInterface};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Vote {
Grant,
Deny,
Abstain,
}
pub type Subject = str;
pub trait Voter: Send + Sync {
fn vote(&self, token: &dyn TokenInterface, subject: &Subject) -> Vote;
}
#[derive(Default)]
pub struct AccessDecisionManager {
voters: Vec<Box<dyn Voter>>,
}
impl AccessDecisionManager {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn add_voter(&mut self, voter: impl Voter + 'static) {
self.voters.push(Box::new(voter));
}
pub fn decide(
&self,
token: &dyn TokenInterface,
subject: &Subject,
) -> Result<(), SecurityError> {
let mut granted = false;
let mut denied = false;
for voter in &self.voters {
match voter.vote(token, subject) {
Vote::Grant => granted = true,
Vote::Deny => denied = true,
Vote::Abstain => {}
}
}
if granted {
return Ok(());
}
if denied || !self.voters.is_empty() {
return Err(SecurityError::AccessDenied {
message: format!("subject `{subject}` denied"),
});
}
Err(SecurityError::AccessDenied {
message: "no voters registered".to_owned(),
})
}
}
#[derive(Debug, Clone)]
pub struct RoleVoter {
role: String,
subject: String,
}
impl RoleVoter {
#[must_use]
pub fn new(role: impl Into<String>, subject: impl Into<String>) -> Self {
Self {
role: role.into(),
subject: subject.into(),
}
}
}
impl Voter for RoleVoter {
fn vote(&self, token: &dyn TokenInterface, subject: &Subject) -> Vote {
if subject != self.subject {
return Vote::Abstain;
}
let Some(user) = token.user() else {
return Vote::Deny;
};
if user.roles().iter().any(|role| role == &self.role) {
Vote::Grant
} else {
Vote::Deny
}
}
}