This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: cedar-policy-slicing-evaluation-fence

Cedar Engine Compile-Time Policy Slicing and In-Memory Evaluation Fence

Enforces deterministic, sub-millisecond Cedar authorization decisions by mandating static compile-time policy slicing and a strict zero-network evaluation fence. Prohibits in-band network fetches, uncompiled schema validations, and dynamic policy discovery within the critical evaluation loop.

Prohibited Anti-Pattern: In-Band Remote Policy Retrieval and Dynamic Attribute Hydration During Authorization Evaluation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Cedar Engine Compile-Time Policy Slicing and In-Memory Evaluation Fence - Enforces deterministic, sub-millisecond Cedar authorization decisions by mandating static compile-time policy slicing and a strict zero-network evaluation fence. Prohibits in-band network fetches, uncompiled schema validations, and dynamic policy discovery within the critical evaluation loop.
globs: src/**/auth/**/*.{ts,tsx,rs,go}, src/**/policy/**/*.{ts,tsx,rs,go}, src/**/security/**/*.{ts,tsx,rs,go}, src/**/middleware/**/*.{ts,tsx,rs,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/cedar-policy-slicing-evaluation-fence"
---

# Cedar Engine Compile-Time Policy Slicing and In-Memory Evaluation Fence

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: In-Band Remote Policy Retrieval and Dynamic Attribute Hydration During Authorization Evaluation

## System Constraints
You are a Principal Security Architect enforcing the Cedar Engine Compile-Time Policy Slicing and Real-Time Evaluation Fence standard. You must prevent dynamic network-dependent authorization calls, uncompiled Cedar policy evaluations, and incomplete entity store hydration on hot paths. Mandate that every authorization check evaluates against an immutable, statically validated, pre-sliced local policy set with all entity attributes deterministically hydrated prior to crossing the evaluation fence.

## Strict Guidelines
- Engineers MUST ALWAYS pre-compile and statically validate Cedar schemas and policy sets ahead-of-time (AOT) or during immutable container initialization.
- Engineers MUST NEVER execute network I/O, database queries, or remote RPC lookups within the Cedar evaluation fence or inside dynamic evaluation callbacks.
- Services MUST extract a minimal, provably sound policy slice for the target service boundary at build or deployment time rather than evaluating against a monolithic global policy repository.
- Code MUST construct a complete, bounded Cedar Entity Store in memory before invoking `isAuthorized`, validating that all referenced principal, action, resource, and context relationships are fully resolved.
- Evaluation engines MUST enforce a strict sub-millisecond execution deadline and immediately fail-closed (DENY) upon encountering syntax errors, evaluation timeouts, or missing required attributes.

## Bad vs Good Implementations
### Cedar Policy Evaluation Fence vs. In-Band Network Hydration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fetches raw policies dynamically over HTTP on the request path, recompiles policies inside the evaluation handler, and mixes database I/O into authorization logic, violating sub-millisecond and zero-network-dependency invariants.
```typescript
import { CedarEngine, RequestContext } from '@cedar-policy/cedar-wasm';
import { fetchRemotePolicies, fetchUserRolesFromDB } from './services/remoteAuth';

export async function authorizeRequest(userId: string, actionId: string, resourceId: string): Promise<boolean> {
  // ANTI-PATTERN: Dynamically fetching policies over the network per-request
  const rawPolicies = await fetchRemotePolicies('service-orders');
  
  // ANTI-PATTERN: Dynamic schema validation and compilation on the hot path
  const engine = new CedarEngine();
  engine.loadPolicies(rawPolicies);

  // ANTI-PATTERN: Leaking network I/O into the evaluation boundary
  const roles = await fetchUserRolesFromDB(userId);
  
  const response = await engine.isAuthorized({
    principal: `User::"${userId}"`,
    action: `Action::"${actionId}"`,
    resource: `Order::"${resourceId}"`,
    context: { roles }
  });

  return response.decision === 'Allow';
}
```

#### Production Standard (Correct)
> **Standard**: Uses an immutable, pre-compiled policy slice loaded at bootstrap. Entities are fully hydrated into memory before the evaluation fence is invoked. Guarantees deterministic, sub-millisecond execution with fail-closed semantics.
```typescript
import { CedarEvaluationFence, PrecompiledPolicySlice, EntityStore, AuthorizationDecision } from '@company/security-cedar';

// Compile-time statically verified and sliced policy set loaded at cold start
declare const ORDER_SERVICE_POLICY_SLICE: PrecompiledPolicySlice;
const fence = new CedarEvaluationFence(ORDER_SERVICE_POLICY_SLICE);

export interface AuthContext {
  readonly principalId: string;
  readonly actionId: string;
  readonly resourceId: string;
  readonly prehydratedEntities: EntityStore;
}

export function authorizeRequest(ctx: AuthContext): boolean {
  // INVARIANT: Pre-resolved entity store; zero network calls inside the evaluation fence
  const result = fence.evaluateStrict({
    principal: { type: 'User', id: ctx.principalId },
    action: { type: 'Action', id: ctx.actionId },
    resource: { type: 'Order', id: ctx.resourceId },
    entities: ctx.prehydratedEntities,
    timeoutMicros: 800 // Hard boundary: 0.8ms ceiling
  });

  if (result.type === 'EvaluationError' || result.decision !== AuthorizationDecision.Allow) {
    // Fail-closed invariant
    return false;
  }

  return true;
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Cedar Engine Compile-Time Policy Slicing and In-Memory Evaluation Fence

Cedar Engine Compile-Time Policy Slicing and In-Memory Evaluation Fence defines an industrial-grade behavioral standard for security engineering. Enforces deterministic, sub-millisecond Cedar authorization decisions by mandating static compile-time policy slicing and a strict zero-network evaluation fence. Prohibits in-band network fetches, uncompiled schema validations, and dynamic policy discovery within the critical evaluation loop. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: In-Band Remote Policy Retrieval and Dynamic Attribute Hydration During Authorization Evaluation Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftIn-Band Remote Policy Retrieval and Dynamic Attribute Hydration During Authorization EvaluationCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS pre-compile and statically validate Cedar schemas and policy sets ahead-of-time (AOT) or during immutable container initialization.

Engineers MUST ALWAYS pre-compile and statically validate Cedar schemas and policy sets ahead-of-time (AOT) or during immutable container initialization.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NEVER execute network I/O, database queries, or remote RPC lookups within the Cedar evaluation fence or inside dynamic evaluation callbacks.

Engineers MUST NEVER execute network I/O, database queries, or remote RPC lookups within the Cedar evaluation fence or inside dynamic evaluation callbacks.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Services MUST extract a minimal, provably sound policy slice for the target service boundary at build or deployment time rather than evaluating against a monolithic global policy repository.

Services MUST extract a minimal, provably sound policy slice for the target service boundary at build or deployment time rather than evaluating against a monolithic global policy repository.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code MUST construct a complete, bounded Cedar Entity Store in memory before invoking `isAuthorized`, validating that all referenced principal, action, resource, and context relationships are fully resolved.

Code MUST construct a complete, bounded Cedar Entity Store in memory before invoking `isAuthorized`, validating that all referenced principal, action, resource, and context relationships are fully resolved.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Evaluation engines MUST enforce a strict sub-millisecond execution deadline and immediately fail-closed (DENY) upon encountering syntax errors, evaluation timeouts, or missing required attributes.

Evaluation engines MUST enforce a strict sub-millisecond execution deadline and immediately fail-closed (DENY) upon encountering syntax errors, evaluation timeouts, or missing required attributes.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Cedar Engine Compile-Time Policy Slicing and In-Memory Evaluation Fence critical for AI coding assistants?

Enforces deterministic, sub-millisecond Cedar authorization decisions by mandating static compile-time policy slicing and a strict zero-network evaluation fence. Prohibits in-band network fetches, uncompiled schema validations, and dynamic policy discovery within the critical evaluation loop. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (In-Band Remote Policy Retrieval and Dynamic Attribute Hydration During Authorization Evaluation) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Cedar