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
58 changes: 58 additions & 0 deletions lexicons/cedar/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ INTENTIUS/chant#1645: the upstream pin (#1648), the scaffold and serializer
import/reconcile (#1653), the docs/LSP/MCP/skills/composites surface (#1654),
and CI/publishing onboarding (#1655).

Landing beside it, and pre-release on its own terms, is the dogwood temporal
dialect (epic #1646) — see [The dogwood dialect](#the-dogwood-dialect-pre-release).
It is a surface *inside* this lexicon rather than a sibling, so the eight
sub-issues above are still the whole of Cedar itself.

## The policy model

A policy is a `Cedar::Policy` entity whose props are:
Expand Down Expand Up @@ -159,6 +164,57 @@ policy. AVP policy stores are taggable and individual policies are not, so
chant's per-policy ownership marker rides in the policy description — the
design record is `src/avp/OWNERSHIP.md`.

## The dogwood dialect (pre-release)

[Dogwood](https://github.com/dogwood-policy/dogwood) is Cedar with temporal
operators: a policy can depend on what already happened in a session, so
approval-before-action, rate limits and budgets become policy rather than
application code. It ships here as a dialect rather than as a sibling lexicon —
a `.dw` file stripped of Cedar semantics is meaningless, and the head of a
`.dw` policy is Cedar's, byte for byte. Its checks are under the `DWD` id
family, declared on the serializer's `extraRulePrefixes`.

```ts
import { TemporalPolicy, TemporalEventSchema, dogwood } from "@intentius/chant-lexicon-cedar";

export const events = new TemporalEventSchema({ schema: dogwood.defaultEventSchema() });

export const readAfterLogin = new TemporalPolicy({
action: { eq: 'Drupe::Action::"Read"' },
whenTemporal: [
dogwood.formerly("1h", dogwood.predicate('Drupe::Action::"Login"', "response", {
"input.user": dogwood.ctx("input.user"),
})),
],
});
```

A build holding temporal policies emits `policies.dw` beside the `.cedar`
outputs, plus `events.dwschema` and `macros.dw` where those are declared.

The builders target dogwood's **parser primitives** — `formerly`, `previous`,
`since`, `exists`, `tp()`, `count for … where`, `sum … for … where` — because
those are the only temporal keywords in the grammar. `count_within`,
`sum_within` and `count_distinct_within` are macros in a default library that
a caller passing `--macros` replaces wholesale, so they are expressible as
calls (`dogwood.countWithin`) and never as operators. `dogwood.defaultMacroLibrary()`
emits the same definitions into a project's own file for anyone who would
rather not depend on the far end's.

Three walls run in the build with no dogwood binary anywhere: a temporal
predicate naming an event kind the emitted `.dwschema` never declares
(DWDC010), a window past the schema's `max_window` or upstream's 24h default
(DWDC011), and a `formerly`/`previous`/`since` with no window (DWDC012, which
the typed builders already make unrepresentable). DWDS010 reports an event
schema that pins nothing — supplying any schema opts out of upstream's
`callerPrincipal` pin, which widens every temporal predicate to cross-principal.

Pre-release. Upstream is a read-only squash-sync mirror of an internal Amazon
repository with no tags, no releases and no stability statement, and its README
says it is not intended for production use. The revision this is built against
is recorded in `src/dogwood/upstream.ts`; full `.dw` validation shells to the
`dogwood` binary and is deliberately not part of any gating check.

## Commands

```bash
Expand All @@ -175,7 +231,9 @@ npm run docs:build # build the Starlight site in docs/

- `src/plugin.ts` — LexiconPlugin with all lifecycle methods
- `src/serializer.ts` — `.cedar` text and JSON policy-set output
- `src/policy-text.ts` — policy-head rendering shared by every renderer
- `src/avp/` — AVP embedding, the policy-store readers, and the ownership channel
- `src/dogwood/` — the temporal dialect: builders, `.dw`/`.dwschema` output
- `src/import/` — `chant import` parser, generator and round-trip fixtures
- `src/detect.ts` — which documents belong to this lexicon
- `src/codegen/` — code generation, docs, and packaging pipelines
Expand Down
218 changes: 218 additions & 0 deletions lexicons/cedar/src/dogwood/event-schema.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
/**
* Event-schema round trip: typed authoring in, `.dwschema` text out, asserted
* against fixtures whose shapes are upstream's.
*
* The fixtures under `./testdata/` are adapted from
* `dogwood-policy/dogwood`'s shipped examples and its bundled default schema
* (Apache-2.0; each file carries its provenance in a header comment). They are
* not byte copies — upstream aligns field types in columns and chant does not
* — so what is pinned here is the surface: the directive, the declarations,
* the spreads, the selectors, and where the pins land.
*/
import { describe, test, expect } from "vitest";
import { readFileSync } from "fs";
import { join } from "path";
import { fileURLToPath } from "url";
import {
concrete,
declaredEventKinds,
defaultEventSchema,
eventDeclaration,
eventSchema,
field,
pinContext,
pinPrincipal,
pinnedField,
principalType,
record,
renderEventSchema,
resourceType,
spreadInputs,
spreadOutputs,
} from "./event-schema";
import { readEventSchema } from "./scan";

const TESTDATA = join(fileURLToPath(new URL(".", import.meta.url)), "testdata");
const UPSTREAM = "dogwood-policy/dogwood@5063bcc2d6d6cf5024d1b0498e6cc8ef52cbcf0c";

function fixture(name: string): string {
return readFileSync(join(TESTDATA, name), "utf-8");
}

/** The provenance header each fixture carries above the emitted bytes. */
function attribution(...sources: string[]): string {
return [
`// Adapted from ${UPSTREAM} (Apache-2.0):`,
...sources.map((s) => `// ${s}`),
"// Upstream's shape; the bytes are what chant's typed builders emit.",
"",
"",
].join("\n");
}

// ── The default shape ──────────────────────────────────────────────

describe("the default (pinned) event schema", () => {
test("round-trips to upstream's pinned.dwschema shape", () => {
expect(fixture("pinned.dwschema")).toBe(
attribution("dogwood-language/configuration/event-schemas/pinned.dwschema") +
renderEventSchema(defaultEventSchema()),
);
});

test("every kind pins callerPrincipal to the deciding request's principal", () => {
const text = renderEventSchema(defaultEventSchema());
expect(text.match(/pin callerPrincipal: principalType\(A\) = principal,/g)).toHaveLength(3);
expect(readEventSchema(text).hasPin).toBe(true);
});

test("request is the deciding kind; response and error are history", () => {
const text = renderEventSchema(defaultEventSchema());
expect(text).toContain("decision event <A>::request {");
expect(text).toContain("\nevent <A>::response {");
expect(text).toContain("\nevent <A>::error {");
expect(declaredEventKinds(defaultEventSchema())).toEqual(["request", "response", "error"]);
});

test("dropping the pin is a named argument, and says so in the file", () => {
const text = renderEventSchema(defaultEventSchema({ pinCallerPrincipal: false }));
expect(text).not.toContain("pin callerPrincipal");
expect(text).toContain("// Cross-principal: callerPrincipal is NOT pinned");
expect(readEventSchema(text).hasPin).toBe(false);
});
});

// ── max_window ─────────────────────────────────────────────────────

describe("the max_window directive", () => {
const raised = () =>
eventSchema(
[
eventDeclaration(
"request",
[
spreadInputs(),
field("callerPrincipal", principalType()),
field("callerResource", resourceType()),
field("requestId", concrete("String")),
],
{ decision: true },
),
eventDeclaration("response", [
spreadInputs(),
spreadOutputs(),
field("callerPrincipal", principalType()),
field("callerResource", resourceType()),
field("requestId", concrete("String")),
]),
],
{
maxWindow: "30d",
comment:
"Raises the look-back cap from the 24h default to 30 days. The directive\nmust come first, before any event declaration.\n\nNo pinned field: this schema correlates across principals on purpose.",
},
);

test("round-trips to upstream's max_window_raised shape", () => {
expect(fixture("max-window-raised.dwschema")).toBe(
attribution("dogwood-docs/examples/max_window_raised/event.dwschema") + renderEventSchema(raised()),
);
});

test("the directive precedes every declaration, as the grammar requires", () => {
const lines = renderEventSchema(raised()).split("\n");
const directive = lines.findIndex((l) => l.startsWith("max_window"));
const firstEvent = lines.findIndex((l) => l.includes("event <A>::"));
expect(directive).toBeGreaterThan(-1);
expect(directive).toBeLessThan(firstEvent);
});

test("the scanner reads the cap back out", () => {
const facts = readEventSchema(renderEventSchema(raised()));
expect(facts.maxWindowText).toBe("30d");
expect(facts.maxWindowSeconds).toBe(30 * 86400);
});

test("an absent directive reads back as upstream's 24h default", () => {
const facts = readEventSchema(renderEventSchema(defaultEventSchema()));
expect(facts.maxWindowText).toBeUndefined();
expect(facts.maxWindowSeconds).toBe(24 * 3600);
});
});

// ── Author-defined kinds ───────────────────────────────────────────

describe("author-defined event kinds", () => {
const custom = () =>
eventSchema(
[
eventDeclaration("attempt", [spreadInputs(), field("actor", principalType())], { decision: true }),
eventDeclaration("outcome", [spreadInputs(), spreadOutputs(), field("actor", principalType())]),
],
{
comment:
"Author-defined event kinds — `attempt` decides, `outcome` is history — and\na renamed injected principal field.",
},
);

test("round-trips to upstream's login_attempt_custom_kind shape", () => {
expect(fixture("custom-kinds.dwschema")).toBe(
attribution("dogwood-docs/examples/login_attempt_custom_kind/event.dwschema") + renderEventSchema(custom()),
);
});

test("request/response are conventional, not required", () => {
expect(declaredEventKinds(custom())).toEqual(["attempt", "outcome"]);
expect(readEventSchema(renderEventSchema(custom())).kinds).toEqual(["attempt", "outcome"]);
});
});

// ── Field forms ────────────────────────────────────────────────────

describe("field forms", () => {
test("a record type nests, and its members are addressed as name.member", () => {
const text = renderEventSchema(
eventSchema([
eventDeclaration("request", [
spreadInputs(),
field("session", record([field("id", concrete("String")), field("tenant", concrete("String"))])),
]),
]),
);
expect(text).toContain(" session: {\n id: String,\n tenant: String,\n },");
});

test("a context pin renders its dotted path", () => {
const text = renderEventSchema(
eventSchema([
eventDeclaration("request", [pinnedField("tenant", concrete("String"), pinContext("input.tenant"))]),
]),
);
expect(text).toContain(" pin tenant: String = context.input.tenant,");
});

test("a scope pin may carry an attribute tail", () => {
const text = renderEventSchema(
eventSchema([
eventDeclaration("request", [pinnedField("dept", concrete("String"), pinPrincipal("dept"))]),
]),
);
expect(text).toContain(" pin dept: String = principal.dept,");
});

test("pinning a whole record is refused — upstream requires a leaf", () => {
expect(() => pinnedField("group", record([field("a", concrete("String"))]), pinPrincipal())).toThrow(
/must be a leaf/,
);
});

test("a duplicated event kind is refused at construction", () => {
expect(() =>
eventSchema([eventDeclaration("request", []), eventDeclaration("request", [])]),
).toThrow(/declared twice/);
});

test("a schema with no declarations is refused", () => {
expect(() => eventSchema([])).toThrow(/at least one event kind/);
});
});
Loading