Skip to main content

engenho_controllers/
crd_conversion.rs

1//! CRD CONVERSION — reading a stored custom resource at a version other
2//! than the one it was written in.
3//!
4//! ★ THE BUG THIS CLOSES IS SILENT AND CORRUPTING. engenho serves every
5//! `served: true` version of a CRD, and every one of them reads and writes
6//! the SAME stored object at its own GVK — `storage: true` was recorded and
7//! not load-bearing. So a CR written as `v1beta1` is handed to a `v1`
8//! client verbatim, with `apiVersion` still claiming `v1beta1` and fields
9//! laid out the way the older schema expected. The client does not error:
10//! it reads the fields it recognises, silently misses the ones that moved,
11//! and writes back a shape the other version cannot parse.
12//!
13//! ★ THERE IS EXACTLY ONE STORAGE VERSION, AND IT IS AN INVARIANT, NOT A
14//! CONVENTION. A CRD declaring two is not "ambiguous" — it is invalid, and
15//! accepting it means the same object is written to two schemas and neither
16//! reader can trust what it gets. [`storage_version`] refuses rather than
17//! picking, because picking is how the corruption starts.
18//!
19//! ★ `None` IS A LEGAL STRATEGY AND IT IS NOT "NO CONVERSION". Upstream's
20//! `strategy: None` means "the versions are structurally identical, just
21//! relabel `apiVersion`". That is a real, correct conversion for the common
22//! case of a version bump with no schema change — and it is why a relabel
23//! must actually happen rather than the object being passed through
24//! untouched with a stale `apiVersion` a client will believe.
25//!
26//! ★ A WEBHOOK STRATEGY WITHOUT A REACHABLE WEBHOOK FAILS THE READ. It does
27//! NOT fall back to a relabel. Falling back would hand the client an object
28//! in the wrong schema while reporting success, which is precisely the
29//! silent corruption above — only now with a configuration that claims to
30//! prevent it.
31
32use serde_json::Value;
33use thiserror::Error;
34
35/// How a CRD says its versions convert.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum Strategy {
38    /// Versions are structurally identical; only `apiVersion` changes.
39    None,
40    /// An external webhook performs the conversion.
41    Webhook { url: String },
42}
43
44/// Why a conversion could not be performed.
45#[derive(Debug, Clone, PartialEq, Eq, Error)]
46pub enum ConversionError {
47    /// The CRD declares no storage version, or more than one.
48    #[error("CRD must declare exactly one storage version, found {found}")]
49    StorageVersionAmbiguous { found: usize },
50    /// The requested version is not served by this CRD.
51    #[error("version {version:?} is not served by this CRD")]
52    VersionNotServed { version: String },
53    /// A webhook strategy is declared but the webhook could not be used.
54    ///
55    /// Deliberately NOT a fallback to a relabel — see the module note.
56    #[error("conversion webhook is required for this CRD but is unavailable: {reason}")]
57    WebhookUnavailable { reason: String },
58    /// The stored object does not carry an `apiVersion`.
59    #[error("stored object has no apiVersion to convert from")]
60    MissingApiVersion,
61}
62
63/// The single storage version a CRD declares.
64///
65/// Refuses on zero or many rather than picking one: a CRD with two storage
66/// versions writes the same object to two schemas, and neither reader can
67/// trust what it gets. Picking is how that corruption starts.
68pub fn storage_version(crd: &Value) -> Result<String, ConversionError> {
69    let versions = crd
70        .get("spec")
71        .and_then(|s| s.get("versions"))
72        .and_then(Value::as_array)
73        .map_or_else(Vec::new, |vs| {
74            vs.iter()
75                .filter(|v| v.get("storage").and_then(Value::as_bool) == Some(true))
76                .filter_map(|v| v.get("name").and_then(Value::as_str))
77                .collect()
78        });
79    match versions.as_slice() {
80        [one] => Ok((*one).to_string()),
81        other => Err(ConversionError::StorageVersionAmbiguous { found: other.len() }),
82    }
83}
84
85/// Read a CRD's conversion strategy.
86///
87/// Absent `spec.conversion` means `None` — upstream's default, and the
88/// right one: a CRD with a single version needs no conversion machinery.
89#[must_use]
90pub fn strategy_of(crd: &Value) -> Strategy {
91    let conv = crd.get("spec").and_then(|s| s.get("conversion"));
92    let named = conv
93        .and_then(|c| c.get("strategy"))
94        .and_then(Value::as_str)
95        .unwrap_or("None");
96    if named != "Webhook" {
97        return Strategy::None;
98    }
99    let url = conv
100        .and_then(|c| c.get("webhook"))
101        .and_then(|w| w.get("clientConfig"))
102        .and_then(|cc| cc.get("url"))
103        .and_then(Value::as_str)
104        .unwrap_or_default()
105        .to_string();
106    Strategy::Webhook { url }
107}
108
109/// Is `version` served by this CRD?
110#[must_use]
111pub fn is_served(crd: &Value, version: &str) -> bool {
112    crd.get("spec")
113        .and_then(|s| s.get("versions"))
114        .and_then(Value::as_array)
115        .is_some_and(|vs| {
116            vs.iter().any(|v| {
117                v.get("name").and_then(Value::as_str) == Some(version)
118                    && v.get("served").and_then(Value::as_bool) != Some(false)
119            })
120        })
121}
122
123/// Convert a stored object to `target_version` under the `None` strategy.
124///
125/// The relabel is the WHOLE conversion here, and it must actually happen:
126/// passing the object through untouched leaves an `apiVersion` the client
127/// will believe, and a client that asked for `v1` and is told `v1beta1`
128/// either errors or — worse — proceeds against the wrong schema.
129pub fn convert_none(
130    crd: &Value,
131    object: &Value,
132    target_version: &str,
133) -> Result<Value, ConversionError> {
134    if !is_served(crd, target_version) {
135        return Err(ConversionError::VersionNotServed {
136            version: target_version.to_string(),
137        });
138    }
139    let current = object
140        .get("apiVersion")
141        .and_then(Value::as_str)
142        .ok_or(ConversionError::MissingApiVersion)?;
143    // Keep the group, replace only the version — `example.com/v1beta1`
144    // becomes `example.com/v1`. Rebuilding the whole string from the CRD's
145    // group would silently "fix" an object stored under a different group,
146    // which is a mismatch worth surfacing rather than papering over.
147    let group = current.rsplit_once('/').map_or("", |(g, _)| g);
148    let mut out = object.clone();
149    out["apiVersion"] = Value::String(if group.is_empty() {
150        target_version.to_string()
151    } else {
152        format!("{group}/{target_version}")
153    });
154    Ok(out)
155}
156
157/// Plan the conversion for a read at `target_version`.
158///
159/// Returns the converted object for the `None` strategy, or the error
160/// naming why a webhook is needed. A caller that CAN reach the webhook
161/// calls it; one that cannot must surface this rather than fall back.
162pub fn convert_for_read(
163    crd: &Value,
164    object: &Value,
165    target_version: &str,
166) -> Result<Value, ConversionError> {
167    // The storage version must be unambiguous before anything is read, or
168    // the object's provenance is already unknowable.
169    let _ = storage_version(crd)?;
170    match strategy_of(crd) {
171        Strategy::None => convert_none(crd, object, target_version),
172        Strategy::Webhook { url } => Err(ConversionError::WebhookUnavailable {
173            reason: if url.is_empty() {
174                "strategy is Webhook but clientConfig declares no url".to_string()
175            } else {
176                format!("webhook at {url} has not been called")
177            },
178        }),
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use serde_json::json;
186
187    fn crd(versions: Value, conversion: Option<Value>) -> Value {
188        let mut c = json!({ "spec": { "group": "example.com", "versions": versions } });
189        if let Some(conv) = conversion {
190            c["spec"]["conversion"] = conv;
191        }
192        c
193    }
194
195    fn two_versions() -> Value {
196        json!([
197            { "name": "v1beta1", "served": true, "storage": false },
198            { "name": "v1", "served": true, "storage": true }
199        ])
200    }
201
202    fn stored() -> Value {
203        json!({
204            "apiVersion": "example.com/v1beta1",
205            "kind": "Widget",
206            "metadata": { "name": "w" },
207            "spec": { "size": 3 }
208        })
209    }
210
211    #[test]
212    fn a_read_at_another_version_relabels_the_object() {
213        // Anti-vacuity, and the bug: before this a v1 client received an
214        // object still claiming v1beta1 and proceeded against the wrong
215        // schema without an error.
216        let c = crd(two_versions(), None);
217        let out = convert_for_read(&c, &stored(), "v1").expect("converts");
218        assert_eq!(out["apiVersion"], "example.com/v1");
219        // Everything else is untouched — a None-strategy conversion is a
220        // relabel, not a rewrite.
221        assert_eq!(out["spec"]["size"], 3);
222        assert_eq!(out["metadata"]["name"], "w");
223    }
224
225    #[test]
226    fn exactly_one_storage_version_is_an_invariant_not_a_convention() {
227        // A CRD with two writes the same object to two schemas and neither
228        // reader can trust what it gets. Refusing beats picking.
229        assert_eq!(storage_version(&crd(two_versions(), None)), Ok("v1".into()));
230
231        let none = json!([{ "name": "v1", "served": true, "storage": false }]);
232        assert_eq!(
233            storage_version(&crd(none, None)),
234            Err(ConversionError::StorageVersionAmbiguous { found: 0 })
235        );
236
237        let two = json!([
238            { "name": "v1", "served": true, "storage": true },
239            { "name": "v2", "served": true, "storage": true }
240        ]);
241        assert_eq!(
242            storage_version(&crd(two, None)),
243            Err(ConversionError::StorageVersionAmbiguous { found: 2 })
244        );
245    }
246
247    #[test]
248    fn a_webhook_strategy_fails_the_read_rather_than_falling_back() {
249        // Falling back to a relabel would hand the client an object in the
250        // WRONG schema while reporting success — the silent corruption this
251        // module exists to stop, with a configuration that claims to
252        // prevent it.
253        let c = crd(
254            two_versions(),
255            Some(json!({
256                "strategy": "Webhook",
257                "webhook": { "clientConfig": { "url": "https://conv.example/convert" } }
258            })),
259        );
260        match convert_for_read(&c, &stored(), "v1") {
261            Err(ConversionError::WebhookUnavailable { reason }) => {
262                assert!(reason.contains("conv.example"), "got: {reason}");
263            }
264            other => panic!("expected WebhookUnavailable, got {other:?}"),
265        }
266    }
267
268    #[test]
269    fn a_webhook_strategy_with_no_url_says_which_half_is_missing() {
270        // "the webhook is unavailable" and "you never configured one" are
271        // different operator actions.
272        let c = crd(
273            two_versions(),
274            Some(json!({ "strategy": "Webhook", "webhook": { "clientConfig": {} } })),
275        );
276        match convert_for_read(&c, &stored(), "v1") {
277            Err(ConversionError::WebhookUnavailable { reason }) => {
278                assert!(reason.contains("no url"), "got: {reason}");
279            }
280            other => panic!("expected WebhookUnavailable, got {other:?}"),
281        }
282    }
283
284    #[test]
285    fn an_absent_conversion_block_means_the_none_strategy() {
286        // Upstream's default, and the right one: a single-version CRD needs
287        // no conversion machinery.
288        assert_eq!(strategy_of(&crd(two_versions(), None)), Strategy::None);
289        assert_eq!(
290            strategy_of(&crd(two_versions(), Some(json!({ "strategy": "None" })))),
291            Strategy::None
292        );
293    }
294
295    #[test]
296    fn an_unserved_version_is_refused() {
297        // Serving a version the CRD withdrew would resurrect a schema the
298        // author deliberately retired.
299        let versions = json!([
300            { "name": "v1", "served": true, "storage": true },
301            { "name": "v1alpha1", "served": false, "storage": false }
302        ]);
303        let c = crd(versions, None);
304        assert!(!is_served(&c, "v1alpha1"));
305        assert_eq!(
306            convert_for_read(&c, &stored(), "v1alpha1"),
307            Err(ConversionError::VersionNotServed {
308                version: "v1alpha1".into()
309            })
310        );
311    }
312
313    #[test]
314    fn the_group_is_preserved_not_rebuilt_from_the_crd() {
315        // Rebuilding it would silently "fix" an object stored under a
316        // different group — a mismatch worth surfacing, not papering over.
317        let c = crd(two_versions(), None);
318        let mut foreign = stored();
319        foreign["apiVersion"] = json!("other.io/v1beta1");
320        let out = convert_for_read(&c, &foreign, "v1").expect("converts");
321        assert_eq!(out["apiVersion"], "other.io/v1");
322    }
323
324    #[test]
325    fn an_object_with_no_api_version_is_refused_not_guessed() {
326        let c = crd(two_versions(), None);
327        let mut bare = stored();
328        bare.as_object_mut().unwrap().remove("apiVersion");
329        assert_eq!(
330            convert_for_read(&c, &bare, "v1"),
331            Err(ConversionError::MissingApiVersion)
332        );
333    }
334
335    #[test]
336    fn an_ambiguous_storage_version_fails_the_read_before_anything_is_converted() {
337        // The object's provenance is already unknowable at that point;
338        // converting anyway would produce a confident wrong answer.
339        let two = json!([
340            { "name": "v1", "served": true, "storage": true },
341            { "name": "v2", "served": true, "storage": true }
342        ]);
343        assert_eq!(
344            convert_for_read(&crd(two, None), &stored(), "v1"),
345            Err(ConversionError::StorageVersionAmbiguous { found: 2 })
346        );
347    }
348}