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
use crate::{
    ctap2::{
        commands::GetInfoResponse, ctap21_bio::BiometricAuthenticatorInfo,
        ctap21_cred::CredentialManagementAuthenticatorInfo, internal::CtapAuthenticatorVersion,
        Ctap20Authenticator,
    },
    transport::Token,
    ui::UiCallback,
};
#[cfg(any(all(doc, not(doctest)), feature = "ctap2-management"))]
use crate::{
    ctap2::{
        commands::{
            BioEnrollmentRequest, ConfigRequest, ConfigSubCommand, CredSubCommand,
            CredentialManagementRequest, Permissions, PublicKeyCredentialDescriptorCM,
            SetMinPinLengthParams, UserCM,
        },
        ctap21_cred::CredentialManagementAuthenticatorSupport,
        CredentialManagementAuthenticator,
    },
    error::WebauthnCError,
};
use std::ops::{Deref, DerefMut};
#[cfg(any(all(doc, not(doctest)), feature = "ctap2-management"))]
use webauthn_rs_proto::UserVerificationPolicy;

/// CTAP 2.1 protocol implementation.
///
/// This contains only CTAP 2.1-specific functionality. All CTAP 2.0
/// functionality is avaliable via a [Deref] to [Ctap20Authenticator].
#[derive(Debug)]
pub struct Ctap21Authenticator<'a, T: Token, U: UiCallback> {
    authenticator: Ctap20Authenticator<'a, T, U>,
}

/// For backwards compatibility, pretend to be a
/// [CTAP 2.0 authenticator][Ctap20Authenticator].
impl<'a, T: Token, U: UiCallback> Deref for Ctap21Authenticator<'a, T, U> {
    type Target = Ctap20Authenticator<'a, T, U>;

    fn deref(&self) -> &Self::Target {
        &self.authenticator
    }
}

impl<'a, T: Token, U: UiCallback> DerefMut for Ctap21Authenticator<'a, T, U> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.authenticator
    }
}

impl<'a, T: Token, U: UiCallback> CtapAuthenticatorVersion<'a, T, U>
    for Ctap21Authenticator<'a, T, U>
{
    const VERSION: &'static str = "FIDO_2_1";
    fn new_with_info(info: GetInfoResponse, token: T, ui_callback: &'a U) -> Self {
        Self {
            authenticator: Ctap20Authenticator::new_with_info(info, token, ui_callback),
        }
    }
}

impl<'a, T: Token, U: UiCallback> Ctap21Authenticator<'a, T, U> {
    /// Returns `true` if the authenticator supports configuration commands.
    ///
    /// # See also
    ///
    /// * [`enable_enterprise_attestation()`][Self::enable_enterprise_attestation]
    /// * [`set_min_pin_length()`][Self::set_min_pin_length]
    /// * [`toggle_always_uv()`][Self::toggle_always_uv]
    #[inline]
    pub fn supports_config(&self) -> bool {
        self.info.supports_config()
    }

    #[cfg(any(all(doc, not(doctest)), feature = "ctap2-management"))]
    async fn config(
        &mut self,
        sub_command: ConfigSubCommand,
        toggle_always_uv: bool,
    ) -> Result<(), WebauthnCError> {
        if !self.supports_config() {
            return Err(WebauthnCError::NotSupported);
        }

        let ui_callback = self.ui_callback;

        let (pin_uv_auth_proto, pin_uv_auth_param) = self
            .get_pin_uv_auth_token(
                sub_command.prf().as_slice(),
                Permissions::AUTHENTICATOR_CONFIGURATION,
                None,
                if toggle_always_uv {
                    UserVerificationPolicy::Discouraged_DO_NOT_USE
                } else {
                    UserVerificationPolicy::Required
                },
            )
            .await?
            .into_pin_uv_params();

        // TODO: handle complex result type
        self.token
            .transmit(
                ConfigRequest::new(sub_command, pin_uv_auth_proto, pin_uv_auth_param),
                ui_callback,
            )
            .await?;

        self.refresh_info().await
    }

    #[cfg(any(all(doc, not(doctest)), feature = "ctap2-management"))]
    /// Toggles the state of the [Always Require User Verification][0] feature.
    ///
    /// This is only available on authenticators which
    /// [support configuration][Self::supports_config].
    ///
    /// [0]: https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-errata-20220621.html#toggle-alwaysUv
    pub async fn toggle_always_uv(&mut self) -> Result<(), WebauthnCError> {
        self.config(ConfigSubCommand::ToggleAlwaysUv, true).await
    }

