kube-core 4.0.0

Kube shared types, traits and client-less behavior
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! CEL validation for CRDs
//!
//! When the `cel` feature is enabled, this module also provides client-side CEL evaluation
//! via Kubernetes CEL extension functions, schema compilation, and validation.

use std::{collections::BTreeMap, str::FromStr};

// --- Client-side CEL evaluation (feature = "cel") ---
// Re-exported from the kube-cel crate when the `cel` feature is enabled.

#[cfg(feature = "cel")]
#[cfg_attr(docsrs, doc(cfg(feature = "cel")))]
pub use kube_cel::*;

use derive_more::From;
#[cfg(feature = "schema")] use schemars::Schema;
use serde::{Deserialize, Serialize};
use serde_json::Value;

// --- Client-side CEL validation helpers (feature = "cel") ---
//
// These back the `validate_cel` / `validate_cel_update` methods that kube-derive generates for
// `#[kube(cel)]` / `#[x_kube(cel)]`. The derive emits thin inherent wrappers that delegate here,
// so the validation logic is compiled once in this crate instead of being re-expanded (and the
// proc-macro re-parsed) at every derive site. The wrappers keep the public method surface, so the
// derive stays the opt-in gatekeeper (only `#[kube(cel)]` types get the methods) and the
// `schema = "manual"` compile-time rejection still lives in the macro.

/// Validate a derived custom resource against its CEL creation rules (`x-kubernetes-validations`)
/// client-side, without an apiserver. Backs the generated `Foo::validate_cel(&self)`.
#[cfg(feature = "cel")]
#[cfg_attr(docsrs, doc(cfg(feature = "cel")))]
pub fn validate_cel<T>(obj: &T) -> Result<(), ValidationErrors>
where
    T: crate::CustomResourceExt + Serialize,
{
    validate_cel_with_old(obj, None)
}

/// Validate a derived custom resource against its CEL transition rules (rules using `oldSelf`)
/// client-side, comparing against `old`. Backs the generated `Foo::validate_cel_update(&self, old)`.
#[cfg(feature = "cel")]
#[cfg_attr(docsrs, doc(cfg(feature = "cel")))]
pub fn validate_cel_update<T>(obj: &T, old: &T) -> Result<(), ValidationErrors>
where
    T: crate::CustomResourceExt + Serialize,
{
    let old = serde_json::to_value(old).expect("resource serializes to JSON");
    validate_cel_with_old(obj, Some(old))
}

#[cfg(feature = "cel")]
fn validate_cel_with_old<T>(obj: &T, old: Option<Value>) -> Result<(), ValidationErrors>
where
    T: crate::CustomResourceExt + Serialize,
{
    let crd = T::crd();
    let schema = serde_json::to_value(
        crd.spec.versions[0]
            .schema
            .as_ref()
            .and_then(|s| s.open_api_v3_schema.as_ref())
            .expect("derived CRD has an openAPIV3Schema"),
    )
    .expect("CRD schema serializes to JSON");
    let object = serde_json::to_value(obj).expect("resource serializes to JSON");
    Validator::new().validate(&schema, &object, old.as_ref())
}

/// Validate a serialized value of a `KubeSchema` type against its CEL validation rules
/// (`x-kubernetes-validations`) client-side, without an apiserver. Backs the generated static
/// `T::validate_cel(value, old)`.
///
/// The schema is generated with the same openAPIV3 settings and structural transforms the CRD path
/// uses, so the `x-kubernetes-validations` rules and structure match what an apiserver would
/// validate; `schemars::schema_for!` (plain JSON-Schema 2020-12, non-inlined `$ref`s) would not be
/// walkable by kube-cel.
#[cfg(all(feature = "cel", feature = "schema"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "cel", feature = "schema"))))]
pub fn validate_cel_schema<T>(value: &Value, old: Option<&Value>) -> Result<(), ValidationErrors>
where
    T: schemars::JsonSchema,
{
    let generate = schemars::generate::SchemaSettings::openapi3()
        .with(|s| {
            s.inline_subschemas = true;
            s.meta_schema = None;
        })
        .with_transform(schemars::transform::AddNullable::default())
        .with_transform(crate::schema::StructuralSchemaRewriter)
        .with_transform(crate::schema::OptionalEnum)
        .with_transform(crate::schema::OptionalIntOrString)
        .into_generator();
    let schema = generate.into_root_schema_for::<T>();
    let schema = serde_json::to_value(&schema).expect("schema serializes to JSON");
    Validator::new().validate(&schema, value, old)
}

