auths-keri 0.1.13

KERI protocol types, SAID computation, and validation
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
//! Validated capability identifiers — the atomic unit of authorization in Auths.

use serde::{Deserialize, Serialize};
use std::fmt;

/// Well-known capability string: permission to sign commits.
pub const SIGN_COMMIT: &str = "sign_commit";
/// Well-known capability string: permission to sign releases.
pub const SIGN_RELEASE: &str = "sign_release";
/// Well-known capability string: permission to add/remove organization members.
pub const MANAGE_MEMBERS: &str = "manage_members";
/// Well-known capability string: permission to rotate keys for an identity.
pub const ROTATE_KEYS: &str = "rotate_keys";

/// Error type for capability parsing and validation.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum CapabilityError {
    /// The capability string is empty.
    #[error("capability is empty")]
    Empty,
    /// The capability string exceeds the maximum length.
    #[error("capability exceeds 64 chars: {0}")]
    TooLong(usize),
    /// The capability string contains invalid characters.
    #[error("invalid characters in capability '{0}': only alphanumeric, ':', '-', '_' allowed")]
    InvalidChars(String),
    /// The capability uses the reserved 'auths:' namespace.
    #[error(
        "reserved namespace 'auths:' — use well-known constructors or choose a different prefix"
    )]
    ReservedNamespace,
    /// The capability uses a reserved infrastructure namespace prefix.
    #[error("the '{0}' prefix is reserved for infrastructure capabilities")]
    ReservedInfraNamespace(String),
}

/// A validated capability identifier.
///
/// Capabilities are the atomic unit of authorization in Auths.
/// They follow a namespace convention:
///
/// - Well-known capabilities: `sign_commit`, `sign_release`, `manage_members`, `rotate_keys`
/// - Custom capabilities: any valid string (alphanumeric + `:` + `-` + `_`, max 64 chars)
///
/// The `auths:` prefix is reserved for future well-known capabilities and cannot be
/// used in custom capabilities created via `parse()`.
///
/// # Examples
///
/// ```
/// use auths_keri::Capability;
///
/// // Well-known capabilities
/// let cap = Capability::sign_commit();
/// assert_eq!(cap.as_str(), "sign_commit");
///
/// // Custom capabilities
/// let custom = Capability::parse("acme:deploy").unwrap();
/// assert_eq!(custom.as_str(), "acme:deploy");
///
/// // Reserved namespace is rejected
/// assert!(Capability::parse("auths:custom").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(try_from = "String", into = "String")]
pub struct Capability(String);

impl Capability {
    /// Maximum length for capability strings.
    pub const MAX_LEN: usize = 64;

    /// Reserved namespace prefix for Auths well-known capabilities.
    const RESERVED_PREFIX: &'static str = "auths:";

