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