spoke-operations 0.19.0

SPOKE lifecycle helpers — pure functions over spoke-schemas wire types
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
//! Pure grant-coverage evaluation (§6.5, MEM-R006/R017) and the
//! non-amplification checks for `memory.grants.grant` (§7.9).
//!
//! Providers hold grant state; these helpers are the reusable policy
//! primitives: `grant_covers` answers whether one grant admits one op
//! requirement, and `validate_grant_issuance` answers whether a granter may
//! issue a new grant without amplifying its own coverage.

use crate::result::{spoke_ok, spoke_reject, SpokeRejectCode, SpokeResult};
use chrono::{DateTime, Utc};
use spoke_schemas::MemoryGrant;

/// What one op needs from a single grant (§6.5 evaluation rules, §7 tables).
#[derive(Debug, Clone)]
pub struct GrantRequirement<'a> {
    /// Required capability from the §7 grant table (`admin` in a grant
    /// implies every capability within that grant's coverage).
    pub capability: &'a str,
    /// Subject the op names; `None` for space-wide ops.
    pub subject_id: Option<&'a str>,
    /// Placement contexts the op names (capture placement, read-by-placement).
    /// Empty = the op names no contexts.
    pub context_ids: Vec<String>,
    /// The op reads shared visibility (`shared_only`, `include_shared`, by-id
    /// shared read, profile read, whole-subject export).
    pub reads_shared: bool,
    /// The op uses a `subject_all` selection — only unrestricted grants pass.
    pub subject_all: bool,
}

struct GrantView<'a> {
    capabilities: &'a [String],
    subject_id: Option<&'a str>,
    /// Empty = unrestricted within the grant's subject/space scope (§6.5).
    context_ids: &'a [String],
    shared_access: bool,
    expires_at: Option<DateTime<Utc>>,
    revoked_at: Option<DateTime<Utc>>,
    principal_id: &'a str,
    space_id: &'a str,
}

fn view_of(grant: &MemoryGrant) -> GrantView<'_> {
    match grant {
        MemoryGrant::RestrictedGrant(grant) => GrantView {
            capabilities: &grant.capabilities,
            subject_id: grant.subject_id.as_ref().map(|s| s.as_str()),
            context_ids: &grant.context_ids,
            shared_access: grant.shared_access.unwrap_or(false),
            expires_at: grant.expires_at.as_deref().copied(),
            revoked_at: grant.revoked_at.as_deref().copied(),
            principal_id: grant.principal_id.as_str(),
            space_id: grant.space_id.as_str(),
        },
        MemoryGrant::UnrestrictedGrant(grant) => GrantView {
            capabilities: &grant.capabilities,
            subject_id: grant.subject_id.as_ref().map(|s| s.as_str()),
            context_ids: &[],
            shared_access: false,
            expires_at: grant.expires_at.as_deref().copied(),
            revoked_at: grant.revoked_at.as_deref().copied(),
            principal_id: grant.principal_id.as_str(),
            space_id: grant.space_id.as_str(),
        },
    }
}

/// §6.5 grant evaluation (MEM-R006/R017): is `grant` unexpired, unrevoked,
/// and sufficient for `requirement`?
pub fn grant_covers(
    grant: &MemoryGrant,
    principal_id: &str,
    space_id: &str,
    now: DateTime<Utc>,
    requirement: &GrantRequirement<'_>,
) -> bool {
    let view = view_of(grant);
    if view.principal_id != principal_id || view.space_id != space_id {
        return false;
    }
    if view.revoked_at.is_some() {
        return false;
    }
    if view.expires_at.is_some_and(|expires_at| expires_at <= now) {
        return false;
    }
    // Subject scope (§6.5): a subject-scoped grant never covers another
    // subject, and never covers space-wide ops — a space-wide requirement
    // needs a space-wide grant.
    match (requirement.subject_id, view.subject_id) {
        (Some(op_subject), Some(grant_subject)) if op_subject != grant_subject => return false,
        (None, Some(_)) => return false,
        _ => {}
    }
    let has_capability = view.capabilities.iter().any(|capability| {
        capability == requirement.capability || capability == "admin"
    });
    if !has_capability {
        return false;
    }
    let unrestricted = view.context_ids.is_empty();
    if !requirement.context_ids.is_empty()
        && !unrestricted
        && !requirement
            .context_ids
            .iter()
            .all(|context| view.context_ids.contains(context))
    {
        return false;
    }
    if requirement.reads_shared && !unrestricted && !view.shared_access {
        return false;
    }
    if requirement.subject_all && !unrestricted {
        return false;
    }
    true
}

