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
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
//! CAP — Capability Token Attack Tests
//!
//! Validates that capability tokens resist forgery, tampering, replay,
//! scope escalation, and malformed input.

use clasp_caps::{CapError, CapabilityToken, CapabilityValidator};
use clasp_core::security::{Action, TokenValidator, ValidationResult};
use ed25519_dalek::SigningKey;
use std::collections::HashSet;
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)
}

// ── CAP-01: Token forgery ──────────────────────────────────────────────
/// A token signed by an untrusted key must be rejected as UntrustedIssuer.
#[test]
fn test_cap_01_token_forgery() {
    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") || msg.contains("Untrusted"),
                "expected UntrustedIssuer, got: {}",
                msg
            );
        }
        other => panic!("expected Invalid(UntrustedIssuer), got: {:?}", other),
    }
}

// ── CAP-02: Scope attenuation bypass ───────────────────────────────────
/// Two vectors: (1) Decode a valid token, widen its scopes, re-encode — must
/// fail with signature error. (2) Delegate with wider scopes — must fail with
/// attenuation violation.
#[test]
fn test_cap_02_scope_attenuation_bypass() {
    use base64::Engine;

    let key = root_key();
    let child_key = SigningKey::from_bytes(&[2u8; 32]);
    let validator = make_validator();

    // Vector 1: Decode a valid token, mutate scopes to widen them, re-encode.
    // The signature no longer covers the modified payload.
    let token = CapabilityToken::create_root(
        &key,
        vec!["read:/lights/*".to_string()],
        future_timestamp(),
        None,
    )
    .unwrap();

    let encoded = token.encode().unwrap();
    let b64 = encoded.strip_prefix("cap_").unwrap();
    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(b64)
        .unwrap();

    // Decode the msgpack, tamper scopes, re-encode
    let mut decoded: CapabilityToken = rmp_serde::from_slice(&bytes).unwrap();
    let original_scopes = decoded.scopes.clone();
    decoded.scopes = vec!["admin:/**".to_string()]; // widen dramatically
    assert_ne!(
        decoded.scopes, original_scopes,
        "scopes must differ after mutation"
    );

    let tampered_bytes = rmp_serde::to_vec_named(&decoded).unwrap();
    let tampered = format!(
        "cap_{}",
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&tampered_bytes)
    );

    match validator.validate(&tampered) {
        ValidationResult::Invalid(msg) => {
            assert!(
                msg.contains("signature") || msg.contains("Signature"),
                "expected signature error for tampered scopes, got: {}",
                msg
            );
        }
        other => panic!(
            "expected Invalid(signature) for tampered scopes, got: {:?}",
            other
        ),
    }

    // Vector 2: Delegation that widens scope must fail at the API level.
    let root = CapabilityToken::create_root(
        &key,
        vec!["read:/lights/**".to_string()],
        future_timestamp(),
        None,
    )
    .unwrap();

    let result = root.delegate(
        &child_key,
        vec!["admin:/**".to_string()],
        future_timestamp(),
        None,
    );
    assert!(
        result.is_err(),
        "delegating wider scopes (read -> admin) must be rejected as AttenuationViolation"
    );
    let err_msg = format!("{}", result.unwrap_err());
    assert!(
        err_msg.contains("attenuation")
            || err_msg.contains("Attenuation")
            || err_msg.contains("subset"),
        "error should mention attenuation violation, got: {}",
        err_msg
    );
}

