use base64::prelude::*;
use serde::{Deserialize, Serialize};
use crate::cbor::Value;
const LARGE_BLOB_KEY_EXT_ID: &str = "largeBlobKey";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LargeBlobSupport {
Required,
Preferred,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistrationInput {
pub support: LargeBlobSupport,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistrationOutput {
pub supported: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticationInput {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub read: Option<bool>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
serialize_with = "b64_opt_ser",
deserialize_with = "b64_opt_de"
)]
pub write: Option<Vec<u8>>,
}
impl AuthenticationInput {
pub fn read() -> Self {
Self {
read: Some(true),
write: None,
}
}
pub fn write(data: Vec<u8>) -> Self {
Self {
read: None,
write: Some(data),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthenticationOutput {
#[serde(
default,
skip_serializing_if = "Option::is_none",
serialize_with = "b64_opt_ser",
deserialize_with = "b64_opt_de"
)]
pub blob: Option<Vec<u8>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub written: Option<bool>,
}
pub(crate) fn to_cbor() -> (String, Value) {
(LARGE_BLOB_KEY_EXT_ID.into(), Value::Bool(true))
}
use crate::ctap2::{Info, Permissions};
use crate::webauthn::extensions::{
AuthenticationExtensionOutputs, AuthenticationProcessor, Ctap2Extension, ExtensionContext,
OutputContext, RegistrationExtensionOutputs, RegistrationProcessor,
};
use crate::webauthn::types::{
PublicKeyCredentialCreationOptions, PublicKeyCredentialRequestOptions,
};
pub struct LargeBlobExtension;
impl Ctap2Extension for LargeBlobExtension {
fn make_credential(
&self,
info: &Info,
options: &PublicKeyCredentialCreationOptions,
) -> Result<Option<Box<dyn RegistrationProcessor>>, String> {
let ext = match &options.extensions {
Some(e) => e,
None => return Ok(None),
};
let lb = match &ext.large_blob {
Some(lb) => lb,
None => return Ok(None),
};
let supported = info.extensions.iter().any(|e| e == LARGE_BLOB_KEY_EXT_ID);
if lb.support == LargeBlobSupport::Required && !supported {
return Err("largeBlob not supported by authenticator".into());
}
if !supported {
return Ok(None);
}
Ok(Some(Box::new(LargeBlobRegistrationProcessor)))
}
fn get_assertion(
&self,
info: &Info,
options: &PublicKeyCredentialRequestOptions,
) -> Result<Option<Box<dyn AuthenticationProcessor>>, String> {
let ext = match &options.extensions {
Some(e) => e,
None => return Ok(None),
};
let lb = match &ext.large_blob {
Some(lb) => lb,
None => return Ok(None),
};
if !info.extensions.iter().any(|e| e == LARGE_BLOB_KEY_EXT_ID) {
return Ok(None);
}
let needs_write = lb.write.is_some();
Ok(Some(Box::new(LargeBlobAuthenticationProcessor {
needs_write,
})))
}
}
struct LargeBlobRegistrationProcessor;
impl RegistrationProcessor for LargeBlobRegistrationProcessor {
fn prepare_inputs(&self, _ctx: &mut ExtensionContext) -> Result<Vec<(String, Value)>, String> {
Ok(vec![to_cbor()])
}
fn prepare_outputs(&self, ctx: &OutputContext<'_>, outputs: &mut RegistrationExtensionOutputs) {
outputs.large_blob = Some(RegistrationOutput {
supported: ctx.has_large_blob_key,
});
}
}
struct LargeBlobAuthenticationProcessor {
needs_write: bool,
}
impl AuthenticationProcessor for LargeBlobAuthenticationProcessor {
fn permissions(&self) -> Permissions {
if self.needs_write {
Permissions::LARGE_BLOB_WRITE
} else {
Permissions::new(0)
}
}
fn prepare_inputs(
&self,
_selected_cred_id: Option<&[u8]>,
_ctx: &mut ExtensionContext,
) -> Result<Vec<(String, Value)>, String> {
Ok(vec![to_cbor()])
}
fn prepare_outputs(
&self,
_ctx: &OutputContext<'_>,
_outputs: &mut AuthenticationExtensionOutputs,
) {
}
}
fn b64_opt_ser<S: serde::Serializer>(v: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
match v {
Some(b) => s.serialize_str(&BASE64_URL_SAFE_NO_PAD.encode(b)),
None => s.serialize_none(),
}
}
fn b64_opt_de<'de, D: serde::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),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_support_json() {
let input = RegistrationInput {
support: LargeBlobSupport::Required,
};
let json = serde_json::to_string(&input).unwrap();
assert!(json.contains("\"required\""));
}
#[test]
fn test_auth_input_json() {
let read = AuthenticationInput::read();
let json = serde_json::to_string(&read).unwrap();
assert!(json.contains("\"read\":true"));
assert!(!json.contains("write"));
}
#[test]
fn test_cbor() {
let (key, val) = to_cbor();
assert_eq!(key, "largeBlobKey");
assert_eq!(val.as_bool(), Some(true));
}
}