kube-cel 0.6.0

Kubernetes CEL extension functions for the cel crate
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
//! Static analysis for CEL validation rules.
//!
//! Provides compile-time checks beyond syntax validation:
//! variable scope validation and cost estimation.

use cel::{Program, common::ast::Expr};

use crate::validation::compilation::CompiledSchema;

/// The context in which a CEL rule is evaluated.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScopeContext {
    /// CRD `x-kubernetes-validations` — only `self`, `oldSelf`, and root vars.
    CrdValidation,
    /// ValidatingAdmissionPolicy — `object`, `oldObject`, `request`, `params`, etc.
    AdmissionPolicy,
}

/// A warning produced by static analysis.
///
/// `#[non_exhaustive]`: an output type the crate constructs; new fields may be
/// added without a breaking change.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct AnalysisWarning {
    /// The CEL rule the warning applies to.
    pub rule: String,
    /// Human-readable description of the warning.
    pub message: String,
    /// Classification of the warning.
    pub kind: WarningKind,
}

/// The kind of warning produced by static analysis.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum WarningKind {
    /// Variable not available in the given scope.
    WrongScope,
    /// Estimated cost may exceed K8s budget.
    CostExceeded,
    /// Schema bounds missing (inflates cost estimate).
    MissingBounds,
}

fn valid_variables(scope: ScopeContext) -> &'static [&'static str] {
    match scope {
        ScopeContext::CrdValidation => &["self", "oldSelf", "apiVersion", "apiGroup", "kind"],
        ScopeContext::AdmissionPolicy => &[
            "self",
            "oldSelf",
            "object",
            "oldObject",
            "request",
            "params",
            "namespaceObject",
            "authorizer",
            "variables",
        ],
    }
}

/// Check a CEL expression for variable scope violations.
#[must_use]
pub fn check_rule_scope(rule: &str, scope: ScopeContext) -> Vec<AnalysisWarning> {
    let program = match Program::compile(rule) {
        Ok(p) => p,
        Err(_) => return vec![],
    };

    let valid = valid_variables(scope);
    let mut warnings = Vec::new();

    for var in program.references().variables() {
        if !valid.contains(&var) {
            warnings.push(AnalysisWarning {
                rule: rule.to_string(),
                message: format!(
                    "variable '{}' is not available in {:?} context; valid variables: {:?}",
                    var, scope, valid
                ),
                kind: WarningKind::WrongScope,
            });
        }
    }

    warnings
}

const DEFAULT_MAX_ITEMS: u64 = 1000;
const DEFAULT_MAX_LENGTH: u64 = 1000;
const K8S_COST_BUDGET: u64 = 1_000_000;
const STRING_TRAVERSAL_FACTOR: f64 = 0.1;

/// Estimate cost of a CEL rule and warn if it may exceed K8s budget.
///
/// This is a coarse heuristic, not an accurate cost model. It catches the most
/// common issue: unbounded list comprehensions without maxItems.
#[must_use]
pub fn estimate_rule_cost(rule: &str, schema: &CompiledSchema) -> Vec<AnalysisWarning> {
    let program = match Program::compile(rule) {
        Ok(p) => p,
        Err(_) => return vec![],
    };

    let expr = program.expression();
    let mut warnings = Vec::new();
    let cost = estimate_expr_cost(&expr.expr, schema);

    if cost > K8S_COST_BUDGET {
        warnings.push(AnalysisWarning {
            rule: rule.to_string(),
            message: format!(
                "estimated cost {} exceeds K8s budget {}; consider adding maxItems/maxLength to schema bounds",
                cost, K8S_COST_BUDGET
            ),
            kind: WarningKind::CostExceeded,
        });
    }

    check_missing_bounds(&expr.expr, schema, rule, &mut warnings);
    warnings
}

