1use std::collections::BTreeSet;
9
10use serde::{Deserialize, Serialize};
11use sha2::{Digest, Sha256};
12
13use crate::bundle::Artifact;
14use crate::frontier_profile::{
15 FrontierProfileLicenseV1, FrontierProfileScopeV1, reject_yaml_indirection,
16 validate_profile_metadata, validate_yaml_structure,
17};
18
19pub const CURRENT_REPOSITORY_SCHEMA_V2: &str = "vela.repository.v2";
20pub const CURRENT_FRONTIER_PROFILE_SCHEMA_V2: &str = "vela.frontier-profile.v2";
21pub const CURRENT_ARTIFACT_RECORD_SCHEMA_V1: &str = "vela.artifact-record.v1";
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
29#[serde(deny_unknown_fields)]
30pub struct CurrentArtifactRecordV1 {
31 pub schema: String,
32 pub artifact_id: String,
33 pub artifact: Artifact,
34 pub imported_object_root: String,
35 pub predecessor_commit: String,
36}
37
38impl CurrentArtifactRecordV1 {
39 pub fn build(
40 artifact: Artifact,
41 imported_object_root: String,
42 predecessor_commit: String,
43 ) -> Result<Self, String> {
44 let value = Self {
45 schema: CURRENT_ARTIFACT_RECORD_SCHEMA_V1.into(),
46 artifact_id: artifact.id.clone(),
47 artifact,
48 imported_object_root,
49 predecessor_commit,
50 };
51 value.verify()?;
52 Ok(value)
53 }
54
55 pub fn parse(bytes: &[u8]) -> Result<Self, String> {
56 let value: Self = serde_json::from_slice(bytes)
57 .map_err(|error| format!("parse current Artifact Record v1: {error}"))?;
58 value.verify()?;
59 if value.canonical_bytes()? != bytes {
60 return Err("current Artifact Record bytes are not canonical JSON".into());
61 }
62 Ok(value)
63 }
64
65 pub fn verify(&self) -> Result<(), String> {
66 if self.schema != CURRENT_ARTIFACT_RECORD_SCHEMA_V1 {
67 return Err(format!(
68 "current Artifact Record schema must be `{CURRENT_ARTIFACT_RECORD_SCHEMA_V1}`"
69 ));
70 }
71 self.artifact.validate_reference_axes()?;
72 if self.artifact_id != self.artifact.id {
73 return Err("current Artifact Record ID does not match its descriptor".into());
74 }
75 require_sha256("artifact.imported_object_root", &self.imported_object_root)?;
76 require_git_oid("artifact.predecessor_commit", &self.predecessor_commit)?;
77 Ok(())
78 }
79
80 pub fn canonical_bytes(&self) -> Result<Vec<u8>, String> {
81 self.verify()?;
82 crate::canonical::to_canonical_bytes(self)
83 }
84
85 pub fn canonical_root(&self) -> Result<String, String> {
86 Ok(format!(
87 "sha256:{}",
88 hex::encode(Sha256::digest(self.canonical_bytes()?))
89 ))
90 }
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
100#[serde(deny_unknown_fields)]
101pub struct CurrentFrontierProfileV2 {
102 pub schema: String,
103 pub frontier_id: String,
104 pub name: String,
105 pub summary: String,
106 pub scope: FrontierProfileScopeV1,
107 pub maintainers: Vec<String>,
108 pub license: FrontierProfileLicenseV1,
109}
110
111impl CurrentFrontierProfileV2 {
112 pub fn from_yaml_str(source: &str) -> Result<Self, String> {
113 reject_yaml_indirection(source)?;
114 let value: serde_yaml::Value = serde_yaml::from_str(source).map_err(|error| {
115 format!("invalid {CURRENT_FRONTIER_PROFILE_SCHEMA_V2} YAML: {error}")
116 })?;
117 validate_yaml_structure(&value)?;
118 let profile: Self = serde_yaml::from_value(value).map_err(|error| {
119 format!("invalid {CURRENT_FRONTIER_PROFILE_SCHEMA_V2} YAML: {error}")
120 })?;
121 profile.validate()?;
122 Ok(profile)
123 }
124
125 pub fn validate(&self) -> Result<(), String> {
126 if self.schema != CURRENT_FRONTIER_PROFILE_SCHEMA_V2 {
127 return Err(format!(
128 "profile.schema must be `{CURRENT_FRONTIER_PROFILE_SCHEMA_V2}`"
129 ));
130 }
131 validate_profile_metadata(
132 &self.frontier_id,
133 &self.name,
134 &self.summary,
135 &self.scope,
136 &self.maintainers,
137 &self.license,
138 )
139 }
140
141 pub fn profile_root(&self) -> Result<String, String> {
142 self.validate()?;
143 crate::canonical::sha256_canonical(self).map(|digest| format!("sha256:{digest}"))
144 }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148#[serde(deny_unknown_fields)]
149pub struct RepositoryObjectRefV1 {
150 pub schema: String,
151 pub id: String,
152 pub root: String,
153 pub path: String,
154}
155
156#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
157#[serde(deny_unknown_fields)]
158pub struct ClaimStandingRefV1 {
159 pub claim_id: String,
160 pub claim_root: String,
161 pub standing: String,
162 pub path: String,
163}
164
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166#[serde(deny_unknown_fields)]
167pub struct CurrentRepositoryV2 {
168 pub schema: String,
169 pub frontier_id: String,
170 pub profile_root: String,
171 pub epoch_id: String,
172 pub epoch_root: String,
173 pub accepted_claims: Vec<ClaimStandingRefV1>,
174 pub pending_claims: Vec<ClaimStandingRefV1>,
175 pub proposals: Vec<RepositoryObjectRefV1>,
176 pub submissions: Vec<RepositoryObjectRefV1>,
177 pub registrations: Vec<RepositoryObjectRefV1>,
178 pub verifications: Vec<RepositoryObjectRefV1>,
179 pub artifacts: Vec<RepositoryObjectRefV1>,
180 pub authority_keyset_root: String,
181 pub authority_policy_root: String,
182}
183
184impl CurrentRepositoryV2 {
185 pub fn parse(bytes: &[u8]) -> Result<Self, String> {
186 if bytes.len() > 8 * 1024 * 1024 {
187 return Err("current repository exceeds the 8 MiB encoded limit".into());
188 }
189 let value: Self = serde_json::from_slice(bytes)
190 .map_err(|error| format!("parse current repository v2: {error}"))?;
191 value.verify()?;
192 if value.canonical_bytes()? != bytes {
193 return Err("current repository bytes are not canonical JSON".into());
194 }
195 Ok(value)
196 }
197
198 pub fn verify(&self) -> Result<(), String> {
199 if self.schema != CURRENT_REPOSITORY_SCHEMA_V2 {
200 return Err(format!(
201 "current repository schema must be `{CURRENT_REPOSITORY_SCHEMA_V2}`"
202 ));
203 }
204 require_prefixed("frontier_id", &self.frontier_id, "vfr_")?;
205 require_sha256("profile_root", &self.profile_root)?;
206 require_prefixed("epoch_id", &self.epoch_id, "vre_")?;
207 require_sha256("epoch_root", &self.epoch_root)?;
208 require_sha256("authority_keyset_root", &self.authority_keyset_root)?;
209 require_sha256("authority_policy_root", &self.authority_policy_root)?;
210
211 verify_claim_refs("accepted_claims", &self.accepted_claims, "accepted")?;
212 verify_claim_refs("pending_claims", &self.pending_claims, "pending_review")?;
213 verify_object_refs("proposals", &self.proposals)?;
214 verify_object_refs("submissions", &self.submissions)?;
215 verify_object_refs("registrations", &self.registrations)?;
216 verify_object_refs("verifications", &self.verifications)?;
217 verify_object_refs("artifacts", &self.artifacts)?;
218
219 let mut paths = BTreeSet::new();
220 for path in self
221 .accepted_claims
222 .iter()
223 .chain(&self.pending_claims)
224 .map(|reference| reference.path.as_str())
225 .chain(
226 self.proposals
227 .iter()
228 .chain(&self.submissions)
229 .chain(&self.registrations)
230 .chain(&self.verifications)
231 .chain(&self.artifacts)
232 .map(|reference| reference.path.as_str()),
233 )
234 {
235 if !paths.insert(path) {
236 return Err(format!("current repository repeats object path `{path}`"));
237 }
238 }
239 Ok(())
240 }
241
242 pub fn canonical_bytes(&self) -> Result<Vec<u8>, String> {
243 self.verify()?;
244 crate::canonical::to_canonical_bytes(self)
245 }
246
247 pub fn canonical_root(&self) -> Result<String, String> {
248 Ok(format!(
249 "sha256:{}",
250 hex::encode(Sha256::digest(self.canonical_bytes()?))
251 ))
252 }
253}
254
255fn verify_claim_refs(
256 field: &str,
257 references: &[ClaimStandingRefV1],
258 expected_standing: &str,
259) -> Result<(), String> {
260 let mut prior = None;
261 let mut roots = BTreeSet::new();
262 for reference in references {
263 require_full_claim_id(&format!("{field}.claim_id"), &reference.claim_id)?;
264 require_sha256(&format!("{field}.claim_root"), &reference.claim_root)?;
265 require_path(&format!("{field}.path"), &reference.path)?;
266 if reference.standing != expected_standing {
267 return Err(format!(
268 "current repository {field} standing must be `{expected_standing}`"
269 ));
270 }
271 if prior.is_some_and(|prior: &str| prior >= reference.claim_id.as_str()) {
272 return Err(format!(
273 "current repository {field} must be strictly sorted by Claim ID"
274 ));
275 }
276 if !roots.insert(reference.claim_root.as_str()) {
277 return Err(format!(
278 "current repository {field} repeats Claim root {}",
279 reference.claim_root
280 ));
281 }
282 prior = Some(reference.claim_id.as_str());
283 }
284 Ok(())
285}
286
287fn verify_object_refs(field: &str, references: &[RepositoryObjectRefV1]) -> Result<(), String> {
288 let mut prior = None;
289 let mut roots = BTreeSet::new();
290 for reference in references {
291 require_text(&format!("{field}.schema"), &reference.schema)?;
292 require_text(&format!("{field}.id"), &reference.id)?;
293 require_sha256(&format!("{field}.root"), &reference.root)?;
294 require_path(&format!("{field}.path"), &reference.path)?;
295 if prior.is_some_and(|prior: &str| prior >= reference.id.as_str()) {
296 return Err(format!(
297 "current repository {field} must be strictly sorted by object ID"
298 ));
299 }
300 if !roots.insert(reference.root.as_str()) {
301 return Err(format!(
302 "current repository {field} repeats object root {}",
303 reference.root
304 ));
305 }
306 prior = Some(reference.id.as_str());
307 }
308 Ok(())
309}
310
311fn require_text(field: &str, value: &str) -> Result<(), String> {
312 if value.trim().is_empty() || value != value.trim() || value.chars().any(char::is_control) {
313 return Err(format!(
314 "current repository {field} must be non-empty, trimmed text"
315 ));
316 }
317 Ok(())
318}
319
320fn require_prefixed(field: &str, value: &str, prefix: &str) -> Result<(), String> {
321 require_text(field, value)?;
322 if !value.starts_with(prefix) {
323 return Err(format!(
324 "current repository {field} must start with `{prefix}`"
325 ));
326 }
327 Ok(())
328}
329
330fn require_full_claim_id(field: &str, value: &str) -> Result<(), String> {
331 let digest = value
332 .strip_prefix("vcl_")
333 .ok_or_else(|| format!("current repository {field} must be vcl_<64 lowercase hex>"))?;
334 if digest.len() != 64 || !digest.bytes().all(is_lower_hex) {
335 return Err(format!(
336 "current repository {field} must be vcl_<64 lowercase hex>"
337 ));
338 }
339 Ok(())
340}
341
342fn require_sha256(field: &str, value: &str) -> Result<(), String> {
343 let digest = value
344 .strip_prefix("sha256:")
345 .ok_or_else(|| format!("current repository {field} must be a full sha256: digest"))?;
346 if digest.len() != 64 || !digest.bytes().all(is_lower_hex) {
347 return Err(format!(
348 "current repository {field} must be a full sha256: digest"
349 ));
350 }
351 Ok(())
352}
353
354fn require_git_oid(field: &str, value: &str) -> Result<(), String> {
355 if !matches!(value.len(), 40 | 64) || !value.bytes().all(is_lower_hex) {
356 return Err(format!(
357 "current repository {field} must be a full lowercase Git object ID"
358 ));
359 }
360 Ok(())
361}
362
363fn require_path(field: &str, value: &str) -> Result<(), String> {
364 require_text(field, value)?;
365 if value.starts_with('/')
366 || value
367 .split('/')
368 .any(|segment| segment.is_empty() || segment == "..")
369 {
370 return Err(format!(
371 "current repository {field} must be a safe relative path"
372 ));
373 }
374 Ok(())
375}
376
377fn is_lower_hex(byte: u8) -> bool {
378 byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)
379}
380
381#[cfg(test)]
382mod tests {
383 use super::*;
384
385 fn root(byte: char) -> String {
386 format!("sha256:{}", byte.to_string().repeat(64))
387 }
388
389 fn claim(byte: char, standing: &str) -> ClaimStandingRefV1 {
390 ClaimStandingRefV1 {
391 claim_id: format!("vcl_{}", byte.to_string().repeat(64)),
392 claim_root: root(byte),
393 standing: standing.into(),
394 path: format!("records/claims/sha256/{}.json", byte.to_string().repeat(64)),
395 }
396 }
397
398 fn fixture() -> CurrentRepositoryV2 {
399 CurrentRepositoryV2 {
400 schema: CURRENT_REPOSITORY_SCHEMA_V2.into(),
401 frontier_id: "vfr_0123456789abcdef".into(),
402 profile_root: root('a'),
403 epoch_id: "vre_0123456789abcdef".into(),
404 epoch_root: root('b'),
405 accepted_claims: vec![claim('c', "accepted")],
406 pending_claims: vec![claim('d', "pending_review")],
407 proposals: vec![],
408 submissions: vec![],
409 registrations: vec![],
410 verifications: vec![],
411 artifacts: vec![],
412 authority_keyset_root: root('e'),
413 authority_policy_root: root('f'),
414 }
415 }
416
417 #[test]
418 fn current_repository_is_closed_and_rooted() {
419 let repository = fixture();
420 repository.verify().unwrap();
421 assert!(repository.canonical_root().unwrap().starts_with("sha256:"));
422 let mut tampered = repository;
423 tampered.accepted_claims[0].standing = "verified".into();
424 assert!(tampered.verify().is_err());
425 }
426
427 #[test]
428 fn current_profile_is_native_closed_metadata() {
429 let current = CurrentFrontierProfileV2 {
430 schema: CURRENT_FRONTIER_PROFILE_SCHEMA_V2.into(),
431 frontier_id: "vfr_0123456789abcdef".into(),
432 name: "Example".into(),
433 summary: "A bounded example Frontier.".into(),
434 scope: FrontierProfileScopeV1 {
435 question: "What is true?".into(),
436 includes: vec!["Exact claims.".into()],
437 excludes: vec!["Unbounded claims.".into()],
438 },
439 maintainers: vec!["Example Maintainer".into()],
440 license: FrontierProfileLicenseV1 {
441 content: "CC-BY-4.0".into(),
442 code: "Apache-2.0 OR MIT".into(),
443 data: "CC0-1.0".into(),
444 },
445 };
446 let yaml = serde_yaml::to_string(¤t).unwrap();
447 let parsed = CurrentFrontierProfileV2::from_yaml_str(&yaml).unwrap();
448 assert_eq!(parsed, current);
449 assert!(current.profile_root().unwrap().starts_with("sha256:"));
450 }
451}