Skip to main content

vela_protocol/kernel/
sign.rs

1//! Ed25519 signing for the event log — the trust infrastructure layer.
2//!
3//! The signed EVENT log is the sole signing authority: a registered human
4//! actor's events carry a verifiable signature, and `verify_event_signature`
5//! checks them against the registered pubkey. The legacy per-finding signature
6//! lane (the v0.37 multi-sig `SignedEnvelope` / threshold machinery) was retired
7//! — `SignedEnvelope` and `Project.signatures` survive only so historical
8//! frontiers that still carry envelopes deserialize and replay unchanged. They
9//! are vestigial data (hash-neutral): nothing creates, verifies, or gates on
10//! them.
11
12use std::path::Path;
13
14use ed25519_dalek::{Signer, SigningKey, Verifier, VerifyingKey};
15use serde::{Deserialize, Serialize};
16
17/// A signed envelope wrapping a finding's cryptographic signature.
18///
19/// Vestigial: retained so historical `Project.signatures` deserialize. The
20/// finding-signature lane is retired; no code path produces or verifies these.
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct SignedEnvelope {
23    pub finding_id: String,
24    /// Hex-encoded Ed25519 signature (128 hex chars = 64 bytes).
25    pub signature: String,
26    /// Hex-encoded public key of the signer (64 hex chars = 32 bytes).
27    pub public_key: String,
28    /// ISO 8601 timestamp of when the signature was produced.
29    pub signed_at: String,
30    /// Algorithm identifier (always "ed25519").
31    pub algorithm: String,
32}
33
34/// Phase M (v0.4): registered actor identity. Maps a stable `actor.id`
35/// to an Ed25519 public key, established at a specific timestamp.
36///
37/// Once an actor is registered in a frontier, any canonical event
38/// whose `actor.id` matches must carry a verifiable signature under
39/// `--strict`. Frontiers without registered actors retain the legacy
40/// "placeholder reviewer" rejection from v0.3 only.
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
42pub struct ActorRecord {
43    /// Stable, namespaced identifier (e.g. "reviewer:human-reviewer").
44    pub id: String,
45    /// Hex-encoded Ed25519 public key (64 hex chars = 32 bytes).
46    pub public_key: String,
47    /// Algorithm identifier (always "ed25519").
48    #[serde(default = "default_algorithm")]
49    pub algorithm: String,
50    /// ISO 8601 timestamp of when the actor was registered.
51    pub created_at: String,
52    /// Historical actor-tier metadata retained only so immutable records
53    /// continue to decode. Current constructors emit `None`; this field grants
54    /// no write or decision authority.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub tier: Option<String>,
57    /// v0.43: Optional ORCID identifier for cross-system identity.
58    /// Format: `0000-0000-0000-000X` (16 digits in 4 groups, final
59    /// character optionally `X` per ISO 7064). When set, the actor's
60    /// identity can be cross-referenced through the public ORCID
61    /// directory at `https://orcid.org/<orcid>`. The substrate stores
62    /// the pointer; it does not verify the ORCID exists online (that
63    /// is L4 work). Pre-v0.43 actors load with `None` and behave
64    /// exactly as before.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub orcid: Option<String>,
67    /// v0.51: Read-side access clearance. `None` (default) means
68    /// public-only access. `Some(Restricted)` permits reading
69    /// `Public` and `Restricted` tiered objects; `Some(Classified)`
70    /// permits all. Unlike the historical `tier` field above, this is active
71    /// read-side policy; it never grants write or decision authority.
72    /// Pre-v0.51 actors load with `None` and behave
73    /// exactly as before — the field is purely additive.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub access_clearance: Option<crate::access_tier::AccessTier>,
76    /// v0.127: revocation timestamp. When set, the actor's key is
77    /// considered compromised or retired as of that moment.
78    /// Signatures on events with `timestamp < revoked_at` remain
79    /// valid (the key was trusted when the event was signed); new
80    /// signatures on events with `timestamp >= revoked_at` are
81    /// rejected by `verify_event_signature`. Pre-v0.127 actors load
82    /// with `None` and verify exactly as before.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub revoked_at: Option<String>,
85    /// v0.127: free-form reason for revocation (e.g. "key
86    /// compromised 2026-05-10", "rotated to reviewer:human-reviewer-v2").
87    /// Display-only; the substrate does not parse this field.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub revoked_reason: Option<String>,
90}
91
92impl ActorRecord {
93    /// v0.127: true iff the actor's key is revoked relative to an
94    /// event timestamp. An event signed before `revoked_at` remains
95    /// valid (the substrate does not retroactively invalidate
96    /// historical signatures); an event signed at-or-after the
97    /// revocation is rejected. Both timestamps are parsed as RFC 3339
98    /// instants so equivalent offsets compare correctly. Invalid
99    /// timestamps fail closed and are treated as revoked.
100    pub fn is_revoked_at(&self, event_timestamp: &str) -> bool {
101        let Ok(event_time) = chrono::DateTime::parse_from_rfc3339(event_timestamp) else {
102            return true;
103        };
104        let Some(revoked_at) = self.revoked_at.as_deref() else {
105            return false;
106        };
107        let Ok(revoked_time) = chrono::DateTime::parse_from_rfc3339(revoked_at) else {
108            return true;
109        };
110        event_time >= revoked_time
111    }
112}
113
114/// v0.43: Validate an ORCID identifier's structural shape. ORCID IDs
115/// are 16 digits in 4 groups of 4 separated by hyphens, with the
116/// final character optionally being `X` (the ISO 7064 check digit).
117/// Accepts bare form `0000-0001-2345-6789`, the URL form
118/// `https://orcid.org/0000-...`, or the prefixed form `orcid:0000-...`
119/// and returns the bare form.
120pub fn validate_orcid(s: &str) -> Result<String, String> {
121    let trimmed = s.trim();
122    let bare = trimmed
123        .strip_prefix("https://orcid.org/")
124        .or_else(|| trimmed.strip_prefix("http://orcid.org/"))
125        .or_else(|| trimmed.strip_prefix("orcid:"))
126        .unwrap_or(trimmed);
127    if bare.len() != 19 {
128        return Err(format!(
129            "ORCID must be 19 chars (0000-0000-0000-000X), got {}",
130            bare.len()
131        ));
132    }
133    let mut groups = bare.split('-');
134    for i in 0..4 {
135        let g = groups
136            .next()
137            .ok_or_else(|| format!("ORCID missing group {} of 4", i + 1))?;
138        if g.len() != 4 {
139            return Err(format!(
140                "ORCID group {} must be 4 chars, got {}",
141                i + 1,
142                g.len()
143            ));
144        }
145        for (j, c) in g.chars().enumerate() {
146            let allow_x = i == 3 && j == 3;
147            if !c.is_ascii_digit() && !(allow_x && c == 'X') {
148                return Err(format!(
149                    "ORCID character '{c}' at group {} pos {} not a digit (or X check digit)",
150                    i + 1,
151                    j + 1
152                ));
153            }
154        }
155    }
156    if groups.next().is_some() {
157        return Err("ORCID has too many hyphenated groups".to_string());
158    }
159    Ok(bare.to_string())
160}
161
162fn default_algorithm() -> String {
163    "ed25519".to_string()
164}
165
166// ── Key generation ───────────────────────────────────────────────────
167
168/// Generate an Ed25519 keypair. Writes the private key to `output_dir/private.key`
169/// and the public key to `output_dir/public.key`. Both are hex-encoded.
170pub fn generate_keypair(output_dir: &Path) -> Result<String, String> {
171    use rand::rngs::OsRng;
172
173    std::fs::create_dir_all(output_dir)
174        .map_err(|e| format!("Failed to create output directory: {e}"))?;
175
176    let signing_key = SigningKey::generate(&mut OsRng);
177    let verifying_key = signing_key.verifying_key();
178
179    let private_hex = hex::encode(signing_key.to_bytes());
180    let public_hex = hex::encode(verifying_key.to_bytes());
181
182    let private_path = output_dir.join("private.key");
183    let public_path = output_dir.join("public.key");
184
185    std::fs::write(&private_path, &private_hex)
186        .map_err(|e| format!("Failed to write private key: {e}"))?;
187    // The private key is a plaintext seed; make it owner-read-only so a
188    // stray backup or shared machine cannot leak the signing authority.
189    // Best-effort and Unix-only (Windows ACLs are a separate concern).
190    harden_key_permissions(&private_path);
191    std::fs::write(&public_path, &public_hex)
192        .map_err(|e| format!("Failed to write public key: {e}"))?;
193
194    Ok(public_hex)
195}
196
197/// Set 0600 on a private-key file where the platform supports it. Best
198/// effort: a failure to tighten permissions must not fail key generation,
199/// but the common case (Unix) gets a private key that is not world- or
200/// group-readable.
201pub fn harden_key_permissions(path: &Path) {
202    #[cfg(unix)]
203    {
204        use std::os::unix::fs::PermissionsExt;
205        if let Ok(meta) = std::fs::metadata(path) {
206            let mut perms = meta.permissions();
207            perms.set_mode(0o600);
208            let _ = std::fs::set_permissions(path, perms);
209        }
210    }
211    #[cfg(not(unix))]
212    {
213        let _ = path;
214    }
215}
216
217// ── Signing and verification ─────────────────────────────────────────
218
219/// Parse a hex-encoded Ed25519 signing key (64 hex chars = the 32-byte seed).
220/// The inline form of [`load_signing_key_from_path`], for callers that hold the
221/// key as a string rather than a file — e.g. a deployment secret delivered as
222/// an environment variable (Fly/Heroku/K8s), where there is no key file to
223/// point a path at.
224pub fn signing_key_from_hex(hex_str: &str) -> Result<SigningKey, String> {
225    let bytes =
226        hex::decode(hex_str.trim()).map_err(|e| format!("Invalid hex in private key: {e}"))?;
227    let key_bytes: [u8; 32] = bytes
228        .try_into()
229        .map_err(|_| "Private key must be exactly 32 bytes".to_string())?;
230    Ok(SigningKey::from_bytes(&key_bytes))
231}
232
233/// Load a signing key from a hex-encoded file.
234fn load_signing_key(path: &Path) -> Result<SigningKey, String> {
235    let hex_str =
236        std::fs::read_to_string(path).map_err(|e| format!("Failed to read private key: {e}"))?;
237    signing_key_from_hex(&hex_str)
238}
239
240/// v0.49.3: public key-loading and primitive-signing helpers so the
241/// hub (and any other downstream binary) can sign small JSON payloads
242/// — e.g., the `/.well-known/vela` manifest — without needing direct
243/// access to the ed25519_dalek dep or to the SigningKey type.
244
245/// Load a hex-encoded Ed25519 signing key from disk.
246///
247/// Same on-disk format `vela sign generate-keypair` writes.
248pub fn load_signing_key_from_path(path: &Path) -> Result<SigningKey, String> {
249    load_signing_key(path)
250}
251
252/// Sign arbitrary bytes with the given key. Returns the 64-byte
253/// signature.
254pub fn sign_bytes(signing_key: &SigningKey, bytes: &[u8]) -> [u8; 64] {
255    signing_key.sign(bytes).to_bytes()
256}
257
258/// Hex-encoded Ed25519 public key (64 chars) for the given signing key.
259pub fn pubkey_hex(signing_key: &SigningKey) -> String {
260    hex::encode(signing_key.verifying_key().to_bytes())
261}
262
263/// Parse a verifying key from a hex string.
264fn parse_verifying_key(hex_str: &str) -> Result<VerifyingKey, String> {
265    let bytes = hex::decode(hex_str).map_err(|e| format!("Invalid hex in public key: {e}"))?;
266    let key_bytes: [u8; 32] = bytes
267        .try_into()
268        .map_err(|_| "Public key must be exactly 32 bytes".to_string())?;
269    VerifyingKey::from_bytes(&key_bytes).map_err(|e| format!("Invalid public key: {e}"))
270}
271
272// ── Event signing (Phase M, v0.4) ────────────────────────────────────
273
274/// Compute the canonical signing bytes for a `StateEvent`. The `signature`
275/// field is excluded from the preimage (you can't sign over your own
276/// signature). The same canonical-JSON rule that derives `vev_…` is reused.
277///
278/// A second implementation must produce byte-identical signing bytes
279/// for the same event content; the verification rule depends on it.
280pub fn event_signing_bytes(
281    event: &crate::events::StateEvent,
282    version: crate::signing_input::SigVersion,
283) -> Result<Vec<u8>, String> {
284    use serde_json::json;
285    let preimage = json!({
286        "schema": event.schema,
287        "id": event.id,
288        "kind": event.kind,
289        "target": event.target,
290        "actor": event.actor,
291        "timestamp": event.timestamp,
292        "reason": event.reason,
293        "before_hash": event.before_hash,
294        "after_hash": event.after_hash,
295        "payload": event.payload,
296        "caveats": event.caveats,
297    });
298    let body = crate::canonical::to_canonical_bytes(&preimage)?;
299    Ok(crate::signing_input::signing_input(
300        version,
301        crate::signing_input::payload_type::EVENT,
302        &body,
303    ))
304}
305
306/// Sign a canonical event with an Ed25519 private key, returning a signature
307/// suitable for `event.signature`. New signatures are v1 (DSSE/PAE), carried as
308/// a `v1:` prefix on the signature string so historical bare-hex signatures read
309/// as v0. The prefix is not part of the event id or the (content-only)
310/// event_log_hash, so the flip is transparent to addressing.
311pub fn sign_event(
312    event: &crate::events::StateEvent,
313    signing_key: &SigningKey,
314) -> Result<String, String> {
315    let bytes = event_signing_bytes(event, crate::signing_input::SigVersion::V1)?;
316    let signature = signing_key.sign(&bytes);
317    Ok(format!("v1:{}", hex::encode(signature.to_bytes())))
318}
319
320/// Verify that `event.signature` is a valid Ed25519 signature over the canonical
321/// signing bytes of `event`, produced by the holder of `expected_pubkey_hex`.
322/// The signing-input version is read from the signature's `v1:` prefix (a bare
323/// hex signature is historical v0); the framing is then fixed, so flipping the
324/// prefix changes the bytes and fails verification (fail-closed).
325pub fn verify_event_signature(
326    event: &crate::events::StateEvent,
327    expected_pubkey_hex: &str,
328) -> Result<bool, String> {
329    use crate::signing_input::SigVersion;
330    let raw = event
331        .signature
332        .as_deref()
333        .ok_or_else(|| format!("event {} has no signature field", event.id))?;
334    let (version, signature_hex) = match raw.strip_prefix("v1:") {
335        Some(hex) => (SigVersion::V1, hex),
336        None => (SigVersion::V0, raw),
337    };
338    let verifying_key = parse_verifying_key(expected_pubkey_hex)?;
339    let sig_bytes =
340        hex::decode(signature_hex).map_err(|e| format!("invalid signature hex: {e}"))?;
341    let signature = ed25519_dalek::Signature::from_bytes(
342        &sig_bytes
343            .try_into()
344            .map_err(|_| "Signature must be 64 bytes")?,
345    );
346    let bytes = event_signing_bytes(event, version)?;
347    Ok(verifying_key.verify(&bytes, &signature).is_ok())
348}
349
350// ── Proposal signing (Phase Q-w, v0.5) ───────────────────────────────
351
352/// Compute the canonical signing bytes for a `StateProposal`. The
353/// `signature` (held externally on the wire) is excluded from the
354/// preimage. Same canonical-JSON discipline as `event_signing_bytes`.
355///
356/// The proposal `id` is included, which deterministically pins the
357/// content (since `vpr_…` is content-addressed under Phase P).
358pub fn proposal_signing_bytes(
359    proposal: &crate::proposals::StateProposal,
360) -> Result<Vec<u8>, String> {
361    use serde_json::json;
362    let preimage = json!({
363        "schema": proposal.schema,
364        "id": proposal.id,
365        "kind": proposal.kind,
366        "target": proposal.target,
367        "actor": proposal.actor,
368        "created_at": proposal.created_at,
369        "reason": proposal.reason,
370        "payload": proposal.payload,
371        "source_refs": proposal.source_refs,
372        "caveats": proposal.caveats,
373    });
374    let body = crate::canonical::to_canonical_bytes(&preimage)?;
375    Ok(crate::signing_input::signing_input(
376        crate::signing_input::SigVersion::V0,
377        crate::signing_input::payload_type::PROPOSAL,
378        &body,
379    ))
380}
381
382/// Sign a proposal with an Ed25519 private key, returning a hex-encoded
383/// signature suitable for transport on a write API.
384pub fn sign_proposal(
385    proposal: &crate::proposals::StateProposal,
386    signing_key: &SigningKey,
387) -> Result<String, String> {
388    let bytes = proposal_signing_bytes(proposal)?;
389    Ok(hex::encode(signing_key.sign(&bytes).to_bytes()))
390}
391
392/// Verify a hex-encoded Ed25519 signature against the canonical signing
393/// bytes of `proposal`, using `expected_pubkey_hex` as the verifying key.
394pub fn verify_proposal_signature(
395    proposal: &crate::proposals::StateProposal,
396    signature_hex: &str,
397    expected_pubkey_hex: &str,
398) -> Result<bool, String> {
399    let verifying_key = parse_verifying_key(expected_pubkey_hex)?;
400    let sig_bytes =
401        hex::decode(signature_hex).map_err(|e| format!("invalid signature hex: {e}"))?;
402    let signature = ed25519_dalek::Signature::from_bytes(
403        &sig_bytes
404            .try_into()
405            .map_err(|_| "Signature must be 64 bytes")?,
406    );
407    let bytes = proposal_signing_bytes(proposal)?;
408    Ok(verifying_key.verify(&bytes, &signature).is_ok())
409}
410
411/// Generic signature verifier for action-on-canonical-bytes: verify
412/// `signature_hex` is a valid Ed25519 signature over `signing_bytes`,
413/// produced by the holder of `expected_pubkey_hex`. Used by write
414/// actions that don't sign over a full proposal/event struct (e.g.,
415/// accept/reject decisions).
416pub fn verify_action_signature(
417    signing_bytes: &[u8],
418    signature_hex: &str,
419    expected_pubkey_hex: &str,
420) -> Result<bool, String> {
421    let verifying_key = parse_verifying_key(expected_pubkey_hex)?;
422    let sig_bytes =
423        hex::decode(signature_hex).map_err(|e| format!("invalid signature hex: {e}"))?;
424    let signature = ed25519_dalek::Signature::from_bytes(
425        &sig_bytes
426            .try_into()
427            .map_err(|_| "Signature must be 64 bytes")?,
428    );
429    Ok(verifying_key.verify(signing_bytes, &signature).is_ok())
430}
431
432// ── Tests ────────────────────────────────────────────────────────────
433
434#[cfg(test)]
435mod tests {
436    use super::*;
437
438    fn test_keypair() -> SigningKey {
439        use rand::rngs::OsRng;
440        SigningKey::generate(&mut OsRng)
441    }
442
443    fn actor_with_revocation(revoked_at: Option<&str>) -> ActorRecord {
444        ActorRecord {
445            id: "reviewer:test".to_string(),
446            public_key: "00".repeat(32),
447            algorithm: "ed25519".to_string(),
448            created_at: "2026-05-01T00:00:00Z".to_string(),
449            tier: None,
450            orcid: None,
451            access_clearance: None,
452            revoked_at: revoked_at.map(ToString::to_string),
453            revoked_reason: None,
454        }
455    }
456
457    #[test]
458    fn actor_revocation_compares_rfc3339_instants_across_offsets() {
459        let actor = actor_with_revocation(Some("2026-05-28T20:00:00-04:00"));
460
461        assert!(actor.is_revoked_at("2026-05-29T00:00:00Z"));
462        assert!(!actor.is_revoked_at("2026-05-28T23:59:59Z"));
463    }
464
465    #[test]
466    fn actor_revocation_fails_closed_on_invalid_timestamps() {
467        let actor = actor_with_revocation(Some("not-a-timestamp"));
468        assert!(actor.is_revoked_at("2026-05-29T00:00:00Z"));
469
470        let active_actor = actor_with_revocation(None);
471        assert!(active_actor.is_revoked_at("not-a-timestamp"));
472    }
473
474    #[cfg(unix)]
475    #[test]
476    fn generated_private_key_is_owner_only() {
477        use std::os::unix::fs::PermissionsExt;
478        let dir = tempfile::tempdir().unwrap();
479        generate_keypair(dir.path()).unwrap();
480        let mode = std::fs::metadata(dir.path().join("private.key"))
481            .unwrap()
482            .permissions()
483            .mode()
484            & 0o777;
485        assert_eq!(mode, 0o600, "private key must be owner-read/write only");
486    }
487
488    /// The deposit-endpoint signing contract: a deposit client (e.g. a producer
489    /// posting to the hub's append endpoint)
490    /// signs `to_vec(json!({action, vfr_id, parent_event_log_hash, batch}))`
491    /// with the owner key; the hub rebuilds that preimage from the parsed wire
492    /// body and checks it with `verify_action_signature`. This asserts the two
493    /// sides agree — including the JSON round-trip the batch takes over the
494    /// wire — so a correctly-signed client request is accepted, and a tampered
495    /// one is not.
496    #[test]
497    fn append_deposit_signature_roundtrips_client_to_server() {
498        use ed25519_dalek::Signer;
499        use serde_json::json;
500
501        let key = test_keypair();
502        let pubkey_hex = hex::encode(key.verifying_key().to_bytes());
503
504        // Client side: build the batch value, then the preimage, then sign.
505        let batch = json!([
506            {"object_kind": "event_only", "event": {"id": "vev_1", "kind": "finding.asserted"}}
507        ]);
508        let preimage = json!({
509            "action": "append",
510            "vfr_id": "vfr_demo",
511            "parent_event_log_hash": "sha256:abc",
512            "batch": batch,
513        });
514        let client_bytes = serde_json::to_vec(&preimage).unwrap();
515        let sig_hex = hex::encode(key.sign(&client_bytes).to_bytes());
516
517        // Server side: the batch arrives as parsed JSON; rebuild the preimage
518        // from it (the round-trip the wire imposes) and verify.
519        let parsed_batch: serde_json::Value =
520            serde_json::from_slice(&serde_json::to_vec(&batch).unwrap()).unwrap();
521        let server_preimage = json!({
522            "action": "append",
523            "vfr_id": "vfr_demo",
524            "parent_event_log_hash": "sha256:abc",
525            "batch": parsed_batch,
526        });
527        let server_bytes = serde_json::to_vec(&server_preimage).unwrap();
528
529        assert_eq!(
530            client_bytes, server_bytes,
531            "preimage bytes must match across the wire"
532        );
533        assert!(
534            verify_action_signature(&server_bytes, &sig_hex, &pubkey_hex).unwrap(),
535            "the client's signature must verify on the server side"
536        );
537        // A tampered parent hash must NOT verify.
538        let tampered = json!({
539            "action": "append", "vfr_id": "vfr_demo",
540            "parent_event_log_hash": "sha256:DIFFERENT", "batch": parsed_batch,
541        });
542        assert!(
543            !verify_action_signature(
544                &serde_json::to_vec(&tampered).unwrap(),
545                &sig_hex,
546                &pubkey_hex
547            )
548            .unwrap(),
549            "a tampered preimage must be rejected"
550        );
551    }
552
553    #[test]
554    fn keygen_produces_valid_files() {
555        let dir = std::env::temp_dir().join("vela_test_keygen");
556        let _ = std::fs::remove_dir_all(&dir);
557
558        let pubkey = generate_keypair(&dir).unwrap();
559        assert_eq!(pubkey.len(), 64); // 32 bytes hex-encoded
560
561        let private_hex = std::fs::read_to_string(dir.join("private.key")).unwrap();
562        let public_hex = std::fs::read_to_string(dir.join("public.key")).unwrap();
563        assert_eq!(private_hex.len(), 64);
564        assert_eq!(public_hex, pubkey);
565
566        let _ = std::fs::remove_dir_all(&dir);
567    }
568
569    #[test]
570    fn registered_actor_signed_event_roundtrip() {
571        // Phase M: a registered actor's event must sign-and-verify
572        // against its registered pubkey via `event_signing_bytes`. This
573        // is the load-bearing claim for the v0.4 strict-mode gate.
574        use crate::events::{
575            EVENT_SCHEMA, NULL_HASH, StateActor, StateEvent, StateTarget, compute_event_id,
576        };
577
578        let key = test_keypair();
579        let pubkey_hex = hex::encode(key.verifying_key().to_bytes());
580
581        let mut event = StateEvent {
582            schema: EVENT_SCHEMA.to_string(),
583            id: String::new(),
584            kind: "finding.reviewed".into(),
585            target: StateTarget {
586                r#type: "finding".to_string(),
587                id: "vf_test".to_string(),
588            },
589            actor: StateActor {
590                id: "reviewer:registered".to_string(),
591                r#type: "human".to_string(),
592            },
593            timestamp: "2026-04-25T00:00:00Z".to_string(),
594            reason: "phase-m round-trip test".to_string(),
595            before_hash: NULL_HASH.to_string(),
596            after_hash: "sha256:abc".to_string(),
597            payload: serde_json::json!({"status": "accepted", "proposal_id": "vpr_test"}),
598            caveats: vec![],
599            signature: None,
600        };
601        event.id = compute_event_id(&event);
602        event.signature = Some(sign_event(&event, &key).unwrap());
603
604        // Verifies against the registered pubkey.
605        assert!(verify_event_signature(&event, &pubkey_hex).unwrap());
606
607        // Tampering with the reason invalidates the signature.
608        let mut tampered = event.clone();
609        tampered.reason = "different reason".to_string();
610        assert!(!verify_event_signature(&tampered, &pubkey_hex).unwrap());
611    }
612
613    #[test]
614    fn v0_and_v1_event_signatures_both_verify() {
615        // The migration seam (M8): a new signature is v1 (v1:-prefixed) and a
616        // historical signature is v0 (bare hex). Both must verify so the flip
617        // never strands a historical event, and a downgrade (claiming a v1
618        // signature is v0) must fail closed.
619        use crate::events::{
620            EVENT_SCHEMA, NULL_HASH, StateActor, StateEvent, StateTarget, compute_event_id,
621        };
622        use crate::signing_input::SigVersion;
623
624        let key = test_keypair();
625        let pubkey = hex::encode(key.verifying_key().to_bytes());
626        let mut event = StateEvent {
627            schema: EVENT_SCHEMA.to_string(),
628            id: String::new(),
629            kind: "finding.reviewed".into(),
630            target: StateTarget {
631                r#type: "finding".to_string(),
632                id: "vf_test".to_string(),
633            },
634            actor: StateActor {
635                id: "reviewer:registered".to_string(),
636                r#type: "human".to_string(),
637            },
638            timestamp: "2026-06-30T00:00:00Z".to_string(),
639            reason: "v0/v1 dual-verify".to_string(),
640            before_hash: NULL_HASH.to_string(),
641            after_hash: "sha256:abc".to_string(),
642            payload: serde_json::json!({"status": "accepted", "proposal_id": "vpr_test"}),
643            caveats: vec![],
644            signature: None,
645        };
646        event.id = compute_event_id(&event);
647
648        // New default: sign_event emits a v1: signature, and it verifies.
649        event.signature = Some(sign_event(&event, &key).unwrap());
650        assert!(event.signature.as_deref().unwrap().starts_with("v1:"));
651        assert!(verify_event_signature(&event, &pubkey).unwrap());
652
653        // Historical v0: a bare-hex signature over the v0 framing still verifies.
654        let v0_bytes = event_signing_bytes(&event, SigVersion::V0).unwrap();
655        let mut v0_event = event.clone();
656        v0_event.signature = Some(hex::encode(key.sign(&v0_bytes).to_bytes()));
657        assert!(verify_event_signature(&v0_event, &pubkey).unwrap());
658
659        // Downgrade attempt: strip the v1: prefix so it claims v0. The framing
660        // then differs from what was signed, so it must fail closed.
661        let mut downgraded = event.clone();
662        let bare = event
663            .signature
664            .as_deref()
665            .unwrap()
666            .strip_prefix("v1:")
667            .unwrap()
668            .to_string();
669        downgraded.signature = Some(bare);
670        assert!(!verify_event_signature(&downgraded, &pubkey).unwrap());
671    }
672
673    #[test]
674    fn provenance_co_author_confers_no_signing_authority() {
675        // The co-authorship block names a non-human assistant (agent:claude)
676        // inside the SIGNED payload. The structural guarantee: the signature is
677        // verified only against actor.id's key, never against any provenance
678        // name. An AI named as a co-author can therefore never stand in as the
679        // signer, so no model is ever in the trust path even when it is recorded
680        // as having drafted the work.
681        use crate::events::{
682            EVENT_SCHEMA, NULL_HASH, StateActor, StateEvent, StateTarget, compute_event_id,
683        };
684        use crate::provenance::{MachineContribution, Provenance};
685
686        let human_key = test_keypair();
687        let human_pubkey = hex::encode(human_key.verifying_key().to_bytes());
688        let agent_key = test_keypair();
689        let agent_pubkey = hex::encode(agent_key.verifying_key().to_bytes());
690
691        let mut payload = serde_json::json!({"status": "accepted", "proposal_id": "vpr_test"});
692        crate::provenance::attach_to_payload(
693            &mut payload,
694            &Provenance {
695                machine_contributions: vec![MachineContribution {
696                    id: "agent:claude".to_string(),
697                    class: "agent".to_string(),
698                    role: "drafted".to_string(),
699                    tool: "claude-code".to_string(),
700                    generated_by: "model: claude-opus-4-8".to_string(),
701                    authority: "none".to_string(),
702                }],
703                ..Default::default()
704            },
705        )
706        .unwrap();
707        assert_eq!(
708            payload["provenance"]["machine_contributions"][0]["id"],
709            "agent:claude"
710        );
711
712        let mut event = StateEvent {
713            schema: EVENT_SCHEMA.to_string(),
714            id: String::new(),
715            kind: "review.accepted".into(),
716            target: StateTarget {
717                r#type: "proposal".to_string(),
718                id: "vpr_test".to_string(),
719            },
720            actor: StateActor {
721                id: "reviewer:will-blair".to_string(),
722                r#type: "human".to_string(),
723            },
724            timestamp: "2026-06-30T00:00:00Z".to_string(),
725            reason: "co-authored accept".to_string(),
726            before_hash: NULL_HASH.to_string(),
727            after_hash: "sha256:abc".to_string(),
728            payload,
729            caveats: vec![],
730            signature: None,
731        };
732        event.id = compute_event_id(&event);
733        event.signature = Some(sign_event(&event, &human_key).unwrap());
734
735        // The accountable human's key verifies the co-authored event.
736        assert!(verify_event_signature(&event, &human_pubkey).unwrap());
737        // The co-author's own key does NOT verify it: being named in provenance
738        // grants zero signing authority.
739        assert!(!verify_event_signature(&event, &agent_pubkey).unwrap());
740        // The block is signed-over, so tampering with the co-author name breaks
741        // the human's signature (the attribution is tamper-evident).
742        let mut tampered = event.clone();
743        tampered.payload["provenance"]["machine_contributions"][0]["id"] =
744            serde_json::json!("agent:someone-else");
745        assert!(!verify_event_signature(&tampered, &human_pubkey).unwrap());
746    }
747
748    // ── v0.43 ORCID validation ───────────────────────────────────────
749
750    #[test]
751    fn validate_orcid_accepts_canonical_form() {
752        assert_eq!(
753            validate_orcid("0000-0001-2345-6789").unwrap(),
754            "0000-0001-2345-6789"
755        );
756    }
757
758    #[test]
759    fn validate_orcid_accepts_check_digit_x() {
760        assert_eq!(
761            validate_orcid("0000-0001-5109-393X").unwrap(),
762            "0000-0001-5109-393X"
763        );
764    }
765
766    #[test]
767    fn validate_orcid_strips_url_prefix() {
768        assert_eq!(
769            validate_orcid("https://orcid.org/0000-0001-2345-6789").unwrap(),
770            "0000-0001-2345-6789"
771        );
772    }
773
774    #[test]
775    fn validate_orcid_strips_orcid_prefix() {
776        assert_eq!(
777            validate_orcid("orcid:0000-0001-2345-6789").unwrap(),
778            "0000-0001-2345-6789"
779        );
780    }
781
782    #[test]
783    fn validate_orcid_rejects_short() {
784        assert!(validate_orcid("0000-0001").is_err());
785    }
786
787    #[test]
788    fn validate_orcid_rejects_letters_in_non_check_position() {
789        assert!(validate_orcid("0000-A001-2345-6789").is_err());
790    }
791
792    #[test]
793    fn validate_orcid_rejects_x_in_first_three_groups() {
794        assert!(validate_orcid("000X-0001-2345-6789").is_err());
795    }
796
797    #[test]
798    fn validate_orcid_rejects_extra_groups() {
799        assert!(validate_orcid("0000-0001-2345-6789-9999").is_err());
800    }
801}