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
// Copyright (c) Mysten Labs, Inc.
// Modifications Copyright (c) 2024 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use std::{
    hash::{Hash, Hasher},
    sync::Arc,
};

use fastcrypto::{
    error::FastCryptoError,
    hash::{HashFunction, Sha256},
    rsa::{Base64UrlUnpadded, Encoding},
    secp256r1::{Secp256r1PublicKey, Secp256r1Signature},
    traits::{ToFromBytes, VerifyingKey},
};
use once_cell::sync::OnceCell;
use passkey_types::webauthn::{ClientDataType, CollectedClientData};
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize};
use shared_crypto::intent::{INTENT_PREFIX_LENGTH, Intent, IntentMessage};

use crate::{
    base_types::{EpochId, IotaAddress},
    crypto::{
        DefaultHash, IotaSignature, IotaSignatureInner, PublicKey, Secp256r1IotaSignature,
        Signature, SignatureScheme,
    },
    digests::ZKLoginInputsDigest,
    error::{IotaError, IotaResult},
    signature::{AuthenticatorTrait, VerifyParams},
    signature_verification::VerifiedDigestCache,
};

#[cfg(test)]
#[path = "unit_tests/passkey_authenticator_test.rs"]
mod passkey_authenticator_test;

/// An passkey authenticator with parsed fields. See field definition below. Can
/// be initialized from [struct RawPasskeyAuthenticator].
#[derive(Debug, Clone, JsonSchema)]
pub struct PasskeyAuthenticator {
    /// `authenticatorData` is a bytearray that encodes
    /// [Authenticator Data](https://www.w3.org/TR/webauthn-2/#sctn-authenticator-data)
    /// structure returned by the authenticator attestation
    /// response as is.
    authenticator_data: Vec<u8>,

    /// `clientDataJSON` contains a JSON-compatible
    /// UTF-8 encoded string of the client data which
    /// is passed to the authenticator by the client
    /// during the authentication request (see [CollectedClientData](https://www.w3.org/TR/webauthn-2/#dictdef-collectedclientdata))
    client_data_json: String,

    /// Normalized r1 signature returned by passkey.
    /// Initialized from `user_signature` in `RawPasskeyAuthenticator`.
    #[serde(skip)]
    signature: Secp256r1Signature,

    /// Compact r1 public key upon passkey creation.
    /// Initialized from `user_signature` in `RawPasskeyAuthenticator`.
    #[serde(skip)]
    pk: Secp256r1PublicKey,

    /// Valid intent parsed from the first 3 bytes of
    /// `client_data_json.challenge`.
    #[serde(skip)]
    intent: Intent,

    /// Valid digest parsed from the last 32 bytes of
    /// `client_data_json.challenge`.
    #[serde(skip)]
    digest: [u8; DefaultHash::OUTPUT_SIZE],

    /// Initialization of bytes for passkey in serialized form.
    #[serde(skip)]
    bytes: OnceCell<Vec<u8>>,
}

/// An raw passkey authenticator struct used during deserialization. Can be
/// converted to [struct PasskeyAuthenticator].
#[derive(Serialize, Deserialize, Debug)]
pub struct RawPasskeyAuthenticator {
    pub authenticator_data: Vec<u8>,
    pub client_data_json: String,
    pub user_signature: Signature,
}

/// Convert [struct RawPasskeyAuthenticator] to [struct PasskeyAuthenticator]
/// with validations.
impl TryFrom<RawPasskeyAuthenticator> for PasskeyAuthenticator {
    type Error = IotaError;

