gitiverse-core 0.2.0

Core domain identities, repository manifests, signed refs, capability access policy, and canonical CBOR protocol types for gitiverse
Documentation
use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use thiserror::Error;
use wire_mesh_core::ports::{CoreError, Identity};
use wire_mesh_wire::DecodeError;
use wire_mesh_wire::identity::{DeviceId, IdentityKey};
use wire_mesh_wire::minicbor::{Decode, Decoder, Encode, Encoder};
use wire_mesh_wire::strict;
use wire_mesh_wire::value::CdeMapBuilder;

use crate::ids::{RepoId, decode_repo_id};
use crate::repo::{decode_device_id, decode_identity_key, encoded_text_key};

/// Failure returned when signing, validating, or verifying a [`SignedRefMap`].
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum SigRefsError {
    #[error("signed refs belong to repo {found}, expected {expected}")]
    RepoMismatch { expected: RepoId, found: RepoId },
    #[error("invalid Git ref name or OID: {0}")]
    InvalidRef(String),
    #[error("signer key does not match claimed signer device-id")]
    SignerMismatch,
    #[error("signed ref map signature does not verify")]
    BadSignature,
    #[error("stale signed ref sequence {presented}: must be strictly greater than {last_accepted}")]
    StaleSequence { presented: u64, last_accepted: u64 },
    #[error("cryptographic port error: {0}")]
    Crypto(#[from] CoreError),
}

/// Validates a Git ref name (full ref path such as `refs/heads/main`) and lowercase hex OID (40 or 64 chars).
pub fn validate_ref_entry(ref_name: &str, oid: &str) -> Result<(), SigRefsError> {
    if ref_name.is_empty()
        || ref_name.starts_with('/')
        || ref_name.ends_with('/')
        || ref_name.starts_with('-')
        || ref_name.contains("//")
        || ref_name.contains("..")
        || ref_name.ends_with(".lock")
        || ref_name.chars().any(|c| {
            c.is_control()
                || c.is_whitespace()
                || matches!(c, '~' | '^' | ':' | '?' | '*' | '[' | '\\')
        })
    {
        return Err(SigRefsError::InvalidRef(format!(
            "invalid ref name {ref_name:?}"
        )));
    }
    let valid_oid_len = oid.len() == 40 || oid.len() == 64;
    let valid_oid_hex = oid
        .bytes()
        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
    if !valid_oid_len || !valid_oid_hex {
        return Err(SigRefsError::InvalidRef(format!(
            "invalid OID {oid:?} for ref {ref_name:?}"
        )));
    }
    Ok(())
}

/// Signed snapshot of repository Git references (`ref_name -> oid`) with monotonic sequence protection against replay.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SignedRefMap {
    pub repo_id: RepoId,
    pub refs: BTreeMap<String, String>,
    pub seq: u64,
    pub timestamp: u64,
    #[serde(with = "crate::ids::serde_device_id")]
    pub signer: DeviceId,
    #[serde(with = "crate::ids::serde_identity_key")]
    pub signer_key: IdentityKey,
    #[serde(with = "crate::ids::serde_hex_bytes")]
    pub signature: Vec<u8>,
}

/// Canonical alias matching the protocol terminology.
pub type SignedRefs = SignedRefMap;

impl SignedRefMap {
    /// Signs a new ref snapshot under `identity` for `repo_id`.
    pub async fn sign(
        repo_id: RepoId,
        refs: BTreeMap<String, String>,
        seq: u64,
        timestamp: u64,
        identity: &dyn Identity,
    ) -> Result<Self, SigRefsError> {
        for (name, oid) in &refs {
            validate_ref_entry(name, oid)?;
        }
        let signer = *identity.device_id();
        let signer_key = identity.identity_key().clone();
        let mut map = Self {
            repo_id,
            refs,
            seq,
            timestamp,
            signer,
            signer_key,
            signature: Vec::new(),
        };
        map.signature = identity.sign(&map.canonical_signing_bytes()).await?;
        Ok(map)
    }

    fn encode_refs_map_bytes(&self) -> Vec<u8> {
        let mut builder = CdeMapBuilder::new();
        for (name, oid) in &self.refs {
            builder.push(name.as_str(), &oid.as_str());
        }
        let mut buf = Vec::new();
        let mut enc = Encoder::new(&mut buf);
        let _ = builder.write(&mut enc);
        buf
    }

