Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .agents/wisdom/process.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Process Wisdom

## CodeRabbit review gate

- **Auto-review is disabled** in `.coderabbit.yaml` (`auto_review.enabled: false`) — must trigger manually with `@coderabbitai review`.
- After pushing new commits with reviewable code (TypeScript, tests, CI config), the review is stale — must re-trigger.
- Free tier has rate limits (35 min cooldown). After hitting the limit, sleep and retry.
- CodeRabbit finds things the pre-push self-review misses (security lens, async assertion gaps). Do not skip it.

## Pre-merge three-step gate

From `docs/engineering-workflow.md`:

1. **CI Status** — all checks green
2. **CodeRabbit** — SUCCESS + no actionable comments + review covers latest commit
3. **Agent judgment** — architecture, security, test coverage

Do not merge until all three pass. Do not assume CodeRabbit auto-triggered — it didn't.

## Reverting a merge on a protected branch

- `develop` is protected — direct pushes are rejected.
- To undo a merge: create a revert branch, push, open a PR, merge that PR.
- Faster: just create a new PR with the fix rather than reverting and re-applying.

## Commit message format

```text
<issue-id>: <short description> (closes #<issue>)
```

Example: `24: first decision: trusted principal, memory facts, can, and decide (closes #24)`

For non-closing commits: `Refs #<issue>`
25 changes: 25 additions & 0 deletions .agents/wisdom/security.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Security Wisdom

## Duplicate source names silently override (🟠 Major)

`Map.set()` silently overwrites entries. If a denial source is registered then accidentally re-registered with a grant-only resolver, the denial disappears and authorization could flip to allow.

**Always**: Check for existing keys before registering. Throw on duplicates.

## Unavailable source must fail closed (🔴 Critical)

When a source returns `status: "unavailable"`, you cannot silently skip it — the unavailable source might contain a denial that overrides a grant from another source. Skipping it opens an allow path.

**Always**: Treat `"unavailable"` as a hard error — throw or return a structured denial. Never continue evaluation.

## Null outcome from resolver (🟠 Major)

A resolver can return `null` (or `undefined`) instead of a proper `SourceOutcome`. Accessing `.status` on null crashes with a cryptic `TypeError`, and if it somehow slips past, the authorization decision is undefined behavior.

**Always**: Validate the outcome object itself before accessing its properties. Throw a descriptive contract-violation error.

## Source should not expose decisions (💡 Design Principle)

The memory adapter returns `SourceOutcome` with facts only — no `decision` field. The core owns the decision. An adapter that smuggles a final allow/deny breaks the separation and can produce conflicting outcomes.

**Always**: Verify adapters return facts, not decisions. Test that `"decision" in outcome` is false.
33 changes: 33 additions & 0 deletions .agents/wisdom/testing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Testing Wisdom

## Await all async assertions (🟡 Minor / false-positive risk)

`expect(promise).rejects.toThrow(...)` returns a promise — if you don't `await` it, the test can finish before the assertion runs, producing false positives. This applies to both `.rejects` and `.resolves`.

**Always**:
```typescript
// ✅ Correct
await expect(auth.can("x")).rejects.toThrow(/error/i);
await expect(auth.can("x")).resolves.toBe(true);

// ❌ Wrong — test can pass even if assertion fails
expect(auth.can("x")).rejects.toThrow(/error/i);
```

## Test contract violations explicitly

When the spec says "malformed output is surfaced as a developer-facing error", test every malformation path:

- Unknown status
- Missing or non-array facts (empty array is valid — means no facts)
- Null/undefined outcome
- Non-array facts
- Invalid fact entries (missing permission, unknown effect)
Comment thread
coderabbitai[bot] marked this conversation as resolved.

## Test the complete end-to-end path

Don't stop at unit-testing the evaluator in isolation. Wire up the real adapter (`useMemoryAdapter`) and verify the full principal → adapter → core → decision flow. This catches integration bugs in source registration and fact collection.

## Denial-overrides-grant must be tested cross-source

