Skip to main content

kaniop_operator/kanidm/
crd.rs

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