    /// Reserved infrastructure capability namespace prefixes.
    const RESERVED_INFRA_PREFIXES: &'static [&'static str] =
        &["compute:", "network:", "storage:", "runtime:", "env:"];

    // ========================================================================
    // Well-known capability constructors
    // ========================================================================

    /// Creates the `sign_commit` capability.
    ///
    /// Grants permission to sign commits.
    #[inline]
    pub fn sign_commit() -> Self {
        Self(SIGN_COMMIT.to_string())
    }

    /// Creates the `sign_release` capability.
    ///
    /// Grants permission to sign releases.
    #[inline]
    pub fn sign_release() -> Self {
        Self(SIGN_RELEASE.to_string())
    }

    /// Creates the `manage_members` capability.
    ///
    /// Grants permission to add/remove members in an organization.
    #[inline]
    pub fn manage_members() -> Self {
        Self(MANAGE_MEMBERS.to_string())
    }

    /// Creates the `rotate_keys` capability.
    ///
    /// Grants permission to rotate keys for an identity.
    #[inline]
    pub fn rotate_keys() -> Self {
        Self(ROTATE_KEYS.to_string())
    }

    // ========================================================================
    // Parsing and validation
    // ========================================================================

    /// Parses and validates a capability string.
    ///
    /// This is the primary way to create custom capabilities. The input is
    /// trimmed and lowercased to produce a canonical form.
    ///
    /// # Validation Rules
    ///
    /// - Non-empty
    /// - Maximum 64 characters
    /// - Only alphanumeric characters, colons (`:`), hyphens (`-`), and underscores (`_`)
    /// - Cannot start with `auths:` (reserved namespace)
    ///
    /// # Examples
    ///
    /// ```
    /// use auths_keri::Capability;
    ///
    /// // Valid custom capabilities
    /// assert!(Capability::parse("deploy").is_ok());
    /// assert!(Capability::parse("acme:deploy").is_ok());
    /// assert!(Capability::parse("org:team:action").is_ok());
    ///
    /// // Invalid capabilities
    /// assert!(Capability::parse("").is_err());           // empty
    /// assert!(Capability::parse("has space").is_err());  // invalid char
    /// assert!(Capability::parse("auths:custom").is_err()); // reserved namespace
    /// ```
    pub fn parse(raw: &str) -> Result<Self, CapabilityError> {
        let canonical = raw.trim().to_lowercase();

        if canonical.is_empty() {
            return Err(CapabilityError::Empty);
        }
        if canonical.len() > Self::MAX_LEN {
            return Err(CapabilityError::TooLong(canonical.len()));
        }
        if !canonical
            .chars()
            .all(|c| c.is_alphanumeric() || c == ':' || c == '-' || c == '_')
        {
            return Err(CapabilityError::InvalidChars(canonical));
        }
        if canonical.starts_with(Self::RESERVED_PREFIX) {
            return Err(CapabilityError::ReservedNamespace);
        }
        for prefix in Self::RESERVED_INFRA_PREFIXES {
            if canonical.starts_with(prefix) {
                return Err(CapabilityError::ReservedInfraNamespace(prefix.to_string()));
            }
        }

        Ok(Self(canonical))
    }

    // ========================================================================
    // Accessors
    // ========================================================================

    /// Returns the canonical string representation of this capability.
    ///
    /// This is the authoritative string form used for comparison, display,
    /// and serialization.
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns `true` if this is a well-known Auths capability.
    pub fn is_well_known(&self) -> bool {
        matches!(
            self.0.as_str(),
            SIGN_COMMIT | SIGN_RELEASE | MANAGE_MEMBERS | ROTATE_KEYS
        )
    }

    /// Returns the namespace portion of the capability (before first colon), if any.
    pub fn namespace(&self) -> Option<&str> {
        self.0.split(':').next().filter(|_| self.0.contains(':'))
    }

    // ========================================================================
    // Capability-claim codec — the single grammar for an ACDC `a.capability`
    // ========================================================================

    /// Separator between capabilities packed into one `a.capability` claim string.
    ///
    /// A capability identifier can never contain a comma ([`Capability::parse`]
    /// only admits alphanumerics, `:`, `-`, `_`), so the comma is an unambiguous
    /// delimiter for the multi-capability claim.
    const CLAIM_SEPARATOR: char = ',';

    /// Encode a set of capabilities into the single `a.capability` claim string.
    ///
    /// This is the one source of truth for the on-wire grammar: capabilities are
    /// joined by [`Self::CLAIM_SEPARATOR`]. The issuer writes the claim with this;
    /// every reader decodes it with [`Self::parse_claim`] — they cannot disagree.
    ///
    /// # Examples
    ///
    /// ```
    /// use auths_keri::Capability;
    /// let caps = [Capability::parse("fs:read").unwrap(), Capability::parse("fs:write").unwrap()];
    /// assert_eq!(Capability::join_claim(&caps), "fs:read,fs:write");
    /// ```
    pub fn join_claim(capabilities: &[Capability]) -> String {
        capabilities
            .iter()
            .map(Capability::as_str)
            .collect::<Vec<_>>()
            .join(&Self::CLAIM_SEPARATOR.to_string())
    }

    /// Decode an `a.capability` claim string into its capabilities.
    ///
    /// The inverse of [`Self::join_claim`]: splits on [`Self::CLAIM_SEPARATOR`] and
    /// parses each segment. Returns `Err` if any segment is not a valid capability,
    /// so an issuer/verifier grammar mismatch fails closed rather than silently
    /// admitting a malformed claim. An empty claim yields no capabilities.
    ///
    /// # Examples
    ///
    /// ```
    /// use auths_keri::Capability;
    /// let caps = Capability::parse_claim("fs:read,fs:write").unwrap();
    /// assert_eq!(caps.len(), 2);
    /// assert!(Capability::parse_claim("").unwrap().is_empty());
    /// ```
    pub fn parse_claim(claim: &str) -> Result<Vec<Capability>, CapabilityError> {
        if claim.is_empty() {
            return Ok(Vec::new());
        }
        claim
            .split(Self::CLAIM_SEPARATOR)
            .map(Capability::parse)
            .collect()
    }
}

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

