kaniop-operator 0.23.0

Core library for the Kanidm Kubernetes operator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
use super::secret::{SECRET_TYPE_LABEL, SecretExt, SecretType};
use super::statefulset::StatefulSetExt;

use crate::kanidm::controller::context::Context;
use crate::kanidm::crd::{
    DomainAppearanceImageStatus, Kanidm, KanidmReplicaState, KanidmReplicaStatus, KanidmStatus,
    KanidmUpgradeCheckResult, KanidmVersionStatus, VersionCompatibilityResult,
};
use crate::version;
use kaniop_k8s_util::error::{Error, Result};

use std::sync::Arc;
use std::time::Duration;

use futures::future::join_all;
use k8s_openapi::api::apps::v1::{StatefulSet, StatefulSetStatus};
use k8s_openapi::api::core::v1::Secret;
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, Time};
use k8s_openapi::jiff::Timestamp;
use kaniop_k8s_util::resources::{get_image_tag, last_transition_time};
use kube::Resource;
use kube::ResourceExt;
use kube::api::{Api, Patch, PatchParams};
use kube::runtime::events::{Event, EventType};
use kube::runtime::reflector::ObjectRef;
use tokio::time::sleep;
use tracing::{debug, trace, warn};

/// At least one replica has been ready for `minReadySeconds`.
const TYPE_AVAILABLE: &str = "Available";
/// Any StatefulSet is progressing
const TYPE_PROGRESSING: &str = "Progressing";
/// Admin secret exists
const TYPE_INITIALIZED: &str = "Initialized";
/// Indicates whether the StatefulSet has failed to create or delete replicas.
const TYPE_REPLICA_FAILURE: &str = "ReplicaFailure";

const CONDITION_TRUE: &str = "True";
const CONDITION_FALSE: &str = "False";

/// Image metadata is needed by the backup transport even when upgrade policy is bypassed.
/// Prefer the applied StatefulSet image; use the desired image before the first StatefulSet.
fn skipped_upgrade_check_version_status(
    running_image_tag: Option<String>,
    desired_image_tag: Option<String>,
) -> Option<KanidmVersionStatus> {
    running_image_tag
        .or(desired_image_tag)
        .map(|image_tag| KanidmVersionStatus {
            image_tag,
            upgrade_check_result: KanidmUpgradeCheckResult::Skipped,
            compatibility_result: VersionCompatibilityResult::NotChecked,
        })
}

#[allow(async_fn_in_trait)]
pub trait StatusExt {
    async fn update_status(&self, ctx: Arc<Context>) -> Result<KanidmStatus>;
}

