Skip to main content

coqui_access_kit/
pins.rs

1//! Where the pins of an account are kept: the contract a matcher asks, and the two sources
2//! that ship (a per-user file in `authorized`, and any [`Table`] of pins).
3//!
4//! A pin is what one account has said it is known by: the SHA-256 of a whole certificate (a
5//! *fingerprint*) or of its public key (a *key*). The library never decides where pins live;
6//! a consumer gives the [`Matcher`](crate::matcher::Matcher) a [`PinSource`] by name.
7
8use std::borrow::Cow;
9use std::fmt;
10use std::sync::Arc;
11
12use coqui_access::guatiao::library::ProviderError;
13use coqui_access::guatiao::{FromValue, Schema, ToValue};
14use coqui_access::{Claims, Person};
15
16use crate::table::{Keyed, Reloading, SourceError, Table};
17
18pub mod authorized;
19pub use authorized::{
20    AuthorizedFile, DirectReader, FileRead, PinFileReader, ReadFailure, TemplateError,
21};
22
23/// The pins of the certificate a person presented: what a [`PinSource`] looks for. Each is
24/// `sha256:<hex>`, lowercase.
25#[derive(Debug, Clone, Default, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct PinSet {
28    /// The SHA-256 of the whole certificate.
29    pub fingerprint: Option<String>,
30    /// The SHA-256 of its `SubjectPublicKeyInfo`.
31    pub key: Option<String>,
32}
33
34impl PinSet {
35    /// The pins the claims `fingerprint` and `spki` carry.
36    pub fn from_claims(claims: &Claims) -> Self {
37        let pick = |name: &str| {
38            claims
39                .get(name)
40                .first()
41                .map(|value| value.to_ascii_lowercase())
42        };
43        Self {
44            fingerprint: pick("fingerprint"),
45            key: pick("spki"),
46        }
47    }
48
49    /// Whether there is nothing to look for.
50    pub fn is_empty(&self) -> bool {
51        self.fingerprint.is_none() && self.key.is_none()
52    }
53}
54
55/// What a source found for one account.
56#[derive(Debug, Clone, PartialEq, Eq)]
57#[non_exhaustive]
58pub enum PinCheck {
59    /// The account holds one of the pins.
60    Holds,
61    /// The source was read and the account holds none of them.
62    Absent,
63    /// The source cannot be trusted for this account (a file with the wrong permissions, a
64    /// home that is not known): counted as no pins, and the reason is reported. The reason
65    /// never holds a pin.
66    Refused(String),
67}
68
69/// A place pins are kept, asked about one account at a time.
70///
71/// `check` is called only for an account a rule already named, never to scan: a source
72/// answers for `person` alone. `Err` is "could not find out" and ends the match with an
73/// error; a source that can read what it needs but must not use it answers
74/// [`PinCheck::Refused`].
75pub trait PinSource: Send + Sync {
76    /// Whether `person` holds one of `pins`.
77    fn check(&self, person: &Person, pins: &PinSet) -> Result<PinCheck, ProviderError>;
78}
79
80/// Whether `text` is a pin, and if so whether it is one of `wanted`.
81///
82/// A pin is `sha256:<64 hex>` (a fingerprint) or `spki-sha256:<64 hex>` (a public key), in
83/// any case. `None` is text that is not a pin.
84pub fn pin_matches(text: &str, wanted: &PinSet) -> Option<bool> {
85    let valid = |hex: &str| hex.len() == 64 && hex.bytes().all(|byte| byte.is_ascii_hexdigit());
86    if let Some(hex) = text.strip_prefix("sha256:") {
87        return valid(hex).then(|| {
88            wanted.fingerprint.as_deref() == Some(&format!("sha256:{}", hex.to_ascii_lowercase()))
89        });
90    }
91    let hex = text.strip_prefix("spki-sha256:")?;
92    valid(hex)
93        .then(|| wanted.key.as_deref() == Some(&format!("sha256:{}", hex.to_ascii_lowercase())))
94}
95
96/// One pin an account holds, as a [`Table`] keeps it: the global source of pins.
97#[derive(Clone, PartialEq, Eq, FromValue, Schema, ToValue)]
98#[map(crate = ::coqui_access::guatiao, deny_unknown_fields)]
99#[non_exhaustive]
100pub struct AccountPin {
101    /// The account's name, as its directory gives it ([`Person::name`]).
102    pub name: String,
103    /// The pin, as a line of a pin file has it: `sha256:<hex>` or `spki-sha256:<hex>`.
104    pub pin: String,
105}
106
107impl AccountPin {
108    /// `name` holds `pin`.
109    pub fn new(name: impl Into<String>, pin: impl Into<String>) -> Self {
110        Self {
111            name: name.into(),
112            pin: pin.into(),
113        }
114    }
115}
116
117impl Keyed for AccountPin {
118    fn key(&self) -> Cow<'_, str> {
119        Cow::Owned(format!(
120            "{}
121{}",
122            self.name,
123            self.pin.to_ascii_lowercase()
124        ))
125    }
126}
127
128impl fmt::Debug for AccountPin {
129    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
130        formatter
131            .debug_struct("AccountPin")
132            .field("name", &"[REDACTED]")
133            .field("pin", &"[REDACTED]")
134            .finish()
135    }
136}
137
138/// Pins kept in any [`Table`] of [`AccountPin`]s: the global source, for a consumer whose
139/// pins live in one place.
140pub struct TablePins {
141    pins: Reloading<AccountPin>,
142}
143
144impl fmt::Debug for TablePins {
145    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
146        formatter.debug_struct("TablePins").finish_non_exhaustive()
147    }
148}
149
150impl TablePins {
151    /// A source over `table`.
152    ///
153    /// # Errors
154    ///
155    /// When the table cannot be read, or holds a line that is not a pin.
156    pub fn new(table: Arc<dyn Table<AccountPin>>) -> Result<Self, SourceError> {
157        let wanted = PinSet::default();
158        Ok(Self {
159            pins: Reloading::new(table, move |records| {
160                if records
161                    .iter()
162                    .any(|record| pin_matches(&record.pin, &wanted).is_none())
163                {
164                    return Err(SourceError::invalid("a pin in the table is not a pin"));
165                }
166                Ok(())
167            })?,
168        })
169    }
170}
171
172impl PinSource for TablePins {
173    fn check(&self, person: &Person, pins: &PinSet) -> Result<PinCheck, ProviderError> {
174        let held = self
175            .pins
176            .read(|records| {
177                records.iter().any(|record| {
178                    record.name == person.name && pin_matches(&record.pin, pins) == Some(true)
179                })
180            })
181            .map_err(|reason| reason.reading("pin table"))?;
182        Ok(if held {
183            PinCheck::Holds
184        } else {
185            PinCheck::Absent
186        })
187    }
188}