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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Types for CTAP2.
//!
//! Note that all ctap2::Authenticators automatically implement RPC with [`Request`] and
//! [`Response`].
use bitflags::bitflags;
use cbor_smol::cbor_deserialize;
use serde::{Deserialize, Serialize};

use crate::{sizes::*, Bytes, Vec};

pub use crate::operation::{Operation, VendorOperation};

pub mod client_pin;
pub mod credential_management;
pub mod get_assertion;
pub mod get_info;
pub mod large_blobs;
pub mod make_credential;

pub type Result<T> = core::result::Result<T, Error>;

#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
#[allow(clippy::large_enum_variant)]
// clippy says...large size difference
/// Enum of all CTAP2 requests.
pub enum Request<'a> {
    // 0x1
    MakeCredential(make_credential::Request<'a>),
    // 0x2
    GetAssertion(get_assertion::Request<'a>),
    // 0x8
    GetNextAssertion,
    // 0x4
    GetInfo,
    // 0x6
    ClientPin(client_pin::Request<'a>),
    // 0x7
    Reset,
    // 0xA
    CredentialManagement(credential_management::Request<'a>),
    // 0xB
    Selection,
    // 0xC
    LargeBlobs(large_blobs::Request<'a>),
    // vendor, to be embellished
    // Q: how to handle the associated CBOR structures
    Vendor(crate::operation::VendorOperation),
}

pub enum CtapMappingError {
    InvalidCommand(u8),
    ParsingError(cbor_smol::Error),
}

impl From<CtapMappingError> for Error {
    fn from(mapping_error: CtapMappingError) -> Error {
        match mapping_error {
            CtapMappingError::InvalidCommand(_cmd) => Error::InvalidCommand,
            CtapMappingError::ParsingError(cbor_error) => match cbor_error {
                cbor_smol::Error::SerdeMissingField => Error::MissingParameter,
                _ => Error::InvalidCbor,
            },
        }
    }
}

impl<'a> Request<'a> {
    /// Deserialize from CBOR where the first byte denotes the operation.
    #[inline(never)]
    pub fn deserialize(data: &'a [u8]) -> Result<Self> {
        if data.is_empty() {
            return Err(
                CtapMappingError::ParsingError(cbor_smol::Error::DeserializeUnexpectedEnd).into(),
            );
        }

        let (&op, data) = data.split_first().ok_or(CtapMappingError::ParsingError(
            cbor_smol::Error::DeserializeUnexpectedEnd,
        ))?;

        let operation = Operation::try_from(op).map_err(|_| {
            debug_now!("invalid operation {}", op);
            CtapMappingError::InvalidCommand(op)
        })?;

        info!("deser {:?}", operation);
        Ok(match operation {
            Operation::MakeCredential => Request::MakeCredential(
                cbor_deserialize(data).map_err(CtapMappingError::ParsingError)?,
            ),

            Operation::GetAssertion => Request::GetAssertion(
                cbor_deserialize(data).map_err(CtapMappingError::ParsingError)?,
            ),

            Operation::GetNextAssertion => Request::GetNextAssertion,

            Operation::CredentialManagement | Operation::PreviewCredentialManagement => {
                Request::CredentialManagement(
                    cbor_deserialize(data).map_err(CtapMappingError::ParsingError)?,
                )
            }

            Operation::Reset => Request::Reset,

            Operation::Selection => Request::Selection,

            Operation::GetInfo => Request::GetInfo,

            Operation::ClientPin => {
                Request::ClientPin(cbor_deserialize(data).map_err(CtapMappingError::ParsingError)?)
            }

            Operation::LargeBlobs => {
                Request::LargeBlobs(cbor_deserialize(data).map_err(CtapMappingError::ParsingError)?)
            }

            // NB: FIDO Alliance "stole" 0x40 and 0x41, so these are not available
            Operation::Vendor(vendor_operation) => Request::Vendor(vendor_operation),

            Operation::BioEnrollment | Operation::PreviewBioEnrollment | Operation::Config => {
                debug_now!("unhandled CBOR operation {:?}", operation);
                return Err(CtapMappingError::InvalidCommand(op).into());
            }
        })
    }
}

#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
/// Enum of all CTAP2 responses.
#[allow(clippy::large_enum_variant)]
pub enum Response {
    MakeCredential(make_credential::Response),
    GetAssertion(get_assertion::Response),
    GetNextAssertion(get_assertion::Response),
    GetInfo(get_info::Response),
    ClientPin(client_pin::Response),
    Reset,
    Selection,
    CredentialManagement(credential_management::Response),
    LargeBlobs(large_blobs::Response),
    // Q: how to handle the associated CBOR structures
    Vendor,
}

impl Response {
    #[inline(never)]
    pub fn serialize<const N: usize>(&self, buffer: &mut Vec<u8, N>) {
        buffer.resize_default(buffer.capacity()).ok();
        let (status, data) = buffer.split_first_mut().unwrap();
        use cbor_smol::cbor_serialize;
        use Response::*;
        let outcome = match self {
            GetInfo(response) => cbor_serialize(response, data),
            MakeCredential(response) => cbor_serialize(response, data),
            ClientPin(response) => cbor_serialize(response, data),
            GetAssertion(response) | GetNextAssertion(response) => cbor_serialize(response, data),
            CredentialManagement(response) => cbor_serialize(response, data),
            LargeBlobs(response) => cbor_serialize(response, data),
            Reset | Selection | Vendor => Ok([].as_slice()),
        };
        if let Ok(slice) = outcome {
            *status = 0;
            // Instead of an empty CBOR map (0xA0), we return an empty response
            if slice == [0xA0] {
                buffer.resize_default(1).ok();
            } else {
                let l = slice.len();
                buffer.resize_default(l + 1).ok();
            }
        } else {
            *status = Error::Other as u8;
            buffer.resize_default(1).ok();
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AuthenticatorOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rk: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub up: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Note: This flag asks to perform UV *within the authenticator*,
    /// for instance with biometrics or on-device PIN entry,
    /// use of pinAuth is implicit where required.
    pub uv: Option<bool>,
}

bitflags! {
    pub struct AuthenticatorDataFlags: u8 {
        const USER_PRESENCE = 1 << 0;
        const USER_VERIFIED = 1 << 2;
        const ATTESTED_CREDENTIAL_DATA = 1 << 6;
        const EXTENSION_DATA = 1 << 7;
    }
}

pub trait SerializeAttestedCredentialData {
    fn serialize(&self, buffer: &mut SerializedAuthenticatorData) -> Result<()>;
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AuthenticatorData<'a, A, E> {
    pub rp_id_hash: &'a [u8; 32],
    pub flags: AuthenticatorDataFlags,
    pub sign_count: u32,
    pub attested_credential_data: Option<A>,
    pub extensions: Option<E>,
}

pub type SerializedAuthenticatorData = Bytes<AUTHENTICATOR_DATA_LENGTH>;

// The reason for this non-use of CBOR is for compatibility with
// FIDO U2F authentication signatures.
impl<'a, A: SerializeAttestedCredentialData, E: serde::Serialize> AuthenticatorData<'a, A, E> {
    #[inline(never)]
    pub fn serialize(&self) -> Result<SerializedAuthenticatorData> {
        let mut bytes = SerializedAuthenticatorData::new();

        // 32 bytes, the RP id's hash
        bytes
            .extend_from_slice(self.rp_id_hash)
            .map_err(|_| Error::Other)?;
        // flags
        bytes.push(self.flags.bits()).map_err(|_| Error::Other)?;
        // signature counts as 32-bit unsigned big-endian integer.
        bytes
            .extend_from_slice(&self.sign_count.to_be_bytes())
            .map_err(|_| Error::Other)?;

        // the attested credential data
        if let Some(attested_credential_data) = &self.attested_credential_data {
            attested_credential_data.serialize(&mut bytes)?;
        }

        // the extensions data
        if let Some(extensions) = self.extensions.as_ref() {
            cbor_smol::cbor_serialize_extending_bytes(extensions, &mut bytes)
                .map_err(|_| Error::Other)?;
        }

        Ok(bytes)
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Error {
    Success = 0x00,
    InvalidCommand = 0x01,
    InvalidParameter = 0x02,
    InvalidLength = 0x03,
    InvalidSeq = 0x04,
    Timeout = 0x05,
    ChannelBusy = 0x06,
    LockRequired = 0x0A,
    InvalidChannel = 0x0B,
    CborUnexpectedType = 0x11,
    InvalidCbor = 0x12,
    MissingParameter = 0x14,
    LimitExceeded = 0x15,
    UnsupportedExtension = 0x16,
    FingerprintDatabaseFull = 0x17,
    LargeBlobStorageFull = 0x18,
    CredentialExcluded = 0x19,
    Processing = 0x21,
    InvalidCredential = 0x22,
    UserActionPending = 0x23,
    OperationPending = 0x24,
    NoOperations = 0x25,
    UnsupportedAlgorithm = 0x26,
    OperationDenied = 0x27,
    KeyStoreFull = 0x28,
    NotBusy = 0x29,
    NoOperationPending = 0x2A,
    UnsupportedOption = 0x2B,
    InvalidOption = 0x2C,
    KeepaliveCancel = 0x2D,
    NoCredentials = 0x2E,
    UserActionTimeout = 0x2F,
    NotAllowed = 0x30,
    PinInvalid = 0x31,
    PinBlocked = 0x32,
    PinAuthInvalid = 0x33,
    PinAuthBlocked = 0x34,
    PinNotSet = 0x35,
    PinRequired = 0x36,
    PinPolicyViolation = 0x37,
    PinTokenExpired = 0x38,
    RequestTooLarge = 0x39,
    ActionTimeout = 0x3A,
    UpRequired = 0x3B,
    UvBlocked = 0x3C,
    IntegrityFailure = 0x3D,
    InvalidSubcommand = 0x3E,
    UvInvalid = 0x3F,
    UnauthorizedPermission = 0x40,
    Other = 0x7F,
    SpecLast = 0xDF,
    ExtensionFirst = 0xE0,
    ExtensionLast = 0xEF,
    VendorFirst = 0xF0,
    VendorLast = 0xFF,
}

/// CTAP2 authenticator API
///
/// Note that all Authenticators automatically implement [`crate::Rpc`] with [`Request`] and
/// [`Response`].
pub trait Authenticator {
    fn get_info(&mut self) -> get_info::Response;
    fn make_credential(
        &mut self,
        request: &make_credential::Request,
    ) -> Result<make_credential::Response>;
    fn get_assertion(
        &mut self,
        request: &get_assertion::Request,
    ) -> Result<get_assertion::Response>;
    fn get_next_assertion(&mut self) -> Result<get_assertion::Response>;
    fn reset(&mut self) -> Result<()>;
    fn client_pin(&mut self, request: &client_pin::Request) -> Result<client_pin::Response>;
    fn credential_management(
        &mut self,
        request: &credential_management::Request,
    ) -> Result<credential_management::Response>;
    fn selection(&mut self) -> Result<()>;
    fn vendor(&mut self, op: VendorOperation) -> Result<()>;

    // Optional extensions
    fn large_blobs(&mut self, request: &large_blobs::Request) -> Result<large_blobs::Response> {
        let _ = request;
        Err(Error::InvalidCommand)
    }

    /// Dispatches the enum of possible requests into the appropriate trait method.
    #[inline(never)]
    fn call_ctap2(&mut self, request: &Request) -> Result<Response> {
        match request {
            // 0x4
            Request::GetInfo => {
                debug_now!("CTAP2.GI");
                Ok(Response::GetInfo(self.get_info()))
            }

            // 0x2
            Request::MakeCredential(request) => {
                debug_now!("CTAP2.MC");
                Ok(Response::MakeCredential(
                    self.make_credential(request).map_err(|e| {
                        debug!("error: {:?}", e);
                        e
                    })?,
                ))
            }

            // 0x1
            Request::GetAssertion(request) => {
                debug_now!("CTAP2.GA");
                Ok(Response::GetAssertion(
                    self.get_assertion(request).map_err(|e| {
                        debug!("error: {:?}", e);
                        e
                    })?,
                ))
            }

            // 0x8
            Request::GetNextAssertion => {
                debug_now!("CTAP2.GNA");
                Ok(Response::GetNextAssertion(
                    self.get_next_assertion().map_err(|e| {
                        debug!("error: {:?}", e);
                        e
                    })?,
                ))
            }

            // 0x7
            Request::Reset => {
                debug_now!("CTAP2.RST");
                self.reset().map_err(|e| {
                    debug!("error: {:?}", e);
                    e
                })?;
                Ok(Response::Reset)
            }

            // 0x6
            Request::ClientPin(request) => {
                debug_now!("CTAP2.PIN");
                Ok(Response::ClientPin(self.client_pin(request).map_err(
                    |e| {
                        debug!("error: {:?}", e);
                        e
                    },
                )?))
            }

            // 0xA
            Request::CredentialManagement(request) => {
                debug_now!("CTAP2.CM");
                Ok(Response::CredentialManagement(
                    self.credential_management(request).map_err(|e| {
                        debug!("error: {:?}", e);
                        e
                    })?,
                ))
            }

            // 0xB
            Request::Selection => {
                debug_now!("CTAP2.SEL");
                self.selection().map_err(|e| {
                    debug!("error: {:?}", e);
                    e
                })?;
                Ok(Response::Selection)
            }

            // 0xC
            Request::LargeBlobs(request) => {
                debug_now!("CTAP2.LB");
                Ok(Response::LargeBlobs(self.large_blobs(request).map_err(
                    |e| {
                        debug!("error: {:?}", e);
                        e
                    },
                )?))
            }

            // Not stable
            Request::Vendor(op) => {
                debug_now!("CTAP2.V");
                self.vendor(*op).map_err(|e| {
                    debug!("error: {:?}", e);
                    e
                })?;
                Ok(Response::Vendor)
            }
        }
    }
}

impl<'a, A: Authenticator> crate::Rpc<Error, Request<'a>, Response> for A {
    /// Dispatches the enum of possible requests into the appropriate trait method.
    #[inline(never)]
    fn call(&mut self, request: &Request) -> Result<Response> {
        self.call_ctap2(request)
    }
}