Skip to content

Allow 'unsafe-eval' in the delivered page policy so driver waits poll - #782

Merged
max-sixty merged 2 commits into
mainfrom
fix/ci-35305477492
Sep 18, 2026
Merged

max-sixty merged 2 commits into
mainfrom
fix/ci-35305477492

Conversation

@leaf-agent

@leaf-agent leaf-agent commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Delivery now sends script-src 'self' 'nonce-…' 'unsafe-eval', so a browser driver's wait polls run under the page policy instead of being refused by it. That is the whole change: one directive plus the test that holds it.

A driver compiles a wait predicate with eval on every poll — Playwright keeps a compiled function across polls, but recompiles a bare expression each frame — and only the poll installed inside the driver's own evaluate call inherits that call's permission. Without the allowance, a wait whose fact is already true when the poll is installed passes, and a wait that actually has to wait dies on the next animation frame with EvalError. That is what the nightly job on d8c873d hit in tests/test_render_conversations.py::test_a_refused_reopen_preserves_a_filter_typed_during_restoration, and the class was latent across the suite rather than specific to that case.

test_the_page_policy_admits_a_driver_poll_that_outlives_its_evaluate sits beside the existing policy-boundary test in tests/test_render_startup.py and waits on a fact that becomes true 250ms later, so the poll must reach a second compile. Reverting the http.py line alone fails it with exactly the nightly's EvalError; with the line it passes. Nothing else in the policy moves — the boundary test still shows default-src, base-uri, form-action, and frame-ancestors refusing what they refused before, and Leaf's own runtime never evals, so the nonce still decides which script runs.

The export policy in exporting.py keeps its strict script-src data: 'nonce-…': every wait the export tests drive already names a function, and the shipped render gate instruments a standalone file through bypass_csp=True rather than through the page's policy.

What this replaces, and the checks

The first version of this PR took the other route: it wrapped all 39 wait_for_function call sites in the tree as functions and added a guard test that read every wait's JavaScript out of the Python source to hold the rule. At this stage a laxer CSP is the cheaper trade, so that is reverted; the branch carries the directive and its test, plus a second commit that drops the new test's try/finally — the function-scoped browser fixture already closes the contexts a journey leaves open — and states the allowance's reach in the http.py comment, since write_live_shell composes published documents through supervised_document too.

Checks on b0019567, with the startup policy selection re-run on ca6f97f6:

  • uv run pytest tests (the everyday gate): 1136 passed. Five failures are this sandbox's, reproduced identically on a clean f249da60 here — three test_interact_session.py cases that write under a read-only /tmp, test_staged_writes_honor_umask_without_copying_a_replaced_symlink_mode, and test_live_shell_artifact.py::test_a_browser_executes_the_published_capture_with_live_api_routes[True], which needs worker/'s node modules.
  • tests/test_render_startup.py --run-nightly whole: 96 passed.
  • The nightly case that failed, test_a_refused_reopen_preserves_a_filter_typed_during_restoration, passes with its bare-expression wait untouched.
  • ruff check and ruff format --check.
  • On ca6f97f6: tests/test_render_startup.py -k policy passes, and still fails with the nightly's EvalError when the script-src line alone is reverted.

No TypeScript changed, so neither the worker nor the browser-framework gate is in scope.

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mechanism holds — I confirmed it in the driver bundle rather than from the
symptom: coreBundle.js's poll predicate reads
evaledExpression ?? globalThis.eval(expression) and assigns evaledExpression
only in the function branches, and the first next() runs synchronously inside
injectedScript.evaluateHandle, so a named function is compiled once under the
driver's own permission and a bare expression is recompiled on every frame. All 39
rewrites are faithful: crossTabActivated, visibleReplyRecorded, and
revisionAtLeast are methods in scripts/verify-site-browser.js, which is what
Playwright was already calling for them.

One finding, on the durable half of the change.

The guard reads names per module, so seven of the eight shared wait constants are invisible to it

