Skip to main content

qualia_core_db/q42/asset_envelope/
licence.rs

1//! Licence / use / redistribution policy for governed Q42 assets.
2//!
3//! Unknown licences fail closed: they never allow redistribution and cannot be
4//! accepted into a validated envelope. Derived assets inherit the union of
5//! upstream obligations (most restrictive wins).
6
7use super::error::AssetEnvelopeError;
8
9/// Recognised upstream licence classes for health/dataset assets.
10#[repr(u8)]
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum LicenceClass {
13    /// Provenance unknown — never redistributable.
14    Unknown = 0,
15    /// CC0 / public-domain-equivalent.
16    Cc0 = 1,
17    /// CC BY 4.0 (attribution).
18    CcBy = 2,
19    /// CC BY-SA 4.0 (attribution + share-alike).
20    CcBySa = 3,
21    /// CC BY-NC 4.0 (non-commercial).
22    CcByNc = 4,
23    /// Explicit proprietary grant recorded on the envelope (still may forbid redistribution).
24    ProprietaryPermitted = 5,
25    /// Social Permissive Commons (threshold discharge, third-party anchored, travelling obligation).
26    SocialPermissiveCommons = 6,
27}
28
29impl LicenceClass {
30    /// Decodes from u8.
31    pub fn from_u8(value: u8) -> Self {
32        match value {
33            1 => Self::Cc0,
34            2 => Self::CcBy,
35            3 => Self::CcBySa,
36            4 => Self::CcByNc,
37            5 => Self::ProprietaryPermitted,
38            6 => Self::SocialPermissiveCommons,
39            _ => Self::Unknown,
40        }
41    }
42
43    /// Parse a short licence tag. Unrecognised strings become [`LicenceClass::Unknown`].
44    pub fn parse(tag: &str) -> Self {
45        if tag.trim().eq_ignore_ascii_case("SocialPermissiveCommons")
46            || tag.trim().eq_ignore_ascii_case("PermissiveCommons")
47        {
48            return Self::SocialPermissiveCommons;
49        }
50        let normalised = tag.trim().to_ascii_uppercase().replace(' ', "-");
51        match normalised.as_str() {
52            "CC0" | "CC0-1.0" | "PUBLIC-DOMAIN" => Self::Cc0,
53            "CC-BY" | "CC-BY-4.0" | "CCBY" => Self::CcBy,
54            "CC-BY-SA" | "CC-BY-SA-4.0" | "CCBYSA" => Self::CcBySa,
55            "CC-BY-NC" | "CC-BY-NC-4.0" | "CCBYNC" => Self::CcByNc,
56            "PROPRIETARY-PERMITTED" | "PROPRIETARY" => Self::ProprietaryPermitted,
57            "SPC" | "SOCIAL-PERMISSIVE-COMMONS" | "PERMISSIVE-COMMONS" | "COMMONS" => {
58                Self::SocialPermissiveCommons
59            }
60            _ => Self::Unknown,
61        }
62    }
63}
64
65/// Intended use class recorded on the envelope.
66#[repr(u8)]
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
68pub enum UseClass {
69    Unknown = 0,
70    Research = 1,
71    NonCommercial = 2,
72    Commercial = 3,
73    Internal = 4,
74}
75
76impl UseClass {
77    /// Builds `UseClass` from `u8`.
78    pub fn from_u8(value: u8) -> Self {
79        match value {
80            1 => Self::Research,
81            2 => Self::NonCommercial,
82            3 => Self::Commercial,
83            4 => Self::Internal,
84            _ => Self::Unknown,
85        }
86    }
87
88    fn restrictiveness(self) -> u8 {
89        match self {
90            Self::Commercial => 1,
91            Self::Research => 2,
92            Self::NonCommercial => 3,
93            Self::Internal => 4,
94            Self::Unknown => 5,
95        }
96    }
97
98    fn stricter(self, other: Self) -> Self {
99        if self.restrictiveness() >= other.restrictiveness() {
100            self
101        } else {
102            other
103        }
104    }
105}
106
107/// Redistribution posture for the asset and its derivatives.
108#[repr(u8)]
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
110pub enum RedistributionClass {
111    Unknown = 0,
112    FreelyRedistributable = 1,
113    AttributionRequired = 2,
114    NonCommercialOnly = 3,
115    NoRedistribution = 4,
116}
117
118impl RedistributionClass {
119    /// Builds `RedistributionClass` from `u8`.
120    pub fn from_u8(value: u8) -> Self {
121        match value {
122            1 => Self::FreelyRedistributable,
123            2 => Self::AttributionRequired,
124            3 => Self::NonCommercialOnly,
125            4 => Self::NoRedistribution,
126            _ => Self::Unknown,
127        }
128    }
129
130    fn restrictiveness(self) -> u8 {
131        match self {
132            Self::FreelyRedistributable => 1,
133            Self::AttributionRequired => 2,
134            Self::NonCommercialOnly => 3,
135            Self::NoRedistribution => 4,
136            Self::Unknown => 5,
137        }
138    }
139
140    fn stricter(self, other: Self) -> Self {
141        if self.restrictiveness() >= other.restrictiveness() {
142            self
143        } else {
144            other
145        }
146    }
147}
148
149/// Obligation flags that propagate to derived assets (bitfield).
150#[repr(transparent)]
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
152pub struct LicenceObligations(pub u16);
153
154impl LicenceObligations {
155    pub const ATTRIBUTION: u16 = 1 << 0;
156    pub const SHARE_ALIKE: u16 = 1 << 1;
157    pub const NON_COMMERCIAL: u16 = 1 << 2;
158    pub const NO_REDISTRIBUTION: u16 = 1 << 3;
159    pub const NOTICE: u16 = 1 << 4;
160    /// spc:ThirdPartyAnchoredObligation: obligation anchored to external custodians or contributors.
161    pub const THIRD_PARTY_ANCHORED: u16 = 1 << 5;
162    /// spc:ArtifactTravellingObligation: obligation travels with the artifact / derivatives.
163    pub const ARTIFACT_TRAVELLING: u16 = 1 << 6;
164    /// Permissive commons dischargeable: converts to unencumbered commons once pool >= cost.
165    pub const COMMONS_DISCHARGEABLE: u16 = 1 << 7;
166
167    /// Empty value.
168    pub const fn empty() -> Self {
169        Self(0)
170    }
171
172    /// `true` when the key exists.
173    pub const fn contains(self, flag: u16) -> bool {
174        self.0 & flag != 0
175    }
176
177    /// `LicenceObligations::union`.
178    pub const fn union(self, other: Self) -> Self {
179        Self(self.0 | other.0)
180    }
181
182    /// Builds `LicenceObligations` from `licence`.
183    pub fn from_licence(class: LicenceClass) -> Self {
184        match class {
185            LicenceClass::Cc0 => Self::empty(),
186            LicenceClass::CcBy => Self(Self::ATTRIBUTION | Self::NOTICE),
187            LicenceClass::CcBySa => Self(Self::ATTRIBUTION | Self::SHARE_ALIKE | Self::NOTICE),
188            LicenceClass::CcByNc => Self(Self::ATTRIBUTION | Self::NON_COMMERCIAL | Self::NOTICE),
189            LicenceClass::ProprietaryPermitted => Self(Self::NOTICE | Self::NO_REDISTRIBUTION),
190            LicenceClass::SocialPermissiveCommons => Self(
191                Self::ATTRIBUTION
192                    | Self::NOTICE
193                    | Self::THIRD_PARTY_ANCHORED
194                    | Self::ARTIFACT_TRAVELLING
195                    | Self::COMMONS_DISCHARGEABLE,
196            ),
197            LicenceClass::Unknown => Self(Self::NO_REDISTRIBUTION | Self::NOTICE),
198        }
199    }
200}
201
202/// Full licence policy recorded on a Q42 asset envelope.
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub struct LicencePolicy {
205    pub class: LicenceClass,
206    pub use_class: UseClass,
207    pub redistribution: RedistributionClass,
208    pub obligations: LicenceObligations,
209    /// Upstream terms URL (may be empty only for CC0 when explicitly recorded).
210    pub terms_url: String,
211    pub attribution: String,
212}
213
214impl LicencePolicy {
215    /// Build a policy from explicit classes. Unknown licence fails closed.
216    pub fn try_new(
217        class: LicenceClass,
218        use_class: UseClass,
219        redistribution: RedistributionClass,
220        terms_url: impl Into<String>,
221        attribution: impl Into<String>,
222    ) -> Result<Self, AssetEnvelopeError> {
223        if class == LicenceClass::Unknown {
224            return Err(AssetEnvelopeError::UnknownLicence);
225        }
226        if redistribution == RedistributionClass::Unknown {
227            return Err(AssetEnvelopeError::UnknownLicence);
228        }
229        if use_class == UseClass::Unknown {
230            return Err(AssetEnvelopeError::UnknownLicence);
231        }
232        let terms_url = terms_url.into();
233        let attribution = attribution.into();
234        if class != LicenceClass::Cc0 && terms_url.trim().is_empty() {
235            return Err(AssetEnvelopeError::MissingTermsUrl);
236        }
237        let mut obligations = LicenceObligations::from_licence(class);
238        if matches!(
239            redistribution,
240            RedistributionClass::NoRedistribution | RedistributionClass::NonCommercialOnly
241        ) {
242            obligations =
243                obligations.union(LicenceObligations(LicenceObligations::NO_REDISTRIBUTION));
244        }
245        if redistribution == RedistributionClass::NonCommercialOnly {
246            obligations = obligations.union(LicenceObligations(LicenceObligations::NON_COMMERCIAL));
247        }
248        if redistribution == RedistributionClass::AttributionRequired {
249            obligations = obligations.union(LicenceObligations(LicenceObligations::ATTRIBUTION));
250        }
251        Ok(Self {
252            class,
253            use_class,
254            redistribution,
255            obligations,
256            terms_url,
257            attribution,
258        })
259    }
260
261    /// Parse from a short licence tag plus recorded terms. Unknown tags fail closed.
262    pub fn from_tag(
263        tag: &str,
264        terms_url: impl Into<String>,
265        attribution: impl Into<String>,
266    ) -> Result<Self, AssetEnvelopeError> {
267        let class = LicenceClass::parse(tag);
268        let (use_class, redistribution) = match class {
269            LicenceClass::Cc0 => (
270                UseClass::Commercial,
271                RedistributionClass::FreelyRedistributable,
272            ),
273            LicenceClass::CcBy | LicenceClass::CcBySa => (
274                UseClass::Commercial,
275                RedistributionClass::AttributionRequired,
276            ),
277            LicenceClass::CcByNc => (
278                UseClass::NonCommercial,
279                RedistributionClass::NonCommercialOnly,
280            ),
281            LicenceClass::ProprietaryPermitted => {
282                (UseClass::Internal, RedistributionClass::NoRedistribution)
283            }
284            LicenceClass::SocialPermissiveCommons => (
285                UseClass::Commercial,
286                RedistributionClass::AttributionRequired,
287            ),
288            LicenceClass::Unknown => {
289                return Err(AssetEnvelopeError::UnknownLicence);
290            }
291        };
292        Self::try_new(class, use_class, redistribution, terms_url, attribution)
293    }
294
295    /// Check whether a Social Permissive Commons obligation has discharged
296    /// based on accumulated payments meeting audited production cost + ROI cap.
297    pub fn is_spc_discharged(&self, accumulated_pool: u64, cost: u64) -> bool {
298        self.obligations
299            .contains(LicenceObligations::COMMONS_DISCHARGEABLE)
300            && crate::modalities::socioeconomics::is_commons_discharged(accumulated_pool, cost)
301    }
302
303    /// May this asset (or a derived bundle) be redistributed outside the local node?
304    pub fn allows_redistribution(&self) -> bool {
305        !self
306            .obligations
307            .contains(LicenceObligations::NO_REDISTRIBUTION)
308            && matches!(
309                self.redistribution,
310                RedistributionClass::FreelyRedistributable
311                    | RedistributionClass::AttributionRequired
312            )
313            && self.class != LicenceClass::Unknown
314    }
315
316    /// Most-restrictive union of two policies for a derived asset.
317    pub fn union_obligations(&self, other: &Self) -> Self {
318        let class = if self.class.restrictiveness() >= other.class.restrictiveness() {
319            self.class
320        } else {
321            other.class
322        };
323        let use_class = self.use_class.stricter(other.use_class);
324        let redistribution = self.redistribution.stricter(other.redistribution);
325        let obligations = self.obligations.union(other.obligations);
326        let terms_url = if other.terms_url.len() > self.terms_url.len() {
327            other.terms_url.clone()
328        } else {
329            self.terms_url.clone()
330        };
331        let attribution = if self.attribution.is_empty() {
332            other.attribution.clone()
333        } else if other.attribution.is_empty() || self.attribution == other.attribution {
334            self.attribution.clone()
335        } else {
336            format!("{}; {}", self.attribution, other.attribution)
337        };
338        Self {
339            class,
340            use_class,
341            redistribution,
342            obligations,
343            terms_url,
344            attribution,
345        }
346    }
347}
348
349impl LicenceClass {
350    fn restrictiveness(self) -> u8 {
351        match self {
352            Self::Cc0 => 1,
353            Self::CcBy => 2,
354            Self::CcBySa => 3,
355            Self::CcByNc => 4,
356            Self::SocialPermissiveCommons => 2,
357            Self::ProprietaryPermitted => 5,
358            Self::Unknown => 6,
359        }
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    #[test]
368    fn commons_manifest_tag_is_recognized() {
369        assert_eq!(
370            LicenceClass::parse("SocialPermissiveCommons"),
371            LicenceClass::SocialPermissiveCommons
372        );
373        assert_eq!(
374            LicenceClass::parse("PermissiveCommons"),
375            LicenceClass::SocialPermissiveCommons
376        );
377    }
378
379    #[test]
380    fn unknown_licence_tag_fails_closed() {
381        assert!(matches!(
382            LicencePolicy::from_tag("totally-made-up", "https://example.test", "x"),
383            Err(AssetEnvelopeError::UnknownLicence)
384        ));
385    }
386
387    #[test]
388    fn cc_by_allows_redistribution_with_attribution() {
389        let policy = LicencePolicy::from_tag(
390            "CC-BY-4.0",
391            "https://creativecommons.org/licenses/by/4.0/",
392            "ChEBI",
393        )
394        .unwrap();
395        assert!(policy.allows_redistribution());
396        assert!(policy.obligations.contains(LicenceObligations::ATTRIBUTION));
397    }
398
399    #[test]
400    fn obligation_union_takes_stricter_side() {
401        let a = LicencePolicy::from_tag(
402            "CC-BY-4.0",
403            "https://creativecommons.org/licenses/by/4.0/",
404            "A",
405        )
406        .unwrap();
407        let b = LicencePolicy::from_tag(
408            "CC-BY-NC-4.0",
409            "https://creativecommons.org/licenses/by-nc/4.0/",
410            "B",
411        )
412        .unwrap();
413        let u = a.union_obligations(&b);
414        assert_eq!(u.class, LicenceClass::CcByNc);
415        assert_eq!(u.redistribution, RedistributionClass::NonCommercialOnly);
416        assert!(u.obligations.contains(LicenceObligations::NON_COMMERCIAL));
417        assert!(!u.allows_redistribution());
418    }
419
420    #[test]
421    fn test_spc_licence_policy_and_discharge() {
422        let spc = LicencePolicy::from_tag(
423            "SPC",
424            "https://socialpermissivecommons.org/terms",
425            "Community Custodians",
426        )
427        .unwrap();
428
429        assert_eq!(spc.class, LicenceClass::SocialPermissiveCommons);
430        assert!(spc
431            .obligations
432            .contains(LicenceObligations::THIRD_PARTY_ANCHORED));
433        assert!(spc
434            .obligations
435            .contains(LicenceObligations::ARTIFACT_TRAVELLING));
436        assert!(spc
437            .obligations
438            .contains(LicenceObligations::COMMONS_DISCHARGEABLE));
439
440        // Before cost is reached: not discharged
441        let cost = 10_000u64;
442        assert!(!spc.is_spc_discharged(5_000, cost));
443
444        // When pool >= cost: discharged
445        assert!(spc.is_spc_discharged(10_000, cost));
446        assert!(spc.is_spc_discharged(12_000, cost));
447    }
448}