Skip to main content

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