gitiverse-core 0.3.0

Core domain identities, repository manifests, signed refs, capability access policy, and canonical CBOR protocol types for gitiverse
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
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>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub writer_token: Option<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> {
        Self::sign_with_token(repo_id, refs, seq, timestamp, None, identity).await
    }

    /// Signs a new ref snapshot under `identity` for `repo_id`, optionally embedding an encoded COSE capability token (`writer_token`) so non-authority collaborators' refs verify offline.
    pub async fn sign_with_token(
        repo_id: RepoId,
        refs: BTreeMap<String, String>,
        seq: u64,
        timestamp: u64,
        writer_token: Option<Vec<u8>>,
        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(),
            writer_token,
        };
        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);
        if let Some(tok) = &self.writer_token {
            builder.push_bytes("writer-token", tok);
        }
        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);
        if let Some(tok) = &self.writer_token {
            builder.push_bytes("writer-token", tok);
        }
        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;
        let mut writer_token: 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)?)?,
                "writer-token" => strict::set_once(&mut writer_token, 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"))?,
            writer_token,
        })
    }
}

/// 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
        );
    }

    #[tokio::test]
    async fn writer_token_round_trips_detects_tampering_and_is_omitted_when_none() {
        let signer = NodeIdentity::generate_es256();
        let repo_id = RepoId::from_bytes([0x33; 32]);

        let bare = SignedRefMap::sign(repo_id, sample_refs(), 1, 500, &signer)
            .await
            .unwrap();
        let bare_cbor = to_vec(&bare);
        assert!(
            !bare_cbor
                .windows(b"writer-token".len())
                .any(|w| w == b"writer-token")
        );

        let token_bytes = vec![0xDE, 0xAD, 0xBE, 0xEF];
        let mut with_tok = SignedRefMap::sign_with_token(
            repo_id,
            sample_refs(),
            2,
            501,
            Some(token_bytes),
            &signer,
        )
        .await
        .unwrap();
        with_tok.verify(&signer, Some(&repo_id)).await.unwrap();

        let encoded = to_vec(&with_tok);
        let decoded: SignedRefMap = decode_exact(&encoded).unwrap();
        assert_eq!(decoded, with_tok);
        let json = serde_json::to_string(&with_tok).unwrap();
        let decoded_json: SignedRefMap = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded_json, with_tok);

        with_tok.writer_token = Some(vec![0xCA, 0xFE]);
        assert_eq!(
            with_tok.verify(&signer, Some(&repo_id)).await.unwrap_err(),
            SigRefsError::BadSignature
        );
    }
}