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