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