Skip to main content

kaniop_radius/reconcile/
observe.rs

1//! Observe the world the token planner decides on.
2//!
3//! [`observe`] reads Kanidm (tokens on the dedicated account) and the
4//! Kubernetes API (Deployment template, ReplicaSets, pods, owned config
5//! Secrets) with live list calls, never the controller cache, and returns a
6//! [`TokenWorld`]. Everything that interprets objects is a pure function over
7//! `k8s_openapi` values so it can be tested from fixtures.
8//!
9//! The in-use scan is the safety net for revocation: missing a consumer
10//! revokes a live token. It therefore errs toward counting:
11//!
12//! - Pods are scanned across the namespace, not by label. A pod counts when
13//!   it is not Succeeded/Failed (Terminating pods count) and carries a
14//!   token-id annotation that can name one of our tokens (on the account, on
15//!   one of our config Secrets, or unparsable), carries our UID label, or
16//!   mounts a config Secret we identify as ours. Another server's pods in the
17//!   same namespace carry the annotation too but are not ours.
18//! - A mounted Secret is ours when it is an owned Secret, when its name has
19//!   the content-addressed shape `<cr>-<10 hex>` (so a Secret that was
20//!   already deleted is still recognised), or when a pod with our UID label
21//!   projects its `radius.toml` key. Every such name is reported in
22//!   [`Consumer::config_secrets`] even if the Secret no longer exists, so the
23//!   planner sees an unresolved reference instead of nothing.
24//! - ReplicaSets count while they have replicas, found through the
25//!   Deployment owner reference or our UID label.
26//! - Annotation values are passed to the planner raw.
27
28use std::collections::BTreeSet;
29use std::fmt::Debug;
30
31use k8s_openapi::api::apps::v1::{Deployment, ReplicaSet};
32use k8s_openapi::api::core::v1::{Container, Pod, PodSpec, Secret};
33use k8s_openapi::apimachinery::pkg::apis::meta::v1::{ObjectMeta, OwnerReference};
34use kanidm_client::KanidmClient;
35use kanidm_proto::internal::ApiToken;
36use kaniop_operator::metrics::ControllerMetrics;
37use kube::api::ListParams;
38use kube::{Api, Client, Resource, ResourceExt};
39use serde::de::DeserializeOwned;
40use time::OffsetDateTime;
41use uuid::Uuid;
42
43use crate::crd::KanidmRadiusServer;
44use crate::reconcile::apply::{check_not_foreign, is_controlled_by};
45use crate::reconcile::error::{ExecError, ExecResult, kube_error};
46use crate::reconcile::identity::RadiusIdentity;
47use crate::reconcile::kanidm_token::{Bearer, list_tokens};
48use crate::reconcile::meta::{
49    ANNOTATION_ROTATE_TOKEN, ANNOTATION_ROTATION_REQUEST, ANNOTATION_TOKEN_ID, LABEL_UID,
50    SECRET_KEY_CONFIG, SECRET_KEY_TOKEN,
51};
52use crate::reconcile::token::{
53    Consumer, ConsumerKind, ObservedSecret, ObservedToken, TemplateRef, TokenWorld,
54};
55use crate::reconcile::workload::CONFIG_HASH_LEN;
56
57/// List page size for namespace-wide lists.
58const LIST_PAGE_SIZE: u32 = 500;
59
60/// The planner input plus the bearer the current template runs with.
61///
62/// The bearer is needed to re-render the config for a config-only change
63/// without minting; it is wrapped in [`Bearer`] so this struct cannot leak it
64/// through `Debug`.
65#[derive(Debug)]
66pub struct Observation {
67    pub world: TokenWorld,
68    /// Bearer from the template's config Secret, if readable.
69    pub template_bearer: Option<Bearer>,
70    /// The Deployment as read live (ours; a foreign one fails `observe`).
71    pub deployment: Option<Deployment>,
72}
73
74/// Names of config Secrets that are ours.
75#[derive(Clone, Debug, Default)]
76pub struct SecretScope {
77    cr_name: String,
78    owned: BTreeSet<String>,
79    /// Ids of tokens that are or were on our account.
80    tokens: BTreeSet<Uuid>,
81}
82
83impl SecretScope {
84    pub fn new(cr_name: &str, owned: impl IntoIterator<Item = String>) -> Self {
85        Self {
86            cr_name: cr_name.to_string(),
87            owned: owned.into_iter().collect(),
88            tokens: BTreeSet::new(),
89        }
90    }
91
92    /// Record the ids of tokens that belong to our account.
93    pub fn with_tokens(mut self, tokens: impl IntoIterator<Item = Uuid>) -> Self {
94        self.tokens.extend(tokens);
95        self
96    }
97
98    /// Can a raw token-id annotation name one of our tokens? An unparsable
99    /// value cannot be ruled out, so it counts. A valid id that is neither on
100    /// the account nor on one of our config Secrets belongs to someone else,
101    /// for example another server in the same namespace.
102    fn may_name_our_token(&self, raw: &str) -> bool {
103        Uuid::parse_str(raw).map_or(true, |id| self.tokens.contains(&id))
104    }
105
106    /// An owned Secret, or a name shaped like our content-addressed config
107    /// Secret (`<cr>-<CONFIG_HASH_LEN lowercase hex>`), which also catches a
108    /// Secret that has been deleted since a pod mounted it.
109    pub fn is_ours(&self, name: &str) -> bool {
110        if self.owned.contains(name) {
111            return true;
112        }
113        name.strip_prefix(self.cr_name.as_str())
114            .and_then(|rest| rest.strip_prefix('-'))
115            .is_some_and(|hash| {
116                hash.len() == CONFIG_HASH_LEN
117                    && hash
118                        .bytes()
119                        .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
120            })
121    }
122}
123
124/// Tokens on the account as planner input.
125pub fn observed_tokens(tokens: &[ApiToken]) -> Vec<ObservedToken> {
126    tokens
127        .iter()
128        .map(|t| ObservedToken {
129            id: t.token_id,
130            issued_at: t.issued_at,
131            expiry: t.expiry,
132        })
133        .collect()
134}
135
136/// Keep only Secrets controlled by this CR. The UID label alone is not
137/// ownership: a foreign Secret carrying our label is ignored.
138pub fn owned_secrets(secrets: Vec<Secret>, owner: &OwnerReference) -> Vec<Secret> {
139    secrets
140        .into_iter()
141        .filter(|s| is_controlled_by(&s.metadata, owner))
142        .collect()
143}
144
145pub(crate) fn annotation(meta: &ObjectMeta, key: &str) -> Option<String> {
146    meta.annotations.as_ref().and_then(|a| a.get(key)).cloned()
147}
148
149/// The bearer stored in a config Secret, if present and non-empty UTF-8.
150pub fn secret_bearer(secret: &Secret) -> Option<Bearer> {
151    let bytes = &secret.data.as_ref()?.get(SECRET_KEY_TOKEN)?.0;
152    let text = std::str::from_utf8(bytes).ok()?.trim();
153    (!text.is_empty()).then(|| Bearer::new(text.to_string()))
154}
155
156/// An owned config Secret as planner input.
157pub fn observed_secret(secret: &Secret) -> ObservedSecret {
158    ObservedSecret {
159        name: secret.name_any(),
160        token_id: annotation(&secret.metadata, ANNOTATION_TOKEN_ID),
161        rotation_request: annotation(&secret.metadata, ANNOTATION_ROTATION_REQUEST),
162        bearer_readable: secret_bearer(secret).is_some(),
163        created_at: secret
164            .metadata
165            .creation_timestamp
166            .as_ref()
167            .and_then(|t| OffsetDateTime::from_unix_timestamp_nanos(t.0.as_nanosecond()).ok()),
168    }
169}
170
171/// Secret names a pod spec refers to, with whether the reference is a
172/// projection of the config key (`radius.toml`).
173fn mounted_secrets(spec: &PodSpec) -> Vec<(String, bool)> {
174    let mut found = Vec::new();
175    for volume in spec.volumes.iter().flatten() {
176        if let Some(secret) = &volume.secret {
177            if let Some(name) = &secret.secret_name {
178                let has_config = secret
179                    .items
180                    .iter()
181                    .flatten()
182                    .any(|item| item.key == SECRET_KEY_CONFIG);
183                found.push((name.clone(), has_config));
184            }
185        }
186        for source in volume
187            .projected
188            .iter()
189            .flat_map(|p| p.sources.iter().flatten())
190        {
191            if let Some(secret) = &source.secret {
192                let has_config = secret
193                    .items
194                    .iter()
195                    .flatten()
196                    .any(|item| item.key == SECRET_KEY_CONFIG);
197                found.push((secret.name.clone(), has_config));
198            }
199        }
200    }
201    let containers = spec
202        .containers
203        .iter()
204        .chain(spec.init_containers.iter().flatten());
205    for container in containers {
206        found.extend(env_secrets(container));
207    }
208    found
209}
210
211fn env_secrets(container: &Container) -> Vec<(String, bool)> {
212    let from_env = container
213        .env
214        .iter()
215        .flatten()
216        .filter_map(|e| e.value_from.as_ref()?.secret_key_ref.as_ref())
217        .map(|r| (r.name.clone(), r.key == SECRET_KEY_CONFIG));
218    let from_env_from = container
219        .env_from
220        .iter()
221        .flatten()
222        .filter_map(|e| e.secret_ref.as_ref())
223        .map(|r| (r.name.clone(), false));
224    from_env.chain(from_env_from).collect()
225}
226
227/// Config Secrets of ours that `spec` mounts, sorted and unique.
228///
229/// With `trust_layout` (objects carrying our UID label or the Deployment
230/// template), any Secret whose `radius.toml` key is projected also counts.
231pub fn config_secrets(
232    spec: Option<&PodSpec>,
233    scope: &SecretScope,
234    trust_layout: bool,
235) -> Vec<String> {
236    let names: BTreeSet<String> = spec
237        .map(mounted_secrets)
238        .into_iter()
239        .flatten()
240        .filter(|(name, has_config)| scope.is_ours(name) || (trust_layout && *has_config))
241        .map(|(name, _)| name)
242        .collect();
243    names.into_iter().collect()
244}
245
246/// What the Deployment pod template points at.
247///
248/// The template's config Secret is the one it mounts; if the template names
249/// several or none, `config_secret` is `None` and the planner mints.
250pub fn template_ref(deployment: &Deployment, scope: &SecretScope) -> TemplateRef {
251    let template = deployment.spec.as_ref().map(|s| &s.template);
252    let mut secrets = config_secrets(template.and_then(|t| t.spec.as_ref()), scope, true);
253    TemplateRef {
254        token_id: template
255            .and_then(|t| t.metadata.as_ref())
256            .and_then(|m| annotation(m, ANNOTATION_TOKEN_ID)),
257        config_secret: if secrets.len() == 1 {
258            secrets.pop()
259        } else {
260            None
261        },
262    }
263}
264
265fn has_our_uid_label(meta: &ObjectMeta, uid: &str) -> bool {
266    meta.labels
267        .as_ref()
268        .and_then(|l| l.get(LABEL_UID))
269        .is_some_and(|v| v == uid)
270}
271
272/// Is this ReplicaSet ours: controlled by our Deployment, or labelled with
273/// our UID (the Deployment template label, so it also finds ReplicaSets whose
274/// Deployment is already gone)?
275pub fn is_our_replicaset(rs: &ReplicaSet, deployment_uid: Option<&str>, cr_uid: &str) -> bool {
276    let by_owner = deployment_uid.is_some_and(|uid| {
277        rs.metadata
278            .owner_references
279            .iter()
280            .flatten()
281            .any(|r| r.controller == Some(true) && r.kind == "Deployment" && r.uid == uid)
282    });
283    by_owner || has_our_uid_label(&rs.metadata, cr_uid)
284}
285
286/// A ReplicaSet counts only while it wants or has replicas.
287pub fn replicaset_has_replicas(rs: &ReplicaSet) -> bool {
288    let wanted = rs.spec.as_ref().and_then(|s| s.replicas).unwrap_or(1);
289    let current = rs.status.as_ref().map_or(0, |s| s.replicas);
290    wanted > 0 || current > 0
291}
292
293/// Consumer for one of our ReplicaSets, or `None` when it has no replicas.
294pub fn replicaset_consumer(rs: &ReplicaSet, scope: &SecretScope) -> Option<Consumer> {
295    if !replicaset_has_replicas(rs) {
296        return None;
297    }
298    let template = rs.spec.as_ref().and_then(|s| s.template.as_ref());
299    Some(Consumer {
300        kind: ConsumerKind::ReplicaSet,
301        name: rs.name_any(),
302        token_id: template
303            .and_then(|t| t.metadata.as_ref())
304            .and_then(|m| annotation(m, ANNOTATION_TOKEN_ID)),
305        config_secrets: config_secrets(template.and_then(|t| t.spec.as_ref()), scope, true),
306    })
307}
308
309/// Consumer for a pod, or `None` when the pod is finished (Succeeded or
310/// Failed) or has nothing to do with us. Terminating pods count: their
311/// containers may still authenticate until they exit.
312pub fn pod_consumer(pod: &Pod, cr_uid: &str, scope: &SecretScope) -> Option<Consumer> {
313    let phase = pod.status.as_ref().and_then(|s| s.phase.as_deref());
314    if matches!(phase, Some("Succeeded" | "Failed")) {
315        return None;
316    }
317    let ours = has_our_uid_label(&pod.metadata, cr_uid);
318    let token_id = annotation(&pod.metadata, ANNOTATION_TOKEN_ID)
319        .filter(|raw| ours || scope.may_name_our_token(raw));
320    let secrets = config_secrets(pod.spec.as_ref(), scope, ours);
321    if !ours && token_id.is_none() && secrets.is_empty() {
322        return None;
323    }
324    Some(Consumer {
325        kind: ConsumerKind::Pod,
326        name: pod.name_any(),
327        token_id,
328        config_secrets: secrets,
329    })
330}
331
332/// Everything read from the API and Kanidm for one observation.
333pub struct ObservedObjects<'a> {
334    pub cr_uid: &'a str,
335    pub cr_name: &'a str,
336    /// Raw `kaniop.rs/radius-rotate-token` value on the CR.
337    pub rotate_request: Option<String>,
338    pub tokens: &'a [ApiToken],
339    /// Config Secrets controlled by this CR (see [`owned_secrets`]).
340    pub secrets: &'a [Secret],
341    pub deployment: Option<&'a Deployment>,
342    pub replicasets: &'a [ReplicaSet],
343    pub pods: &'a [Pod],
344}
345
346/// Assemble the planner input from already-read objects. Pure.
347pub fn build_world(objects: &ObservedObjects<'_>) -> Observation {
348    let scope = SecretScope::new(
349        objects.cr_name,
350        objects.secrets.iter().map(ResourceExt::name_any),
351    )
352    .with_tokens(objects.tokens.iter().map(|t| t.token_id).chain(
353        objects.secrets.iter().filter_map(|s| {
354            annotation(&s.metadata, ANNOTATION_TOKEN_ID).and_then(|raw| Uuid::parse_str(&raw).ok())
355        }),
356    ));
357    let template = objects.deployment.map(|d| template_ref(d, &scope));
358    let deployment_uid = objects.deployment.and_then(|d| d.metadata.uid.as_deref());
359
360    let replicasets = objects
361        .replicasets
362        .iter()
363        .filter(|rs| is_our_replicaset(rs, deployment_uid, objects.cr_uid))
364        .filter_map(|rs| replicaset_consumer(rs, &scope));
365    let pods = objects
366        .pods
367        .iter()
368        .filter_map(|pod| pod_consumer(pod, objects.cr_uid, &scope));
369
370    let template_bearer = template
371        .as_ref()
372        .and_then(|t| t.config_secret.as_deref())
373        .and_then(|name| objects.secrets.iter().find(|s| s.name_any() == name))
374        .and_then(secret_bearer);
375
376    Observation {
377        world: TokenWorld {
378            tokens: observed_tokens(objects.tokens),
379            secrets: objects.secrets.iter().map(observed_secret).collect(),
380            template,
381            consumers: replicasets.chain(pods).collect(),
382            rotate_request: objects.rotate_request.clone(),
383        },
384        template_bearer,
385        deployment: objects.deployment.cloned(),
386    }
387}
388
389async fn list_all<K>(
390    api: &Api<K>,
391    params: ListParams,
392    kind: &str,
393    namespace: &str,
394) -> ExecResult<Vec<K>>
395where
396    K: Resource + Clone + DeserializeOwned + Debug,
397{
398    let mut items = Vec::new();
399    let mut params = params.limit(LIST_PAGE_SIZE);
400    loop {
401        let page = api
402            .list(&params)
403            .await
404            .map_err(|e| kube_error("list", kind, namespace, "*", e))?;
405        items.extend(page.items);
406        match page.metadata.continue_.filter(|token| !token.is_empty()) {
407            Some(token) => params = params.continue_token(&token),
408            None => return Ok(items),
409        }
410    }
411}
412
413/// Owned config Secrets, then every ReplicaSet and pod in the namespace.
414async fn list_consumer_objects(
415    kube: Client,
416    namespace: &str,
417    owner: &OwnerReference,
418) -> ExecResult<(Vec<Secret>, Vec<ReplicaSet>, Vec<Pod>)> {
419    let secret_api: Api<Secret> = Api::namespaced(kube.clone(), namespace);
420    let selector = ListParams::default().labels(&format!("{LABEL_UID}={}", owner.uid));
421    let secrets = owned_secrets(
422        list_all(&secret_api, selector, "Secret", namespace).await?,
423        owner,
424    );
425    // ReplicaSets before pods: a pod listed after its ReplicaSet cannot be a
426    // consumer of a ReplicaSet we missed.
427    let rs_api: Api<ReplicaSet> = Api::namespaced(kube.clone(), namespace);
428    let replicasets = list_all(&rs_api, ListParams::default(), "ReplicaSet", namespace).await?;
429    let pod_api: Api<Pod> = Api::namespaced(kube, namespace);
430    let pods = list_all(&pod_api, ListParams::default(), "Pod", namespace).await?;
431    Ok((secrets, replicasets, pods))
432}
433
434fn namespace_and_owner(radius: &KanidmRadiusServer) -> ExecResult<(String, OwnerReference)> {
435    let namespace = radius.namespace().ok_or(ExecError::MissingMetadata {
436        kind: "KanidmRadiusServer",
437        field: "namespace",
438    })?;
439    let owner = radius
440        .controller_owner_ref(&())
441        .ok_or(ExecError::MissingMetadata {
442            kind: "KanidmRadiusServer",
443            field: "uid",
444        })?;
445    Ok((namespace, owner))
446}
447
448/// Observe Kanidm and Kubernetes for one reconcile.
449///
450/// Fails with [`ExecError::ForeignObject`] if the Deployment name is held by
451/// an object we do not control, before anything is minted. The account must
452/// already exist (call `ensure_identity` first).
453pub async fn observe(
454    client: &KanidmClient,
455    metrics: &ControllerMetrics,
456    kube: Client,
457    radius: &KanidmRadiusServer,
458    identity: &RadiusIdentity,
459) -> ExecResult<Observation> {
460    let (namespace, owner) = namespace_and_owner(radius)?;
461    let name = radius.name_any();
462
463    let deployments: Api<Deployment> = Api::namespaced(kube.clone(), &namespace);
464    let deployment = check_not_foreign(&deployments, &namespace, &name, &owner).await?;
465
466    let tokens = list_tokens(client, metrics, &identity.account_name).await?;
467    let (secrets, replicasets, pods) = list_consumer_objects(kube, &namespace, &owner).await?;
468
469    Ok(build_world(&ObservedObjects {
470        cr_uid: &owner.uid,
471        cr_name: &name,
472        rotate_request: annotation(&radius.metadata, ANNOTATION_ROTATE_TOKEN),
473        tokens: &tokens,
474        secrets: &secrets,
475        deployment: deployment.as_ref(),
476        replicasets: &replicasets,
477        pods: &pods,
478    }))
479}
480
481/// What the finalizer needs from Kubernetes: our Deployment (a foreign one
482/// of the same name is not ours to wait for or delete) and every ReplicaSet
483/// or pod that still uses one of our config Secrets or tokens.
484#[derive(Debug)]
485pub struct DrainObservation {
486    pub deployment: Option<Deployment>,
487    pub consumers: Vec<Consumer>,
488}
489
490/// Kubernetes-only scan used during deletion; reads no Kanidm state.
491pub async fn observe_drain(
492    kube: Client,
493    radius: &KanidmRadiusServer,
494) -> ExecResult<DrainObservation> {
495    let (namespace, owner) = namespace_and_owner(radius)?;
496    let name = radius.name_any();
497    let deployments: Api<Deployment> = Api::namespaced(kube.clone(), &namespace);
498    let deployment = match deployments.get(&name).await {
499        Ok(deployment) if is_controlled_by(&deployment.metadata, &owner) => Some(deployment),
500        Ok(_) => None,
501        Err(kube::Error::Api(status)) if status.code == 404 => None,
502        Err(error) => return Err(kube_error("get", "Deployment", &namespace, &name, error)),
503    };
504    let (secrets, replicasets, pods) = list_consumer_objects(kube, &namespace, &owner).await?;
505    let observation = build_world(&ObservedObjects {
506        cr_uid: &owner.uid,
507        cr_name: &name,
508        rotate_request: None,
509        tokens: &[],
510        secrets: &secrets,
511        deployment: deployment.as_ref(),
512        replicasets: &replicasets,
513        pods: &pods,
514    });
515    Ok(DrainObservation {
516        deployment,
517        consumers: observation.world.consumers,
518    })
519}
520
521#[cfg(test)]
522mod tests {
523    use serde_json::{Value, json};
524    use time::Duration;
525
526    use super::*;
527    use crate::reconcile::token::{CurrentToken, TokenPolicy, plan_tokens};
528
529    const CR: &str = "campus";
530    const CR_UID: &str = "d10066c3-4599-4487-972d-26bb42587a32";
531    const TOKEN_A: &str = "9ad74e68-147f-49e8-96db-dc21c920ff3b";
532    const TOKEN_B: &str = "31b30b65-037a-418f-b7ca-0c376da2db28";
533    // Content-addressed shapes: `<cr>-<10 hex>`.
534    const SECRET_A: &str = "campus-0a1b2c3d4e";
535    const SECRET_B: &str = "campus-f0e1d2c3b4";
536
537    fn scope() -> SecretScope {
538        SecretScope::new(CR, [SECRET_A.to_string(), SECRET_B.to_string()])
539            .with_tokens([uuid(TOKEN_A), uuid(TOKEN_B)])
540    }
541
542    fn uuid(s: &str) -> Uuid {
543        Uuid::parse_str(s).unwrap()
544    }
545
546    fn projected_volume(secret: &str) -> Value {
547        json!({"name": "radius-data", "projected": {"sources": [
548            {"secret": {"name": secret, "items": [{"key": "radius.toml", "path": "radius.toml"}]}},
549            {"secret": {"name": "radius-tls", "items": [{"key": "tls.crt", "path": "cert.pem"}]}}
550        ]}})
551    }
552
553    fn pod_json(
554        name: &str,
555        phase: Option<&str>,
556        volumes: Vec<Value>,
557        annotations: Value,
558        labels: Value,
559    ) -> Value {
560        let mut status = json!({});
561        if let Some(phase) = phase {
562            status = json!({"phase": phase});
563        }
564        json!({
565            "apiVersion": "v1", "kind": "Pod",
566            "metadata": {"name": name, "namespace": "network", "annotations": annotations, "labels": labels},
567            "spec": {"containers": [{"name": "kanidm-radius"}], "volumes": volumes},
568            "status": status
569        })
570    }
571
572    fn pod(value: Value) -> Pod {
573        serde_json::from_value(value).unwrap()
574    }
575
576    fn our_pod(name: &str, secret: &str, token: &str) -> Pod {
577        pod(pod_json(
578            name,
579            Some("Running"),
580            vec![projected_volume(secret)],
581            json!({"kaniop.rs/radius-token-id": token}),
582            json!({"kaniop.rs/radius-uid": CR_UID}),
583        ))
584    }
585
586    #[test]
587    fn pod_matches_by_projected_volume_and_annotation() {
588        let c = pod_consumer(&our_pod("p1", SECRET_A, TOKEN_A), CR_UID, &scope()).unwrap();
589        assert_eq!(c.kind, ConsumerKind::Pod);
590        assert_eq!(c.name, "p1");
591        assert_eq!(c.token_id.as_deref(), Some(TOKEN_A));
592        // Only our config Secret; the user's TLS Secret is not ours.
593        assert_eq!(c.config_secrets, vec![SECRET_A.to_string()]);
594    }
595
596    #[test]
597    fn pod_matches_by_plain_secret_volume_without_annotation() {
598        let p = pod(pod_json(
599            "p2",
600            Some("Running"),
601            vec![json!({"name": "v", "secret": {"secretName": SECRET_B}})],
602            json!({}),
603            json!({}),
604        ));
605        let c = pod_consumer(&p, CR_UID, &scope()).unwrap();
606        assert_eq!(c.config_secrets, vec![SECRET_B.to_string()]);
607        assert_eq!(c.token_id, None);
608    }
609
610    #[test]
611    fn pod_matches_by_env_secret_reference() {
612        let p = pod(json!({
613            "apiVersion": "v1", "kind": "Pod",
614            "metadata": {"name": "p-env", "namespace": "network"},
615            "spec": {"containers": [{"name": "c", "envFrom": [{"secretRef": {"name": SECRET_A}}]}]},
616            "status": {"phase": "Running"}
617        }));
618        let c = pod_consumer(&p, CR_UID, &scope()).unwrap();
619        assert_eq!(c.config_secrets, vec![SECRET_A.to_string()]);
620    }
621
622    #[test]
623    fn pod_matches_by_annotation_alone_and_passes_it_raw() {
624        let p = pod(pod_json(
625            "p3",
626            Some("Pending"),
627            vec![],
628            json!({"kaniop.rs/radius-token-id": "not-a-uuid"}),
629            json!({}),
630        ));
631        let c = pod_consumer(&p, CR_UID, &scope()).unwrap();
632        assert_eq!(c.token_id.as_deref(), Some("not-a-uuid"));
633        assert!(c.config_secrets.is_empty());
634    }
635
636    #[test]
637    fn another_servers_pod_is_not_a_consumer() {
638        // Two servers in one namespace: the other server's pods carry the same
639        // annotation key with a token that is not on our account. They must
640        // not hold our token or block our deletion drain.
641        const OTHER_UID: &str = "0f3c1c5e-8e0a-4d2b-9d54-0b9c3d7a6e11";
642        const OTHER_TOKEN: &str = "6c7a1d52-0c4f-4f0e-8d7b-5b1d0f3a9e22";
643        let p = pod(pod_json(
644            "other-pod",
645            Some("Running"),
646            vec![projected_volume("other-0a1b2c3d4e")],
647            json!({"kaniop.rs/radius-token-id": OTHER_TOKEN}),
648            json!({"kaniop.rs/radius-uid": OTHER_UID}),
649        ));
650        assert_eq!(pod_consumer(&p, CR_UID, &scope()), None);
651    }
652
653    #[test]
654    fn terminating_pod_is_counted() {
655        let mut value = pod_json(
656            "p4",
657            Some("Running"),
658            vec![projected_volume(SECRET_A)],
659            json!({"kaniop.rs/radius-token-id": TOKEN_A}),
660            json!({"kaniop.rs/radius-uid": CR_UID}),
661        );
662        value["metadata"]["deletionTimestamp"] = json!("2026-11-01T10:00:00Z");
663        let c = pod_consumer(&pod(value), CR_UID, &scope());
664        assert_eq!(c.unwrap().token_id.as_deref(), Some(TOKEN_A));
665    }
666
667    #[test]
668    fn succeeded_and_failed_pods_are_ignored() {
669        for phase in ["Succeeded", "Failed"] {
670            let p = pod(pod_json(
671                "done",
672                Some(phase),
673                vec![projected_volume(SECRET_A)],
674                json!({"kaniop.rs/radius-token-id": TOKEN_A}),
675                json!({"kaniop.rs/radius-uid": CR_UID}),
676            ));
677            assert_eq!(pod_consumer(&p, CR_UID, &scope()), None, "{phase}");
678        }
679        // Unknown and missing phases are not finished.
680        for phase in [Some("Unknown"), None] {
681            let p = pod(pod_json(
682                "live",
683                phase,
684                vec![],
685                json!({"kaniop.rs/radius-token-id": TOKEN_A}),
686                json!({}),
687            ));
688            assert!(pod_consumer(&p, CR_UID, &scope()).is_some(), "{phase:?}");
689        }
690    }
691
692    #[test]
693    fn unrelated_pod_is_ignored() {
694        let p = pod(pod_json(
695            "web",
696            Some("Running"),
697            vec![json!({"name": "v", "secret": {"secretName": "radius-tls"}})],
698            json!({}),
699            json!({"app": "web"}),
700        ));
701        assert_eq!(pod_consumer(&p, CR_UID, &scope()), None);
702    }
703
704    #[test]
705    fn pod_mounting_a_deleted_owned_secret_is_still_reported() {
706        // The Secret is not in the owned set (it was deleted), but its name
707        // has our content-addressed shape.
708        let scope = SecretScope::new(CR, [SECRET_B.to_string()]);
709        let c = pod_consumer(&our_pod("p5", SECRET_A, TOKEN_A), CR_UID, &scope).unwrap();
710        assert_eq!(c.config_secrets, vec![SECRET_A.to_string()]);
711    }
712
713    #[test]
714    fn labelled_pod_reports_its_projected_config_secret_whatever_the_name() {
715        let c = pod_consumer(
716            &our_pod("p6", "not-content-addressed", TOKEN_A),
717            CR_UID,
718            &scope(),
719        )
720        .unwrap();
721        assert_eq!(c.config_secrets, vec!["not-content-addressed".to_string()]);
722        // An unlabelled pod doing the same is not claimed.
723        let p = pod(pod_json(
724            "stranger",
725            Some("Running"),
726            vec![projected_volume("not-content-addressed")],
727            json!({}),
728            json!({}),
729        ));
730        assert_eq!(pod_consumer(&p, CR_UID, &scope()), None);
731    }
732
733    #[test]
734    fn labelled_pod_without_any_reference_is_reported_empty() {
735        let p = pod(pod_json(
736            "p7",
737            Some("Running"),
738            vec![],
739            json!({}),
740            json!({"kaniop.rs/radius-uid": CR_UID}),
741        ));
742        let c = pod_consumer(&p, CR_UID, &scope()).unwrap();
743        assert_eq!(c.token_id, None);
744        assert!(c.config_secrets.is_empty());
745    }
746
747    #[test]
748    fn secret_scope_recognises_only_content_addressed_names() {
749        let scope = SecretScope::new(CR, []);
750        assert!(scope.is_ours("campus-0a1b2c3d4e"));
751        assert!(!scope.is_ours("campus-0A1B2C3D4E"), "uppercase");
752        assert!(!scope.is_ours("campus-0a1b2c3d4"), "short");
753        assert!(!scope.is_ours("campus-0a1b2c3d4ef"), "long");
754        assert!(!scope.is_ours("campus-tls"));
755        assert!(!scope.is_ours("other-0a1b2c3d4e"));
756    }
757
758    fn rs_json(
759        name: &str,
760        spec_replicas: Option<i32>,
761        status_replicas: i32,
762        owner_uid: Option<&str>,
763        labelled: bool,
764    ) -> Value {
765        let mut spec = json!({
766            "selector": {"matchLabels": {"a": "b"}},
767            "template": {
768                "metadata": {"annotations": {"kaniop.rs/radius-token-id": TOKEN_A}},
769                "spec": {"containers": [{"name": "c"}], "volumes": [projected_volume(SECRET_A)]}
770            }
771        });
772        if let Some(r) = spec_replicas {
773            spec["replicas"] = json!(r);
774        }
775        let mut meta = json!({"name": name, "namespace": "network"});
776        if let Some(uid) = owner_uid {
777            meta["ownerReferences"] = json!([{
778                "apiVersion": "apps/v1", "kind": "Deployment", "name": CR,
779                "uid": uid, "controller": true
780            }]);
781        }
782        if labelled {
783            meta["labels"] = json!({"kaniop.rs/radius-uid": CR_UID});
784        }
785        json!({"apiVersion": "apps/v1", "kind": "ReplicaSet", "metadata": meta, "spec": spec,
786               "status": {"replicas": status_replicas}})
787    }
788
789    fn rs(value: Value) -> ReplicaSet {
790        serde_json::from_value(value).unwrap()
791    }
792
793    #[test]
794    fn replicaset_with_zero_replicas_is_ignored() {
795        let zero = rs(rs_json("old", Some(0), 0, Some("dep-uid"), true));
796        assert_eq!(replicaset_consumer(&zero, &scope()), None);
797        // Still draining pods: counted until status reaches zero too.
798        let draining = rs(rs_json("old", Some(0), 1, Some("dep-uid"), true));
799        assert!(replicaset_consumer(&draining, &scope()).is_some());
800        let scaled = rs(rs_json("new", Some(2), 2, Some("dep-uid"), true));
801        let c = replicaset_consumer(&scaled, &scope()).unwrap();
802        assert_eq!(c.kind, ConsumerKind::ReplicaSet);
803        assert_eq!(c.token_id.as_deref(), Some(TOKEN_A));
804        assert_eq!(c.config_secrets, vec![SECRET_A.to_string()]);
805        // replicas omitted defaults to 1.
806        let defaulted = rs(rs_json("dflt", None, 0, Some("dep-uid"), true));
807        assert!(replicaset_consumer(&defaulted, &scope()).is_some());
808    }
809
810    #[test]
811    fn replicaset_ownership_by_deployment_uid_or_label() {
812        let by_owner = rs(rs_json("a", Some(1), 1, Some("dep-uid"), false));
813        assert!(is_our_replicaset(&by_owner, Some("dep-uid"), CR_UID));
814        assert!(!is_our_replicaset(&by_owner, Some("other-dep"), CR_UID));
815        assert!(!is_our_replicaset(&by_owner, None, CR_UID));
816        // Deployment gone: the template label still identifies it.
817        let by_label = rs(rs_json("b", Some(1), 1, Some("dep-uid"), true));
818        assert!(is_our_replicaset(&by_label, None, CR_UID));
819        let stranger = rs(rs_json("c", Some(1), 1, None, false));
820        assert!(!is_our_replicaset(&stranger, Some("dep-uid"), CR_UID));
821    }
822
823    fn secret_json(
824        name: &str,
825        token: Option<&str>,
826        bearer: Option<&str>,
827        owner_uid: Option<&str>,
828    ) -> Secret {
829        let mut value = json!({
830            "apiVersion": "v1", "kind": "Secret",
831            "metadata": {"name": name, "namespace": "network",
832                         "labels": {"kaniop.rs/radius-uid": CR_UID}},
833            "data": {}
834        });
835        if let Some(t) = token {
836            value["metadata"]["annotations"] =
837                json!({"kaniop.rs/radius-token-id": t, "kaniop.rs/radius-rotation-request": "r1"});
838        }
839        if let Some(uid) = owner_uid {
840            value["metadata"]["ownerReferences"] = json!([{
841                "apiVersion": "kaniop.rs/v1beta1", "kind": "KanidmRadiusServer",
842                "name": CR, "uid": uid, "controller": true
843            }]);
844        }
845        let mut secret: Secret = serde_json::from_value(value).unwrap();
846        if let Some(b) = bearer {
847            secret.data = Some(std::collections::BTreeMap::from([(
848                "auth_token".to_string(),
849                k8s_openapi::ByteString(b.as_bytes().to_vec()),
850            )]));
851        }
852        secret
853    }
854
855    #[test]
856    fn only_controlled_secrets_are_ours() {
857        let owner = k8s_openapi::apimachinery::pkg::apis::meta::v1::OwnerReference {
858            api_version: "kaniop.rs/v1beta1".into(),
859            kind: "KanidmRadiusServer".into(),
860            name: CR.into(),
861            uid: CR_UID.into(),
862            controller: Some(true),
863            block_owner_deletion: Some(true),
864        };
865        let kept = owned_secrets(
866            vec![
867                secret_json(SECRET_A, Some(TOKEN_A), Some("b"), Some(CR_UID)),
868                // Carries our label but is controlled by someone else.
869                secret_json("spoof", Some(TOKEN_A), Some("b"), Some("other-uid")),
870                secret_json("ownerless", None, None, None),
871            ],
872            &owner,
873        );
874        assert_eq!(kept.len(), 1);
875        assert_eq!(kept[0].name_any(), SECRET_A);
876    }
877
878    #[test]
879    fn observed_secret_reports_annotations_raw_and_bearer_readability() {
880        let s = observed_secret(&secret_json(
881            SECRET_A,
882            Some("garbage"),
883            Some("tok"),
884            Some(CR_UID),
885        ));
886        assert_eq!(s.token_id.as_deref(), Some("garbage"));
887        assert_eq!(s.rotation_request.as_deref(), Some("r1"));
888        assert!(s.bearer_readable);
889        assert_eq!(s.created_at, None);
890        let mut created = secret_json(SECRET_A, Some(TOKEN_A), Some("tok"), Some(CR_UID));
891        created.metadata.creation_timestamp =
892            Some(serde_json::from_value(json!("2026-11-01T10:00:00Z")).unwrap());
893        assert_eq!(
894            observed_secret(&created).created_at,
895            Some(OffsetDateTime::from_unix_timestamp(1_793_527_200).unwrap())
896        );
897        assert!(
898            !observed_secret(&secret_json(SECRET_A, Some(TOKEN_A), None, Some(CR_UID)))
899                .bearer_readable
900        );
901        assert!(
902            !observed_secret(&secret_json(
903                SECRET_A,
904                Some(TOKEN_A),
905                Some("  "),
906                Some(CR_UID)
907            ))
908            .bearer_readable
909        );
910    }
911
912    #[test]
913    fn bearer_debug_never_shows_the_token() {
914        let observation = Observation {
915            world: TokenWorld::default(),
916            template_bearer: Some(Bearer::new("super-secret-bearer".into())),
917            deployment: None,
918        };
919        assert!(!format!("{observation:?}").contains("super-secret-bearer"));
920    }
921
922    fn deployment_json(token: &str, secret: &str, uid: &str) -> Deployment {
923        serde_json::from_value(json!({
924            "apiVersion": "apps/v1", "kind": "Deployment",
925            "metadata": {"name": CR, "namespace": "network", "uid": uid},
926            "spec": {
927                "selector": {"matchLabels": {"a": "b"}},
928                "template": {
929                    "metadata": {"annotations": {"kaniop.rs/radius-token-id": token}},
930                    "spec": {"containers": [{"name": "c"}], "volumes": [projected_volume(secret)]}
931                }
932            }
933        }))
934        .unwrap()
935    }
936
937    #[test]
938    fn template_ref_reads_annotation_and_mounted_config_secret() {
939        let t = template_ref(&deployment_json(TOKEN_B, SECRET_B, "dep-uid"), &scope());
940        assert_eq!(t.token_id.as_deref(), Some(TOKEN_B));
941        assert_eq!(t.config_secret.as_deref(), Some(SECRET_B));
942    }
943
944    fn api_token(id: &str, age: Duration, now: OffsetDateTime) -> ApiToken {
945        serde_json::from_value(json!({
946            "account_id": "00000000-0000-0000-0000-000000000001",
947            "token_id": id,
948            "label": "kaniop-radius-x",
949            "expiry": null,
950            "issued_at": (now - age).unix_timestamp(),
951            "purpose": "readonly"
952        }))
953        .unwrap()
954    }
955
956    /// Rollout in progress: the Deployment already points at token B, one
957    /// old pod still runs token A. A must survive until it is gone, then be
958    /// revoked, and B stays current throughout.
959    #[test]
960    fn observe_then_plan_keeps_old_token_during_rollout() {
961        let now = OffsetDateTime::now_utc();
962        let tokens = [
963            api_token(TOKEN_A, Duration::days(10), now),
964            api_token(TOKEN_B, Duration::hours(1), now),
965        ];
966        let secrets = [
967            secret_json(SECRET_A, Some(TOKEN_A), Some("bearer-a"), Some(CR_UID)),
968            secret_json(SECRET_B, Some(TOKEN_B), Some("bearer-b"), Some(CR_UID)),
969        ];
970        let deployment = deployment_json(TOKEN_B, SECRET_B, "dep-uid");
971        let replicasets = [rs(rs_json("rs-old", Some(1), 1, Some("dep-uid"), true)), {
972            let mut new = rs_json("rs-new", Some(1), 1, Some("dep-uid"), true);
973            new["spec"]["template"]["metadata"]["annotations"]["kaniop.rs/radius-token-id"] =
974                json!(TOKEN_B);
975            new["spec"]["template"]["spec"]["volumes"] = json!([projected_volume(SECRET_B)]);
976            rs(new)
977        }];
978        let mut pods = vec![
979            our_pod("pod-old", SECRET_A, TOKEN_A),
980            our_pod("pod-new", SECRET_B, TOKEN_B),
981        ];
982        let policy = TokenPolicy::from_spec(None);
983        let observe_and_plan = |replicasets: &[ReplicaSet], pods: &[Pod]| {
984            let observation = build_world(&ObservedObjects {
985                cr_uid: CR_UID,
986                cr_name: CR,
987                rotate_request: None,
988                tokens: &tokens,
989                secrets: &secrets,
990                deployment: Some(&deployment),
991                replicasets,
992                pods,
993            });
994            let plan = plan_tokens(&observation.world, &policy, now);
995            (observation, plan)
996        };
997
998        let (observation, plan) = observe_and_plan(&replicasets, &pods);
999        assert_eq!(plan.current, CurrentToken::Keep(uuid(TOKEN_B)));
1000        assert!(plan.revoke.is_empty(), "old token still used: {plan:?}");
1001        assert_eq!(plan.retiring, vec![uuid(TOKEN_A)]);
1002        assert!(plan.gc_secrets.is_empty());
1003        assert_eq!(observation.template_bearer.unwrap().expose(), "bearer-b");
1004
1005        // Old ReplicaSet scaled to zero, but its pod is still Terminating.
1006        let mut drained = replicasets.clone();
1007        drained[0] = rs(rs_json("rs-old", Some(0), 0, Some("dep-uid"), true));
1008        let mut terminating = serde_json::to_value(&pods[0]).unwrap();
1009        terminating["metadata"]["deletionTimestamp"] = json!("2026-11-01T10:00:00Z");
1010        pods[0] = pod(terminating);
1011        let (_, plan) = observe_and_plan(&drained, &pods);
1012        assert!(plan.revoke.is_empty(), "terminating pod holds A: {plan:?}");
1013
1014        // Pod gone: A is revoked, its Secret collected, B untouched.
1015        pods.remove(0);
1016        let (_, plan) = observe_and_plan(&drained, &pods);
1017        assert_eq!(plan.current, CurrentToken::Keep(uuid(TOKEN_B)));
1018        assert_eq!(plan.revoke, vec![uuid(TOKEN_A)]);
1019        assert_eq!(plan.gc_secrets, vec![SECRET_A.to_string()]);
1020    }
1021
1022    /// A pod mounting an owned Secret that has been deleted cannot be
1023    /// resolved to a token, so nothing is revoked until it is gone.
1024    #[test]
1025    fn pod_on_deleted_secret_blocks_revocation() {
1026        let now = OffsetDateTime::now_utc();
1027        let tokens = [
1028            api_token(TOKEN_A, Duration::days(10), now),
1029            api_token(TOKEN_B, Duration::hours(1), now),
1030        ];
1031        // SECRET_A was deleted: only B's Secret exists.
1032        let secrets = [secret_json(
1033            SECRET_B,
1034            Some(TOKEN_B),
1035            Some("bearer-b"),
1036            Some(CR_UID),
1037        )];
1038        let deployment = deployment_json(TOKEN_B, SECRET_B, "dep-uid");
1039        // The pod carries no annotation, so only the mount names a token.
1040        let stranded = pod(pod_json(
1041            "pod-old",
1042            Some("Running"),
1043            vec![projected_volume(SECRET_A)],
1044            json!({}),
1045            json!({"kaniop.rs/radius-uid": CR_UID}),
1046        ));
1047        let observation = build_world(&ObservedObjects {
1048            cr_uid: CR_UID,
1049            cr_name: CR,
1050            rotate_request: None,
1051            tokens: &tokens,
1052            secrets: &secrets,
1053            deployment: Some(&deployment),
1054            replicasets: &[],
1055            pods: std::slice::from_ref(&stranded),
1056        });
1057        assert_eq!(
1058            observation.world.consumers[0].config_secrets,
1059            vec![SECRET_A.to_string()]
1060        );
1061        let plan = plan_tokens(&observation.world, &TokenPolicy::from_spec(None), now);
1062        assert!(plan.revoke.is_empty(), "{plan:?}");
1063        assert_eq!(plan.unresolved_consumers, vec!["pod/pod-old".to_string()]);
1064    }
1065
1066    #[test]
1067    fn status_loss_and_no_deployment_mint_initial() {
1068        let now = OffsetDateTime::now_utc();
1069        let observation = build_world(&ObservedObjects {
1070            cr_uid: CR_UID,
1071            cr_name: CR,
1072            rotate_request: Some("x".into()),
1073            tokens: &[],
1074            secrets: &[],
1075            deployment: None,
1076            replicasets: &[],
1077            pods: &[],
1078        });
1079        assert_eq!(observation.world.rotate_request.as_deref(), Some("x"));
1080        assert!(observation.world.template.is_none());
1081        let plan = plan_tokens(&observation.world, &TokenPolicy::from_spec(None), now);
1082        assert!(matches!(plan.current, CurrentToken::Mint(_)));
1083    }
1084
1085    fn radius_cr() -> KanidmRadiusServer {
1086        serde_json::from_value(json!({
1087            "apiVersion": "kaniop.rs/v1beta1",
1088            "kind": "KanidmRadiusServer",
1089            "metadata": {
1090                "name": CR, "namespace": "network", "uid": CR_UID,
1091                "annotations": {"kaniop.rs/radius-rotate-token": "now-please"}
1092            },
1093            "spec": {
1094                "kanidmRef": {"name": "idm"},
1095                "authorization": {"requiredGroups": ["allowed@idm.example.com"]},
1096                "clients": [{
1097                    "name": "nas", "ipaddr": "192.0.2.1",
1098                    "sharedSecretRef": {"name": "nas-secret", "key": "nas"}
1099                }],
1100                "radiusTls": {"secretRef": {"name": "eap-tls"}}
1101            }
1102        }))
1103        .unwrap()
1104    }
1105
1106    fn list(kind: &str, items: Vec<Value>, continue_token: Option<&str>) -> (u16, Value) {
1107        let mut metadata = json!({});
1108        if let Some(token) = continue_token {
1109            metadata["continue"] = json!(token);
1110        }
1111        (
1112            200,
1113            json!({"apiVersion": "v1", "kind": kind, "metadata": metadata, "items": items}),
1114        )
1115    }
1116
1117    #[tokio::test]
1118    async fn observe_fails_on_a_foreign_deployment_before_touching_kanidm() {
1119        use crate::reconcile::kanidm_mock;
1120        use crate::reconcile::kube_mock::{mock_client, to_json};
1121
1122        let radius = radius_cr();
1123        let identity = RadiusIdentity::for_resource(&radius).unwrap();
1124        let mut foreign = deployment_json(TOKEN_A, SECRET_A, "dep-uid");
1125        foreign.metadata.owner_references = None;
1126        let (kube, recorder) = mock_client(vec![(200, to_json(&foreign))]);
1127        let mock = kanidm_mock::start(|_| (500, "{}".into())).await;
1128        let error = observe(&mock.client, &mock.metrics, kube, &radius, &identity)
1129            .await
1130            .unwrap_err();
1131        assert!(matches!(error, ExecError::ForeignObject { .. }));
1132        assert!(
1133            mock.requests().is_empty(),
1134            "no Kanidm call, so nothing minted"
1135        );
1136        assert_eq!(recorder.await.unwrap().len(), 1);
1137    }
1138
1139    #[tokio::test]
1140    async fn observe_lists_namespace_wide_pages_and_builds_the_world() {
1141        use crate::reconcile::kanidm_mock;
1142        use crate::reconcile::kube_mock::{api_status, mock_client, to_json};
1143
1144        let radius = radius_cr();
1145        let identity = RadiusIdentity::for_resource(&radius).unwrap();
1146        let now = OffsetDateTime::now_utc();
1147        let token_list =
1148            serde_json::to_string(&[api_token(TOKEN_A, Duration::days(1), now)]).unwrap();
1149        let mock = kanidm_mock::start(move |_| (200, token_list.clone())).await;
1150
1151        let mut secret = secret_json(SECRET_A, Some(TOKEN_A), Some("bearer-a"), Some(CR_UID));
1152        secret.metadata.resource_version = Some("1".into());
1153        let page2_pod = our_pod("pod-on-page-two", SECRET_A, TOKEN_A);
1154        let (kube, recorder) = mock_client(vec![
1155            api_status(404, "NotFound"),
1156            list("SecretList", vec![to_json(&secret)], None),
1157            list("ReplicaSetList", vec![], None),
1158            list(
1159                "PodList",
1160                vec![to_json(&our_pod("pod-on-page-one", SECRET_A, TOKEN_A))],
1161                Some("next-page"),
1162            ),
1163            list("PodList", vec![to_json(&page2_pod)], None),
1164        ]);
1165        let observation = observe(&mock.client, &mock.metrics, kube, &radius, &identity)
1166            .await
1167            .unwrap();
1168
1169        let world = &observation.world;
1170        assert_eq!(world.tokens.len(), 1);
1171        assert_eq!(world.secrets[0].name, SECRET_A);
1172        assert!(world.template.is_none());
1173        assert_eq!(world.rotate_request.as_deref(), Some("now-please"));
1174        let names: Vec<_> = world.consumers.iter().map(|c| c.name.as_str()).collect();
1175        assert_eq!(names, ["pod-on-page-one", "pod-on-page-two"]);
1176
1177        let requests = recorder.await.unwrap();
1178        let uris: Vec<_> = requests.iter().map(|r| r.uri.as_str()).collect();
1179        assert!(
1180            uris[1].contains("/secrets")
1181                && uris[1].contains("labelSelector=kaniop.rs%2Fradius-uid%3D"),
1182            "{uris:?}"
1183        );
1184        assert!(
1185            uris[2].contains("/replicasets") && !uris[2].contains("labelSelector"),
1186            "{uris:?}"
1187        );
1188        assert!(
1189            uris[3].contains("/pods") && !uris[3].contains("labelSelector"),
1190            "pods are scanned namespace-wide: {uris:?}"
1191        );
1192        assert!(uris[3].contains("limit=500"));
1193        assert!(uris[4].contains("continue=next-page"), "{uris:?}");
1194    }
1195}