    /// Assembles the domain-separated canonical CBOR signing input covering repo, refs, sequence, timestamp, and signer identity.
    #[must_use]
    pub fn canonical_signing_bytes(&self) -> Vec<u8> {
        let mut builder = CdeMapBuilder::new();
        builder.push("domain", "gitiverse.signed-refs.v1");
        builder.push("repo-id", &self.repo_id);
        builder.push_raw(encoded_text_key("refs"), self.encode_refs_map_bytes());
        builder.push("seq", &self.seq);
        builder.push("timestamp", &self.timestamp);
        builder.push("signer", &self.signer);
        builder.push("signer-key", &self.signer_key);
        let mut buf = Vec::new();
        let mut enc = Encoder::new(&mut buf);
        let _ = builder.write(&mut enc);
        buf
    }

    /// Verifies repo scope, ref/OID syntax, self-certifying `signer_key`, and signature.
    pub async fn verify(
        &self,
        identity: &dyn Identity,
        expected_repo_id: Option<&RepoId>,
    ) -> Result<(), SigRefsError> {
        if let Some(expected) = expected_repo_id
            && &self.repo_id != expected
        {
            return Err(SigRefsError::RepoMismatch {
                expected: *expected,
                found: self.repo_id,
            });
        }
        for (name, oid) in &self.refs {
            validate_ref_entry(name, oid)?;
        }
        if identity.derive_device_id(&self.signer_key.public_key) != self.signer {
            return Err(SigRefsError::SignerMismatch);
        }
        let ok = identity
            .verify(
                &self.signer_key,
                &self.canonical_signing_bytes(),
                &self.signature,
            )
            .await?;
        if !ok {
            return Err(SigRefsError::BadSignature);
        }
        Ok(())
    }

    /// Verifies cryptographic authenticity and enforces strictly monotonic `seq` relative to `last_accepted_seq`.
    pub async fn verify_monotonic(
        &self,
        identity: &dyn Identity,
        expected_repo_id: Option<&RepoId>,
        last_accepted_seq: Option<u64>,
    ) -> Result<(), SigRefsError> {
        self.verify(identity, expected_repo_id).await?;
        if let Some(last_accepted) = last_accepted_seq
            && self.seq <= last_accepted
        {
            return Err(SigRefsError::StaleSequence {
                presented: self.seq,
                last_accepted,
            });
        }
        Ok(())
    }
}

impl Encode<()> for SignedRefMap {
    fn encode<W: wire_mesh_wire::minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), wire_mesh_wire::minicbor::encode::Error<W::Error>> {
        let mut builder = CdeMapBuilder::new();
        builder.push("repo-id", &self.repo_id);
        builder.push_raw(encoded_text_key("refs"), self.encode_refs_map_bytes());
        builder.push("seq", &self.seq);
        builder.push("timestamp", &self.timestamp);
        builder.push("signer", &self.signer);
        builder.push("signer-key", &self.signer_key);
        builder.push_bytes("signature", &self.signature);
        builder.write(e)
    }
}

impl Decode<'_, ()> for SignedRefMap {
    fn decode(
        d: &mut Decoder<'_>,
        _ctx: &mut (),
    ) -> Result<Self, wire_mesh_wire::minicbor::decode::Error> {
        Self::decode_strict(d).map_err(wire_mesh_wire::minicbor::decode::Error::custom)
    }
}

impl SignedRefMap {
    pub(crate) fn decode_strict(d: &mut Decoder<'_>) -> Result<Self, DecodeError> {
        let mut map = strict::MapDecoder::new(d)?;
        let mut repo_id: Option<RepoId> = None;
        let mut refs: Option<BTreeMap<String, String>> = None;
        let mut seq: Option<u64> = None;
        let mut timestamp: Option<u64> = None;
        let mut signer: Option<DeviceId> = None;
        let mut signer_key: Option<IdentityKey> = None;
        let mut signature: Option<Vec<u8>> = None;
        while let Some(key) = map.next_key(d)? {
            match key {
                "repo-id" => strict::set_once(&mut repo_id, decode_repo_id(d)?)?,
                "refs" => {
                    let mut ref_map = strict::MapDecoder::new(d)?;
                    let mut decoded = BTreeMap::new();
                    while let Some(ref_name) = ref_map.next_key(d)? {
                        let oid = strict::text_value(d)?;
                        decoded.insert(ref_name.to_owned(), oid);
                    }
                    strict::set_once(&mut refs, decoded)?;
                }
                "seq" => strict::set_once(&mut seq, strict::uint_value(d)?)?,
                "timestamp" => strict::set_once(&mut timestamp, strict::uint_value(d)?)?,
                "signer" => strict::set_once(&mut signer, decode_device_id(d)?)?,
                "signer-key" => strict::set_once(&mut signer_key, decode_identity_key(d)?)?,
                "signature" => strict::set_once(&mut signature, strict::bytes_value(d)?)?,
                other => return Err(DecodeError::UnknownKey(other.to_owned())),
            }
        }
        Ok(SignedRefMap {
            repo_id: repo_id.ok_or(DecodeError::MissingField("repo-id"))?,
            refs: refs.ok_or(DecodeError::MissingField("refs"))?,
            seq: seq.ok_or(DecodeError::MissingField("seq"))?,
            timestamp: timestamp.ok_or(DecodeError::MissingField("timestamp"))?,
            signer: signer.ok_or(DecodeError::MissingField("signer"))?,
            signer_key: signer_key.ok_or(DecodeError::MissingField("signer-key"))?,
            signature: signature.ok_or(DecodeError::MissingField("signature"))?,
        })
    }
}

