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    /// Optional Secret containing SMTP credentials (username and password).
422    /// Omit for relays without SMTP AUTH. When present, it must contain the
423    /// configured username and password keys (defaults to "username" and "password").
424    #[serde(skip_serializing_if = "Option::is_none")]
425    pub credentials_secret: Option<MailSenderCredentialsSecret>,
426
427    /// Optional same-namespace ConfigMap containing a PEM-encoded CA bundle for
428    /// verifying the Kanidm HTTPS endpoint used by the mail sender.
429    #[serde(skip_serializing_if = "Option::is_none")]
430    pub ca_bundle_ref: Option<CaBundleRef>,
431
432    /// Email address used as the "From" address in sent emails.
433    /// Example: `kanidm@example.com`
434    pub from_address: String,
435
436    /// Optional email address for the "Reply-To" header.
437    /// Example: `admin@example.com`
438    #[serde(skip_serializing_if = "Option::is_none")]
439    pub reply_to_address: Option<String>,
440
441    /// Optional queue polling interval in seconds.
442    /// How often the mail sender checks Kanidm's message queue.
443    /// Defaults to 5 seconds.
444    #[serde(skip_serializing_if = "Option::is_none")]
445    pub queue_poll_interval_seconds: Option<i32>,
446
447    /// Optional SMTP connection timeout in seconds.
448    /// Defaults to 15 seconds.
449    #[serde(skip_serializing_if = "Option::is_none")]
450    pub connect_timeout_seconds: Option<i32>,
451
452    /// Optional custom image for the mail sender deployment.
453    /// Defaults to `kanidm/tools:<version>` matching the Kanidm server image version.
454    #[serde(skip_serializing_if = "Option::is_none")]
455    pub image: Option<String>,
456
457    /// Optional resource requirements for the mail sender deployment.
458    #[serde(skip_serializing_if = "Option::is_none")]
459    pub resources: Option<ResourceRequirements>,
460
461    /// Optional node selector for the mail sender deployment.
462    #[serde(skip_serializing_if = "Option::is_none")]
463    pub node_selector: Option<BTreeMap<String, String>>,
464
465    /// Optional affinity rules for the mail sender deployment.
466    #[serde(skip_serializing_if = "Option::is_none")]
467    pub affinity: Option<Affinity>,
468
469    /// Optional tolerations for the mail sender deployment.
470    #[serde(skip_serializing_if = "Option::is_none")]
471    pub tolerations: Option<Vec<Toleration>>,
472}
473
474#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
475#[cfg_attr(feature = "schemars", derive(JsonSchema))]
476#[serde(rename_all = "camelCase")]
477pub struct MailSenderCredentialsSecret {
478    /// Name of the Kubernetes secret containing SMTP credentials.
479    pub name: String,
480
481    /// Key in the secret containing the SMTP username.
482    /// Defaults to "username".
483    #[serde(default = "default_smtp_username_key", skip_serializing_if = "is_default")]
484    pub username_key: String,
485
486    /// Key in the secret containing the SMTP password.
487    /// Defaults to "password".
488    #[serde(default = "default_smtp_password_key", skip_serializing_if = "is_default")]
489    pub password_key: String,
490}
491
492impl Default for MailSenderCredentialsSecret {
493    fn default() -> Self {
494        Self {
495            name: String::new(),
496            username_key: default_smtp_username_key(),
497            password_key: default_smtp_password_key(),
498        }
499    }
500}
501
502fn default_smtp_username_key() -> String {
503    "username".to_string()
504}
505
506fn default_smtp_password_key() -> String {
507    "password".to_string()
508}
509
510#[derive(Serialize, Deserialize, Clone, Debug, Default)]
511#[cfg_attr(feature = "schemars", derive(JsonSchema))]
512#[serde(rename_all = "camelCase")]
513pub struct ReplicaGroup {
514    /// The name of the replica group.
515    pub name: String,
516
517    /// Number of replicas to deploy for a Kanidm replica group.
518    pub replicas: i32,
519
520    /// The Kanidm role of each node in the replica group.
521    #[serde(default)]
522    pub role: KanidmServerRole,
523
524    /// If true, the first pod of the StatefulSet will be considered as the primary node.
525    /// The rest of the nodes are considered as secondary nodes.
526    /// This means that if database issues occur the content of the primary will take precedence
527    /// over the rest of the nodes.
528    /// This is only valid for the WriteReplica role and can only be set to true for one
529    /// replica group or external replication node.
530    /// Defaults to false.
531    #[serde(default)]
532    pub primary_node: bool,
533
534    /// Service configuration for the replica group.
535    /// - If not specified, pods use the default StatefulSet DNS for internal communication.
536    /// - If specified, a Kubernetes Service of type LoadBalancer is created to expose replica
537    ///   group pods externally.
538    ///   This enables cross-cluster or multi-region access to replicas.
539    #[serde(skip_serializing_if = "Option::is_none")]
540    pub services: Option<KanidmReplicaGroupServices>,
541
542    /// Annotations to add to the StatefulSet created for this replica group.
543    ///
544    /// Each replica group gets its own StatefulSet; these annotations are applied only to the
545    /// StatefulSet for this group.
546    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
547    #[serde(skip_serializing_if = "Option::is_none")]
548    pub stateful_set_annotations: Option<BTreeMap<String, String>>,
549
550    /// Defines the resources requests and limits of the kanidm' container.
551    #[serde(skip_serializing_if = "Option::is_none")]
552    pub resources: Option<ResourceRequirements>,
553
554    /// Defines on which Nodes the Pods are scheduled.
555    #[serde(skip_serializing_if = "Option::is_none")]
556    pub node_selector: Option<BTreeMap<String, String>>,
557
558    /// Defines the Pods' affinity scheduling rules if specified.
559    #[serde(skip_serializing_if = "Option::is_none")]
560    pub affinity: Option<Affinity>,
561
562    /// Defines the Pods' tolerations if specified.
563    #[serde(skip_serializing_if = "Option::is_none")]
564    pub tolerations: Option<Vec<Toleration>>,
565
566    /// Defines the pod's topology spread constraints if specified.
567    #[serde(skip_serializing_if = "Option::is_none")]
568    pub topology_spread_constraints: Option<Vec<TopologySpreadConstraint>>,
569}
570
571// re-implementation of kanidmd_core::config::ServerRole because it is not Serialize
572#[derive(Serialize, Deserialize, Clone, Debug, Default)]
573#[cfg_attr(feature = "schemars", derive(JsonSchema))]
574#[serde(rename_all = "snake_case")]
575pub enum KanidmServerRole {
576    /// Full read-write replica with web UI
577    #[default]
578    WriteReplica,
579    /// Read-write replica without the web UI
580    WriteReplicaNoUi,
581    /// Read-only replica for load balancing read operations.
582    /// **WARNING**: read_only_replica is currently a placeholder and not yet implemented in Kanidm.
583    /// Using this role may lead to divergent data across replicas. Kaniop uses it to configure the
584    /// replication type to pull.
585    ReadOnlyReplica,
586}
587
588#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
589#[cfg_attr(feature = "schemars", derive(JsonSchema))]
590#[serde(rename_all = "camelCase")]
591pub struct KanidmReplicaGroupServices {
592    /// Annotations to apply to each Service for replica group pods.
593    ///
594    /// Available template variables:
595    /// - `{replica_index}`: Index of the pod in the replica group
596    /// - `{pod_name}`: Name of the pod
597    /// - `{domain}`: Domain name
598    #[serde(skip_serializing_if = "Option::is_none")]
599    pub annotations_template: Option<BTreeMap<String, String>>,
600
601    /// Hostname template for each Service created for replica group pods.
602    ///
603    /// Available template variables:
604    /// - `{replica_index}`: Index of the pod in the replica group
605    /// - `{pod_name}`: Name of the pod
606    /// - `{domain}`: Domain name
607    ///
608    /// If not set, the replication hostname defaults to the Service's external IP.
609    #[serde(skip_serializing_if = "Option::is_none")]
610    pub replication_hostname_template: Option<String>,
611
612    /// Map of string keys and values that can be used to organize and categorize (scope and
613    /// select) objects. May match selectors of replication controllers and services.
614    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels
615    #[serde(skip_serializing_if = "Option::is_none")]
616    pub additional_labels: Option<BTreeMap<String, String>>,
617}
618
619#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
620#[cfg_attr(feature = "schemars", derive(JsonSchema))]
621#[serde(rename_all = "camelCase")]
622pub struct ExternalReplicationNode {
623    /// Name of the external replication node. This just have internal use.
624    pub name: String,
625
626    /// The hostname of the external replication node.
627    pub hostname: String,
628
629    /// The replication port of the external replication node.
630    pub port: i32,
631
632    /// Defines the secret that contains the identity certificate of the external replication node.
633    pub certificate: SecretKeySelector,
634
635    /// Defines the type of replication to use. Defaults to MutualPull.
636    #[serde(default)]
637    pub _type: ReplicationType,
638
639    /// Select external replication node as the primary node. This means that if database conflicts
640    /// occur the content of the primary will take precedence over the rest of the nodes.
641    /// Note: just one external replication node or replication group can be selected as primary.
642    /// Defaults to false.
643    #[serde(default)]
644    pub automatic_refresh: bool,
645}
646
647// re-implementation of kanidmd_core::repl::config::RepNodeConfig because it is not Serialize and
648// attributes changed
649#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
650#[cfg_attr(feature = "schemars", derive(JsonSchema))]
651#[serde(rename_all = "kebab-case")]
652pub enum ReplicationType {
653    /// Both nodes can initiate replication with each other
654    #[default]
655    MutualPull,
656    /// This node allows the external node to pull changes, but won't initiate
657    AllowPull,
658    /// This node will pull changes from the external node
659    Pull,
660}
661
662fn default_image() -> String {
663    "kanidm/server:latest".to_string()
664}
665
666// re-implementation of sketching::LogLevel because it is not Serialize
667#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
668#[cfg_attr(feature = "schemars", derive(JsonSchema))]
669#[serde(rename_all = "snake_case")]
670pub enum KanidmLogLevel {
671    /// Most verbose logging level, includes all debug and info messages
672    Trace,
673    /// Debug level logging, useful for troubleshooting
674    Debug,
675    /// Standard informational logging level
676    #[default]
677    Info,
678}
679
680fn default_port_name() -> String {
681    "https".to_string()
682}
683
684fn default_false() -> bool {
685    false
686}
687
688#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
689#[cfg_attr(feature = "schemars", derive(JsonSchema))]
690#[serde(rename_all = "kebab-case")]
691pub enum IpFamily {
692    #[default]
693    Ipv4,
694    Ipv6,
695}
696
697/// PersistentVolumeClaimTemplate defines a PVC template with optional metadata.
698/// This allows users to specify a PVC template without requiring metadata to be explicitly set.
699#[derive(Serialize, Deserialize, Clone, Debug, Default)]
700#[cfg_attr(feature = "schemars", derive(JsonSchema))]
701#[serde(rename_all = "camelCase")]
702pub struct PersistentVolumeClaimTemplate {
703    /// Standard object's metadata. More info:
704    /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
705    #[serde(skip_serializing_if = "Option::is_none")]
706    pub metadata: Option<ObjectMeta>,
707
708    /// spec defines the desired characteristics of a volume requested by a pod author. More info:
709    /// https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
710    pub spec: Option<PersistentVolumeClaimSpec>,
711}
712
713impl PersistentVolumeClaimTemplate {
714    /// Convert this template into a k8s-openapi PersistentVolumeClaim
715    pub fn to_persistent_volume_claim(&self) -> PersistentVolumeClaim {
716        PersistentVolumeClaim {
717            metadata: self.metadata.clone().unwrap_or_default(),
718            spec: self.spec.clone(),
719            ..Default::default()
720        }
721    }
722}
723
724#[derive(Serialize, Deserialize, Clone, Debug, Default)]
725#[cfg_attr(feature = "schemars", derive(JsonSchema))]
726#[serde(rename_all = "camelCase")]
727pub struct KanidmStorage {
728    /// EmptyDirVolumeSource to be used by the StatefulSet. If specified, it takes precedence over
729    /// `ephemeral` and `volumeClaimTemplate`.
730    /// More info: https://kubernetes.io/docs/concepts/storage/volumes/#emptydir
731    #[serde(skip_serializing_if = "Option::is_none")]
732    pub empty_dir: Option<EmptyDirVolumeSource>,
733
734    /// EphemeralVolumeSource to be used by the StatefulSet.
735    /// More info: https://kubernetes.io/docs/concepts/storage/ephemeral-volumes/#generic-ephemeral-volumes
736    #[serde(skip_serializing_if = "Option::is_none")]
737    pub ephemeral: Option<EphemeralVolumeSource>,
738
739    /// Defines the PVC spec to be used by the Kanidm StatefulSets. The easiest way to use a volume
740    /// that cannot be automatically provisioned is to use a label selector alongside manually
741    /// created PersistentVolumes.
742    #[serde(skip_serializing_if = "Option::is_none")]
743    pub volume_claim_template: Option<PersistentVolumeClaimTemplate>,
744}
745
746#[derive(Serialize, Deserialize, Clone, Debug, Default)]
747#[cfg_attr(feature = "schemars", derive(JsonSchema))]
748#[serde(rename_all = "camelCase")]
749pub struct KanidmService {
750    /// Annotations is an unstructured key value map stored with a resource that may be set by
751    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
752    /// be preserved when modifying objects.
753    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
754    #[serde(skip_serializing_if = "Option::is_none")]
755    pub annotations: Option<BTreeMap<String, String>>,
756
757    /// Specify the Service's type where the Kanidm Service is exposed
758    /// Please note that some Ingress controllers like https://github.com/kubernetes/ingress-gce
759    /// forces you to expose your Service on a NodePort
760    /// Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and
761    /// LoadBalancer. "ClusterIP" allocates a cluster-internal IP address for load-balancing to
762    /// endpoints. Endpoints are determined by the selector or if that is not specified, by manual
763    /// construction of an Endpoints object or EndpointSlice objects. If clusterIP is "None",
764    /// no virtual IP is allocated and the endpoints are published as a set of endpoints rather
765    /// than a virtual IP. "NodePort" builds on ClusterIP and allocates a port on every node which
766    /// routes to the same endpoints as the clusterIP. "LoadBalancer" builds on NodePort and creates
767    /// an external load-balancer (if supported in the current cloud) which routes to the same
768    /// endpoints as the clusterIP. "ExternalName" aliases this service to the specified
769    /// externalName. Several other fields do not apply to ExternalName services.
770    /// More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
771    #[serde(skip_serializing_if = "Option::is_none")]
772    pub type_: Option<String>,
773
774    /// Map of string keys and values that can be used to organize and categorize (scope and
775    /// select) objects. May match selectors of replication controllers and services.
776    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels
777    #[serde(skip_serializing_if = "Option::is_none")]
778    pub additional_labels: Option<BTreeMap<String, String>>,
779}
780
781#[derive(Serialize, Deserialize, Clone, Debug, Default)]
782#[cfg_attr(feature = "schemars", derive(JsonSchema))]
783#[serde(rename_all = "camelCase")]
784pub struct KanidmIngress {
785    /// Annotations is an unstructured key value map stored with a resource that may be set by
786    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
787    /// be preserved when modifying objects.
788    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
789    #[serde(skip_serializing_if = "Option::is_none")]
790    pub annotations: Option<BTreeMap<String, String>>,
791
792    /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
793    /// implementations use this field to know whether they should be serving this Ingress resource,
794    /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
795    /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
796    /// it was widely supported by Ingress controllers to create a direct binding between Ingress
797    /// controller and Ingress resources. Newly created Ingress resources should prefer using the
798    /// field. However, even though the annotation is officially deprecated, for backwards
799    /// compatibility reasons, ingress controllers should still honor that annotation if present.
800    #[serde(skip_serializing_if = "Option::is_none")]
801    pub ingress_class_name: Option<String>,
802    /// Defines the name of the secret that contains the TLS private key and certificate for the
803    /// server. If not defined, the default will be the Kanidm name appended with `-tls`.
804    #[schemars(extend("x-kubernetes-validations" = [
805        {
806            "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
807            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
808        }
809    ]))]
810    #[serde(skip_serializing_if = "Option::is_none")]
811    pub tls_secret_name: Option<String>,
812    /// Additional Subject Alternative Names (SANs) to include in the TLS certificate.
813    /// The main domain from the Kanidm spec is automatically included.
814    /// This does not add additional hosts to the ingress resource, only certificate SANs.
815    #[serde(skip_serializing_if = "Option::is_none")]
816    pub extra_tls_hosts: Option<BTreeSet<String>>,
817}
818
819#[derive(Serialize, Deserialize, Clone, Debug, Default)]
820#[cfg_attr(feature = "schemars", derive(JsonSchema))]
821#[serde(rename_all = "camelCase")]
822pub struct KanidmRegionIngress {
823    /// Region identifier for this ingress. Used as a subdomain of the main Kanidm domain to route
824    /// traffic for a specific region.
825    pub region: String,
826
827    /// Annotations is an unstructured key value map stored with a resource that may be set by
828    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
829    /// be preserved when modifying objects.
830    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
831    #[serde(skip_serializing_if = "Option::is_none")]
832    pub annotations: Option<BTreeMap<String, String>>,
833
834    /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
835    /// implementations use this field to know whether they should be serving this Ingress resource,
836    /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
837    /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
838    /// it was widely supported by Ingress controllers to create a direct binding between Ingress
839    /// controller and Ingress resources. Newly created Ingress resources should prefer using the
840    /// field. However, even though the annotation is officially deprecated, for backwards
841    /// compatibility reasons, ingress controllers should still honor that annotation if present.
842    #[serde(skip_serializing_if = "Option::is_none")]
843    pub ingress_class_name: Option<String>,
844    /// Defines the name of the secret that contains the TLS private key and certificate for the
845    /// server. If not defined, the default will be the Kanidm name appended with `-region-tls`.
846    #[schemars(extend("x-kubernetes-validations" = [
847        {
848            "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
849            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
850        }
851    ]))]
852    #[serde(skip_serializing_if = "Option::is_none")]
853    pub tls_secret_name: Option<String>,
854}
855
856#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
857#[cfg_attr(feature = "schemars", derive(JsonSchema))]
858#[serde(rename_all = "camelCase")]
859pub struct KanidmGatewayParentRef {
860    /// Group is the group of the referent.
861    /// When unspecified, defaults to "gateway.networking.k8s.io".
862    #[serde(skip_serializing_if = "Option::is_none")]
863    pub group: Option<String>,
864
865    /// Kind is the kind of the referent.
866    /// When unspecified, defaults to "Gateway".
867    #[serde(skip_serializing_if = "Option::is_none")]
868    pub kind: Option<String>,
869
870    /// Name of the referent.
871    pub name: String,
872
873    /// Namespace of the referent. When unspecified, this refers to the local namespace.
874    #[serde(skip_serializing_if = "Option::is_none")]
875    pub namespace: Option<String>,
876
877    /// SectionName is the name of a section within the target resource.
878    /// When specified, this must refer to a named section within the target resource,
879    /// such as a specific listener on a Gateway.
880    #[serde(skip_serializing_if = "Option::is_none")]
881    pub section_name: Option<String>,
882
883    /// Port is the network port this Route targets.
884    #[serde(skip_serializing_if = "Option::is_none")]
885    pub port: Option<u32>,
886}
887
888#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
889#[cfg_attr(feature = "schemars", derive(JsonSchema))]
890#[serde(rename_all = "camelCase")]
891pub struct KanidmGateway {
892    /// ParentRefs references the Gateway(s) that this HTTPRoute should be attached to.
893    /// Each ParentRef must reference a Gateway in the same namespace as the HTTPRoute.
894    #[schemars(extend("x-kubernetes-validations" = [{"message": "At least one ParentRef is required", "rule": "self.size() > 0"}]))]
895    #[validate(length(min = 1))]
896    pub parent_refs: Vec<KanidmGatewayParentRef>,
897
898    /// Hostnames defines a set of hostnames that should match against the HTTP Host
899    /// header to select a HTTPRoute used to process the request.
900    /// When unspecified, defaults to the Kanidm domain (spec.domain).
901    #[serde(skip_serializing_if = "Option::is_none")]
902    pub hostnames: Option<Vec<String>>,
903
904    /// Annotations is an unstructured key value map stored with a resource that may be set by
905    /// external tools to store and retrieve arbitrary metadata.
906    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
907    #[serde(skip_serializing_if = "Option::is_none")]
908    pub annotations: Option<BTreeMap<String, String>>,
909
910    /// Rules defines a list of HTTPRoute rules.
911    /// Each rule consists of conditions for matching an HTTP request,
912    /// filters for processing it, and backend references for forwarding the request.
913    /// When unspecified, a default rule is created that routes all traffic to the Kanidm service.
914    /// This field allows customization of routing behavior, including session persistence,
915    /// timeouts, filters, and advanced matching conditions.
916    /// Note: The sessionPersistence field in rules is experimental and requires
917    /// Gateway API experimental channel support from the implementation.
918    #[serde(skip_serializing_if = "Option::is_none")]
919    pub rules: Option<Vec<HttpRouteRules>>,
920
921    /// BackendTLSPolicy configuration for TLS validation between the Gateway and Kanidm backend service.
922    /// When specified, creates a BackendTLSPolicy resource to validate TLS connections from the Gateway
923    /// to the Kanidm service (port 8443). This is required when using TLS between Gateway and backend.
924    /// When unspecified, no BackendTLSPolicy is created.
925    #[serde(skip_serializing_if = "Option::is_none")]
926    pub backend_tls_policy: Option<KanidmBackendTLSPolicy>,
927}
928
929#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
930#[cfg_attr(feature = "schemars", derive(JsonSchema))]
931#[serde(rename_all = "camelCase")]
932pub struct KanidmBackendTLSPolicy {
933    /// Annotations is an unstructured key value map stored with a resource that may be set by
934    /// external tools to store and retrieve arbitrary metadata.
935    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
936    #[serde(skip_serializing_if = "Option::is_none")]
937    pub annotations: Option<BTreeMap<String, String>>,
938
939    /// Validation contains backend TLS validation configuration.
940    pub validation: KanidmBackendTLSPolicyValidation,
941}
942
943#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
944#[cfg_attr(feature = "schemars", derive(JsonSchema))]
945#[serde(rename_all = "camelCase")]
946pub struct KanidmBackendTLSPolicyValidation {
947    /// Hostname is the hostname used for TLS validation.
948    /// When unspecified, defaults to the Kanidm domain (spec.domain).
949    #[serde(skip_serializing_if = "Option::is_none")]
950    pub hostname: Option<String>,
951
952    /// WellKnownCACertificates specifies the type of CA certificates to use for validation.
953    /// When specified as "System", uses the system's trusted CA certificates.
954    /// This is the most common option for public certificates (e.g., Let's Encrypt).
955    #[serde(skip_serializing_if = "Option::is_none")]
956    pub well_known_ca_certificates: Option<String>,
957
958    /// CACertificateRefs references CA certificates for validation.
959    /// When specified, these certificates are used to validate the backend TLS connection.
960    /// Useful for private/internal certificates not in the system trust store.
961    #[serde(skip_serializing_if = "Option::is_none")]
962    pub ca_certificate_refs: Option<Vec<KanidmBackendTLSPolicyValidationCACertificateRef>>,
963}
964
965#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
966#[cfg_attr(feature = "schemars", derive(JsonSchema))]
967#[serde(rename_all = "camelCase")]
968pub struct KanidmBackendTLSPolicyValidationCACertificateRef {
969    /// Group is the group of the referent.
970    /// When unspecified, defaults to "" (core API group).
971    #[serde(skip_serializing_if = "Option::is_none")]
972    pub group: Option<String>,
973
974    /// Kind is the kind of the referent.
975    /// When unspecified, defaults to "Secret".
976    #[serde(skip_serializing_if = "Option::is_none")]
977    pub kind: Option<String>,
978
979    /// Name of the referent (the Secret containing the CA certificate).
980    pub name: String,
981}
982
983/// Most recent observed status of the Kanidm cluster. Read-only.
984/// More info:
985/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
986#[derive(Serialize, Deserialize, Clone, Debug, Default)]
987#[cfg_attr(feature = "schemars", derive(JsonSchema))]
988#[serde(rename_all = "camelCase")]
989pub struct KanidmStatus {
990    /// Total number of available pods (ready for at least minReadySeconds) targeted by this Kanidm
991    /// deployment.
992    pub available_replicas: i32,
993
994    #[serde(skip_serializing_if = "Option::is_none")]
995    #[cfg_attr(
996        feature = "schemars",
997        schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
998    )]
999    pub conditions: Option<Vec<Condition>>,
1000
1001    /// Total number of non-terminated pods targeted by this Kanidm cluster.
1002    pub replicas: i32,
1003
1004    /// Total number of unavailable pods targeted by this Kanidm cluster.
1005    pub unavailable_replicas: i32,
1006
1007    /// Total number of non-terminated pods targeted by this Kanidm cluster that have the
1008    /// desired version spec.
1009    pub updated_replicas: i32,
1010
1011    /// Status per replica in the Kanidm cluster.
1012    pub replica_statuses: Vec<KanidmReplicaStatus>,
1013
1014    /// Ready vs desired replicas.
1015    pub replica_column: String,
1016
1017    /// Admin users secret name.
1018    pub secret_name: Option<String>,
1019
1020    /// The current version of the Kanidm server.
1021    pub version: Option<KanidmVersionStatus>,
1022
1023    /// Status of the domain appearance image.
1024    pub domain_appearance_image: Option<DomainAppearanceImageStatus>,
1025
1026    /// Status of the mail sender deployment.
1027    #[serde(skip_serializing_if = "Option::is_none")]
1028    pub mail_sender: Option<MailSenderStatus>,
1029}
1030
1031#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
1032#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1033#[serde(rename_all = "camelCase")]
1034pub struct MailSenderStatus {
1035    /// Name of the service account in Kanidm for mail sending.
1036    /// Format: `<kanidm-name>-mail-sender`
1037    pub service_account_name: String,
1038
1039    /// Name of the Kubernetes secret containing the API token.
1040    /// Format: `<kanidm-name>-mail-sender-token`
1041    pub token_secret_name: String,
1042
1043    /// Name of the Deployment running the mail sender.
1044    /// Format: `<kanidm-name>-mail-sender`
1045    pub deployment_name: String,
1046
1047    /// Name of the ConfigMap containing mail sender configuration.
1048    /// Format: `<kanidm-name>-mail-sender-config`
1049    pub config_map_name: String,
1050
1051    /// The unique identifier for the API token in Kanidm, used for management operations.
1052    #[serde(skip_serializing_if = "Option::is_none")]
1053    pub token_id: Option<String>,
1054
1055    /// Whether the mail sender deployment is ready.
1056    pub ready: bool,
1057}
1058
1059#[derive(Serialize, Deserialize, Clone, Debug)]
1060#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1061#[serde(rename_all = "camelCase")]
1062pub struct KanidmReplicaStatus {
1063    /// Pod name: replica group StatefulSet name plus the pod index.
1064    pub pod_name: String,
1065
1066    /// StatefulSet name: Kanidm name plus the replica group name.
1067    pub statefulset_name: String,
1068
1069    /// The current state of the replica.
1070    pub state: KanidmReplicaState,
1071}
1072
1073#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
1074#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1075#[serde(rename_all = "camelCase")]
1076pub enum KanidmReplicaState {
1077    Ready,
1078    Pending,
1079    CertificateExpiring,
1080    CertificateHostInvalid,
1081}
1082
1083#[derive(Serialize, Deserialize, Clone, Debug)]
1084#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1085#[serde(rename_all = "camelCase")]
1086pub struct KanidmVersionStatus {
1087    pub image_tag: String,
1088
1089    pub upgrade_check_result: KanidmUpgradeCheckResult,
1090
1091    #[serde(default)]
1092    pub compatibility_result: VersionCompatibilityResult,
1093}
1094
1095#[derive(Serialize, Deserialize, Clone, PartialEq, Debug, Default)]
1096#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1097#[serde(rename_all = "snake_case")]
1098pub enum VersionCompatibilityResult {
1099    #[default]
1100    Compatible,
1101    Incompatible,
1102    /// Compatibility was not evaluated because upgrade checks are disabled.
1103    NotChecked,
1104}
1105
1106#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
1107#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1108#[serde(rename_all = "snake_case")]
1109pub enum KanidmUpgradeCheckResult {
1110    Passed,
1111    Failed,
1112    /// The pre-upgrade check was intentionally skipped.
1113    Skipped,
1114}
1115
1116#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
1117#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1118#[serde(rename_all = "camelCase")]
1119pub struct DomainAppearanceImageStatus {
1120    /// The URL from which the image was last fetched.
1121    pub url: String,
1122    /// ETag header from the last fetch (for change detection).
1123    #[serde(skip_serializing_if = "Option::is_none")]
1124    pub etag: Option<String>,
1125    /// Last-Modified header from the last fetch.
1126    #[serde(skip_serializing_if = "Option::is_none")]
1127    pub last_modified: Option<String>,
1128    /// Content-Length from the last fetch.
1129    #[serde(skip_serializing_if = "Option::is_none")]
1130    pub content_length: Option<u64>,
1131    /// Hash of the image content (SHA-256, for validation).
1132    #[serde(skip_serializing_if = "Option::is_none")]
1133    pub content_hash: Option<String>,
1134}
1135
1136#[cfg(test)]
1137mod tests {
1138    use super::*;
1139    use k8s_openapi::api::core::v1::PersistentVolumeClaimSpec;
1140    use serde_json::json;
1141
1142    #[test]
1143    fn test_pvc_template_optional_metadata() {
1144        // Test that we can create a PVC template without metadata
1145        let pvc_template = PersistentVolumeClaimTemplate {
1146            metadata: None,
1147            spec: Some(PersistentVolumeClaimSpec::default()),
1148        };
1149
1150        // Test that it can be converted to a k8s PVC
1151        let k8s_pvc = pvc_template.to_persistent_volume_claim();
1152        assert_eq!(k8s_pvc.metadata, ObjectMeta::default());
1153        assert_eq!(k8s_pvc.spec, pvc_template.spec);
1154    }
1155
1156    #[test]
1157    fn test_pvc_template_with_metadata() {
1158        let custom_metadata = ObjectMeta {
1159            name: Some("test-pvc".to_string()),
1160            labels: Some([("app".to_string(), "test".to_string())].into()),
1161            ..ObjectMeta::default()
1162        };
1163
1164        // Test that we can create a PVC template with metadata
1165        let pvc_template = PersistentVolumeClaimTemplate {
1166            metadata: Some(custom_metadata.clone()),
1167            spec: Some(PersistentVolumeClaimSpec::default()),
1168        };
1169
1170        // Test that it can be converted to a k8s PVC
1171        let k8s_pvc = pvc_template.to_persistent_volume_claim();
1172        assert_eq!(k8s_pvc.metadata, custom_metadata);
1173        assert_eq!(k8s_pvc.spec, pvc_template.spec);
1174    }
1175
1176    #[test]
1177    fn test_kanidm_version_status_backward_compatible() {
1178        let legacy_payload = json!({
1179            "imageTag": "1.9.0",
1180            "upgradeCheckResult": "passed"
1181        });
1182
1183        let status: KanidmVersionStatus =
1184            serde_json::from_value(legacy_payload).expect("legacy status should deserialize");
1185
1186        assert_eq!(status.image_tag, "1.9.0");
1187        assert_eq!(
1188            status.upgrade_check_result,
1189            KanidmUpgradeCheckResult::Passed
1190        );
1191        assert_eq!(
1192            status.compatibility_result,
1193            VersionCompatibilityResult::Compatible
1194        );
1195    }
1196}