sigstore-types 0.2.0

Core types and data structures for Sigstore
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! Encoding helpers and concrete types for sigstore
//!
//! This module provides concrete types with semantic meaning that handle
//! encoding/decoding internally. Each type represents a specific kind of data
//! and serializes appropriately (usually as base64).
//!
//! The design philosophy is:
//! - Use concrete newtype wrappers with semantic meaning
//! - Types handle their own encoding/decoding via serde
//! - Clear type names prevent mixing up different kinds of data

use crate::error::{Error, Result};
use base64::Engine;
use serde::{Deserialize, Serialize};

// ============================================================================
// Serde helper modules (for use with raw Vec<u8> when needed)
// ============================================================================

/// Serde helper for base64 encoding/decoding of byte arrays
///
/// Use this with `#[serde(with = "base64_bytes")]` on `Vec<u8>` fields.
pub mod base64_bytes {
    use base64::{engine::general_purpose::STANDARD, Engine};
    use serde::{Deserialize, Deserializer, Serializer};

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

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        STANDARD.decode(s).map_err(serde::de::Error::custom)
    }
}

/// Serde helper for optional base64 encoding/decoding
pub mod base64_bytes_option {
    use base64::{engine::general_purpose::STANDARD, Engine};
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(bytes: &Option<Vec<u8>>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match bytes {
            Some(b) => serializer.serialize_some(&STANDARD.encode(b)),
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Vec<u8>>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt: Option<String> = Option::deserialize(deserializer)?;
        match opt {
            Some(s) => STANDARD
                .decode(s)
                .map(Some)
                .map_err(serde::de::Error::custom),
            None => Ok(None),
        }
    }
}

/// Serde helper for hex encoding/decoding of byte arrays
pub mod hex_bytes {
    use serde::{Deserialize, Deserializer, Serializer};

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

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        hex::decode(s).map_err(serde::de::Error::custom)
    }
}

// ============================================================================
// Macro for creating base64-encoded newtype wrappers
// ============================================================================

macro_rules! base64_newtype {
    ($(#[$meta:meta])* $name:ident) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
        pub struct $name(Vec<u8>);

        impl $name {
            /// Create from raw bytes
            pub fn new(bytes: Vec<u8>) -> Self {
                Self(bytes)
            }

            /// Create from a byte slice
            pub fn from_bytes(bytes: &[u8]) -> Self {
                Self(bytes.to_vec())
            }

            /// Create from base64-encoded string
            pub fn from_base64(s: &str) -> Result<Self> {
                let bytes = base64::engine::general_purpose::STANDARD
                    .decode(s)
                    .map_err(|e| Error::InvalidEncoding(format!("invalid base64: {}", e)))?;
                Ok(Self(bytes))
            }

            /// Encode as base64 string
            pub fn to_base64(&self) -> String {
                base64::engine::general_purpose::STANDARD.encode(&self.0)
            }

            /// Get the raw bytes
            pub fn as_bytes(&self) -> &[u8] {
                &self.0
            }

            /// Consume and return the inner bytes
            pub fn into_bytes(self) -> Vec<u8> {
                self.0
            }

            /// Get the length in bytes
            pub fn len(&self) -> usize {
                self.0.len()
            }

            /// Check if empty
            pub fn is_empty(&self) -> bool {
                self.0.is_empty()
            }
        }

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

        impl From<Vec<u8>> for $name {
            fn from(bytes: Vec<u8>) -> Self {
                Self(bytes)
            }
        }

        impl From<&[u8]> for $name {
            fn from(bytes: &[u8]) -> Self {
                Self(bytes.to_vec())
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.to_base64())
            }
        }

        impl serde::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serializer.serialize_str(&self.to_base64())
            }
        }

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

// ============================================================================
// Concrete Types for Different Kinds of Binary Data
// ============================================================================

base64_newtype!(
    /// DER-encoded X.509 certificate bytes
    ///
    /// This type represents a certificate in DER format (binary ASN.1).
    /// Serializes as base64 in JSON.
    DerCertificate
);

base64_newtype!(
    /// DER-encoded public key bytes (SubjectPublicKeyInfo format)
    ///
    /// This type represents a public key in DER format.
    /// Serializes as base64 in JSON.
    DerPublicKey
);

base64_newtype!(
    /// Cryptographic signature bytes
    ///
    /// This type represents raw signature bytes (format depends on algorithm).
    /// Serializes as base64 in JSON.
    SignatureBytes
);

base64_newtype!(
    /// DSSE payload bytes
    ///
    /// This type represents the payload content of a DSSE envelope.
    /// Serializes as base64 in JSON.
    PayloadBytes
);

base64_newtype!(
    /// Canonicalized Rekor entry body
    ///
    /// This type represents the canonicalized JSON body of a Rekor log entry.
    /// Serializes as base64 in JSON.
    CanonicalizedBody
);

