suit_validator 0.1.3

no_std-friendly Rust crate for decoding and verifying SUIT Manifest.
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! SUIT Manifest Data Structures
//!
//! This module defines the CBOR structures for SUIT manifests according to
//! [Section 8 of the SUIT Specification](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8).
//!
//! # Core Structures
//!
//! - [`SuitEnvelope`]: Top-level container with authentication and optional payloads
//! - [`SuitManifest`]: The manifest itself containing metadata and command sequences
//! - [`SuitCommon`]: Shared metadata and commands reused across sequences
//! - [`SuitCommandSequence`]: Lists of conditions and directives
//! - [`SuitSharedSequence`]:  Command sequence executed before each command sequence.
//! - [`SuitDigest`]: Cryptographic integrity checks
//!
//! # Encoded Forms
//!
//! Most complex structures are wrapped in `bstr` (byte string) for:
//! - Clarity of parsing boundaries
//! - Efficient integrity checking
//! - Support for severable elements
//!
//! # References
//!
//! - [SUIT Spec: Envelope (Section 8.2)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.2)
//! - [SUIT Spec: Manifest (Section 8.4)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4)

use crate::{SuitError, flat_seq::FlatSequence};
use minicbor::{Decode, Encode, bytes::ByteSlice, decode};
use suit_cbor::{bstr_wrapper, errors::CborError, iter_wrapper};

type Rfc4122Uuid = [u8; 16];

