Skip to main content

coqui_access_key/
lib.rs

1//! Hashed bearer keys for clients that have nobody to type a password, kept in any [`Table`].
2//!
3//! A key is 256 random bits made here, said once, and kept only as a self-describing hash
4//! (`sha256:<hex>` by default, or Argon2id). Each key can be disabled or removed alone and
5//! may have a time it stops being taken. Build the provider in code with [`Keys::builder`].
6#![doc = include_str!("../README.md")]
7#![forbid(unsafe_code)]
8#![warn(missing_debug_implementations)]
9#![warn(missing_docs)]
10
11use std::borrow::Cow;
12use std::collections::BTreeSet;
13use std::fmt;
14use std::sync::Arc;
15
16use coqui_access::guatiao::library::ProviderError;
17use coqui_access::guatiao::{FromValue, Schema, ToValue};
18use coqui_access::{
19    AccountInfo, AccountPut, Accounts, Attempt, Authenticator, Description, Directory, Lookup,
20    Person, PutOutcome, Verdict, error, takes,
21};
22use coqui_access_kit::{
23    KeyHash, Keyed, MemoryTable, RecordLimits, Reloading, SourceError, Table, check_keys,
24    generate_key, is_key_hash, secret, unix_now, verify_key,
25};
26
27/// The most keys a table may hold unless the builder says otherwise.
28pub const DEFAULT_MAX_KEYS: usize = 10_000;
29
30/// The prefix of keys made when the builder names none.
31pub const DEFAULT_PREFIX: &str = "ck_";
32
33/// One key account as a [`Table`] keeps it, keyed by [`name`](KeyRecord::name).
34///
35/// It derives guatiao's `ToValue`, `FromValue` and `Schema`, so a [`Table`] may keep it in
36/// any format.
37#[derive(Clone, PartialEq, Eq, FromValue, Schema, ToValue)]
38#[map(crate = ::coqui_access::guatiao, deny_unknown_fields)]
39#[non_exhaustive]
40pub struct KeyRecord {
41    /// Stable identity; what a [`Verdict::Valid`] lookup names.
42    pub id: String,
43    /// The account name; unique in the table.
44    pub name: String,
45    /// What is kept of the key: `sha256:<hex>` or an Argon2id hash, as [`KeyHash::hash`]
46    /// writes it. One table may mix both.
47    pub hash: String,
48    /// Email address.
49    pub email: Option<String>,
50    /// Directory groups.
51    #[map(default, skip_serializing_if = Vec::is_empty)]
52    pub groups: Vec<String>,
53    /// A disabled key is not taken.
54    #[map(default, skip_serializing_if = core::ops::Not::not)]
55    pub disabled: bool,
56    /// When it was made, in seconds since the Unix epoch.
57    pub made_unix: Option<i64>,
58    /// When it stops being taken, in seconds since the Unix epoch.
59    pub expires_unix: Option<i64>,
60}
61
62impl KeyRecord {
63    /// An enabled key account with no groups. `hash` comes from [`KeyHash::hash`].
64    pub fn new(id: impl Into<String>, name: impl Into<String>, hash: impl Into<String>) -> Self {
65        Self {
66            id: id.into(),
67            name: name.into(),
68            hash: hash.into(),
69            email: None,
70            groups: Vec::new(),
71            disabled: false,
72            made_unix: None,
73            expires_unix: None,
74        }
75    }
76
77    /// Sets the directory groups.
78    #[must_use]
79    pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
80        self.groups = groups.into_iter().map(Into::into).collect();
81        self
82    }
83
84    /// Sets the email address.
85    #[must_use]
86    pub fn email(mut self, email: impl Into<String>) -> Self {
87        self.email = Some(email.into());
88        self
89    }
90
91    /// Sets whether the key is disabled.
92    #[must_use]
93    pub fn disabled(mut self, disabled: bool) -> Self {
94        self.disabled = disabled;
95        self
96    }
97
98    /// Sets when the key stops being taken.
99    #[must_use]
100    pub fn expires_unix(mut self, expires: i64) -> Self {
101        self.expires_unix = Some(expires);
102        self
103    }
104
105    /// Whether it is taken now: not disabled and not past its time.
106    fn taken(&self) -> bool {
107        !self.disabled && self.expires_unix.is_none_or(|expires| unix_now() < expires)
108    }
109}
110
111impl Keyed for KeyRecord {
112    fn key(&self) -> Cow<'_, str> {
113        Cow::Borrowed(&self.name)
114    }
115}
116
117impl fmt::Debug for KeyRecord {
118    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
119        formatter
120            .debug_struct("KeyRecord")
121            .field("id", &"[REDACTED]")
122            .field("name", &"[REDACTED]")
123            .field("hash", &"[REDACTED]")
124            .field("email", &self.email.as_ref().map(|_| "[REDACTED]"))
125            .field("groups", &self.groups.len())
126            .field("disabled", &self.disabled)
127            .finish()
128    }
129}
130
131/// Options for [`Keys`]; every one has a default.
132pub struct KeysBuilder {
133    table: Option<Arc<dyn Table<KeyRecord>>>,
134    prefix: String,
135    hash: KeyHash,
136    max_keys: usize,
137    limits: RecordLimits,
138}
139
140impl fmt::Debug for KeysBuilder {
141    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
142        formatter
143            .debug_struct("KeysBuilder")
144            .field("prefix", &self.prefix)
145            .field("hash", &self.hash)
146            .field("max_keys", &self.max_keys)
147            .finish_non_exhaustive()
148    }
149}
150
151impl KeysBuilder {
152    /// Keeps the keys in `table` instead of in memory.
153    #[must_use]
154    pub fn table(mut self, table: Arc<dyn Table<KeyRecord>>) -> Self {
155        self.table = Some(table);
156        self
157    }
158
159    /// What every key made here begins with, so a key is recognized where it turns up and
160    /// nothing else is looked up among them. Default [`DEFAULT_PREFIX`].
161    #[must_use]
162    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
163        self.prefix = prefix.into();
164        self
165    }
166
167    /// How keys made from now on are kept. Default [`KeyHash::Sha256`]. Keys already in the
168    /// table keep the algorithm their stored string names.
169    #[must_use]
170    pub fn key_hash(mut self, hash: KeyHash) -> Self {
171        self.hash = hash;
172        self
173    }
174
175    /// The most keys the table may hold. Default [`DEFAULT_MAX_KEYS`].
176    #[must_use]
177    pub fn max_keys(mut self, max: usize) -> Self {
178        self.max_keys = max;
179        self
180    }
181
182    /// How large a key account's fields may be. Default [`RecordLimits::DEFAULT`].
183    #[must_use]
184    pub fn record_limits(mut self, limits: RecordLimits) -> Self {
185        self.limits = limits;
186        self
187    }
188
189    /// Loads the table and makes the provider.
190    ///
191    /// # Errors
192    ///
193    /// Returns an error when the prefix is empty or not printable, or the table cannot be
194    /// loaded or holds an invalid or duplicated key.
195    pub fn build(self) -> Result<Keys, SourceError> {
196        if self.prefix.is_empty() || self.prefix.chars().any(char::is_control) {
197            return Err(SourceError::invalid(
198                "prefix must be a non-empty printable string",
199            ));
200        }
201        let table = self
202            .table
203            .unwrap_or_else(|| Arc::new(MemoryTable::<KeyRecord>::new()));
204        let (max, limits) = (self.max_keys, self.limits);
205        Ok(Keys {
206            prefix: self.prefix,
207            hash: self.hash,
208            limits,
209            keys: Reloading::new(table, move |records| validate(records, max, &limits))?,
210        })
211    }
212}
213
214/// A key table as an Authenticator, Directory and Accounts implementation.
215///
216/// The table is read again whenever it reports a change.
217///
218/// ```
219/// use coqui_access::{AccountPut, Accounts, Attempt, Authenticator, Verdict};
220/// use coqui_access_key::Keys;
221///
222/// let keys = Keys::builder().build().unwrap();
223/// let made = keys
224///     .put(AccountPut { name: "relay".into(), ..AccountPut::default() })
225///     .unwrap();
226/// let verdict = keys
227///     .authenticate(Attempt { secret: made.secret, ..Attempt::default() })
228///     .unwrap();
229/// assert!(matches!(verdict, Verdict::Valid(_)));
230/// ```
231#[derive(Debug)]
232pub struct Keys {
233    limits: RecordLimits,
234    prefix: String,
235    hash: KeyHash,
236    keys: Reloading<KeyRecord>,
237}
238
239impl Keys {
240    /// Options for a key table, kept in memory unless [`table`](KeysBuilder::table) says
241    /// otherwise.
242    pub fn builder() -> KeysBuilder {
243        KeysBuilder {
244            table: None,
245            prefix: DEFAULT_PREFIX.to_owned(),
246            hash: KeyHash::default(),
247            max_keys: DEFAULT_MAX_KEYS,
248            limits: RecordLimits::DEFAULT,
249        }
250    }
251
252    /// Makes a fresh 256-bit key with this table's prefix.
253    ///
254    /// # Errors
255    ///
256    /// Returns an error when the operating system random source is unavailable.
257    pub fn new_key(&self) -> Result<String, String> {
258        generate_key(&self.prefix)
259    }
260}
261
262impl Authenticator for Keys {
263    fn authenticate(&self, attempt: Attempt) -> Result<Verdict, ProviderError> {
264        let Some(presented) = attempt.secret.filter(|key| key.starts_with(&self.prefix)) else {
265            return Ok(Verdict::Unknown);
266        };
267        let found = self
268            .keys
269            .read(|records| {
270                // Every record is checked, none stopping the others.
271                let mut found = None;
272                for record in records {
273                    if verify_key(&record.hash, presented.as_bytes()) {
274                        found = Some(record.clone());
275                    }
276                }
277                found
278            })
279            .map_err(|reason| reason.reading("key table"))?;
280        Ok(match found {
281            None => Verdict::Unknown,
282            Some(record) if record.taken() => Verdict::Valid(Lookup {
283                by: "id".to_owned(),
284                value: record.id,
285                ..Lookup::default()
286            }),
287            Some(_) => Verdict::Invalid,
288        })
289    }
290
291    fn describe(&self) -> Result<Description, ProviderError> {
292        Ok(Description {
293            name: Some("Bearer keys".to_owned()),
294            takes: Some(takes::KEY.to_owned()),
295        })
296    }
297}
298
299impl Directory for Keys {
300    fn lookup(&self, lookup: Lookup) -> Result<Option<Person>, ProviderError> {
301        self.keys
302            .read(|records| {
303                records
304                    .iter()
305                    .find(|record| {
306                        record.taken()
307                            && match lookup.by.as_str() {
308                                "id" => record.id == lookup.value,
309                                "name" => record.name == lookup.value,
310                                "email" => record.email.as_deref() == Some(&lookup.value),
311                                _ => false,
312                            }
313                    })
314                    .map(|record| Person {
315                        id: record.id.clone(),
316                        name: record.name.clone(),
317                        display_name: None,
318                        email: record.email.clone(),
319                        groups: record.groups.clone(),
320                        attributes: Default::default(),
321                    })
322            })
323            .map_err(|reason| reason.reading("key table"))
324    }
325}
326
327impl Accounts for Keys {
328    fn accounts(&self) -> Result<Vec<AccountInfo>, ProviderError> {
329        self.keys
330            .read(|records| {
331                records
332                    .iter()
333                    .map(|record| AccountInfo {
334                        id: record.id.clone(),
335                        name: record.name.clone(),
336                        groups: record.groups.clone(),
337                        disabled: Some(record.disabled),
338                        made_unix: record.made_unix,
339                        expires_unix: record.expires_unix,
340                        ..AccountInfo::default()
341                    })
342                    .collect()
343            })
344            .map_err(|reason| reason.reading("key table"))
345    }
346
347    /// Makes an account and its key, or changes what is said of one there is. An account
348    /// that is there and has nothing said to change is given another key, and the one it had
349    /// stops being taken. A key is never given: it is made here and answered once.
350    fn put(&self, account: AccountPut) -> Result<PutOutcome, ProviderError> {
351        if !self.limits.allows_field(&account.name) {
352            return Err(error::bad_value("an account has a name"));
353        }
354        if account.reset || account.unlock {
355            return Err(error::unsupported(
356                "this provider keeps no reset mark or failure count",
357            ));
358        }
359        if account.secret.is_some() {
360            return Err(error::bad_value("a key is made here, not given"));
361        }
362        let unchanged = account.groups.is_none()
363            && account.disabled.is_none()
364            && account.expires_unix.is_none();
365        self.keys
366            .put_with(|records| {
367                let existing = records.iter().find(|record| record.name == account.name);
368                let mut record = match existing {
369                    Some(record) => record.clone(),
370                    None => KeyRecord::new(
371                        secret::identifier().map_err(SourceError::unavailable)?,
372                        account.name.clone(),
373                        "",
374                    ),
375                };
376                let mut made = None;
377                if existing.is_none() || unchanged {
378                    let key = generate_key(&self.prefix).map_err(SourceError::unavailable)?;
379                    record.hash = self.hash.hash(&key).map_err(SourceError::unavailable)?;
380                    record.made_unix = Some(unix_now());
381                    made = Some(key);
382                }
383                if let Some(groups) = account.groups {
384                    record.groups = groups;
385                }
386                if let Some(disabled) = account.disabled {
387                    record.disabled = disabled;
388                }
389                if let Some(expires) = account.expires_unix {
390                    record.expires_unix = Some(expires);
391                }
392                Ok((
393                    record,
394                    PutOutcome {
395                        secret: made,
396                        ..PutOutcome::default()
397                    },
398                ))
399            })
400            .map_err(|reason| reason.writing("key table"))
401    }
402
403    fn remove(&self, name: String) -> Result<(), ProviderError> {
404        self.keys
405            .remove(&name)
406            .map_err(|reason| reason.writing("key table"))
407            .and_then(|removed| {
408                removed
409                    .then_some(())
410                    .ok_or_else(|| error::not_found("there is no such account"))
411            })
412    }
413}
414
415fn validate(records: &[KeyRecord], max: usize, limits: &RecordLimits) -> Result<(), SourceError> {
416    check_keys(records, max)?;
417    let mut ids = BTreeSet::new();
418    let mut hashes = BTreeSet::new();
419    for record in records {
420        if !limits.allows_field(&record.id)
421            || !limits.allows_field(&record.name)
422            || !is_key_hash(&record.hash)
423            || !ids.insert(&record.id)
424            || !hashes.insert(&record.hash)
425            || !limits.allows_groups(&record.groups)
426            || record
427                .email
428                .as_ref()
429                .is_some_and(|email| !limits.allows_email(email))
430        {
431            return Err(SourceError::invalid("a key entry is invalid or duplicated"));
432        }
433    }
434    Ok(())
435}
436
437#[cfg(test)]
438mod tests {
439    use coqui_access_kit::Argon2Params;
440
441    use super::*;
442
443    fn presented(key: &str) -> Attempt {
444        Attempt {
445            secret: Some(key.to_owned()),
446            ..Attempt::default()
447        }
448    }
449
450    fn named(name: &str) -> AccountPut {
451        AccountPut {
452            name: name.to_owned(),
453            ..AccountPut::default()
454        }
455    }
456
457    fn keys_over(table: Arc<MemoryTable<KeyRecord>>) -> Keys {
458        Keys::builder().table(table).build().unwrap()
459    }
460
461    #[test]
462    fn a_table_built_in_code_authenticates_and_resolves() {
463        let table = Arc::new(MemoryTable::new());
464        let keys = keys_over(table.clone());
465        let secret = keys.new_key().unwrap();
466        table
467            .put(
468                KeyRecord::new("robot-1", "relay", KeyHash::Sha256.hash(&secret).unwrap())
469                    .groups(["station"]),
470            )
471            .unwrap();
472        let Verdict::Valid(lookup) = keys.authenticate(presented(&secret)).unwrap() else {
473            panic!("valid key was rejected");
474        };
475        let person = keys.lookup(lookup).unwrap().unwrap();
476        assert_eq!(person.id, "robot-1");
477        assert_eq!(person.groups, vec!["station"]);
478        assert!(!format!("{keys:?}").contains(&secret));
479    }
480
481    #[test]
482    fn a_reset_or_an_unlock_is_refused_as_unsupported() {
483        let keys = Keys::builder().build().unwrap();
484        for put in [
485            AccountPut {
486                reset: true,
487                ..named("relay")
488            },
489            AccountPut {
490                unlock: true,
491                ..named("relay")
492            },
493        ] {
494            let refused = keys.put(put).unwrap_err();
495            assert_eq!(
496                refused.status,
497                coqui_access::guatiao::Status::GUATIAO_ERR_UNSUPPORTED
498            );
499        }
500    }
501
502    #[test]
503    fn unknown_disabled_and_foreign_keys_are_told_apart() {
504        let keys = Keys::builder().build().unwrap();
505        let key = keys.put(named("relay")).unwrap().secret.unwrap();
506        keys.put(AccountPut {
507            disabled: Some(true),
508            ..named("relay")
509        })
510        .unwrap();
511        assert_eq!(
512            keys.authenticate(presented(&key)).unwrap(),
513            Verdict::Invalid
514        );
515        assert_eq!(
516            keys.authenticate(presented(&keys.new_key().unwrap()))
517                .unwrap(),
518            Verdict::Unknown
519        );
520        assert_eq!(
521            keys.authenticate(presented("password")).unwrap(),
522            Verdict::Unknown
523        );
524        assert!(
525            keys.lookup(Lookup {
526                by: "name".to_owned(),
527                value: "relay".to_owned(),
528                ..Lookup::default()
529            })
530            .unwrap()
531            .is_none()
532        );
533    }
534
535    #[test]
536    fn keys_are_made_rotated_expired_and_removed() {
537        let table = Arc::new(MemoryTable::new());
538        let keys = keys_over(table.clone());
539        let first = keys.put(named("cabin")).unwrap().secret.unwrap();
540        assert!(first.starts_with("ck_"));
541        let kept = table.load().unwrap().records;
542        assert!(!kept[0].hash.contains(first.trim_start_matches("ck_")));
543        assert_eq!(kept[0].hash, KeyHash::Sha256.hash(&first).unwrap());
544        // Changing what is said of it keeps the key; saying nothing makes another.
545        let moved = keys
546            .put(AccountPut {
547                groups: Some(vec!["guests".to_owned()]),
548                ..named("cabin")
549            })
550            .unwrap();
551        assert_eq!(moved.secret, None);
552        assert!(matches!(
553            keys.authenticate(presented(&first)).unwrap(),
554            Verdict::Valid(_)
555        ));
556        let second = keys.put(named("cabin")).unwrap().secret.unwrap();
557        assert_ne!(first, second);
558        assert_eq!(
559            keys.authenticate(presented(&first)).unwrap(),
560            Verdict::Unknown
561        );
562        assert!(
563            keys.put(AccountPut {
564                secret: Some("ck_mine".to_owned()),
565                ..named("attic")
566            })
567            .is_err()
568        );
569        keys.put(AccountPut {
570            expires_unix: Some(unix_now() - 1),
571            ..named("cabin")
572        })
573        .unwrap();
574        assert_eq!(
575            keys.authenticate(presented(&second)).unwrap(),
576            Verdict::Invalid
577        );
578        assert!(keys.accounts().unwrap()[0].expires_unix.is_some());
579        keys.remove("cabin".to_owned()).unwrap();
580        assert!(keys.remove("cabin".to_owned()).is_err());
581        assert_eq!(
582            keys.authenticate(presented(&second)).unwrap(),
583            Verdict::Unknown
584        );
585    }
586
587    #[test]
588    fn a_key_made_through_another_handle_is_known_without_rebuilding() {
589        let table = Arc::new(MemoryTable::new());
590        let daemon = keys_over(table.clone());
591        let command = keys_over(table);
592        let key = command.put(named("cabin")).unwrap().secret.unwrap();
593        assert!(matches!(
594            daemon.authenticate(presented(&key)).unwrap(),
595            Verdict::Valid(_)
596        ));
597    }
598
599    #[test]
600    fn one_table_mixes_sha256_and_argon2id_keys() {
601        let cheap = KeyHash::Argon2id(Argon2Params::new(64, 1, 1).unwrap());
602        let table = Arc::new(MemoryTable::new());
603        let sha = Keys::builder().table(table.clone()).build().unwrap();
604        let slow = Keys::builder()
605            .table(table.clone())
606            .key_hash(cheap)
607            .build()
608            .unwrap();
609        let fast_key = sha.put(named("fast")).unwrap().secret.unwrap();
610        let slow_key = slow.put(named("slow")).unwrap().secret.unwrap();
611        let kept = table.load().unwrap().records;
612        assert!(kept[0].hash.starts_with("sha256:"));
613        assert!(kept[1].hash.starts_with("$argon2id$"));
614        for keys in [&sha, &slow] {
615            for (key, name) in [(&fast_key, "fast"), (&slow_key, "slow")] {
616                let Verdict::Valid(lookup) = keys.authenticate(presented(key)).unwrap() else {
617                    panic!("{name} was refused");
618                };
619                assert_eq!(keys.lookup(lookup).unwrap().unwrap().name, name);
620            }
621            // A key of the right prefix that is in neither is not known.
622            assert_eq!(
623                keys.authenticate(presented(&keys.new_key().unwrap()))
624                    .unwrap(),
625                Verdict::Unknown
626            );
627        }
628    }
629
630    #[test]
631    fn a_malformed_table_or_prefix_is_refused() {
632        assert!(Keys::builder().prefix("").build().is_err());
633        assert!(Keys::builder().prefix("a\nb").build().is_err());
634        assert!(Keys::builder().prefix("rk_").build().is_ok());
635        let build = |records: Vec<KeyRecord>, max: usize| {
636            Keys::builder()
637                .table(Arc::new(MemoryTable::from_records(records)))
638                .max_keys(max)
639                .build()
640        };
641        assert!(build(vec![KeyRecord::new("a", "a", "short")], 10).is_err());
642        // A bare digest names no algorithm.
643        assert!(build(vec![KeyRecord::new("a", "a", secret::hash("k", None))], 10).is_err());
644        let one = KeyHash::Sha256.hash("k").unwrap();
645        let two = KeyHash::Sha256.hash("l").unwrap();
646        assert!(
647            build(
648                vec![
649                    KeyRecord::new("a", "a", one.clone()),
650                    KeyRecord::new("b", "b", two.clone())
651                ],
652                10
653            )
654            .is_ok()
655        );
656        assert!(
657            build(
658                vec![
659                    KeyRecord::new("a", "a", one.clone()),
660                    KeyRecord::new("b", "b", one.clone())
661                ],
662                10
663            )
664            .is_err(),
665            "two accounts cannot share a key"
666        );
667        assert!(
668            build(
669                vec![KeyRecord::new("a", "a", one), KeyRecord::new("b", "b", two)],
670                1
671            )
672            .is_err()
673        );
674    }
675}