Skip to main content

structured_webauthn/request/auth/
ser_server_state.rs

1use super::{
2    super::super::bin::{
3        Decode, DecodeBuffer, EncDecErr, Encode, EncodeBuffer, EncodeBufferFallible,
4    },
5    AuthenticationServerState, CredInfo, CredentialId, DiscoverableAuthenticationServerState,
6    ExtensionReq, NonDiscoverableAuthenticationServerState, SentChallenge,
7    ServerCredSpecificExtensionInfo, ServerExtensionInfo, ServerPrfInfo,
8    SignatureCounterEnforcement, UserVerificationRequirement,
9};
10#[cfg(doc)]
11use super::{AllowedCredential, NonDiscoverableCredentialRequestOptions};
12use core::{
13    error::Error,
14    fmt::{self, Display, Formatter},
15};
16#[cfg(doc)]
17use std::time::UNIX_EPOCH;
18use std::time::{SystemTime, SystemTimeError};
19impl EncodeBuffer for ServerPrfInfo {
20    fn encode_into_buffer(&self, buffer: &mut Vec<u8>) {
21        match *self {
22            Self::None => 0u8.encode_into_buffer(buffer),
23            Self::One(req) => {
24                1u8.encode_into_buffer(buffer);
25                req.encode_into_buffer(buffer);
26            }
27            Self::Two(req) => {
28                2u8.encode_into_buffer(buffer);
29                req.encode_into_buffer(buffer);
30            }
31        }
32    }
33}
34impl<'a> DecodeBuffer<'a> for ServerPrfInfo {
35    type Err = EncDecErr;
36    fn decode_from_buffer(data: &mut &'a [u8]) -> Result<Self, Self::Err> {
37        u8::decode_from_buffer(data).and_then(|val| match val {
38            0 => Ok(Self::None),
39            1 => ExtensionReq::decode_from_buffer(data).map(Self::One),
40            2 => ExtensionReq::decode_from_buffer(data).map(Self::Two),
41            _ => Err(EncDecErr),
42        })
43    }
44}
45impl EncodeBuffer for ServerCredSpecificExtensionInfo {
46    fn encode_into_buffer(&self, buffer: &mut Vec<u8>) {
47        self.prf.encode_into_buffer(buffer);
48    }
49}
50impl<'a> DecodeBuffer<'a> for ServerCredSpecificExtensionInfo {
51    type Err = EncDecErr;
52    fn decode_from_buffer(data: &mut &'a [u8]) -> Result<Self, Self::Err> {
53        ServerPrfInfo::decode_from_buffer(data).map(|prf| Self { prf })
54    }
55}
56impl EncodeBuffer for CredInfo {
57    fn encode_into_buffer(&self, buffer: &mut Vec<u8>) {
58        CredentialId::<&[u8]>::from(&self.id).encode_into_buffer(buffer);
59        self.ext.encode_into_buffer(buffer);
60    }
61}
62impl<'a> DecodeBuffer<'a> for CredInfo {
63    type Err = EncDecErr;
64    fn decode_from_buffer(data: &mut &'a [u8]) -> Result<Self, Self::Err> {
65        CredentialId::<Box<[u8]>>::decode_from_buffer(data).and_then(|id| {
66            ServerCredSpecificExtensionInfo::decode_from_buffer(data).map(|ext| Self { id, ext })
67        })
68    }
69}
70impl EncodeBuffer for ServerExtensionInfo {
71    fn encode_into_buffer(&self, buffer: &mut Vec<u8>) {
72        self.prf.encode_into_buffer(buffer);
73    }
74}
75impl<'a> DecodeBuffer<'a> for ServerExtensionInfo {
76    type Err = EncDecErr;
77    fn decode_from_buffer(data: &mut &'a [u8]) -> Result<Self, Self::Err> {
78        ServerPrfInfo::decode_from_buffer(data).map(|prf| Self { prf })
79    }
80}
81impl EncodeBuffer for SignatureCounterEnforcement {
82    fn encode_into_buffer(&self, buffer: &mut Vec<u8>) {
83        match *self {
84            Self::Fail => 0u8,
85            Self::Update => 1,
86            Self::Ignore => 2,
87        }
88        .encode_into_buffer(buffer);
89    }
90}
91impl<'a> DecodeBuffer<'a> for SignatureCounterEnforcement {
92    type Err = EncDecErr;
93    fn decode_from_buffer(data: &mut &'a [u8]) -> Result<Self, Self::Err> {
94        u8::decode_from_buffer(data).and_then(|val| match val {
95            0 => Ok(Self::Fail),
96            1 => Ok(Self::Update),
97            2 => Ok(Self::Ignore),
98            _ => Err(EncDecErr),
99        })
100    }
101}
102impl EncodeBufferFallible for &[CredInfo] {
103    type Err = EncDecErr;
104    /// # Errors
105    ///
106    /// Errors iff `self.len() > usize::from(u16::MAX)`.
107    fn encode_into_buffer(&self, buffer: &mut Vec<u8>) -> Result<(), EncDecErr> {
108        u16::try_from(self.len())
109            .map_err(|_e| EncDecErr)
110            .map(|len| {
111                len.encode_into_buffer(buffer);
112                self.iter().fold((), |(), val| {
113                    val.encode_into_buffer(buffer);
114                });
115            })
116    }
117}
118impl<'a> DecodeBuffer<'a> for Box<[CredInfo]> {
119    type Err = EncDecErr;
120    fn decode_from_buffer(data: &mut &'a [u8]) -> Result<Self, Self::Err> {
121        u16::decode_from_buffer(data).and_then(|len| {
122            let l = usize::from(len);
123            let mut creds = Vec::with_capacity(l);
124            while creds.len() < l {
125                creds.push(CredInfo::decode_from_buffer(data)?);
126            }
127            Ok(creds.into_boxed_slice())
128        })
129    }
130}
131impl EncodeBufferFallible for AuthenticationServerState {
132    type Err = SystemTimeError;
133    fn encode_into_buffer(&self, buffer: &mut Vec<u8>) -> Result<(), Self::Err> {
134        self.challenge.encode_into_buffer(buffer);
135        self.user_verification.encode_into_buffer(buffer);
136        self.extensions.encode_into_buffer(buffer);
137        self.expiration.encode_into_buffer(buffer)
138    }
139}
140impl Encode for DiscoverableAuthenticationServerState {
141    type Output<'a>
142        = Vec<u8>
143    where
144        Self: 'a;
145    type Err = SystemTimeError;
146    #[expect(
147        clippy::arithmetic_side_effects,
148        reason = "comment justifies correctness"
149    )]
150    #[inline]
151    fn encode(&self) -> Result<Self::Output<'_>, Self::Err> {
152        // Length of the anticipated most common output:
153        // * 16 for `SentChallenge`
154        // * 1 for `UserVerificationRequirement`
155        // * 1 or 2 for `ServerExtensionInfo`
156        // * 12 for `SystemTime`
157        // Clearly cannot overflow.
158        let mut buffer = Vec::with_capacity(
159            16 + 1 + 1 + usize::from(!matches!(self.0.extensions.prf, ServerPrfInfo::None)) + 12,
160        );
161        self.0.encode_into_buffer(&mut buffer).map(|()| buffer)
162    }
163}
164/// Error returned from [`NonDiscoverableAuthenticationServerState::encode`].
165#[derive(Debug)]
166pub enum EncodeNonDiscoverableAuthenticationServerStateErr {
167    /// Variant returned when
168    /// [`NonDiscoverableAuthenticationServerState::expiration`](../struct.AuthenticationServerState.html#method.expiration-1)
169    /// is before [`UNIX_EPOCH`].
170    SystemTime(SystemTimeError),
171    /// Variant returned when the corresponding [`NonDiscoverableCredentialRequestOptions::allow_credentials`] has more
172    /// than [`u16::MAX`] [`AllowedCredential`]s.
173    AllowedCredentialsCount,
174}
175impl Display for EncodeNonDiscoverableAuthenticationServerStateErr {
176    #[inline]
177    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
178        match *self {
179            Self::SystemTime(ref err) => err.fmt(f),
180            Self::AllowedCredentialsCount => {
181                f.write_str("there were more than 65,535 AllowedCredentials")
182            }
183        }
184    }
185}
186impl Error for EncodeNonDiscoverableAuthenticationServerStateErr {}
187impl Encode for NonDiscoverableAuthenticationServerState {
188    type Output<'a>
189        = Vec<u8>
190    where
191        Self: 'a;
192    type Err = EncodeNonDiscoverableAuthenticationServerStateErr;
193    #[inline]
194    fn encode(&self) -> Result<Self::Output<'_>, Self::Err> {
195        // Length of the anticipated most common output:
196        // * 16 for `SentChallenge`
197        // * 2 + Σ(2 + len(id_i) + (1|2)) from i = 1 to i = `self.allow_credentials.len()` where i is the
198        //   1-based index of the `AllowedCredential` and len(id_i) is the number of bytes that makes up
199        //   the ith `CredentialId`. Since `self.allow_credentials.len()` is inclusively between 1 and
200        //   65,535, the smallest this can be is 2 + 2 + 16 + 1 = 21; and the largest this can be is
201        //   2 + 65535(2 + 1023 + 2) = 67,304,447. We assume no credential-specific PRF is sent and the
202        //   the average length of the `CredentialId`s is 128.
203        // * 1 for `UserVerificationRequirement`
204        // * 1 or 2 for `ServerExtensionInfo` where we assume 1 is the most common
205        // * 12 for `SystemTime`
206        // This is just an estimate; thus we rely on wrapping arithmetic. If the actual needed capacity is too big,
207        // then a `panic` will happen anyway once we serialize the entire payload.
208        let mut buffer = Vec::with_capacity(
209            (16usize + 2 + 1 + 1 + 12)
210                .wrapping_add(self.allow_credentials.len().wrapping_mul(2 + 128 + 1)),
211        );
212        self.state
213            .encode_into_buffer(&mut buffer)
214            .map_err(EncodeNonDiscoverableAuthenticationServerStateErr::SystemTime)
215            .and_then(|()| {
216                self.allow_credentials
217                    .as_ref()
218                    .encode_into_buffer(&mut buffer)
219                    .map_err(|_e| {
220                        EncodeNonDiscoverableAuthenticationServerStateErr::AllowedCredentialsCount
221                    })
222                    .map(|()| buffer)
223            })
224    }
225}
226impl<'a> DecodeBuffer<'a> for AuthenticationServerState {
227    type Err = EncDecErr;
228    fn decode_from_buffer(data: &mut &'a [u8]) -> Result<Self, Self::Err> {
229        SentChallenge::decode_from_buffer(data).and_then(|challenge| {
230            UserVerificationRequirement::decode_from_buffer(data).and_then(|user_verification| {
231                ServerExtensionInfo::decode_from_buffer(data).and_then(|extensions| {
232                    if super::validate_discoverable_options_helper(extensions, user_verification) {
233                        SystemTime::decode_from_buffer(data).map(|expiration| Self {
234                            challenge,
235                            user_verification,
236                            extensions,
237                            expiration,
238                        })
239                    } else {
240                        Err(EncDecErr)
241                    }
242                })
243            })
244        })
245    }
246}
247/// Error returned from [`DiscoverableAuthenticationServerState::decode`].
248#[derive(Clone, Copy, Debug, Eq, PartialEq)]
249pub enum DecodeDiscoverableAuthenticationServerStateErr {
250    /// Variant returned when there was trailing data after decoding a [`DiscoverableAuthenticationServerState`].
251    TrailingData,
252    /// Variant returned for all other errors.
253    Other,
254}
255impl Display for DecodeDiscoverableAuthenticationServerStateErr {
256    #[inline]
257    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
258        f.write_str(match *self {
259            Self::TrailingData => {
260                "trailing data after decoding DiscoverableAuthenticationServerState"
261            }
262            Self::Other => "DiscoverableAuthenticationServerState could not be decoded",
263        })
264    }
265}
266impl Error for DecodeDiscoverableAuthenticationServerStateErr {}
267impl Decode for DiscoverableAuthenticationServerState {
268    type Input<'a> = &'a [u8];
269    type Err = DecodeDiscoverableAuthenticationServerStateErr;
270    #[inline]
271    fn decode(mut input: Self::Input<'_>) -> Result<Self, Self::Err> {
272        AuthenticationServerState::decode_from_buffer(&mut input)
273            .map_err(|_e| DecodeDiscoverableAuthenticationServerStateErr::Other)
274            .and_then(|state| {
275                if input.is_empty() {
276                    Ok(Self(state))
277                } else {
278                    Err(DecodeDiscoverableAuthenticationServerStateErr::TrailingData)
279                }
280            })
281    }
282}
283/// Error returned from [`NonDiscoverableAuthenticationServerState::decode`].
284#[derive(Clone, Copy, Debug, Eq, PartialEq)]
285pub enum DecodeNonDiscoverableAuthenticationServerStateErr {
286    /// Variant returned when there was trailing data after decoding a [`NonDiscoverableAuthenticationServerState`].
287    TrailingData,
288    /// Variant returned for all other errors.
289    Other,
290}
291impl Display for DecodeNonDiscoverableAuthenticationServerStateErr {
292    #[inline]
293    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
294        f.write_str(match *self {
295            Self::TrailingData => {
296                "trailing data after decoding NonDiscoverableAuthenticationServerState"
297            }
298            Self::Other => "NonDiscoverableAuthenticationServerState could not be decoded",
299        })
300    }
301}
302impl Error for DecodeNonDiscoverableAuthenticationServerStateErr {}
303impl Decode for NonDiscoverableAuthenticationServerState {
304    type Input<'a> = &'a [u8];
305    type Err = DecodeNonDiscoverableAuthenticationServerStateErr;
306    #[inline]
307    fn decode(mut input: Self::Input<'_>) -> Result<Self, Self::Err> {
308        AuthenticationServerState::decode_from_buffer(&mut input)
309            .map_err(|_e| DecodeNonDiscoverableAuthenticationServerStateErr::Other)
310            .and_then(|state| {
311                Box::decode_from_buffer(&mut input)
312                    .map_err(|_e| DecodeNonDiscoverableAuthenticationServerStateErr::Other)
313                    .and_then(|allow_credentials| {
314                        super::validate_non_discoverable_options_helper(
315                            state.user_verification,
316                            &allow_credentials,
317                        )
318                        .map_err(|_e| DecodeNonDiscoverableAuthenticationServerStateErr::Other)
319                        .and({
320                            if allow_credentials.is_empty() {
321                                Err(DecodeNonDiscoverableAuthenticationServerStateErr::Other)
322                            } else if input.is_empty() {
323                                Ok(Self {
324                                    state,
325                                    allow_credentials,
326                                })
327                            } else {
328                                Err(DecodeNonDiscoverableAuthenticationServerStateErr::TrailingData)
329                            }
330                        })
331                    })
332            })
333    }
334}