Skip to main content

qualia_core_db/modalities/logic/shacl_extensions/
identity.rs

1//! Human-centric identity & data-rights SHACL extensions.
2//!
3//! Four structural enforcements the Webizen Sentinel needs, each grounded in the
4//! project's identity principles (`identifiers-not-identity`,
5//! `out-of-band-remainder-is-freedom`, `governance-topology-relational`):
6//!
7//! 1. **Identity as an enumerated state** — an identity is validated as a *bounded
8//!    set of cryptographically-attested identifiers* with a confidence *relation*,
9//!    never collapsed to one definitive identifier. A binding asserting certainty
10//!    (`confidence >= 1.0`) is a `DefinitiveCollapse` and is rejected: the
11//!    out-of-band remainder (the un-resolvable link to the natural person) is what
12//!    keeps the person free, so it is a hard invariant here, not an afterthought.
13//! 2. **Decentralized shape-target routing** — shapes are bound to storage *loci*
14//!    (personal data stores / peers); validation is dispatched to where the data
15//!    lives (local-first) instead of pulling everything into a central index.
16//! 3. **Real-time severity degradation** — off-grid, non-critical violations degrade
17//!    to non-blocking so a *partial* subgraph stays usable; `Critical` violations
18//!    (identity / consent / safety) never degrade — they fail closed. This mirrors
19//!    the deontic non-derogable rule.
20//! 4. **Verifiable-Credential-gated targets** — a SHACL target applies to a focus
21//!    node only when a *verified* W3C VC is presented about it (origin-authenticated
22//!    data-rights property validation; the VC layer checks the signature/expiry first).
23//!
24//! All four runtime predicates are **zero-heap**: bounded slices in, scalars / enums
25//! / caller `out` buffers out. The TTL/opcode emitters write constants or into a
26//! caller slice.
27
28use crate::verifiable_credential::Credential;
29use crate::webizen::SlgOpcode;
30
31// ── 1. Identity as an enumerated, cryptographically-attested state ──────────────
32
33/// Bounded number of identifier bindings an enumerated identity may carry.
34pub const MAX_IDENTITY_BINDINGS: usize = 32;
35
36/// The cryptographic scheme that attests an identifier binding.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum CryptoScheme {
39    Ed25519,
40    MlDsa65,
41    Blake3Commitment,
42    X25519,
43    /// No real crypto backing — does NOT count toward the attestation requirement.
44    Unknown,
45}
46
47/// One identifier in an enumerated identity: a handle, the crypto scheme attesting
48/// it, whether an attestation is actually present, and the confidence (strictly in
49/// `(0,1)`) that this identifier picks out the natural person.
50#[derive(Debug, Clone, Copy, PartialEq)]
51pub struct IdentifierBinding {
52    /// `q_hash` of the identifier (DID, key id, handle, …).
53    pub identifier: u64,
54    pub scheme: CryptoScheme,
55    pub attested: bool,
56    pub confidence: f32,
57}
58
59/// The verdict of [`validate_enumerated_identity`].
60#[derive(Debug, Clone, Copy, PartialEq)]
61pub enum IdentityValidation {
62    /// Enough distinct, crypto-attested identifiers; identity stands as an enumerated
63    /// state. `aggregate_confidence` is the noisy-OR combination (always `< 1.0`).
64    Valid {
65        distinct: u16,
66        attested: u16,
67        aggregate_confidence: f32,
68    },
69    /// Too few distinct identifiers and/or crypto attestations.
70    Underdetermined { distinct: u16, attested: u16 },
71    /// A binding claims certainty (`confidence >= 1.0`) — REJECTED. Identity must
72    /// remain a confidence-relation; collapsing it to a definitive identifier
73    /// destroys the out-of-band remainder.
74    DefinitiveCollapse,
75}
76
77/// Validate an identity as an enumerated state over crypto-attested identifiers.
78///
79/// `min_distinct` distinct identifiers and `min_attested` crypto-attested bindings
80/// are required. A binding with `confidence >= 1.0` short-circuits to
81/// [`IdentityValidation::DefinitiveCollapse`]. Zero-heap (scans the bounded slice).
82pub fn validate_enumerated_identity(
83    bindings: &[IdentifierBinding],
84    min_distinct: u16,
85    min_attested: u16,
86) -> IdentityValidation {
87    let mut distinct = 0u16;
88    let mut attested = 0u16;
89    let mut not_prob = 1.0f32; // running product of (1 - confidence) for noisy-OR
90
91    for (i, b) in bindings.iter().enumerate() {
92        // certainty or non-finite confidence is a definitive collapse — reject outright.
93        if !b.confidence.is_finite() || b.confidence >= 1.0 {
94            return IdentityValidation::DefinitiveCollapse;
95        }
96        // count distinct identifiers (first occurrence only).
97        let first_seen = !bindings[..i].iter().any(|p| p.identifier == b.identifier);
98        if first_seen {
99            distinct += 1;
100        }
101        // a binding counts as attested only with real crypto backing.
102        if b.attested && b.scheme != CryptoScheme::Unknown {
103            attested += 1;
104            not_prob *= 1.0 - b.confidence.clamp(0.0, 1.0);
105        }
106    }
107
108    if distinct < min_distinct || attested < min_attested {
109        return IdentityValidation::Underdetermined { distinct, attested };
110    }
111    let max_open_unit = f32::from_bits(1.0f32.to_bits() - 1);
112    IdentityValidation::Valid {
113        distinct,
114        attested,
115        aggregate_confidence: (1.0 - not_prob).min(max_open_unit),
116    }
117}
118
119/// Emit the SHACL opcodes for the enumerated-identity shape into `out` (zero-heap);
120/// returns the count written. The richer semantic enforcement (collapse rejection,
121/// noisy-OR confidence) lives in [`validate_enumerated_identity`].
122pub fn enumerated_identity_opcodes(
123    min_distinct: u32,
124    min_attested: u32,
125    out: &mut [SlgOpcode],
126) -> usize {
127    let ops = [
128        SlgOpcode::CheckMinCount(min_distinct),
129        SlgOpcode::CheckMinCount(min_attested),
130    ];
131    let n = ops.len().min(out.len());
132    out[..n].copy_from_slice(&ops[..n]);
133    n
134}
135
136// ── 2. Decentralized shape-target routing ──────────────────────────────────────
137
138/// Bounded number of shape→locus routes the router holds.
139pub const MAX_SHAPE_ROUTES: usize = 256;
140
141/// A binding of a SHACL `shape` to a storage `locus` (a personal data store / peer)
142/// where its target nodes live. Validation is dispatched to the locus; data is never
143/// aggregated centrally.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub struct ShapeRoute {
146    pub shape: u64,
147    pub locus: u64,
148}
149
150/// Enumerate the distinct shapes that apply at `locus` (what a local store validates).
151/// Writes shape ids into `out`; returns the count. Zero-heap.
152pub fn shapes_for_locus(routes: &[ShapeRoute], locus: u64, out: &mut [u64]) -> usize {
153    let mut n = 0usize;
154    for r in routes {
155        if r.locus != locus || out[..n].contains(&r.shape) {
156            continue;
157        }
158        if n >= out.len() {
159            break;
160        }
161        out[n] = r.shape;
162        n += 1;
163    }
164    n
165}
166
167/// Enumerate the distinct loci a `shape` must be routed to (fan-out without pulling
168/// the data together). Writes locus ids into `out`; returns the count. Zero-heap.
169pub fn loci_for_shape(routes: &[ShapeRoute], shape: u64, out: &mut [u64]) -> usize {
170    let mut n = 0usize;
171    for r in routes {
172        if r.shape != shape || out[..n].contains(&r.locus) {
173            continue;
174        }
175        if n >= out.len() {
176            break;
177        }
178        out[n] = r.locus;
179        n += 1;
180    }
181    n
182}
183
184/// Whether `shape` is validated locally at `self_locus` (local-first dispatch).
185pub fn route_is_local(routes: &[ShapeRoute], shape: u64, self_locus: u64) -> bool {
186    routes
187        .iter()
188        .any(|r| r.shape == shape && r.locus == self_locus)
189}
190
191// ── 3. Real-time severity degradation ──────────────────────────────────────────
192
193/// SHACL result severity, ordered so `Critical` is the maximum (never degrades).
194#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
195pub enum ShaclSeverity {
196    Info,
197    Warning,
198    Violation,
199    /// Non-derogable: identity / consent / safety. Fails closed even off-grid.
200    Critical,
201}
202
203/// Whether the engine is online (strict) or off-grid (partial-utilization tolerant).
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub enum OperationMode {
206    Online,
207    OffGrid,
208}
209
210/// A SHACL shape violation against a focus node, with its severity.
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub struct ShapeViolation {
213    pub shape: u64,
214    pub focus_node: u64,
215    pub severity: ShaclSeverity,
216}
217
218/// The result of [`degrade_violations`].
219#[derive(Debug, Clone, Copy, PartialEq, Eq)]
220pub struct DegradationOutcome {
221    /// Violations that still block (always `Critical`; off-grid, *only* `Critical`).
222    pub blocking: u16,
223    /// Violations downgraded to non-blocking for off-grid partial utilization.
224    pub degraded: u16,
225    /// `true` when nothing blocks — the (partial) subgraph may be used.
226    pub subgraph_usable: bool,
227}
228
229/// Apply real-time severity degradation. `Online` blocks on every `Violation`/
230/// `Critical` (nothing degrades). `OffGrid` degrades non-`Critical` violations to
231/// non-blocking so a partial subgraph stays usable; `Critical` never degrades.
232///
233/// Writes the post-degradation violations (with adjusted severity) into `out` and
234/// returns the outcome. Zero-heap.
235pub fn degrade_violations(
236    violations: &[ShapeViolation],
237    mode: OperationMode,
238    out: &mut [ShapeViolation],
239) -> DegradationOutcome {
240    let mut blocking = 0u16;
241    let mut degraded = 0u16;
242    let count = violations.len().min(out.len());
243
244    for (i, v) in violations.iter().take(count).enumerate() {
245        let mut adjusted = *v;
246        let blocks = match mode {
247            OperationMode::Online => v.severity >= ShaclSeverity::Violation,
248            OperationMode::OffGrid => {
249                if v.severity == ShaclSeverity::Critical {
250                    true
251                } else {
252                    // degrade a blocking violation down to a non-blocking warning.
253                    if v.severity >= ShaclSeverity::Violation {
254                        adjusted.severity = ShaclSeverity::Warning;
255                        degraded += 1;
256                    }
257                    false
258                }
259            }
260        };
261        if blocks {
262            blocking += 1;
263        }
264        out[i] = adjusted;
265    }
266
267    DegradationOutcome {
268        blocking,
269        degraded,
270        subgraph_usable: blocking == 0,
271    }
272}
273
274// ── 4. Verifiable-Credential-gated SHACL targets ───────────────────────────────
275
276/// A credential gate on a SHACL target: the shape applies to a focus node only when
277/// a verified VC about that node carries the required claim from an accepted issuer.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub struct CredentialGate {
280    /// The SHACL shape this gate guards.
281    pub shape: u64,
282    /// The claim predicate the VC must assert about the subject.
283    pub required_claim_predicate: u64,
284    /// The required object value (`0` = any value of the predicate).
285    pub required_claim_object: u64,
286    /// The accepted issuer (`0` = any grounded issuer — the VC layer enforces grounding).
287    pub accepted_issuer: u64,
288}
289
290/// Decide whether a credential-gated SHACL target applies to `focus_node`, given an
291/// **already cryptographically-verified** credential (call
292/// [`crate::verifiable_credential::verify`] / `verify_grounded` first — this gates on
293/// a *verified* VC, it does not re-check the signature).
294///
295/// Requires: the credential's subject is the focus node; the issuer is accepted; and
296/// the credential carries a claim matching the required predicate/object. Zero-heap
297/// (scans the credential's caller-owned claim list).
298pub fn credential_gates_target(gate: &CredentialGate, focus_node: u64, vc: &Credential) -> bool {
299    if vc.subject != focus_node {
300        return false;
301    }
302    if gate.accepted_issuer != 0 && vc.issuer != gate.accepted_issuer {
303        return false;
304    }
305    vc.claims.iter().any(|q| {
306        q.predicate == gate.required_claim_predicate
307            && (gate.required_claim_object == 0 || q.object == gate.required_claim_object)
308    })
309}
310
311// ── SHACL TTL vocabulary for the identity / data-rights shapes ──────────────────
312
313/// SHACL shapes for human-centric identity & data rights.
314pub fn get_identity_shacl_ttl() -> &'static str {
315    r#"
316@prefix q42: <https://webizen.org/q42#> .
317@prefix sh: <http://www.w3.org/ns/shacl#> .
318@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
319
320# Identity is an ENUMERATED state over multiple cryptographically-attested
321# identifiers — never a single definitive identifier. The out-of-band remainder is
322# preserved: identifier confidence is a RELATION strictly in (0,1), never certainty.
323q42:EnumeratedIdentityShape a sh:NodeShape ;
324    sh:targetClass q42:Principal ;
325    sh:property [
326        sh:path q42:hasIdentifier ;
327        sh:minCount 2 ;
328        sh:message "An identity must enumerate at least two distinct identifiers; a single definitive identifier collapses the out-of-band remainder." ;
329    ] ;
330    sh:property [
331        sh:path q42:identifierAttestation ;
332        sh:minCount 1 ;
333        sh:nodeKind sh:BlankNodeOrIRI ;
334        sh:message "Each identifier must carry a cryptographic attestation (Ed25519 / ML-DSA-65 / BLAKE3 commitment)." ;
335    ] ;
336    sh:property [
337        sh:path q42:identifierConfidence ;
338        sh:datatype xsd:decimal ;
339        sh:minExclusive 0 ;
340        sh:maxExclusive 1 ;
341        sh:message "Identifier confidence is strictly in (0,1); certainty (1.0) is a definitive-collapse and is rejected." ;
342    ] .
343
344# Decentralized routing: a shape is bound to the locus where its targets live, so
345# validation is dispatched locally rather than aggregating personal data centrally.
346q42:ShapeRouteShape a sh:NodeShape ;
347    sh:targetClass q42:ShapeRoute ;
348    sh:property [
349        sh:path q42:routedToLocus ;
350        sh:minCount 1 ;
351        sh:message "Every shape route must name a storage locus; validation goes to the data, not the data to a central index." ;
352    ] .
353
354# A SHACL target gated by a presented, verified Verifiable Credential.
355q42:CredentialGatedTargetShape a sh:NodeShape ;
356    sh:targetSubjectsOf q42:presentsCredential ;
357    sh:property [
358        sh:path q42:presentsCredential ;
359        sh:minCount 1 ;
360        sh:message "This target requires a presented, verified Verifiable Credential." ;
361    ] .
362"#
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use crate::verifiable_credential::Credential;
369    use crate::{q_hash, NQuin};
370
371    fn binding(
372        id: &str,
373        scheme: CryptoScheme,
374        attested: bool,
375        confidence: f32,
376    ) -> IdentifierBinding {
377        IdentifierBinding {
378            identifier: q_hash(id),
379            scheme,
380            attested,
381            confidence,
382        }
383    }
384
385    #[test]
386    fn enumerated_identity_valid_stays_below_certainty() {
387        let bindings = [
388            binding("did:key:a", CryptoScheme::Ed25519, true, 0.6),
389            binding("did:key:b", CryptoScheme::MlDsa65, true, 0.7),
390            binding("handle:c", CryptoScheme::Blake3Commitment, true, 0.5),
391        ];
392        match validate_enumerated_identity(&bindings, 2, 2) {
393            IdentityValidation::Valid {
394                distinct,
395                attested,
396                aggregate_confidence,
397            } => {
398                assert_eq!(distinct, 3);
399                assert_eq!(attested, 3);
400                // noisy-OR of 0.6/0.7/0.5 = 1 - 0.4*0.3*0.5 = 0.94, strictly < 1.
401                assert!(aggregate_confidence > 0.9 && aggregate_confidence < 1.0);
402            }
403            other => panic!("expected Valid, got {other:?}"),
404        }
405    }
406
407    #[test]
408    fn enumerated_identity_underdetermined_when_too_few() {
409        // Only one attested identifier; an Unknown-scheme binding does not count.
410        let bindings = [
411            binding("did:key:a", CryptoScheme::Ed25519, true, 0.6),
412            binding("guess:b", CryptoScheme::Unknown, true, 0.4),
413        ];
414        assert_eq!(
415            validate_enumerated_identity(&bindings, 2, 2),
416            IdentityValidation::Underdetermined {
417                distinct: 2,
418                attested: 1
419            }
420        );
421    }
422
423    #[test]
424    fn certainty_is_a_definitive_collapse() {
425        // A binding asserting certainty must be rejected — the out-of-band remainder
426        // is a hard invariant.
427        let bindings = [
428            binding("did:key:a", CryptoScheme::Ed25519, true, 0.6),
429            binding("gov:id", CryptoScheme::MlDsa65, true, 1.0),
430        ];
431        assert_eq!(
432            validate_enumerated_identity(&bindings, 1, 1),
433            IdentityValidation::DefinitiveCollapse
434        );
435        let over_one = [binding("gov:id", CryptoScheme::MlDsa65, true, 1.25)];
436        assert_eq!(
437            validate_enumerated_identity(&over_one, 1, 1),
438            IdentityValidation::DefinitiveCollapse
439        );
440        let nan_binding = [binding("gov:id", CryptoScheme::MlDsa65, true, f32::NAN)];
441        assert_eq!(
442            validate_enumerated_identity(&nan_binding, 1, 1),
443            IdentityValidation::DefinitiveCollapse
444        );
445    }
446
447    #[test]
448    fn decentralized_routing_dispatches_to_loci() {
449        let routes = [
450            ShapeRoute {
451                shape: 1,
452                locus: 100,
453            },
454            ShapeRoute {
455                shape: 2,
456                locus: 100,
457            },
458            ShapeRoute {
459                shape: 1,
460                locus: 200,
461            },
462            ShapeRoute {
463                shape: 1,
464                locus: 100,
465            }, // duplicate, must dedup
466        ];
467        let mut shapes = [0u64; 8];
468        let n = shapes_for_locus(&routes, 100, &mut shapes);
469        assert_eq!(n, 2);
470        assert!(shapes[..n].contains(&1) && shapes[..n].contains(&2));
471
472        let mut loci = [0u64; 8];
473        let m = loci_for_shape(&routes, 1, &mut loci);
474        assert_eq!(m, 2); // loci 100 and 200, deduped
475        assert!(loci[..m].contains(&100) && loci[..m].contains(&200));
476
477        assert!(route_is_local(&routes, 1, 100));
478        assert!(!route_is_local(&routes, 2, 200));
479    }
480
481    #[test]
482    fn severity_degradation_offgrid_keeps_partial_subgraph_usable() {
483        let violations = [
484            ShapeViolation {
485                shape: 1,
486                focus_node: 10,
487                severity: ShaclSeverity::Violation,
488            },
489            ShapeViolation {
490                shape: 2,
491                focus_node: 11,
492                severity: ShaclSeverity::Warning,
493            },
494        ];
495        let mut out = [violations[0]; 2];
496
497        // Online: the Violation blocks → subgraph not usable.
498        let online = degrade_violations(&violations, OperationMode::Online, &mut out);
499        assert_eq!(online.blocking, 1);
500        assert!(!online.subgraph_usable);
501
502        // Off-grid: the Violation degrades to Warning → nothing blocks → usable.
503        let offgrid = degrade_violations(&violations, OperationMode::OffGrid, &mut out);
504        assert_eq!(offgrid.blocking, 0);
505        assert_eq!(offgrid.degraded, 1);
506        assert!(offgrid.subgraph_usable);
507        assert_eq!(out[0].severity, ShaclSeverity::Warning); // downgraded in place
508    }
509
510    #[test]
511    fn critical_never_degrades_even_offgrid() {
512        let violations = [ShapeViolation {
513            shape: 9,
514            focus_node: 99,
515            severity: ShaclSeverity::Critical,
516        }];
517        let mut out = [violations[0]; 1];
518        let outcome = degrade_violations(&violations, OperationMode::OffGrid, &mut out);
519        assert_eq!(outcome.blocking, 1);
520        assert_eq!(outcome.degraded, 0);
521        assert!(!outcome.subgraph_usable); // fails closed
522        assert_eq!(out[0].severity, ShaclSeverity::Critical);
523    }
524
525    #[test]
526    fn verifiable_credential_gates_the_target() {
527        let alice = q_hash("did:example:alice");
528        let issuer = q_hash("did:example:gov");
529        let cap_pred = q_hash("https://ns.webcivics.net/capability/heldBy");
530        let cap_obj = q_hash("cap:LicensedPractitioner");
531
532        let claim = NQuin {
533            subject: alice,
534            predicate: cap_pred,
535            object: cap_obj,
536            context: 0,
537            metadata: 0,
538            parity: 0,
539        };
540        let vc = Credential {
541            issuer,
542            subject: alice,
543            issued_at: 1000,
544            valid_until: 0,
545            claims: vec![claim],
546        };
547        let gate = CredentialGate {
548            shape: 1,
549            required_claim_predicate: cap_pred,
550            required_claim_object: cap_obj,
551            accepted_issuer: issuer,
552        };
553
554        // Matches: right subject, issuer, and claim.
555        assert!(credential_gates_target(&gate, alice, &vc));
556        // Wrong focus node → does not apply.
557        assert!(!credential_gates_target(
558            &gate,
559            q_hash("did:example:bob"),
560            &vc
561        ));
562        // Wrong issuer → rejected.
563        let gate_other_issuer = CredentialGate {
564            accepted_issuer: q_hash("did:example:rogue"),
565            ..gate
566        };
567        assert!(!credential_gates_target(&gate_other_issuer, alice, &vc));
568        // Missing the required claim object → does not apply.
569        let gate_other_claim = CredentialGate {
570            required_claim_object: q_hash("cap:Something_Else"),
571            ..gate
572        };
573        assert!(!credential_gates_target(&gate_other_claim, alice, &vc));
574        // accepted_issuer = 0 means "any grounded issuer".
575        let gate_any_issuer = CredentialGate {
576            accepted_issuer: 0,
577            ..gate
578        };
579        assert!(credential_gates_target(&gate_any_issuer, alice, &vc));
580    }
581}