auths-keri 0.1.3

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
//! 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(':'))
    }
}

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

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());
    }

    // ========================================================================
    // 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);
        }
    }
}