Skip to main content

kaniop_operator/
object_meta_template.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fmt::Debug;
3use std::hash::Hash;
4
5use k8s_openapi::NamespaceResourceScope;
6use kaniop_k8s_util::error::Result;
7use kube::{
8    Client, Resource, ResourceExt,
9    api::{ObjectMeta, PartialObjectMeta},
10    runtime::reflector::Lookup,
11};
12use serde::{Deserialize, Serialize};
13
14use crate::{
15    controller::context::KubeOperations, crd::MetadataTemplate, metrics::ControllerMetrics,
16};
17
18#[derive(Clone, Debug, Default, PartialEq, Eq)]
19pub struct ManagedMetadataKeys {
20    pub annotations: BTreeSet<String>,
21    pub labels: BTreeSet<String>,
22}
23
24/// Extracts the metadata keys owned by `manager` from the managed-fields list of `meta`.
25/// Only entries with `operation = "Apply"` and no subresource are considered.
26fn managed_metadata_keys<K>(meta: &PartialObjectMeta<K>, manager: &str) -> ManagedMetadataKeys {
27    let mut keys = ManagedMetadataKeys::default();
28
29    let Some(managed_fields) = meta.metadata.managed_fields.as_ref() else {
30        return keys;
31    };
32
33    for entry in managed_fields.iter().filter(|f| {
34        f.operation.as_deref() == Some("Apply")
35            && f.subresource.is_none()
36            && f.manager.as_deref() == Some(manager)
37    }) {
38        let Some(field_meta) = entry
39            .fields_v1
40            .as_ref()
41            .and_then(|f| f.0.as_object())
42            .and_then(|o| o.get("f:metadata"))
43            .and_then(|m| m.as_object())
44        else {
45            continue;
46        };
47
48        if let Some(labels) = field_meta.get("f:labels").and_then(|l| l.as_object()) {
49            for k in labels.keys() {
50                if let Some(stripped) = k.strip_prefix("f:").filter(|&c| c != ".") {
51                    keys.labels.insert(stripped.to_string());
52                }
53            }
54        }
55        if let Some(annotations) = field_meta.get("f:annotations").and_then(|a| a.as_object()) {
56            for k in annotations.keys() {
57                if let Some(stripped) = k.strip_prefix("f:").filter(|&c| c != ".") {
58                    keys.annotations.insert(stripped.to_string());
59                }
60            }
61        }
62    }
63
64    keys
65}
66
67/// Result of filtering a [`MetadataTemplate`] against the set of fields already owned by the
68/// main operator manager. Labels and annotations that would conflict are separated out so callers
69/// can apply the safe subset and surface the discarded keys in logs or events.
70#[derive(Default)]
71pub struct FilteredMetadata {
72    pub labels: BTreeMap<String, String>,
73    pub annotations: BTreeMap<String, String>,
74    /// Label keys from the template that were discarded because the main operator already owns them.
75    pub discarded_labels: BTreeSet<String>,
76    /// Annotation keys from the template that were discarded because the main operator already owns them.
77    pub discarded_annotations: BTreeSet<String>,
78}
79
80impl FilteredMetadata {
81    pub fn has_discards(&self) -> bool {
82        !self.discarded_labels.is_empty() || !self.discarded_annotations.is_empty()
83    }
84}
85
86impl MetadataTemplate {
87    /// Returns the labels and annotations that are safe to apply — i.e. those not already owned
88    /// by the main operator manager — alongside any keys that were discarded due to conflicts.
89    fn filter_owned(&self, owned: &ManagedMetadataKeys) -> FilteredMetadata {
90        let (labels, discarded_labels) = split_owned(self.labels.as_ref(), &owned.labels);
91        let (annotations, discarded_annotations) =
92            split_owned(self.annotations.as_ref(), &owned.annotations);
93        FilteredMetadata {
94            labels,
95            annotations,
96            discarded_labels,
97            discarded_annotations,
98        }
99    }
100}
101
102/// Partitions `source` into keys the template manager may own (not in `owned`) and keys it
103/// may not (already claimed by the main manager). Returns `(kept, discarded)`.
104fn split_owned(
105    source: Option<&BTreeMap<String, String>>,
106    owned: &BTreeSet<String>,
107) -> (BTreeMap<String, String>, BTreeSet<String>) {
108    let Some(m) = source else {
109        return Default::default();
110    };
111    let mut kept = BTreeMap::new();
112    let mut discarded = BTreeSet::new();
113    for (k, v) in m {
114        if owned.contains(k) {
115            discarded.insert(k.clone());
116        } else {
117            kept.insert(k.clone(), v.clone());
118        }
119    }
120    (kept, discarded)
121}
122
123/// Implemented by operator resources that manage a child Kubernetes object whose metadata
124/// (labels and annotations) can be customized via a [`MetadataTemplate`].
125///
126/// Generic over `K` so the same mechanism can serve any resource type that has `ObjectMeta`
127/// (Secret, ConfigMap, …). The default implementations of [`needs_meta_template_apply`] and
128/// [`apply_meta_template`] cover the common SSA cleanup/apply flow; implementors only need to
129/// supply the three required methods.
130pub trait ObjectMetaTemplateExt<K>
131where
132    Self: KubeOperations<Self, K> + ResourceExt + Clone + 'static,
133    <Self as Lookup>::DynamicType: Eq + Hash + Clone,
134    K: Resource<Scope = NamespaceResourceScope>
135        + Default
136        + Clone
137        + Debug
138        + Serialize
139        + for<'de> Deserialize<'de>,
140    <K as Resource>::DynamicType: Default,
141{
142    /// The SSA field-manager name used for the main operator apply.
143    const OPERATOR_NAME: &'static str;
144    /// Name of the managed child object.
145    fn managed_object_name(&self) -> String;
146    /// Template supplying extra labels/annotations, if configured.
147    fn metadata_template(&self) -> Option<&MetadataTemplate>;
148
149    /// Name of the SSA field manager used for template-owned metadata fields.
150    fn template_operator_name() -> String {
151        format!("template.{}", Self::OPERATOR_NAME)
152    }
153
154    /// Checks whether the live object's metadata matches the desired template state and, if not,
155    /// returns the pre-filtered [`FilteredMetadata`] ready to pass to [`apply_meta_template`].
156    ///
157    /// Reads the managed-fields list for both the main operator and the template manager,
158    /// covering all three out-of-sync cases:
159    /// - A desired key is missing or has the wrong value.
160    /// - The desired template is empty but the template manager still owns fields (template removed).
161    /// - The desired template shrank and the template manager owns stale keys.
162    fn needs_meta_template_apply(&self, live: &PartialObjectMeta<K>) -> Option<FilteredMetadata> {
163        let main_keys = managed_metadata_keys(live, Self::OPERATOR_NAME);
164        let template_keys = managed_metadata_keys(live, &Self::template_operator_name());
165        let filtered = self
166            .metadata_template()
167            .map(|t| t.filter_owned(&main_keys))
168            .unwrap_or_default();
169
170        let value_mismatch =
171            |desired: &BTreeMap<String, String>, actual: Option<&BTreeMap<String, String>>| {
172                desired
173                    .iter()
174                    .any(|(k, v)| actual.and_then(|m| m.get(k)) != Some(v))
175            };
176        if value_mismatch(&filtered.labels, live.metadata.labels.as_ref())
177            || value_mismatch(&filtered.annotations, live.metadata.annotations.as_ref())
178        {
179            return Some(filtered);
180        }
181
182        if filtered.labels.is_empty() && filtered.annotations.is_empty() {
183            // No desired fields: in sync only if the template manager owns nothing.
184            if template_keys.labels.is_empty() && template_keys.annotations.is_empty() {
185                return None;
186            }
187            return Some(filtered);
188        }
189
190        // Desired fields non-empty: also verify the template manager owns *exactly* the desired
191        // keys — no stale extras left over from a previously larger template.
192        let desired_labels: BTreeSet<String> = filtered.labels.keys().cloned().collect();
193        let desired_annotations: BTreeSet<String> = filtered.annotations.keys().cloned().collect();
194        if template_keys.labels == desired_labels
195            && template_keys.annotations == desired_annotations
196        {
197            None
198        } else {
199            Some(filtered)
200        }
201    }
202
203    /// Applies `filtered` to the managed child object using the template SSA field manager.
204    ///
205    /// Passing an empty [`FilteredMetadata`] (no labels, no annotations) causes SSA to release any
206    /// previously template-owned keys. Obtain `filtered` from [`needs_meta_template_apply`].
207    /// Callers are responsible for surfacing any discarded keys (see [`FilteredMetadata::has_discards`]).
208    #[allow(async_fn_in_trait)]
209    async fn apply_meta_template(
210        &self,
211        client: Client,
212        metrics: &ControllerMetrics,
213        filtered: FilteredMetadata,
214    ) -> Result<K> {
215        // safe unwrap: implementor is namespaced
216        let namespace = self.namespace().unwrap();
217
218        let obj = build_object_metadata(
219            self.managed_object_name(),
220            namespace,
221            filtered.labels,
222            filtered.annotations,
223        );
224        self.kube_patch(client, metrics, obj, &Self::template_operator_name())
225            .await
226    }
227}
228
229/// Builds an object containing only pre-filtered template metadata for SSA via the template
230/// manager. Passing empty maps causes SSA to release any previously template-owned keys.
231fn build_object_metadata<K: Resource + Default>(
232    name: String,
233    namespace: String,
234    labels: BTreeMap<String, String>,
235    annotations: BTreeMap<String, String>,
236) -> K {
237    let mut obj = K::default();
238    *obj.meta_mut() = ObjectMeta {
239        name: Some(name),
240        namespace: Some(namespace),
241        labels: if labels.is_empty() {
242            None
243        } else {
244            Some(labels)
245        },
246        annotations: if annotations.is_empty() {
247            None
248        } else {
249            Some(annotations)
250        },
251        ..ObjectMeta::default()
252    };
253    obj
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    use k8s_openapi::api::core::v1::Secret;
261    use k8s_openapi::apimachinery::pkg::apis::meta::v1::{
262        FieldsV1, ManagedFieldsEntry, ObjectMeta,
263    };
264    use serde_json::json;
265
266    fn meta_with_managed_fields(
267        manager: &str,
268        operation: &str,
269        subresource: Option<&str>,
270        fields: serde_json::Value,
271    ) -> PartialObjectMeta<Secret> {
272        PartialObjectMeta {
273            metadata: ObjectMeta {
274                managed_fields: Some(vec![ManagedFieldsEntry {
275                    manager: Some(manager.to_string()),
276                    operation: Some(operation.to_string()),
277                    subresource: subresource.map(str::to_string),
278                    fields_v1: Some(FieldsV1(fields)),
279                    fields_type: Some("FieldsV1".to_string()),
280                    ..Default::default()
281                }]),
282                ..Default::default()
283            },
284            ..Default::default()
285        }
286    }
287
288    #[test]
289    fn test_extracts_label_keys() {
290        let fields = json!({
291            "f:metadata": {
292                "f:labels": {
293                    ".": {},
294                    "f:app.kubernetes.io/name": {},
295                    "f:example.com/foo": {},
296                }
297            }
298        });
299        let meta = meta_with_managed_fields("test-manager", "Apply", None, fields);
300        let keys = managed_metadata_keys(&meta, "test-manager");
301        assert!(keys.labels.contains("app.kubernetes.io/name"));
302        assert!(keys.labels.contains("example.com/foo"));
303        assert!(
304            !keys.labels.contains("."),
305            "existence marker must be filtered out"
306        );
307        assert!(keys.annotations.is_empty());
308    }
309
310    #[test]
311    fn test_extracts_annotation_keys() {
312        let fields = json!({
313            "f:metadata": {
314                "f:annotations": {
315                    ".": {},
316                    "f:kaniop.rs/rotation-enabled": {},
317                    "f:example.com/note": {},
318                }
319            }
320        });
321        let meta = meta_with_managed_fields("test-manager", "Apply", None, fields);
322        let keys = managed_metadata_keys(&meta, "test-manager");
323        assert!(keys.annotations.contains("kaniop.rs/rotation-enabled"));
324        assert!(keys.annotations.contains("example.com/note"));
325        assert!(keys.labels.is_empty());
326    }
327
328    #[test]
329    fn test_ignores_wrong_manager() {
330        let fields = json!({ "f:metadata": { "f:labels": { "f:example.com/foo": {} } } });
331        let meta = meta_with_managed_fields("other-manager", "Apply", None, fields);
332        let keys = managed_metadata_keys(&meta, "test-manager");
333        assert!(
334            keys.labels.is_empty(),
335            "keys from a different manager must not be returned"
336        );
337    }
338
339    #[test]
340    fn test_ignores_update_operation() {
341        let fields = json!({ "f:metadata": { "f:labels": { "f:example.com/foo": {} } } });
342        // "Update" operation entries must not be considered for SSA staleness checks.
343        let meta = meta_with_managed_fields("test-manager", "Update", None, fields);
344        let keys = managed_metadata_keys(&meta, "test-manager");
345        assert!(
346            keys.labels.is_empty(),
347            "Update-operation entries must not be returned"
348        );
349    }
350
351    #[test]
352    fn test_ignores_subresource_entry() {
353        let fields = json!({ "f:metadata": { "f:labels": { "f:example.com/foo": {} } } });
354        // e.g. a status subresource entry must not be included.
355        let meta = meta_with_managed_fields("test-manager", "Apply", Some("status"), fields);
356        let keys = managed_metadata_keys(&meta, "test-manager");
357        assert!(
358            keys.labels.is_empty(),
359            "subresource entries must not be returned"
360        );
361    }
362
363    #[test]
364    fn test_no_metadata_fields_returns_none() {
365        // The manager owns only data fields, not metadata labels or annotations.
366        let fields = json!({ "f:data": { ".": {}, "f:CLIENT_ID": {}, "f:CLIENT_SECRET": {} } });
367        let meta = meta_with_managed_fields("test-manager", "Apply", None, fields);
368        let keys = managed_metadata_keys(&meta, "test-manager");
369        assert!(keys.labels.is_empty());
370        assert!(keys.annotations.is_empty());
371    }
372
373    #[test]
374    fn test_no_managed_fields_returns_none() {
375        let meta: PartialObjectMeta<Secret> = PartialObjectMeta::default();
376        let keys = managed_metadata_keys(&meta, "test-manager");
377        assert!(keys.labels.is_empty());
378        assert!(keys.annotations.is_empty());
379    }
380
381    #[test]
382    fn test_multiple_entries_for_same_manager_are_accumulated() {
383        // The same manager can appear more than once in managed_fields when separate Apply
384        // operations owned different subsets of fields (e.g. labels in one apply, annotations
385        // in a later apply). All entries must be accumulated into a single result.
386        let meta: PartialObjectMeta<Secret> = PartialObjectMeta {
387            metadata: ObjectMeta {
388                managed_fields: Some(vec![
389                    ManagedFieldsEntry {
390                        manager: Some("test-manager".to_string()),
391                        operation: Some("Apply".to_string()),
392                        subresource: None,
393                        fields_v1: Some(FieldsV1(json!({
394                            "f:metadata": {
395                                "f:labels": {
396                                    ".": {},
397                                    "f:app.kubernetes.io/name": {},
398                                }
399                            }
400                        }))),
401                        fields_type: Some("FieldsV1".to_string()),
402                        ..Default::default()
403                    },
404                    ManagedFieldsEntry {
405                        manager: Some("test-manager".to_string()),
406                        operation: Some("Apply".to_string()),
407                        subresource: None,
408                        fields_v1: Some(FieldsV1(json!({
409                            "f:metadata": {
410                                "f:annotations": {
411                                    ".": {},
412                                    "f:example.com/note": {},
413                                }
414                            }
415                        }))),
416                        fields_type: Some("FieldsV1".to_string()),
417                        ..Default::default()
418                    },
419                ]),
420                ..Default::default()
421            },
422            ..Default::default()
423        };
424        let keys = managed_metadata_keys(&meta, "test-manager");
425        assert!(
426            keys.labels.contains("app.kubernetes.io/name"),
427            "label from first entry must be present"
428        );
429        assert!(
430            keys.annotations.contains("example.com/note"),
431            "annotation from second entry must be present"
432        );
433    }
434
435    #[test]
436    fn test_extracts_keys_for_each_manager_independently() {
437        let meta: PartialObjectMeta<Secret> = PartialObjectMeta {
438            metadata: ObjectMeta {
439                managed_fields: Some(vec![
440                    ManagedFieldsEntry {
441                        manager: Some("operator".to_string()),
442                        operation: Some("Apply".to_string()),
443                        subresource: None,
444                        fields_v1: Some(FieldsV1(json!({
445                            "f:metadata": {
446                                "f:labels": { ".": {}, "f:app.kubernetes.io/name": {} }
447                            }
448                        }))),
449                        fields_type: Some("FieldsV1".to_string()),
450                        ..Default::default()
451                    },
452                    ManagedFieldsEntry {
453                        manager: Some("template.operator".to_string()),
454                        operation: Some("Apply".to_string()),
455                        subresource: None,
456                        fields_v1: Some(FieldsV1(json!({
457                            "f:metadata": {
458                                "f:labels": { ".": {}, "f:example.com/custom": {} },
459                                "f:annotations": { ".": {}, "f:example.com/note": {} },
460                            }
461                        }))),
462                        fields_type: Some("FieldsV1".to_string()),
463                        ..Default::default()
464                    },
465                    // unrelated manager — must not appear in either result
466                    ManagedFieldsEntry {
467                        manager: Some("other".to_string()),
468                        operation: Some("Apply".to_string()),
469                        subresource: None,
470                        fields_v1: Some(FieldsV1(json!({
471                            "f:metadata": { "f:labels": { "f:other.io/x": {} } }
472                        }))),
473                        fields_type: Some("FieldsV1".to_string()),
474                        ..Default::default()
475                    },
476                ]),
477                ..Default::default()
478            },
479            ..Default::default()
480        };
481
482        let main_keys = managed_metadata_keys(&meta, "operator");
483        let tmpl_keys = managed_metadata_keys(&meta, "template.operator");
484
485        assert!(main_keys.labels.contains("app.kubernetes.io/name"));
486        assert!(main_keys.annotations.is_empty());
487        assert!(
488            !main_keys.labels.contains("example.com/custom"),
489            "template key must not appear in main_keys"
490        );
491
492        assert!(tmpl_keys.labels.contains("example.com/custom"));
493        assert!(tmpl_keys.annotations.contains("example.com/note"));
494        assert!(
495            !tmpl_keys.labels.contains("app.kubernetes.io/name"),
496            "main key must not appear in tmpl_keys"
497        );
498        assert!(
499            !tmpl_keys.labels.contains("other.io/x"),
500            "unrelated manager key must not appear"
501        );
502    }
503
504    #[test]
505    fn test_filter_owned_removes_conflicting_keys() {
506        use crate::crd::MetadataTemplate;
507
508        let owned = ManagedMetadataKeys {
509            labels: ["app.kubernetes.io/name".to_string()].into(),
510            annotations: ["kaniop.rs/managed".to_string()].into(),
511        };
512        let tmpl = MetadataTemplate {
513            labels: Some(BTreeMap::from([
514                (
515                    "app.kubernetes.io/name".to_string(),
516                    "user-value".to_string(),
517                ),
518                ("example.com/custom".to_string(), "ok".to_string()),
519            ])),
520            annotations: Some(BTreeMap::from([
521                ("kaniop.rs/managed".to_string(), "ignored".to_string()),
522                ("example.com/note".to_string(), "kept".to_string()),
523            ])),
524        };
525
526        let filtered = tmpl.filter_owned(&owned);
527
528        assert!(!filtered.labels.contains_key("app.kubernetes.io/name"));
529        assert_eq!(filtered.labels["example.com/custom"], "ok");
530        assert!(!filtered.annotations.contains_key("kaniop.rs/managed"));
531        assert_eq!(filtered.annotations["example.com/note"], "kept");
532
533        assert_eq!(
534            filtered.discarded_labels,
535            BTreeSet::from(["app.kubernetes.io/name".to_string()])
536        );
537        assert_eq!(
538            filtered.discarded_annotations,
539            BTreeSet::from(["kaniop.rs/managed".to_string()])
540        );
541        assert!(filtered.has_discards());
542    }
543
544    #[test]
545    fn test_filter_owned_no_conflicts() {
546        use crate::crd::MetadataTemplate;
547
548        let owned = ManagedMetadataKeys {
549            labels: ["app.kubernetes.io/name".to_string()].into(),
550            annotations: BTreeSet::new(),
551        };
552        let tmpl = MetadataTemplate {
553            labels: Some(BTreeMap::from([(
554                "example.com/custom".to_string(),
555                "val".to_string(),
556            )])),
557            annotations: None,
558        };
559
560        let filtered = tmpl.filter_owned(&owned);
561
562        assert_eq!(filtered.labels["example.com/custom"], "val");
563        assert!(filtered.annotations.is_empty());
564        assert!(!filtered.has_discards());
565    }
566
567    #[test]
568    fn test_filter_owned_both_fields_none() {
569        use crate::crd::MetadataTemplate;
570
571        let owned = ManagedMetadataKeys {
572            labels: ["app.kubernetes.io/name".to_string()].into(),
573            annotations: ["kaniop.rs/managed".to_string()].into(),
574        };
575        let tmpl = MetadataTemplate {
576            labels: None,
577            annotations: None,
578        };
579
580        let filtered = tmpl.filter_owned(&owned);
581
582        assert!(filtered.labels.is_empty());
583        assert!(filtered.annotations.is_empty());
584        assert!(!filtered.has_discards());
585    }
586
587    #[test]
588    fn test_filter_owned_all_keys_conflict() {
589        use crate::crd::MetadataTemplate;
590
591        let owned = ManagedMetadataKeys {
592            labels: [
593                "app.kubernetes.io/name".to_string(),
594                "app.kubernetes.io/instance".to_string(),
595            ]
596            .into(),
597            annotations: ["kaniop.rs/managed".to_string()].into(),
598        };
599        let tmpl = MetadataTemplate {
600            labels: Some(BTreeMap::from([
601                (
602                    "app.kubernetes.io/name".to_string(),
603                    "user-name".to_string(),
604                ),
605                (
606                    "app.kubernetes.io/instance".to_string(),
607                    "user-instance".to_string(),
608                ),
609            ])),
610            annotations: Some(BTreeMap::from([(
611                "kaniop.rs/managed".to_string(),
612                "user-val".to_string(),
613            )])),
614        };
615
616        let filtered = tmpl.filter_owned(&owned);
617
618        assert!(filtered.labels.is_empty(), "all labels should be discarded");
619        assert!(
620            filtered.annotations.is_empty(),
621            "all annotations should be discarded"
622        );
623        assert!(filtered.has_discards());
624        assert_eq!(
625            filtered.discarded_labels,
626            BTreeSet::from([
627                "app.kubernetes.io/name".to_string(),
628                "app.kubernetes.io/instance".to_string()
629            ])
630        );
631        assert_eq!(
632            filtered.discarded_annotations,
633            BTreeSet::from(["kaniop.rs/managed".to_string()])
634        );
635    }
636
637    #[test]
638    fn test_has_discards_only_labels_discarded() {
639        use crate::crd::MetadataTemplate;
640
641        let owned = ManagedMetadataKeys {
642            labels: ["app.kubernetes.io/name".to_string()].into(),
643            annotations: BTreeSet::new(),
644        };
645        let tmpl = MetadataTemplate {
646            labels: Some(BTreeMap::from([(
647                "app.kubernetes.io/name".to_string(),
648                "val".to_string(),
649            )])),
650            annotations: Some(BTreeMap::from([(
651                "example.com/note".to_string(),
652                "kept".to_string(),
653            )])),
654        };
655
656        let filtered = tmpl.filter_owned(&owned);
657
658        assert!(filtered.discarded_labels.contains("app.kubernetes.io/name"));
659        assert!(filtered.discarded_annotations.is_empty());
660        assert!(
661            filtered.has_discards(),
662            "should have discards (labels only)"
663        );
664    }
665
666    #[test]
667    fn test_has_discards_only_annotations_discarded() {
668        use crate::crd::MetadataTemplate;
669
670        let owned = ManagedMetadataKeys {
671            labels: BTreeSet::new(),
672            annotations: ["kaniop.rs/managed".to_string()].into(),
673        };
674        let tmpl = MetadataTemplate {
675            labels: Some(BTreeMap::from([(
676                "example.com/custom".to_string(),
677                "kept".to_string(),
678            )])),
679            annotations: Some(BTreeMap::from([(
680                "kaniop.rs/managed".to_string(),
681                "val".to_string(),
682            )])),
683        };
684
685        let filtered = tmpl.filter_owned(&owned);
686
687        assert!(filtered.discarded_labels.is_empty());
688        assert!(filtered.discarded_annotations.contains("kaniop.rs/managed"));
689        assert!(
690            filtered.has_discards(),
691            "should have discards (annotations only)"
692        );
693    }
694
695    /// `build_object_metadata` produces `None` for empty maps and `Some` for non-empty.
696    #[test]
697    fn test_build_object_metadata_non_empty() {
698        let labels = BTreeMap::from([("example.com/env".to_string(), "prod".to_string())]);
699        let annotations =
700            BTreeMap::from([("example.com/team".to_string(), "platform".to_string())]);
701        let obj: Secret = build_object_metadata(
702            "my-secret".to_string(),
703            "default".to_string(),
704            labels.clone(),
705            annotations.clone(),
706        );
707        assert_eq!(obj.metadata.name.as_deref(), Some("my-secret"));
708        assert_eq!(obj.metadata.namespace.as_deref(), Some("default"));
709        assert_eq!(obj.metadata.labels.as_ref(), Some(&labels));
710        assert_eq!(obj.metadata.annotations.as_ref(), Some(&annotations));
711    }
712
713    #[test]
714    fn test_build_object_metadata_empty_maps_produce_none() {
715        let obj: Secret = build_object_metadata(
716            "my-secret".to_string(),
717            "default".to_string(),
718            BTreeMap::new(),
719            BTreeMap::new(),
720        );
721        assert!(
722            obj.metadata.labels.is_none(),
723            "empty labels should produce None"
724        );
725        assert!(
726            obj.metadata.annotations.is_none(),
727            "empty annotations should produce None"
728        );
729    }
730
731    #[test]
732    fn test_build_object_metadata_labels_only() {
733        let labels = BTreeMap::from([("example.com/env".to_string(), "prod".to_string())]);
734        let obj: Secret = build_object_metadata(
735            "my-secret".to_string(),
736            "default".to_string(),
737            labels.clone(),
738            BTreeMap::new(),
739        );
740        assert_eq!(obj.metadata.labels.as_ref(), Some(&labels));
741        assert!(obj.metadata.annotations.is_none());
742    }
743
744    #[test]
745    fn test_build_object_metadata_annotations_only() {
746        let annotations =
747            BTreeMap::from([("example.com/team".to_string(), "platform".to_string())]);
748        let obj: Secret = build_object_metadata(
749            "my-secret".to_string(),
750            "default".to_string(),
751            BTreeMap::new(),
752            annotations.clone(),
753        );
754        assert!(obj.metadata.labels.is_none());
755        assert_eq!(obj.metadata.annotations.as_ref(), Some(&annotations));
756    }
757}
758
759#[cfg(test)]
760mod needs_meta_template_apply_tests {
761    use super::*;
762    use crate::crd::MetadataTemplate;
763
764    use k8s_openapi::NamespaceResourceScope;
765    use k8s_openapi::api::core::v1::Secret;
766    use k8s_openapi::apimachinery::pkg::apis::meta::v1::{
767        FieldsV1, ManagedFieldsEntry, ObjectMeta,
768    };
769    use kube::Resource;
770    use kube::api::PartialObjectMeta;
771    use serde_json::json;
772    use std::borrow::Cow;
773
774    /// Minimal parent resource for testing [`ObjectMetaTemplateExt::needs_meta_template_apply`]
775    /// without pulling in a full CRD type.
776    #[derive(Clone, Default)]
777    struct TestOwner {
778        metadata: ObjectMeta,
779        template: Option<MetadataTemplate>,
780    }
781
782    impl Resource for TestOwner {
783        type DynamicType = ();
784        type Scope = NamespaceResourceScope;
785
786        fn kind(_: &()) -> Cow<'_, str> {
787            "TestOwner".into()
788        }
789        fn group(_: &()) -> Cow<'_, str> {
790            "test.rs".into()
791        }
792        fn version(_: &()) -> Cow<'_, str> {
793            "v1".into()
794        }
795        fn plural(_: &()) -> Cow<'_, str> {
796            "testowners".into()
797        }
798        fn meta(&self) -> &ObjectMeta {
799            &self.metadata
800        }
801        fn meta_mut(&mut self) -> &mut ObjectMeta {
802            &mut self.metadata
803        }
804    }
805
806    impl ObjectMetaTemplateExt<Secret> for TestOwner {
807        const OPERATOR_NAME: &'static str = "test-operator";
808        fn managed_object_name(&self) -> String {
809            "test-secret".to_string()
810        }
811        fn metadata_template(&self) -> Option<&MetadataTemplate> {
812            self.template.as_ref()
813        }
814    }
815
816    fn owner(template: Option<MetadataTemplate>) -> TestOwner {
817        TestOwner {
818            metadata: ObjectMeta {
819                name: Some("my-resource".to_string()),
820                namespace: Some("default".to_string()),
821                ..Default::default()
822            },
823            template,
824        }
825    }
826
827    /// Build a `PartialObjectMeta<Secret>` with both actual metadata and managed-field entries
828    /// for the template manager (`template.test-operator`).
829    fn secret_meta(
830        labels: BTreeMap<String, String>,
831        annotations: BTreeMap<String, String>,
832        template_label_keys: &[&str],
833        template_annotation_keys: &[&str],
834    ) -> PartialObjectMeta<Secret> {
835        let mut managed_fields = vec![];
836
837        if !template_label_keys.is_empty() || !template_annotation_keys.is_empty() {
838            let mut meta_fields = serde_json::Map::new();
839
840            if !template_label_keys.is_empty() {
841                let mut lf = serde_json::Map::new();
842                lf.insert(".".to_string(), json!({}));
843                for k in template_label_keys {
844                    lf.insert(format!("f:{k}"), json!({}));
845                }
846                meta_fields.insert("f:labels".to_string(), json!(lf));
847            }
848
849            if !template_annotation_keys.is_empty() {
850                let mut af = serde_json::Map::new();
851                af.insert(".".to_string(), json!({}));
852                for k in template_annotation_keys {
853                    af.insert(format!("f:{k}"), json!({}));
854                }
855                meta_fields.insert("f:annotations".to_string(), json!(af));
856            }
857
858            managed_fields.push(ManagedFieldsEntry {
859                manager: Some("template.test-operator".to_string()),
860                operation: Some("Apply".to_string()),
861                subresource: None,
862                fields_v1: Some(FieldsV1(json!({ "f:metadata": meta_fields }))),
863                fields_type: Some("FieldsV1".to_string()),
864                ..Default::default()
865            });
866        }
867
868        PartialObjectMeta {
869            metadata: ObjectMeta {
870                labels: if labels.is_empty() {
871                    None
872                } else {
873                    Some(labels)
874                },
875                annotations: if annotations.is_empty() {
876                    None
877                } else {
878                    Some(annotations)
879                },
880                managed_fields: if managed_fields.is_empty() {
881                    None
882                } else {
883                    Some(managed_fields)
884                },
885                ..Default::default()
886            },
887            ..Default::default()
888        }
889    }
890
891    #[test]
892    fn test_in_sync_no_template_no_stale_fields() {
893        let owner = owner(None);
894        let live: PartialObjectMeta<Secret> = PartialObjectMeta::default();
895        assert!(owner.needs_meta_template_apply(&live).is_none());
896    }
897
898    #[test]
899    fn test_out_of_sync_no_template_stale_fields_remain() {
900        // Template was removed but the template manager still owns fields → cleanup apply needed.
901        let owner = owner(None);
902        let live = secret_meta(
903            BTreeMap::new(),
904            BTreeMap::new(),
905            &["example.com/stale"],
906            &[],
907        );
908        assert!(owner.needs_meta_template_apply(&live).is_some());
909    }
910
911    #[test]
912    fn test_in_sync_template_all_keys_present_and_owned() {
913        let owner = owner(Some(MetadataTemplate {
914            labels: Some(BTreeMap::from([(
915                "example.com/env".to_string(),
916                "prod".to_string(),
917            )])),
918            annotations: None,
919        }));
920        let live = secret_meta(
921            BTreeMap::from([("example.com/env".to_string(), "prod".to_string())]),
922            BTreeMap::new(),
923            &["example.com/env"],
924            &[],
925        );
926        assert!(owner.needs_meta_template_apply(&live).is_none());
927    }
928
929    #[test]
930    fn test_out_of_sync_value_mismatch() {
931        let owner = owner(Some(MetadataTemplate {
932            labels: Some(BTreeMap::from([(
933                "example.com/env".to_string(),
934                "prod".to_string(),
935            )])),
936            annotations: None,
937        }));
938        // Key is present but value differs.
939        let live = secret_meta(
940            BTreeMap::from([("example.com/env".to_string(), "staging".to_string())]),
941            BTreeMap::new(),
942            &["example.com/env"],
943            &[],
944        );
945        assert!(owner.needs_meta_template_apply(&live).is_some());
946    }
947
948    #[test]
949    fn test_out_of_sync_template_manager_owns_stale_extra_key() {
950        // Template shrank: manager still owns a key that is no longer desired.
951        let owner = owner(Some(MetadataTemplate {
952            labels: Some(BTreeMap::from([(
953                "example.com/env".to_string(),
954                "prod".to_string(),
955            )])),
956            annotations: None,
957        }));
958        let live = secret_meta(
959            BTreeMap::from([
960                ("example.com/env".to_string(), "prod".to_string()),
961                ("example.com/stale".to_string(), "old".to_string()),
962            ]),
963            BTreeMap::new(),
964            &["example.com/env", "example.com/stale"],
965            &[],
966        );
967        assert!(owner.needs_meta_template_apply(&live).is_some());
968    }
969
970    #[test]
971    fn test_out_of_sync_template_manager_missing_ownership() {
972        // Label present with correct value but template manager doesn't own it yet.
973        let owner = owner(Some(MetadataTemplate {
974            labels: Some(BTreeMap::from([(
975                "example.com/env".to_string(),
976                "prod".to_string(),
977            )])),
978            annotations: None,
979        }));
980        let live = secret_meta(
981            BTreeMap::from([("example.com/env".to_string(), "prod".to_string())]),
982            BTreeMap::new(),
983            &[], // no template manager managed fields
984            &[],
985        );
986        assert!(owner.needs_meta_template_apply(&live).is_some());
987    }
988
989    #[test]
990    fn test_in_sync_labels_and_annotations() {
991        let owner = owner(Some(MetadataTemplate {
992            labels: Some(BTreeMap::from([(
993                "example.com/env".to_string(),
994                "prod".to_string(),
995            )])),
996            annotations: Some(BTreeMap::from([(
997                "example.com/team".to_string(),
998                "platform".to_string(),
999            )])),
1000        }));
1001        let live = secret_meta(
1002            BTreeMap::from([("example.com/env".to_string(), "prod".to_string())]),
1003            BTreeMap::from([("example.com/team".to_string(), "platform".to_string())]),
1004            &["example.com/env"],
1005            &["example.com/team"],
1006        );
1007        assert!(owner.needs_meta_template_apply(&live).is_none());
1008    }
1009
1010    #[test]
1011    fn test_in_sync_all_template_keys_conflict_with_operator() {
1012        // When every key in the template is already owned by the main operator, filter_owned
1013        // discards them all. The filtered result is empty and the template manager owns nothing,
1014        // so no apply is needed — the conflicting keys are silently dropped.
1015        let owner = owner(Some(MetadataTemplate {
1016            labels: Some(BTreeMap::from([(
1017                "app.kubernetes.io/name".to_string(),
1018                "user-value".to_string(),
1019            )])),
1020            annotations: None,
1021        }));
1022        // Main operator owns "app.kubernetes.io/name"; template manager owns nothing.
1023        let live: PartialObjectMeta<Secret> = PartialObjectMeta {
1024            metadata: ObjectMeta {
1025                labels: Some(BTreeMap::from([(
1026                    "app.kubernetes.io/name".to_string(),
1027                    "operator-value".to_string(),
1028                )])),
1029                managed_fields: Some(vec![ManagedFieldsEntry {
1030                    manager: Some("test-operator".to_string()),
1031                    operation: Some("Apply".to_string()),
1032                    subresource: None,
1033                    fields_v1: Some(FieldsV1(json!({
1034                        "f:metadata": {
1035                            "f:labels": { ".": {}, "f:app.kubernetes.io/name": {} }
1036                        }
1037                    }))),
1038                    fields_type: Some("FieldsV1".to_string()),
1039                    ..Default::default()
1040                }]),
1041                ..Default::default()
1042            },
1043            ..Default::default()
1044        };
1045        assert!(owner.needs_meta_template_apply(&live).is_none());
1046    }
1047
1048    #[test]
1049    fn test_out_of_sync_annotation_value_mismatch() {
1050        // Exercises the annotation branch of the value_mismatch closure separately.
1051        let owner = owner(Some(MetadataTemplate {
1052            labels: None,
1053            annotations: Some(BTreeMap::from([(
1054                "example.com/team".to_string(),
1055                "platform".to_string(),
1056            )])),
1057        }));
1058        // Annotation key present but with the wrong value.
1059        let live = secret_meta(
1060            BTreeMap::new(),
1061            BTreeMap::from([("example.com/team".to_string(), "other-team".to_string())]),
1062            &[],
1063            &["example.com/team"],
1064        );
1065        assert!(owner.needs_meta_template_apply(&live).is_some());
1066    }
1067
1068    #[test]
1069    fn test_out_of_sync_label_key_absent_from_live() {
1070        // Key is not present at all in the live object's labels (not just wrong value).
1071        let owner = owner(Some(MetadataTemplate {
1072            labels: Some(BTreeMap::from([(
1073                "example.com/env".to_string(),
1074                "prod".to_string(),
1075            )])),
1076            annotations: None,
1077        }));
1078        // Live has no labels at all; template manager owns the key (preventing a stale-key
1079        // misdiagnosis), but the value is missing.
1080        let live = secret_meta(BTreeMap::new(), BTreeMap::new(), &["example.com/env"], &[]);
1081        assert!(owner.needs_meta_template_apply(&live).is_some());
1082    }
1083
1084    #[test]
1085    fn test_in_sync_empty_template_no_stale_fields() {
1086        // `secretTemplate: {}` — Some but with neither labels nor annotations set.
1087        // Template manager owns nothing → in sync, no apply needed.
1088        let owner = owner(Some(MetadataTemplate {
1089            labels: None,
1090            annotations: None,
1091        }));
1092        let live: PartialObjectMeta<Secret> = PartialObjectMeta::default();
1093        assert!(owner.needs_meta_template_apply(&live).is_none());
1094    }
1095
1096    #[test]
1097    fn test_out_of_sync_empty_template_stale_fields_remain() {
1098        // `secretTemplate: {}` but the template manager still owns a stale label from a
1099        // previous (larger) template → cleanup apply needed.
1100        let owner = owner(Some(MetadataTemplate {
1101            labels: None,
1102            annotations: None,
1103        }));
1104        let live = secret_meta(
1105            BTreeMap::new(),
1106            BTreeMap::new(),
1107            &["example.com/stale"],
1108            &[],
1109        );
1110        let result = owner.needs_meta_template_apply(&live);
1111        assert!(result.is_some());
1112        let filtered = result.unwrap();
1113        // The filtered result must be empty (nothing to apply — SSA will release ownership).
1114        assert!(filtered.labels.is_empty());
1115        assert!(filtered.annotations.is_empty());
1116        assert!(!filtered.has_discards());
1117    }
1118
1119    #[test]
1120    fn test_in_sync_template_operator_name_prefix() {
1121        // template_operator_name() must prepend "template." to OPERATOR_NAME.
1122        assert_eq!(
1123            TestOwner::template_operator_name(),
1124            "template.test-operator"
1125        );
1126    }
1127}