kaniop_operator/kanidm/
crd.rs

1use crate::crd::is_default;
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use k8s_openapi::api::apps::v1::StatefulSetPersistentVolumeClaimRetentionPolicy;
6use k8s_openapi::api::core::v1::{
7    Affinity, Container, EmptyDirVolumeSource, EnvVar, EphemeralVolumeSource, HostAlias,
8    PersistentVolumeClaim, PersistentVolumeClaimSpec, PodDNSConfig, PodSecurityContext,
9    ResourceRequirements, SecretKeySelector, Toleration, TopologySpreadConstraint, Volume,
10    VolumeMount,
11};
12use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, LabelSelector};
13use kube::CustomResource;
14use kube::api::ObjectMeta;
15#[cfg(feature = "schemars")]
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18
19/// Specification of the desired behavior of the Kanidm cluster. More info:
20/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
21#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, Default)]
22#[cfg_attr(feature = "schemars", derive(JsonSchema))]
23// workaround: '`' character is not allowed in the kube `doc` attribute during doctests
24#[cfg_attr(
25    not(doctest),
26    kube(
27        doc = r#"The `Kanidm` custom resource definition (CRD) defines a desired [Kanidm](https://kanidm.com)
28    setup to run in a Kubernetes cluster. It allows to specify many options such as the number of replicas,
29    persistent storage, and many more.
30
31    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.
32    "#
33    )
34)]
35#[kube(
36    category = "kaniop",
37    group = "kaniop.rs",
38    version = "v1beta1",
39    kind = "Kanidm",
40    plural = "kanidms",
41    singular = "kanidm",
42    shortname = "idm",
43    namespaced,
44    status = "KanidmStatus",
45    printcolumn = r#"{"name":"Replicas","type":"string","description":"The number of replicas: ready/desired","jsonPath":".status.replicaColumn"}"#,
46    printcolumn = r#"{"name":"Domain","type":"string","jsonPath":".spec.domain"}"#,
47    printcolumn = r#"{"name":"Secret","type":"string","jsonPath":".status.secretName"}"#,
48    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#,
49    derive = "Default"
50)]
51#[serde(rename_all = "camelCase")]
52pub struct KanidmSpec {
53    /// The DNS domain name of the server. This is used in a number of security-critical
54    /// contexts such as webauthn, so it *must* match your DNS hostname. It is used to
55    /// create security principal names such as `william@idm.example.com` so that in a
56    /// (future) trust configuration it is possible to have unique Security Principal
57    /// Names (spns) throughout the topology.
58    ///
59    /// This cannot be changed after creation.
60    #[schemars(extend("x-kubernetes-validations" = [{"message": "Domain cannot be changed.", "rule": "self == oldSelf"}]))]
61    #[schemars(regex(
62        pattern = r"^([a-z0-9]([-a-z0-9]*[a-z0-9])?\.)*[a-z0-9]([-a-z0-9]*[a-z0-9])?$"
63    ))]
64    pub domain: String,
65
66    /// The origin for webauthn. This is the url to the server,
67    /// with the port included if it is non-standard (any port
68    /// except 443). This must match or be a descendent of the
69    /// domain name you configure above. If these two items are
70    /// not consistent, the server WILL refuse to start!
71    /// origin = "https://idm.example.com"
72    /// # OR
73    /// origin = "https://idm.example.com:8443"
74    ///
75    /// Defaults to `https://<domain>` if not specified.
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub origin: Option<String>,
78
79    /// Different group of replicas with specific configuration as role, resources, affinity rules, and more.
80    /// Each group will be deployed as a separate StatefulSet.
81    #[schemars(extend("x-kubernetes-validations" = [{"message": "At least one ReplicaGroup is required", "rule": "self.size() > 0"}]))]
82    // max is defined for allowing CEL expression in validation admission policy estimate
83    // expression costs
84    #[validate(length(min = 1, max = 100))]
85    pub replica_groups: Vec<ReplicaGroup>,
86
87    /// List of external replication nodes. This is used to configure replication between
88    /// different Kanidm clusters.
89    ///
90    /// **WARNING**: `admin` and `idm_admin` passwords are going to be reset.
91    // max is defined for allowing CEL expression in validation admission policy estimate
92    // expression costs
93    #[validate(length(max = 100))]
94    #[serde(default, skip_serializing_if = "is_default")]
95    pub external_replication_nodes: Vec<ExternalReplicationNode>,
96
97    /// Container image name. More info: https://kubernetes.io/docs/concepts/containers/images
98    /// This field is optional to allow higher level config management to default or override
99    /// container images in workload controllers like StatefulSets.
100    #[serde(default = "default_image", skip_serializing_if = "is_default")]
101    pub image: String,
102
103    /// Log level for Kanidm.
104    #[serde(default, skip_serializing_if = "is_default")]
105    pub log_level: KanidmLogLevel,
106
107    /// Port name used for the pods and governing service. Default: "https"
108    #[serde(default = "default_port_name", skip_serializing_if = "is_default")]
109    pub port_name: String,
110
111    /// Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag
112    /// is specified, or IfNotPresent otherwise. Cannot be updated.
113    /// More info: https://kubernetes.io/docs/concepts/containers/images#updating-images
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub image_pull_policy: Option<String>,
116
117    /// List of environment variables to set in the `kanidm` container.
118    /// This can be used to set Kanidm configuration options.
119    /// More info: https://kanidm.github.io/kanidm/master/server_configuration.html
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub env: Option<Vec<EnvVar>>,
122
123    /// Namespaces to match for KanidmOAuth2Clients discovery.
124    ///
125    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
126    /// - Empty selector `{}`: matches all namespaces in the cluster
127    /// - Selector with labels: matches namespaces with matching labels
128    ///
129    /// Example for all namespaces: `oauth2ClientNamespaceSelector: {}`
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub oauth2_client_namespace_selector: Option<LabelSelector>,
132
133    /// Namespaces to match for KanidmGroups discovery.
134    ///
135    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
136    /// - Empty selector `{}`: matches all namespaces in the cluster
137    /// - Selector with labels: matches namespaces with matching labels
138    ///
139    /// Example for all namespaces: `groupNamespaceSelector: {}`
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub group_namespace_selector: Option<LabelSelector>,
142
143    /// Namespaces to match for KanidmPersonAccounts discovery.
144    ///
145    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
146    /// - Empty selector `{}`: matches all namespaces in the cluster
147    /// - Selector with labels: matches namespaces with matching labels
148    ///
149    /// Example for all namespaces: `personNamespaceSelector: {}`
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub person_namespace_selector: Option<LabelSelector>,
152
153    /// StorageSpec defines the configured storage for a group Kanidm servers.
154    /// If no storage option is specified, then by default an
155    /// [EmptyDir](https://kubernetes.io/docs/concepts/storage/volumes/#emptydir) will be used.
156    ///
157    /// If multiple storage options are specified, priority will be given as follows:
158    ///  1. emptyDir
159    ///  2. ephemeral
160    ///  3. volumeClaimTemplate
161    ///
162    /// Note: Kaniop does not resize PVCs until Kubernetes fix
163    /// [KEP-4650](https://github.com/kubernetes/enhancements/pull/4651).
164    /// Although, StatefulSet will be recreated if the PVC is resized.
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub storage: Option<KanidmStorage>,
167
168    /// Defines the port name used for the LDAP service. If not defined, LDAP service will not be
169    /// configured. Service port will be `3636`.
170    ///
171    /// StartTLS is not supported due to security risks such as credential leakage and MITM attacks
172    /// that are fundamental in how StartTLS works. StartTLS can not be repaired to prevent this.
173    /// LDAPS is the only secure method of communicating to any LDAP server. Kanidm will use its
174    /// certificates for both HTTPS and LDAPS.
175    #[serde(skip_serializing_if = "Option::is_none")]
176    pub ldap_port_name: Option<String>,
177
178    /// Specifies the name of the secret holding the TLS private key and certificate for the server.
179    /// If not provided, the ingress secret will be used. The server will not start if the secret
180    /// is missing.
181    #[serde(skip_serializing_if = "Option::is_none")]
182    pub tls_secret_name: Option<String>,
183
184    /// Service defines the service configuration for the Kanidm server.
185    #[serde(skip_serializing_if = "Option::is_none")]
186    pub service: Option<KanidmService>,
187
188    /// Ingress configuration for the Kanidm cluster.
189    ///
190    /// The domain specified in the Kanidm spec will be used as the ingress host.
191    /// TLS is required and must be configured either as termination or passthrough at the ingress
192    /// controller level.
193    /// When running multiple replicas, configure session affinity on your ingress controller to
194    /// ensure proper session handling.
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub ingress: Option<KanidmIngress>,
197
198    /// Volumes allows the configuration of additional volumes on the output StatefulSet
199    /// definition. Volumes specified will be appended to other volumes that are generated as a
200    /// result of StorageSpec objects.
201    #[serde(skip_serializing_if = "Option::is_none")]
202    pub volumes: Option<Vec<Volume>>,
203
204    /// VolumeMounts allows the configuration of additional VolumeMounts.
205    ///
206    /// VolumeMounts will be appended to other VolumeMounts in the kanidm’ container, that are
207    /// generated as a result of StorageSpec objects.
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub volume_mounts: Option<Vec<VolumeMount>>,
210
211    /// The field controls if and how PVCs are deleted during the lifecycle of a StatefulSet.
212    /// The default behavior is all PVCs are retained.
213    /// This is a beta field from 1.27. It requires enabling the StatefulSetAutoDeletePVC feature
214    /// gate.
215    #[serde(skip_serializing_if = "Option::is_none")]
216    pub persistent_volume_claim_retention_policy:
217        Option<StatefulSetPersistentVolumeClaimRetentionPolicy>,
218
219    /// SecurityContext holds pod-level security attributes and common container settings.
220    /// This defaults to the default PodSecurityContext.
221    #[serde(skip_serializing_if = "Option::is_none")]
222    pub security_context: Option<PodSecurityContext>,
223
224    /// Defines the DNS policy for the pods.
225    #[serde(skip_serializing_if = "Option::is_none")]
226    pub dns_policy: Option<String>,
227
228    /// Defines the DNS configuration for the pods.
229    #[serde(skip_serializing_if = "Option::is_none")]
230    pub dns_config: Option<PodDNSConfig>,
231
232    /// Containers allows injecting additional containers or modifying operator generated
233    /// containers. This can be used to allow adding an authentication proxy to the Pods or to
234    /// change the behavior of an operator generated container. Containers described here modify
235    /// an operator generated container if they share the same name and modifications are done
236    /// via a strategic merge patch.
237    ///
238    /// The name of container managed by the operator is: kanidm
239    ///
240    /// Overriding containers is entirely outside the scope of what the maintainers will support
241    /// and by doing so, you accept that this behaviour may break at any time without notice.
242    #[serde(skip_serializing_if = "Option::is_none")]
243    pub containers: Option<Vec<Container>>,
244
245    /// InitContainers allows injecting initContainers to the Pod definition. Those can be used to
246    /// e.g. fetch secrets for injection into the Kanidm configuration from external sources.
247    /// Any errors during the execution of an initContainer will lead to a restart of the Pod.
248    /// More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
249    /// InitContainers described here modify an operator generated init containers if they share
250    /// the same name and modifications are done via a strategic merge patch.
251    ///
252    /// The names of init container name managed by the operator are: * init-config-reloader.
253    ///
254    /// Overriding init containers is entirely outside the scope of what the maintainers will
255    /// support and by doing so, you accept that this behaviour may break at any time without notice.
256    #[serde(skip_serializing_if = "Option::is_none")]
257    pub init_containers: Option<Vec<Container>>,
258
259    /// Minimum number of seconds for which a newly created Pod should be ready without any of its
260    /// container crashing for it to be considered available. Defaults to 0 (pod will be considered
261    /// available as soon as it is ready)
262    #[serde(skip_serializing_if = "Option::is_none")]
263    pub min_ready_seconds: Option<i32>,
264
265    /// Optional list of hosts and IPs that will be injected into the Pod’s hosts file if specified.
266    #[serde(skip_serializing_if = "Option::is_none")]
267    pub host_aliases: Option<Vec<HostAlias>>,
268
269    /// Use the host’s network namespace if true.
270    ///
271    /// Make sure to understand the security implications if you want to enable it
272    /// (https://kubernetes.io/docs/concepts/configuration/overview/).
273    ///
274    /// When hostNetwork is enabled, this will set the DNS policy to ClusterFirstWithHostNet
275    /// automatically.
276    #[serde(skip_serializing_if = "Option::is_none")]
277    pub host_network: Option<bool>,
278}
279
280#[derive(Serialize, Deserialize, Clone, Debug, Default)]
281#[cfg_attr(feature = "schemars", derive(JsonSchema))]
282#[serde(rename_all = "camelCase")]
283pub struct ReplicaGroup {
284    /// The name of the replica group.
285    pub name: String,
286
287    /// Number of replicas to deploy for a Kanidm replica group.
288    pub replicas: i32,
289
290    /// The Kanidm role of each node in the replica group.
291    #[serde(default)]
292    pub role: KanidmServerRole,
293
294    /// If true, the first pod of the StatefulSet will be considered as the primary node.
295    /// The rest of the nodes are considered as secondary nodes.
296    /// This means that if database issues occur the content of the primary will take precedence
297    /// over the rest of the nodes.
298    /// This is only valid for the WriteReplica role and can only be set to true for one
299    /// replica group or external replication node.
300    /// Defaults to false.
301    #[serde(default)]
302    pub primary_node: bool,
303
304    /// Defines the resources requests and limits of the kanidm’ container.
305    #[serde(skip_serializing_if = "Option::is_none")]
306    pub resources: Option<ResourceRequirements>,
307
308    /// Defines on which Nodes the Pods are scheduled.
309    #[serde(skip_serializing_if = "Option::is_none")]
310    pub node_selector: Option<BTreeMap<String, String>>,
311
312    /// Defines the Pods’ affinity scheduling rules if specified.
313    #[serde(skip_serializing_if = "Option::is_none")]
314    pub affinity: Option<Affinity>,
315
316    /// Defines the Pods’ tolerations if specified.
317    #[serde(skip_serializing_if = "Option::is_none")]
318    pub tolerations: Option<Vec<Toleration>>,
319
320    /// Defines the pod’s topology spread constraints if specified.
321    #[serde(skip_serializing_if = "Option::is_none")]
322    pub topology_spread_constraints: Option<Vec<TopologySpreadConstraint>>,
323}
324
325// re-implementation of kanidmd_core::config::ServerRole because it is not Serialize
326#[derive(Serialize, Deserialize, Clone, Debug, Default)]
327#[cfg_attr(feature = "schemars", derive(JsonSchema))]
328#[serde(rename_all = "snake_case")]
329pub enum KanidmServerRole {
330    /// Full read-write replica with web UI
331    #[default]
332    WriteReplica,
333    /// Read-write replica without the web UI
334    WriteReplicaNoUI,
335    /// Read-only replica for load balancing read operations
336    ReadOnlyReplica,
337}
338
339#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
340#[cfg_attr(feature = "schemars", derive(JsonSchema))]
341#[serde(rename_all = "camelCase")]
342pub struct ExternalReplicationNode {
343    /// Name of the external replication node. This just have internal use.
344    pub name: String,
345
346    /// The hostname of the external replication node.
347    pub hostname: String,
348
349    /// The replication port of the external replication node.
350    pub port: i32,
351
352    /// Defines the secret that contains the identity certificate of the external replication node.
353    pub certificate: SecretKeySelector,
354
355    /// Defines the type of replication to use. Defaults to MutualPull.
356    #[serde(default)]
357    pub _type: ReplicationType,
358
359    /// Select external replication node as the primary node. This means that if database conflicts
360    /// occur the content of the primary will take precedence over the rest of the nodes.
361    /// Note: just one external replication node or replication group can be selected as primary.
362    /// Defaults to false.
363    #[serde(default)]
364    pub automatic_refresh: bool,
365}
366
367// re-implementation of kanidmd_core::repl::config::RepNodeConfig because it is not Serialize and
368// attributes changed
369#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
370#[cfg_attr(feature = "schemars", derive(JsonSchema))]
371#[serde(rename_all = "kebab-case")]
372pub enum ReplicationType {
373    /// Both nodes can initiate replication with each other
374    #[default]
375    MutualPull,
376    /// This node allows the external node to pull changes, but won't initiate
377    AllowPull,
378    /// This node will pull changes from the external node
379    Pull,
380}
381
382fn default_image() -> String {
383    "kanidm/server:latest".to_string()
384}
385
386// re-implementation of sketching::LogLevel because it is not Serialize
387#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
388#[cfg_attr(feature = "schemars", derive(JsonSchema))]
389#[serde(rename_all = "snake_case")]
390pub enum KanidmLogLevel {
391    /// Most verbose logging level, includes all debug and info messages
392    Trace,
393    /// Debug level logging, useful for troubleshooting
394    Debug,
395    /// Standard informational logging level
396    #[default]
397    Info,
398}
399
400fn default_port_name() -> String {
401    "https".to_string()
402}
403
404/// PersistentVolumeClaimTemplate defines a PVC template with optional metadata.
405/// This allows users to specify a PVC template without requiring metadata to be explicitly set.
406#[derive(Serialize, Deserialize, Clone, Debug, Default)]
407#[cfg_attr(feature = "schemars", derive(JsonSchema))]
408#[serde(rename_all = "camelCase")]
409pub struct PersistentVolumeClaimTemplate {
410    /// Standard object's metadata. More info:
411    /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
412    #[serde(skip_serializing_if = "Option::is_none")]
413    pub metadata: Option<ObjectMeta>,
414
415    /// spec defines the desired characteristics of a volume requested by a pod author. More info:
416    /// https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
417    pub spec: Option<PersistentVolumeClaimSpec>,
418}
419
420impl PersistentVolumeClaimTemplate {
421    /// Convert this template into a k8s-openapi PersistentVolumeClaim
422    pub fn to_persistent_volume_claim(&self) -> PersistentVolumeClaim {
423        PersistentVolumeClaim {
424            metadata: self.metadata.clone().unwrap_or_default(),
425            spec: self.spec.clone(),
426            ..Default::default()
427        }
428    }
429}
430
431#[derive(Serialize, Deserialize, Clone, Debug, Default)]
432#[cfg_attr(feature = "schemars", derive(JsonSchema))]
433#[serde(rename_all = "camelCase")]
434pub struct KanidmStorage {
435    /// EmptyDirVolumeSource to be used by the StatefulSet. If specified, it takes precedence over
436    /// `ephemeral` and `volumeClaimTemplate`.
437    /// More info: https://kubernetes.io/docs/concepts/storage/volumes/#emptydir
438    #[serde(skip_serializing_if = "Option::is_none")]
439    pub empty_dir: Option<EmptyDirVolumeSource>,
440
441    /// EphemeralVolumeSource to be used by the StatefulSet.
442    /// More info: https://kubernetes.io/docs/concepts/storage/ephemeral-volumes/#generic-ephemeral-volumes
443    #[serde(skip_serializing_if = "Option::is_none")]
444    pub ephemeral: Option<EphemeralVolumeSource>,
445
446    /// Defines the PVC spec to be used by the Kanidm StatefulSets. The easiest way to use a volume
447    /// that cannot be automatically provisioned is to use a label selector alongside manually
448    /// created PersistentVolumes.
449    #[serde(skip_serializing_if = "Option::is_none")]
450    pub volume_claim_template: Option<PersistentVolumeClaimTemplate>,
451}
452
453#[derive(Serialize, Deserialize, Clone, Debug, Default)]
454#[cfg_attr(feature = "schemars", derive(JsonSchema))]
455#[serde(rename_all = "camelCase")]
456pub struct KanidmService {
457    /// Annotations is an unstructured key value map stored with a resource that may be set by
458    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
459    /// be preserved when modifying objects.
460    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
461    #[serde(skip_serializing_if = "Option::is_none")]
462    pub annotations: Option<BTreeMap<String, String>>,
463
464    /// Specify the Service's type where the Kanidm Service is exposed
465    /// Please note that some Ingress controllers like https://github.com/kubernetes/ingress-gce
466    /// forces you to expose your Service on a NodePort
467    /// Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and
468    /// LoadBalancer. "ClusterIP" allocates a cluster-internal IP address for load-balancing to
469    /// endpoints. Endpoints are determined by the selector or if that is not specified, by manual
470    /// construction of an Endpoints object or EndpointSlice objects. If clusterIP is "None",
471    /// no virtual IP is allocated and the endpoints are published as a set of endpoints rather
472    /// than a virtual IP. "NodePort" builds on ClusterIP and allocates a port on every node which
473    /// routes to the same endpoints as the clusterIP. "LoadBalancer" builds on NodePort and creates
474    /// an external load-balancer (if supported in the current cloud) which routes to the same
475    /// endpoints as the clusterIP. "ExternalName" aliases this service to the specified
476    /// externalName. Several other fields do not apply to ExternalName services.
477    /// More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
478    #[serde(skip_serializing_if = "Option::is_none")]
479    pub type_: Option<String>,
480}
481
482#[derive(Serialize, Deserialize, Clone, Debug, Default)]
483#[cfg_attr(feature = "schemars", derive(JsonSchema))]
484#[serde(rename_all = "camelCase")]
485pub struct KanidmIngress {
486    /// Annotations is an unstructured key value map stored with a resource that may be set by
487    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
488    /// be preserved when modifying objects.
489    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
490    #[serde(skip_serializing_if = "Option::is_none")]
491    pub annotations: Option<BTreeMap<String, String>>,
492
493    /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
494    /// implementations use this field to know whether they should be serving this Ingress resource,
495    /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
496    /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
497    /// it was widely supported by Ingress controllers to create a direct binding between Ingress
498    /// controller and Ingress resources. Newly created Ingress resources should prefer using the
499    /// field. However, even though the annotation is officially deprecated, for backwards
500    /// compatibility reasons, ingress controllers should still honor that annotation if present.
501    #[serde(skip_serializing_if = "Option::is_none")]
502    pub ingress_class_name: Option<String>,
503    /// Defines the name of the secret that contains the TLS private key and certificate for the
504    /// server. If not defined, the default will be the Kanidm name appended with `-tls`.
505    #[serde(skip_serializing_if = "Option::is_none")]
506    pub tls_secret_name: Option<String>,
507    /// Additional Subject Alternative Names (SANs) to include in the TLS certificate.
508    /// The main domain from the Kanidm spec is automatically included.
509    /// This does not add additional hosts to the ingress resource, only certificate SANs.
510    #[serde(skip_serializing_if = "Option::is_none")]
511    pub extra_tls_hosts: Option<BTreeSet<String>>,
512}
513
514/// Most recent observed status of the Kanidm cluster. Read-only.
515/// More info:
516/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
517#[derive(Serialize, Deserialize, Clone, Debug, Default)]
518#[cfg_attr(feature = "schemars", derive(JsonSchema))]
519#[serde(rename_all = "camelCase")]
520pub struct KanidmStatus {
521    /// Total number of available pods (ready for at least minReadySeconds) targeted by this Kanidm
522    /// deployment.
523    pub available_replicas: i32,
524
525    #[serde(skip_serializing_if = "Option::is_none")]
526    pub conditions: Option<Vec<Condition>>,
527
528    /// Total number of non-terminated pods targeted by this Kanidm cluster.
529    pub replicas: i32,
530
531    /// Total number of unavailable pods targeted by this Kanidm cluster.
532    pub unavailable_replicas: i32,
533
534    /// Total number of non-terminated pods targeted by this Kanidm cluster that have the
535    /// desired version spec.
536    pub updated_replicas: i32,
537
538    /// Status per replica in the Kanidm cluster.
539    pub replica_statuses: Vec<KanidmReplicaStatus>,
540
541    /// Ready vs desired replicas.
542    pub replica_column: String,
543
544    /// Admin users secret name.
545    pub secret_name: Option<String>,
546}
547
548#[derive(Serialize, Deserialize, Clone, Debug)]
549#[cfg_attr(feature = "schemars", derive(JsonSchema))]
550#[serde(rename_all = "camelCase")]
551pub struct KanidmReplicaStatus {
552    /// Pod name: replica group StatefulSet name plus the pod index.
553    pub pod_name: String,
554
555    /// StatefulSet name: Kanidm name plus the replica group name.
556    pub statefulset_name: String,
557
558    /// The current state of the replica.
559    pub state: KanidmReplicaState,
560}
561
562#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
563#[cfg_attr(feature = "schemars", derive(JsonSchema))]
564#[serde(rename_all = "snake_case")]
565pub enum KanidmReplicaState {
566    Initialized,
567    Pending,
568    CertificateExpiring,
569}
570
571#[cfg(test)]
572mod tests {
573    use super::*;
574    use k8s_openapi::api::core::v1::PersistentVolumeClaimSpec;
575
576    #[test]
577    fn test_pvc_template_optional_metadata() {
578        // Test that we can create a PVC template without metadata
579        let pvc_template = PersistentVolumeClaimTemplate {
580            metadata: None,
581            spec: Some(PersistentVolumeClaimSpec::default()),
582        };
583
584        // Test that it can be converted to a k8s PVC
585        let k8s_pvc = pvc_template.to_persistent_volume_claim();
586        assert_eq!(k8s_pvc.metadata, ObjectMeta::default());
587        assert_eq!(k8s_pvc.spec, pvc_template.spec);
588    }
589
590    #[test]
591    fn test_pvc_template_with_metadata() {
592        let custom_metadata = ObjectMeta {
593            name: Some("test-pvc".to_string()),
594            labels: Some([("app".to_string(), "test".to_string())].into()),
595            ..ObjectMeta::default()
596        };
597
598        // Test that we can create a PVC template with metadata
599        let pvc_template = PersistentVolumeClaimTemplate {
600            metadata: Some(custom_metadata.clone()),
601            spec: Some(PersistentVolumeClaimSpec::default()),
602        };
603
604        // Test that it can be converted to a k8s PVC
605        let k8s_pvc = pvc_template.to_persistent_volume_claim();
606        assert_eq!(k8s_pvc.metadata, custom_metadata);
607        assert_eq!(k8s_pvc.spec, pvc_template.spec);
608    }
609}