/// The well-known resource name of the call-count usage cap (`calls:<N>`).
///
/// A capability of the form `calls:<N>` (or `calls<=<N>`) is not an opaque
/// presence token — it is a *quantitative* predicate bounding how many times the
/// credential may be exercised. [`UsageCap::from_capability`] recognizes it; the
/// verifier enforces the bound against a monotonic usage record so the `(N+1)`-th
/// use is unverifiable rather than merely logged.
const USAGE_CAP_RESOURCE: &str = "calls";

/// A quantitative usage bound parsed from a [`Capability`].
///
/// Capabilities are normally opaque presence tokens (`sign_commit`, `acme:deploy`):
/// holding the credential grants the action, with no notion of "how many times".
/// A *quantitative* capability instead bounds a measured resource. The first such
/// resource is the call count: `calls:<N>` means "at most `N` exercises of this
/// credential". The bound rides in the capability claim, which is part of the ACDC
/// SAID, so it cannot be edited without breaking the credential.
///
/// The verifier consumes a monotonic usage record alongside the credential: a
/// presentation whose observed count has reached the cap is rejected with a
/// distinct cap-exceeded verdict, and a presentation replaying an earlier (lower)
/// count than the highest already observed is rejected as a rolled-back counter.
///
/// # Examples
///
/// ```
/// use auths_keri::{Capability, UsageCap};
///
/// let cap = Capability::parse("calls:3").unwrap();
/// assert_eq!(UsageCap::from_capability(&cap), Some(UsageCap::calls(3)));
///
/// // A presence token carries no quantitative bound.
/// let sign = Capability::sign_commit();
/// assert_eq!(UsageCap::from_capability(&sign), None);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct UsageCap {
    /// The maximum number of calls this credential admits.
    max_calls: u64,
}

impl UsageCap {
    /// Construct a call-count cap admitting at most `max_calls` exercises.
    #[inline]
    pub const fn calls(max_calls: u64) -> Self {
        Self { max_calls }
    }

    /// The maximum number of calls this credential admits.
    #[inline]
    pub const fn max_calls(self) -> u64 {
        self.max_calls
    }

    /// Parse the quantitative usage bound carried by a capability, if any.
    ///
    /// Recognizes the call-count grammar `calls:<N>` and the comparison spelling
    /// `calls<=<N>`, where `<N>` is a non-negative decimal integer. Any other
    /// capability (a presence token, a different resource) carries no bound and
    /// yields `None`. A `calls` resource with a missing or non-numeric bound also
    /// yields `None` — the credential then has no enforceable quantitative cap and
    /// is treated as an ordinary (unbounded) capability, never silently zero.
    pub fn from_capability(cap: &Capability) -> Option<Self> {
        Self::from_claim_segment(cap.as_str())
    }

