Repository navigation
fix(apps): parse csp-check scripts with jsdom and scan dist tarballs with gitleaks - #233
Conversation
…with gitleaks csp-check found script tags with a regex, which misses an unterminated script src tag and wrongly reads script text inside a comment. It now parses the page with jsdom, as a browser does. The dist-release pack now unpacks each finished tarball and runs gitleaks over it, as the release design requires. A finding names the rule, file and line but not the matched text. With --release, or when CI is set, a missing gitleaks fails the pack instead of skipping the scan. Assisted-by: AI
|
The latest updates on your projects. Learn more about Vercel for GitHub. 2 Skipped Deployments
|
DOCS-1351 Clear the pre-public batch: fake AWS key, internal identifiers, flip-day checklist and hardening items
Low/Info batch. https://github.com/coder/security-assessments/issues/386 Before the repository goes public (§A):
Hardening, after the flip:
Split into separate issues as work starts. |
|
/coder-agents-review |
Jesswinters
left a comment
There was a problem hiding this comment.
Approving: I found no blockers. Replacing the regex with jsdom is a clear improvement. An unterminated src script is now found, text in comments and textarea is ignored, and inline hashes match the browser's because the parser normalises CRLF. jsdom runs with its defaults, so no script executes and nothing is fetched. The gitleaks scan runs on the unpacked final tarball, the same bytes that go to outDir and into SHA256SUMS. It uses --redact, runs through execFile with an argument array, and always removes its temp dirs. The release CLI requires the scan with --release or in CI.
I'd still fix the first three inline comments before this gates a real release. gitleaks exits 1 on fatal errors as well as on leaks. CI never installs gitleaks, so the planted-secret tests skip silently there. And the library default skips the scan silently. Two smaller gaps are new or still open in the CSP check: scripts inside <template> are no longer checked, and an SVG <script href> is read as an empty inline script.
Checks I ran on db71605: apps/offlinedocs pnpm test 62 pass. apps/dist-release pnpm test gives 48 pass and 4 skipped without gitleaks, and 52 pass with gitleaks 8.30.1, which I installed after verifying its sha256. The 4 new extractScripts tests fail against main. On a fixture offlinedocs build, csp:check passes (6 pages, 90 scripts), and the old and new extractScripts agree on all 6 pages. oxlint and oxfmt are clean, and CI is green.
Generated by Coder Agents on behalf of @Jesswinters.
| import { promisify } from "node:util"; | ||
|
|
||
| const run = promisify(execFile); | ||
| // gitleaks exits 1 when it finds a leak, and 2 or more when it fails to run. |
There was a problem hiding this comment.
Should fix: this comment is wrong for gitleaks 8.30.1, which exits 1 for fatal errors as well as for leaks. I checked with the real binary: a missing directory, a bad --config and an unknown subcommand all print FTL ... and exit 1.
Today a fatal error is only caught by accident, because no report file exists and readFile(report) throws ENOENT, which also hides gitleaks' real message. If a run writes [] and then exits 1, findSecrets returns [] and the pack passes. A timeout does exactly that: I reproduced it by adding --timeout 1 over a directory where a full scan finds a leak. These flags don't do that today, but it is fail-open.
Suggested fix: pass --exit-code with a value gitleaks never uses for errors (say "3") and set LEAKS_FOUND to it. Throw if that code comes back with an empty findings list, and include error.stderr in the rethrown error. Then the test at secrets.test.mjs:58 can assert on gitleaks' own message rather than passing because of the ENOENT.
There was a problem hiding this comment.
Fixed in d60ab8f. findSecrets now passes --exit-code 3 and treats only 3 as leaks; any other non-zero exit throws gitleaks exited <code>: <stderr> (ANSI stripped), and 3 with an empty report throws too. The fatal-error test now wraps the real gitleaks with a bad --config and asserts on gitleaks' own "unable to load gitleaks config" message, and a fake-gitleaks test covers your timeout shape (writes [], exits 1). One difference from what you saw: on 8.30.1 here (macOS arm64) a missing directory doesn't exit 1, it logs WRN skipping and exits 0 with a clean scan, so findSecrets now reads the directory first and throws ENOENT itself.
| * Scan an unpacked package with gitleaks. A finding names the rule, file and line but never the | ||
| * matched text. Without gitleaks on PATH, a required scan fails and an optional one is skipped. | ||
| */ | ||
| export async function findSecrets(dir, { command = "gitleaks", required = false } = {}) { |
There was a problem hiding this comment.
Should fix: required = false here and secretScan = {} in packPackage mean any new caller gets a scan that is silently skipped when gitleaks is missing, and a local run still prints packed ... with no sign the scan never ran. cli.mjs:40 passes required for releases and CI, which is right, but the safe default belongs in the library. Default required to true, pass { required: false } explicitly in tests and the local non-CI path, and print a warning whenever the scan is skipped.
There was a problem hiding this comment.
Fixed in d60ab8f. required now defaults to true, and packPackage inherits that. The CLI requires the scan unless you pass --allow-missing-gitleaks, which is refused with --release or when CI is set, and a skipped scan prints secret scan skipped: gitleaks was not found on PATH via console.warn. The pack tests pass { required: false } explicitly, and a test asserts the warning is printed.
| assert.deepEqual(readdirSync(outDir), []); | ||
| }); | ||
|
|
||
| const hasGitleaks = spawnSync("gitleaks", ["version"]).status === 0; |
There was a problem hiding this comment.
Should fix: CI never installs gitleaks, and these tests skip when it's absent, so the "planted secret fails the pack" check has only ever run locally. The test (@coder/dist-release) job is already on main and could install a pinned gitleaks with a sha256 check, as ci.yml does for actionlint. The plan doc already names a version and checksum. Then make the skip hasGitleaks || process.env.CI ? false : "..." so a CI run without the binary fails instead of skipping.
Also, this spawnSync probe and the execFileSync probe in secrets.test.mjs lines 9 to 17 do the same job. One shared helper, per AGENTS.md, would be better.
There was a problem hiding this comment.
Fixed in d60ab8f. The test job now installs gitleaks 8.30.1 for @coder/dist-release only, checking the linux_x64 tarball against a hard-coded sha256 (551f6fc8…70eb) the same way the actionlint job does. Both test files now import needsGitleaks from one src/gitleaks-probe.mjs, which only skips when CI is unset, so a CI run without the binary fails. I checked that locally: with CI=1 and no gitleaks, 6 tests fail through pnpm turbo run test, so turbo passes CI through.
| ); | ||
| } | ||
| match = scriptTag.exec(html); | ||
| for (const el of new JSDOM(html).window.document.querySelectorAll("script")) { |
There was a problem hiding this comment.
Should fix: querySelectorAll("script") doesn't look into template.content, so <template><script src="https://evil.example/t.js"></script></template> is now reported as clean. I ran both versions: the old regex flagged it and this returns []. script-src still applies once template content is cloned into the page, so this narrows the check. Query each template.content recursively as well.
There was a problem hiding this comment.
Fixed in 6f845fa. extractScripts now walks script, template in document order and recurses into each template.content, so your <template><script src="https://evil.example/t.js"> case and a nested template are both reported. The new test failed before the fix.
| match = scriptTag.exec(html); | ||
| for (const el of new JSDOM(html).window.document.querySelectorAll("script")) { | ||
| if (!isJavaScriptScriptType(el.getAttribute("type") ?? undefined)) continue; | ||
| const src = el.getAttribute("src"); |
There was a problem hiding this comment.
Suggestion: an SVG <svg><script href="https://evil.example/x.js"></script></svg>, and the xlink:href form, come back as { type: "inline", body: "" }. That passes under 'unsafe-inline', even though the browser fetches the external script, which 'self' would block. The old regex missed href too, so this isn't a regression. For elements in the SVG namespace, read href, falling back to getAttributeNS(XLINK_NS, "href"), and treat the result as src.
There was a problem hiding this comment.
Fixed in 6f845fa. A script in the SVG namespace now reads href, falling back to getAttributeNS(XLINK_NS, "href"), as its src, so both forms are checked as external scripts. The new test covers both and an inline SVG script, and failed before the fix.
| * Matching is a plain regex over the serialized HTML, not a full parse: it | ||
| * is only asked to find `<script ...>...</script>` tags, which Next always | ||
| * emits well-formed and un-nested. | ||
| * The document is parsed as a browser would, so an unterminated tag, a |
There was a problem hiding this comment.
Nit: "parsed as a browser would" overclaims. jsdom parses with scripting disabled, so <noscript> content becomes real elements; that errs on the safe side. Templates and SVG differ too, as in the other comments. It's also longer than the one-line comment rule in AGENTS.md. A shorter comment without that claim would be accurate.
There was a problem hiding this comment.
Fixed in 6f845fa. The three lines are now one: "Parsed by jsdom, including <template> content and SVG <script href>."
| Each package tarball may hold only `package.json`, `README.md`, `LICENSE` and the paths that `PACKAGE_ALLOW` in `src/config.mjs` names for that package, whatever the package's own `files` field says. | ||
| TypeScript source files other than declarations fail the pack wherever they are, as do `.map` files, `sourceMappingURL` comments, and entries that are not regular files or directories. | ||
| Any comment left in a shipped `.js`, `.mjs`, `.cjs` or `.d.ts` file fails the pack too; the files are parsed, so `//` inside a string is not a comment. | ||
| Each finished tarball is unpacked and scanned with [gitleaks](https://github.com/gitleaks/gitleaks), and any finding fails the pack; findings name the rule, file and line, never the matched text. |
There was a problem hiding this comment.
Nit: gitleaks' default config skips .svg and other image, font and archive extensions. I confirmed that a planted key in assets/a.svg is not reported, and docs-theme ships assets/favicons/*.svg. Inline gitleaks:allow markers are also honoured; in .css, .json or .md that would let a marked secret through. Consider adding --ignore-gitleaks-allow, either documenting the default path allowlist or shipping a config that drops it, and naming the minimum gitleaks version (the dir subcommand).
There was a problem hiding this comment.
Done in d60ab8f. The scan now passes --ignore-gitleaks-allow, and the README names the minimum version (8.19, for the dir subcommand; CI pins 8.30.1). I looked at shipping a config that drops the default path allowlist, but [extend] useDefault merges the base allowlists and can't remove them, so it would mean vendoring all ~3,200 lines of the default config and keeping it in step with each bump. I left that out and the README now states the gap: .svg, image, font and archive files are skipped, naming docs-theme's assets/favicons/*.svg. A test checks that a gitleaks:allow marker no longer hides a planted key.
| try { | ||
| await run( | ||
| command, | ||
| ["dir", "--no-banner", "--redact", "--report-format", "json", "--report-path", report, dir], |
There was a problem hiding this comment.
Optional: gitleaks also reads GITLEAKS_CONFIG or GITLEAKS_CONFIG_TOML from the environment, and an ignore file from the working directory. Passing an explicit --config and --gitleaks-ignore-path set to the empty work dir would make the scan independent of whoever runs it.
There was a problem hiding this comment.
Done in d60ab8f. The scan writes an [extend] useDefault = true config into its temp dir and passes it as --config, passes that same dir as --gitleaks-ignore-path, and runs gitleaks with that dir as its cwd. A test sets both GITLEAKS_CONFIG and GITLEAKS_CONFIG_TOML to allow-everything configs and still gets the finding. While checking this I found that gitleaks also reads a .gitleaksignore from the scanned directory, whatever --gitleaks-ignore-path says, so findSecrets now fails if one is there. The tarball allowlist already blocks it at that level, but the check costs nothing.
| ...(await checkTarball(pkg, file, { version, license })), | ||
| ]; | ||
| // Scan what the tarball holds, not the directory it was packed from. | ||
| const unpacked = path.join(work, "unpacked"); |
There was a problem hiding this comment.
Optional: the tarball is extracted even when checkEntryTypes has already flagged symlinks or hardlinks. The risk is low, since we produce the tarball ourselves and tar has its own protections, but throwing before extraction is cheap.
There was a problem hiding this comment.
Done in d60ab8f. A new extractTarball in contents.mjs runs checkEntryTypes and throws before calling tar, and packPackage uses it for both extractions. Before the final unpack it also throws on any problem found so far. A test checks that a tarball with a symlink is refused and the destination stays empty.
…n by default gitleaks exits 1 on fatal errors as well as on leaks, so a run that wrote an empty report and then failed (a timeout, for one) passed the pack. Leaks now get their own exit code, 3; any other non-zero exit throws with gitleaks' stderr, and the leak code with no findings throws too. A missing scan directory is an error rather than a clean scan of nothing. The scan was optional unless the caller asked otherwise, so a new caller or a local run skipped it silently. It is now required by default; the CLI's --allow-missing-gitleaks opts out for local dry runs only, is refused with --release or in CI, and a skipped scan prints "secret scan skipped". The scan now passes an explicit config and ignore path and ignores inline gitleaks:allow markers, so GITLEAKS_CONFIG, GITLEAKS_CONFIG_TOML and a .gitleaksignore in the working directory can't change it; a .gitleaksignore in the scanned directory fails it. The default config's path allowlist still skips .svg and other image, font and archive files, which the README now says. The CI test job installs a pinned, sha256-checked gitleaks for this package, and with CI set the secret-scan tests fail instead of skipping when it is missing, so the planted-secret checks run on every PR. Both test files share one gitleaks probe. Tarballs with symlinks or hardlinks are refused before they are extracted. Assisted-by: AI
querySelectorAll does not enter template content, so a script inside a <template> went unchecked even though script-src applies once the template is cloned into the page. An SVG <script href> or xlink:href was read as an empty inline script, which passes under 'unsafe-inline' although the browser fetches it as an external script. Both are now checked, and the comment that claimed the document is parsed exactly as a browser would is shortened to what jsdom actually does. Assisted-by: AI
…eplace CodeQL read the one-off replace of the first newline as an incomplete sanitization. Splitting the planted key into lines and marking only the first says outright that one line carries the gitleaks:allow marker, and the test still fails if the scan honours it. Assisted-by: AI
Merge order
Independent of the other open PRs. Stacks with nothing.
Summary
Two section D items of coder/security-assessments#386. The CSP check read
<script>tags with a regex, whichAGENTS.mdforbids and which misses an unterminated<script src>. The dist-release spec promises that gitleaks scans the unpacked contents of every tarball, whichpack.mjsdid not do.Fix
apps/offlinedocs/scripts/csp-check-helpers.mjs:extractScriptsnow parses the page with jsdom (already a dependency of the app) and readsscriptelements, so an unterminated<script src=...>is found, and script text inside a comment or atextareais not. I did not importapps/docs/scripts/html-dom.mjsacross apps, since it is a one-linenew JSDOM(html). The data-block type check is unchanged.apps/dist-release: a newsrc/secrets.mjsrunsgitleaks dirover the unpacked final tarball insidepackPackage, before it is copied out, so a finding fails the pack and leaves no tarball. Findings print the rule, file and line and never the matched text. The scan is required by default: a missinggitleaksfails the pack unless a local dry run passes--allow-missing-gitleaks, which is refused with--releaseor whenCIis set and printssecret scan skippedwhen it applies. The tests that callpackPackagedirectly pass{ required: false }.Not done:
.github/workflows/release-dist.ymlis not onmain(it lives on the open dist-release PR branches), so installing a pinned gitleaks there stays with that work.Review feedback applied in d60ab8f and 6f845fa; 3d85a37 rewrites the
gitleaks:allowtest fixture so CodeQL no longer reads it as incomplete sanitization. gitleaks now exits 3 for leaks (it exits 1 on fatal errors too), and any other non-zero exit throws with gitleaks' own stderr; 3 with no findings throws as well, and a missing scan directory is an error instead of a clean scan. The scan passes an explicit[extend] useDefaultconfig,--gitleaks-ignore-pathand--ignore-gitleaks-allow, soGITLEAKS_CONFIG,GITLEAKS_CONFIG_TOML, a.gitleaksignorein the working directory and inlinegitleaks:allowmarkers can't change it, and a.gitleaksignorein the scanned directory fails it. The default config's path allowlist still skips.svg, image, font and archive files; dropping it would mean vendoring the whole default config, so the README documents the gap instead. Tarballs with symlinks or hardlinks are refused before extraction. Thetest (@coder/dist-release)CI job now installs gitleaks 8.30.1 with a sha256 check, and the secret-scan tests fail rather than skip in CI when it is missing; both test files share one probe. The CSP check now also reads scripts inside<template>content (recursively) and treats an SVG<script href>orxlink:hrefas an external script.QA
Nothing to see on the site. These are build scripts: the
test (@coder/offlinedocs)andtest (@coder/dist-release)jobs on this PR show the change working.Pages to compare
Testing
Written test first for the four new
extractScriptscases (unterminatedsrc, unclosed inline script, comment andtextarea, unquoted and repeatedsrc); they failed on the regex and pass now.node --testforapps/offlinedocscsp-check tests passes (32).apps/dist-releasetests pass both without gitleaks (48 pass, 4 skipped) and with gitleaks 8.30.1 on PATH (52 pass), including a planted AWS-shaped key built at run time that fails the pack.oxlintis clean.After the review fixes, the new tests were written first and failed against the previous code (11 in
apps/dist-release, 2 inapps/offlinedocs).apps/offlinedocspnpm test: 64 pass.apps/dist-releasepnpm testwith gitleaks 8.30.1 on PATH (sha256 verified): 60 pass; without it: 54 pass, 6 skipped; withCI=1and no gitleaks: 6 fail, as intended. oxfmt, oxlint andpnpm lint:actionsare clean.Upstream
No. Repository-specific scripts.
Dependency bot question (no change made)
renovate.jsonlanded in #82 on 2026-09-15, and no Renovate PR or commit exists since (gh pr listfor the Renovate app returns nothing, and there is no dependency dashboard issue). The only dependency PRs are Dependabot's (#7, #202, #209), which are security updates and need nodependabot.yml. So Renovate is most likely not installed on the repository, andrangeStrategy: pinhas never been applied. Confirming needs the org's GitHub Apps settings.Linear: https://linear.app/codercom/issue/DOCS-1351
Finding: coder/security-assessments#386
🤖 Built with AI assistance.