use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use crate::{
CatalogExport, Condition, EngineSpec, Grant, InvariantSpec, OverrideSpec, RelationSpec, RoleSpec, StrategySpec,
Subject, Tuple,
};
use super::error::Location;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Language {
Blocks,
Rules,
Actors,
}
impl Language {
pub const fn name(self) -> &'static str {
match self {
Language::Blocks => "blocks",
Language::Rules => "rules",
Language::Actors => "actors",
}
}
}
impl fmt::Display for Language {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl FromStr for Language {
type Err = ();
fn from_str(text: &str) -> Result<Self, ()> {
match text {
"blocks" => Ok(Language::Blocks),
"rules" => Ok(Language::Rules),
"actors" => Ok(Language::Actors),
_ => Err(()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Placement {
Before,
After,
Inline,
Inside,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct NoteAnchor {
pub element: String,
pub placement: Placement,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NoteOrigin {
pub file: String,
pub language: Language,
pub line: u32,
pub column: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub field: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Note {
pub text: String,
pub anchor: NoteAnchor,
pub origin: NoteOrigin,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Policy {
pub catalog: CatalogExport,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub roles: Vec<RoleSpec>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub relations: Option<Vec<RelationSpec>>,
#[serde(default)]
pub strategy: StrategySpec,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub overrides: Vec<OverrideSpec>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_relation_depth: Option<usize>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub subjects: Vec<Subject>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub grants: Vec<Grant>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tuples: Vec<Tuple>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub invariants: Vec<InvariantSpec>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<Note>,
}
const ZONES_SCHEMA: u32 = 3;
const FIELDS_SCHEMA: u32 = 4;
impl Policy {
pub fn engine_spec(&self) -> EngineSpec {
EngineSpec {
catalog: self.catalog.clone(),
roles: self.roles.clone(),
relations: self.relations.clone(),
strategy: self.strategy,
overrides: self.overrides.clone(),
max_relation_depth: self.max_relation_depth,
}
}
pub fn to_json(&self) -> Result<String, serde_json::Error> {
let json = serde_json::to_string_pretty(self)?;
let needs_zones = self
.grants
.iter()
.any(|grant| grant.condition.as_ref().is_some_and(Condition::uses_tz));
let needs_fields = self.grants.iter().any(|grant| !grant.fields.is_empty())
|| self.catalog.permissions.iter().any(|def| !def.fields.is_empty());
let schema = if needs_fields { FIELDS_SCHEMA } else { ZONES_SCHEMA };
Ok(match json.strip_prefix("{\n") {
Some(rest) if needs_zones || needs_fields => format!("{{\n \"schema\": {schema},\n{rest}"),
_ => json,
})
}
pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
use serde::de::Error as _;
let mut document: serde_json::Value = serde_json::from_str(json)?;
if let Some(schema) = document.as_object_mut().and_then(|fields| fields.remove("schema")) {
let known = u64::from(crate::dsl::__macro_support::DSL_SCHEMA);
match schema.as_u64() {
Some(found) if found <= known => {}
_ => {
return Err(serde_json::Error::custom(format!(
"unsupported policy schema {schema}; this reader knows up to {known}"
)));
}
}
}
serde_json::from_value(document)
}
pub fn equivalent(&self, other: &Policy) -> bool {
self.clone().canonical().canonical_value() == other.clone().canonical().canonical_value()
}
#[must_use]
pub fn canonical(mut self) -> Policy {
self.catalog.target_kinds.sort();
self.catalog.broad_targets.sort();
self.roles.sort_by(|a, b| a.role.cmp(&b.role));
for role in &mut self.roles {
role.inherits.sort();
}
if let Some(relations) = &mut self.relations {
relations.sort_by(|a, b| (&a.kind, &a.relation).cmp(&(&b.kind, &b.relation)));
}
self.subjects.sort_by_cached_key(json_key);
self.tuples.sort_by_cached_key(json_key);
self.notes.sort_by(|a, b| a.anchor.cmp(&b.anchor));
self
}
pub(crate) fn canonical_value(&self) -> serde_json::Value {
let mut value = serde_json::to_value(self).unwrap_or(serde_json::Value::Null);
if let Some(notes) = value.get_mut("notes").and_then(serde_json::Value::as_array_mut) {
for note in notes {
if let Some(map) = note.as_object_mut() {
map.remove("origin");
}
}
}
value
}
}
fn json_key<T: Serialize>(item: &T) -> String {
serde_json::to_value(item).map(|v| v.to_string()).unwrap_or_default()
}
pub mod ids {
pub const LANGUAGE: &str = "language";
pub const TARGET_KINDS: &str = "target_kinds";
pub const BROAD_TARGETS: &str = "broad_targets";
pub const STRATEGY: &str = "strategy";
pub const MAX_DEPTH: &str = "max_depth";
pub const TUPLES: &str = "tuples";
pub const RELATIONS: &str = "relations";
pub fn permission(key: &str) -> String {
format!("permission:{key}")
}
pub fn role(name: &str) -> String {
format!("role:{name}")
}
pub fn subject(kind: &str, id: &str) -> String {
format!("subject:{kind}:{id}")
}
pub fn assign(subject: &str, role: &str) -> String {
format!("{subject}/assign:{role}")
}
pub fn grant(id: &str) -> String {
format!("grant:{id}")
}
pub fn relation(kind: &str, relation: &str) -> String {
format!("relation:{kind}#{relation}")
}
pub fn tuple(text: &str) -> String {
format!("tuple:{text}")
}
pub fn override_owner(attr: &str) -> String {
format!("override:resource_owner:{attr}")
}
pub fn override_holder(permission: &str) -> String {
format!("override:permission_holder:{permission}")
}
pub fn invariant(kind: &str, ordinal: usize) -> String {
format!("invariant:{kind}:{ordinal}")
}
pub fn field(element: &str, field: &str) -> String {
format!("{element}/{field}")
}
pub fn split(id: &str) -> (&str, Option<&str>) {
let mut from = 0;
while let Some(slash) = id[from..].find('/') {
let at = from + slash;
let rest = &id[at + 1..];
if rest.starts_with("assign:") {
from = at + 1;
} else {
return (&id[..at], Some(rest));
}
}
(id, None)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Origins(BTreeMap<String, Location>);
impl Origins {
pub(crate) fn insert(&mut self, id: String, location: Location) {
self.0.entry(id).or_insert(location);
}
pub(crate) fn rename_prefix(&mut self, from: &str, to: &str) {
let below = format!("{from}/");
let moved: Vec<String> = self
.0
.range::<str, _>((std::ops::Bound::Included(from), std::ops::Bound::Unbounded))
.map(|(id, _)| id)
.take_while(|id| id.starts_with(from))
.filter(|id| id.as_str() == from || id.starts_with(&below))
.cloned()
.collect();
for id in moved {
if let Some(at) = self.0.remove(&id) {
self.0.insert(format!("{to}{}", &id[from.len()..]), at);
}
}
}
pub fn get(&self, id: &str) -> Option<&Location> {
let mut current = id;
loop {
if let Some(found) = self.0.get(current) {
return Some(found);
}
current = current.rsplit_once('/')?.0;
}
}
pub fn exact(&self, id: &str) -> Option<&Location> {
self.0.get(id)
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &Location)> {
self.0.iter().map(|(id, at)| (id.as_str(), at))
}
}