Skip to main content

link_cli/
permissions.rs

1//! An optional permission layer with permissions stored in links (issue #149),
2//! the Rust port of `createPolicy` and `withPermissions` of
3//! `@link-foundation/ui-links`; the C# counterparts are
4//! `PermissionPolicy<TLinkAddress>` and `PermissionsDecorator<TLinkAddress>`.
5//!
6//! A rule is a pair `(g: Subject Object)` marked as `(r: AllowRead g)` or
7//! `(r: AllowWrite g)`: the subjects that are `Subject` (the subject itself,
8//! or a link of that type) may read, or read and write, the links of type
9//! `Object` -- its values and sub-types, not the link of `Object` itself.
10//! `Anything` in either place matches every subject or every link. Types are
11//! those of [`Types`](crate::types::Types) (issue #148).
12//!
13//! Referring to a link is a right of its own (issue #161). Without it an
14//! address the subject may not read answers `Link not found`, exactly as a
15//! missing one. A subject may refer to an address when it may read the link
16//! there, when it is that link, when a rule `(r: AllowReference (g: Subject
17//! Object))` covers it (`Object` itself and the links of type `Object`), or
18//! when it is the `Object` of an `AllowRead` or `AllowWrite` rule of the
19//! subject, so `User writes Note` is enough to type a link as `Note`.
20//! `AllowReference` does not allow reading. A rule from `Anything` to
21//! `Anything` lets every subject refer to every link.
22//!
23//! The markers are points of the data, so every address a rule holds is an
24//! address of the data. The rules live in the data itself or in a store of
25//! their own. Rules in the data are links like any other: a subject that may
26//! write them may change the rules, so give `Anything` writes to
27//! administrators only, or keep the rules apart.
28
29mod tokens;
30
31pub use tokens::LinksTokenTable;
32
33use std::collections::{HashMap, HashSet};
34
35use anyhow::{bail, Result};
36use thiserror::Error;
37
38use crate::error::LinkError;
39use crate::link::Link;
40use crate::link_storage::ChangeObserver;
41use crate::named_type_links::NamedTypeLinks;
42use crate::types::{ensure_point, TypeMarkers, Types, TypesDecorator};
43use crate::undoable_links::{keep_names_before_update, LinksUndoLog};
44
45/// A write a subject may not make; it reads `Forbidden: what`.
46#[derive(Debug, Clone, PartialEq, Eq, Error)]
47#[error("Forbidden: {what}")]
48pub struct Forbidden {
49    /// What was refused, such as `update 7`.
50    pub what: String,
51}
52
53impl Forbidden {
54    pub fn new(what: impl Into<String>) -> Self {
55        Self { what: what.into() }
56    }
57}
58
59/// What a rule allows.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
61pub enum PermissionAccess {
62    /// Reading: the link is seen.
63    Read,
64    /// Reading and writing: the link may be created, updated, deleted and named.
65    Write,
66    /// Referring: the link may be used in another link, not seen.
67    Reference,
68}
69
70impl PermissionAccess {
71    /// Parses `read`, `write` or `reference`.
72    pub fn parse(access: &str) -> Result<Self> {
73        match access {
74            "read" => Ok(Self::Read),
75            "write" => Ok(Self::Write),
76            "reference" => Ok(Self::Reference),
77            _ => bail!("Unknown access: {access}"),
78        }
79    }
80}
81
82/// The four points of the data permission rules are made of: the markers
83/// `AllowRead`, `AllowWrite` and `AllowReference` of rules and `Anything`, which
84/// matches every subject or every link.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86pub struct PermissionMarkers {
87    pub allow_read: u32,
88    pub allow_write: u32,
89    pub anything: u32,
90    pub allow_reference: u32,
91}
92
93impl PermissionMarkers {
94    /// The name of the marker of read rules.
95    pub const ALLOW_READ_NAME: &'static str = "AllowRead";
96    /// The name of the marker of write rules.
97    pub const ALLOW_WRITE_NAME: &'static str = "AllowWrite";
98    /// The name of the marker that matches every subject or link.
99    pub const ANYTHING_NAME: &'static str = "Anything";
100    /// The name of the marker of reference rules.
101    pub const ALLOW_REFERENCE_NAME: &'static str = "AllowReference";
102
103    /// The points named `AllowRead`, `AllowWrite`, `Anything` and
104    /// `AllowReference`, each created as a point `(x: x x)` and named when
105    /// missing. `AllowReference` comes last, so the others keep their addresses
106    /// in a store made before it was added.
107    pub fn ensure<L: NamedTypeLinks + ?Sized>(links: &mut L) -> Result<Self> {
108        Ok(Self {
109            allow_read: ensure_point(links, Self::ALLOW_READ_NAME)?,
110            allow_write: ensure_point(links, Self::ALLOW_WRITE_NAME)?,
111            anything: ensure_point(links, Self::ANYTHING_NAME)?,
112            allow_reference: ensure_point(links, Self::ALLOW_REFERENCE_NAME)?,
113        })
114    }
115
116    /// The marker of the rules of `access`.
117    pub fn of(&self, access: PermissionAccess) -> u32 {
118        match access {
119            PermissionAccess::Read => self.allow_read,
120            PermissionAccess::Write => self.allow_write,
121            PermissionAccess::Reference => self.allow_reference,
122        }
123    }
124}
125
126/// Who may read, write and refer to what.
127///
128/// A subject is a link address; the null link (0) is a guest, which no rule
129/// but one for `Anything` matches. A link is given as `(index, source,
130/// target)`, so a link that is not stored yet, or not any more, can be asked
131/// about too. `data` is the store the links are in, for their types.
132pub trait AccessPolicy {
133    /// The markers the rules are made of.
134    fn markers(&self) -> PermissionMarkers;
135
136    /// Whether `subject` may read `link`; writing allows reading.
137    fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool;
138
139    /// Whether `subject` may write `link`, as it is or as it will be.
140    fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool;
141
142    /// Whether `subject` may write anything at all, and so create links.
143    fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool;
144
145    /// Whether `subject` may refer to `link` although it need not read it. A
146    /// missing address is asked about as an untyped link. A policy without
147    /// this right allows references to readable links only.
148    fn can_reference(
149        &mut self,
150        _data: &mut dyn NamedTypeLinks,
151        _subject: u32,
152        _link: &Link,
153    ) -> bool {
154        false
155    }
156}
157
158impl<P: AccessPolicy + ?Sized> AccessPolicy for &mut P {
159    fn markers(&self) -> PermissionMarkers {
160        (**self).markers()
161    }
162
163    fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
164        (**self).can_read(data, subject, link)
165    }
166
167    fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
168        (**self).can_write(data, subject, link)
169    }
170
171    fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool {
172        (**self).can_create(data, subject)
173    }
174
175    fn can_reference(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
176        (**self).can_reference(data, subject, link)
177    }
178}
179
180impl<P: AccessPolicy + ?Sized> AccessPolicy for Box<P> {
181    fn markers(&self) -> PermissionMarkers {
182        (**self).markers()
183    }
184
185    fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
186        (**self).can_read(data, subject, link)
187    }
188
189    fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
190        (**self).can_write(data, subject, link)
191    }
192
193    fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool {
194        (**self).can_create(data, subject)
195    }
196
197    fn can_reference(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
198        (**self).can_reference(data, subject, link)
199    }
200}
201
202/// Permissions stored as links; see the [module documentation](self).
203pub struct PermissionPolicy {
204    markers: PermissionMarkers,
205    types: TypeMarkers,
206    rules: Option<Box<dyn NamedTypeLinks>>,
207}
208
209impl PermissionPolicy {
210    /// The policy of the rules marked by `markers`, with the types of
211    /// `types`: in the data when `rules` is `None`, else in `rules`.
212    pub fn new(
213        markers: PermissionMarkers,
214        types: TypeMarkers,
215        rules: Option<Box<dyn NamedTypeLinks>>,
216    ) -> Self {
217        Self {
218            markers,
219            types,
220            rules,
221        }
222    }
223
224    /// The policy of the rules in `data`, whose points named `Type`,
225    /// `Extends`, `AllowRead`, `AllowWrite`, `Anything` and `AllowReference`
226    /// are created when missing.
227    pub fn in_data<L: NamedTypeLinks + ?Sized>(data: &mut L) -> Result<Self> {
228        let types = TypeMarkers::ensure(data)?;
229        let markers = PermissionMarkers::ensure(data)?;
230        Ok(Self::new(markers, types, None))
231    }
232
233    /// The policy of the rules in `rules`, a store of their own, over `data`,
234    /// whose points are created when missing as by [`in_data`](Self::in_data).
235    pub fn with_rules<L: NamedTypeLinks + ?Sized>(
236        data: &mut L,
237        rules: Box<dyn NamedTypeLinks>,
238    ) -> Result<Self> {
239        let types = TypeMarkers::ensure(data)?;
240        let markers = PermissionMarkers::ensure(data)?;
241        Ok(Self::new(markers, types, Some(rules)))
242    }
243
244    /// The type markers of the data.
245    pub fn types(&self) -> TypeMarkers {
246        self.types
247    }
248
249    /// The store of the rules when they are kept apart from the data.
250    pub fn rules_mut(&mut self) -> Option<&mut (dyn NamedTypeLinks + 'static)> {
251        self.rules.as_deref_mut()
252    }
253
254    /// The store of the rules: `data` itself, or the rules' own store.
255    pub fn rules_of<'a>(
256        &'a mut self,
257        data: &'a mut dyn NamedTypeLinks,
258    ) -> &'a mut dyn NamedTypeLinks {
259        match self.rules.as_deref_mut() {
260            Some(rules) => rules,
261            None => data,
262        }
263    }
264
265    /// The rules `(Subject Object)` that `marker` marks, in the order of their marks.
266    pub fn granted(&mut self, data: &mut dyn NamedTypeLinks, marker: u32) -> Vec<(u32, u32)> {
267        let rules = self.rules_of(data);
268        let mut marks: Vec<(u32, u32)> = rules
269            .query_links(None, Some(marker), None)
270            .into_iter()
271            // The marker point (x: x x) itself is no mark; in a store of rules
272            // of their own a mark may sit at the marker's address.
273            .filter(|mark| mark.index != marker || mark.target != marker)
274            .map(|mark| (mark.index, mark.target))
275            .collect();
276        marks.sort_by_key(|&(mark, _)| mark);
277        marks
278            .into_iter()
279            .filter_map(|(_, rule)| {
280                if rule == 0 {
281                    return None;
282                }
283                rules.get_link(rule).map(|link| (link.source, link.target))
284            })
285            .collect()
286    }
287
288    /// Whether a rule of `marker` lets `subject` at `link`.
289    pub fn allows(
290        &mut self,
291        data: &mut dyn NamedTypeLinks,
292        marker: u32,
293        subject: u32,
294        link: &Link,
295    ) -> bool {
296        let granted = self.granted(data, marker);
297        if granted.is_empty() {
298            return false;
299        }
300        let anything = self.markers.anything;
301        let mut types = TypesDecorator::with_markers(data, self.types);
302        granted.into_iter().any(|(rule_subject, rule_object)| {
303            is_subject(&mut types, anything, subject, rule_subject)
304                && (rule_object == anything || types.is_of_link(link, rule_object))
305        })
306    }
307
308    /// Writes a rule into `rules`: `subject` may `access` the links of
309    /// `object`. The rule is the pair `(subject object)` marked by `(marker
310    /// rule)`; returns the pair.
311    pub fn allow<L: NamedTypeLinks + ?Sized>(
312        rules: &mut L,
313        markers: PermissionMarkers,
314        access: PermissionAccess,
315        subject: u32,
316        object: u32,
317    ) -> Result<u32> {
318        if subject == markers.allow_read
319            || subject == markers.allow_write
320            || subject == markers.allow_reference
321        {
322            // A pair from a marker would read as a mark.
323            bail!("A marker cannot be a subject");
324        }
325        // A rule given twice is the same rule: the pair and its mark are
326        // found before they are made.
327        let rule = rules.try_get_or_create(subject, object)?;
328        rules.try_get_or_create(markers.of(access), rule)?;
329        Ok(rule)
330    }
331
332    /// Parses `read`, `write` or `reference`.
333    pub fn parse_access(access: &str) -> Result<PermissionAccess> {
334        PermissionAccess::parse(access)
335    }
336}
337
338/// Whether `subject` is `type_id` or of it; a guest is only `Anything`.
339fn is_subject<T: Types>(types: &mut T, anything: u32, subject: u32, type_id: u32) -> bool {
340    type_id == anything || (subject != 0 && types.is_a(subject, type_id))
341}
342
343impl AccessPolicy for PermissionPolicy {
344    fn markers(&self) -> PermissionMarkers {
345        self.markers
346    }
347
348    fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
349        let markers = self.markers;
350        self.allows(data, markers.allow_read, subject, link)
351            || self.allows(data, markers.allow_write, subject, link)
352    }
353
354    fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
355        let marker = self.markers.allow_write;
356        self.allows(data, marker, subject, link)
357    }
358
359    fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool {
360        let marker = self.markers.allow_write;
361        let granted = self.granted(data, marker);
362        let anything = self.markers.anything;
363        let mut types = TypesDecorator::with_markers(data, self.types);
364        granted
365            .into_iter()
366            .any(|(rule_subject, _)| is_subject(&mut types, anything, subject, rule_subject))
367    }
368
369    fn can_reference(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool {
370        let markers = self.markers;
371        if (subject != 0 && link.index == subject)
372            || self.allows(data, markers.allow_reference, subject, link)
373        {
374            return true;
375        }
376        // The object of a rule of the subject is named by that rule: a readable
377        // link of that type shows its address anyway.
378        [
379            markers.allow_read,
380            markers.allow_write,
381            markers.allow_reference,
382        ]
383        .into_iter()
384        .any(|marker| {
385            let granted = self.granted(data, marker);
386            let mut types = TypesDecorator::with_markers(&mut *data, self.types);
387            granted.into_iter().any(|(rule_subject, rule_object)| {
388                rule_object == link.index
389                    && is_subject(&mut types, markers.anything, subject, rule_subject)
390            })
391        })
392    }
393}
394
395/// The store as one subject sees it; see the [module documentation](self).
396///
397/// Reads skip the links the subject may not read, so a hidden link is as
398/// missing as a deleted one: to [`exists`](NamedTypeLinks::exists), to
399/// [`get_link`](NamedTypeLinks::get_link), and to every write, which answers
400/// `Link not found`. A write the subject may not make fails with
401/// [`Forbidden`] and changes nothing. An update needs the right to write the
402/// link before and after it.
403///
404/// A link the subject created through this view is its own while it has no
405/// type (its source is 0), so it can give it one. [`forget`](Self::forget)
406/// drops that claim when the link is gone.
407///
408/// The store below may change more than the link asked for: deleting a link
409/// deletes the links that use it, and an update that makes a link equal to
410/// another merges them, repointing the usages. Every link a write changes
411/// must be the subject's to change; when one is not, the write is undone and
412/// refused as a whole.
413///
414/// A reference needs [`can_reference`](Self::can_reference): without the right
415/// an unreadable address answers as a missing one, to
416/// [`reference_exists`](NamedTypeLinks::reference_exists), to a create and to
417/// an update. The write check runs first, so a type the subject may not write
418/// stays [`Forbidden`] for hidden and missing alike. A reference a link already
419/// holds may stay; once replaced, it cannot be put back without the right.
420/// Choosing the address of a new link
421/// ([`try_ensure_created`](NamedTypeLinks::try_ensure_created)) is a reference
422/// too, so a limited subject cannot choose addresses.
423///
424/// Names follow references: [`get_name`](NamedTypeLinks::get_name) and
425/// [`get_by_name`](NamedTypeLinks::get_by_name) answer only for a link the
426/// subject may refer to, so any other name is an unknown name. Naming or
427/// unnaming a link needs the right to write it, and taking a name needs the
428/// right to write the link that holds it.
429pub struct PermissionsDecorator<L: NamedTypeLinks, P: AccessPolicy = PermissionPolicy> {
430    links: L,
431    policy: P,
432    subject: u32,
433    created: HashSet<u32>,
434}
435
436impl<L: NamedTypeLinks, P: AccessPolicy> PermissionsDecorator<L, P> {
437    /// `links` as `subject` (the null link is a guest) sees it under `policy`.
438    pub fn new(links: L, policy: P, subject: u32) -> Self {
439        Self {
440            links,
441            policy,
442            subject,
443            created: HashSet::new(),
444        }
445    }
446
447    /// The same view with the links `created` before taken as the subject's own.
448    pub fn with_created(mut self, created: HashSet<u32>) -> Self {
449        self.created = created;
450        self
451    }
452
453    /// The subject the store is seen as.
454    pub fn subject(&self) -> u32 {
455        self.subject
456    }
457
458    pub fn set_subject(&mut self, subject: u32) {
459        self.subject = subject;
460    }
461
462    /// The links the subject created through this view and still has.
463    pub fn created(&self) -> &HashSet<u32> {
464        &self.created
465    }
466
467    /// Swaps the links taken as the subject's own, returning the old ones.
468    pub fn replace_created(&mut self, created: HashSet<u32>) -> HashSet<u32> {
469        std::mem::replace(&mut self.created, created)
470    }
471
472    pub fn policy(&self) -> &P {
473        &self.policy
474    }
475
476    pub fn policy_mut(&mut self) -> &mut P {
477        &mut self.policy
478    }
479
480    pub fn inner(&self) -> &L {
481        &self.links
482    }
483
484    pub fn inner_mut(&mut self) -> &mut L {
485        &mut self.links
486    }
487
488    pub fn into_inner(self) -> L {
489        self.links
490    }
491
492    /// Whether `link` is the subject's own: created through this view and
493    /// still without a type.
494    pub fn owns(&self, link: &Link) -> bool {
495        link.source == 0 && self.created.contains(&link.index)
496    }
497
498    /// Whether the subject may read `link`.
499    pub fn can_read(&mut self, link: &Link) -> bool {
500        self.owns(link) || self.policy.can_read(&mut self.links, self.subject, link)
501    }
502
503    /// Whether the subject may write `link` as it is.
504    pub fn can_write(&mut self, link: &Link) -> bool {
505        self.owns(link) || self.policy.can_write(&mut self.links, self.subject, link)
506    }
507
508    /// Whether the subject may refer to the address `id`, which may hold no
509    /// link: a missing address is judged as an untyped link, so only a rule
510    /// for `Anything` covers it.
511    pub fn can_reference(&mut self, id: u32) -> bool {
512        let link = self.links.get_link(id).unwrap_or(Link::new(id, 0, 0));
513        self.owns_triplet(&link)
514            || self.can_read(&link)
515            || self
516                .policy
517                .can_reference(&mut self.links, self.subject, &link)
518    }
519
520    /// The references `before` does not hold yet need the right: without it
521    /// the address answers as a missing one.
522    fn check_references(&mut self, before: Option<&Link>, source: u32, target: u32) -> Result<()> {
523        for part in [source, target] {
524            let held = before.is_some_and(|link| {
525                part == link.index || part == link.source || part == link.target
526            });
527            if part != 0 && !held && !self.can_reference(part) {
528                return Err(LinkError::not_found(part).into());
529            }
530        }
531        Ok(())
532    }
533
534    /// [`owns`](Self::owns) when the store is read as triplets, where a point
535    /// that is only its own type has no type yet either.
536    pub(crate) fn owns_triplet(&self, link: &Link) -> bool {
537        let point = link.source == link.index && link.target == link.index;
538        self.owns(link) || (point && self.created.contains(&link.index))
539    }
540
541    /// [`can_read`](Self::can_read) when the store is read as triplets.
542    pub(crate) fn can_read_triplet(&mut self, link: &Link) -> bool {
543        self.owns_triplet(link) || self.policy.can_read(&mut self.links, self.subject, link)
544    }
545
546    /// [`can_write`](Self::can_write) when the store is read as triplets.
547    pub(crate) fn can_write_triplet(&mut self, link: &Link) -> bool {
548        self.owns_triplet(link) || self.policy.can_write(&mut self.links, self.subject, link)
549    }
550
551    /// Whether the policy lets the subject write `link`, ownership aside.
552    pub(crate) fn policy_can_write(&mut self, link: &Link) -> bool {
553        self.policy.can_write(&mut self.links, self.subject, link)
554    }
555
556    pub(crate) fn policy_can_create(&mut self) -> bool {
557        self.policy.can_create(&mut self.links, self.subject)
558    }
559
560    /// The link at `index` is one the subject made on the store below.
561    pub(crate) fn remember(&mut self, index: u32) {
562        self.created.insert(index);
563    }
564
565    /// The store below and the policy, to judge a request on a layer over the
566    /// same store.
567    pub(crate) fn parts_mut(&mut self) -> (&mut L, &mut P) {
568        (&mut self.links, &mut self.policy)
569    }
570
571    /// The link at `index` is gone: a new one there is not the subject's own.
572    pub fn forget(&mut self, index: u32) {
573        self.created.remove(&index);
574    }
575
576    /// The stored link at `index`, `None` when there is none; a hidden one is
577    /// not found.
578    fn visible(&mut self, index: u32) -> Result<Option<Link>> {
579        if index == 0 {
580            return Ok(None);
581        }
582        let Some(link) = self.links.get_link(index) else {
583            return Ok(None);
584        };
585        if !self.can_read(&link) {
586            return Err(LinkError::not_found(index).into());
587        }
588        Ok(Some(link))
589    }
590
591    fn require_writable(&mut self, index: u32, what: &str) -> Result<()> {
592        let link = self
593            .visible(index)?
594            .ok_or_else(|| anyhow::Error::from(LinkError::not_found(index)))?;
595        if !self.can_write(&link) {
596            return Err(Forbidden::new(format!("{what} {index}")).into());
597        }
598        Ok(())
599    }
600
601    fn require_create(&mut self, source: u32, target: u32) -> Result<()> {
602        if !self.policy_can_create()
603            || (source != 0 && !self.policy_can_write(&Link::new(0, source, target)))
604        {
605            return Err(Forbidden::new("create").into());
606        }
607        Ok(())
608    }
609
610    /// Whether the subject may change a link from `before` to `after`.
611    fn allowed(&mut self, before: Option<Link>, after: Option<Link>) -> bool {
612        match (before, after) {
613            (Some(was), Some(now)) if was == now => true,
614            (None, made) => {
615                self.policy_can_create()
616                    && made.is_none_or(|made| made.source == 0 || self.policy_can_write(&made))
617            }
618            (Some(was), None) => self.can_write(&was),
619            (Some(was), Some(now)) => {
620                (self.owns(&was) && now.source == 0)
621                    || (self.can_write(&was) && self.policy_can_write(&now))
622            }
623        }
624    }
625
626    /// Makes a write on the store below, then checks every link it changed:
627    /// the link asked for is checked already, any other must be the
628    /// subject's to change, or the write is undone and refused.
629    fn checked(
630        &mut self,
631        what: &str,
632        index: u32,
633        mut log: LinksUndoLog,
634        write: impl FnOnce(&mut L, ChangeObserver<'_>) -> Result<Link>,
635        observer: ChangeObserver<'_>,
636    ) -> Result<Link> {
637        let result = write(&mut self.links, &mut |before, after| {
638            log.record_observed(before, after)
639        });
640        let result = match result {
641            Ok(result) => result,
642            Err(error) => {
643                if let Err(undo) = self.undo(&mut log) {
644                    return Err(error.context(format!("and undoing it failed: {undo}")));
645                }
646                return Err(error);
647            }
648        };
649        let mut net: HashMap<u32, (Option<Link>, Option<Link>)> = HashMap::new();
650        let mut order = Vec::new();
651        for &(before, after) in log.changes() {
652            let Some(at) = before.or(after).map(|link| link.index) else {
653                continue;
654            };
655            match net.get_mut(&at) {
656                Some(known) => known.1 = after,
657                None => {
658                    net.insert(at, (before, after));
659                    order.push(at);
660                }
661            }
662        }
663        for &at in &order {
664            let (first, last) = net[&at];
665            if at == index || self.allowed(first, last) {
666                continue;
667            }
668            self.undo(&mut log)?;
669            return Err(Forbidden::new(what).into());
670        }
671        for &at in &order {
672            if net[&at].1.is_none() {
673                self.created.remove(&at);
674            }
675        }
676        for &(before, after) in log.changes() {
677            observer(
678                before.unwrap_or(Link::null()),
679                after.unwrap_or(Link::null()),
680            );
681        }
682        Ok(result)
683    }
684
685    fn undo(&mut self, log: &mut LinksUndoLog) -> Result<()> {
686        for gone in log.undo(&mut self.links)? {
687            self.created.remove(&gone);
688        }
689        Ok(())
690    }
691
692    fn panic_on<T>(result: Result<T>) -> T {
693        result.unwrap_or_else(|error| panic!("{error}"))
694    }
695}
696
697impl<L: NamedTypeLinks, P: AccessPolicy> NamedTypeLinks for PermissionsDecorator<L, P> {
698    /// Panics when the subject may not create; use
699    /// [`try_create`](NamedTypeLinks::try_create).
700    fn create(&mut self, source: u32, target: u32) -> u32 {
701        Self::panic_on(self.try_create(source, target))
702    }
703
704    /// Panics when the subject may not create; use
705    /// [`try_ensure_created`](NamedTypeLinks::try_ensure_created).
706    fn ensure_created(&mut self, id: u32) -> u32 {
707        Self::panic_on(self.try_ensure_created(id))
708    }
709
710    fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
711        if id != 0 && self.exists(id) {
712            return Ok(id);
713        }
714        if !self.policy_can_create() {
715            return Err(Forbidden::new("create").into());
716        }
717        if id != 0 && !self.can_reference(id) {
718            return Err(LinkError::not_found(id).into());
719        }
720        if id != 0 && self.links.exists(id) {
721            // The subject may refer to this hidden link: the point must not land on it.
722            bail!("Link {id} exists");
723        }
724        let created = self.links.try_ensure_created(id)?;
725        if id != 0 {
726            self.created.insert(created);
727        }
728        Ok(created)
729    }
730
731    fn get_link(&mut self, id: u32) -> Option<Link> {
732        let link = self.links.get_link(id)?;
733        self.can_read(&link).then_some(link)
734    }
735
736    fn exists(&mut self, id: u32) -> bool {
737        self.get_link(id).is_some()
738    }
739
740    fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
741        self.require_create(source, target)?;
742        self.check_references(None, source, target)?;
743        let id = self.links.try_create(source, target)?;
744        self.created.insert(id);
745        Ok(id)
746    }
747
748    /// A link the subject may not refer to is as missing as a deleted one.
749    fn reference_exists(&mut self, id: u32) -> bool {
750        self.links.reference_exists(id) && self.can_reference(id)
751    }
752
753    fn claims(&mut self, id: u32) -> Option<bool> {
754        self.links.claims(id)
755    }
756
757    fn next_created_addresses(&mut self, count: usize) -> Result<Vec<u32>> {
758        self.links.next_created_addresses(count)
759    }
760
761    fn update_observed(
762        &mut self,
763        id: u32,
764        source: u32,
765        target: u32,
766        observer: ChangeObserver<'_>,
767    ) -> Result<Link> {
768        let Some(before) = self.visible(id)? else {
769            return self.links.update_observed(id, source, target, observer);
770        };
771        let after = Link::new(id, source, target);
772        if !(self.owns(&before) && source == 0)
773            && (!self.can_write(&before) || !self.policy_can_write(&after))
774        {
775            return Err(Forbidden::new(format!("update {id}")).into());
776        }
777        self.check_references(Some(&before), source, target)?;
778        let mut log = LinksUndoLog::new();
779        keep_names_before_update(&mut log, &mut self.links, id, source, target)?;
780        self.checked(
781            &format!("update {id}"),
782            id,
783            log,
784            |links, recorder| links.update_observed(id, source, target, recorder),
785            observer,
786        )
787    }
788
789    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
790        let Some(before) = self.visible(id)? else {
791            return self.links.delete_observed(id, observer);
792        };
793        if !self.can_write(&before) {
794            return Err(Forbidden::new(format!("delete {id}")).into());
795        }
796        let mut log = LinksUndoLog::new();
797        log.keep_names_of_usages(&mut self.links, id)?;
798        self.checked(
799            &format!("delete {id}"),
800            id,
801            log,
802            |links, recorder| links.delete_observed(id, recorder),
803            observer,
804        )
805    }
806
807    fn all_links(&mut self) -> Vec<Link> {
808        let links = self.links.all_links();
809        links
810            .into_iter()
811            .filter(|link| self.can_read(link))
812            .collect()
813    }
814
815    fn query_links(
816        &mut self,
817        index: Option<u32>,
818        source: Option<u32>,
819        target: Option<u32>,
820    ) -> Vec<Link> {
821        let links = self.links.query_links(index, source, target);
822        links
823            .into_iter()
824            .filter(|link| self.can_read(link))
825            .collect()
826    }
827
828    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
829        let found = self.links.search(source, target)?;
830        self.exists(found).then_some(found)
831    }
832
833    /// Panics when the subject may not create; use
834    /// [`try_get_or_create`](NamedTypeLinks::try_get_or_create).
835    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
836        Self::panic_on(self.try_get_or_create(source, target))
837    }
838
839    /// The name of a link the subject may refer to; any other has none.
840    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
841        if !self.can_reference(id) {
842            return Ok(None);
843        }
844        self.links.get_name(id)
845    }
846
847    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
848        self.require_writable(id, "set-name")?;
849        if let Some(holder) = self.links.get_by_name(name)? {
850            if holder != 0 && holder != id {
851                if let Some(link) = self.links.get_link(holder) {
852                    if !self.can_write(&link) {
853                        // Taking the name takes it from its link.
854                        return Err(Forbidden::new(format!("set-name {id}")).into());
855                    }
856                }
857            }
858        }
859        self.links.set_name(id, name)
860    }
861
862    /// The link of a name, when the subject may refer to it; any other name
863    /// is an unknown name.
864    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
865        let found = self.links.get_by_name(name)?;
866        Ok(found.filter(|&id| id == 0 || self.can_reference(id)))
867    }
868
869    fn remove_name(&mut self, id: u32) -> Result<()> {
870        if let Some(link) = self.links.get_link(id) {
871            if !self.can_read(&link) {
872                // Nothing the subject sees has a name to remove.
873                return Ok(());
874            }
875            self.require_writable(id, "remove-name")?;
876        }
877        self.links.remove_name(id)
878    }
879
880    fn save(&mut self) -> Result<()> {
881        self.links.save()
882    }
883}