kaniop-operator 0.16.4

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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
use crate::crd::is_default;

use std::collections::{BTreeMap, BTreeSet};

use gateway_api::apis::standard::httproutes::HttpRouteRules;
use k8s_openapi::api::apps::v1::StatefulSetPersistentVolumeClaimRetentionPolicy;
use k8s_openapi::api::core::v1::{
    Affinity, Container, EmptyDirVolumeSource, EnvVar, EphemeralVolumeSource, HostAlias,
    PersistentVolumeClaim, PersistentVolumeClaimSpec, PodDNSConfig, PodSecurityContext,
    ResourceRequirements, SecretKeySelector, Toleration, TopologySpreadConstraint, Volume,
    VolumeMount,
};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, LabelSelector};
use kube::api::ObjectMeta;
use kube::CustomResource;
#[cfg(feature = "schemars")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Specification of the desired behavior of the Kanidm cluster. More info:
/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
// workaround: '`' character is not allowed in the kube `doc` attribute during doctests
#[cfg_attr(
    not(doctest),
    kube(
        doc = r#"The `Kanidm` custom resource definition (CRD) defines a desired [Kanidm](https://kanidm.com)
    setup to run in a Kubernetes cluster. It allows to specify many options such as the number of replicas,
    persistent storage, and many more.

    For each `Kanidm` resource, the Operator deploys one or several `StatefulSet` objects in the same namespace. The number of StatefulSets is equal to the number of replicas.
    "#
    )
)]
#[kube(
    category = "kaniop",
    group = "kaniop.rs",
    version = "v1beta1",
    kind = "Kanidm",
    plural = "kanidms",
    singular = "kanidm",
    shortname = "idm",
    namespaced,
    status = "KanidmStatus",
    printcolumn = r#"{"name":"Replicas","type":"string","description":"The number of replicas: ready/desired","jsonPath":".status.replicaColumn"}"#,
    printcolumn = r#"{"name":"Domain","type":"string","jsonPath":".spec.domain"}"#,
    printcolumn = r#"{"name":"Secret","type":"string","jsonPath":".status.secretName"}"#,
    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#,
    derive = "Default"
)]
#[serde(rename_all = "camelCase")]
pub struct KanidmSpec {
    /// The DNS domain name of the server. This is used in a number of security-critical
    /// contexts such as webauthn, so it *must* match your DNS hostname. It is used to
    /// create security principal names such as `william@idm.example.com` so that in a
    /// (future) trust configuration it is possible to have unique Security Principal
    /// Names (spns) throughout the topology.
    ///
    /// This cannot be changed after creation.
    #[schemars(extend("x-kubernetes-validations" = [
        {
            "message": "Domain cannot be changed.",
            "rule": "self == oldSelf"},
        {
            "message": "Domain must be a valid DNS name",
            "rule": "self.matches(r'^([a-z0-9]([-a-z0-9]*[a-z0-9])?\\.)*[a-z0-9]([-a-z0-9]*[a-z0-9])?$')"
        }
    ]))]
    pub domain: String,

    /// The origin for webauthn. This is the url to the server,
    /// with the port included if it is non-standard (any port
    /// except 443). This must match or be a descendent of the
    /// domain name you configure above. If these two items are
    /// not consistent, the server WILL refuse to start!
    /// origin = "https://idm.example.com"
    /// # OR
    /// origin = "https://idm.example.com:8443"
    ///
    /// Defaults to `https://<domain>` if not specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub origin: Option<String>,

    /// Different group of replicas with specific configuration as role, resources, affinity rules, and more.
    /// Each group will be deployed as a separate StatefulSet.
    #[schemars(extend("x-kubernetes-validations" = [{"message": "At least one ReplicaGroup is required", "rule": "self.size() > 0"}]))]
    // max is defined for allowing CEL expression in validation admission policy estimate
    // expression costs
    #[validate(length(min = 1, max = 100))]
    pub replica_groups: Vec<ReplicaGroup>,

    /// List of external replication nodes. This is used to configure replication between
    /// different Kanidm clusters.
    ///
    /// **WARNING**: `admin` and `idm_admin` passwords are going to be reset.
    // max is defined for allowing CEL expression in validation admission policy estimate
    // expression costs.
    #[validate(length(max = 100))]
    #[serde(default, skip_serializing_if = "is_default")]
    pub external_replication_nodes: Vec<ExternalReplicationNode>,

    /// Container image name. More info: https://kubernetes.io/docs/concepts/containers/images
    /// This field is optional to allow higher level config management to default or override
    /// container images in workload controllers like StatefulSets.
    #[serde(default = "default_image", skip_serializing_if = "is_default")]
    pub image: String,

    /// Before starting an upgrade, perform pre-upgrade checks to ensure that data can be
    /// safely migrated to the new version. If pre-checks fail, image change is disallowed.
    /// If set to true, upgrade pre-checks are skipped. Defaults to false.
    #[serde(default, skip_serializing_if = "is_default")]
    pub disable_upgrade_checks: bool,

    /// Log level for Kanidm.
    #[serde(default, skip_serializing_if = "is_default")]
    pub log_level: KanidmLogLevel,

    /// Port name used for the pods and governing service. Defaults to https.
    #[serde(default = "default_port_name", skip_serializing_if = "is_default")]
    pub port_name: String,

    /// Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag
    /// is specified, or IfNotPresent otherwise. Cannot be updated.
    /// More info: https://kubernetes.io/docs/concepts/containers/images#updating-images
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_pull_policy: Option<String>,

    /// List of environment variables to set in the `kanidm` container.
    /// This can be used to set Kanidm configuration options.
    /// More info: https://kanidm.github.io/kanidm/master/server_configuration.html
    #[serde(skip_serializing_if = "Option::is_none")]
    pub env: Option<Vec<EnvVar>>,

    /// Namespaces to match for KanidmOAuth2Clients discovery.
    ///
    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
    /// - Empty selector `{}`: matches all namespaces in the cluster
    /// - Selector with labels: matches namespaces with matching labels
    ///
    /// Example for all namespaces: `oauth2ClientNamespaceSelector: {}`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub oauth2_client_namespace_selector: Option<LabelSelector>,

    /// Namespaces to match for KanidmGroups discovery.
    ///
    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
    /// - Empty selector `{}`: matches all namespaces in the cluster
    /// - Selector with labels: matches namespaces with matching labels
    ///
    /// Example for all namespaces: `groupNamespaceSelector: {}`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group_namespace_selector: Option<LabelSelector>,

    /// Namespaces to match for KanidmPersonAccounts discovery.
    ///
    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
    /// - Empty selector `{}`: matches all namespaces in the cluster
    /// - Selector with labels: matches namespaces with matching labels
    ///
    /// Example for all namespaces: `personNamespaceSelector: {}`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub person_namespace_selector: Option<LabelSelector>,

    /// Namespaces to match for KanidmServiceAccounts discovery.
    ///
    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
    /// - Empty selector `{}`: matches all namespaces in the cluster
    /// - Selector with labels: matches namespaces with matching labels
    ///
    /// Example for all namespaces: `serviceAccountNamespaceSelector: {}`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_account_namespace_selector: Option<LabelSelector>,

    /// StorageSpec defines the configured storage for a group Kanidm servers.
    /// If no storage option is specified, then by default an
    /// [EmptyDir](https://kubernetes.io/docs/concepts/storage/volumes/#emptydir) will be used.
    ///
    /// If multiple storage options are specified, priority will be given as follows:
    ///  1. emptyDir
    ///  2. ephemeral
    ///  3. volumeClaimTemplate
    ///
    /// Note: Kaniop does not resize PVCs until Kubernetes fix
    /// [KEP-4650](https://github.com/kubernetes/enhancements/issues/4650).
    /// Changes to `volumeClaimTemplates` (e.g., PVC resize or StorageClass changes)
    /// are applied non-destructively; the operator does not delete/recreate the
    /// StatefulSet for PVC template modifications.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub storage: Option<KanidmStorage>,

    /// Defines the port name used for the LDAP service. If not defined, LDAP service will not be
    /// configured. Service port will be `3636`.
    ///
    /// StartTLS is not supported due to security risks such as credential leakage and MITM attacks
    /// that are fundamental in how StartTLS works. StartTLS can not be repaired to prevent this.
    /// LDAPS is the only secure method of communicating to any LDAP server. Kanidm will use its
    /// certificates for both HTTPS and LDAPS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ldap_port_name: Option<String>,

    /// Specifies the name of the secret holding the TLS private key and certificate for the server.
    /// If not provided, the ingress secret will be used. The server will not start if the secret
    /// is missing.
    #[schemars(extend("x-kubernetes-validations" = [
        {
            "message": "tlsSecretName must be a valid Kubernetes resource name.",
            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
        }
    ]))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tls_secret_name: Option<String>,

    /// Service defines the service configuration for the Kanidm server.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service: Option<KanidmService>,

    /// Ingress configuration for the Kanidm cluster.
    ///
    /// The domain specified in the Kanidm spec will be used as the ingress host.
    /// TLS is required and must be configured at the ingress controller level (termination or
    /// passthrough).
    /// When running multiple replicas, configure session affinity on your ingress controller to
    /// ensure proper session handling.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ingress: Option<KanidmIngress>,

    /// Region-specific ingress configuration for multi-region deployments.
    ///
    /// Allows defining ingress settings for a specific region, using a subdomain of the main
    /// Kanidm domain.
    /// TLS is required and must be configured at the ingress controller level (termination or
    /// passthrough).
    /// For multi-region deployments, configure session affinity on your ingress controller to ensure proper session handling.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region_ingress: Option<KanidmRegionIngress>,

    /// Gateway API configuration for the Kanidm cluster.
    ///
    /// Allows configuring an HTTPRoute for Gateway API-based ingress routing.
    /// The HTTPRoute will route traffic to the Kanidm service using the specified parentRefs
    /// to attach to Gateway(s).
    /// Both ingress and gateway can be configured simultaneously for migration scenarios.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gateway: Option<KanidmGateway>,

    /// Volumes allows the configuration of additional volumes on the output StatefulSet
    /// definition. Volumes specified will be appended to other volumes that are generated as a
    /// result of StorageSpec objects.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub volumes: Option<Vec<Volume>>,

    /// VolumeMounts allows the configuration of additional VolumeMounts.
    ///
    /// VolumeMounts will be appended to other VolumeMounts in the kanidm' container, that are
    /// generated as a result of StorageSpec objects.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub volume_mounts: Option<Vec<VolumeMount>>,

    /// The field controls if and how PVCs are deleted during the lifecycle of a StatefulSet.
    /// The default behavior is all PVCs are retained.
    /// This is a beta field from 1.27. It requires enabling the StatefulSetAutoDeletePVC feature
    /// gate.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub persistent_volume_claim_retention_policy:
        Option<StatefulSetPersistentVolumeClaimRetentionPolicy>,

    /// SecurityContext holds pod-level security attributes and common container settings.
    /// This defaults to the default PodSecurityContext.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub security_context: Option<PodSecurityContext>,

    /// Defines the DNS policy for the pods.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dns_policy: Option<String>,

    /// Defines the DNS configuration for the pods.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dns_config: Option<PodDNSConfig>,

    /// Containers allows injecting additional containers or modifying operator generated
    /// containers. This can be used to allow adding an authentication proxy to the Pods or to
    /// change the behavior of an operator generated container. Containers described here modify
    /// an operator generated container if they share the same name and modifications are done
    /// via a strategic merge patch.
    ///
    /// The name of container managed by the operator is: kanidm
    ///
    /// Overriding containers is entirely outside the scope of what the maintainers will support
    /// and by doing so, you accept that this behaviour may break at any time without notice.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub containers: Option<Vec<Container>>,

    /// InitContainers allows injecting initContainers to the Pod definition. Those can be used to
    /// e.g. fetch secrets for injection into the Kanidm configuration from external sources.
    /// Any errors during the execution of an initContainer will lead to a restart of the Pod.
    /// More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
    /// InitContainers described here modify an operator generated init containers if they share
    /// the same name and modifications are done via a strategic merge patch.
    ///
    /// The names of init container name managed by the operator are: * init-config-reloader.
    ///
    /// Overriding init containers is entirely outside the scope of what the maintainers will
    /// support and by doing so, you accept that this behaviour may break at any time without notice.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub init_containers: Option<Vec<Container>>,

    /// Minimum number of seconds for which a newly created Pod should be ready without any of its
    /// container crashing for it to be considered available. Defaults to 0 (pod will be considered
    /// available as soon as it is ready)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_ready_seconds: Option<i32>,

    /// Optional list of hosts and IPs that will be injected into the Pod's hosts file if specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub host_aliases: Option<Vec<HostAlias>>,

    /// Use the host's network namespace if true.
    ///
    /// Make sure to understand the security implications if you want to enable it
    /// (https://kubernetes.io/docs/concepts/configuration/overview/).
    ///
    /// When hostNetwork is enabled, this will set the DNS policy to ClusterFirstWithHostNet
    /// automatically.
    #[serde(default, skip_serializing_if = "is_default")]
    pub host_network: Option<bool>,

    /// IP family for bind addresses. Defaults to IPv4.
    ///
    /// - `ipv4`: Uses 0.0.0.0 for bind addresses (default)
    /// - `ipv6`: Uses [::] for bind addresses
    #[serde(default, skip_serializing_if = "is_default")]
    pub ip_family: IpFamily,

    /// RuntimeClassName refers to a RuntimeClass object in the node.k8s.io API group,
    /// which should be used to run the pods in this Kanidm cluster.
    /// If no RuntimeClass resource matches the named class, the pod will not be run.
    /// If unset or empty, the "legacy" RuntimeClass will be used, which is an implicit
    /// class with an empty definition that uses the default runtime handler.
    /// More info: https://kubernetes.io/docs/concepts/containers/runtime-class/
    #[serde(skip_serializing_if = "Option::is_none")]
    pub runtime_class_name: Option<String>,

    /// AutomountServiceAccountToken indicates whether a service account token should be automatically mounted.
    /// If not specified, defaults to true (the token is mounted).
    /// Setting this to false is recommended for security-sensitive applications.
    /// More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
    #[serde(skip_serializing_if = "Option::is_none")]
    pub automount_service_account_token: Option<bool>,

    /// EnableServiceLinks indicates whether information about services should be injected into pod's
    /// environment variables, matching the syntax of Docker links.
    /// Defaults to false for security reasons (prevents service environment variable injection).
    /// Set to true only if you need Kubernetes to inject service information as environment variables.
    /// More info: https://kubernetes.io/docs/concepts/services-networking/service/#environment-variables
    #[serde(default = "default_false", skip_serializing_if = "is_default")]
    pub enable_service_links: bool,

    /// HostUsers controls how the user namespace is configured for the pod.
    /// If set to true, the pod will use the host's user namespace.
    /// If set to false or not specified, the pod will use a user namespace configured by the runtime.
    /// This feature requires support in the container runtime and Kubernetes 1.27+.
    /// More info: https://kubernetes.io/docs/concepts/workloads/pods/user-namespaces/
    #[serde(skip_serializing_if = "Option::is_none")]
    pub host_users: Option<bool>,

    /// Domain appearance customization settings.
    /// Allows customizing the display name and site image (logo) shown on the Kanidm signin page.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain_appearance: Option<DomainAppearanceSpec>,

    /// Mail sender configuration for sending emails (password reset links, notifications).
    /// When enabled, the operator automatically creates a service account in Kanidm's
    /// `idm_message_senders` group, generates an API token, and deploys the `kanidm-mail-sender`
    /// component.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mail_sender: Option<MailSenderSpec>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct DomainAppearanceSpec {
    /// Display name shown when logged in. Defaults to "Kanidm <hostname>" if not specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,

    /// Optional site image (logo) for the signin page.
    /// Uses same pattern as OAuth2 client images.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<DomainAppearanceImageSpec>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct DomainAppearanceImageSpec {
    /// URL to fetch the image from (HTTP/HTTPS only).
    /// The operator will periodically check this URL for changes using HEAD requests
    /// and re-download the image when changes are detected.
    pub url: String,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct MailSenderSpec {
    /// SMTP relay URL for sending emails.
    /// Must be a valid SMTP URL: `smtp://hostname:port` or `smtps://hostname` (default port 465).
    /// Example: `smtps://smtp.example.com` or `smtp://smtp.example.com:587`
    pub relay: String,

    /// Kubernetes secret containing SMTP credentials (username and password).
    /// The secret must have keys for username and password (defaults to "username" and "password").
    pub credentials_secret: MailSenderCredentialsSecret,

    /// Email address used as the "From" address in sent emails.
    /// Example: `kanidm@example.com`
    pub from_address: String,

    /// Optional email address for the "Reply-To" header.
    /// Example: `admin@example.com`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reply_to_address: Option<String>,

    /// Optional queue polling interval in seconds.
    /// How often the mail sender checks Kanidm's message queue.
    /// Defaults to 5 seconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub queue_poll_interval_seconds: Option<i32>,

    /// Optional SMTP connection timeout in seconds.
    /// Defaults to 15 seconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connect_timeout_seconds: Option<i32>,

    /// Optional custom image for the mail sender deployment.
    /// Defaults to `kanidm/tools:<version>` matching the Kanidm server image version.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<String>,

    /// Optional resource requirements for the mail sender deployment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resources: Option<ResourceRequirements>,

    /// Optional node selector for the mail sender deployment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub node_selector: Option<BTreeMap<String, String>>,

    /// Optional affinity rules for the mail sender deployment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub affinity: Option<Affinity>,

    /// Optional tolerations for the mail sender deployment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tolerations: Option<Vec<Toleration>>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct MailSenderCredentialsSecret {
    /// Name of the Kubernetes secret containing SMTP credentials.
    pub name: String,

    /// Key in the secret containing the SMTP username.
    /// Defaults to "username".
    #[serde(default = "default_smtp_username_key", skip_serializing_if = "is_default")]
    pub username_key: String,

    /// Key in the secret containing the SMTP password.
    /// Defaults to "password".
    #[serde(default = "default_smtp_password_key", skip_serializing_if = "is_default")]
    pub password_key: String,
}

