Skip to main content

kaniop_operator/kanidm/
crd.rs

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