clasp-caps 4.5.0

Capability tokens for CLASP protocol (delegatable Ed25519)
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
//! Capability token validator for CLASP router integration
//!
//! Implements `TokenValidator` so capability tokens can be validated
//! alongside existing CPSK tokens via `ValidatorChain`.

use clasp_core::security::{Action, Scope, TokenInfo, TokenValidator, ValidationResult};
use std::collections::HashMap;
use std::time::{Duration, UNIX_EPOCH};

use crate::error::CapError;
use crate::token::{CapabilityToken, TOKEN_PREFIX};

/// Validates CLASP capability tokens.
///
/// Integrates with `ValidatorChain` to support `cap_` prefixed tokens
/// alongside existing `cpsk_` and `ext_` tokens.
pub struct CapabilityValidator {
    /// Trusted root issuer public keys
    trust_anchors: Vec<Vec<u8>>,
    /// Maximum delegation chain depth
    max_depth: usize,
}

impl CapabilityValidator {
    /// Create a new capability validator.
    ///
    /// `trust_anchors` are the Ed25519 public keys of trusted root issuers.
    /// Only tokens whose delegation chain ultimately leads to a trust anchor
    /// will be accepted.
    pub fn new(trust_anchors: Vec<Vec<u8>>, max_depth: usize) -> Self {
        Self {
            trust_anchors,
            max_depth,
        }
    }

    /// Add a trust anchor (root issuer public key)
    pub fn add_trust_anchor(&mut self, public_key: Vec<u8>) {
        self.trust_anchors.push(public_key);
    }

    /// Validate a capability token and return the result
    fn validate_token(&self, token_str: &str) -> std::result::Result<CapabilityToken, CapError> {
        // Decode the token
        let token = CapabilityToken::decode(token_str)?;

        // Check expiration
        if token.is_expired() {
            return Err(CapError::Expired);
        }

        // Check chain depth
        if token.chain_depth() > self.max_depth {
            return Err(CapError::ChainTooDeep {
                depth: token.chain_depth(),
                max: self.max_depth,
            });
        }

        // Verify signature
        token.verify_signature()?;

        // Verify the delegation chain root leads to a trust anchor
        let root_issuer = if token.proofs.is_empty() {
            &token.issuer
        } else {
            &token.proofs[0].issuer
        };

        if !self
            .trust_anchors
            .iter()
            .any(|anchor| anchor == root_issuer)
        {
            return Err(CapError::UntrustedIssuer(hex::encode(root_issuer)));
        }

        // Verify scope attenuation through the chain
        if !token.proofs.is_empty() {
            // Check each link: child scopes must be subset of parent scopes
            for i in 1..token.proofs.len() {
                let parent = &token.proofs[i - 1];
                let child = &token.proofs[i];
                for scope in &child.scopes {
                    if !scope_within_parent(scope, &parent.scopes) {
                        return Err(CapError::AttenuationViolation(format!(
                            "scope '{}' at depth {} exceeds parent",
                            scope, i
                        )));
                    }
                }
            }

            // Check final token's scopes against last proof
            let last_proof = token.proofs.last().unwrap();
            for scope in &token.scopes {
                if !scope_within_parent(scope, &last_proof.scopes) {
                    return Err(CapError::AttenuationViolation(format!(
                        "token scope '{}' exceeds last delegation",
                        scope
                    )));
                }
            }
        }

        Ok(token)
    }
}

/// Check if a scope string is allowed by any of the parent scopes
fn scope_within_parent(scope: &str, parent_scopes: &[String]) -> bool {
    let Some((child_action, child_pattern)) = scope.split_once(':') else {
        return false;
    };

    for parent in parent_scopes {
        let Some((parent_action, parent_pattern)) = parent.split_once(':') else {
            continue;
        };

        let action_ok = match parent_action {
            "admin" => true,
            "write" => child_action == "write" || child_action == "read",
            "read" => child_action == "read",
            _ => parent_action == child_action,
        };

        if action_ok && crate::token::pattern_is_subset(child_pattern, parent_pattern) {
            return true;
        }
    }

    false
}

/// Hex encoding helper (minimal, avoids a dependency)
mod hex {
    pub fn encode(bytes: &[u8]) -> String {
        bytes.iter().map(|b| format!("{:02x}", b)).collect()
    }
}

