1use serde_json::Value;
4
5use super::Resolver;
6use crate::did::{
7 Did, DidDocument, DidUrl, DocumentError, MethodType, ResolutionError, ResolutionOptions,
8 Service, VerificationMaterial, VerificationMethod, VerificationRelationship,
9};
10use crate::jose::{Jwk, JwkError};
11
12#[derive(Debug, Clone, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum Dereferenced {
16 Document(Box<DidDocument>),
18 VerificationMethod(Box<VerificationMethod>),
21 Service(Box<Service>),
23}
24
25impl Dereferenced {
26 pub fn as_document(&self) -> Option<&DidDocument> {
28 match self {
29 Self::Document(document) => Some(document),
30 _ => None,
31 }
32 }
33
34 pub fn as_verification_method(&self) -> Option<&VerificationMethod> {
36 match self {
37 Self::VerificationMethod(method) => Some(method),
38 _ => None,
39 }
40 }
41
42 pub fn as_service(&self) -> Option<&Service> {
44 match self {
45 Self::Service(service) => Some(service),
46 _ => None,
47 }
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
53#[non_exhaustive]
54pub enum DereferenceError {
55 #[error("resolving `{did}`: {error}")]
57 Resolution {
58 did: Did,
60 #[source]
62 error: ResolutionError,
63 },
64 #[error("`{url}`: {reason}")]
66 InvalidDidUrl {
67 url: DidUrl,
69 reason: String,
71 },
72 #[error("`{0}` has a path or query that only its DID method can dereference")]
75 MethodSpecific(DidUrl),
76 #[error("`{0}` is deactivated")]
78 Deactivated(Did),
79 #[error("`{0}` names no verification method or service of the DID document")]
81 NotFound(DidUrl),
82 #[error("`{0}` is not a verification method")]
84 NotVerificationMethod(DidUrl),
85 #[error("verification method `{id}` is not listed under `{relationship}`")]
87 NotInRelationship {
88 id: DidUrl,
90 relationship: VerificationRelationship,
92 },
93 #[error("verification method `{id}` of type `{method_type}` has no usable JWK: {source}")]
96 NoJwk {
97 id: DidUrl,
99 method_type: MethodType,
101 #[source]
103 source: Box<JwkError>,
104 },
105}
106
107impl Resolver {
108 pub async fn dereference(&self, url: &DidUrl) -> Result<Dereferenced, DereferenceError> {
125 let document = self.resolve_for(url).await?;
126 let Some(fragment) = url.fragment() else {
127 return Ok(Dereferenced::Document(Box::new(document)));
128 };
129 let id = document.id.to_url().with_fragment(fragment);
130 if let Some(method) = document.verification_method(&id) {
131 return Ok(Dereferenced::VerificationMethod(Box::new(method.clone())));
132 }
133 if let Some(service) = document.service(&id) {
134 return Ok(Dereferenced::Service(Box::new(service.clone())));
135 }
136 Err(DereferenceError::NotFound(id))
137 }
138
139 pub async fn resolve_verification_method(
149 &self,
150 url: &DidUrl,
151 relationship: Option<VerificationRelationship>,
152 ) -> Result<VerificationMethod, DereferenceError> {
153 let document = self.resolve_for(url).await?;
154 verification_method_in(&document, url, relationship).cloned()
155 }
156
157 pub async fn resolve_public_key(
168 &self,
169 url: &DidUrl,
170 relationship: Option<VerificationRelationship>,
171 ) -> Result<Jwk, DereferenceError> {
172 let method = self.resolve_verification_method(url, relationship).await?;
173 public_key(&method)
174 }
175
176 async fn resolve_for(&self, url: &DidUrl) -> Result<DidDocument, DereferenceError> {
179 let options = resolution_options(url)?;
180 let did = url.did();
181 let result = self.resolve_with(did, &options).await.map_err(|error| {
182 DereferenceError::Resolution {
183 did: did.clone(),
184 error,
185 }
186 })?;
187 if result.document_metadata.is_deactivated() {
188 return Err(DereferenceError::Deactivated(did.clone()));
189 }
190 result
192 .into_document()
193 .map_err(|error| DereferenceError::Resolution {
194 did: did.clone(),
195 error,
196 })
197 }
198}
199
200const VERSION_PARAMETERS: [&str; 2] = ["versionId", "versionTime"];
202
203pub(crate) fn verification_method_in<'a>(
206 document: &'a DidDocument,
207 url: &DidUrl,
208 relationship: Option<VerificationRelationship>,
209) -> Result<&'a VerificationMethod, DereferenceError> {
210 let Some(fragment) = url.fragment() else {
211 return Err(DereferenceError::NotVerificationMethod(url.clone()));
212 };
213 let id = document.id.to_url().with_fragment(fragment);
214 document
215 .resolve_verification_method(&id, relationship)
216 .map_err(|error| match error {
217 DocumentError::NotInRelationship { id, relationship } => {
218 DereferenceError::NotInRelationship { id, relationship }
219 }
220 _ if document.service(&id).is_some() => DereferenceError::NotVerificationMethod(id),
221 _ => DereferenceError::NotFound(id),
222 })
223}
224
225pub(crate) fn public_key(method: &VerificationMethod) -> Result<Jwk, DereferenceError> {
228 match &method.material {
229 VerificationMaterial::PublicKeyJwk(jwk) => Ok(jwk.public()),
230 VerificationMaterial::PublicKeyMultibase(multikey) => {
231 Jwk::from_multikey(multikey).map_err(|source| DereferenceError::NoJwk {
232 id: method.id.clone(),
233 method_type: method.method_type.clone(),
234 source: Box::new(source),
235 })
236 }
237 }
238}
239
240fn resolution_options(url: &DidUrl) -> Result<ResolutionOptions, DereferenceError> {
242 if url.path().is_some() {
243 return Err(DereferenceError::MethodSpecific(url.clone()));
244 }
245 let mut options = ResolutionOptions::default();
246 let Some(query) = url.query() else {
247 return Ok(options);
248 };
249 for pair in query.split('&').filter(|pair| !pair.is_empty()) {
250 let (name, value) = pair.split_once('=').unwrap_or((pair, ""));
251 let name = percent_decode(name);
252 if !VERSION_PARAMETERS.contains(&name.as_str()) {
253 return Err(DereferenceError::MethodSpecific(url.clone()));
254 }
255 let value = Value::String(percent_decode(value));
256 if options.properties.insert(name.clone(), value).is_some() {
257 return Err(DereferenceError::InvalidDidUrl {
258 url: url.clone(),
259 reason: format!("DID parameter `{name}` is given twice"),
260 });
261 }
262 }
263 Ok(options)
264}
265
266fn percent_decode(s: &str) -> String {
269 let bytes = s.as_bytes();
270 let mut out = Vec::with_capacity(bytes.len());
271 let mut i = 0;
272 while i < bytes.len() {
273 let decoded = (bytes[i] == b'%')
274 .then(|| bytes.get(i + 1..i + 3))
275 .flatten()
276 .and_then(|hex| core::str::from_utf8(hex).ok())
277 .and_then(|hex| u8::from_str_radix(hex, 16).ok());
278 if let Some(byte) = decoded {
279 out.push(byte);
280 i += 3;
281 } else {
282 out.push(bytes[i]);
283 i += 1;
284 }
285 }
286 String::from_utf8_lossy(&out).into_owned()
287}