Skip to content

perf: run the strict CSP and JavaScript-policy checks in Rust (560 ms to 99 ms on a large page) - #289

Merged
JuroOravec merged 9 commits into
mainfrom
perf/csp-checks-in-rust
Oct 23, 2026
Merged

JuroOravec merged 9 commits into
mainfrom
perf/csp-checks-in-rust

Conversation

@JuroOravec

@JuroOravec JuroOravec commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Part of #274.

What changes

With security_csp or security_javascript set, serialize() checks the
page it returns. Each check used to turn every tag and attribute of the
page into Python objects: about 400,000 objects on the 1,400-row project
board benchmark page (benchmarks/web/apps/citry), plus several full
garbage collections. Now Rust runs the rules and returns
only what they report, so an ordinary tag never reaches Python.

  • crates/citry_html_transform/src/output_policy.rs applies every rule of
    both checks: native on* attributes, javascript: URLs, raw <script>
    and <style> elements, Vue directive attributes (v-, @, :),
    srcdoc and
    data:text/html documents, the omit fallback rules, and removal of the
    omit marker. It reuses the existing scanner, which reads HTML the way the
    browser's parser does.
  • The Python validators keep their messages, the keys that drop repeated
    findings, the memory of what warn mode saw before the on_serialize
    extension hooks ran, and the
    decision to warn or raise. They replay what Rust found, so reports are
    the same as before.
  • When both validators check the same page, serialize() and the Events
    checks of the raw HTML blocks in a response read it once for both. The
    CSP check reads the page again only when the JavaScript policy removed
    omit markers from it, because that moves the tags after them.
  • The checks of structured Script and Style attributes, the script-type
    rule, and the JavaScript MIME list now use the same Rust functions as the
    HTML checks.
  • The new PyO3 names are private (_check_output_html, three helper
    functions, and the _JAVASCRIPT_MIME_TYPES set), so citry-core has no changelog entry. The _rust.pyi stub and
    the citry_core.html_transform wrapper list them.

Measurements

Release build, the 1,400-row board, 10 fresh
processes per configuration, median of 5 serializes each, before is the
origin/main Python with the same Rust build:

before after
strict CSP serialize 559.8 ms 99.3 ms
garbage collection in it 194 ms, 3 full collections 2 ms, none
default settings 25.3 ms 25.1 ms

The strict page does not hydrate, so it cannot reach the default page's
time. With every check replaced by a no-op it takes 50.2 ms. One Rust
check of the whole page takes 25 ms, and of the body alone 22 ms. The page
is still read twice: once by the check that decides whether the Vue host
carries the body, and once by the final check. Reading the body only once
would save about 22 ms more. That is above the 10 ms threshold set for
doing that work, so it comes in a second PR and this PR does not close
#274.

How the result was checked

  • tests/_output_policy_reference.py keeps a frozen copy of the Python
    rules. test_output_policy_differential.py builds 2,000 pages from a
    fixed seed and compares both sides in every mode: the ordered findings,
    each validator's warning or error, exceptions, the HTML with omit markers
    removed, and the Vue body check's answer. It runs in about 5 seconds. A
    throwaway script made 26 small changes to the Python copy, one at a
    time; the test caught 25. The one it missed (looking up 31 characters of
    an entity name instead of 32) cannot change any rule's result.

  • With CITRY_OUTPUT_POLICY_DIFFERENTIAL=1, every check in any test suite
    also runs the frozen copy and fails on a difference. A run of the whole
    suite (-m "not e2e") passed: 13,050 passed, 145 skipped, no difference.

  • The test also compares the page the CSP check reads again after omit
    markers are removed (708 of the 6,000 shared-read cases), and a
    pre-extension read shared by both validators.

  • Rust unit tests lock the decoder, the javascript: letter rules, script
    types, base64, nesting depth, omit-marker removal, and event order.
    test_output_policy.py locks one whole message per rule, and checks that
    a strict serialize of a 500-row page never builds Python tag objects.

  • The fast repository gate (scripts/check.py --profile fast) passed, and
    mypy also passes with --platform linux.

Behavior changes

Each is its own commit with a test and a changelog line:

  1. The check that decides whether a Vue host carries the body trusted any
    tag with an attribute. It passed an empty prefix for the attribute that
    marks Citry's own tags, and every attribute name starts with the empty
    string. With
    security_csp="warn", a body with <style media="print"> was served in
    the host while a bare <style> kept an empty host. Both now keep an
    empty host. (In strict mode, both already raised, from the check of
    opaque HTML blocks.)
  2. A decimal character reference longer than 4,300 digits made
    serialize() raise "Exceeds the limit (4300 digits)" in every mode. It
    now decodes to the code point it names, or to U+FFFD past U+10FFFF.
    Leading zeros count for nothing, as in a browser, so
    &#000…0106; still reads as j.
  3. Python 3.10, 3.11 and 3.12+ accept different padding in
    b64decode(validate=True). On 3.10 and 3.11 a data:text/html;base64,
    payload with padding after a complete group (PHA+aGk8L3A+=), and on
    3.10 a payload of only = or ==, decoded and could pass. The check
    now accepts exactly what 3.12+ accepts, on every version. No payload
    that an older version rejected is accepted now; browsers reject these
    payloads too.
  4. A Rust panic in the check used to abort serialize() with PyO3's
    PanicException, which except Exception does not catch. It now
    becomes a ValueError, which the validators report as an unreadable
    page: warn modes warn and return the page, strict and forbid raise. In
    omit mode, a page that still carries Citry's omit marker raises, as
    any unreadable omit page already did.