Test that a denial from source B overrides a grant from source A, not just within the same source list. The cross-source case is the one that most easily regresses.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ dist/
*.log
.DS_Store
.pi-subagents/
.scratch/
251 changes: 251 additions & 0 deletions packages/core/__tests__/decision.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
import { describe, it, expect } from "bun:test";
import {
createMizan,
Mizan,
PrincipalEvaluator,
type SourceResolver,
type AuthorizationFact,
} from "../src/index.ts";

// ─── Helpers ───────────────────────────────────────────────────────────────

function sourceWith(...facts: AuthorizationFact[]): SourceResolver {
return {
async resolve() {
return { status: "facts", facts, freshness: "fresh" };
},
};
}

function emptySource(): SourceResolver {
return {
async resolve() {
return { status: "facts", facts: [], freshness: "fresh" };
},
};
}

// ─── PrincipalEvaluator: can() ─────────────────────────────────────────────

describe("PrincipalEvaluator.can()", () => {
it("returns true for exact matching grant", async () => {
const mizan = createMizan();
mizan.registerSource("mem", sourceWith({ permission: "files.read", effect: "grant" }));
const auth = mizan.forPrincipal("user-1");

expect(await auth.can("files.read")).toBe(true);
});

it("returns false for exact matching denial", async () => {
const mizan = createMizan();
mizan.registerSource("mem", sourceWith({ permission: "files.delete", effect: "deny" }));
const auth = mizan.forPrincipal("user-1");

expect(await auth.can("files.delete")).toBe(false);
});

it("returns false when no facts match (deny-by-default)", async () => {
const mizan = createMizan();
mizan.registerSource("mem", sourceWith({ permission: "files.read", effect: "grant" }));
const auth = mizan.forPrincipal("user-1");

expect(await auth.can("files.write")).toBe(false);
});

it("denial overrides grant for the same permission", async () => {
const mizan = createMizan();
mizan.registerSource(
"mem",
sourceWith(
{ permission: "files.read", effect: "grant" },
{ permission: "files.read", effect: "deny" },
),
);
const auth = mizan.forPrincipal("user-1");

// Denial should override grant
expect(await auth.can("files.read")).toBe(false);
});

it("does not affect unrelated permissions", async () => {
const mizan = createMizan();
mizan.registerSource(
"mem",
sourceWith(
{ permission: "files.read", effect: "grant" },
{ permission: "files.delete", effect: "deny" },
),
);
const auth = mizan.forPrincipal("user-1");

expect(await auth.can("files.read")).toBe(true);
expect(await auth.can("files.delete")).toBe(false);
expect(await auth.can("files.write")).toBe(false);
});

it("merges facts from multiple sources", async () => {
const mizan = createMizan();
mizan.registerSource("srcA", sourceWith({ permission: "files.read", effect: "grant" }));
mizan.registerSource("srcB", sourceWith({ permission: "files.write", effect: "grant" }));
const auth = mizan.forPrincipal("user-1");

expect(await auth.can("files.read")).toBe(true);
expect(await auth.can("files.write")).toBe(true);
});

it("denial overrides grant even across sources", async () => {
const mizan = createMizan();
mizan.registerSource("srcA", sourceWith({ permission: "files.read", effect: "grant" }));
mizan.registerSource("srcB", sourceWith({ permission: "files.read", effect: "deny" }));
const auth = mizan.forPrincipal("user-1");

// Denial from srcB overrides grant from srcA
expect(await auth.can("files.read")).toBe(false);
});

it("empty facts produce deny", async () => {
const mizan = createMizan();
mizan.registerSource("mem", emptySource());
const auth = mizan.forPrincipal("user-1");

expect(await auth.can("anything")).toBe(false);
});
});

// ─── PrincipalEvaluator: decide() ──────────────────────────────────────────