impl StatusExt for Kanidm {
    async fn update_status(&self, ctx: Arc<Context>) -> Result<KanidmStatus> {
        let name = &self.name_any();

        async fn publish_incompatible_version_event(
            ctx: &Arc<Context>,
            kanidm: &Kanidm,
            desired: &str,
        ) -> VersionCompatibilityResult {
            let _ignore_error = ctx
                .kaniop_ctx
                .recorder
                .publish(
                    &Event {
                        type_: EventType::Warning,
                        reason: "VersionIncompatible".to_string(),
                        note: Some(format!(
                            "Kanidm image version {} is not compatible with this operator. The operator uses Kanidm client SDK v{}. Either use a compatible image version or set spec.disableUpgradeChecks: true (not recommended).",
                            desired,
                            version::KANIDM_CLIENT_VERSION
                        )),
                        action: "VersionCheck".to_string(),
                        secondary: None,
                    },
                    &kanidm.object_ref(&()),
                )
                .await
                .map_err(|e| {
                    warn!(%e, "failed to publish VersionIncompatible event");
                    Error::KubeError("failed to publish event".to_string(), Box::new(e))
                });
            VersionCompatibilityResult::Incompatible
        }
        let namespace = &self.get_namespace();
        let statefulsets = self
            .spec
            .replica_groups
            .iter()
            .filter_map(|rg| {
                let sts_name = self.statefulset_name(&rg.name);
                let sts_ref = ObjectRef::<StatefulSet>::new_with(&sts_name, ()).within(namespace);
                ctx.stores.stateful_set_store.get(&sts_ref)
            })
            .collect::<Vec<Arc<StatefulSet>>>();

        let sts_status = statefulsets
            .iter()
            .map(|sts| sts.status.clone())
            .collect::<Vec<Option<StatefulSetStatus>>>();

        let secret_ref = ObjectRef::<Secret>::new_with(&self.admins_secret_name(), ())
            .within(&self.get_namespace());
        let admin_secret = ctx
            .stores
            .secret_store
            .get(&secret_ref)
            .map(|s| s.name_any());

        let replica_infos_futures: Vec<_> = statefulsets
            .iter()
            .flat_map(|sts| {
                let replicas = sts.spec.as_ref().and_then(|s| s.replicas).unwrap_or(0);
                let secret_store = ctx.stores.secret_store.clone();
                let ctx_clone = ctx.clone();
                let namespace = namespace.to_string();

                (0..replicas).map(move |i| {
                    let sts_name = sts.name_any();
                    let secret_store = secret_store.clone();
                    let ctx = ctx_clone.clone();
                    let namespace = namespace.clone();
                    let pod_name = format!("{sts_name}-{i}");
                    let pod_env_prefix = self.pod_env_prefix(&pod_name);
                    let host_env = format!("{pod_env_prefix}_HOST");
                    let replication_host = sts.spec.as_ref().and_then(|s| s.template.spec.as_ref().and_then(|t_s| t_s.init_containers.as_ref().and_then(|c| c.first().and_then(|f_c| f_c.env.as_ref().and_then(|env|
                        env.iter().find(|e| e.name == host_env).and_then(|e| e.value.clone()))))));
                    let secret_name = self.replica_secret_name(&pod_name);
                    let replica_cert_label = serde_plain::to_string(&SecretType::ReplicaCert)
                        .expect("replica cert secret type must serialize");

                    let secret_ref =
                        ObjectRef::<Secret>::new_with(&secret_name, ()).within(&namespace);

                    async move {
                        let replica_secret = secret_store.get(&secret_ref);
                        if let Some(secret) = replica_secret.as_deref() {
                            let has_replica_cert_label = secret
                                .metadata
                                .labels
                                .as_ref()
                                .is_some_and(|labels| {
                                    labels.get(SECRET_TYPE_LABEL) == Some(&replica_cert_label)
                                });
                            if !has_replica_cert_label {
                                warn!(namespace, name = secret_name, "replica certificate secret is missing the required replica-cert label and will be ignored");
                            } else if let Err(e) = ctx.insert_repl_cert_exp(secret).await {
                                warn!(namespace, name = secret_name, %e, "failed to parse replica certificate secret, automatic certificate renewal may be affected");
                            }
                        }

                        let is_certificate_expiring =
                            ctx.get_repl_cert_exp(&secret_ref).await.map(|exp| {
                                let now = Timestamp::now().as_second();
                                // 1 month in seconds
                                let threshold = 30 * 24 * 60 * 60;
                                trace!("replica cert expiration {exp}, now {now}, threshold {threshold}");
                                exp - now < threshold
                            });
                        let is_certificate_host_valid = ctx.get_repl_cert_host(&secret_ref).await.map(|h| {
                                let matches = Some(h.clone()) == replication_host;
                                trace!("replica cert host {h}, expected host {:?}, matches {matches}", replication_host);
                                matches
                            });
                        ReplicaInformation {
                            pod_name,
                            statefulset_name: sts_name.clone(),
                            replica_secret_exists: replica_secret.is_some(),
                            is_certificate_expiring,
                            is_certificate_host_valid,
                        }
                    }
                })
            })
            .collect();
        let replica_infos = join_all(replica_infos_futures).await;
        let running_image_tag = statefulsets.iter().find_map(|sts| {
            sts.spec.as_ref().and_then(|s| {
                s.template.spec.as_ref().and_then(|t| {
                    t.containers
                        .first()
                        .and_then(|c| c.image.as_ref().and_then(|i| get_image_tag(i)))
                })
            })
        });
        let desired_image_tag = get_image_tag(&self.spec.image);

        let version = if self.spec.disable_upgrade_checks {
            debug!("upgrade checks are disabled; retaining image version for dependent features");
            skipped_upgrade_check_version_status(running_image_tag, desired_image_tag)
        } else {
            match running_image_tag {
                Some(tag) => {
                    let upgrade_check = self.run_upgrade_pre_check(ctx.clone()).await;
                    let compatibility_result = match desired_image_tag {
                        Some(desired) if !version::is_version_compatible(&desired) => {
                            publish_incompatible_version_event(&ctx, self, &desired).await
                        }
                        _ => VersionCompatibilityResult::Compatible,
                    };
                    Some(KanidmVersionStatus {
                        image_tag: tag,
                        upgrade_check_result: upgrade_check,
                        compatibility_result,
                    })
                }
                None => match desired_image_tag {
                    Some(desired) => {
                        let compatibility_result = if !version::is_version_compatible(&desired) {
                            publish_incompatible_version_event(&ctx, self, &desired).await
                        } else {
                            VersionCompatibilityResult::Compatible
                        };
                        Some(KanidmVersionStatus {
                            image_tag: desired,
                            upgrade_check_result: KanidmUpgradeCheckResult::Passed,
                            compatibility_result,
                        })
                    }
                    None => None,
                },
            }
        };

        let kanidm_api = Api::<Kanidm>::namespaced(ctx.kaniop_ctx.client.clone(), namespace);
        let current_kanidm = kanidm_api.get(name).await.map_err(|e| {
            Error::KubeError(
                format!("failed to get current Kanidm {namespace}/{name}"),
                Box::new(e),
            )
        })?;

        // Keep the image status after the image is removed from the spec: domain appearance
        // reconciliation uses it to delete the image from Kanidm, and clears it afterwards.
        let domain_appearance_image = current_kanidm
            .status
            .as_ref()
            .and_then(|s| s.domain_appearance_image.clone());

        // Preserve the mail sender status set by reconciliation, which patches it independently.
        let mail_sender = current_kanidm
            .status
            .as_ref()
            .and_then(|s| s.mail_sender.clone());

        let new_status = generate_status(
            self.status
                .as_ref()
                .cloned()
                .unwrap_or_default()
                .conditions
                .unwrap_or_default(),
            &sts_status,
            admin_secret,
            replica_infos,
            self.is_replication_enabled(),
            current_kanidm.metadata.generation,
            version,
            domain_appearance_image,
            mail_sender,
        );

        let new_status_patch = serde_json::json!({
            "status": new_status.clone()
        });
        debug!("updating Kanidm status");
        trace!("new status {:?}", new_status_patch);
        let patch = PatchParams::default();
        let _o = kanidm_api
            .patch_status(name, &patch, &Patch::Merge(&new_status_patch))
            .await
            .map_err(|e| {
                Error::KubeError(
                    format!("failed to patch Kanidm/status {namespace}/{name}"),
                    Box::new(e),
                )
            })?;
        Ok(new_status)
    }
}

