Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript
3.7 KB
Raw Blame
/**
 * Short-TTL gfs authorization decision cache (spec community.md §gfs-controller
 * "permission resolution" / Governance controls "Immediate revocation").
 *
 * The cache retains the full attribution of the underlying authorization
 * decision. Serving a cache hit changes only `via` in PermissionClient; it must
 * never erase which subject and direct/inherited authority produced the allow.
 */

import type { Decision } from "./resolve";

export type CachedDecision = Decision;

/**
 * A snapshot of the invalidation state, carried from an authorization check into
 * the writer transaction so a copy can prove its grants were not revoked while
 * blobs were staged. `generation` bumps on every revocation NOTIFY (flushAll);
 * `bypassed` is true while the LISTEN is degraded and NOTIFYs are not processed.
 */
export interface PermissionEpoch {
  generation: number;
  bypassed: boolean;
}

export interface DecisionKey {
  /** Stable key for the caller's resolved subject set (e.g. sorted keys joined). */
  subjectsKey: string;
  resourceId: string;
  op: string;
}

interface Entry {
  decision: CachedDecision;
  expiresAtMs: number;
}

export interface DecisionCacheOptions {
  ttlMs: number;
  /** Injectable clock for deterministic tests; defaults to Date.now. */
  now?: () => number;
  /** Hard cap on entries to bound memory; oldest-inserted evicted first. */
  maxEntries?: number;
}

export class DecisionCache {
  private readonly store = new Map<string, Entry>();
  private readonly ttlMs: number;
  private readonly now: () => number;
  private readonly maxEntries: number;
  private bypassed = false;
  private generationCounter = 0;

  constructor(opts: DecisionCacheOptions) {
    if (!(opts.ttlMs > 0)) {
      throw new Error("DecisionCache: ttlMs must be > 0");
    }
    this.ttlMs = opts.ttlMs;
    this.now = opts.now ?? Date.now;
    this.maxEntries = opts.maxEntries ?? 10_000;
  }

  private keyOf(key: DecisionKey): string {
    return `${key.subjectsKey}\0${key.resourceId}\0${key.op}`;
  }

  /** Cached decision, or undefined on miss / expiry / bypass (caller re-checks). */
  get(key: DecisionKey): CachedDecision | undefined {
    if (this.bypassed) return undefined;
    const k = this.keyOf(key);
    const entry = this.store.get(k);
    if (!entry) return undefined;
    if (this.now() >= entry.expiresAtMs) {
      this.store.delete(k);
      return undefined;
    }
    return { ...entry.decision };
  }

  set(key: DecisionKey, decision: CachedDecision): void {
    if (this.bypassed) return;
    const k = this.keyOf(key);
    if (!this.store.has(k) && this.store.size >= this.maxEntries) {
      const oldest = this.store.keys().next().value;
      if (oldest !== undefined) this.store.delete(oldest);
    }
    this.store.set(k, { decision: { ...decision }, expiresAtMs: this.now() + this.ttlMs });
  }

  /**
   * Drop every entry — called on a NOTIFY so revocation is immediate. Each flush
   * bumps `generation` so an in-flight copy holding an earlier epoch detects that
   * a revocation landed after it authorized and fails closed.
   */
  flushAll(): void {
    this.store.clear();
    this.generationCounter += 1;
  }

  /**
   * Enter/leave fail-closed BYPASS. Entering clears the cache and stops it
   * serving/storing, so every op re-checks the store while invalidation is
   * degraded. Leaving (after a healthy re-LISTEN) re-enables caching.
   */
  setBypassed(bypassed: boolean): void {
    this.bypassed = bypassed;
    if (bypassed) this.store.clear();
  }

  get isBypassed(): boolean {
    return this.bypassed;
  }

  /** Monotonic revocation counter — one bump per flushAll (NOTIFY). */
  get generation(): number {
    return this.generationCounter;
  }

  get size(): number {
    return this.store.size;
  }
}