polyc-crypto 2026.8.0

Provenance signatures (commonware-cryptography ed25519) for polychrome tool calls.
Documentation
//! Provenance signatures for polychrome.
//!
//! Wraps `commonware-cryptography` ed25519 so the harness can sign the bytes
//! that back a tool call's `signature` field and the control plane can verify
//! them. A fixed [`NAMESPACE`] provides cross-domain separation (a signature
//! minted here cannot be replayed in another context).
//!
//! This primitive is runtime-agnostic — it does not pull in `commonware-runtime`
//! or `commonware-p2p`.

use commonware_codec::{DecodeExt, Encode};
use commonware_cryptography::{
    Signer as _, Verifier as _,
    ed25519::{PrivateKey, PublicKey, Signature},
};

pub mod approval;
pub mod approval_assertion;
pub mod canon;
pub mod edge_identity;
pub mod grant;
pub mod handoff;
pub mod hex;
pub mod mandate;
pub mod question;
pub mod routine_observation;
mod salted_hash;
pub mod sensitive;
pub mod session;
pub mod session_grant;
mod signed;
pub mod signing_role;
pub mod subagent;
pub mod tls;
pub mod toolcall;

pub use salted_hash::hash_salted_secret;

/// Domain-separation namespace prepended to every polychrome signature.
pub const NAMESPACE: &[u8] = b"polychrome.v1";

/// Mint 32 cryptographically secure random bytes from the operating system's
/// entropy source.
///
/// The canonical way to generate secret material in this workspace: an
/// ed25519 private key for [`Signer::from_key_bytes`], or the secret half of
/// a `pc_<id>_<secret>` transport bearer. Every byte is uniformly random —
/// unlike an identifier such as a UUID, which fixes several bits to encode
/// its own version and variant and so is not key material, however random the
/// rest of it is.
///
/// # Panics
///
/// Panics if the OS entropy source is unavailable, which on a supported
/// platform means the process cannot safely mint secrets at all — failing
/// loudly beats returning predictable key material.
#[must_use]
pub fn random_secret_bytes() -> [u8; 32] {
    use rand::RngCore as _;
    let mut bytes = [0u8; 32];
    rand::rngs::OsRng
        .try_fill_bytes(&mut bytes)
        .expect("the OS entropy source must be available to mint secrets");
    bytes
}

/// Raised building a [`Signer`] from raw key-material bytes (`#784`) —
/// e.g. loaded from a secret store — rather than the insecure deterministic
/// [`Signer::from_seed`].
#[derive(Debug, thiserror::Error)]
pub enum SignerError {
    /// `bytes` is not a validly-encoded ed25519 private key: wrong length
    /// (must be exactly 32 bytes) or otherwise malformed.
    #[error("invalid ed25519 private key material: {0}")]
    InvalidKeyMaterial(#[from] commonware_codec::Error),
}

/// An ed25519 signing key.
#[derive(Clone)]
pub struct Signer(PrivateKey);

impl Signer {
    /// Build a [`Signer`] from a deterministic seed.
    ///
    /// **Insecure**: for tests and examples only. Production keys come from a
    /// secret store / WIF, not a seed.
    #[must_use]
    pub fn from_seed(seed: u64) -> Self {
        Self(PrivateKey::from_seed(seed))
    }

    /// Build a [`Signer`] from raw ed25519 private-key bytes (exactly 32
    /// bytes), e.g. loaded from a secret store (`#784`). The production-safe
    /// counterpart of [`Signer::from_seed`], which is deterministic and
    /// reachable only in tests.
    ///
    /// # Errors
    ///
    /// Returns [`SignerError`] if `bytes` is not a validly-encoded ed25519
    /// private key.
    pub fn from_key_bytes(bytes: &[u8]) -> Result<Self, SignerError> {
        Ok(Self(PrivateKey::decode(bytes)?))
    }

    /// The verifying public key, encoded as bytes (pass to [`verify`]).
    #[must_use]
    pub fn public_key_bytes(&self) -> Vec<u8> {
        self.0.public_key().encode().to_vec()
    }

    /// Sign `msg` under [`NAMESPACE`]; returns the signature bytes (suitable
    /// for a `signature` wire field).
    #[must_use]
    pub fn sign(&self, msg: &[u8]) -> Vec<u8> {
        self.0.sign(NAMESPACE, msg).encode().to_vec()
    }
}

/// Verify `sig` over `msg` against an encoded `public_key`.
///
/// Returns `false` on any decode failure or signature mismatch — never panics.
#[must_use]
pub fn verify(public_key: &[u8], msg: &[u8], sig: &[u8]) -> bool {
    let Ok(pk) = PublicKey::decode(public_key) else {
        return false;
    };
    let Ok(sig) = Signature::decode(sig) else {
        return false;
    };
    pk.verify(NAMESPACE, msg, &sig)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;

    #[test]
    fn sign_then_verify_round_trips() {
        let signer = Signer::from_seed(1);
        let pk = signer.public_key_bytes();
        let msg = b"tool-call canonical bytes";
        let sig = signer.sign(msg);
        assert!(verify(&pk, msg, &sig));
    }

    #[test]
    fn wrong_message_fails() {
        let signer = Signer::from_seed(1);
        let pk = signer.public_key_bytes();
        let sig = signer.sign(b"original");
        assert!(!verify(&pk, b"tampered", &sig));
    }

    #[test]
    fn wrong_key_fails() {
        let signer = Signer::from_seed(1);
        let other = Signer::from_seed(2);
        let msg = b"msg";
        let sig = signer.sign(msg);
        assert!(!verify(&other.public_key_bytes(), msg, &sig));
    }

    #[test]
    fn garbage_inputs_return_false_not_panic() {
        assert!(!verify(b"not-a-key", b"m", b"not-a-sig"));
        assert!(!verify(&[], &[], &[]));
    }

    // #784: `from_key_bytes` is the production-safe loader for key material
    // pulled from a secret store — it round-trips exactly like `from_seed`
    // and mints a DIFFERENT key than the deterministic seed for the same
    // bytes-as-seed coincidence would.
    #[test]
    fn from_key_bytes_round_trips_and_rejects_bad_length() {
        let key_bytes = [7u8; 32];
        let signer = Signer::from_key_bytes(&key_bytes).expect("valid 32-byte key material");
        let pk = signer.public_key_bytes();
        let msg = b"approval-response canonical bytes";
        let sig = signer.sign(msg);
        assert!(verify(&pk, msg, &sig));

        // Wrong length is rejected rather than silently truncated/padded.
        assert!(Signer::from_key_bytes(&[7u8; 31]).is_err());
        assert!(Signer::from_key_bytes(&[7u8; 33]).is_err());
        assert!(Signer::from_key_bytes(&[]).is_err());
    }
}