1mod named_links;
30mod tokens;
31
32pub use tokens::LinksTokenTable;
33
34use std::collections::{HashMap, HashSet};
35
36use anyhow::{bail, Result};
37use thiserror::Error;
38
39use crate::error::LinkError;
40use crate::link::Link;
41use crate::link_storage::ChangeObserver;
42use crate::named_type_links::NamedTypeLinks;
43use crate::types::{ensure_point, TypeMarkers, Types, TypesDecorator};
44use crate::undoable_links::LinksUndoLog;
45
46#[derive(Debug, Clone, PartialEq, Eq, Error)]
48#[error("Forbidden: {what}")]
49pub struct Forbidden {
50 pub what: String,
52}
53
54impl Forbidden {
55 pub fn new(what: impl Into<String>) -> Self {
56 Self { what: what.into() }
57 }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub enum PermissionAccess {
63 Read,
65 Write,
67 Reference,
69}
70
71impl PermissionAccess {
72 pub fn parse(access: &str) -> Result<Self> {
74 match access {
75 "read" => Ok(Self::Read),
76 "write" => Ok(Self::Write),
77 "reference" => Ok(Self::Reference),
78 _ => bail!("Unknown access: {access}"),
79 }
80 }
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
87pub struct PermissionMarkers {
88 pub allow_read: u32,
89 pub allow_write: u32,
90 pub anything: u32,
91 pub allow_reference: u32,
92}
93
94impl PermissionMarkers {
95 pub const ALLOW_READ_NAME: &'static str = "AllowRead";
97 pub const ALLOW_WRITE_NAME: &'static str = "AllowWrite";
99 pub const ANYTHING_NAME: &'static str = "Anything";
101 pub const ALLOW_REFERENCE_NAME: &'static str = "AllowReference";
103
104 pub fn ensure<L: NamedTypeLinks + ?Sized>(links: &mut L) -> Result<Self> {
109 Ok(Self {
110 allow_read: ensure_point(links, Self::ALLOW_READ_NAME)?,
111 allow_write: ensure_point(links, Self::ALLOW_WRITE_NAME)?,
112 anything: ensure_point(links, Self::ANYTHING_NAME)?,
113 allow_reference: ensure_point(links, Self::ALLOW_REFERENCE_NAME)?,
114 })
115 }
116
117 pub fn of(&self, access: PermissionAccess) -> u32 {
119 match access {
120 PermissionAccess::Read => self.allow_read,
121 PermissionAccess::Write => self.allow_write,
122 PermissionAccess::Reference => self.allow_reference,
123 }
124 }
125}
126
127pub trait AccessPolicy {
134 fn markers(&self) -> PermissionMarkers;
136
137 fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool;
139
140 fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool;
142
143 fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool;
145
146 fn can_reference(
150 &mut self,
151 _data: &mut dyn NamedTypeLinks,
152 _subject: u32,
153 _link: &Link,
154 ) -> bool {
155 false
156 }
157}
158
159impl<P: AccessPolicy + ?Sized> AccessPolicy for &mut P {
160 fn markers(&self) -> PermissionMarkers {
161 (**self).markers()
162 }
163
164 fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
165 (**self).can_read(data, subject, link)
166 }
167
168 fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
169 (**self).can_write(data, subject, link)
170 }
171
172 fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool {
173 (**self).can_create(data, subject)
174 }
175
176 fn can_reference(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
177 (**self).can_reference(data, subject, link)
178 }
179}
180
181impl<P: AccessPolicy + ?Sized> AccessPolicy for Box<P> {
182 fn markers(&self) -> PermissionMarkers {
183 (**self).markers()
184 }
185
186 fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
187 (**self).can_read(data, subject, link)
188 }
189
190 fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
191 (**self).can_write(data, subject, link)
192 }
193
194 fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool {
195 (**self).can_create(data, subject)
196 }
197
198 fn can_reference(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
199 (**self).can_reference(data, subject, link)
200 }
201}
202
203pub struct PermissionPolicy {
205 markers: PermissionMarkers,
206 types: TypeMarkers,
207 rules: Option<Box<dyn NamedTypeLinks>>,
208}
209
210impl PermissionPolicy {
211 pub fn new(
214 markers: PermissionMarkers,
215 types: TypeMarkers,
216 rules: Option<Box<dyn NamedTypeLinks>>,
217 ) -> Self {
218 Self {
219 markers,
220 types,
221 rules,
222 }
223 }
224
225 pub fn in_data<L: NamedTypeLinks + ?Sized>(data: &mut L) -> Result<Self> {
229 let types = TypeMarkers::ensure(data)?;
230 let markers = PermissionMarkers::ensure(data)?;
231 Ok(Self::new(markers, types, None))
232 }
233
234 pub fn with_rules<L: NamedTypeLinks + ?Sized>(
237 data: &mut L,
238 rules: Box<dyn NamedTypeLinks>,
239 ) -> Result<Self> {
240 let types = TypeMarkers::ensure(data)?;
241 let markers = PermissionMarkers::ensure(data)?;
242 Ok(Self::new(markers, types, Some(rules)))
243 }
244
245 pub fn types(&self) -> TypeMarkers {
247 self.types
248 }
249
250 pub fn rules_mut(&mut self) -> Option<&mut (dyn NamedTypeLinks + 'static)> {
252 self.rules.as_deref_mut()
253 }
254
255 pub fn rules_of<'a>(
257 &'a mut self,
258 data: &'a mut dyn NamedTypeLinks,
259 ) -> &'a mut dyn NamedTypeLinks {
260 match self.rules.as_deref_mut() {
261 Some(rules) => rules,
262 None => data,
263 }
264 }
265
266 pub fn granted(&mut self, data: &mut dyn NamedTypeLinks, marker: u32) -> Vec<(u32, u32)> {
268 let rules = self.rules_of(data);
269 let mut marks: Vec<(u32, u32)> = rules
270 .query_links(None, Some(marker), None)
271 .into_iter()
272 .filter(|mark| mark.index != marker || mark.target != marker)
275 .map(|mark| (mark.index, mark.target))
276 .collect();
277 marks.sort_by_key(|&(mark, _)| mark);
278 marks
279 .into_iter()
280 .filter_map(|(_, rule)| {
281 if rule == 0 {
282 return None;
283 }
284 rules.get_link(rule).map(|link| (link.source, link.target))
285 })
286 .collect()
287 }
288
289 pub fn allows(
291 &mut self,
292 data: &mut dyn NamedTypeLinks,
293 marker: u32,
294 subject: u32,
295 link: &Link,
296 ) -> bool {
297 let granted = self.granted(data, marker);
298 if granted.is_empty() {
299 return false;
300 }
301 let anything = self.markers.anything;
302 let mut types = TypesDecorator::with_markers(data, self.types);
303 granted.into_iter().any(|(rule_subject, rule_object)| {
304 is_subject(&mut types, anything, subject, rule_subject)
305 && (rule_object == anything || types.is_of_link(link, rule_object))
306 })
307 }
308
309 pub fn allow<L: NamedTypeLinks + ?Sized>(
313 rules: &mut L,
314 markers: PermissionMarkers,
315 access: PermissionAccess,
316 subject: u32,
317 object: u32,
318 ) -> Result<u32> {
319 if subject == markers.allow_read
320 || subject == markers.allow_write
321 || subject == markers.allow_reference
322 {
323 bail!("A marker cannot be a subject");
325 }
326 let rule = rules.try_get_or_create(subject, object)?;
329 rules.try_get_or_create(markers.of(access), rule)?;
330 Ok(rule)
331 }
332
333 pub fn parse_access(access: &str) -> Result<PermissionAccess> {
335 PermissionAccess::parse(access)
336 }
337}
338
339fn is_subject<T: Types>(types: &mut T, anything: u32, subject: u32, type_id: u32) -> bool {
341 type_id == anything || (subject != 0 && types.is_a(subject, type_id))
342}
343
344impl AccessPolicy for PermissionPolicy {
345 fn markers(&self) -> PermissionMarkers {
346 self.markers
347 }
348
349 fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
350 let markers = self.markers;
351 self.allows(data, markers.allow_read, subject, link)
352 || self.allows(data, markers.allow_write, subject, link)
353 }
354
355 fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
356 let marker = self.markers.allow_write;
357 self.allows(data, marker, subject, link)
358 }
359
360 fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool {
361 let marker = self.markers.allow_write;
362 let granted = self.granted(data, marker);
363 let anything = self.markers.anything;
364 let mut types = TypesDecorator::with_markers(data, self.types);
365 granted
366 .into_iter()
367 .any(|(rule_subject, _)| is_subject(&mut types, anything, subject, rule_subject))
368 }
369
370 fn can_reference(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
371 let markers = self.markers;
372 if (subject != 0 && link.index == subject)
373 || self.allows(data, markers.allow_reference, subject, link)
374 {
375 return true;
376 }
377 [
380 markers.allow_read,
381 markers.allow_write,
382 markers.allow_reference,
383 ]
384 .into_iter()
385 .any(|marker| {
386 let granted = self.granted(data, marker);
387 let mut types = TypesDecorator::with_markers(&mut *data, self.types);
388 granted.into_iter().any(|(rule_subject, rule_object)| {
389 rule_object == link.index
390 && is_subject(&mut types, markers.anything, subject, rule_subject)
391 })
392 })
393 }
394}
395
396pub struct PermissionsDecorator<L: NamedTypeLinks, P: AccessPolicy = PermissionPolicy> {
431 links: L,
432 policy: P,
433 subject: u32,
434 created: HashSet<u32>,
435}
436
437impl<L: NamedTypeLinks, P: AccessPolicy> PermissionsDecorator<L, P> {
438 pub fn new(links: L, policy: P, subject: u32) -> Self {
440 Self {
441 links,
442 policy,
443 subject,
444 created: HashSet::new(),
445 }
446 }
447
448 pub fn with_created(mut self, created: HashSet<u32>) -> Self {
450 self.created = created;
451 self
452 }
453
454 pub fn subject(&self) -> u32 {
456 self.subject
457 }
458
459 pub fn set_subject(&mut self, subject: u32) {
460 self.subject = subject;
461 }
462
463 pub fn created(&self) -> &HashSet<u32> {
465 &self.created
466 }
467
468 pub fn replace_created(&mut self, created: HashSet<u32>) -> HashSet<u32> {
470 std::mem::replace(&mut self.created, created)
471 }
472
473 pub fn policy(&self) -> &P {
474 &self.policy
475 }
476
477 pub fn policy_mut(&mut self) -> &mut P {
478 &mut self.policy
479 }
480
481 pub fn inner(&self) -> &L {
482 &self.links
483 }
484
485 pub fn inner_mut(&mut self) -> &mut L {
486 &mut self.links
487 }
488
489 pub fn into_inner(self) -> L {
490 self.links
491 }
492
493 pub fn owns(&self, link: &Link) -> bool {
496 link.source == 0 && self.created.contains(&link.index)
497 }
498
499 pub fn can_read(&mut self, link: &Link) -> bool {
501 self.owns(link) || self.policy.can_read(&mut self.links, self.subject, link)
502 }
503
504 pub fn can_write(&mut self, link: &Link) -> bool {
506 self.owns(link) || self.policy.can_write(&mut self.links, self.subject, link)
507 }
508
509 pub fn can_reference(&mut self, id: u32) -> bool {
513 let link = self.links.get_link(id).unwrap_or(Link::new(id, 0, 0));
514 self.owns_triplet(&link)
515 || self.can_read(&link)
516 || self
517 .policy
518 .can_reference(&mut self.links, self.subject, &link)
519 }
520
521 fn check_references(&mut self, before: Option<&Link>, source: u32, target: u32) -> Result<()> {
524 for part in [source, target] {
525 let held = before.is_some_and(|link| {
526 part == link.index || part == link.source || part == link.target
527 });
528 if part != 0 && !held && !self.can_reference(part) {
529 return Err(LinkError::not_found(part).into());
530 }
531 }
532 Ok(())
533 }
534
535 pub(crate) fn owns_triplet(&self, link: &Link) -> bool {
538 let point = link.source == link.index && link.target == link.index;
539 self.owns(link) || (point && self.created.contains(&link.index))
540 }
541
542 pub(crate) fn can_read_triplet(&mut self, link: &Link) -> bool {
544 self.owns_triplet(link) || self.policy.can_read(&mut self.links, self.subject, link)
545 }
546
547 pub(crate) fn can_write_triplet(&mut self, link: &Link) -> bool {
549 self.owns_triplet(link) || self.policy.can_write(&mut self.links, self.subject, link)
550 }
551
552 pub(crate) fn policy_can_write(&mut self, link: &Link) -> bool {
554 self.policy.can_write(&mut self.links, self.subject, link)
555 }
556
557 pub(crate) fn policy_can_create(&mut self) -> bool {
558 self.policy.can_create(&mut self.links, self.subject)
559 }
560
561 pub(crate) fn remember(&mut self, index: u32) {
563 self.created.insert(index);
564 }
565
566 pub(crate) fn parts_mut(&mut self) -> (&mut L, &mut P) {
569 (&mut self.links, &mut self.policy)
570 }
571
572 pub fn forget(&mut self, index: u32) {
574 self.created.remove(&index);
575 }
576
577 fn visible(&mut self, index: u32) -> Result<Option<Link>> {
580 if index == 0 {
581 return Ok(None);
582 }
583 let Some(link) = self.links.get_link(index) else {
584 return Ok(None);
585 };
586 if !self.can_read(&link) {
587 return Err(LinkError::not_found(index).into());
588 }
589 Ok(Some(link))
590 }
591
592 fn require_writable(&mut self, index: u32, what: &str) -> Result<()> {
593 let link = self
594 .visible(index)?
595 .ok_or_else(|| anyhow::Error::from(LinkError::not_found(index)))?;
596 if !self.can_write(&link) {
597 return Err(Forbidden::new(format!("{what} {index}")).into());
598 }
599 Ok(())
600 }
601
602 fn require_create(&mut self, source: u32, target: u32) -> Result<()> {
603 if !self.policy_can_create()
604 || (source != 0 && !self.policy_can_write(&Link::new(0, source, target)))
605 {
606 return Err(Forbidden::new("create").into());
607 }
608 Ok(())
609 }
610
611 fn allowed(&mut self, before: Option<Link>, after: Option<Link>) -> bool {
613 match (before, after) {
614 (Some(was), Some(now)) if was == now => true,
615 (None, made) => {
616 self.policy_can_create()
617 && made.is_none_or(|made| made.source == 0 || self.policy_can_write(&made))
618 }
619 (Some(was), None) => self.can_write(&was),
620 (Some(was), Some(now)) => {
621 (self.owns(&was) && now.source == 0)
622 || (self.can_write(&was) && self.policy_can_write(&now))
623 }
624 }
625 }
626
627 fn checked(
631 &mut self,
632 what: &str,
633 index: u32,
634 mut log: LinksUndoLog,
635 write: impl FnOnce(&mut L, ChangeObserver<'_>) -> Result<Link>,
636 observer: ChangeObserver<'_>,
637 ) -> Result<Link> {
638 let result = write(&mut self.links, &mut |before, after| {
639 log.record_observed(before, after)
640 });
641 let result = match result {
642 Ok(result) => result,
643 Err(error) => {
644 if let Err(undo) = self.undo(&mut log) {
645 return Err(error.context(format!("and undoing it failed: {undo}")));
646 }
647 return Err(error);
648 }
649 };
650 let mut net: HashMap<u32, (Option<Link>, Option<Link>)> = HashMap::new();
651 let mut order = Vec::new();
652 for &(before, after) in log.changes() {
653 let Some(at) = before.or(after).map(|link| link.index) else {
654 continue;
655 };
656 match net.get_mut(&at) {
657 Some(known) => known.1 = after,
658 None => {
659 net.insert(at, (before, after));
660 order.push(at);
661 }
662 }
663 }
664 for &at in &order {
665 let (first, last) = net[&at];
666 if at == index || self.allowed(first, last) {
667 continue;
668 }
669 self.undo(&mut log)?;
670 return Err(Forbidden::new(what).into());
671 }
672 for &at in &order {
673 if net[&at].1.is_none() {
674 self.created.remove(&at);
675 }
676 }
677 for &(before, after) in log.changes() {
678 observer(
679 before.unwrap_or(Link::null()),
680 after.unwrap_or(Link::null()),
681 );
682 }
683 Ok(result)
684 }
685
686 fn undo(&mut self, log: &mut LinksUndoLog) -> Result<()> {
687 for gone in log.undo(&mut self.links)? {
688 self.created.remove(&gone);
689 }
690 Ok(())
691 }
692
693 fn panic_on<T>(result: Result<T>) -> T {
694 result.unwrap_or_else(|error| panic!("{error}"))
695 }
696}