gitiverse-core 0.1.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
use core::fmt;
use core::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;
use wire_mesh_wire::DecodeError;
use wire_mesh_wire::identity::DeviceId;
use wire_mesh_wire::minicbor::{Decode, Decoder, Encode, Encoder};
use wire_mesh_wire::strict;

/// Domain identifier for `gitiverse` capability verbs on `wire-mesh`.
pub const DOMAIN_ID: &str = "exadev.io/gitiverse";

/// Capability verb granting read access (clone, fetch, inspect refs, read public/private metadata, read checks).
pub const CAP_READ: &str = "exadev.io/gitiverse:read";

/// Capability verb granting write access (push packs, update refs, publish COB operations).
pub const CAP_WRITE: &str = "exadev.io/gitiverse:write";

/// Capability verb granting maintainer authority (governance updates, policy changes, force/protected ref updates).
pub const CAP_MAINTAIN: &str = "exadev.io/gitiverse:maintain";

/// Capability verb granting CI runner authority to submit signed check attestations.
pub const CAP_CI: &str = "exadev.io/gitiverse:ci";

/// Canonical string prefix for formatted repository identifiers.
pub const REPO_ID_PREFIX: &str = "gitiverse:";

const ID_BYTE_LEN: usize = 32;
const ID_HEX_LEN: usize = ID_BYTE_LEN * 2;

/// Failure returned when parsing a [`RepoId`] or [`ActorId`] from text.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum IdParseError {
    #[error("repository identifier must start with 'gitiverse:'")]
    MissingPrefix,
    #[error("expected {expected} lowercase hex characters, found {found}")]
    InvalidHexLength { expected: usize, found: usize },
    #[error("identifier contains non-hex or uppercase characters")]
    InvalidHex,
}

fn parse_lowercase_hex_32(s: &str) -> Result<[u8; ID_BYTE_LEN], IdParseError> {
    if s.len() != ID_HEX_LEN {
        return Err(IdParseError::InvalidHexLength {
            expected: ID_HEX_LEN,
            found: s.len(),
        });
    }
    if !s
        .bytes()
        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
    {
        return Err(IdParseError::InvalidHex);
    }
    let decoded = hex::decode(s).map_err(|_| IdParseError::InvalidHex)?;
    let arr: [u8; ID_BYTE_LEN] =
        decoded
            .try_into()
            .map_err(|v: Vec<u8>| IdParseError::InvalidHexLength {
                expected: ID_HEX_LEN,
                found: v.len() * 2,
            })?;
    Ok(arr)
}

/// Content-derived 32-byte identifier for a `gitiverse` repository, formatted as `gitiverse:<64-lowercase-hex>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RepoId(pub [u8; ID_BYTE_LEN]);

impl RepoId {
    pub const SIZE: usize = ID_BYTE_LEN;

    #[must_use]
    pub const fn from_bytes(bytes: [u8; ID_BYTE_LEN]) -> Self {
        Self(bytes)
    }

    #[must_use]
    pub const fn as_bytes(&self) -> &[u8; ID_BYTE_LEN] {
        &self.0
    }

    #[must_use]
    pub fn to_hex(&self) -> String {
        hex::encode(self.0)
    }

    pub fn from_hex(hex_str: &str) -> Result<Self, IdParseError> {
        parse_lowercase_hex_32(hex_str).map(Self)
    }
}

impl AsRef<[u8]> for RepoId {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl fmt::Display for RepoId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{REPO_ID_PREFIX}{}", self.to_hex())
    }
}

impl FromStr for RepoId {
    type Err = IdParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let hex_part = s
            .strip_prefix(REPO_ID_PREFIX)
            .ok_or(IdParseError::MissingPrefix)?;
        Self::from_hex(hex_part)
    }
}

impl Serialize for RepoId {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for RepoId {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Self::from_str(&s).map_err(serde::de::Error::custom)
    }
}

impl Encode<()> for RepoId {
    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>> {
        e.bytes(&self.0)?.ok()
    }
}

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

pub(crate) fn decode_repo_id(d: &mut Decoder<'_>) -> Result<RepoId, DecodeError> {
    let bytes = strict::bytes_value(d)?;
    let arr: [u8; ID_BYTE_LEN] =
        bytes
            .try_into()
            .map_err(|v: Vec<u8>| DecodeError::InvalidLength {
                field: "repo-id",
                expected: ID_BYTE_LEN,
                found: v.len(),
            })?;
    Ok(RepoId(arr))
}

/// Cryptographic identity of a `gitiverse` participant (author, maintainer, founder, or runner), wrapping a `wire-mesh` [`DeviceId`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ActorId(pub DeviceId);

impl ActorId {
    pub const SIZE: usize = DeviceId::SIZE;

    #[must_use]
    pub const fn from_device_id(device_id: DeviceId) -> Self {
        Self(device_id)
    }

    #[must_use]
    pub const fn from_bytes(bytes: [u8; ID_BYTE_LEN]) -> Self {
        Self(DeviceId(bytes))
    }

    #[must_use]
    pub const fn as_device_id(&self) -> &DeviceId {
        &self.0
    }

    #[must_use]
    pub const fn as_bytes(&self) -> &[u8; ID_BYTE_LEN] {
        &self.0.0
    }

    #[must_use]
    pub fn to_hex(&self) -> String {
        hex::encode(self.0.0)
    }

    pub fn from_hex(hex_str: &str) -> Result<Self, IdParseError> {
        parse_lowercase_hex_32(hex_str).map(|arr| Self(DeviceId(arr)))
    }
}

