ContextExpr

Enum ContextExpr 

Source
pub enum ContextExpr {
    And(Box<ContextExpr>, Box<ContextExpr>),
    Or(Box<ContextExpr>, Box<ContextExpr>),
    Not(Box<ContextExpr>),
    HasAttribute(String),
    Compare {
        key: String,
        op: CompareOp,
        value: String,
    },
    True,
    False,
}
Expand description

Context expression for ABAC evaluation

This enum represents a boolean expression tree that can be evaluated against a context (attribute map) to determine if conditions are met.

§Design Rationale

  • Recursive Structure: Allows complex nested conditions
  • Type Safety: Rust’s type system prevents malformed expressions
  • Deterministic: No floating point, no random operations
  • Serializable: Can be stored in policy files (YAML/JSON)

§Example

extern crate alloc;
use core_policy::context_expr::{ContextExpr, CompareOp};
use alloc::collections::BTreeMap;
use alloc::string::ToString;

let expr = ContextExpr::And(
    Box::new(ContextExpr::Compare {
        key: "role".into(),
        op: CompareOp::Equal,
        value: "admin".into(),
    }),
    Box::new(ContextExpr::Compare {
        key: "department".into(),
        op: CompareOp::Equal,
        value: "IT".into(),
    }),
);

let mut context = BTreeMap::new();
context.insert("role".to_string(), "admin".to_string());
context.insert("department".to_string(), "IT".to_string());

assert!(expr.evaluate(&context, 0).unwrap());

Variants§

§

And(Box<ContextExpr>, Box<ContextExpr>)

Logical AND (both operands must be true)

§

Or(Box<ContextExpr>, Box<ContextExpr>)

Logical OR (at least one operand must be true)

§

Not(Box<ContextExpr>)

Logical NOT (negates the operand)

§

HasAttribute(String)

Check if an attribute exists in the context

§

Compare

Compare an attribute value with a constant

Fields

§key: String

Attribute key to compare

§op: CompareOp

Comparison operator

§value: String

Value to compare against (as string)

§

True

Always true (useful for testing and default cases)

§

False

Always false

Implementations§

Source§

impl ContextExpr

Source

pub fn evaluate( &self, context: &BTreeMap<String, String>, depth: usize, ) -> Result<bool>

Evaluate this expression against a context

§Arguments
  • context - Attribute map to evaluate against
  • depth - Current recursion depth (prevents stack overflow)
§Returns
  • Ok(true) - Expression evaluates to true
  • Ok(false) - Expression evaluates to false
  • Err(PolicyError::ExpressionTooDeep) - Recursion limit exceeded
§Example
extern crate alloc;
use core_policy::context_expr::{ContextExpr, CompareOp};
use alloc::collections::BTreeMap;
use alloc::string::ToString;

let expr = ContextExpr::Compare {
    key: "role".into(),
    op: CompareOp::Equal,
    value: "admin".into(),
};

let mut context = BTreeMap::new();
context.insert("role".to_string(), "admin".to_string());

assert!(expr.evaluate(&context, 0).unwrap());
Source

pub fn parse(input: &str) -> Result<Self>

Parse a context expression from a string

§Grammar (simplified)
expr       ::= or_expr
or_expr    ::= and_expr (OR and_expr)*
and_expr   ::= not_expr (AND not_expr)*
not_expr   ::= NOT primary | primary
primary    ::= HAS key | key op value | (expr) | TRUE | FALSE
op         ::= == | != | < | <= | > | >=
§Examples
use core_policy::context_expr::ContextExpr;

let expr = ContextExpr::parse("role == \"admin\"").unwrap();
let expr = ContextExpr::parse("role == \"admin\" AND department == \"IT\"").unwrap();
let expr = ContextExpr::parse("(role == \"admin\" OR role == \"moderator\") AND active == \"true\"").unwrap();
let expr = ContextExpr::parse("NOT (status == \"banned\")").unwrap();
let expr = ContextExpr::parse("HAS role").unwrap();
§Errors
  • PolicyError::InvalidExpression - Syntax error in expression
  • PolicyError::ExpressionTooLong - Expression exceeds MAX_EXPR_LENGTH

Trait Implementations§

Source§

impl Clone for ContextExpr

Source§

fn clone(&self) -> ContextExpr

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ContextExpr

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for ContextExpr

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for ContextExpr

Source§

fn eq(&self, other: &ContextExpr) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for ContextExpr

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for ContextExpr

Source§

impl StructuralPartialEq for ContextExpr

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,