Skip to main content

kaniop_operator/kanidm/
crd.rs

1use crate::crd::is_default;
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use gateway_api::apis::standard::httproutes::HttpRouteRules;
6use k8s_openapi::api::apps::v1::StatefulSetPersistentVolumeClaimRetentionPolicy;
7use k8s_openapi::api::core::v1::{
8    Affinity, Container, EmptyDirVolumeSource, EnvVar, EphemeralVolumeSource, HostAlias,
9    PersistentVolumeClaim, PersistentVolumeClaimSpec, PodDNSConfig, PodSecurityContext,
10    ResourceRequirements, SecretKeySelector, Toleration, TopologySpreadConstraint, Volume,
11    VolumeMount,
12};
13use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, LabelSelector};
14use kube::api::ObjectMeta;
15use kube::CustomResource;
16#[cfg(feature = "schemars")]
17use schemars::JsonSchema;
18use serde::{Deserialize, Serialize};
19
20/// Specification of the desired behavior of the Kanidm cluster. More info:
21/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
22#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, Default)]
23#[cfg_attr(feature = "schemars", derive(JsonSchema))]
24// workaround: '`' character is not allowed in the kube `doc` attribute during doctests
25#[cfg_attr(
26    not(doctest),
27    kube(
28        doc = r#"The `Kanidm` custom resource definition (CRD) defines a desired [Kanidm](https://kanidm.com)
29    setup to run in a Kubernetes cluster. It allows to specify many options such as the number of replicas,
30    persistent storage, and many more.
31
32    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.
33    "#
34    )
35)]
36#[kube(
37    category = "kaniop",
38    group = "kaniop.rs",
39    version = "v1beta1",
40    kind = "Kanidm",
41    plural = "kanidms",
42    singular = "kanidm",
43    shortname = "idm",
44    namespaced,
45    status = "KanidmStatus",
46    printcolumn = r#"{"name":"Replicas","type":"string","description":"The number of replicas: ready/desired","jsonPath":".status.replicaColumn"}"#,
47    printcolumn = r#"{"name":"Domain","type":"string","jsonPath":".spec.domain"}"#,
48    printcolumn = r#"{"name":"Secret","type":"string","jsonPath":".status.secretName"}"#,
49    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#,
50    derive = "Default"
51)]
52#[serde(rename_all = "camelCase")]
53pub struct KanidmSpec {
54    /// The DNS domain name of the server. This is used in a number of security-critical
55    /// contexts such as webauthn, so it *must* match your DNS hostname. It is used to
56    /// create security principal names such as `william@idm.example.com` so that in a
57    /// (future) trust configuration it is possible to have unique Security Principal
58    /// Names (spns) throughout the topology.
59    ///
60    /// This cannot be changed after creation.
61    #[schemars(extend("x-kubernetes-validations" = [
62        {
63            "message": "Domain cannot be changed.",
64            "rule": "self == oldSelf"},
65        {
66            "message": "Domain must be a valid DNS name",
67            "rule": "self.matches(r'^([a-z0-9]([-a-z0-9]*[a-z0-9])?\\.)*[a-z0-9]([-a-z0-9]*[a-z0-9])?$')"
68        }
69    ]))]
70    pub domain: String,
71
72    /// The origin for webauthn. This is the url to the server,
73    /// with the port included if it is non-standard (any port
74    /// except 443). This must match or be a descendent of the
75    /// domain name you configure above. If these two items are
76    /// not consistent, the server WILL refuse to start!
77    /// origin = "https://idm.example.com"
78    /// # OR
79    /// origin = "https://idm.example.com:8443"
80    ///
81    /// Defaults to `https://<domain>` if not specified.
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub origin: Option<String>,
84
85    /// Different group of replicas with specific configuration as role, resources, affinity rules, and more.
86    /// Each group will be deployed as a separate StatefulSet.
87    #[schemars(extend("x-kubernetes-validations" = [{"message": "At least one ReplicaGroup is required", "rule": "self.size() > 0"}]))]
88    // max is defined for allowing CEL expression in validation admission policy estimate
89    // expression costs
90    #[validate(length(min = 1, max = 100))]
91    pub replica_groups: Vec<ReplicaGroup>,
92
93    /// List of external replication nodes. This is used to configure replication between
94    /// different Kanidm clusters.
95    ///
96    /// **WARNING**: `admin` and `idm_admin` passwords are going to be reset.
97    // max is defined for allowing CEL expression in validation admission policy estimate
98    // expression costs.
99    #[validate(length(max = 100))]
100    #[serde(default, skip_serializing_if = "is_default")]
101    pub external_replication_nodes: Vec<ExternalReplicationNode>,
102
103    /// Container image name. More info: https://kubernetes.io/docs/concepts/containers/images
104    /// This field is optional to allow higher level config management to default or override
105    /// container images in workload controllers like StatefulSets.
106    #[serde(default = "default_image", skip_serializing_if = "is_default")]
107    pub image: String,
108
109    /// Before starting an upgrade, perform pre-upgrade checks to ensure that data can be
110    /// safely migrated to the new version. If pre-checks fail, image change is disallowed.
111    /// If set to true, upgrade pre-checks are skipped. Defaults to false.
112    #[serde(default, skip_serializing_if = "is_default")]
113    pub disable_upgrade_checks: bool,
114
115    /// Log level for Kanidm.
116    #[serde(default, skip_serializing_if = "is_default")]
117    pub log_level: KanidmLogLevel,
118
119    /// Port name used for the pods and governing service. Defaults to https.
120    #[serde(default = "default_port_name", skip_serializing_if = "is_default")]
121    pub port_name: String,
122
123    /// Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag
124    /// is specified, or IfNotPresent otherwise. Cannot be updated.
125    /// More info: https://kubernetes.io/docs/concepts/containers/images#updating-images
126    #[serde(skip_serializing_if = "Option::is_none")]
127    pub image_pull_policy: Option<String>,
128
129    /// List of environment variables to set in the `kanidm` container.
130    /// This can be used to set Kanidm configuration options.
131    /// More info: https://kanidm.github.io/kanidm/master/server_configuration.html
132    #[serde(skip_serializing_if = "Option::is_none")]
133    pub env: Option<Vec<EnvVar>>,
134
135    /// Namespaces to match for KanidmOAuth2Clients discovery.
136    ///
137    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
138    /// - Empty selector `{}`: matches all namespaces in the cluster
139    /// - Selector with labels: matches namespaces with matching labels
140    ///
141    /// Example for all namespaces: `oauth2ClientNamespaceSelector: {}`
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub oauth2_client_namespace_selector: Option<LabelSelector>,
144
145    /// Namespaces to match for KanidmGroups discovery.
146    ///
147    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
148    /// - Empty selector `{}`: matches all namespaces in the cluster
149    /// - Selector with labels: matches namespaces with matching labels
150    ///
151    /// Example for all namespaces: `groupNamespaceSelector: {}`
152    #[serde(skip_serializing_if = "Option::is_none")]
153    pub group_namespace_selector: Option<LabelSelector>,
154
155    /// Namespaces to match for KanidmPersonAccounts discovery.
156    ///
157    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
158    /// - Empty selector `{}`: matches all namespaces in the cluster
159    /// - Selector with labels: matches namespaces with matching labels
160    ///
161    /// Example for all namespaces: `personNamespaceSelector: {}`
162    #[serde(skip_serializing_if = "Option::is_none")]
163    pub person_namespace_selector: Option<LabelSelector>,
164
165    /// Namespaces to match for KanidmServiceAccounts discovery.
166    ///
167    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
168    /// - Empty selector `{}`: matches all namespaces in the cluster
169    /// - Selector with labels: matches namespaces with matching labels
170    ///
171    /// Example for all namespaces: `serviceAccountNamespaceSelector: {}`
172    #[serde(skip_serializing_if = "Option::is_none")]
173    pub service_account_namespace_selector: Option<LabelSelector>,
174
175    /// StorageSpec defines the configured storage for a group Kanidm servers.
176    /// If no storage option is specified, then by default an
177    /// [EmptyDir](https://kubernetes.io/docs/concepts/storage/volumes/#emptydir) will be used.
178    ///
179    /// If multiple storage options are specified, priority will be given as follows:
180    ///  1. emptyDir
181    ///  2. ephemeral
182    ///  3. volumeClaimTemplate
183    ///
184    /// Note: Kaniop does not resize PVCs until Kubernetes fix
185    /// [KEP-4650](https://github.com/kubernetes/enhancements/issues/4650).
186    /// Although, StatefulSet will be recreated if the PVC is resized.
187    #[serde(skip_serializing_if = "Option::is_none")]
188    pub storage: Option<KanidmStorage>,
189
190    /// Defines the port name used for the LDAP service. If not defined, LDAP service will not be
191    /// configured. Service port will be `3636`.
192    ///
193    /// StartTLS is not supported due to security risks such as credential leakage and MITM attacks
194    /// that are fundamental in how StartTLS works. StartTLS can not be repaired to prevent this.
195    /// LDAPS is the only secure method of communicating to any LDAP server. Kanidm will use its
196    /// certificates for both HTTPS and LDAPS.
197    #[serde(skip_serializing_if = "Option::is_none")]
198    pub ldap_port_name: Option<String>,
199
200    /// Specifies the name of the secret holding the TLS private key and certificate for the server.
201    /// If not provided, the ingress secret will be used. The server will not start if the secret
202    /// is missing.
203    #[schemars(extend("x-kubernetes-validations" = [
204        {
205            "message": "tlsSecretName must be a valid Kubernetes resource name.",
206            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
207        }
208    ]))]
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub tls_secret_name: Option<String>,
211
212    /// Service defines the service configuration for the Kanidm server.
213    #[serde(skip_serializing_if = "Option::is_none")]
214    pub service: Option<KanidmService>,
215
216    /// Ingress configuration for the Kanidm cluster.
217    ///
218    /// The domain specified in the Kanidm spec will be used as the ingress host.
219    /// TLS is required and must be configured at the ingress controller level (termination or
220    /// passthrough).
221    /// When running multiple replicas, configure session affinity on your ingress controller to
222    /// ensure proper session handling.
223    #[serde(skip_serializing_if = "Option::is_none")]
224    pub ingress: Option<KanidmIngress>,
225
226    /// Region-specific ingress configuration for multi-region deployments.
227    ///
228    /// Allows defining ingress settings for a specific region, using a subdomain of the main
229    /// Kanidm domain.
230    /// TLS is required and must be configured at the ingress controller level (termination or
231    /// passthrough).
232    /// For multi-region deployments, configure session affinity on your ingress controller to ensure proper session handling.
233    #[serde(skip_serializing_if = "Option::is_none")]
234    pub region_ingress: Option<KanidmRegionIngress>,
235
236    /// Gateway API configuration for the Kanidm cluster.
237    ///
238    /// Allows configuring an HTTPRoute for Gateway API-based ingress routing.
239    /// The HTTPRoute will route traffic to the Kanidm service using the specified parentRefs
240    /// to attach to Gateway(s).
241    /// Both ingress and gateway can be configured simultaneously for migration scenarios.
242    #[serde(skip_serializing_if = "Option::is_none")]
243    pub gateway: Option<KanidmGateway>,
244
245    /// Volumes allows the configuration of additional volumes on the output StatefulSet
246    /// definition. Volumes specified will be appended to other volumes that are generated as a
247    /// result of StorageSpec objects.
248    #[serde(skip_serializing_if = "Option::is_none")]
249    pub volumes: Option<Vec<Volume>>,
250
251    /// VolumeMounts allows the configuration of additional VolumeMounts.
252    ///
253    /// VolumeMounts will be appended to other VolumeMounts in the kanidm' container, that are
254    /// generated as a result of StorageSpec objects.
255    #[serde(skip_serializing_if = "Option::is_none")]
256    pub volume_mounts: Option<Vec<VolumeMount>>,
257
258    /// The field controls if and how PVCs are deleted during the lifecycle of a StatefulSet.
259    /// The default behavior is all PVCs are retained.
260    /// This is a beta field from 1.27. It requires enabling the StatefulSetAutoDeletePVC feature
261    /// gate.
262    #[serde(skip_serializing_if = "Option::is_none")]
263    pub persistent_volume_claim_retention_policy:
264        Option<StatefulSetPersistentVolumeClaimRetentionPolicy>,
265
266    /// SecurityContext holds pod-level security attributes and common container settings.
267    /// This defaults to the default PodSecurityContext.
268    #[serde(skip_serializing_if = "Option::is_none")]
269    pub security_context: Option<PodSecurityContext>,
270
271    /// Defines the DNS policy for the pods.
272    #[serde(skip_serializing_if = "Option::is_none")]
273    pub dns_policy: Option<String>,
274
275    /// Defines the DNS configuration for the pods.
276    #[serde(skip_serializing_if = "Option::is_none")]
277    pub dns_config: Option<PodDNSConfig>,
278
279    /// Containers allows injecting additional containers or modifying operator generated
280    /// containers. This can be used to allow adding an authentication proxy to the Pods or to
281    /// change the behavior of an operator generated container. Containers described here modify
282    /// an operator generated container if they share the same name and modifications are done
283    /// via a strategic merge patch.
284    ///
285    /// The name of container managed by the operator is: kanidm
286    ///
287    /// Overriding containers is entirely outside the scope of what the maintainers will support
288    /// and by doing so, you accept that this behaviour may break at any time without notice.
289    #[serde(skip_serializing_if = "Option::is_none")]
290    pub containers: Option<Vec<Container>>,
291
292    /// InitContainers allows injecting initContainers to the Pod definition. Those can be used to
293    /// e.g. fetch secrets for injection into the Kanidm configuration from external sources.
294    /// Any errors during the execution of an initContainer will lead to a restart of the Pod.
295    /// More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
296    /// InitContainers described here modify an operator generated init containers if they share
297    /// the same name and modifications are done via a strategic merge patch.
298    ///
299    /// The names of init container name managed by the operator are: * init-config-reloader.
300    ///
301    /// Overriding init containers is entirely outside the scope of what the maintainers will
302    /// support and by doing so, you accept that this behaviour may break at any time without notice.
303    #[serde(skip_serializing_if = "Option::is_none")]
304    pub init_containers: Option<Vec<Container>>,
305
306    /// Minimum number of seconds for which a newly created Pod should be ready without any of its
307    /// container crashing for it to be considered available. Defaults to 0 (pod will be considered
308    /// available as soon as it is ready)
309    #[serde(skip_serializing_if = "Option::is_none")]
310    pub min_ready_seconds: Option<i32>,
311
312    /// Optional list of hosts and IPs that will be injected into the Pod's hosts file if specified.
313    #[serde(skip_serializing_if = "Option::is_none")]
314    pub host_aliases: Option<Vec<HostAlias>>,
315
316    /// Use the host's network namespace if true.
317    ///
318    /// Make sure to understand the security implications if you want to enable it
319    /// (https://kubernetes.io/docs/concepts/configuration/overview/).
320    ///
321    /// When hostNetwork is enabled, this will set the DNS policy to ClusterFirstWithHostNet
322    /// automatically.
323    #[serde(default, skip_serializing_if = "is_default")]
324    pub host_network: Option<bool>,
325
326    /// IP family for bind addresses. Defaults to IPv4.
327    ///
328    /// - `ipv4`: Uses 0.0.0.0 for bind addresses (default)
329    /// - `ipv6`: Uses [::] for bind addresses
330    #[serde(default, skip_serializing_if = "is_default")]
331    pub ip_family: IpFamily,
332
333    /// RuntimeClassName refers to a RuntimeClass object in the node.k8s.io API group,
334    /// which should be used to run the pods in this Kanidm cluster.
335    /// If no RuntimeClass resource matches the named class, the pod will not be run.
336    /// If unset or empty, the "legacy" RuntimeClass will be used, which is an implicit
337    /// class with an empty definition that uses the default runtime handler.
338    /// More info: https://kubernetes.io/docs/concepts/containers/runtime-class/
339    #[serde(skip_serializing_if = "Option::is_none")]
340    pub runtime_class_name: Option<String>,
341
342    /// AutomountServiceAccountToken indicates whether a service account token should be automatically mounted.
343    /// If not specified, defaults to true (the token is mounted).
344    /// Setting this to false is recommended for security-sensitive applications.
345    /// More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub automount_service_account_token: Option<bool>,
348
349    /// EnableServiceLinks indicates whether information about services should be injected into pod's
350    /// environment variables, matching the syntax of Docker links.
351    /// Defaults to false for security reasons (prevents service environment variable injection).
352    /// Set to true only if you need Kubernetes to inject service information as environment variables.
353    /// More info: https://kubernetes.io/docs/concepts/services-networking/service/#environment-variables
354    #[serde(default = "default_false", skip_serializing_if = "is_default")]
355    pub enable_service_links: bool,
356
357    /// HostUsers controls how the user namespace is configured for the pod.
358    /// If set to true, the pod will use the host's user namespace.
359    /// If set to false or not specified, the pod will use a user namespace configured by the runtime.
360    /// This feature requires support in the container runtime and Kubernetes 1.27+.
361    /// More info: https://kubernetes.io/docs/concepts/workloads/pods/user-namespaces/
362    #[serde(skip_serializing_if = "Option::is_none")]
363    pub host_users: Option<bool>,
364
365    /// Domain appearance customization settings.
366    /// Allows customizing the display name and site image (logo) shown on the Kanidm signin page.
367    #[serde(skip_serializing_if = "Option::is_none")]
368    pub domain_appearance: Option<DomainAppearanceSpec>,
369
370    /// Mail sender configuration for sending emails (password reset links, notifications).
371    /// When enabled, the operator automatically creates a service account in Kanidm's
372    /// `idm_message_senders` group, generates an API token, and deploys the `kanidm-mail-sender`
373    /// component.
374    #[serde(skip_serializing_if = "Option::is_none")]
375    pub mail_sender: Option<MailSenderSpec>,
376}
377
378#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
379#[cfg_attr(feature = "schemars", derive(JsonSchema))]
380#[serde(rename_all = "camelCase")]
381pub struct DomainAppearanceSpec {
382    /// Display name shown when logged in. Defaults to "Kanidm <hostname>" if not specified.
383    #[serde(skip_serializing_if = "Option::is_none")]
384    pub display_name: Option<String>,
385
386    /// Optional site image (logo) for the signin page.
387    /// Uses same pattern as OAuth2 client images.
388    #[serde(skip_serializing_if = "Option::is_none")]
389    pub image: Option<DomainAppearanceImageSpec>,
390}
391
392#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
393#[cfg_attr(feature = "schemars", derive(JsonSchema))]
394#[serde(rename_all = "camelCase")]
395pub struct DomainAppearanceImageSpec {
396    /// URL to fetch the image from (HTTP/HTTPS only).
397    /// The operator will periodically check this URL for changes using HEAD requests
398    /// and re-download the image when changes are detected.
399    pub url: String,
400}
401
402#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
403#[cfg_attr(feature = "schemars", derive(JsonSchema))]
404#[serde(rename_all = "camelCase")]
405pub struct MailSenderSpec {
406    /// SMTP relay URL for sending emails.
407    /// Must be a valid SMTP URL: `smtp://hostname:port` or `smtps://hostname` (default port 465).
408    /// Example: `smtps://smtp.example.com` or `smtp://smtp.example.com:587`
409    pub relay: String,
410
411    /// Kubernetes secret containing SMTP credentials (username and password).
412    /// The secret must have keys for username and password (defaults to "username" and "password").
413    pub credentials_secret: MailSenderCredentialsSecret,
414
415    /// Email address used as the "From" address in sent emails.
416    /// Example: `kanidm@example.com`
417    pub from_address: String,
418
419    /// Optional email address for the "Reply-To" header.
420    /// Example: `admin@example.com`
421    #[serde(skip_serializing_if = "Option::is_none")]
422    pub reply_to_address: Option<String>,
423
424    /// Optional queue polling interval in seconds.
425    /// How often the mail sender checks Kanidm's message queue.
426    /// Defaults to 5 seconds.
427    #[serde(skip_serializing_if = "Option::is_none")]
428    pub queue_poll_interval_seconds: Option<i32>,
429
430    /// Optional SMTP connection timeout in seconds.
431    /// Defaults to 15 seconds.
432    #[serde(skip_serializing_if = "Option::is_none")]
433    pub connect_timeout_seconds: Option<i32>,
434
435    /// Optional custom image for the mail sender deployment.
436    /// Defaults to `kanidm/tools:<version>` matching the Kanidm server image version.
437    #[serde(skip_serializing_if = "Option::is_none")]
438    pub image: Option<String>,
439
440    /// Optional resource requirements for the mail sender deployment.
441    #[serde(skip_serializing_if = "Option::is_none")]
442    pub resources: Option<ResourceRequirements>,
443
444    /// Optional node selector for the mail sender deployment.
445    #[serde(skip_serializing_if = "Option::is_none")]
446    pub node_selector: Option<BTreeMap<String, String>>,
447
448    /// Optional affinity rules for the mail sender deployment.
449    #[serde(skip_serializing_if = "Option::is_none")]
450    pub affinity: Option<Affinity>,
451
452    /// Optional tolerations for the mail sender deployment.
453    #[serde(skip_serializing_if = "Option::is_none")]
454    pub tolerations: Option<Vec<Toleration>>,
455}
456
457#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
458#[cfg_attr(feature = "schemars", derive(JsonSchema))]
459#[serde(rename_all = "camelCase")]
460pub struct MailSenderCredentialsSecret {
461    /// Name of the Kubernetes secret containing SMTP credentials.
462    pub name: String,
463
464    /// Key in the secret containing the SMTP username.
465    /// Defaults to "username".
466    #[serde(default = "default_smtp_username_key", skip_serializing_if = "is_default")]
467    pub username_key: String,
468
469    /// Key in the secret containing the SMTP password.
470    /// Defaults to "password".
471    #[serde(default = "default_smtp_password_key", skip_serializing_if = "is_default")]
472    pub password_key: String,
473}
474
475impl Default for MailSenderCredentialsSecret {
476    fn default() -> Self {
477        Self {
478            name: String::new(),
479            username_key: default_smtp_username_key(),
480            password_key: default_smtp_password_key(),
481        }
482    }
483}
484
485fn default_smtp_username_key() -> String {
486    "username".to_string()
487}
488
489fn default_smtp_password_key() -> String {
490    "password".to_string()
491}
492
493#[derive(Serialize, Deserialize, Clone, Debug, Default)]
494#[cfg_attr(feature = "schemars", derive(JsonSchema))]
495#[serde(rename_all = "camelCase")]
496pub struct ReplicaGroup {
497    /// The name of the replica group.
498    pub name: String,
499
500    /// Number of replicas to deploy for a Kanidm replica group.
501    pub replicas: i32,
502
503    /// The Kanidm role of each node in the replica group.
504    #[serde(default)]
505    pub role: KanidmServerRole,
506
507    /// If true, the first pod of the StatefulSet will be considered as the primary node.
508    /// The rest of the nodes are considered as secondary nodes.
509    /// This means that if database issues occur the content of the primary will take precedence
510    /// over the rest of the nodes.
511    /// This is only valid for the WriteReplica role and can only be set to true for one
512    /// replica group or external replication node.
513    /// Defaults to false.
514    #[serde(default)]
515    pub primary_node: bool,
516
517    /// Service configuration for the replica group.
518    /// - If not specified, pods use the default StatefulSet DNS for internal communication.
519    /// - If specified, a Kubernetes Service of type LoadBalancer is created to expose replica
520    ///   group pods externally.
521    ///   This enables cross-cluster or multi-region access to replicas.
522    #[serde(skip_serializing_if = "Option::is_none")]
523    pub services: Option<KanidmReplicaGroupServices>,
524
525    /// Annotations to add to the StatefulSet created for this replica group.
526    ///
527    /// Each replica group gets its own StatefulSet; these annotations are applied only to the
528    /// StatefulSet for this group.
529    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
530    #[serde(skip_serializing_if = "Option::is_none")]
531    pub stateful_set_annotations: Option<BTreeMap<String, String>>,
532
533    /// Defines the resources requests and limits of the kanidm' container.
534    #[serde(skip_serializing_if = "Option::is_none")]
535    pub resources: Option<ResourceRequirements>,
536
537    /// Defines on which Nodes the Pods are scheduled.
538    #[serde(skip_serializing_if = "Option::is_none")]
539    pub node_selector: Option<BTreeMap<String, String>>,
540
541    /// Defines the Pods' affinity scheduling rules if specified.
542    #[serde(skip_serializing_if = "Option::is_none")]
543    pub affinity: Option<Affinity>,
544
545    /// Defines the Pods' tolerations if specified.
546    #[serde(skip_serializing_if = "Option::is_none")]
547    pub tolerations: Option<Vec<Toleration>>,
548
549    /// Defines the pod's topology spread constraints if specified.
550    #[serde(skip_serializing_if = "Option::is_none")]
551    pub topology_spread_constraints: Option<Vec<TopologySpreadConstraint>>,
552}
553
554// re-implementation of kanidmd_core::config::ServerRole because it is not Serialize
555#[derive(Serialize, Deserialize, Clone, Debug, Default)]
556#[cfg_attr(feature = "schemars", derive(JsonSchema))]
557#[serde(rename_all = "snake_case")]
558pub enum KanidmServerRole {
559    /// Full read-write replica with web UI
560    #[default]
561    WriteReplica,
562    /// Read-write replica without the web UI
563    WriteReplicaNoUi,
564    /// Read-only replica for load balancing read operations.
565    /// **WARNING**: read_only_replica is currently a placeholder and not yet implemented in Kanidm.
566    /// Using this role may lead to divergent data across replicas. Kaniop uses it to configure the
567    /// replication type to pull.
568    ReadOnlyReplica,
569}
570
571#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
572#[cfg_attr(feature = "schemars", derive(JsonSchema))]
573#[serde(rename_all = "camelCase")]
574pub struct KanidmReplicaGroupServices {
575    /// Annotations to apply to each Service for replica group pods.
576    ///
577    /// Available template variables:
578    /// - `{replica_index}`: Index of the pod in the replica group
579    /// - `{pod_name}`: Name of the pod
580    /// - `{domain}`: Domain name
581    #[serde(skip_serializing_if = "Option::is_none")]
582    pub annotations_template: Option<BTreeMap<String, String>>,
583
584    /// Hostname template for each Service created for replica group pods.
585    ///
586    /// Available template variables:
587    /// - `{replica_index}`: Index of the pod in the replica group
588    /// - `{pod_name}`: Name of the pod
589    /// - `{domain}`: Domain name
590    ///
591    /// If not set, the replication hostname defaults to the Service's external IP.
592    #[serde(skip_serializing_if = "Option::is_none")]
593    pub replication_hostname_template: Option<String>,
594
595    /// Map of string keys and values that can be used to organize and categorize (scope and
596    /// select) objects. May match selectors of replication controllers and services.
597    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels
598    #[serde(skip_serializing_if = "Option::is_none")]
599    pub additional_labels: Option<BTreeMap<String, String>>,
600}
601
602#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
603#[cfg_attr(feature = "schemars", derive(JsonSchema))]
604#[serde(rename_all = "camelCase")]
605pub struct ExternalReplicationNode {
606    /// Name of the external replication node. This just have internal use.
607    pub name: String,
608
609    /// The hostname of the external replication node.
610    pub hostname: String,
611
612    /// The replication port of the external replication node.
613    pub port: i32,
614
615    /// Defines the secret that contains the identity certificate of the external replication node.
616    pub certificate: SecretKeySelector,
617
618    /// Defines the type of replication to use. Defaults to MutualPull.
619    #[serde(default)]
620    pub _type: ReplicationType,
621
622    /// Select external replication node as the primary node. This means that if database conflicts
623    /// occur the content of the primary will take precedence over the rest of the nodes.
624    /// Note: just one external replication node or replication group can be selected as primary.
625    /// Defaults to false.
626    #[serde(default)]
627    pub automatic_refresh: bool,
628}
629
630// re-implementation of kanidmd_core::repl::config::RepNodeConfig because it is not Serialize and
631// attributes changed
632#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
633#[cfg_attr(feature = "schemars", derive(JsonSchema))]
634#[serde(rename_all = "kebab-case")]
635pub enum ReplicationType {
636    /// Both nodes can initiate replication with each other
637    #[default]
638    MutualPull,
639    /// This node allows the external node to pull changes, but won't initiate
640    AllowPull,
641    /// This node will pull changes from the external node
642    Pull,
643}
644
645fn default_image() -> String {
646    "kanidm/server:latest".to_string()
647}
648
649// re-implementation of sketching::LogLevel because it is not Serialize
650#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
651#[cfg_attr(feature = "schemars", derive(JsonSchema))]
652#[serde(rename_all = "snake_case")]
653pub enum KanidmLogLevel {
654    /// Most verbose logging level, includes all debug and info messages
655    Trace,
656    /// Debug level logging, useful for troubleshooting
657    Debug,
658    /// Standard informational logging level
659    #[default]
660    Info,
661}
662
663fn default_port_name() -> String {
664    "https".to_string()
665}
666
667fn default_false() -> bool {
668    false
669}
670
671#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
672#[cfg_attr(feature = "schemars", derive(JsonSchema))]
673#[serde(rename_all = "kebab-case")]
674pub enum IpFamily {
675    #[default]
676    Ipv4,
677    Ipv6,
678}
679
680/// PersistentVolumeClaimTemplate defines a PVC template with optional metadata.
681/// This allows users to specify a PVC template without requiring metadata to be explicitly set.
682#[derive(Serialize, Deserialize, Clone, Debug, Default)]
683#[cfg_attr(feature = "schemars", derive(JsonSchema))]
684#[serde(rename_all = "camelCase")]
685pub struct PersistentVolumeClaimTemplate {
686    /// Standard object's metadata. More info:
687    /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
688    #[serde(skip_serializing_if = "Option::is_none")]
689    pub metadata: Option<ObjectMeta>,
690
691    /// spec defines the desired characteristics of a volume requested by a pod author. More info:
692    /// https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
693    pub spec: Option<PersistentVolumeClaimSpec>,
694}
695
696impl PersistentVolumeClaimTemplate {
697    /// Convert this template into a k8s-openapi PersistentVolumeClaim
698    pub fn to_persistent_volume_claim(&self) -> PersistentVolumeClaim {
699        PersistentVolumeClaim {
700            metadata: self.metadata.clone().unwrap_or_default(),
701            spec: self.spec.clone(),
702            ..Default::default()
703        }
704    }
705}
706
707#[derive(Serialize, Deserialize, Clone, Debug, Default)]
708#[cfg_attr(feature = "schemars", derive(JsonSchema))]
709#[serde(rename_all = "camelCase")]
710pub struct KanidmStorage {
711    /// EmptyDirVolumeSource to be used by the StatefulSet. If specified, it takes precedence over
712    /// `ephemeral` and `volumeClaimTemplate`.
713    /// More info: https://kubernetes.io/docs/concepts/storage/volumes/#emptydir
714    #[serde(skip_serializing_if = "Option::is_none")]
715    pub empty_dir: Option<EmptyDirVolumeSource>,
716
717    /// EphemeralVolumeSource to be used by the StatefulSet.
718    /// More info: https://kubernetes.io/docs/concepts/storage/ephemeral-volumes/#generic-ephemeral-volumes
719    #[serde(skip_serializing_if = "Option::is_none")]
720    pub ephemeral: Option<EphemeralVolumeSource>,
721
722    /// Defines the PVC spec to be used by the Kanidm StatefulSets. The easiest way to use a volume
723    /// that cannot be automatically provisioned is to use a label selector alongside manually
724    /// created PersistentVolumes.
725    #[serde(skip_serializing_if = "Option::is_none")]
726    pub volume_claim_template: Option<PersistentVolumeClaimTemplate>,
727}
728
729#[derive(Serialize, Deserialize, Clone, Debug, Default)]
730#[cfg_attr(feature = "schemars", derive(JsonSchema))]
731#[serde(rename_all = "camelCase")]
732pub struct KanidmService {
733    /// Annotations is an unstructured key value map stored with a resource that may be set by
734    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
735    /// be preserved when modifying objects.
736    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
737    #[serde(skip_serializing_if = "Option::is_none")]
738    pub annotations: Option<BTreeMap<String, String>>,
739
740    /// Specify the Service's type where the Kanidm Service is exposed
741    /// Please note that some Ingress controllers like https://github.com/kubernetes/ingress-gce
742    /// forces you to expose your Service on a NodePort
743    /// Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and
744    /// LoadBalancer. "ClusterIP" allocates a cluster-internal IP address for load-balancing to
745    /// endpoints. Endpoints are determined by the selector or if that is not specified, by manual
746    /// construction of an Endpoints object or EndpointSlice objects. If clusterIP is "None",
747    /// no virtual IP is allocated and the endpoints are published as a set of endpoints rather
748    /// than a virtual IP. "NodePort" builds on ClusterIP and allocates a port on every node which
749    /// routes to the same endpoints as the clusterIP. "LoadBalancer" builds on NodePort and creates
750    /// an external load-balancer (if supported in the current cloud) which routes to the same
751    /// endpoints as the clusterIP. "ExternalName" aliases this service to the specified
752    /// externalName. Several other fields do not apply to ExternalName services.
753    /// More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
754    #[serde(skip_serializing_if = "Option::is_none")]
755    pub type_: Option<String>,
756
757    /// Map of string keys and values that can be used to organize and categorize (scope and
758    /// select) objects. May match selectors of replication controllers and services.
759    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels
760    #[serde(skip_serializing_if = "Option::is_none")]
761    pub additional_labels: Option<BTreeMap<String, String>>,
762}
763
764#[derive(Serialize, Deserialize, Clone, Debug, Default)]
765#[cfg_attr(feature = "schemars", derive(JsonSchema))]
766#[serde(rename_all = "camelCase")]
767pub struct KanidmIngress {
768    /// Annotations is an unstructured key value map stored with a resource that may be set by
769    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
770    /// be preserved when modifying objects.
771    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
772    #[serde(skip_serializing_if = "Option::is_none")]
773    pub annotations: Option<BTreeMap<String, String>>,
774
775    /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
776    /// implementations use this field to know whether they should be serving this Ingress resource,
777    /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
778    /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
779    /// it was widely supported by Ingress controllers to create a direct binding between Ingress
780    /// controller and Ingress resources. Newly created Ingress resources should prefer using the
781    /// field. However, even though the annotation is officially deprecated, for backwards
782    /// compatibility reasons, ingress controllers should still honor that annotation if present.
783    #[serde(skip_serializing_if = "Option::is_none")]
784    pub ingress_class_name: Option<String>,
785    /// Defines the name of the secret that contains the TLS private key and certificate for the
786    /// server. If not defined, the default will be the Kanidm name appended with `-tls`.
787    #[schemars(extend("x-kubernetes-validations" = [
788        {
789            "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
790            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
791        }
792    ]))]
793    #[serde(skip_serializing_if = "Option::is_none")]
794    pub tls_secret_name: Option<String>,
795    /// Additional Subject Alternative Names (SANs) to include in the TLS certificate.
796    /// The main domain from the Kanidm spec is automatically included.
797    /// This does not add additional hosts to the ingress resource, only certificate SANs.
798    #[serde(skip_serializing_if = "Option::is_none")]
799    pub extra_tls_hosts: Option<BTreeSet<String>>,
800}
801
802#[derive(Serialize, Deserialize, Clone, Debug, Default)]
803#[cfg_attr(feature = "schemars", derive(JsonSchema))]
804#[serde(rename_all = "camelCase")]
805pub struct KanidmRegionIngress {
806    /// Region identifier for this ingress. Used as a subdomain of the main Kanidm domain to route
807    /// traffic for a specific region.
808    pub region: String,
809
810    /// Annotations is an unstructured key value map stored with a resource that may be set by
811    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
812    /// be preserved when modifying objects.
813    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
814    #[serde(skip_serializing_if = "Option::is_none")]
815    pub annotations: Option<BTreeMap<String, String>>,
816
817    /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
818    /// implementations use this field to know whether they should be serving this Ingress resource,
819    /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
820    /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
821    /// it was widely supported by Ingress controllers to create a direct binding between Ingress
822    /// controller and Ingress resources. Newly created Ingress resources should prefer using the
823    /// field. However, even though the annotation is officially deprecated, for backwards
824    /// compatibility reasons, ingress controllers should still honor that annotation if present.
825    #[serde(skip_serializing_if = "Option::is_none")]
826    pub ingress_class_name: Option<String>,
827    /// Defines the name of the secret that contains the TLS private key and certificate for the
828    /// server. If not defined, the default will be the Kanidm name appended with `-region-tls`.
829    #[schemars(extend("x-kubernetes-validations" = [
830        {
831            "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
832            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
833        }
834    ]))]
835    #[serde(skip_serializing_if = "Option::is_none")]
836    pub tls_secret_name: Option<String>,
837}
838
839#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
840#[cfg_attr(feature = "schemars", derive(JsonSchema))]
841#[serde(rename_all = "camelCase")]
842pub struct KanidmGatewayParentRef {
843    /// Name of the referent.
844    pub name: String,
845
846    /// Namespace of the referent. When unspecified, this refers to the local namespace.
847    #[serde(skip_serializing_if = "Option::is_none")]
848    pub namespace: Option<String>,
849
850    /// SectionName is the name of a section within the target resource.
851    /// When specified, this must refer to a named section within the target resource,
852    /// such as a specific listener on a Gateway.
853    #[serde(skip_serializing_if = "Option::is_none")]
854    pub section_name: Option<String>,
855
856    /// Port is the network port this Route targets.
857    #[serde(skip_serializing_if = "Option::is_none")]
858    pub port: Option<u32>,
859}
860
861#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
862#[cfg_attr(feature = "schemars", derive(JsonSchema))]
863#[serde(rename_all = "camelCase")]
864pub struct KanidmGateway {
865    /// ParentRefs references the Gateway(s) that this HTTPRoute should be attached to.
866    /// Each ParentRef must reference a Gateway in the same namespace as the HTTPRoute.
867    #[schemars(extend("x-kubernetes-validations" = [{"message": "At least one ParentRef is required", "rule": "self.size() > 0"}]))]
868    #[validate(length(min = 1))]
869    pub parent_refs: Vec<KanidmGatewayParentRef>,
870
871    /// Hostnames defines a set of hostnames that should match against the HTTP Host
872    /// header to select a HTTPRoute used to process the request.
873    /// When unspecified, defaults to the Kanidm domain (spec.domain).
874    #[serde(skip_serializing_if = "Option::is_none")]
875    pub hostnames: Option<Vec<String>>,
876
877    /// Annotations is an unstructured key value map stored with a resource that may be set by
878    /// external tools to store and retrieve arbitrary metadata.
879    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
880    #[serde(skip_serializing_if = "Option::is_none")]
881    pub annotations: Option<BTreeMap<String, String>>,
882
883    /// Rules defines a list of HTTPRoute rules.
884    /// Each rule consists of conditions for matching an HTTP request,
885    /// filters for processing it, and backend references for forwarding the request.
886    /// When unspecified, a default rule is created that routes all traffic to the Kanidm service.
887    /// This field allows customization of routing behavior, including session persistence,
888    /// timeouts, filters, and advanced matching conditions.
889    /// Note: The sessionPersistence field in rules is experimental and requires
890    /// Gateway API experimental channel support from the implementation.
891    #[serde(skip_serializing_if = "Option::is_none")]
892    pub rules: Option<Vec<HttpRouteRules>>,
893}
894
895/// Most recent observed status of the Kanidm cluster. Read-only.
896/// More info:
897/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
898#[derive(Serialize, Deserialize, Clone, Debug, Default)]
899#[cfg_attr(feature = "schemars", derive(JsonSchema))]
900#[serde(rename_all = "camelCase")]
901pub struct KanidmStatus {
902    /// Total number of available pods (ready for at least minReadySeconds) targeted by this Kanidm
903    /// deployment.
904    pub available_replicas: i32,
905
906    #[serde(skip_serializing_if = "Option::is_none")]
907    pub conditions: Option<Vec<Condition>>,
908
909    /// Total number of non-terminated pods targeted by this Kanidm cluster.
910    pub replicas: i32,
911
912    /// Total number of unavailable pods targeted by this Kanidm cluster.
913    pub unavailable_replicas: i32,
914
915    /// Total number of non-terminated pods targeted by this Kanidm cluster that have the
916    /// desired version spec.
917    pub updated_replicas: i32,
918
919    /// Status per replica in the Kanidm cluster.
920    pub replica_statuses: Vec<KanidmReplicaStatus>,
921
922    /// Ready vs desired replicas.
923    pub replica_column: String,
924
925    /// Admin users secret name.
926    pub secret_name: Option<String>,
927
928    /// The current version of the Kanidm server.
929    pub version: Option<KanidmVersionStatus>,
930
931    /// Status of the domain appearance image.
932    pub domain_appearance_image: Option<DomainAppearanceImageStatus>,
933
934    /// Status of the mail sender deployment.
935    #[serde(skip_serializing_if = "Option::is_none")]
936    pub mail_sender: Option<MailSenderStatus>,
937}
938
939#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
940#[cfg_attr(feature = "schemars", derive(JsonSchema))]
941#[serde(rename_all = "camelCase")]
942pub struct MailSenderStatus {
943    /// Name of the service account in Kanidm for mail sending.
944    /// Format: `<kanidm-name>-mail-sender`
945    pub service_account_name: String,
946
947    /// Name of the Kubernetes secret containing the API token.
948    /// Format: `<kanidm-name>-mail-sender-token`
949    pub token_secret_name: String,
950
951    /// Name of the Deployment running the mail sender.
952    /// Format: `<kanidm-name>-mail-sender`
953    pub deployment_name: String,
954
955    /// Name of the ConfigMap containing mail sender configuration.
956    /// Format: `<kanidm-name>-mail-sender-config`
957    pub config_map_name: String,
958
959    /// Whether the mail sender deployment is ready.
960    pub ready: bool,
961}
962
963#[derive(Serialize, Deserialize, Clone, Debug)]
964#[cfg_attr(feature = "schemars", derive(JsonSchema))]
965#[serde(rename_all = "camelCase")]
966pub struct KanidmReplicaStatus {
967    /// Pod name: replica group StatefulSet name plus the pod index.
968    pub pod_name: String,
969
970    /// StatefulSet name: Kanidm name plus the replica group name.
971    pub statefulset_name: String,
972
973    /// The current state of the replica.
974    pub state: KanidmReplicaState,
975}
976
977#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
978#[cfg_attr(feature = "schemars", derive(JsonSchema))]
979#[serde(rename_all = "camelCase")]
980pub enum KanidmReplicaState {
981    Ready,
982    Pending,
983    CertificateExpiring,
984    CertificateHostInvalid,
985}
986
987#[derive(Serialize, Deserialize, Clone, Debug)]
988#[cfg_attr(feature = "schemars", derive(JsonSchema))]
989#[serde(rename_all = "camelCase")]
990pub struct KanidmVersionStatus {
991    pub image_tag: String,
992
993    pub upgrade_check_result: KanidmUpgradeCheckResult,
994
995    #[serde(default)]
996    pub compatibility_result: VersionCompatibilityResult,
997}
998
999#[derive(Serialize, Deserialize, Clone, PartialEq, Debug, Default)]
1000#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1001#[serde(rename_all = "snake_case")]
1002pub enum VersionCompatibilityResult {
1003    #[default]
1004    Compatible,
1005    Incompatible,
1006}
1007
1008#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
1009#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1010#[serde(rename_all = "snake_case")]
1011pub enum KanidmUpgradeCheckResult {
1012    Passed,
1013    Failed,
1014}
1015
1016#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
1017#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1018#[serde(rename_all = "camelCase")]
1019pub struct DomainAppearanceImageStatus {
1020    /// The URL from which the image was last fetched.
1021    pub url: String,
1022    /// ETag header from the last fetch (for change detection).
1023    #[serde(skip_serializing_if = "Option::is_none")]
1024    pub etag: Option<String>,
1025    /// Last-Modified header from the last fetch.
1026    #[serde(skip_serializing_if = "Option::is_none")]
1027    pub last_modified: Option<String>,
1028    /// Content-Length from the last fetch.
1029    #[serde(skip_serializing_if = "Option::is_none")]
1030    pub content_length: Option<u64>,
1031    /// Hash of the image content (SHA-256, for validation).
1032    #[serde(skip_serializing_if = "Option::is_none")]
1033    pub content_hash: Option<String>,
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038    use super::*;
1039    use k8s_openapi::api::core::v1::PersistentVolumeClaimSpec;
1040    use serde_json::json;
1041
1042    #[test]
1043    fn test_pvc_template_optional_metadata() {
1044        // Test that we can create a PVC template without metadata
1045        let pvc_template = PersistentVolumeClaimTemplate {
1046            metadata: None,
1047            spec: Some(PersistentVolumeClaimSpec::default()),
1048        };
1049
1050        // Test that it can be converted to a k8s PVC
1051        let k8s_pvc = pvc_template.to_persistent_volume_claim();
1052        assert_eq!(k8s_pvc.metadata, ObjectMeta::default());
1053        assert_eq!(k8s_pvc.spec, pvc_template.spec);
1054    }
1055
1056    #[test]
1057    fn test_pvc_template_with_metadata() {
1058        let custom_metadata = ObjectMeta {
1059            name: Some("test-pvc".to_string()),
1060            labels: Some([("app".to_string(), "test".to_string())].into()),
1061            ..ObjectMeta::default()
1062        };
1063
1064        // Test that we can create a PVC template with metadata
1065        let pvc_template = PersistentVolumeClaimTemplate {
1066            metadata: Some(custom_metadata.clone()),
1067            spec: Some(PersistentVolumeClaimSpec::default()),
1068        };
1069
1070        // Test that it can be converted to a k8s PVC
1071        let k8s_pvc = pvc_template.to_persistent_volume_claim();
1072        assert_eq!(k8s_pvc.metadata, custom_metadata);
1073        assert_eq!(k8s_pvc.spec, pvc_template.spec);
1074    }
1075
1076    #[test]
1077    fn test_kanidm_version_status_backward_compatible() {
1078        let legacy_payload = json!({
1079            "imageTag": "1.9.0",
1080            "upgradeCheckResult": "passed"
1081        });
1082
1083        let status: KanidmVersionStatus =
1084            serde_json::from_value(legacy_payload).expect("legacy status should deserialize");
1085
1086        assert_eq!(status.image_tag, "1.9.0");
1087        assert_eq!(
1088            status.upgrade_check_result,
1089            KanidmUpgradeCheckResult::Passed
1090        );
1091        assert_eq!(
1092            status.compatibility_result,
1093            VersionCompatibilityResult::Compatible
1094        );
1095    }
1096}