/// Run all available static analyses on a CEL rule in a single pass.
///
/// Compiles the rule once and performs both scope validation and cost estimation.
/// More efficient than calling [`check_rule_scope`] and [`estimate_rule_cost`] separately.
#[must_use]
pub fn analyze_rule(rule: &str, schema: &CompiledSchema, scope: ScopeContext) -> Vec<AnalysisWarning> {
    let program = match Program::compile(rule) {
        Ok(p) => p,
        Err(_) => return vec![],
    };

    let mut warnings = Vec::new();

    // Scope validation
    let valid = valid_variables(scope);
    for var in program.references().variables() {
        if !valid.contains(&var) {
            warnings.push(AnalysisWarning {
                rule: rule.to_string(),
                message: format!(
                    "variable '{}' is not available in {:?} context; valid variables: {:?}",
                    var, scope, valid
                ),
                kind: WarningKind::WrongScope,
            });
        }
    }

    // Cost estimation
    let expr = program.expression();
    let cost = estimate_expr_cost(&expr.expr, schema);
    if cost > K8S_COST_BUDGET {
        warnings.push(AnalysisWarning {
            rule: rule.to_string(),
            message: format!(
                "estimated cost {} exceeds K8s budget {}; consider adding maxItems/maxLength to schema bounds",
                cost, K8S_COST_BUDGET
            ),
            kind: WarningKind::CostExceeded,
        });
    }
    check_missing_bounds(&expr.expr, schema, rule, &mut warnings);

    warnings
}

fn estimate_expr_cost(expr: &Expr, schema: &CompiledSchema) -> u64 {
    match expr {
        Expr::Comprehension(comp) => {
            let list_size = find_max_items(schema);
            let body_cost = estimate_expr_cost(&comp.loop_step.expr, schema);
            list_size * body_cost.max(1)
        }
        Expr::Call(call) => {
            let base = 1u64;
            let target_cost = call
                .target
                .as_ref()
                .map(|t| estimate_expr_cost(&t.expr, schema))
                .unwrap_or(0);
            let arg_cost: u64 = call
                .args
                .iter()
                .map(|a| estimate_expr_cost(&a.expr, schema))
                .sum();
            if is_string_traversal(&call.func_name) {
                let str_len = find_max_length(schema);
                base + (str_len as f64 * STRING_TRAVERSAL_FACTOR) as u64 + target_cost + arg_cost
            } else {
                base + target_cost + arg_cost
            }
        }
        Expr::Select(sel) => 1 + estimate_expr_cost(&sel.operand.expr, schema),
        Expr::List(list) => list
            .elements
            .iter()
            .map(|e| estimate_expr_cost(&e.expr, schema))
            .sum::<u64>()
            .max(1),
        _ => 1,
    }
}

fn find_max_items(schema: &CompiledSchema) -> u64 {
    if let Some(max) = schema.max_items {
        return max;
    }
    for prop in schema.properties.values() {
        if prop.items.is_some() {
            return prop.max_items.unwrap_or(DEFAULT_MAX_ITEMS);
        }
    }
    DEFAULT_MAX_ITEMS
}

fn find_max_length(schema: &CompiledSchema) -> u64 {
    if let Some(max) = schema.max_length {
        return max;
    }
    for prop in schema.properties.values() {
        if let Some(max) = prop.max_length {
            return max;
        }
    }
    DEFAULT_MAX_LENGTH
}

fn is_string_traversal(func: &str) -> bool {
    matches!(
        func,
        "contains"
            | "startsWith"
            | "endsWith"
            | "matches"
            | "find"
            | "findAll"
            | "replace"
            | "split"
            | "indexOf"
            | "lastIndexOf"
    )
}

fn check_missing_bounds(
    expr: &Expr,
    schema: &CompiledSchema,
    rule: &str,
    warnings: &mut Vec<AnalysisWarning>,
) {
    if let Expr::Comprehension(_) = expr {
        for prop in schema.properties.values() {
            if prop.items.is_some() && prop.max_items.is_none() {
                warnings.push(AnalysisWarning {
                    rule: rule.to_string(),
                    message: "list field has no maxItems bound; cost estimate uses worst-case default".into(),
                    kind: WarningKind::MissingBounds,
                });
                break;
            }
        }
    }
}

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

    #[test]
    fn detect_wrong_scope_variable() {
        let warnings = check_rule_scope(
            "request.userInfo.username == 'admin'",
            ScopeContext::CrdValidation,
        );
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].message.contains("request"));
        assert_eq!(warnings[0].kind, WarningKind::WrongScope);
    }

    #[test]
    fn self_and_old_self_are_valid() {
        let warnings = check_rule_scope("self.replicas >= oldSelf.replicas", ScopeContext::CrdValidation);
        assert!(warnings.is_empty());
    }

    #[test]
    fn admission_policy_scope_allows_request() {
        let warnings = check_rule_scope(
            "request.userInfo.username == 'admin'",
            ScopeContext::AdmissionPolicy,
        );
        assert!(warnings.is_empty());
    }

    #[test]
    fn crd_scope_rejects_object_variable() {
        let warnings = check_rule_scope("object.metadata.name == 'test'", ScopeContext::CrdValidation);
        assert_eq!(warnings.len(), 1);
    }

    #[test]
    fn invalid_syntax_returns_empty() {
        let warnings = check_rule_scope("self.x >=", ScopeContext::CrdValidation);
        assert!(warnings.is_empty());
    }

    #[test]
    fn unbounded_list_comprehension_warns() {
        let schema = json!({
            "type": "object",
            "properties": {
                "items": {
                    "type": "array",
                    "items": {"type": "string"}
                }
            }
        });
        let compiled = compile_schema(&schema);
        let warnings = estimate_rule_cost("self.items.all(item, item.size() > 0)", &compiled);
        assert!(
            warnings
                .iter()
                .any(|w| w.kind == WarningKind::CostExceeded || w.kind == WarningKind::MissingBounds)
        );
    }

    #[test]
    fn bounded_list_no_cost_warning() {
        let schema = json!({
            "type": "object",
            "properties": {
                "items": {
                    "type": "array",
                    "maxItems": 10,
                    "items": {"type": "string", "maxLength": 64}
                }
            }
        });
        let compiled = compile_schema(&schema);
        let warnings = estimate_rule_cost("self.items.all(item, item.size() > 0)", &compiled);
        // With bounded list (10 items), cost should be low
        assert!(warnings.iter().all(|w| w.kind != WarningKind::CostExceeded));
    }

    #[test]
    fn simple_comparison_low_cost() {
        let schema = json!({
            "type": "object",
            "properties": {"x": {"type": "integer"}}
        });
        let compiled = compile_schema(&schema);
        let warnings = estimate_rule_cost("self.x >= 0", &compiled);
        assert!(warnings.is_empty());
    }

    #[test]
    fn analyze_rule_catches_scope_issue() {
        let schema = json!({"type": "object", "properties": {"x": {"type": "integer"}}});
        let compiled = compile_schema(&schema);
        let warnings = analyze_rule("request.name == 'test'", &compiled, ScopeContext::CrdValidation);
        assert!(warnings.iter().any(|w| w.kind == WarningKind::WrongScope));
    }

    #[test]
    fn analyze_rule_catches_cost_and_bounds() {
        let schema = json!({
            "type": "object",
            "properties": {
                "items": {"type": "array", "items": {"type": "string"}}
            }
        });
        let compiled = compile_schema(&schema);
        let warnings = analyze_rule(
            "self.items.all(item, item.size() > 0)",
            &compiled,
            ScopeContext::CrdValidation,
        );
        // `self` should not be flagged as a scope violation
        assert!(
            !warnings
                .iter()
                .any(|w| w.kind == WarningKind::WrongScope && w.message.contains("'self'"))
        );
        // Missing maxItems bound should be reported
        assert!(warnings.iter().any(|w| w.kind == WarningKind::MissingBounds));
    }

    #[test]
    fn missing_bounds_warning() {
        let schema = json!({
            "type": "object",
            "properties": {
                "items": {
                    "type": "array",
                    "items": {"type": "string"}
                }
            }
        });
        let compiled = compile_schema(&schema);
        let warnings = estimate_rule_cost("self.items.all(item, item.size() > 0)", &compiled);
        assert!(warnings.iter().any(|w| w.kind == WarningKind::MissingBounds));
    }
}