mooncedar

    A Cedar policy engine — parser, evaluator, and authorizer in MoonBit.

    Download zip
    Author
    Version
    0.1.1
    License
    Apache-2.0
    Last updated
    5 months ago
    Downloads
    96

    #MoonCedar

    A Cedar policy engine implemented in MoonBit — parser, evaluator, and authorizer.

    #Installation

    Add to your moon.mod:

    { "deps": { "jaredzhou/mooncedar": "0.1.0" } }

    #Quick Start

    // 1. Define a policy
    let policies = @parser.parse_policies(
    #|permit (principal == User::"alice", action == Action::"view", resource in Album::"jane_vacation");|
    )

    // 2. Build an entity store from JSON
    let entities = @json.parse(
    #|[{"uid":{"type":"User","id":"alice"},"attrs":{"role":["String","admin"]},"tags":{},"parents":[]},{"uid":{"type":"Photo","id":"VacationPhoto94.jpg"},"attrs":{},"tags":{},"parents":[{"type":"Album","id":"jane_vacation"}]}]
    )
    let store : @evaluator.MapEntityStore = @json.from_json(entities)

    // 3. Create a request
    let req = @evaluator.Request::{
    principal: @evaluator.concrete_uid("User", "alice"),
    action: @evaluator.concrete_uid("Action", "view"),
    resource: @evaluator.concrete_uid("Photo", "VacationPhoto94.jpg"),
    context: @evaluator.Context::Concrete(@ast.Value::Record(Map([]))),
    }

    // 4. Authorize
    let result = is_authorized(req, policies.iter(), store)
    match result.decision {
    Decision::Allow => println("permitted (\{result.determining_policies[0].policy_id})")
    Decision::Deny => println("denied")
    }
    // => permitted (policy0)

    #Packages

    PackageImportsPurpose
    jaredzhou/mooncedar@parser, @evaluator, @astTop-level: is_authorized, evaluate, reauthorize, concretize
    jaredzhou/mooncedar/ast—AST types: Expr, Policy, EntityUID, Value, Entity
    jaredzhou/mooncedar/parser@astLexer + recursive descent parser + stringify
    jaredzhou/mooncedar/evaluator@astExpression evaluator, scope matching, entity store trait

    #Features

    #Policy Language

    Full Cedar policy syntax support:

    • permit / forbid effects with annotations
    • Scope constraints (==, in, in [set], All)
    • when / unless conditions
    • Expression language: &&, ||, !, >, <, >=, <=, !=, like, in, contains, has, ., .tag
    • Records, sets, if-then-else, extension function calls

    #Expression Builder

    let e = @ast.Expr::var_principal()
    .eq(@ast.Expr::lit_str("alice"))
    .and(@ast.Expr::var_resource()
    .has_tag(@ast.Expr::lit_str("confidential"))
    )

    #Policy Builder

    let policy = @ast.Policy::permit()
    .principal_eq("User", "alice")
    .action_eq("Action", "view")
    .resource_in("Album", "photos")
    .when_(@ast.Expr::var_resource().has_tag(@ast.Expr::lit_str("public")))

    #Strategy Validation

    let errors = @ast.validate_policies(policies)

    #Entity Store (Pluggable)

    // In-memory store
    let store = @evaluator.new_map_store()

    // Custom backend via trait
    struct DbStore { conn : Connection }
    pub impl @evaluator.EntityStore for DbStore with get_entity(self, uid) {
    db_lookup(self.conn, uid)
    }

    Entity hierarchy: is_descendant uses BFS for ancestor traversal. Wildcard matching uses two-pointer backtracking.

    #Partial Evaluation

    Support for unknown PARC (principal, action, resource, context) slots — policies evaluate to residual expressions that can be re-evaluated when more information is available:

    let req = @evaluator.Request::{
    principal: @evaluator.EntityUIDEntry::Unknown(@ast.EntityType("User")),
    action: @evaluator.concrete_uid("Action", "view"),
    resource: @evaluator.concrete_uid("Photo", "x"),
    context: @evaluator.Context::Concrete(@ast.Value::Record(Map([]))),
    }

    let answer = evaluate(req, policies.iter(), store1) // partial result
    let answer = answer.reauthorize(req, store2, Map([])) // fill unknowns
    let result = answer.concretize() // final decision

    #JSON Serialization

    Entity stores and entity UIDs serialize to/from Cedar-compatible JSON format:

    let json_str = (#|[{"uid":{"type":"User","id":"alice"},"attrs":{},"tags":{},"parents":[]}]
    let store : @evaluator.MapEntityStore = @json.from_json(@json.parse(json_str))

    // Serialize back
    let json = store.to_json()
    println(json.stringify())

    #Stringify (AST -> Cedar Source)

    let src = @parser.stringify(policies)

    #Status

    • 546 tests passing (parser, evaluator, authorizer, JSON)
    • Entity stores as pluggable traits
    • JSON serialization (Cedar-compatible format)
    • Policy validation
    • Full expression evaluation (18 expression variants, 12 binary + 3 unary operators)

    #License

    Apache-2.0

    AuthorizationResult

    pub(all) struct AuthorizationResult {
    decision : Decision
    determining_policies : Array[DiagnosticReason]
    errors : Array[DiagnosticError]
    } derive(Eq,
    Debug
    )

    Full result of an authorization request.

    Decision

    pub(all) enum Decision {
    Allow
    Deny
    } derive(Eq,
    Debug
    )

    Authorization decision.

    DecisionRecord

    type DecisionRecord derive(Eq,
    Debug
    )

    Record of a single policy that fully satisfied (scope matched + all conditions passed).

    DiagnosticError

    pub(all) struct DiagnosticError {
    policy_id : String
    position :
    Position

    message : String
    } derive(Eq,
    Debug
    )

    Evaluation error for a specific policy.

    DiagnosticReason

    pub(all) struct DiagnosticReason {
    policy_id : String
    position :
    Position

    } derive(Eq,
    Debug
    )

    Diagnostic — identifying which policy caused a reason or error.

    PartialAuthorizationAnswer

    pub(all) struct PartialAuthorizationAnswer {
    satisfied : Array[DecisionRecord]
    residuals : Array[ResidualRecord]
    errors : Array[DiagnosticError]
    } derive(
    Debug
    )

    Rich result of evaluating all policies against a Request. Holds satisfied decisions, residuals, and errors separately so downstream can concretize / reauthorize / sqlize as needed.

    PartialAuthorizationAnswer::concretize

    Concretize a PartialAuthorizationAnswer into a binary AuthorizationResult. Permit + no satisfied Forbid → Allow; otherwise → Deny. Residual policies are treated as non-determining (they don't count toward Allow).

    PartialAuthorizationAnswer::reauthorize

    Re-evaluate residual policies from a previous round, with an expanded entity store and/or a mapping from unknown names to concrete values.

    The mapping parameter handles expression-level Unknown("x") nodes (e.g., context values that were unknown in the first pass but are now known). The store parameter provides expanded entity hierarchy (e.g., after entity slicing fetched missing entities).

    Satisfied policies from the prior round are carried forward unconditionally.

    ResidualRecord

    type ResidualRecord derive(Eq,
    Debug
    )

    Record of a single policy where some conditions were residual (partial eval).

    evaluate

    Evaluate all policies against a Request. Returns a rich PartialAuthorizationAnswer that preserves residuals and errors for downstream processing.

    is_authorized

    Evaluate policies and produce a binary authorization decision. Convenience that composes evaluate() + concretize().