/// Rule is a CEL validation rule for the CRD field
#[derive(Default, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Rule {
    /// rule represents the expression which will be evaluated by CEL.
    /// The `self` variable in the CEL expression is bound to the scoped value.
    pub rule: String,
    /// message represents CEL validation message for the provided type
    /// If unset, the message is "failed rule: {Rule}".
    #[serde(flatten)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<Message>,
    /// fieldPath represents the field path returned when the validation fails.
    /// It must be a relative JSON path, scoped to the location of the field in the schema
    #[serde(skip_serializing_if = "Option::is_none")]
    pub field_path: Option<String>,
    /// reason is a machine-readable value providing more detail about why a field failed the validation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<Reason>,
    /// optionalOldSelf allows transition rules (using oldSelf) to also evaluate during object creation
    /// When enabled, `oldSelf` becomes a CEL `optional_type`. You must use functions like `optMap()`, `hasValue()`, or `orValue()` to safely compare it against `self`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub optional_old_self: Option<bool>,
}

impl Rule {
    /// Initialize the rule
    ///
    /// ```rust
    /// use kube_core::Rule;
    /// let r = Rule::new("self == oldSelf");
    ///
    /// assert_eq!(r.rule, "self == oldSelf".to_string())
    /// ```
    pub fn new(rule: impl Into<String>) -> Self {
        Self {
            rule: rule.into(),
            ..Default::default()
        }
    }

    /// Set the rule message.
    ///
    /// use kube_core::Rule;
    /// ```rust
    /// use kube_core::{Rule, Message};
    ///
    /// let r = Rule::new("self == oldSelf").message("is immutable");
    /// assert_eq!(r.rule, "self == oldSelf".to_string());
    /// assert_eq!(r.message, Some(Message::Message("is immutable".to_string())));
    /// ```
    pub fn message(mut self, message: impl Into<Message>) -> Self {
        self.message = Some(message.into());
        self
    }

    /// Set the failure reason.
    ///
    /// use kube_core::Rule;
    /// ```rust
    /// use kube_core::{Rule, Reason};
    ///
    /// let r = Rule::new("self == oldSelf").reason(Reason::default());
    /// assert_eq!(r.rule, "self == oldSelf".to_string());
    /// assert_eq!(r.reason, Some(Reason::FieldValueInvalid));
    /// ```
    pub fn reason(mut self, reason: impl Into<Reason>) -> Self {
        self.reason = Some(reason.into());
        self
    }

    /// Set the failure field_path.
    ///
    /// use kube_core::Rule;
    /// ```rust
    /// use kube_core::Rule;
    ///
    /// let r = Rule::new("self == oldSelf").field_path("obj.field");
    /// assert_eq!(r.rule, "self == oldSelf".to_string());
    /// assert_eq!(r.field_path, Some("obj.field".to_string()));
    /// ```
    pub fn field_path(mut self, field_path: impl Into<String>) -> Self {
        self.field_path = Some(field_path.into());
        self
    }

    /// Set the optionalOldSelf configuration.
    ///
    /// ```rust
    /// use kube_core::Rule;
    ///
    /// let r = Rule::new("oldSelf.optMap(o, o == self).orValue(true)").optional_old_self(true);
    /// assert_eq!(r.optional_old_self, Some(true));
    /// ```
    pub fn optional_old_self(mut self, optional: bool) -> Self {
        self.optional_old_self = Some(optional);
        self
    }
}

