Skip to main content

link_cli/permissions/
tokens.rs

1use anyhow::{bail, Result};
2use sha2::{Digest, Sha256};
3
4use crate::named_type_links::NamedTypeLinks;
5use crate::types::ensure_point;
6
7/// The tokens a links server knows, stored as links (issue #149): the
8/// authenticator of `(auth: token)` that `clink --tokens` uses.
9///
10/// A subject `s` of the data has a pair `(p: Token s)`, where `Token` is the
11/// point named `Token`, and each of its tokens is a link `(t: p t)`, named
12/// `sha256:<hex>` after the SHA-256 of the token, so the store never holds a
13/// token itself. The table lives in a store of its own or in the data; any
14/// other authenticator is a callback of
15/// [`LinksSessions`](crate::protocol::LinksSessions).
16pub struct LinksTokenTable<L: NamedTypeLinks> {
17    store: L,
18}
19
20impl<L: NamedTypeLinks> LinksTokenTable<L> {
21    /// The name of the point every token link starts from.
22    pub const TOKEN_NAME: &'static str = "Token";
23
24    pub fn new(store: L) -> Self {
25        Self { store }
26    }
27
28    pub fn store(&self) -> &L {
29        &self.store
30    }
31
32    pub fn store_mut(&mut self) -> &mut L {
33        &mut self.store
34    }
35
36    pub fn into_inner(self) -> L {
37        self.store
38    }
39
40    /// The name of the link of `token`.
41    pub fn name_of(token: &str) -> String {
42        let digest = Sha256::digest(token.as_bytes());
43        let mut name = String::with_capacity(7 + digest.len() * 2);
44        name.push_str("sha256:");
45        for byte in digest {
46            name.push_str(&format!("{byte:02x}"));
47        }
48        name
49    }
50
51    /// The subject of `token`, or `None` when the table does not know it.
52    pub fn authenticate(&mut self, token: &str) -> Result<Option<u32>> {
53        let store = &mut self.store;
54        let point = store.get_by_name(Self::TOKEN_NAME)?.unwrap_or(0);
55        let link = store.get_by_name(&Self::name_of(token))?.unwrap_or(0);
56        if point == 0 || link == 0 {
57            return Ok(None);
58        }
59        let Some(stored) = store.get_link(link) else {
60            return Ok(None);
61        };
62        if stored.target != link {
63            return Ok(None);
64        }
65        let pair = stored.source;
66        if pair == 0 || pair == link {
67            return Ok(None);
68        }
69        match store.get_link(pair) {
70            Some(pair) if pair.source == point && pair.target != 0 => Ok(Some(pair.target)),
71            _ => Ok(None),
72        }
73    }
74
75    /// Lets `token` authenticate as `subject`, instead of any subject it had.
76    ///
77    /// Returns the link of the token.
78    pub fn grant(&mut self, token: &str, subject: u32) -> Result<u32> {
79        if subject == 0 {
80            bail!("A token needs a subject");
81        }
82        let store = &mut self.store;
83        let point = ensure_point(store, Self::TOKEN_NAME)?;
84        let pair = store.try_get_or_create(point, subject)?;
85        let name = Self::name_of(token);
86        let link = match store.get_by_name(&name)? {
87            Some(link) if link != 0 && store.exists(link) => link,
88            _ => store.try_create(0, 0)?,
89        };
90        store.update(link, pair, link)?;
91        store.set_name(link, &name)?;
92        Ok(link)
93    }
94
95    /// Forgets `token`; whether the table knew it.
96    pub fn revoke(&mut self, token: &str) -> Result<bool> {
97        if self.authenticate(token)?.is_none() {
98            return Ok(false);
99        }
100        let Some(link) = self.store.get_by_name(&Self::name_of(token))? else {
101            return Ok(false);
102        };
103        self.store.remove_name(link)?;
104        self.store.delete(link)?;
105        Ok(true)
106    }
107}