Skip to main content

qualia_core_db/sparql_library/
sparql_did.rs

1//! SPARQL-DID Integration
2//!
3//! Zero-allocation implementation of DID extension functions for SPARQL.
4//! Implements Appendix B of the SPARQL-DID Integration Specification.
5
6use crate::sparql_ast::*;
7use crate::NQuin;
8
9/// DID resolution result for the SPARQL ABI layer.
10///
11/// This is the **pointer-resolution** view: a `did:q42` URI is a topological
12/// coordinate (see [`crate::identifier::parse_did_q42`]), and the SPARQL query
13/// engine addresses DIDs as `u64` pointers. `endpoint_url` and
14/// `verification_method` here are therefore `q_hash`-space pointers to the
15/// human-readable strings produced by [`DIDResolver::resolve`].
16///
17/// Fixed-size (`#[repr(C)]`) to preserve the zero-allocation ABI used by the
18/// SPARQL `did:resolve` magic-property wrapper.
19#[repr(C)]
20#[derive(Debug, Clone, Copy)]
21pub struct DidResolutionPointer {
22    pub did: u64,
23    pub endpoint_url: u64,
24    pub verification_method: u64,
25    pub expires: u64,
26}
27
28/// DID resolution result (human-readable, string-based).
29///
30/// Produced by [`DIDResolver::resolve`]. This is **not** a hot path (the SPARQL
31/// ABI layer uses [`DidResolutionPointer`]), so it owns `String`s and carries
32/// the real, deterministic endpoint URL and verification method for a DID.
33#[derive(Debug, Clone)]
34pub struct DidResolutionResult {
35    /// The DID that was resolved (e.g. `did:q42:z6MkpTHR8VNs`).
36    pub did: String,
37    /// A valid, deterministic HTTPS endpoint URL for the DID method.
38    pub endpoint_url: String,
39    /// The verification method identifier (a DID URI fragment or absolute URI).
40    pub verification_method: String,
41    /// Unix-epoch milliseconds at which the resolution was performed.
42    pub resolved_at: u64,
43}
44
45/// DID signature verification result
46#[repr(C)]
47#[derive(Debug, Clone, Copy)]
48pub struct DidVerificationResult {
49    pub did: u64,
50    pub valid: bool,
51    pub algorithm: u8,
52}
53
54/// DID permission check result
55#[repr(C)]
56#[derive(Debug, Clone, Copy)]
57pub struct DidPermissionResult {
58    pub did: u64,
59    pub graph: u64,
60    pub has_permission: bool,
61    pub permission_type: u8, // 0=read, 1=write, 2=admin
62}
63
64/// DID cache entry (fixed-size array for zero-allocation)
65#[repr(C)]
66#[derive(Debug, Clone, Copy)]
67pub struct DidCacheEntry {
68    pub did: u64,
69    pub resolution: DidResolutionPointer,
70    pub timestamp: u64,
71    pub ttl: u32,
72}
73
74/// SPARQL-DID Handler
75pub struct SparqlDidHandler<'a> {
76    pub quins: &'a [NQuin],
77    pub did_cache: [Option<DidCacheEntry>; 32],
78    pub cache_count: u8,
79}
80
81impl<'a> SparqlDidHandler<'a> {
82    /// Creates a default `SparqlDidHandler`.
83    pub fn new(quins: &'a [NQuin]) -> Self {
84        Self {
85            quins,
86            did_cache: [None; 32],
87            cache_count: 0,
88        }
89    }
90
91    /// Resolve a `u64` DID pointer to ABI-layer endpoint/verification pointers
92    /// (with caching).
93    ///
94    /// `endpoint_url` and `verification_method` are derived via FNV-1a over the
95    /// DID's 60-bit identity bytes, salted with a method tag — **not** XOR with a
96    /// magic number. They live in the same `q_hash` pointer space as the rest of
97    /// the SPARQL engine. The human-readable URL and verification-method string
98    /// for a DID are available via [`DIDResolver::resolve`].
99    pub fn resolve_did(&mut self, did: u64) -> Result<DidResolutionPointer, String> {
100        // Check cache first (zero-allocation lookup)
101        for i in 0..self.cache_count as usize {
102            if let Some(entry) = self.did_cache[i] {
103                if entry.did == did {
104                    let now = self.current_timestamp();
105                    // `ttl` is in seconds; timestamps are ms. Saturating so a clock skew
106                    // (now < timestamp) simply treats the entry as fresh, never panics.
107                    if now.saturating_sub(entry.timestamp) < (entry.ttl as u64) * 1000 {
108                        return Ok(entry.resolution);
109                    }
110                }
111            }
112        }
113
114        // Deterministic pointer derivation: FNV-1a over the 60-bit identity,
115        // salted with a domain tag so endpoint and verification-method pointers
116        // cannot collide with each other or with plain dictionary hashes.
117        let id_bytes = (did & 0x0FFF_FFFF_FFFF_FFFF).to_le_bytes();
118        let endpoint_url = fnv1a_tagged(b"did:endpoint:", &id_bytes);
119        let verification_method = fnv1a_tagged(b"did:vm:", &id_bytes);
120
121        let resolution = DidResolutionPointer {
122            did,
123            endpoint_url,
124            verification_method,
125            expires: self.current_timestamp() + 3600000, // 1 hour TTL
126        };
127
128        // Cache the result
129        if self.cache_count < 32 {
130            let entry = DidCacheEntry {
131                did,
132                resolution,
133                timestamp: self.current_timestamp(),
134                ttl: 3600,
135            };
136            self.did_cache[self.cache_count as usize] = Some(entry);
137            self.cache_count += 1;
138        }
139
140        Ok(resolution)
141    }
142
143    /// Verify DID signature (zero-allocation using stack-allocated key frame)
144    pub fn verify_signature(
145        &self,
146        _did: u64,
147        signature: &[u8],
148        data: &[u8],
149    ) -> Result<DidVerificationResult, String> {
150        if signature.len() != 64 {
151            return Err("Invalid signature length".to_string());
152        }
153
154        let _ = (signature, data);
155
156        #[cfg(feature = "interop-crypto")]
157        {
158            use ed25519_dalek::{Signature, Verifier, VerifyingKey};
159
160            let mut sig_bytes = [0u8; 64];
161            sig_bytes.copy_from_slice(signature);
162            if let Ok(sig) = Signature::from_bytes(&sig_bytes) {
163                // Fast-path: if the SPARQL query supplies the public key prepended to the data
164                // (32 bytes PK + payload), we can verify it immediately at the boundary.
165                if data.len() > 32 {
166                    let mut pk_bytes = [0u8; 32];
167                    pk_bytes.copy_from_slice(&data[0..32]);
168                    if let Ok(verifying_key) = VerifyingKey::from_bytes(&pk_bytes) {
169                        let valid = verifying_key.verify(&data[32..], &sig).is_ok();
170                        if valid {
171                            return Ok(DidVerificationResult {
172                                did: _did,
173                                valid: true,
174                                algorithm: 1, // Ed25519
175                            });
176                        }
177                    }
178                }
179            }
180        }
181
182        // If we reach here, either interop-crypto is disabled or the fast-path failed.
183        // We do not have the public key locally, so we fail closed.
184        Err(
185            "did:verify fast-path failed: no resolvable verification key is provisioned \
186             in the SPARQL read-side shim. Verify via the identity/key-vault layer \
187             (KeyVault::verify_signature)."
188                .to_string(),
189        )
190    }
191
192    /// Check DID permission for graph access
193    pub fn check_permission(
194        &self,
195        did: u64,
196        graph: u64,
197        permission_type: u8,
198    ) -> Result<DidPermissionResult, String> {
199        // Check DID has 0x8 prefix
200        if (did & 0x8000000000000000) == 0 {
201            return Err("Invalid DID: missing 0x8 prefix".to_string());
202        }
203
204        let _ = (graph, permission_type);
205
206        // FAIL CLOSED. Access control must be decided by an authority that has
207        // actually evaluated the permission graph (the Webizen VM / deontic policy
208        // layer), not granted unconditionally here. Returning `has_permission: true`
209        // would be an authorization bypass: any caller would be granted any graph.
210        Err(
211            "did:permission is not available in the SPARQL query layer: \
212             access-control decisions must be evaluated against the policy graph by \
213             the governance layer, not granted unconditionally here."
214                .to_string(),
215        )
216    }
217
218    /// Authenticate with DID (strips heavy payloads at boundary)
219    pub fn authenticate_did(
220        &self,
221        did: u64,
222        auth_method: u8,
223        _auth_payload: &[u8],
224    ) -> Result<bool, String> {
225        // Check DID has 0x8 prefix
226        if (did & 0x8000000000000000) == 0 {
227            return Err("Invalid DID: missing 0x8 prefix".to_string());
228        }
229
230        let _ = auth_method;
231
232        // FAIL CLOSED. Authentication requires verifying `_auth_payload` (a JSON-LD
233        // proof / VC / challenge response) against a resolved verification method.
234        // This shim strips that payload at the boundary and holds no key material, so
235        // it cannot authenticate anyone. Returning `Ok(true)` would authenticate every
236        // caller. Route authentication through the identity layer instead.
237        Err("did:auth is not available in the SPARQL query layer: \
238             the authentication proof is stripped at this boundary and cannot be \
239             verified here. Authenticate via the identity/key-vault layer."
240            .to_string())
241    }
242
243    /// Current wall-clock time in Unix-epoch milliseconds (real system time). Used for
244    /// cache freshness; `0` only if the system clock is before the epoch.
245    fn current_timestamp(&self) -> u64 {
246        std::time::SystemTime::now()
247            .duration_since(std::time::UNIX_EPOCH)
248            .map(|d| d.as_millis() as u64)
249            .unwrap_or(0)
250    }
251
252    /// Sign data with DID (zero-allocation)
253    pub fn sign_with_did(&self, did: u64, data: &[u8]) -> Result<Vec<u8>, String> {
254        // Check DID has 0x8 prefix
255        if (did & 0x8000000000000000) == 0 {
256            return Err("Invalid DID: missing 0x8 prefix".to_string());
257        }
258
259        // The SPARQL-DID handler is a read-side query shim: it resolves DIDs to u64
260        // pointers and deliberately strips heavy crypto payloads at the boundary
261        // (see `authenticate_did`). It holds NO private key material, so it cannot and
262        // must not produce a signature here. Signing is the responsibility of the
263        // identity / key-vault layer (e.g. `WebizenIdentityManager` over `key_vault`,
264        // or `CryptographicLibrary::sign_data`), which owns the secret keys.
265        //
266        // Fail closed rather than returning a forged all-zero signature that would
267        // falsely signal success to callers.
268        let _ = data;
269        Err("did:sign is not available in the SPARQL query layer: \
270             no private key is provisioned here. Sign via the identity/key-vault \
271             layer (WebizenIdentityManager / CryptographicLibrary::sign_data)."
272            .to_string())
273    }
274
275    /// Invalidate cache entry
276    pub fn invalidate_cache(&mut self, did: u64) {
277        for i in 0..self.cache_count as usize {
278            if let Some(entry) = self.did_cache[i] {
279                if entry.did == did {
280                    self.did_cache[i] = None;
281                    // Compact cache
282                    for j in i..self.cache_count as usize - 1 {
283                        self.did_cache[j] = self.did_cache[j + 1];
284                    }
285                    self.cache_count -= 1;
286                    return;
287                }
288            }
289        }
290    }
291}
292
293impl<'a> Default for SparqlDidHandler<'a> {
294    fn default() -> Self {
295        Self::new(&[])
296    }
297}
298
299/// DID extension functions (Appendix B)
300/// These are assigned to 0x0 standard dictionary type prefix during planning
301/// to identify them as Magic Property Functions
302
303/// did:resolve - Resolve DID to Document
304///
305/// ABI-layer wrapper: emits the `endpoint_url` and `verification_method`
306/// **pointers** (in `q_hash` space) for the SPARQL binding. For the
307/// human-readable URL, use [`DIDResolver::resolve`].
308pub fn did_resolve(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
309    if args.is_empty() {
310        return false;
311    }
312    let did = args[0];
313
314    let mut handler = SparqlDidHandler::new(quins);
315    match handler.resolve_did(did) {
316        Ok(resolution) => {
317            result.slots[0] = Some(resolution.endpoint_url);
318            result.slots[1] = Some(resolution.verification_method);
319            true
320        }
321        Err(_) => false,
322    }
323}
324
325/// did:verify - Verify DID signature
326pub fn did_verify(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
327    if args.len() < 3 {
328        return false;
329    }
330    let did = args[0];
331    let signature_ptr = args[1];
332    let data_ptr = args[2];
333
334    let handler = SparqlDidHandler::new(quins);
335    // SAFETY: never interpret a query-supplied `u64` as a raw memory pointer — that was
336    // undefined behaviour / an arbitrary-read hazard, and violates "no native pointers
337    // cross the query API". This magic-predicate wrapper holds no resolver to recover the
338    // real signature/data bytes, so it passes empty slices and `verify_signature` fails
339    // closed. Real byte payloads reach did:verify through the resolver-aware dispatch.
340    let _ = (signature_ptr, data_ptr);
341    let signature: &[u8] = &[];
342    let data: &[u8] = &[];
343
344    match handler.verify_signature(did, signature, data) {
345        Ok(verification) => {
346            result.slots[0] = Some(if verification.valid { 1 } else { 0 });
347            result.slots[1] = Some(verification.algorithm as u64);
348            true
349        }
350        Err(_) => false,
351    }
352}
353
354/// did:auth - Authenticate with DID
355pub fn did_auth(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
356    if args.len() < 2 {
357        return false;
358    }
359    let did = args[0];
360    let auth_method = args[1] as u8;
361
362    let handler = SparqlDidHandler::new(quins);
363    // SAFETY: do NOT dereference a query-supplied `u64` as a pointer (see did_verify).
364    // The proof payload is not recoverable here; pass empty → authenticate_did fails
365    // closed (it already refuses to authenticate without a verifiable proof).
366    let auth_payload: &[u8] = &[];
367
368    match handler.authenticate_did(did, auth_method, auth_payload) {
369        Ok(valid) => {
370            result.slots[0] = Some(if valid { 1 } else { 0 });
371            true
372        }
373        Err(_) => false,
374    }
375}
376
377/// did:sign - Sign with DID
378pub fn did_sign(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
379    if args.len() < 2 {
380        return false;
381    }
382    let did = args[0];
383    let data_ptr = args[1];
384
385    let handler = SparqlDidHandler::new(quins);
386    // SAFETY: do NOT dereference a query-supplied `u64` as a pointer (see did_verify).
387    // sign_with_did fails closed regardless (no private key in the query layer).
388    let _ = data_ptr;
389    let data: &[u8] = &[];
390
391    match handler.sign_with_did(did, data) {
392        Ok(_signature) => {
393            result.slots[0] = Some(1); // Success indicator
394            true
395        }
396        Err(_) => false,
397    }
398}
399
400/// did:permission - Check DID permission
401pub fn did_permission(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
402    if args.len() < 3 {
403        return false;
404    }
405    let did = args[0];
406    let graph = args[1];
407    let permission_type = args[2] as u8;
408
409    let handler = SparqlDidHandler::new(quins);
410    match handler.check_permission(did, graph, permission_type) {
411        Ok(permission) => {
412            result.slots[0] = Some(if permission.has_permission { 1 } else { 0 });
413            result.slots[1] = Some(permission.permission_type as u64);
414            true
415        }
416        Err(_) => false,
417    }
418}
419
420/// FNV-1a over a domain tag followed by a byte payload, truncated to 60 bits.
421///
422/// Used by [`SparqlDidHandler::resolve_did`] to derive deterministic
423/// `endpoint_url` / `verification_method` pointers from a DID's identity bits
424/// without XOR-ing against a magic constant. Shares the same FNV constants and
425/// 60-bit mask as [`crate::q_hash`] / [`crate::identifier::parse_did_q42`].
426#[inline]
427fn fnv1a_tagged(tag: &[u8], payload: &[u8]) -> u64 {
428    let mut hash: u64 = 0xcbf29ce484222325;
429    for &b in tag {
430        hash ^= b as u64;
431        hash = hash.wrapping_mul(0x100000001b3);
432    }
433    for &b in payload {
434        hash ^= b as u64;
435        hash = hash.wrapping_mul(0x100000001b3);
436    }
437    hash & 0x0FFF_FFFF_FFFF_FFFF
438}
439
440/// Human-readable DID resolver.
441///
442/// Maps a DID string to a deterministic, valid HTTPS endpoint URL and
443/// verification-method identifier according to the DID method's resolution
444/// convention. This is **not** HTTP resolution (no network call is made); it
445/// produces the URL that *would* be fetched by a universal resolver / the
446/// method's native resolution endpoint. This module is not a hot path, so it
447/// owns `String`s freely.
448///
449/// # Supported methods
450/// | Method | Endpoint URL | Verification method |
451/// |--------|--------------|---------------------|
452/// | `did:q42:` | `https://q42.network/agents/{id_hex}` | `{did}#q42-key` |
453/// | `did:web:` | `https://{domain}/.well-known/did.json` | `{did}#key-1` |
454/// | `did:key:` | `https://dev.uniresolver.io/1.0/identifiers/{did}` | `{did}` |
455pub struct DIDResolver;
456
457impl DIDResolver {
458    /// Construct a new resolver.
459    pub fn new() -> Self {
460        Self
461    }
462
463    /// Resolve a DID to a human-readable endpoint URL and verification method.
464    ///
465    /// Delegates to [`Self::resolve_did`]; provided as the canonical entry point
466    /// named in the SPARQL-DID Integration Specification.
467    pub fn resolve(&self, did: &str) -> Result<DidResolutionResult, String> {
468        self.resolve_did(did)
469    }
470
471    /// Resolve a DID to a human-readable endpoint URL and verification method.
472    pub fn resolve_did(&self, did: &str) -> Result<DidResolutionResult, String> {
473        let resolved_at = current_epoch_millis();
474
475        if let Some(rest) = did.strip_prefix("did:q42:") {
476            if rest.is_empty() {
477                return Err("did:q42 resolution failed: empty identifier".to_string());
478            }
479            // Parse via the identifier module to validate the DID and obtain the
480            // canonical 60-bit topological pointer; the low 60 bits are the
481            // identity hash, which we render as hex for the agent URL.
482            let pointer = crate::identifier::parse_did_q42(did.as_bytes())
483                .map_err(|e| format!("did:q42 resolution failed: {:?}", e))?;
484            let id_hex = format!("{:015x}", pointer & 0x0FFF_FFFF_FFFF_FFFF);
485            Ok(DidResolutionResult {
486                did: did.to_string(),
487                endpoint_url: format!("https://q42.network/agents/{}", id_hex),
488                verification_method: format!("{}#q42-key", did),
489                resolved_at,
490            })
491        } else if let Some(rest) = did.strip_prefix("did:web:") {
492            if rest.is_empty() {
493                return Err("did:web resolution failed: empty domain".to_string());
494            }
495            // did:web resolution: replace ':' with '/' for path components, then
496            // append the standard well-known DID document location.
497            let domain_path = rest.replace(':', "/");
498            Ok(DidResolutionResult {
499                did: did.to_string(),
500                endpoint_url: format!("https://{}/.well-known/did.json", domain_path),
501                verification_method: format!("{}#key-1", did),
502                resolved_at,
503            })
504        } else if let Some(rest) = did.strip_prefix("did:key:") {
505            if rest.is_empty() {
506                return Err("did:key resolution failed: empty key".to_string());
507            }
508            // did:key embeds the public key in the DID itself; the DID is its own
509            // verification method (per the did:key spec). There is no native HTTP
510            // endpoint, so we point at a universal resolver for retrieval.
511            Ok(DidResolutionResult {
512                did: did.to_string(),
513                endpoint_url: format!("https://dev.uniresolver.io/1.0/identifiers/{}", did),
514                verification_method: did.to_string(),
515                resolved_at,
516            })
517        } else if did.starts_with("did:") {
518            // Unknown DID method.
519            let method = did
520                .get(4..)
521                .and_then(|s| s.split(':').next())
522                .unwrap_or("unknown");
523            Err(format!(
524                "DID resolution failed: unsupported DID method '{}'. \
525                 Supported methods: did:q42, did:web, did:key.",
526                method
527            ))
528        } else {
529            Err(format!(
530                "DID resolution failed: '{}' is not a valid DID (must start with 'did:')",
531                did
532            ))
533        }
534    }
535
536    /// Verify a DID's authentication signature.
537    ///
538    /// This performs only the **structural** checks available to the read-side
539    /// SPARQL query layer (that the DID is well-formed and resolvable, and that
540    /// a non-empty signature and payload were supplied). The actual
541    /// cryptographic verification requires public-key material that this shim
542    /// deliberately does not hold — it is the responsibility of the identity /
543    /// key-vault layer ([`crate::key_vault::KeyVault::verify_signature`] /
544    /// `WebizenIdentityRegistry::verify_signature`).
545    ///
546    /// Fails closed: never reports a signature as valid from this layer.
547    pub fn verify_authentication_signature(
548        &self,
549        did: &str,
550        signature: &[u8],
551        payload: &[u8],
552    ) -> Result<bool, String> {
553        // Structural validation: the DID must resolve (be well-formed + known method).
554        self.resolve_did(did)?;
555
556        if signature.is_empty() {
557            return Err("DID signature verification failed: empty signature".to_string());
558        }
559        if payload.is_empty() {
560            return Err("DID signature verification failed: empty payload".to_string());
561        }
562
563        // FAIL CLOSED — see the security rationale on
564        // [`SparqlDidHandler::verify_signature`]. This layer holds no
565        // verifiable public key, so it cannot perform a real Ed25519/ML-DSA
566        // check. Returning `true` would forge a positive verification.
567        Err("did:verify is not available in the SPARQL query layer: \
568             no resolvable verification key is provisioned here. Verify via the \
569             identity/key-vault layer (KeyVault::verify_signature / \
570             WebizenIdentityRegistry::verify_signature)."
571            .to_string())
572    }
573}
574
575impl Default for DIDResolver {
576    fn default() -> Self {
577        Self::new()
578    }
579}
580
581/// Current time as Unix-epoch milliseconds.
582///
583/// The SPARQL ABI layer (`SparqlDidHandler::current_timestamp`) returns a
584/// placeholder because it must stay allocation-free and deterministic for the
585/// query planner. The human-readable resolver is not a hot path, so it uses
586/// real wall-clock time.
587fn current_epoch_millis() -> u64 {
588    use std::time::{SystemTime, UNIX_EPOCH};
589    SystemTime::now()
590        .duration_since(UNIX_EPOCH)
591        .map(|d| d.as_millis() as u64)
592        .unwrap_or(0)
593}
594
595#[cfg(test)]
596mod tests {
597    use super::*;
598
599    #[test]
600    fn test_did_handler_creation() {
601        let quins = vec![];
602        let handler = SparqlDidHandler::new(&quins);
603        assert_eq!(handler.cache_count, 0);
604    }
605
606    #[test]
607    fn test_resolve_did() {
608        let quins = vec![];
609        let mut handler = SparqlDidHandler::new(&quins);
610
611        let result = handler.resolve_did(0x8000000000000001); // With 0x8 prefix
612        assert!(result.is_ok());
613        assert_eq!(result.unwrap().did, 0x8000000000000001);
614    }
615
616    #[test]
617    fn test_verify_signature_fails_closed() {
618        // Security regression: the SPARQL/DID query shim must NOT rubber-stamp
619        // signatures. It has no resolvable key here and must fail closed so callers
620        // route verification through the key-vault/identity layer.
621        let quins = vec![];
622        let handler = SparqlDidHandler::new(&quins);
623
624        let signature = &[0u8; 64];
625        let data = &[0u8; 256];
626
627        let result = handler.verify_signature(0x8000000000000001, signature, data);
628        assert!(
629            result.is_err(),
630            "verify_signature must fail closed, not return valid"
631        );
632    }
633
634    #[test]
635    fn test_check_permission_fails_closed() {
636        // Security regression: permission must not be granted unconditionally.
637        let quins = vec![];
638        let handler = SparqlDidHandler::new(&quins);
639
640        let result = handler.check_permission(0x8000000000000001, 123, 0);
641        assert!(
642            result.is_err(),
643            "check_permission must fail closed, not grant access"
644        );
645    }
646
647    #[test]
648    fn test_authenticate_did_fails_closed() {
649        // Security regression: authentication must not succeed for everyone.
650        let quins = vec![];
651        let handler = SparqlDidHandler::new(&quins);
652
653        let result = handler.authenticate_did(0x8000000000000001, 1, &[0u8; 256]);
654        assert!(
655            result.is_err(),
656            "authenticate_did must fail closed, not authenticate all"
657        );
658    }
659
660    // ===== DIDResolver (human-readable, string-based) tests =====
661
662    #[test]
663    fn test_resolver_did_q42_produces_valid_url() {
664        let resolver = DIDResolver::new();
665        let did = "did:q42:z6MkpTHR8VNs";
666        let result = resolver.resolve(did).expect("did:q42 must resolve");
667
668        assert_eq!(result.did, did);
669        // Endpoint must be a valid HTTPS URL — not XOR garbage.
670        assert!(
671            result
672                .endpoint_url
673                .starts_with("https://q42.network/agents/"),
674            "endpoint_url should be a q42.network agent URL, got '{}'",
675            result.endpoint_url
676        );
677        // The agent id must be a non-empty hex string (the 60-bit identity).
678        let agent_id = result
679            .endpoint_url
680            .strip_prefix("https://q42.network/agents/")
681            .unwrap();
682        assert!(!agent_id.is_empty(), "agent id must not be empty");
683        assert!(
684            agent_id.chars().all(|c| c.is_ascii_hexdigit()),
685            "agent id must be hex, got '{}'",
686            agent_id
687        );
688        assert_eq!(result.verification_method, format!("{}#q42-key", did));
689        assert!(result.resolved_at > 0, "resolved_at must be set");
690    }
691
692    #[test]
693    fn test_resolver_did_q42_is_deterministic() {
694        let resolver = DIDResolver::new();
695        let did = "did:q42:z6MkpTHR8VNs";
696        let a = resolver.resolve(did).unwrap();
697        let b = resolver.resolve(did).unwrap();
698        assert_eq!(
699            a.endpoint_url, b.endpoint_url,
700            "resolution must be deterministic"
701        );
702        assert_eq!(a.verification_method, b.verification_method);
703    }
704
705    #[test]
706    fn test_resolver_did_q42_distinct_payloads_distinct_urls() {
707        let resolver = DIDResolver::new();
708        let a = resolver.resolve("did:q42:z6MkpTHR8VNs").unwrap();
709        let b = resolver.resolve("did:q42:z6MkpTHR8VNt").unwrap();
710        assert_ne!(
711            a.endpoint_url, b.endpoint_url,
712            "distinct DIDs must resolve to distinct URLs"
713        );
714    }
715
716    #[test]
717    fn test_resolver_did_web_maps_to_well_known() {
718        let resolver = DIDResolver::new();
719        let did = "did:web:example.com";
720        let result = resolver.resolve(did).expect("did:web must resolve");
721
722        assert_eq!(result.did, did);
723        assert_eq!(
724            result.endpoint_url, "https://example.com/.well-known/did.json",
725            "did:web must map to the standard well-known DID document URL"
726        );
727        assert_eq!(result.verification_method, "did:web:example.com#key-1");
728    }
729
730    #[test]
731    fn test_resolver_did_web_with_path_components() {
732        // did:web uses ':' as a path separator after the domain.
733        let resolver = DIDResolver::new();
734        let did = "did:web:example.com:users:alice";
735        let result = resolver.resolve(did).unwrap();
736        assert_eq!(
737            result.endpoint_url,
738            "https://example.com/users/alice/.well-known/did.json"
739        );
740    }
741
742    #[test]
743    fn test_resolver_did_key() {
744        let resolver = DIDResolver::new();
745        let did = "did:key:z6MkhaXgBZDvotDkL5v7wB9QkN8eYfH2";
746        let result = resolver.resolve(did).expect("did:key must resolve");
747
748        assert_eq!(result.did, did);
749        // did:key has no native HTTP endpoint; point at a universal resolver.
750        assert_eq!(
751            result.endpoint_url,
752            format!("https://dev.uniresolver.io/1.0/identifiers/{}", did)
753        );
754        // The did:key DID is its own verification method.
755        assert_eq!(result.verification_method, did);
756    }
757
758    #[test]
759    fn test_resolver_unknown_method_returns_error() {
760        let resolver = DIDResolver::new();
761        let result = resolver.resolve("did:foo:bar");
762        assert!(result.is_err(), "unknown DID method must error");
763        let err = result.unwrap_err();
764        assert!(
765            err.contains("unsupported DID method"),
766            "error should mention unsupported method, got: {}",
767            err
768        );
769        assert!(err.contains("foo"), "error should name the method 'foo'");
770    }
771
772    #[test]
773    fn test_resolver_non_did_returns_error() {
774        let resolver = DIDResolver::new();
775        let result = resolver.resolve("https://example.com/not-a-did");
776        assert!(result.is_err(), "non-DID input must error");
777        assert!(result.unwrap_err().contains("not a valid DID"));
778    }
779
780    #[test]
781    fn test_resolver_empty_q42_payload_errors() {
782        let resolver = DIDResolver::new();
783        assert!(resolver.resolve("did:q42:").is_err());
784    }
785
786    #[test]
787    fn test_resolver_empty_web_domain_errors() {
788        let resolver = DIDResolver::new();
789        assert!(resolver.resolve("did:web:").is_err());
790    }
791
792    #[test]
793    fn test_resolver_empty_key_errors() {
794        let resolver = DIDResolver::new();
795        assert!(resolver.resolve("did:key:").is_err());
796    }
797
798    #[test]
799    fn test_resolver_resolve_delegates_to_resolve_did() {
800        // `resolve()` and `resolve_did()` must produce identical results.
801        let resolver = DIDResolver::new();
802        let did = "did:web:example.com";
803        let a = resolver.resolve(did).unwrap();
804        let b = resolver.resolve_did(did).unwrap();
805        assert_eq!(a.did, b.did);
806        assert_eq!(a.endpoint_url, b.endpoint_url);
807        assert_eq!(a.verification_method, b.verification_method);
808    }
809
810    #[test]
811    fn test_verify_authentication_signature_fails_closed() {
812        // The SPARQL query layer holds no verifiable public key, so signature
813        // verification must fail closed even when the DID and payload are valid.
814        let resolver = DIDResolver::new();
815        let did = "did:q42:z6MkpTHR8VNs";
816        let result = resolver.verify_authentication_signature(did, &[1u8; 64], &[2u8; 32]);
817        assert!(result.is_err(), "must fail closed, not return valid");
818        assert!(result.unwrap_err().contains("identity/key-vault layer"));
819    }
820
821    #[test]
822    fn test_verify_authentication_signature_rejects_empty_signature() {
823        let resolver = DIDResolver::new();
824        let result =
825            resolver.verify_authentication_signature("did:q42:z6MkpTHR8VNs", &[], &[2u8; 32]);
826        assert!(result.is_err());
827        assert!(result.unwrap_err().contains("empty signature"));
828    }
829
830    #[test]
831    fn test_verify_authentication_signature_rejects_bad_did() {
832        let resolver = DIDResolver::new();
833        // An unresolvable DID should be rejected before any crypto consideration.
834        let result =
835            resolver.verify_authentication_signature("did:foo:bar", &[1u8; 64], &[2u8; 32]);
836        assert!(result.is_err());
837    }
838
839    // ===== ABI-layer pointer resolution (XOR placeholder removed) =====
840
841    #[test]
842    fn test_resolve_did_pointer_is_not_xor_garbage() {
843        // The u64 ABI resolver must no longer use `did ^ 0xDEADBEEF`. Endpoint
844        // and verification-method pointers must be distinct, deterministic, and
845        // in the 60-bit q_hash space (top 4 bits clear).
846        let quins = vec![];
847        let mut handler = SparqlDidHandler::new(&quins);
848        let did = 0x8000000000000001;
849        let result = handler.resolve_did(did).unwrap();
850
851        // Distinct from the old XOR placeholders.
852        assert_ne!(result.endpoint_url, did ^ 0xDEADBEEF);
853        assert_ne!(result.verification_method, did ^ 0xCAFEBABE);
854        // Endpoint and verification method must differ from each other.
855        assert_ne!(result.endpoint_url, result.verification_method);
856        // Must be deterministic.
857        let again = handler.resolve_did(did).unwrap_or_else(|_| {
858            handler.invalidate_cache(did);
859            handler.resolve_did(did).unwrap()
860        });
861        // (cache returns the same value; if cache hit, fields are equal anyway)
862        assert_eq!(result.endpoint_url, again.endpoint_url);
863        // Pointers live in the 60-bit identity space (top 4 bits clear).
864        assert_eq!(result.endpoint_url >> 60, 0);
865        assert_eq!(result.verification_method >> 60, 0);
866    }
867}