impl From<&str> for Rule {
    fn from(value: &str) -> Self {
        Self {
            rule: value.into(),
            ..Default::default()
        }
    }
}

impl From<(&str, &str)> for Rule {
    fn from((rule, msg): (&str, &str)) -> Self {
        Self {
            rule: rule.into(),
            message: Some(msg.into()),
            ..Default::default()
        }
    }
}
/// Message represents CEL validation message for the provided type
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Message {
    /// Message represents the message displayed when validation fails. The message is required if the Rule contains
    /// line breaks. The message must not contain line breaks.
    /// Example:
    /// "must be a URL with the host matching spec.host"
    Message(String),
    /// Expression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails.
    /// Since messageExpression is used as a failure message, it must evaluate to a string. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced
    /// as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string
    /// that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and
    /// the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged.
    /// messageExpression has access to all the same variables as the rule; the only difference is the return type.
    /// Example:
    /// "x must be less than max ("+string(self.max)+")"
    #[serde(rename = "messageExpression")]
    Expression(String),
}

impl From<&str> for Message {
    fn from(value: &str) -> Self {
        Message::Message(value.to_string())
    }
}

/// Reason is a machine-readable value providing more detail about why a field failed the validation.
///
/// More in [docs](https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#field-reason)
#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
pub enum Reason {
    /// FieldValueInvalid is used to report malformed values (e.g. failed regex
    /// match, too long, out of bounds).
    #[default]
    FieldValueInvalid,
    /// FieldValueForbidden is used to report valid (as per formatting rules)
    /// values which would be accepted under some conditions, but which are not
    /// permitted by the current conditions (such as security policy).
    FieldValueForbidden,
    /// FieldValueRequired is used to report required values that are not
    /// provided (e.g. empty strings, null values, or empty arrays).
    FieldValueRequired,
    /// FieldValueDuplicate is used to report collisions of values that must be
    /// unique (e.g. unique IDs).
    FieldValueDuplicate,
}

impl FromStr for Reason {
    type Err = serde_json::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        serde_json::from_str(s)
    }
}

/// Validate takes schema and applies a set of validation rules to it. The rules are stored
/// on the top level under the "x-kubernetes-validations".
///
/// ```rust
/// use schemars::Schema;
/// use kube::core::{Rule, Reason, Message, validate};
///
/// let mut schema = Schema::default();
/// let rule = Rule{
///     rule: "self.spec.host == self.url.host".into(),
///     message: Some("must be a URL with the host matching spec.host".into()),
///     field_path: Some("spec.host".into()),
///     ..Default::default()
/// };
/// validate(&mut schema, rule)?;
/// assert_eq!(
///     serde_json::to_string(&schema).unwrap(),
///     r#"{"x-kubernetes-validations":[{"fieldPath":"spec.host","message":"must be a URL with the host matching spec.host","rule":"self.spec.host == self.url.host"}]}"#,
/// );
/// # Ok::<(), serde_json::Error>(())
///```
#[cfg(feature = "schema")]
#[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
pub fn validate(s: &mut Schema, rule: impl Into<Rule>) -> serde_json::Result<()> {
    let rule: Rule = rule.into();
    let rule = serde_json::to_value(rule)?;
    s.ensure_object()
        .entry("x-kubernetes-validations")
        .and_modify(|rules| {
            if let Value::Array(rules) = rules {
                rules.push(rule.clone());
            }
        })
        .or_insert(serde_json::to_value(&[rule])?);
    Ok(())
}

/// Validate property mutates property under property_index of the schema
/// with the provided set of validation rules.
///
/// ```rust
/// use schemars::JsonSchema;
/// use kube::core::{Rule, validate_property};
///
/// #[derive(JsonSchema)]
/// struct MyStruct {
///     field: Option<String>,
/// }
///
/// let generate = &mut schemars::generate::SchemaSettings::openapi3().into_generator();
/// let mut schema = MyStruct::json_schema(generate);
/// let rule = Rule::new("self != oldSelf");
/// validate_property(&mut schema, 0, rule)?;
/// assert_eq!(
///     serde_json::to_string(&schema).unwrap(),
///     r#"{"type":"object","properties":{"field":{"type":["string","null"],"x-kubernetes-validations":[{"rule":"self != oldSelf"}]}}}"#
/// );
/// # Ok::<(), serde_json::Error>(())
///```
#[cfg(feature = "schema")]
#[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
pub fn validate_property(
    s: &mut Schema,
    property_index: usize,
    rule: impl Into<Rule> + Clone,
) -> serde_json::Result<()> {
    if let Some(properties) = s.properties_mut() {
        for (n, (_, schema)) in properties.iter_mut().enumerate() {
            if n == property_index {
                let mut prop = Schema::try_from(schema.clone())?;
                validate(&mut prop, rule.clone())?;
                *schema = prop.to_value();
            }
        }
    }
    Ok(())
}

/// Merge schema properties in order to pass overrides or extension properties from the other schema.
///
/// ```rust
/// use schemars::JsonSchema;
/// use kube::core::{Rule, merge_properties};
///
/// #[derive(JsonSchema)]
/// struct MyStruct {
///     a: Option<bool>,
/// }
///
/// #[derive(JsonSchema)]
/// struct MySecondStruct {
///     a: bool,
///     b: Option<bool>,
/// }
/// let generate = &mut schemars::generate::SchemaSettings::openapi3().into_generator();
/// let mut first = MyStruct::json_schema(generate);
/// let mut second = MySecondStruct::json_schema(generate);
/// merge_properties(&mut first, &mut second);
///
/// assert_eq!(
///     serde_json::to_string(&first).unwrap(),
///     r#"{"type":"object","properties":{"a":{"type":"boolean"},"b":{"type":["boolean","null"]}}}"#
/// );
/// # Ok::<(), serde_json::Error>(())
#[cfg(feature = "schema")]
#[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
pub fn merge_properties(s: &mut Schema, merge: &mut Schema) {
    if let Some(properties) = s.properties_mut()
        && let Some(merge_properties) = merge.properties_mut()
    {
        for (k, v) in merge_properties {
            properties.insert(k.clone(), v.clone());
        }
    }
}

/// ListType represents x-kubernetes merge strategy for list.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ListMerge {
    /// Atomic represents a list, where entire list is replaced during merge. At any point in time, a single manager owns the list.
    Atomic,
    /// Set applies to lists that include only scalar elements. These elements must be unique.
    Set,
    /// Map applies to lists of nested types only. The key values must be unique in the list.
    Map(Vec<String>),
}

/// MapMerge represents x-kubernetes merge strategy for map.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MapMerge {
    /// Atomic represents a map, which can only be entirely replaced by a single manager.
    Atomic,
    /// Granular represents a map, which supports separate managers updating individual fields.
    Granular,
}

/// StructMerge represents x-kubernetes merge strategy for struct.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum StructMerge {
    /// Atomic represents a struct, which can only be entirely replaced by a single manager.
    Atomic,
    /// Granular represents a struct, which supports separate managers updating individual fields.
    Granular,
}

/// MergeStrategy represents set of options for a server-side merge strategy applied to a field.
///
/// See upstream documentation of values at https://kubernetes.io/docs/reference/using-api/server-side-apply/#merge-strategy
#[derive(From, Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum MergeStrategy {
    /// ListType represents x-kubernetes merge strategy for list.
    #[serde(rename = "x-kubernetes-list-type")]
    ListType(ListMerge),
    /// MapType represents x-kubernetes merge strategy for map.
    #[serde(rename = "x-kubernetes-map-type")]
    MapType(MapMerge),
    /// StructType represents x-kubernetes merge strategy for struct.
    #[serde(rename = "x-kubernetes-struct-type")]
    StructType(StructMerge),
}

