Skip to main content

qualia_core_db/q42/asset_envelope/
mod.rs

1//! Governed Q42 asset envelope and licence policy (AST-01).
2//!
3//! Cold-construction schema for upstream release identity, digests, formats,
4//! record counts, parser/mapping versions, provenance, licence obligations,
5//! sensitivity, validation, and bounded chunk plans. Unknown licences fail
6//! closed. Derived assets inherit the union of upstream obligations.
7
8mod codec;
9mod envelope;
10mod error;
11mod licence;
12
13pub use codec::ASSET_ENVELOPE_MAGIC;
14pub use envelope::{
15    sha256_into, sha256_of, AssetRoutingLane, AssetSensitivity, ChunkSpec, Q42AssetEnvelope,
16    RecordCounts, ToolchainVersions, UpstreamRelease, ASSET_ENVELOPE_VERSION, MAX_DERIVED_FROM,
17    MAX_ENVELOPE_BYTES, MAX_NAMESPACES, MAX_REJECTION_REASONS, SENTINEL_PASS_BUDGET_BYTES,
18};
19pub use error::AssetEnvelopeError;
20pub use licence::{LicenceClass, LicenceObligations, LicencePolicy, RedistributionClass, UseClass};
21
22#[cfg(test)]
23mod tests {
24    use super::*;
25
26    fn sample_envelope() -> Q42AssetEnvelope {
27        let payload = b"CHEBI:15377 water fixture";
28        Q42AssetEnvelope {
29            asset_id: "did:q42:asset:chebi:261".into(),
30            upstream: UpstreamRelease {
31                source_name: "ChEBI".into(),
32                release_id: "rel261".into(),
33                source_url: "https://www.ebi.ac.uk/chebi/".into(),
34                retrieved_unix: 1_725_000_000,
35                byte_length: payload.len() as u64,
36                sha256: sha256_of(payload),
37            },
38            licence: LicencePolicy::from_tag(
39                "CC-BY-4.0",
40                "https://creativecommons.org/licenses/by/4.0/",
41                "ChEBI consortium",
42            )
43            .unwrap(),
44            toolchain: ToolchainVersions {
45                parser_version: "chebi-tsv-0.1".into(),
46                mapping_version: "chebi-quin-0.1".into(),
47            },
48            raw_format: "tsv".into(),
49            media_type: "text/tab-separated-values".into(),
50            counts: RecordCounts {
51                source: 10,
52                accepted: 9,
53                quarantined: 1,
54            },
55            rejection_reasons: vec!["malformed row 4".into()],
56            identifier_namespaces: vec!["CHEBI".into()],
57            cross_reference_policy: "preserve-upstream-id".into(),
58            evidence_grade: "ontology-identity".into(),
59            citation: "https://doi.org/10.1093/nar/gkaa991".into(),
60            curation_status: "release".into(),
61            sensitivity: AssetSensitivity::Public,
62            routing_lane: AssetRoutingLane::Commons,
63            derived_from: vec![],
64            shacl_profile: "q42:ChebiReleaseShape".into(),
65            validation_report: "ok".into(),
66            chunk_plan: vec![ChunkSpec {
67                index: 0,
68                byte_budget: 8 * 1024 * 1024,
69                record_budget: 50_000,
70            }],
71        }
72    }
73
74    #[test]
75    fn round_trip_preserves_envelope() {
76        let original = sample_envelope();
77        let bytes = original.encode().unwrap();
78        let decoded = Q42AssetEnvelope::decode(&bytes).unwrap();
79        assert_eq!(decoded, original);
80    }
81
82    #[test]
83    fn envelope_digest_is_deterministic() {
84        let a = sample_envelope().envelope_digest().unwrap();
85        let b = sample_envelope().envelope_digest().unwrap();
86        assert_eq!(a, b);
87        assert_ne!(a, [0u8; 32]);
88    }
89
90    #[test]
91    fn payload_digest_verification() {
92        let env = sample_envelope();
93        let good = sha256_of(b"CHEBI:15377 water fixture");
94        assert!(env.verify_payload_digest(&good).is_ok());
95        let bad = sha256_of(b"tampered");
96        assert_eq!(
97            env.verify_payload_digest(&bad),
98            Err(AssetEnvelopeError::DigestMismatch)
99        );
100    }
101
102    #[test]
103    fn invalid_magic_rejected() {
104        let mut bytes = sample_envelope().encode().unwrap();
105        bytes[0] = b'X';
106        assert_eq!(
107            Q42AssetEnvelope::decode(&bytes),
108            Err(AssetEnvelopeError::InvalidMagic)
109        );
110    }
111
112    #[test]
113    fn unknown_licence_cannot_build_policy() {
114        assert_eq!(
115            LicencePolicy::try_new(
116                LicenceClass::Unknown,
117                UseClass::Research,
118                RedistributionClass::NoRedistribution,
119                "https://example.test",
120                "x",
121            ),
122            Err(AssetEnvelopeError::UnknownLicence)
123        );
124    }
125
126    #[test]
127    fn derived_asset_inherits_stricter_obligations() {
128        let raw = sample_envelope();
129        let nc = LicencePolicy::from_tag(
130            "CC-BY-NC-4.0",
131            "https://creativecommons.org/licenses/by-nc/4.0/",
132            "overlay",
133        )
134        .unwrap();
135        let derived = raw
136            .derive_with(
137                "did:q42:asset:chebi:261:normalized",
138                &nc,
139                ToolchainVersions {
140                    parser_version: "chebi-tsv-0.1".into(),
141                    mapping_version: "chebi-quin-0.2".into(),
142                },
143                vec![ChunkSpec {
144                    index: 0,
145                    byte_budget: 4 * 1024 * 1024,
146                    record_budget: 10_000,
147                }],
148            )
149            .unwrap();
150        assert_eq!(derived.licence.class, LicenceClass::CcByNc);
151        assert!(!derived.licence.allows_redistribution());
152        assert_eq!(derived.derived_from, vec![raw.asset_id]);
153        let bytes = derived.encode().unwrap();
154        let again = Q42AssetEnvelope::decode(&bytes).unwrap();
155        assert_eq!(again.licence.obligations, derived.licence.obligations);
156    }
157
158    #[test]
159    fn chunk_over_sentinel_budget_fails() {
160        let mut env = sample_envelope();
161        env.chunk_plan[0].byte_budget = SENTINEL_PASS_BUDGET_BYTES + 1;
162        assert_eq!(env.validate(), Err(AssetEnvelopeError::ChunkBudgetExceeded));
163    }
164
165    #[test]
166    fn sha256_into_matches_sha256_of() {
167        let data = b"caller-buffered";
168        let mut out = [0u8; 32];
169        sha256_into(data, &mut out);
170        assert_eq!(out, sha256_of(data));
171    }
172}