Skip to main content

coqui_access_mtls/
lib.rs

1//! Maps peer certificates, verified by the transport, to directory identities.
2//!
3//! The transport (see `coqui-peer-tls`) proves a peer holds the key of its certificate and
4//! hands the certificate's fingerprint in [`Attempt::certificate`]. This provider keeps the
5//! fingerprints that were accepted in a [`Table`], each under a name and groups. A
6//! certificate nobody accepted is not authenticated and is kept for a while as waiting, in a
7//! second table, so whoever runs the service can accept it. Build the provider in code with
8//! [`MtlsAccounts::builder`].
9#![doc = include_str!("../README.md")]
10#![forbid(unsafe_code)]
11#![warn(missing_debug_implementations)]
12#![warn(missing_docs)]
13
14mod pin;
15mod trust;
16
17use std::borrow::Cow;
18use std::collections::BTreeSet;
19use std::fmt;
20use std::net::SocketAddr;
21use std::sync::{Arc, Mutex, PoisonError};
22use std::time::{Duration, Instant};
23
24use coqui_access::Limit;
25use coqui_access::guatiao::library::ProviderError;
26use coqui_access::guatiao::{FromValue, Schema, ToValue};
27use coqui_access::{
28    AccountInfo, AccountPut, Accounts, Attempt, Authenticator, Description, Directory, Lookup,
29    Person, PutOutcome, Verdict, Waiting, error, takes,
30};
31use coqui_access_kit::pick::Pick;
32use coqui_access_kit::{
33    Keyed, MemoryTable, RecordLimits, Reloading, SourceError, Table, check_keys, secret, unix_now,
34};
35use coqui_peer::{WaitingLimits, WaitingQueue};
36use coqui_peer_tls::{CaPolicy, Digest, PeerId, Policy, Trust};
37
38use pin::{Kind, Normal};
39
40pub use pin::{Pin, PinError};
41pub use trust::{TrustMode, default_account};
42
43/// The most peers a table may hold unless the builder says otherwise.
44pub const DEFAULT_MAX_RECORDS: usize = 10_000;
45/// The most pins (fingerprints and keys together) one account may hold unless the builder
46/// says otherwise.
47pub const DEFAULT_MAX_PINS: usize = 4;
48/// The most certificates a client may send, leaf included, unless the builder says
49/// otherwise.
50pub const DEFAULT_MAX_CHAIN: Limit = Limit::at(8);
51/// The bounds on the waiting list unless the builder says otherwise: one place per source
52/// (an IPv4 address, or an IPv6 /64), 16 in all, and a fingerprint from one source written
53/// down again at most once a minute.
54pub fn default_waiting_limits() -> WaitingLimits {
55    let mut limits = WaitingLimits::default();
56    limits.per_source = DEFAULT_WAITING_PER_SOURCE;
57    limits.total = DEFAULT_WAITING_TOTAL;
58    limits.rerecord = DEFAULT_WAITING_RERECORD;
59    limits
60}
61
62/// Places one source holds on the waiting list unless the builder says otherwise.
63pub const DEFAULT_WAITING_PER_SOURCE: usize = 1;
64/// Places on the waiting list in all unless the builder says otherwise.
65pub const DEFAULT_WAITING_TOTAL: usize = 16;
66/// How soon one fingerprint from one source is written down again unless the builder says
67/// otherwise.
68pub const DEFAULT_WAITING_RERECORD: Duration = Duration::from_secs(60);
69
70/// One accepted peer as a [`Table`] keeps it, keyed by [`name`](PeerRecord::name).
71///
72/// It derives guatiao's `ToValue`, `FromValue` and `Schema`, so a [`Table`] may keep it in
73/// any format.
74#[derive(Clone, PartialEq, Eq, FromValue, Schema, ToValue)]
75#[map(crate = ::coqui_access::guatiao, deny_unknown_fields)]
76#[non_exhaustive]
77pub struct PeerRecord {
78    /// Stable identity; what a [`Verdict::Valid`] lookup names.
79    pub id: String,
80    /// The peer's name; unique in the table.
81    pub name: String,
82    /// The SHA-256 fingerprint of a certificate it pins: written in its canonical form, read
83    /// in any spelling `coqui-peer-tls` reads. Absent for an account pinned by other means.
84    #[map(as_text)]
85    pub certificate: Option<PeerId>,
86    /// Further pins, each naming its `kind` (`fingerprint` or `key`): with `certificate`,
87    /// everything the account is known by. A certificate renewed on the same key keeps a
88    /// `key` pin. An account holds at least one pin and at most the provider's `max_pins`.
89    #[map(default, skip_serializing_if = Vec::is_empty)]
90    pub pins: Vec<Pin>,
91    /// Email address.
92    pub email: Option<String>,
93    /// Directory groups.
94    #[map(default, skip_serializing_if = Vec::is_empty)]
95    pub groups: Vec<String>,
96    /// A disabled peer is refused.
97    #[map(default, skip_serializing_if = core::ops::Not::not)]
98    pub disabled: bool,
99    /// When it was accepted, in seconds since the Unix epoch.
100    pub made_unix: Option<i64>,
101}
102
103impl PeerRecord {
104    /// An enabled peer with no groups, accepted by this fingerprint.
105    pub fn new(id: impl Into<String>, name: impl Into<String>, certificate: &PeerId) -> Self {
106        Self {
107            id: id.into(),
108            name: name.into(),
109            certificate: Some(*certificate),
110            pins: Vec::new(),
111            email: None,
112            groups: Vec::new(),
113            disabled: false,
114            made_unix: None,
115        }
116    }
117
118    /// An enabled peer with no groups, accepted by `pin`: a public key, say, so a renewed
119    /// certificate on the same key signs in.
120    pub fn keyed(id: impl Into<String>, name: impl Into<String>, pin: Pin) -> Self {
121        Self {
122            id: id.into(),
123            name: name.into(),
124            certificate: None,
125            pins: vec![pin],
126            email: None,
127            groups: Vec::new(),
128            disabled: false,
129            made_unix: None,
130        }
131    }
132
133    /// Sets the directory groups.
134    #[must_use]
135    pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
136        self.groups = groups.into_iter().map(Into::into).collect();
137        self
138    }
139
140    /// Sets the email address.
141    #[must_use]
142    pub fn email(mut self, email: impl Into<String>) -> Self {
143        self.email = Some(email.into());
144        self
145    }
146
147    /// Sets whether the peer is disabled.
148    #[must_use]
149    pub fn disabled(mut self, disabled: bool) -> Self {
150        self.disabled = disabled;
151        self
152    }
153
154    /// Every pin the peer holds, in one spelling; `None` when one is not valid.
155    fn held(&self) -> Option<Vec<Normal>> {
156        self.certificate
157            .iter()
158            .map(|id| Some(Normal::of_fingerprint(id)))
159            .chain(self.pins.iter().map(Pin::normal))
160            .collect()
161    }
162
163    fn holds(&self, pin: &Normal) -> bool {
164        self.held().is_some_and(|held| held.contains(pin))
165    }
166
167    fn pin_count(&self) -> usize {
168        usize::from(self.certificate.is_some()) + self.pins.len()
169    }
170
171    /// Adds a pin the peer does not hold yet, unless it holds `most` already.
172    fn add_pin(&mut self, pin: &Pin, most: usize) -> Result<(), SourceError> {
173        let normal = pin
174            .normal()
175            .ok_or_else(|| SourceError::invalid("that is not a certificate pin"))?;
176        if self.holds(&normal) {
177            return Ok(());
178        }
179        if self.pin_count() >= most {
180            return Err(SourceError::invalid(
181                "that peer holds as many pins as the provider allows",
182            ));
183        }
184        match (normal.kind, self.certificate) {
185            (Kind::Fingerprint, None) => {
186                self.certificate = pin.value.parse::<PeerId>().ok();
187            }
188            _ => self.pins.push(Pin {
189                kind: pin.kind.clone(),
190                value: normal.value,
191            }),
192        }
193        Ok(())
194    }
195
196    /// Takes one pin away, never the last one: a peer nothing could sign in as is removed.
197    fn remove_pin(&mut self, pin: &Pin) -> Result<(), SourceError> {
198        let normal = pin
199            .normal()
200            .ok_or_else(|| SourceError::invalid("that is not a certificate pin"))?;
201        if !self.holds(&normal) {
202            return Err(SourceError::invalid("that peer does not hold that pin"));
203        }
204        if self.pin_count() == 1 {
205            return Err(SourceError::invalid(
206                "that is the peer's last pin; remove the peer instead",
207            ));
208        }
209        let own = self.certificate.as_ref().map(Normal::of_fingerprint);
210        if own.as_ref() == Some(&normal) {
211            self.certificate = None;
212        } else {
213            self.pins
214                .retain(|held| held.normal().as_ref() != Some(&normal));
215        }
216        Ok(())
217    }
218}
219
220impl Keyed for PeerRecord {
221    fn key(&self) -> Cow<'_, str> {
222        Cow::Borrowed(&self.name)
223    }
224}
225
226impl fmt::Debug for PeerRecord {
227    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
228        formatter
229            .debug_struct("PeerRecord")
230            .field("id", &"[REDACTED]")
231            .field("name", &"[REDACTED]")
232            .field(
233                "certificate",
234                &self.certificate.as_ref().map(|_| "[REDACTED]"),
235            )
236            .field("pins", &self.pins.len())
237            .field("email", &self.email.as_ref().map(|_| "[REDACTED]"))
238            .field("groups", &self.groups.len())
239            .field("disabled", &self.disabled)
240            .finish()
241    }
242}
243
244/// A fingerprint shown to the service that nobody has accepted, keyed by
245/// [`fingerprint`](Unaccepted::fingerprint).
246///
247/// It derives guatiao's `ToValue`, `FromValue` and `Schema`, so a [`Table`] may keep it in
248/// any format.
249#[derive(Debug, Clone, PartialEq, Eq, FromValue, Schema, ToValue)]
250#[map(crate = ::coqui_access::guatiao, deny_unknown_fields)]
251#[non_exhaustive]
252pub struct Unaccepted {
253    /// The fingerprint: written in its canonical form, read in any spelling `coqui-peer-tls`
254    /// reads.
255    #[map(as_text)]
256    pub fingerprint: PeerId,
257    /// The address it was shown from, when known.
258    pub peer: Option<String>,
259    /// When it was last written down, in seconds since the Unix epoch.
260    pub seen_unix: i64,
261}
262
263impl Unaccepted {
264    /// A fingerprint seen at `seen_unix`, from `peer`.
265    pub fn new(fingerprint: &PeerId, peer: Option<String>, seen_unix: i64) -> Self {
266        Self {
267            fingerprint: *fingerprint,
268            peer,
269            seen_unix,
270        }
271    }
272}
273
274impl Keyed for Unaccepted {
275    fn key(&self) -> Cow<'_, str> {
276        Cow::Owned(self.fingerprint.canonical())
277    }
278}
279
280/// Options for [`MtlsAccounts`]; every one has a default.
281pub struct MtlsAccountsBuilder {
282    table: Option<Arc<dyn Table<PeerRecord>>>,
283    waiting: Option<Arc<dyn Table<Unaccepted>>>,
284    max_records: usize,
285    max_pins: usize,
286    limits: RecordLimits,
287    waiting_limits: WaitingLimits,
288    trust: TrustMode,
289    ca: Option<CaPolicy>,
290    account: Vec<Pick>,
291    max_chain: Limit,
292    policy: Policy,
293}
294
295impl fmt::Debug for MtlsAccountsBuilder {
296    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
297        formatter
298            .debug_struct("MtlsAccountsBuilder")
299            .field("max_records", &self.max_records)
300            .field("max_pins", &self.max_pins)
301            .field("waiting_limits", &self.waiting_limits)
302            .field("trust", &self.trust)
303            .field("max_chain", &self.max_chain)
304            .finish_non_exhaustive()
305    }
306}
307
308impl MtlsAccountsBuilder {
309    /// How client certificates are trusted. Default [`TrustMode::Pinned`].
310    #[must_use]
311    pub fn trust(mut self, trust: TrustMode) -> Self {
312        self.trust = trust;
313        self
314    }
315
316    /// The CA and name globs that [`TrustMode::Ca`] and [`TrustMode::PinnedOrCa`] check a
317    /// chain against; `ip_in_dns` (on by default) lets an `ip:` glob match an address
318    /// written as a DNS name.
319    #[must_use]
320    pub fn ca(mut self, ca: CaPolicy) -> Self {
321        self.ca = Some(ca);
322        self
323    }
324
325    /// How a CA-trusted certificate names its account: picks tried in order over its fields
326    /// (`coqui-peer-tls`'s `CertificateFields::to_map`). Default: its `fingerprint`, by
327    /// `certificate`.
328    #[must_use]
329    pub fn account(mut self, picks: Vec<Pick>) -> Self {
330        self.account = picks;
331        self
332    }
333
334    /// The most certificates a client may send, leaf included. Default 8.
335    #[must_use]
336    pub fn max_chain(mut self, most: Limit) -> Self {
337        self.max_chain = most;
338        self
339    }
340
341    /// The policy a chain is checked under (validity dates, algorithms). Default
342    /// [`Policy::default`].
343    #[must_use]
344    pub fn policy(mut self, policy: Policy) -> Self {
345        self.policy = policy;
346        self
347    }
348
349    /// Keeps the accepted peers in `table` instead of in memory.
350    #[must_use]
351    pub fn table(mut self, table: Arc<dyn Table<PeerRecord>>) -> Self {
352        self.table = Some(table);
353        self
354    }
355
356    /// Keeps the waiting fingerprints in `table` instead of in memory. A table that cannot be
357    /// written means nobody waits.
358    #[must_use]
359    pub fn waiting(mut self, table: Arc<dyn Table<Unaccepted>>) -> Self {
360        self.waiting = Some(table);
361        self
362    }
363
364    /// The most peers the table may hold. Default [`DEFAULT_MAX_RECORDS`].
365    #[must_use]
366    pub fn max_records(mut self, max: usize) -> Self {
367        self.max_records = max;
368        self
369    }
370
371    /// The most pins, fingerprints and keys together, one peer may hold. Default
372    /// [`DEFAULT_MAX_PINS`].
373    #[must_use]
374    pub fn max_pins(mut self, max: usize) -> Self {
375        self.max_pins = max;
376        self
377    }
378
379    /// How large a peer's fields may be. Default [`RecordLimits::DEFAULT`].
380    #[must_use]
381    pub fn record_limits(mut self, limits: RecordLimits) -> Self {
382        self.limits = limits;
383        self
384    }
385
386    /// The bounds on the waiting list, applied by coqui-peer's [`WaitingQueue`]: places per
387    /// source, places in all (a newcomer past them is not written down; nobody is pushed out
388    /// for it), and how soon one fingerprint from one source is written down again. Default
389    /// [`default_waiting_limits`].
390    #[must_use]
391    pub fn waiting_limits(mut self, limits: WaitingLimits) -> Self {
392        self.waiting_limits = limits;
393        self
394    }
395
396    /// Loads the table and makes the provider.
397    ///
398    /// # Errors
399    ///
400    /// Returns an error when the table cannot be loaded or holds an invalid or duplicated
401    /// peer, or the trust needs a CA and none is given.
402    pub fn build(self) -> Result<MtlsAccounts, SourceError> {
403        if self.account.iter().any(|pick| pick.check().is_err()) {
404            return Err(SourceError::invalid(
405                "an account pick is looked up by an attribute, not by filter or claims",
406            ));
407        }
408        let ca = match (self.trust.uses_ca(), self.ca) {
409            (true, Some(ca)) => Some(Trust::Ca(ca)),
410            (true, None) => {
411                return Err(SourceError::invalid(
412                    "trust by a certificate authority needs its ca_file",
413                ));
414            }
415            (false, _) => None,
416        };
417        let table = self
418            .table
419            .unwrap_or_else(|| Arc::new(MemoryTable::<PeerRecord>::new()));
420        let (max, limits, max_pins) = (self.max_records, self.limits, self.max_pins);
421        let waiting_table = self
422            .waiting
423            .unwrap_or_else(|| Arc::new(MemoryTable::<Unaccepted>::new()));
424        let mut queue = WaitingQueue::new(self.waiting_limits);
425        // What is waiting already counts against its source, as old as it was written down.
426        let (now, now_unix) = (Instant::now(), unix_now());
427        for had in waiting_table
428            .load()
429            .map(|kept| kept.records)
430            .unwrap_or_default()
431        {
432            let age = Duration::from_secs(u64::try_from(now_unix - had.seen_unix).unwrap_or(0));
433            let at = now.checked_sub(age).unwrap_or(now);
434            queue.remember(had.fingerprint, source_of(had.peer.as_deref()), at);
435        }
436        Ok(MtlsAccounts {
437            peers: Reloading::new(table, move |records| {
438                validate(records, max, max_pins, &limits)
439            })?,
440            limits,
441            max_pins,
442            waiting_table,
443            queue: Mutex::new(queue),
444            trust: self.trust,
445            ca,
446            account: self.account,
447            max_chain: self.max_chain,
448            policy: self.policy,
449        })
450    }
451}
452
453/// MtlsAccounts as an Authenticator, Directory and Accounts implementation.
454///
455/// The table is read again whenever it reports a change.
456///
457/// ```
458/// use coqui_access::{Attempt, Authenticator, Verdict};
459/// use coqui_access_mtls::MtlsAccounts;
460///
461/// let peers = MtlsAccounts::builder().build().unwrap();
462/// let seen = peers
463///     .authenticate(Attempt {
464///         certificate: Some(
465///             "sha256:0000000000000000000000000000000000000000000000000000000000000000".into(),
466///         ),
467///         ..Attempt::default()
468///     })
469///     .unwrap();
470/// // Nobody accepted it: not authenticated, and kept as waiting.
471/// assert_eq!(seen, Verdict::Unknown);
472/// ```
473pub struct MtlsAccounts {
474    peers: Reloading<PeerRecord>,
475    waiting_table: Arc<dyn Table<Unaccepted>>,
476    /// Decides who is written down as waiting; held while the waiting table is read and
477    /// written.
478    queue: Mutex<WaitingQueue>,
479    limits: RecordLimits,
480    max_pins: usize,
481    trust: TrustMode,
482    ca: Option<Trust>,
483    account: Vec<Pick>,
484    max_chain: Limit,
485    policy: Policy,
486}
487
488impl fmt::Debug for MtlsAccounts {
489    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
490        let queue = self.queue.lock().unwrap_or_else(PoisonError::into_inner);
491        formatter
492            .debug_struct("MtlsAccounts")
493            .field("waiting_limits", &queue.limits())
494            .field("trust", &self.trust)
495            .finish_non_exhaustive()
496    }
497}
498
499impl MtlsAccounts {
500    /// Options for a peer table, kept in memory unless [`table`](MtlsAccountsBuilder::table) says
501    /// otherwise.
502    pub fn builder() -> MtlsAccountsBuilder {
503        MtlsAccountsBuilder {
504            table: None,
505            waiting: None,
506            max_records: DEFAULT_MAX_RECORDS,
507            max_pins: DEFAULT_MAX_PINS,
508            limits: RecordLimits::DEFAULT,
509            trust: TrustMode::Pinned,
510            ca: None,
511            account: default_account(),
512            max_chain: DEFAULT_MAX_CHAIN,
513            policy: Policy::default(),
514            waiting_limits: default_waiting_limits(),
515        }
516    }
517
518    /// Writes a fingerprint nobody accepted down as waiting, when coqui-peer's
519    /// [`WaitingQueue`] admits it: one already waiting stays as it is.
520    ///
521    /// The decision is made inside the waiting table's own update, from the entries it holds
522    /// then (a file table is locked for it), with a queue built from them. So entries another
523    /// provider or process wrote count against their source and the total, and two racing
524    /// providers cannot both take the last place.
525    fn wait(&self, fingerprint: &PeerId, from: Option<String>) {
526        let queue = self.queue.lock().unwrap_or_else(PoisonError::into_inner);
527        let limits = queue.limits();
528        let source = source_of(from.as_deref());
529        let mut evict = Vec::new();
530        // Whether it could be written is not the peer's to be told.
531        let _ = self.waiting_table.update(&mut |waits| {
532            if waits.iter().any(|had| had.fingerprint == *fingerprint) {
533                return Ok(None);
534            }
535            let (now, now_unix) = (Instant::now(), unix_now());
536            let mut fresh = WaitingQueue::new(limits);
537            for had in waits {
538                let age = Duration::from_secs(u64::try_from(now_unix - had.seen_unix).unwrap_or(0));
539                let at = now.checked_sub(age).unwrap_or(now);
540                fresh.remember(had.fingerprint, source_of(had.peer.as_deref()), at);
541            }
542            let admission = fresh.admit(*fingerprint, source, waits.len(), now);
543            if !admission.record {
544                return Ok(None);
545            }
546            evict = admission.evict;
547            Ok(Some(Unaccepted::new(fingerprint, from.clone(), now_unix)))
548        });
549        for old in &evict {
550            let _ = self.waiting_table.remove(&old.canonical());
551        }
552    }
553
554    /// MtlsAccounts that are accepted wait no more.
555    fn waited(&self, accepted: &[Normal]) {
556        let mut queue = self.queue.lock().unwrap_or_else(PoisonError::into_inner);
557        for had in self.waits() {
558            if accepted.contains(&Normal::of_fingerprint(&had.fingerprint)) {
559                queue.forget(&had.fingerprint);
560                let _ = self.waiting_table.remove(&had.fingerprint.canonical());
561            }
562        }
563    }
564
565    /// The waiting entries, oldest first. A table that cannot be read is nobody waiting.
566    fn waits(&self) -> Vec<Unaccepted> {
567        self.waiting_table
568            .load()
569            .map(|snapshot| snapshot.records)
570            .unwrap_or_default()
571    }
572}
573
574impl Authenticator for MtlsAccounts {
575    /// Pinned first (unless the trust is `ca`): a known, enabled record is `Valid` by `id`, a
576    /// disabled one `Invalid`. Then the CA (unless the trust is `pinned`), for a `secure`
577    /// attempt carrying `certificates`: a trusted chain is answered by the `account` picks,
578    /// `Ambiguous` being `Invalid`. Anything else is `Unknown`, and under a pinning trust the
579    /// fingerprint waits.
580    fn authenticate(&self, attempt: Attempt) -> Result<Verdict, ProviderError> {
581        let chain = attempt.certificates.as_deref().unwrap_or_default();
582        if !self.max_chain.allows(chain.len()) {
583            return Ok(Verdict::Unknown);
584        }
585        let fingerprint = attempt
586            .certificate
587            .as_deref()
588            .and_then(|text| text.parse::<PeerId>().ok())
589            .or_else(|| chain.first().map(|leaf| PeerId::of(leaf.as_ref())))
590            .filter(|fingerprint| fingerprint.digest() == Digest::Sha256);
591        if self.trust.pins() {
592            let by_fingerprint = fingerprint.as_ref().map(Normal::of_fingerprint);
593            let by_key = key_of_leaf(&attempt, chain).and_then(|pin| pin.normal());
594            let found = self
595                .peers
596                .read(|records| {
597                    // The certificate itself outranks its key, should two accounts pin them.
598                    by_fingerprint
599                        .iter()
600                        .chain(&by_key)
601                        .find_map(|pin| records.iter().find(|peer| peer.holds(pin)))
602                        .map(|peer| (peer.id.clone(), peer.disabled))
603                })
604                .map_err(|reason| reason.reading("peer table"))?;
605            match found {
606                Some((_, true)) => return Ok(Verdict::Invalid),
607                Some((id, false)) => {
608                    return Ok(Verdict::Valid(Lookup {
609                        by: "id".to_owned(),
610                        value: id,
611                        claims: chain
612                            .first()
613                            .and_then(|leaf| coqui_access_claims::of_certificate(leaf.as_ref())),
614                    }));
615                }
616                None => {}
617            }
618        }
619        if let Some(ca) = &self.ca
620            && attempt.secure == Some(true)
621            && let Some(verdict) = trust::by_ca(ca, &self.policy, &self.account, chain)?
622        {
623            return Ok(verdict);
624        }
625        if self.trust.pins()
626            && let Some(fingerprint) = fingerprint
627        {
628            self.wait(&fingerprint, attempt.peer);
629        }
630        Ok(Verdict::Unknown)
631    }
632
633    fn describe(&self) -> Result<Description, ProviderError> {
634        Ok(Description {
635            name: Some("Client certificates".to_owned()),
636            takes: Some(takes::REQUEST.to_owned()),
637        })
638    }
639}
640
641impl Directory for MtlsAccounts {
642    fn lookup(&self, lookup: Lookup) -> Result<Option<Person>, ProviderError> {
643        let by_certificate = if lookup.by == "certificate" {
644            lookup
645                .value
646                .parse::<PeerId>()
647                .ok()
648                .map(|id| Normal::of_fingerprint(&id))
649        } else {
650            None
651        };
652        self.peers
653            .read(|records| {
654                records
655                    .iter()
656                    .find(|peer| {
657                        !peer.disabled
658                            && match lookup.by.as_str() {
659                                "id" => peer.id == lookup.value,
660                                "name" => peer.name == lookup.value,
661                                "certificate" => {
662                                    by_certificate.as_ref().is_some_and(|own| peer.holds(own))
663                                }
664                                "email" => peer.email.as_deref() == Some(&lookup.value),
665                                _ => false,
666                            }
667                    })
668                    .map(|peer| Person {
669                        id: peer.id.clone(),
670                        name: peer.name.clone(),
671                        display_name: None,
672                        email: peer.email.clone(),
673                        groups: peer.groups.clone(),
674                        attributes: Default::default(),
675                    })
676            })
677            .map_err(|reason| reason.reading("peer table"))
678    }
679}
680
681impl Accounts for MtlsAccounts {
682    fn accounts(&self) -> Result<Vec<AccountInfo>, ProviderError> {
683        self.peers
684            .read(|records| {
685                records
686                    .iter()
687                    .map(|peer| AccountInfo {
688                        id: peer.id.clone(),
689                        name: peer.name.clone(),
690                        groups: peer.groups.clone(),
691                        disabled: Some(peer.disabled),
692                        made_unix: peer.made_unix,
693                        expires_unix: None,
694                        ..AccountInfo::default()
695                    })
696                    .collect()
697            })
698            .map_err(|reason| reason.reading("peer table"))
699    }
700
701    /// Accepts a pin under a name, or changes what is said of a peer there is.
702    ///
703    /// The `secret` of a peer is a pin: a certificate fingerprint in any spelling
704    /// `coqui-peer-tls` reads, or `key:sha256:<hex>` for a public key. For a new name it is
705    /// the peer's first pin; for a peer there is it is one more, up to `max_pins`, and saying
706    /// one the peer holds changes nothing. `remove:` before a pin takes that pin away alone,
707    /// never the last one.
708    fn put(&self, account: AccountPut) -> Result<PutOutcome, ProviderError> {
709        if !self.limits.allows_field(&account.name) {
710            return Err(error::bad_value("a peer has a name"));
711        }
712        if account.reset || account.unlock {
713            return Err(error::unsupported(
714                "this provider keeps no reset mark or failure count",
715            ));
716        }
717        if account.expires_unix.is_some() {
718            return Err(error::bad_value("peers do not expire"));
719        }
720        let change = account
721            .secret
722            .as_deref()
723            .map(|text| match text.strip_prefix(REMOVE_PREFIX) {
724                Some(pin) => Pin::parse(pin).map(Change::Remove),
725                None => Pin::parse(text).map(Change::Add),
726            })
727            .transpose()
728            .map_err(|_| error::bad_value("that is not a certificate fingerprint or key pin"))?;
729        let accepted = self
730            .peers
731            .put_with(|records| {
732                if let Some(Change::Add(pin)) = &change {
733                    let normal = pin
734                        .normal()
735                        .ok_or_else(|| SourceError::invalid("that is not a certificate pin"))?;
736                    if records
737                        .iter()
738                        .any(|peer| peer.holds(&normal) && peer.name != account.name)
739                    {
740                        return Err(SourceError::invalid(
741                            "that certificate belongs to another peer",
742                        ));
743                    }
744                }
745                let mut peer = match (
746                    records.iter().find(|peer| peer.name == account.name),
747                    &change,
748                ) {
749                    (Some(peer), _) => peer.clone(),
750                    (None, Some(Change::Add(_))) => PeerRecord {
751                        id: secret::identifier().map_err(SourceError::unavailable)?,
752                        name: account.name.clone(),
753                        certificate: None,
754                        pins: Vec::new(),
755                        email: None,
756                        groups: Vec::new(),
757                        disabled: false,
758                        made_unix: Some(unix_now()),
759                    },
760                    _ => {
761                        return Err(SourceError::invalid(
762                            "a new peer is accepted by a certificate pin",
763                        ));
764                    }
765                };
766                match &change {
767                    Some(Change::Add(pin)) => peer.add_pin(pin, self.max_pins)?,
768                    Some(Change::Remove(pin)) => peer.remove_pin(pin)?,
769                    None => {}
770                }
771                if let Some(groups) = account.groups {
772                    peer.groups = groups;
773                }
774                if let Some(disabled) = account.disabled {
775                    peer.disabled = disabled;
776                }
777                let accepted = records
778                    .iter()
779                    .filter(|other| other.name != peer.name)
780                    .chain(std::iter::once(&peer))
781                    .filter_map(PeerRecord::held)
782                    .flatten()
783                    .collect::<Vec<_>>();
784                Ok((peer, accepted))
785            })
786            .map_err(|reason| reason.writing("peer table"))?;
787        self.waited(&accepted);
788        Ok(PutOutcome::default())
789    }
790
791    fn remove(&self, name: String) -> Result<(), ProviderError> {
792        self.peers
793            .remove(&name)
794            .map_err(|reason| reason.writing("peer table"))
795            .and_then(|removed| {
796                removed
797                    .then_some(())
798                    .ok_or_else(|| error::not_found("there is no such peer"))
799            })
800    }
801
802    fn waiting(&self) -> Result<Vec<Waiting>, ProviderError> {
803        let _queue = self.queue.lock().unwrap_or_else(PoisonError::into_inner);
804        Ok(self
805            .waits()
806            .into_iter()
807            .rev()
808            .map(|waits| Waiting {
809                shown: waits.fingerprint.canonical(),
810                peer: waits.peer,
811                seen_unix: Some(waits.seen_unix),
812            })
813            .collect())
814    }
815}
816
817/// The source a waiting entry counts against: `address:port`, or a bare address; anything
818/// else shares the one bucket of peers whose address is not known.
819fn source_of(peer: Option<&str>) -> Option<SocketAddr> {
820    let peer = peer?;
821    peer.parse::<SocketAddr>()
822        .ok()
823        .or_else(|| peer.parse().ok().map(|address| SocketAddr::new(address, 0)))
824}
825
826/// The records as a source of pins for a matcher: an enabled record named like the person
827/// holds the fingerprint or the public key the certificate presented.
828impl coqui_access_kit::pins::PinSource for MtlsAccounts {
829    fn check(
830        &self,
831        person: &Person,
832        pins: &coqui_access_kit::pins::PinSet,
833    ) -> Result<coqui_access_kit::pins::PinCheck, ProviderError> {
834        use coqui_access_kit::pins::PinCheck;
835        let wanted: Vec<Normal> = pins
836            .fingerprint
837            .as_deref()
838            .and_then(|text| text.parse::<PeerId>().ok())
839            .map(|id| Normal::of_fingerprint(&id))
840            .into_iter()
841            .chain(pins.key.as_ref().and_then(|value| {
842                Pin {
843                    kind: Pin::KEY.to_owned(),
844                    value: value.clone(),
845                }
846                .normal()
847            }))
848            .collect();
849        let held = self
850            .peers
851            .read(|records| {
852                records.iter().any(|peer| {
853                    peer.name == person.name
854                        && !peer.disabled
855                        && wanted.iter().any(|pin| peer.holds(pin))
856                })
857            })
858            .map_err(|reason| reason.reading("peer table"))?;
859        Ok(if held {
860            PinCheck::Holds
861        } else {
862            PinCheck::Absent
863        })
864    }
865}
866
867/// What a `secret` asks of a peer's pins.
868enum Change {
869    Add(Pin),
870    Remove(Pin),
871}
872
873/// Before a pin in a `secret`: take that pin away from the peer.
874const REMOVE_PREFIX: &str = "remove:";
875
876/// The public key pin of the certificate the transport proved the client holds the key of:
877/// the first of the chain, and only when the attempt is `secure` and its fingerprint, if
878/// it carries one, is that certificate's.
879fn key_of_leaf(attempt: &Attempt, chain: &[coqui_access::guatiao::Bytes]) -> Option<Pin> {
880    let leaf = chain.first()?;
881    if attempt.secure != Some(true) {
882        return None;
883    }
884    if let Some(text) = &attempt.certificate
885        && text.parse::<PeerId>().ok() != Some(PeerId::of(leaf.as_ref()))
886    {
887        return None;
888    }
889    Pin::key_of_certificate(leaf.as_ref())
890}
891
892fn validate(
893    peers: &[PeerRecord],
894    max: usize,
895    max_pins: usize,
896    limits: &RecordLimits,
897) -> Result<(), SourceError> {
898    check_keys(peers, max)?;
899    let mut ids = BTreeSet::new();
900    let mut pinned = BTreeSet::new();
901    for peer in peers {
902        let Some(held) = peer.held() else {
903            return Err(SourceError::invalid(
904                "a peer is pinned by a SHA-256 fingerprint or a public key",
905            ));
906        };
907        if held.is_empty()
908            || held.len() > max_pins
909            || held.iter().any(|pin| !pinned.insert(pin.clone()))
910        {
911            return Err(SourceError::invalid(
912                "a peer holds no pin, too many, or a pin another peer or itself holds",
913            ));
914        }
915        if peer
916            .certificate
917            .is_some_and(|id| id.digest() != Digest::Sha256)
918        {
919            return Err(SourceError::invalid(
920                "a peer certificate is identified by its SHA-256 fingerprint",
921            ));
922        }
923        if !limits.allows_field(&peer.id)
924            || !limits.allows_field(&peer.name)
925            || !ids.insert(&peer.id)
926            || !limits.allows_groups(&peer.groups)
927            || peer
928                .email
929                .as_ref()
930                .is_some_and(|email| !limits.allows_email(email))
931        {
932            return Err(SourceError::invalid(
933                "a peer entry is invalid or duplicated",
934            ));
935        }
936    }
937    Ok(())
938}
939
940#[cfg(test)]
941mod tests {
942    use coqui_peer_tls::Identity;
943
944    use super::*;
945
946    fn attempt(certificate: Option<&str>) -> Attempt {
947        Attempt {
948            name: Some("ignored".to_owned()),
949            secret: Some("ignored".to_owned()),
950            secure: Some(true),
951            certificate: certificate.map(str::to_owned),
952            peer: Some("192.0.2.7:4000".to_owned()),
953            ..Attempt::default()
954        }
955    }
956
957    fn fingerprint() -> PeerId {
958        Identity::generate().unwrap().fingerprint()
959    }
960
961    #[test]
962    fn authenticates_only_known_certificates_and_resolves_groups() {
963        let known = fingerprint();
964        let certificate = known.to_string();
965        let peers = MtlsAccounts::builder()
966            .table(Arc::new(MemoryTable::from_records([PeerRecord::new(
967                "service-1",
968                "site-a",
969                &known,
970            )
971            .groups(["site-a"])])))
972            .build()
973            .unwrap();
974        let Verdict::Valid(lookup) = peers.authenticate(attempt(Some(&certificate))).unwrap()
975        else {
976            panic!("known certificate was rejected");
977        };
978        let person = peers.lookup(lookup).unwrap().unwrap();
979        assert_eq!(person.id, "service-1");
980        assert_eq!(person.groups, vec!["site-a"]);
981        // Any spelling of the fingerprint is the same certificate.
982        let hex = known.canonical();
983        assert!(matches!(
984            peers.authenticate(attempt(Some(&hex))).unwrap(),
985            Verdict::Valid(_)
986        ));
987        assert_eq!(peers.authenticate(attempt(None)).unwrap(), Verdict::Unknown);
988        assert_eq!(
989            peers
990                .authenticate(attempt(Some("not-a-fingerprint")))
991                .unwrap(),
992            Verdict::Unknown
993        );
994        assert!(!format!("{peers:?}").contains(&certificate));
995    }
996
997    #[test]
998    fn disabled_peers_and_malformed_tables_are_refused() {
999        let known = fingerprint();
1000        let certificate = known.to_string();
1001        let build = |records: Vec<PeerRecord>| {
1002            MtlsAccounts::builder()
1003                .table(Arc::new(MemoryTable::from_records(records)))
1004                .build()
1005        };
1006        let peers = build(vec![
1007            PeerRecord::new("service-1", "site-a", &known).disabled(true),
1008        ])
1009        .unwrap();
1010        assert_eq!(
1011            peers.authenticate(attempt(Some(&certificate))).unwrap(),
1012            Verdict::Invalid
1013        );
1014        assert!(
1015            peers
1016                .lookup(Lookup {
1017                    by: "id".to_owned(),
1018                    value: "service-1".to_owned(),
1019                    ..Lookup::default()
1020                })
1021                .unwrap()
1022                .is_none()
1023        );
1024        let twice = vec![
1025            PeerRecord::new("1", "a", &known),
1026            PeerRecord::new("2", "b", &known),
1027        ];
1028        assert!(build(twice).is_err(), "one certificate is one peer");
1029    }
1030
1031    #[test]
1032    fn an_unknown_certificate_waits_and_is_accepted_by_putting_it() {
1033        let peers = MtlsAccounts::builder().build().unwrap();
1034        let fingerprint = fingerprint();
1035        let shown = fingerprint.to_string();
1036        assert_eq!(
1037            peers.authenticate(attempt(Some(&shown))).unwrap(),
1038            Verdict::Unknown
1039        );
1040        // Asking again from the same address does not write it again.
1041        peers.authenticate(attempt(Some(&shown))).unwrap();
1042        let waiting = peers.waiting().unwrap();
1043        assert_eq!(waiting.len(), 1);
1044        assert_eq!(waiting[0].shown, fingerprint.canonical());
1045        assert_eq!(waiting[0].peer.as_deref(), Some("192.0.2.7:4000"));
1046
1047        peers
1048            .put(AccountPut {
1049                name: "site-b".to_owned(),
1050                secret: Some(waiting[0].shown.clone()),
1051                groups: Some(vec!["site-b".to_owned()]),
1052                ..AccountPut::default()
1053            })
1054            .unwrap();
1055        assert!(peers.waiting().unwrap().is_empty());
1056        assert!(matches!(
1057            peers.authenticate(attempt(Some(&shown))).unwrap(),
1058            Verdict::Valid(_)
1059        ));
1060        assert_eq!(peers.accounts().unwrap()[0].name, "site-b");
1061        // The same certificate cannot be two peers; a new peer needs a certificate.
1062        assert!(
1063            peers
1064                .put(AccountPut {
1065                    name: "site-c".to_owned(),
1066                    secret: Some(shown),
1067                    ..AccountPut::default()
1068                })
1069                .is_err()
1070        );
1071        assert!(
1072            peers
1073                .put(AccountPut {
1074                    name: "site-c".to_owned(),
1075                    ..AccountPut::default()
1076                })
1077                .is_err()
1078        );
1079        peers.remove("site-b".to_owned()).unwrap();
1080        assert!(peers.remove("site-b".to_owned()).is_err());
1081    }
1082
1083    #[test]
1084    fn one_address_holds_one_waiting_place() {
1085        let peers = MtlsAccounts::builder().build().unwrap();
1086        for _ in 0..3 {
1087            let shown = fingerprint().to_string();
1088            peers.authenticate(attempt(Some(&shown))).unwrap();
1089        }
1090        assert_eq!(peers.waiting().unwrap().len(), 1);
1091    }
1092
1093    fn from_source(last: u8, certificate: &PeerId) -> Attempt {
1094        Attempt {
1095            peer: Some(format!("192.0.2.{last}:4000")),
1096            certificate: Some(certificate.to_string()),
1097            ..Attempt::default()
1098        }
1099    }
1100
1101    #[test]
1102    fn two_providers_over_one_waiting_table_share_a_sources_place() {
1103        let waiting = Arc::new(MemoryTable::<Unaccepted>::new());
1104        let build = || {
1105            MtlsAccounts::builder()
1106                .waiting(waiting.clone())
1107                .build()
1108                .unwrap()
1109        };
1110        let (first, second) = (build(), build());
1111        first.authenticate(from_source(9, &fingerprint())).unwrap();
1112        // The second provider has not seen the first one's entry in memory, only in the table.
1113        second.authenticate(from_source(9, &fingerprint())).unwrap();
1114        assert_eq!(
1115            waiting.load().unwrap().records.len(),
1116            1,
1117            "one place for 192.0.2.9"
1118        );
1119    }
1120
1121    #[test]
1122    fn providers_racing_over_one_waiting_table_never_pass_its_total() {
1123        let waiting = Arc::new(MemoryTable::<Unaccepted>::new());
1124        let limits = {
1125            let mut limits = default_waiting_limits();
1126            limits.total = 3;
1127            limits
1128        };
1129        let providers: Vec<Arc<MtlsAccounts>> = (0..2)
1130            .map(|_| {
1131                Arc::new(
1132                    MtlsAccounts::builder()
1133                        .waiting(waiting.clone())
1134                        .waiting_limits(limits)
1135                        .build()
1136                        .unwrap(),
1137                )
1138            })
1139            .collect();
1140        let start = Arc::new(std::sync::Barrier::new(16));
1141        let threads: Vec<_> = (0..16u8)
1142            .map(|number| {
1143                let provider = providers[usize::from(number % 2)].clone();
1144                let start = start.clone();
1145                let from = from_source(number + 10, &fingerprint());
1146                std::thread::spawn(move || {
1147                    start.wait();
1148                    provider.authenticate(from).unwrap();
1149                })
1150            })
1151            .collect();
1152        for thread in threads {
1153            thread.join().unwrap();
1154        }
1155        assert_eq!(waiting.load().unwrap().records.len(), 3);
1156    }
1157
1158    #[test]
1159    fn the_waiting_limits_and_the_waiting_table_are_the_callers() {
1160        let waiting = Arc::new(MemoryTable::<Unaccepted>::new());
1161        let peers = MtlsAccounts::builder()
1162            .waiting(waiting.clone())
1163            .waiting_limits({
1164                let mut limits = default_waiting_limits();
1165                limits.total = 2;
1166                limits
1167            })
1168            .build()
1169            .unwrap();
1170        for last in 1..=3 {
1171            let from = Attempt {
1172                peer: Some(format!("192.0.2.{last}:4000")),
1173                certificate: Some(fingerprint().to_string()),
1174                ..Attempt::default()
1175            };
1176            peers.authenticate(from).unwrap();
1177        }
1178        // Full: the newcomer is not written down, and nobody is pushed out for it.
1179        let kept = waiting.load().unwrap().records;
1180        assert_eq!(kept.len(), 2);
1181        assert_eq!(kept[0].peer.as_deref(), Some("192.0.2.1:4000"));
1182        assert_eq!(peers.waiting().unwrap().len(), 2);
1183    }
1184
1185    #[test]
1186    fn two_addresses_in_one_ipv6_64_share_one_place() {
1187        let peers = MtlsAccounts::builder().build().unwrap();
1188        for (address, expected) in [
1189            ("[2001:db8:1:2::1]:4000", 1),
1190            ("[2001:db8:1:2:ffff::9]:4000", 1),
1191            ("[2001:db8:1:3::1]:4000", 2),
1192            ("[::ffff:192.0.2.1]:4000", 3),
1193            ("192.0.2.1:5000", 3),
1194        ] {
1195            let from = Attempt {
1196                peer: Some(address.to_owned()),
1197                certificate: Some(fingerprint().to_string()),
1198                ..Attempt::default()
1199            };
1200            peers.authenticate(from).unwrap();
1201            assert_eq!(peers.waiting().unwrap().len(), expected, "{address}");
1202        }
1203    }
1204
1205    #[test]
1206    fn a_provider_built_over_a_waiting_table_counts_what_is_there() {
1207        let waiting = Arc::new(MemoryTable::<Unaccepted>::new());
1208        let one = fingerprint();
1209        let shown = one.to_string();
1210        let first = MtlsAccounts::builder()
1211            .waiting(waiting.clone())
1212            .build()
1213            .unwrap();
1214        first.authenticate(attempt(Some(&shown))).unwrap();
1215        // A provider built over the same table counts the entry against its source: the
1216        // source's one place stays with the first fingerprint, and a newcomer is not written down.
1217        let again = MtlsAccounts::builder()
1218            .waiting(waiting.clone())
1219            .build()
1220            .unwrap();
1221        again.authenticate(attempt(Some(&shown))).unwrap();
1222        assert_eq!(waiting.load().unwrap().records.len(), 1, "already waiting");
1223        let other = fingerprint();
1224        again
1225            .authenticate(attempt(Some(&other.to_string())))
1226            .unwrap();
1227        let kept = waiting.load().unwrap().records;
1228        assert_eq!(kept.len(), 1, "one place for 192.0.2.7");
1229        assert_eq!(kept[0].fingerprint, one);
1230    }
1231
1232    #[test]
1233    fn fingerprints_are_kept_in_their_canonical_form_and_read_in_any() {
1234        let known = fingerprint();
1235        let record = PeerRecord::new("1", "a", &known);
1236        let value = record.to_value().unwrap();
1237        let map = coqui_access::guatiao::Map::try_from(value.clone()).unwrap();
1238        assert_eq!(
1239            map.get("certificate")
1240                .map(|text| String::from_value(text).unwrap()),
1241            Some(known.canonical())
1242        );
1243        assert_eq!(PeerRecord::from_value(&value).unwrap(), record);
1244        let mut grouped = map.clone();
1245        grouped.set("certificate", known.to_base32_grouped());
1246        assert_eq!(PeerRecord::from_value(&grouped.into()).unwrap(), record);
1247        let mut bad = map;
1248        bad.set("certificate", "bad");
1249        assert!(PeerRecord::from_value(&bad.into()).is_err());
1250    }
1251
1252    #[test]
1253    fn a_waiting_table_that_cannot_be_written_means_nobody_waits() {
1254        struct Fixed;
1255        impl Table<Unaccepted> for Fixed {
1256            fn load(&self) -> Result<coqui_access_kit::Snapshot<Unaccepted>, SourceError> {
1257                Ok(coqui_access_kit::Snapshot::new(
1258                    coqui_access_kit::Revision::default(),
1259                    Vec::new(),
1260                ))
1261            }
1262        }
1263        let peers = MtlsAccounts::builder()
1264            .waiting(Arc::new(Fixed))
1265            .build()
1266            .unwrap();
1267        assert_eq!(
1268            peers
1269                .authenticate(attempt(Some(&fingerprint().to_string())))
1270                .unwrap(),
1271            Verdict::Unknown
1272        );
1273        assert!(peers.waiting().unwrap().is_empty());
1274    }
1275}