kaniop_operator/kanidm/
crd.rs

1use crate::crd::is_default;
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use k8s_openapi::api::apps::v1::StatefulSetPersistentVolumeClaimRetentionPolicy;
6use k8s_openapi::api::core::v1::{
7    Affinity, Container, EmptyDirVolumeSource, EnvVar, EphemeralVolumeSource, HostAlias,
8    PersistentVolumeClaim, PersistentVolumeClaimSpec, PodDNSConfig, PodSecurityContext,
9    ResourceRequirements, SecretKeySelector, Toleration, TopologySpreadConstraint, Volume,
10    VolumeMount,
11};
12use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, LabelSelector};
13use kube::CustomResource;
14use kube::api::ObjectMeta;
15#[cfg(feature = "schemars")]
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18
19/// Specification of the desired behavior of the Kanidm cluster. More info:
20/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
21#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, Default)]
22#[cfg_attr(feature = "schemars", derive(JsonSchema))]
23// workaround: '`' character is not allowed in the kube `doc` attribute during doctests
24#[cfg_attr(
25    not(doctest),
26    kube(
27        doc = r#"The `Kanidm` custom resource definition (CRD) defines a desired [Kanidm](https://kanidm.com)
28    setup to run in a Kubernetes cluster. It allows to specify many options such as the number of replicas,
29    persistent storage, and many more.
30
31    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.
32    "#
33    )
34)]
35#[kube(
36    category = "kaniop",
37    group = "kaniop.rs",
38    version = "v1beta1",
39    kind = "Kanidm",
40    plural = "kanidms",
41    singular = "kanidm",
42    shortname = "idm",
43    namespaced,
44    status = "KanidmStatus",
45    printcolumn = r#"{"name":"Replicas","type":"string","description":"The number of replicas: ready/desired","jsonPath":".status.replicaColumn"}"#,
46    printcolumn = r#"{"name":"Domain","type":"string","jsonPath":".spec.domain"}"#,
47    printcolumn = r#"{"name":"Secret","type":"string","jsonPath":".status.secretName"}"#,
48    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#,
49    derive = "Default"
50)]
51#[serde(rename_all = "camelCase")]
52pub struct KanidmSpec {
53    /// The DNS domain name of the server. This is used in a number of security-critical
54    /// contexts such as webauthn, so it *must* match your DNS hostname. It is used to
55    /// create security principal names such as `william@idm.example.com` so that in a
56    /// (future) trust configuration it is possible to have unique Security Principal
57    /// Names (spns) throughout the topology.
58    ///
59    /// This cannot be changed after creation.
60    #[schemars(extend("x-kubernetes-validations" = [
61        {
62            "message": "Domain cannot be changed.",
63            "rule": "self == oldSelf"},
64        {
65            "message": "Domain must be a valid DNS name",
66            "rule": "self.matches(r'^([a-z0-9]([-a-z0-9]*[a-z0-9])?\\.)*[a-z0-9]([-a-z0-9]*[a-z0-9])?$')"
67        }
68    ]))]
69    pub domain: String,
70
71    /// The origin for webauthn. This is the url to the server,
72    /// with the port included if it is non-standard (any port
73    /// except 443). This must match or be a descendent of the
74    /// domain name you configure above. If these two items are
75    /// not consistent, the server WILL refuse to start!
76    /// origin = "https://idm.example.com"
77    /// # OR
78    /// origin = "https://idm.example.com:8443"
79    ///
80    /// Defaults to `https://<domain>` if not specified.
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub origin: Option<String>,
83
84    /// Different group of replicas with specific configuration as role, resources, affinity rules, and more.
85    /// Each group will be deployed as a separate StatefulSet.
86    #[schemars(extend("x-kubernetes-validations" = [{"message": "At least one ReplicaGroup is required", "rule": "self.size() > 0"}]))]
87    // max is defined for allowing CEL expression in validation admission policy estimate
88    // expression costs
89    #[validate(length(min = 1, max = 100))]
90    pub replica_groups: Vec<ReplicaGroup>,
91
92    /// List of external replication nodes. This is used to configure replication between
93    /// different Kanidm clusters.
94    ///
95    /// **WARNING**: `admin` and `idm_admin` passwords are going to be reset.
96    // max is defined for allowing CEL expression in validation admission policy estimate
97    // expression costs.
98    #[validate(length(max = 100))]
99    #[serde(default, skip_serializing_if = "is_default")]
100    pub external_replication_nodes: Vec<ExternalReplicationNode>,
101
102    /// Container image name. More info: https://kubernetes.io/docs/concepts/containers/images
103    /// This field is optional to allow higher level config management to default or override
104    /// container images in workload controllers like StatefulSets.
105    #[serde(default = "default_image", skip_serializing_if = "is_default")]
106    pub image: String,
107
108    /// Before starting an upgrade, perform pre-upgrade checks to ensure that data can be
109    /// safely migrated to the new version. If pre-checks fail, image change is disallowed.
110    /// If set to true, upgrade pre-checks are skipped. Defaults to false.
111    #[serde(default, skip_serializing_if = "is_default")]
112    pub disable_upgrade_checks: bool,
113
114    /// Log level for Kanidm.
115    #[serde(default, skip_serializing_if = "is_default")]
116    pub log_level: KanidmLogLevel,
117
118    /// Port name used for the pods and governing service. Defaults to https.
119    #[serde(default = "default_port_name", skip_serializing_if = "is_default")]
120    pub port_name: String,
121
122    /// Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag
123    /// is specified, or IfNotPresent otherwise. Cannot be updated.
124    /// More info: https://kubernetes.io/docs/concepts/containers/images#updating-images
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub image_pull_policy: Option<String>,
127
128    /// List of environment variables to set in the `kanidm` container.
129    /// This can be used to set Kanidm configuration options.
130    /// More info: https://kanidm.github.io/kanidm/master/server_configuration.html
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub env: Option<Vec<EnvVar>>,
133
134    /// Namespaces to match for KanidmOAuth2Clients discovery.
135    ///
136    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
137    /// - Empty selector `{}`: matches all namespaces in the cluster
138    /// - Selector with labels: matches namespaces with matching labels
139    ///
140    /// Example for all namespaces: `oauth2ClientNamespaceSelector: {}`
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub oauth2_client_namespace_selector: Option<LabelSelector>,
143
144    /// Namespaces to match for KanidmGroups discovery.
145    ///
146    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
147    /// - Empty selector `{}`: matches all namespaces in the cluster
148    /// - Selector with labels: matches namespaces with matching labels
149    ///
150    /// Example for all namespaces: `groupNamespaceSelector: {}`
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub group_namespace_selector: Option<LabelSelector>,
153
154    /// Namespaces to match for KanidmPersonAccounts discovery.
155    ///
156    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
157    /// - Empty selector `{}`: matches all namespaces in the cluster
158    /// - Selector with labels: matches namespaces with matching labels
159    ///
160    /// Example for all namespaces: `personNamespaceSelector: {}`
161    #[serde(skip_serializing_if = "Option::is_none")]
162    pub person_namespace_selector: Option<LabelSelector>,
163
164    /// Namespaces to match for KanidmServiceAccounts discovery.
165    ///
166    /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
167    /// - Empty selector `{}`: matches all namespaces in the cluster
168    /// - Selector with labels: matches namespaces with matching labels
169    ///
170    /// Example for all namespaces: `serviceAccountNamespaceSelector: {}`
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub service_account_namespace_selector: Option<LabelSelector>,
173
174    /// StorageSpec defines the configured storage for a group Kanidm servers.
175    /// If no storage option is specified, then by default an
176    /// [EmptyDir](https://kubernetes.io/docs/concepts/storage/volumes/#emptydir) will be used.
177    ///
178    /// If multiple storage options are specified, priority will be given as follows:
179    ///  1. emptyDir
180    ///  2. ephemeral
181    ///  3. volumeClaimTemplate
182    ///
183    /// Note: Kaniop does not resize PVCs until Kubernetes fix
184    /// [KEP-4650](https://github.com/kubernetes/enhancements/issues/4650).
185    /// Although, StatefulSet will be recreated if the PVC is resized.
186    #[serde(skip_serializing_if = "Option::is_none")]
187    pub storage: Option<KanidmStorage>,
188
189    /// Defines the port name used for the LDAP service. If not defined, LDAP service will not be
190    /// configured. Service port will be `3636`.
191    ///
192    /// StartTLS is not supported due to security risks such as credential leakage and MITM attacks
193    /// that are fundamental in how StartTLS works. StartTLS can not be repaired to prevent this.
194    /// LDAPS is the only secure method of communicating to any LDAP server. Kanidm will use its
195    /// certificates for both HTTPS and LDAPS.
196    #[serde(skip_serializing_if = "Option::is_none")]
197    pub ldap_port_name: Option<String>,
198
199    /// Specifies the name of the secret holding the TLS private key and certificate for the server.
200    /// If not provided, the ingress secret will be used. The server will not start if the secret
201    /// is missing.
202    #[schemars(extend("x-kubernetes-validations" = [
203        {
204            "message": "tlsSecretName must be a valid Kubernetes resource name.",
205            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
206        }
207    ]))]
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub tls_secret_name: Option<String>,
210
211    /// Service defines the service configuration for the Kanidm server.
212    #[serde(skip_serializing_if = "Option::is_none")]
213    pub service: Option<KanidmService>,
214
215    /// Ingress configuration for the Kanidm cluster.
216    ///
217    /// The domain specified in the Kanidm spec will be used as the ingress host.
218    /// TLS is required and must be configured at the ingress controller level (termination or
219    /// passthrough).
220    /// When running multiple replicas, configure session affinity on your ingress controller to
221    /// ensure proper session handling.
222    #[serde(skip_serializing_if = "Option::is_none")]
223    pub ingress: Option<KanidmIngress>,
224
225    /// Region-specific ingress configuration for multi-region deployments.
226    ///
227    /// Allows defining ingress settings for a specific region, using a subdomain of the main
228    /// Kanidm domain.
229    /// TLS is required and must be configured at the ingress controller level (termination or
230    /// passthrough).
231    /// For multi-region deployments, configure session affinity on your ingress controller to ensure proper session handling.
232    #[serde(skip_serializing_if = "Option::is_none")]
233    pub region_ingress: Option<KanidmRegionIngress>,
234
235    /// Volumes allows the configuration of additional volumes on the output StatefulSet
236    /// definition. Volumes specified will be appended to other volumes that are generated as a
237    /// result of StorageSpec objects.
238    #[serde(skip_serializing_if = "Option::is_none")]
239    pub volumes: Option<Vec<Volume>>,
240
241    /// VolumeMounts allows the configuration of additional VolumeMounts.
242    ///
243    /// VolumeMounts will be appended to other VolumeMounts in the kanidm' container, that are
244    /// generated as a result of StorageSpec objects.
245    #[serde(skip_serializing_if = "Option::is_none")]
246    pub volume_mounts: Option<Vec<VolumeMount>>,
247
248    /// The field controls if and how PVCs are deleted during the lifecycle of a StatefulSet.
249    /// The default behavior is all PVCs are retained.
250    /// This is a beta field from 1.27. It requires enabling the StatefulSetAutoDeletePVC feature
251    /// gate.
252    #[serde(skip_serializing_if = "Option::is_none")]
253    pub persistent_volume_claim_retention_policy:
254        Option<StatefulSetPersistentVolumeClaimRetentionPolicy>,
255
256    /// SecurityContext holds pod-level security attributes and common container settings.
257    /// This defaults to the default PodSecurityContext.
258    #[serde(skip_serializing_if = "Option::is_none")]
259    pub security_context: Option<PodSecurityContext>,
260
261    /// Defines the DNS policy for the pods.
262    #[serde(skip_serializing_if = "Option::is_none")]
263    pub dns_policy: Option<String>,
264
265    /// Defines the DNS configuration for the pods.
266    #[serde(skip_serializing_if = "Option::is_none")]
267    pub dns_config: Option<PodDNSConfig>,
268
269    /// Containers allows injecting additional containers or modifying operator generated
270    /// containers. This can be used to allow adding an authentication proxy to the Pods or to
271    /// change the behavior of an operator generated container. Containers described here modify
272    /// an operator generated container if they share the same name and modifications are done
273    /// via a strategic merge patch.
274    ///
275    /// The name of container managed by the operator is: kanidm
276    ///
277    /// Overriding containers is entirely outside the scope of what the maintainers will support
278    /// and by doing so, you accept that this behaviour may break at any time without notice.
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub containers: Option<Vec<Container>>,
281
282    /// InitContainers allows injecting initContainers to the Pod definition. Those can be used to
283    /// e.g. fetch secrets for injection into the Kanidm configuration from external sources.
284    /// Any errors during the execution of an initContainer will lead to a restart of the Pod.
285    /// More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
286    /// InitContainers described here modify an operator generated init containers if they share
287    /// the same name and modifications are done via a strategic merge patch.
288    ///
289    /// The names of init container name managed by the operator are: * init-config-reloader.
290    ///
291    /// Overriding init containers is entirely outside the scope of what the maintainers will
292    /// support and by doing so, you accept that this behaviour may break at any time without notice.
293    #[serde(skip_serializing_if = "Option::is_none")]
294    pub init_containers: Option<Vec<Container>>,
295
296    /// Minimum number of seconds for which a newly created Pod should be ready without any of its
297    /// container crashing for it to be considered available. Defaults to 0 (pod will be considered
298    /// available as soon as it is ready)
299    #[serde(skip_serializing_if = "Option::is_none")]
300    pub min_ready_seconds: Option<i32>,
301
302    /// Optional list of hosts and IPs that will be injected into the Pod's hosts file if specified.
303    #[serde(skip_serializing_if = "Option::is_none")]
304    pub host_aliases: Option<Vec<HostAlias>>,
305
306    /// Use the host's network namespace if true.
307    ///
308    /// Make sure to understand the security implications if you want to enable it
309    /// (https://kubernetes.io/docs/concepts/configuration/overview/).
310    ///
311    /// When hostNetwork is enabled, this will set the DNS policy to ClusterFirstWithHostNet
312    /// automatically.
313    #[serde(skip_serializing_if = "Option::is_none")]
314    pub host_network: Option<bool>,
315}
316
317#[derive(Serialize, Deserialize, Clone, Debug, Default)]
318#[cfg_attr(feature = "schemars", derive(JsonSchema))]
319#[serde(rename_all = "camelCase")]
320pub struct ReplicaGroup {
321    /// The name of the replica group.
322    pub name: String,
323
324    /// Number of replicas to deploy for a Kanidm replica group.
325    pub replicas: i32,
326
327    /// The Kanidm role of each node in the replica group.
328    #[serde(default)]
329    pub role: KanidmServerRole,
330
331    /// If true, the first pod of the StatefulSet will be considered as the primary node.
332    /// The rest of the nodes are considered as secondary nodes.
333    /// This means that if database issues occur the content of the primary will take precedence
334    /// over the rest of the nodes.
335    /// This is only valid for the WriteReplica role and can only be set to true for one
336    /// replica group or external replication node.
337    /// Defaults to false.
338    #[serde(default)]
339    pub primary_node: bool,
340
341    /// Service configuration for the replica group.
342    /// - If not specified, pods use the default StatefulSet DNS for internal communication.
343    /// - If specified, a Kubernetes Service of type LoadBalancer is created to expose replica
344    ///   group pods externally.
345    ///   This enables cross-cluster or multi-region access to replicas.
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub services: Option<KanidmReplicaGroupServices>,
348
349    /// Annotations to add to the StatefulSet created for this replica group.
350    ///
351    /// Each replica group gets its own StatefulSet; these annotations are applied only to the
352    /// StatefulSet for this group.
353    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
354    #[serde(skip_serializing_if = "Option::is_none")]
355    pub stateful_set_annotations: Option<BTreeMap<String, String>>,
356
357    /// Defines the resources requests and limits of the kanidm' container.
358    #[serde(skip_serializing_if = "Option::is_none")]
359    pub resources: Option<ResourceRequirements>,
360
361    /// Defines on which Nodes the Pods are scheduled.
362    #[serde(skip_serializing_if = "Option::is_none")]
363    pub node_selector: Option<BTreeMap<String, String>>,
364
365    /// Defines the Pods' affinity scheduling rules if specified.
366    #[serde(skip_serializing_if = "Option::is_none")]
367    pub affinity: Option<Affinity>,
368
369    /// Defines the Pods' tolerations if specified.
370    #[serde(skip_serializing_if = "Option::is_none")]
371    pub tolerations: Option<Vec<Toleration>>,
372
373    /// Defines the pod's topology spread constraints if specified.
374    #[serde(skip_serializing_if = "Option::is_none")]
375    pub topology_spread_constraints: Option<Vec<TopologySpreadConstraint>>,
376}
377
378// re-implementation of kanidmd_core::config::ServerRole because it is not Serialize
379#[derive(Serialize, Deserialize, Clone, Debug, Default)]
380#[cfg_attr(feature = "schemars", derive(JsonSchema))]
381#[serde(rename_all = "snake_case")]
382pub enum KanidmServerRole {
383    /// Full read-write replica with web UI
384    #[default]
385    WriteReplica,
386    /// Read-write replica without the web UI
387    WriteReplicaNoUi,
388    /// Read-only replica for load balancing read operations.
389    /// **WARNING**: read_only_replica is currently a placeholder and not yet implemented in Kanidm.
390    /// Using this role may lead to divergent data across replicas. Kaniop uses it to configure the
391    /// replication type to pull.
392    ReadOnlyReplica,
393}
394
395#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
396#[cfg_attr(feature = "schemars", derive(JsonSchema))]
397#[serde(rename_all = "camelCase")]
398pub struct KanidmReplicaGroupServices {
399    /// Annotations to apply to each Service for replica group pods.
400    ///
401    /// Available template variables:
402    /// - `{replica_index}`: Index of the pod in the replica group
403    /// - `{pod_name}`: Name of the pod
404    /// - `{domain}`: Domain name
405    #[serde(skip_serializing_if = "Option::is_none")]
406    pub annotations_template: Option<BTreeMap<String, String>>,
407
408    /// Hostname template for each Service created for replica group pods.
409    ///
410    /// Available template variables:
411    /// - `{replica_index}`: Index of the pod in the replica group
412    /// - `{pod_name}`: Name of the pod
413    /// - `{domain}`: Domain name
414    ///
415    /// If not set, the replication hostname defaults to the Service's external IP.
416    #[serde(skip_serializing_if = "Option::is_none")]
417    pub replication_hostname_template: Option<String>,
418
419    /// Map of string keys and values that can be used to organize and categorize (scope and
420    /// select) objects. May match selectors of replication controllers and services.
421    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels
422    #[serde(skip_serializing_if = "Option::is_none")]
423    pub additional_labels: Option<BTreeMap<String, String>>,
424}
425
426#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
427#[cfg_attr(feature = "schemars", derive(JsonSchema))]
428#[serde(rename_all = "camelCase")]
429pub struct ExternalReplicationNode {
430    /// Name of the external replication node. This just have internal use.
431    pub name: String,
432
433    /// The hostname of the external replication node.
434    pub hostname: String,
435
436    /// The replication port of the external replication node.
437    pub port: i32,
438
439    /// Defines the secret that contains the identity certificate of the external replication node.
440    pub certificate: SecretKeySelector,
441
442    /// Defines the type of replication to use. Defaults to MutualPull.
443    #[serde(default)]
444    pub _type: ReplicationType,
445
446    /// Select external replication node as the primary node. This means that if database conflicts
447    /// occur the content of the primary will take precedence over the rest of the nodes.
448    /// Note: just one external replication node or replication group can be selected as primary.
449    /// Defaults to false.
450    #[serde(default)]
451    pub automatic_refresh: bool,
452}
453
454// re-implementation of kanidmd_core::repl::config::RepNodeConfig because it is not Serialize and
455// attributes changed
456#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
457#[cfg_attr(feature = "schemars", derive(JsonSchema))]
458#[serde(rename_all = "kebab-case")]
459pub enum ReplicationType {
460    /// Both nodes can initiate replication with each other
461    #[default]
462    MutualPull,
463    /// This node allows the external node to pull changes, but won't initiate
464    AllowPull,
465    /// This node will pull changes from the external node
466    Pull,
467}
468
469fn default_image() -> String {
470    "kanidm/server:latest".to_string()
471}
472
473// re-implementation of sketching::LogLevel because it is not Serialize
474#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
475#[cfg_attr(feature = "schemars", derive(JsonSchema))]
476#[serde(rename_all = "snake_case")]
477pub enum KanidmLogLevel {
478    /// Most verbose logging level, includes all debug and info messages
479    Trace,
480    /// Debug level logging, useful for troubleshooting
481    Debug,
482    /// Standard informational logging level
483    #[default]
484    Info,
485}
486
487fn default_port_name() -> String {
488    "https".to_string()
489}
490
491/// PersistentVolumeClaimTemplate defines a PVC template with optional metadata.
492/// This allows users to specify a PVC template without requiring metadata to be explicitly set.
493#[derive(Serialize, Deserialize, Clone, Debug, Default)]
494#[cfg_attr(feature = "schemars", derive(JsonSchema))]
495#[serde(rename_all = "camelCase")]
496pub struct PersistentVolumeClaimTemplate {
497    /// Standard object's metadata. More info:
498    /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
499    #[serde(skip_serializing_if = "Option::is_none")]
500    pub metadata: Option<ObjectMeta>,
501
502    /// spec defines the desired characteristics of a volume requested by a pod author. More info:
503    /// https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
504    pub spec: Option<PersistentVolumeClaimSpec>,
505}
506
507impl PersistentVolumeClaimTemplate {
508    /// Convert this template into a k8s-openapi PersistentVolumeClaim
509    pub fn to_persistent_volume_claim(&self) -> PersistentVolumeClaim {
510        PersistentVolumeClaim {
511            metadata: self.metadata.clone().unwrap_or_default(),
512            spec: self.spec.clone(),
513            ..Default::default()
514        }
515    }
516}
517
518#[derive(Serialize, Deserialize, Clone, Debug, Default)]
519#[cfg_attr(feature = "schemars", derive(JsonSchema))]
520#[serde(rename_all = "camelCase")]
521pub struct KanidmStorage {
522    /// EmptyDirVolumeSource to be used by the StatefulSet. If specified, it takes precedence over
523    /// `ephemeral` and `volumeClaimTemplate`.
524    /// More info: https://kubernetes.io/docs/concepts/storage/volumes/#emptydir
525    #[serde(skip_serializing_if = "Option::is_none")]
526    pub empty_dir: Option<EmptyDirVolumeSource>,
527
528    /// EphemeralVolumeSource to be used by the StatefulSet.
529    /// More info: https://kubernetes.io/docs/concepts/storage/ephemeral-volumes/#generic-ephemeral-volumes
530    #[serde(skip_serializing_if = "Option::is_none")]
531    pub ephemeral: Option<EphemeralVolumeSource>,
532
533    /// Defines the PVC spec to be used by the Kanidm StatefulSets. The easiest way to use a volume
534    /// that cannot be automatically provisioned is to use a label selector alongside manually
535    /// created PersistentVolumes.
536    #[serde(skip_serializing_if = "Option::is_none")]
537    pub volume_claim_template: Option<PersistentVolumeClaimTemplate>,
538}
539
540#[derive(Serialize, Deserialize, Clone, Debug, Default)]
541#[cfg_attr(feature = "schemars", derive(JsonSchema))]
542#[serde(rename_all = "camelCase")]
543pub struct KanidmService {
544    /// Annotations is an unstructured key value map stored with a resource that may be set by
545    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
546    /// be preserved when modifying objects.
547    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
548    #[serde(skip_serializing_if = "Option::is_none")]
549    pub annotations: Option<BTreeMap<String, String>>,
550
551    /// Specify the Service's type where the Kanidm Service is exposed
552    /// Please note that some Ingress controllers like https://github.com/kubernetes/ingress-gce
553    /// forces you to expose your Service on a NodePort
554    /// Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and
555    /// LoadBalancer. "ClusterIP" allocates a cluster-internal IP address for load-balancing to
556    /// endpoints. Endpoints are determined by the selector or if that is not specified, by manual
557    /// construction of an Endpoints object or EndpointSlice objects. If clusterIP is "None",
558    /// no virtual IP is allocated and the endpoints are published as a set of endpoints rather
559    /// than a virtual IP. "NodePort" builds on ClusterIP and allocates a port on every node which
560    /// routes to the same endpoints as the clusterIP. "LoadBalancer" builds on NodePort and creates
561    /// an external load-balancer (if supported in the current cloud) which routes to the same
562    /// endpoints as the clusterIP. "ExternalName" aliases this service to the specified
563    /// externalName. Several other fields do not apply to ExternalName services.
564    /// More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
565    #[serde(skip_serializing_if = "Option::is_none")]
566    pub type_: Option<String>,
567}
568
569#[derive(Serialize, Deserialize, Clone, Debug, Default)]
570#[cfg_attr(feature = "schemars", derive(JsonSchema))]
571#[serde(rename_all = "camelCase")]
572pub struct KanidmIngress {
573    /// Annotations is an unstructured key value map stored with a resource that may be set by
574    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
575    /// be preserved when modifying objects.
576    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
577    #[serde(skip_serializing_if = "Option::is_none")]
578    pub annotations: Option<BTreeMap<String, String>>,
579
580    /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
581    /// implementations use this field to know whether they should be serving this Ingress resource,
582    /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
583    /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
584    /// it was widely supported by Ingress controllers to create a direct binding between Ingress
585    /// controller and Ingress resources. Newly created Ingress resources should prefer using the
586    /// field. However, even though the annotation is officially deprecated, for backwards
587    /// compatibility reasons, ingress controllers should still honor that annotation if present.
588    #[serde(skip_serializing_if = "Option::is_none")]
589    pub ingress_class_name: Option<String>,
590    /// Defines the name of the secret that contains the TLS private key and certificate for the
591    /// server. If not defined, the default will be the Kanidm name appended with `-tls`.
592    #[schemars(extend("x-kubernetes-validations" = [
593        {
594            "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
595            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
596        }
597    ]))]
598    #[serde(skip_serializing_if = "Option::is_none")]
599    pub tls_secret_name: Option<String>,
600    /// Additional Subject Alternative Names (SANs) to include in the TLS certificate.
601    /// The main domain from the Kanidm spec is automatically included.
602    /// This does not add additional hosts to the ingress resource, only certificate SANs.
603    #[serde(skip_serializing_if = "Option::is_none")]
604    pub extra_tls_hosts: Option<BTreeSet<String>>,
605}
606
607#[derive(Serialize, Deserialize, Clone, Debug, Default)]
608#[cfg_attr(feature = "schemars", derive(JsonSchema))]
609#[serde(rename_all = "camelCase")]
610pub struct KanidmRegionIngress {
611    /// Region identifier for this ingress. Used as a subdomain of the main Kanidm domain to route
612    /// traffic for a specific region.
613    pub region: String,
614
615    /// Annotations is an unstructured key value map stored with a resource that may be set by
616    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
617    /// be preserved when modifying objects.
618    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
619    #[serde(skip_serializing_if = "Option::is_none")]
620    pub annotations: Option<BTreeMap<String, String>>,
621
622    /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
623    /// implementations use this field to know whether they should be serving this Ingress resource,
624    /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
625    /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
626    /// it was widely supported by Ingress controllers to create a direct binding between Ingress
627    /// controller and Ingress resources. Newly created Ingress resources should prefer using the
628    /// field. However, even though the annotation is officially deprecated, for backwards
629    /// compatibility reasons, ingress controllers should still honor that annotation if present.
630    #[serde(skip_serializing_if = "Option::is_none")]
631    pub ingress_class_name: Option<String>,
632    /// Defines the name of the secret that contains the TLS private key and certificate for the
633    /// server. If not defined, the default will be the Kanidm name appended with `-region-tls`.
634    #[schemars(extend("x-kubernetes-validations" = [
635        {
636            "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
637            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
638        }
639    ]))]
640    #[serde(skip_serializing_if = "Option::is_none")]
641    pub tls_secret_name: Option<String>,
642}
643
644/// Most recent observed status of the Kanidm cluster. Read-only.
645/// More info:
646/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
647#[derive(Serialize, Deserialize, Clone, Debug, Default)]
648#[cfg_attr(feature = "schemars", derive(JsonSchema))]
649#[serde(rename_all = "camelCase")]
650pub struct KanidmStatus {
651    /// Total number of available pods (ready for at least minReadySeconds) targeted by this Kanidm
652    /// deployment.
653    pub available_replicas: i32,
654
655    #[serde(skip_serializing_if = "Option::is_none")]
656    pub conditions: Option<Vec<Condition>>,
657
658    /// Total number of non-terminated pods targeted by this Kanidm cluster.
659    pub replicas: i32,
660
661    /// Total number of unavailable pods targeted by this Kanidm cluster.
662    pub unavailable_replicas: i32,
663
664    /// Total number of non-terminated pods targeted by this Kanidm cluster that have the
665    /// desired version spec.
666    pub updated_replicas: i32,
667
668    /// Status per replica in the Kanidm cluster.
669    pub replica_statuses: Vec<KanidmReplicaStatus>,
670
671    /// Ready vs desired replicas.
672    pub replica_column: String,
673
674    /// Admin users secret name.
675    pub secret_name: Option<String>,
676
677    /// The current version of the Kanidm server.
678    pub version: Option<KanidmVersionStatus>,
679}
680
681#[derive(Serialize, Deserialize, Clone, Debug)]
682#[cfg_attr(feature = "schemars", derive(JsonSchema))]
683#[serde(rename_all = "camelCase")]
684pub struct KanidmReplicaStatus {
685    /// Pod name: replica group StatefulSet name plus the pod index.
686    pub pod_name: String,
687
688    /// StatefulSet name: Kanidm name plus the replica group name.
689    pub statefulset_name: String,
690
691    /// The current state of the replica.
692    pub state: KanidmReplicaState,
693}
694
695#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
696#[cfg_attr(feature = "schemars", derive(JsonSchema))]
697#[serde(rename_all = "camelCase")]
698pub enum KanidmReplicaState {
699    Ready,
700    Pending,
701    CertificateExpiring,
702    CertificateHostInvalid,
703}
704
705#[derive(Serialize, Deserialize, Clone, Debug)]
706#[cfg_attr(feature = "schemars", derive(JsonSchema))]
707#[serde(rename_all = "camelCase")]
708pub struct KanidmVersionStatus {
709    /// The current image of the Kanidm server.
710    pub image_tag: String,
711
712    /// Status of the pre-upgrade checks performed.
713    pub upgrade_check_result: KanidmUpgradeCheckResult,
714}
715
716#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
717#[cfg_attr(feature = "schemars", derive(JsonSchema))]
718#[serde(rename_all = "snake_case")]
719pub enum KanidmUpgradeCheckResult {
720    Passed,
721    Failed,
722}
723
724#[cfg(test)]
725mod tests {
726    use super::*;
727    use k8s_openapi::api::core::v1::PersistentVolumeClaimSpec;
728
729    #[test]
730    fn test_pvc_template_optional_metadata() {
731        // Test that we can create a PVC template without metadata
732        let pvc_template = PersistentVolumeClaimTemplate {
733            metadata: None,
734            spec: Some(PersistentVolumeClaimSpec::default()),
735        };
736
737        // Test that it can be converted to a k8s PVC
738        let k8s_pvc = pvc_template.to_persistent_volume_claim();
739        assert_eq!(k8s_pvc.metadata, ObjectMeta::default());
740        assert_eq!(k8s_pvc.spec, pvc_template.spec);
741    }
742
743    #[test]
744    fn test_pvc_template_with_metadata() {
745        let custom_metadata = ObjectMeta {
746            name: Some("test-pvc".to_string()),
747            labels: Some([("app".to_string(), "test".to_string())].into()),
748            ..ObjectMeta::default()
749        };
750
751        // Test that we can create a PVC template with metadata
752        let pvc_template = PersistentVolumeClaimTemplate {
753            metadata: Some(custom_metadata.clone()),
754            spec: Some(PersistentVolumeClaimSpec::default()),
755        };
756
757        // Test that it can be converted to a k8s PVC
758        let k8s_pvc = pvc_template.to_persistent_volume_claim();
759        assert_eq!(k8s_pvc.metadata, custom_metadata);
760        assert_eq!(k8s_pvc.spec, pvc_template.spec);
761    }
762}