#[cfg(test)]
mod tests;
#[cfg(doc)]
use super::{
super::response::{
CollectedClientData, Flag,
auth::AuthenticatorData,
register::{
AuthenticatorExtensionOutputStaticState, ClientExtensionsOutputsStaticState,
DynamicState, StaticState,
},
},
AsciiDomain, AsciiDomainStatic, DomainOrigin, Url,
register::{self, PublicKeyCredentialCreationOptions},
};
use super::{
super::{
AuthenticatedCredential,
response::{
AuthenticatorAttachment,
auth::{
Authentication, AuthenticatorExtensionOutput, DiscoverableAuthentication,
HmacSecret, NonDiscoverableAuthentication,
error::{AuthCeremonyErr, ExtensionErr, OneOrTwo},
},
register::{CompressedPubKey, CredentialProtectionPolicy},
},
},
Backup, BackupReq, Ceremony, CeremonyOptions, Challenge, CredentialId,
CredentialMediationRequirement, Credentials, ExtensionReq, FIVE_MINUTES, Hints, Origin,
PrfInput, PublicKeyCredentialDescriptor, RpId, SentChallenge, TimedCeremony,
UserVerificationRequirement,
auth::error::{
DiscoverableCredentialRequestOptionsErr, NonDiscoverableCredentialRequestOptionsErr,
},
};
use core::{
borrow::Borrow,
cmp::Ordering,
hash::{Hash, Hasher},
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;
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 SignatureCounterEnforcement {
#[default]
Fail,
Update,
Ignore,
}
impl SignatureCounterEnforcement {
const fn validate(self, prev: u32, cur: u32) -> Result<u32, AuthCeremonyErr> {
if prev == 0 || cur > prev {
Ok(cur)
} else {
match self {
Self::Fail => Err(AuthCeremonyErr::SignatureCounter),
Self::Update => Ok(if cur == 0 { prev } else { cur }),
Self::Ignore => Ok(prev),
}
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PrfInputOwned {
pub first: Vec<u8>,
pub second: Option<Vec<u8>>,
pub ext_req: ExtensionReq,
}
#[derive(Clone, Copy, Debug)]
pub struct Extension<'prf_first, 'prf_second> {
pub prf: Option<(PrfInput<'prf_first, 'prf_second>, ExtensionReq)>,
}
impl<'prf_first, 'prf_second> Extension<'prf_first, 'prf_second> {
#[inline]
#[must_use]
pub const fn none() -> Self {
Self { prf: None }
}
#[inline]
#[must_use]
pub const fn with_prf<'a: 'prf_first, 'b: 'prf_second>(
input: PrfInput<'a, 'b>,
req: ExtensionReq,
) -> Self {
Self {
prf: Some((input, req)),
}
}
}
impl Default for Extension<'_, '_> {
#[inline]
fn default() -> Self {
Self::none()
}
}
#[derive(Clone, Debug, Default)]
pub struct CredentialSpecificExtension {
pub prf: Option<PrfInputOwned>,
}
#[derive(Clone, Debug)]
pub struct AllowedCredential {
pub credential: PublicKeyCredentialDescriptor<Box<[u8]>>,
pub extension: CredentialSpecificExtension,
}
impl From<PublicKeyCredentialDescriptor<Box<[u8]>>> for AllowedCredential {
#[inline]
fn from(credential: PublicKeyCredentialDescriptor<Box<[u8]>>) -> Self {
Self {
credential,
extension: CredentialSpecificExtension::default(),
}
}
}
impl From<AllowedCredential> for PublicKeyCredentialDescriptor<Box<[u8]>> {
#[inline]
fn from(credential: AllowedCredential) -> Self {
credential.credential
}
}
#[derive(Clone, Debug, Default)]
pub struct AllowedCredentials {
creds: Vec<AllowedCredential>,
prf_count: usize,
}
impl Credentials for AllowedCredentials {
type Credential = AllowedCredential;
#[inline]
fn with_capacity(capacity: usize) -> Self {
Self {
creds: Vec::with_capacity(capacity),
prf_count: 0,
}
}
#[expect(
clippy::arithmetic_side_effects,
reason = "comment explains how overflow is not possible"
)]
#[inline]
fn push(&mut self, cred: Self::Credential) -> bool {
self.creds
.iter()
.try_fold((), |(), c| {
if c.credential.id == cred.credential.id {
Err(())
} else {
Ok(())
}
})
.is_ok_and(|()| {
self.prf_count += usize::from(cred.extension.prf.is_some());
self.creds.push(cred);
true
})
}
#[inline]
fn len(&self) -> usize {
self.creds.len()
}
}
impl AsRef<[AllowedCredential]> for AllowedCredentials {
#[inline]
fn as_ref(&self) -> &[AllowedCredential] {
self.creds.as_slice()
}
}
impl From<&AllowedCredentials> for Box<[CredInfo]> {
#[inline]
fn from(value: &AllowedCredentials) -> Self {
let len = value.creds.len();
value
.creds
.iter()
.fold(Vec::with_capacity(len), |mut creds, cred| {
creds.push(CredInfo {
id: cred.credential.id.clone(),
ext: (&cred.extension).into(),
});
creds
})
.into_boxed_slice()
}
}
impl From<AllowedCredentials> for Vec<PublicKeyCredentialDescriptor<Box<[u8]>>> {
#[inline]
fn from(value: AllowedCredentials) -> Self {
let mut creds = Self::with_capacity(value.creds.len());
value.creds.into_iter().fold((), |(), cred| {
creds.push(cred.credential);
});
creds
}
}
impl From<Vec<PublicKeyCredentialDescriptor<Box<[u8]>>>> for AllowedCredentials {
#[inline]
fn from(value: Vec<PublicKeyCredentialDescriptor<Box<[u8]>>>) -> Self {
let mut creds = Self::with_capacity(value.len());
value.into_iter().fold((), |(), credential| {
_ = creds.push(AllowedCredential {
credential,
extension: CredentialSpecificExtension { prf: None },
});
});
creds
}
}
const fn validate_discoverable_options_helper(
ext: ServerExtensionInfo,
uv: UserVerificationRequirement,
) -> bool {
matches!(ext.prf, ServerPrfInfo::None) || matches!(uv, UserVerificationRequirement::Required)
}
fn validate_non_discoverable_options_helper(
uv: UserVerificationRequirement,
creds: &[CredInfo],
) -> Result<(), NonDiscoverableCredentialRequestOptionsErr> {
creds.iter().try_fold((), |(), cred| {
if matches!(cred.ext.prf, ServerPrfInfo::None)
|| matches!(uv, UserVerificationRequirement::Required)
{
Ok(())
} else {
Err(NonDiscoverableCredentialRequestOptionsErr::PrfWithoutUserVerification)
}
})
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CredentialUiMode {
Immediate,
}
#[derive(Debug)]
pub struct DiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second> {
pub mediation: CredentialMediationRequirement,
pub ui_mode: Option<CredentialUiMode>,
pub public_key: PublicKeyCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second>,
}
impl<'rp_id, 'prf_first, 'prf_second>
DiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second>
{
#[inline]
#[must_use]
pub fn passkey<'a: 'rp_id>(rp_id: &'a RpId) -> Self {
Self {
mediation: CredentialMediationRequirement::default(),
ui_mode: None,
public_key: PublicKeyCredentialRequestOptions::passkey(rp_id),
}
}
#[inline]
pub fn start_ceremony(
self,
) -> Result<
(
DiscoverableAuthenticationServerState,
DiscoverableAuthenticationClientState<'rp_id, 'prf_first, 'prf_second>,
),
DiscoverableCredentialRequestOptionsErr,
> {
let extensions = self.public_key.extensions.into();
if validate_discoverable_options_helper(extensions, self.public_key.user_verification) {
#[cfg(not(feature = "serializable_server_state"))]
let res = Instant::now();
#[cfg(feature = "serializable_server_state")]
let res = SystemTime::now();
res.checked_add(Duration::from_millis(
NonZeroU64::from(self.public_key.timeout).get(),
))
.ok_or(DiscoverableCredentialRequestOptionsErr::InvalidTimeout)
.map(|expiration| {
(
DiscoverableAuthenticationServerState(AuthenticationServerState {
challenge: SentChallenge(self.public_key.challenge.0),
user_verification: self.public_key.user_verification,
extensions,
expiration,
}),
DiscoverableAuthenticationClientState(self),
)
})
} else {
Err(DiscoverableCredentialRequestOptionsErr::PrfWithoutUserVerification)
}
}
#[inline]
pub fn start_ceremony_challenge_only(
self,
) -> Result<
(DiscoverableAuthenticationServerState, [u8; 16]),
DiscoverableCredentialRequestOptionsErr,
> {
self.start_ceremony()
.map(|(server, client)| (server, client.0.public_key.challenge.into_array()))
}
}
#[derive(Debug)]
pub struct NonDiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second> {
pub mediation: CredentialMediationRequirement,
pub options: PublicKeyCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second>,
pub allow_credentials: AllowedCredentials,
}
impl<'rp_id, 'prf_first, 'prf_second>
NonDiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second>
{
#[inline]
#[must_use]
pub fn second_factor<'a: 'rp_id>(
rp_id: &'a RpId,
allow_credentials: AllowedCredentials,
) -> Self {
Self {
mediation: CredentialMediationRequirement::default(),
options: PublicKeyCredentialRequestOptions::second_factor(rp_id),
allow_credentials,
}
}
#[inline]
pub fn start_ceremony(
self,
) -> Result<
(
NonDiscoverableAuthenticationServerState,
NonDiscoverableAuthenticationClientState<'rp_id, 'prf_first, 'prf_second>,
),
NonDiscoverableCredentialRequestOptionsErr,
> {
if self.allow_credentials.is_empty() {
Err(NonDiscoverableCredentialRequestOptionsErr::EmptyAllowedCredentials)
} else if matches!(self.mediation, CredentialMediationRequirement::Conditional) {
Err(NonDiscoverableCredentialRequestOptionsErr::ConditionalMediationRequested)
} else {
let extensions = self.options.extensions.into();
if validate_discoverable_options_helper(extensions, self.options.user_verification) {
let allow_credentials = Box::from(&self.allow_credentials);
validate_non_discoverable_options_helper(
self.options.user_verification,
&allow_credentials,
)
.and_then(|()| {
#[cfg(not(feature = "serializable_server_state"))]
let res = Instant::now();
#[cfg(feature = "serializable_server_state")]
let res = SystemTime::now();
res.checked_add(Duration::from_millis(
NonZeroU64::from(self.options.timeout).get(),
))
.ok_or(NonDiscoverableCredentialRequestOptionsErr::InvalidTimeout)
.map(|expiration| {
(
NonDiscoverableAuthenticationServerState {
state: AuthenticationServerState {
challenge: SentChallenge(self.options.challenge.0),
user_verification: self.options.user_verification,
extensions,
expiration,
},
allow_credentials,
},
NonDiscoverableAuthenticationClientState(self),
)
})
})
} else {
Err(NonDiscoverableCredentialRequestOptionsErr::PrfWithoutUserVerification)
}
}
}
}
#[derive(Debug)]
pub struct PublicKeyCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second> {
pub challenge: Challenge,
pub timeout: NonZeroU32,
pub rp_id: &'rp_id RpId,
pub user_verification: UserVerificationRequirement,
pub hints: Hints,
pub extensions: Extension<'prf_first, 'prf_second>,
}
impl<'rp_id> PublicKeyCredentialRequestOptions<'rp_id, '_, '_> {
#[inline]
#[must_use]
pub fn passkey<'a: 'rp_id>(rp_id: &'a RpId) -> Self {
Self {
challenge: Challenge::new(),
timeout: FIVE_MINUTES,
rp_id,
user_verification: UserVerificationRequirement::Required,
hints: Hints::EMPTY,
extensions: Extension::default(),
}
}
#[inline]
#[must_use]
pub fn second_factor<'a: 'rp_id>(rp_id: &'a RpId) -> Self {
let mut opts = Self::passkey(rp_id);
opts.user_verification = UserVerificationRequirement::Discouraged;
opts
}
}
#[derive(Debug)]
pub struct DiscoverableAuthenticationClientState<'rp_id, 'prf_first, 'prf_second>(
DiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second>,
);
impl<'rp_id, 'prf_first, 'prf_second>
DiscoverableAuthenticationClientState<'rp_id, 'prf_first, 'prf_second>
{
#[inline]
#[must_use]
pub const fn options(
&self,
) -> &DiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second> {
&self.0
}
}
#[derive(Debug)]
pub struct NonDiscoverableAuthenticationClientState<'rp_id, 'prf_first, 'prf_second>(
NonDiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second>,
);
impl<'rp_id, 'prf_first, 'prf_second>
NonDiscoverableAuthenticationClientState<'rp_id, 'prf_first, 'prf_second>
{
#[inline]
#[must_use]
pub const fn options(
&self,
) -> &NonDiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second> {
&self.0
}
}
#[derive(Clone, Copy)]
enum CredPrf {
None,
FalseNoHmac,
FalseFalseHmac,
TrueNoHmac,
TrueTrueHmac,
}
#[derive(Clone, Copy, Debug)]
enum ServerPrfInfo {
None,
One(ExtensionReq),
Two(ExtensionReq),
}
impl ServerPrfInfo {
const fn validate(
self,
user_verified: bool,
cred_prf: CredPrf,
hmac: HmacSecret,
err_unsolicited: bool,
) -> Result<(), ExtensionErr> {
match hmac {
HmacSecret::None => match self {
Self::None => Ok(()),
Self::One(req) | Self::Two(req) => {
if matches!(req, ExtensionReq::Allow)
|| !matches!(cred_prf, CredPrf::TrueTrueHmac)
{
Ok(())
} else {
Err(ExtensionErr::MissingHmacSecret)
}
}
},
HmacSecret::One => match self {
Self::None => {
if err_unsolicited {
Err(ExtensionErr::ForbiddenHmacSecret)
} else if matches!(cred_prf, CredPrf::None | CredPrf::TrueTrueHmac) {
if user_verified {
Ok(())
} else {
Err(ExtensionErr::UserNotVerifiedHmacSecret)
}
} else {
Err(ExtensionErr::HmacSecretForNonHmacSecretCredential)
}
}
Self::One(_) => {
if matches!(cred_prf, CredPrf::None | CredPrf::TrueTrueHmac) {
Ok(())
} else {
Err(ExtensionErr::HmacSecretForNonHmacSecretCredential)
}
}
Self::Two(_) => Err(ExtensionErr::InvalidHmacSecretValue(
OneOrTwo::Two,
OneOrTwo::One,
)),
},
HmacSecret::Two => match self {
Self::None => {
if err_unsolicited {
Err(ExtensionErr::ForbiddenHmacSecret)
} else if matches!(cred_prf, CredPrf::None | CredPrf::TrueTrueHmac) {
if user_verified {
Ok(())
} else {
Err(ExtensionErr::UserNotVerifiedHmacSecret)
}
} else {
Err(ExtensionErr::HmacSecretForNonHmacSecretCredential)
}
}
Self::One(_) => Err(ExtensionErr::InvalidHmacSecretValue(
OneOrTwo::One,
OneOrTwo::Two,
)),
Self::Two(_) => {
if matches!(cred_prf, CredPrf::None | CredPrf::TrueTrueHmac) {
Ok(())
} else {
Err(ExtensionErr::HmacSecretForNonHmacSecretCredential)
}
}
},
}
}
}
#[cfg(test)]
impl PartialEq for ServerPrfInfo {
fn eq(&self, other: &Self) -> bool {
match *self {
Self::None => matches!(*other, Self::None),
Self::One(req) => matches!(*other, Self::One(req2) if req == req2),
Self::Two(req) => matches!(*other, Self::Two(req2) if req == req2),
}
}
}
impl From<Option<(PrfInput<'_, '_>, ExtensionReq)>> for ServerPrfInfo {
fn from(value: Option<(PrfInput<'_, '_>, ExtensionReq)>) -> Self {
value.map_or(Self::None, |val| {
val.0
.second
.map_or_else(|| Self::One(val.1), |_| Self::Two(val.1))
})
}
}
impl From<&PrfInputOwned> for ServerPrfInfo {
fn from(value: &PrfInputOwned) -> Self {
value
.second
.as_ref()
.map_or_else(|| Self::One(value.ext_req), |_| Self::Two(value.ext_req))
}
}
#[derive(Clone, Copy, Debug)]
struct ServerExtensionInfo {
prf: ServerPrfInfo,
}
impl From<Extension<'_, '_>> for ServerExtensionInfo {
fn from(value: Extension<'_, '_>) -> Self {
Self {
prf: value.prf.into(),
}
}
}
#[cfg(test)]
impl PartialEq for ServerExtensionInfo {
fn eq(&self, other: &Self) -> bool {
self.prf == other.prf
}
}
#[derive(Clone, Copy, Debug)]
struct ServerCredSpecificExtensionInfo {
prf: ServerPrfInfo,
}
#[cfg(test)]
impl PartialEq for ServerCredSpecificExtensionInfo {
fn eq(&self, other: &Self) -> bool {
self.prf == other.prf
}
}
impl From<&CredentialSpecificExtension> for ServerCredSpecificExtensionInfo {
fn from(value: &CredentialSpecificExtension) -> Self {
Self {
prf: value
.prf
.as_ref()
.map_or(ServerPrfInfo::None, ServerPrfInfo::from),
}
}
}
impl ServerExtensionInfo {
const fn validate_extensions(
self,
user_verified: bool,
auth_ext: AuthenticatorExtensionOutput,
error_unsolicited: bool,
cred_prf: CredPrf,
) -> Result<(), ExtensionErr> {
ServerPrfInfo::validate(
self.prf,
user_verified,
cred_prf,
auth_ext.hmac_secret,
error_unsolicited,
)
}
}
fn validate_extensions(
ext: ServerExtensionInfo,
user_verified: bool,
cred_ext: Option<ServerCredSpecificExtensionInfo>,
auth_ext: AuthenticatorExtensionOutput,
error_unsolicited: bool,
cred_prf: CredPrf,
) -> Result<(), ExtensionErr> {
cred_ext.map_or_else(
|| {
ext.validate_extensions(user_verified, auth_ext, error_unsolicited, cred_prf)
},
|c_ext| {
if matches!(c_ext.prf, ServerPrfInfo::None) {
ext.prf.validate(
user_verified,
cred_prf,
auth_ext.hmac_secret,
error_unsolicited,
)
} else {
c_ext.prf.validate(
user_verified,
cred_prf,
auth_ext.hmac_secret,
error_unsolicited,
)
}
},
)
}
#[derive(Debug)]
struct CredInfo {
id: CredentialId<Box<[u8]>>,
ext: ServerCredSpecificExtensionInfo,
}
#[cfg(test)]
impl PartialEq for CredInfo {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.ext == other.ext
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AuthenticatorAttachmentEnforcement {
Fail(bool),
Update(bool),
Ignore(bool),
}
impl AuthenticatorAttachmentEnforcement {
const fn validate(
self,
prev: AuthenticatorAttachment,
cur: AuthenticatorAttachment,
) -> Result<AuthenticatorAttachment, AuthCeremonyErr> {
match cur {
AuthenticatorAttachment::None => match self {
Self::Fail(require) | Self::Update(require) | Self::Ignore(require) => {
if require {
Err(AuthCeremonyErr::MissingAuthenticatorAttachment)
} else {
Ok(prev)
}
}
},
AuthenticatorAttachment::Platform => match self {
Self::Fail(_) => {
if matches!(prev, AuthenticatorAttachment::CrossPlatform) {
Err(AuthCeremonyErr::AuthenticatorAttachmentMismatch)
} else {
Ok(cur)
}
}
Self::Update(_) => Ok(cur),
Self::Ignore(_) => {
if matches!(prev, AuthenticatorAttachment::None) {
Ok(cur)
} else {
Ok(prev)
}
}
},
AuthenticatorAttachment::CrossPlatform => match self {
Self::Fail(_) => {
if matches!(prev, AuthenticatorAttachment::Platform) {
Err(AuthCeremonyErr::AuthenticatorAttachmentMismatch)
} else {
Ok(cur)
}
}
Self::Update(_) => Ok(cur),
Self::Ignore(_) => {
if matches!(prev, AuthenticatorAttachment::None) {
Ok(cur)
} else {
Ok(prev)
}
}
},
}
}
}
impl Default for AuthenticatorAttachmentEnforcement {
#[inline]
fn default() -> Self {
Self::Ignore(false)
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum BackupStateReq {
#[default]
None,
Exists,
DoesntExist,
}
#[derive(Clone, Copy, Debug)]
pub struct AuthenticationVerificationOptions<'origins, 'top_origins, O, T> {
pub allowed_origins: &'origins [O],
pub allowed_top_origins: Option<&'top_origins [T]>,
pub backup_state_requirement: BackupStateReq,
pub error_on_unsolicited_extensions: bool,
pub auth_attachment_enforcement: AuthenticatorAttachmentEnforcement,
pub update_uv: bool,
pub sig_counter_enforcement: SignatureCounterEnforcement,
#[cfg(feature = "serde_relaxed")]
pub client_data_json_relaxed: bool,
}
impl<O, T> AuthenticationVerificationOptions<'_, '_, O, T> {
#[inline]
#[must_use]
pub const fn new() -> Self {
Self {
allowed_origins: [].as_slice(),
allowed_top_origins: None,
backup_state_requirement: BackupStateReq::None,
error_on_unsolicited_extensions: true,
auth_attachment_enforcement: AuthenticatorAttachmentEnforcement::Ignore(false),
update_uv: false,
sig_counter_enforcement: SignatureCounterEnforcement::Fail,
#[cfg(feature = "serde_relaxed")]
client_data_json_relaxed: true,
}
}
}
impl<O, T> Default for AuthenticationVerificationOptions<'_, '_, O, T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
#[derive(Debug)]
pub struct DiscoverableAuthenticationServerState(AuthenticationServerState);
impl DiscoverableAuthenticationServerState {
#[inline]
pub fn verify<
'a,
const USER_LEN: usize,
O: PartialEq<Origin<'a>>,
T: PartialEq<Origin<'a>>,
MlDsa87Key: AsRef<[u8]>,
MlDsa65Key: AsRef<[u8]>,
MlDsa44Key: AsRef<[u8]>,
EdKey: AsRef<[u8]>,
P256Key: AsRef<[u8]>,
P384Key: AsRef<[u8]>,
RsaKey: AsRef<[u8]>,
>(
self,
rp_id: &RpId,
response: &'a DiscoverableAuthentication<USER_LEN>,
cred: &mut AuthenticatedCredential<
'_,
'_,
USER_LEN,
CompressedPubKey<MlDsa87Key, MlDsa65Key, MlDsa44Key, EdKey, P256Key, P384Key, RsaKey>,
>,
options: &AuthenticationVerificationOptions<'_, '_, O, T>,
) -> Result<bool, AuthCeremonyErr> {
if cred.user_id == response.response.user_handle() {
if cred.id.as_ref() == response.raw_id.as_ref() {
self.0.verify(rp_id, response, cred, options, None)
} else {
Err(AuthCeremonyErr::CredentialIdMismatch)
}
} else {
Err(AuthCeremonyErr::UserHandleMismatch)
}
}
#[cfg(all(test, feature = "custom", feature = "serializable_server_state"))]
fn is_eq(&self, other: &Self) -> bool {
self.0.is_eq(&other.0)
}
}
#[derive(Debug)]
pub struct NonDiscoverableAuthenticationServerState {
state: AuthenticationServerState,
allow_credentials: Box<[CredInfo]>,
}
impl NonDiscoverableAuthenticationServerState {
#[inline]
pub fn verify<
'a,
const USER_LEN: usize,
O: PartialEq<Origin<'a>>,
T: PartialEq<Origin<'a>>,
MlDsa87Key: AsRef<[u8]>,
MlDsa65Key: AsRef<[u8]>,
MlDsa44Key: AsRef<[u8]>,
EdKey: AsRef<[u8]>,
P256Key: AsRef<[u8]>,
P384Key: AsRef<[u8]>,
RsaKey: AsRef<[u8]>,
>(
self,
rp_id: &RpId,
response: &'a NonDiscoverableAuthentication<USER_LEN>,
cred: &mut AuthenticatedCredential<
'_,
'_,
USER_LEN,
CompressedPubKey<MlDsa87Key, MlDsa65Key, MlDsa44Key, EdKey, P256Key, P384Key, RsaKey>,
>,
options: &AuthenticationVerificationOptions<'_, '_, O, T>,
) -> Result<bool, AuthCeremonyErr> {
response
.response
.user_handle()
.as_ref()
.map_or(Ok(()), |user| {
if *user == cred.user_id() {
Ok(())
} else {
Err(AuthCeremonyErr::UserHandleMismatch)
}
})
.and_then(|()| {
self.allow_credentials
.iter()
.find(|c| c.id == response.raw_id)
.ok_or(AuthCeremonyErr::NoMatchingAllowedCredential)
.and_then(|c| {
if c.id.as_ref() == cred.id.as_ref() {
self.state
.verify(rp_id, response, cred, options, Some(c.ext))
} else {
Err(AuthCeremonyErr::CredentialIdMismatch)
}
})
})
}
#[cfg(all(test, feature = "custom", feature = "serializable_server_state"))]
fn is_eq(&self, other: &Self) -> bool {
self.state.is_eq(&other.state) && self.allow_credentials == other.allow_credentials
}
}
#[derive(Debug)]
struct AuthenticationServerState {
challenge: SentChallenge,
user_verification: UserVerificationRequirement,
extensions: ServerExtensionInfo,
#[cfg(not(feature = "serializable_server_state"))]
expiration: Instant,
#[cfg(feature = "serializable_server_state")]
expiration: SystemTime,
}
impl AuthenticationServerState {
fn verify<
'a,
const USER_LEN: usize,
const DISCOVERABLE: bool,
O: PartialEq<Origin<'a>>,
T: PartialEq<Origin<'a>>,
MlDsa87Key: AsRef<[u8]>,
MlDsa65Key: AsRef<[u8]>,
MlDsa44Key: AsRef<[u8]>,
EdKey: AsRef<[u8]>,
P256Key: AsRef<[u8]>,
P384Key: AsRef<[u8]>,
RsaKey: AsRef<[u8]>,
>(
self,
rp_id: &RpId,
response: &'a Authentication<USER_LEN, DISCOVERABLE>,
cred: &mut AuthenticatedCredential<
'_,
'_,
USER_LEN,
CompressedPubKey<MlDsa87Key, MlDsa65Key, MlDsa44Key, EdKey, P256Key, P384Key, RsaKey>,
>,
options: &AuthenticationVerificationOptions<'_, '_, O, T>,
cred_ext: Option<ServerCredSpecificExtensionInfo>,
) -> Result<bool, AuthCeremonyErr> {
self.partial_validate(
rp_id,
response,
(&cred.static_state.credential_public_key).into(),
&CeremonyOptions {
allowed_origins: options.allowed_origins,
allowed_top_origins: options.allowed_top_origins,
backup_requirement: if cred.dynamic_state.backup == Backup::NotEligible {
BackupReq::NotEligible
} else {
match options.backup_state_requirement {
BackupStateReq::None => BackupReq::Eligible,
BackupStateReq::Exists => BackupReq::Exists,
BackupStateReq::DoesntExist => BackupReq::EligibleNotExists,
}
},
#[cfg(feature = "serde_relaxed")]
client_data_json_relaxed: options.client_data_json_relaxed,
},
)
.map_err(AuthCeremonyErr::from)
.and_then(|auth_data| {
options
.auth_attachment_enforcement
.validate(
cred.dynamic_state.authenticator_attachment,
response.authenticator_attachment,
)
.and_then(|auth_attachment| {
let flags = auth_data.flags();
validate_extensions(
self.extensions,
flags.user_verified,
cred_ext,
auth_data.extensions(),
options.error_on_unsolicited_extensions,
cred.static_state.client_extension_results.prf.map_or(
CredPrf::None,
|prf| {
if prf.enabled {
cred.static_state
.extensions
.hmac_secret
.map_or(CredPrf::TrueNoHmac, |_| CredPrf::TrueTrueHmac)
} else {
cred.static_state
.extensions
.hmac_secret
.map_or(CredPrf::FalseNoHmac, |_| CredPrf::FalseFalseHmac)
}
},
),
)
.map_err(AuthCeremonyErr::Extension)
.and_then(|()| {
options
.sig_counter_enforcement
.validate(cred.dynamic_state.sign_count, auth_data.sign_count())
.and_then(|sig_counter| {
let prev_dyn_state = cred.dynamic_state;
cred.dynamic_state.backup = flags.backup;
if options.update_uv && flags.user_verified {
cred.dynamic_state.user_verified = true;
}
cred.dynamic_state.sign_count = sig_counter;
cred.dynamic_state.authenticator_attachment = auth_attachment;
if flags.user_verified {
Ok(())
} else {
match cred.static_state.extensions.cred_protect {
CredentialProtectionPolicy::None | CredentialProtectionPolicy::UserVerificationOptional => Ok(()),
CredentialProtectionPolicy::UserVerificationOptionalWithCredentialIdList => {
if DISCOVERABLE {
Err(AuthCeremonyErr::DiscoverableCredProtectCredentialIdList)
} else {
Ok(())
}
}
CredentialProtectionPolicy::UserVerificationRequired => {
Err(AuthCeremonyErr::UserNotVerifiedCredProtectRequired)
}
}
}.inspect_err(|_| {
cred.dynamic_state = prev_dyn_state;
}).map(|()| {
prev_dyn_state != cred.dynamic_state
})
})
})
})
})
}
#[cfg(all(test, feature = "custom", feature = "serializable_server_state"))]
fn is_eq(&self, other: &Self) -> bool {
self.challenge == other.challenge
&& self.user_verification == other.user_verification
&& self.extensions == other.extensions
&& self.expiration == other.expiration
}
}
impl TimedCeremony for AuthenticationServerState {
#[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 TimedCeremony for DiscoverableAuthenticationServerState {
#[cfg(any(doc, not(feature = "serializable_server_state")))]
#[inline]
fn expiration(&self) -> Instant {
self.0.expiration()
}
#[cfg(all(not(doc), feature = "serializable_server_state"))]
#[inline]
fn expiration(&self) -> SystemTime {
self.0.expiration()
}
}
impl TimedCeremony for NonDiscoverableAuthenticationServerState {
#[cfg(any(doc, not(feature = "serializable_server_state")))]
#[inline]
fn expiration(&self) -> Instant {
self.state.expiration()
}
#[cfg(all(not(doc), feature = "serializable_server_state"))]
#[inline]
fn expiration(&self) -> SystemTime {
self.state.expiration()
}
}
impl<const USER_LEN: usize, const DISCOVERABLE: bool> Ceremony<USER_LEN, DISCOVERABLE>
for AuthenticationServerState
{
type R = Authentication<USER_LEN, DISCOVERABLE>;
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.user_verification
}
}
impl Borrow<SentChallenge> for AuthenticationServerState {
#[inline]
fn borrow(&self) -> &SentChallenge {
&self.challenge
}
}
impl PartialEq for AuthenticationServerState {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.challenge == other.challenge
}
}
impl PartialEq<&Self> for AuthenticationServerState {
#[inline]
fn eq(&self, other: &&Self) -> bool {
*self == **other
}
}
impl PartialEq<AuthenticationServerState> for &AuthenticationServerState {
#[inline]
fn eq(&self, other: &AuthenticationServerState) -> bool {
**self == *other
}
}
impl Eq for AuthenticationServerState {}
impl Hash for AuthenticationServerState {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.challenge.hash(state);
}
}
impl PartialOrd for AuthenticationServerState {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for AuthenticationServerState {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.challenge.cmp(&other.challenge)
}
}
impl Borrow<SentChallenge> for DiscoverableAuthenticationServerState {
#[inline]
fn borrow(&self) -> &SentChallenge {
self.0.borrow()
}
}
impl PartialEq for DiscoverableAuthenticationServerState {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl PartialEq<&Self> for DiscoverableAuthenticationServerState {
#[inline]
fn eq(&self, other: &&Self) -> bool {
self.0 == other.0
}
}
impl PartialEq<DiscoverableAuthenticationServerState> for &DiscoverableAuthenticationServerState {
#[inline]
fn eq(&self, other: &DiscoverableAuthenticationServerState) -> bool {
self.0 == other.0
}
}
impl Eq for DiscoverableAuthenticationServerState {}
impl Hash for DiscoverableAuthenticationServerState {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl PartialOrd for DiscoverableAuthenticationServerState {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for DiscoverableAuthenticationServerState {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.0.cmp(&other.0)
}
}
impl Borrow<SentChallenge> for NonDiscoverableAuthenticationServerState {
#[inline]
fn borrow(&self) -> &SentChallenge {
self.state.borrow()
}
}
impl PartialEq for NonDiscoverableAuthenticationServerState {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.state == other.state
}
}
impl PartialEq<&Self> for NonDiscoverableAuthenticationServerState {
#[inline]
fn eq(&self, other: &&Self) -> bool {
self.state == other.state
}
}
impl PartialEq<NonDiscoverableAuthenticationServerState>
for &NonDiscoverableAuthenticationServerState
{
#[inline]
fn eq(&self, other: &NonDiscoverableAuthenticationServerState) -> bool {
self.state == other.state
}
}
impl Eq for NonDiscoverableAuthenticationServerState {}
impl Hash for NonDiscoverableAuthenticationServerState {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.state.hash(state);
}
}
impl PartialOrd for NonDiscoverableAuthenticationServerState {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for NonDiscoverableAuthenticationServerState {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.state.cmp(&other.state)
}
}