impl From<DeviceId> for ActorId {
    fn from(value: DeviceId) -> Self {
        Self(value)
    }
}

impl From<ActorId> for DeviceId {
    fn from(value: ActorId) -> Self {
        value.0
    }
}

impl AsRef<[u8]> for ActorId {
    fn as_ref(&self) -> &[u8] {
        &self.0.0
    }
}

impl fmt::Display for ActorId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_hex())
    }
}

impl FromStr for ActorId {
    type Err = IdParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_hex(s)
    }
}

impl Serialize for ActorId {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for ActorId {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Self::from_str(&s).map_err(serde::de::Error::custom)
    }
}

impl Encode<()> for ActorId {
    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>> {
        self.0.encode(e, ctx)
    }
}

impl Decode<'_, ()> for ActorId {
    fn decode(
        d: &mut Decoder<'_>,
        ctx: &mut (),
    ) -> Result<Self, wire_mesh_wire::minicbor::decode::Error> {
        DeviceId::decode(d, ctx).map(Self)
    }
}

/// Serde adapter for `wire_mesh_wire::identity::DeviceId` encoded as 64 lowercase hex characters.
pub mod serde_device_id {
    use super::*;

    pub fn serialize<S: Serializer>(id: &DeviceId, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&hex::encode(id.0))
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<DeviceId, D::Error> {
        let s = String::deserialize(deserializer)?;
        parse_lowercase_hex_32(&s)
            .map(DeviceId)
            .map_err(serde::de::Error::custom)
    }
}

/// Serde adapter for `wire_mesh_wire::identity::IdentityKey` with lowercase hex `public_key`.
pub mod serde_identity_key {
    use super::*;
    use wire_mesh_wire::identity::IdentityKey;

    #[derive(Serialize, Deserialize)]
    struct WireIdentityKey<'a> {
        alg: i64,
        #[serde(borrow)]
        public_key: &'a str,
    }

    #[derive(Serialize)]
    struct WireIdentityKeyOwned {
        alg: i64,
        public_key: String,
    }

    pub fn serialize<S: Serializer>(key: &IdentityKey, serializer: S) -> Result<S::Ok, S::Error> {
        let repr = WireIdentityKeyOwned {
            alg: key.alg,
            public_key: hex::encode(&key.public_key),
        };
        repr.serialize(serializer)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<IdentityKey, D::Error> {
        let repr = WireIdentityKey::deserialize(deserializer)?;
        if !repr
            .public_key
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
        {
            return Err(serde::de::Error::custom("public_key must be lowercase hex"));
        }
        let public_key = hex::decode(repr.public_key).map_err(serde::de::Error::custom)?;
        Ok(IdentityKey {
            alg: repr.alg,
            public_key,
        })
    }
}

/// Serde adapter for arbitrary byte vectors serialised as lowercase hex.
pub mod serde_hex_bytes {
    use super::*;

    pub fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&hex::encode(bytes))
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
        let s = String::deserialize(deserializer)?;
        if !s
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
        {
            return Err(serde::de::Error::custom("expected lowercase hex string"));
        }
        hex::decode(&s).map_err(serde::de::Error::custom)
    }
}

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

    #[test]
    fn capability_verbs_pass_wire_mesh_grammar() {
        for verb in [CAP_READ, CAP_WRITE, CAP_MAINTAIN, CAP_CI] {
            assert_eq!(CapabilityVerb::validate(verb), Ok(()), "{verb}");
        }
    }

    #[test]
    fn repo_id_display_parse_and_cbor_round_trip() {
        let id = RepoId::from_bytes([0xAB; 32]);
        let formatted = id.to_string();
        assert_eq!(formatted, format!("gitiverse:{}", "ab".repeat(32)));
        assert_eq!(RepoId::from_str(&formatted).unwrap(), id);

        let json = serde_json::to_string(&id).unwrap();
        assert_eq!(serde_json::from_str::<RepoId>(&json).unwrap(), id);

        let cbor = to_vec(&id);
        assert_eq!(decode_exact::<RepoId>(&cbor).unwrap(), id);
    }

    #[test]
    fn repo_id_rejects_malformed_inputs() {
        let valid_hex = "ab".repeat(32);
        assert_eq!(
            RepoId::from_str(&valid_hex),
            Err(IdParseError::MissingPrefix)
        );
        assert_eq!(
            RepoId::from_str(&format!("gitiverse:{}", "AB".repeat(32))),
            Err(IdParseError::InvalidHex)
        );
        assert_eq!(
            RepoId::from_str("gitiverse:abcd"),
            Err(IdParseError::InvalidHexLength {
                expected: 64,
                found: 4,
            })
        );
    }

    #[test]
    fn actor_id_round_trips_text_json_and_cbor() {
        let actor = ActorId::from_bytes([0x42; 32]);
        let text = actor.to_string();
        assert_eq!(text, "42".repeat(32));
        assert_eq!(ActorId::from_str(&text).unwrap(), actor);
        assert_eq!(
            ActorId::from_str(&"42".repeat(31)),
            Err(IdParseError::InvalidHexLength {
                expected: 64,
                found: 62
            })
        );

        let json = serde_json::to_string(&actor).unwrap();
        assert_eq!(serde_json::from_str::<ActorId>(&json).unwrap(), actor);

        let cbor = to_vec(&actor);
        assert_eq!(decode_exact::<ActorId>(&cbor).unwrap(), actor);
    }
}