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