Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: memoize the nonce-free Content-Security-Policy on its inputs (#17246)
Daniel Han5a1bf45da0a1
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 4c0fd860aa3..4385bbfe948 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1369,7 +1369,39 @@ def _reportable_hf_endpoints(request) -> dict:return reported+_CSP_CACHE: dict = {}++def _build_csp(script_nonce: "str | None" = None, *, docs: bool = False) -> str:+ """Nonce-free policies are memoized on every input the build reads (env, saved-only set, Colab)."""+ if script_nonce:+ return _build_csp_uncached(script_nonce, docs = docs)+ key = _csp_key(docs)+ policy = _CSP_CACHE.get(key)+ if policy is None:+ policy = _build_csp_uncached(None, docs = docs)+ # A settings save in a worker thread can land mid-build; keep only a policy built from the key's inputs.+ if _csp_key(docs) == key:+ if len(_CSP_CACHE) >= 64:+ _CSP_CACHE.clear()+ _CSP_CACHE[key] = policy+ return policy+++def _csp_key(docs: bool) -> tuple:+ from utils.hub_settings import SOURCE_ENV, saved_only_endpoints+ environ = os.environ+ return (+ docs,+ _IS_COLAB,+ environ.get("HF_ENDPOINT"),+ environ.get("HF_DATASETS_SERVER"),+ environ.get(SOURCE_ENV),+ saved_only_endpoints(),+ )+++def _build_csp_uncached(script_nonce: "str | None" = None, *, docs: bool = False) -> str:script_src = "script-src 'self'"style_src = "style-src 'self' 'unsafe-inline'"worker_src = "worker-src 'self'"diff --git a/studio/backend/tests/test_csp_memo.py b/studio/backend/tests/test_csp_memo.pynew file mode 100644index 00000000000..e2ff4aa41b6--- /dev/null+++ b/studio/backend/tests/test_csp_memo.py@@ -0,0 +1,73 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The nonce-free Content-Security-Policy is built once per set of inputs, and any input change rebuilds it."""++import pytest+++def main_module(monkeypatch):+ import main as _main++ monkeypatch.setattr(_main, "_CSP_CACHE", {})+ for name in ("HF_ENDPOINT", "HF_DATASETS_SERVER"):+ monkeypatch.delenv(name, raising = False)+ return _main+++def _counting(monkeypatch, main_module):+ calls = []+ original = main_module._build_csp_uncached++ def spy(*args, **kwargs):+ calls.append((args, kwargs))+ return original(*args, **kwargs)++ monkeypatch.setattr(main_module, "_build_csp_uncached", spy)+ return calls, original+++def test_repeat_responses_reuse_the_policy(monkeypatch, main_module):+ calls, original = _counting(monkeypatch, main_module)+ first = [main_module._build_csp(), main_module._build_csp(docs = True)]+ for _ in range(5):+ assert [main_module._build_csp(), main_module._build_csp(docs = True)] == first+ assert len(calls) == 2+ assert first == [original(), original(docs = True)]+++def test_a_changed_endpoint_rebuilds_the_policy(monkeypatch, main_module):+ calls, original = _counting(monkeypatch, main_module)+ before = main_module._build_csp()+ monkeypatch.setenv("HF_ENDPOINT", "https://hub.internal:8443")+ after = main_module._build_csp()+ assert after == original()+ assert "hub.internal:8443" in after and "hub.internal:8443" not in before+ monkeypatch.delenv("HF_ENDPOINT")+ assert main_module._build_csp() == before+ assert len(calls) == 2+++def test_nonce_policies_are_never_kept(monkeypatch, main_module):+ calls, _ = _counting(monkeypatch, main_module)+ assert "'nonce-AAA'" in main_module._build_csp("AAA")+ assert "'nonce-BBB'" in main_module._build_csp("BBB")+ assert len(calls) == 2+ assert main_module._CSP_CACHE == {}+++def test_a_settings_save_during_the_build_is_not_cached_under_the_old_key(monkeypatch, main_module):+ original = main_module._build_csp_uncached++ def build_while_a_save_lands(*args, **kwargs):+ policy = original(*args, **kwargs)+ monkeypatch.setenv("HF_ENDPOINT", "https://mirror.example.com")+ return policy++ monkeypatch.setattr(main_module, "_build_csp_uncached", build_while_a_save_lands)+ main_module._build_csp()+ monkeypatch.setattr(main_module, "_build_csp_uncached", original)+ monkeypatch.delenv("HF_ENDPOINT")+ assert main_module._CSP_CACHE == {}+ assert main_module._build_csp() == original()