extern crate alloc;
#[cfg(test)]
mod tests;
#[cfg(doc)]
use super::{Challenge, LimitedVerificationParser};
use super::{
ClientDataJsonParser, CollectedClientData, Origin, SentChallenge,
ser::{
AuthenticationExtensionsPrfValues, AuthenticationExtensionsPrfValuesVisitor,
PRF_VALUES_FIELDS,
},
};
use alloc::borrow::Cow;
use core::{
fmt::{self, Formatter},
marker::PhantomData,
};
use serde::de::{Deserialize, Deserializer, Error, IgnoredAny, MapAccess, Unexpected, Visitor};
#[cfg(doc)]
use serde_json::de;
pub use serde_json::error::Category;
pub use serde_json::error::Error as SerdeJsonErr;
pub(super) struct RelaxedClientDataJsonParser<const REGISTRATION: bool>;
impl<const R: bool> ClientDataJsonParser for RelaxedClientDataJsonParser<R> {
type Err = SerdeJsonErr;
fn parse(json: &[u8]) -> Result<CollectedClientData<'_>, Self::Err> {
const BOM: [u8; 3] = [0xef, 0xbb, 0xbf];
serde_json::from_slice::<CDataJsonHelper<'_, R>>(json.split_at_checked(BOM.len()).map_or(
json,
|(bom, rem)| {
if bom == BOM { rem } else { json }
},
))
.map(|val| val.0)
}
fn get_sent_challenge(json: &[u8]) -> Result<SentChallenge, Self::Err> {
const BOM: [u8; 3] = [0xef, 0xbb, 0xbf];
serde_json::from_slice::<Chall>(json.split_at_checked(BOM.len()).map_or(
json,
|(bom, rem)| {
if bom == BOM { rem } else { json }
},
))
.map(|c| c.0)
}
}
struct Chall(SentChallenge);
impl<'de> Deserialize<'de> for Chall {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ChallVisitor;
impl<'d> Visitor<'d> for ChallVisitor {
type Value = Chall;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str("Chall")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'d>,
{
enum Field {
Challenge,
Other,
}
impl<'e> Deserialize<'e> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'e>,
{
struct FieldVisitor;
impl Visitor<'_> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(formatter, "'{CHALLENGE}'")
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
if v == b"challenge" {
Ok(Field::Challenge)
} else {
Ok(Field::Other)
}
}
}
deserializer.deserialize_bytes(FieldVisitor)
}
}
let mut chall = None;
while let Some(key) = map.next_key()? {
match key {
Field::Challenge => {
if chall.is_some() {
return Err(Error::duplicate_field(CHALLENGE));
}
chall = map.next_value().map(Some)?;
}
Field::Other => map.next_value::<IgnoredAny>().map(|_| ())?,
}
}
chall
.ok_or_else(|| Error::missing_field(CHALLENGE))
.map(Chall)
}
}
const FIELDS: &[&str; 1] = &[CHALLENGE];
deserializer.deserialize_struct("Chall", FIELDS, ChallVisitor)
}
}
const TYPE: &str = "type";
const CHALLENGE: &str = "challenge";
const ORIGIN: &str = "origin";
const CROSS_ORIGIN: &str = "crossOrigin";
const TOP_ORIGIN: &str = "topOrigin";
const FIELDS: &[&str; 5] = &[TYPE, CHALLENGE, ORIGIN, CROSS_ORIGIN, TOP_ORIGIN];
struct RelaxedHelper<'a, const REGISTRATION: bool>(PhantomData<fn() -> &'a ()>);
impl<'de: 'a, 'a, const R: bool> Visitor<'de> for RelaxedHelper<'a, R> {
type Value = CollectedClientData<'a>;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str("CollectedClientData")
}
#[expect(
clippy::too_many_lines,
reason = "don't want to move code to an outer scope"
)]
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
const CREATE: &str = "webauthn.create";
const GET: &str = "webauthn.get";
enum Field {
Type,
Challenge,
Origin,
CrossOrigin,
TopOrigin,
Other,
}
impl<'d> Deserialize<'d> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'d>,
{
struct FieldVisitor;
impl Visitor<'_> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(
formatter,
"'{TYPE}', '{CHALLENGE}', '{ORIGIN}', '{CROSS_ORIGIN}', or '{TOP_ORIGIN}'"
)
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match v {
b"type" => Ok(Field::Type),
b"challenge" => Ok(Field::Challenge),
b"origin" => Ok(Field::Origin),
b"crossOrigin" => Ok(Field::CrossOrigin),
b"topOrigin" => Ok(Field::TopOrigin),
_ => Ok(Field::Other),
}
}
}
deserializer.deserialize_bytes(FieldVisitor)
}
}
struct Type(bool);
impl<'d> Deserialize<'d> for Type {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'d>,
{
struct TypeVisitor;
impl Visitor<'_> for TypeVisitor {
type Value = Type;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(formatter, "'{CREATE}' or '{GET}'")
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match v {
b"webauthn.create" => Ok(Type(true)),
b"webauthn.get" => Ok(Type(false)),
_ => Err(Error::invalid_value(
Unexpected::Bytes(v),
&format!("'{CREATE}' or '{GET}'").as_str(),
)),
}
}
}
deserializer.deserialize_bytes(TypeVisitor)
}
}
struct OriginWrapper<'d>(Origin<'d>);
impl<'d: 'e, 'e> Deserialize<'d> for OriginWrapper<'e> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'d>,
{
struct OriginWrapperVisitor<'f>(PhantomData<fn() -> &'f ()>);
impl<'f: 'g, 'g> Visitor<'f> for OriginWrapperVisitor<'g> {
type Value = OriginWrapper<'g>;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str("OriginWrapper")
}
fn visit_borrowed_bytes<E>(self, v: &'f [u8]) -> Result<Self::Value, E>
where
E: Error,
{
Ok(OriginWrapper(Origin(String::from_utf8_lossy(v))))
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
Ok(OriginWrapper(Origin(Cow::Owned(
String::from_utf8_lossy(v.as_slice()).into_owned(),
))))
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_byte_buf(v.to_owned())
}
}
deserializer.deserialize_bytes(OriginWrapperVisitor(PhantomData))
}
}
let mut typ = false;
let mut chall = None;
let mut orig = None;
let mut cross = None;
let mut top_orig = None;
while let Some(key) = map.next_key()? {
match key {
Field::Type => {
if typ {
return Err(Error::duplicate_field(TYPE));
}
typ = map.next_value::<Type>().and_then(|v| {
if v.0 {
if R {
Ok(true)
} else {
Err(Error::invalid_value(Unexpected::Str(CREATE), &GET))
}
} else if R {
Err(Error::invalid_value(Unexpected::Str(GET), &CREATE))
} else {
Ok(true)
}
})?;
}
Field::Challenge => {
if chall.is_some() {
return Err(Error::duplicate_field(CHALLENGE));
}
chall = map.next_value().map(Some)?;
}
Field::Origin => {
if orig.is_some() {
return Err(Error::duplicate_field(ORIGIN));
}
orig = map.next_value::<OriginWrapper<'_>>().map(|o| Some(o.0))?;
}
Field::CrossOrigin => {
if cross.is_some() {
return Err(Error::duplicate_field(CROSS_ORIGIN));
}
cross = map.next_value().map(Some)?;
}
Field::TopOrigin => {
if top_orig.is_some() {
return Err(Error::duplicate_field(TOP_ORIGIN));
}
top_orig = map.next_value::<Option<OriginWrapper<'_>>>().map(Some)?;
}
Field::Other => map.next_value::<IgnoredAny>().map(|_| ())?,
}
}
if typ {
chall
.ok_or_else(|| Error::missing_field(CHALLENGE))
.and_then(|challenge| {
orig.ok_or_else(|| Error::missing_field(ORIGIN))
.map(|origin| CollectedClientData {
challenge,
origin,
cross_origin: cross.flatten().unwrap_or_default(),
top_origin: top_orig.flatten().map(|o| o.0),
})
})
} else {
Err(Error::missing_field(TYPE))
}
}
}
struct CDataJsonHelper<'a, const REGISTRATION: bool>(CollectedClientData<'a>);
impl<'de: 'a, 'a, const R: bool> Deserialize<'de> for CDataJsonHelper<'a, R> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer
.deserialize_struct(
"CollectedClientData",
FIELDS,
RelaxedHelper::<R>(PhantomData),
)
.map(Self)
}
}
pub(super) struct AuthenticationExtensionsPrfValuesRelaxed(pub AuthenticationExtensionsPrfValues);
impl<'de> Deserialize<'de> for AuthenticationExtensionsPrfValuesRelaxed {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer
.deserialize_struct(
"AuthenticationExtensionsPrfValuesRelaxed",
PRF_VALUES_FIELDS,
AuthenticationExtensionsPrfValuesVisitor::<true>,
)
.map(Self)
}
}