extern crate alloc;
#[cfg(test)]
mod tests;
use crate::{
request::{
Challenge, RpId, Url,
register::{PublicKeyCredentialUserEntity, UserHandle},
},
response::{
auth::error::{
AuthCeremonyErr, AuthenticatorDataErr as AuthAuthDataErr,
AuthenticatorExtensionOutputErr as AuthAuthExtErr,
},
error::{CollectedClientDataErr, CredentialIdErr},
register::error::{
AttestationObjectErr, AttestedCredentialDataErr,
AuthenticatorDataErr as RegAuthDataErr,
AuthenticatorExtensionOutputErr as RegAuthExtErr, PubKeyErr, RegCeremonyErr,
},
},
};
use alloc::borrow::Cow;
use core::{
borrow::Borrow,
cmp::Ordering,
convert::Infallible,
fmt::{self, Display, Formatter},
hash::{Hash, Hasher},
str,
};
use rsa::sha2::{Sha256, digest::OutputSizeUser as _};
#[cfg(feature = "serde_relaxed")]
use ser_relaxed::SerdeJsonErr;
pub mod auth;
#[cfg(feature = "bin")]
pub mod bin;
mod cbor;
#[cfg(feature = "custom")]
pub mod custom;
pub mod error;
pub mod register;
#[cfg(feature = "serde")]
pub(crate) mod ser;
#[cfg(feature = "serde_relaxed")]
pub mod ser_relaxed;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Backup {
NotEligible,
Eligible,
Exists,
}
impl PartialEq<&Self> for Backup {
#[inline]
fn eq(&self, other: &&Self) -> bool {
*self == **other
}
}
impl PartialEq<Backup> for &Backup {
#[inline]
fn eq(&self, other: &Backup) -> bool {
**self == *other
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AuthenticatorTransport {
Ble,
Hybrid,
Internal,
Nfc,
SmartCard,
Usb,
}
impl AuthenticatorTransport {
const fn to_u8(self) -> u8 {
match self {
Self::Ble => 0x1,
Self::Hybrid => 0x2,
Self::Internal => 0x4,
Self::Nfc => 0x8,
Self::SmartCard => 0x10,
Self::Usb => 0x20,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct AuthTransports(u8);
impl AuthTransports {
#[cfg(feature = "custom")]
pub const NONE: Self = Self::new();
#[cfg(feature = "custom")]
pub const ALL: Self = Self::all();
#[cfg(any(feature = "bin", feature = "custom", feature = "serde"))]
pub(super) const fn new() -> Self {
Self(0)
}
#[cfg(any(feature = "bin", feature = "custom"))]
const fn all() -> Self {
Self::new()
.add_transport(AuthenticatorTransport::Ble)
.add_transport(AuthenticatorTransport::Hybrid)
.add_transport(AuthenticatorTransport::Internal)
.add_transport(AuthenticatorTransport::Nfc)
.add_transport(AuthenticatorTransport::SmartCard)
.add_transport(AuthenticatorTransport::Usb)
}
#[inline]
#[must_use]
pub const fn count(self) -> u32 {
self.0.count_ones()
}
#[inline]
#[must_use]
pub const fn is_empty(self) -> bool {
self.0 == 0
}
#[inline]
#[must_use]
pub const fn contains(self, transport: AuthenticatorTransport) -> bool {
let val = transport.to_u8();
self.0 & val == val
}
#[cfg(any(feature = "bin", feature = "custom", feature = "serde"))]
const fn add_transport(self, transport: AuthenticatorTransport) -> Self {
Self(self.0 | transport.to_u8())
}
#[cfg(feature = "custom")]
#[inline]
#[must_use]
pub const fn add(self, transport: AuthenticatorTransport) -> Self {
self.add_transport(transport)
}
#[cfg(feature = "custom")]
#[inline]
#[must_use]
pub const fn remove(self, transport: AuthenticatorTransport) -> Self {
Self(self.0 & !transport.to_u8())
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum AuthenticatorAttachment {
#[default]
None,
Platform,
CrossPlatform,
}
impl PartialEq<&Self> for AuthenticatorAttachment {
#[inline]
fn eq(&self, other: &&Self) -> bool {
*self == **other
}
}
impl PartialEq<AuthenticatorAttachment> for &AuthenticatorAttachment {
#[inline]
fn eq(&self, other: &AuthenticatorAttachment) -> bool {
**self == *other
}
}
pub const CRED_ID_MAX_LEN: usize = 1023;
pub const CRED_ID_MIN_LEN: usize = 16;
#[derive(Clone, Copy, Debug)]
pub struct CredentialId<T>(T);
impl<T> CredentialId<T> {
#[inline]
pub fn into_inner(self) -> T {
self.0
}
#[inline]
pub const fn inner(&self) -> &T {
&self.0
}
}
impl<'a> CredentialId<&'a [u8]> {
fn from_slice<'b: 'a>(value: &'b [u8]) -> Result<Self, CredentialIdErr> {
if (CRED_ID_MIN_LEN..=CRED_ID_MAX_LEN).contains(&value.len()) {
Ok(Self(value))
} else {
Err(CredentialIdErr)
}
}
}
impl<T: AsRef<[u8]>> AsRef<[u8]> for CredentialId<T> {
#[inline]
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl<T: Borrow<[u8]>> Borrow<[u8]> for CredentialId<T> {
#[inline]
fn borrow(&self) -> &[u8] {
self.0.borrow()
}
}
impl<'a: 'b, 'b> From<&'a CredentialId<Box<[u8]>>> for CredentialId<&'b Box<[u8]>> {
#[inline]
fn from(value: &'a CredentialId<Box<[u8]>>) -> Self {
Self(&value.0)
}
}
impl<'a: 'b, 'b> From<CredentialId<&'a Box<[u8]>>> for CredentialId<&'b [u8]> {
#[inline]
fn from(value: CredentialId<&'a Box<[u8]>>) -> Self {
Self(value.0)
}
}
impl<'a: 'b, 'b> From<&'a CredentialId<Box<[u8]>>> for CredentialId<&'b [u8]> {
#[inline]
fn from(value: &'a CredentialId<Box<[u8]>>) -> Self {
Self(&value.0)
}
}
impl From<CredentialId<&[u8]>> for CredentialId<Box<[u8]>> {
#[inline]
fn from(value: CredentialId<&[u8]>) -> Self {
Self(value.0.into())
}
}
impl<T: PartialEq<T2>, T2: PartialEq<T>> PartialEq<CredentialId<T>> for CredentialId<T2> {
#[inline]
fn eq(&self, other: &CredentialId<T>) -> bool {
self.0 == other.0
}
}
impl<T: PartialEq<T2>, T2: PartialEq<T>> PartialEq<CredentialId<T>> for &CredentialId<T2> {
#[inline]
fn eq(&self, other: &CredentialId<T>) -> bool {
**self == *other
}
}
impl<T: PartialEq<T2>, T2: PartialEq<T>> PartialEq<&CredentialId<T>> for CredentialId<T2> {
#[inline]
fn eq(&self, other: &&CredentialId<T>) -> bool {
*self == **other
}
}
impl<T: Eq> Eq for CredentialId<T> {}
impl<T: Hash> Hash for CredentialId<T> {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl<T: PartialOrd<T2>, T2: PartialOrd<T>> PartialOrd<CredentialId<T>> for CredentialId<T2> {
#[inline]
fn partial_cmp(&self, other: &CredentialId<T>) -> Option<Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl<T: Ord> Ord for CredentialId<T> {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.0.cmp(&other.0)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SentChallenge(pub u128);
impl SentChallenge {
#[expect(
clippy::little_endian_bytes,
reason = "Challenge and SentChallenge need to be compatible, and we need to ensure the data is sent and received in the same order"
)]
#[inline]
#[must_use]
pub const fn from_array(value: [u8; 16]) -> Self {
Self(u128::from_le_bytes(value))
}
#[inline]
#[must_use]
pub const fn from_challenge(value: Challenge) -> Self {
Self(value.into_data())
}
}
impl From<Challenge> for SentChallenge {
#[inline]
fn from(value: Challenge) -> Self {
Self::from_challenge(value)
}
}
impl From<[u8; 16]> for SentChallenge {
#[inline]
fn from(value: [u8; 16]) -> Self {
Self::from_array(value)
}
}
impl PartialEq<&Self> for SentChallenge {
#[inline]
fn eq(&self, other: &&Self) -> bool {
*self == **other
}
}
impl PartialEq<SentChallenge> for &SentChallenge {
#[inline]
fn eq(&self, other: &SentChallenge) -> bool {
**self == *other
}
}
impl PartialOrd for SentChallenge {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SentChallenge {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.0.cmp(&other.0)
}
}
impl Hash for SentChallenge {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_u128(self.0);
}
}
#[derive(Debug, Eq)]
pub struct Origin<'a>(pub Cow<'a, str>);
impl PartialEq<Origin<'_>> for Origin<'_> {
#[inline]
fn eq(&self, other: &Origin<'_>) -> bool {
self.0 == other.0
}
}
impl PartialEq<&Origin<'_>> for Origin<'_> {
#[inline]
fn eq(&self, other: &&Origin<'_>) -> bool {
*self == **other
}
}
impl PartialEq<Origin<'_>> for &Origin<'_> {
#[inline]
fn eq(&self, other: &Origin<'_>) -> bool {
**self == *other
}
}
impl PartialEq<str> for Origin<'_> {
#[inline]
fn eq(&self, other: &str) -> bool {
self.0.as_ref() == other
}
}
impl PartialEq<Origin<'_>> for str {
#[inline]
fn eq(&self, other: &Origin<'_>) -> bool {
*other == *self
}
}
impl PartialEq<&str> for Origin<'_> {
#[inline]
fn eq(&self, other: &&str) -> bool {
*self == **other
}
}
impl PartialEq<Origin<'_>> for &str {
#[inline]
fn eq(&self, other: &Origin<'_>) -> bool {
**self == *other
}
}
impl PartialEq<String> for Origin<'_> {
#[inline]
fn eq(&self, other: &String) -> bool {
self.0 == *other
}
}
impl PartialEq<Origin<'_>> for String {
#[inline]
fn eq(&self, other: &Origin<'_>) -> bool {
*other == *self
}
}
impl PartialEq<Url> for Origin<'_> {
#[inline]
fn eq(&self, other: &Url) -> bool {
self.0.as_ref() == other.as_ref()
}
}
impl PartialEq<Origin<'_>> for Url {
#[inline]
fn eq(&self, other: &Origin<'_>) -> bool {
*other == *self
}
}
impl PartialEq<&Url> for Origin<'_> {
#[inline]
fn eq(&self, other: &&Url) -> bool {
*self == **other
}
}
impl PartialEq<Origin<'_>> for &Url {
#[inline]
fn eq(&self, other: &Origin<'_>) -> bool {
**self == *other
}
}
#[derive(Clone, Copy, Debug)]
pub struct Flag {
pub user_present: bool,
pub user_verified: bool,
pub backup: Backup,
}
pub(super) trait AuthData<'a>: Sized {
type UpBitErr;
type CredData;
type Ext: AuthExtOutput + Copy;
fn user_is_not_present() -> Result<(), Self::UpBitErr>;
fn contains_at_bit() -> bool;
fn new(
rp_id_hash: &'a [u8],
flags: Flag,
sign_count: u32,
attested_credential_data: Self::CredData,
extensions: Self::Ext,
) -> Self;
fn rp_hash(&self) -> &'a [u8];
fn flag(&self) -> Flag;
}
#[derive(Debug)]
pub struct CollectedClientData<'a> {
pub challenge: SentChallenge,
pub origin: Origin<'a>,
pub cross_origin: bool,
pub top_origin: Option<Origin<'a>>,
}
impl<'a> CollectedClientData<'a> {
#[inline]
pub fn from_client_data_json<'b: 'a, const REGISTRATION: bool>(
json: &'b [u8],
) -> Result<Self, CollectedClientDataErr> {
LimitedVerificationParser::<REGISTRATION>::parse(json)
}
#[cfg(feature = "serde_relaxed")]
#[inline]
pub fn from_client_data_json_relaxed<'b: 'a, const REGISTRATION: bool>(
json: &'b [u8],
) -> Result<Self, SerdeJsonErr> {
ser_relaxed::RelaxedClientDataJsonParser::<REGISTRATION>::parse(json)
}
}
trait ClientDataJsonParser {
type Err;
fn parse(json: &[u8]) -> Result<CollectedClientData<'_>, Self::Err>;
fn get_sent_challenge(json: &[u8]) -> Result<SentChallenge, Self::Err>;
}
struct LimitedVerificationParser<const REGISTRATION: bool>;
impl<const R: bool> LimitedVerificationParser<R> {
#[expect(unsafe_code, reason = "comment justifies its correctness")]
#[expect(
clippy::arithmetic_side_effects,
clippy::indexing_slicing,
reason = "comments justify their correctness"
)]
fn parse_string(val: &[u8]) -> Result<(Cow<'_, str>, &'_ [u8]), CollectedClientDataErr> {
enum State {
Normal,
Escape,
UnicodeEscape,
UnicodeHex1,
UnicodeHex2,
UnicodeHex3(u8),
}
let mut utf8 = Vec::new();
let mut all_ascii = true;
let mut cur_idx = 0;
let mut state = State::Normal;
for (counter, &b) in val.iter().enumerate() {
match state {
State::Normal => {
match b {
b'"' => {
if utf8.is_empty() {
if all_ascii {
let s = &val[cur_idx..counter];
let v = unsafe { str::from_utf8_unchecked(s) };
return Ok((Cow::Borrowed(v), &val[counter + 1..]));
}
return str::from_utf8(&val[cur_idx..counter])
.map_err(CollectedClientDataErr::Utf8)
.map(|v| (Cow::Borrowed(v), &val[counter + 1..]));
}
utf8.extend_from_slice(&val[cur_idx..counter]);
if all_ascii {
let v = unsafe { String::from_utf8_unchecked(utf8) };
return Ok((Cow::Owned(v), &val[counter + 1..]));
}
return String::from_utf8(utf8)
.map_err(CollectedClientDataErr::Utf8Owned)
.map(|v| (Cow::Owned(v), &val[counter + 1..]));
}
b'\\' => {
utf8.extend_from_slice(&val[cur_idx..counter]);
state = State::Escape;
}
..=0x1f => return Err(CollectedClientDataErr::InvalidEscapedString),
128.. => all_ascii = false,
_ => (),
}
}
State::Escape => {
match b {
b'"' | b'\\' => {
cur_idx = counter;
state = State::Normal;
}
b'u' => {
state = State::UnicodeEscape;
}
_ => {
return Err(CollectedClientDataErr::InvalidEscapedString);
}
}
}
State::UnicodeEscape => {
if b != b'0' {
return Err(CollectedClientDataErr::InvalidEscapedString);
}
state = State::UnicodeHex1;
}
State::UnicodeHex1 => {
if b != b'0' {
return Err(CollectedClientDataErr::InvalidEscapedString);
}
state = State::UnicodeHex2;
}
State::UnicodeHex2 => {
state = State::UnicodeHex3(match b {
b'0' => 0,
b'1' => 0x10,
_ => return Err(CollectedClientDataErr::InvalidEscapedString),
});
}
State::UnicodeHex3(v) => {
match b {
b'0'..=b'9' | b'a'..=b'f' => {
utf8.push(v | (b - if b < b'a' { b'0' } else { 87 }));
cur_idx = counter + 1;
state = State::Normal;
}
_ => return Err(CollectedClientDataErr::InvalidEscapedString),
}
}
}
}
Err(CollectedClientDataErr::InvalidObject)
}
}
impl<const R: bool> ClientDataJsonParser for LimitedVerificationParser<R> {
type Err = CollectedClientDataErr;
#[expect(
clippy::little_endian_bytes,
reason = "Challenge::serialize and this need to be consistent across architectures"
)]
#[expect(clippy::too_many_lines, reason = "110 lines is fine")]
fn parse(json: &[u8]) -> Result<CollectedClientData<'_>, Self::Err> {
const HEADER: &[u8; 18] = br#"{"type":"webauthn."#;
const GET: &[u8; 3] = b"get";
const CREATE: &[u8; 6] = b"create";
const AFTER_TYPE: &[u8; 15] = br#"","challenge":""#;
const AFTER_CHALLENGE: &[u8; 12] = br#"","origin":""#;
const AFTER_ORIGIN: &[u8; 15] = br#","crossOrigin":"#;
const TRUE: &[u8; 4] = b"true";
const FALSE: &[u8; 5] = b"false";
const AFTER_CROSS: &[u8; 13] = br#""topOrigin":""#;
json.split_last().ok_or(CollectedClientDataErr::Len).and_then(|(last, last_rem)| {
if *last == b'}' {
last_rem.split_at_checked(HEADER.len()).ok_or(CollectedClientDataErr::Len).and_then(|(header, header_rem)| {
if header == HEADER {
if R {
header_rem.split_at_checked(CREATE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(create, create_rem)| {
if create == CREATE {
Ok(create_rem)
} else {
Err(CollectedClientDataErr::Type)
}
})
} else {
header_rem.split_at_checked(GET.len()).ok_or(CollectedClientDataErr::Len).and_then(|(get, get_rem)| {
if get == GET {
Ok(get_rem)
} else {
Err(CollectedClientDataErr::Type)
}
})
}.and_then(|type_rem| {
type_rem.split_at_checked(AFTER_TYPE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(chall_key, chall_key_rem)| {
if chall_key == AFTER_TYPE {
chall_key_rem.split_at_checked(Challenge::BASE64_LEN).ok_or(CollectedClientDataErr::Len).and_then(|(base64_chall, base64_chall_rem)| {
let mut chall = [0; 16];
base64url_nopad::decode_buffer_exact(base64_chall, chall.as_mut_slice()).map_err(|_e| CollectedClientDataErr::Challenge).and_then(|()| {
base64_chall_rem.split_at_checked(AFTER_CHALLENGE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(origin_key, origin_key_rem)| {
if origin_key == AFTER_CHALLENGE {
Self::parse_string(origin_key_rem).and_then(|(origin, origin_rem)| {
origin_rem.split_at_checked(AFTER_ORIGIN.len()).ok_or(CollectedClientDataErr::Len).and_then(|(cross_key, cross_key_rem)| {
if cross_key == AFTER_ORIGIN {
cross_key_rem.split_at_checked(TRUE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(cross_true, cross_true_rem)| {
if cross_true == TRUE {
Ok((true, cross_true_rem))
} else {
cross_key_rem.split_at_checked(FALSE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(cross_false, cross_false_rem)| {
if cross_false == FALSE {
Ok((false, cross_false_rem))
} else {
Err(CollectedClientDataErr::CrossOrigin)
}
})
}.and_then(|(cross, cross_rem)| {
cross_rem.split_first().map_or(Ok((cross, None)), |(comma, comma_rem)| {
if *comma == b',' {
comma_rem.split_at_checked(AFTER_CROSS.len()).map_or(Ok((cross, None)), |(top, top_rem)| {
if top == AFTER_CROSS {
if cross {
Self::parse_string(top_rem).and_then(|(top_origin, top_origin_rem)| {
top_origin_rem.first().map_or(Ok(()), |v| {
if *v == b',' {
Ok(())
} else {
Err(CollectedClientDataErr::InvalidObject)
}
}).and_then(|()| {
if origin == top_origin {
Err(CollectedClientDataErr::TopOriginSameAsOrigin)
} else {
Ok((true, Some(Origin(top_origin))))
}
})
})
} else {
Err(CollectedClientDataErr::TopOriginWithoutCrossOrigin)
}
} else {
Ok((cross, None))
}
})
} else {
Err(CollectedClientDataErr::InvalidObject)
}
}).map(|(cross_origin, top_origin)| CollectedClientData { challenge: SentChallenge(u128::from_le_bytes(chall)), origin: Origin(origin), cross_origin, top_origin, })
})
})
} else {
Err(CollectedClientDataErr::CrossOriginKey)
}
})
})
} else {
Err(CollectedClientDataErr::OriginKey)
}
})
})
})
} else {
Err(CollectedClientDataErr::ChallengeKey)
}
})
})
} else {
Err(CollectedClientDataErr::InvalidStart)
}
})
} else {
Err(CollectedClientDataErr::InvalidObject)
}
})
}
#[expect(
clippy::arithmetic_side_effects,
reason = "comment justifies correctness"
)]
#[expect(
clippy::little_endian_bytes,
reason = "Challenge::serialize and this need to be consistent across architectures"
)]
fn get_sent_challenge(json: &[u8]) -> Result<SentChallenge, Self::Err> {
let idx = if R { 39 } else { 36 };
json.get(idx..idx + Challenge::BASE64_LEN)
.ok_or(CollectedClientDataErr::Len)
.and_then(|chall_slice| {
let mut chall = [0; 16];
base64url_nopad::decode_buffer_exact(chall_slice, chall.as_mut_slice())
.map_err(|_e| CollectedClientDataErr::Challenge)
.map(|()| SentChallenge(u128::from_le_bytes(chall)))
})
}
}
pub(super) trait AuthExtOutput {
fn missing(self) -> bool;
}
struct CborSuccess<'a, T> {
value: T,
remaining: &'a [u8],
}
trait FromCbor<'a>: Sized {
type Err;
fn from_cbor(cbor: &'a [u8]) -> Result<CborSuccess<'a, Self>, Self::Err>;
}
enum AuthenticatorDataErr<UpErr, CredData, AuthExt> {
Len,
UserNotPresent(UpErr),
FlagsBit1Not0,
FlagsBit5Not0,
AttestedCredentialData,
BackupWithoutEligibility,
AttestedCredential(CredData),
AuthenticatorExtension(AuthExt),
NoExtensionBitWithData,
ExtensionBitWithoutData,
TrailingData,
}
impl<U, C: Display, A: Display> Display for AuthenticatorDataErr<U, C, A> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match *self {
Self::Len => f.write_str("authenticator data had an invalid length"),
Self::UserNotPresent(_) => f.write_str("user was not present"),
Self::FlagsBit1Not0 => f.write_str("flags 1-bit was 1"),
Self::FlagsBit5Not0 => f.write_str("flags 5-bit was 1"),
Self::AttestedCredentialData => f.write_str("attested credential data was included during authentication or was not included during registration"),
Self::BackupWithoutEligibility => {
f.write_str("backup state bit was 1 despite backup eligibility being 0")
}
Self::AttestedCredential(ref err) => err.fmt(f),
Self::AuthenticatorExtension(ref err) => err.fmt(f),
Self::NoExtensionBitWithData => {
f.write_str("extension bit was 0 despite extensions existing")
}
Self::ExtensionBitWithoutData => {
f.write_str("extension bit was 1 despite no extensions existing")
}
Self::TrailingData => {
f.write_str("slice had trailing data that could not be deserialized")
}
}
}
}
impl From<AuthenticatorDataErr<Infallible, AttestedCredentialDataErr, RegAuthExtErr>>
for RegAuthDataErr
{
#[inline]
fn from(
value: AuthenticatorDataErr<Infallible, AttestedCredentialDataErr, RegAuthExtErr>,
) -> Self {
match value {
AuthenticatorDataErr::Len => Self::Len,
AuthenticatorDataErr::UserNotPresent(v) => match v {},
AuthenticatorDataErr::FlagsBit1Not0 => Self::FlagsBit1Not0,
AuthenticatorDataErr::FlagsBit5Not0 => Self::FlagsBit5Not0,
AuthenticatorDataErr::AttestedCredentialData => Self::AttestedCredentialDataNotIncluded,
AuthenticatorDataErr::BackupWithoutEligibility => Self::BackupWithoutEligibility,
AuthenticatorDataErr::AttestedCredential(err) => Self::AttestedCredential(err),
AuthenticatorDataErr::AuthenticatorExtension(err) => Self::AuthenticatorExtension(err),
AuthenticatorDataErr::NoExtensionBitWithData => Self::NoExtensionBitWithData,
AuthenticatorDataErr::ExtensionBitWithoutData => Self::ExtensionBitWithoutData,
AuthenticatorDataErr::TrailingData => Self::TrailingData,
}
}
}
impl From<AuthenticatorDataErr<(), Infallible, AuthAuthExtErr>> for AuthAuthDataErr {
#[inline]
fn from(value: AuthenticatorDataErr<(), Infallible, AuthAuthExtErr>) -> Self {
match value {
AuthenticatorDataErr::Len => Self::Len,
AuthenticatorDataErr::UserNotPresent(()) => Self::UserNotPresent,
AuthenticatorDataErr::FlagsBit1Not0 => Self::FlagsBit1Not0,
AuthenticatorDataErr::FlagsBit5Not0 => Self::FlagsBit5Not0,
AuthenticatorDataErr::AttestedCredentialData => Self::AttestedCredentialDataIncluded,
AuthenticatorDataErr::AttestedCredential(val) => match val {},
AuthenticatorDataErr::BackupWithoutEligibility => Self::BackupWithoutEligibility,
AuthenticatorDataErr::AuthenticatorExtension(err) => Self::AuthenticatorExtension(err),
AuthenticatorDataErr::NoExtensionBitWithData => Self::NoExtensionBitWithData,
AuthenticatorDataErr::ExtensionBitWithoutData => Self::ExtensionBitWithoutData,
AuthenticatorDataErr::TrailingData => Self::TrailingData,
}
}
}
impl<'a, A> FromCbor<'a> for A
where
A: AuthData<'a>,
A::CredData: FromCbor<'a>,
A::Ext: FromCbor<'a>,
{
type Err = AuthenticatorDataErr<
A::UpBitErr,
<A::CredData as FromCbor<'a>>::Err,
<A::Ext as FromCbor<'a>>::Err,
>;
#[expect(clippy::big_endian_bytes, reason = "CBOR integers are in big-endian")]
fn from_cbor(cbor: &'a [u8]) -> Result<CborSuccess<'a, Self>, Self::Err> {
const SIGN_COUNT_LEN: usize = 4;
const UP: u8 = 0b0000_0001;
const RFU1: u8 = UP << 1;
const UV: u8 = RFU1 << 1;
const BE: u8 = UV << 1;
const BS: u8 = BE << 1;
const RFU2: u8 = BS << 1;
const AT: u8 = RFU2 << 1;
const ED: u8 = AT << 1;
cbor.split_at_checked(Sha256::output_size()).ok_or_else(|| AuthenticatorDataErr::Len).and_then(|(rp_id_slice, rp_id_rem)| {
rp_id_rem.split_first().ok_or_else(|| AuthenticatorDataErr::Len).and_then(|(&flag, flag_rem)| {
let user_present = flag & UP == UP;
if user_present {
Ok(())
} else {
A::user_is_not_present().map_err(AuthenticatorDataErr::UserNotPresent)
}
.and_then(|()| {
if flag & RFU1 == 0 {
if flag & RFU2 == 0 {
let at_bit = A::contains_at_bit();
if flag & AT == AT {
if at_bit {
Ok(())
} else {
Err(AuthenticatorDataErr::AttestedCredentialData)
}
} else if at_bit {
Err(AuthenticatorDataErr::AttestedCredentialData)
} else {
Ok(())
}.and_then(|()| {
let bs = flag & BS == BS;
if flag & BE == BE {
if bs {
Ok(Backup::Exists)
} else {
Ok(Backup::Eligible)
}
} else if bs {
Err(AuthenticatorDataErr::BackupWithoutEligibility)
} else {
Ok(Backup::NotEligible)
}
.and_then(|backup| {
flag_rem.split_at_checked(SIGN_COUNT_LEN).ok_or_else(|| AuthenticatorDataErr::Len).and_then(|(count_slice, count_rem)| {
A::CredData::from_cbor(count_rem).map_err(AuthenticatorDataErr::AttestedCredential).and_then(|att_data| {
A::Ext::from_cbor(att_data.remaining).map_err(AuthenticatorDataErr::AuthenticatorExtension).and_then(|ext| {
if ext.remaining.is_empty() {
let ed = flag & ED == ED;
if ext.value.missing() {
if ed {
Err(AuthenticatorDataErr::ExtensionBitWithoutData)
} else {
Ok(())
}
} else if ed {
Ok(())
} else {
Err(AuthenticatorDataErr::NoExtensionBitWithData)
}.map(|()| {
let mut sign_count = [0; SIGN_COUNT_LEN];
sign_count.copy_from_slice(count_slice);
CborSuccess { value: A::new(rp_id_slice, Flag { user_present, user_verified: flag & UV == UV, backup, }, u32::from_be_bytes(sign_count), att_data.value, ext.value), remaining: ext.remaining, }
})
} else {
Err(AuthenticatorDataErr::TrailingData)
}
})
})
})
})
})
} else {
Err(AuthenticatorDataErr::FlagsBit5Not0)
}
} else {
Err(AuthenticatorDataErr::FlagsBit1Not0)
}
})
})
})
}
}
pub(super) struct ParsedAuthData<'a, A> {
data: A,
auth_data_and_32_trailing_bytes: &'a [u8],
}
pub(super) enum AuthRespErr<AuthDataErr> {
CollectedClientData(CollectedClientDataErr),
#[cfg(feature = "serde_relaxed")]
CollectedClientDataRelaxed(SerdeJsonErr),
Auth(AuthDataErr),
PubKey(PubKeyErr),
Signature,
}
impl<A: Display> Display for AuthRespErr<A> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match *self {
Self::CollectedClientData(ref err) => write!(f, "CollectedClientData could not be parsed: {err}"),
#[cfg(feature = "serde_relaxed")]
Self::CollectedClientDataRelaxed(ref err) => write!(f, "CollectedClientData could not be parsed: {err}"),
Self::Auth(ref err) => write!(f, "auth data could not be parsed: {err}"),
Self::PubKey(err) => err.fmt(f),
Self::Signature => f.write_str("the signature over the authenticator data and CollectedClientData could not be verified"),
}
}
}
impl From<AuthRespErr<AttestationObjectErr>> for RegCeremonyErr {
#[inline]
fn from(value: AuthRespErr<AttestationObjectErr>) -> Self {
match value {
AuthRespErr::CollectedClientData(err) => Self::CollectedClientData(err),
#[cfg(feature = "serde_relaxed")]
AuthRespErr::CollectedClientDataRelaxed(err) => Self::CollectedClientDataRelaxed(err),
AuthRespErr::Auth(err) => Self::AttestationObject(err),
AuthRespErr::PubKey(err) => Self::PubKey(err),
AuthRespErr::Signature => Self::AttestationSignature,
}
}
}
impl From<AuthRespErr<AuthAuthDataErr>> for AuthCeremonyErr {
#[inline]
fn from(value: AuthRespErr<AuthAuthDataErr>) -> Self {
match value {
AuthRespErr::CollectedClientData(err) => Self::CollectedClientData(err),
#[cfg(feature = "serde_relaxed")]
AuthRespErr::CollectedClientDataRelaxed(err) => Self::CollectedClientDataRelaxed(err),
AuthRespErr::Auth(err) => Self::AuthenticatorData(err),
AuthRespErr::PubKey(err) => Self::PubKey(err),
AuthRespErr::Signature => Self::AssertionSignature,
}
}
}
pub(super) trait AuthDataContainer<'a>: Sized {
type Auth: AuthData<'a>;
type Err;
fn from_data(data: &'a [u8]) -> Result<ParsedAuthData<'a, Self>, Self::Err>;
fn authenticator_data(&self) -> &Self::Auth;
}
pub(super) trait AuthResponse {
type Auth<'a>: AuthDataContainer<'a>
where
Self: 'a;
type CredKey<'a>;
#[expect(
clippy::type_complexity,
reason = "type aliases with bounds are even more problematic at least until lazy_type_alias is stable"
)]
fn parse_data_and_verify_sig(
&self,
key: Self::CredKey<'_>,
relaxed: bool,
) -> Result<
(CollectedClientData<'_>, Self::Auth<'_>),
AuthRespErr<<Self::Auth<'_> as AuthDataContainer<'_>>::Err>,
>;
}
pub(super) trait Response {
type Auth: AuthResponse;
fn auth(&self) -> &Self::Auth;
}
pub(super) enum CeremonyErr<AuthDataErr> {
Timeout,
AuthResp(AuthRespErr<AuthDataErr>),
OriginMismatch,
CrossOrigin,
TopOriginMismatch,
ChallengeMismatch,
RpIdHashMismatch,
UserNotVerified,
BackupEligible,
BackupNotEligible,
BackupExists,
BackupDoesNotExist,
}
impl<A: Display> Display for CeremonyErr<A> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match *self {
Self::Timeout => f.write_str("ceremony timed out"),
Self::AuthResp(ref err) => err.fmt(f),
Self::OriginMismatch => {
f.write_str("the origin sent from the client is not an allowed origin")
}
Self::CrossOrigin => {
f.write_str("cross origin was from the client, but it is not allowed")
}
Self::TopOriginMismatch => {
f.write_str("the top origin sent from the client is not an allowed top origin")
}
Self::ChallengeMismatch => f.write_str(
"the challenge sent to the client does not match the challenge sent back",
),
Self::RpIdHashMismatch => f.write_str(
"the SHA-256 hash of the RP ID doesn't match the hash sent from the client",
),
Self::UserNotVerified => f.write_str("user was not verified despite being required to"),
Self::BackupEligible => f.write_str(
"credential is eligible to be backed up despite requiring that it not be",
),
Self::BackupNotEligible => f.write_str(
"credential is not eligible to be backed up despite requiring that it be",
),
Self::BackupExists => {
f.write_str("credential backup exists despite requiring that a backup not exist")
}
Self::BackupDoesNotExist => f.write_str(
"credential backup does not exist despite requiring that a backup exist",
),
}
}
}
impl From<CeremonyErr<AttestationObjectErr>> for RegCeremonyErr {
#[inline]
fn from(value: CeremonyErr<AttestationObjectErr>) -> Self {
match value {
CeremonyErr::Timeout => Self::Timeout,
CeremonyErr::AuthResp(err) => err.into(),
CeremonyErr::OriginMismatch => Self::OriginMismatch,
CeremonyErr::CrossOrigin => Self::CrossOrigin,
CeremonyErr::TopOriginMismatch => Self::TopOriginMismatch,
CeremonyErr::ChallengeMismatch => Self::ChallengeMismatch,
CeremonyErr::RpIdHashMismatch => Self::RpIdHashMismatch,
CeremonyErr::UserNotVerified => Self::UserNotVerified,
CeremonyErr::BackupEligible => Self::BackupEligible,
CeremonyErr::BackupNotEligible => Self::BackupNotEligible,
CeremonyErr::BackupExists => Self::BackupExists,
CeremonyErr::BackupDoesNotExist => Self::BackupDoesNotExist,
}
}
}
impl From<CeremonyErr<AuthAuthDataErr>> for AuthCeremonyErr {
#[inline]
fn from(value: CeremonyErr<AuthAuthDataErr>) -> Self {
match value {
CeremonyErr::Timeout => Self::Timeout,
CeremonyErr::AuthResp(err) => err.into(),
CeremonyErr::OriginMismatch => Self::OriginMismatch,
CeremonyErr::CrossOrigin => Self::CrossOrigin,
CeremonyErr::TopOriginMismatch => Self::TopOriginMismatch,
CeremonyErr::ChallengeMismatch => Self::ChallengeMismatch,
CeremonyErr::RpIdHashMismatch => Self::RpIdHashMismatch,
CeremonyErr::UserNotVerified => Self::UserNotVerified,
CeremonyErr::BackupEligible => Self::BackupEligible,
CeremonyErr::BackupNotEligible => Self::BackupNotEligible,
CeremonyErr::BackupExists => Self::BackupExists,
CeremonyErr::BackupDoesNotExist => Self::BackupDoesNotExist,
}
}
}
#[derive(Debug)]
pub struct AllAcceptedCredentialsOptions<'rp, 'user, const USER_LEN: usize> {
pub rp_id: &'rp RpId,
pub user_id: &'user UserHandle<USER_LEN>,
pub all_accepted_credential_ids: Vec<CredentialId<Box<[u8]>>>,
}
#[derive(Debug)]
pub struct CurrentUserDetailsOptions<'rp_id, 'name, 'display_name, 'id, const LEN: usize> {
pub rp_id: &'rp_id RpId,
pub user: PublicKeyCredentialUserEntity<'name, 'display_name, 'id, LEN>,
}
enum HmacSecretGet<const REG: bool> {
None,
One,
Two,
}
enum HmacSecretGetErr {
Len,
Type,
Value,
}
impl<const REG: bool> FromCbor<'_> for HmacSecretGet<REG> {
type Err = HmacSecretGetErr;
fn from_cbor(cbor: &[u8]) -> Result<CborSuccess<'_, Self>, Self::Err> {
const AES_BLOCK_SIZE: usize = 16;
const HMAC_SHA_256_LEN: usize = 32;
const TWO_HMAC_SHA_256_LEN: usize = HMAC_SHA_256_LEN << 1;
#[expect(
clippy::integer_division_remainder_used,
reason = "doesn't need to be constant time"
)]
const ONE_SECRET_LEN: usize =
HMAC_SHA_256_LEN + (AES_BLOCK_SIZE - (HMAC_SHA_256_LEN % AES_BLOCK_SIZE));
#[expect(
clippy::integer_division_remainder_used,
reason = "doesn't need to be constant time"
)]
const TWO_SECRET_LEN: usize =
TWO_HMAC_SHA_256_LEN + (AES_BLOCK_SIZE - (TWO_HMAC_SHA_256_LEN % AES_BLOCK_SIZE));
const KEY: [u8; 15] = [
cbor::TEXT_14,
b'h',
b'm',
b'a',
b'c',
b'-',
b's',
b'e',
b'c',
b'r',
b'e',
b't',
b'-',
b'm',
b'c',
];
enum CborVal<'a> {
Success,
Continue(&'a [u8]),
}
if REG {
cbor.split_at_checked(KEY.len())
.map_or(Ok(CborVal::Success), |(key, key_rem)| {
if key == KEY {
Ok(CborVal::Continue(key_rem))
} else {
Ok(CborVal::Success)
}
})
} else {
cbor.split_at_checked(cbor::HMAC_SECRET.len()).map_or(
Ok(CborVal::Success),
|(key, key_rem)| {
if key == cbor::HMAC_SECRET {
Ok(CborVal::Continue(key_rem))
} else {
Ok(CborVal::Success)
}
},
)
}
.and_then(|cbor_val| match cbor_val {
CborVal::Success => Ok(CborSuccess {
value: Self::None,
remaining: cbor,
}),
CborVal::Continue(key_rem) => key_rem
.split_first()
.ok_or(HmacSecretGetErr::Len)
.and_then(|(bytes, bytes_rem)| {
if *bytes == cbor::BYTES_INFO_24 {
bytes_rem
.split_first()
.ok_or(HmacSecretGetErr::Len)
.and_then(|(&len, len_rem)| {
len_rem
.split_at_checked(usize::from(len))
.ok_or(HmacSecretGetErr::Len)
.and_then(|(_, remaining)| match usize::from(len) {
ONE_SECRET_LEN => Ok(CborSuccess {
value: Self::One,
remaining,
}),
TWO_SECRET_LEN => Ok(CborSuccess {
value: Self::Two,
remaining,
}),
_ => Err(HmacSecretGetErr::Value),
})
})
} else {
Err(HmacSecretGetErr::Type)
}
}),
})
}
}