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