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