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
use p256::SecretKey;
use passkey_types::{
    ctap2::{
        make_credential::{Request, Response},
        AttestedCredentialData, AuthenticatorData, Ctap2Error, StatusCode,
    },
    Passkey,
};

use crate::{Authenticator, CoseKeyPair, CredentialStore, UserValidationMethod};

impl<S, U> Authenticator<S, U>
where
    S: CredentialStore + Sync,
    U: UserValidationMethod + Sync,
{
    /// This method is invoked by the host to request generation of a new credential in the authenticator.
    pub async fn make_credential(&mut self, input: Request) -> Result<Response, StatusCode> {
        let flags = if input.options.up {
            self.check_user(&input.options).await?
        } else {
            return Err(Ctap2Error::InvalidOption.into());
        };

        // 1. If the excludeList parameter is present and contains a credential ID that is present
        //    on this authenticator and bound to the specified rpId, wait for user presence, then
        //    terminate this procedure and return error code CTAP2_ERR_CREDENTIAL_EXCLUDED. User
        //    presence check is required for CTAP2 authenticators before the RP gets told that the
        //    token is already registered to behave similarly to CTAP1/U2F authenticators.

        if input
            .exclude_list
            .as_ref()
            .filter(|list| !list.is_empty())
            .is_some()
        {
            if let Ok(false) = self
                .store()
                .find_credentials(input.exclude_list.as_deref(), &input.rp.id)
                .await
                .map(|creds| creds.is_empty())
            {
                return Err(Ctap2Error::CredentialExcluded.into());
            }
        }

        // 2. If the pubKeyCredParams parameter does not contain a valid COSEAlgorithmIdentifier
        //    value that is supported by the authenticator, terminate this procedure and return
        //    error code CTAP2_ERR_UNSUPPORTED_ALGORITHM.
        let algorithm = self.choose_algorithm(&input.pub_key_cred_params)?;

        // 3. If the options parameter is present, process all the options. If the option is known
        //    but not supported, terminate this procedure and return CTAP2_ERR_UNSUPPORTED_OPTION.
        //    If the option is known but not valid for this command, terminate this procedure and
        //    return CTAP2_ERR_INVALID_OPTION. Ignore any options that are not understood.
        //    Note that because this specification defines normative behaviors for them, all
        //    authenticators MUST understand the "rk", "up", and "uv" options.
        // NB: this is handled at the very begining of the method

        // 4. TODO, if the extensions parameter is present, process any extensions that this
        //    authenticator supports. Authenticator extension outputs generated by the authenticator
        //    extension processing are returned in the authenticator data.

        // NB: We do not currently support any Pin Protocols (1 or 2) as this does not make sense
        // in the context of 1Password. This is to be revisisted to see if we can hook this into
        // using some key that we already have, such as the Biometry unlock key for example.
        // 5. If pinAuth parameter is present and pinProtocol is 1, verify it by matching it against
        //    first 16 bytes of HMAC-SHA-256 of clientDataHash parameter using
        //    pinToken: HMAC- SHA-256(pinToken, clientDataHash).
        //     1. If the verification succeeds, set the "uv" bit to 1 in the response.
        //     2. If the verification fails, return CTAP2_ERR_PIN_AUTH_INVALID error.
        // 6. If pinAuth parameter is not present and clientPin been set on the authenticator,
        //    return CTAP2_ERR_PIN_REQUIRED error.
        // 7. If pinAuth parameter is present and the pinProtocol is not supported,
        //    return CTAP2_ERR_PIN_AUTH_INVALID.
        if input.pin_auth.is_some() {
            // we currently don't support pin authentication
            return Err(Ctap2Error::UnsupportedOption.into());
        }

        // 8. If the authenticator has a display, show the items contained within the user and rp
        //    parameter structures to the user. Alternatively, request user interaction in an
        //    authenticator-specific way (e.g., flash the LED light). Request permission to create
        //    a credential. If the user declines permission, return the CTAP2_ERR_OPERATION_DENIED
        //    error.

        // 9. Generate a new credential key pair for the algorithm specified.
        let credential_id: Vec<u8> = {
            use rand::RngCore;
            let mut data = vec![0u8; 16];
            rand::thread_rng().fill_bytes(&mut data);
            data
        };

        let private_key = {
            let mut rng = rand::thread_rng();
            SecretKey::random(&mut rng)
        };

        // Encoding of the keypair into their CoseKey representation before moving the private CoseKey
        // into the passkey. Keeping the public key ready for step 11 below and returning the attested
        // credential.
        let CoseKeyPair { public, private } = CoseKeyPair::from_secret_key(&private_key, algorithm);

        let passkey = Passkey {
            key: private,
            rp_id: input.rp.id.clone(),
            credential_id: credential_id.into(),
            user_handle: input.options.rk.then_some(input.user.id.clone()),
            counter: None,
        };

        // 10. If "rk" in options parameter is set to true:
        //     1. If a credential for the same RP ID and account ID already exists on the
        //        authenticator, overwrite that credential.
        //     2. Store the user parameter along the newly-created key pair.
        //     3. If authenticator does not have enough internal storage to persist the new
        //        credential, return CTAP2_ERR_KEY_STORE_FULL.
        // --> This seems like in the wrong place since we still need the passkey, see after step 11.

        // 11. Generate an attestation statement for the newly-created key using clientDataHash.

        // SAFETY: the only case where this fails is if credential_id's length cannot be represented
        // as a u16. This is checked at step 9, therefore this will never return an error
        let acd = AttestedCredentialData::new(
            *self.aaguid(),
            passkey.credential_id.clone().into(),
            public,
        )
        .unwrap();

        let auth_data = AuthenticatorData::new(&input.rp.id, passkey.counter)
            .set_flags(flags)
            .set_attested_credential_data(acd);

        let response = Response {
            auth_data,
            fmt: "None".into(),
            att_stmt: vec![0xa0].into(), // CBOR exquivalent to empty map
        };

        // 10
        self.store_mut()
            .save_credential(passkey, input.user.into(), input.rp)
            .await?;

        Ok(response)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use coset::iana;
    use passkey_types::{
        ctap2::make_credential::{Options, PublicKeyCredentialRpEntity},
        ctap2::Aaguid,
        rand::random_vec,
        webauthn, Bytes,
    };

    use tokio::sync::Mutex;

    use super::*;
    use crate::{user_validation::MockUserValidationMethod, MemoryStore};

    fn good_request() -> Request {
        Request {
            client_data_hash: random_vec(32).into(),
            rp: PublicKeyCredentialRpEntity {
                id: "future.1password.com".into(),
                name: Some("1password".into()),
            },
            user: webauthn::PublicKeyCredentialUserEntity {
                id: random_vec(16).into(),
                display_name: "wendy".into(),
                name: "Appleseed".into(),
            },
            pub_key_cred_params: vec![webauthn::PublicKeyCredentialParameters {
                ty: webauthn::PublicKeyCredentialType::PublicKey,
                alg: iana::Algorithm::ES256,
            }],
            exclude_list: None,
            extensions: None,
            options: Options {
                rk: true,
                up: true,
                uv: true,
            },
            pin_auth: None,
            pin_protocol: None,
        }
    }

    #[tokio::test]
    async fn assert_storage_on_success() {
        let shared_store = Arc::new(Mutex::new(MemoryStore::new()));
        let user_mock = MockUserValidationMethod::verified_user(1);

        let mut authenticator =
            Authenticator::new(Aaguid::new_empty(), shared_store.clone(), user_mock);

        let request = good_request();

        authenticator
            .make_credential(request)
            .await
            .expect("error happened while trying to make a new credential");

        let store = shared_store.lock().await;

        assert_eq!(store.len(), 1);
    }

    #[tokio::test]
    async fn assert_excluded_credentials() {
        let cred_id: Bytes = random_vec(16).into();
        let response = Request {
            exclude_list: Some(vec![webauthn::PublicKeyCredentialDescriptor {
                ty: webauthn::PublicKeyCredentialType::PublicKey,
                id: cred_id.clone(),
                transports: Some(vec![webauthn::AuthenticatorTransport::Usb]),
            }]),
            ..good_request()
        };
        let passkey = Passkey {
            // contents of key doesn't matter, only the id
            key: Default::default(),
            rp_id: "".into(),
            credential_id: cred_id.clone(),
            user_handle: Some(response.user.id.clone()),
            counter: None,
        };
        let shared_store = Arc::new(Mutex::new(MemoryStore::new()));
        let user_mock = MockUserValidationMethod::verified_user(1);

        shared_store.lock().await.insert(cred_id.into(), passkey);

        let mut authenticator =
            Authenticator::new(Aaguid::new_empty(), shared_store.clone(), user_mock);

        let err = authenticator
            .make_credential(response)
            .await
            .expect_err("make credential succeded even though store contains excluded id");

        assert_eq!(err, Ctap2Error::CredentialExcluded.into());
        assert_eq!(shared_store.lock().await.len(), 1);
    }

    #[tokio::test]
    async fn assert_unsupported_algorithm() {
        let user_mock = MockUserValidationMethod::verified_user(1);
        let mut authenticator =
            Authenticator::new(Aaguid::new_empty(), MemoryStore::new(), user_mock);

        let request = Request {
            pub_key_cred_params: vec![webauthn::PublicKeyCredentialParameters {
                ty: webauthn::PublicKeyCredentialType::PublicKey,
                alg: iana::Algorithm::RSAES_OAEP_SHA_256,
            }],
            ..good_request()
        };

        let err = authenticator
            .make_credential(request)
            .await
            .expect_err("Succeeded with an unsupported algorithm");

        assert_eq!(err, Ctap2Error::UnsupportedAlgorithm.into());
    }
}