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 either as termination or passthrough at the ingress
219    /// controller level.
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    /// Volumes allows the configuration of additional volumes on the output StatefulSet
226    /// definition. Volumes specified will be appended to other volumes that are generated as a
227    /// result of StorageSpec objects.
228    #[serde(skip_serializing_if = "Option::is_none")]
229    pub volumes: Option<Vec<Volume>>,
230
231    /// VolumeMounts allows the configuration of additional VolumeMounts.
232    ///
233    /// VolumeMounts will be appended to other VolumeMounts in the kanidm’ container, that are
234    /// generated as a result of StorageSpec objects.
235    #[serde(skip_serializing_if = "Option::is_none")]
236    pub volume_mounts: Option<Vec<VolumeMount>>,
237
238    /// The field controls if and how PVCs are deleted during the lifecycle of a StatefulSet.
239    /// The default behavior is all PVCs are retained.
240    /// This is a beta field from 1.27. It requires enabling the StatefulSetAutoDeletePVC feature
241    /// gate.
242    #[serde(skip_serializing_if = "Option::is_none")]
243    pub persistent_volume_claim_retention_policy:
244        Option<StatefulSetPersistentVolumeClaimRetentionPolicy>,
245
246    /// SecurityContext holds pod-level security attributes and common container settings.
247    /// This defaults to the default PodSecurityContext.
248    #[serde(skip_serializing_if = "Option::is_none")]
249    pub security_context: Option<PodSecurityContext>,
250
251    /// Defines the DNS policy for the pods.
252    #[serde(skip_serializing_if = "Option::is_none")]
253    pub dns_policy: Option<String>,
254
255    /// Defines the DNS configuration for the pods.
256    #[serde(skip_serializing_if = "Option::is_none")]
257    pub dns_config: Option<PodDNSConfig>,
258
259    /// Containers allows injecting additional containers or modifying operator generated
260    /// containers. This can be used to allow adding an authentication proxy to the Pods or to
261    /// change the behavior of an operator generated container. Containers described here modify
262    /// an operator generated container if they share the same name and modifications are done
263    /// via a strategic merge patch.
264    ///
265    /// The name of container managed by the operator is: kanidm
266    ///
267    /// Overriding containers is entirely outside the scope of what the maintainers will support
268    /// 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 containers: Option<Vec<Container>>,
271
272    /// InitContainers allows injecting initContainers to the Pod definition. Those can be used to
273    /// e.g. fetch secrets for injection into the Kanidm configuration from external sources.
274    /// Any errors during the execution of an initContainer will lead to a restart of the Pod.
275    /// More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
276    /// InitContainers described here modify an operator generated init containers if they share
277    /// the same name and modifications are done via a strategic merge patch.
278    ///
279    /// The names of init container name managed by the operator are: * init-config-reloader.
280    ///
281    /// Overriding init containers is entirely outside the scope of what the maintainers will
282    /// support and by doing so, you accept that this behaviour may break at any time without notice.
283    #[serde(skip_serializing_if = "Option::is_none")]
284    pub init_containers: Option<Vec<Container>>,
285
286    /// Minimum number of seconds for which a newly created Pod should be ready without any of its
287    /// container crashing for it to be considered available. Defaults to 0 (pod will be considered
288    /// available as soon as it is ready)
289    #[serde(skip_serializing_if = "Option::is_none")]
290    pub min_ready_seconds: Option<i32>,
291
292    /// Optional list of hosts and IPs that will be injected into the Pod’s hosts file if specified.
293    #[serde(skip_serializing_if = "Option::is_none")]
294    pub host_aliases: Option<Vec<HostAlias>>,
295
296    /// Use the host’s network namespace if true.
297    ///
298    /// Make sure to understand the security implications if you want to enable it
299    /// (https://kubernetes.io/docs/concepts/configuration/overview/).
300    ///
301    /// When hostNetwork is enabled, this will set the DNS policy to ClusterFirstWithHostNet
302    /// automatically.
303    #[serde(skip_serializing_if = "Option::is_none")]
304    pub host_network: Option<bool>,
305}
306
307#[derive(Serialize, Deserialize, Clone, Debug, Default)]
308#[cfg_attr(feature = "schemars", derive(JsonSchema))]
309#[serde(rename_all = "camelCase")]
310pub struct ReplicaGroup {
311    /// The name of the replica group.
312    pub name: String,
313
314    /// Number of replicas to deploy for a Kanidm replica group.
315    pub replicas: i32,
316
317    /// The Kanidm role of each node in the replica group.
318    #[serde(default)]
319    pub role: KanidmServerRole,
320
321    /// If true, the first pod of the StatefulSet will be considered as the primary node.
322    /// The rest of the nodes are considered as secondary nodes.
323    /// This means that if database issues occur the content of the primary will take precedence
324    /// over the rest of the nodes.
325    /// This is only valid for the WriteReplica role and can only be set to true for one
326    /// replica group or external replication node.
327    /// Defaults to false.
328    #[serde(default)]
329    pub primary_node: bool,
330
331    /// Defines the resources requests and limits of the kanidm’ container.
332    #[serde(skip_serializing_if = "Option::is_none")]
333    pub resources: Option<ResourceRequirements>,
334
335    /// Defines on which Nodes the Pods are scheduled.
336    #[serde(skip_serializing_if = "Option::is_none")]
337    pub node_selector: Option<BTreeMap<String, String>>,
338
339    /// Defines the Pods’ affinity scheduling rules if specified.
340    #[serde(skip_serializing_if = "Option::is_none")]
341    pub affinity: Option<Affinity>,
342
343    /// Defines the Pods’ tolerations if specified.
344    #[serde(skip_serializing_if = "Option::is_none")]
345    pub tolerations: Option<Vec<Toleration>>,
346
347    /// Defines the pod’s topology spread constraints if specified.
348    #[serde(skip_serializing_if = "Option::is_none")]
349    pub topology_spread_constraints: Option<Vec<TopologySpreadConstraint>>,
350}
351
352// re-implementation of kanidmd_core::config::ServerRole because it is not Serialize
353#[derive(Serialize, Deserialize, Clone, Debug, Default)]
354#[cfg_attr(feature = "schemars", derive(JsonSchema))]
355#[serde(rename_all = "snake_case")]
356pub enum KanidmServerRole {
357    /// Full read-write replica with web UI
358    #[default]
359    WriteReplica,
360    /// Read-write replica without the web UI
361    WriteReplicaNoUI,
362    /// Read-only replica for load balancing read operations
363    ReadOnlyReplica,
364}
365
366#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
367#[cfg_attr(feature = "schemars", derive(JsonSchema))]
368#[serde(rename_all = "camelCase")]
369pub struct ExternalReplicationNode {
370    /// Name of the external replication node. This just have internal use.
371    pub name: String,
372
373    /// The hostname of the external replication node.
374    pub hostname: String,
375
376    /// The replication port of the external replication node.
377    pub port: i32,
378
379    /// Defines the secret that contains the identity certificate of the external replication node.
380    pub certificate: SecretKeySelector,
381
382    /// Defines the type of replication to use. Defaults to MutualPull.
383    #[serde(default)]
384    pub _type: ReplicationType,
385
386    /// Select external replication node as the primary node. This means that if database conflicts
387    /// occur the content of the primary will take precedence over the rest of the nodes.
388    /// Note: just one external replication node or replication group can be selected as primary.
389    /// Defaults to false.
390    #[serde(default)]
391    pub automatic_refresh: bool,
392}
393
394// re-implementation of kanidmd_core::repl::config::RepNodeConfig because it is not Serialize and
395// attributes changed
396#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
397#[cfg_attr(feature = "schemars", derive(JsonSchema))]
398#[serde(rename_all = "kebab-case")]
399pub enum ReplicationType {
400    /// Both nodes can initiate replication with each other
401    #[default]
402    MutualPull,
403    /// This node allows the external node to pull changes, but won't initiate
404    AllowPull,
405    /// This node will pull changes from the external node
406    Pull,
407}
408
409fn default_image() -> String {
410    "kanidm/server:latest".to_string()
411}
412
413// re-implementation of sketching::LogLevel because it is not Serialize
414#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
415#[cfg_attr(feature = "schemars", derive(JsonSchema))]
416#[serde(rename_all = "snake_case")]
417pub enum KanidmLogLevel {
418    /// Most verbose logging level, includes all debug and info messages
419    Trace,
420    /// Debug level logging, useful for troubleshooting
421    Debug,
422    /// Standard informational logging level
423    #[default]
424    Info,
425}
426
427fn default_port_name() -> String {
428    "https".to_string()
429}
430
431/// PersistentVolumeClaimTemplate defines a PVC template with optional metadata.
432/// This allows users to specify a PVC template without requiring metadata to be explicitly set.
433#[derive(Serialize, Deserialize, Clone, Debug, Default)]
434#[cfg_attr(feature = "schemars", derive(JsonSchema))]
435#[serde(rename_all = "camelCase")]
436pub struct PersistentVolumeClaimTemplate {
437    /// Standard object's metadata. More info:
438    /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
439    #[serde(skip_serializing_if = "Option::is_none")]
440    pub metadata: Option<ObjectMeta>,
441
442    /// spec defines the desired characteristics of a volume requested by a pod author. More info:
443    /// https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
444    pub spec: Option<PersistentVolumeClaimSpec>,
445}
446
447impl PersistentVolumeClaimTemplate {
448    /// Convert this template into a k8s-openapi PersistentVolumeClaim
449    pub fn to_persistent_volume_claim(&self) -> PersistentVolumeClaim {
450        PersistentVolumeClaim {
451            metadata: self.metadata.clone().unwrap_or_default(),
452            spec: self.spec.clone(),
453            ..Default::default()
454        }
455    }
456}
457
458#[derive(Serialize, Deserialize, Clone, Debug, Default)]
459#[cfg_attr(feature = "schemars", derive(JsonSchema))]
460#[serde(rename_all = "camelCase")]
461pub struct KanidmStorage {
462    /// EmptyDirVolumeSource to be used by the StatefulSet. If specified, it takes precedence over
463    /// `ephemeral` and `volumeClaimTemplate`.
464    /// More info: https://kubernetes.io/docs/concepts/storage/volumes/#emptydir
465    #[serde(skip_serializing_if = "Option::is_none")]
466    pub empty_dir: Option<EmptyDirVolumeSource>,
467
468    /// EphemeralVolumeSource to be used by the StatefulSet.
469    /// More info: https://kubernetes.io/docs/concepts/storage/ephemeral-volumes/#generic-ephemeral-volumes
470    #[serde(skip_serializing_if = "Option::is_none")]
471    pub ephemeral: Option<EphemeralVolumeSource>,
472
473    /// Defines the PVC spec to be used by the Kanidm StatefulSets. The easiest way to use a volume
474    /// that cannot be automatically provisioned is to use a label selector alongside manually
475    /// created PersistentVolumes.
476    #[serde(skip_serializing_if = "Option::is_none")]
477    pub volume_claim_template: Option<PersistentVolumeClaimTemplate>,
478}
479
480#[derive(Serialize, Deserialize, Clone, Debug, Default)]
481#[cfg_attr(feature = "schemars", derive(JsonSchema))]
482#[serde(rename_all = "camelCase")]
483pub struct KanidmService {
484    /// Annotations is an unstructured key value map stored with a resource that may be set by
485    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
486    /// be preserved when modifying objects.
487    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
488    #[serde(skip_serializing_if = "Option::is_none")]
489    pub annotations: Option<BTreeMap<String, String>>,
490
491    /// Specify the Service's type where the Kanidm Service is exposed
492    /// Please note that some Ingress controllers like https://github.com/kubernetes/ingress-gce
493    /// forces you to expose your Service on a NodePort
494    /// Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and
495    /// LoadBalancer. "ClusterIP" allocates a cluster-internal IP address for load-balancing to
496    /// endpoints. Endpoints are determined by the selector or if that is not specified, by manual
497    /// construction of an Endpoints object or EndpointSlice objects. If clusterIP is "None",
498    /// no virtual IP is allocated and the endpoints are published as a set of endpoints rather
499    /// than a virtual IP. "NodePort" builds on ClusterIP and allocates a port on every node which
500    /// routes to the same endpoints as the clusterIP. "LoadBalancer" builds on NodePort and creates
501    /// an external load-balancer (if supported in the current cloud) which routes to the same
502    /// endpoints as the clusterIP. "ExternalName" aliases this service to the specified
503    /// externalName. Several other fields do not apply to ExternalName services.
504    /// More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
505    #[serde(skip_serializing_if = "Option::is_none")]
506    pub type_: Option<String>,
507}
508
509#[derive(Serialize, Deserialize, Clone, Debug, Default)]
510#[cfg_attr(feature = "schemars", derive(JsonSchema))]
511#[serde(rename_all = "camelCase")]
512pub struct KanidmIngress {
513    /// Annotations is an unstructured key value map stored with a resource that may be set by
514    /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
515    /// be preserved when modifying objects.
516    /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
517    #[serde(skip_serializing_if = "Option::is_none")]
518    pub annotations: Option<BTreeMap<String, String>>,
519
520    /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
521    /// implementations use this field to know whether they should be serving this Ingress resource,
522    /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
523    /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
524    /// it was widely supported by Ingress controllers to create a direct binding between Ingress
525    /// controller and Ingress resources. Newly created Ingress resources should prefer using the
526    /// field. However, even though the annotation is officially deprecated, for backwards
527    /// compatibility reasons, ingress controllers should still honor that annotation if present.
528    #[serde(skip_serializing_if = "Option::is_none")]
529    pub ingress_class_name: Option<String>,
530    /// Defines the name of the secret that contains the TLS private key and certificate for the
531    /// server. If not defined, the default will be the Kanidm name appended with `-tls`.
532    #[schemars(extend("x-kubernetes-validations" = [
533        {
534            "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
535            "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
536        }
537    ]))]
538    #[serde(skip_serializing_if = "Option::is_none")]
539    pub tls_secret_name: Option<String>,
540    /// Additional Subject Alternative Names (SANs) to include in the TLS certificate.
541    /// The main domain from the Kanidm spec is automatically included.
542    /// This does not add additional hosts to the ingress resource, only certificate SANs.
543    #[serde(skip_serializing_if = "Option::is_none")]
544    pub extra_tls_hosts: Option<BTreeSet<String>>,
545}
546
547/// Most recent observed status of the Kanidm cluster. Read-only.
548/// More info:
549/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
550#[derive(Serialize, Deserialize, Clone, Debug, Default)]
551#[cfg_attr(feature = "schemars", derive(JsonSchema))]
552#[serde(rename_all = "camelCase")]
553pub struct KanidmStatus {
554    /// Total number of available pods (ready for at least minReadySeconds) targeted by this Kanidm
555    /// deployment.
556    pub available_replicas: i32,
557
558    #[serde(skip_serializing_if = "Option::is_none")]
559    pub conditions: Option<Vec<Condition>>,
560
561    /// Total number of non-terminated pods targeted by this Kanidm cluster.
562    pub replicas: i32,
563
564    /// Total number of unavailable pods targeted by this Kanidm cluster.
565    pub unavailable_replicas: i32,
566
567    /// Total number of non-terminated pods targeted by this Kanidm cluster that have the
568    /// desired version spec.
569    pub updated_replicas: i32,
570
571    /// Status per replica in the Kanidm cluster.
572    pub replica_statuses: Vec<KanidmReplicaStatus>,
573
574    /// Ready vs desired replicas.
575    pub replica_column: String,
576
577    /// Admin users secret name.
578    pub secret_name: Option<String>,
579
580    /// The current version of the Kanidm server.
581    pub version: Option<KanidmVersionStatus>,
582}
583
584#[derive(Serialize, Deserialize, Clone, Debug)]
585#[cfg_attr(feature = "schemars", derive(JsonSchema))]
586#[serde(rename_all = "camelCase")]
587pub struct KanidmReplicaStatus {
588    /// Pod name: replica group StatefulSet name plus the pod index.
589    pub pod_name: String,
590
591    /// StatefulSet name: Kanidm name plus the replica group name.
592    pub statefulset_name: String,
593
594    /// The current state of the replica.
595    pub state: KanidmReplicaState,
596}
597
598#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
599#[cfg_attr(feature = "schemars", derive(JsonSchema))]
600#[serde(rename_all = "snake_case")]
601pub enum KanidmReplicaState {
602    Initialized,
603    Pending,
604    CertificateExpiring,
605}
606
607#[derive(Serialize, Deserialize, Clone, Debug)]
608#[cfg_attr(feature = "schemars", derive(JsonSchema))]
609#[serde(rename_all = "camelCase")]
610pub struct KanidmVersionStatus {
611    /// The current image of the Kanidm server.
612    pub image_tag: String,
613
614    /// Status of the pre-upgrade checks performed.
615    pub upgrade_check_result: KanidmUpgradeCheckResult,
616}
617
618#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
619#[cfg_attr(feature = "schemars", derive(JsonSchema))]
620#[serde(rename_all = "snake_case")]
621pub enum KanidmUpgradeCheckResult {
622    Passed,
623    Failed,
624}
625
626#[cfg(test)]
627mod tests {
628    use super::*;
629    use k8s_openapi::api::core::v1::PersistentVolumeClaimSpec;
630
631    #[test]
632    fn test_pvc_template_optional_metadata() {
633        // Test that we can create a PVC template without metadata
634        let pvc_template = PersistentVolumeClaimTemplate {
635            metadata: None,
636            spec: Some(PersistentVolumeClaimSpec::default()),
637        };
638
639        // Test that it can be converted to a k8s PVC
640        let k8s_pvc = pvc_template.to_persistent_volume_claim();
641        assert_eq!(k8s_pvc.metadata, ObjectMeta::default());
642        assert_eq!(k8s_pvc.spec, pvc_template.spec);
643    }
644
645    #[test]
646    fn test_pvc_template_with_metadata() {
647        let custom_metadata = ObjectMeta {
648            name: Some("test-pvc".to_string()),
649            labels: Some([("app".to_string(), "test".to_string())].into()),
650            ..ObjectMeta::default()
651        };
652
653        // Test that we can create a PVC template with metadata
654        let pvc_template = PersistentVolumeClaimTemplate {
655            metadata: Some(custom_metadata.clone()),
656            spec: Some(PersistentVolumeClaimSpec::default()),
657        };
658
659        // Test that it can be converted to a k8s PVC
660        let k8s_pvc = pvc_template.to_persistent_volume_claim();
661        assert_eq!(k8s_pvc.metadata, custom_metadata);
662        assert_eq!(k8s_pvc.spec, pvc_template.spec);
663    }
664}