Skip to main content

coqui_access_mtls/
pin.rs

1//! What an account pins a client certificate by: its fingerprint, or its public key.
2
3use std::fmt;
4
5use coqui_access::guatiao::{FromValue, Schema, ToValue};
6use coqui_peer_tls::{Digest, PeerId};
7
8/// One thing an account pins, as a record names it: a `kind` and a canonical `value`.
9///
10/// - `fingerprint`: the SHA-256 of the whole certificate, as `sha256:<hex>`. A renewed
11///   certificate is a new fingerprint.
12/// - `key`: the SHA-256 of the certificate's SubjectPublicKeyInfo, as `sha256:<hex>`. A
13///   certificate renewed on the same key keeps it.
14///
15/// As text, for [`AccountPut::secret`](coqui_access::AccountPut::secret), a fingerprint is
16/// `sha256:<hex>` (any spelling `coqui-peer-tls` reads) and a key is `key:sha256:<hex>`.
17#[derive(Clone, PartialEq, Eq, Hash, FromValue, Schema, ToValue)]
18#[map(crate = ::coqui_access::guatiao, deny_unknown_fields)]
19#[non_exhaustive]
20pub struct Pin {
21    /// [`Pin::FINGERPRINT`] or [`Pin::KEY`].
22    pub kind: String,
23    /// `sha256:<64 hex digits>` of what the kind names.
24    pub value: String,
25}
26
27/// The two kinds, as the program tells them apart.
28#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
29pub(crate) enum Kind {
30    Fingerprint,
31    Key,
32}
33
34/// A pin in one spelling, so two spellings of the same thing compare equal.
35#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
36pub(crate) struct Normal {
37    pub(crate) kind: Kind,
38    pub(crate) value: String,
39}
40
41impl Pin {
42    /// The kind of a pin on the whole certificate.
43    pub const FINGERPRINT: &'static str = "fingerprint";
44    /// The kind of a pin on the certificate's public key.
45    pub const KEY: &'static str = "key";
46
47    /// The pin on a certificate's SHA-256 fingerprint.
48    pub fn fingerprint(fingerprint: &PeerId) -> Self {
49        Self {
50            kind: Self::FINGERPRINT.to_owned(),
51            value: fingerprint.canonical(),
52        }
53    }
54
55    /// The pin on the public key of a DER certificate; `None` when it does not parse.
56    pub fn key_of_certificate(der: &[u8]) -> Option<Self> {
57        coqui_access_claims::public_key_hash(der).map(|value| Self {
58            kind: Self::KEY.to_owned(),
59            value,
60        })
61    }
62
63    /// The pin on a DER `SubjectPublicKeyInfo`.
64    pub fn key_of_public_key_info(info: &[u8]) -> Self {
65        Self {
66            kind: Self::KEY.to_owned(),
67            value: coqui_access_claims::public_key_info_hash(info),
68        }
69    }
70
71    /// Reads a pin from the text [`text`](Pin::text) writes.
72    ///
73    /// # Errors
74    ///
75    /// When the text is neither a SHA-256 fingerprint nor `key:sha256:<hex>`.
76    pub fn parse(text: &str) -> Result<Self, PinError> {
77        let pin = match text.strip_prefix("key:") {
78            Some(value) => Self {
79                kind: Self::KEY.to_owned(),
80                value: value.to_owned(),
81            },
82            None => Self {
83                kind: Self::FINGERPRINT.to_owned(),
84                value: text.to_owned(),
85            },
86        };
87        pin.normal()
88            .map(|normal| Self {
89                kind: pin.kind.clone(),
90                value: normal.value,
91            })
92            .ok_or(PinError)
93    }
94
95    /// The text [`parse`](Pin::parse) reads: `sha256:<hex>` for a fingerprint,
96    /// `key:sha256:<hex>` for a key.
97    pub fn text(&self) -> String {
98        match self.kind.as_str() {
99            Self::KEY => format!("key:{}", self.value),
100            _ => self.value.clone(),
101        }
102    }
103
104    /// The pin in one spelling, or `None` when its kind or value is not valid.
105    pub(crate) fn normal(&self) -> Option<Normal> {
106        match self.kind.as_str() {
107            Self::FINGERPRINT => {
108                let id = self.value.parse::<PeerId>().ok()?;
109                (id.digest() == Digest::Sha256).then(|| Normal::of_fingerprint(&id))
110            }
111            Self::KEY => {
112                let hex = self.value.strip_prefix("sha256:")?;
113                let valid = hex.len() == 64 && hex.bytes().all(|byte| byte.is_ascii_hexdigit());
114                valid.then(|| Normal {
115                    kind: Kind::Key,
116                    value: format!("sha256:{}", hex.to_ascii_lowercase()),
117                })
118            }
119            _ => None,
120        }
121    }
122}
123
124impl Normal {
125    pub(crate) fn of_fingerprint(fingerprint: &PeerId) -> Self {
126        Self {
127            kind: Kind::Fingerprint,
128            value: fingerprint.canonical(),
129        }
130    }
131}
132
133/// The kind of a pin shows; what it pins does not.
134impl fmt::Debug for Pin {
135    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
136        formatter
137            .debug_struct("Pin")
138            .field("kind", &self.kind)
139            .field("value", &"[REDACTED]")
140            .finish()
141    }
142}
143
144/// Text that is not a pin. It never quotes the text.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146#[non_exhaustive]
147pub struct PinError;
148
149impl fmt::Display for PinError {
150    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
151        formatter.write_str("not a SHA-256 certificate fingerprint or key:sha256:<hex> key pin")
152    }
153}
154
155impl core::error::Error for PinError {}