ma_core/ipfs/
gateway_resolver.rs1use super::gateway::GatewayPool;
8use super::ttl_cache::{Cached, TtlCache};
9use crate::Document;
10use async_trait::async_trait;
11use web_time::Duration;
12
13#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
18#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
19pub trait DidDocumentResolver: Send + Sync {
20 async fn resolve(&self, did: &str) -> crate::error::Result<Document>;
21
22 fn set_cache_ttls(&self, _positive_ttl: Duration, _negative_ttl: Duration) {}
26
27 fn cache_ttls(&self) -> Option<(Duration, Duration)> {
29 None
30 }
31}
32
33#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
38#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
39pub trait IpnsPathResolver: Send + Sync {
40 async fn resolve_ipns_path(&self, path: &str) -> crate::error::Result<String>;
41}
42
43pub struct IpfsGatewayResolver {
48 pool: GatewayPool,
49 cache: TtlCache<Vec<u8>>,
50 ipns_cache: TtlCache<String>,
51}
52
53impl Default for IpfsGatewayResolver {
54 fn default() -> Self {
56 Self::from_pool(GatewayPool::default())
57 }
58}
59
60impl From<GatewayPool> for IpfsGatewayResolver {
61 fn from(pool: GatewayPool) -> Self {
62 Self::from_pool(pool)
63 }
64}
65
66impl IpfsGatewayResolver {
67 #[must_use]
69 pub fn public_default() -> Self {
70 Self::from_pool(GatewayPool::public_default())
71 }
72
73 #[must_use]
77 pub fn new(gateway_url: impl Into<String>) -> Self {
78 Self::from_pool(GatewayPool::new(gateway_url))
79 }
80
81 #[must_use]
84 pub fn local_first(gateway_url: impl Into<String>) -> Self {
85 Self::from_pool(GatewayPool::local_first(gateway_url))
86 }
87
88 fn from_pool(pool: GatewayPool) -> Self {
89 Self {
90 pool,
91 cache: TtlCache::new(Duration::from_mins(1), Duration::from_secs(10)),
92 ipns_cache: TtlCache::new(Duration::from_mins(1), Duration::from_secs(10)),
93 }
94 }
95
96 #[must_use]
98 pub fn pool(&self) -> &GatewayPool {
99 &self.pool
100 }
101
102 #[must_use]
103 pub fn with_cache_ttls(self, positive_ttl: Duration, negative_ttl: Duration) -> Self {
104 self.cache.set_ttls(positive_ttl, negative_ttl);
105 self.ipns_cache.set_ttls(positive_ttl, negative_ttl);
106 self
107 }
108
109 #[must_use]
113 pub fn with_base_cooldown(mut self, cooldown: Duration) -> Self {
114 self.pool = self.pool.with_base_cooldown(cooldown);
115 self
116 }
117
118 #[must_use]
121 pub fn with_request_timeout(self, timeout: Duration) -> Self {
122 self.pool.set_request_timeout(Some(timeout));
123 self
124 }
125
126 pub fn set_request_timeout(&self, timeout: Option<Duration>) {
129 self.pool.set_request_timeout(timeout);
130 }
131
132 pub async fn resolve_ipns_path(&self, path: &str) -> crate::error::Result<String> {
134 self.resolve_ipns_path_cached(path).await
135 }
136
137 async fn resolve_ipns_path_cached(&self, path: &str) -> crate::error::Result<String> {
138 if let Some(cached) = self.ipns_cache.read(path) {
139 return Self::cached_ipns_result(cached, path);
140 }
141
142 let lock = self.ipns_cache.lock_for(path);
143 let _guard = lock.lock().await;
144
145 if let Some(cached) = self.ipns_cache.read(path) {
146 self.ipns_cache.release_lock(path, &lock);
147 return Self::cached_ipns_result(cached, path);
148 }
149
150 match self.pool.resolve_ipns_path(path).await {
151 Ok(resolved) => {
152 self.ipns_cache
153 .write_hit(path.to_string(), resolved.clone());
154 self.ipns_cache.release_lock(path, &lock);
155 Ok(resolved)
156 }
157 Err(e) => {
158 let detail = e.to_string();
159 self.ipns_cache.write_miss(path.to_string(), detail);
160 self.ipns_cache.release_lock(path, &lock);
161 Err(e)
162 }
163 }
164 }
165
166 fn cached_ipns_result(cached: Cached<String>, path: &str) -> crate::error::Result<String> {
167 match cached {
168 Cached::Hit(resolved) => Ok(resolved),
169 Cached::Miss(detail) => Err(crate::error::Error::IpnsResolution {
170 path: path.to_string(),
171 detail,
172 }),
173 }
174 }
175
176 fn cached_result(cached: Cached<Vec<u8>>, did: String) -> crate::error::Result<Document> {
177 match cached {
178 Cached::Hit(body) => {
179 parse_document_bytes(&body).map_err(|detail| crate::error::Error::Resolution {
180 did,
181 detail: format!("cached document parse failed: {detail}"),
182 })
183 }
184 Cached::Miss(detail) => Err(crate::error::Error::Resolution { did, detail }),
185 }
186 }
187}
188
189#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
190#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
191impl DidDocumentResolver for IpfsGatewayResolver {
192 async fn resolve(&self, did: &str) -> crate::error::Result<Document> {
193 let parsed = crate::Did::try_from(did).map_err(crate::error::Error::Validation)?;
194 let did_key = parsed.base_id();
196
197 if let Some(cached) = self.cache.read(&did_key) {
198 return Self::cached_result(cached, did_key);
199 }
200
201 let resolve_lock = self.cache.lock_for(&did_key);
202 let _resolve_guard = resolve_lock.lock().await;
203
204 if let Some(cached) = self.cache.read(&did_key) {
207 self.cache.release_lock(&did_key, &resolve_lock);
208 return Self::cached_result(cached, did_key);
209 }
210
211 let path = format!("/ipns/{}", parsed.ipns);
212 let fetched = self
213 .pool
214 .fetch(&path, Some("application/vnd.ipld.dag-cbor"), |body| {
215 parse_document_bytes(body)
216 .map(|document| (document, body.to_vec()))
217 .map_err(|detail| format!("invalid DID document: {detail}"))
218 })
219 .await;
220
221 match fetched {
222 Ok((document, body)) => {
223 self.cache.write_hit(did_key.clone(), body);
224 self.cache.release_lock(&did_key, &resolve_lock);
225 Ok(document)
226 }
227 Err(detail) => {
228 tracing::warn!(did = %did_key, error = %detail, "DID document resolve failed");
229 self.cache.write_miss(did_key.clone(), detail.clone());
230 self.cache.release_lock(&did_key, &resolve_lock);
231 Err(crate::error::Error::Resolution {
232 did: did_key,
233 detail,
234 })
235 }
236 }
237 }
238
239 fn set_cache_ttls(&self, positive_ttl: Duration, negative_ttl: Duration) {
240 self.cache.set_ttls(positive_ttl, negative_ttl);
241 self.ipns_cache.set_ttls(positive_ttl, negative_ttl);
242 }
243
244 fn cache_ttls(&self) -> Option<(Duration, Duration)> {
245 Some((self.cache.positive_ttl(), self.cache.negative_ttl()))
246 }
247}
248
249#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
250#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
251impl IpnsPathResolver for IpfsGatewayResolver {
252 async fn resolve_ipns_path(&self, path: &str) -> crate::error::Result<String> {
253 self.resolve_ipns_path_cached(path).await
254 }
255}
256
257fn parse_document_bytes(bytes: &[u8]) -> std::result::Result<Document, String> {
258 let document =
259 Document::decode(bytes).map_err(|err| format!("DAG-CBOR decode failed: {err}"))?;
260 document
261 .validate()
262 .map_err(|err| format!("document validation failed: {err}"))?;
263 document
264 .verify()
265 .map_err(|err| format!("document proof verification failed: {err}"))?;
266 Ok(document)
267}
268
269#[cfg(test)]
270mod tests {
271 use super::{parse_document_bytes, IpfsGatewayResolver};
272 use crate::{
273 generate_identity_from_secret, ipfs::ttl_cache::Cached,
274 multiformat::signature_multibase_encode, CODEC_EDDSA_SIG,
275 };
276
277 #[test]
278 fn parses_dag_cbor_documents() {
279 let identity = generate_identity_from_secret([7u8; 32]).expect("identity");
280 let cbor = identity.document.encode().expect("cbor");
281 let parsed = parse_document_bytes(&cbor).expect("parsed cbor");
282 assert_eq!(parsed, identity.document);
283 }
284
285 #[test]
286 fn rejects_non_document_payloads() {
287 let err = parse_document_bytes(b"<html>nope</html>").expect_err("invalid payload");
288 assert!(err.contains("DAG-CBOR decode failed"));
289 }
290
291 #[test]
292 fn rejects_json_documents() {
293 let identity = generate_identity_from_secret([5u8; 32]).expect("identity");
294 let json = serde_json::to_vec(&identity.document).expect("json serialize");
295 let err = parse_document_bytes(&json).expect_err("resolver requires DAG-CBOR");
296 assert!(err.contains("DAG-CBOR decode failed"));
297 }
298
299 #[test]
300 fn rejects_document_with_mutated_payload() {
301 let identity = generate_identity_from_secret([9u8; 32]).expect("identity");
302 let mut document = identity.document;
303 document.updated_at = "2026-08-08T12:00:00Z".to_string();
304
305 let err = parse_document_bytes(&document.encode().expect("cbor"))
306 .expect_err("mutated payload must fail proof verification");
307 assert!(err.contains("document proof verification failed"));
308 }
309
310 #[test]
311 fn rejects_document_with_malformed_proof() {
312 let identity = generate_identity_from_secret([11u8; 32]).expect("identity");
313 let mut document = identity.document;
314 document.proof.proof_value = "not-multibase".to_string();
315
316 let err = parse_document_bytes(&document.encode().expect("cbor"))
317 .expect_err("malformed proof must fail verification");
318 assert!(err.contains("document proof verification failed"));
319 }
320
321 #[test]
322 fn rejects_document_with_unknown_proof_key() {
323 let identity = generate_identity_from_secret([13u8; 32]).expect("identity");
324 let mut document = identity.document;
325 document.proof.verification_method = format!("{}#unknown", document.id);
326
327 let err = parse_document_bytes(&document.encode().expect("cbor"))
328 .expect_err("unknown proof key must fail verification");
329 assert!(err.contains("document proof verification failed"));
330 }
331
332 #[test]
333 fn rejects_document_without_assertion_relationship() {
334 let identity = generate_identity_from_secret([15u8; 32]).expect("identity");
335 let mut document = identity.document;
336 document.assertion_method.clear();
337
338 let err = parse_document_bytes(&document.encode().expect("cbor"))
339 .expect_err("missing assertion relationship must fail validation");
340 assert!(err.contains("document validation failed"));
341 }
342
343 #[test]
344 fn rejects_document_with_invalid_signature() {
345 let identity = generate_identity_from_secret([17u8; 32]).expect("identity");
346 let mut document = identity.document;
347 document.proof.proof_value = signature_multibase_encode(CODEC_EDDSA_SIG, &[0; 64]);
348
349 let err = parse_document_bytes(&document.encode().expect("cbor"))
350 .expect_err("invalid signature must fail proof verification");
351 assert!(err.contains("document proof verification failed"));
352 }
353
354 #[test]
355 fn rejects_unverified_cached_document() {
356 let identity = generate_identity_from_secret([19u8; 32]).expect("identity");
357 let did = identity.document.id.clone();
358 let mut document = identity.document;
359 document.updated_at = "2026-08-08T12:00:00Z".to_string();
360
361 let err =
362 IpfsGatewayResolver::cached_result(Cached::Hit(document.encode().expect("cbor")), did)
363 .expect_err("cached document must be proof-verified");
364 assert!(err.to_string().contains("cached document parse failed"));
365 }
366
367 #[test]
368 fn resolver_constructors_delegate_to_pool() {
369 let resolver = IpfsGatewayResolver::new("https://example.test/ipfs");
370 assert_eq!(
371 resolver.pool().gateways(),
372 [
373 "https://example.test/ipfs/".to_string(),
374 "https://ipfs.io/".to_string(),
375 ]
376 );
377 }
378}