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    /// Defines the resources requests and limits of the kanidm’ container.
350    #[serde(skip_serializing_if = "Option::is_none")]
351    pub resources: Option<ResourceRequirements>,
352
353    /// Defines on which Nodes the Pods are scheduled.
354    #[serde(skip_serializing_if = "Option::is_none")]
355    pub node_selector: Option<BTreeMap<String, String>>,
356
357    /// Defines the Pods’ affinity scheduling rules if specified.
358    #[serde(skip_serializing_if = "Option::is_none")]
359    pub affinity: Option<Affinity>,
360
361    /// Defines the Pods’ tolerations if specified.
362    #[serde(skip_serializing_if = "Option::is_none")]
363    pub tolerations: Option<Vec<Toleration>>,
364
365    /// Defines the pod’s topology spread constraints if specified.
366    #[serde(skip_serializing_if = "Option::is_none")]
367    pub topology_spread_constraints: Option<Vec<TopologySpreadConstraint>>,
368}
369
370// re-implementation of kanidmd_core::config::ServerRole because it is not Serialize
371#[derive(Serialize, Deserialize, Clone, Debug, Default)]
372#[cfg_attr(feature = "schemars", derive(JsonSchema))]
373#[serde(rename_all = "snake_case")]
374pub enum KanidmServerRole {
375    /// Full read-write replica with web UI
376    #[default]
377    WriteReplica,
378    /// Read-write replica without the web UI
379    WriteReplicaNoUI,
380    /// Read-only replica for load balancing read operations.
381    /// **WARNING**: read_only_replica is currently a placeholder and not yet implemented in Kanidm.
382    /// Using this role may lead to divergent data across replicas. Kaniop uses it to configure the
383    /// replication type to pull.
384    ReadOnlyReplica,
385}
386
387#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
388#[cfg_attr(feature = "schemars", derive(JsonSchema))]
389#[serde(rename_all = "camelCase")]
390pub struct KanidmReplicaGroupServices {
391    /// Annotations to apply to each Service for replica group pods.
392    ///
393    /// Available template variables:
394    /// - `{replica_index}`: Index of the pod in the replica group
395    /// - `{pod_name}`: Name of the pod
396    /// - `{domain}`: Domain name
397    #[serde(skip_serializing_if = "Option::is_none")]
398    pub annotations_template: Option<BTreeMap<String, String>>,
399
400    /// Hostname template for each Service created for replica group pods.
401    ///
402    /// Available template variables:
403    /// - `{replica_index}`: Index of the pod in the replica group
404    /// - `{pod_name}`: Name of the pod
405    /// - `{domain}`: Domain name
406    ///
407    /// If not set, the replication hostname defaults to the Service's external IP.
408    #[serde(skip_serializing_if = "Option::is_none")]
409    pub replication_hostname_template: Option<String>,
410
411    /// Map of string keys and values that can be used to organize and categorize (scope and
412    /// select) objects. May match selectors of replication controllers and services.
413    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels
414    #[serde(skip_serializing_if = "Option::is_none")]
415    pub additional_labels: Option<BTreeMap<String, String>>,
416}
417
418#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
419#[cfg_attr(feature = "schemars", derive(JsonSchema))]
420#[serde(rename_all = "camelCase")]
421pub struct ExternalReplicationNode {
422    /// Name of the external replication node. This just have internal use.
423    pub name: String,
424
425    /// The hostname of the external replication node.
426    pub hostname: String,
427
428    /// The replication port of the external replication node.
429    pub port: i32,
430
431    /// Defines the secret that contains the identity certificate of the external replication node.
432    pub certificate: SecretKeySelector,
433
434    /// Defines the type of replication to use. Defaults to MutualPull.
435    #[serde(default)]
436    pub _type: ReplicationType,
437
438    /// Select external replication node as the primary node. This means that if database conflicts
439    /// occur the content of the primary will take precedence over the rest of the nodes.
440    /// Note: just one external replication node or replication group can be selected as primary.
441    /// Defaults to false.
442    #[serde(default)]
443    pub automatic_refresh: bool,
444}
445
446// re-implementation of kanidmd_core::repl::config::RepNodeConfig because it is not Serialize and
447// attributes changed
448#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
449#[cfg_attr(feature = "schemars", derive(JsonSchema))]
450#[serde(rename_all = "kebab-case")]
451pub enum ReplicationType {
452    /// Both nodes can initiate replication with each other
453    #[default]
454    MutualPull,
455    /// This node allows the external node to pull changes, but won't initiate
456    AllowPull,
457    /// This node will pull changes from the external node
458    Pull,
459}
460
461fn default_image() -> String {
462    "kanidm/server:latest".to_string()
463}
464
465// re-implementation of sketching::LogLevel because it is not Serialize
466#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
467#[cfg_attr(feature = "schemars", derive(JsonSchema))]
468#[serde(rename_all = "snake_case")]
469pub enum KanidmLogLevel {
470    /// Most verbose logging level, includes all debug and info messages
471    Trace,
472    /// Debug level logging, useful for troubleshooting
473    Debug,
474    /// Standard informational logging level
475    #[default]
476    Info,
477}
478
479fn default_port_name() -> String {
480    "https".to_string()
481}
482
483/// PersistentVolumeClaimTemplate defines a PVC template with optional metadata.
484/// This allows users to specify a PVC template without requiring metadata to be explicitly set.
485#[derive(Serialize, Deserialize, Clone, Debug, Default)]
486#[cfg_attr(feature = "schemars", derive(JsonSchema))]
487#[serde(rename_all = "camelCase")]
488pub struct PersistentVolumeClaimTemplate {
489    /// Standard object's metadata. More info:
490    /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
491    #[serde(skip_serializing_if = "Option::is_none")]
492    pub metadata: Option<ObjectMeta>,
493
494    /// spec defines the desired characteristics of a volume requested by a pod author. More info:
495    /// https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
496    pub spec: Option<PersistentVolumeClaimSpec>,
497}
498
499impl PersistentVolumeClaimTemplate {
500    /// Convert this template into a k8s-openapi PersistentVolumeClaim
501    pub fn to_persistent_volume_claim(&self) -> PersistentVolumeClaim {
502        PersistentVolumeClaim {
503            metadata: self.metadata.clone().unwrap_or_default(),
504            spec: self.spec.clone(),
505            ..Default::default()
506        }
507    }
508}
509
510#[derive(Serialize, Deserialize, Clone, Debug, Default)]
511#[cfg_attr(feature = "schemars", derive(JsonSchema))]
512#[serde(rename_all = "camelCase")]
513pub struct KanidmStorage {
514    /// EmptyDirVolumeSource to be used by the StatefulSet. If specified, it takes precedence over
515    /// `ephemeral` and `volumeClaimTemplate`.
516    /// More info: https://kubernetes.io/docs/concepts/storage/volumes/#emptydir
517    #[serde(skip_serializing_if = "Option::is_none")]
518    pub empty_dir: Option<EmptyDirVolumeSource>,
519
520    /// EphemeralVolumeSource to be used by the StatefulSet.
521    /// More info: https://kubernetes.io/docs/concepts/storage/ephemeral-volumes/#generic-ephemeral-volumes
522    #[serde(skip_serializing_if = "Option::is_none")]
523    pub ephemeral: Option<EphemeralVolumeSource>,
524
525    /// Defines the PVC spec to be used by the Kanidm StatefulSets. The easiest way to use a volume
526    /// that cannot be automatically provisioned is to use a label selector alongside manually
527    /// created PersistentVolumes.
528    #[serde(skip_serializing_if = "Option::is_none")]
529    pub volume_claim_template: Option<PersistentVolumeClaimTemplate>,
530}
531
532#[derive(Serialize, Deserialize, Clone, Debug, Default)]
533#[cfg_attr(feature = "schemars", derive(JsonSchema))]
534#[serde(rename_all = "camelCase")]
535pub struct KanidmService {
536    /// Annotations is an unstructured key value map stored with a resource that may be set by
537    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
538    /// be preserved when modifying objects.
539    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
540    #[serde(skip_serializing_if = "Option::is_none")]
541    pub annotations: Option<BTreeMap<String, String>>,
542
543    /// Specify the Service's type where the Kanidm Service is exposed
544    /// Please note that some Ingress controllers like https://github.com/kubernetes/ingress-gce
545    /// forces you to expose your Service on a NodePort
546    /// Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and
547    /// LoadBalancer. "ClusterIP" allocates a cluster-internal IP address for load-balancing to
548    /// endpoints. Endpoints are determined by the selector or if that is not specified, by manual
549    /// construction of an Endpoints object or EndpointSlice objects. If clusterIP is "None",
550    /// no virtual IP is allocated and the endpoints are published as a set of endpoints rather
551    /// than a virtual IP. "NodePort" builds on ClusterIP and allocates a port on every node which
552    /// routes to the same endpoints as the clusterIP. "LoadBalancer" builds on NodePort and creates
553    /// an external load-balancer (if supported in the current cloud) which routes to the same
554    /// endpoints as the clusterIP. "ExternalName" aliases this service to the specified
555    /// externalName. Several other fields do not apply to ExternalName services.
556    /// More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
557    #[serde(skip_serializing_if = "Option::is_none")]
558    pub type_: Option<String>,
559}
560
561#[derive(Serialize, Deserialize, Clone, Debug, Default)]
562#[cfg_attr(feature = "schemars", derive(JsonSchema))]
563#[serde(rename_all = "camelCase")]
564pub struct KanidmIngress {
565    /// Annotations is an unstructured key value map stored with a resource that may be set by
566    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
567    /// be preserved when modifying objects.
568    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
569    #[serde(skip_serializing_if = "Option::is_none")]
570    pub annotations: Option<BTreeMap<String, String>>,
571
572    /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
573    /// implementations use this field to know whether they should be serving this Ingress resource,
574    /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
575    /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
576    /// it was widely supported by Ingress controllers to create a direct binding between Ingress
577    /// controller and Ingress resources. Newly created Ingress resources should prefer using the
578    /// field. However, even though the annotation is officially deprecated, for backwards
579    /// compatibility reasons, ingress controllers should still honor that annotation if present.
580    #[serde(skip_serializing_if = "Option::is_none")]
581    pub ingress_class_name: Option<String>,
582    /// Defines the name of the secret that contains the TLS private key and certificate for the
583    /// server. If not defined, the default will be the Kanidm name appended with `-tls`.
584    #[schemars(extend("x-kubernetes-validations" = [
585        {
586            "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
587            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
588        }
589    ]))]
590    #[serde(skip_serializing_if = "Option::is_none")]
591    pub tls_secret_name: Option<String>,
592    /// Additional Subject Alternative Names (SANs) to include in the TLS certificate.
593    /// The main domain from the Kanidm spec is automatically included.
594    /// This does not add additional hosts to the ingress resource, only certificate SANs.
595    #[serde(skip_serializing_if = "Option::is_none")]
596    pub extra_tls_hosts: Option<BTreeSet<String>>,
597}
598
599#[derive(Serialize, Deserialize, Clone, Debug, Default)]
600#[cfg_attr(feature = "schemars", derive(JsonSchema))]
601#[serde(rename_all = "camelCase")]
602pub struct KanidmRegionIngress {
603    /// Region identifier for this ingress. Used as a subdomain of the main Kanidm domain to route
604    /// traffic for a specific region.
605    pub region: String,
606
607    /// Annotations is an unstructured key value map stored with a resource that may be set by
608    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
609    /// be preserved when modifying objects.
610    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
611    #[serde(skip_serializing_if = "Option::is_none")]
612    pub annotations: Option<BTreeMap<String, String>>,
613
614    /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
615    /// implementations use this field to know whether they should be serving this Ingress resource,
616    /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
617    /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
618    /// it was widely supported by Ingress controllers to create a direct binding between Ingress
619    /// controller and Ingress resources. Newly created Ingress resources should prefer using the
620    /// field. However, even though the annotation is officially deprecated, for backwards
621    /// compatibility reasons, ingress controllers should still honor that annotation if present.
622    #[serde(skip_serializing_if = "Option::is_none")]
623    pub ingress_class_name: Option<String>,
624    /// Defines the name of the secret that contains the TLS private key and certificate for the
625    /// server. If not defined, the default will be the Kanidm name appended with `-region-tls`.
626    #[schemars(extend("x-kubernetes-validations" = [
627        {
628            "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
629            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
630        }
631    ]))]
632    #[serde(skip_serializing_if = "Option::is_none")]
633    pub tls_secret_name: Option<String>,
634}
635
636/// Most recent observed status of the Kanidm cluster. Read-only.
637/// More info:
638/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
639#[derive(Serialize, Deserialize, Clone, Debug, Default)]
640#[cfg_attr(feature = "schemars", derive(JsonSchema))]
641#[serde(rename_all = "camelCase")]
642pub struct KanidmStatus {
643    /// Total number of available pods (ready for at least minReadySeconds) targeted by this Kanidm
644    /// deployment.
645    pub available_replicas: i32,
646
647    #[serde(skip_serializing_if = "Option::is_none")]
648    pub conditions: Option<Vec<Condition>>,
649
650    /// Total number of non-terminated pods targeted by this Kanidm cluster.
651    pub replicas: i32,
652
653    /// Total number of unavailable pods targeted by this Kanidm cluster.
654    pub unavailable_replicas: i32,
655
656    /// Total number of non-terminated pods targeted by this Kanidm cluster that have the
657    /// desired version spec.
658    pub updated_replicas: i32,
659
660    /// Status per replica in the Kanidm cluster.
661    pub replica_statuses: Vec<KanidmReplicaStatus>,
662
663    /// Ready vs desired replicas.
664    pub replica_column: String,
665
666    /// Admin users secret name.
667    pub secret_name: Option<String>,
668
669    /// The current version of the Kanidm server.
670    pub version: Option<KanidmVersionStatus>,
671}
672
673#[derive(Serialize, Deserialize, Clone, Debug)]
674#[cfg_attr(feature = "schemars", derive(JsonSchema))]
675#[serde(rename_all = "camelCase")]
676pub struct KanidmReplicaStatus {
677    /// Pod name: replica group StatefulSet name plus the pod index.
678    pub pod_name: String,
679
680    /// StatefulSet name: Kanidm name plus the replica group name.
681    pub statefulset_name: String,
682
683    /// The current state of the replica.
684    pub state: KanidmReplicaState,
685}
686
687#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
688#[cfg_attr(feature = "schemars", derive(JsonSchema))]
689#[serde(rename_all = "camelCase")]
690pub enum KanidmReplicaState {
691    Ready,
692    Pending,
693    CertificateExpiring,
694    CertificateHostInvalid,
695}
696
697#[derive(Serialize, Deserialize, Clone, Debug)]
698#[cfg_attr(feature = "schemars", derive(JsonSchema))]
699#[serde(rename_all = "camelCase")]
700pub struct KanidmVersionStatus {
701    /// The current image of the Kanidm server.
702    pub image_tag: String,
703
704    /// Status of the pre-upgrade checks performed.
705    pub upgrade_check_result: KanidmUpgradeCheckResult,
706}
707
708#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
709#[cfg_attr(feature = "schemars", derive(JsonSchema))]
710#[serde(rename_all = "snake_case")]
711pub enum KanidmUpgradeCheckResult {
712    Passed,
713    Failed,
714}
715
716#[cfg(test)]
717mod tests {
718    use super::*;
719    use k8s_openapi::api::core::v1::PersistentVolumeClaimSpec;
720
721    #[test]
722    fn test_pvc_template_optional_metadata() {
723        // Test that we can create a PVC template without metadata
724        let pvc_template = PersistentVolumeClaimTemplate {
725            metadata: None,
726            spec: Some(PersistentVolumeClaimSpec::default()),
727        };
728
729        // Test that it can be converted to a k8s PVC
730        let k8s_pvc = pvc_template.to_persistent_volume_claim();
731        assert_eq!(k8s_pvc.metadata, ObjectMeta::default());
732        assert_eq!(k8s_pvc.spec, pvc_template.spec);
733    }
734
735    #[test]
736    fn test_pvc_template_with_metadata() {
737        let custom_metadata = ObjectMeta {
738            name: Some("test-pvc".to_string()),
739            labels: Some([("app".to_string(), "test".to_string())].into()),
740            ..ObjectMeta::default()
741        };
742
743        // Test that we can create a PVC template with metadata
744        let pvc_template = PersistentVolumeClaimTemplate {
745            metadata: Some(custom_metadata.clone()),
746            spec: Some(PersistentVolumeClaimSpec::default()),
747        };
748
749        // Test that it can be converted to a k8s PVC
750        let k8s_pvc = pvc_template.to_persistent_volume_claim();
751        assert_eq!(k8s_pvc.metadata, custom_metadata);
752        assert_eq!(k8s_pvc.spec, pvc_template.spec);
753    }
754}