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