    fn try_from(raw: RawPasskeyAuthenticator) -> Result<Self, Self::Error> {
        let client_data_json_parsed: CollectedClientData =
            serde_json::from_str(&raw.client_data_json).map_err(|_| {
                IotaError::InvalidSignature {
                    error: "Invalid client data json".to_string(),
                }
            })?;

        if client_data_json_parsed.ty != ClientDataType::Get {
            return Err(IotaError::InvalidSignature {
                error: "Invalid client data type".to_string(),
            });
        };

        let parsed_challenge = Base64UrlUnpadded::decode_vec(&client_data_json_parsed.challenge)
            .map_err(|_| IotaError::InvalidSignature {
                error: "Invalid encoded challenge".to_string(),
            })?;

        let intent =
            Intent::from_bytes(&parsed_challenge[..INTENT_PREFIX_LENGTH]).map_err(|_| {
                IotaError::InvalidSignature {
                    error: "Invalid intent from challenge".to_string(),
                }
            })?;

        let digest = parsed_challenge[INTENT_PREFIX_LENGTH..]
            .try_into()
            .map_err(|_| IotaError::InvalidSignature {
                error: "Invalid digest from challenge".to_string(),
            })?;

        if raw.user_signature.scheme() != SignatureScheme::Secp256r1 {
            return Err(IotaError::InvalidSignature {
                error: "Invalid signature scheme".to_string(),
            });
        };

        let pk = Secp256r1PublicKey::from_bytes(raw.user_signature.public_key_bytes()).map_err(
            |_| IotaError::InvalidSignature {
                error: "Invalid r1 pk".to_string(),
            },
        )?;

        let signature = Secp256r1Signature::from_bytes(raw.user_signature.signature_bytes())
            .map_err(|_| IotaError::InvalidSignature {
                error: "Invalid r1 sig".to_string(),
            })?;

        Ok(PasskeyAuthenticator {
            authenticator_data: raw.authenticator_data,
            client_data_json: raw.client_data_json,
            signature,
            pk,
            intent,
            digest,
            bytes: OnceCell::new(),
        })
    }
}

impl<'de> Deserialize<'de> for PasskeyAuthenticator {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;

        let serializable = RawPasskeyAuthenticator::deserialize(deserializer)?;
        serializable
            .try_into()
            .map_err(|e: IotaError| Error::custom(e.to_string()))
    }
}

impl Serialize for PasskeyAuthenticator {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::ser::Serializer,
    {
        let mut bytes = Vec::with_capacity(Secp256r1IotaSignature::LENGTH);
        bytes.push(SignatureScheme::Secp256r1.flag());
        bytes.extend_from_slice(self.signature.as_ref());
        bytes.extend_from_slice(self.pk.as_ref());

        let raw = RawPasskeyAuthenticator {
            authenticator_data: self.authenticator_data.clone(),
            client_data_json: self.client_data_json.clone(),
            user_signature: Signature::Secp256r1IotaSignature(
                Secp256r1IotaSignature::from_bytes(&bytes).unwrap(),
            ),
        };
        raw.serialize(serializer)
    }
}
impl PasskeyAuthenticator {
    /// A constructor for [struct PasskeyAuthenticator] with custom
    /// defined fields. Used for testing.
    pub fn new_for_testing(
        authenticator_data: Vec<u8>,
        client_data_json: String,
        user_signature: Signature,
    ) -> Result<Self, IotaError> {
        let raw = RawPasskeyAuthenticator {
            authenticator_data,
            client_data_json,
            user_signature,
        };
        raw.try_into()
    }

    /// Returns the public key of the passkey authenticator.
    pub fn get_pk(&self) -> IotaResult<PublicKey> {
        Ok(PublicKey::Passkey((&self.pk).into()))
    }
}

/// Necessary trait for [struct SenderSignedData].
impl PartialEq for PasskeyAuthenticator {
    fn eq(&self, other: &Self) -> bool {
        self.as_ref() == other.as_ref()
    }
}

/// Necessary trait for [struct SenderSignedData].
impl Eq for PasskeyAuthenticator {}

/// Necessary trait for [struct SenderSignedData].
impl Hash for PasskeyAuthenticator {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_ref().hash(state);
    }
}

impl AuthenticatorTrait for PasskeyAuthenticator {
    fn verify_user_authenticator_epoch(
        &self,
        _epoch: EpochId,
        _max_epoch_upper_bound_delta: Option<u64>,
    ) -> IotaResult {
        Ok(())
    }

