#[cfg(test)]
mod tests;
use super::{
super::{
DynamicState, Metadata, RegisteredCredential, StaticState,
response::{
AuthenticatorAttachment,
register::{
Attestation, AttestationFormat, AuthenticatorExtensionOutput,
ClientExtensionsOutputs, CredentialProtectionPolicy, HmacSecret, Registration,
UncompressedPubKey,
error::{ExtensionErr, RegCeremonyErr},
},
},
},
Ceremony, Challenge, CredentialMediationRequirement, ExtensionInfo, ExtensionReq, FIVE_MINUTES,
Hints, Origin, PrfInput, PublicKeyCredentialDescriptor, RpId, SentChallenge, TimedCeremony,
UserVerificationRequirement,
register::error::CreationOptionsErr,
};
#[cfg(doc)]
use crate::{
request::{
AsciiDomain, AsciiDomainStatic, DomainOrigin, Url,
auth::{AuthenticationVerificationOptions, PublicKeyCredentialRequestOptions},
},
response::{AuthTransports, AuthenticatorTransport, Backup, CollectedClientData, Flag},
};
use core::{
borrow::Borrow,
cmp::Ordering,
fmt::{self, Display, Formatter},
hash::{Hash, Hasher},
mem,
num::{NonZeroU32, NonZeroU64},
time::Duration,
};
#[cfg(any(doc, not(feature = "serializable_server_state")))]
use std::time::Instant;
#[cfg(any(doc, feature = "serializable_server_state"))]
use std::time::SystemTime;
#[cfg(feature = "bin")]
pub mod bin;
#[cfg(feature = "custom")]
mod custom;
pub mod error;
#[cfg(feature = "serde")]
pub mod ser;
#[cfg(feature = "serializable_server_state")]
pub mod ser_server_state;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum BackupReq {
#[default]
None,
NotEligible,
Eligible,
EligibleNotExists,
Exists,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum CredProtect {
#[default]
None,
UserVerificationOptional(bool, ExtensionInfo),
UserVerificationOptionalWithCredentialIdList(bool, ExtensionInfo),
UserVerificationRequired(bool, ExtensionInfo),
}
impl CredProtect {
const fn validate(self, other: CredentialProtectionPolicy) -> Result<(), ExtensionErr> {
match self {
Self::None => Ok(()),
Self::UserVerificationOptional(_, info) => {
if matches!(other, CredentialProtectionPolicy::None) {
if matches!(
info,
ExtensionInfo::RequireEnforceValue | ExtensionInfo::RequireDontEnforceValue
) {
Err(ExtensionErr::MissingCredProtect)
} else {
Ok(())
}
} else {
Ok(())
}
}
Self::UserVerificationOptionalWithCredentialIdList(_, info) => match info {
ExtensionInfo::RequireEnforceValue => match other {
CredentialProtectionPolicy::None => Err(ExtensionErr::MissingCredProtect),
CredentialProtectionPolicy::UserVerificationOptional => {
Err(ExtensionErr::InvalidCredProtectValue(self, other))
}
CredentialProtectionPolicy::UserVerificationOptionalWithCredentialIdList
| CredentialProtectionPolicy::UserVerificationRequired => Ok(()),
},
ExtensionInfo::RequireDontEnforceValue => {
if matches!(other, CredentialProtectionPolicy::None) {
Err(ExtensionErr::MissingCredProtect)
} else {
Ok(())
}
}
ExtensionInfo::AllowEnforceValue => {
if matches!(other, CredentialProtectionPolicy::UserVerificationOptional) {
Err(ExtensionErr::InvalidCredProtectValue(self, other))
} else {
Ok(())
}
}
ExtensionInfo::AllowDontEnforceValue => Ok(()),
},
Self::UserVerificationRequired(_, info) => match info {
ExtensionInfo::RequireEnforceValue => match other {
CredentialProtectionPolicy::None => Err(ExtensionErr::MissingCredProtect),
CredentialProtectionPolicy::UserVerificationOptional
| CredentialProtectionPolicy::UserVerificationOptionalWithCredentialIdList => {
Err(ExtensionErr::InvalidCredProtectValue(self, other))
}
CredentialProtectionPolicy::UserVerificationRequired => Ok(()),
},
ExtensionInfo::RequireDontEnforceValue => {
if matches!(other, CredentialProtectionPolicy::None) {
Err(ExtensionErr::MissingCredProtect)
} else {
Ok(())
}
}
ExtensionInfo::AllowEnforceValue => {
if matches!(
other,
CredentialProtectionPolicy::None
| CredentialProtectionPolicy::UserVerificationRequired
) {
Ok(())
} else {
Err(ExtensionErr::InvalidCredProtectValue(self, other))
}
}
ExtensionInfo::AllowDontEnforceValue => Ok(()),
},
}
}
}
impl Display for CredProtect {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match *self {
Self::None => f.write_str("do not sent a credProtect request"),
Self::UserVerificationOptional(enforce, info) => {
write!(
f,
"request user verification optional with enforcement {enforce} and {info}"
)
}
Self::UserVerificationOptionalWithCredentialIdList(enforce, info) => write!(
f,
"user verification optional with credential ID list with enforcement {enforce} and {info}"
),
Self::UserVerificationRequired(enforce, info) => {
write!(
f,
"user verification required with enforcement {enforce} and {info}"
)
}
}
}
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum CoseAlgorithmIdentifier {
Mldsa87,
Mldsa65,
Mldsa44,
Eddsa,
Es256,
Es384,
Rs256,
}
impl CoseAlgorithmIdentifier {
const fn to_u8(self) -> u8 {
match self {
Self::Mldsa87 => 0x1,
Self::Mldsa65 => 0x2,
Self::Mldsa44 => 0x4,
Self::Eddsa => 0x8,
Self::Es256 => 0x10,
Self::Es384 => 0x20,
Self::Rs256 => 0x40,
}
}
}
impl PartialEq<&Self> for CoseAlgorithmIdentifier {
#[inline]
fn eq(&self, other: &&Self) -> bool {
*self == **other
}
}
impl PartialEq<CoseAlgorithmIdentifier> for &CoseAlgorithmIdentifier {
#[inline]
fn eq(&self, other: &CoseAlgorithmIdentifier) -> bool {
**self == *other
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CoseAlgorithmIdentifiers(u8);
impl CoseAlgorithmIdentifiers {
pub const ALL: Self = Self(0)
.add(CoseAlgorithmIdentifier::Mldsa87)
.add(CoseAlgorithmIdentifier::Mldsa65)
.add(CoseAlgorithmIdentifier::Mldsa44)
.add(CoseAlgorithmIdentifier::Eddsa)
.add(CoseAlgorithmIdentifier::Es256)
.add(CoseAlgorithmIdentifier::Es384)
.add(CoseAlgorithmIdentifier::Rs256);
const fn add(self, alg: CoseAlgorithmIdentifier) -> Self {
Self(self.0 | alg.to_u8())
}
#[inline]
#[must_use]
pub const fn remove(self, alg: CoseAlgorithmIdentifier) -> Self {
let val = alg.to_u8();
if self.0 == val {
self
} else {
Self(self.0 & !val)
}
}
#[inline]
#[must_use]
pub const fn contains(self, alg: CoseAlgorithmIdentifier) -> bool {
let val = alg.to_u8();
self.0 & val == val
}
const fn validate(self, other: UncompressedPubKey<'_>) -> Result<(), RegCeremonyErr> {
if match other {
UncompressedPubKey::MlDsa87(_) => self.contains(CoseAlgorithmIdentifier::Mldsa87),
UncompressedPubKey::MlDsa65(_) => self.contains(CoseAlgorithmIdentifier::Mldsa65),
UncompressedPubKey::MlDsa44(_) => self.contains(CoseAlgorithmIdentifier::Mldsa44),
UncompressedPubKey::Ed25519(_) => self.contains(CoseAlgorithmIdentifier::Eddsa),
UncompressedPubKey::P256(_) => self.contains(CoseAlgorithmIdentifier::Es256),
UncompressedPubKey::P384(_) => self.contains(CoseAlgorithmIdentifier::Es384),
UncompressedPubKey::Rsa(_) => self.contains(CoseAlgorithmIdentifier::Rs256),
} {
Ok(())
} else {
Err(RegCeremonyErr::PublicKeyAlgorithmMismatch)
}
}
}
impl Default for CoseAlgorithmIdentifiers {
#[inline]
fn default() -> Self {
Self::ALL
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(u8)]
pub enum FourToSixtyThree {
Four = 4,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Eleven,
Twelve,
Thirteen,
Fourteen,
Fifteen,
Sixteen,
Seventeen,
Eighteen,
Nineteen,
Twenty,
TwentyOne,
TwentyTwo,
TwentyThree,
TwentyFour,
TwentyFive,
TwentySix,
TwentySeven,
TwentyEight,
TwentyNine,
Thirty,
ThirtyOne,
ThirtyTwo,
ThirtyThree,
ThirtyFour,
ThirtyFive,
ThirtySix,
ThirtySeven,
ThirtyEight,
ThirtyNine,
Fourty,
FourtyOne,
FourtyTwo,
FourtyThree,
FourtyFour,
FourtyFive,
FourtySix,
FourtySeven,
FourtyEight,
FourtyNine,
Fifty,
FiftyOne,
FiftyTwo,
FiftyThree,
FiftyFour,
FiftyFive,
FiftySix,
FiftySeven,
FiftyEight,
FiftyNine,
Sixty,
SixtyOne,
SixtyTwo,
SixtyThree,
}
impl FourToSixtyThree {
#[expect(clippy::as_conversions, reason = "comment justifies correctness")]
#[inline]
#[must_use]
pub const fn into_u8(self) -> u8 {
self as u8
}
#[expect(unsafe_code, reason = "comment justifies correctness")]
#[inline]
#[must_use]
pub const fn from_u8(val: u8) -> Option<Self> {
match val {
4..=63 => {
Some(unsafe { mem::transmute::<u8, Self>(val) })
}
_ => None,
}
}
}
impl Display for FourToSixtyThree {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.into_u8().fmt(f)
}
}
impl From<FourToSixtyThree> for u8 {
#[inline]
fn from(value: FourToSixtyThree) -> Self {
value.into_u8()
}
}
impl Default for FourToSixtyThree {
#[inline]
fn default() -> Self {
Self::Four
}
}
#[derive(Clone, Copy, Debug)]
pub struct Extension<'prf_first, 'prf_second> {
pub cred_props: Option<ExtensionReq>,
pub cred_protect: CredProtect,
pub min_pin_length: Option<(FourToSixtyThree, ExtensionInfo)>,
pub prf: Option<(PrfInput<'prf_first, 'prf_second>, ExtensionInfo)>,
}
impl<'prf_first, 'prf_second> Extension<'prf_first, 'prf_second> {
#[inline]
#[must_use]
pub const fn none() -> Self {
Self {
cred_props: None,
cred_protect: CredProtect::None,
min_pin_length: None,
prf: None,
}
}
#[inline]
#[must_use]
pub const fn with_cred_props(req: ExtensionReq) -> Self {
Self {
cred_props: Some(req),
..Self::none()
}
}
#[inline]
#[must_use]
pub const fn with_cred_protect(cred_protect: CredProtect) -> Self {
Self {
cred_protect,
..Self::none()
}
}
#[inline]
#[must_use]
pub const fn with_min_pin_length(min_len: FourToSixtyThree, info: ExtensionInfo) -> Self {
Self {
min_pin_length: Some((min_len, info)),
..Self::none()
}
}
#[inline]
#[must_use]
pub const fn with_prf<'a: 'prf_first, 'b: 'prf_second>(
input: PrfInput<'a, 'b>,
info: ExtensionInfo,
) -> Self {
Self {
prf: Some((input, info)),
..Self::none()
}
}
}
impl Default for Extension<'_, '_> {
#[inline]
fn default() -> Self {
Self::none()
}
}
#[cfg(test)]
impl PartialEq for Extension<'_, '_> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.cred_props == other.cred_props
&& self.cred_protect == other.cred_protect
&& self.min_pin_length == other.min_pin_length
&& self.prf == other.prf
}
}
pub const USER_HANDLE_MAX_LEN: usize = 64;
pub const USER_HANDLE_MIN_LEN: usize = 1;
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct UserHandle<const LEN: usize>([u8; LEN]);
impl<const LEN: usize> UserHandle<LEN> {
#[inline]
#[must_use]
pub const fn as_slice(&self) -> &[u8] {
self.0.as_slice()
}
#[inline]
#[must_use]
pub const fn as_array(&self) -> &[u8; LEN] {
&self.0
}
#[inline]
#[must_use]
pub const fn into_array(self) -> [u8; LEN] {
self.0
}
}
macro_rules! user {
( $( $x:literal),* ) => {
$(
impl Default for UserHandle<$x> {
#[inline]
fn default() -> Self {
let mut data = [0; $x];
rand::fill(data.as_mut_slice());
Self(data)
}
}
)*
};
}
user!(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64
);
impl<const LEN: usize> UserHandle<LEN>
where
Self: Default,
{
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
impl<const LEN: usize> AsRef<[u8]> for UserHandle<LEN> {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_slice()
}
}
impl<const LEN: usize> Borrow<[u8]> for UserHandle<LEN> {
#[inline]
fn borrow(&self) -> &[u8] {
self.as_slice()
}
}
impl<const LEN: usize> PartialEq<&Self> for UserHandle<LEN> {
#[inline]
fn eq(&self, other: &&Self) -> bool {
*self == **other
}
}
impl<const LEN: usize> PartialEq<UserHandle<LEN>> for &UserHandle<LEN> {
#[inline]
fn eq(&self, other: &UserHandle<LEN>) -> bool {
**self == *other
}
}
impl<const LEN: usize> From<UserHandle<LEN>> for [u8; LEN] {
#[inline]
fn from(value: UserHandle<LEN>) -> Self {
value.into_array()
}
}
impl<'a: 'b, 'b, const LEN: usize> From<&'a UserHandle<LEN>> for &'b [u8; LEN] {
#[inline]
fn from(value: &'a UserHandle<LEN>) -> Self {
value.as_array()
}
}
pub type UserHandle64 = UserHandle<USER_HANDLE_MAX_LEN>;
pub type UserHandle16 = UserHandle<16>;
impl UserHandle16 {
#[inline]
#[must_use]
pub fn new_uuid_v4() -> Self {
let mut this = Self::new();
this.0[6] = (this.0[6] & 0x0F) | 0x40;
this.0[8] = (this.0[8] & 0x3F) | 0x80;
this
}
#[inline]
#[must_use]
pub const fn is_uuid_v4(&self) -> bool {
self.0[6] >> 4 == 0x4 && self.0[8] >> 6 == 0x2
}
#[cfg(feature = "custom")]
#[inline]
#[must_use]
pub fn from_uuid_v4(uuid_v4: [u8; 16]) -> Option<Self> {
let this = Self(uuid_v4);
this.is_uuid_v4().then_some(this)
}
}
#[derive(Clone, Debug)]
pub struct PublicKeyCredentialUserEntity<'name, 'display_name, 'id, const LEN: usize> {
pub name: &'name str,
pub id: &'id UserHandle<LEN>,
pub display_name: &'display_name str,
}
pub type PublicKeyCredentialUserEntity64<'name, 'display_name, 'id> =
PublicKeyCredentialUserEntity<'name, 'display_name, 'id, USER_HANDLE_MAX_LEN>;
pub type PublicKeyCredentialUserEntity16<'name, 'display_name, 'id> =
PublicKeyCredentialUserEntity<'name, 'display_name, 'id, 16>;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ResidentKeyRequirement {
Required,
Discouraged,
Preferred,
}
impl AuthenticatorAttachment {
const fn validate(self, require_response: bool, other: Self) -> Result<(), RegCeremonyErr> {
match self {
Self::None => {
if require_response && matches!(other, Self::None) {
Err(RegCeremonyErr::MissingAuthenticatorAttachment)
} else {
Ok(())
}
}
Self::Platform => match other {
Self::None => {
if require_response {
Err(RegCeremonyErr::MissingAuthenticatorAttachment)
} else {
Ok(())
}
}
Self::Platform => Ok(()),
Self::CrossPlatform => Err(RegCeremonyErr::AuthenticatorAttachmentMismatch),
},
Self::CrossPlatform => match other {
Self::None => {
if require_response {
Err(RegCeremonyErr::MissingAuthenticatorAttachment)
} else {
Ok(())
}
}
Self::CrossPlatform => Ok(()),
Self::Platform => Err(RegCeremonyErr::AuthenticatorAttachmentMismatch),
},
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AuthenticatorSelectionCriteria {
pub authenticator_attachment: AuthenticatorAttachment,
pub resident_key: ResidentKeyRequirement,
pub user_verification: UserVerificationRequirement,
}
impl AuthenticatorSelectionCriteria {
#[inline]
#[must_use]
pub fn passkey() -> Self {
Self {
authenticator_attachment: AuthenticatorAttachment::default(),
resident_key: ResidentKeyRequirement::Required,
user_verification: UserVerificationRequirement::Required,
}
}
#[inline]
#[must_use]
pub fn second_factor() -> Self {
Self {
authenticator_attachment: AuthenticatorAttachment::default(),
resident_key: ResidentKeyRequirement::Discouraged,
user_verification: UserVerificationRequirement::Discouraged,
}
}
const fn validate(
self,
require_auth_attachment: bool,
auth_attachment: AuthenticatorAttachment,
) -> Result<(), RegCeremonyErr> {
self.authenticator_attachment
.validate(require_auth_attachment, auth_attachment)
}
}
const fn validate_options_helper(
auth_crit: AuthenticatorSelectionCriteria,
extensions: ServerExtensionInfo,
) -> Result<(), CreationOptionsErr> {
if matches!(
auth_crit.user_verification,
UserVerificationRequirement::Required
) {
Ok(())
} else if !matches!(extensions.prf, ServerPrfInfo::None) {
Err(CreationOptionsErr::PrfWithoutUserVerification)
} else if matches!(
extensions.cred_protect,
CredProtect::UserVerificationRequired(_, _)
) {
Err(CreationOptionsErr::CredProtectRequiredWithoutUserVerification)
} else {
Ok(())
}
}
#[derive(Debug)]
pub struct CredentialCreationOptions<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
const USER_LEN: usize,
> {
pub mediation: CredentialMediationRequirement,
pub public_key: PublicKeyCredentialCreationOptions<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
USER_LEN,
>,
}
impl<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
const USER_LEN: usize,
>
CredentialCreationOptions<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
USER_LEN,
>
{
#[inline]
#[must_use]
pub fn passkey<'a: 'rp_id, 'b: 'user_name, 'c: 'user_display_name, 'd: 'user_id>(
rp_id: &'a RpId,
user: PublicKeyCredentialUserEntity<'b, 'c, 'd, USER_LEN>,
exclude_credentials: Vec<PublicKeyCredentialDescriptor<Box<[u8]>>>,
) -> Self {
Self {
mediation: CredentialMediationRequirement::default(),
public_key: PublicKeyCredentialCreationOptions::passkey(
rp_id,
user,
exclude_credentials,
),
}
}
#[inline]
#[must_use]
pub fn second_factor<'a: 'rp_id, 'b: 'user_name, 'c: 'user_display_name, 'd: 'user_id>(
rp_id: &'a RpId,
user: PublicKeyCredentialUserEntity<'b, 'c, 'd, USER_LEN>,
exclude_credentials: Vec<PublicKeyCredentialDescriptor<Box<[u8]>>>,
) -> Self {
let mut opts = Self::passkey(rp_id, user, exclude_credentials);
opts.public_key.authenticator_selection = AuthenticatorSelectionCriteria::second_factor();
opts.public_key.extensions.cred_props = Some(ExtensionReq::Allow);
opts.public_key.extensions.cred_protect =
CredProtect::UserVerificationOptionalWithCredentialIdList(
false,
ExtensionInfo::AllowEnforceValue,
);
opts
}
#[inline]
pub fn start_ceremony(
mut self,
) -> Result<
(
RegistrationServerState<USER_LEN>,
RegistrationClientState<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
USER_LEN,
>,
),
CreationOptionsErr,
> {
let extensions = self.public_key.extensions.into();
validate_options_helper(self.public_key.authenticator_selection, extensions).and_then(
|()| {
match self
.public_key
.authenticator_selection
.authenticator_attachment
{
AuthenticatorAttachment::None => Ok(()),
AuthenticatorAttachment::Platform => {
if self.public_key.hints.contains_cross_platform_hints() {
Err(CreationOptionsErr::HintsIncompatibleWithAuthAttachment)
} else {
Ok(())
}
}
AuthenticatorAttachment::CrossPlatform => {
if self.public_key.hints.contains_platform_hints() {
Err(CreationOptionsErr::HintsIncompatibleWithAuthAttachment)
} else {
Ok(())
}
}
}
.and_then(|()| {
#[cfg(not(feature = "serializable_server_state"))]
let now = Instant::now();
#[cfg(feature = "serializable_server_state")]
let now = SystemTime::now();
now.checked_add(Duration::from_millis(
NonZeroU64::from(self.public_key.timeout).get(),
))
.ok_or(CreationOptionsErr::InvalidTimeout)
.map(|expiration| {
self.public_key
.exclude_credentials
.sort_unstable_by(|a, b| a.id.as_ref().cmp(b.id.as_ref()));
self.public_key
.exclude_credentials
.dedup_by(|a, b| a.id.as_ref() == b.id.as_ref());
(
RegistrationServerState {
mediation: self.mediation,
challenge: SentChallenge(self.public_key.challenge.0),
pub_key_cred_params: self.public_key.pub_key_cred_params,
authenticator_selection: self.public_key.authenticator_selection,
extensions,
expiration,
user_id: *self.public_key.user.id,
},
RegistrationClientState(self),
)
})
})
},
)
}
}
pub type CredentialCreationOptions64<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
> = CredentialCreationOptions<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
USER_HANDLE_MAX_LEN,
>;
pub type CredentialCreationOptions16<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
> = CredentialCreationOptions<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
16,
>;
#[derive(Debug)]
pub struct PublicKeyCredentialCreationOptions<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
const USER_LEN: usize,
> {
pub rp_id: &'rp_id RpId,
pub user: PublicKeyCredentialUserEntity<'user_name, 'user_display_name, 'user_id, USER_LEN>,
pub challenge: Challenge,
pub pub_key_cred_params: CoseAlgorithmIdentifiers,
pub timeout: NonZeroU32,
pub exclude_credentials: Vec<PublicKeyCredentialDescriptor<Box<[u8]>>>,
pub authenticator_selection: AuthenticatorSelectionCriteria,
pub hints: Hints,
pub extensions: Extension<'prf_first, 'prf_second>,
}
impl<'rp_id, 'user_name, 'user_display_name, 'user_id, const USER_LEN: usize>
PublicKeyCredentialCreationOptions<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'_,
'_,
USER_LEN,
>
{
#[inline]
#[must_use]
pub fn passkey<'a: 'rp_id, 'b: 'user_name, 'c: 'user_display_name, 'd: 'user_id>(
rp_id: &'a RpId,
user: PublicKeyCredentialUserEntity<'b, 'c, 'd, USER_LEN>,
exclude_credentials: Vec<PublicKeyCredentialDescriptor<Box<[u8]>>>,
) -> Self {
Self {
rp_id,
user,
challenge: Challenge::new(),
pub_key_cred_params: CoseAlgorithmIdentifiers::default(),
timeout: FIVE_MINUTES,
exclude_credentials,
authenticator_selection: AuthenticatorSelectionCriteria::passkey(),
hints: Hints::EMPTY,
extensions: Extension {
cred_props: None,
cred_protect: CredProtect::UserVerificationRequired(
false,
ExtensionInfo::AllowEnforceValue,
),
min_pin_length: None,
prf: None,
},
}
}
#[inline]
#[must_use]
pub fn second_factor<'a: 'rp_id, 'b: 'user_name, 'c: 'user_display_name, 'd: 'user_id>(
rp_id: &'a RpId,
user: PublicKeyCredentialUserEntity<'b, 'c, 'd, USER_LEN>,
exclude_credentials: Vec<PublicKeyCredentialDescriptor<Box<[u8]>>>,
) -> Self {
let mut opts = Self::passkey(rp_id, user, exclude_credentials);
opts.authenticator_selection = AuthenticatorSelectionCriteria::second_factor();
opts.extensions.cred_props = Some(ExtensionReq::Allow);
opts.extensions.cred_protect = CredProtect::UserVerificationOptionalWithCredentialIdList(
false,
ExtensionInfo::AllowEnforceValue,
);
opts
}
}
pub type PublicKeyCredentialCreationOptions64<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
> = PublicKeyCredentialCreationOptions<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
USER_HANDLE_MAX_LEN,
>;
pub type PublicKeyCredentialCreationOptions16<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
> = PublicKeyCredentialCreationOptions<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
16,
>;
#[derive(Debug)]
pub struct RegistrationClientState<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
const USER_LEN: usize,
>(
CredentialCreationOptions<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
USER_LEN,
>,
);
impl<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
const USER_LEN: usize,
>
RegistrationClientState<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
USER_LEN,
>
{
#[inline]
#[must_use]
pub const fn options(
&self,
) -> &CredentialCreationOptions<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
USER_LEN,
> {
&self.0
}
}
pub type RegistrationClientState64<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
> = RegistrationClientState<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
USER_HANDLE_MAX_LEN,
>;
pub type RegistrationClientState16<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
> = RegistrationClientState<
'rp_id,
'user_name,
'user_display_name,
'user_id,
'prf_first,
'prf_second,
16,
>;
#[derive(Clone, Copy, Debug)]
pub struct RegistrationVerificationOptions<'origins, 'top_origins, O, T> {
pub allowed_origins: &'origins [O],
pub allowed_top_origins: Option<&'top_origins [T]>,
pub backup_requirement: BackupReq,
pub error_on_unsolicited_extensions: bool,
pub require_authenticator_attachment: bool,
#[cfg(feature = "serde_relaxed")]
pub client_data_json_relaxed: bool,
}
impl<O, T> RegistrationVerificationOptions<'_, '_, O, T> {
#[inline]
#[must_use]
pub const fn new() -> Self {
Self {
allowed_origins: [].as_slice(),
allowed_top_origins: None,
backup_requirement: BackupReq::None,
error_on_unsolicited_extensions: true,
require_authenticator_attachment: false,
#[cfg(feature = "serde_relaxed")]
client_data_json_relaxed: true,
}
}
}
impl<O, T> Default for RegistrationVerificationOptions<'_, '_, O, T> {
#[inline]
fn default() -> Self {
Self {
allowed_origins: &[],
allowed_top_origins: None,
backup_requirement: BackupReq::default(),
error_on_unsolicited_extensions: true,
require_authenticator_attachment: false,
#[cfg(feature = "serde_relaxed")]
client_data_json_relaxed: true,
}
}
}
#[derive(Clone, Copy, Debug)]
enum ServerPrfInfo {
None,
One(ExtensionInfo),
Two(ExtensionInfo),
}
#[cfg(test)]
impl PartialEq for ServerPrfInfo {
fn eq(&self, other: &Self) -> bool {
match *self {
Self::None => matches!(*other, Self::None),
Self::One(info) => matches!(*other, Self::One(info2) if info == info2),
Self::Two(info) => matches!(*other, Self::Two(info2) if info == info2),
}
}
}
impl From<Option<(PrfInput<'_, '_>, ExtensionInfo)>> for ServerPrfInfo {
fn from(value: Option<(PrfInput<'_, '_>, ExtensionInfo)>) -> Self {
value.map_or(Self::None, |val| {
val.0
.second
.map_or_else(|| Self::One(val.1), |_| Self::Two(val.1))
})
}
}
#[derive(Clone, Copy, Debug)]
struct ServerExtensionInfo {
cred_props: Option<ExtensionReq>,
cred_protect: CredProtect,
min_pin_length: Option<(FourToSixtyThree, ExtensionInfo)>,
prf: ServerPrfInfo,
}
impl ServerExtensionInfo {
fn validate(
self,
client_ext: ClientExtensionsOutputs,
auth_ext: AuthenticatorExtensionOutput,
error_unsolicited: bool,
) -> Result<(), ExtensionErr> {
if error_unsolicited {
self.validate_unsolicited(client_ext, auth_ext)
} else {
Ok(())
}
.and_then(|()| {
self.validate_required(client_ext, auth_ext)
.and_then(|()| self.validate_value(client_ext, auth_ext))
})
}
fn validate_unsolicited(
mut self,
client_ext: ClientExtensionsOutputs,
auth_ext: AuthenticatorExtensionOutput,
) -> Result<(), ExtensionErr> {
if self.cred_props.is_some() {
if !matches!(self.cred_protect, CredProtect::None) {
if self.min_pin_length.is_some() {
if !matches!(self.prf, ServerPrfInfo::None) {
Ok(())
} else if client_ext.prf.is_some() {
Err(ExtensionErr::ForbiddenPrf)
} else if !matches!(auth_ext.hmac_secret, HmacSecret::None) {
Err(ExtensionErr::ForbiddenHmacSecret)
} else {
Ok(())
}
} else if auth_ext.min_pin_length.is_some() {
Err(ExtensionErr::ForbiddenMinPinLength)
} else {
self.min_pin_length =
Some((FourToSixtyThree::Four, ExtensionInfo::RequireEnforceValue));
self.validate_unsolicited(client_ext, auth_ext)
}
} else if !matches!(auth_ext.cred_protect, CredentialProtectionPolicy::None) {
Err(ExtensionErr::ForbiddenCredProtect)
} else {
self.cred_protect = CredProtect::UserVerificationOptional(
false,
ExtensionInfo::RequireEnforceValue,
);
self.validate_unsolicited(client_ext, auth_ext)
}
} else if client_ext.cred_props.is_some() {
Err(ExtensionErr::ForbiddenCredProps)
} else {
self.cred_props = Some(ExtensionReq::Require);
self.validate_unsolicited(client_ext, auth_ext)
}
}
fn validate_required(
self,
client_ext: ClientExtensionsOutputs,
auth_ext: AuthenticatorExtensionOutput,
) -> Result<(), ExtensionErr> {
self.cred_props
.map_or(Ok(()), |info| {
if matches!(info, ExtensionReq::Require) {
if client_ext
.cred_props
.is_some_and(|props| props.rk.is_some())
{
Ok(())
} else {
Err(ExtensionErr::MissingCredProps)
}
} else {
Ok(())
}
})
.and_then(|()| {
self.min_pin_length
.map_or(Ok(()), |info| {
if matches!(
info.1,
ExtensionInfo::RequireEnforceValue
| ExtensionInfo::RequireDontEnforceValue
) {
auth_ext
.min_pin_length
.ok_or(ExtensionErr::MissingMinPinLength)
.map(|_| ())
} else {
Ok(())
}
})
.and_then(|()| match self.prf {
ServerPrfInfo::None => Ok(()),
ServerPrfInfo::One(info) | ServerPrfInfo::Two(info) => {
if matches!(
info,
ExtensionInfo::RequireEnforceValue
| ExtensionInfo::RequireDontEnforceValue
) {
if client_ext.prf.is_some() {
Ok(())
} else {
Err(ExtensionErr::MissingPrf)
}
} else {
Ok(())
}
}
})
})
}
fn validate_value(
self,
client_ext: ClientExtensionsOutputs,
auth_ext: AuthenticatorExtensionOutput,
) -> Result<(), ExtensionErr> {
self.cred_protect
.validate(auth_ext.cred_protect)
.and_then(|()| {
self.min_pin_length
.map_or(Ok(()), |info| {
if matches!(
info.1,
ExtensionInfo::RequireEnforceValue | ExtensionInfo::AllowEnforceValue
) {
auth_ext.min_pin_length.map_or(Ok(()), |pin| {
if pin >= info.0 {
Ok(())
} else {
Err(ExtensionErr::InvalidMinPinLength(info.0, pin))
}
})
} else {
Ok(())
}
})
.and_then(|()| match self.prf {
ServerPrfInfo::None => Ok(()),
ServerPrfInfo::One(info) | ServerPrfInfo::Two(info) => {
if matches!(
info,
ExtensionInfo::RequireEnforceValue
| ExtensionInfo::AllowEnforceValue
) {
client_ext
.prf
.map_or(Ok(()), |prf| {
if prf.enabled {
Ok(())
} else {
Err(ExtensionErr::InvalidPrfValue)
}
})
.and({
if matches!(auth_ext.hmac_secret, HmacSecret::NotEnabled) {
Err(ExtensionErr::InvalidHmacSecretValue)
} else {
Ok(())
}
})
} else {
Ok(())
}
}
})
})
}
}
impl From<Extension<'_, '_>> for ServerExtensionInfo {
fn from(value: Extension<'_, '_>) -> Self {
Self {
cred_props: value.cred_props,
cred_protect: value.cred_protect,
min_pin_length: value.min_pin_length,
prf: value.prf.into(),
}
}
}
#[cfg(test)]
impl PartialEq for ServerExtensionInfo {
fn eq(&self, other: &Self) -> bool {
self.prf == other.prf
}
}
#[derive(Debug)]
pub struct RegistrationServerState<const USER_LEN: usize> {
mediation: CredentialMediationRequirement,
challenge: SentChallenge,
pub_key_cred_params: CoseAlgorithmIdentifiers,
authenticator_selection: AuthenticatorSelectionCriteria,
extensions: ServerExtensionInfo,
#[cfg(not(feature = "serializable_server_state"))]
expiration: Instant,
#[cfg(feature = "serializable_server_state")]
expiration: SystemTime,
user_id: UserHandle<USER_LEN>,
}
impl<const USER_LEN: usize> RegistrationServerState<USER_LEN> {
#[cfg(all(test, feature = "custom", feature = "serializable_server_state"))]
fn is_eq(&self, other: &Self) -> bool {
self.mediation == other.mediation
&& self.challenge == other.challenge
&& self.pub_key_cred_params == other.pub_key_cred_params
&& self.authenticator_selection == other.authenticator_selection
&& self.extensions == other.extensions
&& self.expiration == other.expiration
&& self.user_id == other.user_id
}
#[inline]
pub fn verify<'a, O: PartialEq<Origin<'a>>, T: PartialEq<Origin<'a>>>(
self,
rp_id: &RpId,
response: &'a Registration,
options: &RegistrationVerificationOptions<'_, '_, O, T>,
) -> Result<RegisteredCredential<'a, USER_LEN>, RegCeremonyErr> {
self.partial_validate(rp_id, response, (), &options.into())
.map_err(RegCeremonyErr::from)
.and_then(|attestation_object| {
let auth_data = attestation_object.auth_data();
let flags = auth_data.flags();
if matches!(self.mediation, CredentialMediationRequirement::Conditional)
|| flags.user_present
{
self.authenticator_selection
.validate(
options.require_authenticator_attachment,
response.authenticator_attachment,
)
.and_then(|()| {
let attested_credential_data = auth_data.attested_credential_data();
self.pub_key_cred_params
.validate(attested_credential_data.credential_public_key)
.and_then(|()| {
let extensions = auth_data.extensions();
self.extensions
.validate(
response.client_extension_results,
extensions,
options.error_on_unsolicited_extensions,
)
.map_err(RegCeremonyErr::Extension)
.and_then(|()| {
RegisteredCredential::new(
attested_credential_data.credential_id,
response.response.transports(),
self.user_id,
StaticState {
credential_public_key: attested_credential_data
.credential_public_key,
extensions: extensions.into(),
client_extension_results: response
.client_extension_results
.into(),
},
DynamicState {
user_verified: flags.user_verified,
backup: flags.backup,
sign_count: auth_data.sign_count(),
authenticator_attachment: response
.authenticator_attachment,
},
Metadata {
attestation: match attestation_object
.attestation()
{
AttestationFormat::None => {
Attestation::None
}
AttestationFormat::Packed(_) => {
Attestation::Surrogate
}
},
aaguid: attested_credential_data.aaguid,
extensions: extensions.into(),
client_extension_results: response
.client_extension_results
.into(),
resident_key: self
.authenticator_selection
.resident_key,
},
)
.map_err(RegCeremonyErr::Credential)
})
})
})
} else {
Err(RegCeremonyErr::UserNotPresent)
}
})
}
}
impl<const USER_LEN: usize> TimedCeremony for RegistrationServerState<USER_LEN> {
#[cfg(any(doc, not(feature = "serializable_server_state")))]
#[inline]
fn expiration(&self) -> Instant {
self.expiration
}
#[cfg(all(not(doc), feature = "serializable_server_state"))]
#[inline]
fn expiration(&self) -> SystemTime {
self.expiration
}
}
impl<const USER_LEN: usize> Ceremony<USER_LEN, false> for RegistrationServerState<USER_LEN> {
type R = Registration;
fn rand_challenge(&self) -> SentChallenge {
self.challenge
}
#[cfg(not(feature = "serializable_server_state"))]
fn expiry(&self) -> Instant {
self.expiration
}
#[cfg(feature = "serializable_server_state")]
fn expiry(&self) -> SystemTime {
self.expiration
}
fn user_verification(&self) -> UserVerificationRequirement {
self.authenticator_selection.user_verification
}
}
impl<const USER_LEN: usize> Borrow<SentChallenge> for RegistrationServerState<USER_LEN> {
#[inline]
fn borrow(&self) -> &SentChallenge {
&self.challenge
}
}
impl<const USER_LEN: usize> PartialEq for RegistrationServerState<USER_LEN> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.challenge == other.challenge
}
}
impl<const USER_LEN: usize> PartialEq<&Self> for RegistrationServerState<USER_LEN> {
#[inline]
fn eq(&self, other: &&Self) -> bool {
*self == **other
}
}
impl<const USER_LEN: usize> PartialEq<RegistrationServerState<USER_LEN>>
for &RegistrationServerState<USER_LEN>
{
#[inline]
fn eq(&self, other: &RegistrationServerState<USER_LEN>) -> bool {
**self == *other
}
}
impl<const USER_LEN: usize> Eq for RegistrationServerState<USER_LEN> {}
impl<const USER_LEN: usize> Hash for RegistrationServerState<USER_LEN> {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.challenge.hash(state);
}
}
impl<const USER_LEN: usize> PartialOrd for RegistrationServerState<USER_LEN> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<const USER_LEN: usize> Ord for RegistrationServerState<USER_LEN> {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.challenge.cmp(&other.challenge)
}
}
pub type RegistrationServerState64 = RegistrationServerState<USER_HANDLE_MAX_LEN>;
pub type RegistrationServerState16 = RegistrationServerState<16>;