    /// The first quantitative usage bound among a set of capabilities, if any.
    ///
    /// A credential carries at most one call-count cap; this returns the first one
    /// found so the verifier can enforce it regardless of where it sits among the
    /// granted capabilities.
    pub fn from_capabilities(caps: &[Capability]) -> Option<Self> {
        caps.iter().find_map(Self::from_capability)
    }

    /// Parse one capability-claim segment as a usage bound.
    ///
    /// The `calls<=<N>` spelling is accepted even though [`Capability::parse`] does
    /// not admit `<`/`=` (so it never reaches here through a parsed capability) —
    /// recognizing both spellings keeps the predicate grammar stable if a future
    /// capability charset admits the comparison operator.
    fn from_claim_segment(segment: &str) -> Option<Self> {
        let bound = segment
            .strip_prefix(&format!("{USAGE_CAP_RESOURCE}:"))
            .or_else(|| segment.strip_prefix(&format!("{USAGE_CAP_RESOURCE}<=")))?;
        bound.parse::<u64>().ok().map(Self::calls)
    }

    /// Whether a capability *intends* to be a quantitative usage cap.
    ///
    /// True for any capability addressing the reserved quantitative resource — the
    /// `calls:` / `calls<=` prefix — regardless of whether its bound parses. This is
    /// the discriminator that separates "a `calls`-resource predicate" (which must
    /// carry a valid numeric bound) from an ordinary presence token that happens to
    /// be unrecognized. An issuer uses it to reject a `calls`-prefixed capability
    /// whose bound does not parse, instead of silently minting it as an uncapped
    /// opaque string.
    fn segment_targets_usage_resource(segment: &str) -> bool {
        segment.starts_with(&format!("{USAGE_CAP_RESOURCE}:"))
            || segment.starts_with(&format!("{USAGE_CAP_RESOURCE}<="))
    }

    /// Whether `cap` is a MALFORMED quantitative usage predicate.
    ///
    /// `true` iff the capability targets the reserved `calls` usage resource (the
    /// `calls:` / `calls<=` prefix) but its bound does NOT parse to a valid
    /// non-negative call count — e.g. `calls:`, `calls:abc`, `calls:-1`. Such a
    /// capability looks like a budget but enforces none: [`Self::from_capability`]
    /// yields `None`, so the credential would verify at any count. An issuer must
    /// refuse it rather than mint a cap that is silently no cap.
    ///
    /// A well-formed cap (`calls:3`) is **not** malformed; a presence token
    /// (`sign_commit`, `acme:deploy`) is **not** malformed (it targets no usage
    /// resource); only a `calls`-resource capability with an unparseable bound is.
    ///
    /// # Examples
    ///
    /// ```
    /// use auths_keri::{Capability, UsageCap};
    ///
    /// assert!(UsageCap::is_malformed_quant_predicate(&Capability::parse("calls:abc").unwrap()));
    /// assert!(UsageCap::is_malformed_quant_predicate(&Capability::parse("calls:").unwrap()));
    /// assert!(!UsageCap::is_malformed_quant_predicate(&Capability::parse("calls:3").unwrap()));
    /// assert!(!UsageCap::is_malformed_quant_predicate(&Capability::sign_commit()));
    /// ```
    pub fn is_malformed_quant_predicate(cap: &Capability) -> bool {
        let segment = cap.as_str();
        Self::segment_targets_usage_resource(segment) && Self::from_claim_segment(segment).is_none()
    }
}

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

impl TryFrom<String> for Capability {
    type Error = CapabilityError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        let canonical = s.trim().to_lowercase();

        if canonical.is_empty() {
            return Err(CapabilityError::Empty);
        }
        if canonical.len() > Self::MAX_LEN {
            return Err(CapabilityError::TooLong(canonical.len()));
        }
        if !canonical
            .chars()
            .all(|c| c.is_alphanumeric() || c == ':' || c == '-' || c == '_')
        {
            return Err(CapabilityError::InvalidChars(canonical));
        }