impl Default for MailSenderCredentialsSecret {
    fn default() -> Self {
        Self {
            name: String::new(),
            username_key: default_smtp_username_key(),
            password_key: default_smtp_password_key(),
        }
    }
}

fn default_smtp_username_key() -> String {
    "username".to_string()
}

fn default_smtp_password_key() -> String {
    "password".to_string()
}

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct ReplicaGroup {
    /// The name of the replica group.
    pub name: String,

    /// Number of replicas to deploy for a Kanidm replica group.
    pub replicas: i32,

    /// The Kanidm role of each node in the replica group.
    #[serde(default)]
    pub role: KanidmServerRole,

    /// If true, the first pod of the StatefulSet will be considered as the primary node.
    /// The rest of the nodes are considered as secondary nodes.
    /// This means that if database issues occur the content of the primary will take precedence
    /// over the rest of the nodes.
    /// This is only valid for the WriteReplica role and can only be set to true for one
    /// replica group or external replication node.
    /// Defaults to false.
    #[serde(default)]
    pub primary_node: bool,

    /// Service configuration for the replica group.
    /// - If not specified, pods use the default StatefulSet DNS for internal communication.
    /// - If specified, a Kubernetes Service of type LoadBalancer is created to expose replica
    ///   group pods externally.
    ///   This enables cross-cluster or multi-region access to replicas.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub services: Option<KanidmReplicaGroupServices>,

    /// Annotations to add to the StatefulSet created for this replica group.
    ///
    /// Each replica group gets its own StatefulSet; these annotations are applied only to the
    /// StatefulSet for this group.
    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stateful_set_annotations: Option<BTreeMap<String, String>>,

    /// Defines the resources requests and limits of the kanidm' container.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resources: Option<ResourceRequirements>,

    /// Defines on which Nodes the Pods are scheduled.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub node_selector: Option<BTreeMap<String, String>>,

    /// Defines the Pods' affinity scheduling rules if specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub affinity: Option<Affinity>,

    /// Defines the Pods' tolerations if specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tolerations: Option<Vec<Toleration>>,

    /// Defines the pod's topology spread constraints if specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub topology_spread_constraints: Option<Vec<TopologySpreadConstraint>>,
}

