Skip to main content

ts_webauthn/response/
authenticator_data.rs

1//! Authenticator data from the response.
2
3use base64ct::{Base64UrlUnpadded, Encoding};
4use ts_io::{Cursor, OutOfBounds};
5
6use crate::response::attestation::{CredentialData, CredentialDataError};
7
8/// Authenticator data flags.
9///
10/// <https://w3c.github.io/webauthn/#authdata-flags>
11#[derive(Clone, Copy, PartialEq)]
12pub struct Flags(u8);
13impl Flags {
14    /// `UP` bit.
15    pub const USER_PRESENT: u8 = 0b0000_0001;
16    /// `UV` bit.
17    pub const USER_VERIFIED: u8 = 0b0000_0100;
18    /// `BE` bit.
19    pub const BACKUP_ELIGABLE: u8 = 0b0000_1000;
20    /// `BS` bit.
21    pub const BACKED_UP: u8 = 0b0001_0000;
22    /// `AT` bit.
23    pub const ATTESTATION_DATA: u8 = 0b0100_0000;
24    /// `ED` bit.
25    pub const EXTENSIONS_DATA: u8 = 0b1000_0000;
26
27    /// Returns if these flags contain the other flags.
28    pub fn has(self, flags: u8) -> bool {
29        self.0 & flags == flags
30    }
31}
32impl core::fmt::Debug for Flags {
33    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
34        write!(f, "{:08b}", self.0)
35    }
36}
37
38/// <https://w3c.github.io/webauthn/#authenticator-data>
39#[derive(Clone)]
40pub struct AuthenticatorData {
41    /// The `sha256` hash of the relying party ID the authenticator received.
42    pub relying_party_id_hash: [u8; 32],
43    /// The authenticator flags.
44    pub flags: Flags,
45    /// The internal signature counter for this credential, if unsupported, this should always be 0.
46    pub signature_count: u32,
47    /// The attested credential data for credential creation.
48    pub attested_credential_data: Option<CredentialData>,
49    /// Any extension data.
50    pub extensions: Option<Vec<u8>>,
51}
52
53impl TryFrom<&[u8]> for AuthenticatorData {
54    type Error = AuthenticatorDataError;
55
56    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
57        let mut cursor = Cursor::new(value);
58
59        // Contrary to the spec, the first byte is 88
60        // and the second byte is the remaining length...
61        // where does this come from?
62
63        let relying_party_id_hash = cursor.read_array::<32>()?;
64        let flags = Flags(cursor.read_array::<1>()?[0]);
65        let signature_count = u32::from_be_bytes(cursor.read_array()?);
66
67        #[expect(clippy::if_then_some_else_none, reason = "cannot use ? operator")]
68        let attested_credential_data = if flags.has(Flags::ATTESTATION_DATA) {
69            Some(CredentialData::try_from(&mut cursor)?)
70        } else {
71            None
72        };
73
74        let extensions = flags
75            .has(Flags::EXTENSIONS_DATA)
76            .then(|| cursor.remaining().to_vec());
77
78        Ok(Self {
79            relying_party_id_hash,
80            flags,
81            signature_count,
82            attested_credential_data,
83            extensions,
84        })
85    }
86}
87
88impl core::fmt::Debug for AuthenticatorData {
89    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
90        let rp_id_hash = Base64UrlUnpadded::encode_string(&self.relying_party_id_hash);
91        let extensions = self
92            .extensions
93            .as_deref()
94            .map(Base64UrlUnpadded::encode_string);
95
96        f.debug_struct("AuthenticatorData")
97            .field("relying_party_id_hash", &rp_id_hash)
98            .field("flags", &self.flags)
99            .field("signature_count", &self.signature_count)
100            .field("attested_credential_data", &self.attested_credential_data)
101            .field("extensions", &extensions)
102            .finish()
103    }
104}
105
106/// Error variants for parsing some bytes as authenticator data.
107#[derive(Debug)]
108#[non_exhaustive]
109#[allow(missing_docs)]
110pub enum AuthenticatorDataError {
111    #[non_exhaustive]
112    Read { source: OutOfBounds },
113
114    #[non_exhaustive]
115    CredentialData { source: CredentialDataError },
116}
117
118impl core::fmt::Display for AuthenticatorDataError {
119    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
120        match &self {
121            Self::Read { .. } => write!(f, "could not read the required bytes"),
122            Self::CredentialData { .. } => {
123                write!(f, "could not deserialize the attested credential data")
124            }
125        }
126    }
127}
128
129impl core::error::Error for AuthenticatorDataError {
130    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
131        match &self {
132            Self::Read { source, .. } => Some(source),
133            Self::CredentialData { source, .. } => Some(source),
134        }
135    }
136}
137
138impl From<OutOfBounds> for AuthenticatorDataError {
139    fn from(source: OutOfBounds) -> Self {
140        Self::Read { source }
141    }
142}
143
144impl From<CredentialDataError> for AuthenticatorDataError {
145    fn from(source: CredentialDataError) -> Self {
146        Self::CredentialData { source }
147    }
148}