_javascript_names builds its name map from the module it is parsing, but the
waits the suite reuses most are constants one helper module states and the test
modules import. Measured on this head, the guard resolves 447 of 548
wait_for_function call sites and silently skips 101 — every use of
SCROLL_SETTLED (tests/render_cases_interaction.py), STORED_DRAFT_SETTLED and
RENDERED (tests/render_harness.py), SCROLL_STILL and LEGEND_TRUE
(tests/render_cases_layout.py), SCROLLED (tests/render_cases_widgets.py), and
TAB_TONE (tests/render_cases_navigation.py). None of those seven is reached
through an in-module wait_for_function either, so nothing in the repository holds
the rule over them. BOTH_STAMPS survives only incidentally, through
render_harness.py's own direct wait on it.

So the single edit that would re-break the most waits at once is the one the guard
does not see. Rewriting SCROLL_SETTLED's head into a bare expression reintroduces
the flake at 28 call sites and the guard passes — I ran that mutation against this
head and it reports 1 passed. That also makes the claim in tests/CLAUDE.md, that
the test "holds the rule over every wait the repository's Python states", not yet
true.

Pushing the fix: resolve each wait against its own module first and fall back to
names bound anywhere in the tree, dropping any name two modules bind to different
JavaScript so reading order cannot decide the result. That takes the guard from 447
to 546 of 548 resolved — the two left are a loop variable in
test_render_controls.py and navigate's ready parameter, whose default
BOTH_STAMPS is covered on its own account — and under the same mutation it now
fails, naming all 28 dependent sites.

The test_staged_writes_honor_umask_without_copying_a_replaced_symlink_mode
failure in this file is not this branch's: it fails identically at the merge base
6067849c in a worktree of its own, and nothing in the diff reaches staged writes.

@max-sixty

Copy link
Copy Markdown
Owner

Is it possible to simplify this? at this stage, we would prefer code and a lax-er CSP

A browser driver compiles a wait predicate with eval on every poll, and only
the poll installed inside its own evaluate call inherits that call's
permission. Delivery's script-src had no 'unsafe-eval', so any wait whose fact
was not already true when the poll was installed died on the next animation
frame with EvalError, which reads as an intermittent test failure rather than
as a policy refusal.

Delivery now carries 'unsafe-eval' beside the nonce, and
test_the_page_policy_admits_a_driver_poll_that_outlives_its_evaluate holds it
with a fact that becomes true 250ms after the wait is installed. Leaf's own
runtime never evals, so the nonce still decides which script runs.
@leaf-agent leaf-agent changed the title Name a function in every browser wait so no poll recompiles under CSP Allow 'unsafe-eval' in the delivered page policy so driver waits poll Sep 18, 2026
@leaf-agent

Copy link
Copy Markdown
Collaborator Author

Done — the branch is one commit on main now: delivery sends script-src 'self' 'nonce-…' 'unsafe-eval', and one test holds it. The 39 wrapped call sites, the source-reading guard, and the tests/CLAUDE.md rule are all reverted.

The test is test_the_page_policy_admits_a_driver_poll_that_outlives_its_evaluate, beside the existing policy-boundary test in tests/test_render_startup.py. It waits on a fact that becomes true 250ms later, so the poll has to reach a second compile: reverting the http.py line alone fails it with the nightly's exact EvalError. Without it the directive is a line nobody can explain, and the next tightening buys the flake back.

What the relaxation costs: an injected script gadget could eval attacker data instead of being stopped by the policy. It does not widen who can run script in the first place — the nonce still decides that — and Leaf's own runtime never evals. exporting.py's standalone policy keeps its strict script-src data: 'nonce-…', since the export tests' waits already name functions and the shipped render gate instruments a file through bypass_csp=True rather than through the page's policy.

