wire-mesh-wire 0.1.0

Wire types and canonical CBOR codec for the wire-mesh protocol (spec/*.cddl), hand-written against RFC 8949 4.2 core deterministic encoding
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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
//! `tokens.cddl` — capability verbs, scopes, and signed capability tokens.
//!
//! [`CoseSign1`] is the literal RFC 9052 §4.2 four-element array, not a
//! bespoke struct, so signing and verification can use off-the-shelf COSE
//! maths over it. `protected` and `payload` stay opaque `Vec<u8>` on the
//! wire type: the nested `.cbor` content is parsed on demand by domain code
//! via [`CoseSign1::decode_protected`] / [`CoseSign1::decode_claims`],
//! which decode strictly and must re-encode identically under CDE (pinned
//! by tests against the frozen conformance vectors).

use minicbor::data::Type;
use minicbor::{Decode, Decoder, Encode, Encoder};

use crate::error::DecodeError;
use crate::identity::{DeviceId, IdentityKey};
use crate::strict;
use crate::value::{CanonicalMap, CborValue, CdeKey, CdeMapBuilder, HeaderLabel};

/// Why a capability verb is not valid.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerbError {
    /// No colon separating subsystem/registrant from action, or more than
    /// one.
    BadShape,
    /// The verb matches no tier's grammar.
    Malformed(String),
}

impl core::fmt::Display for VerbError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            VerbError::BadShape => write!(f, "a capability verb is '<subsystem>:<action>'"),
            VerbError::Malformed(v) => write!(
                f,
                "verb {v:?} matches no core, namespaced, or private-use tier"
            ),
        }
    }
}

impl std::error::Error for VerbError {}

/// `capability-verb = core-capability / namespaced-capability / private-use-capability`,
/// a validated string newtype like `DomainId`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CapabilityVerb(pub String);

impl CapabilityVerb {
    /// Validate against the three tiers from `tokens.cddl`.
    ///
    /// - core: `[a-z][a-z0-9-]*:[a-z][a-z0-9-]*`
    /// - namespaced: `[a-z0-9.-]+/[A-Za-z0-9_.-]+:[A-Za-z0-9_.-]+`
    /// - private-use: `x-[A-Za-z0-9_.-]+:[A-Za-z0-9_.-]+`
    pub fn validate(verb: &str) -> Result<(), VerbError> {
        let Some((head, action)) = verb.split_once(':') else {
            return Err(VerbError::BadShape);
        };
        let action_ok = |a: &str| {
            let bytes = a.as_bytes();
            !bytes.is_empty()
                && bytes[0].is_ascii_lowercase()
                && bytes[1..]
                    .iter()
                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
        };
        let loose_ok = |a: &str| {
            !a.is_empty()
                && a.bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.' || b == b'-')
        };
        // core tier
        let head_core_ok = |h: &str| {
            let bytes = h.as_bytes();
            !bytes.is_empty()
                && bytes[0].is_ascii_lowercase()
                && bytes[1..]
                    .iter()
                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
        };
        if head_core_ok(head) && action_ok(action) {
            return Ok(());
        }
        // namespaced tier
        if let Some((registrant, local)) = head.split_once('/') {
            let registrant_ok = !registrant.is_empty()
                && registrant.bytes().all(|b| {
                    b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-'
                });
            if registrant_ok && loose_ok(local) && loose_ok(action) {
                return Ok(());
            }
        }
        // private-use tier
        if let Some(rest) = head.strip_prefix("x-") {
            if loose_ok(rest) && loose_ok(action) {
                return Ok(());
            }
        }
        Err(VerbError::Malformed(verb.to_owned()))
    }
}

/// Why a scope is not valid.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScopeError {
    /// `kind` is empty: a zero-length kind names no scope.
    EmptyKind,
    /// `path` is present but empty: an absent path already means the kind's
    /// whole-scope root, so a present-but-empty path is meaningless.
    EmptyPath,
}

impl core::fmt::Display for ScopeError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            ScopeError::EmptyKind => write!(f, "capability scope kind must be non-empty"),
            ScopeError::EmptyPath => write!(f, "capability scope path must be non-empty when present (absent means the whole-scope root)"),
        }
    }
}

impl std::error::Error for ScopeError {}

/// `capability-scope = { kind: tstr, ? path: tstr }`. `kind` is open on
/// purpose; `path` absent means the kind's whole-scope root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CapabilityScope {
    pub kind: String,
    pub path: Option<String>,
}

impl CapabilityScope {
    pub fn validate(&self) -> Result<(), ScopeError> {
        if self.kind.is_empty() {
            return Err(ScopeError::EmptyKind);
        }
        if self.path.as_deref() == Some("") {
            return Err(ScopeError::EmptyPath);
        }
        Ok(())
    }

    /// Does this scope narrow `parent` (same kind, path within the
    /// parent's subtree)? A delegated token's scope must satisfy this
    /// against its parent's scope; a root token has no parent and any
    /// scope.
    ///
    /// Comparison is on `/`-segment boundaries: `/work/sub` narrows
    /// `/work`, but `/workbook` does not despite the string prefix. A path
    /// containing a `.` or `..` segment never narrows anything: purely
    /// lexical comparison would let `/work/../org` pass under `/work` — a
    /// path that normalises outside the parent — so any relative segment
    /// fails the comparison wholesale. Fail closed rather than
    /// reimplementing path normalisation, matching the TS core's verifier.
    pub fn is_within(&self, parent: &CapabilityScope) -> bool {
        if self.kind != parent.kind {
            return false;
        }
        let Some(parent_path) = &parent.path else {
            return true;
        };
        let Some(path) = &self.path else {
            return false;
        };
        if has_relative_segment(path) || has_relative_segment(parent_path) {
            return false;
        }
        if path == parent_path {
            return true;
        }
        if !path.starts_with(parent_path.as_str()) {
            return false;
        }
        // A parent that ends in a slash already names a segment boundary, so everything under it narrows it; otherwise the next character of the child must start a new segment.
        parent_path.ends_with('/') || path[parent_path.len()..].starts_with('/')
    }
}

/// True when the path contains a `.` or `..` segment. See
/// [`CapabilityScope::is_within`] for why such paths never narrow.
fn has_relative_segment(path: &str) -> bool {
    path.split('/')
        .any(|segment| segment == "." || segment == "..")
}

impl Encode<()> for CapabilityScope {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        let len = 1 + usize::from(self.path.is_some());
        e.map(len as u64)?;
        e.str("kind")?.str(&self.kind)?;
        if let Some(path) = &self.path {
            e.str("path")?.str(path)?;
        }
        e.ok()
    }
}

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

pub(crate) fn scope_from(d: &mut Decoder<'_>) -> Result<CapabilityScope, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut kind: Option<String> = None;
    let mut path: Option<String> = None;
    while let Some(key) = map.next_key(d)? {
        match key {
            "kind" => strict::set_once(&mut kind, strict::text_value(d)?)?,
            "path" => strict::set_once(&mut path, strict::text_value(d)?)?,
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(CapabilityScope {
        kind: kind.ok_or(DecodeError::MissingField("kind"))?,
        path,
    })
}

/// `cose-token-headers = { ? 1 => int, ? 4 => bstr, * cose-header-label => any }`.
///
/// The typed `alg`/`kid` fields are populated only from the *integer*
/// labels 1 and 4. A text "1"/"4" key is a distinct CBOR key from integer
/// 1/4 (they encode differently), so on decode it is preserved verbatim in
/// `extra` — which is also what makes re-encoding byte-exact for the
/// frozen vectors, whose protected headers carry the text-key form. The
/// [`CoseTokenHeaders::alg`] and [`CoseTokenHeaders::kid`] accessors accept
/// both forms.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CoseTokenHeaders {
    pub alg: Option<i64>,
    pub kid: Option<Vec<u8>>,
    pub extra: CanonicalMap<HeaderLabel, CborValue>,
}

impl CoseTokenHeaders {
    pub fn new() -> Self {
        Self::default()
    }

    /// The `alg` header, accepting either key form: integer label 1 (the
    /// RFC 9052 form) or text "1" (the form the frozen vectors encode).
    pub fn alg(&self) -> Option<i64> {
        if let Some(alg) = self.alg {
            return Some(alg);
        }
        match self.extra.get(&HeaderLabel::Text("1".to_owned())) {
            Some(CborValue::Int(v)) => Some(*v),
            Some(CborValue::UInt(v)) => i64::try_from(*v).ok(),
            _ => None,
        }
    }

    /// The `kid` header, accepting either key form. Integer label 4 first.
    pub fn kid(&self) -> Option<&[u8]> {
        if let Some(kid) = &self.kid {
            return Some(kid);
        }
        match self.extra.get(&HeaderLabel::Text("4".to_owned())) {
            Some(CborValue::Bytes(b)) => Some(b),
            _ => None,
        }
    }
}

impl Encode<()> for CoseTokenHeaders {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        // Typed fields and the open tail must be ordered together by CDE
        // encoded-key order (an integer label 2 sorts between labels 1 and
        // 4; a one-char text label sorts after integer labels but before
        // longer ones), so assemble through the builder rather than
        // writing fields then tail.
        let mut builder = CdeMapBuilder::new();
        if let Some(alg) = self.alg {
            builder.push(&HeaderLabel::Int(HeaderLabel::ALG), &alg);
        }
        if let Some(kid) = &self.kid {
            builder.push_bytes(&HeaderLabel::Int(HeaderLabel::KID), kid);
        }
        for (label, value) in self.extra.iter() {
            let mut key_buf = Vec::new();
            let mut key_enc = Encoder::new(&mut key_buf);
            label
                .write_key(&mut key_enc)
                .unwrap_or_else(|_| unreachable!("Vec<u8> writes are infallible"));
            let mut value_buf = Vec::new();
            let mut value_enc = Encoder::new(&mut value_buf);
            value
                .encode(&mut value_enc, &mut ())
                .unwrap_or_else(|_| unreachable!("Vec<u8> writes are infallible"));
            builder.push_raw(key_buf, value_buf);
        }
        builder.write(e)
    }
}

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

pub(crate) fn headers_from(d: &mut Decoder<'_>) -> Result<CoseTokenHeaders, DecodeError> {
    // Header labels are `int / tstr`, not the text keys MapDecoder reads, so this loop orders raw label encodings through KeyOrder directly.
    let n = strict::definite_map(d)?;
    let mut order = strict::KeyOrder::new();
    let mut headers = CoseTokenHeaders::new();
    for _ in 0..n {
        let label = HeaderLabel::decode_strict(d)?;
        order.push(&label.encoded())?;
        match label {
            HeaderLabel::Int(HeaderLabel::ALG) => {
                strict::set_once(&mut headers.alg, strict::int_value(d)?)?;
            }
            HeaderLabel::Int(HeaderLabel::KID) => {
                strict::set_once(&mut headers.kid, strict::bytes_value(d)?)?;
            }
            label => {
                let value = CborValue::decode_strict(d)?;
                headers.extra.insert(label, value)?;
            }
        }
    }
    Ok(headers)
}

/// The literal RFC 9052 §4.2 `COSE_Sign1` four-element array.
///
/// `protected` is the encoded protected-header map (the content of the
/// first array element's bstr), `payload` the signed content (`None` for
/// the CDDL's `bstr / nil` nil case; always `Some` for a capability
/// token), both opaque at this layer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CoseSign1 {
    pub protected: Vec<u8>,
    pub unprotected: CoseTokenHeaders,
    pub payload: Option<Vec<u8>>,
    pub signature: Vec<u8>,
}

impl CoseSign1 {
    /// Strictly decode a `COSE_Sign1` from a complete byte string,
    /// rejecting trailing bytes.
    pub fn decode_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
        let mut d = Decoder::new(bytes);
        let value = cose_sign1_from(&mut d)?;
        if d.position() != bytes.len() {
            return Err(DecodeError::TrailingBytes {
                consumed: d.position(),
                total: bytes.len(),
            });
        }
        Ok(value)
    }

    /// Encode to bytes.
    pub fn encode_to_vec(&self) -> Vec<u8> {
        minicbor::to_vec(self).unwrap_or_else(|_| unreachable!("Vec<u8> writes are infallible"))
    }

    /// Parse the protected header map on demand. The frozen vectors' text
    /// "1"/"4" key quirk is preserved verbatim by [`CoseTokenHeaders`].
    pub fn decode_protected(&self) -> Result<CoseTokenHeaders, DecodeError> {
        let mut d = Decoder::new(&self.protected);
        let headers = headers_from(&mut d)?;
        if d.position() != self.protected.len() {
            return Err(DecodeError::TrailingBytes {
                consumed: d.position(),
                total: self.protected.len(),
            });
        }
        Ok(headers)
    }

    /// Parse the payload as `token-claims` on demand.
    pub fn decode_claims(&self) -> Result<TokenClaims, DecodeError> {
        let payload = self
            .payload
            .as_deref()
            .ok_or(DecodeError::Constraint("token payload is nil"))?;
        TokenClaims::decode_bytes(payload)
    }

    /// Parse the payload as `handle-claims` (discovery.cddl) on demand.
    pub fn decode_handle_claims(&self) -> Result<crate::discovery::HandleClaims, DecodeError> {
        let payload = self
            .payload
            .as_deref()
            .ok_or(DecodeError::Constraint("handle-record payload is nil"))?;
        crate::discovery::HandleClaims::decode_bytes(payload)
    }

    /// Parse the payload as `room-notice-claims` (room.cddl) on demand.
    pub fn decode_room_notice_claims(&self) -> Result<crate::room::RoomNoticeClaims, DecodeError> {
        let payload = self
            .payload
            .as_deref()
            .ok_or(DecodeError::Constraint("room-notice payload is nil"))?;
        crate::room::RoomNoticeClaims::decode_bytes(payload)
    }
}

impl Encode<()> for CoseSign1 {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        e.array(4)?;
        e.bytes(&self.protected)?;
        self.unprotected.encode(e, &mut ())?;
        match &self.payload {
            Some(payload) => e.bytes(payload)?,
            None => e.null()?,
        };
        e.bytes(&self.signature)?;
        e.ok()
    }
}

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

pub(crate) fn cose_sign1_from(d: &mut Decoder<'_>) -> Result<CoseSign1, DecodeError> {
    let arity = strict::definite_array(d)?;
    if arity != 4 {
        return Err(DecodeError::WrongArity {
            expected: 4,
            found: arity,
        });
    }
    let protected = strict::bytes_value(d)?;
    let unprotected = headers_from(d)?;
    let payload = match d.datatype().map_err(DecodeError::from_minicbor)? {
        Type::Bytes => Some(strict::bytes_value(d)?),
        Type::Null => {
            d.null().map_err(DecodeError::from_minicbor)?;
            None
        }
        other => {
            return Err(DecodeError::UnexpectedType {
                expected: "byte string or null payload",
                found: other.to_string(),
            })
        }
    };
    let signature = strict::bytes_value(d)?;
    Ok(CoseSign1 {
        protected,
        unprotected,
        payload,
        signature,
    })
}

/// `capability-token = cose-sign1`.
pub type CapabilityToken = CoseSign1;

/// `token-claims` — the signed payload of a capability token.
///
/// CDE key order over the full key set (typed fields plus the open `* tstr
/// => any` tail) is computed by the encoder: `scope` (6 encoded bytes),
/// `bearer`/`issuer`/`parent` (7), `expires` (8), `token-id` (9),
/// `capability`/`issuer-key`/`not-before`/`conditions` (11),
/// `valid-until` (12), with any extension claim interleaved by its own
/// encoded length.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenClaims {
    pub token_id: Vec<u8>,
    pub issuer: DeviceId,
    pub issuer_key: IdentityKey,
    pub bearer: DeviceId,
    pub capability: CapabilityVerb,
    pub scope: CapabilityScope,
    /// Unix ms.
    pub expires: u64,
    pub not_before: Option<u64>,
    /// Unix ms; bounds the lifetime of the authorised content/action
    /// itself, independent of and in addition to `expires` (authorisation
    /// to present the token). Absent means unbounded.
    pub valid_until: Option<u64>,
    /// `bstr .cbor` of a trilean predicate-node array, opaque at this
    /// layer -- see tokens.cddl's own comment on the field. This
    /// implementation has no predicate evaluator: `verify_capability_token`
    /// (wire-mesh-core) refuses any token where this is `Some`, rather than
    /// silently accepting a token whose issuer intended further
    /// restrictions this verifier cannot check. Kept as a first-class,
    /// typed field specifically so it can never fall into `extra` and be
    /// silently dropped the way `valid-until` once did before that gap was
    /// found and fixed.
    pub conditions: Option<Vec<u8>>,
    /// `bstr .cbor capability-token`: a fully self-contained nested
    /// COSE_Sign1 of the parent token, opaque at this layer.
    pub parent: Option<Vec<u8>>,
    /// Bounds how many further delegation hops the chain may take below
    /// this token; absent means unbounded, 0 means none. Typed (never left
    /// to `extra`) precisely so the verifier can enforce it: an untyped
    /// field is an unchecked field.
    pub delegations_remaining: Option<u64>,
    /// `bstr .cbor capability-token`: the grant-capability that authorised
    /// this token's mint (wire-mesh#323), opaque at this layer.
    pub authorised_by: Option<Vec<u8>>,
    /// On a manage:grant token: the single verb it authorises minting.
    /// Absent means any verb within the token's own scope.
    pub grants_capability: Option<CapabilityVerb>,
    /// On a manage:request token (wire-mesh#324): the single verb it
    /// authorises requesting. Absent means any verb within the token's own
    /// scope.
    pub requests_capability: Option<CapabilityVerb>,
    pub extra: CanonicalMap<String, CborValue>,
}

impl TokenClaims {
    /// Checks every capability verb the claims carry, `capability`,
    /// `grants-capability` and `requests-capability`, against the
    /// capability-verb grammar.
    pub fn validate_verbs(&self) -> Result<(), VerbError> {
        CapabilityVerb::validate(&self.capability.0)?;
        for verb in [&self.grants_capability, &self.requests_capability]
            .into_iter()
            .flatten()
        {
            CapabilityVerb::validate(&verb.0)?;
        }
        Ok(())
    }

    /// Strictly decode from a complete byte string, rejecting trailing
    /// bytes.
    pub fn decode_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
        let mut d = Decoder::new(bytes);
        let claims = token_claims_from(&mut d)?;
        if d.position() != bytes.len() {
            return Err(DecodeError::TrailingBytes {
                consumed: d.position(),
                total: bytes.len(),
            });
        }
        Ok(claims)
    }

    /// Encode to bytes. Must reproduce the original payload bytes exactly
    /// for a CDE-encoded input; pinned by tests against the frozen
    /// conformance vectors.
    pub fn encode_to_vec(&self) -> Vec<u8> {
        minicbor::to_vec(self).unwrap_or_else(|_| unreachable!("Vec<u8> writes are infallible"))
    }
}

impl Encode<()> for TokenClaims {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        let mut builder = CdeMapBuilder::new();
        builder.push_bytes("token-id", &self.token_id);
        builder.push("issuer", &self.issuer);
        builder.push("issuer-key", &self.issuer_key);
        builder.push("bearer", &self.bearer);
        builder.push("capability", &self.capability.0.as_str());
        builder.push("scope", &self.scope);
        builder.push("expires", &self.expires);
        if let Some(not_before) = self.not_before {
            builder.push("not-before", &not_before);
        }
        if let Some(valid_until) = self.valid_until {
            builder.push("valid-until", &valid_until);
        }
        if let Some(conditions) = &self.conditions {
            builder.push_bytes("conditions", conditions);
        }
        if let Some(parent) = &self.parent {
            builder.push_bytes("parent", parent);
        }
        if let Some(remaining) = self.delegations_remaining {
            builder.push("delegations-remaining", &remaining);
        }
        if let Some(authorised_by) = &self.authorised_by {
            builder.push_bytes("authorised-by", authorised_by);
        }
        if let Some(grants) = &self.grants_capability {
            builder.push("grants-capability", &grants.0.as_str());
        }
        if let Some(requests) = &self.requests_capability {
            builder.push("requests-capability", &requests.0.as_str());
        }
        for (key, value) in self.extra.iter() {
            let mut value_buf = Vec::new();
            let mut value_enc = Encoder::new(&mut value_buf);
            value
                .encode(&mut value_enc, &mut ())
                .unwrap_or_else(|_| unreachable!("Vec<u8> writes are infallible"));
            builder.push_raw(key.encoded(), value_buf);
        }
        builder.write(e)
    }
}

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

pub(crate) fn token_claims_from(d: &mut Decoder<'_>) -> Result<TokenClaims, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut token_id: Option<Vec<u8>> = None;
    let mut issuer: Option<DeviceId> = None;
    let mut issuer_key: Option<IdentityKey> = None;
    let mut bearer: Option<DeviceId> = None;
    let mut capability: Option<String> = None;
    let mut scope: Option<CapabilityScope> = None;
    let mut expires: Option<u64> = None;
    let mut not_before: Option<u64> = None;
    let mut valid_until: Option<u64> = None;
    let mut conditions: Option<Vec<u8>> = None;
    let mut parent: Option<Vec<u8>> = None;
    let mut delegations_remaining: Option<u64> = None;
    let mut authorised_by: Option<Vec<u8>> = None;
    let mut grants_capability: Option<String> = None;
    let mut requests_capability: Option<String> = None;
    let mut extra = CanonicalMap::new();
    while let Some(key) = map.next_key(d)? {
        match key {
            "token-id" => strict::set_once(&mut token_id, strict::bytes_value(d)?)?,
            "issuer" => strict::set_once(&mut issuer, crate::identity::device_id_from(d)?)?,
            "issuer-key" => {
                strict::set_once(&mut issuer_key, crate::identity::identity_key_from(d)?)?
            }
            "bearer" => strict::set_once(&mut bearer, crate::identity::device_id_from(d)?)?,
            "capability" => strict::set_once(&mut capability, strict::text_value(d)?)?,
            "scope" => strict::set_once(&mut scope, scope_from(d)?)?,
            "expires" => strict::set_once(&mut expires, strict::uint_value(d)?)?,
            "not-before" => strict::set_once(&mut not_before, strict::uint_value(d)?)?,
            "valid-until" => strict::set_once(&mut valid_until, strict::uint_value(d)?)?,
            "conditions" => strict::set_once(&mut conditions, strict::bytes_value(d)?)?,
            "parent" => strict::set_once(&mut parent, strict::bytes_value(d)?)?,
            "delegations-remaining" => {
                strict::set_once(&mut delegations_remaining, strict::uint_value(d)?)?
            }
            "authorised-by" => strict::set_once(&mut authorised_by, strict::bytes_value(d)?)?,
            "grants-capability" => {
                strict::set_once(&mut grants_capability, strict::text_value(d)?)?
            }
            "requests-capability" => {
                strict::set_once(&mut requests_capability, strict::text_value(d)?)?
            }
            other => {
                let value = CborValue::decode_strict(d)?;
                extra.insert(other.to_owned(), value)?;
            }
        }
    }
    Ok(TokenClaims {
        token_id: token_id.ok_or(DecodeError::MissingField("token-id"))?,
        issuer: issuer.ok_or(DecodeError::MissingField("issuer"))?,
        issuer_key: issuer_key.ok_or(DecodeError::MissingField("issuer-key"))?,
        bearer: bearer.ok_or(DecodeError::MissingField("bearer"))?,
        capability: CapabilityVerb(capability.ok_or(DecodeError::MissingField("capability"))?),
        scope: scope.ok_or(DecodeError::MissingField("scope"))?,
        expires: expires.ok_or(DecodeError::MissingField("expires"))?,
        not_before,
        valid_until,
        conditions,
        parent,
        delegations_remaining,
        authorised_by,
        grants_capability: grants_capability.map(CapabilityVerb),
        requests_capability: requests_capability.map(CapabilityVerb),
        extra,
    })
}

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

    #[test]
    fn token_claims_rejects_duplicate_typed_key() {
        // { "expires": 1, "expires": 2 }: the repeated key is rejected as a
        // duplicate rather than silently taking the last value.
        let bytes = [
            0xa2, 0x67, b'e', b'x', b'p', b'i', b'r', b'e', b's', 0x01, 0x67, b'e', b'x', b'p',
            b'i', b'r', b'e', b's', 0x02,
        ];
        assert_eq!(
            TokenClaims::decode_bytes(&bytes),
            Err(DecodeError::DuplicateKey)
        );
    }

    #[test]
    fn token_claims_rejects_unsorted_keys() {
        // { "issuer": <id>, "bearer": <id> }: "bearer" (8 bytes) sorts
        // before "issuer" (9), so issuer-first is out of CDE order.
        let id = [0x11u8; 32];
        let mut bytes = vec![0xa2, 0x66];
        bytes.extend_from_slice(b"issuer");
        bytes.push(0x58);
        bytes.push(32);
        bytes.extend_from_slice(&id);
        bytes.push(0x66);
        bytes.extend_from_slice(b"bearer");
        bytes.push(0x58);
        bytes.push(32);
        bytes.extend_from_slice(&id);
        assert_eq!(
            TokenClaims::decode_bytes(&bytes),
            Err(DecodeError::UnsortedMapKeys)
        );
    }

    #[test]
    fn token_claims_rejects_non_minimal_integer_head() {
        // alg for a minimal -7 is the single byte 0x26; 0x38 0x26 is the
        // same value in a two-byte head, which CDE forbids.
        let mut bytes = vec![0xa2, 0x63];
        bytes.extend_from_slice(b"alg");
        bytes.extend_from_slice(&[0x38, 0x06]);
        bytes.push(0x6a);
        bytes.extend_from_slice(b"public-key");
        bytes.extend_from_slice(&[0x58, 0x41]);
        bytes.extend_from_slice(&[0x04; 65]);
        let mut d = Decoder::new(&bytes);
        assert_eq!(
            crate::identity::identity_key_from(&mut d),
            Err(DecodeError::NonMinimalHead)
        );
    }

    #[test]
    fn verb_tiers() {
        for verb in [
            "pin:write",
            "exec:pty",
            "exec:proc",
            "a-b:c-d",
            "example.com/rooms:list",
            "exa.dev/thing.v2:run",
            "a.b/c:x",
            "x-private:thing",
            "x-a_.-b:x_y.-z",
        ] {
            assert_eq!(CapabilityVerb::validate(verb), Ok(()), "{verb}");
        }
        for verb in [
            "nolons",
            "two:colons:here",
            "EXEC:pty",
            "exec:",
            ":exec",
            "exa.dev:run", // namespaced needs a '/' in the head
            "x-bad verb:thing",
            "-lead:action",
            // The core action starts with a letter, like its subsystem.
            "exec:1",
            "exec:-x",
            "exec:1pty",
        ] {
            assert_ne!(CapabilityVerb::validate(verb), Ok(()), "{verb}");
        }
    }

    /// The grammar's edges, for every tier: the empty string, a leading or
    /// trailing space, a trailing newline, NUL, non-ASCII and an uppercase
    /// letter where only lowercase is allowed. The cases are the ones the
    /// anchored TypeScript schema refuses too (`anchored-patterns.unit.test.ts`).
    #[test]
    fn capability_verb_edges_match_the_grammar() {
        for verb in [
            "",
            " exec:pty",
            "exec:pty ",
            "exec:pty\n",
            "exec:pty\0",
            "exec\0:pty",
            "exec:pty\r",
            "exec:p\u{e9}ty",
            "ex\u{e9}c:pty",
            "exec:pty\u{2028}",
            "Exec:pty",
            "example.com/Tool:run:more",
            "Example.com/tool:run",
            "example.com/tool:run\n",
            "example.com/tool:",
            "example.com/:run",
            "/tool:run",
            "x-local:run\n",
            "x-local:",
            "X-local:run",
        ] {
            assert_ne!(CapabilityVerb::validate(verb), Ok(()), "{verb:?}");
        }
        let long_action = "a".repeat(10_000);
        assert_eq!(
            CapabilityVerb::validate(&format!("exec:{long_action}")),
            Ok(())
        );
    }

    #[test]
    fn claims_verbs_are_all_validated() {
        let ok = CapabilityVerb("exec:pty".to_owned());
        let bad = CapabilityVerb("two:colons:here".to_owned());
        let claims = |capability: &CapabilityVerb,
                      grants: Option<&CapabilityVerb>,
                      requests: Option<&CapabilityVerb>| TokenClaims {
            token_id: vec![0; 16],
            issuer: crate::identity::DeviceId([1; 32]),
            issuer_key: crate::identity::IdentityKey {
                alg: -8,
                public_key: vec![2; 32],
            },
            bearer: crate::identity::DeviceId([3; 32]),
            capability: capability.clone(),
            scope: CapabilityScope {
                kind: "folder".to_owned(),
                path: None,
            },
            expires: 1,
            not_before: None,
            valid_until: None,
            conditions: None,
            parent: None,
            delegations_remaining: None,
            authorised_by: None,
            grants_capability: grants.cloned(),
            requests_capability: requests.cloned(),
            extra: CanonicalMap::new(),
        };

        assert_eq!(claims(&ok, Some(&ok), Some(&ok)).validate_verbs(), Ok(()));
        assert_eq!(claims(&ok, None, None).validate_verbs(), Ok(()));
        assert!(claims(&bad, None, None).validate_verbs().is_err());
        assert!(claims(&ok, Some(&bad), None).validate_verbs().is_err());
        assert!(claims(&ok, None, Some(&bad)).validate_verbs().is_err());
    }

    /// Every edge of the path rule, each pinned to what the TypeScript core's `scopeNarrows` answers: the same rule in the same words, so the two implementations cannot disagree on a path.
    #[test]
    fn scope_within_agrees_with_the_typescript_rule_at_every_edge() {
        let within = |child: &str, parent: &str| {
            let scope = |path: &str| CapabilityScope {
                kind: "folder".to_owned(),
                path: Some(path.to_owned()),
            };
            scope(child).is_within(&scope(parent))
        };
        // A parent ending in a slash names a segment boundary already: everything under it narrows it, the root `/` included.
        assert!(within("/work/x", "/"));
        assert!(within("/", "/"));
        assert!(within("/work/sub", "/work/"));
        assert!(within("/work/", "/work/"));
        assert!(
            within("/work//x", "/work/"),
            "doubled slashes are not collapsed"
        );
        assert!(
            !within("/work", "/work/"),
            "the parent's own name without its slash is outside it"
        );
        assert!(!within("/other", "/work/"));
        // Without the trailing slash the next character must start a segment.
        assert!(within("/work", "/work"));
        assert!(within("/work/sub", "/work"));
        assert!(within("/work/", "/work"));
        assert!(
            !within("/workshop", "/work"),
            "a shared prefix is not a shared segment"
        );
        assert!(!within("/work-other", "/work"));
        // Paths with a dot segment never narrow, on either side, even an identical one.
        assert!(!within("/work/./x", "/work"));
        assert!(!within("/work/../x", "/work"));
        assert!(!within("/work", "/work/.."));
        assert!(!within("/work/..", "/work/.."));
        assert!(!within("/.", "/"));
        // An empty path is within no parent but the empty one, and the empty parent holds the paths that start a segment.
        assert!(!within("", "/work"));
        assert!(within("/x", ""));
        assert!(!within("x", ""));
    }

    #[test]
    fn scope_within_narrows() {
        let root = CapabilityScope {
            kind: "folder".to_owned(),
            path: None,
        };
        let work = CapabilityScope {
            kind: "folder".to_owned(),
            path: Some("/work".to_owned()),
        };
        let subdir = CapabilityScope {
            kind: "folder".to_owned(),
            path: Some("/work/subdir".to_owned()),
        };
        let sibling = CapabilityScope {
            kind: "folder".to_owned(),
            path: Some("/work-other".to_owned()),
        };
        let other_kind = CapabilityScope {
            kind: "node".to_owned(),
            path: Some("/work".to_owned()),
        };
        assert!(subdir.is_within(&work));
        assert!(work.is_within(&work));
        assert!(work.is_within(&root));
        assert!(
            !sibling.is_within(&work),
            "prefix must respect the segment boundary"
        );
        let escape = CapabilityScope {
            kind: "folder".to_owned(),
            path: Some("/work/../org".to_owned()),
        };
        assert!(
            !escape.is_within(&work),
            "a relative segment normalises outside the parent: fail closed, not lexically"
        );
        let dot = CapabilityScope {
            kind: "folder".to_owned(),
            path: Some("/work/./sub".to_owned()),
        };
        assert!(!dot.is_within(&work), "'.' segments never narrow either");
        assert!(
            !root.is_within(&work),
            "root is wider than a path-scoped parent"
        );
        assert!(!subdir.is_within(&other_kind));
    }

    #[test]
    fn scope_validation() {
        assert_eq!(
            CapabilityScope {
                kind: "folder".to_owned(),
                path: None
            }
            .validate(),
            Ok(())
        );
        assert_eq!(
            CapabilityScope {
                kind: String::new(),
                path: None
            }
            .validate(),
            Err(ScopeError::EmptyKind)
        );
        assert_eq!(
            CapabilityScope {
                kind: "folder".to_owned(),
                path: Some(String::new())
            }
            .validate(),
            Err(ScopeError::EmptyPath)
        );
    }

    #[test]
    fn headers_accept_both_label_forms_but_reencode_only_what_was_there() {
        // Integer form round-trips as integer form.
        let headers = CoseTokenHeaders {
            alg: Some(-7),
            kid: Some(vec![0x11; 32]),
            extra: CanonicalMap::new(),
        };
        let bytes = minicbor::to_vec(&headers).expect("encode");
        let back: CoseTokenHeaders = minicbor::decode(&bytes).expect("decode");
        assert_eq!(back, headers);
        assert_eq!(bytes[1], 0x01, "alg encoded under integer label 1");

        // Text form decodes into extra, re-encodes as text, and is still readable through the accessors: {"1": -7, "4": h'11'*32}.
        let mut text_form: Vec<u8> = vec![0xa2, 0x61, b'1', 0x26, 0x61, b'4', 0x58, 0x20];
        text_form.extend(core::iter::repeat_n(0x11, 32));
        let decoded: CoseTokenHeaders = minicbor::decode(&text_form).expect("decode");
        assert_eq!(decoded.alg(), Some(-7));
        assert_eq!(decoded.kid(), Some(vec![0x11; 32].as_slice()));
        assert_eq!(minicbor::to_vec(&decoded).expect("re-encode"), text_form);
    }

    #[test]
    fn cose_sign1_nil_payload_round_trip() {
        let cose = CoseSign1 {
            protected: vec![0xa0],
            unprotected: CoseTokenHeaders::new(),
            payload: None,
            signature: vec![0xff; 64],
        };
        let bytes = cose.encode_to_vec();
        assert_eq!(bytes[0], 0x84, "four-element array");
        let back = CoseSign1::decode_bytes(&bytes).expect("decode");
        assert_eq!(back, cose);
        // The nil payload encodes as 0xf6.
        assert!(bytes.contains(&0xf6));
    }

    #[test]
    fn cose_sign1_rejects_wrong_arity() {
        // Three-element array.
        let bytes = [0x83, 0x41, 0x01, 0xa0, 0x41, 0x02];
        assert!(CoseSign1::decode_bytes(&bytes).is_err());
        // Trailing bytes after the array.
        let mut with_trailer = CoseSign1 {
            protected: vec![0xa0],
            unprotected: CoseTokenHeaders::new(),
            payload: None,
            signature: vec![],
        }
        .encode_to_vec();
        with_trailer.push(0x01);
        assert!(CoseSign1::decode_bytes(&with_trailer).is_err());
    }

    #[test]
    fn token_claims_encode_matches_cde_interleaving() {
        // An extension claim with a 2-character key must sort before every
        // typed field of the frozen claims (whose shortest key, "scope",
        // encodes to 6 bytes) — impossible to express by writing typed
        // fields first and the tail after, which is why the encoder goes
        // through CdeMapBuilder.
        let mut extra = CanonicalMap::new();
        extra
            .insert("zz".to_owned(), CborValue::UInt(1))
            .expect("unique");
        let claims = TokenClaims {
            token_id: vec![1; 16],
            issuer: DeviceId([2; 32]),
            issuer_key: IdentityKey {
                alg: -8,
                public_key: vec![3; 32],
            },
            bearer: DeviceId([4; 32]),
            capability: CapabilityVerb("exec:pty".to_owned()),
            scope: CapabilityScope {
                kind: "folder".to_owned(),
                path: Some("/work".to_owned()),
            },
            expires: 42,
            not_before: None,
            valid_until: None,
            conditions: None,
            parent: None,
            delegations_remaining: None,
            authorised_by: None,
            grants_capability: None,
            requests_capability: None,
            extra,
        };
        let bytes = claims.encode_to_vec();
        let decoded = TokenClaims::decode_bytes(&bytes).expect("decode");
        assert_eq!(decoded, claims);
        // Map arity 8, first key is the 3-byte-encoded "zz".
        assert_eq!(bytes[0], 0xa8);
        assert_eq!(&bytes[1..4], &[0x62, b'z', b'z']);
    }

    #[test]
    fn token_claims_round_trips_the_grant_permission_fields() {
        // Every new wire-mesh#323 field present at once, plus delegations-remaining
        // newly typed: each must survive encode/decode rather than falling into
        // `extra` (or out of the struct entirely) the way delegations-remaining
        // previously did.
        let claims = TokenClaims {
            token_id: vec![1; 16],
            issuer: DeviceId([2; 32]),
            issuer_key: IdentityKey {
                alg: -7,
                public_key: vec![3; 32],
            },
            bearer: DeviceId([4; 32]),
            capability: CapabilityVerb("manage:grant".to_owned()),
            scope: CapabilityScope {
                kind: "folder".to_owned(),
                path: Some("/work".to_owned()),
            },
            expires: 42,
            not_before: None,
            valid_until: None,
            conditions: Some(vec![0x81, 0xf6]),
            parent: None,
            delegations_remaining: Some(3),
            authorised_by: Some(vec![5; 48]),
            grants_capability: Some(CapabilityVerb("exec:pty".to_owned())),
            extra: CanonicalMap::new(),
            requests_capability: None,
        };
        let bytes = claims.encode_to_vec();
        let decoded = TokenClaims::decode_bytes(&bytes).expect("decode");
        assert_eq!(decoded, claims);
    }
}