kaniop_operator/kanidm/
crd.rs

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