Repository navigation
Keyless: refuse cross-site browser requests, and the missing adversarial suite - #3
Conversation
Origin is not enough to tell that a browser started a request. No engine attaches it to a same-origin GET, nor to a cross-site GET issued in no-cors mode, and a no-cors fetch aimed at http://127.0.0.1:<port> really does arrive: only Chromium withholds it, through Private Network Access, which Firefox and Safari have not shipped. Against a live server on the current head, a request shaped exactly the way those two emit it was served the model list keylessly under inference, and reached the management handlers under full. Sec-Fetch-Site says who initiated the request, on every request whatever the mode, and a page cannot forge it: the Sec- prefix makes it a forbidden header name. Only cross-site and same-site are refused. same-origin is Studio's own page and none is the user typing the URL, so both stay admitted. Absence stays admitted too, and has to: curl, the OpenAI SDKs and Safari before 16.4 send no Sec-Fetch-* at all, and serving them is the point of the setting. That also means the header is only there to be read where the transport is a potentially trustworthy URL, so this narrows full scope, which is loopback-only, more tightly than plain-HTTP LAN inference. It never widens either. Adds the adversarial suite the feature was missing, in its own file so the existing test budget is untouched: scope=off refused through the security dependency rather than only through scope_covers, the settings route that grants the scope refusing to let a keyless caller widen it, public bind and public peer, management routes under inference, root_path and trailing slash driven end to end, the dynamic /v1/models/ prefix pinned to the one handler it can reach, a session JWT naming an unknown subject, the ASGI twin of the header rules, every hosted-mode flag, the full-scope denials with the tunnel flag cleared so they are not over-determined, and the revoke-after-admission race from the review, pinned directly since the original reproducer can no longer run on this head.
biome check reports useExhaustiveDependencies on the effect that reloads keyless settings: cloudflareUrl is in the dependency list but never read in the body. That is deliberate. It is there so a tunnel appearing or going away re-fetches exposure from the backend and the warning copy stays current. Annotated the way the rest of the frontend annotates a trigger dependency, so the file is clean.
The setting adds an admission path and must never take one away. A working key or session has to keep authenticating on every scope and on every transport, including the ones keyless itself is refused on: public bind, active tunnel, Colab, --secure, and the browser shapes the Sec-Fetch-Site rule now rejects. A usable bearer is resolved before any scope or transport check runs, so nothing in the gating can reach it, and this holds that shape in place. It also asserts the credential authenticates as itself rather than through either keyless scheme. That is not cosmetic: the middleware classifies a key-bearing request as non-keyless precisely so an existing API client keeps its own tool policy, and a downgrade would quietly take away tools it already had. Removing the APPROVED_DUMMY_BEARERS clause from the dependency fails this test with "api_key was downgraded to keyless on loopback/inference". Revoked and expired keys are re-checked at the widest scope in the same test, so the two directions cannot drift apart.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2c689a892c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for scope_name in ("off", "inference", "full"): | ||
| set_keyless_api_access(scope_name) | ||
| for label, transport in transports.items(): | ||
| lan_access.lan_listener_status = lambda t = transport: { |
There was a problem hiding this comment.
Restore lan_listener_status after the credential matrix
Assigning directly to lan_access.lan_listener_status leaves the fake installed after this test. In a serial run—or whenever xdist schedules subsequent tests on the same worker—test_lan_access_settings.py therefore observes the final hard-coded listener instead of the real listener state, causing later assertions such as the failed-start and stopped-listener checks to fail or become meaningless. Use the monkeypatch fixture (or save and restore the original in finally) so the replacement is scoped to this test.
Useful? React with 👍 / 👎.
|
Superseded by unslothai#9683. unslothai#9102 merged before this landed, so the same three commits are now rebased onto main and targeted there instead. Thanks for the feature, and sorry for the fork-PR detour: I could not push to this branch directly even with maintainer edits on. |
…nslothai#16312) ## Summary SDXL sessions in Studio were slower than eager (`speed_mode=off`) while the deferred per-block U-Net compile was still running. Each render waited for a slice of that compile. On L4, renders 3-10 took 12.0-19.6 s against 9.5-10.0 s eager. On A100 the compile never finished within 20 back-to-back renders, and the session took 91-95 s against 56 s eager. With this change the background compile runs only while no render is running. A back-to-back session now runs at eager speed or better from the 3rd image on. A session with idle time between images still reaches the compiled speed. Its renders stay at eager speed until the compile is done. ## Root cause `_wait_or_pause_bg_compile` (diffusion.py) called `BackgroundCompile.pause(budget_s=slice)`. That call made each render wait for three things, one after another, before it could start: 1. The slice itself (`UNSLOTH_DIFFUSION_BG_COMPILE_SLICE_S`, default = the load's fastest eager render: 9.4-9.7 s on L4, 2.7 s on A100). 2. The block graph in flight. The compile could only park at a block boundary (`yield_point`), so the render waited for that graph to finish: 0.3-5.3 s per render on L4 with the slice set to 0 (logs from the earlier round). 3. One more block graph after every resume (`_owe_graph`), the guard that kept back-to-back renders from starving the compile. Running the render next to the compile is not an option. That compile is pure-Python dynamo / inductor work holding the GIL, and an earlier attempt measured renders 11-15x slower next to it. This is also why a shorter slice did not help: the render still waited at a block boundary. ## Change `diffusion_bg_compile.py`, idle-only mode (default on): - **No slice, no wait, nothing owed.** A render stops the compile right away. The compile resumes only once no render has run for `UNSLOTH_DIFFUSION_BG_COMPILE_IDLE_S` (1 s). The kick itself also waits that long, so the response of the 3rd image is not slowed. Back-to-back renders (the next request arrives within 1 s) leave the compile parked. With idle time between images, the compile runs during the gaps. - **Mid-trace freeze** (resident denoiser, Python 3.12+). The compile thread no longer runs on to the end of its block graph. It is frozen at its next Python call through `sys.monitoring` PY_START, typically 1-13 ms after the render asks. Safety rules: - The callback only acts on the compile thread, and only inside torch's compile (`torch._dynamo` / `_inductor` / `_functorch` frames). - It never parks with a lock-taking module on the stack (logging, structlog, tqdm, imports, warnings, threading / concurrent, the inductor compile-worker pool, Studio's compile config). - It never parks in a Studio frame that is inside one of its lock blocks. Those blocks are found from the function's AST, so the CUDA-graph wrapper the sample replay runs through is not refused as a whole. - Frame verdicts are memoised per pause, so a refused region stays cheap. - The event is switched off as soon as the thread parks. - **compile_lock.** dynamo's `compile_lock` is wrapped (same RLock). A thread that needs it while the frozen compile holds it lets the compile finish that one frame, and the compile then freezes again, instead of deadlocking. - **Blocked compile thread.** A compile thread blocked without the GIL (a Triton / C++ build in the pool, a subprocess) costs the render nothing. The render does not wait for it: if the thread's innermost frame does not change for 20 ms, the render goes ahead. - **Offloaded denoisers** are not frozen (their eager forward moves weights). For them, and on older Python, the compile parks at the next block boundary with no slice and nothing owed. - **Diagnostics.** A render that took more than 0.1 s to stop the compile logs where and why. `describe()` gains `idle_only`, `freezes`, `thaws`, `pause_wait_s`. Kill switches: - `UNSLOTH_DIFFUSION_BG_COMPILE_IDLE_ONLY=0` restores the previous slice behaviour exactly. The old tests run under it. - `UNSLOTH_DIFFUSION_BG_COMPILE_FREEZE=0` keeps idle-only but stops only at block boundaries. LoRA renders still wait for the whole compile, as before. Whole-module compiles (DiT families, `UNSLOTH_DIFFUSION_UNET_REGIONAL=0`) do not yield, so they keep their current wait path. ## Results SDXL 1024^2, 25 steps, dpmpp_2m karras, a fresh Studio home and inductor cache per cell, 20 new prompts per cell, one warm-up render first. The base is the PR's merge base at the time of each run (`b1b286c9b7` for L4 #1 / A100 #1, `d6ab4f64ac` for the rest; the commits in between do not touch these files); head is base plus this change. Eager is base with `speed_mode=off`. Gap = 8 s idle before each render after the first, not counted in the time. rN = repeat N. **Back-to-back, total seconds for 20 images (same VM per row)** | VM | base default | head default | base eager | head renders 3-20 | eager renders 3-20 | |---|---|---|---|---|---| | L4 #1 | 241.73 / 236.47 | **191.90 / 191.86** | 193.14 / 192.33 | 9.33-9.69 | 9.49-9.89 | | L4 #2 | 242.05 / 242.07 | **196.95 / 196.76** | 197.80 / 198.11 | 9.57-9.81 | 9.74-10.01 | | L4 #3 | - | **195.25** | 195.50 / 196.21 | 9.53-9.68 | 9.67-9.90 | | A100 #1 | 94.66 / 91.48 | **56.05 / 55.97** | 55.88 / 56.26 | 2.66-2.71 | 2.77-3.03 | | A100 #2 | - | **55.87** | 55.79 / 56.16 | 2.66-2.69 | 2.77-2.87 | On base, L4 renders 3-10 take 12.0-19.6 s. A100 base renders take 3.0-8.3 s across all 20, because its compile never finishes. **With idle gaps (the compile gets idle time)** | VM | base default | head default r1 / r2 | base eager | head: first compiled render | head renders 3-9 (eager at the same index) | then | |---|---|---|---|---|---|---| | L4 #3 | 211.77 (renders 3-5: 17.2-19.6 s) | 196.10 / **189.42** | 198.09 (eager, same gaps) | render 10 (compile 136 s, 7 pauses) | 9.70-9.89 (9.85-9.97) | 8.86-8.95 | | A100 #2 | 58.45 (renders 2-7: 3.4-4.8 s) | 57.70 / **52.42** | 56.08 (eager, same gaps) | render 10 (compile 74 s, 6 pauses) | 2.67-2.94 (2.79-2.81) | 2.25-2.30 | - Stop latency: 23 of 26 pauses froze the compile mid-trace within 0.001-0.013 s. The other 3 stopped it within 0.16 s. - On A100, 3 of the 14 head renders in that window ran above eager, by 0.03, 0.13 and 0.14 s (2.83 / 2.92 / 2.94 s). The other 11 were at or below eager. - The first compiled render (L4 10.13-10.16 s) includes the first CUDA-graph capture. Base pays the same cost (10.33 s). **A/A** - Repeated eager arms: within 0.4 s per session on L4 and 0.4 s on A100. - Repeated head arms: within 0.2 s per session back-to-back. - Head r1 / r2 back-to-back: pixel-identical images (LPIPS 0 on all 20, both cards). **Images** - Head back-to-back vs base, A100: identical on all 20 (LPIPS 0). Base never compiled there. - Head back-to-back vs base, L4: identical before base's compile finished (9 of 20), compiled-vs-eager differences after (mean LPIPS 0.033, max 0.098). Base A/A shows the same split. - With gaps on L4: head vs base 13 of 20 identical, mean 0.022. **Another compiled family:** FLUX.2-klein-4B (4 steps, whole-model compile path). Head and base give identical images (LPIPS 0, 6 of 6) and the same times, 2 repeats each on A100 and L4: - A100: 0.75-0.77 s per image on both. - L4: 2.11-2.17 s per image on both. ## Tests - New `tests/test_diffusion_bg_compile_idle.py`. Every test errors on base (`IDLE_ENV` / `pause(freeze=)` do not exist there). Real dynamo traces on CPU check that: - a render freezes the compile inside a running trace within 0.2 s, with no progress while the render holds the pause; - the event is off once parked; - the compiled output after resume matches eager; - the resume waits out the idle grace; - back-to-back pauses never wait and owe nothing; - without freeze, the compile parks at the next block boundary; - close ends a parked or a frozen compile; - another thread compiling while the trace is frozen does not deadlock: one thaw, then the compile freezes again; - the frame refusal rules hold (a Studio frame is refused only inside its lock block; `GraphedForward._eager` is not a lock block; the memoised walk matches a fresh one); - the compile_lock proxy behaves like the RLock it wraps; - the render-side routing is right (resident freezes, offloaded does not, LoRA still waits). - `tests/test_diffusion_unet_block_compile.py`: the slice-mode tests now run with `UNSLOTH_DIFFUSION_BG_COMPILE_IDLE_ONLY=0` and still pass. - Related suites (bg compile float seeds / state objects, U-Net block compile, Z-Image CFG split, cold start, speed, block graph, CUDA graph, offload CUDA graph, video i2v): 610 passed, 7 failed. The same 7 fail on base: `test_diffusion_cuda_graph.py::test_capture_then_replay_uses_one_graph_and_copies_statics` (passes alone, order-dependent) and 6 in `test_video_i2v.py`. ## Not proven - Renders 1-2 of a session are still slower than eager on base and head alike: about +0.3 s at the 2nd image and +1.7-2.0 s at the 3rd (L4 11.7 s vs 9.8 s eager, A100 4.8 s vs 2.8 s). This is the deferred profile's own cost: it warms the compile pool at the 2nd image, then at the 3rd engages channels_last / fused QKV / fused VAE and pays a first fused VAE decode of 1.5 s. It is not the background compile, and this change does not touch it. - The first head cell on each VM ran its engagement render at 17.1-17.5 s (L4) and 10.5 s (A100). Later head cells ran it at 11.7 s and 4.8 s. This points to the first use of a fresh source tree on the VM, not to this change. It was not isolated. - A back-to-back client never gives the compile idle time, so it stays at eager speed for the whole session (it never gets the compiled speedup, 9.7 vs 8.9 s on L4). - Freeze safety rests on a deny list of lock-taking modules and an AST scan of Studio functions for `with ...lock...` blocks. Locks held by C++ code or by modules outside that list are not covered. - Not every row ran the final code: - L4 #3 and A100 #2 ran the final code (base `d6ab4f64ac`). - L4 #2 ran it before one deny-list change (base `d6ab4f64ac`): `torch._inductor.async_compile` was still refused, which kept the compile running beside 5 renders for 0.7-1.6 s, and structlog / rich were added later. - L4 #1, A100 #1 and the FLUX.2-klein rows ran an earlier revision (base `b1b286c9b7`). In that revision every Studio CUDA-graph frame was refused, so with idle gaps the compile was never frozen and ran beside the renders (30-370 s renders); that is fixed in the final code. Its back-to-back rows never reached that path: every pause found the compile already parked at a block boundary. - With the final code, no hang or slow render beyond the numbers above was seen across the 9 SDXL cells of L4 #3 / A100 #2 (180 renders). - One A100 run lost its disk mid-run (`OSError: [Errno 5] Input/output error`), and its last cell hung with no output. It was counted as infrastructure and rerun on a fresh VM (A100 #2). That hang was not root-caused. - Measured on L4 and A100 (Colab, Python 3.13, torch 2.13) only. Not run: T4, H100, B200, AMD, Mac, Windows, Python 3.11 (where the block-boundary fallback applies), offloaded SDXL budgets, LoRA sessions, the HTTP server path (cells call `DiffusionBackend.generate` in process).
Merging this into
feat/studio-keyless-api-accesslands it on unslothai#9102. Two commits, both scoped to the keyless feature.1.
Origindoes not identify a browserReviewing unslothai#9102 I ran the browser request shapes against a live server on head
e7a23f1b0, and one gets past the Origin rule.No engine attaches
Originto a same-origin GET, nor to a cross-site GET issued inno-corsmode. Only Chromium withholds ano-corsfetch aimed athttp://127.0.0.1:<port>, via Private Network Access; Firefox and Safari have not shipped it, so there the request arrives. Measured on head, before the fix:no-corsGET/v1/modelsno-corsPOST/v1/unloadOrigin)The response is opaque to the page, so this is not a read primitive. It is a blind request primitive and an "is Unsloth Studio running here" oracle, and under
fullit reaches management handlers, where only FastAPI's JSON body requirement stops the POSTs. The guards you added are what hold the line:GET /api/auth/api-keysstill answers 403 through_require_a_credential_of_its_own.The fix reads
Sec-Fetch-Site, which the browser sets on every request whatever the mode and which a page cannot forge, since theSec-prefix makes it a forbidden header name. Onlycross-siteandsame-siteare refused.same-originis Studio's own page andnoneis the user typing the URL, so both stay admitted.Absence stays admitted, and has to: curl, the OpenAI SDKs and Safari before 16.4 send no
Sec-Fetch-*at all, and serving them is the point of the setting. That also means the header is only present where the transport is a potentially trustworthy URL, so this narrowsfull, which is loopback-only, more tightly than plain-HTTP LAN inference. It never widens either.After the fix, the same 63-case end-to-end run over curl-shaped requests is byte-identical to before, and every browser-shaped row above is 401.
2. The adversarial suite the feature was missing
New file, so the existing test budget is untouched. 13 tests, covering what the current suite asserts only at the predicate layer, only in one direction, or not at all:
scope=offrefused through thesecuritydependency, not only throughscope_coversGET/PUT /api/settings/keyless-api-accessand_require_ui_session_for_keyless, which had no test at all. This is the self-promotion question: a keyless caller must not be able to widen its own scopeinferencefrom a public bind and a public peerinferenceroot_pathand trailing slash driven throughkeyless_request_allowed, not justscope_coversGET /v1/models/prefix pinned to the one handler it can reach. It admits every non-empty suffix rather than an exact pair, so the safety argument rests on route topology; the test fails the day a secondGET /models/...route is registeredasgi_request_is_keylesscalled directly. The duplicate-header rule has three implementations and only one was covered_hosted_mode_forbiddenflag, includinglan_access_is_colabandlan_access_secure_launchfulldenials with_remote_connector_activecleared. In the current suite it is leftTrue, so the wildcard-bind and LAN denials pass even if_full_scope_transport_allowedis deletedVerification
test_tool_result_fits_window, fails identically on merge basee79354e9eand is unrelatedbiome checkon the eight changed files is now error free. The second commit annotates thecloudflareUrltrigger dependency, which was the one Biome error on the branch