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 pub safety_backup_min_retention: String,
222}
223
224fn default_max_concurrent_parts() -> u32 {
225 4
226}
227
228fn default_safety_backup_retention() -> String {
229 "720h".to_string()
230}
231
232#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
233#[cfg_attr(feature = "schemars", derive(JsonSchema))]
234#[serde(rename_all = "camelCase")]
235pub struct KanidmBackupRepositoryStatus {
236 #[serde(skip_serializing_if = "Option::is_none")]
237 pub observed_generation: Option<i64>,
238 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub usage_started: Option<bool>,
242 #[serde(default, skip_serializing_if = "Vec::is_empty")]
243 #[cfg_attr(
244 feature = "schemars",
245 schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
246 )]
247 pub conditions: Vec<Condition>,
248}
249
250#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, PartialEq)]
251#[cfg_attr(feature = "schemars", derive(JsonSchema))]
252#[cfg_attr(
253 feature = "schemars",
254 schemars(extend("x-kubernetes-validations" = [
255 {
256 "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.",
257 "rule": "self.kanidmRef == oldSelf.kanidmRef"
258 },
259 {
260 "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.",
261 "rule": "self.repositoryRef == oldSelf.repositoryRef"
262 },
263 {
264 "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.",
265 "rule": "self.schedule == oldSelf.schedule"
266 },
267 {
268 "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.",
269 "rule": "!has(oldSelf.retention) || self.retention == oldSelf.retention"
270 },
271 {
272 "message": "concurrencyPolicy must be Forbid",
273 "rule": "self.concurrencyPolicy == 'Forbid'"
274 },
275 {
276 "message": "localVersions must be between 1 and 3650",
277 "rule": "self.localVersions >= 1 && self.localVersions <= 3650"
278 }
279 ]))
280)]
281#[kube(
282 category = "kaniop",
283 group = "kaniop.rs",
284 version = "v1alpha1",
285 kind = "KanidmBackupSchedule",
286 plural = "kanidmbackupschedules",
287 singular = "kanidmbackupschedule",
288 shortname = "kbs",
289 namespaced,
290 status = "KanidmBackupScheduleStatus",
291 printcolumn = r#"{"name":"Kanidm","type":"string","jsonPath":".spec.kanidmRef.name"}"#,
292 printcolumn = r#"{"name":"Schedule","type":"string","jsonPath":".spec.schedule"}"#,
293 printcolumn = r#"{"name":"Suspended","type":"boolean","jsonPath":".spec.suspend"}"#,
294 printcolumn = r#"{"name":"Ready","type":"string","jsonPath":".status.conditions[?(@.type=='Ready')].status"}"#,
295 printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#
296)]
297#[serde(rename_all = "camelCase")]
298pub struct KanidmBackupScheduleSpec {
299 pub kanidm_ref: ScheduleKanidmRef,
304 pub repository_ref: ScheduleRepositoryRef,
309 pub schedule: String,
317 #[serde(default = "default_timezone")]
319 pub time_zone: String,
320 #[serde(default)]
323 pub suspend: bool,
324 #[serde(default = "default_concurrency_policy")]
326 pub concurrency_policy: String,
327 #[serde(skip_serializing_if = "Option::is_none")]
329 pub jitter_seconds: Option<u32>,
330 #[serde(default = "default_local_versions")]
332 pub local_versions: u32,
333 #[serde(skip_serializing_if = "Option::is_none")]
339 pub retention: Option<RetentionPolicySpec>,
340}
341
342fn default_timezone() -> String {
343 "UTC".to_string()
344}
345
346fn default_concurrency_policy() -> String {
347 "Forbid".to_string()
348}
349
350fn default_local_versions() -> u32 {
351 7
352}
353
354#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
355#[cfg_attr(feature = "schemars", derive(JsonSchema))]
356#[serde(rename_all = "camelCase")]
357pub struct ScheduleKanidmRef {
358 pub name: String,
359}
360
361#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
362#[cfg_attr(feature = "schemars", derive(JsonSchema))]
363#[serde(rename_all = "camelCase")]
364pub struct ScheduleRepositoryRef {
365 pub name: String,
366}
367
368#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
369#[cfg_attr(feature = "schemars", derive(JsonSchema))]
370#[cfg_attr(
371 feature = "schemars",
372 schemars(extend("x-kubernetes-validations" = [
373 {
374 "message": "keepLast must be between 1 and 3650",
375 "rule": "self.keepLast >= 1 && self.keepLast <= 3650"
376 },
377 {
378 "message": "daily must be between 0 and 3650",
379 "rule": "self.daily >= 0 && self.daily <= 3650"
380 },
381 {
382 "message": "weekly must be between 0 and 520",
383 "rule": "self.weekly >= 0 && self.weekly <= 520"
384 },
385 {
386 "message": "monthly must be between 0 and 120",
387 "rule": "self.monthly >= 0 && self.monthly <= 120"
388 }
389 ]))
390)]
391#[serde(rename_all = "camelCase")]
392pub struct RetentionPolicySpec {
393 #[serde(default = "default_keep_last")]
394 pub keep_last: u32,
395 #[serde(default = "default_daily")]
396 pub daily: u32,
397 #[serde(default = "default_weekly")]
398 pub weekly: u32,
399 #[serde(default = "default_monthly")]
400 pub monthly: u32,
401 #[serde(default = "default_min_age")]
402 pub min_age: String,
403}
404
405fn default_keep_last() -> u32 {
406 8
407}
408
409fn default_daily() -> u32 {
410 7
411}
412
413fn default_weekly() -> u32 {
414 4
415}
416
417fn default_monthly() -> u32 {
418 12
419}
420
421fn default_min_age() -> String {
422 "24h".to_string()
423}
424
425#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
426#[cfg_attr(feature = "schemars", derive(JsonSchema))]
427#[serde(rename_all = "camelCase")]
428pub struct DiscoveryStatus {
429 #[serde(skip_serializing_if = "Option::is_none")]
430 pub last_scan_time: Option<String>,
431 #[serde(skip_serializing_if = "Option::is_none")]
432 pub last_successful_scan_time: Option<String>,
433 #[serde(skip_serializing_if = "Option::is_none")]
434 #[cfg_attr(feature = "schemars", schemars(extend("x-kubernetes-validations" = [{"message": "lastDiscoveredCount must be non-negative", "rule": "self >= 0"}])))]
435 pub last_discovered_count: Option<u32>,
436 #[serde(skip_serializing_if = "Option::is_none")]
437 pub last_error: Option<String>,
438 #[serde(default, skip_serializing_if = "Vec::is_empty")]
439 #[cfg_attr(
440 feature = "schemars",
441 schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
442 )]
443 pub conditions: Vec<Condition>,
444}
445
446#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
447#[cfg_attr(feature = "schemars", derive(JsonSchema))]
448#[serde(rename_all = "camelCase")]
449pub struct KanidmBackupScheduleStatus {
450 #[serde(skip_serializing_if = "Option::is_none")]
451 pub observed_generation: Option<i64>,
452 #[serde(skip_serializing_if = "Option::is_none")]
453 pub last_discovered_backup_ref: Option<String>,
454 #[serde(skip_serializing_if = "Option::is_none")]
455 pub last_successful_backup_time: Option<String>,
456 #[serde(default, skip_serializing_if = "Vec::is_empty")]
457 #[cfg_attr(
458 feature = "schemars",
459 schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
460 )]
461 pub conditions: Vec<Condition>,
462 #[serde(skip_serializing_if = "Option::is_none")]
463 pub discovery: Option<DiscoveryStatus>,
464}
465
466#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, PartialEq)]
467#[cfg_attr(feature = "schemars", derive(JsonSchema))]
468#[cfg_attr(
469 feature = "schemars",
470 schemars(extend("x-kubernetes-validations" = [
471 {
472 "message": "KanidmBackup spec is immutable",
473 "rule": "self == oldSelf"
474 }
475 ]))
476)]
477#[kube(
478 category = "kaniop",
479 group = "kaniop.rs",
480 version = "v1alpha1",
481 kind = "KanidmBackup",
482 plural = "kanidmbackups",
483 singular = "kanidmbackup",
484 shortname = "kb",
485 namespaced,
486 status = "KanidmBackupStatus",
487 printcolumn = r#"{"name":"Kanidm","type":"string","jsonPath":".spec.kanidmRef.name"}"#,
488 printcolumn = r#"{"name":"Backup Date","type":"string","jsonPath":".status.createdAt"}"#,
489 printcolumn = r#"{"name":"Version","type":"string","jsonPath":".status.kanidmVersion"}"#,
490 printcolumn = r#"{"name":"Phase","type":"string","jsonPath":".status.phase"}"#,
491 printcolumn = r#"{"name":"Consistency","type":"string","jsonPath":".status.consistency"}"#,
492 printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#
493)]
494#[serde(rename_all = "camelCase")]
495pub struct KanidmBackupSpec {
496 pub backup_id: String,
497 pub kanidm_ref: BackupKanidmRef,
498 pub repository_ref: BackupRepositoryRef,
499 pub manifest_key: String,
500}
501
502#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
503#[cfg_attr(feature = "schemars", derive(JsonSchema))]
504#[serde(rename_all = "camelCase")]
505pub struct BackupKanidmRef {
506 pub name: String,
507 pub uid: String,
508}
509
510#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
511#[cfg_attr(feature = "schemars", derive(JsonSchema))]
512#[serde(rename_all = "camelCase")]
513pub struct BackupRepositoryRef {
514 pub name: String,
515}
516
517#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
518#[cfg_attr(feature = "schemars", derive(JsonSchema))]
519pub enum KanidmBackupPhase {
520 #[default]
521 Discovering,
522 Ready,
523 Deleting,
524 Deleted,
525 Invalid,
526}
527
528fn serialize_backup_created_at<S>(
529 created_at: &Option<String>,
530 serializer: S,
531) -> Result<S::Ok, S::Error>
532where
533 S: Serializer,
534{
535 match created_at {
536 Some(created_at) => {
537 let formatted = DateTime::parse_from_rfc3339(created_at)
538 .map(|timestamp| {
539 timestamp
540 .with_timezone(&Utc)
541 .to_rfc3339_opts(SecondsFormat::Secs, true)
542 })
543 .unwrap_or_else(|_| created_at.clone());
544 serializer.serialize_some(&formatted)
545 }
546 None => serializer.serialize_none(),
547 }
548}
549
550#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
551#[cfg_attr(feature = "schemars", derive(JsonSchema))]
552#[serde(rename_all = "camelCase")]
553pub struct KanidmBackupStatus {
554 #[serde(skip_serializing_if = "Option::is_none")]
555 pub observed_generation: Option<i64>,
556 #[serde(default)]
557 pub phase: KanidmBackupPhase,
558 #[serde(skip_serializing_if = "Option::is_none")]
559 pub consistency: Option<String>,
560 #[serde(skip_serializing_if = "Option::is_none")]
561 pub reason: Option<String>,
562 #[serde(skip_serializing_if = "Option::is_none")]
563 pub kanidm_version: Option<String>,
564 #[serde(skip_serializing_if = "Option::is_none")]
565 pub image_digest: Option<String>,
566 #[serde(skip_serializing_if = "Option::is_none")]
567 pub size_bytes: Option<u64>,
568 #[serde(skip_serializing_if = "Option::is_none")]
569 pub payload_sha256: Option<String>,
570 #[serde(
571 skip_serializing_if = "Option::is_none",
572 serialize_with = "serialize_backup_created_at"
573 )]
574 pub created_at: Option<String>,
575 #[serde(default, skip_serializing_if = "Vec::is_empty")]
576 #[cfg_attr(
577 feature = "schemars",
578 schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
579 )]
580 pub conditions: Vec<Condition>,
581}
582
583#[cfg(test)]
584mod tests {
585 use super::*;
586
587 #[test]
588 fn encryption_key_ref_defaults_key() {
589 let key_ref: EncryptionKeyRef =
590 serde_json::from_value(serde_json::json!({"name": "kek"})).unwrap();
591 assert_eq!(key_ref.key, "encryption-key");
592 }
593
594 #[test]
595 fn ca_bundle_ref_serialization() {
596 let ca_ref = CaBundleRef {
597 name: "homelab-ca".to_string(),
598 key: "ca.crt".to_string(),
599 };
600 let json = serde_json::to_value(&ca_ref).unwrap();
601 assert_eq!(
602 json,
603 serde_json::json!({"name": "homelab-ca", "key": "ca.crt"})
604 );
605 assert_eq!(serde_json::from_value::<CaBundleRef>(json).unwrap(), ca_ref);
606 assert!(
607 serde_json::from_value::<CaBundleRef>(serde_json::json!({"name": "homelab-ca"}))
608 .is_err()
609 );
610 }
611
612 #[test]
613 fn repository_spec_serialization() {
614 let spec = KanidmBackupRepositorySpec {
615 s3: S3Config {
616 bucket: "my-bucket".to_string(),
617 prefix: "prod".to_string(),
618 region: "eu-west-1".to_string(),
619 endpoint: "https://s3.eu-west-1.amazonaws.com".to_string(),
620 force_path_style: false,
621 ca_bundle_ref: None,
622 insecure: false,
623 },
624 authentication: RepositoryAuthentication {
625 writer: AuthMethod {
626 workload_identity: Some(WorkloadIdentity { audience: None }),
627 secret_ref: None,
628 },
629 reader: AuthMethod {
630 workload_identity: Some(WorkloadIdentity { audience: None }),
631 secret_ref: None,
632 },
633 deleter: AuthMethod {
634 workload_identity: Some(WorkloadIdentity { audience: None }),
635 secret_ref: None,
636 },
637 },
638 encryption: Some(RepositoryEncryption {
639 mode: EncryptionMode::ProviderKms,
640 key_id: Some("alias/kaniop-backups".to_string()),
641 key_ref: None,
642 }),
643 limits: Some(RepositoryLimits {
644 max_upload_bytes_per_second: Some(52428800),
645 max_download_bytes_per_second: Some(104857600),
646 max_concurrent_parts: 4,
647 safety_backup_min_retention: "720h".to_string(),
648 }),
649 };
650 let json = serde_json::to_string(&spec).unwrap();
651 assert!(json.contains("my-bucket"));
652 assert!(json.contains("providerKms"));
653 }
654
655 #[test]
656 fn schedule_spec_defaults() {
657 let json = r#"{
658 "kanidmRef": {"name": "corp-idm"},
659 "repositoryRef": {"name": "offsite"},
660 "schedule": "3 */6 * * *"
661 }"#;
662 let spec: KanidmBackupScheduleSpec = serde_json::from_str(json).unwrap();
663 assert_eq!(spec.time_zone, "UTC");
664 assert_eq!(spec.concurrency_policy, "Forbid");
665 assert_eq!(spec.local_versions, 7);
666 assert!(!spec.suspend);
667 }
668
669 #[test]
670 fn backup_phase_default() {
671 let phase = KanidmBackupPhase::default();
672 assert_eq!(phase, KanidmBackupPhase::Discovering);
673 }
674
675 #[test]
676 fn backup_spec_is_immutable() {
677 let spec = KanidmBackupSpec {
678 backup_id: "019c7c76-f423-7a12-8f41-2bea7588a303".to_string(),
679 kanidm_ref: BackupKanidmRef {
680 name: "corp-idm".to_string(),
681 uid: "9e630aed".to_string(),
682 },
683 repository_ref: BackupRepositoryRef {
684 name: "offsite".to_string(),
685 },
686 manifest_key: "v1/tenants/ns/clusters/k/backups/b/manifest.json".to_string(),
687 };
688 let json = serde_json::to_string(&spec).unwrap();
689 let parsed: KanidmBackupSpec = serde_json::from_str(&json).unwrap();
690 assert_eq!(spec, parsed);
691 }
692
693 #[test]
694 fn retention_policy_spec_defaults() {
695 let json = r#"{}"#;
696 let spec: RetentionPolicySpec = serde_json::from_str(json).unwrap();
697 assert_eq!(spec.keep_last, 8);
698 assert_eq!(spec.daily, 7);
699 assert_eq!(spec.weekly, 4);
700 assert_eq!(spec.monthly, 12);
701 assert_eq!(spec.min_age, "24h");
702 }
703
704 #[test]
705 fn backup_status_serialization_formats_created_at() {
706 let status = KanidmBackupStatus {
707 created_at: Some("2026-08-31T11:34:46.913205633+02:00".to_string()),
708 ..Default::default()
709 };
710
711 let serialized = serde_json::to_value(&status).unwrap();
712
713 assert_eq!(serialized["createdAt"], "2026-08-31T09:34:46Z");
714 assert_eq!(
715 status.created_at.as_deref(),
716 Some("2026-08-31T11:34:46.913205633+02:00")
717 );
718 }
719
720 #[test]
721 fn backup_printer_columns_show_date_and_version() {
722 use kube::CustomResourceExt;
723
724 let crd = serde_json::to_value(KanidmBackup::crd()).unwrap();
725 let columns = &crd["spec"]["versions"][0]["additionalPrinterColumns"];
726 let columns = columns.as_array().unwrap();
727 let backup_date = columns
728 .iter()
729 .find(|column| column["name"] == "Backup Date")
730 .unwrap();
731 let age = columns
732 .iter()
733 .find(|column| column["name"] == "Age")
734 .unwrap();
735 let serialized = serde_json::to_string(columns).unwrap();
736
737 assert_eq!(backup_date["type"], "string");
738 assert_eq!(backup_date["jsonPath"], ".status.createdAt");
739 assert_eq!(age["type"], "date");
740 assert_eq!(age["jsonPath"], ".metadata.creationTimestamp");
741 assert!(serialized.contains("Version"));
742 assert!(serialized.contains(".status.kanidmVersion"));
743 assert!(!serialized.contains("BackupID"));
744 }
745}