qualia_client_core/consent_credential.rs
1//! **Revocable consent credentials** with *crypto-enforced* payload revocation + a **durable, attestable
2//! conduct record** — the mechanism that resolves "revocable data vs durable accountability"
3//! (`docs/plans/social-worker-support-and-accountability.md` §2 + §4).
4//!
5//! The consideration (Timothy, 2026-07-06): a person can grant an agent (a social worker — a human) a
6//! **consent credential** to an **encrypted payload**, and can **take it away**. When taken away the
7//! **payload becomes unavailable** — *not* by flipping a flag, but by **destroying the key** (envelope
8//! encryption: the payload is `Enc(data_key, payload)`; the credential carries the *wrapped* data key;
9//! revoke ⇒ the wrapped key is destroyed ⇒ no key, no payload). **But the agent's interaction records
10//! persist** — how and why they acted — so revoking consent cannot erase a worker's accountability, and a
11//! worker cannot hold the person's data hostage *for* accountability. The durable [`ConductRecord`] binds to
12//! a **commitment** of the payload (not the payload), and carries an [`Attestation`] (a signature and/or a
13//! zero-knowledge proof over the real `crypto/zk_proofs` system) so a **court can audit** that the agent
14//! acted, on what basis, at what time — *without* re-exposing the revoked private data.
15//!
16//! **The payload lives in a permissive commons** (Timothy, 2026-07-06). The ciphertext is an
17//! [`EncryptedCommonsPayload`] — **stored/replicated by many parties so it cannot be deleted** (anti-erasure:
18//! not by an agent covering their tracks, not by a hostile actor destroying evidence, not by accidental
19//! loss) — **yet accessible only to holders of the right credential**. Wide storage ≠ wide access: the
20//! ciphertext is useless without a key. This resolves *anti-deletion vs privacy vs access-control* at once,
21//! and it sharpens revocation: you cannot delete bytes others hold, so **revocation is access, not
22//! deletion** — revoke a credential ⇒ that holder's key is destroyed ⇒ they lose access, while the durable
23//! commons ciphertext persists for other holders and as un-erasable evidence. The person's *ultimate*
24//! control is **crypto-shredding**: destroy **all** keys ⇒ the ciphertext is permanently unreadable by
25//! anyone (effective erasure) even though the bytes survive. (Continuous with the permissive-commons +
26//! distributed-memory-custody + erasure-prevention stances elsewhere.)
27//!
28//! **Credentials are not only self-consent, and need not be unilateral** (Timothy, 2026-07-06). A
29//! credential's authority may derive from the **subject**, from a **court** (to support proceedings / the
30//! audit case), or from another attested **authority** (a statutory body, a guardian) — see
31//! [`CredentialAuthority`]. And a credential may be **multi-signature** ([`Authorization::MultiSig`]): an
32//! exercise then requires (a) **instigation by a participating party** — so no outside/authority actor can
33//! act alone — **and** (b) a **threshold** of party signatures. Even a valid court credential, if multi-sig,
34//! cannot be exercised without a participating party setting it in motion and the threshold signing. This is
35//! the check on authority: *unable to act without instigation of one of the participating parties.*
36//!
37//! **Scope of this module.** The pure **domain model + the invariants** — the commons payload, the
38//! *revocable* per-holder access, the court/authority + multi-sig authorization, and the *durable* conduct
39//! trail. It does **not** perform the actual
40//! envelope encryption, the real Groth16 proof, the replication/seeding, or the `consent_store`/vault
41//! wiring — those compose from `wellfair/consent_store.rs` (whose flag-`revoke` this design says should
42//! become crypto-enforced), `wellfair/vault.rs`, the WebTorrent/seeder layer (the commons replication), and
43//! `qualia-core-db::crypto::zk_proofs` (coordinate). This is the shape the wiring must honour.
44
45use serde::{Deserialize, Serialize};
46
47/// A commitment to a payload — a 32-byte hash/commitment (e.g. BLAKE3/SHA-256, computed by the crypto
48/// layer). It **survives revocation** and binds a [`ConductRecord`] to *what* was acted on, without holding
49/// or re-exposing the payload itself. It is also the **content address** of the [`EncryptedCommonsPayload`].
50pub type PayloadCommitment = [u8; 32];
51
52/// An **encrypted payload in a permissive commons** — content-addressed ciphertext that **many parties may
53/// store (replicate)** so it **cannot be deleted** (anti-erasure), but that is **accessible only to holders
54/// of the right credential** (the wrapped decryption key). Wide storage ≠ wide access: without a key the
55/// ciphertext is opaque.
56///
57/// Revocation acts on **access** (the credential's key — see [`ConsentCredential::revoke`]), *not* on this
58/// blob; the blob persists for other credential-holders and as un-erasable evidence. The person's ultimate
59/// control is **crypto-shredding** — once no credential can decrypt it (all keys destroyed), it is
60/// permanently unreadable by anyone, effective erasure though the bytes survive (see
61/// [`is_crypto_shredded`]).
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63pub struct EncryptedCommonsPayload {
64 /// Content address / commitment of the ciphertext — its durable identifier (equals the
65 /// [`PayloadCommitment`] a credential and conduct record bind to).
66 pub commitment: PayloadCommitment,
67 /// The envelope-encrypted bytes. Opaque without a credential; safe to replicate widely.
68 pub ciphertext: Vec<u8>,
69 /// The parties (by identifier) who hold a copy — the commons. Replication = durability: no single
70 /// party's deletion destroys the payload while another copy exists.
71 pub storers: Vec<String>,
72}
73
74impl EncryptedCommonsPayload {
75 /// Creates a new instance.
76 pub fn new(commitment: PayloadCommitment, ciphertext: Vec<u8>, storers: Vec<String>) -> Self {
77 Self {
78 commitment,
79 ciphertext,
80 storers,
81 }
82 }
83
84 /// Number of independent copies held — the anti-deletion / durability measure.
85 pub fn replication(&self) -> usize {
86 self.storers.len()
87 }
88
89 /// Durable against unilateral deletion (held by more than one storer). A single-copy payload is *not*
90 /// yet in a resilient commons.
91 pub fn is_durable(&self) -> bool {
92 self.storers.len() > 1
93 }
94
95 /// Add a storer (a party replicates a copy — increases durability). Idempotent.
96 pub fn add_storer(&mut self, did: impl Into<String>) {
97 let did = did.into();
98 if !self.storers.iter().any(|s| s == &did) {
99 self.storers.push(did);
100 }
101 }
102
103 /// One storer drops their copy. Returns `true` if copies **remain** (the payload survives) — the point
104 /// of the commons: unilateral deletion does not erase what others hold.
105 pub fn drop_storer(&mut self, did: &str) -> bool {
106 self.storers.retain(|s| s != did);
107 !self.storers.is_empty()
108 }
109}
110
111/// **Crypto-shredding check.** Is this commons payload *effectively erased* — permanently unreadable — for a
112/// given set of credentials at `now`? True iff **no** credential grants a live key to it (every credential
113/// for this commitment is revoked/expired, or none exists). The bytes may still be replicated across the
114/// commons, but with no key anywhere they cannot be decrypted by anyone — the person's ultimate erasure
115/// control, achieved by destroying keys rather than by chasing copies.
116pub fn is_crypto_shredded(
117 payload: &EncryptedCommonsPayload,
118 credentials: &[ConsentCredential],
119 now_unix: u64,
120) -> bool {
121 !credentials
122 .iter()
123 .any(|c| c.payload_commitment == payload.commitment && c.payload_key(now_unix).is_some())
124}
125
126/// Where a credential's authority derives from — the *basis* on which access is granted. Not always
127/// self-consent: a **court** can hold one (to support proceedings), as can another attested **authority**.
128/// Authority-issued credentials are legitimate — and, when multi-sig, still cannot be exercised unilaterally.
129#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
130#[serde(rename_all = "snake_case")]
131pub enum CredentialAuthority {
132 /// The data-subject's own consent.
133 #[default]
134 Subject,
135 /// A court / judicial order — supports court-of-law access (audit / proceedings).
136 Court { order_ref: String },
137 /// Another attested authoritative agent (a statutory body, a guardian, …), by its instrument.
138 Authority {
139 authority_did: String,
140 instrument_ref: String,
141 },
142}
143
144/// A participating party in a multi-signature authorization.
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146pub struct Party {
147 pub did: String,
148 /// The party's role in the authorization (e.g. `"subject"`, `"guardian"`, `"advocate"`, `"court"`).
149 pub role: String,
150}
151
152/// How a credential may be **exercised** (acted on the payload).
153#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
154#[serde(rename_all = "snake_case")]
155pub enum Authorization {
156 /// The holder may act alone.
157 #[default]
158 Single,
159 /// **Multi-signature.** An exercise must be (a) **instigated by one of the participating parties** — so
160 /// no outside/authority actor can act unilaterally — AND (b) signed by at least `threshold` of the
161 /// `parties`. The "unable to act without instigation of one of the participating parties" rule.
162 MultiSig {
163 parties: Vec<Party>,
164 threshold: usize,
165 },
166}
167
168/// A request to exercise a credential: **who instigated it**, and the party signatures collected.
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
170pub struct ExerciseRequest {
171 pub instigator_did: String,
172 /// DIDs of parties who have signed off on this exercise.
173 pub signatures: Vec<String>,
174}
175
176impl ExerciseRequest {
177 /// Creates a new instance.
178 pub fn new(instigator_did: impl Into<String>, signatures: Vec<String>) -> Self {
179 Self {
180 instigator_did: instigator_did.into(),
181 signatures,
182 }
183 }
184}
185
186impl Authorization {
187 /// Is this exercise authorised? `Single` → always. `MultiSig` → the instigator must be a participating
188 /// party (no unilateral outside/authority action) AND at least `threshold` **distinct** participating
189 /// parties must have signed.
190 pub fn authorizes(&self, req: &ExerciseRequest) -> bool {
191 match self {
192 Authorization::Single => true,
193 Authorization::MultiSig { parties, threshold } => {
194 let is_party = |did: &str| parties.iter().any(|p| p.did == did);
195 if !is_party(&req.instigator_did) {
196 return false; // must be instigated by a participating party
197 }
198 let signers: std::collections::BTreeSet<&str> = req
199 .signatures
200 .iter()
201 .map(|s| s.as_str())
202 .filter(|s| is_party(s))
203 .collect();
204 signers.len() >= *threshold
205 }
206 }
207 }
208}
209
210/// A **consent credential** — grants an agent scoped access to an encrypted payload; revocable, with the
211/// revocation *crypto-enforced* (the wrapped key is destroyed). Its authority may be self-consent, a court,
212/// or another authority ([`CredentialAuthority`]); its exercise may require multi-sig
213/// ([`Authorization`]).
214#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
215pub struct ConsentCredential {
216 pub id: String,
217 /// The person granting consent (the data-subject).
218 pub subject_did: String,
219 /// The granted agent (e.g. the social worker — a human, by identifier).
220 pub agent_did: String,
221 /// What is granted, purpose-bound (minimal-disclosure scope).
222 pub scope: String,
223 pub purpose: String,
224 /// A commitment to the granted payload — durable, binds the conduct trail.
225 pub payload_commitment: PayloadCommitment,
226 pub granted_unix: u64,
227 /// Optional expiry — access ceases at/after this time even without an explicit revoke.
228 pub expiry_unix: Option<u64>,
229 /// Set on revoke — the moment after which the payload is unavailable.
230 pub revoked_unix: Option<u64>,
231 /// The **wrapped data key** the agent needs to decrypt the payload — present while access is permitted,
232 /// **destroyed (`None`) on revoke/expiry**. This is the crypto-revocation: no key ⇒ no payload. Private
233 /// so it can only be read through [`payload_key`](ConsentCredential::payload_key), which enforces the
234 /// active check.
235 #[serde(default, skip_serializing_if = "Option::is_none")]
236 wrapped_key: Option<Vec<u8>>,
237 /// Where this credential's authority derives from (subject / court / authority).
238 #[serde(default)]
239 pub authority: CredentialAuthority,
240 /// How it may be exercised (alone, or multi-sig requiring party instigation + threshold).
241 #[serde(default)]
242 pub authorization: Authorization,
243}
244
245impl ConsentCredential {
246 /// Grant a credential. `wrapped_key` is the data key wrapped for the agent (from the vault's envelope
247 /// encryption) — the thing revocation destroys.
248 #[allow(clippy::too_many_arguments)]
249 pub fn grant(
250 id: impl Into<String>,
251 subject_did: impl Into<String>,
252 agent_did: impl Into<String>,
253 scope: impl Into<String>,
254 purpose: impl Into<String>,
255 payload_commitment: PayloadCommitment,
256 wrapped_key: Vec<u8>,
257 granted_unix: u64,
258 expiry_unix: Option<u64>,
259 ) -> Self {
260 Self {
261 id: id.into(),
262 subject_did: subject_did.into(),
263 agent_did: agent_did.into(),
264 scope: scope.into(),
265 purpose: purpose.into(),
266 payload_commitment,
267 granted_unix,
268 expiry_unix,
269 revoked_unix: None,
270 wrapped_key: Some(wrapped_key),
271 authority: CredentialAuthority::Subject,
272 authorization: Authorization::Single,
273 }
274 }
275
276 /// Set the credential's authority basis (a court order / another authority). Builder-style.
277 pub fn with_authority(mut self, authority: CredentialAuthority) -> Self {
278 self.authority = authority;
279 self
280 }
281
282 /// Require **multi-sig** exercise: instigation by a participating party + `threshold` party signatures.
283 /// Builder-style. This is what makes the credential *unable to act without a participating party*.
284 pub fn requiring_multisig(mut self, parties: Vec<Party>, threshold: usize) -> Self {
285 self.authorization = Authorization::MultiSig { parties, threshold };
286 self
287 }
288
289 /// Whether the credential is currently active (not revoked, not past expiry).
290 pub fn is_active(&self, now_unix: u64) -> bool {
291 if self.revoked_unix.is_some() {
292 return false;
293 }
294 match self.expiry_unix {
295 Some(exp) => now_unix < exp,
296 None => true,
297 }
298 }
299
300 /// **Revoke** the credential — *crypto-enforced*: records the moment **and destroys the wrapped key**,
301 /// so the payload can no longer be decrypted (it returns to the person). Idempotent.
302 pub fn revoke(&mut self, now_unix: u64) {
303 if self.revoked_unix.is_none() {
304 self.revoked_unix = Some(now_unix);
305 }
306 self.wrapped_key = None; // the key is gone — no key, no payload
307 }
308
309 /// The wrapped data key **iff access is currently permitted** — `None` once revoked or expired. A `None`
310 /// here *is* "the payload is unavailable to the agent": with no key there is nothing to decrypt with.
311 pub fn payload_key(&self, now_unix: u64) -> Option<&[u8]> {
312 if self.is_active(now_unix) {
313 self.wrapped_key.as_deref()
314 } else {
315 None
316 }
317 }
318
319 /// Whether the encrypted payload is *technically* accessible right now (active + key present) —
320 /// **ignoring** any multi-sig requirement. For a multi-sig credential use [`can_exercise`] /
321 /// [`exercise`], which enforce party-instigation + threshold.
322 ///
323 /// [`can_exercise`]: ConsentCredential::can_exercise
324 /// [`exercise`]: ConsentCredential::exercise
325 pub fn payload_accessible(&self, now_unix: u64) -> bool {
326 self.payload_key(now_unix).is_some()
327 }
328
329 /// Whether a specific exercise is permitted: the credential is active **and** the request satisfies the
330 /// [`Authorization`] (for multi-sig: instigated by a participating party + threshold signatures). This is
331 /// the gate that stops an authority acting unilaterally.
332 pub fn can_exercise(&self, req: &ExerciseRequest, now_unix: u64) -> bool {
333 self.is_active(now_unix) && self.authorization.authorizes(req)
334 }
335
336 /// The wrapped data key **iff this exercise is authorised** (active + authorization satisfied). The
337 /// authorization-aware counterpart to [`payload_key`](ConsentCredential::payload_key): a multi-sig
338 /// credential yields a key only when a participating party instigated it and the threshold has signed.
339 pub fn exercise(&self, req: &ExerciseRequest, now_unix: u64) -> Option<&[u8]> {
340 if self.can_exercise(req, now_unix) {
341 self.wrapped_key.as_deref()
342 } else {
343 None
344 }
345 }
346}
347
348/// The cryptographic **attestation** on a [`ConductRecord`] — attributable + court-auditable.
349#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
350#[serde(rename_all = "snake_case")]
351pub enum Attestation {
352 /// A detached signature over the record (ed25519 / ML-DSA) — binds the agent to the conduct. Hex.
353 Signature { alg: String, sig_hex: String },
354 /// A **zero-knowledge proof** over `crypto/zk_proofs` — proves a property (e.g. "the agent held a valid
355 /// consent credential for the payload committed to by `payload_commitment` at `time`") **without
356 /// revealing the payload**. Referenced by id; the proof + verifying key live in the ZK layer.
357 ZkProof { proof_id: String },
358}
359
360/// A **durable** record of *how and why* an agent acted — the conduct trail. It **persists after the
361/// consent credential is revoked and the payload is gone** (revoking consent does not erase accountability),
362/// and it binds to the payload **commitment** (not the payload), so it proves the agent acted on a specific
363/// datum **without** retaining or re-exposing that datum. Append-only in practice (the store is
364/// tamper-evident — signed WAL); this type is the record.
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366pub struct ConductRecord {
367 pub id: String,
368 /// The agent who acted (a human worker — accountable).
369 pub agent_did: String,
370 /// The consent credential the action was taken under (links act → authority).
371 pub credential_id: String,
372 /// What the agent did (accessed / decided / referred / requested / escalated / **omitted**).
373 pub action: String,
374 /// Why — the stated basis/authority for the act.
375 pub reason: String,
376 pub time_unix: u64,
377 /// Binds the record to *what* was acted on — the payload commitment (durable; the payload is not held).
378 pub payload_commitment: PayloadCommitment,
379 /// The attestation making this court-auditable and attributable.
380 pub attestation: Attestation,
381}
382
383impl ConductRecord {
384 /// Does this conduct record concern the payload committed to by `commitment`? (Audit link — verify the
385 /// agent acted on a specific datum by its commitment, without needing the datum.)
386 pub fn concerns_commitment(&self, commitment: &PayloadCommitment) -> bool {
387 &self.payload_commitment == commitment
388 }
389}
390
391/// Filter a conduct trail to the records taken under one consent credential — the **audit view**. These are
392/// exactly the records that survive that credential's revocation (the accountability the person cannot erase
393/// and the worker cannot withhold).
394pub fn audit_trail_for_credential<'a>(
395 records: &'a [ConductRecord],
396 credential_id: &str,
397) -> Vec<&'a ConductRecord> {
398 records
399 .iter()
400 .filter(|r| r.credential_id == credential_id)
401 .collect()
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407
408 const C: PayloadCommitment = [7u8; 32];
409
410 fn cred() -> ConsentCredential {
411 ConsentCredential::grant(
412 "cc-1",
413 "did:wf:person",
414 "did:wf:social-worker",
415 "housing-support-case",
416 "assess and arrange support",
417 C,
418 b"wrapped-data-key".to_vec(),
419 1_000,
420 Some(2_000),
421 )
422 }
423
424 fn conduct(id: &str, cred_id: &str, action: &str) -> ConductRecord {
425 ConductRecord {
426 id: id.into(),
427 agent_did: "did:wf:social-worker".into(),
428 credential_id: cred_id.into(),
429 action: action.into(),
430 reason: "acting under the granted consent".into(),
431 time_unix: 1_100,
432 payload_commitment: C,
433 attestation: Attestation::Signature {
434 alg: "ed25519".into(),
435 sig_hex: "deadbeef".into(),
436 },
437 }
438 }
439
440 #[test]
441 fn granted_payload_is_accessible_until_revoked() {
442 let c = cred();
443 assert!(
444 c.payload_accessible(1_100),
445 "active grant → payload accessible"
446 );
447 assert!(c.payload_key(1_100).is_some());
448 }
449
450 #[test]
451 fn revocation_is_crypto_enforced_the_key_is_destroyed_and_payload_gone() {
452 let mut c = cred();
453 assert!(c.payload_accessible(1_100));
454 c.revoke(1_200);
455 // No key, no payload — not a flag, the wrapped key is gone.
456 assert!(
457 !c.payload_accessible(1_300),
458 "revoked → payload unavailable"
459 );
460 assert!(
461 c.payload_key(1_300).is_none(),
462 "the wrapped key is destroyed"
463 );
464 assert_eq!(c.revoked_unix, Some(1_200));
465 // Even serialized, the key does not travel (it's gone / skipped).
466 let json = serde_json::to_string(&c).unwrap();
467 assert!(
468 !json.contains("wrapped"),
469 "no key material persists after revoke"
470 );
471 }
472
473 #[test]
474 fn expiry_also_makes_the_payload_unavailable() {
475 let c = cred(); // expires at 2_000
476 assert!(c.payload_accessible(1_999));
477 assert!(!c.payload_accessible(2_000), "past expiry → no access");
478 assert!(!c.payload_accessible(2_001));
479 }
480
481 #[test]
482 fn conduct_records_persist_after_revocation_and_stay_auditable() {
483 // The person revokes; the payload is gone — but the worker's conduct trail remains.
484 let mut c = cred();
485 let trail = vec![
486 conduct("k1", "cc-1", "accessed the housing record"),
487 conduct("k2", "cc-1", "requested an emergency placement"),
488 conduct("k3", "other-cred", "unrelated act"),
489 ];
490 c.revoke(1_500);
491 assert!(!c.payload_accessible(1_600), "data gone");
492
493 // The conduct trail for this credential is untouched by revocation — the accountability survives.
494 let audit = audit_trail_for_credential(&trail, "cc-1");
495 assert_eq!(
496 audit.len(),
497 2,
498 "both acts under cc-1 remain auditable after revoke"
499 );
500 // Each binds to the payload commitment, proving WHAT was acted on without holding the payload.
501 assert!(audit.iter().all(|r| r.concerns_commitment(&C)));
502 // And carries a court-auditable attestation.
503 assert!(audit
504 .iter()
505 .all(|r| matches!(r.attestation, Attestation::Signature { .. })));
506 }
507
508 #[test]
509 fn a_conduct_record_can_carry_a_zk_attestation() {
510 // The ZK path: prove the agent held a valid credential for the committed payload, without the payload.
511 let r = ConductRecord {
512 attestation: Attestation::ZkProof {
513 proof_id: "zk:groth16:abc".into(),
514 },
515 ..conduct("k", "cc-1", "acted")
516 };
517 assert!(matches!(r.attestation, Attestation::ZkProof { .. }));
518 assert!(r.concerns_commitment(&C));
519 }
520
521 #[test]
522 fn commons_payload_survives_unilateral_deletion_but_is_useless_without_a_key() {
523 let mut p = EncryptedCommonsPayload::new(
524 C,
525 b"opaque-ciphertext".to_vec(),
526 vec![
527 "did:wf:person".into(),
528 "did:wf:storer-a".into(),
529 "did:wf:storer-b".into(),
530 ],
531 );
532 assert!(p.is_durable(), "replicated across the commons");
533 assert_eq!(p.replication(), 3);
534
535 // A hostile party (or the agent) deleting THEIR copy does not erase the payload.
536 assert!(
537 p.drop_storer("did:wf:storer-a"),
538 "copies remain after one deletion"
539 );
540 assert_eq!(p.replication(), 2);
541 assert!(p.drop_storer("did:wf:person"), "still survives");
542
543 // Only when the last copy goes is the blob absent — the commons resists that.
544 assert!(!p.drop_storer("did:wf:storer-b"), "no copies left");
545 // The ciphertext, wherever held, is opaque — access is credential-gated, not storage-gated.
546 assert!(!p.ciphertext.is_empty());
547 }
548
549 #[test]
550 fn crypto_shredding_when_the_last_key_is_revoked_makes_it_unreadable_though_bytes_persist() {
551 let payload = EncryptedCommonsPayload::new(
552 C,
553 b"ct".to_vec(),
554 vec!["did:wf:person".into(), "did:wf:archive".into()],
555 );
556 let mut c = cred(); // the only credential granting a key to C
557 // While the credential is live, the payload is not shredded (a key exists).
558 assert!(!is_crypto_shredded(
559 &payload,
560 std::slice::from_ref(&c),
561 1_100
562 ));
563 // Destroy the key (revoke) — no credential grants a key to C now → crypto-shredded.
564 c.revoke(1_200);
565 assert!(
566 is_crypto_shredded(&payload, std::slice::from_ref(&c), 1_300),
567 "no key anywhere → permanently unreadable, even though the commons bytes survive"
568 );
569 // The bytes are still replicated (not chased down) — erasure was by key-destruction.
570 assert!(payload.is_durable());
571 }
572
573 fn party(did: &str, role: &str) -> Party {
574 Party {
575 did: did.into(),
576 role: role.into(),
577 }
578 }
579
580 #[test]
581 fn a_court_or_authority_can_hold_a_credential() {
582 // A court credential (e.g. to support proceedings / the audit case).
583 let c = cred().with_authority(CredentialAuthority::Court {
584 order_ref: "order:2026-42".into(),
585 });
586 assert!(matches!(c.authority, CredentialAuthority::Court { .. }));
587 // Single authorization by default → the holder can access while active.
588 assert!(c.payload_accessible(1_100));
589
590 let c2 = cred().with_authority(CredentialAuthority::Authority {
591 authority_did: "did:wf:child-protection".into(),
592 instrument_ref: "mandate:7".into(),
593 });
594 assert!(matches!(
595 c2.authority,
596 CredentialAuthority::Authority { .. }
597 ));
598 }
599
600 #[test]
601 fn multisig_requires_party_instigation_and_threshold_signatures() {
602 let parties = vec![
603 party("did:wf:person", "subject"),
604 party("did:wf:advocate", "advocate"),
605 party("did:wf:court", "court"),
606 ];
607 let c = cred().requiring_multisig(parties, 2);
608
609 // Instigated by a participating party + 2 party signatures → authorised; exercise yields the key.
610 let ok = ExerciseRequest::new(
611 "did:wf:person",
612 vec!["did:wf:person".into(), "did:wf:advocate".into()],
613 );
614 assert!(c.can_exercise(&ok, 1_100));
615 assert!(
616 c.exercise(&ok, 1_100).is_some(),
617 "authorised exercise yields the key"
618 );
619
620 // Below threshold (only 1 party signature) → not authorised.
621 let too_few = ExerciseRequest::new("did:wf:person", vec!["did:wf:person".into()]);
622 assert!(!c.can_exercise(&too_few, 1_100));
623 assert!(c.exercise(&too_few, 1_100).is_none());
624 }
625
626 #[test]
627 fn an_authority_cannot_act_unilaterally_under_multisig() {
628 // A court holds a multi-sig credential. It CANNOT exercise it without a participating party
629 // instigating — this is "unable to act without instigation of one of the participating parties".
630 let parties = vec![
631 party("did:wf:person", "subject"),
632 party("did:wf:guardian", "guardian"),
633 ];
634 let c = cred()
635 .with_authority(CredentialAuthority::Court {
636 order_ref: "order:9".into(),
637 })
638 .requiring_multisig(parties, 1);
639
640 // The court (NOT a participating party) tries to instigate alone → refused, even with a signature
641 // it collected, because the instigator is not a participating party.
642 let court_alone = ExerciseRequest::new("did:wf:court", vec!["did:wf:court".into()]);
643 assert!(
644 !c.can_exercise(&court_alone, 1_100),
645 "an outside authority cannot act unilaterally"
646 );
647 assert!(c.exercise(&court_alone, 1_100).is_none());
648
649 // But once a participating party (the guardian) instigates and signs, the threshold is met.
650 let party_instigated =
651 ExerciseRequest::new("did:wf:guardian", vec!["did:wf:guardian".into()]);
652 assert!(
653 c.can_exercise(&party_instigated, 1_100),
654 "a participating party's instigation authorises it"
655 );
656 }
657
658 #[test]
659 fn revocation_defeats_even_an_authorised_multisig_exercise() {
660 let parties = vec![
661 party("did:wf:person", "subject"),
662 party("did:wf:advocate", "advocate"),
663 ];
664 let mut c = cred().requiring_multisig(parties, 2);
665 let req = ExerciseRequest::new(
666 "did:wf:person",
667 vec!["did:wf:person".into(), "did:wf:advocate".into()],
668 );
669 assert!(c.exercise(&req, 1_100).is_some());
670 c.revoke(1_200);
671 // Even a fully-signed, party-instigated exercise gets no key once revoked — the key is gone.
672 assert!(
673 c.exercise(&req, 1_300).is_none(),
674 "revocation (key destroyed) beats authorisation"
675 );
676 }
677
678 #[test]
679 fn serde_round_trips() {
680 let c = cred();
681 let back: ConsentCredential =
682 serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
683 assert_eq!(c, back);
684 let r = conduct("k", "cc-1", "acted");
685 let back_r: ConductRecord =
686 serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap();
687 assert_eq!(r, back_r);
688 }
689}