impl Kanidm {
    async fn run_upgrade_pre_check(&self, ctx: Arc<Context>) -> KanidmUpgradeCheckResult {
        let upgrade_check = vec!["kanidmd", "domain", "upgrade-check"];
        debug!("running kanidmd domain upgrade-check");

        const MAX_RETRIES: u32 = 5;
        const RETRY_DELAY_MS: u64 = 2000;

        for attempt in 0..MAX_RETRIES {
            let result = self.exec_any(ctx.clone(), upgrade_check.clone()).await;
            match result {
                Ok(r) => {
                    debug!("kanidmd domain upgrade-check passed: {:?}", r);
                    return KanidmUpgradeCheckResult::Passed;
                }
                Err(e) => {
                    debug!(%e, "kanidmd domain upgrade-check failed (attempt {})", attempt + 1);
                    if attempt < MAX_RETRIES - 1 {
                        trace!(%e, "kanidmd domain upgrade-check failed, retrying");
                        sleep(Duration::from_millis(RETRY_DELAY_MS)).await;
                    } else {
                        match e {
                            Error::KubeExecError(e_msg) => {
                                warn!(%e_msg, "`kanidmd domain upgrade-check` failed");
                            }
                            _ => {
                                warn!(%e, "`kanidmd domain upgrade-check` failed after retries");
                            }
                        }
                        let _ignore_error = ctx
                            .kaniop_ctx
                            .recorder
                            .publish(
                                &Event {
                                    type_: EventType::Warning,
                                    reason: "UpgradeCheckFailed".to_string(),
                                    note: Some("`kanidmd domain upgrade-check` failed. See kanidm operator logs for details.".to_string()),
                                    action: "UpgradeCheck".to_string(),
                                    secondary: None,
                                },
                                &self.object_ref(&()),
                            )
                            .await
                            .map_err(|e| {
                                warn!(%e, "failed to publish KanidmError event");
                                Error::KubeError("failed to publish event".to_string(), Box::new(e))
                            });
                    }
                }
            }
        }

        KanidmUpgradeCheckResult::Failed
    }
}

