ferricel-core 0.2.2

Core compiler and runtime library for ferricel (CEL → Wasm)
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
//! CEL to Wasm compiler.
//!
//! Use [`Builder`] to configure and compile CEL expressions into standalone
//! WebAssembly modules. The compiler supports host-provided
//! [flat extensions](https://flavio.github.io/ferricel/host-extensions.html#flat-extensions)
//! and [builder chains](https://flavio.github.io/ferricel/host-extensions.html#builder-chains).

pub mod access;
pub mod collections;
pub mod context;
pub mod expr;
pub mod functions;
pub mod helpers;
pub mod literals;
pub mod operators;
#[cfg(feature = "k8s-vap")]
#[cfg_attr(docsrs, doc(cfg(feature = "k8s-vap")))]
pub mod vap;

use std::collections::{BTreeSet, HashMap};

use anyhow::Context;
use cel::{common::ast::Expr, parser::Parser};
// Re-export the public API types
pub use context::ExtensionKey;
use context::{CompilerContext, CompilerEnv};
use ferricel_types::{
    extensions::{BuilderChainDecl, ExtensionDecl, UsedExtension},
    functions::RuntimeFunction,
};
use walrus::{FunctionBuilder, FunctionId, ModuleConfig, ValType};

// Embed the runtime Wasm at compile time.
// The build script (build.rs) copies the Wasm into OUT_DIR, resolving it from
// either the workspace target directory (development) or a bundled file
// placed by `make publish-prep` (when publishing to crates.io).
const RUNTIME_BYTES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/runtime.wasm"));

use crate::schema::ProtoSchema;

/// Builder for configuring and constructing a [`Compiler`].
///
/// All builder methods are consuming (take and return `Self`).
/// Call [`compiler::Builder::build`](Builder::build) to obtain an immutable [`Compiler`].
///
/// # Example
///
/// ```no_run
/// use ferricel_core::compiler::Builder;
///
/// let compiler = Builder::new()
///     .with_container("my.namespace")
///     .build();
///
/// let wasm_bytes = compiler.compile("1 + 1").unwrap();
/// ```
pub struct Builder {
    proto_descriptor: Option<Vec<u8>>,
    container: Option<String>,
    logger: slog::Logger,
    extensions: BTreeSet<ExtensionDecl>,
    builder_chains: Vec<BuilderChainDecl>,
}

impl Builder {
    /// Create a new builder with sensible defaults.
    ///
    /// The default logger discards all output.  Override it with
    /// [`with_logger`](Self::with_logger) if you need log output.
    pub fn new() -> Self {
        Self {
            proto_descriptor: None,
            container: None,
            logger: slog::Logger::root(slog::Discard, slog::o!()),
            extensions: BTreeSet::new(),
            builder_chains: Vec::new(),
        }
    }

    /// Override the logger used during compilation.
    pub fn with_logger(mut self, logger: slog::Logger) -> Self {
        self.logger = logger;
        self
    }

    /// Set a Protocol Buffer descriptor set (binary `FileDescriptorSet`).
    ///
    /// The bytes are stored and parsed eagerly when this method is called,
    /// so bad input is rejected immediately.
    pub fn with_proto_descriptor(mut self, bytes: Vec<u8>) -> Result<Self, anyhow::Error> {
        // Validate eagerly by attempting to parse.
        ProtoSchema::from_descriptor_set(&bytes)?;
        self.proto_descriptor = Some(bytes);
        Ok(self)
    }

    /// Set the container (namespace) used for CEL type-name resolution.
    pub fn with_container(mut self, container: impl Into<String>) -> Self {
        self.container = Some(container.into());
        self
    }

    /// Append one extension function declaration.
    ///
    /// May be called multiple times to register several extensions.
    ///
    /// See the [Host Extensions](https://flavio.github.io/ferricel/host-extensions.html#flat-extensions)
    /// user guide for details.
    pub fn with_extension(mut self, decl: ExtensionDecl) -> Self {
        self.extensions.insert(decl);
        self
    }