impl MergeStrategy {
    fn keys(self) -> serde_json::Result<BTreeMap<String, Value>> {
        if let Self::ListType(ListMerge::Map(keys)) = self {
            let mut data = BTreeMap::new();
            data.insert("x-kubernetes-list-type".into(), "map".into());
            data.insert("x-kubernetes-list-map-keys".into(), serde_json::to_value(&keys)?);

            return Ok(data);
        }

        let value = serde_json::to_value(self)?;
        serde_json::from_value(value)
    }
}

/// Merge strategy property mutates property under property_index of the schema
/// with the provided set of merge strategy rules.
///
/// ```rust
/// use schemars::JsonSchema;
/// use kube::core::{MapMerge, merge_strategy_property};
///
/// #[derive(JsonSchema)]
/// struct MyStruct {
///     field: Option<String>,
/// }
///
/// let generate = &mut schemars::generate::SchemaSettings::openapi3().into_generator();
/// let mut schema = MyStruct::json_schema(generate);
/// merge_strategy_property(&mut schema, 0, MapMerge::Atomic)?;
/// assert_eq!(
///     serde_json::to_string(&schema).unwrap(),
///     r#"{"type":"object","properties":{"field":{"type":["string","null"],"x-kubernetes-map-type":"atomic"}}}"#
/// );
///
/// # Ok::<(), serde_json::Error>(())
///```
#[cfg(feature = "schema")]
#[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
pub fn merge_strategy_property(
    s: &mut Schema,
    property_index: usize,
    strategy: impl Into<MergeStrategy>,
) -> serde_json::Result<()> {
    if let Some(properties) = s.properties_mut() {
        for (n, (_, schema)) in properties.iter_mut().enumerate() {
            if n == property_index {
                return merge_strategy(schema, strategy.into());
            }
        }
    }

    Ok(())
}

/// Merge strategy takes schema and applies a set of merge strategy x-kubernetes rules to it,
/// such as "x-kubernetes-list-type" and "x-kubernetes-list-map-keys".
///
/// ```rust
/// use kube::core::{ListMerge, Reason, Message, merge_strategy};
///
/// let mut schema = serde_json::Value::Object(Default::default());
/// merge_strategy(&mut schema, ListMerge::Map(vec!["key".into(),"another".into()]).into())?;
/// assert_eq!(
///     serde_json::to_string(&schema).unwrap(),
///     r#"{"x-kubernetes-list-map-keys":["key","another"],"x-kubernetes-list-type":"map"}"#,
/// );
///
/// # Ok::<(), serde_json::Error>(())
///```
#[cfg(feature = "schema")]
#[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
pub fn merge_strategy(s: &mut Value, strategy: MergeStrategy) -> serde_json::Result<()> {
    for (key, value) in strategy.keys()? {
        if let Some(s) = s.as_object_mut() {
            s.insert(key, value);
        }
    }
    Ok(())
}

#[cfg(feature = "schema")]
trait SchemaExt {
    fn properties_mut(&mut self) -> Option<&mut serde_json::Map<String, Value>>;
}

#[cfg(feature = "schema")]
impl SchemaExt for Schema {
    fn properties_mut(&mut self) -> Option<&mut serde_json::Map<String, Value>> {
        self.ensure_object()
            .entry("properties")
            .or_insert_with(|| Value::Object(Default::default()))
            .as_object_mut()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_rule_serialization_optional_old_self() {
        let rule_str = "oldSelf.optMap(o, o == self).orValue(true)";
        let r = Rule::new(rule_str).optional_old_self(true);

        // Test Serialization
        let json = serde_json::to_value(&r).unwrap();
        assert_eq!(
            json,
            json!({
                "rule": rule_str,
                "optionalOldSelf": true
            })
        );

        // Test Round-trip (Deserialization)
        let r2: Rule = serde_json::from_value(json).unwrap();
        assert_eq!(r2.rule, rule_str);
        assert_eq!(r2.optional_old_self, Some(true));
    }
}