1use chrono::{DateTime, SecondsFormat, Utc};
2use k8s_openapi::apimachinery::pkg::apis::meta::v1::Condition;
3use kube::CustomResource;
4#[cfg(feature = "schemars")]
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize, Serializer};
7
8#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, PartialEq)]
9#[cfg_attr(feature = "schemars", derive(JsonSchema))]
10#[cfg_attr(
11 feature = "schemars",
12 schemars(extend("x-kubernetes-validations" = [
13 {
14 "message": "s3.bucket is immutable after creation. To use a different bucket, delete this KanidmBackupRepository and create a new one. Existing Backup CRs referencing this repository are not affected, but remote S3 data in the old bucket remains accessible only through the old Repository.",
15 "rule": "self.s3.bucket == oldSelf.s3.bucket"
16 },
17 {
18 "message": "s3.prefix is immutable after creation. To use a different prefix, delete this KanidmBackupRepository and create a new one. Existing Backup CRs referencing this repository are not affected, but remote S3 data under the old prefix remains accessible only through the old Repository.",
19 "rule": "self.s3.prefix == oldSelf.s3.prefix"
20 },
21 {
22 "message": "s3.endpoint is immutable after creation. To use a different endpoint, delete this KanidmBackupRepository and create a new one. Existing Backup CRs referencing this repository are not affected, but remote S3 data at the old endpoint remains accessible only through the old Repository.",
23 "rule": "self.s3.endpoint == oldSelf.s3.endpoint"
24 }
25 ]))
26)]
27#[kube(
28 category = "kaniop",
29 group = "kaniop.rs",
30 version = "v1alpha1",
31 kind = "KanidmBackupRepository",
32 plural = "kanidmbackuprepositories",
33 singular = "kanidmbackuprepository",
34 shortname = "kbr",
35 namespaced,
36 status = "KanidmBackupRepositoryStatus",
37 printcolumn = r#"{"name":"Bucket","type":"string","jsonPath":".spec.s3.bucket"}"#,
38 printcolumn = r#"{"name":"Prefix","type":"string","jsonPath":".spec.s3.prefix"}"#,
39 printcolumn = r#"{"name":"Ready","type":"string","jsonPath":".status.conditions[?(@.type=='Ready')].status"}"#,
40 printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#
41)]
42#[serde(rename_all = "camelCase")]
43pub struct KanidmBackupRepositorySpec {
44 pub s3: S3Config,
46 pub authentication: RepositoryAuthentication,
48 #[serde(skip_serializing_if = "Option::is_none")]
52 pub encryption: Option<RepositoryEncryption>,
53 #[serde(skip_serializing_if = "Option::is_none")]
55 pub limits: Option<RepositoryLimits>,
56}
57
58#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
59#[cfg_attr(feature = "schemars", derive(JsonSchema))]
60#[serde(rename_all = "camelCase")]
61pub struct CaBundleRef {
62 pub name: String,
64 pub key: String,
66}
67
68#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
69#[cfg_attr(feature = "schemars", derive(JsonSchema))]
70#[cfg_attr(
71 feature = "schemars",
72 schemars(extend("x-kubernetes-validations" = [
73 {
74 "message": "endpoint must use HTTPS unless insecure is enabled",
75 "rule": "self.endpoint.startsWith('https://') || self.insecure"
76 }
77 ]))
78)]
79#[serde(rename_all = "camelCase")]
80pub struct S3Config {
81 #[schemars(extend("x-kubernetes-validations" = [{"message": "bucket must not be empty", "rule": "self.size() > 0"}]))]
85 pub bucket: String,
86 #[schemars(extend("x-kubernetes-validations" = [{"message": "prefix must not contain path traversal segments", "rule": "!self.contains('..')"}]))]
90 pub prefix: String,
91 pub region: String,
93 pub endpoint: String,
97 #[serde(default)]
99 pub force_path_style: bool,
100 #[serde(skip_serializing_if = "Option::is_none")]
102 pub ca_bundle_ref: Option<CaBundleRef>,
103 #[serde(default)]
105 pub insecure: bool,
106}
107
108#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
109#[cfg_attr(feature = "schemars", derive(JsonSchema))]
110#[serde(rename_all = "camelCase")]
111pub struct RepositoryAuthentication {
112 pub writer: AuthMethod,
113 pub reader: AuthMethod,
114 pub deleter: AuthMethod,
115}
116
117#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
118#[cfg_attr(feature = "schemars", derive(JsonSchema))]
119#[cfg_attr(
120 feature = "schemars",
121 schemars(extend("x-kubernetes-validations" = [
122 {
123 "message": "exactly one of workloadIdentity or secretRef must be set",
124 "rule": "(has(self.workloadIdentity) ? 1 : 0) + (has(self.secretRef) ? 1 : 0) == 1"
125 }
126 ]))
127)]
128#[serde(rename_all = "camelCase")]
129pub struct AuthMethod {
130 #[serde(skip_serializing_if = "Option::is_none")]
131 pub workload_identity: Option<WorkloadIdentity>,
132 #[serde(skip_serializing_if = "Option::is_none")]
133 pub secret_ref: Option<SecretRef>,
134}
135
136#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
137#[cfg_attr(feature = "schemars", derive(JsonSchema))]
138#[serde(rename_all = "camelCase")]
139pub struct WorkloadIdentity {
140 #[serde(skip_serializing_if = "Option::is_none")]
141 pub audience: Option<String>,
142}
143
144#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
145#[cfg_attr(feature = "schemars", derive(JsonSchema))]
146#[serde(rename_all = "camelCase")]
147pub struct SecretRef {
148 pub name: String,
149}
150
151#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
152#[cfg_attr(feature = "schemars", derive(JsonSchema))]
153#[serde(rename_all = "camelCase")]
154pub struct EncryptionKeyRef {
155 pub name: String,
157 #[serde(default = "default_encryption_key")]
159 pub key: String,
160}
161
162fn default_encryption_key() -> String {
163 crate::auth::ENCRYPTION_KEY_SECRET_ENTRY.to_string()
164}
165
166#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
167#[cfg_attr(feature = "schemars", derive(JsonSchema))]
168#[cfg_attr(
169 feature = "schemars",
170 schemars(extend("x-kubernetes-validations" = [
171 {
172 "message": "keyId is required when mode is providerKms and forbidden otherwise",
173 "rule": "(self.mode == 'providerKms') == has(self.keyId)"
174 },
175 {
176 "message": "keyRef is required when mode is clientSide and forbidden otherwise",
177 "rule": "(self.mode == 'clientSide') == has(self.keyRef)"
178 }
179 ]))
180)]
181#[serde(rename_all = "camelCase")]
182pub struct RepositoryEncryption {
183 pub mode: EncryptionMode,
184 #[serde(skip_serializing_if = "Option::is_none")]
185 pub key_id: Option<String>,
186 #[serde(skip_serializing_if = "Option::is_none")]
187 pub key_ref: Option<EncryptionKeyRef>,
188}
189
190#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
191#[cfg_attr(feature = "schemars", derive(JsonSchema))]
192pub enum EncryptionMode {
193 #[serde(rename = "providerManaged")]
194 ProviderManaged,
195 #[serde(rename = "providerKms")]
196 ProviderKms,
197 #[serde(rename = "clientSide")]
198 ClientSide,
199}
200
201#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
202#[cfg_attr(feature = "schemars", derive(JsonSchema))]
203#[cfg_attr(
204 feature = "schemars",
205 schemars(extend("x-kubernetes-validations" = [
206 {
207 "message": "maxConcurrentParts must be between 1 and 64",
208 "rule": "self.maxConcurrentParts >= 1 && self.maxConcurrentParts <= 64"
209 }
210 ]))
211)]
212#[serde(rename_all = "camelCase")]
213pub struct RepositoryLimits {
214 #[serde(skip_serializing_if = "Option::is_none")]
215 pub max_upload_bytes_per_second: Option<u64>,
216 #[serde(skip_serializing_if = "Option::is_none")]
217 pub max_download_bytes_per_second: Option<u64>,
218 #[serde(default = "default_max_concurrent_parts")]
219 pub max_concurrent_parts: u32,
220 #[serde(default = "default_safety_backup_retention")]
221 #[cfg_attr(
222 feature = "schemars",
223 schemars(extend("x-kubernetes-validations" = [{
224 "message": "safetyBackupMinRetention must contain digits with optional h or d suffix",
225 "rule": "self.matches('^[0-9]+[hd]?$')"
226 }]))
227 )]
228 pub safety_backup_min_retention: String,
229}
230
231fn default_max_concurrent_parts() -> u32 {
232 4
233}
234
235fn default_safety_backup_retention() -> String {
236 "720h".to_string()
237}
238
239#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
240#[cfg_attr(feature = "schemars", derive(JsonSchema))]
241#[serde(rename_all = "camelCase")]
242pub struct KanidmBackupRepositoryStatus {
243 #[serde(skip_serializing_if = "Option::is_none")]
244 pub observed_generation: Option<i64>,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
248 pub usage_started: Option<bool>,
249 #[serde(default, skip_serializing_if = "Vec::is_empty")]
250 #[cfg_attr(
251 feature = "schemars",
252 schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
253 )]
254 pub conditions: Vec<Condition>,
255}
256
257#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, PartialEq)]
258#[cfg_attr(feature = "schemars", derive(JsonSchema))]
259#[cfg_attr(
260 feature = "schemars",
261 schemars(extend("x-kubernetes-validations" = [
262 {
263 "message": "kanidmRef is immutable after creation. To target a different Kanidm, delete this KanidmBackupSchedule and create a new one. Existing Backup CRs and remote S3 data are not affected by Schedule deletion.",
264 "rule": "self.kanidmRef == oldSelf.kanidmRef"
265 },
266 {
267 "message": "repositoryRef is immutable after creation. To use a different repository, delete this KanidmBackupSchedule and create a new one. Existing Backup CRs and remote S3 data are not affected by Schedule deletion.",
268 "rule": "self.repositoryRef == oldSelf.repositoryRef"
269 },
270 {
271 "message": "schedule is immutable after creation. To change the cron schedule, delete this KanidmBackupSchedule and create a new one. Existing Backup CRs and remote S3 data are not affected by Schedule deletion.",
272 "rule": "self.schedule == oldSelf.schedule"
273 },
274 {
275 "message": "retention is immutable after creation. To change retention policy, delete this KanidmBackupSchedule and create a new one. Existing Backup CRs and remote S3 data are not affected by Schedule deletion; retention is applied at discovery time based on the current Schedule spec.",
276 "rule": "!has(oldSelf.retention) || self.retention == oldSelf.retention"
277 },
278 {
279 "message": "concurrencyPolicy must be Forbid",
280 "rule": "self.concurrencyPolicy == 'Forbid'"
281 },
282 {
283 "message": "localVersions must be between 2 and 3650",
284 "rule": "self.localVersions >= 2 && self.localVersions <= 3650"
285 }
286 ]))
287)]
288#[kube(
289 category = "kaniop",
290 group = "kaniop.rs",
291 version = "v1alpha1",
292 kind = "KanidmBackupSchedule",
293 plural = "kanidmbackupschedules",
294 singular = "kanidmbackupschedule",
295 shortname = "kbs",
296 namespaced,
297 status = "KanidmBackupScheduleStatus",
298 printcolumn = r#"{"name":"Kanidm","type":"string","jsonPath":".spec.kanidmRef.name"}"#,
299 printcolumn = r#"{"name":"Schedule","type":"string","jsonPath":".spec.schedule"}"#,
300 printcolumn = r#"{"name":"Suspended","type":"boolean","jsonPath":".spec.suspend"}"#,
301 printcolumn = r#"{"name":"Ready","type":"string","jsonPath":".status.conditions[?(@.type=='Ready')].status"}"#,
302 printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#
303)]
304#[serde(rename_all = "camelCase")]
305pub struct KanidmBackupScheduleSpec {
306 pub kanidm_ref: ScheduleKanidmRef,
311 pub repository_ref: ScheduleRepositoryRef,
316 pub schedule: String,
328 #[serde(default = "default_timezone")]
330 pub time_zone: String,
331 #[serde(default)]
334 pub suspend: bool,
335 #[serde(default = "default_concurrency_policy")]
337 pub concurrency_policy: String,
338 #[serde(skip_serializing_if = "Option::is_none")]
340 pub jitter_seconds: Option<u32>,
341 #[serde(default = "default_local_versions")]
346 pub local_versions: u32,
347 #[serde(skip_serializing_if = "Option::is_none")]
353 pub retention: Option<RetentionPolicySpec>,
354}
355
356fn default_timezone() -> String {
357 "UTC".to_string()
358}
359
360fn default_concurrency_policy() -> String {
361 "Forbid".to_string()
362}
363
364fn default_local_versions() -> u32 {
365 7
366}
367
368#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
369#[cfg_attr(feature = "schemars", derive(JsonSchema))]
370#[serde(rename_all = "camelCase")]
371pub struct ScheduleKanidmRef {
372 pub name: String,
373}
374
375#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
376#[cfg_attr(feature = "schemars", derive(JsonSchema))]
377#[serde(rename_all = "camelCase")]
378pub struct ScheduleRepositoryRef {
379 pub name: String,
380}
381
382#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
383#[cfg_attr(feature = "schemars", derive(JsonSchema))]
384#[cfg_attr(
385 feature = "schemars",
386 schemars(extend("x-kubernetes-validations" = [
387 {
388 "message": "keepLast must be between 1 and 3650",
389 "rule": "self.keepLast >= 1 && self.keepLast <= 3650"
390 },
391 {
392 "message": "daily must be between 0 and 3650",
393 "rule": "self.daily >= 0 && self.daily <= 3650"
394 },
395 {
396 "message": "weekly must be between 0 and 520",
397 "rule": "self.weekly >= 0 && self.weekly <= 520"
398 },
399 {
400 "message": "monthly must be between 0 and 120",
401 "rule": "self.monthly >= 0 && self.monthly <= 120"
402 }
403 ]))
404)]
405#[serde(rename_all = "camelCase")]
406pub struct RetentionPolicySpec {
407 #[serde(default = "default_keep_last")]
408 pub keep_last: u32,
409 #[serde(default = "default_daily")]
410 pub daily: u32,
411 #[serde(default = "default_weekly")]
412 pub weekly: u32,
413 #[serde(default = "default_monthly")]
414 pub monthly: u32,
415 #[serde(default = "default_min_age")]
416 #[cfg_attr(
417 feature = "schemars",
418 schemars(extend("x-kubernetes-validations" = [{
419 "message": "minAge must contain digits with optional h or d suffix",
420 "rule": "self.matches('^[0-9]+[hd]?$')"
421 }]))
422 )]
423 pub min_age: String,
424}
425
426fn default_keep_last() -> u32 {
427 8
428}
429
430fn default_daily() -> u32 {
431 7
432}
433
434fn default_weekly() -> u32 {
435 4
436}
437
438fn default_monthly() -> u32 {
439 12
440}
441
442fn default_min_age() -> String {
443 "24h".to_string()
444}
445
446#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
447#[cfg_attr(feature = "schemars", derive(JsonSchema))]
448#[serde(rename_all = "camelCase")]
449pub struct DiscoveryStatus {
450 #[serde(skip_serializing_if = "Option::is_none")]
451 pub last_scan_time: Option<String>,
452 #[serde(skip_serializing_if = "Option::is_none")]
453 pub last_successful_scan_time: Option<String>,
454 #[serde(skip_serializing_if = "Option::is_none")]
455 #[cfg_attr(feature = "schemars", schemars(extend("x-kubernetes-validations" = [{"message": "lastDiscoveredCount must be non-negative", "rule": "self >= 0"}])))]
456 pub last_discovered_count: Option<u32>,
457 #[serde(skip_serializing_if = "Option::is_none")]
458 pub last_error: Option<String>,
459 #[serde(default, skip_serializing_if = "Vec::is_empty")]
460 #[cfg_attr(
461 feature = "schemars",
462 schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
463 )]
464 pub conditions: Vec<Condition>,
465}
466
467#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
468#[cfg_attr(feature = "schemars", derive(JsonSchema))]
469#[serde(rename_all = "camelCase")]
470pub struct KanidmBackupScheduleStatus {
471 #[serde(skip_serializing_if = "Option::is_none")]
472 pub observed_generation: Option<i64>,
473 #[serde(skip_serializing_if = "Option::is_none")]
474 pub last_discovered_backup_ref: Option<String>,
475 #[serde(skip_serializing_if = "Option::is_none")]
476 pub last_successful_backup_time: Option<String>,
477 #[serde(default, skip_serializing_if = "Vec::is_empty")]
478 #[cfg_attr(
479 feature = "schemars",
480 schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
481 )]
482 pub conditions: Vec<Condition>,
483 #[serde(skip_serializing_if = "Option::is_none")]
484 pub discovery: Option<DiscoveryStatus>,
485}
486
487#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, PartialEq)]
488#[cfg_attr(feature = "schemars", derive(JsonSchema))]
489#[cfg_attr(
490 feature = "schemars",
491 schemars(extend("x-kubernetes-validations" = [
492 {
493 "message": "KanidmBackup spec is immutable",
494 "rule": "self == oldSelf"
495 }
496 ]))
497)]
498#[kube(
499 category = "kaniop",
500 group = "kaniop.rs",
501 version = "v1alpha1",
502 kind = "KanidmBackup",
503 plural = "kanidmbackups",
504 singular = "kanidmbackup",
505 shortname = "kb",
506 namespaced,
507 status = "KanidmBackupStatus",
508 printcolumn = r#"{"name":"Kanidm","type":"string","jsonPath":".spec.kanidmRef.name"}"#,
509 printcolumn = r#"{"name":"Backup Date","type":"string","jsonPath":".status.createdAt"}"#,
510 printcolumn = r#"{"name":"Version","type":"string","jsonPath":".status.kanidmVersion"}"#,
511 printcolumn = r#"{"name":"Phase","type":"string","jsonPath":".status.phase"}"#,
512 printcolumn = r#"{"name":"Consistency","type":"string","jsonPath":".status.consistency"}"#,
513 printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#
514)]
515#[serde(rename_all = "camelCase")]
516pub struct KanidmBackupSpec {
517 pub backup_id: String,
518 pub kanidm_ref: BackupKanidmRef,
519 pub repository_ref: BackupRepositoryRef,
520 pub manifest_key: String,
521}
522
523#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
524#[cfg_attr(feature = "schemars", derive(JsonSchema))]
525#[serde(rename_all = "camelCase")]
526pub struct BackupKanidmRef {
527 pub name: String,
528 pub uid: String,
529}
530
531#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
532#[cfg_attr(feature = "schemars", derive(JsonSchema))]
533#[serde(rename_all = "camelCase")]
534pub struct BackupRepositoryRef {
535 pub name: String,
536}
537
538#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
539#[cfg_attr(feature = "schemars", derive(JsonSchema))]
540pub enum KanidmBackupPhase {
541 #[default]
542 Discovering,
543 Ready,
544 Deleting,
545 Deleted,
546 Invalid,
547}
548
549fn serialize_backup_created_at<S>(
550 created_at: &Option<String>,
551 serializer: S,
552) -> Result<S::Ok, S::Error>
553where
554 S: Serializer,
555{
556 match created_at {
557 Some(created_at) => {
558 let formatted = DateTime::parse_from_rfc3339(created_at)
559 .map(|timestamp| {
560 timestamp
561 .with_timezone(&Utc)
562 .to_rfc3339_opts(SecondsFormat::Secs, true)
563 })
564 .unwrap_or_else(|_| created_at.clone());
565 serializer.serialize_some(&formatted)
566 }
567 None => serializer.serialize_none(),
568 }
569}
570
571#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
572#[cfg_attr(feature = "schemars", derive(JsonSchema))]
573#[serde(rename_all = "camelCase")]
574pub struct KanidmBackupStatus {
575 #[serde(skip_serializing_if = "Option::is_none")]
576 pub observed_generation: Option<i64>,
577 #[serde(default)]
578 pub phase: KanidmBackupPhase,
579 #[serde(skip_serializing_if = "Option::is_none")]
580 pub consistency: Option<String>,
581 #[serde(skip_serializing_if = "Option::is_none")]
582 pub reason: Option<String>,
583 #[serde(skip_serializing_if = "Option::is_none")]
584 pub kanidm_version: Option<String>,
585 #[serde(skip_serializing_if = "Option::is_none")]
586 pub image_digest: Option<String>,
587 #[serde(skip_serializing_if = "Option::is_none")]
588 pub size_bytes: Option<u64>,
589 #[serde(skip_serializing_if = "Option::is_none")]
590 pub payload_sha256: Option<String>,
591 #[serde(
592 skip_serializing_if = "Option::is_none",
593 serialize_with = "serialize_backup_created_at"
594 )]
595 pub created_at: Option<String>,
596 #[serde(default, skip_serializing_if = "Vec::is_empty")]
597 #[cfg_attr(
598 feature = "schemars",
599 schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
600 )]
601 pub conditions: Vec<Condition>,
602}
603
604#[cfg(test)]
605mod tests {
606 use super::*;
607
608 #[test]
609 fn encryption_key_ref_defaults_key() {
610 let key_ref: EncryptionKeyRef =
611 serde_json::from_value(serde_json::json!({"name": "kek"})).unwrap();
612 assert_eq!(key_ref.key, "encryption-key");
613 }
614
615 #[test]
616 fn ca_bundle_ref_serialization() {
617 let ca_ref = CaBundleRef {
618 name: "homelab-ca".to_string(),
619 key: "ca.crt".to_string(),
620 };
621 let json = serde_json::to_value(&ca_ref).unwrap();
622 assert_eq!(
623 json,
624 serde_json::json!({"name": "homelab-ca", "key": "ca.crt"})
625 );
626 assert_eq!(serde_json::from_value::<CaBundleRef>(json).unwrap(), ca_ref);
627 assert!(
628 serde_json::from_value::<CaBundleRef>(serde_json::json!({"name": "homelab-ca"}))
629 .is_err()
630 );
631 }
632
633 #[test]
634 fn repository_spec_serialization() {
635 let spec = KanidmBackupRepositorySpec {
636 s3: S3Config {
637 bucket: "my-bucket".to_string(),
638 prefix: "prod".to_string(),
639 region: "eu-west-1".to_string(),
640 endpoint: "https://s3.eu-west-1.amazonaws.com".to_string(),
641 force_path_style: false,
642 ca_bundle_ref: None,
643 insecure: false,
644 },
645 authentication: RepositoryAuthentication {
646 writer: AuthMethod {
647 workload_identity: Some(WorkloadIdentity { audience: None }),
648 secret_ref: None,
649 },
650 reader: AuthMethod {
651 workload_identity: Some(WorkloadIdentity { audience: None }),
652 secret_ref: None,
653 },
654 deleter: AuthMethod {
655 workload_identity: Some(WorkloadIdentity { audience: None }),
656 secret_ref: None,
657 },
658 },
659 encryption: Some(RepositoryEncryption {
660 mode: EncryptionMode::ProviderKms,
661 key_id: Some("alias/kaniop-backups".to_string()),
662 key_ref: None,
663 }),
664 limits: Some(RepositoryLimits {
665 max_upload_bytes_per_second: Some(52428800),
666 max_download_bytes_per_second: Some(104857600),
667 max_concurrent_parts: 4,
668 safety_backup_min_retention: "720h".to_string(),
669 }),
670 };
671 let json = serde_json::to_string(&spec).unwrap();
672 assert!(json.contains("my-bucket"));
673 assert!(json.contains("providerKms"));
674 }
675
676 #[test]
677 fn schedule_spec_defaults() {
678 let json = r#"{
679 "kanidmRef": {"name": "corp-idm"},
680 "repositoryRef": {"name": "offsite"},
681 "schedule": "3 */6 * * *"
682 }"#;
683 let spec: KanidmBackupScheduleSpec = serde_json::from_str(json).unwrap();
684 assert_eq!(spec.time_zone, "UTC");
685 assert_eq!(spec.concurrency_policy, "Forbid");
686 assert_eq!(spec.local_versions, 7);
687 assert!(!spec.suspend);
688 }
689
690 #[test]
691 fn backup_phase_default() {
692 let phase = KanidmBackupPhase::default();
693 assert_eq!(phase, KanidmBackupPhase::Discovering);
694 }
695
696 #[test]
697 fn backup_spec_is_immutable() {
698 let spec = KanidmBackupSpec {
699 backup_id: "019c7c76-f423-7a12-8f41-2bea7588a303".to_string(),
700 kanidm_ref: BackupKanidmRef {
701 name: "corp-idm".to_string(),
702 uid: "9e630aed".to_string(),
703 },
704 repository_ref: BackupRepositoryRef {
705 name: "offsite".to_string(),
706 },
707 manifest_key: "v1/tenants/ns/clusters/k/backups/b/manifest.json".to_string(),
708 };
709 let json = serde_json::to_string(&spec).unwrap();
710 let parsed: KanidmBackupSpec = serde_json::from_str(&json).unwrap();
711 assert_eq!(spec, parsed);
712 }
713
714 #[test]
715 fn retention_policy_spec_defaults() {
716 let json = r#"{}"#;
717 let spec: RetentionPolicySpec = serde_json::from_str(json).unwrap();
718 assert_eq!(spec.keep_last, 8);
719 assert_eq!(spec.daily, 7);
720 assert_eq!(spec.weekly, 4);
721 assert_eq!(spec.monthly, 12);
722 assert_eq!(spec.min_age, "24h");
723 }
724
725 #[test]
726 fn backup_status_serialization_formats_created_at() {
727 let status = KanidmBackupStatus {
728 created_at: Some("2026-08-31T11:34:46.913205633+02:00".to_string()),
729 ..Default::default()
730 };
731
732 let serialized = serde_json::to_value(&status).unwrap();
733
734 assert_eq!(serialized["createdAt"], "2026-08-31T09:34:46Z");
735 assert_eq!(
736 status.created_at.as_deref(),
737 Some("2026-08-31T11:34:46.913205633+02:00")
738 );
739 }
740
741 #[test]
742 fn backup_printer_columns_show_date_and_version() {
743 use kube::CustomResourceExt;
744
745 let crd = serde_json::to_value(KanidmBackup::crd()).unwrap();
746 let columns = &crd["spec"]["versions"][0]["additionalPrinterColumns"];
747 let columns = columns.as_array().unwrap();
748 let backup_date = columns
749 .iter()
750 .find(|column| column["name"] == "Backup Date")
751 .unwrap();
752 let age = columns
753 .iter()
754 .find(|column| column["name"] == "Age")
755 .unwrap();
756 let serialized = serde_json::to_string(columns).unwrap();
757
758 assert_eq!(backup_date["type"], "string");
759 assert_eq!(backup_date["jsonPath"], ".status.createdAt");
760 assert_eq!(age["type"], "date");
761 assert_eq!(age["jsonPath"], ".metadata.creationTimestamp");
762 assert!(serialized.contains("Version"));
763 assert!(serialized.contains(".status.kanidmVersion"));
764 assert!(!serialized.contains("BackupID"));
765 }
766}