#[cfg(test)]
mod tests;
#[cfg(doc)]
use super::{
hash::hash_set::MaxLenHashSet,
request::{
auth::{
AllowedCredential, AllowedCredentials, CredentialSpecificExtension,
DiscoverableAuthenticationServerState, DiscoverableCredentialRequestOptions,
NonDiscoverableAuthenticationServerState, NonDiscoverableCredentialRequestOptions,
PublicKeyCredentialRequestOptions,
},
register::{CredentialCreationOptions, RegistrationServerState},
},
response::{AuthenticatorAttachment, register::ClientExtensionsOutputs},
};
use crate::{
request::{
error::{
AsciiDomainErr, DomainOriginParseErr, PortParseErr, RpIdErr, SchemeParseErr, UrlErr,
},
register::{BackupReq, RegistrationVerificationOptions},
},
response::{
AuthData as _, AuthDataContainer, AuthResponse, AuthTransports, Backup, CeremonyErr,
CredentialId, Origin, Response, SentChallenge,
},
};
use core::{
borrow::Borrow,
cell::Cell,
fmt::{self, Display, Formatter},
num::NonZeroU32,
str::FromStr,
};
use rsa::sha2::{Digest as _, Sha256};
#[cfg(any(doc, not(feature = "serializable_server_state")))]
use std::time::Instant;
#[cfg(feature = "serializable_server_state")]
use std::time::SystemTime;
use url::Url as Uri;
pub mod auth;
pub mod error;
pub mod register;
#[cfg(feature = "serde")]
mod ser;
#[cfg(feature = "serializable_server_state")]
pub(super) mod ser_server_state;
#[expect(
missing_copy_implementations,
reason = "want to enforce randomly-generated challenges"
)]
#[derive(Debug)]
pub struct Challenge(u128);
impl Challenge {
pub(super) const BASE64_LEN: usize = base64url_nopad::encode_len(16);
#[inline]
#[must_use]
pub fn new() -> Self {
Self(rand::random())
}
#[inline]
#[must_use]
pub const fn into_data(self) -> u128 {
self.0
}
#[inline]
#[must_use]
pub const fn as_data(&self) -> u128 {
self.0
}
#[inline]
#[must_use]
pub const fn into_array(self) -> [u8; 16] {
self.as_array()
}
#[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 as_array(&self) -> [u8; 16] {
self.0.to_le_bytes()
}
}
impl Default for Challenge {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl From<Challenge> for u128 {
#[inline]
fn from(value: Challenge) -> Self {
value.0
}
}
impl From<&Challenge> for u128 {
#[inline]
fn from(value: &Challenge) -> Self {
value.0
}
}
impl From<Challenge> for [u8; 16] {
#[inline]
fn from(value: Challenge) -> Self {
value.into_array()
}
}
impl From<&Challenge> for [u8; 16] {
#[inline]
fn from(value: &Challenge) -> Self {
value.as_array()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AsciiDomain(String);
impl AsciiDomain {
#[expect(clippy::unreachable, reason = "want to crash when there is a bug")]
#[inline]
pub fn remove_trailing_dot(&mut self) {
if *self
.0
.as_bytes()
.last()
.unwrap_or_else(|| unreachable!("there is a bug in AsciiDomain::from_slice"))
== b'.'
{
_ = self.0.pop();
}
}
}
impl AsRef<str> for AsciiDomain {
#[inline]
fn as_ref(&self) -> &str {
self.0.as_str()
}
}
impl Borrow<str> for AsciiDomain {
#[inline]
fn borrow(&self) -> &str {
self.0.as_str()
}
}
impl From<AsciiDomain> for String {
#[inline]
fn from(value: AsciiDomain) -> Self {
value.0
}
}
impl PartialEq<&Self> for AsciiDomain {
#[inline]
fn eq(&self, other: &&Self) -> bool {
*self == **other
}
}
impl PartialEq<AsciiDomain> for &AsciiDomain {
#[inline]
fn eq(&self, other: &AsciiDomain) -> bool {
**self == *other
}
}
impl TryFrom<Vec<u8>> for AsciiDomain {
type Error = AsciiDomainErr;
#[expect(unsafe_code, reason = "comment justifies correctness")]
#[expect(
clippy::arithmetic_side_effects,
reason = "comments justify correctness"
)]
#[inline]
fn try_from(mut value: Vec<u8>) -> Result<Self, Self::Error> {
const DIFF: u8 = b'a' - b'A';
let bytes = value.as_slice();
bytes
.as_ref()
.last()
.ok_or(AsciiDomainErr::Empty)
.and_then(|b| {
let len = bytes.len();
if *b == b'.' {
if len == 1 {
Err(AsciiDomainErr::RootDomain)
} else if len > 254 {
Err(AsciiDomainErr::Len)
} else {
Ok(())
}
} else if len > 253 {
Err(AsciiDomainErr::Len)
} else {
Ok(())
}
})
.and_then(|()| {
value
.iter_mut()
.try_fold(0u8, |mut label_len, byt| {
let b = *byt;
if b == b'.' {
if label_len == 0 {
Err(AsciiDomainErr::EmptyLabel)
} else {
Ok(0)
}
} else if label_len == 63 {
Err(AsciiDomainErr::LabelLen)
} else {
label_len += 1;
match b {
..b'A' | b'['..=0x7F => Ok(label_len),
b'A'..=b'Z' => {
*byt += DIFF;
Ok(label_len)
}
0x80.. => Err(AsciiDomainErr::NotAscii),
}
}
})
.map(|_| {
let utf8 = unsafe { String::from_utf8_unchecked(value) };
Self(utf8)
})
})
}
}
impl TryFrom<String> for AsciiDomain {
type Error = AsciiDomainErr;
#[inline]
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::try_from(value.into_bytes())
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AsciiDomainStatic(&'static str);
impl AsciiDomainStatic {
#[inline]
#[must_use]
pub const fn as_str(self) -> &'static str {
self.0
}
#[expect(
clippy::arithmetic_side_effects,
reason = "comment justifies correctness"
)]
#[expect(
clippy::else_if_without_else,
reason = "part of if branch and else branch are the same"
)]
#[inline]
#[must_use]
pub const fn new(domain: &'static str) -> Option<Self> {
let mut utf8 = domain.as_bytes();
if let Some(lst) = utf8.last() {
let len = utf8.len();
if *lst == b'.' {
if len == 1 || len > 254 {
return None;
}
} else if len > 253 {
return None;
}
let mut label_len = 0;
while let [first, ref rest @ ..] = *utf8 {
if first == b'.' {
if label_len == 0 {
return None;
}
label_len = 0;
} else if label_len == 63 {
return None;
} else {
match first {
..b'A' | b'['..=0x7F => label_len += 1,
b'A'..=b'Z' | 0x80.. => return None,
}
}
utf8 = rest;
}
Some(Self(domain))
} else {
None
}
}
}
impl AsRef<str> for AsciiDomainStatic {
#[inline]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Borrow<str> for AsciiDomainStatic {
#[inline]
fn borrow(&self) -> &str {
self.as_str()
}
}
impl From<AsciiDomainStatic> for &'static str {
#[inline]
fn from(value: AsciiDomainStatic) -> Self {
value.0
}
}
impl From<AsciiDomainStatic> for String {
#[inline]
fn from(value: AsciiDomainStatic) -> Self {
value.0.to_owned()
}
}
impl From<AsciiDomainStatic> for AsciiDomain {
#[inline]
fn from(value: AsciiDomainStatic) -> Self {
Self(value.0.to_owned())
}
}
impl PartialEq<&Self> for AsciiDomainStatic {
#[inline]
fn eq(&self, other: &&Self) -> bool {
*self == **other
}
}
impl PartialEq<AsciiDomainStatic> for &AsciiDomainStatic {
#[inline]
fn eq(&self, other: &AsciiDomainStatic) -> bool {
**self == *other
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Url(String);
impl AsRef<str> for Url {
#[inline]
fn as_ref(&self) -> &str {
self.0.as_str()
}
}
impl Borrow<str> for Url {
#[inline]
fn borrow(&self) -> &str {
self.0.as_str()
}
}
impl From<Url> for String {
#[inline]
fn from(value: Url) -> Self {
value.0
}
}
impl PartialEq<&Self> for Url {
#[inline]
fn eq(&self, other: &&Self) -> bool {
*self == **other
}
}
impl PartialEq<Url> for &Url {
#[inline]
fn eq(&self, other: &Url) -> bool {
**self == *other
}
}
impl FromStr for Url {
type Err = UrlErr;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
let violation = Cell::new(false);
Uri::options()
.syntax_violation_callback(Some(&|_| {
violation.set(true);
}))
.parse(s)
.map_err(|_e| UrlErr)
.and_then(|url| {
if violation.into_inner() {
Err(UrlErr)
} else {
Ok(Self(url.into()))
}
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RpId {
Domain(AsciiDomain),
StaticDomain(AsciiDomainStatic),
Url(Url),
}
impl RpId {
#[inline]
#[must_use]
pub const fn from_static_domain(domain: &'static str) -> Option<Self> {
if let Some(dom) = AsciiDomainStatic::new(domain) {
Some(Self::StaticDomain(dom))
} else {
None
}
}
fn validate_rp_id_hash<E>(&self, hash: &[u8]) -> Result<(), CeremonyErr<E>> {
if *hash == *Sha256::digest(self.as_ref()) {
Ok(())
} else {
Err(CeremonyErr::RpIdHashMismatch)
}
}
}
impl AsRef<str> for RpId {
#[inline]
fn as_ref(&self) -> &str {
match *self {
Self::Domain(ref dom) => dom.as_ref(),
Self::StaticDomain(dom) => dom.as_str(),
Self::Url(ref url) => url.as_ref(),
}
}
}
impl Borrow<str> for RpId {
#[inline]
fn borrow(&self) -> &str {
match *self {
Self::Domain(ref dom) => dom.borrow(),
Self::StaticDomain(dom) => dom.as_str(),
Self::Url(ref url) => url.borrow(),
}
}
}
impl From<RpId> for String {
#[inline]
fn from(value: RpId) -> Self {
match value {
RpId::Domain(dom) => dom.into(),
RpId::StaticDomain(dom) => dom.into(),
RpId::Url(url) => url.into(),
}
}
}
impl PartialEq<&Self> for RpId {
#[inline]
fn eq(&self, other: &&Self) -> bool {
*self == **other
}
}
impl PartialEq<RpId> for &RpId {
#[inline]
fn eq(&self, other: &RpId) -> bool {
**self == *other
}
}
impl From<AsciiDomain> for RpId {
#[inline]
fn from(value: AsciiDomain) -> Self {
Self::Domain(value)
}
}
impl From<AsciiDomainStatic> for RpId {
#[inline]
fn from(value: AsciiDomainStatic) -> Self {
Self::StaticDomain(value)
}
}
impl From<Url> for RpId {
#[inline]
fn from(value: Url) -> Self {
Self::Url(value)
}
}
impl TryFrom<String> for RpId {
type Error = RpIdErr;
#[inline]
fn try_from(value: String) -> Result<Self, Self::Error> {
Url::from_str(value.as_str())
.map(Self::Url)
.or_else(|_err| {
AsciiDomain::try_from(value)
.map(Self::Domain)
.map_err(|_e| RpIdErr)
})
}
}
#[derive(Clone, Copy, Debug, Default)]
pub enum Scheme<'a> {
None,
Any,
#[default]
Https,
Ssh,
Other(&'a str),
NoneHttps,
NoneSsh,
NoneOther(&'a str),
}
impl Scheme<'_> {
#[expect(clippy::unreachable, reason = "there is a bug, so we want to crash")]
fn is_equal_to_origin_scheme(self, other: Self) -> bool {
match self {
Self::None => matches!(other, Self::None),
Self::Any => true,
Self::Https => matches!(other, Self::Https),
Self::Ssh => matches!(other, Self::Ssh),
Self::Other(scheme) => match other {
Self::None => false,
Self::Any | Self::NoneHttps | Self::NoneSsh | Self::NoneOther(_) => {
unreachable!("there is a bug in DomainOrigin::try_from")
}
Self::Https => scheme == "https",
Self::Ssh => scheme == "ssh",
Self::Other(scheme_other) => scheme == scheme_other,
},
Self::NoneHttps => match other {
Self::None | Self::Https => true,
Self::Ssh | Self::Other(_) => false,
Self::Any | Self::NoneHttps | Self::NoneSsh | Self::NoneOther(_) => {
unreachable!("there is a bug in DomainOrigin::try_from")
}
},
Self::NoneSsh => match other {
Self::None | Self::Ssh => true,
Self::Any | Self::NoneHttps | Self::NoneSsh | Self::NoneOther(_) => {
unreachable!("there is a bug in DomainOrigin::try_from")
}
Self::Https | Self::Other(_) => false,
},
Self::NoneOther(scheme) => match other {
Self::None => true,
Self::Any | Self::NoneHttps | Self::NoneSsh | Self::NoneOther(_) => {
unreachable!("there is a bug in DomainOrigin::try_from")
}
Self::Https => scheme == "https",
Self::Ssh => scheme == "ssh",
Self::Other(scheme_other) => scheme == scheme_other,
},
}
}
}
impl<'a: 'b, 'b> TryFrom<&'a str> for Scheme<'b> {
type Error = SchemeParseErr;
#[inline]
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
match value {
"" => Err(SchemeParseErr),
"https" => Ok(Self::Https),
"ssh" => Ok(Self::Ssh),
_ => Ok(Self::Other(value)),
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub enum Port {
#[default]
None,
Any,
Val(u16),
NoneVal(u16),
}
impl Port {
#[expect(clippy::unreachable, reason = "there is a bug, so we want to crash")]
fn is_equal_to_origin_port(self, other: Self) -> bool {
match self {
Self::None => matches!(other, Self::None),
Self::Any => true,
Self::Val(port) => match other {
Self::None => false,
Self::Any | Self::NoneVal(_) => {
unreachable!("there is a bug in DomainOrigin::try_from")
}
Self::Val(port_other) => port == port_other,
},
Self::NoneVal(port) => match other {
Self::None => true,
Self::Any | Self::NoneVal(_) => {
unreachable!("there is a bug in DomainOrigin::try_from")
}
Self::Val(port_other) => port == port_other,
},
}
}
}
impl FromStr for Port {
type Err = PortParseErr;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.parse().map_err(PortParseErr::ParseInt).and_then(|port| {
if s.len()
== match port {
..=9 => 1,
10..=99 => 2,
100..=999 => 3,
1_000..=9_999 => 4,
10_000.. => 5,
}
{
Ok(Self::Val(port))
} else {
Err(PortParseErr::NotCanonical)
}
})
}
}
#[derive(Clone, Copy, Debug)]
pub struct DomainOrigin<'a, 'b> {
pub scheme: Scheme<'a>,
pub host: &'b str,
pub port: Port,
}
impl<'b> DomainOrigin<'_, 'b> {
#[must_use]
#[inline]
pub const fn new<'c: 'b>(host: &'c str) -> Self {
Self {
scheme: Scheme::Https,
host,
port: Port::None,
}
}
#[must_use]
#[inline]
pub const fn new_ignore_port<'c: 'b>(host: &'c str) -> Self {
Self {
scheme: Scheme::Https,
host,
port: Port::Any,
}
}
}
impl PartialEq<Origin<'_>> for DomainOrigin<'_, '_> {
#[inline]
fn eq(&self, other: &Origin<'_>) -> bool {
DomainOrigin::try_from(other.0.as_ref()).is_ok_and(|dom| {
self.scheme.is_equal_to_origin_scheme(dom.scheme)
&& self.host == dom.host
&& self.port.is_equal_to_origin_port(dom.port)
})
}
}
impl PartialEq<Origin<'_>> for &DomainOrigin<'_, '_> {
#[inline]
fn eq(&self, other: &Origin<'_>) -> bool {
**self == *other
}
}
impl PartialEq<&Origin<'_>> for DomainOrigin<'_, '_> {
#[inline]
fn eq(&self, other: &&Origin<'_>) -> bool {
*self == **other
}
}
impl PartialEq<DomainOrigin<'_, '_>> for Origin<'_> {
#[inline]
fn eq(&self, other: &DomainOrigin<'_, '_>) -> bool {
*other == *self
}
}
impl PartialEq<DomainOrigin<'_, '_>> for &Origin<'_> {
#[inline]
fn eq(&self, other: &DomainOrigin<'_, '_>) -> bool {
*other == **self
}
}
impl PartialEq<&DomainOrigin<'_, '_>> for Origin<'_> {
#[inline]
fn eq(&self, other: &&DomainOrigin<'_, '_>) -> bool {
**other == *self
}
}
impl<'a: 'b + 'c, 'b, 'c> TryFrom<&'a str> for DomainOrigin<'b, 'c> {
type Error = DomainOriginParseErr;
#[inline]
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
match value.split_once("://") {
None => Ok((Scheme::None, value)),
Some((poss_scheme, rem)) => Scheme::try_from(poss_scheme)
.map_err(DomainOriginParseErr::Scheme)
.map(|scheme| (scheme, rem)),
}
.and_then(|(scheme, rem)| {
rem.split_once(':')
.map_or_else(
|| Ok((rem, Port::None)),
|(rem2, poss_port)| {
Port::from_str(poss_port)
.map_err(DomainOriginParseErr::Port)
.map(|port| (rem2, port))
},
)
.map(|(host, port)| Self { scheme, host, port })
})
}
}
#[derive(Clone, Debug)]
pub struct PublicKeyCredentialDescriptor<T> {
pub id: CredentialId<T>,
pub transports: AuthTransports,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum UserVerificationRequirement {
Required,
Discouraged,
Preferred,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PublicKeyCredentialHint {
SecurityKey,
ClientDevice,
Hybrid,
}
impl PublicKeyCredentialHint {
const fn is_eq(self, other: Self) -> bool {
match self {
Self::SecurityKey => matches!(other, Self::SecurityKey),
Self::ClientDevice => matches!(other, Self::ClientDevice),
Self::Hybrid => matches!(other, Self::Hybrid),
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Hints([Option<PublicKeyCredentialHint>; 3]);
impl Hints {
pub const EMPTY: Self = Self([None; 3]);
#[inline]
#[must_use]
pub const fn add(mut self, hint: PublicKeyCredentialHint) -> Self {
let mut vals = self.0.as_mut_slice();
while let [ref mut first, ref mut rem @ ..] = *vals {
match *first {
None => {
*first = Some(hint);
return self;
}
Some(h) => {
if h.is_eq(hint) {
return self;
}
}
}
vals = rem;
}
self
}
#[inline]
#[must_use]
pub const fn first(self) -> Option<PublicKeyCredentialHint> {
self.0[0]
}
#[inline]
#[must_use]
pub const fn second(self) -> Option<PublicKeyCredentialHint> {
self.0[1]
}
#[inline]
#[must_use]
pub const fn third(self) -> Option<PublicKeyCredentialHint> {
self.0[2]
}
#[expect(
clippy::arithmetic_side_effects,
clippy::as_conversions,
reason = "comment justifies correctness"
)]
#[inline]
#[must_use]
pub const fn count(self) -> u8 {
self.first().is_some() as u8 + self.second().is_some() as u8 + self.third().is_some() as u8
}
#[inline]
#[must_use]
pub const fn is_empty(self) -> bool {
self.count() == 0
}
#[inline]
#[must_use]
pub const fn contains(self, hint: PublicKeyCredentialHint) -> bool {
let mut vals = self.0.as_slice();
while let [ref first, ref rem @ ..] = *vals {
match *first {
None => return false,
Some(h) => {
if h.is_eq(hint) {
return true;
}
}
}
vals = rem;
}
false
}
#[inline]
#[must_use]
pub const fn contains_cross_platform_hints(self) -> bool {
let mut vals = self.0.as_slice();
while let [ref first, ref rem @ ..] = *vals {
match *first {
None => return false,
Some(h) => {
if matches!(
h,
PublicKeyCredentialHint::SecurityKey | PublicKeyCredentialHint::Hybrid
) {
return true;
}
}
}
vals = rem;
}
false
}
#[inline]
#[must_use]
pub const fn contains_platform_hints(self) -> bool {
let mut vals = self.0.as_slice();
while let [ref first, ref rem @ ..] = *vals {
match *first {
None => return false,
Some(h) => {
if h.is_eq(PublicKeyCredentialHint::ClientDevice) {
return true;
}
}
}
vals = rem;
}
false
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExtensionReq {
Require,
Allow,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExtensionInfo {
RequireEnforceValue,
RequireDontEnforceValue,
AllowEnforceValue,
AllowDontEnforceValue,
}
impl Display for ExtensionInfo {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(match *self {
Self::RequireEnforceValue => "require the corresponding extension response and enforce its value",
Self::RequireDontEnforceValue => "require the corresponding extension response but don't enforce its value",
Self::AllowEnforceValue => "don't require the corresponding extension response; but if sent, enforce its value",
Self::AllowDontEnforceValue => "don't require the corresponding extension response; and if sent, don't enforce its value",
})
}
}
#[expect(clippy::doc_markdown, reason = "false positive")]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum CredentialMediationRequirement {
#[default]
Required,
Conditional,
}
pub trait Credentials: Sized {
type Credential;
#[inline]
#[must_use]
fn new() -> Self {
Self::with_capacity(0)
}
fn with_capacity(capacity: usize) -> Self;
fn push(&mut self, cred: Self::Credential) -> bool;
fn len(&self) -> usize;
#[inline]
fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<T> Credentials for Vec<T> {
type Credential = T;
#[inline]
fn with_capacity(capacity: usize) -> Self {
Self::with_capacity(capacity)
}
#[inline]
fn push(&mut self, cred: Self::Credential) -> bool {
self.push(cred);
true
}
#[inline]
fn len(&self) -> usize {
self.len()
}
}
struct CeremonyOptions<'origins, 'top_origins, O, T> {
allowed_origins: &'origins [O],
allowed_top_origins: Option<&'top_origins [T]>,
backup_requirement: BackupReq,
#[cfg(feature = "serde_relaxed")]
client_data_json_relaxed: bool,
}
impl<'o, 't, O, T> From<&RegistrationVerificationOptions<'o, 't, O, T>>
for CeremonyOptions<'o, 't, O, T>
{
fn from(value: &RegistrationVerificationOptions<'o, 't, O, T>) -> Self {
Self {
allowed_origins: value.allowed_origins,
allowed_top_origins: value.allowed_top_origins,
backup_requirement: value.backup_requirement,
#[cfg(feature = "serde_relaxed")]
client_data_json_relaxed: value.client_data_json_relaxed,
}
}
}
trait Ceremony<const USER_LEN: usize, const DISCOVERABLE: bool> {
type R: Response;
fn rand_challenge(&self) -> SentChallenge;
#[cfg(not(feature = "serializable_server_state"))]
fn expiry(&self) -> Instant;
#[cfg(feature = "serializable_server_state")]
fn expiry(&self) -> SystemTime;
fn user_verification(&self) -> UserVerificationRequirement;
#[expect(
clippy::type_complexity,
reason = "type aliases with bounds are even more problematic at least until lazy_type_alias is stable"
)]
#[expect(clippy::too_many_lines, reason = "102 lines is fine")]
fn partial_validate<'a, O: PartialEq<Origin<'a>>, T: PartialEq<Origin<'a>>>(
&self,
rp_id: &RpId,
resp: &'a Self::R,
key: <<Self::R as Response>::Auth as AuthResponse>::CredKey<'_>,
options: &CeremonyOptions<'_, '_, O, T>,
) -> Result<
<<Self::R as Response>::Auth as AuthResponse>::Auth<'a>,
CeremonyErr<
<<<Self::R as Response>::Auth as AuthResponse>::Auth<'a> as AuthDataContainer<'a>>::Err,
>,
> {
#[cfg(not(feature = "serializable_server_state"))]
let active = self.expiry() >= Instant::now();
#[cfg(feature = "serializable_server_state")]
let active = self.expiry() >= SystemTime::now();
if active {
#[cfg(feature = "serde_relaxed")]
let relaxed = options.client_data_json_relaxed;
#[cfg(not(feature = "serde_relaxed"))]
let relaxed = false;
resp.auth()
.parse_data_and_verify_sig(key, relaxed)
.map_err(CeremonyErr::AuthResp)
.and_then(|(client_data_json, auth_response)| {
if options.allowed_origins.is_empty() {
if match *rp_id {
RpId::Domain(ref dom) => {
DomainOrigin::new(dom.as_ref()) == client_data_json.origin
}
RpId::Url(ref url) => url == client_data_json.origin,
RpId::StaticDomain(dom) => {
DomainOrigin::new(dom.0) == client_data_json.origin
}
} {
Ok(())
} else {
Err(CeremonyErr::OriginMismatch)
}
} else {
options
.allowed_origins
.iter()
.find(|o| **o == client_data_json.origin)
.ok_or(CeremonyErr::OriginMismatch)
.map(|_| ())
}
.and_then(|()| {
match options.allowed_top_origins {
None => {
if client_data_json.cross_origin {
Err(CeremonyErr::CrossOrigin)
} else if client_data_json.top_origin.is_some() {
Err(CeremonyErr::TopOriginMismatch)
} else {
Ok(())
}
}
Some(top_origins) => client_data_json.top_origin.map_or(Ok(()), |t| {
top_origins
.iter()
.find(|top| **top == t)
.ok_or(CeremonyErr::TopOriginMismatch)
.map(|_| ())
}),
}
.and_then(|()| {
if self.rand_challenge() == client_data_json.challenge {
let auth_data = auth_response.authenticator_data();
rp_id
.validate_rp_id_hash(auth_data.rp_hash())
.and_then(|()| {
let flag = auth_data.flag();
if flag.user_verified
|| !matches!(
self.user_verification(),
UserVerificationRequirement::Required
)
{
match options.backup_requirement {
BackupReq::None => Ok(()),
BackupReq::NotEligible => {
if matches!(flag.backup, Backup::NotEligible) {
Ok(())
} else {
Err(CeremonyErr::BackupEligible)
}
}
BackupReq::Eligible => {
if matches!(flag.backup, Backup::NotEligible) {
Err(CeremonyErr::BackupNotEligible)
} else {
Ok(())
}
}
BackupReq::EligibleNotExists => {
if matches!(flag.backup, Backup::Eligible) {
Ok(())
} else {
Err(CeremonyErr::BackupExists)
}
}
BackupReq::Exists => {
if matches!(flag.backup, Backup::Exists) {
Ok(())
} else {
Err(CeremonyErr::BackupDoesNotExist)
}
}
}
} else {
Err(CeremonyErr::UserNotVerified)
}
})
.map(|()| auth_response)
} else {
Err(CeremonyErr::ChallengeMismatch)
}
})
})
})
} else {
Err(CeremonyErr::Timeout)
}
}
}
pub trait TimedCeremony {
#[cfg_attr(docsrs, doc(auto_cfg = false))]
#[cfg(any(doc, not(feature = "serializable_server_state")))]
fn expiration(&self) -> Instant;
#[cfg(all(not(doc), feature = "serializable_server_state"))]
fn expiration(&self) -> SystemTime;
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PrfInput<'first, 'second> {
pub first: &'first [u8],
pub second: Option<&'second [u8]>,
}
impl<'first, 'second> PrfInput<'first, 'second> {
#[inline]
#[must_use]
pub const fn with_first<'a: 'first>(first: &'a [u8]) -> Self {
Self {
first,
second: None,
}
}
#[inline]
#[must_use]
pub const fn with_two<'a: 'first, 'b: 'second>(first: &'a [u8], second: &'b [u8]) -> Self {
Self {
first,
second: Some(second),
}
}
}
pub const FIVE_MINUTES: NonZeroU32 = NonZeroU32::new(300_000).unwrap();