Skip to main content

kaniop_radius/reconcile/
token.rs

1//! Pure token planner for the RADIUS service account.
2//!
3//! Every reconcile observes the world (tokens on the dedicated Kanidm account,
4//! owned config Secrets, the Deployment pod template, ReplicaSets and pods)
5//! and [`plan_tokens`] decides which token pods should use, which tokens to
6//! revoke and which config Secrets to garbage-collect. The planner performs no
7//! I/O and never reads CR status, so losing status cannot change a decision.
8//!
9//! Safety invariants, each covered by a test below:
10//!
11//! - The current token, the template's token and every token a consumer
12//!   (template, ReplicaSet, pod) references are never revoked.
13//! - If any consumer reference cannot be resolved to a token id (unparsable
14//!   annotation, or a mounted config Secret that is gone or carries no
15//!   parsable token id), nothing is revoked in that pass: the planner cannot
16//!   prove which token that consumer holds.
17//! - No token younger than [`TokenPolicy::orphan_grace`] is revoked, whether
18//!   or not it has an owned Secret. A token minted by a reconcile that crashed
19//!   (or is still in flight) before its Secret or Deployment landed is
20//!   therefore safe until the grace expires.
21//! - A config change alone never mints: the current token is derived from the
22//!   template's Secret, not from the rendered content.
23//! - Replication lag never mints twice: the template's token is kept while it
24//!   is missing from the token list only if every config Secret naming it is
25//!   younger than the orphan grace. A token that is not listed is never
26//!   revoked, so this rule cannot revoke anything.
27//! - Minting never raises the account above [`TokenPolicy::max_tokens`].
28//! - Output lists are sorted, so equal inputs give equal plans.
29//!
30//! Clock assumption: `issued_at` and `expiry` come from the Kanidm server
31//! clock and `now` from the operator clock. Skew is assumed to be well below
32//! the orphan grace (10 minutes) and the safety margin (1 day). If Kanidm
33//! runs ahead, tokens look younger and are held longer (safe direction); if
34//! it runs behind, the grace shrinks by the skew. All date arithmetic is
35//! checked: an out-of-range result means "not yet" for due and grace checks
36//! and "already" for the expiry check, so overflow never panics and always
37//! errs toward keeping tokens alive and minting early.
38//!
39//! Executors must take `revoke` and `gc_secrets` only from a plan computed on
40//! a fresh observation made after the Deployment apply (reconcile step 8),
41//! never from the plan that decided to mint.
42
43use std::collections::{BTreeMap, BTreeSet};
44
45use time::{Duration, OffsetDateTime};
46use uuid::Uuid;
47
48use kaniop_operator::crd::SecretRotation;
49
50/// Tokens younger than this are never revoked (crash and in-flight safety).
51pub const ORPHAN_GRACE: Duration = Duration::minutes(10);
52/// Upper bound on tokens on the account; minting stops at this count.
53pub const MAX_TOKENS: usize = 4;
54/// A token whose expiry falls within this margin is replaced before it lapses.
55pub const SAFETY_MARGIN: Duration = Duration::days(1);
56/// A blocked reconcile warns when the running token expires within this
57/// window: twice [`SAFETY_MARGIN`], so the warning comes a margin before the
58/// planner would have replaced the token.
59pub const EXPIRY_WARNING: Duration = Duration::days(2);
60/// Longest accepted rotation period (matches the spec validation in
61/// `inputs::validate_spec`).
62const MAX_PERIOD_DAYS: i64 = 365;
63
64/// A token listed on the dedicated Kanidm account.
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct ObservedToken {
67    pub id: Uuid,
68    /// Kanidm `ApiToken.issued_at` (Kanidm server clock).
69    pub issued_at: OffsetDateTime,
70    /// Kanidm `ApiToken.expiry`; `None` never expires.
71    pub expiry: Option<OffsetDateTime>,
72}
73
74/// An owned config Secret, as read from the API.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct ObservedSecret {
77    pub name: String,
78    /// Raw `kaniop.rs/radius-token-id` annotation; parsed by the planner.
79    pub token_id: Option<String>,
80    /// Raw `kaniop.rs/radius-rotation-request` annotation.
81    pub rotation_request: Option<String>,
82    /// Whether a non-empty `auth_token` could be read from the Secret data.
83    pub bearer_readable: bool,
84    /// `metadata.creationTimestamp` (API server clock), if set.
85    pub created_at: Option<OffsetDateTime>,
86}
87
88/// What the Deployment pod template points at.
89#[derive(Clone, Debug, Default, PartialEq, Eq)]
90pub struct TemplateRef {
91    /// Raw `kaniop.rs/radius-token-id` template annotation.
92    pub token_id: Option<String>,
93    /// Name of the config Secret the template mounts.
94    pub config_secret: Option<String>,
95}
96
97/// Kind of a running consumer of a token.
98#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
99pub enum ConsumerKind {
100    /// A ReplicaSet owned by the Deployment that still has replicas.
101    ReplicaSet,
102    /// A non-terminal pod (Running, Pending, Unknown or Terminating).
103    Pod,
104}
105
106/// A ReplicaSet or pod that may hold a token.
107///
108/// The observer includes every ReplicaSet with replicas and every pod that is
109/// not Succeeded/Failed and either carries the token-id annotation or mounts a
110/// config Secret it identifies as ours. It lists each such Secret name even if
111/// the Secret no longer exists, so the planner can tell the reference is
112/// unresolved instead of silently dropping it.
113#[derive(Clone, Debug, PartialEq, Eq)]
114pub struct Consumer {
115    pub kind: ConsumerKind,
116    pub name: String,
117    /// Raw `kaniop.rs/radius-token-id` annotation.
118    pub token_id: Option<String>,
119    /// Config Secrets mounted by this consumer.
120    pub config_secrets: Vec<String>,
121}
122
123impl Consumer {
124    /// `replicaset/<name>` or `pod/<name>`, as used in status and events.
125    pub fn label(&self) -> String {
126        let kind = match self.kind {
127            ConsumerKind::ReplicaSet => "replicaset",
128            ConsumerKind::Pod => "pod",
129        };
130        format!("{kind}/{}", self.name)
131    }
132}
133
134/// Everything the planner looks at. Deliberately has no CR status field.
135#[derive(Clone, Debug, Default, PartialEq, Eq)]
136pub struct TokenWorld {
137    pub tokens: Vec<ObservedToken>,
138    pub secrets: Vec<ObservedSecret>,
139    /// `None` when the Deployment does not exist.
140    pub template: Option<TemplateRef>,
141    pub consumers: Vec<Consumer>,
142    /// Raw `kaniop.rs/radius-rotate-token` annotation on the CR.
143    pub rotate_request: Option<String>,
144}
145
146/// Rotation and safety parameters.
147#[derive(Clone, Debug, PartialEq, Eq)]
148pub struct TokenPolicy {
149    /// Rotation period when automatic rotation is enabled.
150    pub rotation_period: Option<Duration>,
151    pub safety_margin: Duration,
152    pub orphan_grace: Duration,
153    pub max_tokens: usize,
154}
155
156impl TokenPolicy {
157    /// Policy for a CR's `tokenRotation`. The shared `SecretRotation` type has
158    /// no schema bound, so `validate_spec` rejects periods outside 1..=365
159    /// before a pass gets here; the planner still clamps to 1..=365 days so a
160    /// 0 or huge value can never mint-loop or overflow a date.
161    pub fn from_spec(rotation: Option<&SecretRotation>) -> Self {
162        let rotation_period = rotation
163            .filter(|r| r.enabled)
164            .map(|r| Duration::days(i64::from(r.period_days).clamp(1, MAX_PERIOD_DAYS)));
165        Self {
166            rotation_period,
167            safety_margin: SAFETY_MARGIN,
168            orphan_grace: ORPHAN_GRACE,
169            max_tokens: MAX_TOKENS,
170        }
171    }
172
173    /// Expiry to request for a token minted at `now`: `now + 2 x period` when
174    /// rotation is enabled, otherwise none.
175    pub fn new_token_expiry(&self, now: OffsetDateTime) -> Option<OffsetDateTime> {
176        let period = self.rotation_period?;
177        now.checked_add(period.checked_mul(2)?)
178    }
179}
180
181/// Why a new token is needed.
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183pub enum MintReason {
184    /// No Deployment template, or the template references no token at all.
185    Initial,
186    /// The template's token cannot be used: its config Secret is missing, has
187    /// no readable bearer or no parsable token id, or the token is no longer
188    /// on the Kanidm account (revoked out of band).
189    BearerLost,
190    /// The token has expired or expires within the safety margin.
191    Expired,
192    /// `issued_at + periodDays` has passed.
193    Due,
194    /// The CR rotate annotation differs from the value on the config Secret.
195    Requested,
196}
197
198impl MintReason {
199    /// Stable reason string for conditions and events.
200    pub fn reason(self) -> &'static str {
201        match self {
202            Self::Initial => "Initial",
203            Self::BearerLost => "BearerLost",
204            Self::Expired => "Expired",
205            Self::Due => "Due",
206            Self::Requested => "Requested",
207        }
208    }
209}
210
211/// The token pods should run with after this reconcile.
212#[derive(Clone, Copy, Debug, PartialEq, Eq)]
213pub enum CurrentToken {
214    Keep(Uuid),
215    Mint(MintReason),
216    /// A mint is needed but the account already holds `max_tokens` tokens.
217    Blocked,
218}
219
220/// Planner output. All lists are sorted.
221#[derive(Clone, Debug, PartialEq, Eq)]
222pub struct TokenPlan {
223    pub current: CurrentToken,
224    /// Tokens to revoke.
225    pub revoke: Vec<Uuid>,
226    /// Owned config Secrets nothing references.
227    pub gc_secrets: Vec<String>,
228    /// Tokens on the account kept but not current (`status.retiringTokenIds`).
229    pub retiring: Vec<Uuid>,
230    /// Consumers whose token could not be resolved; while non-empty nothing
231    /// is revoked. Entries are `template`, `replicaset/<name>` or `pod/<name>`.
232    pub unresolved_consumers: Vec<String>,
233}
234
235/// Decide token actions from the observed world. Pure and deterministic.
236pub fn plan_tokens(world: &TokenWorld, policy: &TokenPolicy, now: OffsetDateTime) -> TokenPlan {
237    let tokens: BTreeMap<Uuid, &ObservedToken> = world.tokens.iter().map(|t| (t.id, t)).collect();
238    let secrets: BTreeMap<&str, &ObservedSecret> =
239        world.secrets.iter().map(|s| (s.name.as_str(), s)).collect();
240
241    let usage = resolve_usage(world, &secrets);
242
243    let current = match current_token(world, policy, now, &tokens, &secrets) {
244        Ok(id) => CurrentToken::Keep(id),
245        Err(_) if tokens.len() >= policy.max_tokens => CurrentToken::Blocked,
246        Err(reason) => CurrentToken::Mint(reason),
247    };
248    let keep_id = match current {
249        CurrentToken::Keep(id) => Some(id),
250        CurrentToken::Mint(_) | CurrentToken::Blocked => None,
251    };
252    let young = |t: &ObservedToken| !reached(t.issued_at, policy.orphan_grace, now);
253
254    let mut revoke = Vec::new();
255    let mut retiring = Vec::new();
256    for (id, t) in &tokens {
257        if Some(*id) == keep_id {
258            continue;
259        }
260        if usage.unresolved.is_empty() && !usage.in_use.contains(id) && !young(t) {
261            revoke.push(*id);
262        } else {
263            retiring.push(*id);
264        }
265    }
266
267    let gc_secrets = secrets
268        .values()
269        .filter(|s| !usage.referenced_secrets.contains(s.name.as_str()))
270        .filter(|s| {
271            // A Secret of a token still inside the grace may belong to an
272            // in-flight rollout; keep it until the token ages out.
273            parse_id(s.token_id.as_deref())
274                .and_then(|id| tokens.get(&id))
275                .is_none_or(|t| !young(t))
276        })
277        .map(|s| s.name.clone())
278        .collect();
279
280    TokenPlan {
281        current,
282        revoke,
283        gc_secrets,
284        retiring,
285        unresolved_consumers: usage.unresolved.into_iter().collect(),
286    }
287}
288
289/// Tokens and Secrets referenced by the template, ReplicaSets and pods.
290struct Usage<'a> {
291    in_use: BTreeSet<Uuid>,
292    referenced_secrets: BTreeSet<&'a str>,
293    unresolved: BTreeSet<String>,
294}
295
296fn resolve_usage<'a>(
297    world: &'a TokenWorld,
298    secrets: &BTreeMap<&str, &ObservedSecret>,
299) -> Usage<'a> {
300    let mut usage = Usage {
301        in_use: BTreeSet::new(),
302        referenced_secrets: BTreeSet::new(),
303        unresolved: BTreeSet::new(),
304    };
305    let template = world.template.as_ref().map(|t| {
306        (
307            "template".to_string(),
308            t.token_id.as_deref(),
309            t.config_secret
310                .iter()
311                .map(String::as_str)
312                .collect::<Vec<_>>(),
313        )
314    });
315    let consumers = world.consumers.iter().map(|c| {
316        (
317            c.label(),
318            c.token_id.as_deref(),
319            c.config_secrets.iter().map(String::as_str).collect(),
320        )
321    });
322    for (label, annotation, mounted) in template.into_iter().chain(consumers) {
323        // Every reference must resolve; one that does not means the consumer
324        // may hold a token we cannot name.
325        let mut resolved_any = false;
326        let mut all_resolved = true;
327        let ids = annotation
328            .map(|raw| Uuid::parse_str(raw).ok())
329            .into_iter()
330            .chain(mounted.iter().map(|name| {
331                usage.referenced_secrets.insert(name);
332                secrets
333                    .get(name)
334                    .and_then(|s| parse_id(s.token_id.as_deref()))
335            }));
336        for id in ids {
337            match id {
338                Some(id) => {
339                    usage.in_use.insert(id);
340                    resolved_any = true;
341                }
342                None => all_resolved = false,
343            }
344        }
345        if !(resolved_any && all_resolved) {
346            usage.unresolved.insert(label);
347        }
348    }
349    usage
350}
351
352/// The template's token if it can stay, else why a new one is needed.
353///
354/// The template's config Secret is authoritative: its token-id annotation was
355/// written together with the bearer the pods load. The template's own
356/// annotation only feeds the in-use set.
357fn current_token(
358    world: &TokenWorld,
359    policy: &TokenPolicy,
360    now: OffsetDateTime,
361    tokens: &BTreeMap<Uuid, &ObservedToken>,
362    secrets: &BTreeMap<&str, &ObservedSecret>,
363) -> Result<Uuid, MintReason> {
364    let template = world.template.as_ref().ok_or(MintReason::Initial)?;
365    let Some(secret_name) = template.config_secret.as_deref() else {
366        return Err(match template.token_id {
367            None => MintReason::Initial,
368            Some(_) => MintReason::BearerLost,
369        });
370    };
371    let secret = secrets
372        .get(secret_name)
373        .filter(|s| s.bearer_readable)
374        .ok_or(MintReason::BearerLost)?;
375    let id = parse_id(secret.token_id.as_deref()).ok_or(MintReason::BearerLost)?;
376    let Some(token) = tokens.get(&id) else {
377        // A token minted by the previous pass may not have replicated to the
378        // Kanidm server that answered the list yet: while every Secret naming
379        // it is inside the grace, keep it instead of minting again. A young
380        // Secret does not prove a young token (a config change re-renders an
381        // old one whose first Secret may be collected already), so a token
382        // revoked or expired out of band can be kept up to the grace; expiry
383        // and due cannot be judged without the token.
384        if !written_within_grace(world, id, policy, now) {
385            return Err(MintReason::BearerLost);
386        }
387        if rotation_requested(world, secret) {
388            return Err(MintReason::Requested);
389        }
390        return Ok(id);
391    };
392
393    let expiring = token.expiry.is_some_and(|expiry| {
394        expiry
395            .checked_sub(policy.safety_margin)
396            .is_none_or(|limit| now >= limit)
397    });
398    if expiring {
399        return Err(MintReason::Expired);
400    }
401    if policy
402        .rotation_period
403        .is_some_and(|period| reached(token.issued_at, period, now))
404    {
405        return Err(MintReason::Due);
406    }
407    if rotation_requested(world, secret) {
408        return Err(MintReason::Requested);
409    }
410    Ok(id)
411}
412
413/// The CR rotate annotation is set and differs from the value on `secret`.
414fn rotation_requested(world: &TokenWorld, secret: &ObservedSecret) -> bool {
415    non_empty(world.rotate_request.as_deref())
416        .is_some_and(|wanted| non_empty(secret.rotation_request.as_deref()) != Some(wanted))
417}
418
419/// Every config Secret naming token `id` was created less than the orphan
420/// grace ago. A Secret without a creation time counts as old.
421fn written_within_grace(
422    world: &TokenWorld,
423    id: Uuid,
424    policy: &TokenPolicy,
425    now: OffsetDateTime,
426) -> bool {
427    world
428        .secrets
429        .iter()
430        .filter(|s| parse_id(s.token_id.as_deref()) == Some(id))
431        .all(|s| {
432            s.created_at
433                .is_some_and(|created| !reached(created, policy.orphan_grace, now))
434        })
435}
436
437/// Whether `expiry` falls within [`EXPIRY_WARNING`] of `now` (or has
438/// passed); an out-of-range difference counts as within.
439pub fn expires_within_warning(expiry: OffsetDateTime, now: OffsetDateTime) -> bool {
440    expiry
441        .checked_sub(EXPIRY_WARNING)
442        .is_none_or(|limit| now >= limit)
443}
444
445/// `start + span <= now`; an out-of-range sum is "not yet".
446fn reached(start: OffsetDateTime, span: Duration, now: OffsetDateTime) -> bool {
447    start.checked_add(span).is_some_and(|at| now >= at)
448}
449
450fn parse_id(raw: Option<&str>) -> Option<Uuid> {
451    raw.and_then(|r| Uuid::parse_str(r).ok())
452}
453
454fn non_empty(value: Option<&str>) -> Option<&str> {
455    value.filter(|v| !v.is_empty())
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    const A: Uuid = Uuid::from_u128(0xa);
463    const B: Uuid = Uuid::from_u128(0xb);
464    const C: Uuid = Uuid::from_u128(0xc);
465    const D: Uuid = Uuid::from_u128(0xd);
466    const E: Uuid = Uuid::from_u128(0xe);
467
468    fn now() -> OffsetDateTime {
469        // 2026-10-31T12:00:00Z
470        OffsetDateTime::from_unix_timestamp(1_793_448_000).expect("valid timestamp")
471    }
472
473    fn ago(d: Duration) -> OffsetDateTime {
474        now() - d
475    }
476
477    fn token(id: Uuid, issued: OffsetDateTime) -> ObservedToken {
478        ObservedToken {
479            id,
480            issued_at: issued,
481            expiry: None,
482        }
483    }
484
485    fn token_exp(id: Uuid, issued: OffsetDateTime, expiry: OffsetDateTime) -> ObservedToken {
486        ObservedToken {
487            id,
488            issued_at: issued,
489            expiry: Some(expiry),
490        }
491    }
492
493    fn secret(name: &str, id: Uuid) -> ObservedSecret {
494        ObservedSecret {
495            name: name.to_string(),
496            token_id: Some(id.to_string()),
497            rotation_request: None,
498            bearer_readable: true,
499            created_at: None,
500        }
501    }
502
503    fn secret_at(name: &str, id: Uuid, created: OffsetDateTime) -> ObservedSecret {
504        ObservedSecret {
505            created_at: Some(created),
506            ..secret(name, id)
507        }
508    }
509
510    /// Just after a rotation to B: the template already mounts `s-b`, the old
511    /// pod still runs A, and the Kanidm replica that answered the token list
512    /// has not seen B yet.
513    fn lagging(secret_b_age: Duration) -> TokenWorld {
514        TokenWorld {
515            tokens: vec![token(A, ago(Duration::days(3)))],
516            secrets: vec![
517                secret_at("s-a", A, ago(Duration::days(3))),
518                secret_at("s-b", B, ago(secret_b_age)),
519            ],
520            template: template(B, "s-b"),
521            consumers: vec![pod("p-a", Some(&A.to_string()), &["s-a"])],
522            rotate_request: None,
523        }
524    }
525
526    fn template(id: Uuid, secret: &str) -> Option<TemplateRef> {
527        Some(TemplateRef {
528            token_id: Some(id.to_string()),
529            config_secret: Some(secret.to_string()),
530        })
531    }
532
533    fn pod(name: &str, id: Option<&str>, secrets: &[&str]) -> Consumer {
534        Consumer {
535            kind: ConsumerKind::Pod,
536            name: name.to_string(),
537            token_id: id.map(str::to_string),
538            config_secrets: secrets.iter().map(|s| s.to_string()).collect(),
539        }
540    }
541
542    fn rs(name: &str, id: Uuid, secret: &str) -> Consumer {
543        Consumer {
544            kind: ConsumerKind::ReplicaSet,
545            name: name.to_string(),
546            token_id: Some(id.to_string()),
547            config_secrets: vec![secret.to_string()],
548        }
549    }
550
551    fn rotation(days: u32) -> TokenPolicy {
552        TokenPolicy::from_spec(Some(&SecretRotation {
553            enabled: true,
554            period_days: days,
555        }))
556    }
557
558    fn no_rotation() -> TokenPolicy {
559        TokenPolicy::from_spec(None)
560    }
561
562    /// Steady state: template, ReplicaSet and pod all on token A via `s-a`.
563    fn steady(issued: OffsetDateTime) -> TokenWorld {
564        TokenWorld {
565            tokens: vec![token(A, issued)],
566            secrets: vec![secret("s-a", A)],
567            template: template(A, "s-a"),
568            consumers: vec![
569                rs("rs-a", A, "s-a"),
570                pod("p-a", Some(&A.to_string()), &["s-a"]),
571            ],
572            rotate_request: None,
573        }
574    }
575
576    struct Case {
577        name: &'static str,
578        world: TokenWorld,
579        policy: TokenPolicy,
580        current: CurrentToken,
581        revoke: Vec<Uuid>,
582        gc: Vec<&'static str>,
583    }
584
585    fn cases() -> Vec<Case> {
586        let old = ago(Duration::days(3));
587        vec![
588            Case {
589                name: "empty world mints Initial",
590                world: TokenWorld::default(),
591                policy: rotation(30),
592                current: CurrentToken::Mint(MintReason::Initial),
593                revoke: vec![],
594                gc: vec![],
595            },
596            Case {
597                name: "status loss with valid template token keeps it",
598                world: steady(old),
599                policy: rotation(30),
600                current: CurrentToken::Keep(A),
601                revoke: vec![],
602                gc: vec![],
603            },
604            Case {
605                name: "config change keeps the token while old pods drain",
606                world: TokenWorld {
607                    tokens: vec![token(A, old)],
608                    secrets: vec![secret("s-a1", A), secret("s-a2", A)],
609                    template: template(A, "s-a2"),
610                    consumers: vec![
611                        rs("rs-old", A, "s-a1"),
612                        pod("p-old", Some(&A.to_string()), &["s-a1"]),
613                        pod("p-new", Some(&A.to_string()), &["s-a2"]),
614                    ],
615                    rotate_request: None,
616                },
617                policy: rotation(30),
618                current: CurrentToken::Keep(A),
619                revoke: vec![],
620                gc: vec![],
621            },
622            Case {
623                name: "config change after drain collects old Secret, never the token",
624                world: TokenWorld {
625                    tokens: vec![token(A, old)],
626                    secrets: vec![secret("s-a1", A), secret("s-a2", A)],
627                    template: template(A, "s-a2"),
628                    consumers: vec![pod("p-new", Some(&A.to_string()), &["s-a2"])],
629                    rotate_request: None,
630                },
631                policy: rotation(30),
632                current: CurrentToken::Keep(A),
633                revoke: vec![],
634                gc: vec!["s-a1"],
635            },
636            Case {
637                name: "rotation due mints Due",
638                world: steady(ago(Duration::days(31))),
639                policy: rotation(30),
640                current: CurrentToken::Mint(MintReason::Due),
641                revoke: vec![],
642                gc: vec![],
643            },
644            Case {
645                name: "rotation due exactly at the period boundary",
646                world: steady(ago(Duration::days(30))),
647                policy: rotation(30),
648                current: CurrentToken::Mint(MintReason::Due),
649                revoke: vec![],
650                gc: vec![],
651            },
652            Case {
653                name: "one second before due keeps",
654                world: steady(ago(Duration::days(30) - Duration::seconds(1))),
655                policy: rotation(30),
656                current: CurrentToken::Keep(A),
657                revoke: vec![],
658                gc: vec![],
659            },
660            Case {
661                name: "expired token mints Expired",
662                world: TokenWorld {
663                    tokens: vec![token_exp(A, old, ago(Duration::hours(1)))],
664                    ..steady(old)
665                },
666                policy: no_rotation(),
667                current: CurrentToken::Mint(MintReason::Expired),
668                revoke: vec![],
669                gc: vec![],
670            },
671            Case {
672                name: "expiry within safety margin mints Expired",
673                world: TokenWorld {
674                    tokens: vec![token_exp(A, old, now() + Duration::hours(23))],
675                    ..steady(old)
676                },
677                policy: no_rotation(),
678                current: CurrentToken::Mint(MintReason::Expired),
679                revoke: vec![],
680                gc: vec![],
681            },
682            Case {
683                name: "expiry beyond safety margin keeps",
684                world: TokenWorld {
685                    tokens: vec![token_exp(A, old, now() + Duration::hours(25))],
686                    ..steady(old)
687                },
688                policy: no_rotation(),
689                current: CurrentToken::Keep(A),
690                revoke: vec![],
691                gc: vec![],
692            },
693            Case {
694                name: "rotate annotation differing from Secret mints Requested",
695                world: TokenWorld {
696                    rotate_request: Some("leak-2026-10-31".into()),
697                    ..steady(old)
698                },
699                policy: rotation(30),
700                current: CurrentToken::Mint(MintReason::Requested),
701                revoke: vec![],
702                gc: vec![],
703            },
704            Case {
705                name: "rotate annotation equal to Secret keeps",
706                world: TokenWorld {
707                    secrets: vec![ObservedSecret {
708                        rotation_request: Some("leak-1".into()),
709                        ..secret("s-a", A)
710                    }],
711                    rotate_request: Some("leak-1".into()),
712                    ..steady(old)
713                },
714                policy: rotation(30),
715                current: CurrentToken::Keep(A),
716                revoke: vec![],
717                gc: vec![],
718            },
719            Case {
720                name: "removing the rotate annotation does not rotate",
721                world: TokenWorld {
722                    secrets: vec![ObservedSecret {
723                        rotation_request: Some("leak-1".into()),
724                        ..secret("s-a", A)
725                    }],
726                    rotate_request: None,
727                    ..steady(old)
728                },
729                policy: rotation(30),
730                current: CurrentToken::Keep(A),
731                revoke: vec![],
732                gc: vec![],
733            },
734            Case {
735                name: "unreadable bearer mints BearerLost",
736                world: TokenWorld {
737                    secrets: vec![ObservedSecret {
738                        bearer_readable: false,
739                        ..secret("s-a", A)
740                    }],
741                    ..steady(old)
742                },
743                policy: rotation(30),
744                current: CurrentToken::Mint(MintReason::BearerLost),
745                revoke: vec![],
746                gc: vec![],
747            },
748            Case {
749                name: "deleted config Secret mints BearerLost and holds the token",
750                world: TokenWorld {
751                    secrets: vec![],
752                    ..steady(old)
753                },
754                policy: rotation(30),
755                current: CurrentToken::Mint(MintReason::BearerLost),
756                revoke: vec![],
757                gc: vec![],
758            },
759            Case {
760                name: "token revoked out of band mints BearerLost; dangling Secret kept while used",
761                world: TokenWorld {
762                    tokens: vec![],
763                    ..steady(old)
764                },
765                policy: rotation(30),
766                current: CurrentToken::Mint(MintReason::BearerLost),
767                revoke: vec![],
768                gc: vec![],
769            },
770            Case {
771                name: "dangling Secret of an out-of-band revoked token is collected once unused",
772                world: TokenWorld {
773                    tokens: vec![token(B, old)],
774                    secrets: vec![secret("s-a", A), secret("s-b", B)],
775                    template: template(B, "s-b"),
776                    consumers: vec![pod("p-b", Some(&B.to_string()), &["s-b"])],
777                    rotate_request: None,
778                },
779                policy: rotation(30),
780                current: CurrentToken::Keep(B),
781                revoke: vec![],
782                gc: vec!["s-a"],
783            },
784            Case {
785                name: "old token held while only the template references it",
786                world: TokenWorld {
787                    tokens: vec![token(A, old), token(B, old)],
788                    secrets: vec![secret("s-a", A), secret("s-b", B)],
789                    template: Some(TemplateRef {
790                        token_id: Some(A.to_string()),
791                        config_secret: Some("s-b".into()),
792                    }),
793                    consumers: vec![],
794                    rotate_request: None,
795                },
796                policy: rotation(30),
797                current: CurrentToken::Keep(B),
798                revoke: vec![],
799                gc: vec!["s-a"],
800            },
801            Case {
802                name: "old token held while a ReplicaSet uses it",
803                world: TokenWorld {
804                    tokens: vec![token(A, old), token(B, old)],
805                    secrets: vec![secret("s-a", A), secret("s-b", B)],
806                    template: template(B, "s-b"),
807                    consumers: vec![rs("rs-a", A, "s-a")],
808                    rotate_request: None,
809                },
810                policy: rotation(30),
811                current: CurrentToken::Keep(B),
812                revoke: vec![],
813                gc: vec![],
814            },
815            Case {
816                name: "old token held while a Terminating pod mounts its Secret (no annotation)",
817                world: TokenWorld {
818                    tokens: vec![token(A, old), token(B, old)],
819                    secrets: vec![secret("s-a", A), secret("s-b", B)],
820                    template: template(B, "s-b"),
821                    consumers: vec![pod("p-a-terminating", None, &["s-a"])],
822                    rotate_request: None,
823                },
824                policy: rotation(30),
825                current: CurrentToken::Keep(B),
826                revoke: vec![],
827                gc: vec![],
828            },
829            Case {
830                name: "old token held while a pod carries only its annotation",
831                world: TokenWorld {
832                    tokens: vec![token(A, old), token(B, old)],
833                    secrets: vec![secret("s-b", B)],
834                    template: template(B, "s-b"),
835                    consumers: vec![pod("p-a", Some(&A.to_string()), &[])],
836                    rotate_request: None,
837                },
838                policy: rotation(30),
839                current: CurrentToken::Keep(B),
840                revoke: vec![],
841                gc: vec![],
842            },
843            Case {
844                name: "two tokens both referenced by pods during rollout are both held",
845                world: TokenWorld {
846                    tokens: vec![token(A, old), token(B, ago(Duration::minutes(1)))],
847                    secrets: vec![secret("s-a", A), secret("s-b", B)],
848                    template: template(B, "s-b"),
849                    consumers: vec![
850                        rs("rs-a", A, "s-a"),
851                        rs("rs-b", B, "s-b"),
852                        pod("p-a", Some(&A.to_string()), &["s-a"]),
853                        pod("p-b", Some(&B.to_string()), &["s-b"]),
854                    ],
855                    rotate_request: None,
856                },
857                policy: rotation(30),
858                current: CurrentToken::Keep(B),
859                revoke: vec![],
860                gc: vec![],
861            },
862            Case {
863                name: "retired token revoked once unused and its Secret collected",
864                world: TokenWorld {
865                    tokens: vec![token(A, old), token(B, ago(Duration::hours(1)))],
866                    secrets: vec![secret("s-a", A), secret("s-b", B)],
867                    template: template(B, "s-b"),
868                    consumers: vec![pod("p-b", Some(&B.to_string()), &["s-b"])],
869                    rotate_request: None,
870                },
871                policy: rotation(30),
872                current: CurrentToken::Keep(B),
873                revoke: vec![A],
874                gc: vec!["s-a"],
875            },
876            Case {
877                name: "orphan younger than grace is kept",
878                world: TokenWorld {
879                    tokens: vec![token(A, old), token(B, ago(Duration::minutes(9)))],
880                    ..steady(old)
881                },
882                policy: rotation(30),
883                current: CurrentToken::Keep(A),
884                revoke: vec![],
885                gc: vec![],
886            },
887            Case {
888                name: "orphan exactly at grace is revoked",
889                world: TokenWorld {
890                    tokens: vec![token(A, old), token(B, ago(Duration::minutes(10)))],
891                    ..steady(old)
892                },
893                policy: rotation(30),
894                current: CurrentToken::Keep(A),
895                revoke: vec![B],
896                gc: vec![],
897            },
898            Case {
899                name: "orphan older than grace is revoked",
900                world: TokenWorld {
901                    tokens: vec![token(A, old), token(B, ago(Duration::hours(2)))],
902                    ..steady(old)
903                },
904                policy: rotation(30),
905                current: CurrentToken::Keep(A),
906                revoke: vec![B],
907                gc: vec![],
908            },
909            Case {
910                name: "young retired token and its Secret from a crash before apply are held",
911                world: TokenWorld {
912                    tokens: vec![token(A, old), token(B, ago(Duration::minutes(2)))],
913                    secrets: vec![secret("s-a", A), secret("s-b", B)],
914                    ..steady(old)
915                },
916                policy: rotation(30),
917                current: CurrentToken::Keep(A),
918                revoke: vec![],
919                gc: vec![],
920            },
921            Case {
922                name: "orphan issued in the future (Kanidm clock ahead) is kept",
923                world: TokenWorld {
924                    tokens: vec![token(A, old), token(B, now() + Duration::minutes(5))],
925                    ..steady(old)
926                },
927                policy: rotation(30),
928                current: CurrentToken::Keep(A),
929                revoke: vec![],
930                gc: vec![],
931            },
932            Case {
933                name: "more than max tokens blocks minting but still revokes unused ones",
934                world: TokenWorld {
935                    tokens: vec![
936                        token(A, ago(Duration::days(40))),
937                        token(B, old),
938                        token(C, old),
939                        token(D, ago(Duration::minutes(1))),
940                        token(E, ago(Duration::minutes(1))),
941                    ],
942                    ..steady(ago(Duration::days(40)))
943                },
944                policy: rotation(30),
945                current: CurrentToken::Blocked,
946                revoke: vec![B, C],
947                gc: vec![],
948            },
949            Case {
950                name: "exactly max tokens blocks a mint that would exceed it",
951                world: TokenWorld {
952                    tokens: vec![
953                        token(A, old),
954                        token(B, ago(Duration::minutes(1))),
955                        token(C, ago(Duration::minutes(1))),
956                        token(D, ago(Duration::minutes(1))),
957                    ],
958                    rotate_request: Some("leak".into()),
959                    ..steady(old)
960                },
961                policy: no_rotation(),
962                current: CurrentToken::Blocked,
963                revoke: vec![],
964                gc: vec![],
965            },
966            Case {
967                name: "more than max tokens does not block a Keep",
968                world: TokenWorld {
969                    tokens: vec![
970                        token(A, old),
971                        token(B, ago(Duration::minutes(1))),
972                        token(C, ago(Duration::minutes(1))),
973                        token(D, ago(Duration::minutes(1))),
974                        token(E, ago(Duration::minutes(1))),
975                    ],
976                    ..steady(old)
977                },
978                policy: rotation(30),
979                current: CurrentToken::Keep(A),
980                revoke: vec![],
981                gc: vec![],
982            },
983            Case {
984                name: "current never revoked even when template annotation names another token",
985                world: TokenWorld {
986                    tokens: vec![token(A, old), token(B, old)],
987                    secrets: vec![secret("s-b", B)],
988                    template: Some(TemplateRef {
989                        token_id: Some(A.to_string()),
990                        config_secret: Some("s-b".into()),
991                    }),
992                    consumers: vec![pod("p-b", Some(&A.to_string()), &["s-b"])],
993                    rotate_request: None,
994                },
995                policy: rotation(30),
996                current: CurrentToken::Keep(B),
997                revoke: vec![],
998                gc: vec![],
999            },
1000            Case {
1001                name: "current never revoked when a stray Secret claims it and nobody mounts it",
1002                world: TokenWorld {
1003                    tokens: vec![token(A, old)],
1004                    secrets: vec![secret("s-a", A), secret("stray", A)],
1005                    ..steady(old)
1006                },
1007                policy: rotation(30),
1008                current: CurrentToken::Keep(A),
1009                revoke: vec![],
1010                gc: vec!["stray"],
1011            },
1012            Case {
1013                name: "unparsable pod annotation blocks every revocation",
1014                world: TokenWorld {
1015                    tokens: vec![token(A, old), token(B, old)],
1016                    secrets: vec![secret("s-a", A), secret("s-b", B)],
1017                    template: template(B, "s-b"),
1018                    consumers: vec![pod("p-weird", Some("not-a-uuid"), &[])],
1019                    rotate_request: None,
1020                },
1021                policy: rotation(30),
1022                current: CurrentToken::Keep(B),
1023                revoke: vec![],
1024                gc: vec!["s-a"],
1025            },
1026            Case {
1027                name: "pod mounting a Secret with an unparsable token id blocks every revocation",
1028                world: TokenWorld {
1029                    tokens: vec![token(A, old), token(B, old)],
1030                    secrets: vec![
1031                        ObservedSecret {
1032                            token_id: Some("garbage".into()),
1033                            ..secret("s-x", A)
1034                        },
1035                        secret("s-b", B),
1036                    ],
1037                    template: template(B, "s-b"),
1038                    consumers: vec![pod("p-x", None, &["s-x"])],
1039                    rotate_request: None,
1040                },
1041                policy: rotation(30),
1042                current: CurrentToken::Keep(B),
1043                revoke: vec![],
1044                gc: vec![],
1045            },
1046            Case {
1047                name: "pod mounting a deleted config Secret blocks every revocation",
1048                world: TokenWorld {
1049                    tokens: vec![token(A, old), token(B, old), token(C, old)],
1050                    secrets: vec![secret("s-b", B)],
1051                    template: template(B, "s-b"),
1052                    consumers: vec![pod("p-gone", Some(&A.to_string()), &["s-a-deleted"])],
1053                    rotate_request: None,
1054                },
1055                policy: rotation(30),
1056                current: CurrentToken::Keep(B),
1057                revoke: vec![],
1058                gc: vec![],
1059            },
1060            Case {
1061                name: "non-canonical UUID spelling in a pod annotation still holds the token",
1062                world: TokenWorld {
1063                    tokens: vec![token(A, old), token(B, old)],
1064                    secrets: vec![secret("s-b", B)],
1065                    template: template(B, "s-b"),
1066                    consumers: vec![pod(
1067                        "p-a",
1068                        Some(&A.simple().to_string().to_uppercase()),
1069                        &[],
1070                    )],
1071                    rotate_request: None,
1072                },
1073                policy: rotation(30),
1074                current: CurrentToken::Keep(B),
1075                revoke: vec![],
1076                gc: vec![],
1077            },
1078            Case {
1079                name: "unparsable token id on the template Secret mints BearerLost",
1080                world: TokenWorld {
1081                    secrets: vec![ObservedSecret {
1082                        token_id: Some("nope".into()),
1083                        ..secret("s-a", A)
1084                    }],
1085                    ..steady(old)
1086                },
1087                policy: rotation(30),
1088                current: CurrentToken::Mint(MintReason::BearerLost),
1089                revoke: vec![],
1090                gc: vec![],
1091            },
1092            Case {
1093                name: "template with a token annotation but no Secret mints BearerLost",
1094                world: TokenWorld {
1095                    tokens: vec![token(A, old)],
1096                    secrets: vec![],
1097                    template: Some(TemplateRef {
1098                        token_id: Some(A.to_string()),
1099                        config_secret: None,
1100                    }),
1101                    consumers: vec![],
1102                    rotate_request: None,
1103                },
1104                policy: rotation(30),
1105                current: CurrentToken::Mint(MintReason::BearerLost),
1106                revoke: vec![],
1107                gc: vec![],
1108            },
1109            Case {
1110                name: "template without any reference mints Initial and revokes nothing",
1111                world: TokenWorld {
1112                    tokens: vec![token(A, old)],
1113                    secrets: vec![],
1114                    template: Some(TemplateRef::default()),
1115                    consumers: vec![],
1116                    rotate_request: None,
1117                },
1118                policy: rotation(30),
1119                current: CurrentToken::Mint(MintReason::Initial),
1120                revoke: vec![],
1121                gc: vec![],
1122            },
1123            Case {
1124                name: "deployment gone mints Initial and holds tokens pods still use",
1125                world: TokenWorld {
1126                    template: None,
1127                    ..steady(old)
1128                },
1129                policy: rotation(30),
1130                current: CurrentToken::Mint(MintReason::Initial),
1131                revoke: vec![],
1132                gc: vec![],
1133            },
1134            Case {
1135                name: "rotation disabled and no expiry keeps forever",
1136                world: steady(ago(Duration::days(3650))),
1137                policy: no_rotation(),
1138                current: CurrentToken::Keep(A),
1139                revoke: vec![],
1140                gc: vec![],
1141            },
1142            Case {
1143                name: "expired takes precedence over due",
1144                world: TokenWorld {
1145                    tokens: vec![token_exp(
1146                        A,
1147                        ago(Duration::days(61)),
1148                        ago(Duration::days(1)),
1149                    )],
1150                    ..steady(ago(Duration::days(61)))
1151                },
1152                policy: rotation(30),
1153                current: CurrentToken::Mint(MintReason::Expired),
1154                revoke: vec![],
1155                gc: vec![],
1156            },
1157            Case {
1158                name: "replication lag: current token missing inside the grace is kept",
1159                world: lagging(Duration::minutes(2)),
1160                policy: rotation(30),
1161                current: CurrentToken::Keep(B),
1162                revoke: vec![],
1163                gc: vec![],
1164            },
1165            Case {
1166                name: "replication lag: one second before the grace is still kept",
1167                world: lagging(ORPHAN_GRACE - Duration::seconds(1)),
1168                policy: rotation(30),
1169                current: CurrentToken::Keep(B),
1170                revoke: vec![],
1171                gc: vec![],
1172            },
1173            Case {
1174                name: "replication lag: current token missing at the grace mints BearerLost",
1175                world: lagging(ORPHAN_GRACE),
1176                policy: rotation(30),
1177                current: CurrentToken::Mint(MintReason::BearerLost),
1178                revoke: vec![],
1179                gc: vec![],
1180            },
1181            Case {
1182                name: "replication lag: current token missing after the grace mints BearerLost",
1183                world: lagging(Duration::hours(1)),
1184                policy: rotation(30),
1185                current: CurrentToken::Mint(MintReason::BearerLost),
1186                revoke: vec![],
1187                gc: vec![],
1188            },
1189            Case {
1190                name: "replication lag: unused old token is still revoked inside the grace",
1191                world: TokenWorld {
1192                    consumers: vec![pod("p-b", Some(&B.to_string()), &["s-b"])],
1193                    ..lagging(Duration::minutes(2))
1194                },
1195                policy: rotation(30),
1196                current: CurrentToken::Keep(B),
1197                revoke: vec![A],
1198                gc: vec!["s-a"],
1199            },
1200            Case {
1201                name: "replication lag: an unresolved consumer still holds every revocation",
1202                world: TokenWorld {
1203                    consumers: vec![
1204                        pod("p-b", Some(&B.to_string()), &["s-b"]),
1205                        pod("p-gone", None, &["s-deleted"]),
1206                    ],
1207                    ..lagging(Duration::minutes(2))
1208                },
1209                policy: rotation(30),
1210                current: CurrentToken::Keep(B),
1211                revoke: vec![],
1212                gc: vec!["s-a"],
1213            },
1214            Case {
1215                name: "replication lag: a rotation request is still honoured",
1216                world: TokenWorld {
1217                    rotate_request: Some("leak".into()),
1218                    ..lagging(Duration::minutes(2))
1219                },
1220                policy: rotation(30),
1221                current: CurrentToken::Mint(MintReason::Requested),
1222                revoke: vec![],
1223                gc: vec![],
1224            },
1225            Case {
1226                name: "replication lag: an older Secret of the same token decides its age",
1227                world: TokenWorld {
1228                    // A config change re-rendered a token minted long ago and
1229                    // since revoked out of band: the new Secret is young, the
1230                    // token is not.
1231                    secrets: vec![
1232                        secret_at("s-a", A, ago(Duration::days(3))),
1233                        secret_at("s-b1", B, ago(Duration::days(2))),
1234                        secret_at("s-b", B, ago(Duration::minutes(2))),
1235                    ],
1236                    ..lagging(Duration::minutes(2))
1237                },
1238                policy: rotation(30),
1239                current: CurrentToken::Mint(MintReason::BearerLost),
1240                revoke: vec![],
1241                gc: vec!["s-b1"],
1242            },
1243            Case {
1244                name: "replication lag: a Secret without creation time is not young",
1245                world: TokenWorld {
1246                    secrets: vec![
1247                        secret_at("s-a", A, ago(Duration::days(3))),
1248                        secret("s-b", B),
1249                    ],
1250                    ..lagging(Duration::minutes(2))
1251                },
1252                policy: rotation(30),
1253                current: CurrentToken::Mint(MintReason::BearerLost),
1254                revoke: vec![],
1255                gc: vec![],
1256            },
1257            Case {
1258                name: "expired unused tokens are revoked",
1259                world: TokenWorld {
1260                    tokens: vec![
1261                        token(A, old),
1262                        token_exp(B, ago(Duration::days(70)), ago(Duration::days(10))),
1263                    ],
1264                    ..steady(old)
1265                },
1266                policy: rotation(30),
1267                current: CurrentToken::Keep(A),
1268                revoke: vec![B],
1269                gc: vec![],
1270            },
1271        ]
1272    }
1273
1274    #[test]
1275    fn planner_table() {
1276        let mut failures = Vec::new();
1277        for case in cases() {
1278            let plan = plan_tokens(&case.world, &case.policy, now());
1279            let gc: Vec<String> = case.gc.iter().map(|s| s.to_string()).collect();
1280            if plan.current != case.current || plan.revoke != case.revoke || plan.gc_secrets != gc {
1281                failures.push(format!(
1282                    "{}:\n  expected current={:?} revoke={:?} gc={:?}\n  got      current={:?} revoke={:?} gc={:?}",
1283                    case.name,
1284                    case.current,
1285                    case.revoke,
1286                    gc,
1287                    plan.current,
1288                    plan.revoke,
1289                    plan.gc_secrets
1290                ));
1291            }
1292        }
1293        assert!(failures.is_empty(), "{}", failures.join("\n"));
1294    }
1295
1296    /// Cross-cutting invariants checked on every table world.
1297    #[test]
1298    fn invariants_hold_for_every_case() {
1299        for case in cases() {
1300            let plan = plan_tokens(&case.world, &case.policy, now());
1301            let revoke: BTreeSet<Uuid> = plan.revoke.iter().copied().collect();
1302            if let CurrentToken::Keep(id) = plan.current {
1303                assert!(!revoke.contains(&id), "{}: current revoked", case.name);
1304            }
1305            let mut referenced: Vec<&Option<String>> =
1306                case.world.consumers.iter().map(|c| &c.token_id).collect();
1307            if let Some(t) = &case.world.template {
1308                referenced.push(&t.token_id);
1309            }
1310            for raw in referenced.into_iter().flatten() {
1311                if let Ok(id) = Uuid::parse_str(raw) {
1312                    assert!(!revoke.contains(&id), "{}: in-use {id} revoked", case.name);
1313                }
1314            }
1315            for t in &case.world.tokens {
1316                if revoke.contains(&t.id) {
1317                    assert!(
1318                        now() - t.issued_at >= ORPHAN_GRACE,
1319                        "{}: young token revoked",
1320                        case.name
1321                    );
1322                }
1323            }
1324            if !plan.unresolved_consumers.is_empty() {
1325                assert!(
1326                    plan.revoke.is_empty(),
1327                    "{}: revoked while unresolved",
1328                    case.name
1329                );
1330            }
1331            if matches!(plan.current, CurrentToken::Mint(_)) {
1332                assert!(
1333                    case.world.tokens.len() < case.policy.max_tokens,
1334                    "{}: mint would exceed max tokens",
1335                    case.name
1336                );
1337            }
1338            let mut sorted = plan.revoke.clone();
1339            sorted.sort();
1340            assert_eq!(sorted, plan.revoke, "{}: revoke unsorted", case.name);
1341            let mut sorted = plan.gc_secrets.clone();
1342            sorted.sort();
1343            assert_eq!(sorted, plan.gc_secrets, "{}: gc unsorted", case.name);
1344        }
1345    }
1346
1347    #[test]
1348    fn output_is_independent_of_input_order() {
1349        for case in cases() {
1350            let mut reversed = case.world.clone();
1351            reversed.tokens.reverse();
1352            reversed.secrets.reverse();
1353            reversed.consumers.reverse();
1354            assert_eq!(
1355                plan_tokens(&case.world, &case.policy, now()),
1356                plan_tokens(&reversed, &case.policy, now()),
1357                "{}",
1358                case.name
1359            );
1360        }
1361    }
1362
1363    #[test]
1364    fn retiring_lists_kept_non_current_tokens() {
1365        let world = TokenWorld {
1366            tokens: vec![
1367                token(A, ago(Duration::days(3))),
1368                token(B, ago(Duration::hours(1))),
1369            ],
1370            secrets: vec![secret("s-a", A), secret("s-b", B)],
1371            template: template(B, "s-b"),
1372            consumers: vec![rs("rs-a", A, "s-a")],
1373            rotate_request: None,
1374        };
1375        let plan = plan_tokens(&world, &rotation(30), now());
1376        assert_eq!(plan.current, CurrentToken::Keep(B));
1377        assert_eq!(plan.retiring, vec![A]);
1378        assert!(plan.unresolved_consumers.is_empty());
1379    }
1380
1381    #[test]
1382    fn replication_lag_keeps_the_old_token_retiring() {
1383        let plan = plan_tokens(&lagging(Duration::minutes(2)), &rotation(30), now());
1384        assert_eq!(plan.current, CurrentToken::Keep(B));
1385        assert_eq!(plan.retiring, vec![A]);
1386        assert!(plan.revoke.is_empty());
1387        assert!(plan.unresolved_consumers.is_empty());
1388    }
1389
1390    #[test]
1391    fn unresolved_consumers_are_reported_sorted() {
1392        let world = TokenWorld {
1393            tokens: vec![token(A, ago(Duration::days(3)))],
1394            secrets: vec![],
1395            template: Some(TemplateRef {
1396                token_id: Some("bad".into()),
1397                config_secret: None,
1398            }),
1399            consumers: vec![
1400                pod("z", Some("bad"), &[]),
1401                pod("a", None, &["missing"]),
1402                Consumer {
1403                    kind: ConsumerKind::ReplicaSet,
1404                    name: "r".into(),
1405                    token_id: None,
1406                    config_secrets: vec![],
1407                },
1408            ],
1409            rotate_request: None,
1410        };
1411        let plan = plan_tokens(&world, &rotation(30), now());
1412        assert_eq!(
1413            plan.unresolved_consumers,
1414            vec!["pod/a", "pod/z", "replicaset/r", "template"]
1415        );
1416        assert!(plan.revoke.is_empty());
1417    }
1418
1419    #[test]
1420    fn duplicate_token_entries_count_once() {
1421        let mut world = steady(ago(Duration::days(40)));
1422        world.tokens = vec![
1423            token(A, ago(Duration::days(40))),
1424            token(A, ago(Duration::days(40))),
1425            token(B, ago(Duration::minutes(1))),
1426            token(B, ago(Duration::minutes(1))),
1427            token(C, ago(Duration::minutes(1))),
1428            token(C, ago(Duration::minutes(1))),
1429        ];
1430        let plan = plan_tokens(&world, &rotation(30), now());
1431        assert_eq!(plan.current, CurrentToken::Mint(MintReason::Due));
1432    }
1433
1434    #[test]
1435    fn extreme_dates_do_not_panic() {
1436        let world = TokenWorld {
1437            tokens: vec![
1438                token_exp(
1439                    A,
1440                    OffsetDateTime::new_utc(time::Date::MIN, time::Time::MIDNIGHT),
1441                    OffsetDateTime::new_utc(time::Date::MIN, time::Time::MIDNIGHT),
1442                ),
1443                token(
1444                    B,
1445                    OffsetDateTime::new_utc(time::Date::MAX, time::Time::MIDNIGHT),
1446                ),
1447            ],
1448            secrets: vec![secret("s-b", B)],
1449            template: template(B, "s-b"),
1450            consumers: vec![],
1451            rotate_request: None,
1452        };
1453        let plan = plan_tokens(&world, &rotation(365), now());
1454        // Far-future issued_at: never due, never old enough to revoke.
1455        assert_eq!(plan.current, CurrentToken::Keep(B));
1456        // Ancient expired token is unused and old: revoked.
1457        assert_eq!(plan.revoke, vec![A]);
1458
1459        let world = TokenWorld {
1460            tokens: vec![token_exp(
1461                A,
1462                ago(Duration::days(1)),
1463                OffsetDateTime::new_utc(time::Date::MIN, time::Time::MIDNIGHT),
1464            )],
1465            ..steady(ago(Duration::days(1)))
1466        };
1467        assert_eq!(
1468            plan_tokens(&world, &no_rotation(), now()).current,
1469            CurrentToken::Mint(MintReason::Expired)
1470        );
1471        let max = OffsetDateTime::new_utc(time::Date::MAX, time::Time::MIDNIGHT);
1472        assert_eq!(rotation(365).new_token_expiry(max), None);
1473    }
1474
1475    #[test]
1476    fn policy_from_spec() {
1477        assert_eq!(no_rotation().rotation_period, None);
1478        assert_eq!(
1479            TokenPolicy::from_spec(Some(&SecretRotation {
1480                enabled: false,
1481                period_days: 7,
1482            }))
1483            .rotation_period,
1484            None
1485        );
1486        assert_eq!(rotation(7).rotation_period, Some(Duration::days(7)));
1487        assert_eq!(rotation(0).rotation_period, Some(Duration::days(1)));
1488        assert_eq!(
1489            rotation(u32::MAX).rotation_period,
1490            Some(Duration::days(365))
1491        );
1492        assert_eq!(no_rotation().orphan_grace, Duration::minutes(10));
1493        assert_eq!(no_rotation().max_tokens, 4);
1494    }
1495
1496    #[test]
1497    fn new_token_expiry_is_twice_the_period() {
1498        assert_eq!(no_rotation().new_token_expiry(now()), None);
1499        assert_eq!(
1500            rotation(30).new_token_expiry(now()),
1501            Some(now() + Duration::days(60))
1502        );
1503    }
1504
1505    /// With rotation enabled, a freshly minted token becomes Due no later than
1506    /// it enters the expiry safety margin, for every allowed period.
1507    #[test]
1508    fn due_always_precedes_expiry_margin() {
1509        for days in 1..=365 {
1510            let policy = rotation(days);
1511            let issued = now();
1512            let expiry = policy.new_token_expiry(issued).expect("expiry");
1513            let world = TokenWorld {
1514                tokens: vec![token_exp(A, issued, expiry)],
1515                ..steady(issued)
1516            };
1517            let at_due = issued + Duration::days(i64::from(days));
1518            assert_eq!(
1519                plan_tokens(&world, &policy, at_due - Duration::seconds(1)).current,
1520                CurrentToken::Keep(A),
1521                "period {days}"
1522            );
1523            let at_margin = expiry - policy.safety_margin;
1524            assert!(at_due <= at_margin, "period {days}");
1525        }
1526    }
1527
1528    #[test]
1529    fn expiry_warning_is_twice_the_safety_margin() {
1530        assert_eq!(EXPIRY_WARNING, SAFETY_MARGIN * 2);
1531        let expiry = now() + EXPIRY_WARNING;
1532        assert!(expires_within_warning(expiry, now()));
1533        assert!(!expires_within_warning(
1534            expiry + Duration::seconds(1),
1535            now()
1536        ));
1537        assert!(expires_within_warning(ago(Duration::days(1)), now()));
1538        let min = OffsetDateTime::new_utc(time::Date::MIN, time::Time::MIDNIGHT);
1539        assert!(expires_within_warning(min, now()));
1540    }
1541
1542    #[test]
1543    fn consumer_labels_name_kind_and_object() {
1544        assert_eq!(pod("p-a", None, &[]).label(), "pod/p-a");
1545        assert_eq!(rs("rs-a", A, "s-a").label(), "replicaset/rs-a");
1546    }
1547
1548    #[test]
1549    fn reasons_are_stable() {
1550        assert_eq!(MintReason::Initial.reason(), "Initial");
1551        assert_eq!(MintReason::BearerLost.reason(), "BearerLost");
1552        assert_eq!(MintReason::Expired.reason(), "Expired");
1553        assert_eq!(MintReason::Due.reason(), "Due");
1554        assert_eq!(MintReason::Requested.reason(), "Requested");
1555    }
1556}