// ── CAP-03: Chain depth bypass ─────────────────────────────────────────
/// A delegation chain of depth 4 must be rejected when max_depth is 3.
#[test]
fn test_cap_03_chain_depth_bypass() {
    let key_a = SigningKey::from_bytes(&[1u8; 32]);
    let key_b = SigningKey::from_bytes(&[2u8; 32]);
    let key_c = SigningKey::from_bytes(&[3u8; 32]);
    let key_d = SigningKey::from_bytes(&[4u8; 32]);
    let key_e = SigningKey::from_bytes(&[5u8; 32]);

    let pub_a = key_a.verifying_key().to_bytes().to_vec();
    let validator = CapabilityValidator::new(vec![pub_a], 3);

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

    let t1 = t0
        .delegate(
            &key_b,
            vec!["write:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();
    let t2 = t1
        .delegate(
            &key_c,
            vec!["write:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();
    let t3 = t2
        .delegate(
            &key_d,
            vec!["write:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();
    let t4 = t3
        .delegate(
            &key_e,
            vec!["read:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();

    assert_eq!(t4.chain_depth(), 4);

    let encoded = t4.encode().unwrap();
    match validator.validate(&encoded) {
        ValidationResult::Invalid(msg) => {
            assert!(
                msg.contains("deep") || msg.contains("chain") || msg.contains("Chain"),
                "expected ChainTooDeep, got: {}",
                msg
            );
        }
        other => panic!("expected Invalid(ChainTooDeep), got: {:?}", other),
    }

    // Depth 3 should still be accepted
    let encoded_3 = t3.encode().unwrap();
    assert!(
        matches!(validator.validate(&encoded_3), ValidationResult::Valid(_)),
        "depth 3 should be accepted with max_depth=3"
    );
}

// ── CAP-04: Proof chain manipulation ───────────────────────────────────
/// Two manipulation vectors on a 3-level chain: (1) Tamper proof chain scopes
/// in the encoded token → InvalidSignature. (2) Strip root proof link →
/// UntrustedIssuer (intermediate key is not an anchor).
#[test]
fn test_cap_04_proof_chain_manipulation() {
    use base64::Engine;

    let validator = make_validator();
    let key_a = root_key(); // anchor
    let key_b = SigningKey::from_bytes(&[2u8; 32]);
    let key_c = SigningKey::from_bytes(&[3u8; 32]);

    // Build a 3-level chain: anchor(A) → B → C
    let t_a = CapabilityToken::create_root(
        &key_a,
        vec!["admin:/**".to_string()],
        future_timestamp(),
        None,
    )
    .unwrap();

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

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

    // Baseline: legit chain validates
    let legit_encoded = t_c.encode().unwrap();
    assert!(
        matches!(
            validator.validate(&legit_encoded),
            ValidationResult::Valid(_)
        ),
        "legitimate 3-level chain should validate"
    );

    // Vector 1: Tamper with proof chain scopes (widen root's scopes in proof)
    let b64 = legit_encoded.strip_prefix("cap_").unwrap();
    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(b64)
        .unwrap();
    let mut decoded: CapabilityToken = rmp_serde::from_slice(&bytes).unwrap();
    assert!(
        !decoded.proofs.is_empty(),
        "delegated token must have proof links"
    );
    // Tamper: change root proof's scopes
    decoded.proofs[0].scopes = vec!["read:/narrow".to_string()];
    let tampered_bytes = rmp_serde::to_vec_named(&decoded).unwrap();
    let tampered = format!(
        "cap_{}",
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&tampered_bytes)
    );
    match validator.validate(&tampered) {
        ValidationResult::Invalid(msg) => {
            assert!(
                msg.contains("signature") || msg.contains("Signature"),
                "proof chain tamper should produce signature error, got: {}",
                msg
            );
        }
        other => panic!(
            "expected Invalid for tampered proof chain, got: {:?}",
            other
        ),
    }

    // Vector 2: Strip the root proof link (remove first proof)
    let mut decoded2: CapabilityToken = rmp_serde::from_slice(&bytes).unwrap();
    decoded2.proofs.remove(0); // Remove root anchor link
    let stripped_bytes = rmp_serde::to_vec_named(&decoded2).unwrap();
    let stripped = format!(
        "cap_{}",
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&stripped_bytes)
    );
    match validator.validate(&stripped) {
        ValidationResult::Invalid(msg) => {
            // B is not a trust anchor, so chain cannot be verified
            assert!(
                msg.contains("untrusted")
                    || msg.contains("Untrusted")
                    || msg.contains("signature")
                    || msg.contains("Signature"),
                "stripped proof should produce untrusted/signature error, got: {}",
                msg
            );
        }
        other => panic!(
            "expected Invalid for stripped proof chain, got: {:?}",
            other
        ),
    }
}

// ── CAP-05: Replay attack ──────────────────────────────────────────────
/// Stateless validator: same token validates identically on repeated calls.
/// Different tokens with same scopes have distinct nonces and both validate
/// independently. Documents: replay protection is router-layer, not validator.
#[test]
fn test_cap_05_replay_attack() {
    let validator = make_validator();
    let key = root_key();

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

    // Nonce must be present and non-empty
    assert!(!token_1.nonce.is_empty(), "token must have a nonce");

    let encoded_1 = token_1.encode().unwrap();

    // First validation: extract scopes and verify they're correct
    let info_1 = match validator.validate(&encoded_1) {
        ValidationResult::Valid(info) => info,
        other => panic!("expected Valid on first validation, got: {:?}", other),
    };
    assert!(
        info_1.has_scope(Action::Write, "/lights/room1"),
        "validated token must grant write:/lights/room1"
    );

    // Second validation of same token: must return identical scopes (no degradation)
    let info_2 = match validator.validate(&encoded_1) {
        ValidationResult::Valid(info) => info,
        other => panic!("expected Valid on replay, got: {:?}", other),
    };
    assert!(
        info_2.has_scope(Action::Write, "/lights/room1"),
        "replayed token must still grant same scopes (stateless = no degradation)"
    );

    // Create a SECOND token with same scopes but different nonce
    let token_2 = CapabilityToken::create_root(
        &key,
        vec!["write:/lights/**".to_string()],
        future_timestamp(),
        None,
    )
    .unwrap();
    assert_ne!(
        token_1.nonce, token_2.nonce,
        "two tokens must have distinct nonces"
    );

    let encoded_2 = token_2.encode().unwrap();
    let info_3 = match validator.validate(&encoded_2) {
        ValidationResult::Valid(info) => info,
        other => panic!("expected Valid for second token, got: {:?}", other),
    };
    assert!(
        info_3.has_scope(Action::Write, "/lights/room1"),
        "second token with same scopes must also validate"
    );

    // NOTE: Replay protection is router-layer; validator is stateless by design.
    // This test proves the validator returns consistent results across calls.
}

// ── CAP-06: Nonce collision ────────────────────────────────────────────
/// Generate 100K tokens and verify all nonces are unique.
#[test]
fn test_cap_06_nonce_collision() {
    let key = root_key();
    let mut nonces = HashSet::new();

    for _ in 0..100_000 {
        let token = CapabilityToken::create_root(
            &key,
            vec!["read:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();
        assert!(
            nonces.insert(token.nonce.clone()),
            "nonce collision detected: {}",
            token.nonce
        );
    }

    assert_eq!(nonces.len(), 100_000);
}

// ── CAP-07: Trust anchor runtime manipulation ──────────────────────────
/// Verify there is no protocol path to add trust anchors at runtime
/// through token delegation — only the constructor or add_trust_anchor
/// (which requires &mut) can add them.
#[test]
fn test_cap_07_trust_anchor_runtime() {
    let key_a = root_key();
    let key_b = SigningKey::from_bytes(&[2u8; 32]);

    let pub_a = key_a.verifying_key().to_bytes().to_vec();
    let validator = CapabilityValidator::new(vec![pub_a], 5);

    // key_b is NOT a trust anchor
    let token_b = CapabilityToken::create_root(
        &key_b,
        vec!["admin:/**".to_string()],
        future_timestamp(),
        None,
    )
    .unwrap();
    let encoded_b = token_b.encode().unwrap();
    assert!(
        matches!(validator.validate(&encoded_b), ValidationResult::Invalid(_)),
        "key_b must not be accepted as trust anchor"
    );

    // Delegating from key_a to key_b doesn't make key_b a trust anchor
    let root_a = CapabilityToken::create_root(
        &key_a,
        vec!["admin:/**".to_string()],
        future_timestamp(),
        None,
    )
    .unwrap();

    let delegated = root_a
        .delegate(
            &key_b,
            vec!["admin:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();

    // The delegated token should be valid (chain rooted in key_a)
    let encoded_del = delegated.encode().unwrap();
    assert!(matches!(
        validator.validate(&encoded_del),
        ValidationResult::Valid(_)
    ));

    // But a fresh root from key_b is still rejected
    assert!(matches!(
        validator.validate(&encoded_b),
        ValidationResult::Invalid(_)
    ));
}

// ── CAP-08: Malformed msgpack ──────────────────────────────────────────
/// Random bytes, truncated payloads, wrong types, bad base64 — all must
/// produce errors without panicking.
#[test]
fn test_cap_08_malformed_msgpack() {
    use base64::Engine;
    let validator = make_validator();

    // Random bytes
    let random = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .encode([0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02, 0x03, 0x04]);
    assert!(matches!(
        validator.validate(&format!("cap_{}", random)),
        ValidationResult::Invalid(_)
    ));

    // Truncated header
    let truncated = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([0x92]);
    assert!(matches!(
        validator.validate(&format!("cap_{}", truncated)),
        ValidationResult::Invalid(_)
    ));

    // Invalid base64
    assert!(matches!(
        validator.validate("cap_!!!not-valid!!!"),
        ValidationResult::Invalid(_)
    ));

    // Wrong prefix
    assert!(matches!(
        validator.validate("cpsk_something"),
        ValidationResult::NotMyToken
    ));

    // Empty after prefix
    assert!(matches!(
        validator.validate("cap_"),
        ValidationResult::Invalid(_)
    ));

    // Very long garbage
    let long_garbage = "A".repeat(10000);
    let long_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(long_garbage.as_bytes());
    assert!(matches!(
        validator.validate(&format!("cap_{}", long_b64)),
        ValidationResult::Invalid(_)
    ));

    // Valid msgpack but wrong structure (an integer)
    let int_bytes = rmp_serde::to_vec_named(&42u32).unwrap();
    let int_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&int_bytes);
    assert!(matches!(
        validator.validate(&format!("cap_{}", int_b64)),
        ValidationResult::Invalid(_)
    ));
}

// ── CAP-09: Action hierarchy escalation ────────────────────────────────
/// A `read` token must not delegate `write`. A `write` token must not
/// delegate `admin`.
#[test]
fn test_cap_09_action_hierarchy_escalation() {
    let key_a = root_key();
    let key_b = SigningKey::from_bytes(&[2u8; 32]);

    // read -> write delegation must fail
    let read_root = CapabilityToken::create_root(
        &key_a,
        vec!["read:/**".to_string()],
        future_timestamp(),
        None,
    )
    .unwrap();

    let result = read_root.delegate(
        &key_b,
        vec!["write:/**".to_string()],
        future_timestamp(),
        None,
    );
    assert!(result.is_err(), "read -> write delegation must be rejected");

    // write -> admin delegation must fail
    let write_root = CapabilityToken::create_root(
        &key_a,
        vec!["write:/**".to_string()],
        future_timestamp(),
        None,
    )
    .unwrap();

    let result = write_root.delegate(
        &key_b,
        vec!["admin:/**".to_string()],
        future_timestamp(),
        None,
    );
    assert!(
        result.is_err(),
        "write -> admin delegation must be rejected"
    );

    // admin -> write -> read is fine (monotonic attenuation)
    let admin_root = CapabilityToken::create_root(
        &key_a,
        vec!["admin:/**".to_string()],
        future_timestamp(),
        None,
    )
    .unwrap();

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

    let key_c = SigningKey::from_bytes(&[3u8; 32]);
    let read_grandchild = write_child
        .delegate(
            &key_c,
            vec!["read:/**".to_string()],
            future_timestamp(),
            None,
        )
        .unwrap();

    assert!(read_grandchild.verify_signature().is_ok());
}

// ── CAP-10: Pattern wildcard injection ─────────────────────────────────
/// FINDING: pattern_is_subset treats `**` as a single segment when parent
/// has `*`. This allows scope widening from /lights/* to /lights/**
/// (one-level → recursive). Documents the bug and validates it end-to-end.
#[test]
fn test_cap_10_pattern_wildcard_injection() {
    use clasp_caps::token::pattern_is_subset;

    let key_a = root_key();
    let key_b = SigningKey::from_bytes(&[2u8; 32]);
    let validator = make_validator();

    // FIXED: pattern_is_subset now correctly rejects ** as subset of *
    assert!(
        !pattern_is_subset("/lights/**", "/lights/*"),
        "/lights/** is wider than /lights/*, not a subset"
    );

    // Delegation from /lights/* to /lights/** must be rejected (AttenuationViolation)
    let narrow_root = CapabilityToken::create_root(
        &key_a,
        vec!["write:/lights/*".to_string()],
        future_timestamp(),
        None,
    )
    .unwrap();

    let result = narrow_root.delegate(
        &key_b,
        vec!["write:/lights/**".to_string()],
        future_timestamp(),
        None,
    );
    assert!(
        result.is_err(),
        "delegation from /* to /** must be rejected"
    );
    assert!(
        matches!(result.unwrap_err(), CapError::AttenuationViolation(_)),
        "error must be AttenuationViolation"
    );

    // Parent token should NOT grant multi-level
    let parent_encoded = narrow_root.encode().unwrap();
    let parent_info = match validator.validate(&parent_encoded) {
        ValidationResult::Valid(info) => info,
        other => panic!("parent should validate, got: {:?}", other),
    };
    assert!(
        !parent_info.has_scope(Action::Write, "/lights/room1/brightness"),
        "parent with /lights/* must NOT grant multi-level access"
    );

    // Widening to a completely different namespace is still blocked
    let result = narrow_root.delegate(
        &key_b,
        vec!["write:/**".to_string()],
        future_timestamp(),
        None,
    );
    assert!(result.is_err(), "/** must not be allowed under /lights/*");
}