    /// Register a fluent builder chain extension family (e.g. `kw.k8s`, `kw.sigstore`).
    ///
    /// May be called multiple times to register several chains.
    ///
    /// See the [Builder Chains](https://flavio.github.io/ferricel/host-extensions.html#builder-chains)
    /// user guide for details on step types, multi-arg steps, and disambiguation.
    pub fn with_builder_chain(mut self, decl: BuilderChainDecl) -> Self {
        self.builder_chains.push(decl);
        self
    }

    /// Consume the builder and produce an immutable [`Compiler`].
    ///
    /// This is infallible — all fallible work (descriptor parsing) is done in
    /// [`with_proto_descriptor`](Self::with_proto_descriptor).
    pub fn build(self) -> Compiler {
        // Parse the schema; we already validated it above, so unwrap is safe.
        let schema = self.proto_descriptor.as_ref().map(|b| {
            ProtoSchema::from_descriptor_set(b).expect("proto descriptor already validated")
        });

        Compiler {
            schema,
            container: self.container,
            logger: self.logger,
            extensions: self.extensions,
            builder_chains: self.builder_chains,
        }
    }
}

impl Default for Builder {
    fn default() -> Self {
        Self::new()
    }
}

/// An immutable CEL-to-Wasm compiler.
///
/// Construct via [`Builder`].  The parsed `ProtoSchema` (if any) is
/// ready at construction time and reused across every call to [`compile`](Self::compile).
pub struct Compiler {
    schema: Option<ProtoSchema>,
    container: Option<String>,
    logger: slog::Logger,
    extensions: BTreeSet<ExtensionDecl>,
    builder_chains: Vec<BuilderChainDecl>,
}

impl Compiler {
    /// Compile a CEL expression into a WebAssembly module.
    ///
    /// Returns the compiled Wasm module as bytes.
    /// The resulting module exports two functions:
    ///
    /// - `evaluate(i64) -> i64`:       takes JSON-encoded bindings, returns JSON-encoded result
    /// - `evaluate_proto(i64) -> i64`: takes protobuf-encoded `ferricel.Bindings`, returns JSON-encoded result
    ///
    /// Both functions return a packed ptr+len i64 on success.  If the CEL expression
    /// produces a runtime error (overflow, divide-by-zero, etc.) the Wasm traps via
    /// `cel_abort`, and the host receives `Err(...)` from the call.
    ///
    /// The i64 packs ptr (low 32 bits) and len (high 32 bits) into a single value.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ferricel_core::compiler::Builder;
    ///
    /// let compiler = Builder::new().build();
    /// let wasm_bytes = compiler.compile("1 + 1").unwrap();
    /// ```
    pub fn compile(&self, cel_code: &str) -> Result<Vec<u8>, anyhow::Error> {
        // 1. Load the runtime template from embedded bytes
        let mut module = ModuleConfig::new().parse(RUNTIME_BYTES)?;

        // 2. Set up the compiler environment and manage exports
        let mut functions = HashMap::new();

        for func in RuntimeFunction::iter() {
            let id = module.exports.get_func(func.name()).with_context(|| {
                format!(
                    "Runtime function '{}' not found in module exports",
                    func.name()
                )
            })?;

            functions.insert(func, id);

            // If it shouldn't be exported, remove it
            if !func.is_exported() {
                module.exports.remove(func.name())?;
            }
        }

        let env = CompilerEnv { functions };

        // 3. Parse the CEL expression
        let root_ast = Parser::new()
            .enable_optional_syntax(true)
            .parse(cel_code)
            .map_err(|e| anyhow::anyhow!("Parse error: {:?}", e))?;

        let ctx = CompilerContext::new(
            self.schema.clone(),
            self.container.clone(),
            self.logger.clone(),
            &self.extensions,
            &self.builder_chains,
        );

        // 4. Build the 'evaluate' function (i64) -> (i32, i64) — JSON bindings path
        let evaluate_id = build_evaluate_function(&mut module, &env, &ctx, &root_ast.expr)?;
        module.exports.add("evaluate", evaluate_id);

        // 5. Build the 'evaluate_proto' function (i64) -> (i32, i64) — protobuf bindings path
        let evaluate_proto_id =
            build_evaluate_proto_function(&mut module, &env, &ctx, &root_ast.expr)?;
        module.exports.add("evaluate_proto", evaluate_proto_id);

        // 6. Run garbage collection to remove unreferenced items (dead code elimination)
        walrus::passes::gc::run(&mut module);

        // 7. Populate the producers custom section
        add_producers_entries(&mut module);

        // 8. Embed the original CEL source for tooling and debugging
        module.customs.add(walrus::RawCustomSection {
            name: "ferricel.cel-source".to_string(),
            data: cel_code.as_bytes().to_vec(),
        });

        // 9. Embed the set of host extensions used by this module.
        let used: Vec<UsedExtension> = ctx.used_extensions.borrow().iter().cloned().collect();
        module.customs.add(walrus::RawCustomSection {
            name: "ferricel.extensions".to_string(),
            data: serde_json::to_vec(&used).context("Failed to serialize used extensions")?,
        });

        // 10. Emit the module as bytes
        Ok(module.emit_wasm())
    }

    /// Compile a Kubernetes `ValidatingAdmissionPolicy` from its YAML manifest
    /// into a self-contained WebAssembly module.
    ///
    /// The resulting module exports:
    ///
    /// - `evaluate(i64) -> i64` — JSON-encoded bindings input
    ///
    /// The result JSON is a [Kubewarden](https://kubewarden.io/)
    /// [`ValidationResponse`](https://docs.kubewarden.io/admission-controller/1.35/en/reference/spec/03-validating-policies.html#_the_validationresponse_object):
    ///
    /// Accepted response:
    /// ```json
    /// {"accepted": true}
    /// ```
    ///
    /// Rejected response:
    /// ```json
    /// {"accepted": false, "message": "...", "code": 422}
    /// ```
    ///
    /// The YAML must contain exactly one `ValidatingAdmissionPolicy` document.
    /// The caller must pass, at minimum, `object` in the bindings. When the
    /// policy references `namespaceObject` or `params`, the host must also
    /// register `kubernetes.get` / `kubernetes.list` extension implementations
    /// on the `Engine`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ferricel_core::compiler::Builder;
    ///
    /// let yaml = std::fs::read_to_string("policy.yaml").unwrap();
    /// let compiler = Builder::new().build();
    /// let wasm_bytes = compiler.compile_vap(&yaml).unwrap();
    /// ```
    #[cfg(feature = "k8s-vap")]
    #[cfg_attr(docsrs, doc(cfg(feature = "k8s-vap")))]
    pub fn compile_vap(&self, vap_yaml: &str) -> Result<Vec<u8>, anyhow::Error> {
        let policy = parse_vap_yaml(vap_yaml)?;
        self.compile_vap_from_policy(&policy)
    }

    /// Compile a `ValidatingAdmissionPolicy` directly (bypassing YAML parsing).
    ///
    /// Useful when the caller has already parsed or constructed the policy
    /// programmatically from a `k8s_openapi::api::admissionregistration::v1::ValidatingAdmissionPolicy`.
    ///
    /// The full policy is serialized back to YAML and embedded as a
    /// `ferricel.vap-source` custom section for tooling and debugging.
    #[cfg(feature = "k8s-vap")]
    #[cfg_attr(docsrs, doc(cfg(feature = "k8s-vap")))]
    pub fn compile_vap_from_policy(
        &self,
        policy: &k8s_openapi::api::admissionregistration::v1::ValidatingAdmissionPolicy,
    ) -> Result<Vec<u8>, anyhow::Error> {
        Ok(self.build_vap_module(policy)?.emit_wasm())
    }

    /// Internal helper: compile a VAP policy into a walrus [`Module`] and embed
    /// the full policy serialized as YAML in the `ferricel.vap-source` custom section.
    #[cfg(feature = "k8s-vap")]
    fn build_vap_module(
        &self,
        policy: &k8s_openapi::api::admissionregistration::v1::ValidatingAdmissionPolicy,
    ) -> Result<walrus::Module, anyhow::Error> {
        let spec = policy
            .spec
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("ValidatingAdmissionPolicy has no spec"))?;

        if spec.validations.as_deref().unwrap_or(&[]).is_empty() {
            anyhow::bail!("ValidatingAdmissionPolicy must have at least one validation");
        }

        let extensions = self.extensions.clone();

        // Merge user-supplied builder chains with the implicit kw.k8s chain.
        let mut builder_chains = self.builder_chains.clone();
        builder_chains.push(vap::kw_k8s_chain());

        // Load runtime template
        let mut module = ModuleConfig::new().parse(RUNTIME_BYTES)?;

        // Build CompilerEnv
        let mut functions = HashMap::new();
        for func in RuntimeFunction::iter() {
            let id = module.exports.get_func(func.name()).with_context(|| {
                format!(
                    "Runtime function '{}' not found in module exports",
                    func.name()
                )
            })?;
            functions.insert(func, id);
            if !func.is_exported() {
                module.exports.remove(func.name())?;
            }
        }
        let env = CompilerEnv { functions };

        let ctx = CompilerContext::new(
            self.schema.clone(),
            self.container.clone(),
            self.logger.clone(),
            &extensions,
            &builder_chains,
        );

        // Build `evaluate` (JSON bindings)
        let evaluate_id = vap::build_vap_evaluate_function(&mut module, &env, &ctx, spec)?;
        module.exports.add("evaluate", evaluate_id);

        // If the policy uses paramKind, the compiler emits a hardcoded kw.k8s.get
        // call that doesn't go through the normal extension-call instrumentation.
        // Record it explicitly here.
        if spec.param_kind.is_some() {
            ctx.record_extension(Some("kw.k8s"), "get");
        }

        walrus::passes::gc::run(&mut module);
        add_producers_entries(&mut module);

        // Embed the full policy serialized as YAML for tooling and debugging.
        let vap_yaml = yaml_serde::to_string(policy)
            .context("Failed to serialize ValidatingAdmissionPolicy to YAML")?;
        module.customs.add(walrus::RawCustomSection {
            name: "ferricel.vap-source".to_string(),
            data: vap_yaml.into_bytes(),
        });

        // Embed the set of host extensions used by this module.
        let used: Vec<UsedExtension> = ctx.used_extensions.borrow().iter().cloned().collect();
        module.customs.add(walrus::RawCustomSection {
            name: "ferricel.extensions".to_string(),
            data: serde_json::to_vec(&used).context("Failed to serialize used extensions")?,
        });

        Ok(module)
    }
}

/// Populate the standardised WebAssembly `producers` section.
///
/// Entries are **added to** (not replaced) whatever the embedded `runtime.wasm`
/// template already recorded (typically `rustc` / `LLVM` entries from the Rust
/// toolchain).  This follows the tool-conventions spec, which explicitly states
/// that "it is possible (and common) for multiple tools to be used in the
/// overall pipeline that produces and optimizes a given wasm module".
///
/// Adds:
/// - `language`:     `"CEL"` (empty version — CEL has no distinct release cycle
///   separate from this compiler)
/// - `processed-by`: `"ferricel"` with the crate version from `CARGO_PKG_VERSION`
fn add_producers_entries(module: &mut walrus::Module) {
    module.producers.add_language("CEL", "");
    module
        .producers
        .add_processed_by("ferricel", env!("CARGO_PKG_VERSION"));
}

/// Read the list of host extensions used by a compiled Wasm module.
///
/// Parses the `ferricel.extensions` custom section embedded by the compiler and
/// returns the recorded set of [`UsedExtension`] entries, sorted by
/// `(namespace, function)`.
///
/// Returns an empty `Vec` if the section is absent (e.g. for modules compiled
/// without any host extensions, or by an older version of ferricel).
///
/// # Errors
///
/// Returns an error if `wasm` is not a valid WebAssembly module, or if the
/// `ferricel.extensions` section cannot be deserialized.
///
/// # Example
///
/// ```no_run
/// use ferricel_core::extensions_used;
///
/// let wasm = std::fs::read("policy.wasm").unwrap();
/// let used = extensions_used(&wasm).unwrap();
/// for ext in &used {
///     println!("{}/{}", ext.namespace.as_deref().unwrap_or("(none)"), ext.function);
/// }
/// ```
pub fn extensions_used(wasm: &[u8]) -> Result<Vec<UsedExtension>, anyhow::Error> {
    Ok(crate::inspect(wasm)?.extensions)
}

/// Build the `evaluate` Wasm function `(i64) -> i64` using JSON-encoded bindings.
///
/// Deserializes bindings with [`RuntimeFunction::DeserializeJson`], evaluates the expression,
/// and serializes the result via [`RuntimeFunction::SerializeResult`].  If the result is a
/// `CelValue::Error`, `SerializeResult` calls `cel_abort` which traps the Wasm instance,
/// propagating the error as `Err(...)` on the host side.
fn build_evaluate_function(
    module: &mut walrus::Module,
    env: &CompilerEnv,
    ctx: &CompilerContext,
    expr: &Expr,
) -> Result<FunctionId, anyhow::Error> {
    let mut func = FunctionBuilder::new(&mut module.types, &[ValType::I64], &[ValType::I64]);
    let bindings_encoded_arg = module.locals.add(ValType::I64);
    let mut body = func.func_body();

    body.local_get(bindings_encoded_arg)
        .call(env.get(RuntimeFunction::DeserializeJson))
        .call(env.get(RuntimeFunction::InitBindings));

    expr::compile_expr(expr, &mut body, env, ctx, module)?;

    body.call(env.get(RuntimeFunction::SerializeResult));

    Ok(func.finish(vec![bindings_encoded_arg], &mut module.funcs))
}

/// Build the `evaluate_proto` Wasm function `(i64) -> i64` using protobuf-encoded bindings.
///
/// Deserializes bindings with [`RuntimeFunction::DeserializeProto`], evaluates the expression,
/// and serializes the result via [`RuntimeFunction::SerializeResult`].  If the result is a
/// `CelValue::Error`, `SerializeResult` calls `cel_abort` which traps the Wasm instance,
/// propagating the error as `Err(...)` on the host side.
fn build_evaluate_proto_function(
    module: &mut walrus::Module,
    env: &CompilerEnv,
    ctx: &CompilerContext,
    expr: &Expr,
) -> Result<FunctionId, anyhow::Error> {
    let mut func = FunctionBuilder::new(&mut module.types, &[ValType::I64], &[ValType::I64]);
    let bindings_encoded_arg = module.locals.add(ValType::I64);
    let mut body = func.func_body();

    body.local_get(bindings_encoded_arg)
        .call(env.get(RuntimeFunction::DeserializeProto))
        .call(env.get(RuntimeFunction::InitBindings));

    expr::compile_expr(expr, &mut body, env, ctx, module)?;

    body.call(env.get(RuntimeFunction::SerializeResult));

    Ok(func.finish(vec![bindings_encoded_arg], &mut module.funcs))
}

// ─── VAP YAML parsing ─────────────────────────────────────────────────────────

/// Parse a `ValidatingAdmissionPolicy` YAML string.
///
/// The YAML must contain exactly one `ValidatingAdmissionPolicy` document; an
/// error is returned if zero or more than one document is found.
#[cfg(feature = "k8s-vap")]
pub(crate) fn parse_vap_yaml(
    yaml: &str,
) -> Result<k8s_openapi::api::admissionregistration::v1::ValidatingAdmissionPolicy, anyhow::Error> {
    use k8s_openapi::api::admissionregistration::v1::ValidatingAdmissionPolicy;
    use serde::Deserialize as _;

    let mut iter = yaml_serde::Deserializer::from_str(yaml);

    // Deserialize the first document.
    let first = iter
        .next()
        .ok_or_else(|| anyhow::anyhow!("YAML is empty, expected a ValidatingAdmissionPolicy"))?;
    let policy = ValidatingAdmissionPolicy::deserialize(first)
        .map_err(|e| anyhow::anyhow!("Failed to parse ValidatingAdmissionPolicy YAML: {}", e))?;

    // Reject multi-document YAML files.
    if iter.next().is_some() {
        anyhow::bail!(
            "Expected exactly one ValidatingAdmissionPolicy document, but found more than one"
        );
    }

    Ok(policy)
}