struct ReplicaInformation {
    pod_name: String,
    statefulset_name: String,
    replica_secret_exists: bool,
    is_certificate_expiring: Option<bool>,
    is_certificate_host_valid: Option<bool>,
}

pub fn is_kanidm_available(status: KanidmStatus) -> bool {
    status
        .conditions
        .unwrap_or_default()
        .iter()
        .any(|c| c.type_ == TYPE_AVAILABLE && c.status == CONDITION_TRUE)
}

pub fn is_kanidm_initialized(status: KanidmStatus) -> bool {
    status
        .conditions
        .unwrap_or_default()
        .iter()
        .any(|c| c.type_ == TYPE_INITIALIZED && c.status == CONDITION_TRUE)
}

#[allow(clippy::too_many_arguments)]
fn generate_status(
    previous_conditions: Vec<Condition>,
    statefulset_statuses: &[Option<StatefulSetStatus>],
    secret_name: Option<String>,
    replica_infos: Vec<ReplicaInformation>,
    is_replication_enabled: bool,
    kanidm_generation: Option<i64>,
    version: Option<KanidmVersionStatus>,
    domain_appearance_image: Option<DomainAppearanceImageStatus>,
    mail_sender: Option<crate::kanidm::crd::MailSenderStatus>,
) -> KanidmStatus {
    let available_replicas = statefulset_statuses
        .iter()
        .filter_map(|sts| sts.as_ref())
        .map(|sts| sts.available_replicas.unwrap_or(0))
        .sum();

    let replicas = statefulset_statuses
        .iter()
        .filter_map(|sts| sts.as_ref())
        .map(|sts| sts.replicas)
        .sum();

    let replica_statuses = replica_infos
        .iter()
        .map(|ri| KanidmReplicaStatus {
            pod_name: ri.pod_name.clone(),
            statefulset_name: ri.statefulset_name.clone(),
            state: if ri.replica_secret_exists || !is_replication_enabled {
                if ri.is_certificate_expiring == Some(true) {
                    debug!("replica cert is expiring for pod {}", ri.pod_name);
                    KanidmReplicaState::CertificateExpiring
                } else if ri.is_certificate_host_valid == Some(false) {
                    debug!("replica cert host is invalid for pod {}", ri.pod_name);
                    KanidmReplicaState::CertificateHostInvalid
                } else {
                    KanidmReplicaState::Ready
                }
            } else {
                KanidmReplicaState::Pending
            },
        })
        .collect::<Vec<KanidmReplicaStatus>>();

    let new_conditions = generate_status_conditions(
        previous_conditions,
        statefulset_statuses,
        secret_name.is_some(),
        &replica_statuses,
        kanidm_generation,
    );

    let replica_column = format!("{available_replicas}/{replicas}");
    KanidmStatus {
        conditions: Some(new_conditions),
        available_replicas,
        replicas,
        unavailable_replicas: replicas - available_replicas,
        updated_replicas: statefulset_statuses
            .iter()
            .filter_map(|sts| sts.as_ref())
            .map(|sts| sts.updated_replicas.unwrap_or(0))
            .sum(),
        replica_statuses,
        replica_column,
        secret_name,
        version,
        domain_appearance_image,
        mail_sender,
    }
}

