mod named_links;
mod tokens;
pub use tokens::LinksTokenTable;
use std::collections::{HashMap, HashSet};
use anyhow::{bail, Result};
use thiserror::Error;
use crate::error::LinkError;
use crate::link::Link;
use crate::link_storage::ChangeObserver;
use crate::named_type_links::NamedTypeLinks;
use crate::types::{ensure_point, TypeMarkers, Types, TypesDecorator};
use crate::undoable_links::LinksUndoLog;
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("Forbidden: {what}")]
pub struct Forbidden {
pub what: String,
}
impl Forbidden {
pub fn new(what: impl Into<String>) -> Self {
Self { what: what.into() }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PermissionAccess {
Read,
Write,
Reference,
}
impl PermissionAccess {
pub fn parse(access: &str) -> Result<Self> {
match access {
"read" => Ok(Self::Read),
"write" => Ok(Self::Write),
"reference" => Ok(Self::Reference),
_ => bail!("Unknown access: {access}"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PermissionMarkers {
pub allow_read: u32,
pub allow_write: u32,
pub anything: u32,
pub allow_reference: u32,
}
impl PermissionMarkers {
pub const ALLOW_READ_NAME: &'static str = "AllowRead";
pub const ALLOW_WRITE_NAME: &'static str = "AllowWrite";
pub const ANYTHING_NAME: &'static str = "Anything";
pub const ALLOW_REFERENCE_NAME: &'static str = "AllowReference";
pub fn ensure<L: NamedTypeLinks + ?Sized>(links: &mut L) -> Result<Self> {
Ok(Self {
allow_read: ensure_point(links, Self::ALLOW_READ_NAME)?,
allow_write: ensure_point(links, Self::ALLOW_WRITE_NAME)?,
anything: ensure_point(links, Self::ANYTHING_NAME)?,
allow_reference: ensure_point(links, Self::ALLOW_REFERENCE_NAME)?,
})
}
pub fn of(&self, access: PermissionAccess) -> u32 {
match access {
PermissionAccess::Read => self.allow_read,
PermissionAccess::Write => self.allow_write,
PermissionAccess::Reference => self.allow_reference,
}
}
}
pub trait AccessPolicy {
fn markers(&self) -> PermissionMarkers;
fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool;
fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool;
fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool;
fn can_reference(
&mut self,
_data: &mut dyn NamedTypeLinks,
_subject: u32,
_link: &Link,
) -> bool {
false
}
}
impl<P: AccessPolicy + ?Sized> AccessPolicy for &mut P {
fn markers(&self) -> PermissionMarkers {
(**self).markers()
}
fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
(**self).can_read(data, subject, link)
}
fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
(**self).can_write(data, subject, link)
}
fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool {
(**self).can_create(data, subject)
}
fn can_reference(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
(**self).can_reference(data, subject, link)
}
}
impl<P: AccessPolicy + ?Sized> AccessPolicy for Box<P> {
fn markers(&self) -> PermissionMarkers {
(**self).markers()
}
fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
(**self).can_read(data, subject, link)
}
fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
(**self).can_write(data, subject, link)
}
fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool {
(**self).can_create(data, subject)
}
fn can_reference(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
(**self).can_reference(data, subject, link)
}
}
pub struct PermissionPolicy {
markers: PermissionMarkers,
types: TypeMarkers,
rules: Option<Box<dyn NamedTypeLinks>>,
}
impl PermissionPolicy {
pub fn new(
markers: PermissionMarkers,
types: TypeMarkers,
rules: Option<Box<dyn NamedTypeLinks>>,
) -> Self {
Self {
markers,
types,
rules,
}
}
pub fn in_data<L: NamedTypeLinks + ?Sized>(data: &mut L) -> Result<Self> {
let types = TypeMarkers::ensure(data)?;
let markers = PermissionMarkers::ensure(data)?;
Ok(Self::new(markers, types, None))
}
pub fn with_rules<L: NamedTypeLinks + ?Sized>(
data: &mut L,
rules: Box<dyn NamedTypeLinks>,
) -> Result<Self> {
let types = TypeMarkers::ensure(data)?;
let markers = PermissionMarkers::ensure(data)?;
Ok(Self::new(markers, types, Some(rules)))
}
pub fn types(&self) -> TypeMarkers {
self.types
}
pub fn rules_mut(&mut self) -> Option<&mut (dyn NamedTypeLinks + 'static)> {
self.rules.as_deref_mut()
}
pub fn rules_of<'a>(
&'a mut self,
data: &'a mut dyn NamedTypeLinks,
) -> &'a mut dyn NamedTypeLinks {
match self.rules.as_deref_mut() {
Some(rules) => rules,
None => data,
}
}
pub fn granted(&mut self, data: &mut dyn NamedTypeLinks, marker: u32) -> Vec<(u32, u32)> {
let rules = self.rules_of(data);
let mut marks: Vec<(u32, u32)> = rules
.query_links(None, Some(marker), None)
.into_iter()
.filter(|mark| mark.index != marker || mark.target != marker)
.map(|mark| (mark.index, mark.target))
.collect();
marks.sort_by_key(|&(mark, _)| mark);
marks
.into_iter()
.filter_map(|(_, rule)| {
if rule == 0 {
return None;
}
rules.get_link(rule).map(|link| (link.source, link.target))
})
.collect()
}
pub fn allows(
&mut self,
data: &mut dyn NamedTypeLinks,
marker: u32,
subject: u32,
link: &Link,
) -> bool {
let granted = self.granted(data, marker);
if granted.is_empty() {
return false;
}
let anything = self.markers.anything;
let mut types = TypesDecorator::with_markers(data, self.types);
granted.into_iter().any(|(rule_subject, rule_object)| {
is_subject(&mut types, anything, subject, rule_subject)
&& (rule_object == anything || types.is_of_link(link, rule_object))
})
}
pub fn allow<L: NamedTypeLinks + ?Sized>(
rules: &mut L,
markers: PermissionMarkers,
access: PermissionAccess,
subject: u32,
object: u32,
) -> Result<u32> {
if subject == markers.allow_read
|| subject == markers.allow_write
|| subject == markers.allow_reference
{
bail!("A marker cannot be a subject");
}
let rule = rules.try_get_or_create(subject, object)?;
rules.try_get_or_create(markers.of(access), rule)?;
Ok(rule)
}
pub fn parse_access(access: &str) -> Result<PermissionAccess> {
PermissionAccess::parse(access)
}
}
fn is_subject<T: Types>(types: &mut T, anything: u32, subject: u32, type_id: u32) -> bool {
type_id == anything || (subject != 0 && types.is_a(subject, type_id))
}
impl AccessPolicy for PermissionPolicy {
fn markers(&self) -> PermissionMarkers {
self.markers
}
fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
let markers = self.markers;
self.allows(data, markers.allow_read, subject, link)
|| self.allows(data, markers.allow_write, subject, link)
}
fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
let marker = self.markers.allow_write;
self.allows(data, marker, subject, link)
}
fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool {
let marker = self.markers.allow_write;
let granted = self.granted(data, marker);
let anything = self.markers.anything;
let mut types = TypesDecorator::with_markers(data, self.types);
granted
.into_iter()
.any(|(rule_subject, _)| is_subject(&mut types, anything, subject, rule_subject))
}
fn can_reference(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
let markers = self.markers;
if (subject != 0 && link.index == subject)
|| self.allows(data, markers.allow_reference, subject, link)
{
return true;
}
[
markers.allow_read,
markers.allow_write,
markers.allow_reference,
]
.into_iter()
.any(|marker| {
let granted = self.granted(data, marker);
let mut types = TypesDecorator::with_markers(&mut *data, self.types);
granted.into_iter().any(|(rule_subject, rule_object)| {
rule_object == link.index
&& is_subject(&mut types, markers.anything, subject, rule_subject)
})
})
}
}
pub struct PermissionsDecorator<L: NamedTypeLinks, P: AccessPolicy = PermissionPolicy> {
links: L,
policy: P,
subject: u32,
created: HashSet<u32>,
}
impl<L: NamedTypeLinks, P: AccessPolicy> PermissionsDecorator<L, P> {
pub fn new(links: L, policy: P, subject: u32) -> Self {
Self {
links,
policy,
subject,
created: HashSet::new(),
}
}
pub fn with_created(mut self, created: HashSet<u32>) -> Self {
self.created = created;
self
}
pub fn subject(&self) -> u32 {
self.subject
}
pub fn set_subject(&mut self, subject: u32) {
self.subject = subject;
}
pub fn created(&self) -> &HashSet<u32> {
&self.created
}
pub fn replace_created(&mut self, created: HashSet<u32>) -> HashSet<u32> {
std::mem::replace(&mut self.created, created)
}
pub fn policy(&self) -> &P {
&self.policy
}
pub fn policy_mut(&mut self) -> &mut P {
&mut self.policy
}
pub fn inner(&self) -> &L {
&self.links
}
pub fn inner_mut(&mut self) -> &mut L {
&mut self.links
}
pub fn into_inner(self) -> L {
self.links
}
pub fn owns(&self, link: &Link) -> bool {
link.source == 0 && self.created.contains(&link.index)
}
pub fn can_read(&mut self, link: &Link) -> bool {
self.owns(link) || self.policy.can_read(&mut self.links, self.subject, link)
}
pub fn can_write(&mut self, link: &Link) -> bool {
self.owns(link) || self.policy.can_write(&mut self.links, self.subject, link)
}
pub fn can_reference(&mut self, id: u32) -> bool {
let link = self.links.get_link(id).unwrap_or(Link::new(id, 0, 0));
self.owns_triplet(&link)
|| self.can_read(&link)
|| self
.policy
.can_reference(&mut self.links, self.subject, &link)
}
fn check_references(&mut self, before: Option<&Link>, source: u32, target: u32) -> Result<()> {
for part in [source, target] {
let held = before.is_some_and(|link| {
part == link.index || part == link.source || part == link.target
});
if part != 0 && !held && !self.can_reference(part) {
return Err(LinkError::not_found(part).into());
}
}
Ok(())
}
pub(crate) fn owns_triplet(&self, link: &Link) -> bool {
let point = link.source == link.index && link.target == link.index;
self.owns(link) || (point && self.created.contains(&link.index))
}
pub(crate) fn can_read_triplet(&mut self, link: &Link) -> bool {
self.owns_triplet(link) || self.policy.can_read(&mut self.links, self.subject, link)
}
pub(crate) fn can_write_triplet(&mut self, link: &Link) -> bool {
self.owns_triplet(link) || self.policy.can_write(&mut self.links, self.subject, link)
}
pub(crate) fn policy_can_write(&mut self, link: &Link) -> bool {
self.policy.can_write(&mut self.links, self.subject, link)
}
pub(crate) fn policy_can_create(&mut self) -> bool {
self.policy.can_create(&mut self.links, self.subject)
}
pub(crate) fn remember(&mut self, index: u32) {
self.created.insert(index);
}
pub(crate) fn parts_mut(&mut self) -> (&mut L, &mut P) {
(&mut self.links, &mut self.policy)
}
pub fn forget(&mut self, index: u32) {
self.created.remove(&index);
}
fn visible(&mut self, index: u32) -> Result<Option<Link>> {
if index == 0 {
return Ok(None);
}
let Some(link) = self.links.get_link(index) else {
return Ok(None);
};
if !self.can_read(&link) {
return Err(LinkError::not_found(index).into());
}
Ok(Some(link))
}
fn require_writable(&mut self, index: u32, what: &str) -> Result<()> {
let link = self
.visible(index)?
.ok_or_else(|| anyhow::Error::from(LinkError::not_found(index)))?;
if !self.can_write(&link) {
return Err(Forbidden::new(format!("{what} {index}")).into());
}
Ok(())
}
fn require_create(&mut self, source: u32, target: u32) -> Result<()> {
if !self.policy_can_create()
|| (source != 0 && !self.policy_can_write(&Link::new(0, source, target)))
{
return Err(Forbidden::new("create").into());
}
Ok(())
}
fn allowed(&mut self, before: Option<Link>, after: Option<Link>) -> bool {
match (before, after) {
(Some(was), Some(now)) if was == now => true,
(None, made) => {
self.policy_can_create()
&& made.is_none_or(|made| made.source == 0 || self.policy_can_write(&made))
}
(Some(was), None) => self.can_write(&was),
(Some(was), Some(now)) => {
(self.owns(&was) && now.source == 0)
|| (self.can_write(&was) && self.policy_can_write(&now))
}
}
}
fn checked(
&mut self,
what: &str,
index: u32,
mut log: LinksUndoLog,
write: impl FnOnce(&mut L, ChangeObserver<'_>) -> Result<Link>,
observer: ChangeObserver<'_>,
) -> Result<Link> {
let result = write(&mut self.links, &mut |before, after| {
log.record_observed(before, after)
});
let result = match result {
Ok(result) => result,
Err(error) => {
if let Err(undo) = self.undo(&mut log) {
return Err(error.context(format!("and undoing it failed: {undo}")));
}
return Err(error);
}
};
let mut net: HashMap<u32, (Option<Link>, Option<Link>)> = HashMap::new();
let mut order = Vec::new();
for &(before, after) in log.changes() {
let Some(at) = before.or(after).map(|link| link.index) else {
continue;
};
match net.get_mut(&at) {
Some(known) => known.1 = after,
None => {
net.insert(at, (before, after));
order.push(at);
}
}
}
for &at in &order {
let (first, last) = net[&at];
if at == index || self.allowed(first, last) {
continue;
}
self.undo(&mut log)?;
return Err(Forbidden::new(what).into());
}
for &at in &order {
if net[&at].1.is_none() {
self.created.remove(&at);
}
}
for &(before, after) in log.changes() {
observer(
before.unwrap_or(Link::null()),
after.unwrap_or(Link::null()),
);
}
Ok(result)
}
fn undo(&mut self, log: &mut LinksUndoLog) -> Result<()> {
for gone in log.undo(&mut self.links)? {
self.created.remove(&gone);
}
Ok(())
}
fn panic_on<T>(result: Result<T>) -> T {
result.unwrap_or_else(|error| panic!("{error}"))
}
}