/* -------------------------------------------------------------------------- */
/*                    bstr Wrappers exposed to the public api                 */
/* -------------------------------------------------------------------------- */
bstr_wrapper!(BstrSuitAuthentication, SuitAuthentication<'a>);
bstr_wrapper!(BstrSuitDigest, SuitDigest<'a>);
bstr_wrapper!(BstrSuitCommon, SuitCommon<'a>);
bstr_wrapper!(BstrSuitCommandSequence, SuitCommandSequence<'a>);
bstr_wrapper!(BstrSuitTextMap, SuitTextMap<'a>);
bstr_wrapper!(BstrSuitManifest, SuitManifest<'a>);
bstr_wrapper!(BstrSuitSharedSequence, SuitSharedSequence<'a>);
/* -------------------------------------------------------------------------- */
/*             lazy iterable element Wrappers exposed to the public api       */
/* -------------------------------------------------------------------------- */
iter_wrapper!(
    IterableSuitSeverableManifestMember,
    SuitSeverableManifestMembers<'a>
);
iter_wrapper!(IterableSuitPayload, SuitPayload<'a>);
iter_wrapper!(IterableComponentIdentifier, SuitComponentIdentifier<'a>);
iter_wrapper!(IterableByteSlice, &'a ByteSlice);
iter_wrapper!(IterableU64, u64);
iter_wrapper!(IterBstrSuitSharedSequence, BstrSuitSharedSequence<'a>);
iter_wrapper!(IterBstrSuitCommandSequence, BstrSuitCommandSequence<'a>);
iter_wrapper!(IterSuitTextComponentPair, SuitTextComponentPair<'a>);
iter_wrapper!(IterSuitTagAndTextLmap, (Tag38LTag<'a>, SuitTextLMap<'a>));

// Wrapping structure helper to show the inner cbor structure you are trying to decode
// ! Make sure it doesn't exists anymore on release
#[cfg(debug_assertions)]
#[allow(dead_code)]
#[derive(Encode, Debug)]
#[cbor(transparent)]
pub struct Debug<T>(pub T);

/// SUIT Envelope - Top-level container with authentication and optional elements.
///
/// The envelope wraps the manifest with cryptographic authentication, optional severable
/// elements, and integrated payloads. All elements are byte-string wrapped for clear
/// parsing boundaries and integrity verification.
///
/// # Mandatory Fields
///
/// - `wrapper`: COSE authentication block containing digest and signature
/// - `manifest`: The manifest itself with version, sequence, and command sequences
///
/// # Optional Elements
///
/// - `manifest_members`: Severable elements that can be removed from the envelope
///   (fetch, install, text) while maintaining signature validity
/// - `payload`: Integrated payloads bundled within the envelope
///
/// # References
///
/// - [SUIT Spec: Envelope (Section 8.2)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.2)
/// - [SUIT Spec: Severable Elements (Section 8.6)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.6)
#[derive(Debug, Encode, Decode)]
#[cbor(map)]
pub struct SuitEnvelope<'a> {
    /// Authentication wrapper with COSE signature and digest (always present)
    #[b(2)] // we borrow a bstr so we need #[b()] instead of #[n()]
    pub(crate) wrapper: BstrSuitAuthentication<'a>,
    /// The manifest itself (always present, required to implement per Section 8.4)
    #[b(3)]
    pub manifest: BstrSuitManifest<'a>,
    /// Optional severable elements (fetch, install, text) - can be removed from envelope
    #[n(4)]
    manifest_members: Option<IterableSuitSeverableManifestMember<'a>>,
    /// Optional integrated payloads bundled within the envelope (Section 5.5)
    #[n(5)]
    pub payload: Option<IterableSuitPayload<'a>>,
}

/// Integrated payload within the envelope.
///
/// Payloads can be bundled directly in the manifest envelope for small datasets.
/// URIs reference these payloads using fragment identifiers (e.g., "#name.bin").
///
/// # References
///
/// - [SUIT Spec: Integrated Payloads (Section 5.5)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-5.5)
#[derive(Debug, Encode, Decode)]
pub struct SuitPayload<'a> {
    #[n(0)]
    pub key: &'a str,
    #[cbor(n(1), with = "minicbor::bytes")]
    pub value: &'a [u8],
}

/// Authentication wrapper - COSE signature and manifest digest.
///
/// This structure contains:
/// 1. A digest of the manifest bytes (for TOCTOU protection)
/// 2. One or more COSE authentication blocks (COSE_Sign, COSE_Mac, etc.)
///
/// Per Section 8.3, the digest **MUST** be verified before cryptographic computation
/// to prevent Time-of-Check to Time-of-Use (TOCTOU) attacks.
///
/// # References
///
/// - [SUIT Spec: Authentication (Section 8.3)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.3)
/// - [RFC 9124: Security Considerations (Section 4.3.30)](https://www.rfc-editor.org/rfc/rfc9124#section-4.3.30)
#[derive(Debug, Encode, Decode)]
#[cbor(array)]
pub(crate) struct SuitAuthentication<'a> {
    #[cbor(b(0), with = "minicbor::bytes")] // we will treat it directly so Bstr is not needed
    pub(crate) digest: &'a [u8],
    #[cbor(b(1), with = "minicbor::bytes")] // we will treat it directly so Bstr is not needed
    pub(crate) authentication_block: &'a [u8], // we only support one authentication block
}

impl SuitAuthentication<'_> {
    /// Verify the digest of the [`SuitAuthentication`] block (computed) over bstr wrapped
    ///  [`SuitEnvelope::manifest`] bytes.
    pub(crate) fn suit_verify_digest(&self, manifest_bytes: &[u8]) -> Result<(), SuitError> {
        let digest: SuitDigest = decode(self.digest)?;
        digest.suit_verify_digest(manifest_bytes)
    }
}

/// Cryptographic digest for integrity verification.
///
/// Supports multiple hash algorithms as defined in the COSE Algorithms registry.
/// SHA-256 is mandatory to implement; others are optional.
///
/// # Supported Algorithms
///
/// | Algorithm | ID | Status |
/// |-----------|----|----|
/// | SHA-256 | -16 | Mandatory |
/// | SHA-384 | -43 | Optional |
/// | SHA-512 | -44 | Optional |
/// | SHAKE128 | -18 | Not Supported |
/// | SHAKE256 | -45 | Not Supported |
///
/// # References
///
/// - [SUIT Spec: Digest Container (Section 10)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-10)
/// - [COSE Algorithms (RFC 9054)](https://www.rfc-editor.org/rfc/rfc9054#section-8)
#[derive(Debug, Encode, Decode)]
#[cbor(array)]
pub struct SuitDigest<'a> {
    #[n(0)]
    pub hash_alg: HashAlg,
    #[cbor(b(1), with = "minicbor::bytes")]
    pub bytes: &'a [u8],
}

#[derive(Debug, Encode, Decode)]
#[cbor(index_only)]
pub enum HashAlg {
    #[n(-16)]
    Sha256,
    #[n(-18)]
    Shake128,
    #[n(-43)]
    Sha384,
    #[n(-44)]
    Sha512,
    #[n(-45)]
    Shake256,
}

impl SuitDigest<'_> {
    /// Verify a Suit Digest computed over a `buffer`.
    ///
    /// Supports Sha256, Sha384, Sha512
    pub fn suit_verify_digest(&self, buffer: &[u8]) -> Result<(), SuitError> {
        match self.hash_alg {
            HashAlg::Sha256 => self.verify_sha256(buffer),
            HashAlg::Sha384 => self.verify_sha384(buffer),
            HashAlg::Sha512 => self.verify_sha512(buffer),
            HashAlg::Shake128 => Err(SuitError::unexpected_hash_alg(-18)),
            HashAlg::Shake256 => Err(SuitError::unexpected_hash_alg(-45)),
        }
    }

    /// Verify a Suit Digest computed over a `buffer` with Sha256.
    fn verify_sha256(&self, buffer: &[u8]) -> Result<(), SuitError> {
        use sha2::{Digest, Sha256};
        use subtle::ConstantTimeEq;
        let mut hasher = Sha256::new();

        hasher.update(buffer);
        let finalized = hasher.finalize();
        let computed = finalized;

        if computed.ct_eq(self.bytes).unwrap_u8() == 1 {
            Ok(())
        } else {
            Err(SuitError::invalid_digest())
        }
    }

    /// Verify a Suit Digest computed over a `buffer` with Sha384.
    fn verify_sha384(&self, buffer: &[u8]) -> Result<(), SuitError> {
        use sha2::Sha384;
        use sha3::Digest;
        use subtle::ConstantTimeEq;

        let mut hasher = Sha384::new();

        hasher.update(buffer);
        let finalized = hasher.finalize();
        let computed = finalized;

        if computed.ct_eq(self.bytes).unwrap_u8() == 1 {
            Ok(())
        } else {
            Err(SuitError::default())
        }
    }

    /// Verify a Suit Digest computed over a `buffer` with Sha512.
    fn verify_sha512(&self, buffer: &[u8]) -> Result<(), SuitError> {
        use sha2::Sha512;
        use sha3::Digest;
        use subtle::ConstantTimeEq;

        let mut hasher = Sha512::new();

        hasher.update(buffer);
        let finalized = hasher.finalize();
        let computed = finalized;

        if computed.ct_eq(self.bytes).unwrap_u8() == 1 {
            Ok(())
        } else {
            Err(SuitError::default())
        }
    }
}

/// SUIT Manifest - Primary metadata for firmware updates or trusted invocation.
///
/// Contains version, sequence number, and the command sequences that define
/// the update or invocation process. All manifest elements are scoped to specific
/// components identified in the common section.
///
/// # Mandatory Fields
///
/// - `version`: Must be 1 (Section 8.4.1)
/// - `sequence_number`: Monotonically increasing anti-rollback counter (Section 8.4.2)
/// - `common`: Shared components and commands for all sequences (Section 8.4.5)
///
/// # Command Sequences
///
/// The manifest defines up to 5 optional command sequences:
///
/// | Sequence | Purpose | Update | Invocation |
/// |----------|---------|--------|-----------|
/// | validate | Verify installation | ✓ | ✓ |
/// | load | Prepare for execution | | ✓ |
/// | invoke | Transfer control | | ✓ |
/// | payload_fetch | Obtain resources | ✓ | |
/// | install | Apply installation | ✓ | |
///
/// See Section 8.4.6 of the SUIT specification for sequence execution order.
///
/// # References
///
/// - [SUIT Spec: Manifest Structure (Section 8.4)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4)
/// - [SUIT Spec: Update Procedure (Section 6.1)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-6.1)
#[derive(Debug, Encode, Decode)]
#[cbor(map)]
pub struct SuitManifest<'a> {
    #[n(1)]
    pub version: u64, // must be 1

    #[n(2)]
    pub sequence_number: u64,

    #[b(3)] // we borrow a bstr so we need #[b()] instead of #[n()]
    pub common: BstrSuitCommon<'a>,

    #[n(4)]
    pub reference_uri: Option<&'a str>,

    // Unseverable members (top-level keys in manifest: 7,8,9)
    // SUIT_Unseverable_Members are not under a single key: they are individual optional keys.
    #[b(7)]
    pub validate: Option<BstrSuitCommandSequence<'a>>, // ? suit-validate

    #[b(8)]
    pub load: Option<BstrSuitCommandSequence<'a>>, // ? suit-load

    #[b(9)]
    pub invoke: Option<BstrSuitCommandSequence<'a>>, // ? suit-invoke

    // Severable members choice (top-level keys: 16,20,23)
    // each may be a Digest or a bstr.cbor SUIT_Command_Sequence / SUIT_Text_Map
    #[b(16)]
    pub payload_fetch: Option<DigestOrCbor<'a, BstrSuitCommandSequence<'a>>>,

    #[b(20)]
    pub install: Option<DigestOrCbor<'a, BstrSuitCommandSequence<'a>>>,

    #[b(23)]
    pub text: Option<DigestOrCbor<'a, BstrSuitTextMap<'a>>>,
    // Any future extensions will be ignored/omitted by derive (or add a catch-all decode if needed)
}

#[derive(Debug, Encode, Decode)]
#[cbor(map)]
pub struct SuitSeverableManifestMembers<'a> {
    #[b(16)]
    pub payload_fetch: Option<BstrSuitCommandSequence<'a>>,

    #[b(20)]
    pub install: Option<BstrSuitCommandSequence<'a>>,

    #[b(23)]
    pub text: Option<BstrSuitTextMap<'a>>,
}

#[derive(Debug, Encode, Decode)]
#[cbor(map)]
pub struct SuitIntegratedPayload<'a> {
    #[cbor(n(0), with = "minicbor::bytes")]
    pub key: &'a [u8],
    #[n(1)]
    pub value: &'a str,
}

/// Severable element encoding - either a digest or wrapped CBOR object.
///
/// Allows command sequences and text sections to be severable from the manifest.
/// A digest is included in the manifest; the actual content is in the envelope.
/// This reduces manifest size while maintaining integrity.
///
/// # Variants
///
/// - `Digest`: SUIT_Digest referencing content in the envelope
/// - `Cbor`: Inline content when not severable
///
/// # References
///
/// - [SUIT Spec: Severable Elements (Section 8.6)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.6)
#[derive(Debug, Encode)]
pub enum DigestOrCbor<'a, T: 'a> {
    #[n(1)]
    Digest(#[n(0)] SuitDigest<'a>),
    #[n(2)]
    Cbor(#[n(0)] T),
}

/// Common metadata shared across all command sequences in a manifest.
///
/// Contains the list of components targeted by this manifest and the shared command
/// sequence that executes prior to each other sequence. This reduces manifest size
/// by allowing reusable parameters and commands.
///
/// # Execution Order
///
/// For each command sequence (fetch, install, validate, load, invoke):
/// 1. Common sequence executes first (if present)
/// 2. Then the specific sequence executes
///
/// Per Section 8.4.5, the common sequence **MUST NOT** have side effects beyond
/// setting parameter values.
///
/// # References
///
/// - [SUIT Spec: Common (Section 8.4.5)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4.5)
/// - [SUIT Spec: Metadata Overview (Section 5.3.2)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-5.3.2)
#[derive(Debug, Encode, Decode)]
#[cbor(map)]
pub struct SuitCommon<'a> {
    #[n(2)]
    pub components: SuitComponents<'a>,
    #[b(4)] // we borrow bstr
    pub shared_seq: Option<BstrSuitSharedSequence<'a>>,
}
#[derive(Debug, Encode, Decode)]
#[cbor(transparent)]
pub struct SuitComponents<'a>(#[cbor(borrow)] IterableComponentIdentifier<'a>); // += at least 1

impl<'a> SuitComponents<'a> {
    pub fn get(
        &self,
    ) -> Result<impl Iterator<Item = Result<SuitComponentIdentifier<'a>, CborError>>, SuitError>
    {
        self.0.get().map_err(|e| e.into())
    }
}

/// Component identifier - hierarchical array of byte strings.
///
/// Can represent simple IDs like `[h'00']` or filesystem paths like `['usr','bin','env']`.
/// Allows construction of hierarchical component structures for complex devices.
///
/// # References
///
/// - [SUIT Spec: Component Identifier (Section 8.4.5.1)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4.5.1)
#[derive(Debug, Encode, Decode)]
#[cbor(transparent)]
pub struct SuitComponentIdentifier<'a>(#[cbor(borrow)] IterableByteSlice<'a>);

impl<'a> SuitComponentIdentifier<'a> {
    pub fn get(&self) -> Result<impl Iterator<Item = Result<&'a ByteSlice, CborError>>, SuitError> {
        self.0.get().map_err(|e| e.into())
    }
}

/// Shared command sequence executed before each command sequence.
///
/// Contains conditions and commands common to multiple sequences. Per Section 8.4.5,
/// this sequence **MUST NOT** have side effects beyond setting parameters.
/// Custom commands are forbidden in shared sequences for security.
///
/// # References
///
/// - [SUIT Spec: suit-shared-sequence (Section 8.4.5)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4.5)
#[derive(Debug, Encode, Decode)]
#[cbor(transparent)]
pub struct SuitSharedSequence<'a>(#[b(0)] pub(crate) FlatSequence<'a>); // + = at least 1

/// Commands valid in the shared sequence.
///
/// Restricted set compared to general directives - no fetch/copy/invoke allowed.
/// Custom commands are explicitly forbidden for security.
#[derive(Debug, Encode, Decode)]
pub enum SuitSharedCommand<'a> {
    #[n(12)]
    SetComponentIndex(#[n(0)] IndexArg<'a>),
    #[b(32)]
    RunSequence(
        #[b(0)]
        // we borrow a bstr so we need #[b()] instead of #[n()]
        BstrSuitSharedSequence<'a>,
    ),
    #[n(15)]
    TryEach(#[n(0)] SuitDirectiveTryEachArgumentShared<'a>),
    #[n(20)]
    OverrideParameters(#[n(0)] SuitParameters<'a>), // TODO should 1 +
}

/// Component index selector for set-component-index directive.
///
/// Allows flexible component targeting:
/// - **Single**: Index a specific component
/// - **True**: Apply to all components
/// - **Multiple**: Array of component indices
///
/// # References
///
/// - [SUIT Spec: set-component-index (Section 8.4.10.1)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4.10.1)
#[derive(Debug, Encode)]
pub enum IndexArg<'a> {
    #[n(0)]
    Single(#[n(0)] u64), // uint
    #[n(1)]
    True(#[n(0)] bool), // true
    #[n(2)]
    Multiple(#[n(0)] IterableU64<'a>), // [+uint]
}

#[derive(Debug, Encode, Decode)]
#[cbor(transparent)]
pub struct SuitDirectiveTryEachArgumentShared<'a> {
    #[cbor(borrow)]
    pub sequences: Option<IterBstrSuitSharedSequence<'a>>, // 2* bstr.cbor SUIT_Shared_Sequence
}

/// Command sequence - ordered lists of conditions and directives.
///
/// Defines update or invocation procedures executed by the manifest processor.
/// Sequences include payload-fetch, install, validate, load, and invoke.
/// See Section 6.4 for the abstract machine semantics.
///
/// # References
///
/// - [SUIT Spec: Command Sequences (Section 8.4.6)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4.6)
/// - [SUIT Spec: Abstract Machine (Section 6.4)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-6.4)
#[derive(Debug, Encode, Decode)]
#[cbor(transparent)]
pub struct SuitCommandSequence<'a>(#[b(0)] pub(crate) FlatSequence<'a>);

/// Custom command value for application-defined commands.
///
/// Supports extensibility via custom command codes (ID < -256).
/// Values can be bytes, text, integers, or explicit nil.
///
/// # References
///
/// - [SUIT Spec: Custom Commands (Section 8.4.11)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4.11)
#[derive(Debug, Encode)]
pub enum CommandCustomValue<'a> {
    #[n(0)]
    Bytes(#[n(0)] &'a [u8]),
    #[n(1)]
    Text(#[n(0)] &'a str),
    #[n(2)]
    Integer(#[n(0)] i64),
    #[n(3)]
    Nil,
}

/// Reporting policy for command execution outcomes.
///
/// Bitfield indicating whether success/failure and system information should be
/// reported for this command. Used for manifest processor reporting and attestation.
///
/// # References
///
/// - [SUIT Spec: Reporting Policy (Section 8.4.7)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4.7)
#[derive(Debug, Encode, Decode)]
#[cbor(transparent)]
pub struct SuitRepPolicy(pub SuitReportingBits);

bitflags::bitflags! {
    #[derive(Debug)]
    pub struct SuitReportingBits: u8 {
        const SEND_RECORD_SUCCESS  = 0b0001;
        const SEND_RECORD_FAILURE  = 0b0010;
        const SEND_SYSINFO_SUCCESS = 0b0100;
        const SEND_SYSINFO_FAILURE = 0b1000;
    }
}

/// Conditions that must pass for sequence execution to continue.
///
/// Test device properties and payload integrity. If any condition fails,
/// the current command sequence terminates unless soft-failure is enabled.
///
/// # Variants
///
/// - `VendorIdentifier`: Device vendor matches manifest vendor (Section 8.4.9.1)
/// - `ClassIdentifier`: Device class matches manifest class (Section 8.4.9.1)
/// - `DeviceIdentifier`: Device ID matches manifest ID (Section 8.4.9.1, optional)
/// - `ImageMatch`: Stored image matches expected digest (Section 8.4.9.2)
/// - `ComponentSlot`: Component index matches expected slot (Section 8.4.9.4)
/// - `CheckContent`: Content matches expected bytes (Section 8.4.9.3)
/// - `Abort`: Unconditional failure (Section 8.4.9.5)
///
/// # References
///
/// - [SUIT Spec: Conditions (Section 8.4.9)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4.9)
#[derive(Debug, Encode, Decode)]
pub enum SuitCondition {
    #[n(1)]
    VendorIdentifier(#[n(0)] SuitRepPolicy),

    #[n(2)]
    ClassIdentifier(#[n(0)] SuitRepPolicy),

    #[n(3)]
    ImageMatch(#[n(0)] SuitRepPolicy),

    #[n(5)]
    ComponentSlot(#[n(0)] SuitRepPolicy),

    #[n(6)]
    CheckContent(#[n(0)] SuitRepPolicy),

    #[n(14)]
    Abort(#[n(0)] SuitRepPolicy),

    #[n(24)]
    DeviceIdentifier(#[n(0)] SuitRepPolicy),
}
impl SuitCondition {
    pub fn policy(&self) -> &SuitReportingBits {
        match self {
            SuitCondition::VendorIdentifier(SuitRepPolicy(p))
            | SuitCondition::ClassIdentifier(SuitRepPolicy(p))
            | SuitCondition::ImageMatch(SuitRepPolicy(p))
            | SuitCondition::ComponentSlot(SuitRepPolicy(p))
            | SuitCondition::CheckContent(SuitRepPolicy(p))
            | SuitCondition::Abort(SuitRepPolicy(p))
            | SuitCondition::DeviceIdentifier(SuitRepPolicy(p)) => p,
        }
    }
}

/// Directives - actions with side effects executed by the manifest processor.
///
/// Unlike conditions, directives perform actual work like fetching, writing,
/// and executing payloads. Failure of a directive terminates the sequence.
///
/// # Variants
///
/// - `Write`: Write immediate content to component (Section 8.4.10.6)
/// - `SetComponentIndex`: Select current component (Section 8.4.10.1)
/// - `RunSequence`: Execute a nested sequence (Section 8.4.10.8)
/// - `TryEach`: Try alternatives until one succeeds (Section 8.4.10.2)
/// - `OverrideParameters`: Replace parameter values (Section 8.4.10.3)
/// - `Fetch`: Obtain image from URI (Section 8.4.10.4)
/// - `Copy`: Copy from source to current component (Section 8.4.10.5)
/// - `Swap`: Exchange source and destination (Section 8.4.10.9)
/// - `Invoke`: Transfer execution to component (Section 8.4.10.7)
///
/// # References
///
/// - [SUIT Spec: Directives (Section 8.4.10)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4.10)
#[derive(Debug, Encode, Decode)]
#[cbor(map)]
pub enum SuitDirective<'a> {
    #[n(18)]
    Write(#[n(0)] SuitRepPolicy),

    #[n(12)]
    SetComponentIndex(#[n(0)] IndexArg<'a>),

    #[n(32)]
    RunSequence(
        #[b(0)] // we borrow a bstr so we need #[b()] instead of #[n()]
        BstrSuitCommandSequence<'a>,
    ),

    #[b(15)]
    TryEach(#[n(0)] SuitDirectiveTryEachArgument<'a>),

    #[b(20)]
    OverrideParameters(#[n(0)] SuitParameters<'a>),

    #[n(21)]
    Fetch(#[n(0)] SuitRepPolicy),

    #[n(22)]
    Copy(#[n(0)] SuitRepPolicy),

    #[n(31)]
    Swap(#[n(0)] SuitRepPolicy),

    #[n(23)]
    Invoke(#[n(0)] SuitRepPolicy),
}

impl SuitDirective<'_> {
    pub fn policy(&self) -> Option<&SuitReportingBits> {
        match self {
            SuitDirective::Write(SuitRepPolicy(p))
            | SuitDirective::Fetch(SuitRepPolicy(p))
            | SuitDirective::Copy(SuitRepPolicy(p))
            | SuitDirective::Swap(SuitRepPolicy(p))
            | SuitDirective::Invoke(SuitRepPolicy(p)) => Some(p),
            _ => None,
        }
    }
}

#[derive(Debug, Encode, Decode)]
#[cbor(transparent)]
pub struct SuitDirectiveTryEachArgument<'a>(#[cbor(borrow)] pub IterBstrSuitCommandSequence<'a>);

/// Command parameters - inputs consumed by conditions and directives.
///
/// Scoped per component. Parameters are reused across commands to reduce
/// manifest size. See Section 8.4.8 for all defined parameters and their usage.
///
/// # References
///
/// - [SUIT Spec: Parameters (Section 8.4.8)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4.8)
#[derive(Debug, Encode, Decode)]
#[cbor(map)]
pub struct SuitParameters<'a> {
    #[cbor(n(1), decode_with = "crate::suit_decode::decode_uuid_or_cborpen")]
    pub vendor_identifier: Option<&'a [u8]>, // Rfc4122Uuid / cbor-pen
    #[cbor(n(2), with = "minicbor::bytes")]
    pub class_identifier: Option<Rfc4122Uuid>,
    #[b(3)] // We borrow the bstr
    pub image_digest: Option<BstrSuitDigest<'a>>,
    #[n(5)]
    pub component_slot: Option<u64>,
    #[n(12)]
    pub strict_order: Option<bool>,
    #[n(13)]
    pub soft_failure: Option<bool>,
    #[n(14)]
    pub image_size: Option<u64>,
    #[cbor(n(18), with = "minicbor::bytes")]
    pub content: Option<&'a [u8]>,
    #[n(21)]
    pub uri: Option<&'a str>,
    #[n(22)]
    pub source_component: Option<u64>,
    #[cbor(n(23), with = "minicbor::bytes")]
    pub invoke_args: Option<&'a [u8]>,
    #[n(24)]
    pub device_identifier: Option<Rfc4122Uuid>,
    #[cbor(n(25), with = "minicbor::bytes")]
    pub fetch_args: Option<&'a [u8]>,
    // custom: Option<CustomParameterValue,
}

// #[derive(Debug, Clone, Encode, Decode)]
// pub enum CustomParameterValue {
//     #[n(0)]
//     Int(#[n(0)] i64),
//     #[n(1)]ByteDecodeVec
//     Bool(#[n(0)] bool),
//     #[n(2)]
//     Text(#[n(0)] &'a str),
//     #[n(3)]
//     Bytes(#[n(0)] &'a ByteSlice),
// }

/// RFC 5646 language tag.
///
/// Identifies language variants of text descriptions in manifest.
/// Format: `[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*`
///
/// # References
///
/// - [SUIT Spec: suit-text (Section 8.4.4)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4.4)
/// - [RFC 5646: Language Tags](https://www.rfc-editor.org/rfc/rfc5646)
#[derive(Debug, Encode, Hash, Eq, PartialEq)]
#[cbor(transparent)]
pub struct Tag38LTag<'a>(pub &'a str);

/// Human-readable text descriptions for manifest and components.
///
/// Severable element containing manifest description, update instructions,
/// and per-component information in multiple languages. Typically removed
/// before delivery to constrained devices.
///
/// # References
///
/// - [SUIT Spec: suit-text (Section 8.4.4)](https://datatracker.ietf.org/doc/html/draft-ietf-suit-manifest#section-8.4.4)
#[derive(Debug, Encode, Decode)]
#[cbor(transparent)]
pub struct SuitTextMap<'a> {
    #[cbor(borrow)]
    pub entries: IterSuitTagAndTextLmap<'a>,
}

#[derive(Debug, Encode, Decode)]
pub struct SuitTextLMap<'a> {
    #[b(0)]
    pub text_keys: SuitTextKeys<'a>,
    #[b(1)]
    pub components: IterSuitTextComponentPair<'a>,
}
#[derive(Debug, Encode, Decode)]
pub struct SuitTextComponentPair<'a> {
    #[b(0)]
    pub key: SuitComponentIdentifier<'a>,
    #[b(1)]
    pub text_component: SuitTextComponentKeys<'a>,
}

#[derive(Debug, Encode, Decode)]
#[cbor(map)]
pub struct SuitTextComponentKeys<'a> {
    #[n(1)]
    pub vendor_name: Option<&'a str>,
    #[n(2)]
    pub model_name: Option<&'a str>,
    #[n(3)]
    pub vendor_domain: Option<&'a str>,
    #[n(4)]
    pub model_info: Option<&'a str>,
    #[n(5)]
    pub component_description: Option<&'a str>,
    #[n(6)]
    pub component_version: Option<&'a str>,
}

#[derive(Debug, Decode, Encode)]
#[cbor(map)]
pub struct SuitTextKeys<'a> {
    #[n(1)]
    pub description: Option<&'a str>,
    #[n(2)]
    pub update_description: Option<&'a str>,
    #[n(3)]
    pub manifest_json_source: Option<&'a str>,
    #[n(4)]
    pub manifest_yaml_source: Option<&'a str>,
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_digest_verify() {
        use super::*;
        use minicbor::decode;

        let digest: SuitDigest = decode(&cbor_macro::cbo!(
            r#" [
                    / algorithm-id / -16 / "sha256" /,
                    / digest-bytes /
    h'6658ea560262696dd1f13b782239a064da7c6c5cbaf52fded428a6fc83c7e5af'
                ] "#
        ))
        .unwrap();
        let manifest_bytes = &cbor_macro::cbo!(
            r#"<< {
                / manifest-version / 1:1,
                / manifest-sequence-number / 2:0,
                / common / 3:<< {
                    / components / 2:[
                        [h'00']
                    ],
                    / shared-sequence / 4:<< [
                        / directive-override-parameters / 20,{
                            / vendor-id /
    1:h'fa6b4a53d5ad5fdfbe9de663e4d41ffe' / fa6b4a53-d5ad-5fdf-
    be9d-e663e4d41ffe /,
                            / class-id /
    2:h'1492af1425695e48bf429b2d51f2ab45' /
    1492af14-2569-5e48-bf42-9b2d51f2ab45 /,
                            / image-digest / 3:<< [
                                / algorithm-id / -16 / "sha256" /,
                                / digest-bytes /
    h'00112233445566778899aabbccddeeff0123456789abcdeffedcba9876543210'
                            ] >>,
                            / image-size / 14:34768
                        },
                        / condition-vendor-identifier / 1,15,
                        / condition-class-identifier / 2,15
                    ] >>
                } >>,
                / validate / 7:<< [
                    / condition-image-match / 3,15
                ] >>,
                / invoke / 9:<< [
                    / directive-invoke / 23,2
                ] >>
            } >>"#
        );
        digest.suit_verify_digest(manifest_bytes).unwrap()
    }
}