Skip to content

feat(audit-engine): emit sub-phase boundaries from the streamed rules pass - #226

Merged
nc9 merged 1 commit into
mainfrom
perf/post-crawl-attribution-1860
Sep 7, 2026
Merged

nc9 merged 1 commit into
mainfrom
perf/post-crawl-attribution-1860

Conversation

@nc9

@nc9 nc9 commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Investigation support for squirrelscan/repo#1860. Not a fix: this makes the thing measurable and reports what the measurement says.

Why

The first production run on the streaming path (drscholls.com, 150 pages, full, rendered, cloud prefetch on, standard-3) showed the streamed page loop flat, 2583 to 2659 MB across 120 pages, with two ~1 GB steps around it:

  • +1.1 GB between "rules started" and the first 20-page heartbeat
  • +1.0 GB between the last page heartbeat and "rules completed"

runStreamingRules emitted nothing between those two points, so neither step could be attributed to anything from the event stream.

What this adds

An onPhase hook reporting the pass's sub-phases in order: universe, site-fetch, page-rules, site-query, site-rules. The engine samples nothing itself, because process is the caller's concern and the container already owns RSS sampling.

What the measurement says

Reproduced on a 153-page crawl of ~1 MB, ~19k-node pages, RSS sampled synchronously at each boundary (a timer-based sampler reads nothing here: these phases are sync CPU that never yields):

batch universe page-rules site-fetch site-query site-rules
10 +233 MB +324 MB −1 MB +74 MB −3 MB
25 +501 MB +404 MB +1 MB +43 MB −1 MB
50 +673 MB +730 MB +2 MB −58 MB +2 MB

Both production steps are the same term: one batch's parse working set, sampled at different points in a saw-tooth that rises within a batch and drops when the batch is collected. Nothing new is unbounded; the batch is simply large for pages of this weight.

I want to state one thing plainly, because I guessed wrong before measuring: I expected createSiteQuery to be the second step, since its link-graph scan had a hardcoded batch of 500 and pulls whole PageRecords. It is not. It moves memory by tens of MB, and the site pass by single digits. The collected-signals design from #1021 is doing exactly its job.

The one real change

createSiteQuery's link-graph scan now takes the caller's batch size instead of its own 500. It reads only normalizedUrl and parsedData but receives whole PageRecords, so 500 of them is a latent whole-crawl read sitting on the one path that must not have one. Measured harmless at 153 pages; bounded now so it stays that way at 5,000. The page_features cursors keep 500, since those rows are small scalars.

Not addressed here

The production run also showed 1.45 GB already resident at crawl end for 150 pages, about 10 MB per page. That is the crawl phase, not the post-crawl pipeline, and it is page-count dependent, so it is the term that decides whether large crawls fit. It needs its own investigation.

scripts/post-crawl-attribution.ts is the harness that produced the table. All golden and site-query gates pass unchanged.

… pass

A production run (drscholls.com, 150 pages, rendered, cloud prefetch on,
standard-3) showed two ~1 GB RSS steps around a page loop that was itself
flat: one between "rules started" and the first page heartbeat, one between
the last heartbeat and "rules completed". Neither could be attributed,
because `runStreamingRules` emitted nothing between those two points.

It now reports its sub-phases — universe, site-fetch, page-rules, site-query,
site-rules — through an `onPhase` hook. The engine deliberately samples
nothing itself; `process` is the caller's concern, so the container keeps
owning the RSS sampling it already does.

With that hook, the same shape reproduces locally on a 153-page crawl of
~1 MB, ~19k-node pages, and both steps are the SAME term — one batch's parse
working set, sampled at different points in the saw-tooth:

  batch   universe   page-rules   site-fetch / site-query / site-rules
     10    +233 MB      +324 MB    -1 / +74 / -3 MB
     25    +501 MB      +404 MB    +1 / +43 / -1 MB
     50    +673 MB      +730 MB    +2 / -58 / +2 MB

Worth stating plainly because I guessed wrong before measuring: the site pass
is NOT implicated, and neither is createSiteQuery. The collected-signals
design is doing its job — site-rules moves memory by single-digit MB at every
batch size.

Also threads the caller's batch size into createSiteQuery's link-graph scan,
which had its own hardcoded 500 and pulls whole PageRecords (html included)
while reading only normalizedUrl and parsedData. Measured harmless at 153
pages, but 500 full records is a latent whole-crawl read on exactly the path
that must not have one, so it is now bounded by the same dial as everything
else. The page_features cursors keep 500: those rows are small scalars.

scripts/post-crawl-attribution.ts is the harness that produced the table.

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 merged commit 5d35747 into main Sep 7, 2026
13 checks passed
@nc9
nc9 deleted the perf/post-crawl-attribution-1860 branch September 7, 2026 07:31
nc9 added a commit that referenced this pull request Sep 16, 2026
…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 added a commit that referenced this pull request Sep 16, 2026
* fix(rules): leaked-secrets precision: boundary guard, keyword prefilter, 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]>

* test(rules): leaked-secrets meta-tests per pattern and known-gap flips #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]>

* test(rules): leaked-secrets snapshot, README gap list and bench A/B for #357

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

* perf(rules): bound the Discord bot token id segment to 24-28 chars #365

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]>

* fix(rules): leaked-secrets round 2: percent-escape boundary, JWT-owned 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]>

* fix(rules): leaked-secrets: a naming attribute of the same tag counts 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]>

* fix(rules): leaked-secrets round 3: Shopify boot JSON, PostHog phc_, 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]>

* test(rules): keep the prefilter soundness test off bun's 5 s default 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]>

* fix(rules): leaked-secrets: inline scripts carry their open tag, dedup 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]>

* fix(rules): leaked-secrets: a host test for cdn.shopify.com, no regexes 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]>

* fix(rules): leaked-secrets: decide the Shopify page by parsed hostname, 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]>

---------

Signed-off-by: Nik Cubrilovic <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant