Skip to content

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.

Studio: hold the login rate limit on the Colab public link (#17259)

Nilaya64065f250b9
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 2296eec6f2d..39493e93b59 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -2636,7 +2636,11 @@ def run_server(
from utils.forwarded_headers import uvicorn_forwarded_kwargs, wrap_direct_server
config_kwargs.update(uvicorn_forwarded_kwargs(is_colab = _IS_COLAB))
- served_app = app if config_kwargs["proxy_headers"] else wrap_direct_server(app, app.state)
+ served_app = (
+ app
+ if config_kwargs["proxy_headers"]
+ else wrap_direct_server(app, app.state, is_colab = _IS_COLAB)
+ )
if tls is not None:
from utils.studio_tls import StudioTLSConfig
config = StudioTLSConfig(served_app, tls = tls, **config_kwargs)
diff --git a/studio/backend/tests/test_forwarded_header_trust.py b/studio/backend/tests/test_forwarded_header_trust.py
index 1cf3457c338..6087adc65d1 100644
--- a/studio/backend/tests/test_forwarded_header_trust.py
+++ b/studio/backend/tests/test_forwarded_header_trust.py
@@ -74,7 +74,7 @@ def _served(*, is_colab = False, cloudflare_url = None):
inner = Starlette(routes = [Route("/login", _login, methods = ["POST"])])
inner.state.cloudflare_url = cloudflare_url
kwargs = uvicorn_forwarded_kwargs(is_colab = is_colab)
- served = inner if kwargs["proxy_headers"] else wrap_direct_server(inner, inner.state)
+ served = inner if kwargs["proxy_headers"] else wrap_direct_server(inner, inner.state, is_colab)
config = uvicorn.Config(served, log_level = "warning", **kwargs)
config.load()
return config.loaded_app
@@ -131,18 +131,48 @@ def test_the_operator_opt_in_still_honours_forwarded_headers(_no_user, monkeypat
assert seen[0]["scheme"] == "https"
-def test_colab_keeps_its_proxy_header_trust():
- assert uvicorn_forwarded_kwargs(is_colab = True) == {
- "proxy_headers": True,
- "forwarded_allow_ips": "*",
- }
+def test_colab_tunnel_visitor_cannot_pick_a_fresh_login_bucket(_no_user):
+ attempts = auth_routes._LOGIN_MAX_FAILS + 3
+ seen = _post_all(
+ _served(is_colab = True, cloudflare_url = _TUNNEL_URL),
+ [
+ {
+ "host": _TUNNEL_HOST,
+ "cf-connecting-ip": "198.51.100.7",
+ "x-forwarded-for": f"203.0.113.{i}, 198.51.100.7",
+ "x-forwarded-proto": "https",
+ }
+ for i in range(attempts)
+ ],
+ host = _TUNNEL_HOST,
+ )
+ assert {r["client"] for r in seen} == {"198.51.100.7"}
+ assert {r["scheme"] for r in seen} == {"https"}
+ statuses = [r["status"] for r in seen]
+ assert statuses[: auth_routes._LOGIN_MAX_FAILS] == [401] * auth_routes._LOGIN_MAX_FAILS
+ assert statuses[-1] == 429
+
+
+def test_colab_notebook_proxy_keeps_https_and_keys_on_the_address_it_appended(_no_user):
+ attempts = auth_routes._LOGIN_MAX_FAILS + 3
+ seen = _post_all(
+ _served(is_colab = True),
+ [
+ {"x-forwarded-for": f"203.0.113.{i}, 10.0.0.2", "x-forwarded-proto": "https"}
+ for i in range(attempts)
+ ],
+ host = "8888-test.prod.colab.dev",
+ )
+ assert {r["client"] for r in seen} == {"10.0.0.2"}
+ assert {r["scheme"] for r in seen} == {"https"}
+ assert [r["status"] for r in seen][-1] == 429
def test_run_server_and_the_lan_listener_use_the_shared_arguments():
backend = Path(__file__).resolve().parents[1]
run_src = (backend / "run.py").read_text(encoding = "utf-8")
assert "uvicorn_forwarded_kwargs(is_colab = _IS_COLAB)" in run_src
- assert "wrap_direct_server(app, app.state)" in run_src
+ assert "wrap_direct_server(app, app.state, is_colab = _IS_COLAB)" in run_src
import lan_access
assert "uvicorn_forwarded_kwargs(is_colab = False)" in inspect.getsource(
diff --git a/studio/backend/utils/forwarded_headers.py b/studio/backend/utils/forwarded_headers.py
index 66f15fcfe78..fc335cfdecf 100644
--- a/studio/backend/utils/forwarded_headers.py
+++ b/studio/backend/utils/forwarded_headers.py
@@ -1,8 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Rewrites client and scheme only for the Studio Cloudflare tunnel, since any loopback peer could
-spoof X-Forwarded-For; only Colab or UNSLOTH_STUDIO_TRUST_FORWARDED keep the default"""
+"""Rewrites client and scheme only for the Studio Cloudflare tunnel and Colab's notebook proxy, since any
+loopback peer could spoof X-Forwarded-For; only UNSLOTH_STUDIO_TRUST_FORWARDED keeps the default"""
from __future__ import annotations
@@ -18,46 +18,59 @@ from utils.client_ip import (
def uvicorn_forwarded_kwargs(*, is_colab: bool) -> dict[str, Any]:
"""The ``proxy_headers`` / ``forwarded_allow_ips`` arguments for ``uvicorn.Config``."""
- if is_colab:
- return {"proxy_headers": True, "forwarded_allow_ips": "*"}
- if trust_forwarded_headers():
+ if trust_forwarded_headers() and not is_colab:
# uvicorn's own behaviour, including FORWARDED_ALLOW_IPS
return {"proxy_headers": True}
return {"proxy_headers": False}
class ManagedTunnelProxyHeaders:
- """Rewrite client and scheme for requests relayed by Studio's managed Cloudflare tunnel only."""
-
- def __init__(self, app, app_state):
+ def __init__(
+ self,
+ app,
+ app_state,
+ is_colab = False,
+ ):
self.app = app
self.app_state = app_state
+ self.is_colab = is_colab
async def __call__(self, scope, receive, send):
if scope.get("type") in ("http", "websocket"):
client = scope.get("client")
peer = client[0] if client else None
if _is_loopback_ip(peer) and request_from_managed_tunnel(scope, self.app_state):
- headers = scope.get("headers") or ()
- proto = None
- cf_ip = None
- for name, value in headers:
- if name == b"x-forwarded-proto":
- proto = value.decode("latin-1").strip()
- elif name == b"cf-connecting-ip":
- cf_ip = value.decode("latin-1")
- scope = dict(scope)
- if proto in ("http", "https", "ws", "wss"):
- if scope["type"] == "websocket":
- scope["scheme"] = proto.replace("http", "ws")
- else:
- scope["scheme"] = proto
- visitor = _normalize_addr(cf_ip)
- if visitor:
- scope["client"] = (visitor, 0)
+ scope = _rewrite_client_and_scheme(scope, b"cf-connecting-ip")
+ elif self.is_colab:
+ # Colab's proxy appends the peer it saw; earlier entries are caller-supplied.
+ scope = _rewrite_client_and_scheme(scope, b"x-forwarded-for")
await self.app(scope, receive, send)
-def wrap_direct_server(app, app_state):
+def _rewrite_client_and_scheme(scope, client_header):
+ proto = None
+ addrs = []
+ for name, value in scope.get("headers") or ():
+ if name == b"x-forwarded-proto":
+ proto = value.decode("latin-1").strip()
+ elif name == client_header:
+ addrs.append(value.decode("latin-1"))
+ scope = dict(scope)
+ if proto in ("http", "https", "ws", "wss"):
+ if scope["type"] == "websocket":
+ scope["scheme"] = proto.replace("http", "ws")
+ else:
+ scope["scheme"] = proto
+ visitor = _normalize_addr(",".join(addrs).rsplit(",", 1)[-1]) if addrs else None
+ if visitor:
+ scope["client"] = (visitor, 0)
+ return scope
+
+
+def wrap_direct_server(
+ app,
+ app_state,
+ is_colab = False,
+):
"""The ASGI app to hand uvicorn when its own proxy-header rewriting is off."""
- return ManagedTunnelProxyHeaders(app, app_state)
+ return ManagedTunnelProxyHeaders(app, app_state, is_colab)