Skip to content

feat(cedar): schema-driven codegen + configSchema + upstream pin (#1650) - #1664

Merged
lex00 merged 1 commit into
mainfrom
cedar/codegen
Aug 10, 2026
Merged

lex00 merged 1 commit into
mainfrom
cedar/codegen

Conversation

@lex00

@lex00 lex00 commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Closes #1650. Part of epic #1645. Stacked on #1656 (cedar/scaffold-serializer) — retargets to main when that merges.

generate() reads a Cedar schema and emits a class per entity type, a constant per action, a UID template-literal type per entity, and the Policy authoring class the serializer already consumes. The example says it best:

import { Policy, ReadAction, WriteAction } from "@intentius/chant-lexicon-cedar";

export const ownerRead = new Policy({
  principal: { is: "App::User" },
  action: { eq: ReadAction },
  resource: { is: "App::Document" },
  when: ["resource.owner == principal"],
});

ReadAction and "App::Document" are checked at compile time. An action the schema never declared, or "App::Documnt", does not build. Cedar's own validator catches the same class of mistake, but only after the text is written and only if it is run.

Scope

configSchema (src/config.ts). The cedar namespace via z.strictObject: schema (path to the project's .cedarschema, default schema.cedarschema) and validation (mode, warnings, requireProjectSchema). Module augmentation of ChantConfig per overview.mdx, wired onto the plugin, and — the part that makes it more than decoration — actually read: plugin.generate() and plugin.coverage() load it via loadCedarConfig(), and config-namespace.test.ts pins the path from chant.config.ts to the file generate() opens.

validation.mode is z.literal("strict") on purpose: ValidationMode in cedar-wasm 4.12.0 accepts nothing else and anything more throws from inside the wasm (#1648 §5.7).

generate() via core generatePipeline. fetchSchemas reads a project-local file; there is no network. parseSchema goes through schemaToJsonWithResolvedTypes and drives the emitters off the resolved SchemaJson: entity types → createResource classes, records (entity shapes and action contexts) → createProperty classes, actions → typed string constants, {type:"Entity",name} → the referenced entity's UID type, Set → arrays, required:false → optional properties, extension types → string. NamingStrategy names the primary declarations; derived names (UserAttributes, ReadContext, UserUid) are de-duplicated against the same pool.

Common types are resolved by us, not by the wasm. The report's example showed {"type":"Chant::Level"} — and that is what 4.12.0 still emits. schemaToJsonWithResolvedTypes fully qualifies common types in attribute position but leaves the definition in commonTypes; resolveTypeRef closes that last hop (with a cycle guard), so nothing downstream ever sees an alias.

Everything the report warned about is encoded in src/spec/wasm.ts, which is the only place the package is called from: /nodejs only (the root ESM build cannot start under Bun), typeof === "string" before the resolver (a JS object traps the instance — verified recoverable, and there is a test that keeps using the wasm after a rejected call), try/catch around every call (malformed input throws from serde rather than returning a failure answer), and no use of parse-success as a proxy for schema-presence.

The wasm loads lazily via createRequire on first call. Importing this package is something a chant.config.ts does purely to bring the cedar key into ChantConfig; a top-level import would charge every such import 4.2 MB of wasm and ~13 MB RSS.

Determinism. Resolved-schema keys arrive sorted (Rust BTreeMap); everything else is sorted explicitly; no clock, no randomness. generate.test.ts runs the pipeline twice and compares all three artifacts byte-for-byte.

The bundled default schema

Cedar's codegen input is the project's file, which means generate() has nothing to read in a checkout that has not written one — every fresh clone, just check-lexicons, and this lexicon's own examples. A generate step that only works after the user does something is a generate step nothing gates.

So src/spec/default-schema.cedarschema ships as the last resort in the resolution order (cedar.schema → schema.cedarschema → bundled). It is a real application-authorization model — 7 entity types (User, Group, Team, ServiceAccount, Folder, Document, Application), 9 actions (read, list, write, create, comment, delete, share, approve, admin), common types, optionals, sets and entity references — not a stub, so the 33-name surface it produces is worth validating against. cedar.validation.requireProjectSchema turns the fallback off for a project that has its own schema.

Pins

Two, for two different things (#1648 §0 makes the distinction; #1390 supplies the rule).

  • CEDAR_WASM_VERSION = "4.12.0" — the package. upstreamPin bumps it against cedar-policy/cedar releases.
  • CEDAR_LANG_VERSION = "4.5" — the grammar that package implements. generate() asserts getCedarLangVersion() against it before reading anything, and refuses on a mismatch (CHANT_ACCEPT_CEDAR_LANG=1 to proceed once). This is the value worth asserting: a package bump that leaves the language at 4.5 cannot change what parses.

Beside them, a content pin over the resolved JSON of the bundled default schema, per the lexicons/aws/src/spec/pin.ts pattern, with the 16 covered names committed in pinned-names.json. Digesting the resolved form rather than the schema text means reformatting the schema does not move it (there is a test); what does move it is an edit to the schema, or — the case it exists for — a cedar-wasm upgrade resolving the same schema differently. Both rewrite the generated types, and src/generated/ is not committed.

Unlike aws this one refuses on any digest move rather than only on a declaration-set change. It can afford to: the input is a file in this repo and a dependency at a pinned version, neither of which republishes under the build's feet the way the CloudFormation archive does.

ops/lexicon-upgrade/cedar-upgrade.op.ts follows the other *-upgrade.op.ts files, with the four sibling lists updated so the wiring test passes: the workflow matrix, IN_SCOPE_LEXICONS, PINNED_LEXICONS, and the composite's own scope test.

validate() and coverage()

validate() requires 33 names — the Policy class, 7 entity classes, 7 attribute records, 9 action constants, 9 context records (tier-3 wants 30). Listing them is the point: src/generated/ is gitignored, so without the list nothing in the repo records what the default schema should produce, and a codegen change that dropped every action would still pass "the registry parses."

coverage() reports schema coverage — are all entity types and actions reachable from the generated artifacts — rather than core's computeCoverage dimensions (property constraints, create-only/write-only lifecycle, return attributes), none of which a Cedar schema has. Reporting 0% across four axes that cannot apply would be worse than reporting nothing. A gap here is a real defect: an action with no generated constant is one a policy can only name as a hand-typed string.

KNOWN_FAILURES delta

Removed exactly one entry:

  • cedar → "Every shipped example builds" — both examples now author a policy set against generated types. examples/basic-policies/ ships its own .cedarschema (a subset of the bundled default, so it compiles against a package generated either way) plus chant.config.ts pointing cedar.schema at it; examples/getting-started/ is filled in with a two-policy set. examples/examples.test.ts builds both and feeds the emitted .cedar to checkParsePolicySet — building is not the same as being valid Cedar, and this asserts both.

Left in place:

cedar is 20/21 tier-1 with one tracked failure; scripts/check-lexicons.ts exits 0 with no untracked failures.

CI

prepack gains generate and validate (it was bundle && build), because src/index.ts now re-exports the generated surface and there is finally something to validate. The chant.yml comment #1649's fix added is updated to match, and cedar joins the validate job, where every other lexicon with a real generate already is.

Known gap, not this PR's

The .cedar text validates under cedar-wasm. The JSON companion does not: the serializer writes when/unless bodies as { __expr: "<text>" }, and Cedar's JSON grammar has no such escape — it wants an expression tree (unknown variant '__expr', expected one of 'Value', 'Var', …). Producing one means parsing Cedar expression text, which is epic #1645's import/reconcile sub-issue, not codegen's. examples.test.ts asserts the JSON is emitted and well-formed, and says in a comment why it is not fed to the validator, rather than encoding the broken behaviour as a passing check.

Gates

Gate Result
npx tsc --noEmit -p lexicons/cedar/tsconfig.build.json pass
npm run build -w @intentius/chant-lexicon-cedar pass
npx vitest run lexicons/cedar 97 passed / 11 files
npx vitest run packages/core/src/codegen 341 passed / 28 files
npx tsx scripts/check-lexicons.ts exit 0, 1 tracked failure, 0 untracked
npx vitest run (full suite) 11440 passed, 5 skipped
npm run --prefix lexicons/cedar prepack pass — 16 declarations, 4/4 validation checks

@lex00
lex00 changed the base branch from cedar/scaffold-serializer to main August 10, 2026 17:09
`generate()` reads a Cedar schema and emits a class per entity type, a
constant per action, a UID template-literal type per entity, and the
`Policy` authoring class the serializer already consumes — so
`action: { eq: ReadAction }` is a compile-time fact and a renamed entity
type is a compiler-guided refactor. Part of #1645.

The pipeline is core's `generatePipeline`; the input is what is unusual.
Every other lexicon fetches one global upstream spec, so `fetchSchemas`
is an HTTP call. Cedar's spec-of-interest is the project's own
`.cedarschema`, so it is a file read with a resolution order:
`cedar.schema` from `chant.config.ts`, then `schema.cedarschema` in the
project root, then the schema bundled at
`src/spec/default-schema.cedarschema`.

That third step is the one worth defending. Without it `generate()` has
nothing to read in a checkout that has not written a schema yet — every
fresh clone, `just check-lexicons`, and this lexicon's own examples —
and a generate step that only works after the user does something is a
generate step nothing gates. The default is a real seven-entity,
nine-action application-authorization schema, not a stub, and
`cedar.validation.requireProjectSchema` turns the fallback off for
projects that have moved past it.

Parsing goes through `schemaToJsonWithResolvedTypes`, per the #1648
verification: `schemaToJson` emits `EntityOrCommon` for every named type
and cannot tell an entity reference from a primitive from a common-type
alias, so an emitter reading it would re-implement Cedar's own name
resolution. Common types in attribute position survive resolution as
bare qualified names and are collapsed here. The wasm is reached only
through `src/spec/wasm.ts`, which imports `/nodejs` (the root ESM build
cannot start under Bun), guards `typeof === "string"` before the
resolver (a JS object traps the instance rather than returning a
failure), wraps every call in try/catch (malformed input throws from
serde instead of returning an answer), and loads lazily so importing
this package for its type augmentation does not pay for 4.2 MB of wasm.

Two pins, for two different things. `CEDAR_WASM_VERSION` is the package
`upstreamPin` bumps; `CEDAR_LANG_VERSION` is the grammar `generate()`
asserts before emitting anything, since a package bump that leaves the
language at 4.5 cannot change what parses. Beside them a content pin
over the resolved JSON of the bundled default schema — it moves when the
schema is edited and, the case it exists for, when a cedar-wasm upgrade
resolves the same schema differently. Both rewrite generated types, and
`src/generated/` is not committed.

`validate()` checks 33 required names over the default schema's surface
(tier-3 wants 30). `coverage()` reports schema coverage — entity types
and actions reachable from the generated artifacts — rather than core's
CloudFormation-shaped dimensions, none of which a Cedar schema has.

KNOWN_FAILURES: "Every shipped example builds" is removed; both examples
now author a policy set against generated types, and the emitted
`.cedar` text is fed to `cedar-wasm` in `examples/examples.test.ts`.
The postSynthChecks entry stays — that is #1651's.

cedar joins the lexicon-upgrade lane (workflow matrix, op file,
IN_SCOPE_LEXICONS, PINNED_LEXICONS) and the chant.yml validate job, now
that its prepack has a real generate and a real validate.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018FAMfgpQTVDnsnqJzyHasZ
@lex00
lex00 merged commit 2767111 into main Aug 10, 2026
6 checks passed
lex00 added a commit that referenced this pull request Aug 10, 2026
Part of #1645 (cedar 6/8).

templateParser/templateGenerator/detectTemplate for the cedar lexicon, and a
fix to the serializer's JSON companion, which was writing a key Cedar does
not have.

The JSON leg is now built by handing the emitted `.cedar` text back to
`cedar-wasm` (policySetTextToParts + policyToJson/templateToJson per policy)
instead of being derived from the in-memory model. It shipped writing when/
unless bodies as `{"__expr": "<text>"}`, which every Cedar tool rejects with
`unknown variant '__expr'` (#1664). Going through the module gives real
expression trees, and it also files a policy carrying a ?principal/?resource
slot under `templates` rather than `staticPolicies` — Cedar decides which it
is, not the serializer. Text the module cannot parse yields a build warning
and no JSON file rather than an invalid one.

The importer round-trips byte-for-byte on the text leg: condition bodies are
lifted from the source verbatim by a delimiter scanner and then verified
against the tree policyToJson makes of the same clause, falling back to the
rendered form on any mismatch. Two normalizations are real and asserted
rather than hidden — annotations come back alphabetically, and interleaved
when/unless clauses regroup — and both settle after one lap.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018FAMfgpQTVDnsnqJzyHasZ
lex00 added a commit that referenced this pull request Aug 10, 2026
…#1666)

* feat(cedar): import/export round-trip + valid JSON policy leg (#1653)

Part of #1645 (cedar 6/8).

templateParser/templateGenerator/detectTemplate for the cedar lexicon, and a
fix to the serializer's JSON companion, which was writing a key Cedar does
not have.

The JSON leg is now built by handing the emitted `.cedar` text back to
`cedar-wasm` (policySetTextToParts + policyToJson/templateToJson per policy)
instead of being derived from the in-memory model. It shipped writing when/
unless bodies as `{"__expr": "<text>"}`, which every Cedar tool rejects with
`unknown variant '__expr'` (#1664). Going through the module gives real
expression trees, and it also files a policy carrying a ?principal/?resource
slot under `templates` rather than `staticPolicies` — Cedar decides which it
is, not the serializer. Text the module cannot parse yields a build warning
and no JSON file rather than an invalid one.

The importer round-trips byte-for-byte on the text leg: condition bodies are
lifted from the source verbatim by a delimiter scanner and then verified
against the tree policyToJson makes of the same clause, falling back to the
rendered form on any mismatch. Two normalizations are real and asserted
rather than hidden — annotations come back alphabetically, and interleaved
when/unless clauses regroup — and both settle after one lap.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018FAMfgpQTVDnsnqJzyHasZ

* fix(cedar): type the wasm PolicySet casts in tests for the repo-wide typecheck (#1653)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

cedar 3/8: schema-driven generate() + configSchema

1 participant