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