impl TokenValidator for CapabilityValidator {
    fn validate(&self, token: &str) -> ValidationResult {
        // Only handle cap_ tokens
        if !token.starts_with(TOKEN_PREFIX) {
            return ValidationResult::NotMyToken;
        }

        match self.validate_token(token) {
            Ok(cap_token) => {
                // Convert capability scopes to CLASP Scope objects
                let scopes: Vec<Scope> = cap_token
                    .scopes
                    .iter()
                    .filter_map(|s| {
                        let (action_str, pattern) = s.split_once(':')?;
                        let action = match action_str {
                            "admin" => Action::Admin,
                            "write" => Action::Write,
                            "read" => Action::Read,
                            _ => return None,
                        };
                        Scope::new(action, pattern).ok()
                    })
                    .collect();

                let expires_at = if cap_token.expires_at > 0 {
                    Some(UNIX_EPOCH + Duration::from_secs(cap_token.expires_at))
                } else {
                    None
                };

                let mut metadata = HashMap::new();
                metadata.insert(
                    "chain_depth".to_string(),
                    cap_token.chain_depth().to_string(),
                );

                let info = TokenInfo {
                    token_id: cap_token.nonce.clone(),
                    subject: None, // Capability tokens are bearer tokens
                    scopes,
                    expires_at,
                    metadata,
                };

                ValidationResult::Valid(info)
            }
            Err(CapError::Expired) => ValidationResult::Expired,
            Err(e) => ValidationResult::Invalid(e.to_string()),
        }
    }

    fn name(&self) -> &str {
        "Capability"
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::token::CapabilityToken;
    use ed25519_dalek::SigningKey;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn future_timestamp() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 3600
    }

    fn root_key() -> SigningKey {
        SigningKey::from_bytes(&[1u8; 32])
    }

    fn make_validator() -> CapabilityValidator {
        let key = root_key();
        let pub_key = key.verifying_key().to_bytes().to_vec();
        CapabilityValidator::new(vec![pub_key], 5)
    }

