Skip to main content

vela_protocol/objects/
claim_record.rs

1//! Current scientific assertion object: `vela.claim-record.v1`.
2//!
3//! Claim Records contain the assertion and its exact support identity. Standing
4//! is derived from the current repository and its covered Decisions; it is
5//! never stored in this object.
6
7use std::collections::BTreeMap;
8
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11use sha2::{Digest, Sha256};
12
13use super::artifact_reference::require_artifact_reference_id;
14
15pub const CLAIM_RECORD_V1_SCHEMA: &str = "vela.claim-record.v1";
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(deny_unknown_fields)]
19pub struct ClaimAssertion {
20    pub text: String,
21    pub kind: String,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(deny_unknown_fields)]
26pub struct ClaimEvidenceRef {
27    pub relation: String,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub artifact_id: Option<String>,
30    pub artifact_root: String,
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub artifact_path: Option<String>,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct ClaimSource {
38    pub kind: String,
39    pub title: String,
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub locator: Option<String>,
42    #[serde(default, skip_serializing_if = "Vec::is_empty")]
43    pub authors: Vec<String>,
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub year: Option<i32>,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct ClaimRelation {
51    pub kind: String,
52    pub target_claim_id: String,
53}
54
55/// A versioned Claim body. The full canonical root is security identity; the
56/// readable `vcl_` prefix is routing only.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(deny_unknown_fields)]
59pub struct ClaimRecordV1 {
60    pub schema: String,
61    pub claim_id: String,
62    pub revision: u32,
63    pub assertion: ClaimAssertion,
64    pub conditions: Vec<String>,
65    pub evidence: Vec<ClaimEvidenceRef>,
66    pub provenance: Vec<ClaimSource>,
67    pub relations: Vec<ClaimRelation>,
68    pub created_at: String,
69    /// Closed protocol fields remain small. Domain detail is
70    /// namespaced and canonical but cannot carry Standing or authority.
71    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
72    pub extensions: BTreeMap<String, Value>,
73}
74
75impl ClaimRecordV1 {
76    #[allow(clippy::too_many_arguments)]
77    pub fn build(
78        revision: u32,
79        assertion: ClaimAssertion,
80        conditions: Vec<String>,
81        evidence: Vec<ClaimEvidenceRef>,
82        provenance: Vec<ClaimSource>,
83        relations: Vec<ClaimRelation>,
84        created_at: String,
85        extensions: BTreeMap<String, Value>,
86    ) -> Result<Self, String> {
87        let mut value = Self {
88            schema: CLAIM_RECORD_V1_SCHEMA.to_string(),
89            claim_id: String::new(),
90            revision,
91            assertion,
92            conditions,
93            evidence,
94            provenance,
95            relations,
96            created_at,
97            extensions,
98        };
99        value.validate_semantics()?;
100        value.claim_id = value.derive_id()?;
101        value.verify()?;
102        Ok(value)
103    }
104
105    pub fn parse(bytes: &[u8]) -> Result<Self, String> {
106        if bytes.len() > 8 * 1024 * 1024 {
107            return Err("Claim Record exceeds the 8 MiB encoded limit".into());
108        }
109        let value: Self = serde_json::from_slice(bytes)
110            .map_err(|error| format!("parse Claim Record v1: {error}"))?;
111        value.verify()?;
112        Ok(value)
113    }
114
115    pub fn verify(&self) -> Result<(), String> {
116        self.validate_semantics()?;
117        let expected = self.derive_id()?;
118        if self.claim_id != expected {
119            return Err(format!(
120                "Claim Record id mismatch: declared {}, rebuilt {expected}",
121                self.claim_id
122            ));
123        }
124        Ok(())
125    }
126
127    pub fn canonical_bytes(&self) -> Result<Vec<u8>, String> {
128        crate::canonical::to_canonical_bytes(self)
129    }
130
131    pub fn canonical_root(&self) -> Result<String, String> {
132        Ok(format!(
133            "sha256:{}",
134            hex::encode(Sha256::digest(self.canonical_bytes()?))
135        ))
136    }
137
138    fn derive_id(&self) -> Result<String, String> {
139        #[derive(Serialize)]
140        struct ClaimIdentity<'a> {
141            schema: &'static str,
142            revision: u32,
143            assertion: &'a ClaimAssertion,
144            conditions: &'a [String],
145            evidence: &'a [ClaimEvidenceRef],
146            provenance: &'a [ClaimSource],
147        }
148        let bytes = crate::canonical::to_canonical_bytes(&ClaimIdentity {
149            schema: "vela.claim-identity.v1",
150            revision: self.revision,
151            assertion: &self.assertion,
152            conditions: &self.conditions,
153            evidence: &self.evidence,
154            provenance: &self.provenance,
155        })?;
156        Ok(format!("vcl_{}", hex::encode(Sha256::digest(bytes))))
157    }
158
159    fn validate_semantics(&self) -> Result<(), String> {
160        if self.schema != CLAIM_RECORD_V1_SCHEMA {
161            return Err(format!(
162                "Claim Record schema must be `{CLAIM_RECORD_V1_SCHEMA}`"
163            ));
164        }
165        if self.revision == 0 {
166            return Err("Claim Record revision must be positive".into());
167        }
168        require_scientific_text("assertion.text", &self.assertion.text)?;
169        require_text("assertion.kind", &self.assertion.kind)?;
170        for condition in &self.conditions {
171            require_scientific_text("conditions", condition)?;
172        }
173        for evidence in &self.evidence {
174            require_text("evidence.relation", &evidence.relation)?;
175            if let Some(artifact_id) = &evidence.artifact_id {
176                require_artifact_reference_id("Claim Record", "evidence.artifact_id", artifact_id)?;
177            }
178            require_sha256("evidence.artifact_root", &evidence.artifact_root)?;
179            if let Some(path) = &evidence.artifact_path {
180                require_relative_path("evidence.artifact_path", path)?;
181            }
182        }
183        for source in &self.provenance {
184            require_text("provenance.kind", &source.kind)?;
185            require_text("provenance.title", &source.title)?;
186            if let Some(locator) = &source.locator {
187                require_text("provenance.locator", locator)?;
188            }
189            for author in &source.authors {
190                require_text("provenance.authors", author)?;
191            }
192        }
193        for relation in &self.relations {
194            require_text("relations.kind", &relation.kind)?;
195            require_full_claim_id("relations.target_claim_id", &relation.target_claim_id)?;
196        }
197        chrono::DateTime::parse_from_rfc3339(&self.created_at)
198            .map_err(|_| "Claim Record created_at must be RFC 3339".to_string())?;
199        for (namespace, value) in &self.extensions {
200            if !namespace.contains('.') || namespace.starts_with('.') || namespace.ends_with('.') {
201                return Err(format!(
202                    "Claim Record extension `{namespace}` must use a dotted namespace"
203                ));
204            }
205            if !value.is_object() {
206                return Err(format!(
207                    "Claim Record extension `{namespace}` must be a JSON object"
208                ));
209            }
210            reject_authority_extension(namespace, value)?;
211        }
212        Ok(())
213    }
214}
215
216fn reject_authority_extension(namespace: &str, value: &Value) -> Result<(), String> {
217    const FORBIDDEN: &[&str] = &[
218        "standing",
219        "accepted",
220        "accepted_state",
221        "decision",
222        "authority",
223        "signature",
224    ];
225    if let Some(object) = value.as_object() {
226        for key in object.keys() {
227            if FORBIDDEN.contains(&key.as_str()) {
228                return Err(format!(
229                    "Claim Record extension `{namespace}` cannot carry authority field `{key}`"
230                ));
231            }
232        }
233    }
234    Ok(())
235}
236
237fn require_text(field: &str, value: &str) -> Result<(), String> {
238    if value.trim().is_empty() || value != value.trim() || value.chars().any(char::is_control) {
239        return Err(format!(
240            "Claim Record {field} must be non-empty, trimmed text"
241        ));
242    }
243    Ok(())
244}
245
246fn require_scientific_text(field: &str, value: &str) -> Result<(), String> {
247    if value.trim().is_empty()
248        || value != value.trim()
249        || value
250            .chars()
251            .any(|character| character.is_control() && character != '\n' && character != '\t')
252    {
253        return Err(format!(
254            "Claim Record {field} must be non-empty, trimmed scientific text"
255        ));
256    }
257    Ok(())
258}
259
260fn require_full_claim_id(field: &str, value: &str) -> Result<(), String> {
261    let digest = value
262        .strip_prefix("vcl_")
263        .ok_or_else(|| format!("Claim Record {field} must be a full vcl_ digest"))?;
264    if digest.len() != 64
265        || !digest
266            .bytes()
267            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
268    {
269        return Err(format!("Claim Record {field} must be a full vcl_ digest"));
270    }
271    Ok(())
272}
273
274fn require_sha256(field: &str, value: &str) -> Result<(), String> {
275    let digest = value
276        .strip_prefix("sha256:")
277        .ok_or_else(|| format!("Claim Record {field} must be a full sha256: digest"))?;
278    if digest.len() != 64
279        || !digest
280            .bytes()
281            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
282    {
283        return Err(format!(
284            "Claim Record {field} must be a full sha256: digest"
285        ));
286    }
287    Ok(())
288}
289
290fn require_relative_path(field: &str, value: &str) -> Result<(), String> {
291    require_text(field, value)?;
292    if value.starts_with('/') || value.split('/').any(|segment| segment == "..") {
293        return Err(format!("Claim Record {field} must be a safe relative path"));
294    }
295    Ok(())
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    fn root(byte: char) -> String {
303        format!("sha256:{}", byte.to_string().repeat(64))
304    }
305
306    #[test]
307    fn claim_record_is_content_addressed_and_carries_no_standing() {
308        let record = ClaimRecordV1::build(
309            1,
310            ClaimAssertion {
311                text: "A bounded computation returned no witness.".into(),
312                kind: "computational".into(),
313            },
314            vec!["Range 1..100 inclusive.".into()],
315            vec![ClaimEvidenceRef {
316                relation: "supports".into(),
317                artifact_id: Some("a".repeat(64)),
318                artifact_root: root('a'),
319                artifact_path: Some(format!("records/artifacts/sha256/{}", "a".repeat(64))),
320            }],
321            vec![ClaimSource {
322                kind: "repository_import".into(),
323                title: "Historical Finding vf_fixture".into(),
324                locator: None,
325                authors: vec![],
326                year: None,
327            }],
328            vec![],
329            "2026-07-27T00:00:00Z".into(),
330            BTreeMap::new(),
331        )
332        .unwrap();
333        assert!(record.claim_id.starts_with("vcl_"));
334        ClaimRecordV1::parse(&record.canonical_bytes().unwrap()).unwrap();
335
336        let mut raw = serde_json::to_value(&record).unwrap();
337        raw["claim_id"] = Value::String("vcl_tampered".into());
338        assert!(ClaimRecordV1::parse(&serde_json::to_vec(&raw).unwrap()).is_err());
339    }
340
341    #[test]
342    fn extension_cannot_smuggle_standing_or_authority() {
343        let mut extensions = BTreeMap::new();
344        extensions.insert(
345            "example.extension.v1".into(),
346            serde_json::json!({"standing": "accepted"}),
347        );
348        let error = ClaimRecordV1::build(
349            1,
350            ClaimAssertion {
351                text: "Claim".into(),
352                kind: "theoretical".into(),
353            },
354            vec![],
355            vec![],
356            vec![],
357            vec![],
358            "2026-07-27T00:00:00Z".into(),
359            extensions,
360        )
361        .unwrap_err();
362        assert!(error.contains("cannot carry authority field"));
363    }
364
365    #[test]
366    fn scientific_assertions_preserve_bounded_multiline_text() {
367        let record = ClaimRecordV1::build(
368            1,
369            ClaimAssertion {
370                text: "Let n be positive.\n\nThen the bounded conclusion follows.".into(),
371                kind: "theoretical".into(),
372            },
373            vec!["Assume the stated hypotheses.\nUse the exact pinned source.".into()],
374            vec![],
375            vec![],
376            vec![],
377            "2026-07-27T00:00:00Z".into(),
378            BTreeMap::new(),
379        )
380        .unwrap();
381        assert!(record.assertion.text.contains("\n\n"));
382        ClaimRecordV1::parse(&record.canonical_bytes().unwrap()).unwrap();
383    }
384
385    #[test]
386    fn current_content_hash_evidence_is_valid() {
387        let record = ClaimRecordV1::build(
388            1,
389            ClaimAssertion {
390                text: "A retained verifier reproduced the bounded result.".into(),
391                kind: "computational".into(),
392            },
393            vec!["Exact retained inputs only.".into()],
394            vec![ClaimEvidenceRef {
395                relation: "supports".into(),
396                artifact_id: Some("a".repeat(64)),
397                artifact_root: root('a'),
398                artifact_path: Some(format!("records/artifacts/sha256/{}", "a".repeat(64))),
399            }],
400            vec![ClaimSource {
401                kind: "repository".into(),
402                title: "Current content-addressed evidence".into(),
403                locator: None,
404                authors: vec![],
405                year: None,
406            }],
407            vec![],
408            "2026-07-29T00:00:00Z".into(),
409            BTreeMap::new(),
410        )
411        .unwrap();
412        assert!(record.claim_id.starts_with("vcl_"));
413    }
414
415    #[test]
416    fn malformed_evidence_artifact_id_fails_closed() {
417        let error = ClaimRecordV1::build(
418            1,
419            ClaimAssertion {
420                text: "A retained verifier reproduced the bounded result.".into(),
421                kind: "computational".into(),
422            },
423            vec![],
424            vec![ClaimEvidenceRef {
425                relation: "supports".into(),
426                artifact_id: Some("sha256:short".into()),
427                artifact_root: root('a'),
428                artifact_path: None,
429            }],
430            vec![],
431            vec![],
432            "2026-07-29T00:00:00Z".into(),
433            BTreeMap::new(),
434        )
435        .unwrap_err();
436        assert!(error.contains("full lowercase content hash"));
437    }
438}