/// The grant being issued via `memory.grants.grant`.
#[derive(Debug, Clone)]
pub struct IssuedGrant<'a> {
    /// Requested capabilities (§7.9 `minItems: 1`, `uniqueItems: true` —
    /// callers validate; the protocol core vocabulary includes `admin`,
    /// which implies all other capabilities within the grant's coverage).
    pub capabilities: &'a [&'a str],
    /// `Some` = subject-scoped issuance; `None` = space-wide.
    pub subject_id: Option<&'a str>,
    /// Requested placement-context restriction; empty = unrestricted.
    pub context_ids: &'a [String],
    /// Requested shared visibility access (meaningful only when restricted).
    pub shared_access: bool,
    /// Requested expiry; `None` = non-expiring.
    pub expires_at: Option<DateTime<Utc>>,
}

fn not_authorized(reason: &str) -> SpokeResult<()> {
    spoke_reject(
        SpokeRejectCode::NotAuthorized,
        format!("Grant issuance would amplify granter coverage: {reason}"),
        None,
    )
}

/// §7.9 non-amplification, two stages:
///
/// 1. **Applicability** — a valid (unrevoked, unexpired) `admin` grant for
///    the principal and space whose coverage matches the issued grant's
///    facets: subject scope (space-wide issuance needs a space-wide admin
///    grant; subject-scoped issuance needs a space-wide or same-subject
///    grant), context scope (unrestricted issuance needs unrestricted
///    granter coverage; restricted issuance needs coverage of every issued
///    context), and the `shared_access` facet. Empty applicable set →
///    `NOT_AUTHORIZED`; the matching grant is the single-grant coverage §6.5
///    requires (disjoint grants are never unioned).
/// 2. **Expiry bound** — computed over the *applicable* set only: the
///    issued `expires_at` must be ≤ the earliest applicable admin expiry,
///    and a non-expiring issuance requires that no applicable admin grant
///    expires. Unrelated grants (different subject, disjoint contexts)
///    never enter the bound.
///
/// All failures reject `NOT_AUTHORIZED`.
pub fn validate_grant_issuance(
    granter_grants: &[MemoryGrant],
    principal_id: &str,
    space_id: &str,
    now: DateTime<Utc>,
    issued: &IssuedGrant<'_>,
) -> SpokeResult<()> {
    // Stage 1: applicable admin grants.
    let applicable: Vec<GrantView<'_>> = granter_grants
        .iter()
        .map(view_of)
        .filter(|view| view.principal_id == principal_id && view.space_id == space_id)
        .filter(|view| view.revoked_at.is_none())
        .filter(|view| view.expires_at.is_none_or(|expires_at| expires_at > now))
        .filter(|view| view.capabilities.iter().any(|capability| capability == "admin"))
        .filter(|view| {
            let subject_ok = match issued.subject_id {
                None => view.subject_id.is_none(),
                Some(subject) => {
                    view.subject_id.is_none() || view.subject_id == Some(subject)
                }
            };
            let contexts_ok = if issued.context_ids.is_empty() {
                view.context_ids.is_empty()
            } else {
                view.context_ids.is_empty()
                    || issued
                        .context_ids
                        .iter()
                        .all(|context| view.context_ids.contains(context))
            };
            let shared_ok =
                !issued.shared_access || view.context_ids.is_empty() || view.shared_access;
            subject_ok && contexts_ok && shared_ok
        })
        .collect();
    if applicable.is_empty() {
        return not_authorized(
            "no applicable admin grant matches the issued subject, contexts, and shared_access",
        );
    }

    // Stage 2: expiry bound over the applicable set only (§7.9 earliest
    // *applicable* grant expiry).
    let earliest_applicable_expiry = applicable.iter().filter_map(|view| view.expires_at).min();
    match (issued.expires_at, earliest_applicable_expiry) {
        (Some(issued_expiry), Some(earliest)) if issued_expiry > earliest => not_authorized(
            "expires_at is later than the earliest applicable admin grant expiry",
        ),
        (None, Some(_)) => {
            not_authorized("non-expiring issuance requires a non-expiring applicable admin grant")
        }
        _ => spoke_ok(()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{SpokeRejectCode, SpokeResult};
    use chrono::{DateTime, Duration, Utc};
    use serde_json::{json, Value};
    use spoke_schemas::MemoryGrant;

    const SPACE: &str = "sp_1";
    const GRANTEE: &str = "p1";

    fn now() -> DateTime<Utc> {
        DateTime::parse_from_rfc3339("2026-06-01T00:00:00Z")
            .expect("fixed now")
            .with_timezone(&Utc)
    }

    fn grant_json(extra: Value) -> Value {
        let mut base = json!({
            "schema_version": 1,
            "grant_id": "g1",
            "space_id": SPACE,
            "principal_id": GRANTEE,
            "capabilities": ["capture"],
            "created_at": "2026-01-01T00:00:00Z",
            "revision": 1,
            "extensions": {},
        });
        base.as_object_mut().expect("object").extend(
            extra.as_object().expect("extra object").clone(),
        );
        base
    }

    fn make_grant(extra: Value) -> MemoryGrant {
        serde_json::from_value(grant_json(extra)).expect("valid grant")
    }

    fn requirement(capability: &str) -> GrantRequirement<'_> {
        GrantRequirement {
            capability,
            subject_id: None,
            context_ids: Vec::new(),
            reads_shared: false,
            subject_all: false,
        }
    }

    #[test]
    fn grant_covers_capability_and_admin_implies_all() {
        let grant = make_grant(json!({}));
        assert!(grant_covers(&grant, GRANTEE, SPACE, now(), &requirement("capture")));
        assert!(!grant_covers(&grant, GRANTEE, SPACE, now(), &requirement("recall")));

        let admin = make_grant(json!({"capabilities": ["admin"]}));
        assert!(grant_covers(&admin, GRANTEE, SPACE, now(), &requirement("recall")));
    }

    #[test]
    fn grant_covers_rejects_wrong_principal_space_expired_revoked() {
        let grant = make_grant(json!({}));
        assert!(!grant_covers(&grant, "p_other", SPACE, now(), &requirement("capture")));
        assert!(!grant_covers(&grant, GRANTEE, "sp_other", now(), &requirement("capture")));

        let expired = make_grant(json!({"expires_at": "2026-01-02T00:00:00Z"}));
        assert!(!grant_covers(&expired, GRANTEE, SPACE, now(), &requirement("capture")));

        let revoked = make_grant(json!({"revoked_at": "2026-01-02T00:00:00Z"}));
        assert!(!grant_covers(&revoked, GRANTEE, SPACE, now(), &requirement("capture")));

        let future = make_grant(json!({"expires_at": "2027-01-01T00:00:00Z"}));
        assert!(grant_covers(&future, GRANTEE, SPACE, now(), &requirement("capture")));
    }

    #[test]
    fn grant_covers_subject_matching() {
        let subject_grant = make_grant(json!({"subject_id": "s1"}));
        let req_s1 = GrantRequirement { subject_id: Some("s1"), ..requirement("capture") };
        let req_s2 = GrantRequirement { subject_id: Some("s2"), ..requirement("capture") };
        assert!(grant_covers(&subject_grant, GRANTEE, SPACE, now(), &req_s1));
        assert!(!grant_covers(&subject_grant, GRANTEE, SPACE, now(), &req_s2));

        let space_wide = make_grant(json!({}));
        assert!(grant_covers(&space_wide, GRANTEE, SPACE, now(), &req_s2));
    }

    #[test]
    fn grant_covers_space_wide_ops_require_space_wide_grants() {
        // §6.5: a subject-scoped grant never covers space-wide operations.
        let subject_grant = make_grant(json!({"subject_id": "s1"}));
        let space_wide_op = requirement("capture");
        assert!(!grant_covers(&subject_grant, GRANTEE, SPACE, now(), &space_wide_op));

        let space_wide = make_grant(json!({}));
        assert!(grant_covers(&space_wide, GRANTEE, SPACE, now(), &space_wide_op));
    }

    #[test]
    fn grant_covers_context_coverage() {
        let restricted = make_grant(json!({"context_ids": ["c1"]}));
        let op_c1 = GrantRequirement {
            context_ids: vec!["c1".to_owned()],
            ..requirement("capture")
        };
        let op_c2 = GrantRequirement {
            context_ids: vec!["c2".to_owned()],
            ..requirement("capture")
        };
        assert!(grant_covers(&restricted, GRANTEE, SPACE, now(), &op_c1));
        assert!(!grant_covers(&restricted, GRANTEE, SPACE, now(), &op_c2));

        let unrestricted = make_grant(json!({}));
        assert!(grant_covers(&unrestricted, GRANTEE, SPACE, now(), &op_c2));

        let restricted_two = make_grant(json!({"context_ids": ["c1", "c2"]}));
        let op_both = GrantRequirement {
            context_ids: vec!["c1".to_owned(), "c2".to_owned()],
            ..requirement("capture")
        };
        assert!(grant_covers(&restricted_two, GRANTEE, SPACE, now(), &op_both));
    }

    #[test]
    fn grant_covers_shared_visibility_requires_unrestricted_or_shared_access() {
        let req_shared = GrantRequirement { reads_shared: true, ..requirement("records_read") };

        let restricted_no_shared = make_grant(json!({
            "capabilities": ["records_read"],
            "context_ids": ["c1"],
        }));
        assert!(!grant_covers(&restricted_no_shared, GRANTEE, SPACE, now(), &req_shared));

        let restricted_shared = make_grant(json!({
            "capabilities": ["records_read"],
            "context_ids": ["c1"],
            "shared_access": true,
        }));
        assert!(grant_covers(&restricted_shared, GRANTEE, SPACE, now(), &req_shared));

        let unrestricted = make_grant(json!({"capabilities": ["records_read"]}));
        assert!(grant_covers(&unrestricted, GRANTEE, SPACE, now(), &req_shared));
    }

    #[test]
    fn grant_covers_subject_all_never_passes_context_limited_grants() {
        let req_all = GrantRequirement { subject_all: true, ..requirement("records_read") };

        let restricted = make_grant(json!({
            "capabilities": ["records_read"],
            "context_ids": ["c1"],
            "shared_access": true,
        }));
        assert!(!grant_covers(&restricted, GRANTEE, SPACE, now(), &req_all));

        let unrestricted = make_grant(json!({"capabilities": ["records_read"]}));
        assert!(grant_covers(&unrestricted, GRANTEE, SPACE, now(), &req_all));

        let space_wide_restricted = make_grant(json!({
            "capabilities": ["records_read"],
            "context_ids": ["c1"],
        }));
        assert!(!grant_covers(&space_wide_restricted, GRANTEE, SPACE, now(), &req_all));
    }

    fn issued<'a>(capabilities: &'a [&'a str]) -> IssuedGrant<'a> {
        IssuedGrant {
            capabilities,
            subject_id: None,
            context_ids: &[],
            shared_access: false,
            expires_at: None,
        }
    }

    #[test]
    fn issuance_requires_an_applicable_admin_grant() {
        // §7.9 Grant: `admin`. A capture-only principal can never issue.
        let capture_only = vec![make_grant(json!({"capabilities": ["capture"]}))];
        match validate_grant_issuance(&capture_only, GRANTEE, SPACE, now(), &issued(&["capture"])) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }

        // An admin grant implies every capability within its coverage.
        let admin_granter = vec![make_grant(json!({"capabilities": ["admin"]}))];
        assert!(
            validate_grant_issuance(&admin_granter, GRANTEE, SPACE, now(), &issued(&["recall"]))
                .is_ok()
        );
    }

    #[test]
    fn issuance_rejects_subject_scope_amplification() {
        let granter = vec![make_grant(json!({
            "capabilities": ["admin"],
            "subject_id": "s1",
        }))];
        let cross_subject = IssuedGrant { subject_id: Some("s2"), ..issued(&["capture"]) };
        match validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &cross_subject) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }

        let same_subject = IssuedGrant { subject_id: Some("s1"), ..issued(&["capture"]) };
        assert!(validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &same_subject).is_ok());

        let space_wide_granter = vec![make_grant(json!({"capabilities": ["admin"]}))];
        assert!(
            validate_grant_issuance(&space_wide_granter, GRANTEE, SPACE, now(), &cross_subject)
                .is_ok()
        );
    }

    #[test]
    fn issuance_rejects_context_amplification_and_unrestricted_escalation() {
        let granter = vec![make_grant(json!({
            "capabilities": ["admin"],
            "context_ids": ["c1"],
        }))];
        let wider = IssuedGrant {
            context_ids: &["c1".to_owned(), "c2".to_owned()],
            ..issued(&["capture"])
        };
        match validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &wider) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }

        // Critical: a restricted granter can never issue an unrestricted
        // (contexts omitted) grant — that would escalate to all contexts,
        // shared visibility, and `subject_all`.
        let unrestricted_issuance = issued(&["capture"]);
        match validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &unrestricted_issuance) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }

        let same = IssuedGrant { context_ids: &["c1".to_owned()], ..issued(&["capture"]) };
        assert!(validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &same).is_ok());

        let unrestricted_granter = vec![make_grant(json!({"capabilities": ["admin"]}))];
        assert!(
            validate_grant_issuance(&unrestricted_granter, GRANTEE, SPACE, now(), &wider).is_ok()
        );
    }

    #[test]
    fn issuance_never_unions_disjoint_grants() {
        // §6.5/§7.9: one grant must subsume the issuance. Admin for c1 plus
        // a capture grant for c2 cannot jointly authorize a c2 issuance.
        let granter = vec![
            make_grant(json!({"capabilities": ["admin"], "context_ids": ["c1"]})),
            make_grant(json!({"capabilities": ["capture"], "context_ids": ["c2"]})),
        ];
        let issued_c2 = IssuedGrant {
            context_ids: &["c2".to_owned()],
            ..issued(&["capture"])
        };
        match validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &issued_c2) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }

        // Two disjoint admin grants cannot jointly cover a wide issuance.
        let disjoint_admins = vec![
            make_grant(json!({"capabilities": ["admin"], "context_ids": ["c1"]})),
            make_grant(json!({"capabilities": ["admin"], "context_ids": ["c2"]})),
        ];
        let issued_both = IssuedGrant {
            context_ids: &["c1".to_owned(), "c2".to_owned()],
            ..issued(&["capture"])
        };
        match validate_grant_issuance(&disjoint_admins, GRANTEE, SPACE, now(), &issued_both) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }
    }

    #[test]
    fn issuance_rejects_shared_access_without_granter_shared_access() {
        let granter = vec![make_grant(json!({
            "capabilities": ["admin"],
            "context_ids": ["c1"],
        }))];
        let shared = IssuedGrant {
            context_ids: &["c1".to_owned()],
            shared_access: true,
            ..issued(&["records_read"])
        };
        match validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &shared) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }

        let granter_with_shared = vec![make_grant(json!({
            "capabilities": ["admin"],
            "context_ids": ["c1"],
            "shared_access": true,
        }))];
        assert!(
            validate_grant_issuance(&granter_with_shared, GRANTEE, SPACE, now(), &shared).is_ok()
        );
    }

    #[test]
    fn issuance_expiry_cannot_outlive_granter() {
        let granter = vec![make_grant(json!({
            "capabilities": ["admin"],
            "expires_at": "2027-01-01T00:00:00Z",
        }))];

        // Non-expiring issuance while the granter's coverage expires → reject.
        match validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &issued(&["capture"])) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }

        // Longer-lived issuance → reject.
        let longer: DateTime<Utc> = DateTime::parse_from_rfc3339("2027-06-01T00:00:00Z")
            .expect("date")
            .with_timezone(&Utc);
        let too_long = IssuedGrant { expires_at: Some(longer), ..issued(&["capture"]) };
        match validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &too_long) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }

        // Shorter-lived issuance → ok.
        let shorter = IssuedGrant {
            expires_at: Some(now() + Duration::days(30)),
            ..issued(&["capture"])
        };
        assert!(validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &shorter).is_ok());

        // Non-expiring granter may issue any expiry.
        let eternal_granter = vec![make_grant(json!({"capabilities": ["admin"]}))];
        assert!(
            validate_grant_issuance(&eternal_granter, GRANTEE, SPACE, now(), &too_long).is_ok()
        );
    }

    #[test]
    fn issuance_expiry_is_bounded_by_earliest_applicable_admin_expiry() {
        // Two identical unrestricted admin grants expiring 2027 and 2028:
        // the 2028 expiry does not loosen the bound — the earliest applies.
        let granter = vec![
            make_grant(json!({
                "capabilities": ["admin"],
                "expires_at": "2027-01-01T00:00:00Z",
            })),
            make_grant(json!({
                "capabilities": ["admin"],
                "expires_at": "2028-01-01T00:00:00Z",
            })),
        ];

        let expiry_2028: DateTime<Utc> = DateTime::parse_from_rfc3339("2028-01-01T00:00:00Z")
            .expect("date")
            .with_timezone(&Utc);
        let at_2028 = IssuedGrant { expires_at: Some(expiry_2028), ..issued(&["capture"]) };
        match validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &at_2028) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }

        let expiry_2027: DateTime<Utc> = DateTime::parse_from_rfc3339("2027-01-01T00:00:00Z")
            .expect("date")
            .with_timezone(&Utc);
        let at_2027 = IssuedGrant { expires_at: Some(expiry_2027), ..issued(&["capture"]) };
        assert!(validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &at_2027).is_ok());

        let earlier = IssuedGrant {
            expires_at: Some(now() + Duration::days(30)),
            ..issued(&["capture"])
        };
        assert!(validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &earlier).is_ok());

        // Non-expiring issuance is rejected while ANY applicable admin
        // grant expires, even though a 2028-expiring grant also covers.
        let non_expiring = issued(&["capture"]);
        match validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &non_expiring) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }
    }

    #[test]
    fn issuance_expiry_bound_ignores_inapplicable_subject_scoped_grants() {
        // An expiring admin grant for s1 must not bound an s2 issuance.
        let granter = vec![
            make_grant(json!({"capabilities": ["admin"], "subject_id": "s2"})),
            make_grant(json!({
                "capabilities": ["admin"],
                "subject_id": "s1",
                "expires_at": "2027-01-01T00:00:00Z",
            })),
        ];

        let s2_non_expiring = IssuedGrant { subject_id: Some("s2"), ..issued(&["capture"]) };
        assert!(
            validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &s2_non_expiring).is_ok()
        );

        let expiry_2028: DateTime<Utc> = DateTime::parse_from_rfc3339("2028-01-01T00:00:00Z")
            .expect("date")
            .with_timezone(&Utc);
        let s2_at_2028 = IssuedGrant {
            subject_id: Some("s2"),
            expires_at: Some(expiry_2028),
            ..issued(&["capture"])
        };
        assert!(
            validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &s2_at_2028).is_ok()
        );

        // The s1 issuance IS bounded by the s1 grant.
        let s1_non_expiring = IssuedGrant { subject_id: Some("s1"), ..issued(&["capture"]) };
        match validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &s1_non_expiring) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }
    }

    #[test]
    fn issuance_expiry_bound_ignores_context_disjoint_grants() {
        // An expiring admin grant restricted to c1 must not bound a c2
        // issuance.
        let granter = vec![
            make_grant(json!({"capabilities": ["admin"], "context_ids": ["c2"]})),
            make_grant(json!({
                "capabilities": ["admin"],
                "context_ids": ["c1"],
                "expires_at": "2027-01-01T00:00:00Z",
            })),
        ];

        let c2_non_expiring = IssuedGrant {
            context_ids: &["c2".to_owned()],
            ..issued(&["capture"])
        };
        assert!(
            validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &c2_non_expiring).is_ok()
        );

        let expiry_2028: DateTime<Utc> = DateTime::parse_from_rfc3339("2028-01-01T00:00:00Z")
            .expect("date")
            .with_timezone(&Utc);
        let c2_at_2028 = IssuedGrant {
            context_ids: &["c2".to_owned()],
            expires_at: Some(expiry_2028),
            ..issued(&["capture"])
        };
        assert!(
            validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &c2_at_2028).is_ok()
        );

        // The c1 issuance IS bounded by the c1 grant.
        let c1_non_expiring = IssuedGrant {
            context_ids: &["c1".to_owned()],
            ..issued(&["capture"])
        };
        match validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &c1_non_expiring) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }
    }

    #[test]
    fn issuance_ignores_other_principals_and_spaces() {
        let other_principal = make_grant(json!({"principal_id": "p9", "capabilities": ["admin"]}));
        let other_space = make_grant(json!({"space_id": "sp_9", "capabilities": ["admin"]}));
        let granter = vec![other_principal, other_space];
        match validate_grant_issuance(&granter, GRANTEE, SPACE, now(), &issued(&["capture"])) {
            SpokeResult::Reject(reject) => assert_eq!(reject.code, SpokeRejectCode::NotAuthorized),
            SpokeResult::Ok(_) => panic!("expected reject"),
        }
    }
}