Left unchanged on purpose (follow-up issues to file)

🤖 Generated with Claude Code

JuroOravec and others added 9 commits October 23, 2026 17:57
With security_csp set, the check of the served body copy trusts any tag
that has an attribute, so a body with <style media="print"> is served in
the host while a bare <style> keeps an empty host. This test records that
behavior before it changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The check that decides whether a Vue host carries the body passed an
empty trust-marker prefix, and every attribute name starts with the empty
string, so it trusted any tag that had an attribute. Citry adds its own
trusted dependency tags only after this check, so the check now trusts no
tag by its attributes: a body with <style media="print"> keeps an empty
host, like a bare <style>.

Part of #274.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The strict-CSP and JavaScript-policy checks decode attribute values with
html.unescape, which converts a decimal reference to an int. Python
refuses a string of more than 4,300 digits, so such a value made
serialize() raise in every mode. The decoder now drops leading zeros and
treats any number of more than seven digits as past U+10FFFF before it
calls html.unescape,
so the reference decodes to the code point it names, or to U+FFFD.

Part of #274.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The JavaScript policy decodes a data:text/html;base64 URL with
b64decode(validate=True), and Python 3.10, 3.11 and 3.12+ accept
different padding. On 3.10 and 3.11 a payload with padding after a
complete group ("PHA+aGk8L3A+="), and on 3.10 a payload of only "=" or
"==", decoded, so the policy scanned the document and could pass it.
3.12+ rejects them, and the policy then reports the document because it
cannot read it. The decoder now accepts exactly what 3.12+ accepts on
every version. No input that 3.10 or 3.11 rejected is accepted now.

Part of #274.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in Rust

A new module, output_policy.rs, reads finished HTML with the existing
browser-state scanner and applies every rule of Citry's strict-CSP and
JavaScript-policy output checks: native event attributes, javascript:
URLs, raw script and style elements, Vue activation attributes, embedded
srcdoc and data:text/html documents, omit-mode fallbacks, and removal of
the omit marker. It returns only what a rule reports, plus the script
and style elements the selected rules look at, so a page with no problem costs one scan and almost
no allocation.

The rules copy the Python versions exactly, including Python's
html.unescape decoding and its case-insensitive letter matching, so the
Python validators can replay the results without a change in findings.
output_scanner.rs gains scan_output_html_with, which hands each start tag
to a callback instead of keeping it.

Part of #274.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
serialize() with security_csp or security_javascript set turned every
tag and attribute of the page into Python objects for each check, about
400,000 objects on the 1,400-row board. The validators now call the Rust
rules through a private _check_output_html and replay only what they
report, so an ordinary tag never reaches Python. The validators keep
their messages, de-duplication keys, warn-mode memory and warn-or-raise
decisions, so reports stay the same.

When both validators check the same page, serialize() and the Events
opaque-block checks read it once for both. The Vue body check calls Rust
directly. The rules the structured Script and Style checks share with the
HTML checks (activation and event attributes, javascript: URLs, script
types, the JavaScript MIME list) now come from the same Rust functions.

tests/_output_policy_reference.py keeps a frozen copy of the Python rules.
test_output_policy_differential.py compares the two on 2,000 seeded pages
in every mode, and CITRY_OUTPUT_POLICY_DIFFERENTIAL=1 runs the same
comparison inside every check of any test suite.

Part of #274.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A panic in the Rust output check used to reach Python as PyO3's
PanicException, a BaseException, so the validators' except Exception
missed it and serialize() aborted in every mode. The binding now turns a
panic into ValueError("citry output check failed: ..."), which the
validators report as an unreadable page: warn modes warn and serve the
page (in omit mode, a page that still carries Citry's omit marker
raises), strict and forbid raise. The panic catching that native_render
already did moves to a shared panics.rs.

Part of #274.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Measured on the 1,400-row project board (benchmarks/web/apps/citry) with
a release build: 10 fresh processes per version, median 559.8 ms before
and 99.3 ms after.

Part of #274.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The Python wrapper reports only a lone surrogate or a Rust panic as an
  unreadable page; any other error from the binding, such as an unknown
  mode, is a caller bug and is raised. It accepts trusted tag starts in
  any collection, as the Python checks did.
- A shared check now records the trust options it was made with, and a
  validator refuses one made with different ones.
- A rule code a validator has no wording for is an error, not another
  rule's message.
- serialize() computes the trusted tag starts only when a check runs.
- The differential test now also compares the page the CSP check reads
  again after omit markers are removed, a pre-extension check shared by
  both validators, nested object and embed documents, more URL
  attributes, non-ASCII names, repeated attributes, and trusted raw
  elements.
- Docs, comments and the changelog say exactly when one read serves both
  checks, where the messages are written, and what happens when the check
  cannot read the page.

Part of #274.

Co-Authored-By: Claude Opus 5.5 <[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