From 9a74cca6850434348f5851dab13c4da0b783b3fe Mon Sep 17 00:00:00 2001 From: Amir Husayn Panahifar Date: Thu, 26 Nov 2026 18:42:01 +0330 Subject: [PATCH] fix(web): reach the API through the dashboard's own origin Signing in returned 200, but the browser never sent the session cookie back, so every following request was a 401. The dashboard called the API on another origin (http://localhost:8000): opened as 127.0.0.1:3000 or a LAN address that is a different site, so the SameSite cookie was never stored, and browsers also drop a Secure cookie over plain http. - the web server proxies /api/* to API_PROXY_TARGET (http://api:8000 in compose) and the client calls /api by default, so the cookie is first-party on any host; NEXT_PUBLIC_API_BASE is now only for an API on its own host - /api is excluded from the locale middleware, and the proxy timeout is raised to 10 minutes for large uploads and downloads - AUTH_COOKIE_SECURE defaults to auto: Secure whenever the request came over HTTPS, directly or via X-Forwarded-Proto; true/false force it - .env.example, compose, both READMEs and the CHANGELOG updated --- .env.example | 20 ++++++---- CHANGELOG.md | 19 ++++++---- README.fa.md | 11 +++--- README.md | 11 +++--- backend/sokhan/api/routes_auth.py | 56 +++++++++++++++++++++------- backend/sokhan/config.py | 12 +++--- backend/tests/test_cookie_session.py | 18 ++++++++- deploy/docker-compose.yml | 7 +++- web/Dockerfile | 10 +++-- web/next.config.mjs | 14 +++++++ web/src/lib/api.ts | 5 ++- web/src/middleware.ts | 3 +- 12 files changed, 133 insertions(+), 53 deletions(-) diff --git a/.env.example b/.env.example index 1a2c912..1f97a3d 100644 --- a/.env.example +++ b/.env.example @@ -96,12 +96,12 @@ ADMIN_API_KEY= # --- Dashboard session cookie --- # The web dashboard signs in with an httpOnly cookie instead of keeping the -# API token in localStorage. Secure cookies work on http://localhost; set -# AUTH_COOKIE_SECURE=false only for a plain-http install on a LAN address. -# Keep SameSite=lax while the web app and the API share a site -# (app.example.com + api.example.com); use "none" (requires Secure) when -# they live on different sites. SOKHAN_CORS_ORIGINS must list the web origin. -AUTH_COOKIE_SECURE=true +# API token in localStorage. It reaches the API through its own /api path, +# so the cookie is first-party on any host. AUTH_COOKIE_SECURE=auto marks it +# Secure whenever the browser uses HTTPS (directly or via a proxy setting +# X-Forwarded-Proto); true/false force it. SameSite=none (with HTTPS) is only +# needed when NEXT_PUBLIC_API_BASE points at an API on a different site. +AUTH_COOKIE_SECURE=auto AUTH_COOKIE_SAMESITE=lax AUTH_COOKIE_MAX_AGE_DAYS=30 @@ -124,8 +124,12 @@ WEB_BASE_URL=http://localhost:3000 API_BASE_URL=http://localhost:8000 # --- Web --- -# Browser-facing API base URL used by the Next.js app. -NEXT_PUBLIC_API_BASE=http://localhost:8000 +# Browser-facing API base URL, baked into the web build. Leave empty: the +# dashboard then calls /api on its own origin, which the web server proxies +# to API_PROXY_TARGET. Set it only when the API is served from its own host +# (that also needs SOKHAN_CORS_ORIGINS and AUTH_COOKIE_SAMESITE=none). +NEXT_PUBLIC_API_BASE= +API_PROXY_TARGET=http://api:8000 # --- Job-completion webhooks (optional) --- # Jobs uploaded with a callback_url get a POST when they finish. The payload diff --git a/CHANGELOG.md b/CHANGELOG.md index ceecc37..d698acb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,23 +8,26 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje ### Security - Sign-in through the dashboard flows (register, login, connect code) now - also sets the token as an `HttpOnly; Secure; SameSite=lax` session - cookie, and the API accepts it in place of a bearer header. Every + also sets the token as an `HttpOnly; SameSite=lax` session cookie + (`Secure` whenever the browser uses HTTPS), and the API accepts it in place of a bearer header. Every cookie-authenticated write must send the session's CSRF token in `X-CSRF-Token` (403 otherwise); the token is an HMAC of the session token, so nothing extra is stored. `GET /auth/session` returns the signed-in account and its CSRF token, and logout clears the cookie. Bearer auth (bot, API scripts, OpenAI-compatible clients) is unchanged - and needs no CSRF token. New settings: `AUTH_COOKIE_SECURE`, - `AUTH_COOKIE_SAMESITE`, `AUTH_COOKIE_MAX_AGE_DAYS`. CORS now allows - credentials for the configured `SOKHAN_CORS_ORIGINS` (#33). + and needs no CSRF token. New settings: `AUTH_COOKIE_SECURE` + (`auto`/`true`/`false`), `AUTH_COOKIE_SAMESITE`, + `AUTH_COOKIE_MAX_AGE_DAYS`. CORS now allows credentials for the + configured `SOKHAN_CORS_ORIGINS` (#33). - The dashboard no longer keeps the API token in `localStorage`, where an XSS could read it (CodeQL `js/clear-text-storage-of-sensitive-data`). It relies on the httpOnly session cookie, sends the CSRF token on writes, learns who is signed in from `GET /auth/session`, and wipes the token - earlier versions left in `localStorage`. **Self-hosters:** - `SOKHAN_CORS_ORIGINS` must list the dashboard's origin, and a plain-http - install on a LAN address needs `AUTH_COOKIE_SECURE=false` (#33). + earlier versions left in `localStorage`. The dashboard reaches the API + through its own `/api` path, proxied by the web server to + `API_PROXY_TARGET`, so the cookie is first-party on localhost, 127.0.0.1, + a LAN address or a domain alike; `NEXT_PUBLIC_API_BASE` now defaults to + empty and is only for an API on its own host (#33). ### Added diff --git a/README.fa.md b/README.fa.md index 980e4fa..d1f6b61 100644 --- a/README.fa.md +++ b/README.fa.md @@ -177,10 +177,10 @@ docker pull ghcr.io/abolfazlrwm/sokhan-web:latest خودش نوشته: با `up -d --build` لوکال بسازید، یا با `docker compose -f deploy/docker-compose.yml pull` و `up -d --no-build` ایمیج‌های منتشرشده را اجرا کنید. نسخه‌های پین‌شده تابع تگ‌های گیت هستند -(مثل `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). توجه: ایمیج وب مقدار -`NEXT_PUBLIC_API_BASE` (پیش‌فرض `http://localhost:8000`) را موقع build -می‌گیرد — دیپلوی‌هایی که داشبورد را از origin دیگری سرو می‌کنند باید خودشان -این build argument را بدهند. +(مثل `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). داشبورد API را از +مسیر `/api` روی همان origin خودش صدا می‌زند و وب‌سرور آن را به +`API_PROXY_TARGET` (پیش‌فرض `http://api:8000`، موقع build) پراکسی می‌کند؛ +برای همین یک ایمیج روی هر هاست یا دامنه‌ای کار می‌کند. ## توسعه @@ -230,7 +230,8 @@ SOKHAN_REAL_MODEL_TEST=1 pytest backend/tests/test_real_model.py | `TELEGRAM_BOT_TOKEN` | خالی | فعال‌سازی فرایند ربات | | `WEB_BASE_URL` | `http://localhost:3000` | لینک‌هایی که ربات می‌فرستد | | `API_BASE_URL` | `http://localhost:8000` | آدرس API که ربات صدا می‌زند | -| `NEXT_PUBLIC_API_BASE` | `http://localhost:8000` | آدرس API که اپ وب صدا می‌زند (زمان build) | +| `NEXT_PUBLIC_API_BASE` | خالی (همان origin، `/api`) | آدرس API که اپ وب صدا می‌زند، فقط وقتی API روی هاست جدا است (زمان build) | +| `API_PROXY_TARGET` | `http://api:8000` | مقصد پراکسی `/api` در وب‌سرور (زمان build) | فهرست کامنت‌دار در [.env.example](.env.example). diff --git a/README.md b/README.md index 55ef6f0..0d19bdd 100644 --- a/README.md +++ b/README.md @@ -176,10 +176,10 @@ docker pull ghcr.io/abolfazlrwm/sokhan-web:latest `build:` blocks: keep `up -d --build` to build locally, or `docker compose -f deploy/docker-compose.yml pull` and `up -d --no-build` to run the published images. Pinned versions follow the -git tags (e.g. `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). Note the web image -bakes `NEXT_PUBLIC_API_BASE` (default `http://localhost:8000`) at build -time — deployments serving the dashboard from another origin pass the -build argument themselves. +git tags (e.g. `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). The dashboard calls +the API through its own `/api` path, which the web server proxies to +`API_PROXY_TARGET` (default `http://api:8000`, baked at build time), so one +image works on any host or domain. ## Development @@ -229,7 +229,8 @@ SOKHAN_REAL_MODEL_TEST=1 pytest backend/tests/test_real_model.py | `TELEGRAM_BOT_TOKEN` | empty | enables the bot process | | `WEB_BASE_URL` | `http://localhost:3000` | links the bot sends | | `API_BASE_URL` | `http://localhost:8000` | API address the bot calls | -| `NEXT_PUBLIC_API_BASE` | `http://localhost:8000` | API address the web app calls (build-time) | +| `NEXT_PUBLIC_API_BASE` | empty (same-origin `/api`) | API address the web app calls, only for an API on its own host (build-time) | +| `API_PROXY_TARGET` | `http://api:8000` | Where the web server proxies `/api` (build-time) | See [.env.example](.env.example) for the commented list. diff --git a/backend/sokhan/api/routes_auth.py b/backend/sokhan/api/routes_auth.py index e87b145..94a0458 100644 --- a/backend/sokhan/api/routes_auth.py +++ b/backend/sokhan/api/routes_auth.py @@ -18,7 +18,7 @@ clients and the bot. import re -from fastapi import APIRouter, Depends, HTTPException, Response, status +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status from pydantic import BaseModel from sqlalchemy import select from sqlalchemy.orm import Session @@ -74,7 +74,24 @@ def _validate_credentials(email: str, password: str) -> str: return email -def _start_session(response: Response, user: User, token: str) -> AuthResponse: +def _cookie_is_secure(request: Request) -> bool: + """Whether the session cookie gets the Secure attribute. + + `auto` (the default) follows the scheme the browser used: HTTPS directly + or behind a proxy that sets X-Forwarded-Proto. Browsers drop a Secure + cookie that arrives over plain http (Safari even on localhost), which + left plain-http installs unable to stay signed in. + """ + mode = get_settings().auth_cookie_secure.strip().lower() + if mode in ("true", "1", "yes"): + return True + if mode in ("false", "0", "no"): + return False + forwarded = request.headers.get("x-forwarded-proto", "").split(",")[0].strip().lower() + return request.url.scheme == "https" or forwarded == "https" + + +def _start_session(request: Request, response: Response, user: User, token: str) -> AuthResponse: """Set the httpOnly session cookie and answer with the CSRF token.""" settings = get_settings() response.set_cookie( @@ -83,7 +100,7 @@ def _start_session(response: Response, user: User, token: str) -> AuthResponse: max_age=settings.auth_cookie_max_age_days * 24 * 3600, path="/", httponly=True, - secure=settings.auth_cookie_secure, + secure=_cookie_is_secure(request), samesite=settings.auth_cookie_samesite, ) return AuthResponse( @@ -91,20 +108,23 @@ def _start_session(response: Response, user: User, token: str) -> AuthResponse: ) -def _end_session(response: Response) -> None: +def _end_session(request: Request, response: Response) -> None: settings = get_settings() response.delete_cookie( SESSION_COOKIE, path="/", httponly=True, - secure=settings.auth_cookie_secure, + secure=_cookie_is_secure(request), samesite=settings.auth_cookie_samesite, ) @router.post("/register", response_model=AuthResponse) def register( - payload: Credentials, response: Response, session: Session = Depends(get_db) + payload: Credentials, + request: Request, + response: Response, + session: Session = Depends(get_db), ) -> AuthResponse: email = _validate_credentials(payload.email, payload.password) if session.scalar(select(User).where(User.email == email)): @@ -118,12 +138,15 @@ def register( ) session.add(user) session.commit() - return _start_session(response, user, token) + return _start_session(request, response, user, token) @router.post("/login", response_model=AuthResponse) def login( - payload: Credentials, response: Response, session: Session = Depends(get_db) + payload: Credentials, + request: Request, + response: Response, + session: Session = Depends(get_db), ) -> AuthResponse: email = payload.email.strip().lower() user = session.scalar(select(User).where(User.email == email)) @@ -133,17 +156,20 @@ def login( token = generate_token() user.token_hash = token_hash(token) session.commit() - return _start_session(response, user, token) + return _start_session(request, response, user, token) @router.post("/token-login", response_model=AuthResponse) def token_login( - payload: TokenLogin, response: Response, session: Session = Depends(get_db) + payload: TokenLogin, + request: Request, + response: Response, + session: Session = Depends(get_db), ) -> AuthResponse: user = session.scalar(select(User).where(User.token_hash == token_hash(payload.api_token))) if user is None: raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid connect code") - return _start_session(response, user, payload.api_token) + return _start_session(request, response, user, payload.api_token) @router.get("/session", response_model=SessionOut) @@ -159,7 +185,11 @@ def current_session( @router.post("/logout", status_code=status.HTTP_204_NO_CONTENT) -def logout(user: User = Depends(get_current_user), session: Session = Depends(get_db)) -> Response: +def logout( + request: Request, + user: User = Depends(get_current_user), + session: Session = Depends(get_db), +) -> Response: """Revoke the caller's token so it stops working everywhere. An account has a single active token, so this signs out every client @@ -170,7 +200,7 @@ def logout(user: User = Depends(get_current_user), session: Session = Depends(ge user.token_hash = token_hash(generate_token()) session.commit() response = Response(status_code=status.HTTP_204_NO_CONTENT) - _end_session(response) + _end_session(request, response) return response diff --git a/backend/sokhan/config.py b/backend/sokhan/config.py index afcf59c..46fc543 100644 --- a/backend/sokhan/config.py +++ b/backend/sokhan/config.py @@ -74,12 +74,12 @@ class Settings(BaseSettings): # Leave empty to disable the admin endpoints entirely. admin_api_key: str = "" - # Dashboard session cookie (httpOnly). Secure by default: browsers still - # accept it on http://localhost, so only plain-http LAN installs need - # AUTH_COOKIE_SECURE=false. SameSite=lax works whenever the web app and - # the API share a site (localhost:3000 + localhost:8000, or - # app.example.com + api.example.com); different sites need "none". - auth_cookie_secure: bool = True + # Dashboard session cookie (httpOnly). AUTH_COOKIE_SECURE=auto sets the + # Secure attribute whenever the browser came in over HTTPS (directly or + # via X-Forwarded-Proto); true/false force it. The web app proxies the + # API under its own origin (/api), so SameSite=lax always applies; a + # separately hosted API on another site needs "none" plus HTTPS. + auth_cookie_secure: str = "auto" auth_cookie_samesite: str = "lax" auth_cookie_max_age_days: int = 30 diff --git a/backend/tests/test_cookie_session.py b/backend/tests/test_cookie_session.py index cf5cb41..f8068a6 100644 --- a/backend/tests/test_cookie_session.py +++ b/backend/tests/test_cookie_session.py @@ -31,8 +31,24 @@ def test_login_sets_an_httponly_session_cookie(cookie_client): assert body["csrf_token"] == csrf_token_for(body["api_token"]) -def test_cookie_is_secure_by_default(client): +def test_cookie_secure_follows_the_scheme_by_default(client): + # Plain http: a Secure cookie would be dropped by the browser. + plain = client.post("/auth/register", json=CREDENTIALS).headers["set-cookie"] + assert "Secure" not in plain + + # HTTPS terminated by a reverse proxy in front of the API. + behind_tls = client.post( + "/auth/login", json=CREDENTIALS, headers={"X-Forwarded-Proto": "https"} + ).headers["set-cookie"] + assert "Secure" in behind_tls + + +def test_cookie_secure_can_be_forced(client, monkeypatch): + monkeypatch.setenv("AUTH_COOKIE_SECURE", "true") + get_settings.cache_clear() + cookie = client.post("/auth/register", json=CREDENTIALS).headers["set-cookie"] + assert "Secure" in cookie diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 8dea281..fb1e92d 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -53,7 +53,7 @@ services: PLAN_PRO_MAX_FILE_MINUTES: ${PLAN_PRO_MAX_FILE_MINUTES:-180} PLAN_PRO_MONTHLY_MINUTES: ${PLAN_PRO_MONTHLY_MINUTES:-1200} ADMIN_API_KEY: ${ADMIN_API_KEY:-} - AUTH_COOKIE_SECURE: ${AUTH_COOKIE_SECURE:-true} + AUTH_COOKIE_SECURE: ${AUTH_COOKIE_SECURE:-auto} AUTH_COOKIE_SAMESITE: ${AUTH_COOKIE_SAMESITE:-lax} AUTH_COOKIE_MAX_AGE_DAYS: ${AUTH_COOKIE_MAX_AGE_DAYS:-30} MAX_UPLOAD_MB: ${MAX_UPLOAD_MB:-200} @@ -95,7 +95,10 @@ services: build: context: ../web args: - NEXT_PUBLIC_API_BASE: ${NEXT_PUBLIC_API_BASE:-http://localhost:8000} + # Empty: the browser calls /api on the web origin, proxied to the api + # service, so the session cookie is first-party on any host. + NEXT_PUBLIC_API_BASE: ${NEXT_PUBLIC_API_BASE:-} + API_PROXY_TARGET: ${API_PROXY_TARGET:-http://api:8000} ports: - "${SOKHAN_WEB_PORT:-3000}:3000" depends_on: diff --git a/web/Dockerfile b/web/Dockerfile index 0162404..b938507 100644 --- a/web/Dockerfile +++ b/web/Dockerfile @@ -5,10 +5,14 @@ COPY package.json package-lock.json ./ RUN npm ci COPY . . -# NEXT_PUBLIC_ variables are inlined into the client bundle at build time, -# so the API base URL is provided as a build argument. -ARG NEXT_PUBLIC_API_BASE=http://localhost:8000 +# Both are baked into the build. The browser calls the API through this +# app's own /api path, proxied to API_PROXY_TARGET (the compose service by +# default). NEXT_PUBLIC_API_BASE stays empty unless the API is served from +# its own host. +ARG NEXT_PUBLIC_API_BASE= +ARG API_PROXY_TARGET=http://api:8000 ENV NEXT_PUBLIC_API_BASE=$NEXT_PUBLIC_API_BASE +ENV API_PROXY_TARGET=$API_PROXY_TARGET RUN npm run build diff --git a/web/next.config.mjs b/web/next.config.mjs index 89dfc26..e54d22d 100644 --- a/web/next.config.mjs +++ b/web/next.config.mjs @@ -1,8 +1,22 @@ import createNextIntlPlugin from "next-intl/plugin"; +// The dashboard talks to the API through its own origin (/api/*), so the +// httpOnly session cookie is always first-party: it works on localhost, +// 127.0.0.1, a LAN address or a real domain alike, without CORS. The +// target is baked into the build (standalone output); compose passes the +// in-network address, `next dev` defaults to a local API. +const apiProxyTarget = (process.env.API_PROXY_TARGET || "http://localhost:8000").replace(/\/$/, ""); + /** @type {import('next').NextConfig} */ const nextConfig = { output: "standalone", + async rewrites() { + return [{ source: "/api/:path*", destination: `${apiProxyTarget}/:path*` }]; + }, + experimental: { + // Uploads and transcript downloads can outlast the 30 s proxy default. + proxyTimeout: 10 * 60 * 1000, + }, }; const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts"); diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index e7de38a..36ec8ea 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -4,7 +4,10 @@ // session's CSRF token. A 401 marks the session signed out and bounces the // user back to the login screen. -const API_BASE = process.env.NEXT_PUBLIC_API_BASE || "http://localhost:8000"; +// Same-origin by default: next.config.mjs proxies /api/* to the backend, so +// the session cookie is first-party wherever the dashboard is served from. +// Set NEXT_PUBLIC_API_BASE only for an API on its own host. +const API_BASE = (process.env.NEXT_PUBLIC_API_BASE || "/api").replace(/\/$/, ""); /** Fired on this tab whenever the session state changes. */ export const SESSION_CHANGE_EVENT = "sokhan:session-change"; diff --git a/web/src/middleware.ts b/web/src/middleware.ts index 73358a6..0cbb380 100644 --- a/web/src/middleware.ts +++ b/web/src/middleware.ts @@ -4,5 +4,6 @@ import { routing } from "./i18n/routing"; export default createMiddleware(routing); export const config = { - matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\..*).*)"], + // /api is the proxied backend: it must not get a locale prefix. + matcher: ["/((?!api/|_next/static|_next/image|favicon.ico|.*\\..*).*)"], };