Skip to content

Gzip pages too, with the CSRF token masked afresh on every render (#63, stacked on #126) - #306

Open
r0ny123 wants to merge 19 commits into
masterfrom
perf/compress-html-masked-csrf
Open

r0ny123 wants to merge 19 commits into
masterfrom
perf/compress-html-masked-csrf

Conversation

@r0ny123

@r0ny123 r0ny123 commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #126. Merge it first; until then this diff also shows its commits. This PR's own is the last one, ce8d7ad.

Part of #63. #126 gzips stylesheets, scripts and JSON, and leaves pages alone (mcritweb/compression.py on #126). A page carries the session's CSRF token next to input it reflects, such as a search term. While the token is the same in every response, that is what a BREACH attack needs to read it out of the lengths of compressed responses. This masks the token afresh on every render, so it is never the same twice, and compresses pages too. The settings and server pages show other secrets, so they stay uncompressed.

Change.

  • csrf_token() (mcritweb/csrf.py:52) returns the session token masked behind a fresh random pad. The value is hex of the pad followed by the token XOR the pad, the scheme Rails uses.
    • validate_csrf() (mcritweb/csrf.py:100) unmasks a submission of that length and compares it in constant time, as before.
    • Anything else is compared as it came, so the bare token of a page rendered before this change still works.
    • The session keeps the same token.
  • mcritweb/compression.py no longer leaves text/html out.
    • A view that shows another secret is marked @uncompressed (mcritweb/compression.py:40), and its responses are left alone. The marked views are authentication.settings (mcritweb/views/authentication.py:411), which shows the user's API token, and administration.server and administration.change_server (mcritweb/views/administration.py:302, :314), which show the registration token and the backend's token.
    • The username is printed on every page a signed-in user sees, next to a search term on some. It is not a secret, and those pages are compressed.
  • Docs:
    • ADR-0002 takes "no per-response token variation" off the list of what the hand-rolled CSRF lacks, and says why.
    • ADR-0017 and the README say which responses are compressed and which are not. The README tells a proxy that compresses on its own to keep text/html out of its gzip_types.

Verification. On the testbed, #126's head (4c80af2) and this branch (ce8d7ad) ran as side instances against the live backend, logged in as analyst1, an admin. Apart from the logins, the only POSTs were the function page's own to /explore/findLoops/, which computes an answer and writes nothing.

Bytes on the wire for a client that accepts gzip (curl). Each cell is one render. On the branch the masked token and the timestamps make a page's size vary by a few bytes between renders.

page #126 this branch
/ 29,711 7,826
/explore/samples 107,605 13,623
/explore/samples/1 66,427 12,105
/explore/functions/83 46,790 11,108
1vN result 6ab3b4455ccfc2538ffea9b6 226,839 14,854
cross compare result 6ab3bc93e867efea4ffec3c5 46,672 11,874
unique blocks result 6ab3b4465ccfc2538ffea9c4 136,294 25,207
/data/matches/function/549/2356 69,410 15,572
/help 51,388 16,843
/data/jobs?active=getMatchesForSample 72,113 11,239
/settings (not compressed) 46,086 47,046
/admin/server (not compressed) 27,552 29,472

The two uncompressed pages grow by 192 bytes for each token they carry, since a masked token is four times the token's length in hex.

Lighthouse 12.8.2, mobile. The two sides ran in turn, page by page, two runs each. Performance is given for each run; FCP and LCP are the mean of the two.

page Performance FCP LCP
/ 96/95 -> 96/97 1.68 -> 1.64 s 2.73 -> 2.60 s
/explore/samples 87/91 -> 93/96 2.29 -> 1.73 s 3.18 -> 2.59 s
/explore/samples/1 92/89 -> 93/92 2.06 -> 1.88 s 3.03 -> 2.74 s
/explore/functions/83 69/65 -> 73/69 3.08 -> 2.81 s 4.82 -> 4.47 s
1vN result 6ab3b4455ccfc2538ffea9b6 83/83 -> 88/95 2.75 -> 1.96 s 3.92 -> 2.89 s
/help 80/80 -> 81/82 1.91 -> 1.73 s 4.99 -> 4.82 s

On #126, jQuery and the project's scripts still block rendering on both sides; #245 and #304 defer them. What this PR changes is the size of the page itself. The other three categories are the same on both sides. Best Practices is 93 on both, because base.html has no viewport meta tag, so the viewport and font-size audits fail. #253 adds the tag; this PR does not touch it.

Tests.

Relation to open PRs. A trial merge (git merge-tree) with each open PR head. #126 already conflicts with #160 and #176. This PR adds a conflict in one more file:

#253's new column-settings forms read their token from the page's csrf-token meta tag through csrfToken() (static/post_action.js), as the other script-built forms do, so they carry a masked one too. A page that prints a stored secret in future needs @uncompressed on its view. The template scan says so when the secret's name contains "token".

Master 8fd5a8c is merged in directly (a1819d0), with #126's part resolved as on #126, and two adaptation commits: 6e392fe leaves #254's users page, which names the holders of legacy tokens and the button that rotates them, out of the scan for printed tokens, and 5a3dfae regenerates the icon subset for master's new icons.

r0ny123 added 16 commits August 30, 2026 04:44
Issue #63, first bullet: "remove data-tables js/css once it is not needed
anymore". base.html loaded 623 KB of render-blocking JavaScript and 41 KB of
CSS on every page in the app, for two calls.

DataTables is removed outright, not moved. Its one initialiser selected
`#job-table`, and the jobs page renders its table with `table_id=active` -
the job method - so the selector matched nothing on every request. Confirmed
against the running app: `id="job-table"` appears in zero of /data/jobs,
?active=..., ?state=... and /. It was also configured with paging, searching
and info all off, so even where it had matched it would only have restyled
the table.

jQuery UI moves to result_cross.html, the only page that calls `.sortable()`.
{% block style %} runs after base.html's scripts, so jQuery is in place first.

Measured with Chromium, total decoded bytes per page:

    /                     1667 KB -> 1017 KB
    /explore/samples      1667 KB -> 1017 KB
    /data/jobs            1667 KB -> 1017 KB
    /data/result/<cross>  1691 KB -> 1595 KB   (keeps jQuery UI)

Behaviour is unchanged: `.sortable()` still applies on the cross compare, the
clipboard tooltips still get Bootstrap instances rather than jQuery UI's -
both libraries define `.tooltip()`, and removing jQuery UI makes which one
wins deterministic rather than a load-order race - and no page logs a console
error.

Deliberately not done: `defer` on the remaining scripts, and removing jQuery.
Both need an audit of 23 inline blocks and 36 onclick handlers, several of
which call functions declared at the top level of those blocks; that is a
separate change. The remaining majority of the render-blocking weight is CSS,
not JS - bootstrap.css alone is 196 KB and is the unminified build.
Every unit job on every Python version fails with:

    /opt/hostedtoolcache/Python/3.11.16/x64/bin/python: No module named pytest

The Makefile said "pytest and pytest-cov arrive with mcrit, so requirements.txt
covers both". mcrit declares them under its `dev` extra:

    $ python -c "import importlib.metadata as m; print(m.requires('mcrit'))"
    ... 'pytest; extra == "dev"', 'pytest-cov; extra == "dev"' ...

so a plain `pip install -r requirements.txt` does not bring them in, and the
suite has not actually run in CI since mcrit moved them there. Ruff is green
throughout, which is why this looked like a working pipeline.

Installed in the workflow rather than added to requirements.txt: neither is a
runtime dependency and a deployment should not get them. Pinned, for the same
reason the lint job pins ruff. The two stale comments that said otherwise are
corrected.
`init` still ran `pip install -r requirements.txt` alone, so a fresh checkout
that follows the README lands without pytest and `make test` fails with
"No module named pytest" - the same failure the CI change on this branch fixes
for the runner, left unfixed for a contributor.

pytest and pytest-cov are not runtime dependencies and are not in
requirements.txt; mcrit declares them under its `dev` extra, which nothing
here requests, so they do not arrive transitively either. Install them from
`init`, pinned to the versions CI uses, and say so once above the target
rather than in a comment further down that describes a step that never ran.

Reported by Codex review.
…rst one was safe

The previous commit did #63's first bullet. The other four are "consider", "enable
text compression" and "what to inline"; a recorded, measured decision is the
resolution for those, so ADR-0015 makes them. Numbers first, all from Chromium
driving the app over real HTTP against the captured corpus.

  * text compression is the largest win left, and it is not ours. Nothing is
    compressed anywhere: Flask's static handler does not, and neither does the
    reference deployment - nginx.conf, mcritweb_plain.conf and mcritweb_ssl.conf in
    danielplohmann/docker-mcrit at 7e9501a carry no gzip directive, and location /
    proxies /static/ straight through. Simulating `gzip on;` in front of this branch,
    cold Fast-3G load of /, median of 7: first paint 3872 ms -> 1024 ms, wire
    1,069,548 B -> 354,002 B. That is more than the whole of the first bullet, and it
    belongs in docker-mcrit.

  * lazy dropzone: right target, wrong shape today. dropzone.js is 353,924 B, 38% of
    every page, but it loads at the end of <body>, so blocking it outright - an upper
    bound - moves first paint by 8 ms. It buys DOMContentLoaded (1585 -> 1009 ms) and
    23% of the transfer. The cost is Flask-Dropzone: dropzone.config() emits
    Dropzone.options.myDropzone *after* the library and only works because discovery
    waits for DOMContentLoaded. Injected late, contentLoaded() sees readyState
    "complete" and binds the element with default options - no CSRF header, no
    autoProcessQueue: false. Doing it right means replacing create()/config() by hand
    in the one place static/dropzone.js's local patch has to keep working.
    "autocomplete on mouseover" is 4,621 B, 1,507 gzipped: no.

  * removing jQuery: no. 15 of 26 inline blocks call $, 36 inline event attributes
    hang off them, trace_CFG/main.js and main_duo.js expect it from base.html, jQuery
    UI cannot load without it, and .tooltip()/.modal() go through Bootstrap's jQuery
    bridge. 89,503 B, 30,882 gzipped - under 9% of a compressed page.

  * inline vs reference is already right: 7,141 B of inline JS against 902,940 B of
    referenced library. The remaining CSS weight (bootstrap.css is the unminified
    build) compresses 8x, so gzip answers that too.

ADR-0004 asked #63 to assert rather than assume which library owns $.fn.tooltip, and
called the current arrangement a load-order race. Measured, it is not one. Bootstrap
5.0.2 defines its jQuery plugins on DOMContentLoaded, after every plain <script> in
the document, so it wins the name in both arrangements - jQuery UI before it, as
base.html used to, and after it, as result_cross.html now does. Checked on every page
that renders a [data-toggle="tooltip"] target: $.fn.tooltip.Constructor.NAME is
"tooltip", bootstrap.Tooltip.getInstance(el) is set, $(el).data("ui-tooltip") is not.
What does flip it is loading jQuery UI *after* DOMContentLoaded, which is exactly what
a lazy loader would do - so the hazard is lazy loading, not ordering.
test_bootstrap_is_loaded_synchronously pins that.

The one factual correction: the previous commit said DataTables' initialiser "selected
an element the app never renders". The app does render id="job-table" - job_table
still defaults to it and job_overview and single_sample take the default, confirmed on
/explore/samples/1. What made DataTables dead is narrower: the initialiser lived on
the jobs page, which passes table_id=active. The removal stands; the reason in the
comments and the test docstring did not, and now says what was measured.

New tests, each mutation-checked by breaking the code it guards:

  TestTheJobsPage             - none of the three jobs views renders id="job-table"
  TestTheCrossComparePage     - the rendered page ships jquery-ui, jquery.js reaches
                                it first, and no other page ships it at all
  test_only_base_html_loads_a_jquery      - both CFG templates' second jQuery stays
                                            commented out
  test_bootstrap_is_loaded_synchronously  - no defer/async on the bundle

code_of() now strips HTML comments as well as Jinja ones, which is what makes the
second-jQuery check see the commented-out includes as absent rather than present.
…zone, gzip

Font Awesome is reduced to the icons the templates use, Bootstrap ships
minified and deferred, the Dropzone script and stylesheet load on the first
drag or on opening the modal, and responses over 1 KiB of compressible types
leave gzipped (MCRITWEB_COMPRESS_RESPONSES turns it off behind a proxy that
compresses itself).
ADR-0015 had left compression to the proxy and the other bullets to a later
audit. Both happened; 0015 is marked superseded and 0016 holds the
measurements and the rules that follow from them.
The type-ahead conflicts are the ones that matter. This branch's side of
js/ac_family_names.html and the submit dropzone still carried the old
family-name code - names shipped with |tojson and pushed unescaped into a
widget that renders suggestions through innerHTML, which is the injection
master closed in #168 (and #146 moved to a JSON endpoint). Master's
escaped code is kept in both places; what this branch contributes there
is only its reason to change them, that Bootstrap is now deferred, so the
widgets are built once the deferred scripts have run. In
ac_family_names.html the DOMContentLoaded listener is also the scope,
replacing master's IIFE, so this branch's timing test can see it. The
Playwright tests that drive the real widget pass with Bootstrap deferred.

The rest:
- base.html: the minified Bootstrap and the Font Awesome subset, with
  master's signed-in font preload (#62) - the subset loads the same
  ../webfonts/fa-solid-900.woff2 the preload names; Bootstrap and
  post_action.js deferred, page_loading.js kept a plain script as master
  has it; clearDropzone keeps the lazy-load guard with master's const.
- the dropzone keeps mcritInitDropzone(), with master's const myDropzone
  (#61) - nothing outside that function uses it.
- import.html takes master's import status script, with dropzone.min.js.
- README keeps the compression paragraph and master's reverse-proxy
  section.
- the Font Awesome subset is regenerated for three icons master's
  templates added (arrows-rotate, code, diagram-project), nothing else
  changes in it; the subset script lists the webfont file stems as
  non-glyphs, since master's preload and its comment name
  fa-solid-900.woff2 and the icon scan read that as an icon.

1026 passed, ruff clean.
…libraries

Master replaced the family names shipped with each page by a type-ahead that
fetches them as they are typed (#192), and the submit dropzone now includes
js/ac_family_names.html instead of building its own list. Kept master's
widget and this branch's reason to touch it: Bootstrap is deferred, so the
widgets are built in a DOMContentLoaded listener rather than master's IIFE.
The dropzone macro takes master's signature without `families` and keeps
`lazy`, which base.html's overlay still passes.
The lazy loader, the query and submit pages and the import page loaded
static/dropzone.min.js, which is stock Dropzone 5.9.2. Only dropzone.js
carries the patch that sends the head of a dropped file, so a drop posted
no file_header and the submit form was no longer pre-filled. All three
load dropzone.js again; dropzone.min.js is the retired file now.

A failed fetch of the script left mcritDropzoneLoading set, so the overlay
never opened again on that page. It is cleared on error, and the next drag
tries again without adding a second stylesheet. A dragover while the
script is on its way no longer queues the same callback again. The two
URLs go into the script through |tojson.
send_file answers If-None-Match against the plain ETag before the
after_request hook renames it, so a client revalidating its gzipped copy
never matched and downloaded every asset again. The conditional check is
made again against the renamed ETag.

HTML is no longer compressed. A page carries the session's CSRF token, the
same in every response, next to input it reflects, which is what a BREACH
attack needs. Downloads, the /api passthrough, bodies of unknown length
and bodies over 1 MiB are left alone too: the exports and the cached
result download are streamed so that they never sit in memory whole, and
reading them in to gzip them undid that.

gzip;q=0 is a refusal; request.accept_encodings reads it as one. The
README said docker-mcrit's NGINX compresses; its configuration has no
gzip directive (ADR 0015).
…irect in its test

Master's templates now use fa-pen, which the Font Awesome subset did not carry, so
scripts/subset_fontawesome.py is rerun. /data/jobs now redirects to the URL that
names its first tab, so the DataTables id check follows the redirect to the page
that is actually rendered.
Batch C brought master docs/adr/0016-slow-function-search-is-mcrits.md,
so this branch's 0016 shared the number. The record moves to 0017 and
ADR-0015's status line points at it; nothing else names the file.
A page carries the session's CSRF token next to input it reflects, a
search term, which is what BREACH needs to read the token out of the
lengths of compressed responses while the token is the same in every
one. generate_csrf() now hands out the token XORed with a fresh pad,
pad first, as Rails does, and validate_csrf() unmasks a submission of
that length; the bare token is still accepted. With that, text/html is
compressed like the other text types.

The settings page shows the user's API token, and the server page the
registration and backend tokens, secrets that are the same in every
response. Their views are marked @uncompressed and left alone. A test
scans the templates for printed tokens and fails when a page that
prints one is not marked.
r0ny123 added a commit that referenced this pull request Oct 26, 2026
Submitting a binary whose sha256 is already a sample stopped at
"Sample was already in database" without asking MCRIT, and promoting a
binary query did the same. With familiary/mcrit#306, MCRIT replaces the
analysis of a sample whose sha256_verified is false or null with its
own disassembly of the uploaded bytes, so a user holding the real
binary of a report-submitted sample could not verify it from here.

Both routes now send the binary when the known sample is not verified
(False, None, or no attribute on an older mcrit package) and go to the
job. Blank family and version are sent as None, since mcrit applies
what the upload names to the replaced sample. An mcrit without #306
answers 409, which addBinarySample returns as None, and the routes then
fall back to the old message and the sample page. A verified sample
and an .smda report of a known sha256 are unchanged.
# Conflicts:
#	mcritweb/__init__.py
#	mcritweb/templates/base.html
#	mcritweb/templates/table/submit_or_query_dropzone.html
#	mcritweb/views/administration.py
#	mcritweb/views/authentication.py
Master's #254 adds a notice to the users page naming the accounts that
still hold a pre-1.5.0 token, and a button that regenerates them. Neither
prints a token, so the page stays compressed, and the scan's list of
names that are not secrets takes in legacy_token_user_ids and the
button's endpoint.
Master's legacy-token notice and statistics page use fa-key and
fa-triangle-exclamation, which the cut stylesheet did not name.
Regenerated with scripts/subset_fontawesome.py; the fonts are unchanged.
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