base64_newtype!(
    /// Signed Entry Timestamp (SET) bytes
    ///
    /// This type represents a signed timestamp from the transparency log.
    /// Serializes as base64 in JSON.
    SignedTimestamp
);

base64_newtype!(
    /// RFC 3161 timestamp token bytes
    ///
    /// This type represents a DER-encoded RFC 3161 timestamp response.
    /// Serializes as base64 in JSON.
    TimestampToken
);

base64_newtype!(
    /// PEM-encoded content (double-encoded in base64)
    ///
    /// This type represents PEM text that gets base64-encoded for JSON.
    /// Used when APIs expect base64-encoded PEM strings.
    PemContent
);

// ============================================================================
// Identifier Types (String Wrappers for Semantic Clarity)
// ============================================================================

/// UUID for a Rekor log entry
///
/// This is the unique identifier for an entry in the transparency log.
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct EntryUuid(String);

impl EntryUuid {
    pub fn new(s: String) -> Self {
        EntryUuid(s)
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn into_string(self) -> String {
        self.0
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl From<String> for EntryUuid {
    fn from(s: String) -> Self {
        EntryUuid::new(s)
    }
}

impl AsRef<str> for EntryUuid {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

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

/// Transparency log index (numeric string)
///
/// Represents a log index in the transparency log.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct LogIndex(String);

impl LogIndex {
    pub fn new(s: String) -> Self {
        LogIndex(s)
    }

    pub fn from_u64(index: u64) -> Self {
        LogIndex(index.to_string())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn into_string(self) -> String {
        self.0
    }

    pub fn as_u64(&self) -> Result<u64> {
        self.0
            .parse()
            .map_err(|e| Error::InvalidEncoding(format!("invalid log index '{}': {}", self.0, e)))
    }
}

impl From<String> for LogIndex {
    fn from(s: String) -> Self {
        LogIndex::new(s)
    }
}

impl From<u64> for LogIndex {
    fn from(index: u64) -> Self {
        LogIndex::from_u64(index)
    }
}

impl AsRef<str> for LogIndex {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

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

/// Transparency log key ID
///
/// Base64-encoded identifier for a transparency log (typically SHA-256 of public key).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct LogKeyId(String);

impl LogKeyId {
    pub fn new(s: String) -> Self {
        LogKeyId(s)
    }

    /// Create from raw bytes (will be base64-encoded)
    pub fn from_bytes(bytes: &[u8]) -> Self {
        LogKeyId(base64::engine::general_purpose::STANDARD.encode(bytes))
    }

    /// Decode to raw bytes
    pub fn decode(&self) -> Result<Vec<u8>> {
        base64::engine::general_purpose::STANDARD
            .decode(&self.0)
            .map_err(|e| Error::InvalidEncoding(format!("invalid base64 in log key id: {}", e)))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn into_string(self) -> String {
        self.0
    }
}

impl From<String> for LogKeyId {
    fn from(s: String) -> Self {
        LogKeyId::new(s)
    }
}

impl AsRef<str> for LogKeyId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

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

/// Key ID for signature key identification
///
/// Optional hint used in DSSE to identify which key was used for signing.
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct KeyId(String);

impl KeyId {
    pub fn new(s: String) -> Self {
        KeyId(s)
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn into_string(self) -> String {
        self.0
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl From<String> for KeyId {
    fn from(s: String) -> Self {
        KeyId::new(s)
    }
}

impl AsRef<str> for KeyId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

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

// ============================================================================
// SHA-256 Hash Type (Fixed Size)
// ============================================================================

/// SHA-256 hash digest (32 bytes)
///
/// Fixed-size hash with compile-time size guarantees.
/// Serializes as base64, deserializes from either hex (64 chars) or base64.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Sha256Hash([u8; 32]);

impl Sha256Hash {
    pub fn from_bytes(bytes: [u8; 32]) -> Self {
        Sha256Hash(bytes)
    }

    pub fn try_from_slice(bytes: &[u8]) -> Result<Self> {
        if bytes.len() != 32 {
            return Err(Error::InvalidEncoding(format!(
                "SHA-256 hash must be 32 bytes, got {}",
                bytes.len()
            )));
        }
        let mut arr = [0u8; 32];
        arr.copy_from_slice(bytes);
        Ok(Sha256Hash(arr))
    }

    pub fn from_hex(hex_str: &str) -> Result<Self> {
        let bytes = hex::decode(hex_str)
            .map_err(|e| Error::InvalidEncoding(format!("invalid hex: {}", e)))?;
        Self::try_from_slice(&bytes)
    }

    pub fn from_base64(s: &str) -> Result<Self> {
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(s)
            .map_err(|e| Error::InvalidEncoding(format!("invalid base64: {}", e)))?;
        Self::try_from_slice(&bytes)
    }

    /// Parse from hex or base64 string (auto-detect format)
    pub fn from_hex_or_base64(s: &str) -> Result<Self> {
        if s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit()) {
            return Self::from_hex(s);
        }
        Self::from_base64(s)
    }

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

    pub fn to_base64(&self) -> String {
        base64::engine::general_purpose::STANDARD.encode(self.0)
    }

    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    pub fn as_slice(&self) -> &[u8] {
        &self.0
    }
}

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

impl From<[u8; 32]> for Sha256Hash {
    fn from(bytes: [u8; 32]) -> Self {
        Sha256Hash(bytes)
    }
}

impl serde::Serialize for Sha256Hash {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_base64())
    }
}

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

// ============================================================================
// Hex-Encoded Log ID (for Rekor V1 API compatibility)
// ============================================================================

/// Hex-encoded transparency log ID
///
/// The Rekor V1 API returns log IDs as hex-encoded strings.
/// This type handles the hex encoding and can convert to base64 for bundles.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct HexLogId(String);

impl HexLogId {
    pub fn new(s: String) -> Self {
        HexLogId(s)
    }

    /// Create from raw bytes (will be hex-encoded)
    pub fn from_bytes(bytes: &[u8]) -> Self {
        HexLogId(hex::encode(bytes))
    }

    /// Decode to raw bytes
    pub fn decode(&self) -> Result<Vec<u8>> {
        hex::decode(&self.0).map_err(|e| Error::InvalidEncoding(format!("invalid hex: {}", e)))
    }

    /// Convert to base64 encoding (for bundle format)
    pub fn to_base64(&self) -> Result<String> {
        let bytes = self.decode()?;
        Ok(base64::engine::general_purpose::STANDARD.encode(&bytes))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn into_string(self) -> String {
        self.0
    }
}

impl From<String> for HexLogId {
    fn from(s: String) -> Self {
        HexLogId::new(s)
    }
}

impl AsRef<str> for HexLogId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

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

// ============================================================================
// Hex-Encoded Hash (for Rekor V1 API)
// ============================================================================

/// Hex-encoded hash value
///
/// Used in Rekor V1 API responses where hashes are hex-encoded.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct HexHash(String);

impl HexHash {
    pub fn new(s: String) -> Self {
        HexHash(s)
    }

    pub fn from_bytes(bytes: &[u8]) -> Self {
        HexHash(hex::encode(bytes))
    }

    pub fn decode(&self) -> Result<Vec<u8>> {
        hex::decode(&self.0).map_err(|e| Error::InvalidEncoding(format!("invalid hex: {}", e)))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn into_string(self) -> String {
        self.0
    }

    /// Convert to Sha256Hash (validates length)
    pub fn to_sha256(&self) -> Result<Sha256Hash> {
        Sha256Hash::from_hex(&self.0)
    }
}

impl From<String> for HexHash {
    fn from(s: String) -> Self {
        HexHash::new(s)
    }
}

impl AsRef<str> for HexHash {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_der_certificate_roundtrip() {
        let cert = DerCertificate::from_bytes(b"fake cert data");
        let json = serde_json::to_string(&cert).unwrap();
        let decoded: DerCertificate = serde_json::from_str(&json).unwrap();
        assert_eq!(cert, decoded);
    }

    #[test]
    fn test_signature_bytes_roundtrip() {
        let sig = SignatureBytes::from_bytes(b"fake signature");
        let json = serde_json::to_string(&sig).unwrap();
        let decoded: SignatureBytes = serde_json::from_str(&json).unwrap();
        assert_eq!(sig, decoded);
    }

    #[test]
    fn test_sha256_hash() {
        let hash_hex = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
        let hash = Sha256Hash::from_hex(hash_hex).unwrap();
        assert_eq!(hash.to_hex(), hash_hex);

        // Can also deserialize from hex
        let json_hex = format!("\"{}\"", hash_hex);
        let from_hex: Sha256Hash = serde_json::from_str(&json_hex).unwrap();
        assert_eq!(hash, from_hex);
    }

    #[test]
    fn test_hex_log_id() {
        let bytes = vec![1, 2, 3, 4];
        let log_id = HexLogId::from_bytes(&bytes);
        assert_eq!(log_id.as_str(), "01020304");
        assert_eq!(log_id.decode().unwrap(), bytes);
        assert_eq!(log_id.to_base64().unwrap(), "AQIDBA==");
    }

    #[test]
    fn test_log_key_id() {
        let bytes = vec![1, 2, 3, 4];
        let key_id = LogKeyId::from_bytes(&bytes);
        assert_eq!(key_id.decode().unwrap(), bytes);
    }
}