use std::fmt;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use jmap_did_types::{Did, DidKey, KeyType};
use jmap_peer_auth::ed25519_dalek::VerifyingKey;
use serde_json::Value;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DidDocument<'a> {
Cached(&'a Value),
Refreshed(&'a Value),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DidAuthRejection {
Unresolved,
DocumentIdMismatch,
KeyNotBound,
RefreshRequired,
}
impl fmt::Display for DidAuthRejection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unresolved => f.write_str("DID could not be resolved"),
Self::DocumentIdMismatch => f.write_str("DID document id does not match the DID"),
Self::KeyNotBound => {
f.write_str("signing key is not in the DID document's authentication keys")
}
Self::RefreshRequired => {
f.write_str("signing key is not in the cached DID document's authentication keys")
}
}
}
}
impl std::error::Error for DidAuthRejection {}
pub fn verify_did_binding(
did: &Did,
document: Option<DidDocument<'_>>,
signing_key: &VerifyingKey,
) -> Result<(), DidAuthRejection> {
let (document, cached) = match document.ok_or(DidAuthRejection::Unresolved)? {
DidDocument::Cached(document) => (document, true),
DidDocument::Refreshed(document) => (document, false),
};
if document.get("id").and_then(Value::as_str) != Some(did.as_str()) {
return Err(DidAuthRejection::DocumentIdMismatch);
}
if authentication_keys(did, document).any(|key| &key == signing_key.as_bytes()) {
Ok(())
} else if cached {
Err(DidAuthRejection::RefreshRequired)
} else {
Err(DidAuthRejection::KeyNotBound)
}
}
fn authentication_keys<'a>(
did: &'a Did,
document: &'a Value,
) -> impl Iterator<Item = [u8; 32]> + 'a {
let absolute = move |id: &str| match id.strip_prefix('#') {
Some(_) => format!("{did}{id}"),
None => id.to_owned(),
};
let methods: Vec<&Value> = document
.get("verificationMethod")
.and_then(Value::as_array)
.into_iter()
.flatten()
.collect();
document
.get("authentication")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(move |entry| match entry {
Value::String(reference) => {
let reference = absolute(reference);
methods.iter().copied().find(|method| {
method
.get("id")
.and_then(Value::as_str)
.map(absolute)
.as_deref()
== Some(reference.as_str())
})
}
Value::Object(_) => Some(entry),
_ => None,
})
.filter_map(ed25519_key)
}
fn ed25519_key(method: &Value) -> Option<[u8; 32]> {
if let Some(jwk) = method.get("publicKeyJwk") {
let member = |name| jwk.get(name).and_then(Value::as_str);
if member("kty")? != "OKP" || member("crv")? != "Ed25519" || jwk.get("d").is_some() {
return None;
}
URL_SAFE_NO_PAD.decode(member("x")?).ok()?.try_into().ok()
} else {
let multibase = method.get("publicKeyMultibase")?.as_str()?;
let key = DidKey::from_did(&format!("did:key:{multibase}").parse().ok()?).ok()?;
if key.key_type() != KeyType::Ed25519 {
return None;
}
key.public_key().try_into().ok()
}
}