    /// Verify an intent message of a transaction with an passkey authenticator.
    fn verify_claims<T>(
        &self,
        intent_msg: &IntentMessage<T>,
        author: IotaAddress,
        _aux_verify_data: &VerifyParams,
        _zklogin_inputs_cache: Arc<VerifiedDigestCache<ZKLoginInputsDigest>>,
    ) -> IotaResult
    where
        T: Serialize,
    {
        // Check the intent and signing is consisted from what's parsed from
        // client_data_json.challenge
        if intent_msg.intent != self.intent || to_signing_digest(intent_msg) != self.digest {
            return Err(IotaError::InvalidSignature {
                error: "Invalid challenge".to_string(),
            });
        };

        // Construct msg = authenticator_data || sha256(client_data_json).
        let mut message = self.authenticator_data.clone();
        let client_data_hash = Sha256::digest(self.client_data_json.as_bytes()).digest;
        message.extend_from_slice(&client_data_hash);

        // Check if author is derived from the public key.
        if author != IotaAddress::from(&self.get_pk()?) {
            return Err(IotaError::InvalidSignature {
                error: "Invalid author".to_string(),
            });
        };

        // Verify the signature against pk and message.
        self.pk
            .verify(&message, &self.signature)
            .map_err(|_| IotaError::InvalidSignature {
                error: "Fails to verify".to_string(),
            })
    }
}

impl ToFromBytes for PasskeyAuthenticator {
    fn from_bytes(bytes: &[u8]) -> Result<Self, FastCryptoError> {
        // The first byte matches the flag of PasskeyAuthenticator.
        if bytes.first().ok_or(FastCryptoError::InvalidInput)?
            != &SignatureScheme::PasskeyAuthenticator.flag()
        {
            return Err(FastCryptoError::InvalidInput);
        }
        let passkey: PasskeyAuthenticator =
            bcs::from_bytes(&bytes[1..]).map_err(|_| FastCryptoError::InvalidSignature)?;
        Ok(passkey)
    }
}

impl AsRef<[u8]> for PasskeyAuthenticator {
    fn as_ref(&self) -> &[u8] {
        self.bytes
            .get_or_try_init::<_, eyre::Report>(|| {
                let as_bytes = bcs::to_bytes(self).expect("BCS serialization should not fail");
                let mut bytes = Vec::with_capacity(1 + as_bytes.len());
                bytes.push(SignatureScheme::PasskeyAuthenticator.flag());
                bytes.extend_from_slice(as_bytes.as_slice());
                Ok(bytes)
            })
            .expect("OnceCell invariant violated")
    }
}
/// Compute the digest that the signature committed over as `intent ||
/// hash(tx_data)`, total of 3 + 32 = 35 bytes.
pub fn to_signing_message<T: Serialize>(
    intent_msg: &IntentMessage<T>,
) -> [u8; INTENT_PREFIX_LENGTH + DefaultHash::OUTPUT_SIZE] {
    let mut extended = [0; INTENT_PREFIX_LENGTH + DefaultHash::OUTPUT_SIZE];
    extended[..INTENT_PREFIX_LENGTH].copy_from_slice(&intent_msg.intent.to_bytes());
    extended[INTENT_PREFIX_LENGTH..].copy_from_slice(&to_signing_digest(intent_msg));
    extended
}

/// Compute the BCS hash of the value in intent message. In the case of
/// transaction data, this is the BCS hash of `struct TransactionData`,
/// different from the transaction digest itself that computes the BCS hash of
/// the Rust type prefix and `struct TransactionData`. (See `fn digest` in `impl
/// Message for SenderSignedData`).
pub fn to_signing_digest<T: Serialize>(
    intent_msg: &IntentMessage<T>,
) -> [u8; DefaultHash::OUTPUT_SIZE] {
    let mut hasher = DefaultHash::default();
    bcs::serialize_into(&mut hasher, &intent_msg.value)
        .expect("Message serialization should not fail");
    hasher.finalize().digest
}