        // During deserialization, allow well-known capabilities and auths: prefix
        // This ensures backward compatibility with existing attestations
        Ok(Self(canonical))
    }
}

impl std::str::FromStr for Capability {
    type Err = CapabilityError;

    /// Parses a capability string with CLI-friendly alias resolution.
    ///
    /// Normalizes the input (trim, lowercase, replace hyphens with underscores)
    /// and matches well-known capabilities before falling through to
    /// `Capability::parse()` for custom capability validation.
    ///
    /// Args:
    /// * `s`: The capability string (e.g., "sign_commit", "Sign-Commit").
    ///
    /// Usage:
    /// ```
    /// use auths_keri::Capability;
    /// let cap: Capability = "sign_commit".parse().unwrap();
    /// assert_eq!(cap.as_str(), "sign_commit");
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let normalized = s.trim().to_lowercase().replace('-', "_");
        match normalized.as_str() {
            "sign_commit" | "signcommit" => Ok(Capability::sign_commit()),
            "sign_release" | "signrelease" => Ok(Capability::sign_release()),
            "manage_members" | "managemembers" => Ok(Capability::manage_members()),
            "rotate_keys" | "rotatekeys" => Ok(Capability::rotate_keys()),
            _ => Capability::parse(&normalized),
        }
    }
}

