From 89c5145a7e8677dfc256233cee05de3ac5385558 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 7 Sep 2026 22:00:59 -0600 Subject: [PATCH 1/3] feat(ops): an `environment` option on a scheduled Op, emitted as the generated job's deployment gate (#2257) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `generateOpsPipeline` emitted no `environment:` on any job, so a GitHub environment with required reviewers bound nothing a chant-generated pipeline ran. The option lands on `ScheduledOpSpec` beside #2242's `setup` and `permissions`, not on `OpConfig` beside #2120's `schedule`: a cadence is runtime-neutral data three readers render, while which forge environment a job deploys to has exactly one reader, is a property of that job rather than of the Op (the pull-request plan touches no environment; only the push apply belongs behind the reviewer), and would have to be overridden per generate call anyway for an Op generated into more than one environment. github emits `environment: { name, url? }` on the Op's own job and never on the gate-notice job beside it, which exists to say a chant gate is pending and would be useless held behind the same reviewer. `permissionsFor` gains nothing: environment protection is repository configuration, not a token scope. `assertEnvironment` refuses only what could never bind — a blank name, and a `url` that is neither absolute nor an expression the forge resolves — because GitHub creates an unprotected environment on first use rather than failing, so whether reviewers exist is not answerable from workflow content. forgejo drops the key: Forgejo Actions has no environments, no protection rules and no required reviewers. Dropping it silently would be the worst available outcome when the whole point of the option is a human holding an apply, so the generated file gains a header comment naming the environment that was asked for, saying nothing on the forge enforces it, and pointing at chant's own gate. The drop is scoped to the Op generator rather than added to the dialect's `DROPPED_KEYS`, so every other document the dialect transforms is untouched. gitlab maps it to its own `environment:`, which exists there with the same two fields and a protected-environment approval rule behind it. As with the schedule, the approval rule is a project setting this file cannot declare, so the generated header names the environment to protect. Additive throughout: a spec without `environment` emits the same bytes it did before. --- .../src/components/generate-op-pipeline.ts | 47 ++++++++++- .../src/components/generate-op-pipeline.ts | 80 +++++++++++++++++++ .../src/components/generate-op-pipeline.ts | 72 +++++++++++++++++ packages/core/src/lexicon.ts | 41 ++++++++++ 4 files changed, 238 insertions(+), 2 deletions(-) diff --git a/lexicons/forgejo/src/components/generate-op-pipeline.ts b/lexicons/forgejo/src/components/generate-op-pipeline.ts index 8f014e577c..874ae6c1dd 100644 --- a/lexicons/forgejo/src/components/generate-op-pipeline.ts +++ b/lexicons/forgejo/src/components/generate-op-pipeline.ts @@ -35,6 +35,17 @@ * configuration to point `gh` at a Forgejo instance, so this refuses the mode * by name rather than generating a job whose finding step fails on every run. * + * A spec's `environment` (#2257) is dropped on the same terms as + * `permissions:`, and for a stronger reason: Forgejo Actions has no + * environments at all — no protection rules, no required reviewers, no + * per-environment secrets — so the key names an object that does not exist on + * the instance. Dropping it silently would be the worst outcome available, + * because the whole point of the option is a human holding an apply, so this + * also writes a comment into the generated file's header saying which + * environment was asked for and that nothing on Forgejo enforces it. What + * still holds the apply here is chant's own gate (#2119), which is a fact on + * the `chant/lifecycle` branch and needs nothing from the forge. + * * The gated-apply notice job (#2243) does not cross over either, for the same * reason and by the same mechanism as `permissions:`: it shells to `gh`, which * a Forgejo `act_runner` neither ships nor can point at its own instance, and @@ -64,6 +75,34 @@ function forgejoize(value: Record, dialect: ForgejoDialectOptio return transformWorkflowObject(value, dialect).value as Record; } +/** + * Strip the job-level `environment:` github emitted (#2257). Forgejo Actions + * has no environments, so the key would read as a deployment gate and hold + * nothing back. Dropped from the rebuilt doc rather than from the dialect's + * own `DROPPED_KEYS`, so this touches the Op generator alone and leaves every + * other document the dialect transforms exactly as it emits today. + */ +function withoutEnvironment(jobsDoc: Record): Record { + return Object.fromEntries( + Object.entries(jobsDoc).map(([jobName, job]) => { + if (typeof job !== "object" || job === null || !("environment" in job)) return [jobName, job]; + const { environment: _dropped, ...rest } = job as Record; + return [jobName, rest]; + }), + ); +} + +/** Say in the generated file which environment gate did not survive the crossing. */ +function droppedEnvironmentHeader(environmentName: string): string[] { + return [ + `# chant dropped \`environment: ${environmentName}\` from this workflow: Forgejo Actions has no`, + "# environments, so there is no protection rule, required reviewer or wait timer for the key to", + "# name. This job is not held back by anything on the forge. What still stops the apply is chant's", + "# own gate: the run records a pending fact on the chant/lifecycle branch and ends, and `chant", + "# approve ` is what lets the next run through.", + ]; +} + /** * Synthesize one `.forgejo/workflows/*.yml` per scheduled Op. Reuses github's * trigger/job structure ({@link buildGithubOpPipelineDocs}) — its `setup`-step @@ -92,13 +131,17 @@ export function generateForgejoOpPipeline( const { files, jobs } = buildGithubOpPipelineDocs(ops, options); return { - files: files.map(({ name, doc }) => { + // One file per spec, in spec order, which is what lets the header below + // read its Op's own `environment` off the input by position. + files: files.map(({ name, doc }, index) => { + const environment = ops[index].environment; const forgejoDoc: GithubOpPipelineDoc = { + ...(environment ? { header: droppedEnvironmentHeader(environment.name) } : {}), on: forgejoize(doc.on, dialectOptions), ...(doc.env ? { env: forgejoize(doc.env, dialectOptions) } : {}), concurrency: forgejoize(doc.concurrency, dialectOptions), permissions: {}, - jobsDoc: forgejoize(doc.jobsDoc, dialectOptions), + jobsDoc: forgejoize(withoutEnvironment(doc.jobsDoc), dialectOptions), }; return { name, yaml: emitOpPipelineYAML(forgejoDoc) }; }), diff --git a/lexicons/github/src/components/generate-op-pipeline.ts b/lexicons/github/src/components/generate-op-pipeline.ts index c45972b6ff..c7550321c5 100644 --- a/lexicons/github/src/components/generate-op-pipeline.ts +++ b/lexicons/github/src/components/generate-op-pipeline.ts @@ -46,12 +46,24 @@ * reason) and never touching one it does; {@link mergePermissions} refuses a * blanket grant, an overlap with the mode's own set, an unknown scope name, * and pull-request write on a trigger that has no pull request. + * + * A third widens it the other way (#2257): a spec's `environment` emits + * `environment:` on the Op's own job, which is how a GitHub environment's + * protection rules — required reviewers above all — come to hold a generated + * apply. That is a second gate beside chant's own, not a replacement for it: + * the reviewer stops the job before any step runs, chant's gate ledger + * (#2119) stops the apply inside a run that already started, and the two + * compose in either combination. It costs {@link permissionsFor} nothing — + * environment protection is repository configuration, not a token scope — and + * {@link assertEnvironment} refuses only what would emit as configured and + * bind nothing. */ import { emitYAML } from "@intentius/chant/yaml"; import { resolveOpTrigger } from "@intentius/chant/lexicon"; import type { ComponentPipelineOptions as GenerateGithubOpOptions, + OpEnvironment, OpFindingMode, OpPipelineJob, OpPipelineResult as GenerateGithubOpResult, @@ -70,6 +82,15 @@ export type { GenerateGithubOpOptions, GenerateGithubOpResult }; * `./generate-pipeline.ts`'s `GithubPipelineDoc` split. */ export interface GithubOpPipelineDoc { + /** + * Comment lines emitted above the document, `#` prefix included, when a + * dialect has something to say about what it could not carry across + * (#2257). Empty on github, which drops nothing; the forgejo dialect uses + * it to name the `environment:` its runner has no concept of, so the fact + * that a reviewer gate did not survive is readable in the generated file + * rather than only in a build warning. + */ + header?: string[]; /** * The `on:` trigger mapping, per {@link ScheduledOpSpec}'s trigger kind * (#2084): `{ schedule, workflow_dispatch }` for cron, `{ pull_request }` @@ -408,6 +429,43 @@ export function assertSetupSteps(name: string, setup: OpSetupStep[]): void { }); } +/** + * Validate a spec's `environment` (#2257). GitHub creates an environment it + * has never seen on first use rather than failing the run, and an environment + * created that way carries no protection rules at all — so a job can name one + * and read as gated while being gated by nothing. Neither this generator nor + * GitHub can tell those apart at build time (the environment and its + * reviewers are repository configuration, not workflow content), which is why + * what is refused here is only the shape that could never bind: a name that + * is blank, and a `url` that is neither absolute nor an expression the forge + * resolves. The rest is the README's job to say out loud. + */ +export function assertEnvironment(name: string, environment: OpEnvironment): void { + const where = `Scheduled Op "${name}" environment`; + if (environment.name.trim() === "") { + throw new Error( + `${where} has an empty \`name\`. An environment is named repository configuration — the ` + + `protection rules and reviewers live on the environment, not in this workflow — so there is ` + + `nothing for a blank name to resolve to. Give it the environment's name, or drop the option.`, + ); + } + if (environment.url === undefined) return; + const url = environment.url.trim(); + if (url === "") { + throw new Error( + `${where} "${environment.name}" has an empty \`url\`. Omit the field rather than setting it to "".`, + ); + } + if (!/^https?:\/\//.test(url) && !url.includes("${{")) { + throw new Error( + `${where} "${environment.name}" has \`url: "${environment.url}"\`, which is neither an absolute ` + + `http(s) URL nor a \${{ }} expression. GitHub renders this value as the deployment's own link, ` + + `so a relative path becomes a dead link on the environment page rather than an error anywhere. ` + + `Write the full URL, or an expression the run resolves to one.`, + ); + } +} + /** * Merge a spec's additive `permissions` over the finding-mode's own set * (#2242), refusing by name anything that is not strictly additive: @@ -472,6 +530,18 @@ export function mergePermissions( return merged; } +/** + * Emit a spec's environment as the job's `environment:` mapping. Always the + * mapping form, never the `environment: name` string shorthand, so adding a + * `url` later is a new key rather than a reshaped value. + */ +function environmentDoc(environment: OpEnvironment): Record { + return { + name: environment.name, + ...(environment.url === undefined ? {} : { url: environment.url }), + }; +} + /** Emit one setup entry as a GitHub Actions step. */ function setupStepDoc(step: OpSetupStep): Record { if ("uses" in step) { @@ -527,6 +597,7 @@ export function buildGithubOpPipelineDocs( const setup = spec.setup ?? []; assertSetupSteps(spec.name, setup); + if (spec.environment) assertEnvironment(spec.name, spec.environment); // A `push` job is the one that has to survive a gate (#2243): the apply // runs with `--gated-exit 0` so a pending approval is a green run, and @@ -563,6 +634,11 @@ export function buildGithubOpPipelineDocs( [jobName]: { "runs-on": "ubuntu-latest", container: image, + // On this Op's own job and never on the notice job beside it: the + // notice exists to say a chant gate is pending, and putting it + // behind the same reviewer would hold the message back until + // somebody had already acted. + ...(spec.environment ? { environment: environmentDoc(spec.environment) } : {}), ...(gated ? { outputs: Object.fromEntries( @@ -592,6 +668,10 @@ export function buildGithubOpPipelineDocs( */ export function emitOpPipelineYAML(doc: GithubOpPipelineDoc): string { const sections: string[] = []; + // A dialect's note about what it could not carry (#2257), when there is + // one. Absent on github, so an unannotated document is emitted exactly as + // it was before the field existed. + if (doc.header && doc.header.length > 0) sections.push(doc.header.join("\n")); sections.push("on:" + emitYAML(doc.on, 1)); if (doc.env && Object.keys(doc.env).length > 0) sections.push("env:" + emitYAML(doc.env, 1)); sections.push("concurrency:" + emitYAML(doc.concurrency, 1)); diff --git a/lexicons/gitlab/src/components/generate-op-pipeline.ts b/lexicons/gitlab/src/components/generate-op-pipeline.ts index d9070b7ca9..85b4dd2fc4 100644 --- a/lexicons/gitlab/src/components/generate-op-pipeline.ts +++ b/lexicons/gitlab/src/components/generate-op-pipeline.ts @@ -42,6 +42,19 @@ * the job itself) that chant does not generate. Ignoring the map would emit a * job that reads as having OIDC and runs with no credentials. * + * A spec's `environment` (#2257) does cross, because GitLab has the concept + * under the same key and with the same two fields: `environment: { name, url + * }` on the job, an environment object in the project, and — on a protected + * environment — an approval rule that holds the deployment job until an + * approver releases it. So the reviewer gate the option exists for is + * expressible here, unlike the two #2242 options above, and it is emitted + * rather than refused. What GitLab does not have is any way for this file to + * declare the protection: an environment's approval rules are project + * settings (Settings > CI/CD > Protected environments), exactly as GitHub's + * required reviewers are repository settings, so the generated header names + * the environment to protect the way it already names the schedule to create. + * chant's own gate (#2119) runs inside the job either way. + * * The gated-apply mapping (#2243) has nothing to attach to here. It exists * because a push-to-main apply that stops at its gate exits 3 and paints the * branch red on every merge; this generator has no push pipeline at all, @@ -58,12 +71,46 @@ import { emitYAML } from "@intentius/chant/yaml"; import { resolveOpTrigger } from "@intentius/chant/lexicon"; import type { ComponentPipelineOptions as GenerateGitlabOpOptions, + OpEnvironment, OpFindingMode, OpPipelineJob, OpPipelineResult as GenerateGitlabOpResult, ScheduledOpSpec, } from "@intentius/chant/lexicon"; +/** + * Validate a spec's `environment` (#2257) on GitLab's own terms. A GitLab job + * naming an environment that does not exist creates an unprotected one on + * first deploy rather than failing, so — as on github — the only shapes worth + * refusing at build time are the ones that could never bind: a blank name, + * and a `url` that is neither absolute nor a variable expression GitLab + * expands, which would render as a dead "View deployment" link. + */ +function assertGitlabEnvironment(name: string, environment: OpEnvironment): void { + const where = `Scheduled Op "${name}" environment`; + if (environment.name.trim() === "") { + throw new Error( + `${where} has an empty \`name\`. A GitLab environment is a project object, and its approval ` + + `rules live on that object rather than in this file, so a blank name resolves to nothing. ` + + `Give it the environment's name, or drop the option.`, + ); + } + if (environment.url === undefined) return; + const url = environment.url.trim(); + if (url === "") { + throw new Error( + `${where} "${environment.name}" has an empty \`url\`. Omit the field rather than setting it to "".`, + ); + } + if (!/^https?:\/\//.test(url) && !url.includes("$")) { + throw new Error( + `${where} "${environment.name}" has \`url: "${environment.url}"\`, which is neither an absolute ` + + `http(s) URL nor a variable expression GitLab expands. It becomes the environment's own link, ` + + `so a relative path is a dead link on the environment page rather than an error anywhere.`, + ); + } +} + /** * Refuse the two #2242 options GitLab cannot honour, by name and before any * YAML exists, and return the `run` setup lines that do translate. See the @@ -114,6 +161,19 @@ function setupLine(spec: ScheduledOpSpec, cron: string, jobName: string, mode: O return `# ${jobName}: cron "${cron}", ${SELECTOR_VAR}="${spec.name}", finding-mode ${mode}${tokenNote}`; } +/** + * The follow-up line an Op with an `environment` adds under its setup line + * (#2257). The `environment:` key below binds the job to the environment; it + * cannot declare the approval rule, which is a project setting, so the header + * says where that is set the same way it says where the schedule is created. + */ +function environmentLine(environment: OpEnvironment): string { + return ( + `# deploys to environment "${environment.name}" — protect it under Settings > CI/CD >` + + " Protected environments to require an approval before the job runs" + ); +} + /** * Synthesize one `.gitlab-ci.yml` job per scheduled Op, all in a single file * (GitLab has no per-file cron — see the module doc). Wired into core's Op @@ -168,6 +228,10 @@ export function generateGitlabOpPipeline( const jobName = toJobName(spec.name); jobs.push({ jobName, op: spec.name, trigger, findingMode }); headerLines.push(setupLine(spec, trigger.schedule, jobName, findingMode)); + if (spec.environment) { + assertGitlabEnvironment(spec.name, spec.environment); + headerLines.push(environmentLine(spec.environment)); + } const runParts = runCommand.map((part) => part.replace("{name}", spec.name)); const script = [...setupScript, ...beforeScript, runParts.join(" "), ...extraScript]; @@ -175,6 +239,14 @@ export function generateGitlabOpPipeline( doc[jobName] = { stage: STAGE, image, + ...(spec.environment + ? { + environment: { + name: spec.environment.name, + ...(spec.environment.url === undefined ? {} : { url: spec.environment.url }), + }, + } + : {}), rules: [{ if: `$CI_PIPELINE_SOURCE == "schedule" && $${SELECTOR_VAR} == "${spec.name}"` }], script, }; diff --git a/packages/core/src/lexicon.ts b/packages/core/src/lexicon.ts index 8676856f07..45f91b57bc 100644 --- a/packages/core/src/lexicon.ts +++ b/packages/core/src/lexicon.ts @@ -551,6 +551,38 @@ export interface OpSetupRunStep { env?: Record; } +/** + * The deployment environment a generated Op job runs in (#2257) — a forge + * object rather than a chant one. On GitHub Actions an environment carries + * its own protection rules (required reviewers, a wait timer, a branch + * restriction) and its own secrets and variables, so naming one on a job is + * how a generated apply is put behind a human before the job starts. GitLab + * has the same key with the same two fields and its own protected-environment + * approvals behind it. Forgejo Actions has no environments at all, so its + * dialect drops the key and says so in the generated file's header. + * + * This is not a chant gate and does not replace one. The environment reviewer + * stops the job before any step runs; chant's own gate (#2119) stops the apply + * inside a run that already started, on a fact recorded on the + * `chant/lifecycle` branch, and is cleared by `chant approve`. A project may + * have either, both, or neither per environment. + */ +export interface OpEnvironment { + /** + * The environment's name, exactly as the forge spells it. Nothing creates + * it: an environment is repository configuration, and a job naming one that + * does not exist yet gets an unprotected environment created on first run + * rather than an error, which is precisely why the name is not guessed here. + */ + name: string; + /** + * The URL shown against the resulting deployment. Absolute, or an + * expression the forge resolves (`${{ ... }}`) — a relative path renders as + * a dead link on the deployments page rather than failing anywhere. + */ + url?: string; +} + /** One scheduled Op to generate CI for — the cron-triggered counterpart to a component (generate mode). */ export interface ScheduledOpSpec { /** Op name (`*.op.ts`'s `Op({ name })`) — what `chant run ` targets. */ @@ -594,6 +626,15 @@ export interface ScheduledOpSpec { * grants and OIDC cannot work without. */ permissions?: Record; + /** + * The forge deployment environment this Op's generated job runs in + * (#2257). Per Op, beside `setup` and `permissions`, and for the same + * reason: which environment a job deploys to is a property of that job — a + * pull-request plan touches none, and only the push apply belongs behind + * the reviewer. See {@link OpEnvironment} for how it composes with chant's + * own gate. + */ + environment?: OpEnvironment; } /** From ee4b296e64a9b267540d1f6870aa259c9175dea2 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 7 Sep 2026 22:04:44 -0600 Subject: [PATCH 2/3] test(ops): pin the environment key per forge, and pin the additive claim to bytes (#2257) Fifteen new assertions across the three generators and the plan-on-pr example, all of them red against the parent commit: the key on github's job and its absence on the notice job beside it, the url form, forgejo's drop plus the header that says which environment did not survive, gitlab's own environment: mapping and its protected-environments header line, and the three refusals. Each generator additionally pins the exact document a spec with no environment emits, as a literal produced by the generator at the parent commit rather than by this one. That is what makes "additive" falsifiable: those three passed before the change and pass after it, so they are a byte comparison against the old output and not a tautology. --- .../components/generate-op-pipeline.test.ts | 79 +++++++++++ .../components/generate-op-pipeline.test.ts | 127 ++++++++++++++++++ .../components/generate-op-pipeline.test.ts | 82 +++++++++++ lexicons/terraform/examples/examples.test.ts | 53 ++++++++ 4 files changed, 341 insertions(+) diff --git a/lexicons/forgejo/src/components/generate-op-pipeline.test.ts b/lexicons/forgejo/src/components/generate-op-pipeline.test.ts index 860c362fbe..51dbfa676e 100644 --- a/lexicons/forgejo/src/components/generate-op-pipeline.test.ts +++ b/lexicons/forgejo/src/components/generate-op-pipeline.test.ts @@ -14,6 +14,7 @@ import type { ScheduledOpSpec } from "@intentius/chant/lexicon"; interface ParsedJob { "runs-on"?: string; + environment?: Record; outputs?: Record; steps: Array<{ id?: string; uses?: string; run?: string }>; } @@ -198,3 +199,81 @@ describe("generateForgejoOpPipeline: the gated apply on push (#2243)", () => { expect(gh.jobs).toHaveProperty("app-apply-gate-notice"); }); }); + +/** + * chant #2257 — the option Forgejo has no concept for at all. Unlike + * `permissions:`, which the runner reads and ignores, an environment is an + * object that does not exist on a Forgejo instance: no protection rules, no + * required reviewers, no wait timers. Emitting the key would read as a + * deployment gate and hold nothing back, so it is dropped — and, because the + * whole point of the option is a human holding an apply, the drop is said out + * loud in the file rather than only in a build warning. + */ +describe("generateForgejoOpPipeline: a dropped deployment environment (#2257)", () => { + const APPLY: ScheduledOpSpec = { name: "app-apply", trigger: { kind: "push", branches: ["main"] } }; + const GATED: ScheduledOpSpec = { ...APPLY, environment: { name: "production" } }; + + /** The document a spec with no `environment` emitted before the option existed. */ + const AUDIT_YAML_BEFORE_2257 = + [ + "on:", + " schedule:", + " - cron: '0 6 * * *'", + " workflow_dispatch: {}", + "", + "concurrency:", + " group: actions-audit", + " cancel-in-progress: false", + "", + "jobs:", + " actions-audit:", + " runs-on: docker", + " container: node:22-slim", + " steps:", + " - uses: https://code.forgejo.org/actions/checkout@v4", + " - run: chant run actions-audit", + " env:", + " GITHUB_TOKEN: '${{ github.token }}'", + " GH_TOKEN: '${{ github.token }}'", + ].join("\n") + "\n"; + + test("a spec with no environment emits the bytes it emitted before the option existed", () => { + const yaml = generateForgejoOpPipeline([ + { name: "actions-audit", schedule: "0 6 * * *", findingMode: "issue" }, + ]).files[0].yaml; + expect(yaml).toBe(AUDIT_YAML_BEFORE_2257); + }); + + test("drops the key, and github with the same spec keeps it", () => { + const fj = parseFile(generateForgejoOpPipeline([GATED]).files[0].yaml); + expect(fj.jobs!["app-apply"].environment).toBeUndefined(); + // A dialect drop, not a builder that never computed it. + expect(generateGithubOpPipeline([GATED]).files[0].yaml).toContain("environment:"); + }); + + test("says in the generated header which environment did not survive, and what still gates", () => { + const yaml = generateForgejoOpPipeline([GATED]).files[0].yaml; + expect(yaml.startsWith("# chant dropped `environment: production`")).toBe(true); + expect(yaml).toContain("Forgejo Actions has no"); + expect(yaml).toContain("not held back by anything on the forge"); + // The gate that does survive is chant's own, which needs nothing from the forge. + expect(yaml).toContain("chant/lifecycle"); + expect(yaml).toContain("approve "); + }); + + test("the header only appears for the Op that asked for an environment", () => { + const files = generateForgejoOpPipeline([ + { ...GATED, name: "app-apply" }, + { name: "app-watch", schedule: "0 6 * * *" }, + ]).files; + expect(files[0].yaml).toContain("# chant dropped `environment: production`"); + expect(files[1].yaml).not.toContain("# chant dropped"); + expect(files[1].yaml.startsWith("on:")).toBe(true); + }); + + test("refuses the same malformed environment github refuses, through the shared builder", () => { + expect(() => + generateForgejoOpPipeline([{ ...APPLY, environment: { name: "production", url: "/deploys" } }]), + ).toThrow(/neither an absolute http\(s\) URL nor a/); + }); +}); diff --git a/lexicons/github/src/components/generate-op-pipeline.test.ts b/lexicons/github/src/components/generate-op-pipeline.test.ts index 5ad0c04b12..5e62e01323 100644 --- a/lexicons/github/src/components/generate-op-pipeline.test.ts +++ b/lexicons/github/src/components/generate-op-pipeline.test.ts @@ -27,6 +27,7 @@ interface ParsedStep { interface ParsedJob { "runs-on"?: string; container?: string; + environment?: Record; needs?: string; if?: string; permissions?: Record; @@ -515,3 +516,129 @@ describe("generateGithubOpPipeline: the gated apply on push (#2243)", () => { expect(step?.run).toContain("set -o pipefail"); }); }); + +/** + * chant #2257 — the second gate. A GitHub environment carries its own + * protection rules (required reviewers above all), and until this existed no + * generated job named one, so a `production` environment declared in a + * repository bound nothing chant generated. What is asserted here is the key + * on the right job, the key's absence everywhere else, and that adding it + * changes nothing else in the document. + */ +describe("generateGithubOpPipeline: a deployment environment on the Op's job (#2257)", () => { + const APPLY: ScheduledOpSpec = { name: "app-apply", trigger: { kind: "push", branches: ["main"] } }; + const GATED: ScheduledOpSpec = { ...APPLY, environment: { name: "production" } }; + + /** + * The exact document a spec with no `environment` emitted before the option + * existed, produced by the generator at the commit this change branched + * from. The claim the option makes is that it is additive; this is what + * makes that claim falsifiable rather than a sentence in a PR body. + */ + const AUDIT_YAML_BEFORE_2257 = + [ + "on:", + " schedule:", + " - cron: '0 6 * * *'", + " workflow_dispatch: {}", + "", + "concurrency:", + " group: actions-audit", + " cancel-in-progress: false", + "", + "permissions:", + " contents: read", + " issues: write", + "", + "jobs:", + " actions-audit:", + " runs-on: ubuntu-latest", + " container: node:22-slim", + " steps:", + " - uses: actions/checkout@v4", + " - run: chant run actions-audit", + " env:", + " GITHUB_TOKEN: '${{ github.token }}'", + " GH_TOKEN: '${{ github.token }}'", + ].join("\n") + "\n"; + + test("a spec with no environment emits the bytes it emitted before the option existed", () => { + const yaml = generateGithubOpPipeline([ + { name: "actions-audit", schedule: "0 6 * * *", findingMode: "issue" }, + ]).files[0].yaml; + expect(yaml).toBe(AUDIT_YAML_BEFORE_2257); + }); + + test("emits environment: on the Op's job, as a mapping rather than the string shorthand", () => { + const job = parseFile(generateGithubOpPipeline([GATED]).files[0].yaml).jobs!["app-apply"]; + expect(job.environment).toEqual({ name: "production" }); + }); + + test("carries the url when the spec sets one", () => { + const spec: ScheduledOpSpec = { + ...APPLY, + environment: { name: "production", url: "https://app.example.com" }, + }; + const job = parseFile(generateGithubOpPipeline([spec]).files[0].yaml).jobs!["app-apply"]; + expect(job.environment).toEqual({ + name: "production", + url: "https://app.example.com", + }); + }); + + test("adding the environment changes exactly the environment block and nothing else", () => { + const before = generateGithubOpPipeline([APPLY]).files[0].yaml; + const after = generateGithubOpPipeline([GATED]).files[0].yaml; + expect(after).toContain(" environment:\n name: production\n"); + expect(after.replace(" environment:\n name: production\n", "")).toBe(before); + }); + + test("the gate-notice job is not held behind the same reviewer", () => { + // It exists to say a chant gate is pending. Behind the environment it + // would only be readable after somebody had already released the job it + // is reporting on, which is after the message stops being useful. + const notice = parseFile(generateGithubOpPipeline([GATED]).files[0].yaml).jobs![ + "app-apply-gate-notice" + ]; + expect(notice.environment).toBeUndefined(); + }); + + test("costs no token scope: environment protection is repository configuration", () => { + // `permissionsFor` gains nothing from the option — the reviewer lives on + // the environment object, not on GITHUB_TOKEN — so the workflow-level set + // is identical with and without it. + const withEnv = parseFile(generateGithubOpPipeline([GATED]).files[0].yaml); + const withoutEnv = parseFile(generateGithubOpPipeline([APPLY]).files[0].yaml); + expect(withEnv.permissions).toEqual(withoutEnv.permissions); + expect(withEnv.permissions).toEqual({ contents: "read" }); + }); + + test("applies to any trigger, so a pull_request plan can name a review environment too", () => { + const spec: ScheduledOpSpec = { + name: "app-plan", + trigger: { kind: "pull_request", branches: ["main"] }, + findingMode: "comment", + environment: { name: "review", url: "${{ steps.deploy.outputs.url }}" }, + }; + const job = parseFile(generateGithubOpPipeline([spec]).files[0].yaml).jobs!["app-plan"]; + expect(job.environment?.name).toBe("review"); + }); + + test("refuses a blank environment name, which resolves to nothing", () => { + expect(() => + generateGithubOpPipeline([{ ...APPLY, environment: { name: " " } }]), + ).toThrow(/environment has an empty `name`/); + }); + + test("refuses a url that is neither absolute nor an expression, which renders as a dead link", () => { + expect(() => + generateGithubOpPipeline([{ ...APPLY, environment: { name: "production", url: "/deploys" } }]), + ).toThrow(/neither an absolute http\(s\) URL nor a/); + }); + + test("refuses an empty url rather than emitting one", () => { + expect(() => + generateGithubOpPipeline([{ ...APPLY, environment: { name: "production", url: "" } }]), + ).toThrow(/has an empty `url`/); + }); +}); diff --git a/lexicons/gitlab/src/components/generate-op-pipeline.test.ts b/lexicons/gitlab/src/components/generate-op-pipeline.test.ts index 2b7ae104e4..70e4be2100 100644 --- a/lexicons/gitlab/src/components/generate-op-pipeline.test.ts +++ b/lexicons/gitlab/src/components/generate-op-pipeline.test.ts @@ -169,3 +169,85 @@ describe("generateGitlabOpPipeline: setup steps and additive permissions (#2242) ).toThrow(/adds permissions \{ id-token: write \}.*id_tokens:/s); }); }); + +/** + * chant #2257 — the one option of the three that GitLab actually has. An + * environment is a project object here too, with the same two fields on the + * job and a protected-environment approval rule behind it, so the reviewer + * gate the option exists for is expressible and is emitted rather than + * refused. What is not expressible is the protection itself, which is a + * project setting, so the header names it the way it already names the + * schedule to create. + */ +describe("generateGitlabOpPipeline: a deployment environment (#2257)", () => { + const AUDIT: ScheduledOpSpec = { name: "actions-audit", schedule: "0 6 * * *", findingMode: "issue" }; + + /** The document a spec with no `environment` emitted before the option existed. */ + const YAML_BEFORE_2257 = + [ + "# Scheduled Ops (chant #927) — GitLab has no in-file cron. Create one", + "# Pipeline Schedule per Op below (Settings > CI/CD > Schedules): set its", + "# cron to the value noted here and its CHANT_SCHEDULED_OP CI/CD variable to", + "# the Op's name, so only that job runs on that schedule.", + "#", + '# actions-audit: cron "0 6 * * *", CHANT_SCHEDULED_OP="actions-audit", finding-mode issue' + + " — needs a GITLAB_TOKEN CI/CD variable (masked, scope: api)", + "", + "stages:", + " - scheduled-ops", + "", + "actions-audit:", + " stage: scheduled-ops", + " image: node:22-slim", + " rules:", + ` - if: '$CI_PIPELINE_SOURCE == "schedule" && $CHANT_SCHEDULED_OP == "actions-audit"'`, + " script:", + " - chant run actions-audit", + ].join("\n") + "\n"; + + test("a spec with no environment emits the bytes it emitted before the option existed", () => { + expect(generateGitlabOpPipeline([AUDIT]).files[0].yaml).toBe(YAML_BEFORE_2257); + }); + + test("maps it onto GitLab's own environment: key, with the url when there is one", () => { + const spec: ScheduledOpSpec = { + ...AUDIT, + environment: { name: "production", url: "https://app.example.com" }, + }; + const job = parseYAML(generateGitlabOpPipeline([spec]).files[0].yaml)["actions-audit"] as { + environment?: Record; + }; + expect(job.environment).toEqual({ name: "production", url: "https://app.example.com" }); + }); + + test("names the environment to protect in the header, beside the schedule to create", () => { + const spec: ScheduledOpSpec = { ...AUDIT, environment: { name: "production" } }; + const yaml = generateGitlabOpPipeline([spec]).files[0].yaml; + expect(yaml).toContain('deploys to environment "production"'); + expect(yaml).toContain("Settings > CI/CD > Protected environments"); + // The approval rule is a project setting; this file can only bind the job + // to the environment, so the header says where the rule is set. + expect(yaml).toContain("require an approval before the job runs"); + }); + + test("adding the environment changes only the header line and the job's own key", () => { + const spec: ScheduledOpSpec = { ...AUDIT, environment: { name: "production" } }; + const after = generateGitlabOpPipeline([spec]).files[0].yaml; + const withoutHeaderLine = after + .split("\n") + .filter((line) => !line.startsWith("# deploys to environment")) + .join("\n"); + expect(withoutHeaderLine.replace(" environment:\n name: production\n", "")).toBe( + YAML_BEFORE_2257, + ); + }); + + test("refuses a blank name and a url that is neither absolute nor a variable expression", () => { + expect(() => generateGitlabOpPipeline([{ ...AUDIT, environment: { name: " " } }])).toThrow( + /environment has an empty `name`/, + ); + expect(() => + generateGitlabOpPipeline([{ ...AUDIT, environment: { name: "production", url: "/deploys" } }]), + ).toThrow(/neither an absolute http\(s\) URL nor a variable expression/); + }); +}); diff --git a/lexicons/terraform/examples/examples.test.ts b/lexicons/terraform/examples/examples.test.ts index 98ed74300e..c6cd5d0ddb 100644 --- a/lexicons/terraform/examples/examples.test.ts +++ b/lexicons/terraform/examples/examples.test.ts @@ -184,11 +184,23 @@ const PLAN_SPEC: ScheduledOpSpec = { permissions: { "id-token": "write" }, }; +/** + * The apply half additionally names a GitHub environment (#2257), which is + * the forge-native half of the pair of gates this example ships: a required + * reviewer on `production` holds the job before any step runs, and chant's + * own gate holds the apply inside a run that already started. The plan half + * names none — it deploys nothing, and putting a reviewer in front of a plan + * on every pull request is the fastest way to teach people to click through + * one. + */ +const APPLY_ENVIRONMENT = "production"; + const APPLY_SPEC: ScheduledOpSpec = { name: "app-apply", trigger: { kind: "push", branches: ["main"] }, setup: assumeRole("AWS_APPLY_ROLE_ARN"), permissions: { "id-token": "write" }, + environment: { name: APPLY_ENVIRONMENT }, }; async function planOnPrWorkflows(): Promise<{ plan: string; apply: string }> { @@ -219,6 +231,7 @@ interface WorkflowJob { if?: string; "runs-on"?: string; container?: string; + environment?: Record; permissions?: Record; outputs?: Record; steps: WorkflowStep[]; @@ -508,6 +521,46 @@ describe("plan-on-pr generates the pull_request plan and push apply pair (#2221) expect(script).toContain('"$CHANT_APPROVE"'); }); + // ── The forge-native gate beside chant's own (#2257) ──────────────────── + + it("puts the apply job behind a GitHub environment, and the plan job behind none", async () => { + const { plan, apply } = await planOnPrWorkflows(); + const parsed = parsePush(apply); + expect(parsed.jobs["app-apply"].environment).toEqual({ name: APPLY_ENVIRONMENT }); + // A required reviewer on `production` holds the apply before its first + // step. The plan deploys nothing, so it names no environment at all. + expect(plan).not.toContain("environment:"); + }); + + it("does not hold the pending-gate notice behind the same reviewer", async () => { + // The notice job says a chant gate is waiting. Behind the environment it + // would only be readable once somebody had already released the job it + // reports on. + const { apply } = await planOnPrWorkflows(); + expect(parsePush(apply).jobs["app-apply-gate-notice"].environment).toBeUndefined(); + }); + + it("buys the environment gate with no extra token scope", async () => { + // Environment protection is repository configuration — the reviewer lives + // on the environment object, not on GITHUB_TOKEN — so the apply's + // permission set is what it was before the environment was named. + const { apply } = await planOnPrWorkflows(); + const parsed = parsePush(apply); + expect(parsed.permissions).toEqual({ contents: "read", "id-token": "write" }); + expect(parsed.permissions).not.toHaveProperty("deployments"); + }); + + it("keeps chant's own gate in the run: the two gates compose, neither replaces the other", async () => { + // The environment reviewer stops the job before it starts; the gate below + // stops the apply inside a run that already started, on a fact recorded on + // the chant/lifecycle branch. Both are present in this example on purpose. + const { apply } = await planOnPrWorkflows(); + expect(runStep(parsePush(apply)).run).toContain("chant run app-apply --gated-exit 0 --json"); + const result = await build(join(planOnPrDir, "src"), [terraformSerializer]); + const applyOp = result.entities.get("app-apply") as unknown as { props: OpConfig }; + expect(applyOp.props.phases.map((p) => p.name)).toContain("Gate"); + }); + it("applies only the plan its own Plan step saved", async () => { const result = await build(join(planOnPrDir, "src"), [terraformSerializer]); const applyOp = result.entities.get("app-apply") as unknown as { props: OpConfig }; From 7f83f4f1e559dec399bb5cfeb6068824127d3635 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 7 Sep 2026 22:13:34 -0600 Subject: [PATCH 3/3] docs(ops): how the environment reviewer and chant's gate compose (#2257) The ops guide gains a "Two gates, and how they compose" section: the reviewer stops the job before it starts, so nothing is checked out and no role is assumed; chant's gate stops the apply inside a run that already started, on a plan that already exists, and is cleared by a commit rather than a button. Either alone is coherent, both is the usual production arrangement, and the choice is per environment. The per-Op options paragraph now covers all three and says what each provider does with the new one. The terraform ops page and the plan-on-pr README carry the worked version: the apply spec names `production`, the emitted YAML shows the key, and both say that the environment costs no token scope and that the pending-gate notice job stays outside it. The lexicon-authoring page tells a generator author that this is the option where a silent drop is worst. Regenerating the terraform docs twin also picked up a stale lexicon version line (0.57.0 to 0.59.0) that predates this branch. --- docs/src/content/docs/guide/ops.mdx | 18 +++++++- .../docs/lexicon-authoring/ci-integration.mdx | 23 +++++++--- lexicons/terraform/docs/pages/ops.mdx | 7 +++ .../terraform/docs/src/content/docs/index.mdx | 2 +- .../terraform/docs/src/content/docs/ops.mdx | 7 +++ .../terraform/examples/plan-on-pr/README.md | 44 +++++++++++++++++++ 6 files changed, 92 insertions(+), 9 deletions(-) diff --git a/docs/src/content/docs/guide/ops.mdx b/docs/src/content/docs/guide/ops.mdx index 9fdd0d0604..2322b50212 100644 --- a/docs/src/content/docs/guide/ops.mdx +++ b/docs/src/content/docs/guide/ops.mdx @@ -261,9 +261,11 @@ Any non-`report` mode on a `pull_request` trigger also gets `pull-requests: writ A fountain [`Steward`](/chant/lexicons/fountain/steward/) is the third: every op it lists that carries a cadence becomes a `Schedule` on the teammate, in-thread, and a fire that lands while a turn is running is dropped rather than queued. -Two per-Op options widen what the generated job can do without loosening that set ([#2242](https://github.com/INTENTIUS/chant/issues/2242)). `setup` is an ordered list of steps emitted between the checkout and the `beforeScript` lines, each either `{ uses, with?, env? }` or `{ run, env? }`. It is the only way a generated job reaches a marketplace action, and `aws-actions/configure-aws-credentials` is the motivating one. `permissions` is a map merged over the finding mode's own set, additively: it can add a scope no mode grants, `id-token: write` above all, and the github generator refuses at build time any entry that touches a scope the mode already granted, names `write-all`, names a scope GitHub does not define, or asks for `pull-requests: write` on a trigger with no pull request. A `setup` action reference has to be pinned to something other than the action repository's own default branch. A generated workflow is committed once and then re-run unattended over whatever role it assumes. +Three per-Op options sit beside the finding mode, two of them widening what the generated job can do without loosening that set ([#2242](https://github.com/INTENTIUS/chant/issues/2242)) and the third deciding who may let the job start at all ([#2257](https://github.com/INTENTIUS/chant/issues/2257)). `setup` is an ordered list of steps emitted between the checkout and the `beforeScript` lines, each either `{ uses, with?, env? }` or `{ run, env? }`. It is the only way a generated job reaches a marketplace action, and `aws-actions/configure-aws-credentials` is the motivating one. `permissions` is a map merged over the finding mode's own set, additively: it can add a scope no mode grants, `id-token: write` above all, and the github generator refuses at build time any entry that touches a scope the mode already granted, names `write-all`, names a scope GitHub does not define, or asks for `pull-requests: write` on a trigger with no pull request. A `setup` action reference has to be pinned to something other than the action repository's own default branch. A generated workflow is committed once and then re-run unattended over whatever role it assumes. -The two options land differently per provider. GitHub emits both. Forgejo emits the steps, since its runner runs `uses:` steps, and drops `permissions:` along with the mode's own scopes, because the Forgejo runner ignores the section and issues no OIDC token off a workflow permission. GitLab refuses both by name at build time: a `uses:` step has no GitLab equivalent (jobs run `script` lines, and a `{ run }` entry is emitted as one), and GitLab's OIDC surface is a separate `id_tokens:` declaration chant does not generate, so ignoring the map would emit a job that reads as having OIDC and runs with no credentials. +Those two land differently per provider. GitHub emits both. Forgejo emits the steps, since its runner runs `uses:` steps, and drops `permissions:` along with the mode's own scopes, because the Forgejo runner ignores the section and issues no OIDC token off a workflow permission. GitLab refuses both by name at build time: a `uses:` step has no GitLab equivalent (jobs run `script` lines, and a `{ run }` entry is emitted as one), and GitLab's OIDC surface is a separate `id_tokens:` declaration chant does not generate, so ignoring the map would emit a job that reads as having OIDC and runs with no credentials. + +The third option points the other way. `environment`, a `{ name, url? }`, emits `environment:` on that Op's job, which is how a GitHub environment's protection rules (required reviewers, a wait timer, a branch restriction) come to hold a generated apply. It costs no token scope, since environment protection is repository configuration rather than something `GITHUB_TOKEN` carries. Nothing about the environment itself is validated, because GitHub creates an unprotected one on first use rather than failing, so whether reviewers exist cannot be answered from workflow content. What the generator refuses is only the shape that could never bind, meaning a blank name or a `url` that is neither absolute nor an expression the run resolves. GitLab has the same key with the same two fields and a protected environment's approval rule behind it, so it maps across, and the generated header names the environment to protect since the rule is a project setting this file cannot declare. Forgejo Actions has no environments at all, so the key is dropped **and** the generated file gains a header comment naming the environment that was asked for and stating that nothing on the forge enforces it. That is the one option where a silent drop would be worst, because the whole point of it is a human holding an apply. A `ScheduledOpSpec` isn't limited to cron. Its `trigger` also takes `{ kind: "pull_request", branches? }` and `{ kind: "push", branches? }`, for an Op whose CI trigger is a PR or a push rather than a clock (a Terraform `plan` on `pull_request`, posted as a PR comment, paired with `apply` on `push` to the default branch, is the motivating case). GitHub and Forgejo support all three trigger kinds; GitLab, which has no `pull_request`/`push` event model, throws a clear error if given anything but cron. @@ -277,6 +279,18 @@ A `push` job is the one that has to survive a gate. GitHub Actions has no neutra Forgejo takes the first two and drops the third: the notice job shells to `gh`, which a Forgejo runner neither ships nor can point at its own instance, the same reason `comment` mode is refused there. GitLab takes none of it, because its Op generator has no push pipeline to attach them to. +### Two gates, and how they compose + +An Op with an `environment` on a forge that has environments is behind two gates, and they stop different things at different moments. + +The **environment reviewer** stops the job before it starts. Nothing is checked out and no credentials are minted; the run sits in the forge's own queue showing "waiting for review" until somebody with access to that environment releases it. It is the forge's gate, configured on the forge, and it applies to whatever the job does, chant included. + +**chant's own gate** ([#2119](https://github.com/INTENTIUS/chant/issues/2119)) stops the apply inside a run that already started. The Op plans and reaches its Gate phase. Finding no resolution on the gate ledger, it records a pending fact on the `chant/lifecycle` branch and ends there. Nothing is held open in between. `chant approve --approver you` records the answer as another fact on that branch, and the next run reads it and applies. Because it is a fact rather than a held connection, the decision survives the run that asked for it, and the approver is reading a plan that already exists rather than a promise of one. + +That difference is the reason to want both. The environment reviewer answers whether this job may run at all, cheaply and before any cost is incurred. chant's gate answers whether this exact plan should be applied, which nothing can answer before the job has run far enough to produce the plan. Either alone is coherent. The reviewer alone is the forge-native shape a team already knows, with `gate: "never"` on the root; chant's gate alone needs no forge features and works identically on Forgejo, where there are none. Neither, for a root whose merges should apply unattended, is also a choice. The choice is per environment, so a `staging` environment with no protection and `gate: "never"` sits happily beside a `production` environment with two reviewers and a gated apply. + +The follow-up job that reports a pending chant gate stays outside the environment. It exists to say an approval is waiting, and behind the same reviewer it would only become readable after somebody had already acted. + ## Replay (policy drift) `PolicyReplayOp` is the same shape applied to authorization policy. A [dogwood](/chant/lexicons/cedar/) `.dw` policy set carries time-window clauses — `formerly within 1h …` — so what a policy decides depends on a history the build cannot see. Replaying the declared set against a recorded event trace is how that gets checked, and the answer moves as the history does. diff --git a/docs/src/content/docs/lexicon-authoring/ci-integration.mdx b/docs/src/content/docs/lexicon-authoring/ci-integration.mdx index 9c156619a9..64b0f94ba0 100644 --- a/docs/src/content/docs/lexicon-authoring/ci-integration.mdx +++ b/docs/src/content/docs/lexicon-authoring/ci-integration.mdx @@ -222,14 +222,25 @@ in `packages/core/src/lexicon.ts:441`. `generateOpPipeline` is the cron-triggered sibling for scheduled Ops (chant #927), with the same "CI providers only" rule. It receives `ScheduledOpSpec[]` -rather than components, and each spec can carry two things the options block +rather than components, and each spec can carry three things the options block cannot, because they are per Op: `setup`, an ordered list of `{ uses, with?, -env? }` / `{ run, env? }` steps emitted ahead of the `beforeScript` lines, and +env? }` / `{ run, env? }` steps emitted ahead of the `beforeScript` lines, `permissions`, a map your generator merges additively over whatever the -finding mode already grants (chant #2242). A provider with no equivalent -degrades by name at build time rather than dropping the option: gitlab refuses -a `uses` entry and an additive `permissions` map, forgejo emits the steps and -drops the permissions the way it already drops the mode's own. +finding mode already grants (chant #2242), and `environment`, a `{ name, url? +}` naming the forge deployment environment the job runs in (chant #2257). A +provider with no equivalent degrades by name at build time rather than +dropping the option: gitlab refuses a `uses` entry and an additive +`permissions` map, forgejo emits the steps and drops the permissions the way +it already drops the mode's own. + +`environment` is the one of the three where a silent drop would be worst, +because the option exists so a human can hold a job. A provider without +environments therefore both drops the key and says so in the file it +generates; forgejo writes a header comment naming the environment and stating +that nothing on the forge enforces it. GitLab does have environments, and maps +the option onto its own `environment:` key. If your provider has the concept, +emit it and let the protection rules stay where they live, in the provider's +own configuration. If it does not, be loud. Each job is a **thin trigger**: it runs the component's deploy command. The deploy logic stays in the component, not in the generated YAML — the whole point diff --git a/lexicons/terraform/docs/pages/ops.mdx b/lexicons/terraform/docs/pages/ops.mdx index 27221be78e..05058c5317 100644 --- a/lexicons/terraform/docs/pages/ops.mdx +++ b/lexicons/terraform/docs/pages/ops.mdx @@ -179,6 +179,7 @@ const { files } = await generateOpsPipeline( trigger: { kind: "push", branches: ["main"] }, setup: assumeRole("AWS_APPLY_ROLE_ARN"), permissions: { "id-token": "write" }, + environment: { name: "production" }, }, ], "github", @@ -207,6 +208,8 @@ jobs: app-apply: runs-on: ubuntu-latest container: node:22-slim + environment: + name: production outputs: gated: '${{ steps.chant-run.outputs.gated }}' op: '${{ steps.chant-run.outputs.op }}' @@ -271,6 +274,10 @@ The pending state also leaves the Actions log. The `app-apply-gate-notice` job a Forgejo takes the mapping and the step summary and drops the notice job: it shells to `gh`, which no Forgejo runner points at its own instance, the same reason `comment` mode is refused there. GitLab takes neither, since its Op generator refuses a `push` trigger outright. +**The apply also runs in a GitHub environment, which is a second gate in front of the first** ([#2257](https://github.com/INTENTIUS/chant/issues/2257)). `environment: { name: "production" }` on the apply spec emits `environment: production` on that job, and a `production` environment configured in the repository with required reviewers then holds the job before its first step. The two gates stop different things. The reviewer stops the job from starting at all, so nothing is checked out and no role is assumed until somebody releases it; chant's gate stops the apply inside a run that already started, on a plan that already exists, and is cleared by a `chant approve` commit rather than by a button. Wanting both is the common case, and neither is required by the other: the reviewer alone pairs with `gate: "never"` on the root, and chant's gate alone is what a Forgejo estate gets, since Forgejo Actions has no environments and its generator drops the key with a header comment saying so. The plan half names no environment, because it deploys nothing and a reviewer prompt on every pull request is the fastest way to teach people to click through one. + +The environment costs no permission. Protection rules live on the environment object in repository settings, not on `GITHUB_TOKEN`, so the apply job's `permissions:` are the same `contents: read` and `id-token: write` they were without it. The `app-apply-gate-notice` job stays outside the environment on purpose: it exists to say a chant gate is pending, and behind the same reviewer it would only be readable after somebody had already acted. + `examples/plan-on-pr/` is the worked version of this shape, and `examples/scheduled-watch/` is the cron one. ## Reconcile: adoption, not regeneration diff --git a/lexicons/terraform/docs/src/content/docs/index.mdx b/lexicons/terraform/docs/src/content/docs/index.mdx index e65db93df1..4426863b42 100644 --- a/lexicons/terraform/docs/src/content/docs/index.mdx +++ b/lexicons/terraform/docs/src/content/docs/index.mdx @@ -34,7 +34,7 @@ mapping, and what TF001 reports. | Pseudo-parameters | 0 | | Lint rules | 28 | -**Lexicon version:** 0.57.0 +**Lexicon version:** 0.59.0 **Namespace:** `Terraform` - [All Rules](./rules) — 28 rules diff --git a/lexicons/terraform/docs/src/content/docs/ops.mdx b/lexicons/terraform/docs/src/content/docs/ops.mdx index 5fb55f4ab6..877439fdbc 100644 --- a/lexicons/terraform/docs/src/content/docs/ops.mdx +++ b/lexicons/terraform/docs/src/content/docs/ops.mdx @@ -183,6 +183,7 @@ const { files } = await generateOpsPipeline( trigger: { kind: "push", branches: ["main"] }, setup: assumeRole("AWS_APPLY_ROLE_ARN"), permissions: { "id-token": "write" }, + environment: { name: "production" }, }, ], "github", @@ -211,6 +212,8 @@ jobs: app-apply: runs-on: ubuntu-latest container: node:22-slim + environment: + name: production outputs: gated: '${{ steps.chant-run.outputs.gated }}' op: '${{ steps.chant-run.outputs.op }}' @@ -275,6 +278,10 @@ The pending state also leaves the Actions log. The `app-apply-gate-notice` job a Forgejo takes the mapping and the step summary and drops the notice job: it shells to `gh`, which no Forgejo runner points at its own instance, the same reason `comment` mode is refused there. GitLab takes neither, since its Op generator refuses a `push` trigger outright. +**The apply also runs in a GitHub environment, which is a second gate in front of the first** ([#2257](https://github.com/INTENTIUS/chant/issues/2257)). `environment: { name: "production" }` on the apply spec emits `environment: production` on that job, and a `production` environment configured in the repository with required reviewers then holds the job before its first step. The two gates stop different things. The reviewer stops the job from starting at all, so nothing is checked out and no role is assumed until somebody releases it; chant's gate stops the apply inside a run that already started, on a plan that already exists, and is cleared by a `chant approve` commit rather than by a button. Wanting both is the common case, and neither is required by the other: the reviewer alone pairs with `gate: "never"` on the root, and chant's gate alone is what a Forgejo estate gets, since Forgejo Actions has no environments and its generator drops the key with a header comment saying so. The plan half names no environment, because it deploys nothing and a reviewer prompt on every pull request is the fastest way to teach people to click through one. + +The environment costs no permission. Protection rules live on the environment object in repository settings, not on `GITHUB_TOKEN`, so the apply job's `permissions:` are the same `contents: read` and `id-token: write` they were without it. The `app-apply-gate-notice` job stays outside the environment on purpose: it exists to say a chant gate is pending, and behind the same reviewer it would only be readable after somebody had already acted. + `examples/plan-on-pr/` is the worked version of this shape, and `examples/scheduled-watch/` is the cron one. ## Reconcile: adoption, not regeneration diff --git a/lexicons/terraform/examples/plan-on-pr/README.md b/lexicons/terraform/examples/plan-on-pr/README.md index abe992527d..1acf163b0b 100644 --- a/lexicons/terraform/examples/plan-on-pr/README.md +++ b/lexicons/terraform/examples/plan-on-pr/README.md @@ -41,6 +41,7 @@ const { files } = await generateOpsPipeline( trigger: { kind: "push", branches: ["main"] }, setup: assumeRole("AWS_APPLY_ROLE_ARN"), permissions: { "id-token": "write" }, + environment: { name: "production" }, }, ], "github", @@ -167,3 +168,46 @@ that lookup answers with nothing — a direct push to the branch — it opens an issue instead, which is why it carries `issues: write` beside `pull-requests: write`. Those permissions sit on that job, so the apply next to it stays `contents: read`. + +## The environment reviewer, and the gate inside the run + +The apply spec also names a GitHub environment, `production`, which the github +generator emits as `environment: production` on that job: + +```yaml +jobs: + app-apply: + runs-on: ubuntu-latest + environment: + name: production +``` + +That is the forge-native half of a pair of gates, and the two stop different +things at different moments. Configure `production` in the repository's +Settings > Environments with a required reviewer, and the job never starts: +nothing is checked out, the apply role is never assumed, and the run sits +showing "waiting for review" until somebody with access releases it. chant's +own gate runs later and inside the job. The Op inits, plans, reaches its Gate +phase, finds no resolution on the ledger and records the pending fact, so the +approver is reading a plan that already exists rather than approving the idea +of one, and `chant approve app-apply approve-app-apply --approver you` is a +commit rather than a button. + +Wanting both is the usual arrangement on a production root, and neither needs +the other. The reviewer alone pairs with `gate: "never"`, which is the +forge-native shape a team already knows. chant's gate alone needs no forge +feature at all, which is what a Forgejo estate gets: Forgejo Actions has no +environments, so its Op generator drops the key and writes a header comment +into the generated file saying the environment was asked for and that nothing +on the forge enforces it. The choice is per environment, so a `staging` root +with no protection and `gate: "never"` sits happily beside this one. + +The plan half names no environment. It deploys nothing, and a reviewer prompt +on every pull request is the fastest way to teach people to click through one. + +None of this costs a permission. Protection rules live on the environment +object in repository settings rather than on `GITHUB_TOKEN`, so the apply job's +scopes are the same `contents: read` and `id-token: write` they were before the +environment was named. `app-apply-gate-notice` stays outside the environment +too: it exists to say the chant gate is pending, and behind the same reviewer +it would only be readable once somebody had already acted.