Skip to content

fix(rules): leaked-secrets precision and test habits (#357, #363) - #366

Merged
nc9 merged 11 commits into
mainfrom
fix/357-363-leaked-secrets-precision
Sep 16, 2026
Merged

nc9 merged 11 commits into
mainfrom
fix/357-363-leaked-secrets-precision

Conversation

@nc9

@nc9 nc9 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

fix(rules): leaked-secrets precision and test habits (#357, #363, #365)

Closes #357. Closes #363. Closes #365.

What changed

On 776 real sites the detector produced zero confirmed leaks and about 1,100 false findings. This PR lands the precision work, the test habits, and the Discord fix on one branch.

Detector (packages/rules/src/security/leaked-secrets.ts)

  • Left-boundary guard on every prefix pattern: a match preceded by [A-Za-z0-9_] is rejected (Telegram inside a UUID pair, Resend inside _Care_Dry…, fooghp_), except when the preceding character is the last hex digit of a %XX escape (URL-encoded JSON). Generic key-anchored assignments are exempt by design.
  • Keyword prefilter: each FAST pattern declares lowercase keywords; the existing gram index gates the regex on them. No lowercased copy is built for the FAST tier.
  • CONTEXT tier: a 40-character bounded look-behind from each brand keyword replaces the ±500-char window. Values are word-bounded both sides. A keyword after the value never counts, except inside one HTML tag, where a naming attribute (name, id, property, itemprop, data-*) counts in either attribute order, and a <script> whose naming attribute carries the keyword makes its whole block the look-behind.
  • classifyKeyContext: a minified member key (t.a=) is "none", not "assigned"; a brand word is a credential key only when it is the whole key.
  • FALSE_POSITIVE_PATTERNS anchored to the value's head and tail, repeated-character runs counted by a linear walk. Twitter bearer tokens fire; a token containing xxx is kept.
  • Generic assignments (API key, secret, token, AWS secret, Bearer, Basic) skip values with whitespace, under a length-scaled entropy floor min(3.5, log2(len) - 0.5), equal to their own key once case and separators go, URL-encoded labels, and the tail of an unclosed src=/href= path (a ? keeps a query-string credential). A quoted value containing a digit under a credential key bypasses the identifier heuristic.
  • Public tiers: PayPal moved after Azure Storage Key and requires a value position; DigitalOcean Spaces moved after New Relic; Sanity moved to the context tier under sanity; PostHog phc_ and storefrontAccessToken are FAST public patterns; Mixpanel, Raygun and Shopify Storefront are public context patterns; a generic API key or access token under a public brand parent or tag (12 brands in PUBLIC_BRANDS) reports public under the brand's name, while a password, secret or auth token under the same parent stays a leak. accessToken + 32 hex on a page loading from cdn.shopify.com is Shopify's.
  • A Bearer match yields to a JWT finding only for that exact token at that occurrence; an unrecognised JWT still reports as an opaque bearer token.
  • Rule-level dedup prefers the public classification of a value and drops a generic record whose body is exactly a public value (Set lookup, never containment).
  • Discord bot token id segment bounded to 24–28 characters (security/leaked-secrets: Discord Bot Token pattern is quadratic on long base64 runs (2.7 s per 200 KB data URI) #365): 1,639 ms to 2.5 ms on a 200 KB alphanumeric data URI, pinned with a linear-scaling test.

Type changes, all optional fields: FAST entries gain keywords, generic, valuePosition; CONTEXT entries gain publicByDesign. The meta-test fails any FAST pattern that declares no keywords.

Tests

  • Meta-tests per pattern, derived from its generator: a positive whose input carries a declared keyword, prefilter selected for the positive and deselected when the keyword is removed, corrupted-keyword near-miss, mid-token near-miss, duplicate collapsing to one finding, and the three directions of the look-behind for the context tier.
  • The corpus gained the real-world shapes from the 383-file private corpus, the round-2 and round-3 cases, and three pinned real leaks: a Bearer JWT inside a Next.js RSC flight payload, a literal Bearer header in a first-party fetch(), and ENCRYPTED_STORAGE_SECRET_KEY in an inline env dump beside a Turnstile test key that stays silent.
  • The sibling suite's fixtures that put the brand word after the value or relied on t.a= reporting are rewritten to the new semantics.

Numbers

Full private corpus (383 files, 126 MB) at cb46651: 1,235 findings before, 352 after (138 public URLs, 44 medium URLs, 0 high); every added row is a correct public re-typing and the pinned real leaks report. 59.8 to 55.3 ms/MB.

Synthetic bench (66.7 MB, seed 1, 7 iterations, same machine state): origin/main best 1,247 ms / mean 1,773 ms; this branch best 948 ms / mean 1,042 ms; 14.2 ms/MB.

Suites: corpus 1,557 pass / 21 todo / 0 fail; sibling tests/leaked-secrets.test.ts 62 pass; literal-prefilter.test.ts 27 pass; audit-engine golden v1/v2 parity 1 pass. Package typecheck and the detect-secrets gate clean. Three focused codex passes on the detector diff; all findings folded in.

Accepted judgement calls

  1. Entropy floor is length-scaled, min(3.5, log2(len) - 0.5): a flat 3.5 is unreachable below 12 characters. password: "changeme" reports by choice.
  2. The identifier heuristic is bypassed only for a quoted value with a digit under a credential key; unquoted identifiers and digit-free instruction strings still drop.
  3. The 40-character gap counts raw characters, whitespace included; a pretty-printed manifest aligning a key more than 40 characters from its value is a documented limit. Inside one tag, either attribute order counts.
  4. Value position (PayPal) is the assignment test: client-id=… in a script URL counts, /collections/azione-… does not.
  5. Minified member keys are "none": 100% noise on the real corpus.
  6. A brand word is a credential key only as the whole key (data-heroku-dyno is not).
  7. FAST keywords are the literal every match contains; the weak sub-4-character ones (:, ., ac, do, az, -us) prove nothing to the 4-gram index, so those patterns always run, as before.
  8. The prefilter reads only the gram index; the context tier's lowercased copy stays lazy.
  9. The false-positive list is head/tail anchored; example.com stays a substring test.
  10. Sanity needs the sanity keyword and a credential key.
  11. The left-boundary guard exempts only the key-anchored generics.
  12. Brand parents claim API keys and access tokens only, never passwords, secrets or auth tokens (sentry:{authToken}).
  13. The URL-path drop has no url( marker and a ? keeps a query-string credential.

Remaining gaps (9, all pinned as knownGap with a todo each)

  1. Clerk sk_live_[a-zA-Z0-9]{40,} can never fire: Stripe Live runs first and the overlap dedup drops it.
  2. A Bearer value under 20 characters is reported by neither tier.
  3. PayPal's class omits uppercase B–Y, so a real mixed-case client id never fires.
  4. Neon neon_[\w-]{32,} matches a neon_-prefixed hyphenated URL slug.
  5. The Supabase pattern is the generic HS256 header: any session JWT reports as Supabase anon and a service_role JWT reports as public.
  6. Stripe pk_test_ has no pattern; under apiKey: the generic assignment warns on it.
  7. Railway API tokens are plain UUIDs; the railway_… pattern matches a shape Railway does not issue.
  8. No size cap: a 5 MB external script is scanned in full.
  9. A call argument is not a value position: rg4js('apiKey', '…') and mixpanel.init("…") report only when the argument's own shape is a pattern.

nc9 added 3 commits September 16, 2026 11:07
…er, bounded look-behind, anchored FP list #357 #363

On 776 real sites the detector produced zero confirmed leaks and ~1,100
false findings. This lands the precision work from pub#357 and the test
habits from pub#363 in the detector:

- every prefix pattern rejects a match whose preceding character is a word
  character (Telegram inside a UUID pair, Resend inside _Care_Dry…, fooghp_)
- each FAST pattern declares lowercase `keywords`; the gram index gates the
  regex on them (no lowercased copy of the body is built for it)
- the CONTEXT tier reads a 40-character bounded look-behind from each brand
  keyword instead of a ±500 window; values are word-bounded; a keyword after
  the value never counts
- a minified member key (t.a=) is no longer a credential context, and a brand
  word counts as one only when it is the whole key (not data-heroku-dyno)
- FALSE_POSITIVE_PATTERNS are anchored to the value's head and tail; the
  repeated-character test is a linear walk (Twitter bearer tokens fire, a
  token containing xxx is kept)
- PayPal runs after Azure Storage Key and needs a value position; DigitalOcean
  Spaces runs after New Relic; Sanity moves to the context tier under `sanity`
- generic assignments, Bearer, Basic and the AWS secret skip values with
  whitespace or under a length-scaled entropy floor (min(3.5, log2(len)-0.5))
- a quoted value with a digit under a credential key bypasses the identifier
  heuristic (real Cloudflare tokens carry `_`, real Sanity tokens open skA…)

The sibling suite's fixtures that put the brand word after the value, or
relied on t.a= reporting, are rewritten to the new semantics. The
FAST_PATTERNS entry type gains three optional fields (keywords, generic,
valuePosition); the CONTEXT type is unchanged.

Signed-off-by: Nik Cubrilovic <[email protected]>
…#363 #357

For every FAST/CONTEXT pattern, derived from its generator: a positive whose
input carries a declared keyword, a prefilter assertion (selected for the
positive, deselected when the keyword is removed), a corrupted-keyword
near-miss, a mid-token near-miss for the prefixed tier, a duplicate that
collapses to one finding, and for the context tier the three directions of
the bounded look-behind (30 before fires, 40 fires, 41 and 60 do not, after
does not). A pattern with no keywords fails the meta-test.

Twenty known gaps flip to hard expectations; 13 distinct remain.

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 marked this pull request as draft September 16, 2026 01:08
nc9 added 6 commits September 16, 2026 11:09
Unbounded, `[MN][A-Za-z\d]{23,}` consumed every alphanumeric run to its end
from each M and N in it before backtracking for the dot: 2.7 s on a page with
one 200 KB image data URI, 1.6 s reproduced on a synthetic one. Bounded to
Discord's real id length it is 2.5 ms. A test pins both the budget and
linear scaling against a 4x body.

Signed-off-by: Nik Cubrilovic <[email protected]>
…d Bearer, label values, public storefront tiers #357

- the left-boundary guard lets a token through when the character before it
  is the last hex digit of a %XX escape: URL-encoded JSON (%22pk_live_…%22)
  reports again, decoder or no decoder
- a Bearer whose value is a JWT head (eyJ… followed by a dotted segment) is
  the JWT pattern's, so the Bearer match no longer duplicates it
- generic assignments drop a value that equals its own key once case and
  separators go (password:"Password", passwd:"passwd"; digits kept so
  secretkey1 is not secret_key) and a URL-encoded label (%20, or letters
  ending in %)
- ContextPattern gains optional publicByDesign; Mixpanel project tokens,
  Raygun API keys and Shopify Storefront access tokens (32 hex under a
  shopify keyword: storefrontAccessToken, the X-Shopify-Storefront-Access-
  Token header, the web-pixel Api-Key) report under leaked-secrets-public.
  A generic assignment yields to one of them only when the keyword is within
  the look-behind AND the value is that pattern's whole shape, so
  shopify:{password:"…"} still reports; the window is cut from the original
  content before lowercasing so Unicode case folding cannot shift it

Corpus: URL-encoded JSON cases, the label/percent/public shapes, generators
for the two new patterns; 1513 pass / 23 todo. README gap list (10 remain)
and bench row (best 1022 ms, 7 iterations, same corpus).

Signed-off-by: Nik Cubrilovic <[email protected]>
… in either order #357

The 40-character keyword gap is about prose distance. Inside one HTML tag
the whole tag is the look-behind: `<meta content="…" name="algolia-api-key">`
is the attribute order much generated HTML writes, and it names its value
exactly as the other order does. The exception is bounded by the tag's
`<`…`>` (2 KB either way) and requires the keyword to sit in a naming
attribute (name, id, property, itemprop, data-*); the next tag, or text
after the value, does not reach back. Both orders are asserted in the
sibling suite and the corpus; the pretty-printed-manifest alignment case
stays a documented limit.

Also: the shared global naming-attribute regexes are reset before matchAll
(which clones lastIndex), so an early return cannot leave classifyTagKeys
starting mid-tag.

Signed-off-by: Nik Cubrilovic <[email protected]>
…brand-parent public tier, URL-path drop, pinned real leaks #357

From the full 383-file real corpus:

- Shopify: `<script id="shopify-features">{"accessToken":"…"}` (a naming
  <script> tag's whole block is its keyword's look-behind, for the generic
  deferral and the context pass alike), `storefrontAccessToken` anywhere (a
  FAST public pattern ahead of the generics), and `accessToken`/`access_token`
  + 32 lowercase hex on a page loading from cdn.shopify.com all land in the
  public tier
- PostHog `phc_[A-Za-z0-9]{40,}` is a FAST public pattern ahead of the
  generic assignment
- a generic API key or access token whose key sits under a public brand
  (parent key `raygun:{`, tag `<builder-component>`, or the brand within the
  look-behind; 12 brands listed as PUBLIC_BRANDS) reports public under the
  brand's name; a password, secret or auth token under the same parent is
  still a leak (`sentry:{authToken}`)
- a generic match that is the tail of a URL path (unclosed src=/href= in
  the 60 chars before it, no `?` between) is dropped; a query string is not
  a path
- a Bearer yields to a JWT finding only for that exact token at that
  occurrence (head + "." + payload in seenValues), so an unrecognised JWT
  still reports as an opaque bearer token; the non-HS256-JWT gap closes
- the rule's dedup prefers the public classification of a value and drops a
  generic record whose body is exactly a public value (a Set lookup, never
  containment: a public username must not hide the database URL around it)

Three real leak shapes are pinned as positives: a Bearer JWT inside a
Next.js RSC flight payload, a literal Bearer header in a first-party
fetch(), and ENCRYPTED_STORAGE_SECRET_KEY in an inline env dump beside a
Turnstile test key that stays silent.

Signed-off-by: Nik Cubrilovic <[email protected]>
…timeout

The soundness test rebuilt a gram index over 16 KB of filler for each of
~36,000 generated samples: ~5 s quiet, which is bun's default timeout
exactly, and a timeout under load on any branch. The filler is now 512
characters a side (still past the index's 256-character floor, so the
property is unchanged; the widest-table case has its own test) and the test
carries an explicit 60 s budget. The corpus suite's three heavier tests (the
5 MB size-cap probe, the 200 KB data-URI timing test, the snapshot over every
case) get explicit budgets too. Under load 12–20 the prefilter file runs in
0.8–1.0 s and the corpus file in 2.6 s.

Signed-off-by: Nik Cubrilovic <[email protected]>
…p by quoted body, WordPress oEmbed nonce #357

From the full-rule run over the 345-page corpus:

- the inline-script pass is handed the script's own open tag in front of
  its text, so `<script id="shopify-features">{"accessToken":…}` is
  classified public by both passes and there is nothing for the rule's
  dedup to reconcile
- the rule's dedup compares the QUOTED BODY on both sides: a public record
  that was itself a re-typed generic carries its key (`access-token":"…"`)
  just as the generic leak record does (`accessToken":"…"`), and comparing
  the leak's body against the public value never matched
- `data-secret` on a wp-embedded-content element, or a ten-character
  alphanumeric under `data-secret`, is WordPress's public oEmbed nonce

The barkley-design.com "Generic Token" finding was the same Shopify
accessToken, not the meta description; the description is pinned as a
negative anyway, along with the oEmbed nonce and a fourth real leak
(`GA4_API_SECRET = '…'`).

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9

nc9 commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

fix(rules): leaked-secrets precision and test habits (#357, #363, #365)

Closes #357. Closes #363. Closes #365.

What changed

On 776 real sites the detector produced zero confirmed leaks and about 1,100 false findings. This PR lands the precision work, the test habits, and the Discord fix on one branch.

Detector (packages/rules/src/security/leaked-secrets.ts)

  • Left-boundary guard on every prefix pattern: a match preceded by [A-Za-z0-9_] is rejected (Telegram inside a UUID pair, Resend inside _Care_Dry…, fooghp_), except when the preceding character is the last hex digit of a %XX escape (URL-encoded JSON). Generic key-anchored assignments are exempt by design.
  • Keyword prefilter: each FAST pattern declares lowercase keywords; the existing gram index gates the regex on them. No lowercased copy is built for the FAST tier.
  • CONTEXT tier: a 40-character bounded look-behind from each brand keyword replaces the ±500-char window. Values are word-bounded both sides. A keyword after the value never counts, except inside one HTML tag, where a naming attribute (name, id, property, itemprop, data-*) counts in either attribute order, and a <script> whose naming attribute carries the keyword makes its whole block the look-behind.
  • classifyKeyContext: a minified member key (t.a=) is "none", not "assigned"; a brand word is a credential key only when it is the whole key.
  • FALSE_POSITIVE_PATTERNS anchored to the value's head and tail, repeated-character runs counted by a linear walk. Twitter bearer tokens fire; a token containing xxx is kept.
  • Generic assignments (API key, secret, token, AWS secret, Bearer, Basic) skip values with whitespace, under a length-scaled entropy floor min(3.5, log2(len) - 0.5), equal to their own key once case and separators go, URL-encoded labels, and the tail of an unclosed src=/href= path (a ? keeps a query-string credential). A quoted value containing a digit under a credential key bypasses the identifier heuristic.
  • Public tiers: PayPal moved after Azure Storage Key and requires a value position; DigitalOcean Spaces moved after New Relic; Sanity moved to the context tier under sanity; PostHog phc_ and storefrontAccessToken are FAST public patterns; Mixpanel, Raygun and Shopify Storefront are public context patterns; a generic API key or access token under a public brand parent or tag (12 brands in PUBLIC_BRANDS) reports public under the brand's name, while a password, secret or auth token under the same parent stays a leak. accessToken + 32 hex on a page loading from cdn.shopify.com is Shopify's.
  • A Bearer match yields to a JWT finding only for that exact token at that occurrence; an unrecognised JWT still reports as an opaque bearer token.
  • Rule-level dedup prefers the public classification of a value and drops a generic record whose body is exactly a public value (Set lookup, never containment).
  • Discord bot token id segment bounded to 24–28 characters (security/leaked-secrets: Discord Bot Token pattern is quadratic on long base64 runs (2.7 s per 200 KB data URI) #365): 1,639 ms to 2.5 ms on a 200 KB alphanumeric data URI, pinned with a linear-scaling test.

Type changes, all optional fields: FAST entries gain keywords, generic, valuePosition; CONTEXT entries gain publicByDesign. The meta-test fails any FAST pattern that declares no keywords.

Tests

  • Meta-tests per pattern, derived from its generator: a positive whose input carries a declared keyword, prefilter selected for the positive and deselected when the keyword is removed, corrupted-keyword near-miss, mid-token near-miss, duplicate collapsing to one finding, and the three directions of the look-behind for the context tier.
  • The corpus gained the real-world shapes from the 383-file private corpus, the round-2 and round-3 cases, and three pinned real leaks: a Bearer JWT inside a Next.js RSC flight payload, a literal Bearer header in a first-party fetch(), and ENCRYPTED_STORAGE_SECRET_KEY in an inline env dump beside a Turnstile test key that stays silent.
  • The sibling suite's fixtures that put the brand word after the value or relied on t.a= reporting are rewritten to the new semantics.

Numbers

Full private corpus (383 files, 126 MB) at cb46651: 1,235 findings before, 352 after (138 public URLs, 44 medium URLs, 0 high); every added row is a correct public re-typing and the pinned real leaks report. 59.8 to 55.3 ms/MB.

Synthetic bench (66.7 MB, seed 1, 7 iterations, same machine state): origin/main best 1,247 ms / mean 1,773 ms; this branch best 948 ms / mean 1,042 ms; 14.2 ms/MB.

Suites: corpus 1,557 pass / 21 todo / 0 fail; sibling tests/leaked-secrets.test.ts 62 pass; literal-prefilter.test.ts 27 pass; audit-engine golden v1/v2 parity 1 pass. Package typecheck and the detect-secrets gate clean. Three focused codex passes on the detector diff; all findings folded in.

Accepted judgement calls

  1. Entropy floor is length-scaled, min(3.5, log2(len) - 0.5): a flat 3.5 is unreachable below 12 characters. password: "changeme" reports by choice.
  2. The identifier heuristic is bypassed only for a quoted value with a digit under a credential key; unquoted identifiers and digit-free instruction strings still drop.
  3. The 40-character gap counts raw characters, whitespace included; a pretty-printed manifest aligning a key more than 40 characters from its value is a documented limit. Inside one tag, either attribute order counts.
  4. Value position (PayPal) is the assignment test: client-id=… in a script URL counts, /collections/azione-… does not.
  5. Minified member keys are "none": 100% noise on the real corpus.
  6. A brand word is a credential key only as the whole key (data-heroku-dyno is not).
  7. FAST keywords are the literal every match contains; the weak sub-4-character ones (:, ., ac, do, az, -us) prove nothing to the 4-gram index, so those patterns always run, as before.
  8. The prefilter reads only the gram index; the context tier's lowercased copy stays lazy.
  9. The false-positive list is head/tail anchored; example.com stays a substring test.
  10. Sanity needs the sanity keyword and a credential key.
  11. The left-boundary guard exempts only the key-anchored generics.
  12. Brand parents claim API keys and access tokens only, never passwords, secrets or auth tokens (sentry:{authToken}).
  13. The URL-path drop has no url( marker and a ? keeps a query-string credential.

Remaining gaps (9, all pinned as knownGap with a todo each)

  1. Clerk sk_live_[a-zA-Z0-9]{40,} can never fire: Stripe Live runs first and the overlap dedup drops it.
  2. A Bearer value under 20 characters is reported by neither tier.
  3. PayPal's class omits uppercase B–Y, so a real mixed-case client id never fires.
  4. Neon neon_[\w-]{32,} matches a neon_-prefixed hyphenated URL slug.
  5. The Supabase pattern is the generic HS256 header: any session JWT reports as Supabase anon and a service_role JWT reports as public.
  6. Stripe pk_test_ has no pattern; under apiKey: the generic assignment warns on it.
  7. Railway API tokens are plain UUIDs; the railway_… pattern matches a shape Railway does not issue.
  8. No size cap: a 5 MB external script is scanned in full.
  9. A call argument is not a value position: rg4js('apiKey', '…') and mixpanel.init("…") report only when the argument's own shape is a pattern.

@nc9
nc9 marked this pull request as ready for review September 16, 2026 02:40
…es built from keywords #357

CodeQL on #366: js/incomplete-url-substring-sanitization on the round-3
Shopify page check (a bare `includes("cdn.shopify.com")`, which
`cdn.shopify.com.evil.test` satisfies) and three js/incomplete-hostname-regexp
alerts on the `keywords` literals for Google OAuth, Slack webhooks and
Sentry DSNs. The table regexes already escape every dot in those hosts; the
alerts came from the corpus meta-test building `new RegExp` out of the
keyword strings to corrupt them. Keywords are substrings and nothing builds a
regex from them now: the meta-test rewrites occurrences by a case-folded
indexOf walk. The Shopify page check is `(?:https?:)?//cdn\.shopify\.com/`.
Negatives pinned for `cdn.shopify.com.evil.test`/`notcdn.shopify.com` and a
`sentryXio` DSN host.

Signed-off-by: Nik Cubrilovic <[email protected]>
…e, not a content regex #357

CodeQL #226 (js/regex/missing-regexp-anchor) on the cdn.shopify.com host
regex. The page check now collects every absolute or protocol-relative URL
in the body (capped at 2,000), parses each with `new URL()` and compares
`hostname` whole to cdn.shopify.com; no regex decides a host on raw content
anywhere in the detector now (the remaining host-bearing regexes are the
Sentry DSN, Slack and Discord webhook and Google OAuth client id SHAPES,
which extract a value rather than sanitise a page). Lookalike negatives
kept (`cdn.shopify.com.evil.test` in a link, an `href` and a
protocol-relative URL; `notcdn.shopify.com`), and a protocol-relative
`//cdn.shopify.com/` positive pinned.

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 merged commit 328da7c into main Sep 16, 2026
14 checks passed
@nc9
nc9 deleted the fix/357-363-leaked-secrets-precision branch September 16, 2026 03:09
@nc9 nc9 mentioned this pull request Sep 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants