tenuo 0.3.5

Task-scoped authorization for AI agents: signed warrants that constrain tools and arguments, narrow on delegation, and verify offline. Rust core of Tenuo.
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
//! CEL (Common Expression Language) evaluation for Tenuo constraints.
//!
//! This module provides cached CEL evaluation using the cel-interpreter crate.
//! CEL programs are compiled once and cached for performance.
//!
//! # Feature Flag
//!
//! This module requires the `cel` feature flag to be enabled:
//!
//! ```toml
//! tenuo = { version = "0.1", features = ["cel"] }
//! ```
//!
//! When disabled, CEL constraints can still be serialized/deserialized (for
//! interoperability), but evaluation will return an error.
//!
//! ## Security Properties
//!
//! The CEL cache is **security-neutral**:
//!
//! 1. **Immutable expressions**: Warrant expressions never change after creation.
//!    The cache key is the expression string itself.
//!
//! 2. **Compiled programs only**: We cache the compiled AST/bytecode, NOT
//!    evaluation results. Each execution evaluates against fresh context.
//!
//! 3. **Deterministic**: Same expression + same inputs = same result.
//!    Caching the program doesn't change behavior.
//!
//! 4. **Revocation independent**: Warrant revocation is checked at the warrant
//!    level before CEL evaluation. Cached programs don't bypass revocation.
//!
//! Therefore, long TTLs are safe. Memory is the only constraint (bounded by max_capacity).
//!
//! ## Standard Library Functions
//!
//! Tenuo provides several standard library functions for use in CEL expressions:
//!
//! ### Time Functions
//!
//! #### `time_now(_unused) -> String`
//!
//! Returns the current time in RFC3339 format (e.g., `"2024-01-15T10:30:00Z"`).
//!
//! **Example:**
//! ```cel
//! // Check if a timestamp is in the future
//! time_is_expired(deadline) == false && time_since(deadline) < 3600
//! ```
//!
//! #### `time_is_expired(timestamp: String) -> bool`
//!
//! Checks if an RFC3339 timestamp has passed.
//!
//! **Example:**
//! ```cel
//! // Only allow if not expired
//! !time_is_expired(order.expires_at)
//! ```
//!
//! #### `time_since(timestamp: String) -> i64`
//!
//! Returns the number of seconds since the given RFC3339 timestamp.
//! Returns `0` if the timestamp is invalid or in the future.
//!
//! **Example:**
//! ```cel
//! // Allow only if created within last hour
//! time_since(order.created_at) < 3600
//! ```
//!
//! ### Network Functions
//!
//! #### `net_in_cidr(ip: String, cidr: String) -> bool`
//!
//! Checks if an IP address (IPv4 or IPv6) is within a CIDR block.
//!
//! **Example:**
//! ```cel
//! // Only allow requests from internal network
//! net_in_cidr(request.ip, "10.0.0.0/8") || net_in_cidr(request.ip, "192.168.0.0/16")
//! ```
//!
//! #### `net_is_private(ip: String) -> bool`
//!
//! Checks if an IP address is in a private network range (RFC 1918 for IPv4,
//! or private IPv6 ranges).
//!
//! **Example:**
//! ```cel
//! // Block public IPs
//! net_is_private(request.ip)
//! ```
//!
//! ## Usage in Warrants
//!
//! These functions can be used in CEL constraints when creating warrants:
//!
//! ```rust,ignore
//! use tenuo::{Warrant, CelConstraint};
//!
//! let warrant = Warrant::builder()
//!     .capability("api_call")
//!     .constraint("ip", CelConstraint::new(
//!         "net_in_cidr(value, '10.0.0.0/8')"
//!     ))
//!     .constraint("deadline", CelConstraint::new(
//!         "!time_is_expired(value)"
//!     ))
//!     .build(&keypair)?;
//! ```

use crate::constraints::ConstraintValue;
use crate::error::{Error, Result};
use std::collections::HashMap;

// CEL implementation is only available with the "cel" feature
#[cfg(feature = "cel")]
use cel_interpreter::{Context, Program, Value};
#[cfg(feature = "cel")]
use chrono::{DateTime, Utc};
#[cfg(feature = "cel")]
use ipnetwork::IpNetwork;
#[cfg(all(feature = "cel", not(target_arch = "wasm32")))]
use moka::sync::Cache;
#[cfg(feature = "cel")]
use std::net::IpAddr;
#[cfg(feature = "cel")]
use std::panic::{catch_unwind, AssertUnwindSafe};
#[cfg(feature = "cel")]
use std::sync::Arc;

// ============================================================================
// CEL Feature: Full Implementation
// ============================================================================

/// Maximum number of compiled programs kept per process.
#[cfg(feature = "cel")]
const CEL_CACHE_CAPACITY: u64 = 1000;

#[cfg(all(feature = "cel", not(target_arch = "wasm32")))]
static CEL_CACHE: std::sync::LazyLock<Cache<String, Arc<Program>>> =
    std::sync::LazyLock::new(|| Cache::builder().max_capacity(CEL_CACHE_CAPACITY).build());

/// wasm32 has no monotonic clock, which moka's eviction needs, so the WASM
/// build keeps a plain bounded map instead. Same capacity; when full it is
/// cleared rather than evicted by recency, which is enough for the SDK.
#[cfg(all(feature = "cel", target_arch = "wasm32"))]
static CEL_CACHE: std::sync::LazyLock<std::sync::Mutex<HashMap<String, Arc<Program>>>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(HashMap::new()));

/// Compile a CEL expression, using cache if available.
///
/// # Feature Flag
///
/// Requires the `cel` feature. Without it, returns `CelError`.
#[cfg(all(feature = "cel", not(target_arch = "wasm32")))]
pub fn compile(expression: &str) -> Result<Arc<Program>> {
    if let Some(program) = CEL_CACHE.get(expression) {
        return Ok(program);
    }

    let program = Program::compile(expression)
        .map_err(|e| Error::CelError(format!("compilation failed: {}", e)))?;

    let program = Arc::new(program);
    CEL_CACHE.insert(expression.to_string(), program.clone());

    Ok(program)
}

/// Compile a CEL expression on wasm32, using the bounded map cache.
#[cfg(all(feature = "cel", target_arch = "wasm32"))]
pub fn compile(expression: &str) -> Result<Arc<Program>> {
    if let Ok(cache) = CEL_CACHE.lock() {
        if let Some(program) = cache.get(expression) {
            return Ok(program.clone());
        }
    }

    let program = Program::compile(expression)
        .map_err(|e| Error::CelError(format!("compilation failed: {}", e)))?;

    let program = Arc::new(program);
    if let Ok(mut cache) = CEL_CACHE.lock() {
        if cache.len() as u64 >= CEL_CACHE_CAPACITY {
            cache.clear();
        }
        cache.insert(expression.to_string(), program.clone());
    }

    Ok(program)
}

/// Compile a CEL expression (stub when `cel` feature is disabled).
#[cfg(not(feature = "cel"))]
pub fn compile(_expression: &str) -> Result<()> {
    Err(Error::FeatureNotEnabled { feature: "cel" })
}

/// Evaluate a CEL expression against a context built from constraint values.
///
/// The context contains:
/// - `value`: The primary value being checked
/// - Any additional variables passed in `vars`
///
/// # Feature Flag
///
/// Requires the `cel` feature. Without it, returns `CelError`.
#[cfg(feature = "cel")]
pub fn evaluate(
    expression: &str,
    value: &ConstraintValue,
    vars: &HashMap<String, ConstraintValue>,
) -> Result<bool> {
    let program = compile(expression)?;

    let mut context = create_context();

    context
        .add_variable("value", constraint_value_to_cel(value)?)
        .map_err(|e| Error::CelError(format!("failed to add variable: {}", e)))?;

    for (name, val) in vars {
        context
            .add_variable(name, constraint_value_to_cel(val)?)
            .map_err(|e| Error::CelError(format!("failed to add variable '{}': {}", name, e)))?;
    }

    let result = execute_program(&program, &context)?;

    match result {
        Value::Bool(b) => Ok(b),
        other => Err(Error::CelError(format!(
            "expression must return bool, got {:?}",
            other
        ))),
    }
}

/// Evaluate a CEL expression (stub when `cel` feature is disabled).
#[cfg(not(feature = "cel"))]
pub fn evaluate(
    _expression: &str,
    _value: &ConstraintValue,
    _vars: &HashMap<String, ConstraintValue>,
) -> Result<bool> {
    Err(Error::FeatureNotEnabled { feature: "cel" })
}

/// Evaluate a CEL expression with the value as the root context.
///
/// For object values, each field becomes a top-level variable, and the whole
/// object is available through the opt-in `tenuo_object()` function so
/// expressions can test optional fields with `has(tenuo_object().field)`.
/// Keeping the object out of `value` preserves existing list-only policies.
/// For other values, the value is available as `value`.
///
/// # Feature Flag
///
/// Requires the `cel` feature. Without it, returns `CelError`.
#[cfg(feature = "cel")]
pub fn evaluate_with_value_context(expression: &str, value: &ConstraintValue) -> Result<bool> {
    let program = compile(expression)?;

    let mut context = create_context();

    match value {
        ConstraintValue::Object(map) => {
            let object = constraint_value_to_cel(value)?;
            let object_function: Box<
                dyn Fn(&mut cel_interpreter::FunctionContext) -> cel_interpreter::ResolveResult
                    + Send
                    + Sync,
            > = Box::new(move |_| Ok(object.clone()));
            context.add_function("tenuo_object", object_function);
            for (key, val) in map {
                context
                    .add_variable(key, constraint_value_to_cel(val)?)
                    .map_err(|e| {
                        Error::CelError(format!("failed to add variable '{}': {}", key, e))
                    })?;
            }
        }
        other => {
            context
                .add_variable("value", constraint_value_to_cel(other)?)
                .map_err(|e| Error::CelError(format!("failed to add variable: {}", e)))?;
        }
    }

    let result = execute_program(&program, &context)?;

    match result {
        Value::Bool(b) => Ok(b),
        other => Err(Error::CelError(format!(
            "expression must return bool, got {:?}",
            other
        ))),
    }
}

/// Execute an untrusted CEL program without allowing interpreter panics to
/// cross the authorization boundary. A panic is a failed constraint, so the
/// caller's existing fail-closed error path can deny the request.
#[cfg(feature = "cel")]
fn execute_program(program: &Program, context: &Context) -> Result<Value> {
    catch_unwind(AssertUnwindSafe(|| program.execute(context)))
        .map_err(|_| Error::CelError("execution panicked".to_string()))?
        .map_err(|e| Error::CelError(format!("execution failed: {e}")))
}

/// Evaluate a CEL expression (stub when `cel` feature is disabled).
#[cfg(not(feature = "cel"))]
pub fn evaluate_with_value_context(_expression: &str, _value: &ConstraintValue) -> Result<bool> {
    Err(Error::FeatureNotEnabled { feature: "cel" })
}

/// Convert a ConstraintValue to a CEL Value.
#[cfg(feature = "cel")]
fn constraint_value_to_cel(cv: &ConstraintValue) -> Result<Value> {
    match cv {
        ConstraintValue::String(s) => Ok(Value::String(s.clone().into())),
        ConstraintValue::Integer(i) => Ok(Value::Int(*i)),
        ConstraintValue::Float(f) => Ok(Value::Float(*f)),
        ConstraintValue::Boolean(b) => Ok(Value::Bool(*b)),
        ConstraintValue::Null => Ok(Value::Null),
        ConstraintValue::List(list) => {
            let cel_list: std::result::Result<Vec<Value>, _> =
                list.iter().map(constraint_value_to_cel).collect();
            Ok(Value::List(cel_list?.into()))
        }
        ConstraintValue::Object(map) => {
            let cel_map: std::result::Result<HashMap<String, Value>, _> = map
                .iter()
                .map(|(k, v)| constraint_value_to_cel(v).map(|cv| (k.clone(), cv)))
                .collect();
            Ok(Value::Map(cel_map?.into()))
        }
    }
}

/// Clear the CEL program cache.
#[cfg(all(feature = "cel", not(target_arch = "wasm32")))]
pub fn clear_cache() {
    CEL_CACHE.invalidate_all();
}

/// Clear the CEL program cache (wasm32 bounded map).
#[cfg(all(feature = "cel", target_arch = "wasm32"))]
pub fn clear_cache() {
    if let Ok(mut cache) = CEL_CACHE.lock() {
        cache.clear();
    }
}

/// Clear the CEL program cache (no-op when `cel` feature is disabled).
#[cfg(not(feature = "cel"))]
pub fn clear_cache() {
    // No-op: CEL is disabled
}

/// Get the number of cached CEL programs.
#[cfg(all(feature = "cel", not(target_arch = "wasm32")))]
pub fn cache_size() -> u64 {
    CEL_CACHE.entry_count()
}

/// Get the number of cached CEL programs (wasm32 bounded map).
#[cfg(all(feature = "cel", target_arch = "wasm32"))]
pub fn cache_size() -> u64 {
    CEL_CACHE.lock().map(|c| c.len() as u64).unwrap_or(0)
}

/// Get the number of cached CEL programs (always 0 when `cel` feature is disabled).
#[cfg(not(feature = "cel"))]
pub fn cache_size() -> u64 {
    0
}

/// Create a CEL context with the standard library functions registered.
#[cfg(feature = "cel")]
pub fn create_context() -> Context<'static> {
    let mut context = Context::default();

    // Time Functions
    context.add_function("time_now", |_unused: Value| -> String {
        Utc::now().to_rfc3339()
    });

    context.add_function("time_is_expired", |timestamp: Value| -> bool {
        let ts_str = match timestamp {
            Value::String(s) => s,
            _ => return false,
        };
        match DateTime::parse_from_rfc3339(&ts_str) {
            Ok(dt) => dt < Utc::now(),
            Err(_) => false,
        }
    });

    context.add_function("time_since", |timestamp: Value| -> i64 {
        let ts_str = match timestamp {
            Value::String(s) => s,
            _ => return 0,
        };
        match DateTime::parse_from_rfc3339(&ts_str) {
            Ok(dt) => (Utc::now() - dt.with_timezone(&Utc)).num_seconds(),
            Err(_) => 0,
        }
    });

    // Network Functions
    context.add_function("net_in_cidr", |ip: Value, cidr: Value| -> bool {
        let ip_str = match ip {
            Value::String(s) => s,
            _ => return false,
        };
        let cidr_str = match cidr {
            Value::String(s) => s,
            _ => return false,
        };

        let ip_addr: IpAddr = match ip_str.parse() {
            Ok(addr) => addr,
            Err(_) => return false,
        };

        let network: IpNetwork = match cidr_str.parse() {
            Ok(net) => net,
            Err(_) => return false,
        };

        network.contains(ip_addr)
    });

    context.add_function("net_is_private", |ip: Value| -> bool {
        let ip_str = match ip {
            Value::String(s) => s,
            _ => return false,
        };

        let ip_addr: IpAddr = match ip_str.parse() {
            Ok(addr) => addr,
            Err(_) => return false,
        };

        match ip_addr {
            IpAddr::V4(addr) => addr.is_private(),
            IpAddr::V6(addr) => (addr.segments()[0] & 0xfe00) == 0xfc00,
        }
    });

    context
}

// ============================================================================
// Tests (only when CEL is enabled)
// ============================================================================

#[cfg(all(test, feature = "cel"))]
mod tests {
    use super::*;

    #[test]
    fn test_simple_comparison() {
        let value = ConstraintValue::Integer(5000);
        assert!(evaluate("value < 10000", &value, &HashMap::new()).unwrap());
        assert!(!evaluate("value > 10000", &value, &HashMap::new()).unwrap());
    }

    #[test]
    fn test_string_operations() {
        let value = ConstraintValue::String("staging-web".to_string());
        assert!(evaluate("value.startsWith('staging')", &value, &HashMap::new()).unwrap());
        assert!(!evaluate("value.startsWith('prod')", &value, &HashMap::new()).unwrap());
    }

    #[test]
    fn test_boolean_logic() {
        let value = ConstraintValue::Integer(7500);
        assert!(evaluate("value > 5000 && value < 10000", &value, &HashMap::new()).unwrap());
        assert!(evaluate("value < 1000 || value > 5000", &value, &HashMap::new()).unwrap());
    }

    #[test]
    fn test_list_operations() {
        let value = ConstraintValue::List(vec![
            ConstraintValue::String("admin".to_string()),
            ConstraintValue::String("user".to_string()),
        ]);
        assert!(evaluate("'admin' in value", &value, &HashMap::new()).unwrap());
        assert!(!evaluate("'superuser' in value", &value, &HashMap::new()).unwrap());
    }

    #[test]
    fn test_list_macros_fail_closed_on_non_lists() {
        let values = [
            ConstraintValue::String("admin".to_string()),
            ConstraintValue::Integer(5),
            ConstraintValue::Boolean(true),
            ConstraintValue::Object(std::collections::BTreeMap::from([
                ("admin".to_string(), ConstraintValue::Boolean(false)),
                (
                    "role".to_string(),
                    ConstraintValue::String("admin".to_string()),
                ),
            ])),
        ];

        for value in &values {
            let all = evaluate_with_value_context("value.all(item, item == 'admin')", value);
            assert!(all.is_err(), "all over {value:?} must fail closed: {all:?}");
            let exists = evaluate_with_value_context("value.exists(item, item == 'admin')", value);
            assert!(
                exists.is_err(),
                "exists over {value:?} must fail closed: {exists:?}"
            );
        }
    }

    #[test]
    fn test_interpreter_rejects_non_iterable_without_panicking() {
        for expression in [
            "value.all(item, item == 'admin')",
            "value.exists(item, item == 'admin')",
        ] {
            let program = Program::compile(expression).unwrap();
            let mut context = create_context();
            context.add_variable("value", "sensitive-value").unwrap();
            assert!(matches!(
                program.execute(&context),
                Err(cel_interpreter::ExecutionError::NoSuchOverload)
            ));
        }
    }

    #[test]
    fn test_list_macros_still_accept_lists() {
        let value = ConstraintValue::List(vec![
            ConstraintValue::String("admin".to_string()),
            ConstraintValue::String("admin".to_string()),
        ]);

        assert!(evaluate_with_value_context("value.all(item, item == 'admin')", &value).unwrap());
        assert!(
            evaluate_with_value_context("value.exists(item, item == 'admin')", &value).unwrap()
        );
    }

    #[test]
    fn test_evaluation_recovers_after_macro_error() {
        let scalar = ConstraintValue::String("admin".to_string());
        let list = ConstraintValue::List(vec![scalar.clone()]);
        let vars = HashMap::new();
        for expression in [
            "value.all(item, item == 'admin')",
            "value.exists(item, item == 'admin')",
        ] {
            assert!(evaluate(expression, &scalar, &vars).is_err());
            assert!(evaluate(expression, &list, &vars).unwrap());
            assert!(evaluate_with_value_context(expression, &scalar).is_err());
            assert!(evaluate_with_value_context(expression, &list).unwrap());
        }
        assert!(evaluate("size(value) < 3", &ConstraintValue::Integer(5), &vars).is_err());
        assert!(
            evaluate_with_value_context("size(value) < 3", &ConstraintValue::Integer(5)).is_err()
        );
    }

    #[test]
    fn test_object_context() {
        let value = ConstraintValue::Object(
            [
                ("amount".to_string(), ConstraintValue::Integer(5000)),
                (
                    "currency".to_string(),
                    ConstraintValue::String("USD".to_string()),
                ),
            ]
            .into_iter()
            .collect(),
        );

        assert!(evaluate_with_value_context("amount < 10000", &value).unwrap());
        assert!(evaluate_with_value_context("currency == 'USD'", &value).unwrap());
        assert!(
            evaluate_with_value_context("amount < 10000 && currency == 'USD'", &value).unwrap()
        );
    }

    #[test]
    fn test_object_context_exposes_optional_fields_opt_in() {
        let obj = |approve: Option<bool>| {
            let mut fields = vec![("amount".to_string(), ConstraintValue::Integer(3600))];
            if let Some(a) = approve {
                fields.push(("approve".to_string(), ConstraintValue::Boolean(a)));
            }
            ConstraintValue::Object(fields.into_iter().collect())
        };
        let expr =
            "amount <= 4000 && (!has(tenuo_object().approve) || tenuo_object().approve == false)";
        assert!(evaluate_with_value_context(expr, &obj(None)).unwrap());
        assert!(evaluate_with_value_context(expr, &obj(Some(false))).unwrap());
        assert!(!evaluate_with_value_context(expr, &obj(Some(true))).unwrap());
        // Fields stay available as top-level variables.
        assert!(
            evaluate_with_value_context("tenuo_object().amount == amount", &obj(None)).unwrap()
        );
    }

    #[test]
    fn test_tenuo_object_policy_fails_closed_without_function() {
        let program =
            Program::compile("!has(tenuo_object().approve) || tenuo_object().approve == false")
                .unwrap();
        let context = create_context();

        assert!(program.execute(&context).is_err());
    }

    #[test]
    fn test_object_field_named_value_keeps_legacy_precedence() {
        let value = ConstraintValue::Object(
            [
                ("value".to_string(), ConstraintValue::Integer(7)),
                ("approve".to_string(), ConstraintValue::Boolean(false)),
            ]
            .into_iter()
            .collect(),
        );
        assert!(evaluate_with_value_context(
            "value == 7 && approve == false && tenuo_object().approve == false",
            &value
        )
        .unwrap());
    }

    #[test]
    fn test_complex_expression() {
        let value = ConstraintValue::Object(
            [
                ("amount".to_string(), ConstraintValue::Integer(75000)),
                (
                    "approver".to_string(),
                    ConstraintValue::String("cfo@company.com".to_string()),
                ),
            ]
            .into_iter()
            .collect(),
        );

        // From spec: amount < 10000 || (amount < 100000 && approver != '')
        let expr = "amount < 10000 || (amount < 100000 && approver != '')";
        assert!(evaluate_with_value_context(expr, &value).unwrap());
    }

    #[test]
    fn test_cache_works() {
        clear_cache();
        // Note: moka cache is lazy, entry_count may not reflect immediately
        // So we just verify compilation caching works by checking the cache exists

        let value = ConstraintValue::Integer(42);

        // First evaluation compiles the expression
        evaluate("value == 42", &value, &HashMap::new()).unwrap();

        // Second evaluation should use cached program
        evaluate("value == 42", &value, &HashMap::new()).unwrap();

        // Different expression also works
        evaluate("value > 0", &value, &HashMap::new()).unwrap();

        // Verify compile function works directly and caches
        let p1 = compile("value == 100").unwrap();
        let p2 = compile("value == 100").unwrap();
        assert!(
            std::sync::Arc::ptr_eq(&p1, &p2),
            "same expression should return same Arc"
        );
    }

    #[test]
    fn test_invalid_expression() {
        let value = ConstraintValue::Integer(42);
        let result = evaluate("this is not valid CEL !!!", &value, &HashMap::new());
        assert!(result.is_err());
    }

    #[test]
    fn test_non_bool_result_error() {
        let value = ConstraintValue::Integer(42);
        let result = evaluate("value + 1", &value, &HashMap::new());
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("must return bool"));
    }
}