uv run pytest tests and the whole of tests/test_render_startup.py --run-nightly pass here, as does the nightly case that started this with its bare-expression wait untouched; the five everyday failures in this sandbox reproduce identically on a clean f249da60 (read-only /tmp, and worker/'s node modules). Details are in the description.

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mechanism holds and the test is non-vacuous — checked here rather than taken from the description. Reverting the http.py line alone fails test_the_page_policy_admits_a_driver_poll_that_outlives_its_evaluate with the nightly's exact refusal (EvalError: Evaluating a string as JavaScript violates the following Content Security Policy directive), and with the line in place the case that started this, test_a_refused_reopen_preserves_a_filter_typed_during_restoration, passes with its bare-expression wait untouched. Nothing shipped under skills/leaf/assets/ or skills/leaf/packages/ contains eval( or new Function(, so the allowance wakes no dormant path in a vendored bundle, and every wait in tests/test_render_export.py names a function, so the export policy can stay strict on its own terms.

The published site carries the allowance, where no driver ever polls

supervised_document has a second caller. live_shell.write_live_shell composes every revision document through it, and scripts/site.py's build() runs publish_live_shells over every published page directory, products included. So each page on https://leaf.page/ is served to ordinary readers with script-src 'self' 'nonce-…' 'unsafe-eval', indefinitely, on a path where no driver polls anything — the static half of the site, not just the per-reader container the suite drives.

That may still be the trade that was asked for: the nonce decides which script runs either way, and no Leaf or vendored code evals, so the allowance only matters to an injected gadget that already got script execution. But it is the durable half of the cost and neither the comment nor the description names it, so the next reader of http.py sees a directive justified entirely by a test driver. Suggested wording inline. Narrowing it to the served document instead would mean a write_live_shell argument and two policies to keep in step, which is the cost the single directive was chosen to avoid — that is a call for you rather than something I would push.

Comment thread skills/leaf/scripts/leaf/http.py Resolved
Comment thread tests/test_render_startup.py Outdated
try:
page.evaluate("() => setTimeout(() => { window.lateFact = true }, 250)")
page.wait_for_function("window.lateFact === true", timeout=5_000)
finally:

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we have try / finally in tests rather than fixtures?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No good reason — removed in ca6f97f. tests/CLAUDE.md already states the rule the function-scoped browser fixture makes possible: it rejects collected problems after the journey and then closes the remaining contexts, so a test closes a page explicitly "only when the lifecycle or an earlier release matters to the journey". Neither matters here, and I had copied the shape from the policy tests above it rather than from the rule.

The residue is wider than this test: 62 finally: page.close() blocks across 12 test modules, 60 of them predating the fixture's context ownership (#667). I left them alone here to keep this branch one directive plus its test. The sweep is also a read per site rather than a mechanical delete: a close in finally runs before the fixture's health reading rather than after it, so a journey that holds a route open, or whose handler is still reading a fetched body, may be depending on that ordering. Happy to do it as its own PR if you want it.

Also applied my own pending suggestion on http.py in the same commit: the comment now names the allowance's reach, since write_live_shell composes published documents through supervised_document too. The directive itself is unchanged, and the test still fails with the nightly's EvalError when the script-src line is reverted.

tests/CLAUDE.md states the rule the function-scoped browser fixture makes
possible: it rejects collected problems after the journey and then closes the
remaining contexts, so a test closes a page explicitly only where the lifecycle
or an earlier release matters to its own reading. The new policy test's
try/finally was copied from its neighbours and matters to neither.

The http.py comment also now names the allowance's reach: write_live_shell
composes published documents through supervised_document, so the site's static
pages carry it to readers no driver polls.
@leaf-agent

Copy link
Copy Markdown
Collaborator Author

The same EvalError refusal came back on main's nightly for dd8e0de, in test_a_refused_reopen_preserves_a_filter_typed_during_restoration again — so this is live on main rather than a one-off on d8c873d.

That run's other failure, test_a_restored_auxiliary_surface_has_final_geometry_before_runtime_loads, is unrelated: it reads geometry before the render-blocking theme applies. #807 carries it, and nothing in it touches the delivery policy.

max-sixty pushed a commit that referenced this pull request Sep 18, 2026
`test_a_restored_auxiliary_surface_has_final_geometry_before_runtime_loads[saved0-…]`
failed on main's nightly for
[`dd8e0de`](https://github.com/max-sixty/leaf/actions/runs/35378363742)
because its first geometry reading was taken before the page's
render-blocking theme applied: it compared the user agent's own layout
of the authored HTML against the themed page and reported the difference
— the whole theme — as restoration moving the shell. The four
pre-runtime measurements in the suite now wait for first contentful
paint, through one new harness helper.

A box is not a paint. `bounding_box`, and Playwright's `to_be_visible`
with it, force a layout that answers from the stylesheets that have
arrived so far; a render-blocking stylesheet still in flight holds the
*paint* back but not that forced layout. So
`expect(page.locator("h1")).to_be_visible()` returns with a box the
theme has never touched, and the reading behind it is the user agent's.
Holding `theme.css` open on this page produces the nightly's two numbers
exactly:

```
theme held:   {'x': 8,     'y': 21.4375, 'width': 1584}   sheets 0  paint 0
theme landed: {'x': 136.5, 'y': 42,      'width': 768}
```

`displayed(page)` waits on `first-contentful-paint`, which is the
browser's own record that the render-blocking head has been applied and
what it composed is on screen. That is the state each of these tests
means to measure, since each one asks what a reader sees before the
runtime loads — so the wait states the test's own premise rather than
adding a tolerance to its assertion. Three other tests took the same
reading behind element visibility alone and carried the same latent
failure: `test_authored_html_paints_while_runtime_startup_is_held`
beside it, and the two site shells in `test_site.py`. All four take the
wait now, and `tests/CLAUDE.md` states the rule next to `BOTH_STAMPS`,
where the readiness facts a test may consume are already listed.

No product code changes. The page's pre-runtime geometry was already
right: every one of these tests passes once the theme has applied.

<details><summary>Bug-back and checks</summary>

The window is small enough that the case passes on a warm rerun, so the
bug-back widens it with the browser rather than with repetition: 400ms
of CDP-emulated latency on every response, applied to a copy of the
failing test parameterized on whether it takes the wait. Without
`displayed` it fails with the nightly's exact reading (`x 136.5 vs 8 ±
1`, `y 42 vs 21.4375 ± 1`, `width 768 vs 1584 ± 1`); with it, it passes.
Held-route probing gave the reading above, which is where the numbers
came from. Both were re-run on `78f9ba7a`, this branch's base, after the
theme change landed there.

- `uv run pytest tests/test_render_startup.py --run-nightly`: 95 passed.
- `uv run pytest tests/test_site.py -n0 --run-nightly -k
"paints_in_its_final_position or every_stage_of_site_startup"`: 2
passed.
- `uv run pre-commit run` over the four changed files: passed.
- The everyday gate, `uv run pytest tests`, on the same diff over
`dd8e0de`: 1136 passed, 5 failed. Those five are this sandbox's: three
`test_interact_session.py` cases and
`test_staged_writes_honor_umask_without_copying_a_replaced_symlink_mode`
fail on a read-only `/tmp` and on the file mode this container returns,
and `test_live_shell_artifact.py` wants `worker/`'s node modules, which
are not installed here. None of them load a browser.

The same nightly carried one more failure,
`test_a_refused_reopen_preserves_a_filter_typed_during_restoration`,
refused by the delivered page's CSP. That is #782's, and nothing here
touches it.

</details>

Co-authored-by: leaf-agent <[email protected]>
@max-sixty
max-sixty merged commit eb04198 into main Sep 18, 2026
5 checks passed
@max-sixty
max-sixty deleted the fix/ci-35305477492 branch September 18, 2026 23:41
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.

2 participants