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    /// Whether the policy lets the subject write `link`, ownership aside.
432    fn policy_can_write(&mut self, link: &Link) -> bool {
433        self.policy.can_write(&mut self.links, self.subject, link)
434    }
435
436    fn policy_can_create(&mut self) -> bool {
437        self.policy.can_create(&mut self.links, self.subject)
438    }
439
440    /// The link at `index` is gone: a new one there is not the subject's own.
441    pub fn forget(&mut self, index: u32) {
442        self.created.remove(&index);
443    }
444
445    /// The stored link at `index`, `None` when there is none; a hidden one is
446    /// not found.
447    fn visible(&mut self, index: u32) -> Result<Option<Link>> {
448        if index == 0 {
449            return Ok(None);
450        }
451        let Some(link) = self.links.get_link(index) else {
452            return Ok(None);
453        };
454        if !self.can_read(&link) {
455            return Err(LinkError::not_found(index).into());
456        }
457        Ok(Some(link))
458    }
459
460    fn require_writable(&mut self, index: u32, what: &str) -> Result<()> {
461        let link = self
462            .visible(index)?
463            .ok_or_else(|| anyhow::Error::from(LinkError::not_found(index)))?;
464        if !self.can_write(&link) {
465            return Err(Forbidden::new(format!("{what} {index}")).into());
466        }
467        Ok(())
468    }
469
470    fn require_create(&mut self, source: u32, target: u32) -> Result<()> {
471        if !self.policy_can_create()
472            || (source != 0 && !self.policy_can_write(&Link::new(0, source, target)))
473        {
474            return Err(Forbidden::new("create").into());
475        }
476        Ok(())
477    }
478
479    /// Whether the subject may change a link from `before` to `after`.
480    fn allowed(&mut self, before: Option<Link>, after: Option<Link>) -> bool {
481        match (before, after) {
482            (Some(was), Some(now)) if was == now => true,
483            (None, made) => {
484                self.policy_can_create()
485                    && made.is_none_or(|made| made.source == 0 || self.policy_can_write(&made))
486            }
487            (Some(was), None) => self.can_write(&was),
488            (Some(was), Some(now)) => {
489                (self.owns(&was) && now.source == 0)
490                    || (self.can_write(&was) && self.policy_can_write(&now))
491            }
492        }
493    }
494
495    /// Makes a write on the store below, then checks every link it changed:
496    /// the link asked for is checked already, any other must be the
497    /// subject's to change, or the write is undone and refused.
498    fn checked(
499        &mut self,
500        what: &str,
501        index: u32,
502        mut log: LinksUndoLog,
503        write: impl FnOnce(&mut L, ChangeObserver<'_>) -> Result<Link>,
504        observer: ChangeObserver<'_>,
505    ) -> Result<Link> {
506        let result = write(&mut self.links, &mut |before, after| {
507            log.record_observed(before, after)
508        });
509        let result = match result {
510            Ok(result) => result,
511            Err(error) => {
512                if let Err(undo) = self.undo(&mut log) {
513                    return Err(error.context(format!("and undoing it failed: {undo}")));
514                }
515                return Err(error);
516            }
517        };
518        let mut net: HashMap<u32, (Option<Link>, Option<Link>)> = HashMap::new();
519        let mut order = Vec::new();
520        for &(before, after) in log.changes() {
521            let Some(at) = before.or(after).map(|link| link.index) else {
522                continue;
523            };
524            match net.get_mut(&at) {
525                Some(known) => known.1 = after,
526                None => {
527                    net.insert(at, (before, after));
528                    order.push(at);
529                }
530            }
531        }
532        for &at in &order {
533            let (first, last) = net[&at];
534            if at == index || self.allowed(first, last) {
535                continue;
536            }
537            self.undo(&mut log)?;
538            return Err(Forbidden::new(what).into());
539        }
540        for &at in &order {
541            if net[&at].1.is_none() {
542                self.created.remove(&at);
543            }
544        }
545        for &(before, after) in log.changes() {
546            observer(
547                before.unwrap_or(Link::null()),
548                after.unwrap_or(Link::null()),
549            );
550        }
551        Ok(result)
552    }
553
554    fn undo(&mut self, log: &mut LinksUndoLog) -> Result<()> {
555        for gone in log.undo(&mut self.links)? {
556            self.created.remove(&gone);
557        }
558        Ok(())
559    }
560
561    fn panic_on<T>(result: Result<T>) -> T {
562        result.unwrap_or_else(|error| panic!("{error}"))
563    }
564}
565
566impl<L: NamedTypeLinks, P: AccessPolicy> NamedTypeLinks for PermissionsDecorator<L, P> {
567    /// Panics when the subject may not create; use
568    /// [`try_create`](NamedTypeLinks::try_create).
569    fn create(&mut self, source: u32, target: u32) -> u32 {
570        Self::panic_on(self.try_create(source, target))
571    }
572
573    /// Panics when the subject may not create; use
574    /// [`try_ensure_created`](NamedTypeLinks::try_ensure_created).
575    fn ensure_created(&mut self, id: u32) -> u32 {
576        Self::panic_on(self.try_ensure_created(id))
577    }
578
579    fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
580        if id != 0 && self.visible(id)?.is_some() {
581            return Ok(id);
582        }
583        if !self.policy_can_create() {
584            return Err(Forbidden::new("create").into());
585        }
586        let missing = id != 0 && !self.links.exists(id);
587        let id = self.links.try_ensure_created(id)?;
588        if missing {
589            self.created.insert(id);
590        }
591        Ok(id)
592    }
593
594    fn get_link(&mut self, id: u32) -> Option<Link> {
595        let link = self.links.get_link(id)?;
596        self.can_read(&link).then_some(link)
597    }
598
599    fn exists(&mut self, id: u32) -> bool {
600        self.get_link(id).is_some()
601    }
602
603    fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
604        self.require_create(source, target)?;
605        let id = self.links.try_create(source, target)?;
606        self.created.insert(id);
607        Ok(id)
608    }
609
610    fn reference_exists(&mut self, id: u32) -> bool {
611        self.links.reference_exists(id)
612    }
613
614    fn claims(&mut self, id: u32) -> Option<bool> {
615        self.links.claims(id)
616    }
617
618    fn next_created_addresses(&mut self, count: usize) -> Result<Vec<u32>> {
619        self.links.next_created_addresses(count)
620    }
621
622    fn update_observed(
623        &mut self,
624        id: u32,
625        source: u32,
626        target: u32,
627        observer: ChangeObserver<'_>,
628    ) -> Result<Link> {
629        let Some(before) = self.visible(id)? else {
630            return self.links.update_observed(id, source, target, observer);
631        };
632        let after = Link::new(id, source, target);
633        if !(self.owns(&before) && source == 0)
634            && (!self.can_write(&before) || !self.policy_can_write(&after))
635        {
636            return Err(Forbidden::new(format!("update {id}")).into());
637        }
638        let mut log = LinksUndoLog::new();
639        keep_names_before_update(&mut log, &mut self.links, id, source, target)?;
640        self.checked(
641            &format!("update {id}"),
642            id,
643            log,
644            |links, recorder| links.update_observed(id, source, target, recorder),
645            observer,
646        )
647    }
648
649    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
650        let Some(before) = self.visible(id)? else {
651            return self.links.delete_observed(id, observer);
652        };
653        if !self.can_write(&before) {
654            return Err(Forbidden::new(format!("delete {id}")).into());
655        }
656        let mut log = LinksUndoLog::new();
657        log.keep_names_of_usages(&mut self.links, id)?;
658        self.checked(
659            &format!("delete {id}"),
660            id,
661            log,
662            |links, recorder| links.delete_observed(id, recorder),
663            observer,
664        )
665    }
666
667    fn all_links(&mut self) -> Vec<Link> {
668        let links = self.links.all_links();
669        links
670            .into_iter()
671            .filter(|link| self.can_read(link))
672            .collect()
673    }
674
675    fn query_links(
676        &mut self,
677        index: Option<u32>,
678        source: Option<u32>,
679        target: Option<u32>,
680    ) -> Vec<Link> {
681        let links = self.links.query_links(index, source, target);
682        links
683            .into_iter()
684            .filter(|link| self.can_read(link))
685            .collect()
686    }
687
688    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
689        let found = self.links.search(source, target)?;
690        self.exists(found).then_some(found)
691    }
692
693    /// Panics when the subject may not create; use
694    /// [`try_get_or_create`](NamedTypeLinks::try_get_or_create).
695    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
696        Self::panic_on(self.try_get_or_create(source, target))
697    }
698
699    /// The name of any link: names are references.
700    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
701        self.links.get_name(id)
702    }
703
704    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
705        self.require_writable(id, "set-name")?;
706        if let Some(holder) = self.links.get_by_name(name)? {
707            if holder != 0 && holder != id {
708                if let Some(link) = self.links.get_link(holder) {
709                    if !self.can_write(&link) {
710                        // Taking the name takes it from its link.
711                        return Err(Forbidden::new(format!("set-name {id}")).into());
712                    }
713                }
714            }
715        }
716        self.links.set_name(id, name)
717    }
718
719    /// The link of any name: names are references.
720    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
721        self.links.get_by_name(name)
722    }
723
724    fn remove_name(&mut self, id: u32) -> Result<()> {
725        if let Some(link) = self.links.get_link(id) {
726            if !self.can_read(&link) {
727                // Nothing the subject sees has a name to remove.
728                return Ok(());
729            }
730            self.require_writable(id, "remove-name")?;
731        }
732        self.links.remove_name(id)
733    }
734
735    fn save(&mut self) -> Result<()> {
736        self.links.save()
737    }
738}
739
740/// The tokens a links server knows, stored as links (issue #149): the
741/// authenticator of `(auth: token)` that `clink --tokens` uses.
742///
743/// A subject `s` of the data has a pair `(p: Token s)`, where `Token` is the
744/// point named `Token`, and each of its tokens is a link `(t: p t)`, named
745/// `sha256:<hex>` after the SHA-256 of the token, so the store never holds a
746/// token itself. The table lives in a store of its own or in the data; any
747/// other authenticator is a callback of
748/// [`LinksSessions`](crate::protocol::LinksSessions).
749pub struct LinksTokenTable<L: NamedTypeLinks> {
750    store: L,
751}
752
753impl<L: NamedTypeLinks> LinksTokenTable<L> {
754    /// The name of the point every token link starts from.
755    pub const TOKEN_NAME: &'static str = "Token";
756
757    pub fn new(store: L) -> Self {
758        Self { store }
759    }
760
761    pub fn store(&self) -> &L {
762        &self.store
763    }
764
765    pub fn store_mut(&mut self) -> &mut L {
766        &mut self.store
767    }
768
769    pub fn into_inner(self) -> L {
770        self.store
771    }
772
773    /// The name of the link of `token`.
774    pub fn name_of(token: &str) -> String {
775        let digest = Sha256::digest(token.as_bytes());
776        let mut name = String::with_capacity(7 + digest.len() * 2);
777        name.push_str("sha256:");
778        for byte in digest {
779            name.push_str(&format!("{byte:02x}"));
780        }
781        name
782    }
783
784    /// The subject of `token`, or `None` when the table does not know it.
785    pub fn authenticate(&mut self, token: &str) -> Result<Option<u32>> {
786        let store = &mut self.store;
787        let point = store.get_by_name(Self::TOKEN_NAME)?.unwrap_or(0);
788        let link = store.get_by_name(&Self::name_of(token))?.unwrap_or(0);
789        if point == 0 || link == 0 {
790            return Ok(None);
791        }
792        let Some(stored) = store.get_link(link) else {
793            return Ok(None);
794        };
795        if stored.target != link {
796            return Ok(None);
797        }
798        let pair = stored.source;
799        if pair == 0 || pair == link {
800            return Ok(None);
801        }
802        match store.get_link(pair) {
803            Some(pair) if pair.source == point && pair.target != 0 => Ok(Some(pair.target)),
804            _ => Ok(None),
805        }
806    }
807
808    /// Lets `token` authenticate as `subject`, instead of any subject it had.
809    ///
810    /// Returns the link of the token.
811    pub fn grant(&mut self, token: &str, subject: u32) -> Result<u32> {
812        if subject == 0 {
813            bail!("A token needs a subject");
814        }
815        let store = &mut self.store;
816        let point = ensure_point(store, Self::TOKEN_NAME)?;
817        let pair = store.try_get_or_create(point, subject)?;
818        let name = Self::name_of(token);
819        let link = match store.get_by_name(&name)? {
820            Some(link) if link != 0 && store.exists(link) => link,
821            _ => store.try_create(0, 0)?,
822        };
823        store.update(link, pair, link)?;
824        store.set_name(link, &name)?;
825        Ok(link)
826    }
827
828    /// Forgets `token`; whether the table knew it.
829    pub fn revoke(&mut self, token: &str) -> Result<bool> {
830        if self.authenticate(token)?.is_none() {
831            return Ok(false);
832        }
833        let Some(link) = self.store.get_by_name(&Self::name_of(token))? else {
834            return Ok(false);
835        };
836        self.store.remove_name(link)?;
837        self.store.delete(link)?;
838        Ok(true)
839    }
840}