Skip to main content

vela_protocol/objects/
verification_record.rs

1//! Scoped verifier output: `vela.verification-record.v1`.
2//!
3//! Verification is an authenticated observation over exact inputs. Even a
4//! passing record changes no Claim Standing without a separate authorized
5//! Decision and canonical Event.
6
7use ed25519_dalek::SigningKey;
8use serde::{Deserialize, Serialize};
9use sha2::{Digest, Sha256};
10
11use crate::identity::IdentityBinding;
12
13pub const VERIFICATION_RECORD_V1_SCHEMA: &str = "vela.verification-record.v1";
14pub const VERIFICATION_RECORD_AUTH_ALGORITHM: &str = "ed25519";
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(deny_unknown_fields)]
18pub struct VerificationSubject {
19    pub claim_id: String,
20    pub artifact_ids: Vec<String>,
21    pub submission_id: String,
22    pub submission_root: String,
23    pub proposal_id: String,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(deny_unknown_fields)]
28pub struct VerificationMethod {
29    pub profile: String,
30    pub implementation: String,
31    pub environment_root: String,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(deny_unknown_fields)]
36pub struct VerificationScope {
37    pub property: String,
38    pub does_not_establish: Vec<String>,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(deny_unknown_fields)]
43pub struct IndependenceDisclosure {
44    pub declared_independent_of: Vec<String>,
45    pub shared_dependencies: Vec<String>,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct VerificationAuthentication {
51    pub algorithm: String,
52    pub identity_binding: IdentityBinding,
53    pub signature: String,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct VerificationRecordV1 {
59    pub schema: String,
60    pub verification_record_id: String,
61    pub subject: VerificationSubject,
62    pub method: VerificationMethod,
63    pub scope: VerificationScope,
64    pub outcome: String,
65    pub verifier: String,
66    pub independence: IndependenceDisclosure,
67    pub output_artifact_ids: Vec<String>,
68    pub started_at: String,
69    pub completed_at: String,
70    pub authentication: VerificationAuthentication,
71}
72
73#[derive(Debug, Clone)]
74pub struct VerificationRecordDraft {
75    pub subject: VerificationSubject,
76    pub method: VerificationMethod,
77    pub scope: VerificationScope,
78    pub outcome: String,
79    pub verifier: String,
80    pub independence: IndependenceDisclosure,
81    pub output_artifact_ids: Vec<String>,
82    pub started_at: String,
83    pub completed_at: String,
84}
85
86impl VerificationRecordV1 {
87    pub fn build(
88        draft: VerificationRecordDraft,
89        identity_binding: IdentityBinding,
90        key: &SigningKey,
91    ) -> Result<Self, String> {
92        identity_binding.verify()?;
93        if identity_binding.actor_id != draft.verifier {
94            return Err("Verification Record verifier must match its identity binding".into());
95        }
96        if identity_binding.public_key_hex != hex::encode(key.verifying_key().to_bytes()) {
97            return Err(
98                "Verification Record signing key does not match its identity binding".into(),
99            );
100        }
101        let mut value = Self {
102            schema: VERIFICATION_RECORD_V1_SCHEMA.to_string(),
103            verification_record_id: String::new(),
104            subject: draft.subject,
105            method: draft.method,
106            scope: draft.scope,
107            outcome: draft.outcome,
108            verifier: draft.verifier,
109            independence: draft.independence,
110            output_artifact_ids: draft.output_artifact_ids,
111            started_at: draft.started_at,
112            completed_at: draft.completed_at,
113            authentication: VerificationAuthentication {
114                algorithm: VERIFICATION_RECORD_AUTH_ALGORITHM.to_string(),
115                identity_binding,
116                signature: String::new(),
117            },
118        };
119        value.validate_semantics()?;
120        let preimage = value.signed_preimage()?;
121        value.authentication.signature = hex::encode(crate::sign::sign_bytes(key, &preimage));
122        value.verification_record_id = value.derive_id()?;
123        value.verify()?;
124        Ok(value)
125    }
126
127    pub fn parse(bytes: &[u8]) -> Result<Self, String> {
128        if bytes.len() > 4 * 1024 * 1024 {
129            return Err("Verification Record exceeds the 4 MiB encoded limit".into());
130        }
131        let value: Self = serde_json::from_slice(bytes)
132            .map_err(|error| format!("parse Verification Record v1: {error}"))?;
133        value.verify()?;
134        Ok(value)
135    }
136
137    pub fn verify(&self) -> Result<(), String> {
138        self.validate_semantics()?;
139        self.authentication.identity_binding.verify()?;
140        if self.authentication.identity_binding.actor_id != self.verifier {
141            return Err("Verification Record authentication does not bind its verifier".into());
142        }
143        let preimage = self.signed_preimage()?;
144        if !crate::sign::verify_action_signature(
145            &preimage,
146            &self.authentication.signature,
147            &self.authentication.identity_binding.public_key_hex,
148        )? {
149            return Err("Verification Record whole-body signature does not verify".into());
150        }
151        let expected = self.derive_id()?;
152        if expected != self.verification_record_id {
153            return Err(format!(
154                "Verification Record id mismatch: declared {}, rebuilt {expected}",
155                self.verification_record_id
156            ));
157        }
158        Ok(())
159    }
160
161    pub fn canonical_bytes(&self) -> Result<Vec<u8>, String> {
162        crate::canonical::to_canonical_bytes(self)
163    }
164
165    pub fn canonical_root(&self) -> Result<String, String> {
166        Ok(format!(
167            "sha256:{}",
168            hex::encode(Sha256::digest(self.canonical_bytes()?))
169        ))
170    }
171
172    fn signed_preimage(&self) -> Result<Vec<u8>, String> {
173        let mut unsigned = self.clone();
174        unsigned.verification_record_id.clear();
175        unsigned.authentication.signature.clear();
176        crate::canonical::to_canonical_bytes(&unsigned)
177    }
178
179    fn derive_id(&self) -> Result<String, String> {
180        Ok(format!(
181            "vvr_{}",
182            &hex::encode(Sha256::digest(self.signed_preimage()?))[..16]
183        ))
184    }
185
186    fn validate_semantics(&self) -> Result<(), String> {
187        if self.schema != VERIFICATION_RECORD_V1_SCHEMA {
188            return Err(format!(
189                "Verification Record schema must be `{VERIFICATION_RECORD_V1_SCHEMA}`"
190            ));
191        }
192        if self.authentication.algorithm != VERIFICATION_RECORD_AUTH_ALGORITHM {
193            return Err("Verification Record authentication.algorithm must be `ed25519`".into());
194        }
195        if !(self.subject.claim_id.starts_with("vcl_") || self.subject.claim_id.starts_with("vf_"))
196        {
197            return Err(
198                "Verification Record subject.claim_id must be vcl_ or historical vf_".into(),
199            );
200        }
201        require_prefixed("subject.submission_id", &self.subject.submission_id, "vsb_")?;
202        require_sha256("subject.submission_root", &self.subject.submission_root)?;
203        require_prefixed("subject.proposal_id", &self.subject.proposal_id, "vpr_")?;
204        for artifact_id in self
205            .subject
206            .artifact_ids
207            .iter()
208            .chain(self.output_artifact_ids.iter())
209        {
210            require_prefixed("artifact id", artifact_id, "va_")?;
211        }
212        require_text("method.profile", &self.method.profile)?;
213        require_text("method.implementation", &self.method.implementation)?;
214        require_sha256("method.environment_root", &self.method.environment_root)?;
215        require_text("scope.property", &self.scope.property)?;
216        if self.scope.does_not_establish.is_empty() {
217            return Err(
218                "Verification Record scope must state at least one limitation or explicit nonclaim"
219                    .into(),
220            );
221        }
222        for limitation in &self.scope.does_not_establish {
223            require_text("scope.does_not_establish", limitation)?;
224        }
225        if !["pass", "fail", "error", "inconclusive"].contains(&self.outcome.as_str()) {
226            return Err(
227                "Verification Record outcome must be pass, fail, error, or inconclusive".into(),
228            );
229        }
230        require_text("verifier", &self.verifier)?;
231        for actor in &self.independence.declared_independent_of {
232            require_text("independence.declared_independent_of", actor)?;
233            if actor == &self.verifier {
234                return Err("Verification Record cannot claim independence from itself".into());
235            }
236        }
237        for dependency in &self.independence.shared_dependencies {
238            require_text("independence.shared_dependencies", dependency)?;
239        }
240        let started = chrono::DateTime::parse_from_rfc3339(&self.started_at)
241            .map_err(|_| "Verification Record started_at must be RFC 3339".to_string())?;
242        let completed = chrono::DateTime::parse_from_rfc3339(&self.completed_at)
243            .map_err(|_| "Verification Record completed_at must be RFC 3339".to_string())?;
244        if completed < started {
245            return Err("Verification Record completed_at precedes started_at".into());
246        }
247        Ok(())
248    }
249}
250
251fn require_text(field: &str, value: &str) -> Result<(), String> {
252    if value.trim().is_empty() || value != value.trim() || value.chars().any(char::is_control) {
253        return Err(format!(
254            "Verification Record {field} must be non-empty, trimmed text"
255        ));
256    }
257    if value.len() > 16 * 1024 {
258        return Err(format!("Verification Record {field} exceeds 16 KiB"));
259    }
260    Ok(())
261}
262
263fn require_prefixed(field: &str, value: &str, prefix: &str) -> Result<(), String> {
264    require_text(field, value)?;
265    if !value.starts_with(prefix) {
266        return Err(format!(
267            "Verification Record {field} must start with {prefix}"
268        ));
269    }
270    Ok(())
271}
272
273fn require_sha256(field: &str, value: &str) -> Result<(), String> {
274    let digest = value
275        .strip_prefix("sha256:")
276        .ok_or_else(|| format!("Verification Record {field} must be a full sha256: digest"))?;
277    if digest.len() != 64
278        || !digest
279            .bytes()
280            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
281    {
282        return Err(format!(
283            "Verification Record {field} must be a full sha256: digest"
284        ));
285    }
286    Ok(())
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292    use crate::identity::{ActorClass, IdentityBindingDraft};
293    use rand::rngs::OsRng;
294
295    fn root(byte: char) -> String {
296        format!("sha256:{}", byte.to_string().repeat(64))
297    }
298
299    fn fixture() -> (VerificationRecordDraft, IdentityBinding, SigningKey) {
300        let key = SigningKey::generate(&mut OsRng);
301        let identity = IdentityBinding::build(
302            IdentityBindingDraft {
303                actor_id: "service:fixture-verifier".into(),
304                actor_class: ActorClass::Org,
305                created_at: "2026-07-26T00:00:00Z".into(),
306            },
307            &key,
308        )
309        .unwrap();
310        let draft = VerificationRecordDraft {
311            subject: VerificationSubject {
312                claim_id: "vf_fixture".into(),
313                artifact_ids: vec!["va_input".into()],
314                submission_id: "vsb_fixture".into(),
315                submission_root: root('a'),
316                proposal_id: "vpr_fixture".into(),
317            },
318            method: VerificationMethod {
319                profile: "fixture-v1".into(),
320                implementation: "oci://fixture@sha256:abc".into(),
321                environment_root: root('b'),
322            },
323            scope: VerificationScope {
324                property: "The witness satisfies the bounded condition.".into(),
325                does_not_establish: vec!["Scientific acceptance.".into()],
326            },
327            outcome: "pass".into(),
328            verifier: "service:fixture-verifier".into(),
329            independence: IndependenceDisclosure {
330                declared_independent_of: vec!["agent:fixture".into()],
331                shared_dependencies: vec!["problem specification v1".into()],
332            },
333            output_artifact_ids: vec!["va_log".into()],
334            started_at: "2026-07-26T00:00:00Z".into(),
335            completed_at: "2026-07-26T00:00:01Z".into(),
336        };
337        (draft, identity, key)
338    }
339
340    #[test]
341    fn verification_record_is_signed_and_changes_no_standing() {
342        let (draft, identity, key) = fixture();
343        let record = VerificationRecordV1::build(draft, identity, &key).unwrap();
344        assert!(record.verification_record_id.starts_with("vvr_"));
345        VerificationRecordV1::parse(&record.canonical_bytes().unwrap()).unwrap();
346        let value = serde_json::to_value(&record).unwrap();
347        assert!(value.get("standing").is_none());
348        assert!(value.get("accepted").is_none());
349    }
350
351    #[test]
352    fn subject_drift_breaks_whole_body_signature() {
353        let (draft, identity, key) = fixture();
354        let mut record = VerificationRecordV1::build(draft, identity, &key).unwrap();
355        record.subject.submission_root = root('c');
356        assert!(record.verify().is_err());
357    }
358}