DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(auth): forward requested handoff host and avoid shared quota lockout
Bingxi Zhao (Frank)baa3263a7a90
diff --git a/README.md b/README.mdindex fd4414490..1e58c9198 100644--- a/README.md+++ b/README.md@@ -893,7 +893,7 @@ The **first registered user becomes admin** and owns model catalogs, provider cr**Enable it:** turn auth on in `data/user/settings/auth.json`, restart `deeptutor start`, register the first admin at `/register`, then add users from `/admin/users` and assign models, KBs, skills, partners, tool/MCP/CLI-app policy, and code-execution access through grants; configure shared books under each user's **Book access** panel.-For split private/public origins, set `auth.private_login_hosts` (or `AUTH_PRIVATE_LOGIN_HOSTS`) to the private frontend hosts that may show password sign-in and registration. The backend accepts frontend-host assertions only from loopback by default. If the Web frontend connects from another container or host, set `AUTH_TRUSTED_FRONTEND_PROXY_IPS` to that frontend proxy's exact IP address on the backend process (comma-separated for more than one). Keep the backend API private to the frontend proxy and do not include general client networks in this list. Loopback is always allowed; when the list is non-empty, an authenticated user on a private origin can open **Profile → Public device sign-in** and create a short-lived, host-bound pairing link for an HTTPS public origin. The public `/handoff` page exchanges the one-time code for an equally short JWE ticket in a POST body, consumes the ticket once, and receives the normal HttpOnly session cookie.+For split private/public origins, set `auth.private_login_hosts` (or `AUTH_PRIVATE_LOGIN_HOSTS`) to the private frontend hosts that may show password sign-in and registration. The frontend forwards the incoming HTTP `Host` to the backend as its frontend-host assertion. Preserve the browser's `Host` through your reverse proxy, and make the public ingress reject requests naming a private host; do not expose a raw Next.js port that accepts arbitrary `Host` values. HTTP `Host` can be forged by a direct client, so private-host authorization depends on that ingress boundary. The backend accepts frontend-host assertions only from loopback by default. If the Web frontend connects from another container or host, set `AUTH_TRUSTED_FRONTEND_PROXY_IPS` to that frontend proxy's exact IP address on the backend process (comma-separated for more than one). Keep the backend API private to the frontend proxy and do not include general client networks in this list. Loopback is always allowed; when the list is non-empty, an authenticated user on a private origin can open **Profile → Public device sign-in** and create a short-lived, host-bound pairing link for an HTTPS public origin. The public `/handoff` page exchanges the one-time code for an equally short JWE ticket in a POST body, consumes the ticket once, and receives the normal HttpOnly session cookie.> PocketBase stays a single-user integration — keep `integrations.pocketbase_url` blank for multi-user deployments unless you've wired up an external user store.diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.pyindex 946b1df8a..c2e6a7b46 100644--- a/deeptutor/api/routers/auth.py+++ b/deeptutor/api/routers/auth.py@@ -110,6 +110,8 @@ PRIVATE_LOGIN_HOSTS = frozenset(# Only a frontend proxy on an explicitly trusted peer may assert the browser# host. Never derive this identity from Host or X-Forwarded-* on a direct API call.+# The frontend's incoming Host is meaningful only when its public ingress+# rejects forged private hosts and direct access to its raw listener.def _trusted_proxy_ips() -> frozenset[str]:raw = os.environ.get("AUTH_TRUSTED_FRONTEND_PROXY_IPS", "127.0.0.1,::1")trusted: set[str] = set()diff --git a/deeptutor/multi_user/session_handoff.py b/deeptutor/multi_user/session_handoff.pyindex 8d2698c39..1c52192dd 100644--- a/deeptutor/multi_user/session_handoff.py+++ b/deeptutor/multi_user/session_handoff.py@@ -29,9 +29,6 @@ CODE_LIFETIME_SECONDS = 300TICKET_LIFETIME_SECONDS = 120MAX_CODE_ATTEMPTS = 5CREATE_RATE_LIMIT = (5, 60)-EXCHANGE_RATE_LIMIT = (10, 60)-COMPLETE_RATE_LIMIT = (10, 60)-GLOBAL_EXCHANGE_RATE_LIMIT = (30, 60)STATE_RETENTION_SECONDS = 600_DB_FILENAME = "session_handoff.sqlite3"@@ -339,8 +336,10 @@ class SessionHandoffStore:now: int | None = None,) -> str:current = int(time.time() if now is None else now)- self._rate_limit(f"exchange:{public_host}", EXCHANGE_RATE_LIMIT, now=now)- self._rate_limit("exchange:global", GLOBAL_EXCHANGE_RATE_LIMIT, now=now)+ # An anonymous caller can submit arbitrary codes. A shared host/global+ # quota would let a few bad requests lock out every legitimate handoff+ # on that site. Codes are 256-bit secrets, looked up by hash; a bogus+ # code costs one indexed lookup and cannot guess a valid record.code_hash = hash_secret(code)with self._connect() as connection:self._initialize(connection)@@ -409,7 +408,8 @@ class SessionHandoffStore:now: int | None = None,) -> str:current = int(time.time() if now is None else now)- self._rate_limit(f"complete:{public_host}", COMPLETE_RATE_LIMIT, now=now)+ # As with exchange, a shared quota here would let anonymous invalid+ # tickets prevent every user on this public host from signing in.ticket_hash = hash_secret(ticket)with self._connect() as connection:self._initialize(connection)diff --git a/tests/multi_user/test_session_handoff.py b/tests/multi_user/test_session_handoff.pyindex 3eb265504..ca2ccf590 100644--- a/tests/multi_user/test_session_handoff.py+++ b/tests/multi_user/test_session_handoff.py@@ -54,6 +54,33 @@ def test_handoff_code_and_ticket_are_single_use(tmp_path, monkeypatch) -> None:store.consume_ticket(ticket=exchanged, public_host="app.example", now=106)+def test_invalid_public_requests_cannot_exhaust_other_users_handoffs(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr(session_handoff, "load_or_create_auth_secret", lambda: "test-secret")+ store = session_handoff.SessionHandoffStore(tmp_path / "handoff.sqlite3")+ ticket = session_handoff.encrypt_ticket_payload(+ {"mode": "builtin", "host": "app.example", "exp": 220},+ secret="test-secret",+ )+ record = store.create(+ encrypted_ticket=ticket,+ ticket_hash=session_handoff.hash_secret(ticket),+ public_host="app.example",+ now=100,+ )++ for index in range(40):+ with pytest.raises(session_handoff.HandoffRejected):+ store.exchange(code=f"invalid-code-{index:032d}", public_host="app.example", now=101)+ exchanged = store.exchange(code=record.code, public_host="app.example", now=102)++ for index in range(40):+ with pytest.raises(session_handoff.HandoffRejected):+ store.consume_ticket(+ ticket=f"invalid-ticket-{index:032d}", public_host="app.example", now=103+ )+ assert store.consume_ticket(ticket=exchanged, public_host="app.example", now=104) == exchanged++def test_expired_code_is_rejected_and_rate_limited(tmp_path, monkeypatch) -> None:store = session_handoff.SessionHandoffStore(tmp_path / "handoff.sqlite3")ticket = session_handoff.encrypt_ticket_payload(diff --git a/web/lib/backend-forward.ts b/web/lib/backend-forward.tsindex ec992e651..47c3bd79f 100644--- a/web/lib/backend-forward.ts+++ b/web/lib/backend-forward.ts@@ -15,10 +15,11 @@ const UNTRUSTED_FORWARD_HEADERS = [FRONTEND_HOST_HEADER,];-export function prepareBackendForwardHeaders(- source: Headers,- frontendHost: string,-): Headers {+export function prepareBackendForwardHeaders(source: Headers): Headers {+ // NextRequest.nextUrl.host is the Next server's bind address in standalone+ // and source deployments. The HTTP Host header carries the requested+ // frontend host through Next's proxy, including when TLS ends upstream.+ const frontendHost = source.get("host");const headers = new Headers(source);const connectionTokens = (headers.get("connection") || "").split(",")@@ -28,6 +29,6 @@ export function prepareBackendForwardHeaders(for (const name of [...UNTRUSTED_FORWARD_HEADERS, ...connectionTokens]) {headers.delete(name);}- headers.set(FRONTEND_HOST_HEADER, frontendHost);+ if (frontendHost) headers.set(FRONTEND_HOST_HEADER, frontendHost);return headers;}diff --git a/web/lib/streaming-upload-proxy.ts b/web/lib/streaming-upload-proxy.tsindex c9220a6b5..ceba20fb8 100644--- a/web/lib/streaming-upload-proxy.ts+++ b/web/lib/streaming-upload-proxy.ts@@ -33,12 +33,11 @@ export interface UploadProxyDependencies {function forwardedHeaders(source: Headers,- { request, frontendHost }: { request: boolean; frontendHost?: string },+ { request }: { request: boolean },) {- const headers =- request && frontendHost- ? prepareBackendForwardHeaders(source, frontendHost)- : new Headers(source);+ const headers = request+ ? prepareBackendForwardHeaders(source)+ : new Headers(source);for (const name of HOP_BY_HOP_HEADERS) {headers.delete(name);}@@ -67,7 +66,6 @@ export async function forwardBackendUpload(method: request.method,headers: forwardedHeaders(request.headers, {request: true,- frontendHost: incomingUrl.host,}),signal: request.signal,redirect: "manual",diff --git a/web/proxy.ts b/web/proxy.tsindex 205e82a0d..56f698cc6 100644--- a/web/proxy.ts+++ b/web/proxy.ts@@ -66,7 +66,7 @@ export function proxy(req: NextRequest): NextResponse {if (isBackendPath(pathname)) {return NextResponse.rewrite(new URL(pathname + search, API_BASE_URL), {request: {- headers: prepareBackendForwardHeaders(req.headers, req.nextUrl.host),+ headers: prepareBackendForwardHeaders(req.headers),},});}diff --git a/web/tests/proxy-policy.test.ts b/web/tests/proxy-policy.test.tsindex 826a1a36c..49bffa3ad 100644--- a/web/tests/proxy-policy.test.ts+++ b/web/tests/proxy-policy.test.ts@@ -126,7 +126,7 @@ test("backend forwarding replaces client identity headers with frontend host", (connection: "keep-alive, x-remove-me",cookie: "dt_token=session",forwarded: "for=1.2.3.4;host=attacker.example",- host: "attacker.example",+ host: "app.example","x-forwarded-for": "1.2.3.4","x-forwarded-host": "attacker.example","x-forwarded-proto": "https",@@ -134,7 +134,6 @@ test("backend forwarding replaces client identity headers with frontend host", ("x-deeptutor-frontend-host": "attacker.example","x-remove-me": "hop-by-hop",}),- "app.example",);assert.equal(headers.get("x-deeptutor-frontend-host"), "app.example");@@ -152,6 +151,14 @@ test("backend forwarding replaces client identity headers with frontend host", (}});+test("backend forwarding does not invent a frontend host from the Next URL", () => {+ const headers = prepareBackendForwardHeaders(new Headers({+ "x-forwarded-host": "app.example",+ "x-deeptutor-frontend-host": "app.example",+ }));+ assert.equal(headers.has("x-deeptutor-frontend-host"), false);+});+test("isAuthExempt does NOT exempt protected app routes", () => {assert.equal(isAuthExempt("/chat"), false);assert.equal(isAuthExempt("/dashboard"), false);