// re-implementation of kanidmd_core::config::ServerRole because it is not Serialize
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum KanidmServerRole {
    /// Full read-write replica with web UI
    #[default]
    WriteReplica,
    /// Read-write replica without the web UI
    WriteReplicaNoUi,
    /// Read-only replica for load balancing read operations.
    /// **WARNING**: read_only_replica is currently a placeholder and not yet implemented in Kanidm.
    /// Using this role may lead to divergent data across replicas. Kaniop uses it to configure the
    /// replication type to pull.
    ReadOnlyReplica,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmReplicaGroupServices {
    /// Annotations to apply to each Service for replica group pods.
    ///
    /// Available template variables:
    /// - `{replica_index}`: Index of the pod in the replica group
    /// - `{pod_name}`: Name of the pod
    /// - `{domain}`: Domain name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations_template: Option<BTreeMap<String, String>>,

    /// Hostname template for each Service created for replica group pods.
    ///
    /// Available template variables:
    /// - `{replica_index}`: Index of the pod in the replica group
    /// - `{pod_name}`: Name of the pod
    /// - `{domain}`: Domain name
    ///
    /// If not set, the replication hostname defaults to the Service's external IP.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub replication_hostname_template: Option<String>,

    /// Map of string keys and values that can be used to organize and categorize (scope and
    /// select) objects. May match selectors of replication controllers and services.
    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels
    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_labels: Option<BTreeMap<String, String>>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct ExternalReplicationNode {
    /// Name of the external replication node. This just have internal use.
    pub name: String,

    /// The hostname of the external replication node.
    pub hostname: String,

    /// The replication port of the external replication node.
    pub port: i32,

    /// Defines the secret that contains the identity certificate of the external replication node.
    pub certificate: SecretKeySelector,

    /// Defines the type of replication to use. Defaults to MutualPull.
    #[serde(default)]
    pub _type: ReplicationType,

    /// Select external replication node as the primary node. This means that if database conflicts
    /// occur the content of the primary will take precedence over the rest of the nodes.
    /// Note: just one external replication node or replication group can be selected as primary.
    /// Defaults to false.
    #[serde(default)]
    pub automatic_refresh: bool,
}

// re-implementation of kanidmd_core::repl::config::RepNodeConfig because it is not Serialize and
// attributes changed
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum ReplicationType {
    /// Both nodes can initiate replication with each other
    #[default]
    MutualPull,
    /// This node allows the external node to pull changes, but won't initiate
    AllowPull,
    /// This node will pull changes from the external node
    Pull,
}

fn default_image() -> String {
    "kanidm/server:latest".to_string()
}

// re-implementation of sketching::LogLevel because it is not Serialize
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum KanidmLogLevel {
    /// Most verbose logging level, includes all debug and info messages
    Trace,
    /// Debug level logging, useful for troubleshooting
    Debug,
    /// Standard informational logging level
    #[default]
    Info,
}

fn default_port_name() -> String {
    "https".to_string()
}

fn default_false() -> bool {
    false
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum IpFamily {
    #[default]
    Ipv4,
    Ipv6,
}

/// PersistentVolumeClaimTemplate defines a PVC template with optional metadata.
/// This allows users to specify a PVC template without requiring metadata to be explicitly set.
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct PersistentVolumeClaimTemplate {
    /// Standard object's metadata. More info:
    /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<ObjectMeta>,

    /// spec defines the desired characteristics of a volume requested by a pod author. More info:
    /// https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
    pub spec: Option<PersistentVolumeClaimSpec>,
}

impl PersistentVolumeClaimTemplate {
    /// Convert this template into a k8s-openapi PersistentVolumeClaim
    pub fn to_persistent_volume_claim(&self) -> PersistentVolumeClaim {
        PersistentVolumeClaim {
            metadata: self.metadata.clone().unwrap_or_default(),
            spec: self.spec.clone(),
            ..Default::default()
        }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmStorage {
    /// EmptyDirVolumeSource to be used by the StatefulSet. If specified, it takes precedence over
    /// `ephemeral` and `volumeClaimTemplate`.
    /// More info: https://kubernetes.io/docs/concepts/storage/volumes/#emptydir
    #[serde(skip_serializing_if = "Option::is_none")]
    pub empty_dir: Option<EmptyDirVolumeSource>,

    /// EphemeralVolumeSource to be used by the StatefulSet.
    /// More info: https://kubernetes.io/docs/concepts/storage/ephemeral-volumes/#generic-ephemeral-volumes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ephemeral: Option<EphemeralVolumeSource>,

    /// Defines the PVC spec to be used by the Kanidm StatefulSets. The easiest way to use a volume
    /// that cannot be automatically provisioned is to use a label selector alongside manually
    /// created PersistentVolumes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub volume_claim_template: Option<PersistentVolumeClaimTemplate>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmService {
    /// Annotations is an unstructured key value map stored with a resource that may be set by
    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
    /// be preserved when modifying objects.
    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<BTreeMap<String, String>>,

    /// Specify the Service's type where the Kanidm Service is exposed
    /// Please note that some Ingress controllers like https://github.com/kubernetes/ingress-gce
    /// forces you to expose your Service on a NodePort
    /// Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and
    /// LoadBalancer. "ClusterIP" allocates a cluster-internal IP address for load-balancing to
    /// endpoints. Endpoints are determined by the selector or if that is not specified, by manual
    /// construction of an Endpoints object or EndpointSlice objects. If clusterIP is "None",
    /// no virtual IP is allocated and the endpoints are published as a set of endpoints rather
    /// than a virtual IP. "NodePort" builds on ClusterIP and allocates a port on every node which
    /// routes to the same endpoints as the clusterIP. "LoadBalancer" builds on NodePort and creates
    /// an external load-balancer (if supported in the current cloud) which routes to the same
    /// endpoints as the clusterIP. "ExternalName" aliases this service to the specified
    /// externalName. Several other fields do not apply to ExternalName services.
    /// More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
    #[serde(skip_serializing_if = "Option::is_none")]
    pub type_: Option<String>,

    /// Map of string keys and values that can be used to organize and categorize (scope and
    /// select) objects. May match selectors of replication controllers and services.
    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels
    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_labels: Option<BTreeMap<String, String>>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmIngress {
    /// Annotations is an unstructured key value map stored with a resource that may be set by
    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
    /// be preserved when modifying objects.
    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<BTreeMap<String, String>>,

    /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
    /// implementations use this field to know whether they should be serving this Ingress resource,
    /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
    /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
    /// it was widely supported by Ingress controllers to create a direct binding between Ingress
    /// controller and Ingress resources. Newly created Ingress resources should prefer using the
    /// field. However, even though the annotation is officially deprecated, for backwards
    /// compatibility reasons, ingress controllers should still honor that annotation if present.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ingress_class_name: Option<String>,
    /// Defines the name of the secret that contains the TLS private key and certificate for the
    /// server. If not defined, the default will be the Kanidm name appended with `-tls`.
    #[schemars(extend("x-kubernetes-validations" = [
        {
            "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
        }
    ]))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tls_secret_name: Option<String>,
    /// Additional Subject Alternative Names (SANs) to include in the TLS certificate.
    /// The main domain from the Kanidm spec is automatically included.
    /// This does not add additional hosts to the ingress resource, only certificate SANs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extra_tls_hosts: Option<BTreeSet<String>>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmRegionIngress {
    /// Region identifier for this ingress. Used as a subdomain of the main Kanidm domain to route
    /// traffic for a specific region.
    pub region: String,

    /// Annotations is an unstructured key value map stored with a resource that may be set by
    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
    /// be preserved when modifying objects.
    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<BTreeMap<String, String>>,

    /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
    /// implementations use this field to know whether they should be serving this Ingress resource,
    /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
    /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
    /// it was widely supported by Ingress controllers to create a direct binding between Ingress
    /// controller and Ingress resources. Newly created Ingress resources should prefer using the
    /// field. However, even though the annotation is officially deprecated, for backwards
    /// compatibility reasons, ingress controllers should still honor that annotation if present.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ingress_class_name: Option<String>,
    /// Defines the name of the secret that contains the TLS private key and certificate for the
    /// server. If not defined, the default will be the Kanidm name appended with `-region-tls`.
    #[schemars(extend("x-kubernetes-validations" = [
        {
            "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
        }
    ]))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tls_secret_name: Option<String>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmGatewayParentRef {
    /// Group is the group of the referent.
    /// When unspecified, defaults to "gateway.networking.k8s.io".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,

    /// Kind is the kind of the referent.
    /// When unspecified, defaults to "Gateway".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,

    /// Name of the referent.
    pub name: String,

    /// Namespace of the referent. When unspecified, this refers to the local namespace.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub namespace: Option<String>,

    /// SectionName is the name of a section within the target resource.
    /// When specified, this must refer to a named section within the target resource,
    /// such as a specific listener on a Gateway.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub section_name: Option<String>,

    /// Port is the network port this Route targets.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub port: Option<u32>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmGateway {
    /// ParentRefs references the Gateway(s) that this HTTPRoute should be attached to.
    /// Each ParentRef must reference a Gateway in the same namespace as the HTTPRoute.
    #[schemars(extend("x-kubernetes-validations" = [{"message": "At least one ParentRef is required", "rule": "self.size() > 0"}]))]
    #[validate(length(min = 1))]
    pub parent_refs: Vec<KanidmGatewayParentRef>,

    /// Hostnames defines a set of hostnames that should match against the HTTP Host
    /// header to select a HTTPRoute used to process the request.
    /// When unspecified, defaults to the Kanidm domain (spec.domain).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hostnames: Option<Vec<String>>,

    /// Annotations is an unstructured key value map stored with a resource that may be set by
    /// external tools to store and retrieve arbitrary metadata.
    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<BTreeMap<String, String>>,

    /// Rules defines a list of HTTPRoute rules.
    /// Each rule consists of conditions for matching an HTTP request,
    /// filters for processing it, and backend references for forwarding the request.
    /// When unspecified, a default rule is created that routes all traffic to the Kanidm service.
    /// This field allows customization of routing behavior, including session persistence,
    /// timeouts, filters, and advanced matching conditions.
    /// Note: The sessionPersistence field in rules is experimental and requires
    /// Gateway API experimental channel support from the implementation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rules: Option<Vec<HttpRouteRules>>,

    /// BackendTLSPolicy configuration for TLS validation between the Gateway and Kanidm backend service.
    /// When specified, creates a BackendTLSPolicy resource to validate TLS connections from the Gateway
    /// to the Kanidm service (port 8443). This is required when using TLS between Gateway and backend.
    /// When unspecified, no BackendTLSPolicy is created.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backend_tls_policy: Option<KanidmBackendTLSPolicy>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmBackendTLSPolicy {
    /// Annotations is an unstructured key value map stored with a resource that may be set by
    /// external tools to store and retrieve arbitrary metadata.
    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<BTreeMap<String, String>>,

    /// Validation contains backend TLS validation configuration.
    pub validation: KanidmBackendTLSPolicyValidation,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmBackendTLSPolicyValidation {
    /// Hostname is the hostname used for TLS validation.
    /// When unspecified, defaults to the Kanidm domain (spec.domain).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hostname: Option<String>,

    /// WellKnownCACertificates specifies the type of CA certificates to use for validation.
    /// When specified as "System", uses the system's trusted CA certificates.
    /// This is the most common option for public certificates (e.g., Let's Encrypt).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub well_known_ca_certificates: Option<String>,

    /// CACertificateRefs references CA certificates for validation.
    /// When specified, these certificates are used to validate the backend TLS connection.
    /// Useful for private/internal certificates not in the system trust store.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ca_certificate_refs: Option<Vec<KanidmBackendTLSPolicyValidationCACertificateRef>>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmBackendTLSPolicyValidationCACertificateRef {
    /// Group is the group of the referent.
    /// When unspecified, defaults to "" (core API group).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,

    /// Kind is the kind of the referent.
    /// When unspecified, defaults to "Secret".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,

    /// Name of the referent (the Secret containing the CA certificate).
    pub name: String,
}

/// Most recent observed status of the Kanidm cluster. Read-only.
/// More info:
/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmStatus {
    /// Total number of available pods (ready for at least minReadySeconds) targeted by this Kanidm
    /// deployment.
    pub available_replicas: i32,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "schemars",
        schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
    )]
    pub conditions: Option<Vec<Condition>>,

    /// Total number of non-terminated pods targeted by this Kanidm cluster.
    pub replicas: i32,

    /// Total number of unavailable pods targeted by this Kanidm cluster.
    pub unavailable_replicas: i32,

    /// Total number of non-terminated pods targeted by this Kanidm cluster that have the
    /// desired version spec.
    pub updated_replicas: i32,

    /// Status per replica in the Kanidm cluster.
    pub replica_statuses: Vec<KanidmReplicaStatus>,

    /// Ready vs desired replicas.
    pub replica_column: String,

    /// Admin users secret name.
    pub secret_name: Option<String>,

    /// The current version of the Kanidm server.
    pub version: Option<KanidmVersionStatus>,

    /// Status of the domain appearance image.
    pub domain_appearance_image: Option<DomainAppearanceImageStatus>,

    /// Status of the mail sender deployment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mail_sender: Option<MailSenderStatus>,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct MailSenderStatus {
    /// Name of the service account in Kanidm for mail sending.
    /// Format: `<kanidm-name>-mail-sender`
    pub service_account_name: String,

    /// Name of the Kubernetes secret containing the API token.
    /// Format: `<kanidm-name>-mail-sender-token`
    pub token_secret_name: String,

    /// Name of the Deployment running the mail sender.
    /// Format: `<kanidm-name>-mail-sender`
    pub deployment_name: String,

    /// Name of the ConfigMap containing mail sender configuration.
    /// Format: `<kanidm-name>-mail-sender-config`
    pub config_map_name: String,

    /// The unique identifier for the API token in Kanidm, used for management operations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token_id: Option<String>,

    /// Whether the mail sender deployment is ready.
    pub ready: bool,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmReplicaStatus {
    /// Pod name: replica group StatefulSet name plus the pod index.
    pub pod_name: String,

    /// StatefulSet name: Kanidm name plus the replica group name.
    pub statefulset_name: String,

    /// The current state of the replica.
    pub state: KanidmReplicaState,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum KanidmReplicaState {
    Ready,
    Pending,
    CertificateExpiring,
    CertificateHostInvalid,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct KanidmVersionStatus {
    pub image_tag: String,

    pub upgrade_check_result: KanidmUpgradeCheckResult,

    #[serde(default)]
    pub compatibility_result: VersionCompatibilityResult,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Debug, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum VersionCompatibilityResult {
    #[default]
    Compatible,
    Incompatible,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum KanidmUpgradeCheckResult {
    Passed,
    Failed,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct DomainAppearanceImageStatus {
    /// The URL from which the image was last fetched.
    pub url: String,
    /// ETag header from the last fetch (for change detection).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub etag: Option<String>,
    /// Last-Modified header from the last fetch.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_modified: Option<String>,
    /// Content-Length from the last fetch.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_length: Option<u64>,
    /// Hash of the image content (SHA-256, for validation).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_hash: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use k8s_openapi::api::core::v1::PersistentVolumeClaimSpec;
    use serde_json::json;

    #[test]
    fn test_pvc_template_optional_metadata() {
        // Test that we can create a PVC template without metadata
        let pvc_template = PersistentVolumeClaimTemplate {
            metadata: None,
            spec: Some(PersistentVolumeClaimSpec::default()),
        };

        // Test that it can be converted to a k8s PVC
        let k8s_pvc = pvc_template.to_persistent_volume_claim();
        assert_eq!(k8s_pvc.metadata, ObjectMeta::default());
        assert_eq!(k8s_pvc.spec, pvc_template.spec);
    }

    #[test]
    fn test_pvc_template_with_metadata() {
        let custom_metadata = ObjectMeta {
            name: Some("test-pvc".to_string()),
            labels: Some([("app".to_string(), "test".to_string())].into()),
            ..ObjectMeta::default()
        };

        // Test that we can create a PVC template with metadata
        let pvc_template = PersistentVolumeClaimTemplate {
            metadata: Some(custom_metadata.clone()),
            spec: Some(PersistentVolumeClaimSpec::default()),
        };

        // Test that it can be converted to a k8s PVC
        let k8s_pvc = pvc_template.to_persistent_volume_claim();
        assert_eq!(k8s_pvc.metadata, custom_metadata);
        assert_eq!(k8s_pvc.spec, pvc_template.spec);
    }

    #[test]
    fn test_kanidm_version_status_backward_compatible() {
        let legacy_payload = json!({
            "imageTag": "1.9.0",
            "upgradeCheckResult": "passed"
        });

        let status: KanidmVersionStatus =
            serde_json::from_value(legacy_payload).expect("legacy status should deserialize");

        assert_eq!(status.image_tag, "1.9.0");
        assert_eq!(
            status.upgrade_check_result,
            KanidmUpgradeCheckResult::Passed
        );
        assert_eq!(
            status.compatibility_result,
            VersionCompatibilityResult::Compatible
        );
    }
}