Repository navigation
feat(cedar): schema-driven codegen + configSchema + upstream pin (#1650) - #1664
Merged
Merged
Conversation
This was referenced Aug 10, 2026
`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
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1650. Part of epic #1645. Stacked on #1656 (
cedar/scaffold-serializer) — retargets tomainwhen 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 thePolicyauthoring class the serializer already consumes. The example says it best:ReadActionand"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). Thecedarnamespace viaz.strictObject:schema(path to the project's.cedarschema, defaultschema.cedarschema) andvalidation(mode,warnings,requireProjectSchema). Module augmentation ofChantConfigperoverview.mdx, wired onto the plugin, and — the part that makes it more than decoration — actually read:plugin.generate()andplugin.coverage()load it vialoadCedarConfig(), andconfig-namespace.test.tspins the path fromchant.config.tsto the filegenerate()opens.validation.modeisz.literal("strict")on purpose:ValidationModein cedar-wasm 4.12.0 accepts nothing else and anything more throws from inside the wasm (#1648 §5.7).generate()via coregeneratePipeline.fetchSchemasreads a project-local file; there is no network.parseSchemagoes throughschemaToJsonWithResolvedTypesand drives the emitters off the resolvedSchemaJson: entity types →createResourceclasses, records (entity shapes and action contexts) →createPropertyclasses, actions → typed string constants,{type:"Entity",name}→ the referenced entity's UID type,Set→ arrays,required:false→ optional properties, extension types →string.NamingStrategynames 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.schemaToJsonWithResolvedTypesfully qualifies common types in attribute position but leaves the definition incommonTypes;resolveTypeRefcloses 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:/nodejsonly (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
createRequireon first call. Importing this package is something achant.config.tsdoes purely to bring thecedarkey intoChantConfig; 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.tsruns 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.cedarschemaships 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.requireProjectSchematurns 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.upstreamPinbumps it againstcedar-policy/cedarreleases.CEDAR_LANG_VERSION = "4.5"— the grammar that package implements.generate()assertsgetCedarLangVersion()against it before reading anything, and refuses on a mismatch (CHANT_ACCEPT_CEDAR_LANG=1to 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.tspattern, with the 16 covered names committed inpinned-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, andsrc/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.tsfollows the other*-upgrade.op.tsfiles, 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()andcoverage()validate()requires 33 names — thePolicyclass, 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'scomputeCoveragedimensions (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) pluschant.config.tspointingcedar.schemaat it;examples/getting-started/is filled in with a two-policy set.examples/examples.test.tsbuilds both and feeds the emitted.cedartocheckParsePolicySet— building is not the same as being valid Cedar, and this asserts both.Left in place:
cedar → "postSynthChecks() returns at least 1 check"— cedar 4/8: lint rules + post-synth + auditCatalog #1651's, reworded now that the typed classes it was waiting on exist.cedar is 20/21 tier-1 with one tracked failure;
scripts/check-lexicons.tsexits 0 with no untracked failures.CI
prepackgainsgenerateandvalidate(it wasbundle && build), becausesrc/index.tsnow re-exports the generated surface and there is finally something to validate. Thechant.ymlcomment #1649's fix added is updated to match, and cedar joins thevalidatejob, where every other lexicon with a real generate already is.Known gap, not this PR's
The
.cedartext validates undercedar-wasm. The JSON companion does not: the serializer writeswhen/unlessbodies 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.tsasserts 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
npx tsc --noEmit -p lexicons/cedar/tsconfig.build.jsonnpm run build -w @intentius/chant-lexicon-cedarnpx vitest run lexicons/cedarnpx vitest run packages/core/src/codegennpx tsx scripts/check-lexicons.tsnpx vitest run(full suite)npm run --prefix lexicons/cedar prepack