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 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/// A write a subject may not make; it reads `Forbidden: what`.
47#[derive(Debug, Clone, PartialEq, Eq, Error)]
48#[error("Forbidden: {what}")]
49pub struct Forbidden {
50    /// What was refused, such as `update 7`.
51    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/// What a rule allows.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub enum PermissionAccess {
63    /// Reading: the link is seen.
64    Read,
65    /// Reading and writing: the link may be created, updated, deleted and named.
66    Write,
67    /// Referring: the link may be used in another link, not seen.
68    Reference,
69}
70
71impl PermissionAccess {
72    /// Parses `read`, `write` or `reference`.
73    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/// The four points of the data permission rules are made of: the markers
84/// `AllowRead`, `AllowWrite` and `AllowReference` of rules and `Anything`, which
85/// matches every subject or every link.
86#[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    /// The name of the marker of read rules.
96    pub const ALLOW_READ_NAME: &'static str = "AllowRead";
97    /// The name of the marker of write rules.
98    pub const ALLOW_WRITE_NAME: &'static str = "AllowWrite";
99    /// The name of the marker that matches every subject or link.
100    pub const ANYTHING_NAME: &'static str = "Anything";
101    /// The name of the marker of reference rules.
102    pub const ALLOW_REFERENCE_NAME: &'static str = "AllowReference";
103
104    /// The points named `AllowRead`, `AllowWrite`, `Anything` and
105    /// `AllowReference`, each created as a point `(x: x x)` and named when
106    /// missing. `AllowReference` comes last, so the others keep their addresses
107    /// in a store made before it was added.
108    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    /// The marker of the rules of `access`.
118    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
127/// Who may read, write and refer to what.
128///
129/// A subject is a link address; the null link (0) is a guest, which no rule
130/// but one for `Anything` matches. A link is given as `(index, source,
131/// target)`, so a link that is not stored yet, or not any more, can be asked
132/// about too. `data` is the store the links are in, for their types.
133pub trait AccessPolicy {
134    /// The markers the rules are made of.
135    fn markers(&self) -> PermissionMarkers;
136
137    /// Whether `subject` may read `link`; writing allows reading.
138    fn can_read(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool;
139
140    /// Whether `subject` may write `link`, as it is or as it will be.
141    fn can_write(&mut self, data: &mut dyn NamedTypeLinks, subject: u32, link: &Link) -> bool;
142
143    /// Whether `subject` may write anything at all, and so create links.
144    fn can_create(&mut self, data: &mut dyn NamedTypeLinks, subject: u32) -> bool;
145
146    /// Whether `subject` may refer to `link` although it need not read it. A
147    /// missing address is asked about as an untyped link. A policy without
148    /// this right allows references to readable links only.
149    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
203/// Permissions stored as links; see the [module documentation](self).
204pub struct PermissionPolicy {
205    markers: PermissionMarkers,
206    types: TypeMarkers,
207    rules: Option<Box<dyn NamedTypeLinks>>,
208}
209
210impl PermissionPolicy {
211    /// The policy of the rules marked by `markers`, with the types of
212    /// `types`: in the data when `rules` is `None`, else in `rules`.
213    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    /// The policy of the rules in `data`, whose points named `Type`,
226    /// `Extends`, `AllowRead`, `AllowWrite`, `Anything` and `AllowReference`
227    /// are created when missing.
228    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    /// The policy of the rules in `rules`, a store of their own, over `data`,
235    /// whose points are created when missing as by [`in_data`](Self::in_data).
236    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    /// The type markers of the data.
246    pub fn types(&self) -> TypeMarkers {
247        self.types
248    }
249
250    /// The store of the rules when they are kept apart from the data.
251    pub fn rules_mut(&mut self) -> Option<&mut (dyn NamedTypeLinks + 'static)> {
252        self.rules.as_deref_mut()
253    }
254
255    /// The store of the rules: `data` itself, or the rules' own store.
256    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    /// The rules `(Subject Object)` that `marker` marks, in the order of their marks.
267    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            // The marker point (x: x x) itself is no mark; in a store of rules
273            // of their own a mark may sit at the marker's address.
274            .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    /// Whether a rule of `marker` lets `subject` at `link`.
290    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    /// Writes a rule into `rules`: `subject` may `access` the links of
310    /// `object`. The rule is the pair `(subject object)` marked by `(marker
311    /// rule)`; returns the pair.
312    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            // A pair from a marker would read as a mark.
324            bail!("A marker cannot be a subject");
325        }
326        // A rule given twice is the same rule: the pair and its mark are
327        // found before they are made.
328        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    /// Parses `read`, `write` or `reference`.
334    pub fn parse_access(access: &str) -> Result<PermissionAccess> {
335        PermissionAccess::parse(access)
336    }
337}
338
339/// Whether `subject` is `type_id` or of it; a guest is only `Anything`.
340fn 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        // The object of a rule of the subject is named by that rule: a readable
378        // link of that type shows its address anyway.
379        [
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
396/// The store as one subject sees it; see the [module documentation](self).
397///
398/// Reads skip the links the subject may not read, so a hidden link is as
399/// missing as a deleted one: to [`exists`](NamedTypeLinks::exists), to
400/// [`get_link`](NamedTypeLinks::get_link), and to every write, which answers
401/// `Link not found`. A write the subject may not make fails with
402/// [`Forbidden`] and changes nothing. An update needs the right to write the
403/// link before and after it.
404///
405/// A link the subject created through this view is its own while it has no
406/// type (its source is 0), so it can give it one. [`forget`](Self::forget)
407/// drops that claim when the link is gone.
408///
409/// The store below may change more than the link asked for: deleting a link
410/// deletes the links that use it, and an update that makes a link equal to
411/// another merges them, repointing the usages. Every link a write changes
412/// must be the subject's to change; when one is not, the write is undone and
413/// refused as a whole.
414///
415/// A reference needs [`can_reference`](Self::can_reference): without the right
416/// an unreadable address answers as a missing one, to
417/// [`reference_exists`](NamedTypeLinks::reference_exists), to a create and to
418/// an update. The write check runs first, so a type the subject may not write
419/// stays [`Forbidden`] for hidden and missing alike. A reference a link already
420/// holds may stay; once replaced, it cannot be put back without the right.
421/// Choosing the address of a new link
422/// ([`try_ensure_created`](NamedTypeLinks::try_ensure_created)) is a reference
423/// too, so a limited subject cannot choose addresses.
424///
425/// Names follow references: [`get_name`](NamedTypeLinks::get_name) and
426/// [`get_by_name`](NamedTypeLinks::get_by_name) answer only for a link the
427/// subject may refer to, so any other name is an unknown name. Naming or
428/// unnaming a link needs the right to write it, and taking a name needs the
429/// right to write the link that holds it.
430pub 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    /// `links` as `subject` (the null link is a guest) sees it under `policy`.
439    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    /// The same view with the links `created` before taken as the subject's own.
449    pub fn with_created(mut self, created: HashSet<u32>) -> Self {
450        self.created = created;
451        self
452    }
453
454    /// The subject the store is seen as.
455    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    /// The links the subject created through this view and still has.
464    pub fn created(&self) -> &HashSet<u32> {
465        &self.created
466    }
467
468    /// Swaps the links taken as the subject's own, returning the old ones.
469    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    /// Whether `link` is the subject's own: created through this view and
494    /// still without a type.
495    pub fn owns(&self, link: &Link) -> bool {
496        link.source == 0 && self.created.contains(&link.index)
497    }
498
499    /// Whether the subject may read `link`.
500    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    /// Whether the subject may write `link` as it is.
505    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    /// Whether the subject may refer to the address `id`, which may hold no
510    /// link: a missing address is judged as an untyped link, so only a rule
511    /// for `Anything` covers it.
512    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    /// The references `before` does not hold yet need the right: without it
522    /// the address answers as a missing one.
523    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    /// [`owns`](Self::owns) when the store is read as triplets, where a point
536    /// that is only its own type has no type yet either.
537    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    /// [`can_read`](Self::can_read) when the store is read as triplets.
543    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    /// [`can_write`](Self::can_write) when the store is read as triplets.
548    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    /// Whether the policy lets the subject write `link`, ownership aside.
553    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    /// The link at `index` is one the subject made on the store below.
562    pub(crate) fn remember(&mut self, index: u32) {
563        self.created.insert(index);
564    }
565
566    /// The store below and the policy, to judge a request on a layer over the
567    /// same store.
568    pub(crate) fn parts_mut(&mut self) -> (&mut L, &mut P) {
569        (&mut self.links, &mut self.policy)
570    }
571
572    /// The link at `index` is gone: a new one there is not the subject's own.
573    pub fn forget(&mut self, index: u32) {
574        self.created.remove(&index);
575    }
576
577    /// The stored link at `index`, `None` when there is none; a hidden one is
578    /// not found.
579    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    /// Whether the subject may change a link from `before` to `after`.
612    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    /// Makes a write on the store below, then checks every link it changed:
628    /// the link asked for is checked already, any other must be the
629    /// subject's to change, or the write is undone and refused.
630    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}