From fad4d650d650541907db30e6b820fdaba675b808 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Wed, 26 Aug 2026 13:40:38 -0600 Subject: [PATCH] feat(audit): efficiency finding dimension + initial wasteful-configuration rules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a fourth audit finding dimension, "efficiency" (#444), alongside security/correctness/best-practice: wasteful CI configuration that isn't a safety or correctness issue. Wired end to end: - catalog.ts: Category gains "efficiency" - report-model.ts: ReportCounts.efficiency tallied separately (disjoint from security/correctness by construction — proven with a dedicated test) - report.ts / report-html.ts: the category tally/chips surface the new count Initial rules (all report-only/guidance — efficiency findings default to the lower-urgency tier): github: GHA059 (dependency setup action without caching), GHA060 (runner pricier than the job needs), GHA061 (uncapped multiplicative matrix fan-out), GHA062 (unbounded artifact retention), GHA063 (unconditional docker build with no path filter/guard), GHA064 (pull-request workflow missing a concurrency group — deploy workflows stay with GHA024) gitlab: WGL049 (dependency install without a cache), WGL050 (merge-request job missing interruptible: true) Docs regenerated via renderRulesReference(); post-synth barrels regenerated via generate-post-synth-barrels.ts. Positive/negative tests per rule plus a report-model test proving efficiency findings don't leak into the security/correctness tallies. Fixes #444 Co-Authored-By: Claude Fable 5 --- .../content/docs/lint-rules/audit-rules.mdx | 48 +++++++ lexicons/github/src/lint/audit-catalog.ts | 9 ++ .../github/src/lint/post-synth/gha063.test.ts | 86 ++++++++++++ lexicons/github/src/lint/post-synth/gha063.ts | 60 ++++++++ .../github/src/lint/post-synth/gha064.test.ts | 73 ++++++++++ lexicons/github/src/lint/post-synth/gha064.ts | 55 ++++++++ .../github/src/lint/post-synth/gha065.test.ts | 85 ++++++++++++ lexicons/github/src/lint/post-synth/gha065.ts | 129 ++++++++++++++++++ .../github/src/lint/post-synth/gha066.test.ts | 66 +++++++++ lexicons/github/src/lint/post-synth/gha066.ts | 47 +++++++ .../github/src/lint/post-synth/gha067.test.ts | 85 ++++++++++++ lexicons/github/src/lint/post-synth/gha067.ts | 76 +++++++++++ .../github/src/lint/post-synth/gha068.test.ts | 71 ++++++++++ lexicons/github/src/lint/post-synth/gha068.ts | 51 +++++++ lexicons/github/src/lint/post-synth/index.ts | 12 ++ .../src/lint/post-synth/yaml-helpers.ts | 30 ++-- lexicons/github/src/plugin.test.ts | 2 +- lexicons/gitlab/src/lint/audit-catalog.ts | 5 + lexicons/gitlab/src/lint/post-synth/index.ts | 4 + .../gitlab/src/lint/post-synth/wgl049.test.ts | 71 ++++++++++ lexicons/gitlab/src/lint/post-synth/wgl049.ts | 57 ++++++++ .../gitlab/src/lint/post-synth/wgl050.test.ts | 57 ++++++++ lexicons/gitlab/src/lint/post-synth/wgl050.ts | 49 +++++++ lexicons/gitlab/src/plugin.test.ts | 2 +- packages/core/src/audit/catalog.test.ts | 2 +- packages/core/src/audit/catalog.ts | 9 +- packages/core/src/audit/report-html.ts | 2 +- packages/core/src/audit/report-model.ts | 3 + packages/core/src/audit/report.test.ts | 22 +++ packages/core/src/audit/report.ts | 2 +- 30 files changed, 1248 insertions(+), 22 deletions(-) create mode 100644 lexicons/github/src/lint/post-synth/gha063.test.ts create mode 100644 lexicons/github/src/lint/post-synth/gha063.ts create mode 100644 lexicons/github/src/lint/post-synth/gha064.test.ts create mode 100644 lexicons/github/src/lint/post-synth/gha064.ts create mode 100644 lexicons/github/src/lint/post-synth/gha065.test.ts create mode 100644 lexicons/github/src/lint/post-synth/gha065.ts create mode 100644 lexicons/github/src/lint/post-synth/gha066.test.ts create mode 100644 lexicons/github/src/lint/post-synth/gha066.ts create mode 100644 lexicons/github/src/lint/post-synth/gha067.test.ts create mode 100644 lexicons/github/src/lint/post-synth/gha067.ts create mode 100644 lexicons/github/src/lint/post-synth/gha068.test.ts create mode 100644 lexicons/github/src/lint/post-synth/gha068.ts create mode 100644 lexicons/gitlab/src/lint/post-synth/wgl049.test.ts create mode 100644 lexicons/gitlab/src/lint/post-synth/wgl049.ts create mode 100644 lexicons/gitlab/src/lint/post-synth/wgl050.test.ts create mode 100644 lexicons/gitlab/src/lint/post-synth/wgl050.ts diff --git a/docs/src/content/docs/lint-rules/audit-rules.mdx b/docs/src/content/docs/lint-rules/audit-rules.mdx index 723d6c1db2..1753083141 100644 --- a/docs/src/content/docs/lint-rules/audit-rules.mdx +++ b/docs/src/content/docs/lint-rules/audit-rules.mdx @@ -364,6 +364,42 @@ Bump the reference to a patched ref/commit named by the advisory. Authority: [OSSF Scorecard — Vulnerabilities](https://github.com/ossf/scorecard/blob/main/docs/checks.md#vulnerabilities) +### GHA063 + +**Dependency setup action without caching enabled** — report-only · guidance + +Enable the setup action's `cache:` option or add an actions/cache step. + +### GHA064 + +**Expensive runner without justification** — report-only · guidance + +Confirm the job needs that OS, or move it to a Linux runner. + +### GHA065 + +**Unbounded matrix fan-out** — report-only · guidance + +Trim the matrix with include/exclude, or cap it with max-parallel. + +### GHA066 + +**Unbounded artifact retention** — report-only · guidance + +Set a retention-days sized to how long the artifact is actually needed. + +### GHA067 + +**Unconditional heavy step with no path filter** — report-only · guidance + +Scope the trigger's paths, or add an if: guard to the step. + +### GHA068 + +**Pull-request workflow missing a concurrency group** — report-only · guidance + +Add a concurrency group with cancel-in-progress: true. + ## GitLab CI (WGL) ### WGL010 @@ -634,6 +670,18 @@ Authority: [OSSF Scorecard — Pinned-Dependencies](https://github.com/ossf/scor Add a `workflow:name` for clearer pipeline naming. +### WGL049 + +**Dependency install without a cache** — report-only · guidance + +Add a `cache:` covering the dependency directory. + +### WGL050 + +**Merge-request job missing interruptible** — report-only · guidance + +Add `interruptible: true` so a superseded pipeline can be cancelled. + ## Forgejo (WFJ) ### WFJ010 diff --git a/lexicons/github/src/lint/audit-catalog.ts b/lexicons/github/src/lint/audit-catalog.ts index cedbe3cfac..e38a91daa9 100644 --- a/lexicons/github/src/lint/audit-catalog.ts +++ b/lexicons/github/src/lint/audit-catalog.ts @@ -56,4 +56,13 @@ export const githubAuditCatalog: Record = { GHA060: auditRule("GHA060", "merge-worthy", "guidance", "Over-scoped generated token", "Narrow the GitHub App token's permission-* inputs to the scopes its consuming steps actually use, or remove the unused ones.", { authority: [SCORECARD_TOKEN, GH_TOKEN] }), GHA061: auditRule("GHA061", "merge-worthy", "guidance", "Action reference outside the configured usage policy", "Replace the reference with one from the approved allowlist, or get it added if it should be trusted.", { category: "security" }), GHA062: auditRule("GHA062", "merge-worthy", "guidance", "Pinned reference matches a known-vulnerability advisory", "Bump the reference to a patched ref/commit named by the advisory.", { authority: [SCORECARD_VULN] }), + + // Efficiency (#444) — waste, not a safety/correctness issue. Always + // report-only: none of these warrant a merge on their own. + GHA063: auditRule("GHA063", "report-only", "guidance", "Dependency setup action without caching enabled", "Enable the setup action's `cache:` option or add an actions/cache step.", { category: "efficiency" }), + GHA064: auditRule("GHA064", "report-only", "guidance", "Expensive runner without justification", "Confirm the job needs that OS, or move it to a Linux runner.", { category: "efficiency" }), + GHA065: auditRule("GHA065", "report-only", "guidance", "Unbounded matrix fan-out", "Trim the matrix with include/exclude, or cap it with max-parallel.", { category: "efficiency" }), + GHA066: auditRule("GHA066", "report-only", "guidance", "Unbounded artifact retention", "Set a retention-days sized to how long the artifact is actually needed.", { category: "efficiency" }), + GHA067: auditRule("GHA067", "report-only", "guidance", "Unconditional heavy step with no path filter", "Scope the trigger's paths, or add an if: guard to the step.", { category: "efficiency" }), + GHA068: auditRule("GHA068", "report-only", "guidance", "Pull-request workflow missing a concurrency group", "Add a concurrency group with cancel-in-progress: true.", { category: "efficiency" }), }; diff --git a/lexicons/github/src/lint/post-synth/gha063.test.ts b/lexicons/github/src/lint/post-synth/gha063.test.ts new file mode 100644 index 0000000000..168c8e3eb1 --- /dev/null +++ b/lexicons/github/src/lint/post-synth/gha063.test.ts @@ -0,0 +1,86 @@ +import { describe, test, expect } from "vitest"; +import type { PostSynthContext } from "@intentius/chant/lint/post-synth"; +import { gha063 } from "./gha063"; + +function makeCtx(yaml: string): PostSynthContext { + return { + outputs: new Map([["github", yaml]]), + entities: new Map(), + buildResult: { outputs: new Map([["github", yaml]]), entities: new Map(), warnings: [], errors: [], sourceFileCount: 1 }, + }; +} + +describe("GHA063: dependency setup without caching", () => { + test("flags setup-node with no cache option and no cache step", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "20" + - run: npm ci +`; + const diags = gha063.check(makeCtx(yaml)); + expect(diags).toHaveLength(1); + expect(diags[0].checkId).toBe("GHA063"); + expect(diags[0].entity).toBe("build"); + }); + + test("does not flag setup-node with cache enabled", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "20" + cache: npm + - run: npm ci +`; + expect(gha063.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag setup-node when a separate actions/cache step covers it", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "20" + - uses: actions/cache@v4 + with: + path: ~/.npm + key: npm-\${{ hashFiles('package-lock.json') }} + - run: npm ci +`; + expect(gha063.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a job with no setup action at all", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: make build +`; + expect(gha063.check(makeCtx(yaml))).toHaveLength(0); + }); +}); diff --git a/lexicons/github/src/lint/post-synth/gha063.ts b/lexicons/github/src/lint/post-synth/gha063.ts new file mode 100644 index 0000000000..00a9b5f4fc --- /dev/null +++ b/lexicons/github/src/lint/post-synth/gha063.ts @@ -0,0 +1,60 @@ +/** + * GHA063: Dependency Setup Without Caching + * + * Flags a `actions/setup-{node,python,java,ruby,dotnet}` step that leaves its + * built-in `cache:` option unset, with no adjacent `actions/cache` step to + * cover the gap. Every run re-downloads the same dependencies from the + * registry from a cold cache — pure wasted time and bandwidth, not a + * correctness or security issue (efficiency, #444). + */ + +import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth"; +import { getPrimaryOutput, jobEntries, parseActionUses } from "./yaml-helpers"; + +/** Setup actions whose `with.cache` option enables built-in dependency caching. */ +const CACHEABLE_SETUP_ACTIONS = new Set(["actions/setup-node", "actions/setup-python", "actions/setup-java", "actions/setup-ruby", "actions/setup-dotnet"]); + +function cacheEnabled(withBlock: unknown): boolean { + if (!withBlock || typeof withBlock !== "object") return false; + const cache = (withBlock as Record).cache; + if (typeof cache === "boolean") return cache; + if (typeof cache === "string") return cache.trim().length > 0 && cache.trim() !== "false"; + return false; +} + +export const gha063: PostSynthCheck = { + id: "GHA063", + description: "Dependency setup action without caching enabled", + + check(ctx: PostSynthContext): PostSynthDiagnostic[] { + const diagnostics: PostSynthDiagnostic[] = []; + + for (const [, output] of ctx.outputs) { + const yaml = getPrimaryOutput(output); + + for (const [jobName, jobObj] of jobEntries(yaml)) { + const steps = Array.isArray(jobObj.steps) ? (jobObj.steps as Array>) : []; + const hasGenericCacheStep = steps.some((s) => parseActionUses(String(s.uses ?? ""))?.slug === "actions/cache"); + if (hasGenericCacheStep) continue; + + for (const step of steps) { + const uses = typeof step.uses === "string" ? step.uses : undefined; + if (!uses) continue; + const parsed = parseActionUses(uses); + if (!parsed || !CACHEABLE_SETUP_ACTIONS.has(parsed.slug)) continue; + if (cacheEnabled(step.with)) continue; + + diagnostics.push({ + checkId: "GHA063", + severity: "info", + message: `Job "${jobName}" uses ${parsed.slug} without enabling its \`cache:\` option, and no separate actions/cache step covers it — dependencies are re-fetched from a cold cache on every run. Set \`with.cache\` (e.g. \`cache: npm\`) or add an actions/cache step.`, + entity: jobName, + lexicon: "github", + }); + } + } + } + + return diagnostics; + }, +}; diff --git a/lexicons/github/src/lint/post-synth/gha064.test.ts b/lexicons/github/src/lint/post-synth/gha064.test.ts new file mode 100644 index 0000000000..0d93cc570b --- /dev/null +++ b/lexicons/github/src/lint/post-synth/gha064.test.ts @@ -0,0 +1,73 @@ +import { describe, test, expect } from "vitest"; +import type { PostSynthContext } from "@intentius/chant/lint/post-synth"; +import { gha064 } from "./gha064"; + +function makeCtx(yaml: string): PostSynthContext { + return { + outputs: new Map([["github", yaml]]), + entities: new Map(), + buildResult: { outputs: new Map([["github", yaml]]), entities: new Map(), warnings: [], errors: [], sourceFileCount: 1 }, + }; +} + +describe("GHA064: expensive runner without justification", () => { + test("flags a macOS runner with no macOS-specific step", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + runs-on: macos-latest + steps: + - uses: actions/checkout@v4 + - run: npm test +`; + const diags = gha064.check(makeCtx(yaml)); + expect(diags).toHaveLength(1); + expect(diags[0].checkId).toBe("GHA064"); + expect(diags[0].entity).toBe("build"); + }); + + test("does not flag macOS when a step is Xcode-specific", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + runs-on: macos-latest + steps: + - uses: actions/checkout@v4 + - run: xcodebuild -scheme App build +`; + expect(gha064.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag runs-on driven by a matrix expression", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: \${{ matrix.os }} + steps: + - run: npm test +`; + expect(gha064.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a Linux runner", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + runs-on: ubuntu-latest + steps: + - run: npm test +`; + expect(gha064.check(makeCtx(yaml))).toHaveLength(0); + }); +}); diff --git a/lexicons/github/src/lint/post-synth/gha064.ts b/lexicons/github/src/lint/post-synth/gha064.ts new file mode 100644 index 0000000000..da00868d86 --- /dev/null +++ b/lexicons/github/src/lint/post-synth/gha064.ts @@ -0,0 +1,55 @@ +/** + * GHA064: Expensive Runner Without Justification + * + * Flags a job hardcoded onto a pricier macOS/Windows runner (billed at a + * multiple of Linux minutes) when none of its `run:` steps show any sign the + * job actually needs that OS. A matrix-driven `runs-on: ${{ matrix.os }}` + * (intentional cross-platform testing) is never flagged — only a literal, + * hardcoded label. Efficiency (#444), not a correctness/security issue. + */ + +import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth"; +import { getPrimaryOutput, extractRunsOnByJob, extractRunBlocks } from "./yaml-helpers"; + +const OS_JUSTIFICATION: Array<{ prefix: string; label: string; keywords: RegExp }> = [ + { prefix: "macos-", label: "macOS", keywords: /xcodebuild|xcode-select|\.xcodeproj|\.xcworkspace|carthage|fastlane|cocoapods|pod install|swiftpm|codesign|notarize/i }, + { prefix: "windows-", label: "Windows", keywords: /msbuild|\.sln\b|\.ps1\b|vcvarsall|nuget\s|choco\s|Set-ItemProperty|Get-ChildItem/i }, +]; + +export const gha064: PostSynthCheck = { + id: "GHA064", + description: "Job hardcoded onto an expensive runner with no sign it needs that OS", + + check(ctx: PostSynthContext): PostSynthDiagnostic[] { + const diagnostics: PostSynthDiagnostic[] = []; + + for (const [, output] of ctx.outputs) { + const yaml = getPrimaryOutput(output); + const runsOnByJob = extractRunsOnByJob(yaml); + const runBlocks = extractRunBlocks(yaml); + + for (const [jobName, labels] of runsOnByJob) { + if (labels.some((l) => l.includes("${{"))) continue; // matrix/expression-driven — intentional + + for (const { prefix, label, keywords } of OS_JUSTIFICATION) { + const matched = labels.find((l) => l.toLowerCase().startsWith(prefix)); + if (!matched) continue; + + const justified = runBlocks.some((r) => r.job === jobName && keywords.test(r.run)); + if (justified) break; + + diagnostics.push({ + checkId: "GHA064", + severity: "info", + message: `Job "${jobName}" runs on "${matched}" (a pricier ${label} runner) but no step looks ${label}-specific. Confirm it needs ${label}, or move it to a Linux runner.`, + entity: jobName, + lexicon: "github", + }); + break; + } + } + } + + return diagnostics; + }, +}; diff --git a/lexicons/github/src/lint/post-synth/gha065.test.ts b/lexicons/github/src/lint/post-synth/gha065.test.ts new file mode 100644 index 0000000000..35292b2f90 --- /dev/null +++ b/lexicons/github/src/lint/post-synth/gha065.test.ts @@ -0,0 +1,85 @@ +import { describe, test, expect } from "vitest"; +import type { PostSynthContext } from "@intentius/chant/lint/post-synth"; +import { gha065 } from "./gha065"; + +function makeCtx(yaml: string): PostSynthContext { + return { + outputs: new Map([["github", yaml]]), + entities: new Map(), + buildResult: { outputs: new Map([["github", yaml]]), entities: new Map(), warnings: [], errors: [], sourceFileCount: 1 }, + }; +} + +describe("GHA065: unbounded matrix fan-out", () => { + test("flags a large multi-dimension matrix with no max-parallel", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + node: [14, 16, 18, 20, 22] + runs-on: \${{ matrix.os }} + steps: + - run: npm test +`; + const diags = gha065.check(makeCtx(yaml)); + expect(diags).toHaveLength(1); + expect(diags[0].checkId).toBe("GHA065"); + expect(diags[0].entity).toBe("build"); + expect(diags[0].message).toContain("15 jobs"); + }); + + test("does not flag when max-parallel caps the fan-out", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + strategy: + max-parallel: 4 + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + node: [14, 16, 18, 20, 22] + runs-on: \${{ matrix.os }} + steps: + - run: npm test +`; + expect(gha065.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a small matrix under the threshold", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + strategy: + matrix: + os: [ubuntu-latest, macos-latest] + node: [18, 20] + runs-on: \${{ matrix.os }} + steps: + - run: npm test +`; + expect(gha065.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a single-dimension matrix", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + strategy: + matrix: + node: [16, 18, 20, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22] + runs-on: ubuntu-latest + steps: + - run: npm test +`; + expect(gha065.check(makeCtx(yaml))).toHaveLength(0); + }); +}); diff --git a/lexicons/github/src/lint/post-synth/gha065.ts b/lexicons/github/src/lint/post-synth/gha065.ts new file mode 100644 index 0000000000..47dd71c50e --- /dev/null +++ b/lexicons/github/src/lint/post-synth/gha065.ts @@ -0,0 +1,129 @@ +/** + * GHA065: Unbounded Matrix Fan-Out + * + * Flags a `strategy.matrix` that combines two or more dimensions into more + * jobs than a `max-parallel:` cap bounds. Two orthogonal axes each with a + * handful of values multiply, not add — `os` x `node` x `arch` can produce + * dozens of jobs from a config that reads like a short list. Unbounded, that + * is capacity spent on a combination nobody asked for, not a correctness or + * security issue (efficiency, #444). + * + * Parses the `matrix:` block by indentation, not the structural YAML parser + * — a flow list of bare words (`os: [ubuntu-latest, macos-latest]`, the + * overwhelmingly common hand-written form) is not one it round-trips, only + * a flow list of numbers. Mirrors GHA009's regex-based matrix handling for + * the same reason. + */ + +import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth"; +import { getPrimaryOutput, extractJobs } from "./yaml-helpers"; + +/** Above this many combinations, an uncapped matrix is flagged. */ +const FANOUT_THRESHOLD = 12; + +/** The raw text of one job's block within `jobs:`, or undefined if not found. */ +function jobSection(yaml: string, jobName: string): string | undefined { + const jobsIdx = yaml.search(/^jobs:\s*$/m); + if (jobsIdx === -1) return undefined; + const afterJobs = yaml.slice(jobsIdx + yaml.slice(jobsIdx).indexOf("\n") + 1); + const header = ` ${jobName}:\n`; + const start = afterJobs.indexOf(header); + if (start === -1) return undefined; + const rest = afterJobs.slice(start + header.length); + const nextJobMatch = rest.search(/\n {2}\S/); + return nextJobMatch === -1 ? rest : rest.slice(0, nextJobMatch); +} + +interface MatrixInfo { + dims: Array<{ key: string; size: number }>; + maxParallel: boolean; +} + +/** Parse a job section's `strategy.matrix` dimensions and whether max-parallel caps it. */ +function parseMatrix(section: string): MatrixInfo | undefined { + const lines = section.split("\n"); + const matrixLineIdx = lines.findIndex((l) => /^\s*matrix:\s*$/.test(l)); + if (matrixLineIdx === -1) return undefined; + const matrixIndent = lines[matrixLineIdx].search(/\S/); + + const maxParallel = lines.some((l) => { + const m = l.match(/^(\s*)max-parallel:/); + return !!m && m[1].length === matrixIndent; + }); + + const dims: Array<{ key: string; size: number }> = []; + let i = matrixLineIdx + 1; + while (i < lines.length) { + const line = lines[i]; + if (line.trim() === "") { i++; continue; } + const indent = line.search(/\S/); + if (indent <= matrixIndent) break; // dedented out of the matrix: block + + const kv = line.match(/^\s*([a-zA-Z0-9_-]+):\s*(.*)$/); + if (!kv) { i++; continue; } + const [, key, rest] = kv; + const value = rest.trim(); + + if (value.startsWith("[")) { + const inner = value.replace(/^\[|\]\s*$/g, "").trim(); + dims.push({ key, size: inner === "" ? 0 : inner.split(",").length }); + i++; + continue; + } + if (value !== "") { + dims.push({ key, size: 1 }); // a bare scalar dimension + i++; + continue; + } + // Block-list value on subsequent, deeper-indented lines. + let size = 0; + i++; + while (i < lines.length) { + const l2 = lines[i]; + if (l2.trim() === "") { i++; continue; } + const ind2 = l2.search(/\S/); + if (ind2 <= indent) break; + if (/^\s*-\s/.test(l2)) size++; + i++; + } + dims.push({ key, size }); + } + + return { dims, maxParallel }; +} + +export const gha065: PostSynthCheck = { + id: "GHA065", + description: "Matrix combines dimensions into an uncapped, large fan-out", + + check(ctx: PostSynthContext): PostSynthDiagnostic[] { + const diagnostics: PostSynthDiagnostic[] = []; + + for (const [, output] of ctx.outputs) { + const yaml = getPrimaryOutput(output); + + for (const [jobName] of extractJobs(yaml)) { + const section = jobSection(yaml, jobName); + if (!section) continue; + const matrix = parseMatrix(section); + if (!matrix) continue; + + const dims = matrix.dims.filter((d) => d.key !== "include" && d.key !== "exclude" && d.size > 0); + if (dims.length < 2) continue; // a single axis isn't "combined" fan-out + + const combos = dims.reduce((a, d) => a * d.size, 1); + if (combos <= FANOUT_THRESHOLD || matrix.maxParallel) continue; + + diagnostics.push({ + checkId: "GHA065", + severity: "info", + message: `Job "${jobName}"'s matrix combines ${dims.length} dimensions (${dims.map((d) => d.key).join(" x ")}) into ${combos} jobs with no \`max-parallel:\` cap. Confirm the full cross-product is intended, trim it with \`include\`/\`exclude\`, or add \`max-parallel:\`.`, + entity: jobName, + lexicon: "github", + }); + } + } + + return diagnostics; + }, +}; diff --git a/lexicons/github/src/lint/post-synth/gha066.test.ts b/lexicons/github/src/lint/post-synth/gha066.test.ts new file mode 100644 index 0000000000..95fa81d5d1 --- /dev/null +++ b/lexicons/github/src/lint/post-synth/gha066.test.ts @@ -0,0 +1,66 @@ +import { describe, test, expect } from "vitest"; +import type { PostSynthContext } from "@intentius/chant/lint/post-synth"; +import { gha066 } from "./gha066"; + +function makeCtx(yaml: string): PostSynthContext { + return { + outputs: new Map([["github", yaml]]), + entities: new Map(), + buildResult: { outputs: new Map([["github", yaml]]), entities: new Map(), warnings: [], errors: [], sourceFileCount: 1 }, + }; +} + +describe("GHA066: unbounded artifact retention", () => { + test("flags upload-artifact with no retention-days", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/upload-artifact@v4 + with: + name: build-output + path: dist/ +`; + const diags = gha066.check(makeCtx(yaml)); + expect(diags).toHaveLength(1); + expect(diags[0].checkId).toBe("GHA066"); + expect(diags[0].entity).toBe("build"); + expect(diags[0].message).toContain("build-output"); + }); + + test("does not flag upload-artifact with retention-days set", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/upload-artifact@v4 + with: + name: build-output + path: dist/ + retention-days: 7 +`; + expect(gha066.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a job with no artifact upload", () => { + const yaml = `name: CI +on: + push: +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: npm test +`; + expect(gha066.check(makeCtx(yaml))).toHaveLength(0); + }); +}); diff --git a/lexicons/github/src/lint/post-synth/gha066.ts b/lexicons/github/src/lint/post-synth/gha066.ts new file mode 100644 index 0000000000..b16a0b13f1 --- /dev/null +++ b/lexicons/github/src/lint/post-synth/gha066.ts @@ -0,0 +1,47 @@ +/** + * GHA066: Unbounded Artifact Retention + * + * Flags an `actions/upload-artifact` step with no `retention-days`, which + * falls back to the repository's default (up to 90 days). Build logs, test + * output, and intermediate artifacts rarely need to outlive the PR they came + * from; an unset retention silently accumulates storage. Efficiency (#444), + * not a correctness or security issue. + */ + +import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth"; +import { getPrimaryOutput, jobEntries, parseActionUses } from "./yaml-helpers"; + +export const gha066: PostSynthCheck = { + id: "GHA066", + description: "Uploaded artifact has no explicit retention-days", + + check(ctx: PostSynthContext): PostSynthDiagnostic[] { + const diagnostics: PostSynthDiagnostic[] = []; + + for (const [, output] of ctx.outputs) { + const yaml = getPrimaryOutput(output); + + for (const [jobName, jobObj] of jobEntries(yaml)) { + const steps = Array.isArray(jobObj.steps) ? (jobObj.steps as Array>) : []; + for (const step of steps) { + const uses = typeof step.uses === "string" ? step.uses : undefined; + if (!uses || parseActionUses(uses)?.slug !== "actions/upload-artifact") continue; + + const withBlock = step.with as Record | undefined; + if (withBlock && withBlock["retention-days"] !== undefined) continue; + + const name = typeof withBlock?.name === "string" ? withBlock.name : undefined; + diagnostics.push({ + checkId: "GHA066", + severity: "info", + message: `Job "${jobName}" uploads${name ? ` artifact "${name}"` : " an artifact"} with no \`retention-days\` — it falls back to the repository's default (up to 90 days). Set a \`retention-days\` sized to how long the artifact is actually needed.`, + entity: jobName, + lexicon: "github", + }); + } + } + } + + return diagnostics; + }, +}; diff --git a/lexicons/github/src/lint/post-synth/gha067.test.ts b/lexicons/github/src/lint/post-synth/gha067.test.ts new file mode 100644 index 0000000000..4b3213422f --- /dev/null +++ b/lexicons/github/src/lint/post-synth/gha067.test.ts @@ -0,0 +1,85 @@ +import { describe, test, expect } from "vitest"; +import type { PostSynthContext } from "@intentius/chant/lint/post-synth"; +import { gha067 } from "./gha067"; + +function makeCtx(yaml: string): PostSynthContext { + return { + outputs: new Map([["github", yaml]]), + entities: new Map(), + buildResult: { outputs: new Map([["github", yaml]]), entities: new Map(), warnings: [], errors: [], sourceFileCount: 1 }, + }; +} + +describe("GHA067: unconditional docker build with no path filter or guard", () => { + test("flags a docker build on push with no paths filter and no if guard", () => { + const yaml = `name: CI +on: + push: {} +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: docker build -t app . +`; + const diags = gha067.check(makeCtx(yaml)); + expect(diags).toHaveLength(1); + expect(diags[0].checkId).toBe("GHA067"); + expect(diags[0].entity).toBe("build"); + }); + + test("does not flag when the trigger has a paths filter", () => { + const yaml = `name: CI +on: + push: + paths: + - "src/**" +jobs: + build: + runs-on: ubuntu-latest + steps: + - run: docker build -t app . +`; + expect(gha067.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag when the step has an if guard", () => { + const yaml = `name: CI +on: + push: {} +jobs: + build: + runs-on: ubuntu-latest + steps: + - run: docker build -t app . + if: github.event.head_commit.modified contains 'Dockerfile' +`; + expect(gha067.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a workflow with no push/pull_request trigger", () => { + const yaml = `name: CI +on: + workflow_dispatch: {} +jobs: + build: + runs-on: ubuntu-latest + steps: + - run: docker build -t app . +`; + expect(gha067.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a step that isn't a docker build", () => { + const yaml = `name: CI +on: + push: {} +jobs: + build: + runs-on: ubuntu-latest + steps: + - run: npm test +`; + expect(gha067.check(makeCtx(yaml))).toHaveLength(0); + }); +}); diff --git a/lexicons/github/src/lint/post-synth/gha067.ts b/lexicons/github/src/lint/post-synth/gha067.ts new file mode 100644 index 0000000000..c698a47883 --- /dev/null +++ b/lexicons/github/src/lint/post-synth/gha067.ts @@ -0,0 +1,76 @@ +/** + * GHA067: Unconditional Heavy Step With No Path Filter + * + * Flags a `docker build`/`docker buildx build` step that has no `if:` guard, + * in a workflow that triggers on `push`/`pull_request` with no `paths:` or + * `paths-ignore:` filter. A docs-only or unrelated change still pays for a + * full image build because nothing scopes the trigger or guards the step. + * Efficiency (#444), not a correctness or security issue. + */ + +import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth"; +import { getPrimaryOutput, parseDoc, jobEntries } from "./yaml-helpers"; + +const DOCKER_BUILD_RE = /\bdocker(\s+buildx)?\s+build\b/i; + +function triggerObject(on: unknown, key: string): Record | undefined { + if (!on || typeof on !== "object" || Array.isArray(on)) return undefined; + const trig = (on as Record)[key]; + return trig && typeof trig === "object" && !Array.isArray(trig) ? (trig as Record) : undefined; +} + +function hasPushOrPRTrigger(on: unknown): boolean { + if (typeof on === "string") return on === "push" || on === "pull_request"; + if (Array.isArray(on)) return on.includes("push") || on.includes("pull_request"); + if (on && typeof on === "object") { + const keys = Object.keys(on as Record); + return keys.includes("push") || keys.includes("pull_request"); + } + return false; +} + +function hasPathFilter(on: unknown): boolean { + for (const key of ["push", "pull_request"]) { + const trig = triggerObject(on, key); + if (!trig) continue; + if (Array.isArray(trig.paths) && trig.paths.length > 0) return true; + if (Array.isArray(trig["paths-ignore"]) && trig["paths-ignore"].length > 0) return true; + } + return false; +} + +export const gha067: PostSynthCheck = { + id: "GHA067", + description: "Unconditional docker build with no path filter or guard", + + check(ctx: PostSynthContext): PostSynthDiagnostic[] { + const diagnostics: PostSynthDiagnostic[] = []; + + for (const [, output] of ctx.outputs) { + const yaml = getPrimaryOutput(output); + const doc = parseDoc(yaml); + if (!doc) continue; + if (!hasPushOrPRTrigger(doc.on)) continue; + if (hasPathFilter(doc.on)) continue; + + for (const [jobName, jobObj] of jobEntries(yaml)) { + const steps = Array.isArray(jobObj.steps) ? (jobObj.steps as Array>) : []; + for (const step of steps) { + const run = typeof step.run === "string" ? step.run : undefined; + if (!run || !DOCKER_BUILD_RE.test(run)) continue; + if (step.if !== undefined) continue; // already guarded + + diagnostics.push({ + checkId: "GHA067", + severity: "info", + message: `Job "${jobName}" runs a Docker build on every push/pull_request with no \`paths:\`/\`paths-ignore:\` filter and no \`if:\` guard — unrelated changes (docs, etc.) still pay for a full image build. Scope the trigger's paths or add a guard.`, + entity: jobName, + lexicon: "github", + }); + } + } + } + + return diagnostics; + }, +}; diff --git a/lexicons/github/src/lint/post-synth/gha068.test.ts b/lexicons/github/src/lint/post-synth/gha068.test.ts new file mode 100644 index 0000000000..034e9df043 --- /dev/null +++ b/lexicons/github/src/lint/post-synth/gha068.test.ts @@ -0,0 +1,71 @@ +import { describe, test, expect } from "vitest"; +import type { PostSynthContext } from "@intentius/chant/lint/post-synth"; +import { gha068 } from "./gha068"; + +function makeCtx(yaml: string): PostSynthContext { + return { + outputs: new Map([["github", yaml]]), + entities: new Map(), + buildResult: { outputs: new Map([["github", yaml]]), entities: new Map(), warnings: [], errors: [], sourceFileCount: 1 }, + }; +} + +describe("GHA068: pull-request workflow missing a concurrency group", () => { + test("flags a pull_request workflow with no concurrency block", () => { + const yaml = `name: CI +on: + pull_request: {} +jobs: + test: + runs-on: ubuntu-latest + steps: + - run: npm test +`; + const diags = gha068.check(makeCtx(yaml)); + expect(diags).toHaveLength(1); + expect(diags[0].checkId).toBe("GHA068"); + expect(diags[0].message).toContain("CI"); + }); + + test("does not flag when a concurrency block is present", () => { + const yaml = `name: CI +on: + pull_request: {} +concurrency: + group: \${{ github.workflow }}-\${{ github.ref }} + cancel-in-progress: true +jobs: + test: + runs-on: ubuntu-latest + steps: + - run: npm test +`; + expect(gha068.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a deploy workflow (covered by GHA024)", () => { + const yaml = `name: Deploy +on: + pull_request: {} +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - run: ./deploy.sh +`; + expect(gha068.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a workflow with no pull_request trigger", () => { + const yaml = `name: CI +on: + push: {} +jobs: + test: + runs-on: ubuntu-latest + steps: + - run: npm test +`; + expect(gha068.check(makeCtx(yaml))).toHaveLength(0); + }); +}); diff --git a/lexicons/github/src/lint/post-synth/gha068.ts b/lexicons/github/src/lint/post-synth/gha068.ts new file mode 100644 index 0000000000..ce7a4c18e5 --- /dev/null +++ b/lexicons/github/src/lint/post-synth/gha068.ts @@ -0,0 +1,51 @@ +/** + * GHA068: Pull-Request Workflow Missing a Concurrency Group + * + * Flags a workflow triggered on `pull_request` with no top-level + * `concurrency:` block. Without one, a superseded push keeps its old run + * going instead of cancelling it, so every commit on a PR pays for the full + * pipeline instead of just the latest. Deploy workflows are left to GHA024, + * which already covers them (overlapping-deployment risk, not capacity). + * Efficiency (#444), not a correctness or security issue. + */ + +import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth"; +import { getPrimaryOutput, parseDoc, extractJobs, extractWorkflowName } from "./yaml-helpers"; + +function hasPullRequestTrigger(on: unknown): boolean { + if (typeof on === "string") return on === "pull_request"; + if (Array.isArray(on)) return on.includes("pull_request"); + if (on && typeof on === "object") return "pull_request" in (on as Record); + return false; +} + +export const gha068: PostSynthCheck = { + id: "GHA068", + description: "Pull-request workflow missing a concurrency group", + + check(ctx: PostSynthContext): PostSynthDiagnostic[] { + const diagnostics: PostSynthDiagnostic[] = []; + + for (const [, output] of ctx.outputs) { + const yaml = getPrimaryOutput(output); + const doc = parseDoc(yaml); + if (!doc || !hasPullRequestTrigger(doc.on)) continue; + + const workflowName = extractWorkflowName(yaml) ?? ""; + const jobNames = [...extractJobs(yaml).keys()]; + const isDeployWorkflow = /deploy/i.test(workflowName) || jobNames.some((n) => /deploy/i.test(n)); + if (isDeployWorkflow) continue; // GHA024 already covers deploy workflows + + if (!/^\s*concurrency:/m.test(yaml)) { + diagnostics.push({ + checkId: "GHA068", + severity: "info", + message: `Workflow${workflowName ? ` "${workflowName}"` : ""} triggers on pull_request with no \`concurrency:\` group — a new push doesn't cancel the superseded run, so every commit on the PR consumes a full run's worth of runner capacity. Add a \`concurrency:\` group with \`cancel-in-progress: true\`.`, + lexicon: "github", + }); + } + } + + return diagnostics; + }, +}; diff --git a/lexicons/github/src/lint/post-synth/index.ts b/lexicons/github/src/lint/post-synth/index.ts index 38b90690fe..a099c2ffb6 100644 --- a/lexicons/github/src/lint/post-synth/index.ts +++ b/lexicons/github/src/lint/post-synth/index.ts @@ -49,6 +49,12 @@ import { gha059 } from "./gha059"; import { gha060 } from "./gha060"; import { gha061 } from "./gha061"; import { gha062 } from "./gha062"; +import { gha063 } from "./gha063"; +import { gha064 } from "./gha064"; +import { gha065 } from "./gha065"; +import { gha066 } from "./gha066"; +import { gha067 } from "./gha067"; +import { gha068 } from "./gha068"; export const postSynthChecks: PostSynthCheck[] = [ gha006, @@ -100,4 +106,10 @@ export const postSynthChecks: PostSynthCheck[] = [ gha060, gha061, gha062, + gha063, + gha064, + gha065, + gha066, + gha067, + gha068, ]; diff --git a/lexicons/github/src/lint/post-synth/yaml-helpers.ts b/lexicons/github/src/lint/post-synth/yaml-helpers.ts index 7e5843708f..ac54b28215 100644 --- a/lexicons/github/src/lint/post-synth/yaml-helpers.ts +++ b/lexicons/github/src/lint/post-synth/yaml-helpers.ts @@ -172,7 +172,8 @@ export interface ImageRef { source: "container" | "service" | "step"; } -function parseDoc(yaml: string): Record | undefined { +/** Parse a workflow YAML into a structured document, tolerant of parse errors. */ +export function parseDoc(yaml: string): Record | undefined { try { return parseYAML(yaml); } catch { @@ -180,6 +181,20 @@ function parseDoc(yaml: string): Record | undefined { } } +/** Every job in the workflow as `[name, rawJobObject]`, via the structural parser. */ +export function jobEntries(yaml: string): Array<[string, Record]> { + const doc = parseDoc(yaml); + const jobs = doc?.jobs; + if (!jobs || typeof jobs !== "object") return []; + const out: Array<[string, Record]> = []; + for (const [name, val] of Object.entries(jobs as Record)) { + if (val && typeof val === "object" && !Array.isArray(val)) { + out.push([name, val as Record]); + } + } + return out; +} + /** * Every step object (raw, as parsed from YAML — `uses`, `with`, `id`, `run`, * `env`, etc.) grouped by owning job. Unlike {@link extractJobs} (which only @@ -200,19 +215,6 @@ export function extractStepsByJob(yaml: string): Map]> { - const doc = parseDoc(yaml); - const jobs = doc?.jobs; - if (!jobs || typeof jobs !== "object") return []; - const out: Array<[string, Record]> = []; - for (const [name, val] of Object.entries(jobs as Record)) { - if (val && typeof val === "object" && !Array.isArray(val)) { - out.push([name, val as Record]); - } - } - return out; -} - /** * Extract every `uses:` reference from the workflow — both step-level actions * and job-level reusable-workflow calls. Uses the structural YAML parser so diff --git a/lexicons/github/src/plugin.test.ts b/lexicons/github/src/plugin.test.ts index 2fa1a5fe98..bfde4665e6 100644 --- a/lexicons/github/src/plugin.test.ts +++ b/lexicons/github/src/plugin.test.ts @@ -24,7 +24,7 @@ describe("githubPlugin", () => { test("provides post-synth checks", () => { const checks = githubPlugin.postSynthChecks!(); - expect(checks.length).toBe(49); + expect(checks.length).toBe(55); const checkIds = checks.map((c) => c.id); expect(checkIds).toContain("GHA006"); diff --git a/lexicons/gitlab/src/lint/audit-catalog.ts b/lexicons/gitlab/src/lint/audit-catalog.ts index 8a997f455e..8fab51149f 100644 --- a/lexicons/gitlab/src/lint/audit-catalog.ts +++ b/lexicons/gitlab/src/lint/audit-catalog.ts @@ -44,4 +44,9 @@ export const gitlabAuditCatalog: Record = { WGL046: auditRule("WGL046", "merge-worthy", "guidance", "Cache populated in a merge-request pipeline", "Don't populate caches from merge-request pipelines (poisoning risk).", { authority: [GH_PWN] }), WGL047: auditRule("WGL047", "merge-worthy", "guidance", "Software piped to a shell without verification", "Verify a checksum/signature before executing fetched scripts.", { authority: [SCORECARD_PINNED] }), WGL048: auditRule("WGL048", "report-only", "guidance", "Pipeline without workflow:name", "Add a `workflow:name` for clearer pipeline naming.", { category: "best-practice" }), + + // Efficiency (#444) — waste, not a safety/correctness issue. Always + // report-only: none of these warrant a merge on their own. + WGL049: auditRule("WGL049", "report-only", "guidance", "Dependency install without a cache", "Add a `cache:` covering the dependency directory.", { category: "efficiency" }), + WGL050: auditRule("WGL050", "report-only", "guidance", "Merge-request job missing interruptible", "Add `interruptible: true` so a superseded pipeline can be cancelled.", { category: "efficiency" }), }; diff --git a/lexicons/gitlab/src/lint/post-synth/index.ts b/lexicons/gitlab/src/lint/post-synth/index.ts index 535ff24327..12a895e2c8 100644 --- a/lexicons/gitlab/src/lint/post-synth/index.ts +++ b/lexicons/gitlab/src/lint/post-synth/index.ts @@ -39,6 +39,8 @@ import { wgl045 } from "./wgl045"; import { wgl046 } from "./wgl046"; import { wgl047 } from "./wgl047"; import { wgl048 } from "./wgl048"; +import { wgl049 } from "./wgl049"; +import { wgl050 } from "./wgl050"; export const postSynthChecks: PostSynthCheck[] = [ wgl010, @@ -80,4 +82,6 @@ export const postSynthChecks: PostSynthCheck[] = [ wgl046, wgl047, wgl048, + wgl049, + wgl050, ]; diff --git a/lexicons/gitlab/src/lint/post-synth/wgl049.test.ts b/lexicons/gitlab/src/lint/post-synth/wgl049.test.ts new file mode 100644 index 0000000000..cc8bd52d65 --- /dev/null +++ b/lexicons/gitlab/src/lint/post-synth/wgl049.test.ts @@ -0,0 +1,71 @@ +import { describe, test, expect } from "vitest"; +import type { PostSynthContext } from "@intentius/chant/lint/post-synth"; +import { wgl049 } from "./wgl049"; + +function makeCtx(yaml: string): PostSynthContext { + return { + outputs: new Map([["gitlab", yaml]]), + entities: new Map(), + buildResult: { outputs: new Map([["gitlab", yaml]]), entities: new Map(), warnings: [], errors: [], sourceFileCount: 1 }, + }; +} + +describe("WGL049: dependency install without a cache", () => { + test("flags a job that installs deps with no cache in scope", () => { + const yaml = `build: + stage: build + script: + - npm ci + - npm run build +`; + const diags = wgl049.check(makeCtx(yaml)); + expect(diags).toHaveLength(1); + expect(diags[0].checkId).toBe("WGL049"); + expect(diags[0].entity).toBe("build"); + }); + + test("does not flag when the job has its own cache", () => { + const yaml = `build: + stage: build + cache: + key: npm-cache + paths: + - node_modules/ + script: + - npm ci +`; + expect(wgl049.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag when a pipeline-wide cache: block exists", () => { + const yaml = `cache: + key: global + paths: + - node_modules/ + +build: + stage: build + script: + - npm ci +`; + expect(wgl049.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a job that extends another config", () => { + const yaml = `build: + extends: .node-job + script: + - npm ci +`; + expect(wgl049.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a job with no dependency install command", () => { + const yaml = `lint: + stage: test + script: + - eslint . +`; + expect(wgl049.check(makeCtx(yaml))).toHaveLength(0); + }); +}); diff --git a/lexicons/gitlab/src/lint/post-synth/wgl049.ts b/lexicons/gitlab/src/lint/post-synth/wgl049.ts new file mode 100644 index 0000000000..610ab7ef87 --- /dev/null +++ b/lexicons/gitlab/src/lint/post-synth/wgl049.ts @@ -0,0 +1,57 @@ +/** + * WGL049: Dependency Install Without a Cache + * + * Flags a job whose `script:` runs a package-manager install command (`npm + * ci`, `pip install`, `bundle install`, etc.) with no `cache:` in scope — + * neither on the job itself, nor at the pipeline's `default:`/top level. + * Every run re-fetches the same dependencies from a cold cache. A job that + * `extends:` another config is left alone — the cache may be inherited and + * this check has no way to confirm that. Efficiency (#444), not a + * correctness or security issue. + */ + +import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth"; +import { getPrimaryOutput, extractJobs, extractJobSection } from "./yaml-helpers"; + +const DEP_INSTALL_RE = /\b(npm (install|ci)|yarn install|pnpm install|pip install|pip3 install|bundle install|composer install|go mod download|mvn (install|dependency:resolve))\b/i; + +function hasPipelineWideCache(yaml: string): boolean { + const sections = yaml.split("\n\n"); + if (sections.some((s) => /^cache:/.test(s))) return true; + const defaultSection = sections.find((s) => /^default:/.test(s)); + return !!defaultSection && /\n\s+cache:/.test(defaultSection); +} + +export const wgl049: PostSynthCheck = { + id: "WGL049", + description: "Job installs dependencies with no cache: in scope", + + check(ctx: PostSynthContext): PostSynthDiagnostic[] { + const diagnostics: PostSynthDiagnostic[] = []; + + for (const [, output] of ctx.outputs) { + const yaml = getPrimaryOutput(output); + if (hasPipelineWideCache(yaml)) continue; + + for (const [jobName, job] of extractJobs(yaml)) { + if (jobName.startsWith(".")) continue; // hidden/template job, not run directly + if (job.extends && job.extends.length > 0) continue; // cache may be inherited; can't confirm + + const section = extractJobSection(yaml, jobName); + if (!section) continue; + if (/^\s+cache:/m.test(section)) continue; // job-level cache present + if (!DEP_INSTALL_RE.test(section)) continue; + + diagnostics.push({ + checkId: "WGL049", + severity: "info", + message: `Job "${jobName}" installs dependencies with no cache: in scope — every run re-fetches from the registry. Add a cache: covering the dependency directory.`, + entity: jobName, + lexicon: "gitlab", + }); + } + } + + return diagnostics; + }, +}; diff --git a/lexicons/gitlab/src/lint/post-synth/wgl050.test.ts b/lexicons/gitlab/src/lint/post-synth/wgl050.test.ts new file mode 100644 index 0000000000..00a6da645b --- /dev/null +++ b/lexicons/gitlab/src/lint/post-synth/wgl050.test.ts @@ -0,0 +1,57 @@ +import { describe, test, expect } from "vitest"; +import type { PostSynthContext } from "@intentius/chant/lint/post-synth"; +import { wgl050 } from "./wgl050"; + +function makeCtx(yaml: string): PostSynthContext { + return { + outputs: new Map([["gitlab", yaml]]), + entities: new Map(), + buildResult: { outputs: new Map([["gitlab", yaml]]), entities: new Map(), warnings: [], errors: [], sourceFileCount: 1 }, + }; +} + +describe("WGL050: merge-request job missing interruptible", () => { + test("flags a merge-request-reachable job with no interruptible: true", () => { + const yaml = `test: + rules: + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + script: + - npm test +`; + const diags = wgl050.check(makeCtx(yaml)); + expect(diags).toHaveLength(1); + expect(diags[0].checkId).toBe("WGL050"); + expect(diags[0].entity).toBe("test"); + }); + + test("does not flag when interruptible: true is set", () => { + const yaml = `test: + rules: + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + interruptible: true + script: + - npm test +`; + expect(wgl050.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a deploy job", () => { + const yaml = `deploy-app: + rules: + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + script: + - ./deploy.sh +`; + expect(wgl050.check(makeCtx(yaml))).toHaveLength(0); + }); + + test("does not flag a job not reachable from merge requests", () => { + const yaml = `test: + rules: + - if: $CI_COMMIT_BRANCH == "main" + script: + - npm test +`; + expect(wgl050.check(makeCtx(yaml))).toHaveLength(0); + }); +}); diff --git a/lexicons/gitlab/src/lint/post-synth/wgl050.ts b/lexicons/gitlab/src/lint/post-synth/wgl050.ts new file mode 100644 index 0000000000..8d4a19e3cd --- /dev/null +++ b/lexicons/gitlab/src/lint/post-synth/wgl050.ts @@ -0,0 +1,49 @@ +/** + * WGL050: Merge-Request Job Missing interruptible + * + * Flags a job reachable from merge-request pipelines that doesn't set + * `interruptible: true`. Without it, GitLab's auto-cancel-redundant-pipelines + * setting can't cancel the job when a new push supersedes it, so the runner + * keeps spending capacity on a pipeline nobody wants anymore. Deploy jobs are + * left alone — cancelling mid-deploy is its own hazard, not an efficiency + * win. Efficiency (#444), not a correctness or security issue. + */ + +import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth"; +import { getPrimaryOutput, isMergeRequestReachable } from "./yaml-helpers"; + +const RESERVED_TOP_LEVEL_KEYS = new Set(["stages", "default", "workflow", "variables", "include", "cache"]); + +export const wgl050: PostSynthCheck = { + id: "WGL050", + description: "Merge-request-reachable job is not interruptible", + + check(ctx: PostSynthContext): PostSynthDiagnostic[] { + const diagnostics: PostSynthDiagnostic[] = []; + + for (const [, output] of ctx.outputs) { + const yaml = getPrimaryOutput(output); + + for (const section of yaml.split("\n\n")) { + const top = section.split("\n")[0]?.match(/^(\.?[a-z][a-z0-9_.-]*):/i); + if (!top) continue; + const jobName = top[1]; + if (jobName.startsWith(".") || RESERVED_TOP_LEVEL_KEYS.has(jobName)) continue; + if (/deploy/i.test(jobName)) continue; // cancelling mid-deploy is a hazard, not a win + + if (!isMergeRequestReachable(section)) continue; + if (/^\s+interruptible:\s*true\s*$/m.test(section)) continue; + + diagnostics.push({ + checkId: "WGL050", + severity: "info", + message: `Job "${jobName}" runs on merge-request pipelines but is not interruptible: true — when a new commit supersedes this pipeline, this job keeps running instead of being cancelled. Add interruptible: true.`, + entity: jobName, + lexicon: "gitlab", + }); + } + } + + return diagnostics; + }, +}; diff --git a/lexicons/gitlab/src/plugin.test.ts b/lexicons/gitlab/src/plugin.test.ts index 81e3277632..4b9340a821 100644 --- a/lexicons/gitlab/src/plugin.test.ts +++ b/lexicons/gitlab/src/plugin.test.ts @@ -87,7 +87,7 @@ describe("gitlabPlugin", () => { test("returns post-synth checks", () => { const checks = gitlabPlugin.postSynthChecks!(); - expect(checks).toHaveLength(39); + expect(checks).toHaveLength(41); const ids = checks.map((c) => c.id); expect(ids).toContain("WGL010"); expect(ids).toContain("WGL011"); diff --git a/packages/core/src/audit/catalog.test.ts b/packages/core/src/audit/catalog.test.ts index a0b977a5a5..efeada77a0 100644 --- a/packages/core/src/audit/catalog.test.ts +++ b/packages/core/src/audit/catalog.test.ts @@ -91,7 +91,7 @@ describe("RULE_CATALOG (aggregated: core static + lexicon-contributed, #687)", ( expect(m.remediation.length, `${id} has remediation`).toBeGreaterThan(0); expect(["merge-worthy", "report-only"]).toContain(m.tier); expect(["deterministic", "guidance"]).toContain(m.fixKind); - expect(["security", "correctness", "best-practice"], `${id} has a valid category`).toContain(m.category); + expect(["security", "correctness", "best-practice", "efficiency"], `${id} has a valid category`).toContain(m.category); } }); diff --git a/packages/core/src/audit/catalog.ts b/packages/core/src/audit/catalog.ts index 2b4e6f5544..5a76aa1b6d 100644 --- a/packages/core/src/audit/catalog.ts +++ b/packages/core/src/audit/catalog.ts @@ -26,10 +26,13 @@ export type FixKind = "deterministic" | "guidance"; * What kind of finding this is — orthogonal to `tier` (fix confidence). Lets the * report say "N security, M best-practice, K correctness" instead of branding * everything "security." `security` = exposure/vuln/supply-chain; `correctness` - * = a structural bug (broken reference, invalid schema, never-runs); everything - * else is `best-practice` (hygiene/style/deprecation/reliability). + * = a structural bug (broken reference, invalid schema, never-runs); `efficiency` + * (#444) = waste — redundant work, an oversized execution environment, + * unintended fan-out, unbounded retention — never a safety/correctness issue, + * so it is excluded from the security and correctness tallies; everything else + * is `best-practice` (hygiene/style/deprecation/reliability). */ -export type Category = "security" | "correctness" | "best-practice"; +export type Category = "security" | "correctness" | "best-practice" | "efficiency"; export interface Authority { name: string; diff --git a/packages/core/src/audit/report-html.ts b/packages/core/src/audit/report-html.ts index 56cf5e993c..21a4a43bf0 100644 --- a/packages/core/src/audit/report-html.ts +++ b/packages/core/src/audit/report-html.ts @@ -111,7 +111,7 @@ function renderReportOnly(findings: EnrichedFinding[], n: number): string { function renderHeader(counts: ReportCounts, snapshot: AuditSnapshot | undefined, notes: string[]): string { const sev = `${counts.errors} error ${counts.warnings} warning ${counts.infos} info`; const tiers = `${counts.quickWin} quick-win ${counts.needsReview} needs-review ${counts.reportOnly} hygiene`; - const cats = `${counts.security} security ${counts.correctness} correctness ${counts.bestPractice} best-practice`; + const cats = `${counts.security} security ${counts.correctness} correctness ${counts.bestPractice} best-practice ${counts.efficiency} efficiency`; const meta: string[] = []; if (snapshot) { if (snapshot.host) meta.push(esc(snapshot.host)); diff --git a/packages/core/src/audit/report-model.ts b/packages/core/src/audit/report-model.ts index 380a88e1f6..2439e7647c 100644 --- a/packages/core/src/audit/report-model.ts +++ b/packages/core/src/audit/report-model.ts @@ -62,6 +62,8 @@ export interface ReportCounts { security: number; correctness: number; bestPractice: number; + /** Waste findings (#444) — excluded from `security`/`correctness` by construction (disjoint categories). */ + efficiency: number; } export interface ReportModel { @@ -269,6 +271,7 @@ export function buildReportModel(findings: AuditFinding[], opts: BuildModelOptio security: shown.filter((f) => f.meta.category === "security").length, correctness: shown.filter((f) => f.meta.category === "correctness").length, bestPractice: shown.filter((f) => f.meta.category === "best-practice").length, + efficiency: shown.filter((f) => f.meta.category === "efficiency").length, }; return { diff --git a/packages/core/src/audit/report.test.ts b/packages/core/src/audit/report.test.ts index 8cfd52e9c6..8c18530fd0 100644 --- a/packages/core/src/audit/report.test.ts +++ b/packages/core/src/audit/report.test.ts @@ -127,6 +127,28 @@ describe("renderMarkdown — reworked structure", () => { }); }); +describe("efficiency dimension (#444)", () => { + test("buildReportModel tallies efficiency separately, excluded from security/correctness", async () => { + const { buildReportModel } = await import("./report-model"); + const findings: AuditFinding[] = [ + { checkId: "GHA063", severity: "info", message: "no cache.", file: ".github/workflows/ci.yml", lexicon: "github", entity: "build" }, // efficiency + { checkId: "GHA021", severity: "warning", message: "unpinned checkout.", file: ".github/workflows/ci.yml", lexicon: "github", entity: "build" }, // security + { checkId: "GHA028", severity: "error", message: "no triggers.", file: ".github/workflows/ci.yml", lexicon: "github" }, // correctness + ]; + const { counts } = buildReportModel(findings, { catalog: CATALOG }); + expect(counts.efficiency).toBe(1); + expect(counts.security).toBe(1); + expect(counts.correctness).toBe(1); + // the efficiency finding must not have leaked into either tally + expect(counts.security + counts.correctness + counts.bestPractice + counts.efficiency).toBe(counts.total); + }); + + test("markdown report surfaces the efficiency tally in the By category line", () => { + const out = md([{ checkId: "GHA063", severity: "info", message: "no cache.", file: ".github/workflows/ci.yml", lexicon: "github", entity: "build" }]); + expect(out).toContain("By category: 0 security, 0 correctness, 0 best-practice, 1 efficiency."); + }); +}); + describe("catalog threading (#687)", () => { test("buildReportModel uses a passed-in catalog over core's static one", async () => { const { buildReportModel } = await import("./report-model"); diff --git a/packages/core/src/audit/report.ts b/packages/core/src/audit/report.ts index de8b05619c..9f315e1952 100644 --- a/packages/core/src/audit/report.ts +++ b/packages/core/src/audit/report.ts @@ -111,7 +111,7 @@ export function renderMarkdown(findings: AuditFinding[], opts: RenderOptions = { `${counts.quickWin} quick-win, ${counts.needsReview} needs-review, ${counts.reportOnly} report-only ` + `(${counts.errors} error, ${counts.warnings} warning, ${counts.infos} info).`, "", - `By category: ${counts.security} security, ${counts.correctness} correctness, ${counts.bestPractice} best-practice.`, + `By category: ${counts.security} security, ${counts.correctness} correctness, ${counts.bestPractice} best-practice, ${counts.efficiency} efficiency.`, "", );