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