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