use serde::{Deserialize, Serialize};
use crate::attr::Attributes;
use crate::condition::Condition;
use crate::engine::Engine;
use crate::governance::{Governance, Mutation, Violation};
use crate::grant::{Effect, Grant, SubjectMatcher, TargetSelector};
use crate::rebac::TupleStore;
use crate::resource::Anchor;
use crate::subject::Subject;
pub const META_TEMPLATE: &str = "template";
pub const META_TEMPLATE_VERSION: &str = "template_version";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TemplateGrant {
pub id: String,
pub permission: String,
pub target: TargetSelector,
#[serde(default = "default_effect")]
pub effect: Effect,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<Anchor>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub condition: Option<Condition>,
}
fn default_effect() -> Effect {
Effect::Allow
}
impl TemplateGrant {
pub fn allow(id: impl Into<String>, permission: impl Into<String>, target: TargetSelector) -> Self {
Self {
id: id.into(),
permission: permission.into(),
target,
effect: Effect::Allow,
scope: None,
condition: None,
}
}
#[must_use]
pub fn scoped(mut self, scope: Anchor) -> Self {
self.scope = Some(scope);
self
}
#[must_use]
pub fn when(mut self, condition: Condition) -> Self {
self.condition = Some(condition);
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RoleTemplate {
pub id: String,
pub version: u32,
pub grants: Vec<TemplateGrant>,
}
impl RoleTemplate {
pub fn new(id: impl Into<String>, version: u32) -> Self {
Self {
id: id.into(),
version,
grants: Vec::new(),
}
}
#[must_use]
pub fn grant(mut self, grant: TemplateGrant) -> Self {
self.grants.push(grant);
self
}
pub fn materialize(&self, subject: SubjectMatcher, scope: Option<Anchor>, id_prefix: &str) -> Materialized {
let mutations = self
.grants
.iter()
.map(|model| {
let mut grant = Grant::new(
format!("{id_prefix}:{}", model.id),
model.effect,
subject.clone(),
model.permission.clone(),
model.target.clone(),
);
grant.scope = model.scope.clone().or_else(|| scope.clone());
grant.condition = model.condition.clone();
Mutation::Add(grant)
})
.collect();
let mut meta = Attributes::new();
meta.insert(META_TEMPLATE.to_string(), self.id.as_str().into());
meta.insert(META_TEMPLATE_VERSION.to_string(), self.version.into());
Materialized {
template: self.id.clone(),
template_version: self.version,
mutations,
meta,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Materialized {
pub template: String,
pub template_version: u32,
pub mutations: Vec<Mutation>,
pub meta: Attributes,
}
impl Materialized {
pub fn ordered(&self, engine: &Engine) -> Vec<&Mutation> {
let depth = |m: &Mutation| match m {
Mutation::Add(grant) => engine.catalog().prerequisites(&grant.permission).count(),
_ => 0,
};
let mut ordered: Vec<&Mutation> = self.mutations.iter().collect();
ordered.sort_by_key(|m| depth(m));
ordered
}
pub fn apply(
&self,
governance: &Governance,
engine: &Engine,
actor: &Subject,
current: &[Grant],
tuples: Option<&dyn TupleStore>,
) -> Result<Vec<Grant>, Vec<Violation>> {
let ordered = self.ordered(engine);
let mut grants = current.to_vec();
for mutation in &ordered {
match governance.evaluate(engine, actor, &grants, mutation, tuples) {
Ok(next) => grants = next,
Err(violations) => {
return governance
.apply_with(engine, actor, &grants, mutation, tuples, &self.meta)
.and(Err(violations));
}
}
}
let mut grants = current.to_vec();
for mutation in ordered {
grants = governance.apply_with(engine, actor, &grants, mutation, tuples, &self.meta)?;
}
Ok(grants)
}
}