    #[test]
    fn test_validate_root_token() {
        let validator = make_validator();
        let key = root_key();

        let token = CapabilityToken::create_root(
            &key,
            vec!["admin:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();

        let encoded = token.encode().unwrap();
        match validator.validate(&encoded) {
            ValidationResult::Valid(info) => {
                assert!(!info.scopes.is_empty());
                assert!(info.has_scope(Action::Admin, "/anything"));
            }
            other => panic!("expected Valid, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_delegated_token() {
        let validator = make_validator();
        let root_key = root_key();
        let child_key = SigningKey::from_bytes(&[2u8; 32]);

        let root = CapabilityToken::create_root(
            &root_key,
            vec!["admin:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();

        let child = root
            .delegate(
                &child_key,
                vec!["write:/lights/**".to_string()],
                future_timestamp(),
                None,
            )
            .unwrap();

        let encoded = child.encode().unwrap();
        match validator.validate(&encoded) {
            ValidationResult::Valid(info) => {
                assert!(info.has_scope(Action::Write, "/lights/room1"));
                assert!(!info.has_scope(Action::Write, "/audio/channel1"));
            }
            other => panic!("expected Valid, got {:?}", other),
        }
    }

    #[test]
    fn test_reject_untrusted_issuer() {
        let validator = make_validator();
        let untrusted_key = SigningKey::from_bytes(&[99u8; 32]);

        let token = CapabilityToken::create_root(
            &untrusted_key,
            vec!["admin:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();

        let encoded = token.encode().unwrap();
        match validator.validate(&encoded) {
            ValidationResult::Invalid(msg) => {
                assert!(msg.contains("untrusted"));
            }
            other => panic!("expected Invalid, got {:?}", other),
        }
    }

    #[test]
    fn test_not_my_token() {
        let validator = make_validator();
        match validator.validate("cpsk_something") {
            ValidationResult::NotMyToken => {}
            other => panic!("expected NotMyToken, got {:?}", other),
        }
    }

    #[test]
    fn test_expired_token() {
        let validator = make_validator();
        let key = root_key();

        // Create a token that's already expired
        let token = CapabilityToken::create_root(
            &key,
            vec!["admin:/**".to_string()],
            0, // Expired at epoch
            None,
        )
        .unwrap();

        let encoded = token.encode().unwrap();
        match validator.validate(&encoded) {
            ValidationResult::Expired => {}
            other => panic!("expected Expired, got {:?}", other),
        }
    }

    // --- Negative tests ---

    #[test]
    fn test_malformed_token_bad_base64() {
        let validator = make_validator();
        match validator.validate("cap_!!!not-valid-base64!!!") {
            ValidationResult::Invalid(msg) => {
                assert!(
                    msg.contains("encoding"),
                    "expected encoding error, got: {}",
                    msg
                );
            }
            other => panic!("expected Invalid, got {:?}", other),
        }
    }

    #[test]
    fn test_malformed_token_truncated() {
        let validator = make_validator();
        // Valid prefix + valid base64, but truncated msgpack
        use base64::Engine;
        let truncated = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([0x92, 0x01, 0x02]);
        match validator.validate(&format!("cap_{}", truncated)) {
            ValidationResult::Invalid(_) => {}
            other => panic!("expected Invalid, got {:?}", other),
        }
    }

    #[test]
    fn test_signature_tampered_token() {
        let validator = make_validator();
        let key = root_key();

        let mut token = CapabilityToken::create_root(
            &key,
            vec!["admin:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();

        // Tamper with signature
        token.signature[0] ^= 0xFF;
        let encoded = token.encode().unwrap();
        match validator.validate(&encoded) {
            ValidationResult::Invalid(msg) => {
                assert!(
                    msg.contains("signature"),
                    "expected signature error, got: {}",
                    msg
                );
            }
            other => panic!("expected Invalid, got {:?}", other),
        }
    }

    #[test]
    fn test_chain_depth_exceeds_max() {
        // Create a validator with max_depth = 1
        let key = root_key();
        let pub_key = key.verifying_key().to_bytes().to_vec();
        let validator = CapabilityValidator::new(vec![pub_key], 1);

        let key_b = SigningKey::from_bytes(&[2u8; 32]);
        let key_c = SigningKey::from_bytes(&[3u8; 32]);

        let root = CapabilityToken::create_root(
            &key,
            vec!["admin:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();

        let child = root
            .delegate(
                &key_b,
                vec!["write:/**".to_string()],
                future_timestamp(),
                None,
            )
            .unwrap();

        let grandchild = child
            .delegate(
                &key_c,
                vec!["read:/**".to_string()],
                future_timestamp(),
                None,
            )
            .unwrap();

        // grandchild has chain_depth 2, which exceeds max_depth 1
        let encoded = grandchild.encode().unwrap();
        match validator.validate(&encoded) {
            ValidationResult::Invalid(msg) => {
                assert!(
                    msg.contains("deep") || msg.contains("chain"),
                    "expected chain depth error, got: {}",
                    msg
                );
            }
            other => panic!("expected Invalid, got {:?}", other),
        }
    }

    #[test]
    fn test_multiple_trust_anchors() {
        let key_a = root_key();
        let key_b = SigningKey::from_bytes(&[42u8; 32]);

        let pub_a = key_a.verifying_key().to_bytes().to_vec();
        let pub_b = key_b.verifying_key().to_bytes().to_vec();

        let validator = CapabilityValidator::new(vec![pub_a, pub_b], 5);

        // Token from anchor A
        let token_a = CapabilityToken::create_root(
            &key_a,
            vec!["admin:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();
        let encoded_a = token_a.encode().unwrap();
        assert!(matches!(
            validator.validate(&encoded_a),
            ValidationResult::Valid(_)
        ));

        // Token from anchor B
        let token_b = CapabilityToken::create_root(
            &key_b,
            vec!["read:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();
        let encoded_b = token_b.encode().unwrap();
        assert!(matches!(
            validator.validate(&encoded_b),
            ValidationResult::Valid(_)
        ));

        // Token from untrusted anchor C
        let key_c = SigningKey::from_bytes(&[99u8; 32]);
        let token_c = CapabilityToken::create_root(
            &key_c,
            vec!["admin:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();
        let encoded_c = token_c.encode().unwrap();
        assert!(matches!(
            validator.validate(&encoded_c),
            ValidationResult::Invalid(_)
        ));
    }
}