/// Generates a list of status conditions for a Kanidm based on its current status and previous conditions.
fn generate_status_conditions(
    previous_conditions: Vec<Condition>,
    statefulset_statuses: &[Option<StatefulSetStatus>],
    secret_exists: bool,
    replica_statuses: &[KanidmReplicaStatus],
    kanidm_generation: Option<i64>,
) -> Vec<Condition> {
    let sts_statuses = statefulset_statuses.iter().filter_map(|sts| sts.as_ref());

    let available_condition = match sts_statuses
        .clone()
        .any(|s| s.available_replicas >= Some(1))
    {
        true => Condition {
            type_: TYPE_AVAILABLE.to_string(),
            status: CONDITION_TRUE.to_string(),
            reason: "ReplicaReady".to_string(),
            message: "At least one replica is ready.".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: kanidm_generation,
        },
        false => Condition {
            type_: TYPE_AVAILABLE.to_string(),
            status: CONDITION_FALSE.to_string(),
            reason: "NoReplicaReady".to_string(),
            message: "No replicas are ready.".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: kanidm_generation,
        },
    };

    let initialized_condition = match secret_exists {
        true => Condition {
            type_: TYPE_INITIALIZED.to_string(),
            status: CONDITION_TRUE.to_string(),
            reason: "AdminSecretExists".to_string(),
            message: "admin and idm_admin passwords have been generated.".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: kanidm_generation,
        },
        false => Condition {
            type_: TYPE_INITIALIZED.to_string(),
            status: CONDITION_FALSE.to_string(),
            reason: "AdminSecretNotExists".to_string(),
            message: "admin and idm_admin passwords have not been generated.".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: kanidm_generation,
        },
    };

    let replicate_failure_condition = match sts_statuses.clone().any(|s| {
        s.conditions
            .as_ref()
            .map(|conditions| {
                conditions
                    .iter()
                    .any(|c| c.type_ == TYPE_REPLICA_FAILURE && c.status == CONDITION_TRUE)
            })
            .unwrap_or(false)
    }) {
        true => Condition {
            type_: TYPE_REPLICA_FAILURE.to_string(),
            status: CONDITION_TRUE.to_string(),
            reason: "ReplicaCreationFailure".to_string(),
            message: "Failed to create or delete replicas.".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: kanidm_generation,
        },
        false => Condition {
            type_: TYPE_REPLICA_FAILURE.to_string(),
            status: CONDITION_FALSE.to_string(),
            reason: "NoReplicaFailure".to_string(),
            message: "No replica creation or deletion failures.".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: kanidm_generation,
        },
    };

    let previous_observed_generation = previous_conditions
        .iter()
        .find_map(|c| c.observed_generation);

    // A status that never recorded an observed generation has not reported on any spec yet, so the
    // first report counts as a change. Otherwise a Kanidm whose reconciliation keeps failing would
    // already start out as "not progressing", and every later status would be identical, so neither
    // the status update after a failed reconciliation nor any observer could see that an attempt
    // was made.
    let generation_changed = previous_observed_generation != kanidm_generation;

    let progressing_condition = if generation_changed {
        Condition {
            type_: TYPE_PROGRESSING.to_string(),
            status: CONDITION_TRUE.to_string(),
            reason: "SpecChanged".to_string(),
            message: "Kanidm spec has changed.".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: kanidm_generation,
        }
    } else if sts_statuses
        .clone()
        .any(|s| s.current_revision != s.update_revision)
    {
        Condition {
            type_: TYPE_PROGRESSING.to_string(),
            status: CONDITION_TRUE.to_string(),
            reason: "RollingUpdateInProgress".to_string(),
            message: "StatefulSet rolling update is in progress.".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: kanidm_generation,
        }
    } else if sts_statuses.clone().any(|s| {
        s.conditions
            .as_ref()
            .map(|conditions| {
                conditions
                    .iter()
                    .any(|c| c.type_ == TYPE_PROGRESSING && c.status == CONDITION_TRUE)
            })
            .unwrap_or(false)
    }) {
        Condition {
            type_: TYPE_PROGRESSING.to_string(),
            status: CONDITION_TRUE.to_string(),
            reason: "Progressing".to_string(),
            message: "StatefulSet is progressing.".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: kanidm_generation,
        }
    } else if replica_statuses
        .iter()
        .any(|rs| rs.state != KanidmReplicaState::Ready)
    {
        Condition {
            type_: TYPE_PROGRESSING.to_string(),
            status: CONDITION_TRUE.to_string(),
            reason: "ReplicaStatusPending".to_string(),
            message: "At least one replica is not ready.".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: kanidm_generation,
        }
    } else if sts_statuses
        .clone()
        .any(|s| s.replicas > s.available_replicas.unwrap_or(0))
    {
        Condition {
            type_: TYPE_PROGRESSING.to_string(),
            status: CONDITION_TRUE.to_string(),
            reason: "ReplicaCreation".to_string(),
            message: "Replicas are being created.".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: kanidm_generation,
        }
    } else {
        Condition {
            type_: TYPE_PROGRESSING.to_string(),
            status: CONDITION_FALSE.to_string(),
            reason: "NotProgressing".to_string(),
            message: "StatefulSet is not progressing.".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: kanidm_generation,
        }
    };

    [
        available_condition,
        progressing_condition,
        initialized_condition,
        replicate_failure_condition,
    ]
    .into_iter()
    .fold(previous_conditions, |previous_conditions, c| {
        update_conditions(previous_conditions, &c)
    })
}

