Skip to main content

vela_protocol/objects/
proposal_v1.rs

1//! Current candidate transition: `vela.proposal.v1`.
2
3use serde::{Deserialize, Serialize};
4use sha2::{Digest, Sha256};
5
6pub const PROPOSAL_V1_SCHEMA: &str = "vela.proposal.v1";
7
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(deny_unknown_fields)]
10pub struct ProposalSubject {
11    pub kind: String,
12    pub id: String,
13    pub root: String,
14}
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(deny_unknown_fields)]
18pub struct ProposalProducerPackage {
19    pub kind: String,
20    pub id: String,
21    pub root: String,
22    pub path: String,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(deny_unknown_fields)]
27pub struct ImportedProposalSource {
28    pub proposal_id: String,
29    pub proposal_root: String,
30    pub predecessor_commit: String,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(deny_unknown_fields)]
35pub struct ProposalV1 {
36    pub schema: String,
37    pub proposal_id: String,
38    pub action: String,
39    pub subject: ProposalSubject,
40    pub actor: String,
41    pub created_at: String,
42    pub reason: String,
43    pub producer_package: ProposalProducerPackage,
44    pub caveats: Vec<String>,
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub imported_from: Option<ImportedProposalSource>,
47}
48
49impl ProposalV1 {
50    #[allow(clippy::too_many_arguments)]
51    pub fn build(
52        action: String,
53        subject: ProposalSubject,
54        actor: String,
55        created_at: String,
56        reason: String,
57        producer_package: ProposalProducerPackage,
58        caveats: Vec<String>,
59        imported_from: Option<ImportedProposalSource>,
60    ) -> Result<Self, String> {
61        let mut value = Self {
62            schema: PROPOSAL_V1_SCHEMA.to_string(),
63            proposal_id: String::new(),
64            action,
65            subject,
66            actor,
67            created_at,
68            reason,
69            producer_package,
70            caveats,
71            imported_from,
72        };
73        value.validate_semantics()?;
74        value.proposal_id = value.derive_id()?;
75        value.verify()?;
76        Ok(value)
77    }
78
79    pub fn parse(bytes: &[u8]) -> Result<Self, String> {
80        if bytes.len() > 2 * 1024 * 1024 {
81            return Err("Proposal exceeds the 2 MiB encoded limit".into());
82        }
83        let value: Self =
84            serde_json::from_slice(bytes).map_err(|error| format!("parse Proposal v1: {error}"))?;
85        value.verify()?;
86        Ok(value)
87    }
88
89    pub fn verify(&self) -> Result<(), String> {
90        self.validate_semantics()?;
91        let expected = self.derive_id()?;
92        if self.proposal_id != expected {
93            return Err(format!(
94                "Proposal id mismatch: declared {}, rebuilt {expected}",
95                self.proposal_id
96            ));
97        }
98        Ok(())
99    }
100
101    pub fn canonical_bytes(&self) -> Result<Vec<u8>, String> {
102        crate::canonical::to_canonical_bytes(self)
103    }
104
105    pub fn canonical_root(&self) -> Result<String, String> {
106        Ok(format!(
107            "sha256:{}",
108            hex::encode(Sha256::digest(self.canonical_bytes()?))
109        ))
110    }
111
112    fn derive_id(&self) -> Result<String, String> {
113        let mut body = self.clone();
114        body.proposal_id.clear();
115        let bytes = crate::canonical::to_canonical_bytes(&body)?;
116        Ok(format!("vpr_{}", &hex::encode(Sha256::digest(bytes))[..16]))
117    }
118
119    fn validate_semantics(&self) -> Result<(), String> {
120        if self.schema != PROPOSAL_V1_SCHEMA {
121            return Err(format!("Proposal schema must be `{PROPOSAL_V1_SCHEMA}`"));
122        }
123        if !["claim.add", "claim.revise", "claim.withdraw"].contains(&self.action.as_str()) {
124            return Err("Proposal action is not a current transition".into());
125        }
126        if self.subject.kind != "claim" {
127            return Err("Proposal subject.kind must be `claim`".into());
128        }
129        require_prefixed("subject.id", &self.subject.id, "vcl_")?;
130        require_sha256("subject.root", &self.subject.root)?;
131        require_text("actor", &self.actor)?;
132        chrono::DateTime::parse_from_rfc3339(&self.created_at)
133            .map_err(|_| "Proposal created_at must be RFC 3339".to_string())?;
134        require_text("reason", &self.reason)?;
135        if self.producer_package.kind != "submission_v1" {
136            return Err("Proposal producer_package.kind must be `submission_v1`".into());
137        }
138        require_prefixed("producer_package.id", &self.producer_package.id, "vsb_")?;
139        require_sha256("producer_package.root", &self.producer_package.root)?;
140        require_relative_path("producer_package.path", &self.producer_package.path)?;
141        for caveat in &self.caveats {
142            require_text("caveats", caveat)?;
143        }
144        if let Some(source) = &self.imported_from {
145            require_prefixed("imported_from.proposal_id", &source.proposal_id, "vpr_")?;
146            require_sha256("imported_from.proposal_root", &source.proposal_root)?;
147            require_git_oid(
148                "imported_from.predecessor_commit",
149                &source.predecessor_commit,
150            )?;
151        }
152        Ok(())
153    }
154}
155
156fn require_text(field: &str, value: &str) -> Result<(), String> {
157    if value.trim().is_empty() || value != value.trim() || value.chars().any(char::is_control) {
158        return Err(format!("Proposal {field} must be non-empty, trimmed text"));
159    }
160    Ok(())
161}
162
163fn require_prefixed(field: &str, value: &str, prefix: &str) -> Result<(), String> {
164    require_text(field, value)?;
165    if !value.starts_with(prefix) {
166        return Err(format!("Proposal {field} must start with {prefix}"));
167    }
168    Ok(())
169}
170
171fn require_sha256(field: &str, value: &str) -> Result<(), String> {
172    let digest = value
173        .strip_prefix("sha256:")
174        .ok_or_else(|| format!("Proposal {field} must be a full sha256: digest"))?;
175    if digest.len() != 64
176        || !digest
177            .bytes()
178            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
179    {
180        return Err(format!("Proposal {field} must be a full sha256: digest"));
181    }
182    Ok(())
183}
184
185fn require_git_oid(field: &str, value: &str) -> Result<(), String> {
186    if !matches!(value.len(), 40 | 64)
187        || !value
188            .bytes()
189            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
190    {
191        return Err(format!("Proposal {field} must be a full Git object id"));
192    }
193    Ok(())
194}
195
196fn require_relative_path(field: &str, value: &str) -> Result<(), String> {
197    require_text(field, value)?;
198    if value.starts_with('/') || value.split('/').any(|segment| segment == "..") {
199        return Err(format!("Proposal {field} must be a safe relative path"));
200    }
201    Ok(())
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    fn root(byte: char) -> String {
209        format!("sha256:{}", byte.to_string().repeat(64))
210    }
211
212    #[test]
213    fn proposal_v1_requires_a_current_submission_and_claim() {
214        let value = ProposalV1::build(
215            "claim.add".into(),
216            ProposalSubject {
217                kind: "claim".into(),
218                id: "vcl_fixture".into(),
219                root: root('a'),
220            },
221            "agent:producer".into(),
222            "2026-07-27T00:00:00Z".into(),
223            "Submit bounded evidence for review.".into(),
224            ProposalProducerPackage {
225                kind: "submission_v1".into(),
226                id: "vsb_fixture".into(),
227                root: root('b'),
228                path: format!("records/submissions/sha256/{}.json", "b".repeat(64)),
229            },
230            vec!["Bounded result only.".into()],
231            Some(ImportedProposalSource {
232                proposal_id: "vpr_legacy".into(),
233                proposal_root: root('c'),
234                predecessor_commit: "d".repeat(40),
235            }),
236        )
237        .unwrap();
238        assert!(value.proposal_id.starts_with("vpr_"));
239        ProposalV1::parse(&value.canonical_bytes().unwrap()).unwrap();
240    }
241
242    #[test]
243    fn receipt_backed_proposal_is_not_current() {
244        let error = ProposalV1::build(
245            "claim.add".into(),
246            ProposalSubject {
247                kind: "claim".into(),
248                id: "vcl_fixture".into(),
249                root: root('a'),
250            },
251            "agent:producer".into(),
252            "2026-07-27T00:00:00Z".into(),
253            "Request".into(),
254            ProposalProducerPackage {
255                kind: "receipt_v1".into(),
256                id: "vrc_fixture".into(),
257                root: root('b'),
258                path: "records/receipts/sha256/fixture.json".into(),
259            },
260            vec![],
261            None,
262        )
263        .unwrap_err();
264        assert!(error.contains("submission_v1"));
265    }
266}