use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::cbor::Value;
mod base64url {
use base64::prelude::*;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn serialize<S: Serializer>(bytes: &Vec<u8>, s: S) -> Result<S::Ok, S::Error> {
BASE64_URL_SAFE_NO_PAD.encode(bytes).serialize(s)
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
let s = String::deserialize(d)?;
BASE64_URL_SAFE_NO_PAD
.decode(&s)
.map_err(serde::de::Error::custom)
}
}
mod base64url_opt {
use base64::prelude::*;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn serialize<S: Serializer>(bytes: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
match bytes {
Some(b) => BASE64_URL_SAFE_NO_PAD.encode(b).serialize(s),
None => s.serialize_none(),
}
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
let opt = Option::<String>::deserialize(d)?;
match opt {
Some(s) => BASE64_URL_SAFE_NO_PAD
.decode(&s)
.map(Some)
.map_err(serde::de::Error::custom),
None => Ok(None),
}
}
}
macro_rules! string_enum {
(
$(#[$meta:meta])*
$vis:vis enum $Name:ident {
$(
$(#[$vmeta:meta])*
$Variant:ident
),+
$(,)?
}
) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
$vis enum $Name {
$(
$(#[$vmeta])*
$Variant,
)+
}
impl $Name {
#[allow(dead_code)]
pub(crate) fn from_str(s: &str) -> Option<Self> {
serde_json::from_value(serde_json::Value::String(s.to_string())).ok()
}
}
impl std::fmt::Display for $Name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let json = serde_json::to_string(self).map_err(|_| std::fmt::Error)?;
f.write_str(json.trim_matches('"'))
}
}
};
}
string_enum! {
pub enum PublicKeyCredentialType {
PublicKey,
}
}
string_enum! {
#[derive(Default)]
pub enum AttestationConveyancePreference {
#[default]
None,
Indirect,
Direct,
Enterprise,
}
}
string_enum! {
#[derive(Default)]
pub enum UserVerificationRequirement {
Required,
#[default]
Preferred,
Discouraged,
}
}
string_enum! {
#[derive(Default)]
pub enum ResidentKeyRequirement {
Required,
#[default]
Preferred,
Discouraged,
}
}
string_enum! {
pub enum AuthenticatorAttachment {
Platform,
CrossPlatform,
}
}
string_enum! {
pub enum AuthenticatorTransport {
Usb,
Nfc,
Ble,
Hybrid,
Internal,
}
}
string_enum! {
pub enum PublicKeyCredentialHint {
SecurityKey,
ClientDevice,
Hybrid,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicKeyCredentialRpEntity {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
impl PublicKeyCredentialRpEntity {
#[allow(dead_code)]
fn id_hash(&self) -> Option<[u8; 32]> {
self.id.as_ref().map(|id| {
let mut hasher = Sha256::new();
hasher.update(id.as_bytes());
hasher.finalize().into()
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicKeyCredentialUserEntity {
#[serde(with = "base64url")]
pub id: Vec<u8>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
}
impl PublicKeyCredentialUserEntity {
pub(crate) fn to_cbor(&self) -> Value {
let mut entries = vec![(Value::Text("id".into()), Value::Bytes(self.id.clone()))];
if let Some(name) = &self.name {
entries.push((Value::Text("name".into()), Value::Text(name.clone())));
}
if let Some(dn) = &self.display_name {
entries.push((Value::Text("displayName".into()), Value::Text(dn.clone())));
}
Value::Map(entries)
}
pub(crate) fn from_cbor(value: &Value) -> Option<Self> {
let id = value
.map_get_text("id")
.and_then(|v| v.as_bytes())
.map(|b| b.to_vec())?;
let name = value
.map_get_text("name")
.and_then(|v| v.as_text())
.map(|s| s.to_string());
let display_name = value
.map_get_text("displayName")
.and_then(|v| v.as_text())
.map(|s| s.to_string());
Some(Self {
id,
name,
display_name,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicKeyCredentialParameters {
#[serde(rename = "type")]
pub type_: PublicKeyCredentialType,
pub alg: i64,
}
impl PublicKeyCredentialParameters {
pub(crate) fn to_cbor(&self) -> Value {
Value::Map(vec![
(
Value::Text("type".into()),
Value::Text(self.type_.to_string()),
),
(Value::Text("alg".into()), Value::Int(self.alg)),
])
}
pub(crate) fn from_cbor(value: &Value) -> Option<Self> {
let type_ = value
.map_get_text("type")
.and_then(|v| v.as_text())
.and_then(PublicKeyCredentialType::from_str)
.unwrap_or(PublicKeyCredentialType::PublicKey);
let alg = value.map_get_text("alg").and_then(|v| v.as_int())?;
Some(Self { type_, alg })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicKeyCredentialDescriptor {
#[serde(rename = "type")]
pub type_: PublicKeyCredentialType,
#[serde(with = "base64url")]
pub id: Vec<u8>,
#[serde(skip_serializing_if = "Option::is_none")]
pub transports: Option<Vec<AuthenticatorTransport>>,
}
impl PublicKeyCredentialDescriptor {
pub(crate) fn to_cbor(&self) -> Value {
let mut entries = vec![
(
Value::Text("type".into()),
Value::Text(self.type_.to_string()),
),
(Value::Text("id".into()), Value::Bytes(self.id.clone())),
];
if let Some(transports) = &self.transports {
entries.push((
Value::Text("transports".into()),
Value::Array(
transports
.iter()
.map(|t| Value::Text(t.to_string()))
.collect(),
),
));
}
Value::Map(entries)
}
pub(crate) fn from_cbor(value: &Value) -> Option<Self> {
let type_ = value
.map_get_text("type")
.and_then(|v| v.as_text())
.and_then(PublicKeyCredentialType::from_str)
.unwrap_or(PublicKeyCredentialType::PublicKey);
let id = value
.map_get_text("id")
.and_then(|v| v.as_bytes())
.map(|b| b.to_vec())?;
let transports = value
.map_get_text("transports")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_text().and_then(AuthenticatorTransport::from_str))
.collect()
});
Some(Self {
type_,
id,
transports,
})
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticatorSelectionCriteria {
#[serde(skip_serializing_if = "Option::is_none")]
pub authenticator_attachment: Option<AuthenticatorAttachment>,
#[serde(skip_serializing_if = "Option::is_none")]
pub resident_key: Option<ResidentKeyRequirement>,
#[serde(skip_serializing_if = "Option::is_none")]
pub user_verification: Option<UserVerificationRequirement>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicKeyCredentialCreationOptions {
pub rp: PublicKeyCredentialRpEntity,
pub user: PublicKeyCredentialUserEntity,
#[serde(with = "base64url")]
pub challenge: Vec<u8>,
pub pub_key_cred_params: Vec<PublicKeyCredentialParameters>,
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub exclude_credentials: Option<Vec<PublicKeyCredentialDescriptor>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub authenticator_selection: Option<AuthenticatorSelectionCriteria>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hints: Option<Vec<PublicKeyCredentialHint>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub attestation: Option<AttestationConveyancePreference>,
#[serde(skip_serializing_if = "Option::is_none")]
pub attestation_formats: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub extensions: Option<super::extensions::RegistrationExtensionInputs>,
}
impl PublicKeyCredentialCreationOptions {
pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(json)
}
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string(self)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicKeyCredentialRequestOptions {
#[serde(with = "base64url")]
pub challenge: Vec<u8>,
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rp_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_credentials: Option<Vec<PublicKeyCredentialDescriptor>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub user_verification: Option<UserVerificationRequirement>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hints: Option<Vec<PublicKeyCredentialHint>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub extensions: Option<super::extensions::AuthenticationExtensionInputs>,
}
impl PublicKeyCredentialRequestOptions {
pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(json)
}
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string(self)
}
}
#[derive(Debug, Clone)]
pub struct CollectedClientData {
json: Vec<u8>,
pub type_: String,
pub challenge: Vec<u8>,
pub origin: String,
pub cross_origin: bool,
}
impl CollectedClientData {
pub fn create(type_: &str, challenge: &[u8], origin: &str, cross_origin: bool) -> Self {
use base64::prelude::*;
let challenge_b64 = BASE64_URL_SAFE_NO_PAD.encode(challenge);
let json = format!(
r#"{{"type":"{}","challenge":"{}","origin":"{}","crossOrigin":{}}}"#,
type_, challenge_b64, origin, cross_origin
);
Self {
json: json.into_bytes(),
type_: type_.to_string(),
challenge: challenge.to_vec(),
origin: origin.to_string(),
cross_origin,
}
}
pub fn from_json(json: Vec<u8>) -> Result<Self, String> {
use base64::prelude::*;
let parsed: serde_json::Value =
serde_json::from_slice(&json).map_err(|e| format!("invalid client data JSON: {e}"))?;
let obj = parsed
.as_object()
.ok_or("client data JSON must be an object")?;
let type_ = obj
.get("type")
.and_then(|v| v.as_str())
.ok_or("missing 'type' in client data")?
.to_string();
let challenge_b64 = obj
.get("challenge")
.and_then(|v| v.as_str())
.ok_or("missing 'challenge' in client data")?;
let challenge = BASE64_URL_SAFE_NO_PAD
.decode(challenge_b64)
.map_err(|e| format!("invalid challenge base64: {e}"))?;
let origin = obj
.get("origin")
.and_then(|v| v.as_str())
.ok_or("missing 'origin' in client data")?
.to_string();
let cross_origin = obj
.get("crossOrigin")
.and_then(|v| v.as_bool())
.unwrap_or(false);
Ok(Self {
json,
type_,
challenge,
origin,
cross_origin,
})
}
pub fn as_bytes(&self) -> &[u8] {
&self.json
}
pub fn hash(&self) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(&self.json);
hasher.finalize().into()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticatorAttestationResponse {
#[serde(rename = "clientDataJSON", with = "base64url")]
pub client_data_json: Vec<u8>,
#[serde(with = "base64url")]
pub attestation_object: Vec<u8>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticatorAssertionResponse {
#[serde(rename = "clientDataJSON", with = "base64url")]
pub client_data_json: Vec<u8>,
#[serde(with = "base64url")]
pub authenticator_data: Vec<u8>,
#[serde(with = "base64url")]
pub signature: Vec<u8>,
#[serde(
skip_serializing_if = "Option::is_none",
with = "base64url_opt",
default
)]
pub user_handle: Option<Vec<u8>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegistrationResponse {
#[serde(with = "base64url")]
pub id: Vec<u8>,
pub response: AuthenticatorAttestationResponse,
#[serde(skip_serializing_if = "Option::is_none")]
pub authenticator_attachment: Option<AuthenticatorAttachment>,
#[serde(rename = "type")]
pub type_: PublicKeyCredentialType,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_extension_results: Option<super::extensions::RegistrationExtensionOutputs>,
}
impl RegistrationResponse {
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string(self)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticationResponse {
#[serde(with = "base64url")]
pub id: Vec<u8>,
pub response: AuthenticatorAssertionResponse,
#[serde(skip_serializing_if = "Option::is_none")]
pub authenticator_attachment: Option<AuthenticatorAttachment>,
#[serde(rename = "type")]
pub type_: PublicKeyCredentialType,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_extension_results: Option<super::extensions::AuthenticationExtensionOutputs>,
}
impl AuthenticationResponse {
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string(self)
}
}
impl PublicKeyCredentialRpEntity {
pub(crate) fn to_ctap2(
&self,
effective_rp_id: &str,
) -> crate::ctap2::types::PublicKeyCredentialRpEntity {
crate::ctap2::types::PublicKeyCredentialRpEntity {
id: effective_rp_id.to_string(),
name: Some(self.name.clone()),
}
}
}
pub(crate) fn encode_allow_exclude_list(list: &[PublicKeyCredentialDescriptor]) -> Value {
Value::Array(list.iter().map(|d| d.to_cbor()).collect())
}
pub(crate) fn encode_pub_key_cred_params(params: &[PublicKeyCredentialParameters]) -> Value {
Value::Array(params.iter().map(|p| p.to_cbor()).collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_collected_client_data_create() {
let challenge = b"test-challenge";
let cd =
CollectedClientData::create("webauthn.create", challenge, "https://example.com", false);
assert_eq!(cd.type_, "webauthn.create");
assert_eq!(cd.challenge, challenge);
assert_eq!(cd.origin, "https://example.com");
assert!(!cd.cross_origin);
let json_str = std::str::from_utf8(cd.as_bytes()).unwrap();
assert!(json_str.contains(r#""type":"webauthn.create""#));
assert!(json_str.contains(r#""origin":"https://example.com""#));
assert!(json_str.contains(r#""crossOrigin":false"#));
}
#[test]
fn test_collected_client_data_hash() {
let cd = CollectedClientData::create("webauthn.get", b"ch", "https://example.com", false);
let hash = cd.hash();
assert_eq!(hash.len(), 32);
assert_eq!(hash, cd.hash());
}
#[test]
fn test_rp_entity_id_hash() {
let mut rp = PublicKeyCredentialRpEntity {
name: "Example".to_string(),
id: None,
};
assert!(rp.id_hash().is_none());
rp.id = Some("example.com".to_string());
let hash = rp.id_hash().unwrap();
assert_eq!(hash.len(), 32);
}
#[test]
fn test_credential_descriptor() {
let desc = PublicKeyCredentialDescriptor {
type_: PublicKeyCredentialType::PublicKey,
id: vec![1, 2, 3],
transports: None,
};
assert_eq!(desc.type_, PublicKeyCredentialType::PublicKey);
assert_eq!(desc.id, vec![1, 2, 3]);
assert!(desc.transports.is_none());
}
#[test]
fn test_credential_parameters() {
let params = PublicKeyCredentialParameters {
type_: PublicKeyCredentialType::PublicKey,
alg: -7,
};
assert_eq!(params.type_, PublicKeyCredentialType::PublicKey);
assert_eq!(params.alg, -7);
}
#[test]
fn test_enum_str_values() {
assert_eq!(PublicKeyCredentialType::PublicKey.to_string(), "public-key");
assert_eq!(AttestationConveyancePreference::None.to_string(), "none");
assert_eq!(
AttestationConveyancePreference::Direct.to_string(),
"direct"
);
assert_eq!(
UserVerificationRequirement::Required.to_string(),
"required"
);
assert_eq!(
UserVerificationRequirement::Preferred.to_string(),
"preferred"
);
assert_eq!(
UserVerificationRequirement::Discouraged.to_string(),
"discouraged"
);
assert_eq!(ResidentKeyRequirement::Required.to_string(), "required");
assert_eq!(AuthenticatorAttachment::Platform.to_string(), "platform");
assert_eq!(
AuthenticatorAttachment::CrossPlatform.to_string(),
"cross-platform"
);
assert_eq!(AuthenticatorTransport::Usb.to_string(), "usb");
assert_eq!(
PublicKeyCredentialHint::SecurityKey.to_string(),
"security-key"
);
}
#[test]
fn test_to_ctap2_rp() {
let rp = PublicKeyCredentialRpEntity {
name: "Example RP".to_string(),
id: Some("example.com".to_string()),
};
let ctap2_rp = rp.to_ctap2("example.com");
assert_eq!(ctap2_rp.id, "example.com");
assert_eq!(ctap2_rp.name.as_deref(), Some("Example RP"));
}
#[test]
fn test_user_entity_cbor_roundtrip() {
let user = PublicKeyCredentialUserEntity {
id: vec![1, 2, 3],
name: Some("alice".to_string()),
display_name: Some("Alice".to_string()),
};
let cbor = user.to_cbor();
let user2 = PublicKeyCredentialUserEntity::from_cbor(&cbor).unwrap();
assert_eq!(user, user2);
}
#[test]
fn test_credential_params_cbor_roundtrip() {
let params = PublicKeyCredentialParameters {
type_: PublicKeyCredentialType::PublicKey,
alg: -7,
};
let cbor = params.to_cbor();
let params2 = PublicKeyCredentialParameters::from_cbor(&cbor).unwrap();
assert_eq!(params, params2);
}
#[test]
fn test_credential_descriptor_cbor_roundtrip() {
let desc = PublicKeyCredentialDescriptor {
type_: PublicKeyCredentialType::PublicKey,
id: vec![0xAA, 0xBB],
transports: Some(vec![
AuthenticatorTransport::Usb,
AuthenticatorTransport::Nfc,
]),
};
let cbor = desc.to_cbor();
let desc2 = PublicKeyCredentialDescriptor::from_cbor(&cbor).unwrap();
assert_eq!(desc, desc2);
}
#[test]
fn test_creation_options_from_json() {
let json = r#"{
"rp": {"name": "Example", "id": "example.com"},
"user": {"id": "dXNlci0x", "name": "alice", "displayName": "Alice"},
"challenge": "Y2hhbGxlbmdl",
"pubKeyCredParams": [{"type": "public-key", "alg": -7}],
"timeout": 60000,
"authenticatorSelection": {
"userVerification": "preferred",
"residentKey": "required"
}
}"#;
let opts = PublicKeyCredentialCreationOptions::from_json(json).unwrap();
assert_eq!(opts.rp.name, "Example");
assert_eq!(opts.rp.id.as_deref(), Some("example.com"));
assert_eq!(opts.user.name.as_deref(), Some("alice"));
assert_eq!(opts.challenge, b"challenge");
assert_eq!(opts.pub_key_cred_params.len(), 1);
assert_eq!(opts.pub_key_cred_params[0].alg, -7);
assert_eq!(opts.timeout, Some(60000));
let sel = opts.authenticator_selection.unwrap();
assert_eq!(
sel.user_verification,
Some(UserVerificationRequirement::Preferred)
);
assert_eq!(sel.resident_key, Some(ResidentKeyRequirement::Required));
}
#[test]
fn test_request_options_from_json() {
let json = r#"{
"challenge": "Y2hhbGxlbmdl",
"rpId": "example.com",
"allowCredentials": [{"type": "public-key", "id": "AABB"}],
"userVerification": "discouraged"
}"#;
let opts = PublicKeyCredentialRequestOptions::from_json(json).unwrap();
assert_eq!(opts.challenge, b"challenge");
assert_eq!(opts.rp_id.as_deref(), Some("example.com"));
assert_eq!(opts.allow_credentials.as_ref().unwrap().len(), 1);
assert_eq!(
opts.user_verification,
Some(UserVerificationRequirement::Discouraged)
);
}
#[test]
fn test_request_options_with_large_blob_write() {
let json = r#"{
"challenge": "AAAA",
"rpId": "example.com",
"allowCredentials": [{"type": "public-key", "id": "BBBB"}],
"userVerification": "discouraged",
"extensions": {
"largeBlob": {"write": "aGVsbG8"}
}
}"#;
let opts = PublicKeyCredentialRequestOptions::from_json(json).unwrap();
let ext = opts.extensions.unwrap();
let lb = ext.large_blob.unwrap();
assert_eq!(lb.write.unwrap(), b"hello");
assert!(lb.read.is_none());
}
#[test]
fn test_request_options_with_large_blob_read() {
let json = r#"{
"challenge": "AAAA",
"rpId": "example.com",
"allowCredentials": [{"type": "public-key", "id": "BBBB"}],
"userVerification": "discouraged",
"extensions": {
"largeBlob": {"read": true}
}
}"#;
let opts = PublicKeyCredentialRequestOptions::from_json(json).unwrap();
let ext = opts.extensions.unwrap();
let lb = ext.large_blob.unwrap();
assert_eq!(lb.read, Some(true));
assert!(lb.write.is_none());
}
#[test]
fn test_creation_options_with_large_blob() {
let json = r#"{
"rp": {"name": "Test", "id": "example.com"},
"user": {"id": "dXNlcg", "name": "test@example.com", "displayName": "Test"},
"challenge": "AAAA",
"pubKeyCredParams": [{"type": "public-key", "alg": -7}],
"authenticatorSelection": {"residentKey": "required"},
"extensions": {
"largeBlob": {"support": "required"}
}
}"#;
let opts = PublicKeyCredentialCreationOptions::from_json(json).unwrap();
let ext = opts.extensions.unwrap();
let lb = ext.large_blob.unwrap();
assert_eq!(
lb.support,
super::super::extensions::large_blob::LargeBlobSupport::Required,
);
}
#[test]
fn test_registration_response_to_json() {
let resp = RegistrationResponse {
id: vec![0xAA, 0xBB],
response: AuthenticatorAttestationResponse {
client_data_json: b"{}".to_vec(),
attestation_object: vec![0x01, 0x02],
},
authenticator_attachment: Some(AuthenticatorAttachment::CrossPlatform),
client_extension_results: None,
type_: PublicKeyCredentialType::PublicKey,
};
let json = resp.to_json().unwrap();
let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
assert_eq!(parsed["id"], "qrs");
assert_eq!(parsed["type"], "public-key");
assert_eq!(parsed["authenticatorAttachment"], "cross-platform");
assert!(parsed["response"]["clientDataJSON"].is_string());
assert!(parsed["response"]["attestationObject"].is_string());
}
#[test]
fn test_authentication_response_to_json() {
let resp = AuthenticationResponse {
id: vec![0xCC],
response: AuthenticatorAssertionResponse {
client_data_json: b"{}".to_vec(),
authenticator_data: vec![0x01],
signature: vec![0x02, 0x03],
user_handle: Some(b"user".to_vec()),
},
authenticator_attachment: None,
client_extension_results: None,
type_: PublicKeyCredentialType::PublicKey,
};
let json = resp.to_json().unwrap();
let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
assert_eq!(parsed["id"], "zA");
assert_eq!(parsed["type"], "public-key");
assert!(parsed["response"]["signature"].is_string());
assert!(parsed["response"]["userHandle"].is_string());
}
}