/// Stateful per-signer monotonic sequence watermark tracker preventing stale signed-ref replay.
#[derive(Debug, Clone, Default)]
pub struct SignedRefTracker {
    latest: BTreeMap<(RepoId, DeviceId), SignedRefMap>,
}

impl SignedRefTracker {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the last accepted sequence number for `(repo_id, signer)`, if any.
    #[must_use]
    pub fn last_seq(&self, repo_id: &RepoId, signer: &DeviceId) -> Option<u64> {
        self.latest.get(&(*repo_id, *signer)).map(|m| m.seq)
    }

    /// Returns the latest accepted [`SignedRefMap`] for `(repo_id, signer)`, if any.
    #[must_use]
    pub fn latest(&self, repo_id: &RepoId, signer: &DeviceId) -> Option<&SignedRefMap> {
        self.latest.get(&(*repo_id, *signer))
    }

    /// Verifies `map` (optionally pinned to `expected_repo_id`) and advances the monotonic watermark on success.
    pub async fn verify_and_accept(
        &mut self,
        identity: &dyn Identity,
        expected_repo_id: Option<&RepoId>,
        map: SignedRefMap,
    ) -> Result<(), SigRefsError> {
        let last_seq = self.last_seq(&map.repo_id, &map.signer);
        map.verify_monotonic(identity, expected_repo_id, last_seq)
            .await?;
        self.latest.insert((map.repo_id, map.signer), map);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use wire_mesh_core::adapters::NodeIdentity;
    use wire_mesh_wire::{decode_exact, to_vec};

    fn sample_refs() -> BTreeMap<String, String> {
        let mut refs = BTreeMap::new();
        refs.insert("refs/heads/main".to_owned(), "a".repeat(40));
        refs.insert("refs/tags/v0.1.0".to_owned(), "b".repeat(40));
        refs
    }

    #[tokio::test]
    async fn signed_refs_verify_round_trip_and_enforce_monotonic_seq() {
        let signer = NodeIdentity::generate_ed25519();
        let repo_id = RepoId::from_bytes([0x11; 32]);
        let s1 = SignedRefMap::sign(repo_id, sample_refs(), 1, 10_000, &signer)
            .await
            .unwrap();
        let s2 = SignedRefMap::sign(repo_id, sample_refs(), 2, 10_005, &signer)
            .await
            .unwrap();

        let cbor = to_vec(&s1);
        let decoded: SignedRefMap = decode_exact(&cbor).unwrap();
        assert_eq!(decoded, s1);

        let mut tracker = SignedRefTracker::new();
        tracker
            .verify_and_accept(&signer, Some(&repo_id), s2.clone())
            .await
            .unwrap();
        assert_eq!(tracker.last_seq(&repo_id, signer.device_id()), Some(2));

        // Stale replay of seq=1 and duplicate seq=2 must both fail.
        let err_stale = tracker
            .verify_and_accept(&signer, Some(&repo_id), s1)
            .await
            .unwrap_err();
        assert_eq!(
            err_stale,
            SigRefsError::StaleSequence {
                presented: 1,
                last_accepted: 2,
            }
        );

        let err_dup = tracker
            .verify_and_accept(&signer, Some(&repo_id), s2)
            .await
            .unwrap_err();
        assert_eq!(
            err_dup,
            SigRefsError::StaleSequence {
                presented: 2,
                last_accepted: 2,
            }
        );
    }

    #[tokio::test]
    async fn tampered_or_wrong_repo_signed_refs_fail() {
        let signer = NodeIdentity::generate_es256();
        let repo_a = RepoId::from_bytes([0x01; 32]);
        let repo_b = RepoId::from_bytes([0x02; 32]);
        let mut signed = SignedRefMap::sign(repo_a, sample_refs(), 5, 999, &signer)
            .await
            .unwrap();

        assert_eq!(
            signed.verify(&signer, Some(&repo_b)).await.unwrap_err(),
            SigRefsError::RepoMismatch {
                expected: repo_b,
                found: repo_a,
            }
        );

        signed
            .refs
            .insert("refs/heads/main".to_owned(), "c".repeat(40));
        assert_eq!(
            signed.verify(&signer, Some(&repo_a)).await.unwrap_err(),
            SigRefsError::BadSignature
        );
    }
}