use serde_json::Value;
use super::Resolver;
use crate::did::{
Did, DidDocument, DidUrl, DocumentError, MethodType, ResolutionError, ResolutionOptions,
Service, VerificationMaterial, VerificationMethod, VerificationRelationship,
};
use crate::jose::{Jwk, JwkError};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Dereferenced {
Document(Box<DidDocument>),
VerificationMethod(Box<VerificationMethod>),
Service(Box<Service>),
}
impl Dereferenced {
pub fn as_document(&self) -> Option<&DidDocument> {
match self {
Self::Document(document) => Some(document),
_ => None,
}
}
pub fn as_verification_method(&self) -> Option<&VerificationMethod> {
match self {
Self::VerificationMethod(method) => Some(method),
_ => None,
}
}
pub fn as_service(&self) -> Option<&Service> {
match self {
Self::Service(service) => Some(service),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum DereferenceError {
#[error("resolving `{did}`: {error}")]
Resolution {
did: Did,
#[source]
error: ResolutionError,
},
#[error("`{url}`: {reason}")]
InvalidDidUrl {
url: DidUrl,
reason: String,
},
#[error("`{0}` has a path or query that only its DID method can dereference")]
MethodSpecific(DidUrl),
#[error("`{0}` is deactivated")]
Deactivated(Did),
#[error("`{0}` names no verification method or service of the DID document")]
NotFound(DidUrl),
#[error("`{0}` is not a verification method")]
NotVerificationMethod(DidUrl),
#[error("verification method `{id}` is not listed under `{relationship}`")]
NotInRelationship {
id: DidUrl,
relationship: VerificationRelationship,
},
#[error("verification method `{id}` of type `{method_type}` has no usable JWK: {source}")]
NoJwk {
id: DidUrl,
method_type: MethodType,
#[source]
source: Box<JwkError>,
},
}
impl Resolver {
pub async fn dereference(&self, url: &DidUrl) -> Result<Dereferenced, DereferenceError> {
let document = self.resolve_for(url).await?;
let Some(fragment) = url.fragment() else {
return Ok(Dereferenced::Document(Box::new(document)));
};
let id = document.id.to_url().with_fragment(fragment);
if let Some(method) = document.verification_method(&id) {
return Ok(Dereferenced::VerificationMethod(Box::new(method.clone())));
}
if let Some(service) = document.service(&id) {
return Ok(Dereferenced::Service(Box::new(service.clone())));
}
Err(DereferenceError::NotFound(id))
}
pub async fn resolve_verification_method(
&self,
url: &DidUrl,
relationship: Option<VerificationRelationship>,
) -> Result<VerificationMethod, DereferenceError> {
let document = self.resolve_for(url).await?;
verification_method_in(&document, url, relationship).cloned()
}
pub async fn resolve_public_key(
&self,
url: &DidUrl,
relationship: Option<VerificationRelationship>,
) -> Result<Jwk, DereferenceError> {
let method = self.resolve_verification_method(url, relationship).await?;
public_key(&method)
}
async fn resolve_for(&self, url: &DidUrl) -> Result<DidDocument, DereferenceError> {
let options = resolution_options(url)?;
let did = url.did();
let result = self.resolve_with(did, &options).await.map_err(|error| {
DereferenceError::Resolution {
did: did.clone(),
error,
}
})?;
if result.document_metadata.is_deactivated() {
return Err(DereferenceError::Deactivated(did.clone()));
}
result
.into_document()
.map_err(|error| DereferenceError::Resolution {
did: did.clone(),
error,
})
}
}
const VERSION_PARAMETERS: [&str; 2] = ["versionId", "versionTime"];
pub(crate) fn verification_method_in<'a>(
document: &'a DidDocument,
url: &DidUrl,
relationship: Option<VerificationRelationship>,
) -> Result<&'a VerificationMethod, DereferenceError> {
let Some(fragment) = url.fragment() else {
return Err(DereferenceError::NotVerificationMethod(url.clone()));
};
let id = document.id.to_url().with_fragment(fragment);
document
.resolve_verification_method(&id, relationship)
.map_err(|error| match error {
DocumentError::NotInRelationship { id, relationship } => {
DereferenceError::NotInRelationship { id, relationship }
}
_ if document.service(&id).is_some() => DereferenceError::NotVerificationMethod(id),
_ => DereferenceError::NotFound(id),
})
}
pub(crate) fn public_key(method: &VerificationMethod) -> Result<Jwk, DereferenceError> {
match &method.material {
VerificationMaterial::PublicKeyJwk(jwk) => Ok(jwk.public()),
VerificationMaterial::PublicKeyMultibase(multikey) => {
Jwk::from_multikey(multikey).map_err(|source| DereferenceError::NoJwk {
id: method.id.clone(),
method_type: method.method_type.clone(),
source: Box::new(source),
})
}
}
}
fn resolution_options(url: &DidUrl) -> Result<ResolutionOptions, DereferenceError> {
if url.path().is_some() {
return Err(DereferenceError::MethodSpecific(url.clone()));
}
let mut options = ResolutionOptions::default();
let Some(query) = url.query() else {
return Ok(options);
};
for pair in query.split('&').filter(|pair| !pair.is_empty()) {
let (name, value) = pair.split_once('=').unwrap_or((pair, ""));
let name = percent_decode(name);
if !VERSION_PARAMETERS.contains(&name.as_str()) {
return Err(DereferenceError::MethodSpecific(url.clone()));
}
let value = Value::String(percent_decode(value));
if options.properties.insert(name.clone(), value).is_some() {
return Err(DereferenceError::InvalidDidUrl {
url: url.clone(),
reason: format!("DID parameter `{name}` is given twice"),
});
}
}
Ok(options)
}
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let decoded = (bytes[i] == b'%')
.then(|| bytes.get(i + 1..i + 3))
.flatten()
.and_then(|hex| core::str::from_utf8(hex).ok())
.and_then(|hex| u8::from_str_radix(hex, 16).ok());
if let Some(byte) = decoded {
out.push(byte);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8_lossy(&out).into_owned()
}