Skip to main content

vela_protocol/objects/
current_repository.rs

1//! Closed current-only repository manifest for Frontier Profile v2.
2//!
3//! The manifest indexes active content-addressed objects and the authority
4//! material that can change their standing. It carries no decision or
5//! acceptance power by itself; its exact root follows the signed
6//! repository-manifest delta chain.
7
8use std::collections::BTreeSet;
9
10use serde::{Deserialize, Serialize};
11use sha2::{Digest, Sha256};
12use unicode_normalization::UnicodeNormalization;
13
14pub const CURRENT_REPOSITORY_SCHEMA_V3: &str = "vela.repository.v3";
15pub const CURRENT_FRONTIER_PROFILE_SCHEMA_V2: &str = "vela.frontier-profile.v2";
16const PROFILE_NAME_MAX_BYTES: usize = 256;
17const PROFILE_SUMMARY_MAX_BYTES: usize = 2 * 1024;
18const PROFILE_QUESTION_MAX_BYTES: usize = 4 * 1024;
19const PROFILE_SCOPE_ITEM_MAX_BYTES: usize = 2 * 1024;
20const PROFILE_MAINTAINER_MAX_BYTES: usize = 256;
21const PROFILE_LICENSE_MAX_BYTES: usize = 256;
22
23#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
24#[serde(deny_unknown_fields)]
25pub struct FrontierProfileScopeV2 {
26    pub question: String,
27    pub includes: Vec<String>,
28    pub excludes: Vec<String>,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
32#[serde(deny_unknown_fields)]
33pub struct FrontierProfileLicenseV2 {
34    pub content: String,
35    pub code: String,
36    pub data: String,
37}
38
39/// Current-only repository metadata.
40///
41/// Profile v2 deliberately keeps a small, human-editable field set. Repository
42/// identity and standing come from `.vela/origin.json` and
43/// `.vela/repository.json`, never from a generated compatibility view.
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(deny_unknown_fields)]
46pub struct CurrentFrontierProfileV2 {
47    pub schema: String,
48    pub frontier_id: String,
49    pub name: String,
50    pub summary: String,
51    pub scope: FrontierProfileScopeV2,
52    pub maintainers: Vec<String>,
53    pub license: FrontierProfileLicenseV2,
54}
55
56impl CurrentFrontierProfileV2 {
57    pub fn from_yaml_str(source: &str) -> Result<Self, String> {
58        reject_yaml_indirection(source)?;
59        let value: serde_yaml::Value = serde_yaml::from_str(source).map_err(|error| {
60            format!("invalid {CURRENT_FRONTIER_PROFILE_SCHEMA_V2} YAML: {error}")
61        })?;
62        validate_yaml_structure(&value)?;
63        let profile: Self = serde_yaml::from_value(value).map_err(|error| {
64            format!("invalid {CURRENT_FRONTIER_PROFILE_SCHEMA_V2} YAML: {error}")
65        })?;
66        profile.validate()?;
67        Ok(profile)
68    }
69
70    pub fn validate(&self) -> Result<(), String> {
71        if self.schema != CURRENT_FRONTIER_PROFILE_SCHEMA_V2 {
72            return Err(format!(
73                "profile.schema must be `{CURRENT_FRONTIER_PROFILE_SCHEMA_V2}`"
74            ));
75        }
76        validate_frontier_id(&self.frontier_id)?;
77        validate_profile_text("profile.name", &self.name, PROFILE_NAME_MAX_BYTES)?;
78        validate_profile_text("profile.summary", &self.summary, PROFILE_SUMMARY_MAX_BYTES)?;
79        validate_profile_text(
80            "profile.scope.question",
81            &self.scope.question,
82            PROFILE_QUESTION_MAX_BYTES,
83        )?;
84        let includes = validate_unique_profile_text(
85            "profile.scope.includes",
86            &self.scope.includes,
87            PROFILE_SCOPE_ITEM_MAX_BYTES,
88        )?;
89        let excludes = validate_unique_profile_text(
90            "profile.scope.excludes",
91            &self.scope.excludes,
92            PROFILE_SCOPE_ITEM_MAX_BYTES,
93        )?;
94        if includes.intersection(&excludes).next().is_some() {
95            return Err(
96                "profile.scope cannot contain the same statement in includes and excludes".into(),
97            );
98        }
99        validate_unique_profile_text(
100            "profile.maintainers",
101            &self.maintainers,
102            PROFILE_MAINTAINER_MAX_BYTES,
103        )?;
104        validate_profile_text(
105            "profile.license.content",
106            &self.license.content,
107            PROFILE_LICENSE_MAX_BYTES,
108        )?;
109        validate_profile_text(
110            "profile.license.code",
111            &self.license.code,
112            PROFILE_LICENSE_MAX_BYTES,
113        )?;
114        validate_profile_text(
115            "profile.license.data",
116            &self.license.data,
117            PROFILE_LICENSE_MAX_BYTES,
118        )
119    }
120
121    pub fn profile_root(&self) -> Result<String, String> {
122        self.validate()?;
123        crate::canonical::sha256_canonical(self).map(|digest| format!("sha256:{digest}"))
124    }
125}
126
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128#[serde(deny_unknown_fields)]
129pub struct RepositoryObjectRefV1 {
130    pub schema: String,
131    pub id: String,
132    pub root: String,
133    pub path: String,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(deny_unknown_fields)]
138pub struct ClaimStandingRefV1 {
139    pub claim_id: String,
140    pub claim_root: String,
141    pub standing: String,
142    pub path: String,
143}
144
145/// Current repository manifest. Scientific and operational object sets remain
146/// explicit and content addressed behind one immutable repository origin.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148#[serde(deny_unknown_fields)]
149pub struct CurrentRepositoryV3 {
150    pub schema: String,
151    pub frontier_id: String,
152    pub profile_root: String,
153    pub origin_id: String,
154    pub origin_root: String,
155    pub accepted_claims: Vec<ClaimStandingRefV1>,
156    pub pending_claims: Vec<ClaimStandingRefV1>,
157    pub proposals: Vec<RepositoryObjectRefV1>,
158    pub submissions: Vec<RepositoryObjectRefV1>,
159    pub registrations: Vec<RepositoryObjectRefV1>,
160    pub verifications: Vec<RepositoryObjectRefV1>,
161    pub artifacts: Vec<RepositoryObjectRefV1>,
162    pub authority_keyset_root: String,
163    pub authority_policy_root: String,
164}
165
166impl CurrentRepositoryV3 {
167    pub fn parse(bytes: &[u8]) -> Result<Self, String> {
168        if bytes.len() > 8 * 1024 * 1024 {
169            return Err("current repository exceeds the 8 MiB encoded limit".into());
170        }
171        let value: Self = serde_json::from_slice(bytes)
172            .map_err(|error| format!("parse current repository v3: {error}"))?;
173        value.verify()?;
174        if value.canonical_bytes()? != bytes {
175            return Err("current repository bytes are not canonical JSON".into());
176        }
177        Ok(value)
178    }
179
180    pub fn verify(&self) -> Result<(), String> {
181        if self.schema != CURRENT_REPOSITORY_SCHEMA_V3 {
182            return Err(format!(
183                "current repository schema must be `{CURRENT_REPOSITORY_SCHEMA_V3}`"
184            ));
185        }
186        require_prefixed("frontier_id", &self.frontier_id, "vfr_")?;
187        require_sha256("profile_root", &self.profile_root)?;
188        require_prefixed("origin_id", &self.origin_id, "vro_")?;
189        require_sha256("origin_root", &self.origin_root)?;
190        require_sha256("authority_keyset_root", &self.authority_keyset_root)?;
191        require_sha256("authority_policy_root", &self.authority_policy_root)?;
192
193        verify_claim_refs("accepted_claims", &self.accepted_claims, "accepted")?;
194        verify_claim_refs("pending_claims", &self.pending_claims, "pending_review")?;
195        verify_object_refs("proposals", &self.proposals)?;
196        verify_object_refs("submissions", &self.submissions)?;
197        verify_object_refs("registrations", &self.registrations)?;
198        verify_object_refs("verifications", &self.verifications)?;
199        verify_object_refs("artifacts", &self.artifacts)?;
200
201        let mut paths = BTreeSet::new();
202        for path in self
203            .accepted_claims
204            .iter()
205            .chain(&self.pending_claims)
206            .map(|reference| reference.path.as_str())
207            .chain(
208                self.proposals
209                    .iter()
210                    .chain(&self.submissions)
211                    .chain(&self.registrations)
212                    .chain(&self.verifications)
213                    .chain(&self.artifacts)
214                    .map(|reference| reference.path.as_str()),
215            )
216        {
217            if !paths.insert(path) {
218                return Err(format!("current repository repeats object path `{path}`"));
219            }
220        }
221        Ok(())
222    }
223
224    pub fn canonical_bytes(&self) -> Result<Vec<u8>, String> {
225        self.verify()?;
226        crate::canonical::to_canonical_bytes(self)
227    }
228
229    pub fn canonical_root(&self) -> Result<String, String> {
230        Ok(format!(
231            "sha256:{}",
232            hex::encode(Sha256::digest(self.canonical_bytes()?))
233        ))
234    }
235}
236
237fn verify_claim_refs(
238    field: &str,
239    references: &[ClaimStandingRefV1],
240    expected_standing: &str,
241) -> Result<(), String> {
242    let mut prior = None;
243    let mut roots = BTreeSet::new();
244    for reference in references {
245        require_full_claim_id(&format!("{field}.claim_id"), &reference.claim_id)?;
246        require_sha256(&format!("{field}.claim_root"), &reference.claim_root)?;
247        require_path(&format!("{field}.path"), &reference.path)?;
248        if reference.standing != expected_standing {
249            return Err(format!(
250                "current repository {field} standing must be `{expected_standing}`"
251            ));
252        }
253        if prior.is_some_and(|prior: &str| prior >= reference.claim_id.as_str()) {
254            return Err(format!(
255                "current repository {field} must be strictly sorted by Claim ID"
256            ));
257        }
258        if !roots.insert(reference.claim_root.as_str()) {
259            return Err(format!(
260                "current repository {field} repeats Claim root {}",
261                reference.claim_root
262            ));
263        }
264        prior = Some(reference.claim_id.as_str());
265    }
266    Ok(())
267}
268
269fn verify_object_refs(field: &str, references: &[RepositoryObjectRefV1]) -> Result<(), String> {
270    let mut prior = None;
271    let mut roots = BTreeSet::new();
272    for reference in references {
273        require_text(&format!("{field}.schema"), &reference.schema)?;
274        require_text(&format!("{field}.id"), &reference.id)?;
275        require_sha256(&format!("{field}.root"), &reference.root)?;
276        require_path(&format!("{field}.path"), &reference.path)?;
277        if prior.is_some_and(|prior: &str| prior >= reference.id.as_str()) {
278            return Err(format!(
279                "current repository {field} must be strictly sorted by object ID"
280            ));
281        }
282        if !roots.insert(reference.root.as_str()) {
283            return Err(format!(
284                "current repository {field} repeats object root {}",
285                reference.root
286            ));
287        }
288        prior = Some(reference.id.as_str());
289    }
290    Ok(())
291}
292
293fn validate_frontier_id(value: &str) -> Result<(), String> {
294    let suffix = value
295        .strip_prefix("vfr_")
296        .ok_or_else(|| "profile.frontier_id must be vfr_<16 lowercase hex>".to_string())?;
297    if suffix.len() != 16 || !suffix.bytes().all(is_lower_hex) {
298        return Err("profile.frontier_id must be vfr_<16 lowercase hex>".into());
299    }
300    Ok(())
301}
302
303fn validate_profile_text(field: &str, value: &str, max_bytes: usize) -> Result<(), String> {
304    if value.trim().is_empty() {
305        return Err(format!("{field} must not be empty"));
306    }
307    if value.len() > max_bytes {
308        return Err(format!("{field} must be at most {max_bytes} UTF-8 bytes"));
309    }
310    if value.nfc().collect::<String>() != value {
311        return Err(format!("{field} must use Unicode NFC normalization"));
312    }
313    if value
314        .chars()
315        .any(|character| character.is_control() && character != '\n')
316    {
317        return Err(format!("{field} contains a forbidden control character"));
318    }
319    Ok(())
320}
321
322fn validate_unique_profile_text(
323    field: &str,
324    values: &[String],
325    max_item_bytes: usize,
326) -> Result<BTreeSet<String>, String> {
327    let mut observed = BTreeSet::new();
328    for (index, value) in values.iter().enumerate() {
329        validate_profile_text(&format!("{field}[{index}]"), value, max_item_bytes)?;
330        if !observed.insert(value.nfc().collect()) {
331            return Err(format!("{field} must not contain duplicate values"));
332        }
333    }
334    Ok(observed)
335}
336
337/// Reject YAML anchors, aliases, and explicit tags before Serde resolves them.
338fn reject_yaml_indirection(source: &str) -> Result<(), String> {
339    let characters = source.chars().collect::<Vec<_>>();
340    let mut index = 0;
341    let mut single_quoted = false;
342    let mut double_quoted = false;
343    let mut double_escape = false;
344    let mut comment = false;
345    while index < characters.len() {
346        let character = characters[index];
347        if comment {
348            comment = character != '\n';
349            index += 1;
350            continue;
351        }
352        if single_quoted {
353            if character == '\'' {
354                if characters.get(index + 1) == Some(&'\'') {
355                    index += 2;
356                    continue;
357                }
358                single_quoted = false;
359            }
360            index += 1;
361            continue;
362        }
363        if double_quoted {
364            if double_escape {
365                double_escape = false;
366            } else if character == '\\' {
367                double_escape = true;
368            } else if character == '"' {
369                double_quoted = false;
370            }
371            index += 1;
372            continue;
373        }
374        let previous = index
375            .checked_sub(1)
376            .and_then(|offset| characters.get(offset));
377        match character {
378            '\'' => single_quoted = true,
379            '"' => double_quoted = true,
380            '#' if previous.is_none_or(|value| value.is_whitespace()) => comment = true,
381            '&' | '*'
382                if previous.is_none_or(|value| {
383                    value.is_whitespace() || matches!(value, '-' | '[' | '{' | ',' | ':')
384                }) && characters.get(index + 1).is_some_and(|value| {
385                    !value.is_whitespace() && !matches!(value, ']' | '}' | ',' | '#')
386                }) =>
387            {
388                return Err(format!(
389                    "{CURRENT_FRONTIER_PROFILE_SCHEMA_V2} forbids YAML anchors and aliases"
390                ));
391            }
392            '!' if previous.is_none_or(|value| {
393                value.is_whitespace() || matches!(value, '-' | '[' | '{' | ',' | ':')
394            }) && characters.get(index + 1).is_some_and(|value| {
395                !value.is_whitespace() && !matches!(value, ']' | '}' | ',' | '#')
396            }) =>
397            {
398                return Err(format!(
399                    "{CURRENT_FRONTIER_PROFILE_SCHEMA_V2} forbids explicit YAML tags"
400                ));
401            }
402            _ => {}
403        }
404        index += 1;
405    }
406    Ok(())
407}
408
409fn validate_yaml_structure(value: &serde_yaml::Value) -> Result<(), String> {
410    match value {
411        serde_yaml::Value::Mapping(mapping) => {
412            for (key, value) in mapping {
413                if key.as_str() == Some("<<") {
414                    return Err(format!(
415                        "{CURRENT_FRONTIER_PROFILE_SCHEMA_V2} forbids YAML merge keys"
416                    ));
417                }
418                validate_yaml_structure(key)?;
419                validate_yaml_structure(value)?;
420            }
421        }
422        serde_yaml::Value::Sequence(sequence) => {
423            for value in sequence {
424                validate_yaml_structure(value)?;
425            }
426        }
427        serde_yaml::Value::Tagged(_) => {
428            return Err(format!(
429                "{CURRENT_FRONTIER_PROFILE_SCHEMA_V2} forbids explicit YAML tags"
430            ));
431        }
432        _ => {}
433    }
434    Ok(())
435}
436
437fn require_text(field: &str, value: &str) -> Result<(), String> {
438    if value.trim().is_empty() || value != value.trim() || value.chars().any(char::is_control) {
439        return Err(format!(
440            "current repository {field} must be non-empty, trimmed text"
441        ));
442    }
443    Ok(())
444}
445
446fn require_prefixed(field: &str, value: &str, prefix: &str) -> Result<(), String> {
447    require_text(field, value)?;
448    if !value.starts_with(prefix) {
449        return Err(format!(
450            "current repository {field} must start with `{prefix}`"
451        ));
452    }
453    Ok(())
454}
455
456fn require_full_claim_id(field: &str, value: &str) -> Result<(), String> {
457    let digest = value
458        .strip_prefix("vcl_")
459        .ok_or_else(|| format!("current repository {field} must be vcl_<64 lowercase hex>"))?;
460    if digest.len() != 64 || !digest.bytes().all(is_lower_hex) {
461        return Err(format!(
462            "current repository {field} must be vcl_<64 lowercase hex>"
463        ));
464    }
465    Ok(())
466}
467
468fn require_sha256(field: &str, value: &str) -> Result<(), String> {
469    let digest = value
470        .strip_prefix("sha256:")
471        .ok_or_else(|| format!("current repository {field} must be a full sha256: digest"))?;
472    if digest.len() != 64 || !digest.bytes().all(is_lower_hex) {
473        return Err(format!(
474            "current repository {field} must be a full sha256: digest"
475        ));
476    }
477    Ok(())
478}
479
480fn require_path(field: &str, value: &str) -> Result<(), String> {
481    require_text(field, value)?;
482    if value.starts_with('/')
483        || value
484            .split('/')
485            .any(|segment| segment.is_empty() || segment == "..")
486    {
487        return Err(format!(
488            "current repository {field} must be a safe relative path"
489        ));
490    }
491    Ok(())
492}
493
494fn is_lower_hex(byte: u8) -> bool {
495    byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)
496}
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501
502    fn root(byte: char) -> String {
503        format!("sha256:{}", byte.to_string().repeat(64))
504    }
505
506    fn claim(byte: char, standing: &str) -> ClaimStandingRefV1 {
507        ClaimStandingRefV1 {
508            claim_id: format!("vcl_{}", byte.to_string().repeat(64)),
509            claim_root: root(byte),
510            standing: standing.into(),
511            path: format!("records/claims/sha256/{}.json", byte.to_string().repeat(64)),
512        }
513    }
514
515    fn fixture() -> CurrentRepositoryV3 {
516        CurrentRepositoryV3 {
517            schema: CURRENT_REPOSITORY_SCHEMA_V3.into(),
518            frontier_id: "vfr_0123456789abcdef".into(),
519            profile_root: root('a'),
520            origin_id: "vro_0123456789abcdef".into(),
521            origin_root: root('b'),
522            accepted_claims: vec![claim('c', "accepted")],
523            pending_claims: vec![claim('d', "pending_review")],
524            proposals: vec![],
525            submissions: vec![],
526            registrations: vec![],
527            verifications: vec![],
528            artifacts: vec![],
529            authority_keyset_root: root('e'),
530            authority_policy_root: root('f'),
531        }
532    }
533
534    #[test]
535    fn current_repository_is_closed_and_rooted() {
536        let repository = fixture();
537        repository.verify().unwrap();
538        assert!(repository.canonical_root().unwrap().starts_with("sha256:"));
539        let mut tampered = repository;
540        tampered.accepted_claims[0].standing = "verified".into();
541        assert!(tampered.verify().is_err());
542    }
543
544    #[test]
545    fn current_repository_v3_binds_one_origin() {
546        let repository = fixture();
547        repository.verify().unwrap();
548        let bytes = repository.canonical_bytes().unwrap();
549        assert_eq!(CurrentRepositoryV3::parse(&bytes).unwrap(), repository);
550        let mut tampered = repository;
551        tampered.origin_id = "vre_0123456789abcdef".into();
552        assert!(tampered.verify().is_err());
553    }
554
555    #[test]
556    fn current_profile_is_native_closed_metadata() {
557        let current = CurrentFrontierProfileV2 {
558            schema: CURRENT_FRONTIER_PROFILE_SCHEMA_V2.into(),
559            frontier_id: "vfr_0123456789abcdef".into(),
560            name: "Example".into(),
561            summary: "A bounded example Frontier.".into(),
562            scope: FrontierProfileScopeV2 {
563                question: "What is true?".into(),
564                includes: vec!["Exact claims.".into()],
565                excludes: vec!["Unbounded claims.".into()],
566            },
567            maintainers: vec!["Example Maintainer".into()],
568            license: FrontierProfileLicenseV2 {
569                content: "CC-BY-4.0".into(),
570                code: "Apache-2.0 OR MIT".into(),
571                data: "CC0-1.0".into(),
572            },
573        };
574        let yaml = serde_yaml::to_string(&current).unwrap();
575        let parsed = CurrentFrontierProfileV2::from_yaml_str(&yaml).unwrap();
576        assert_eq!(parsed, current);
577        assert!(current.profile_root().unwrap().starts_with("sha256:"));
578    }
579}