Skip to main content

qualia_core_db/semantic_instruments/attestation/
native.rs

1//! Native Ed25519 attestation adapter (SI-04).
2//!
3//! Seals an [`InstrumentAttestation`] through the engine VC core. A valid
4//! signature authenticates origin/integrity, not substantive truth.
5
6use crate::crypto::verifiable_credential::{self, Credential, VcError};
7use crate::q_hash;
8use crate::semantic_instruments::attestation::kinds::{AttestationKind, InstrumentAttestation};
9use crate::semantic_instruments::errors::InstrumentError;
10use crate::NQuin;
11use ed25519_dalek::{Signature, SigningKey, VerifyingKey};
12
13/// Issued native attestation plus the Ed25519 seal over its VC digest.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct NativeIssued {
16    pub attestation: InstrumentAttestation,
17    pub signature: Signature,
18}
19
20fn claim_quin(issuer: u64, predicate: u64, object: u64) -> NQuin {
21    NQuin {
22        subject: issuer,
23        predicate,
24        object,
25        context: 0,
26        metadata: 0,
27        parity: NQuin::calculate_parity(issuer, predicate, object, 0, 0),
28    }
29}
30
31fn credential_from(attestation: &InstrumentAttestation) -> Credential {
32    let issuer = q_hash(&attestation.actor);
33    let subject = if attestation.kind == AttestationKind::CapabilityAward {
34        q_hash(&attestation.award_subject)
35    } else {
36        q_hash(&attestation.release_id)
37    };
38
39    let mut claims = vec![
40        claim_quin(
41            issuer,
42            q_hash(attestation.kind.as_iri()),
43            q_hash(&attestation.content_digest),
44        ),
45        claim_quin(
46            issuer,
47            q_hash("si:releaseId"),
48            q_hash(&attestation.release_id),
49        ),
50        claim_quin(issuer, q_hash("si:signatureIsNotTruth"), q_hash("true")),
51    ];
52    if attestation.kind == AttestationKind::CapabilityAward {
53        claims.push(claim_quin(
54            issuer,
55            q_hash("si:awardSubject"),
56            q_hash(&attestation.award_subject),
57        ));
58        claims.push(claim_quin(
59            issuer,
60            q_hash("si:assessmentReleaseId"),
61            q_hash(&attestation.assessment_release_id),
62        ));
63    }
64
65    Credential {
66        issuer,
67        subject,
68        issued_at: attestation.issued_at,
69        valid_until: attestation.valid_until,
70        claims,
71    }
72}
73
74fn map_vc_error(err: VcError) -> InstrumentError {
75    match err {
76        VcError::Expired => InstrumentError::Expired,
77        VcError::InvalidSignature
78        | VcError::UngroundedIssuer
79        | VcError::DecodeTooShort
80        | VcError::DecodeBadClaimCount => InstrumentError::Tampered,
81    }
82}
83
84/// Seal `attestation` with the issuer's Ed25519 key.
85pub fn issue_native(
86    signing_key: &SigningKey,
87    attestation: InstrumentAttestation,
88) -> Result<NativeIssued, InstrumentError> {
89    attestation.validate()?;
90    let credential = credential_from(&attestation);
91    let signature = verifiable_credential::issue(signing_key, &credential);
92    Ok(NativeIssued {
93        attestation,
94        signature,
95    })
96}
97
98/// Verify origin of `issued` at `now_unix`. Does not assert the claim is true.
99pub fn verify_native(
100    issuer_key: &VerifyingKey,
101    issued: &NativeIssued,
102    now_unix: u32,
103) -> Result<(), InstrumentError> {
104    issued.attestation.validate()?;
105    if issued.attestation.valid_until != 0 && now_unix > issued.attestation.valid_until {
106        return Err(InstrumentError::Expired);
107    }
108    let credential = credential_from(&issued.attestation);
109    verifiable_credential::verify(&credential, issuer_key, &issued.signature, now_unix)
110        .map_err(map_vc_error)
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    fn key() -> SigningKey {
118        SigningKey::from_bytes(&[7u8; 32])
119    }
120
121    fn digest(fill: char) -> String {
122        format!("sha256:{}", fill.to_string().repeat(64))
123    }
124
125    fn sample() -> InstrumentAttestation {
126        InstrumentAttestation {
127            kind: AttestationKind::Authorship,
128            release_id: "si:release:demo-unit-convert".into(),
129            content_digest: digest('a'),
130            actor: "did:example:author".into(),
131            issued_at: 1_000,
132            valid_until: 2_000,
133            origin_is_not_truth: true,
134            award_subject: String::new(),
135            assessment_release_id: String::new(),
136        }
137    }
138
139    #[test]
140    fn issue_and_verify_roundtrip() {
141        let sk = key();
142        let issued = issue_native(&sk, sample()).expect("issue");
143        assert_eq!(verify_native(&sk.verifying_key(), &issued, 1_500), Ok(()));
144        assert!(issued.attestation.origin_is_not_truth);
145        assert_eq!(issued.attestation.kind, AttestationKind::Authorship);
146    }
147
148    #[test]
149    fn tampered_content_digest_fails_verification() {
150        let sk = key();
151        let mut issued = issue_native(&sk, sample()).expect("issue");
152        issued.attestation.content_digest = digest('b');
153        assert_eq!(
154            verify_native(&sk.verifying_key(), &issued, 1_500),
155            Err(InstrumentError::Tampered)
156        );
157    }
158
159    #[test]
160    fn expired_attestation_fails() {
161        let sk = key();
162        let mut attestation = sample();
163        attestation.valid_until = 10;
164        let issued = issue_native(&sk, attestation).expect("issue");
165        assert_eq!(
166            verify_native(&sk.verifying_key(), &issued, 11),
167            Err(InstrumentError::Expired)
168        );
169    }
170}