/// Update conditions based on the current status and previous conditions in the Kanidm.
///
/// The previous `lastTransitionTime` is kept while the condition status and reason do not change,
/// so reconciling an unchanged Kanidm produces an identical status, which neither updates the
/// object nor triggers another reconciliation.
fn update_conditions(
    previous_conditions: Vec<Condition>,
    new_condition: &Condition,
) -> Vec<Condition> {
    let new_condition = &Condition {
        last_transition_time: last_transition_time(
            Some(&previous_conditions),
            &new_condition.type_,
            &new_condition.status,
            &new_condition.reason,
        ),
        ..new_condition.clone()
    };
    if previous_conditions
        .iter()
        .any(|c| c.type_ == *new_condition.type_)
    {
        previous_conditions
            .iter()
            .filter(|c| c.type_ != *new_condition.type_)
            .cloned()
            .chain(std::iter::once(new_condition.clone()))
            .collect()
    } else {
        previous_conditions
            .iter()
            .cloned()
            .chain(std::iter::once(new_condition.clone()))
            .collect()
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn skipped_checks_use_running_version_over_desired_version() {
        let status = skipped_upgrade_check_version_status(
            Some("1.11.2".to_string()),
            Some("1.12.0".to_string()),
        )
        .expect("running image tag is available");
        assert_eq!(status.image_tag, "1.11.2");
        assert_eq!(
            status.upgrade_check_result,
            KanidmUpgradeCheckResult::Skipped
        );
        assert_eq!(
            status.compatibility_result,
            VersionCompatibilityResult::NotChecked
        );
    }

    #[test]
    fn skipped_checks_use_desired_version_before_first_statefulset() {
        let status = skipped_upgrade_check_version_status(None, Some("1.12.0".to_string()))
            .expect("desired image tag is available");
        assert_eq!(status.image_tag, "1.12.0");
        assert_eq!(
            status.upgrade_check_result,
            KanidmUpgradeCheckResult::Skipped
        );
    }

    #[test]
    fn skipped_checks_do_not_fabricate_version_for_digest_only_images() {
        assert!(skipped_upgrade_check_version_status(None, None).is_none());
    }

    fn ready_statefulset_status() -> Option<StatefulSetStatus> {
        Some(StatefulSetStatus {
            replicas: 1,
            available_replicas: Some(1),
            ready_replicas: Some(1),
            current_revision: Some("rev-1".to_string()),
            update_revision: Some("rev-1".to_string()),
            ..Default::default()
        })
    }

    fn with_transition_time(conditions: Vec<Condition>, second: i64) -> Vec<Condition> {
        conditions
            .into_iter()
            .map(|c| Condition {
                last_transition_time: Time(Timestamp::from_second(second).unwrap()),
                ..c
            })
            .collect()
    }

    /// Conditions of a Kanidm that already reported on `generation`.
    fn previously_observed(generation: i64) -> Vec<Condition> {
        vec![Condition {
            type_: TYPE_PROGRESSING.to_string(),
            status: CONDITION_FALSE.to_string(),
            reason: "NotProgressing".to_string(),
            message: "StatefulSet is not progressing.".to_string(),
            last_transition_time: Time(Timestamp::from_second(1_700_000_000).unwrap()),
            observed_generation: Some(generation),
        }]
    }

    fn progressing_condition(conditions: &[Condition]) -> &Condition {
        conditions
            .iter()
            .find(|c| c.type_ == TYPE_PROGRESSING)
            .expect("progressing condition is always generated")
    }

    /// Conditions without their transition times, which change on every reported transition.
    fn condition_values(conditions: Vec<Condition>) -> Vec<(String, String, String, Option<i64>)> {
        conditions
            .into_iter()
            .map(|c| (c.type_, c.status, c.reason, c.observed_generation))
            .collect()
    }

    #[test]
    fn test_generate_status_conditions_keeps_transition_time_without_changes() {
        let sts_statuses = [ready_statefulset_status()];
        let previous = with_transition_time(
            generate_status_conditions(previously_observed(1), &sts_statuses, true, &[], Some(1)),
            1_700_000_000,
        );

        let conditions =
            generate_status_conditions(previous.clone(), &sts_statuses, true, &[], Some(1));

        assert_eq!(conditions, previous);
    }

    #[test]
    fn test_generate_status_conditions_updates_transition_time_on_change() {
        let previous = with_transition_time(
            generate_status_conditions(
                Vec::new(),
                &[ready_statefulset_status()],
                true,
                &[],
                Some(1),
            ),
            1_700_000_000,
        );
        let mut sts_status = ready_statefulset_status();
        if let Some(status) = sts_status.as_mut() {
            status.available_replicas = Some(0);
        }

        let conditions = generate_status_conditions(previous, &[sts_status], true, &[], Some(1));

        let old_time = Time(Timestamp::from_second(1_700_000_000).unwrap());
        for condition in &conditions {
            match condition.type_.as_str() {
                TYPE_AVAILABLE | TYPE_PROGRESSING => {
                    assert_ne!(condition.last_transition_time, old_time, "{condition:?}")
                }
                _ => assert_eq!(condition.last_transition_time, old_time, "{condition:?}"),
            }
        }
    }

    #[test]
    fn test_first_status_reports_progressing_without_observed_generation() {
        let sts_statuses: &[Option<StatefulSetStatus>] = &[];

        let conditions = generate_status_conditions(Vec::new(), sts_statuses, false, &[], Some(1));

        let progressing = progressing_condition(&conditions);
        assert_eq!(progressing.status, CONDITION_TRUE);
        assert_eq!(progressing.reason, "SpecChanged");
        assert_eq!(progressing.observed_generation, Some(1));
    }

    #[test]
    fn test_status_adopted_without_observed_generation_reports_progressing() {
        let sts_statuses: &[Option<StatefulSetStatus>] = &[];
        // Conditions written by an older operator carry no observed generation.
        let previous = vec![create_condition(TYPE_AVAILABLE, CONDITION_FALSE)];

        let conditions = generate_status_conditions(previous, sts_statuses, false, &[], Some(3));

        let progressing = progressing_condition(&conditions);
        assert_eq!(progressing.status, CONDITION_TRUE);
        assert_eq!(progressing.observed_generation, Some(3));
    }

    #[test]
    fn test_unconverged_kanidm_status_reports_progress_once_and_then_settles() {
        // A Kanidm that never converges (e.g. a StatefulSet that cannot be applied) has to report
        // two distinct statuses so observers can see that reconciliation was attempted, and then
        // keep producing an identical status to avoid reconciling in a loop.
        let sts_statuses: &[Option<StatefulSetStatus>] = &[];

        let first = generate_status_conditions(Vec::new(), sts_statuses, false, &[], Some(1));
        assert_eq!(progressing_condition(&first).status, CONDITION_TRUE);

        let second = generate_status_conditions(first, sts_statuses, false, &[], Some(1));
        let progressing = progressing_condition(&second);
        assert_eq!(progressing.status, CONDITION_FALSE);
        assert_eq!(progressing.reason, "NotProgressing");
        assert_eq!(progressing.observed_generation, Some(1));

        let third = generate_status_conditions(second.clone(), sts_statuses, false, &[], Some(1));
        assert_eq!(
            condition_values(third),
            condition_values(second),
            "an unchanged reconciliation must not change any condition"
        );
    }

    fn create_condition(type_: &str, status: &str) -> Condition {
        Condition {
            type_: type_.to_string(),
            status: status.to_string(),
            reason: "".to_string(),
            message: "".to_string(),
            last_transition_time: Time(Timestamp::now()),
            observed_generation: None,
        }
    }

    #[test]
    fn test_update_conditions_with_existing_status_type() {
        let previous_conditions = vec![
            create_condition(TYPE_AVAILABLE, CONDITION_TRUE),
            create_condition(TYPE_PROGRESSING, CONDITION_FALSE),
        ];
        let new_condition = create_condition(TYPE_AVAILABLE, CONDITION_FALSE);

        let updated_conditions = update_conditions(previous_conditions.clone(), &new_condition);

        assert_eq!(updated_conditions.len(), 2);
        assert!(
            updated_conditions
                .iter()
                .any(|c| c.type_ == TYPE_AVAILABLE && c.status == CONDITION_FALSE)
        );
        assert!(
            updated_conditions
                .iter()
                .any(|c| c.type_ == TYPE_PROGRESSING && c.status == CONDITION_FALSE)
        );
    }

    #[test]
    fn test_update_conditions_without_existing_status_type() {
        let previous_conditions = vec![create_condition(TYPE_PROGRESSING, CONDITION_FALSE)];
        let new_condition = create_condition(TYPE_AVAILABLE, CONDITION_TRUE);

        let updated_conditions = update_conditions(previous_conditions.clone(), &new_condition);

        assert_eq!(updated_conditions.len(), 2);
        assert!(
            updated_conditions
                .iter()
                .any(|c| c.type_ == TYPE_AVAILABLE && c.status == CONDITION_TRUE)
        );
        assert!(
            updated_conditions
                .iter()
                .any(|c| c.type_ == TYPE_PROGRESSING && c.status == CONDITION_FALSE)
        );
    }

    #[test]
    fn test_update_conditions_with_empty_previous_conditions() {
        let previous_conditions = vec![];
        let new_condition = create_condition(TYPE_AVAILABLE, CONDITION_TRUE);

        let updated_conditions = update_conditions(previous_conditions.clone(), &new_condition);

        assert_eq!(updated_conditions.len(), 1);
        assert!(
            updated_conditions
                .iter()
                .any(|c| c.type_ == TYPE_AVAILABLE && c.status == CONDITION_TRUE)
        );
    }
}