impl From<Capability> for String {
    fn from(cap: Capability) -> Self {
        cap.0
    }
}

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

    // ========================================================================
    // Capability serialization tests
    // ========================================================================

    #[test]
    fn capability_serializes_to_snake_case() {
        assert_eq!(
            serde_json::to_string(&Capability::sign_commit()).unwrap(),
            r#""sign_commit""#
        );
        assert_eq!(
            serde_json::to_string(&Capability::sign_release()).unwrap(),
            r#""sign_release""#
        );
        assert_eq!(
            serde_json::to_string(&Capability::manage_members()).unwrap(),
            r#""manage_members""#
        );
        assert_eq!(
            serde_json::to_string(&Capability::rotate_keys()).unwrap(),
            r#""rotate_keys""#
        );
    }

    #[test]
    fn capability_deserializes_from_snake_case() {
        assert_eq!(
            serde_json::from_str::<Capability>(r#""sign_commit""#).unwrap(),
            Capability::sign_commit()
        );
        assert_eq!(
            serde_json::from_str::<Capability>(r#""sign_release""#).unwrap(),
            Capability::sign_release()
        );
        assert_eq!(
            serde_json::from_str::<Capability>(r#""manage_members""#).unwrap(),
            Capability::manage_members()
        );
        assert_eq!(
            serde_json::from_str::<Capability>(r#""rotate_keys""#).unwrap(),
            Capability::rotate_keys()
        );
    }

    #[test]
    fn capability_custom_serializes_as_string() {
        let cap = Capability::parse("acme:deploy").unwrap();
        assert_eq!(serde_json::to_string(&cap).unwrap(), r#""acme:deploy""#);
    }

    #[test]
    fn capability_custom_deserializes_unknown_strings() {
        // Unknown strings become custom capabilities
        let cap: Capability = serde_json::from_str(r#""custom-capability""#).unwrap();
        assert_eq!(cap, Capability::parse("custom-capability").unwrap());
    }

    // ========================================================================
    // Capability parse() validation tests
    // ========================================================================

    #[test]
    fn capability_parse_accepts_valid_strings() {
        assert!(Capability::parse("deploy").is_ok());
        assert!(Capability::parse("acme:deploy").is_ok());
        assert!(Capability::parse("my-custom-cap").is_ok());
        assert!(Capability::parse("org:team:action").is_ok());
        assert!(Capability::parse("with_underscore").is_ok()); // underscore allowed
    }

    #[test]
    fn capability_parse_rejects_invalid_strings() {
        // Empty
        assert!(matches!(Capability::parse(""), Err(CapabilityError::Empty)));

        // Too long
        assert!(matches!(
            Capability::parse(&"a".repeat(65)),
            Err(CapabilityError::TooLong(65))
        ));

        // Invalid characters
        assert!(matches!(
            Capability::parse("has spaces"),
            Err(CapabilityError::InvalidChars(_))
        ));
        assert!(matches!(
            Capability::parse("has.dot"),
            Err(CapabilityError::InvalidChars(_))
        ));
    }

    #[test]
    fn capability_parse_rejects_reserved_namespace() {
        assert!(matches!(
            Capability::parse("auths:custom"),
            Err(CapabilityError::ReservedNamespace)
        ));
        assert!(matches!(
            Capability::parse("auths:sign_commit"),
            Err(CapabilityError::ReservedNamespace)
        ));
    }

    #[test]
    fn capability_parse_accepts_role_markers() {
        // The org delegation layer encodes role markers ("role:admin") inside
        // capability vecs; "role:" is not a reserved prefix and must round-trip.
        let cap = Capability::parse("role:admin").unwrap();
        assert_eq!(cap.as_str(), "role:admin");

        let json = serde_json::to_string(&cap).unwrap();
        let roundtrip: Capability = serde_json::from_str(&json).unwrap();
        assert_eq!(cap, roundtrip);
    }

    #[test]
    fn capability_parse_normalizes_to_lowercase() {
        let cap = Capability::parse("DEPLOY").unwrap();
        assert_eq!(cap.as_str(), "deploy");

        let cap = Capability::parse("ACME:Deploy").unwrap();
        assert_eq!(cap.as_str(), "acme:deploy");
    }

    #[test]
    fn capability_parse_trims_whitespace() {
        let cap = Capability::parse("  deploy  ").unwrap();
        assert_eq!(cap.as_str(), "deploy");
    }

    // ========================================================================
    // Capability equality and hashing tests
    // ========================================================================

    #[test]
    fn capability_is_hashable() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(Capability::sign_commit());
        set.insert(Capability::sign_release());
        set.insert(Capability::parse("test").unwrap());
        assert_eq!(set.len(), 3);
        assert!(set.contains(&Capability::sign_commit()));
    }

    #[test]
    fn capability_equality_with_different_construction_paths() {
        // Well-known constructor equals deserialized
        let from_constructor = Capability::sign_commit();
        let from_deser: Capability = serde_json::from_str(r#""sign_commit""#).unwrap();
        assert_eq!(from_constructor, from_deser);

        // Parse equals deserialized for custom capabilities
        let from_parse = Capability::parse("acme:deploy").unwrap();
        let from_deser: Capability = serde_json::from_str(r#""acme:deploy""#).unwrap();
        assert_eq!(from_parse, from_deser);
    }

    // ========================================================================
    // Capability display and accessor tests
    // ========================================================================

    #[test]
    fn capability_display_matches_canonical_form() {
        assert_eq!(Capability::sign_commit().to_string(), "sign_commit");
        assert_eq!(Capability::sign_release().to_string(), "sign_release");
        assert_eq!(Capability::manage_members().to_string(), "manage_members");
        assert_eq!(Capability::rotate_keys().to_string(), "rotate_keys");
        assert_eq!(
            Capability::parse("acme:deploy").unwrap().to_string(),
            "acme:deploy"
        );
    }

    #[test]
    fn capability_as_str_returns_canonical_form() {
        assert_eq!(Capability::sign_commit().as_str(), "sign_commit");
        assert_eq!(Capability::sign_release().as_str(), "sign_release");
        assert_eq!(Capability::manage_members().as_str(), "manage_members");
        assert_eq!(Capability::rotate_keys().as_str(), "rotate_keys");
        assert_eq!(
            Capability::parse("acme:deploy").unwrap().as_str(),
            "acme:deploy"
        );
    }

    #[test]
    fn capability_is_well_known() {
        assert!(Capability::sign_commit().is_well_known());
        assert!(Capability::sign_release().is_well_known());
        assert!(Capability::manage_members().is_well_known());
        assert!(Capability::rotate_keys().is_well_known());
        assert!(!Capability::parse("custom").unwrap().is_well_known());
    }

    #[test]
    fn capability_namespace() {
        assert_eq!(
            Capability::parse("acme:deploy").unwrap().namespace(),
            Some("acme")
        );
        assert_eq!(
            Capability::parse("org:team:action").unwrap().namespace(),
            Some("org")
        );
        assert_eq!(Capability::parse("deploy").unwrap().namespace(), None);
    }

    // ========================================================================
    // Capability vec serialization tests
    // ========================================================================

    #[test]
    fn capability_vec_serializes_as_array() {
        let caps = vec![Capability::sign_commit(), Capability::sign_release()];
        let json = serde_json::to_string(&caps).unwrap();
        assert_eq!(json, r#"["sign_commit","sign_release"]"#);
    }

    #[test]
    fn capability_vec_deserializes_from_array() {
        let json = r#"["sign_commit","manage_members","custom-cap"]"#;
        let caps: Vec<Capability> = serde_json::from_str(json).unwrap();
        assert_eq!(caps.len(), 3);
        assert_eq!(caps[0], Capability::sign_commit());
        assert_eq!(caps[1], Capability::manage_members());
        assert_eq!(caps[2], Capability::parse("custom-cap").unwrap());
    }

    // ========================================================================
    // Capability-claim codec tests — issuer and verifier share one grammar
    // ========================================================================

    #[test]
    fn claim_codec_roundtrips_multi_capability() {
        let caps = vec![
            Capability::parse("fs:read").unwrap(),
            Capability::parse("fs:write").unwrap(),
        ];
        let claim = Capability::join_claim(&caps);
        assert_eq!(claim, "fs:read,fs:write");
        assert_eq!(Capability::parse_claim(&claim).unwrap(), caps);
    }

    #[test]
    fn claim_codec_roundtrips_single_capability() {
        let caps = vec![Capability::sign_commit()];
        let claim = Capability::join_claim(&caps);
        assert_eq!(claim, "sign_commit");
        assert_eq!(Capability::parse_claim(&claim).unwrap(), caps);
    }

    #[test]
    fn parse_claim_empty_is_no_capabilities() {
        assert!(Capability::parse_claim("").unwrap().is_empty());
    }

    #[test]
    fn parse_claim_rejects_malformed_segment() {
        // A segment with an invalid char fails closed rather than silently dropping.
        assert!(matches!(
            Capability::parse_claim("fs:read,has space"),
            Err(CapabilityError::InvalidChars(_))
        ));
    }

    #[test]
    fn join_claim_of_empty_is_empty_string() {
        assert_eq!(Capability::join_claim(&[]), "");
    }

    // ========================================================================
    // UsageCap — quantitative capability predicate tests
    // ========================================================================

    #[test]
    fn usage_cap_parses_colon_grammar() {
        let cap = Capability::parse("calls:3").unwrap();
        assert_eq!(UsageCap::from_capability(&cap), Some(UsageCap::calls(3)));
        assert_eq!(UsageCap::from_capability(&cap).unwrap().max_calls(), 3);
    }

    #[test]
    fn usage_cap_parses_comparison_grammar() {
        // `calls<=5` does not pass Capability::parse (charset), but the segment
        // parser recognizes the comparison spelling directly.
        assert_eq!(
            UsageCap::from_claim_segment("calls<=5"),
            Some(UsageCap::calls(5))
        );
    }

    #[test]
    fn usage_cap_zero_is_a_real_bound() {
        let cap = Capability::parse("calls:0").unwrap();
        assert_eq!(UsageCap::from_capability(&cap), Some(UsageCap::calls(0)));
    }

    #[test]
    fn presence_token_carries_no_usage_cap() {
        assert_eq!(UsageCap::from_capability(&Capability::sign_commit()), None);
        let deploy = Capability::parse("acme:deploy").unwrap();
        assert_eq!(UsageCap::from_capability(&deploy), None);
    }

    #[test]
    fn calls_resource_with_non_numeric_bound_is_not_a_cap() {
        // `calls:abc` is a valid capability string but not an enforceable bound —
        // it must not silently become a zero cap.
        let cap = Capability::parse("calls:abc").unwrap();
        assert_eq!(UsageCap::from_capability(&cap), None);
    }

    #[test]
    fn usage_cap_found_among_many_capabilities() {
        let caps = vec![
            Capability::sign_commit(),
            Capability::parse("calls:7").unwrap(),
            Capability::parse("acme:deploy").unwrap(),
        ];
        assert_eq!(UsageCap::from_capabilities(&caps), Some(UsageCap::calls(7)));
    }

    #[test]
    fn usage_cap_displays_canonical_grammar() {
        assert_eq!(UsageCap::calls(3).to_string(), "calls:3");
    }

    #[test]
    fn malformed_quant_predicate_flags_unparseable_calls_bounds() {
        // A `calls`-resource capability whose bound does not parse is malformed: it
        // looks like a budget but enforces none.
        for bad in ["calls:", "calls:abc"] {
            let cap = Capability::parse(bad).unwrap();
            assert_eq!(
                UsageCap::from_capability(&cap),
                None,
                "{bad} carries no cap"
            );
            assert!(
                UsageCap::is_malformed_quant_predicate(&cap),
                "{bad} must be flagged malformed"
            );
        }
        // `calls:-1` normalizes to `calls:_1` (a `-` is admitted, not a sign); its
        // bound `_1` does not parse, so it is malformed too.
        let neg: Capability = "calls:-1".parse().unwrap();
        assert!(UsageCap::is_malformed_quant_predicate(&neg));
    }

    #[test]
    fn malformed_quant_predicate_passes_wellformed_and_presence_tokens() {
        // A well-formed cap is not malformed.
        assert!(!UsageCap::is_malformed_quant_predicate(
            &Capability::parse("calls:3").unwrap()
        ));
        // Zero is a real bound, not malformed.
        assert!(!UsageCap::is_malformed_quant_predicate(
            &Capability::parse("calls:0").unwrap()
        ));
        // Presence tokens target no usage resource — never malformed.
        assert!(!UsageCap::is_malformed_quant_predicate(
            &Capability::sign_commit()
        ));
        assert!(!UsageCap::is_malformed_quant_predicate(
            &Capability::parse("acme:deploy").unwrap()
        ));
        // A capability that merely *contains* "calls" but does not target the
        // resource prefix is not a quantitative predicate.
        assert!(!UsageCap::is_malformed_quant_predicate(
            &Capability::parse("recalls:thing").unwrap()
        ));
    }

    // ========================================================================
    // Serde roundtrip tests (critical for backward compat)
    // ========================================================================

    #[test]
    fn capability_serde_roundtrip_well_known() {
        let caps = vec![
            Capability::sign_commit(),
            Capability::sign_release(),
            Capability::manage_members(),
            Capability::rotate_keys(),
        ];
        for cap in caps {
            let json = serde_json::to_string(&cap).unwrap();
            let roundtrip: Capability = serde_json::from_str(&json).unwrap();
            assert_eq!(cap, roundtrip);
        }
    }

    #[test]
    fn capability_serde_roundtrip_custom() {
        let caps = vec![
            Capability::parse("deploy").unwrap(),
            Capability::parse("acme:deploy").unwrap(),
            Capability::parse("org:team:action").unwrap(),
        ];
        for cap in caps {
            let json = serde_json::to_string(&cap).unwrap();
            let roundtrip: Capability = serde_json::from_str(&json).unwrap();
            assert_eq!(cap, roundtrip);
        }
    }
}