Skip to main content

vela_protocol/kernel/
sign.rs

1//! Ed25519 primitives for authority-free producer and verifier records.
2//!
3//! This module does not implement repository authority or scientific
4//! Decisions. Current repository authority is authenticated by the dedicated
5//! runtime boundary; producer identities, Submissions, and Verification
6//! Records use only the small byte-signing surface below.
7
8use std::path::Path;
9
10use ed25519_dalek::{Signer, SigningKey, Verifier, VerifyingKey};
11
12/// Generate an Ed25519 keypair for an authority-free producer or verifier.
13///
14/// The private seed is written as lowercase hex to `private.key`; the public
15/// key is written to `public.key`. Repository-authority credentials are never
16/// loaded through this path.
17pub fn generate_keypair(output_dir: &Path) -> Result<String, String> {
18    use rand::rngs::OsRng;
19
20    std::fs::create_dir_all(output_dir)
21        .map_err(|error| format!("failed to create output directory: {error}"))?;
22    let signing_key = SigningKey::generate(&mut OsRng);
23    let public_hex = pubkey_hex(&signing_key);
24    let private_path = output_dir.join("private.key");
25    std::fs::write(&private_path, hex::encode(signing_key.to_bytes()))
26        .map_err(|error| format!("failed to write private key: {error}"))?;
27    harden_key_permissions(&private_path);
28    std::fs::write(output_dir.join("public.key"), &public_hex)
29        .map_err(|error| format!("failed to write public key: {error}"))?;
30    Ok(public_hex)
31}
32
33/// Set owner-only permissions on a seed file where supported.
34pub fn harden_key_permissions(path: &Path) {
35    #[cfg(unix)]
36    {
37        use std::os::unix::fs::PermissionsExt;
38        if let Ok(metadata) = std::fs::metadata(path) {
39            let mut permissions = metadata.permissions();
40            permissions.set_mode(0o600);
41            let _ = std::fs::set_permissions(path, permissions);
42        }
43    }
44    #[cfg(not(unix))]
45    {
46        let _ = path;
47    }
48}
49
50/// Parse a lowercase or uppercase hex-encoded 32-byte Ed25519 seed.
51pub fn signing_key_from_hex(hex_str: &str) -> Result<SigningKey, String> {
52    let bytes =
53        hex::decode(hex_str.trim()).map_err(|error| format!("invalid private-key hex: {error}"))?;
54    let seed: [u8; 32] = bytes
55        .try_into()
56        .map_err(|_| "private key must be exactly 32 bytes".to_string())?;
57    Ok(SigningKey::from_bytes(&seed))
58}
59
60/// Load the producer/verifier seed format emitted by [`generate_keypair`].
61pub fn load_signing_key_from_path(path: &Path) -> Result<SigningKey, String> {
62    let source = std::fs::read_to_string(path)
63        .map_err(|error| format!("failed to read private key: {error}"))?;
64    signing_key_from_hex(&source)
65}
66
67/// Sign exact canonical bytes.
68pub fn sign_bytes(signing_key: &SigningKey, bytes: &[u8]) -> [u8; 64] {
69    signing_key.sign(bytes).to_bytes()
70}
71
72/// Return the lowercase hex-encoded 32-byte public key.
73pub fn pubkey_hex(signing_key: &SigningKey) -> String {
74    hex::encode(signing_key.verifying_key().to_bytes())
75}
76
77/// Verify an Ed25519 signature over exact canonical bytes.
78pub fn verify_action_signature(
79    signing_bytes: &[u8],
80    signature_hex: &str,
81    expected_pubkey_hex: &str,
82) -> Result<bool, String> {
83    let verifying_key = parse_verifying_key(expected_pubkey_hex)?;
84    let bytes =
85        hex::decode(signature_hex).map_err(|error| format!("invalid signature hex: {error}"))?;
86    let signature = ed25519_dalek::Signature::from_bytes(
87        &bytes
88            .try_into()
89            .map_err(|_| "signature must be exactly 64 bytes")?,
90    );
91    Ok(verifying_key.verify(signing_bytes, &signature).is_ok())
92}
93
94fn parse_verifying_key(hex_str: &str) -> Result<VerifyingKey, String> {
95    let bytes = hex::decode(hex_str).map_err(|error| format!("invalid public-key hex: {error}"))?;
96    let key: [u8; 32] = bytes
97        .try_into()
98        .map_err(|_| "public key must be exactly 32 bytes".to_string())?;
99    VerifyingKey::from_bytes(&key).map_err(|error| format!("invalid public key: {error}"))
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    #[test]
107    fn exact_bytes_verify_and_drift_fails() {
108        use rand::rngs::OsRng;
109
110        let key = SigningKey::generate(&mut OsRng);
111        let signature = hex::encode(sign_bytes(&key, b"bounded claim"));
112        assert!(verify_action_signature(b"bounded claim", &signature, &pubkey_hex(&key)).unwrap());
113        assert!(!verify_action_signature(b"changed claim", &signature, &pubkey_hex(&key)).unwrap());
114    }
115
116    #[test]
117    fn malformed_keys_and_signatures_fail_closed() {
118        assert!(signing_key_from_hex("00").is_err());
119        assert!(verify_action_signature(b"x", "00", "00").is_err());
120    }
121}