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