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 /// Changes to `volumeClaimTemplates` (e.g., PVC resize or StorageClass changes)
187 /// are applied non-destructively; the operator does not delete/recreate the
188 /// StatefulSet for PVC template modifications.
189 #[serde(skip_serializing_if = "Option::is_none")]
190 pub storage: Option<KanidmStorage>,
191
192 /// Defines the port name used for the LDAP service. If not defined, LDAP service will not be
193 /// configured. Service port will be `3636`.
194 ///
195 /// StartTLS is not supported due to security risks such as credential leakage and MITM attacks
196 /// that are fundamental in how StartTLS works. StartTLS can not be repaired to prevent this.
197 /// LDAPS is the only secure method of communicating to any LDAP server. Kanidm will use its
198 /// certificates for both HTTPS and LDAPS.
199 #[serde(skip_serializing_if = "Option::is_none")]
200 pub ldap_port_name: Option<String>,
201
202 /// Specifies the name of the secret holding the TLS private key and certificate for the server.
203 /// If not provided, the ingress secret will be used. The server will not start if the secret
204 /// is missing.
205 #[schemars(extend("x-kubernetes-validations" = [
206 {
207 "message": "tlsSecretName must be a valid Kubernetes resource name.",
208 "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
209 }
210 ]))]
211 #[serde(skip_serializing_if = "Option::is_none")]
212 pub tls_secret_name: Option<String>,
213
214 /// Service defines the service configuration for the Kanidm server.
215 #[serde(skip_serializing_if = "Option::is_none")]
216 pub service: Option<KanidmService>,
217
218 /// Ingress configuration for the Kanidm cluster.
219 ///
220 /// The domain specified in the Kanidm spec will be used as the ingress host.
221 /// TLS is required and must be configured at the ingress controller level (termination or
222 /// passthrough).
223 /// When running multiple replicas, configure session affinity on your ingress controller to
224 /// ensure proper session handling.
225 #[serde(skip_serializing_if = "Option::is_none")]
226 pub ingress: Option<KanidmIngress>,
227
228 /// Region-specific ingress configuration for multi-region deployments.
229 ///
230 /// Allows defining ingress settings for a specific region, using a subdomain of the main
231 /// Kanidm domain.
232 /// TLS is required and must be configured at the ingress controller level (termination or
233 /// passthrough).
234 /// For multi-region deployments, configure session affinity on your ingress controller to ensure proper session handling.
235 #[serde(skip_serializing_if = "Option::is_none")]
236 pub region_ingress: Option<KanidmRegionIngress>,
237
238 /// Gateway API configuration for the Kanidm cluster.
239 ///
240 /// Allows configuring an HTTPRoute for Gateway API-based ingress routing.
241 /// The HTTPRoute will route traffic to the Kanidm service using the specified parentRefs
242 /// to attach to Gateway(s).
243 /// Both ingress and gateway can be configured simultaneously for migration scenarios.
244 #[serde(skip_serializing_if = "Option::is_none")]
245 pub gateway: Option<KanidmGateway>,
246
247 /// Volumes allows the configuration of additional volumes on the output StatefulSet
248 /// definition. Volumes specified will be appended to other volumes that are generated as a
249 /// result of StorageSpec objects.
250 #[serde(skip_serializing_if = "Option::is_none")]
251 pub volumes: Option<Vec<Volume>>,
252
253 /// VolumeMounts allows the configuration of additional VolumeMounts.
254 ///
255 /// VolumeMounts will be appended to other VolumeMounts in the kanidm' container, that are
256 /// generated as a result of StorageSpec objects.
257 #[serde(skip_serializing_if = "Option::is_none")]
258 pub volume_mounts: Option<Vec<VolumeMount>>,
259
260 /// The field controls if and how PVCs are deleted during the lifecycle of a StatefulSet.
261 /// The default behavior is all PVCs are retained.
262 /// This is a beta field from 1.27. It requires enabling the StatefulSetAutoDeletePVC feature
263 /// gate.
264 #[serde(skip_serializing_if = "Option::is_none")]
265 pub persistent_volume_claim_retention_policy:
266 Option<StatefulSetPersistentVolumeClaimRetentionPolicy>,
267
268 /// SecurityContext holds pod-level security attributes and common container settings.
269 /// This defaults to the default PodSecurityContext.
270 #[serde(skip_serializing_if = "Option::is_none")]
271 pub security_context: Option<PodSecurityContext>,
272
273 /// Defines the DNS policy for the pods.
274 #[serde(skip_serializing_if = "Option::is_none")]
275 pub dns_policy: Option<String>,
276
277 /// Defines the DNS configuration for the pods.
278 #[serde(skip_serializing_if = "Option::is_none")]
279 pub dns_config: Option<PodDNSConfig>,
280
281 /// Containers allows injecting additional containers or modifying operator generated
282 /// containers. This can be used to allow adding an authentication proxy to the Pods or to
283 /// change the behavior of an operator generated container. Containers described here modify
284 /// an operator generated container if they share the same name and modifications are done
285 /// via a strategic merge patch.
286 ///
287 /// The name of container managed by the operator is: kanidm
288 ///
289 /// Overriding containers is entirely outside the scope of what the maintainers will support
290 /// and by doing so, you accept that this behaviour may break at any time without notice.
291 #[serde(skip_serializing_if = "Option::is_none")]
292 pub containers: Option<Vec<Container>>,
293
294 /// InitContainers allows injecting initContainers to the Pod definition. Those can be used to
295 /// e.g. fetch secrets for injection into the Kanidm configuration from external sources.
296 /// Any errors during the execution of an initContainer will lead to a restart of the Pod.
297 /// More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
298 /// InitContainers described here modify an operator generated init containers if they share
299 /// the same name and modifications are done via a strategic merge patch.
300 ///
301 /// The names of init container name managed by the operator are: * init-config-reloader.
302 ///
303 /// Overriding init containers is entirely outside the scope of what the maintainers will
304 /// support and by doing so, you accept that this behaviour may break at any time without notice.
305 #[serde(skip_serializing_if = "Option::is_none")]
306 pub init_containers: Option<Vec<Container>>,
307
308 /// Minimum number of seconds for which a newly created Pod should be ready without any of its
309 /// container crashing for it to be considered available. Defaults to 0 (pod will be considered
310 /// available as soon as it is ready)
311 #[serde(skip_serializing_if = "Option::is_none")]
312 pub min_ready_seconds: Option<i32>,
313
314 /// Optional list of hosts and IPs that will be injected into the Pod's hosts file if specified.
315 #[serde(skip_serializing_if = "Option::is_none")]
316 pub host_aliases: Option<Vec<HostAlias>>,
317
318 /// Use the host's network namespace if true.
319 ///
320 /// Make sure to understand the security implications if you want to enable it
321 /// (https://kubernetes.io/docs/concepts/configuration/overview/).
322 ///
323 /// When hostNetwork is enabled, this will set the DNS policy to ClusterFirstWithHostNet
324 /// automatically.
325 #[serde(default, skip_serializing_if = "is_default")]
326 pub host_network: Option<bool>,
327
328 /// IP family for bind addresses. Defaults to IPv4.
329 ///
330 /// - `ipv4`: Uses 0.0.0.0 for bind addresses (default)
331 /// - `ipv6`: Uses [::] for bind addresses
332 #[serde(default, skip_serializing_if = "is_default")]
333 pub ip_family: IpFamily,
334
335 /// RuntimeClassName refers to a RuntimeClass object in the node.k8s.io API group,
336 /// which should be used to run the pods in this Kanidm cluster.
337 /// If no RuntimeClass resource matches the named class, the pod will not be run.
338 /// If unset or empty, the "legacy" RuntimeClass will be used, which is an implicit
339 /// class with an empty definition that uses the default runtime handler.
340 /// More info: https://kubernetes.io/docs/concepts/containers/runtime-class/
341 #[serde(skip_serializing_if = "Option::is_none")]
342 pub runtime_class_name: Option<String>,
343
344 /// AutomountServiceAccountToken indicates whether a service account token should be automatically mounted.
345 /// If not specified, defaults to true (the token is mounted).
346 /// Setting this to false is recommended for security-sensitive applications.
347 /// More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
348 #[serde(skip_serializing_if = "Option::is_none")]
349 pub automount_service_account_token: Option<bool>,
350
351 /// EnableServiceLinks indicates whether information about services should be injected into pod's
352 /// environment variables, matching the syntax of Docker links.
353 /// Defaults to false for security reasons (prevents service environment variable injection).
354 /// Set to true only if you need Kubernetes to inject service information as environment variables.
355 /// More info: https://kubernetes.io/docs/concepts/services-networking/service/#environment-variables
356 #[serde(default = "default_false", skip_serializing_if = "is_default")]
357 pub enable_service_links: bool,
358
359 /// HostUsers controls how the user namespace is configured for the pod.
360 /// If set to true, the pod will use the host's user namespace.
361 /// If set to false or not specified, the pod will use a user namespace configured by the runtime.
362 /// This feature requires support in the container runtime and Kubernetes 1.27+.
363 /// More info: https://kubernetes.io/docs/concepts/workloads/pods/user-namespaces/
364 #[serde(skip_serializing_if = "Option::is_none")]
365 pub host_users: Option<bool>,
366
367 /// Domain appearance customization settings.
368 /// Allows customizing the display name and site image (logo) shown on the Kanidm signin page.
369 #[serde(skip_serializing_if = "Option::is_none")]
370 pub domain_appearance: Option<DomainAppearanceSpec>,
371
372 /// Mail sender configuration for sending emails (password reset links, notifications).
373 /// When enabled, the operator automatically creates a service account in Kanidm's
374 /// `idm_message_senders` group, generates an API token, and deploys the `kanidm-mail-sender`
375 /// component.
376 #[serde(skip_serializing_if = "Option::is_none")]
377 pub mail_sender: Option<MailSenderSpec>,
378}
379
380#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
381#[cfg_attr(feature = "schemars", derive(JsonSchema))]
382#[serde(rename_all = "camelCase")]
383pub struct DomainAppearanceSpec {
384 /// Display name shown when logged in. Defaults to "Kanidm <hostname>" if not specified.
385 #[serde(skip_serializing_if = "Option::is_none")]
386 pub display_name: Option<String>,
387
388 /// Optional site image (logo) for the signin page.
389 /// Uses same pattern as OAuth2 client images.
390 #[serde(skip_serializing_if = "Option::is_none")]
391 pub image: Option<DomainAppearanceImageSpec>,
392}
393
394#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
395#[cfg_attr(feature = "schemars", derive(JsonSchema))]
396#[serde(rename_all = "camelCase")]
397pub struct DomainAppearanceImageSpec {
398 /// URL to fetch the image from (HTTP/HTTPS only).
399 /// The operator will periodically check this URL for changes using HEAD requests
400 /// and re-download the image when changes are detected.
401 pub url: String,
402}
403
404#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
405#[cfg_attr(feature = "schemars", derive(JsonSchema))]
406#[serde(rename_all = "camelCase")]
407pub struct MailSenderSpec {
408 /// SMTP relay URL for sending emails.
409 /// Must be a valid SMTP URL: `smtp://hostname:port` or `smtps://hostname` (default port 465).
410 /// Example: `smtps://smtp.example.com` or `smtp://smtp.example.com:587`
411 pub relay: String,
412
413 /// Kubernetes secret containing SMTP credentials (username and password).
414 /// The secret must have keys for username and password (defaults to "username" and "password").
415 pub credentials_secret: MailSenderCredentialsSecret,
416
417 /// Email address used as the "From" address in sent emails.
418 /// Example: `kanidm@example.com`
419 pub from_address: String,
420
421 /// Optional email address for the "Reply-To" header.
422 /// Example: `admin@example.com`
423 #[serde(skip_serializing_if = "Option::is_none")]
424 pub reply_to_address: Option<String>,
425
426 /// Optional queue polling interval in seconds.
427 /// How often the mail sender checks Kanidm's message queue.
428 /// Defaults to 5 seconds.
429 #[serde(skip_serializing_if = "Option::is_none")]
430 pub queue_poll_interval_seconds: Option<i32>,
431
432 /// Optional SMTP connection timeout in seconds.
433 /// Defaults to 15 seconds.
434 #[serde(skip_serializing_if = "Option::is_none")]
435 pub connect_timeout_seconds: Option<i32>,
436
437 /// Optional custom image for the mail sender deployment.
438 /// Defaults to `kanidm/tools:<version>` matching the Kanidm server image version.
439 #[serde(skip_serializing_if = "Option::is_none")]
440 pub image: Option<String>,
441
442 /// Optional resource requirements for the mail sender deployment.
443 #[serde(skip_serializing_if = "Option::is_none")]
444 pub resources: Option<ResourceRequirements>,
445
446 /// Optional node selector for the mail sender deployment.
447 #[serde(skip_serializing_if = "Option::is_none")]
448 pub node_selector: Option<BTreeMap<String, String>>,
449
450 /// Optional affinity rules for the mail sender deployment.
451 #[serde(skip_serializing_if = "Option::is_none")]
452 pub affinity: Option<Affinity>,
453
454 /// Optional tolerations for the mail sender deployment.
455 #[serde(skip_serializing_if = "Option::is_none")]
456 pub tolerations: Option<Vec<Toleration>>,
457}
458
459#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
460#[cfg_attr(feature = "schemars", derive(JsonSchema))]
461#[serde(rename_all = "camelCase")]
462pub struct MailSenderCredentialsSecret {
463 /// Name of the Kubernetes secret containing SMTP credentials.
464 pub name: String,
465
466 /// Key in the secret containing the SMTP username.
467 /// Defaults to "username".
468 #[serde(default = "default_smtp_username_key", skip_serializing_if = "is_default")]
469 pub username_key: String,
470
471 /// Key in the secret containing the SMTP password.
472 /// Defaults to "password".
473 #[serde(default = "default_smtp_password_key", skip_serializing_if = "is_default")]
474 pub password_key: String,
475}
476
477impl Default for MailSenderCredentialsSecret {
478 fn default() -> Self {
479 Self {
480 name: String::new(),
481 username_key: default_smtp_username_key(),
482 password_key: default_smtp_password_key(),
483 }
484 }
485}
486
487fn default_smtp_username_key() -> String {
488 "username".to_string()
489}
490
491fn default_smtp_password_key() -> String {
492 "password".to_string()
493}
494
495#[derive(Serialize, Deserialize, Clone, Debug, Default)]
496#[cfg_attr(feature = "schemars", derive(JsonSchema))]
497#[serde(rename_all = "camelCase")]
498pub struct ReplicaGroup {
499 /// The name of the replica group.
500 pub name: String,
501
502 /// Number of replicas to deploy for a Kanidm replica group.
503 pub replicas: i32,
504
505 /// The Kanidm role of each node in the replica group.
506 #[serde(default)]
507 pub role: KanidmServerRole,
508
509 /// If true, the first pod of the StatefulSet will be considered as the primary node.
510 /// The rest of the nodes are considered as secondary nodes.
511 /// This means that if database issues occur the content of the primary will take precedence
512 /// over the rest of the nodes.
513 /// This is only valid for the WriteReplica role and can only be set to true for one
514 /// replica group or external replication node.
515 /// Defaults to false.
516 #[serde(default)]
517 pub primary_node: bool,
518
519 /// Service configuration for the replica group.
520 /// - If not specified, pods use the default StatefulSet DNS for internal communication.
521 /// - If specified, a Kubernetes Service of type LoadBalancer is created to expose replica
522 /// group pods externally.
523 /// This enables cross-cluster or multi-region access to replicas.
524 #[serde(skip_serializing_if = "Option::is_none")]
525 pub services: Option<KanidmReplicaGroupServices>,
526
527 /// Annotations to add to the StatefulSet created for this replica group.
528 ///
529 /// Each replica group gets its own StatefulSet; these annotations are applied only to the
530 /// StatefulSet for this group.
531 /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
532 #[serde(skip_serializing_if = "Option::is_none")]
533 pub stateful_set_annotations: Option<BTreeMap<String, String>>,
534
535 /// Defines the resources requests and limits of the kanidm' container.
536 #[serde(skip_serializing_if = "Option::is_none")]
537 pub resources: Option<ResourceRequirements>,
538
539 /// Defines on which Nodes the Pods are scheduled.
540 #[serde(skip_serializing_if = "Option::is_none")]
541 pub node_selector: Option<BTreeMap<String, String>>,
542
543 /// Defines the Pods' affinity scheduling rules if specified.
544 #[serde(skip_serializing_if = "Option::is_none")]
545 pub affinity: Option<Affinity>,
546
547 /// Defines the Pods' tolerations if specified.
548 #[serde(skip_serializing_if = "Option::is_none")]
549 pub tolerations: Option<Vec<Toleration>>,
550
551 /// Defines the pod's topology spread constraints if specified.
552 #[serde(skip_serializing_if = "Option::is_none")]
553 pub topology_spread_constraints: Option<Vec<TopologySpreadConstraint>>,
554}
555
556// re-implementation of kanidmd_core::config::ServerRole because it is not Serialize
557#[derive(Serialize, Deserialize, Clone, Debug, Default)]
558#[cfg_attr(feature = "schemars", derive(JsonSchema))]
559#[serde(rename_all = "snake_case")]
560pub enum KanidmServerRole {
561 /// Full read-write replica with web UI
562 #[default]
563 WriteReplica,
564 /// Read-write replica without the web UI
565 WriteReplicaNoUi,
566 /// Read-only replica for load balancing read operations.
567 /// **WARNING**: read_only_replica is currently a placeholder and not yet implemented in Kanidm.
568 /// Using this role may lead to divergent data across replicas. Kaniop uses it to configure the
569 /// replication type to pull.
570 ReadOnlyReplica,
571}
572
573#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
574#[cfg_attr(feature = "schemars", derive(JsonSchema))]
575#[serde(rename_all = "camelCase")]
576pub struct KanidmReplicaGroupServices {
577 /// Annotations to apply to each Service for replica group pods.
578 ///
579 /// Available template variables:
580 /// - `{replica_index}`: Index of the pod in the replica group
581 /// - `{pod_name}`: Name of the pod
582 /// - `{domain}`: Domain name
583 #[serde(skip_serializing_if = "Option::is_none")]
584 pub annotations_template: Option<BTreeMap<String, String>>,
585
586 /// Hostname template for each Service created for replica group pods.
587 ///
588 /// Available template variables:
589 /// - `{replica_index}`: Index of the pod in the replica group
590 /// - `{pod_name}`: Name of the pod
591 /// - `{domain}`: Domain name
592 ///
593 /// If not set, the replication hostname defaults to the Service's external IP.
594 #[serde(skip_serializing_if = "Option::is_none")]
595 pub replication_hostname_template: Option<String>,
596
597 /// Map of string keys and values that can be used to organize and categorize (scope and
598 /// select) objects. May match selectors of replication controllers and services.
599 /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels
600 #[serde(skip_serializing_if = "Option::is_none")]
601 pub additional_labels: Option<BTreeMap<String, String>>,
602}
603
604#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
605#[cfg_attr(feature = "schemars", derive(JsonSchema))]
606#[serde(rename_all = "camelCase")]
607pub struct ExternalReplicationNode {
608 /// Name of the external replication node. This just have internal use.
609 pub name: String,
610
611 /// The hostname of the external replication node.
612 pub hostname: String,
613
614 /// The replication port of the external replication node.
615 pub port: i32,
616
617 /// Defines the secret that contains the identity certificate of the external replication node.
618 pub certificate: SecretKeySelector,
619
620 /// Defines the type of replication to use. Defaults to MutualPull.
621 #[serde(default)]
622 pub _type: ReplicationType,
623
624 /// Select external replication node as the primary node. This means that if database conflicts
625 /// occur the content of the primary will take precedence over the rest of the nodes.
626 /// Note: just one external replication node or replication group can be selected as primary.
627 /// Defaults to false.
628 #[serde(default)]
629 pub automatic_refresh: bool,
630}
631
632// re-implementation of kanidmd_core::repl::config::RepNodeConfig because it is not Serialize and
633// attributes changed
634#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
635#[cfg_attr(feature = "schemars", derive(JsonSchema))]
636#[serde(rename_all = "kebab-case")]
637pub enum ReplicationType {
638 /// Both nodes can initiate replication with each other
639 #[default]
640 MutualPull,
641 /// This node allows the external node to pull changes, but won't initiate
642 AllowPull,
643 /// This node will pull changes from the external node
644 Pull,
645}
646
647fn default_image() -> String {
648 "kanidm/server:latest".to_string()
649}
650
651// re-implementation of sketching::LogLevel because it is not Serialize
652#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
653#[cfg_attr(feature = "schemars", derive(JsonSchema))]
654#[serde(rename_all = "snake_case")]
655pub enum KanidmLogLevel {
656 /// Most verbose logging level, includes all debug and info messages
657 Trace,
658 /// Debug level logging, useful for troubleshooting
659 Debug,
660 /// Standard informational logging level
661 #[default]
662 Info,
663}
664
665fn default_port_name() -> String {
666 "https".to_string()
667}
668
669fn default_false() -> bool {
670 false
671}
672
673#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
674#[cfg_attr(feature = "schemars", derive(JsonSchema))]
675#[serde(rename_all = "kebab-case")]
676pub enum IpFamily {
677 #[default]
678 Ipv4,
679 Ipv6,
680}
681
682/// PersistentVolumeClaimTemplate defines a PVC template with optional metadata.
683/// This allows users to specify a PVC template without requiring metadata to be explicitly set.
684#[derive(Serialize, Deserialize, Clone, Debug, Default)]
685#[cfg_attr(feature = "schemars", derive(JsonSchema))]
686#[serde(rename_all = "camelCase")]
687pub struct PersistentVolumeClaimTemplate {
688 /// Standard object's metadata. More info:
689 /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
690 #[serde(skip_serializing_if = "Option::is_none")]
691 pub metadata: Option<ObjectMeta>,
692
693 /// spec defines the desired characteristics of a volume requested by a pod author. More info:
694 /// https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
695 pub spec: Option<PersistentVolumeClaimSpec>,
696}
697
698impl PersistentVolumeClaimTemplate {
699 /// Convert this template into a k8s-openapi PersistentVolumeClaim
700 pub fn to_persistent_volume_claim(&self) -> PersistentVolumeClaim {
701 PersistentVolumeClaim {
702 metadata: self.metadata.clone().unwrap_or_default(),
703 spec: self.spec.clone(),
704 ..Default::default()
705 }
706 }
707}
708
709#[derive(Serialize, Deserialize, Clone, Debug, Default)]
710#[cfg_attr(feature = "schemars", derive(JsonSchema))]
711#[serde(rename_all = "camelCase")]
712pub struct KanidmStorage {
713 /// EmptyDirVolumeSource to be used by the StatefulSet. If specified, it takes precedence over
714 /// `ephemeral` and `volumeClaimTemplate`.
715 /// More info: https://kubernetes.io/docs/concepts/storage/volumes/#emptydir
716 #[serde(skip_serializing_if = "Option::is_none")]
717 pub empty_dir: Option<EmptyDirVolumeSource>,
718
719 /// EphemeralVolumeSource to be used by the StatefulSet.
720 /// More info: https://kubernetes.io/docs/concepts/storage/ephemeral-volumes/#generic-ephemeral-volumes
721 #[serde(skip_serializing_if = "Option::is_none")]
722 pub ephemeral: Option<EphemeralVolumeSource>,
723
724 /// Defines the PVC spec to be used by the Kanidm StatefulSets. The easiest way to use a volume
725 /// that cannot be automatically provisioned is to use a label selector alongside manually
726 /// created PersistentVolumes.
727 #[serde(skip_serializing_if = "Option::is_none")]
728 pub volume_claim_template: Option<PersistentVolumeClaimTemplate>,
729}
730
731#[derive(Serialize, Deserialize, Clone, Debug, Default)]
732#[cfg_attr(feature = "schemars", derive(JsonSchema))]
733#[serde(rename_all = "camelCase")]
734pub struct KanidmService {
735 /// Annotations is an unstructured key value map stored with a resource that may be set by
736 /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
737 /// be preserved when modifying objects.
738 /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
739 #[serde(skip_serializing_if = "Option::is_none")]
740 pub annotations: Option<BTreeMap<String, String>>,
741
742 /// Specify the Service's type where the Kanidm Service is exposed
743 /// Please note that some Ingress controllers like https://github.com/kubernetes/ingress-gce
744 /// forces you to expose your Service on a NodePort
745 /// Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and
746 /// LoadBalancer. "ClusterIP" allocates a cluster-internal IP address for load-balancing to
747 /// endpoints. Endpoints are determined by the selector or if that is not specified, by manual
748 /// construction of an Endpoints object or EndpointSlice objects. If clusterIP is "None",
749 /// no virtual IP is allocated and the endpoints are published as a set of endpoints rather
750 /// than a virtual IP. "NodePort" builds on ClusterIP and allocates a port on every node which
751 /// routes to the same endpoints as the clusterIP. "LoadBalancer" builds on NodePort and creates
752 /// an external load-balancer (if supported in the current cloud) which routes to the same
753 /// endpoints as the clusterIP. "ExternalName" aliases this service to the specified
754 /// externalName. Several other fields do not apply to ExternalName services.
755 /// More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
756 #[serde(skip_serializing_if = "Option::is_none")]
757 pub type_: Option<String>,
758
759 /// Map of string keys and values that can be used to organize and categorize (scope and
760 /// select) objects. May match selectors of replication controllers and services.
761 /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels
762 #[serde(skip_serializing_if = "Option::is_none")]
763 pub additional_labels: Option<BTreeMap<String, String>>,
764}
765
766#[derive(Serialize, Deserialize, Clone, Debug, Default)]
767#[cfg_attr(feature = "schemars", derive(JsonSchema))]
768#[serde(rename_all = "camelCase")]
769pub struct KanidmIngress {
770 /// Annotations is an unstructured key value map stored with a resource that may be set by
771 /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
772 /// be preserved when modifying objects.
773 /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
774 #[serde(skip_serializing_if = "Option::is_none")]
775 pub annotations: Option<BTreeMap<String, String>>,
776
777 /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
778 /// implementations use this field to know whether they should be serving this Ingress resource,
779 /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
780 /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
781 /// it was widely supported by Ingress controllers to create a direct binding between Ingress
782 /// controller and Ingress resources. Newly created Ingress resources should prefer using the
783 /// field. However, even though the annotation is officially deprecated, for backwards
784 /// compatibility reasons, ingress controllers should still honor that annotation if present.
785 #[serde(skip_serializing_if = "Option::is_none")]
786 pub ingress_class_name: Option<String>,
787 /// Defines the name of the secret that contains the TLS private key and certificate for the
788 /// server. If not defined, the default will be the Kanidm name appended with `-tls`.
789 #[schemars(extend("x-kubernetes-validations" = [
790 {
791 "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
792 "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
793 }
794 ]))]
795 #[serde(skip_serializing_if = "Option::is_none")]
796 pub tls_secret_name: Option<String>,
797 /// Additional Subject Alternative Names (SANs) to include in the TLS certificate.
798 /// The main domain from the Kanidm spec is automatically included.
799 /// This does not add additional hosts to the ingress resource, only certificate SANs.
800 #[serde(skip_serializing_if = "Option::is_none")]
801 pub extra_tls_hosts: Option<BTreeSet<String>>,
802}
803
804#[derive(Serialize, Deserialize, Clone, Debug, Default)]
805#[cfg_attr(feature = "schemars", derive(JsonSchema))]
806#[serde(rename_all = "camelCase")]
807pub struct KanidmRegionIngress {
808 /// Region identifier for this ingress. Used as a subdomain of the main Kanidm domain to route
809 /// traffic for a specific region.
810 pub region: String,
811
812 /// Annotations is an unstructured key value map stored with a resource that may be set by
813 /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
814 /// be preserved when modifying objects.
815 /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
816 #[serde(skip_serializing_if = "Option::is_none")]
817 pub annotations: Option<BTreeMap<String, String>>,
818
819 /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
820 /// implementations use this field to know whether they should be serving this Ingress resource,
821 /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
822 /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
823 /// it was widely supported by Ingress controllers to create a direct binding between Ingress
824 /// controller and Ingress resources. Newly created Ingress resources should prefer using the
825 /// field. However, even though the annotation is officially deprecated, for backwards
826 /// compatibility reasons, ingress controllers should still honor that annotation if present.
827 #[serde(skip_serializing_if = "Option::is_none")]
828 pub ingress_class_name: Option<String>,
829 /// Defines the name of the secret that contains the TLS private key and certificate for the
830 /// server. If not defined, the default will be the Kanidm name appended with `-region-tls`.
831 #[schemars(extend("x-kubernetes-validations" = [
832 {
833 "message": "ingress.tlsSecretName must be a valid Kubernetes resource name.",
834 "rule": "self.matches(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$')"
835 }
836 ]))]
837 #[serde(skip_serializing_if = "Option::is_none")]
838 pub tls_secret_name: Option<String>,
839}
840
841#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
842#[cfg_attr(feature = "schemars", derive(JsonSchema))]
843#[serde(rename_all = "camelCase")]
844pub struct KanidmGatewayParentRef {
845 /// Group is the group of the referent.
846 /// When unspecified, defaults to "gateway.networking.k8s.io".
847 #[serde(skip_serializing_if = "Option::is_none")]
848 pub group: Option<String>,
849
850 /// Kind is the kind of the referent.
851 /// When unspecified, defaults to "Gateway".
852 #[serde(skip_serializing_if = "Option::is_none")]
853 pub kind: Option<String>,
854
855 /// Name of the referent.
856 pub name: String,
857
858 /// Namespace of the referent. When unspecified, this refers to the local namespace.
859 #[serde(skip_serializing_if = "Option::is_none")]
860 pub namespace: Option<String>,
861
862 /// SectionName is the name of a section within the target resource.
863 /// When specified, this must refer to a named section within the target resource,
864 /// such as a specific listener on a Gateway.
865 #[serde(skip_serializing_if = "Option::is_none")]
866 pub section_name: Option<String>,
867
868 /// Port is the network port this Route targets.
869 #[serde(skip_serializing_if = "Option::is_none")]
870 pub port: Option<u32>,
871}
872
873#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
874#[cfg_attr(feature = "schemars", derive(JsonSchema))]
875#[serde(rename_all = "camelCase")]
876pub struct KanidmGateway {
877 /// ParentRefs references the Gateway(s) that this HTTPRoute should be attached to.
878 /// Each ParentRef must reference a Gateway in the same namespace as the HTTPRoute.
879 #[schemars(extend("x-kubernetes-validations" = [{"message": "At least one ParentRef is required", "rule": "self.size() > 0"}]))]
880 #[validate(length(min = 1))]
881 pub parent_refs: Vec<KanidmGatewayParentRef>,
882
883 /// Hostnames defines a set of hostnames that should match against the HTTP Host
884 /// header to select a HTTPRoute used to process the request.
885 /// When unspecified, defaults to the Kanidm domain (spec.domain).
886 #[serde(skip_serializing_if = "Option::is_none")]
887 pub hostnames: Option<Vec<String>>,
888
889 /// Annotations is an unstructured key value map stored with a resource that may be set by
890 /// external tools to store and retrieve arbitrary metadata.
891 /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
892 #[serde(skip_serializing_if = "Option::is_none")]
893 pub annotations: Option<BTreeMap<String, String>>,
894
895 /// Rules defines a list of HTTPRoute rules.
896 /// Each rule consists of conditions for matching an HTTP request,
897 /// filters for processing it, and backend references for forwarding the request.
898 /// When unspecified, a default rule is created that routes all traffic to the Kanidm service.
899 /// This field allows customization of routing behavior, including session persistence,
900 /// timeouts, filters, and advanced matching conditions.
901 /// Note: The sessionPersistence field in rules is experimental and requires
902 /// Gateway API experimental channel support from the implementation.
903 #[serde(skip_serializing_if = "Option::is_none")]
904 pub rules: Option<Vec<HttpRouteRules>>,
905
906 /// BackendTLSPolicy configuration for TLS validation between the Gateway and Kanidm backend service.
907 /// When specified, creates a BackendTLSPolicy resource to validate TLS connections from the Gateway
908 /// to the Kanidm service (port 8443). This is required when using TLS between Gateway and backend.
909 /// When unspecified, no BackendTLSPolicy is created.
910 #[serde(skip_serializing_if = "Option::is_none")]
911 pub backend_tls_policy: Option<KanidmBackendTLSPolicy>,
912}
913
914#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
915#[cfg_attr(feature = "schemars", derive(JsonSchema))]
916#[serde(rename_all = "camelCase")]
917pub struct KanidmBackendTLSPolicy {
918 /// Annotations is an unstructured key value map stored with a resource that may be set by
919 /// external tools to store and retrieve arbitrary metadata.
920 /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
921 #[serde(skip_serializing_if = "Option::is_none")]
922 pub annotations: Option<BTreeMap<String, String>>,
923
924 /// Validation contains backend TLS validation configuration.
925 pub validation: KanidmBackendTLSPolicyValidation,
926}
927
928#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
929#[cfg_attr(feature = "schemars", derive(JsonSchema))]
930#[serde(rename_all = "camelCase")]
931pub struct KanidmBackendTLSPolicyValidation {
932 /// Hostname is the hostname used for TLS validation.
933 /// When unspecified, defaults to the Kanidm domain (spec.domain).
934 #[serde(skip_serializing_if = "Option::is_none")]
935 pub hostname: Option<String>,
936
937 /// WellKnownCACertificates specifies the type of CA certificates to use for validation.
938 /// When specified as "System", uses the system's trusted CA certificates.
939 /// This is the most common option for public certificates (e.g., Let's Encrypt).
940 #[serde(skip_serializing_if = "Option::is_none")]
941 pub well_known_ca_certificates: Option<String>,
942
943 /// CACertificateRefs references CA certificates for validation.
944 /// When specified, these certificates are used to validate the backend TLS connection.
945 /// Useful for private/internal certificates not in the system trust store.
946 #[serde(skip_serializing_if = "Option::is_none")]
947 pub ca_certificate_refs: Option<Vec<KanidmBackendTLSPolicyValidationCACertificateRef>>,
948}
949
950#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
951#[cfg_attr(feature = "schemars", derive(JsonSchema))]
952#[serde(rename_all = "camelCase")]
953pub struct KanidmBackendTLSPolicyValidationCACertificateRef {
954 /// Group is the group of the referent.
955 /// When unspecified, defaults to "" (core API group).
956 #[serde(skip_serializing_if = "Option::is_none")]
957 pub group: Option<String>,
958
959 /// Kind is the kind of the referent.
960 /// When unspecified, defaults to "Secret".
961 #[serde(skip_serializing_if = "Option::is_none")]
962 pub kind: Option<String>,
963
964 /// Name of the referent (the Secret containing the CA certificate).
965 pub name: String,
966}
967
968/// Most recent observed status of the Kanidm cluster. Read-only.
969/// More info:
970/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
971#[derive(Serialize, Deserialize, Clone, Debug, Default)]
972#[cfg_attr(feature = "schemars", derive(JsonSchema))]
973#[serde(rename_all = "camelCase")]
974pub struct KanidmStatus {
975 /// Total number of available pods (ready for at least minReadySeconds) targeted by this Kanidm
976 /// deployment.
977 pub available_replicas: i32,
978
979 #[serde(skip_serializing_if = "Option::is_none")]
980 #[cfg_attr(
981 feature = "schemars",
982 schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
983 )]
984 pub conditions: Option<Vec<Condition>>,
985
986 /// Total number of non-terminated pods targeted by this Kanidm cluster.
987 pub replicas: i32,
988
989 /// Total number of unavailable pods targeted by this Kanidm cluster.
990 pub unavailable_replicas: i32,
991
992 /// Total number of non-terminated pods targeted by this Kanidm cluster that have the
993 /// desired version spec.
994 pub updated_replicas: i32,
995
996 /// Status per replica in the Kanidm cluster.
997 pub replica_statuses: Vec<KanidmReplicaStatus>,
998
999 /// Ready vs desired replicas.
1000 pub replica_column: String,
1001
1002 /// Admin users secret name.
1003 pub secret_name: Option<String>,
1004
1005 /// The current version of the Kanidm server.
1006 pub version: Option<KanidmVersionStatus>,
1007
1008 /// Status of the domain appearance image.
1009 pub domain_appearance_image: Option<DomainAppearanceImageStatus>,
1010
1011 /// Status of the mail sender deployment.
1012 #[serde(skip_serializing_if = "Option::is_none")]
1013 pub mail_sender: Option<MailSenderStatus>,
1014}
1015
1016#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
1017#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1018#[serde(rename_all = "camelCase")]
1019pub struct MailSenderStatus {
1020 /// Name of the service account in Kanidm for mail sending.
1021 /// Format: `<kanidm-name>-mail-sender`
1022 pub service_account_name: String,
1023
1024 /// Name of the Kubernetes secret containing the API token.
1025 /// Format: `<kanidm-name>-mail-sender-token`
1026 pub token_secret_name: String,
1027
1028 /// Name of the Deployment running the mail sender.
1029 /// Format: `<kanidm-name>-mail-sender`
1030 pub deployment_name: String,
1031
1032 /// Name of the ConfigMap containing mail sender configuration.
1033 /// Format: `<kanidm-name>-mail-sender-config`
1034 pub config_map_name: String,
1035
1036 /// The unique identifier for the API token in Kanidm, used for management operations.
1037 #[serde(skip_serializing_if = "Option::is_none")]
1038 pub token_id: Option<String>,
1039
1040 /// Whether the mail sender deployment is ready.
1041 pub ready: bool,
1042}
1043
1044#[derive(Serialize, Deserialize, Clone, Debug)]
1045#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1046#[serde(rename_all = "camelCase")]
1047pub struct KanidmReplicaStatus {
1048 /// Pod name: replica group StatefulSet name plus the pod index.
1049 pub pod_name: String,
1050
1051 /// StatefulSet name: Kanidm name plus the replica group name.
1052 pub statefulset_name: String,
1053
1054 /// The current state of the replica.
1055 pub state: KanidmReplicaState,
1056}
1057
1058#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
1059#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1060#[serde(rename_all = "camelCase")]
1061pub enum KanidmReplicaState {
1062 Ready,
1063 Pending,
1064 CertificateExpiring,
1065 CertificateHostInvalid,
1066}
1067
1068#[derive(Serialize, Deserialize, Clone, Debug)]
1069#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1070#[serde(rename_all = "camelCase")]
1071pub struct KanidmVersionStatus {
1072 pub image_tag: String,
1073
1074 pub upgrade_check_result: KanidmUpgradeCheckResult,
1075
1076 #[serde(default)]
1077 pub compatibility_result: VersionCompatibilityResult,
1078}
1079
1080#[derive(Serialize, Deserialize, Clone, PartialEq, Debug, Default)]
1081#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1082#[serde(rename_all = "snake_case")]
1083pub enum VersionCompatibilityResult {
1084 #[default]
1085 Compatible,
1086 Incompatible,
1087}
1088
1089#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
1090#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1091#[serde(rename_all = "snake_case")]
1092pub enum KanidmUpgradeCheckResult {
1093 Passed,
1094 Failed,
1095}
1096
1097#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
1098#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1099#[serde(rename_all = "camelCase")]
1100pub struct DomainAppearanceImageStatus {
1101 /// The URL from which the image was last fetched.
1102 pub url: String,
1103 /// ETag header from the last fetch (for change detection).
1104 #[serde(skip_serializing_if = "Option::is_none")]
1105 pub etag: Option<String>,
1106 /// Last-Modified header from the last fetch.
1107 #[serde(skip_serializing_if = "Option::is_none")]
1108 pub last_modified: Option<String>,
1109 /// Content-Length from the last fetch.
1110 #[serde(skip_serializing_if = "Option::is_none")]
1111 pub content_length: Option<u64>,
1112 /// Hash of the image content (SHA-256, for validation).
1113 #[serde(skip_serializing_if = "Option::is_none")]
1114 pub content_hash: Option<String>,
1115}
1116
1117#[cfg(test)]
1118mod tests {
1119 use super::*;
1120 use k8s_openapi::api::core::v1::PersistentVolumeClaimSpec;
1121 use serde_json::json;
1122
1123 #[test]
1124 fn test_pvc_template_optional_metadata() {
1125 // Test that we can create a PVC template without metadata
1126 let pvc_template = PersistentVolumeClaimTemplate {
1127 metadata: None,
1128 spec: Some(PersistentVolumeClaimSpec::default()),
1129 };
1130
1131 // Test that it can be converted to a k8s PVC
1132 let k8s_pvc = pvc_template.to_persistent_volume_claim();
1133 assert_eq!(k8s_pvc.metadata, ObjectMeta::default());
1134 assert_eq!(k8s_pvc.spec, pvc_template.spec);
1135 }
1136
1137 #[test]
1138 fn test_pvc_template_with_metadata() {
1139 let custom_metadata = ObjectMeta {
1140 name: Some("test-pvc".to_string()),
1141 labels: Some([("app".to_string(), "test".to_string())].into()),
1142 ..ObjectMeta::default()
1143 };
1144
1145 // Test that we can create a PVC template with metadata
1146 let pvc_template = PersistentVolumeClaimTemplate {
1147 metadata: Some(custom_metadata.clone()),
1148 spec: Some(PersistentVolumeClaimSpec::default()),
1149 };
1150
1151 // Test that it can be converted to a k8s PVC
1152 let k8s_pvc = pvc_template.to_persistent_volume_claim();
1153 assert_eq!(k8s_pvc.metadata, custom_metadata);
1154 assert_eq!(k8s_pvc.spec, pvc_template.spec);
1155 }
1156
1157 #[test]
1158 fn test_kanidm_version_status_backward_compatible() {
1159 let legacy_payload = json!({
1160 "imageTag": "1.9.0",
1161 "upgradeCheckResult": "passed"
1162 });
1163
1164 let status: KanidmVersionStatus =
1165 serde_json::from_value(legacy_payload).expect("legacy status should deserialize");
1166
1167 assert_eq!(status.image_tag, "1.9.0");
1168 assert_eq!(
1169 status.upgrade_check_result,
1170 KanidmUpgradeCheckResult::Passed
1171 );
1172 assert_eq!(
1173 status.compatibility_result,
1174 VersionCompatibilityResult::Compatible
1175 );
1176 }
1177}