describe("PrincipalEvaluator.decide()", () => {
it("returns allow with null reason for a matching grant", async () => {
const mizan = createMizan();
mizan.registerSource("mem", sourceWith({ permission: "files.read", effect: "grant" }));
const auth = mizan.forPrincipal("user-1");

const result = await auth.decide("files.read");
expect(result.decision).toBe("allow");
expect(result.reason).toBeNull();
});

it("returns deny with matching-denial reason for a matching denial", async () => {
const mizan = createMizan();
mizan.registerSource("mem", sourceWith({ permission: "files.delete", effect: "deny" }));
const auth = mizan.forPrincipal("user-1");

const result = await auth.decide("files.delete");
expect(result.decision).toBe("deny");
expect(result.reason).toBe("matching-denial");
});

it("returns deny with no-grant reason when no facts match", async () => {
const mizan = createMizan();
mizan.registerSource("mem", sourceWith({ permission: "files.read", effect: "grant" }));
const auth = mizan.forPrincipal("user-1");

const result = await auth.decide("nonexistent");
expect(result.decision).toBe("deny");
expect(result.reason).toBe("no-grant");
});

it("returns deny with matching-denial when denial overrides grant", async () => {
const mizan = createMizan();
mizan.registerSource("mem", sourceWith({ permission: "files.read", effect: "grant" }, { permission: "files.read", effect: "deny" }));
const auth = mizan.forPrincipal("user-1");

const result = await auth.decide("files.read");
expect(result.decision).toBe("deny");
expect(result.reason).toBe("matching-denial");
});

it("does not throw for expected outcomes", async () => {
const mizan = createMizan();
mizan.registerSource("mem", emptySource());
const auth = mizan.forPrincipal("user-1");

await expect(auth.can("anything")).resolves.toBe(false);
await expect(auth.decide("anything")).resolves.toHaveProperty("decision", "deny");
});
});

// ─── Configuration errors ──────────────────────────────────────────────────

describe("Configuration errors", () => {
it("throws when no sources are registered and can is called", async () => {
const mizan = createMizan();
const auth = mizan.forPrincipal("user-1");

await expect(auth.can("anything")).rejects.toThrow(/no sources registered/i);
});

it("throws when a source resolves with malformed status", async () => {
const mizan = createMizan();
mizan.registerSource("bad", {
async resolve() {
// @ts-expect-error — intentionally malformed
return { status: "garbage", facts: [] };
},
});
const auth = mizan.forPrincipal("user-1");

await expect(auth.can("x")).rejects.toThrow(/contract violation/i);
});

it("throws when registering a duplicate source name", () => {
const mizan = createMizan();
const resolver: SourceResolver = emptySource();
mizan.registerSource("dup", resolver);

expect(() => mizan.registerSource("dup", resolver)).toThrow(
/already registered/i,
);
});

it("throws when a source resolves with null outcome", async () => {
const mizan = createMizan();
mizan.registerSource("bad", {
async resolve() {
// @ts-expect-error — intentionally null
return null;
},
});
const auth = mizan.forPrincipal("user-1");

await expect(auth.can("x")).rejects.toThrow(/contract violation/i);
});

it("throws when a source is unavailable", async () => {
const mizan = createMizan();
mizan.registerSource("unavail", {
async resolve() {
return { status: "unavailable", facts: [] };
},
});
const auth = mizan.forPrincipal("user-1");

await expect(auth.can("x")).rejects.toThrow(/unavailable/i);
});
});

// ─── Principal binding ─────────────────────────────────────────────────────

describe("forPrincipal()", () => {
it("returns a PrincipalEvaluator bound to the given principal", () => {
const mizan = createMizan();
const auth = mizan.forPrincipal("user-42");
expect(auth).toBeInstanceOf(PrincipalEvaluator);
});
});

// ─── Mizan class API ───────────────────────────────────────────────────────

describe("Mizan", () => {
it("registerSource stores a resolver", () => {
const mizan = createMizan();
const resolver: SourceResolver = emptySource();
mizan.registerSource("test", resolver);
// No throw means success
});

it("can be exported and instantiated", () => {
const mizan = new Mizan();
expect(mizan).toBeDefined();
});
});
Loading
Loading