    #[cfg(any(all(doc, not(doctest)), feature = "ctap2-management"))]
    /// Sets a [minimum PIN length policy][0].
    ///
    /// This is only available on authenticators which
    /// [support configuration][Self::supports_config].
    ///
    /// [0]: https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-errata-20220621.html#setMinPINLength
    pub async fn set_min_pin_length(
        &mut self,
        new_min_pin_length: Option<u32>,
        min_pin_length_rpids: Vec<String>,
        force_change_pin: Option<bool>,
    ) -> Result<(), WebauthnCError> {
        self.config(
            ConfigSubCommand::SetMinPinLength(SetMinPinLengthParams {
                new_min_pin_length,
                min_pin_length_rpids,
                force_change_pin,
            }),
            false,
        )
        .await
    }

    /// Returns `true` if the authenticator supports
    /// [enterprise attestation][0].
    ///
    /// # See also
    ///
    /// * [`enable_enterprise_attestation()`][Self::enable_enterprise_attestation]
    ///
    /// [0]: https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-errata-20220621.html#sctn-feature-descriptions-enterp-attstn
    #[inline]
    pub fn supports_enterprise_attestation(&self) -> bool {
        self.info.supports_enterprise_attestation()
    }

    #[cfg(any(all(doc, not(doctest)), feature = "ctap2-management"))]
    /// Enables the [Enterprise Attestation][0] feature.
    ///
    /// This is only available on authenticators which support
    /// [configuration][Self::supports_config] and
    /// [enterprise attestation][Self::supports_enterprise_attestation].
    ///
    /// [0]: https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-errata-20220621.html#sctn-feature-descriptions-enterp-attstn
    pub async fn enable_enterprise_attestation(&mut self) -> Result<(), WebauthnCError> {
        if !self.supports_enterprise_attestation() || !self.supports_config() {
            return Err(WebauthnCError::NotSupported);
        }
        self.config(ConfigSubCommand::EnableEnterpriseAttestation, false)
            .await
    }

    /// Returns `true` if the authenticator supports
    /// [CTAP 2.1 credential management][0].
    ///
    /// ## See also
    ///
    /// * [`CredentialManagementAuthenticator`][]
    /// * [`update_credential_user`][Self::update_credential_user]
    ///
    /// [0]: https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-errata-20220621.html#authenticatorCredentialManagement
    #[inline]
    pub fn supports_ctap21_credential_management(&self) -> bool {
        self.info.ctap21_credential_management()
    }

    /// Updates user information for a discoverable credential.
    ///
    /// This is only available on authenticators which support
    /// [CTAP 2.1 credential management][Self::supports_ctap21_credential_management],
    /// otherwise it returns [`WebauthnCError::NotSupported`].
    ///
    /// ## Note
    ///
    /// This function does not provide a "permissions RP ID" with the request,
    /// as it only works correctly with authenticators supporting the
    /// `pinUvAuthToken` feature.
    ///
    /// ## See also
    ///
    /// * [`CredentialManagementAuthenticator`] trait
    #[cfg(any(all(doc, not(doctest)), feature = "ctap2-management"))]
    pub async fn update_credential_user(
        &mut self,
        credential_id: PublicKeyCredentialDescriptorCM,
        user: UserCM,
    ) -> Result<(), WebauthnCError> {
        self.check_credential_management_support()?;

        self.cred_mgmt(CredSubCommand::UpdateUserInformation(credential_id, user))
            .await
            .map(|_| ())
    }
}

impl<'a, T: Token, U: UiCallback> BiometricAuthenticatorInfo<U> for Ctap21Authenticator<'a, T, U> {
    #[cfg(any(all(doc, not(doctest)), feature = "ctap2-management"))]
    type RequestType = BioEnrollmentRequest;

    #[inline]
    fn biometrics(&self) -> Option<bool> {
        self.info.ctap21_biometrics()
    }
}

impl<'a, T: Token, U: UiCallback> CredentialManagementAuthenticatorInfo<U>
    for Ctap21Authenticator<'a, T, U>
{
    #[cfg(any(all(doc, not(doctest)), feature = "ctap2-management"))]
    type RequestType = CredentialManagementRequest;
    // HACK: type RequestType = super::commands::PrototypeCredentialManagementRequest;

    #[inline]
    fn supports_credential_management(&self) -> bool {
        self.supports_ctap21_credential_management()
    }
}