From 6b9204a94337ad4c96bcb81ad3dee2e0673a4c3c Mon Sep 17 00:00:00 2001 From: Creylay Date: Fri, 4 Dec 2026 12:20:06 -0300 Subject: [PATCH 1/5] fix: reject requests for unknown Host headers --- DashAI/back/app.py | 7 +++++++ DashAI/back/config.py | 7 +++++++ tests/back/api/test_trusted_host_security.py | 21 ++++++++++++++++++++ tests/back/conftest.py | 5 +++++ 4 files changed, 40 insertions(+) create mode 100644 tests/back/api/test_trusted_host_security.py diff --git a/DashAI/back/app.py b/DashAI/back/app.py index bee897724..e47cd6322 100644 --- a/DashAI/back/app.py +++ b/DashAI/back/app.py @@ -7,6 +7,7 @@ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware +from fastapi.middleware.trustedhost import TrustedHostMiddleware from kink import di from DashAI.back.api.api_v1.api import api_router_v1 @@ -157,6 +158,12 @@ def create_app( allow_methods=["*"], allow_headers=["*"], ) + # Added last so it runs first: a request whose Host is not one of ours is + # refused before any other middleware or endpoint sees it. + allowed_hosts = [ + host.strip() for host in config["ALLOWED_HOSTS"].split(",") if host.strip() + ] + app.add_middleware(TrustedHostMiddleware, allowed_hosts=allowed_hosts) app.container = container logger.debug("Application successfully created.") diff --git a/DashAI/back/config.py b/DashAI/back/config.py index 05a435559..8f5ed0022 100644 --- a/DashAI/back/config.py +++ b/DashAI/back/config.py @@ -46,6 +46,13 @@ class DefaultSettings(BaseSettings): # lets any web page the user visits call the API on their behalf. CORS_ALLOWED_ORIGINS: str = "http://localhost:3000,http://127.0.0.1:3000" + # Host names the API answers to, as a comma-separated list (checked + # against the request's Host header). Rejecting unknown hosts blocks DNS + # rebinding, where a foreign site points its own name at 127.0.0.1 to talk + # to the API as if it were same-origin. Add the name or IP you use to reach + # a Docker or server deployment (e.g. ALLOWED_HOSTS=localhost,10.0.0.5). + ALLOWED_HOSTS: str = "localhost,127.0.0.1" + # Keep generative models loaded in the job worker between chat messages. MODEL_CACHE_ENABLED: bool = True # Seconds a cached model may stay unused before it is unloaded. diff --git a/tests/back/api/test_trusted_host_security.py b/tests/back/api/test_trusted_host_security.py new file mode 100644 index 000000000..1eb91ccbb --- /dev/null +++ b/tests/back/api/test_trusted_host_security.py @@ -0,0 +1,21 @@ +"""Security test for the Host header check. + +The API used to answer any Host header, which let a foreign site use DNS +rebinding (pointing its own name at 127.0.0.1) to talk to the API as if it +were same-origin. Requests for an unknown host must now be refused. +""" + +ENDPOINT = "/api/v1/credential/" + + +def test_unknown_host_is_rejected(client): + """A request addressed to a foreign host name is refused.""" + response = client.get(ENDPOINT, headers={"Host": "attacker.example"}) + assert response.status_code == 400 + + +def test_localhost_hosts_are_accepted(client): + """The hosts the desktop app and dev frontend use keep working.""" + for host in ("localhost", "127.0.0.1", "localhost:8000", "127.0.0.1:8000"): + response = client.get(ENDPOINT, headers={"Host": host}) + assert response.status_code == 200, host diff --git a/tests/back/conftest.py b/tests/back/conftest.py index e23b95022..c9dc349de 100644 --- a/tests/back/conftest.py +++ b/tests/back/conftest.py @@ -12,6 +12,11 @@ from DashAI.back.dependencies.job_queues.huey_job_queue import HueyJobQueue from tests.back.scratch import clear_scratch +# FastAPI's TestClient sends "Host: testserver". Allow it for the test apps only +# (set before any create_app() reads the settings), so production keeps its +# localhost-only default. +os.environ.setdefault("ALLOWED_HOSTS", "localhost,127.0.0.1,testserver") + TEST_PATH = pathlib.Path("tmp") TEST_DATASETS_PATH = pathlib.Path("./tests/back/test_datasets") RANDOM_STATE = 50 From 52bb8741e4c161c233de9bf8a42f8afde1ddc72e Mon Sep 17 00:00:00 2001 From: Creylay Date: Fri, 4 Dec 2026 12:31:03 -0300 Subject: [PATCH 2/5] docs: document secure Docker deployment and configurable demo hosts --- Dockerfile | 3 +++ Dockerfile.cuda | 3 +++ README.rst | 31 +++++++++++++++++++++++++++++++ docker-compose.demo.yml | 19 +++++++++++++++++++ 4 files changed, 56 insertions(+) diff --git a/Dockerfile b/Dockerfile index 0cafda4b8..fa152ac41 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,6 +12,9 @@ COPY . . COPY --from=frontend /app/DashAI/front/build DashAI/front/build RUN uv sync --locked --extra cpu --no-dev --no-cache ENV PATH="/app/.venv/bin:$PATH" +# Listens on every interface so the published port works. The API has no login: +# see "Security" in the Docker section of README.rst before exposing it beyond +# your machine (ALLOWED_HOSTS, reverse proxy with authentication). ENV DASHAI_HOST=0.0.0.0 EXPOSE 8000 CMD ["python", "-m", "DashAI", "--no-browser"] diff --git a/Dockerfile.cuda b/Dockerfile.cuda index 067728548..397876126 100644 --- a/Dockerfile.cuda +++ b/Dockerfile.cuda @@ -50,6 +50,9 @@ COPY . . # built frontend from stage 1 COPY --from=frontend /app/DashAI/front/build DashAI/front/build +# Listens on every interface so the published port works. The API has no login: +# see "Security" in the Docker section of README.rst before exposing it beyond +# your machine (ALLOWED_HOSTS, reverse proxy with authentication). ENV DASHAI_HOST=0.0.0.0 EXPOSE 8000 CMD ["python3", "-m", "DashAI", "--no-browser"] diff --git a/README.rst b/README.rst index 44acc6df1..c0c778c88 100644 --- a/README.rst +++ b/README.rst @@ -292,6 +292,37 @@ runtime depends on your setup: NVIDIA Container Toolkit inside the WSL distro, following the `CUDA on WSL guide `_. +Security +-------- + +The dashAI API has no login of its own. The desktop app only listens on +``127.0.0.1``, but inside a container dashAI listens on every interface +(``DASHAI_HOST=0.0.0.0``), so anyone who can reach the published port has full +control of that instance: its datasets, models and stored credentials. + +* **Local use:** publish the port on your own machine only, so nothing else on + the network can reach it: + + .. code:: bash + + $ docker run -p 127.0.0.1:8000:8000 dashai + +* **Access from other machines:** dashAI only answers requests addressed to + ``localhost`` or ``127.0.0.1``. Add the name or IP you use to reach the + server with ``ALLOWED_HOSTS``, and put the container behind a reverse proxy + that requires authentication: + + .. code:: bash + + $ docker run -p 8000:8000 -e ALLOWED_HOSTS=localhost,dashai.example.org dashai + + ``docker-compose.demo.yml`` reads the same list from the + ``DASHAI_ALLOWED_HOSTS`` variable: + + .. code:: bash + + $ DASHAI_ALLOWED_HOSTS=localhost,dashai.example.org docker compose -f docker-compose.demo.yml up + Test datasets ============= diff --git a/docker-compose.demo.yml b/docker-compose.demo.yml index 2e3c8542c..52527495d 100644 --- a/docker-compose.demo.yml +++ b/docker-compose.demo.yml @@ -1,6 +1,14 @@ +# dashAI only answers requests addressed to an allowed host. Set +# DASHAI_ALLOWED_HOSTS to the name or IP users reach this server with, e.g. +# DASHAI_ALLOWED_HOSTS=localhost,demo.example.org docker compose -f docker-compose.demo.yml up +# The API has no login: keep the server behind a proxy with authentication. +x-dashai-environment: &dashai-environment + ALLOWED_HOSTS: ${DASHAI_ALLOWED_HOSTS:-localhost,127.0.0.1} + services: dashai-1: image: dashai:latest + environment: *dashai-environment ports: - "8001:8000" volumes: @@ -13,6 +21,7 @@ services: dashai-2: image: dashai:latest + environment: *dashai-environment ports: - "8002:8000" volumes: @@ -25,6 +34,7 @@ services: dashai-3: image: dashai:latest + environment: *dashai-environment ports: - "8003:8000" volumes: @@ -37,6 +47,7 @@ services: dashai-4: image: dashai:latest + environment: *dashai-environment ports: - "8004:8000" volumes: @@ -49,6 +60,7 @@ services: dashai-5: image: dashai:latest + environment: *dashai-environment ports: - "8005:8000" volumes: @@ -61,6 +73,7 @@ services: dashai-6: image: dashai:latest + environment: *dashai-environment ports: - "8006:8000" volumes: @@ -73,6 +86,7 @@ services: dashai-7: image: dashai:latest + environment: *dashai-environment ports: - "8007:8000" volumes: @@ -85,6 +99,7 @@ services: dashai-8: image: dashai:latest + environment: *dashai-environment ports: - "8008:8000" volumes: @@ -97,6 +112,7 @@ services: dashai-9: image: dashai:latest + environment: *dashai-environment ports: - "8009:8000" volumes: @@ -109,6 +125,7 @@ services: dashai-10: image: dashai:latest + environment: *dashai-environment ports: - "8010:8000" volumes: @@ -121,6 +138,7 @@ services: dashai-11: image: dashai:latest + environment: *dashai-environment ports: - "8011:8000" volumes: @@ -133,6 +151,7 @@ services: dashai-12: image: dashai:latest + environment: *dashai-environment ports: - "8012:8000" volumes: From ec7534dcc7195c27b26400ac0956240156d30122 Mon Sep 17 00:00:00 2001 From: Creylay Date: Fri, 4 Dec 2026 12:58:14 -0300 Subject: [PATCH 3/5] fix: require a per-launch secret on API requests --- DashAI/back/api/api_v1/api.py | 2 + DashAI/back/api/api_v1/endpoints/auth.py | 33 +++++ DashAI/back/api/front_api.py | 4 + DashAI/back/api/launch_secret.py | 135 ++++++++++++++++++ DashAI/back/app.py | 11 ++ DashAI/back/config.py | 6 + tests/back/RAG/conftest.py | 2 + tests/back/api/conftest.py | 2 + tests/back/api/test_launch_secret_security.py | 88 ++++++++++++ tests/back/models/conftest.py | 2 + tests/back/schemas/test_schemas.py | 5 +- tests/back/types/inference_test.py | 2 + tests/back/types/load_preview_test.py | 2 + 13 files changed, 293 insertions(+), 1 deletion(-) create mode 100644 DashAI/back/api/api_v1/endpoints/auth.py create mode 100644 DashAI/back/api/launch_secret.py create mode 100644 tests/back/api/test_launch_secret_security.py diff --git a/DashAI/back/api/api_v1/api.py b/DashAI/back/api/api_v1/api.py index 3e2ae7b83..853ed818f 100644 --- a/DashAI/back/api/api_v1/api.py +++ b/DashAI/back/api/api_v1/api.py @@ -1,6 +1,7 @@ from fastapi import APIRouter from DashAI.back.api.api_v1.endpoints.app_config import router as app_config +from DashAI.back.api.api_v1.endpoints.auth import router as auth from DashAI.back.api.api_v1.endpoints.components import router as components from DashAI.back.api.api_v1.endpoints.converters import router as converters from DashAI.back.api.api_v1.endpoints.credentials import router as credentials @@ -64,3 +65,4 @@ api_router_v1.include_router(system, prefix="/system") api_router_v1.include_router(app_config, prefix="/app-config") api_router_v1.include_router(loaded_models, prefix="/loaded-models") +api_router_v1.include_router(auth, prefix="/auth") diff --git a/DashAI/back/api/api_v1/endpoints/auth.py b/DashAI/back/api/api_v1/endpoints/auth.py new file mode 100644 index 000000000..6dcaf54b0 --- /dev/null +++ b/DashAI/back/api/api_v1/endpoints/auth.py @@ -0,0 +1,33 @@ +from typing import Dict + +from fastapi import APIRouter, Response + +from DashAI.back.api.launch_secret import set_launch_cookie + +router = APIRouter() + + +@router.get("/launch") +async def start_launch_session(response: Response) -> Dict[str, bool]: + """Hand the browser this launch's secret cookie. + + The backend sets the cookie itself when it serves the app at ``/app/``. + The dev frontend is served by Vite instead, so it calls this endpoint once + on start (and again after a backend restart) to get the cookie. + + This endpoint is open on purpose: the cookie is ``HttpOnly`` and + ``SameSite=Strict``, so a foreign page that calls it can neither read the + secret nor make the browser attach it to its own requests. + + Parameters + ---------- + response : Response + The response that carries the ``Set-Cookie`` header. + + Returns + ------- + dict + ``{"ok": True}``. + """ + set_launch_cookie(response) + return {"ok": True} diff --git a/DashAI/back/api/front_api.py b/DashAI/back/api/front_api.py index b5b4e64ce..60a9bd7e5 100644 --- a/DashAI/back/api/front_api.py +++ b/DashAI/back/api/front_api.py @@ -7,6 +7,8 @@ from fastapi.responses import FileResponse, RedirectResponse from kink import di, inject +from DashAI.back.api.launch_secret import set_launch_cookie + mimetypes.add_type("text/javascript", ".js") router = APIRouter() @@ -24,6 +26,8 @@ async def read_index( response = FileResponse(index_path) response.headers["Cache-Control"] = "no-cache" response.headers["Expires"] = "0" + # Opening the app is what hands the browser this launch's API secret. + set_launch_cookie(response) return response diff --git a/DashAI/back/api/launch_secret.py b/DashAI/back/api/launch_secret.py new file mode 100644 index 000000000..4012b7fff --- /dev/null +++ b/DashAI/back/api/launch_secret.py @@ -0,0 +1,135 @@ +"""Per-launch secret that ties API requests to dashAI's own frontend. + +The API has no login, and CORS only hides responses: a foreign page can still +send simple requests (form posts, uploads, plain GETs) that take effect. To +tell dashAI's own frontend apart, every launch generates a random secret that +the backend hands to the browser in an ``HttpOnly`` + ``SameSite=Strict`` +cookie when it serves the app (or through the bootstrap endpoint the dev +frontend calls). Script code cannot read that cookie, and the browser only +attaches it to requests that come from dashAI itself, so requests started by a +foreign page arrive without it and are refused. + +Non-browser clients (scripts, server deployments) can send the secret in an +``Authorization: Bearer`` header; set ``API_TOKEN`` to make it a known, fixed +value instead of a random one. +""" + +import secrets +from typing import Iterable + +from kink import di +from starlette.requests import HTTPConnection +from starlette.responses import JSONResponse, Response +from starlette.types import ASGIApp, Receive, Scope, Send +from starlette.websockets import WebSocketClose + +COOKIE_NAME = "dashai_launch" +ERROR_CODE = "launch_secret_required" + + +def new_launch_secret(configured: str = "") -> str: + """Return the configured API token, or a fresh random secret. + + Parameters + ---------- + configured : str + The ``API_TOKEN`` setting. Empty means "generate one for this launch". + + Returns + ------- + str + The secret every protected request must carry. + """ + return configured or secrets.token_urlsafe(32) + + +def set_launch_cookie(response: Response) -> None: + """Hand the current launch secret to the browser. + + Parameters + ---------- + response : Response + The response that will carry the ``Set-Cookie`` header. + """ + response.set_cookie( + COOKIE_NAME, + di["launch_secret"], + httponly=True, + samesite="strict", + path="/", + ) + + +def has_launch_secret(connection: HTTPConnection) -> bool: + """Tell whether a request carries the current launch secret. + + The secret is read from the launch cookie, or from an + ``Authorization: Bearer`` header for non-browser clients. + + Parameters + ---------- + connection : HTTPConnection + The incoming HTTP request or websocket handshake. + + Returns + ------- + bool + True when the supplied secret matches the current one. + """ + supplied = connection.cookies.get(COOKIE_NAME) + if not supplied: + scheme, _, token = connection.headers.get("authorization", "").partition(" ") + if scheme.lower() == "bearer": + supplied = token.strip() + if not supplied: + return False + return secrets.compare_digest( + supplied.encode("utf-8"), di["launch_secret"].encode("utf-8") + ) + + +class LaunchSecretMiddleware: + """Refuse API requests that do not carry the launch secret. + + Parameters + ---------- + app : ASGIApp + The wrapped application. + protected_prefix : str + Requests whose path starts with this prefix need the secret. + exempt_paths : Iterable[str] + Exact paths under the prefix that stay open (the bootstrap endpoint + that hands the cookie out). + """ + + def __init__( + self, app: ASGIApp, protected_prefix: str, exempt_paths: Iterable[str] + ) -> None: + self.app = app + self.protected_prefix = protected_prefix + self.exempt_paths = frozenset(exempt_paths) + + def _needs_secret(self, scope: Scope) -> bool: + if scope["type"] not in ("http", "websocket"): + return False + path = scope["path"] + if not path.startswith(self.protected_prefix) or path in self.exempt_paths: + return False + # CORS preflights never carry cookies; CORSMiddleware answers them. + return not (scope["type"] == "http" and scope["method"] == "OPTIONS") + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if not self._needs_secret(scope) or has_launch_secret(HTTPConnection(scope)): + await self.app(scope, receive, send) + return + if scope["type"] == "websocket": + await WebSocketClose(code=1008)(scope, receive, send) + return + response = JSONResponse( + { + "detail": "This request did not come from the dashAI app.", + "code": ERROR_CODE, + }, + status_code=401, + ) + await response(scope, receive, send) diff --git a/DashAI/back/app.py b/DashAI/back/app.py index e47cd6322..016151f31 100644 --- a/DashAI/back/app.py +++ b/DashAI/back/app.py @@ -12,6 +12,7 @@ from DashAI.back.api.api_v1.api import api_router_v1 from DashAI.back.api.front_api import router as app_router +from DashAI.back.api.launch_secret import LaunchSecretMiddleware, new_launch_secret from DashAI.back.container import build_container from DashAI.back.dependencies.config_builder import build_config_dict from DashAI.back.dependencies.database.backfill import ( @@ -146,6 +147,16 @@ def create_app( app.include_router(app_router) + # Middleware added first runs last (innermost). The launch secret check + # goes innermost so CORSMiddleware still answers preflights and adds its + # headers to the 401, letting the dev frontend see the status. + di["launch_secret"] = new_launch_secret(config["API_TOKEN"]) + app.add_middleware( + LaunchSecretMiddleware, + protected_prefix="/api/", + exempt_paths=[f"{config['API_V1_STR']}/auth/launch"], + ) + allowed_origins = [ origin.strip() for origin in config["CORS_ALLOWED_ORIGINS"].split(",") diff --git a/DashAI/back/config.py b/DashAI/back/config.py index 8f5ed0022..569b86579 100644 --- a/DashAI/back/config.py +++ b/DashAI/back/config.py @@ -53,6 +53,12 @@ class DefaultSettings(BaseSettings): # a Docker or server deployment (e.g. ALLOWED_HOSTS=localhost,10.0.0.5). ALLOWED_HOSTS: str = "localhost,127.0.0.1" + # Secret every API request must carry (see DashAI/back/api/launch_secret). + # Empty means a new random secret per launch, handed to the browser in a + # cookie when it opens the app. Set API_TOKEN to a fixed value for Docker or + # server setups whose scripts call the API with "Authorization: Bearer". + API_TOKEN: str = "" + # Keep generative models loaded in the job worker between chat messages. MODEL_CACHE_ENABLED: bool = True # Seconds a cached model may stay unused before it is unloaded. diff --git a/tests/back/RAG/conftest.py b/tests/back/RAG/conftest.py index 754b5804c..cf9bf130b 100644 --- a/tests/back/RAG/conftest.py +++ b/tests/back/RAG/conftest.py @@ -398,6 +398,8 @@ def client(test_path: Path): _mark_download_required_components_present(app) test_client = TestClient(app) + # Get this launch's API secret cookie, as the frontend does on start. + test_client.get("/api/v1/auth/launch") yield test_client if job_queue and isinstance(job_queue, HueyJobQueue): diff --git a/tests/back/api/conftest.py b/tests/back/api/conftest.py index 8858920b6..715550be9 100644 --- a/tests/back/api/conftest.py +++ b/tests/back/api/conftest.py @@ -39,6 +39,8 @@ def client(test_path: Path): job_queue.set_test_mode(True) test_client = TestClient(app) + # Get this launch's API secret cookie, as the frontend does on start. + test_client.get("/api/v1/auth/launch") yield test_client if job_queue and isinstance(job_queue, HueyJobQueue): diff --git a/tests/back/api/test_launch_secret_security.py b/tests/back/api/test_launch_secret_security.py new file mode 100644 index 000000000..1253ca1fc --- /dev/null +++ b/tests/back/api/test_launch_secret_security.py @@ -0,0 +1,88 @@ +"""Security tests for the per-launch API secret. + +CORS only hides responses, so a foreign page could still send simple requests +(form posts, uploads, plain GETs) that take effect. Every API request must now +carry this launch's secret, which the browser only gets from dashAI itself in +an HttpOnly, SameSite=Strict cookie. +""" + +import pytest +from fastapi.testclient import TestClient +from kink import di +from starlette.websockets import WebSocketDisconnect + +from DashAI.back.api.launch_secret import COOKIE_NAME, ERROR_CODE, new_launch_secret + +ENDPOINT = "/api/v1/credential/" +LAUNCH = "/api/v1/auth/launch" + + +@pytest.fixture(name="stranger") +def fixture_stranger(client): + """A client on the same app that never got the launch cookie.""" + return TestClient(client.app) + + +def test_request_without_secret_is_refused(stranger): + response = stranger.get(ENDPOINT) + assert response.status_code == 401 + assert response.json()["code"] == ERROR_CODE + + +def test_simple_form_post_without_secret_is_refused(stranger): + """A cross-site form post (no preflight) must not reach the endpoint.""" + response = stranger.post( + "/api/v1/job/", data={"job_type": "DatasetJob", "kwargs": "{}"} + ) + assert response.status_code == 401 + + +def test_wrong_secret_is_refused(stranger): + stranger.cookies.set(COOKIE_NAME, "not-the-secret") + assert stranger.get(ENDPOINT).status_code == 401 + + +def test_launch_endpoint_hands_out_a_strict_httponly_cookie(stranger): + response = stranger.get(LAUNCH) + assert response.status_code == 200 + set_cookie = response.headers["set-cookie"].lower() + assert f"{COOKIE_NAME}=" in set_cookie + assert "httponly" in set_cookie + assert "samesite=strict" in set_cookie + assert stranger.get(ENDPOINT).status_code == 200 + + +def test_opening_the_app_hands_out_the_cookie(stranger): + config = stranger.app.container._services["config"] + build = config["FRONT_BUILD_PATH"] + build.mkdir(parents=True, exist_ok=True) + index = build / "index.html" + created = not index.exists() + if created: + index.write_text("") + try: + response = stranger.get("/app/") + assert response.status_code == 200 + assert COOKIE_NAME in response.headers["set-cookie"] + assert stranger.get(ENDPOINT).status_code == 200 + finally: + if created: + index.unlink(missing_ok=True) + + +def test_bearer_header_is_accepted(stranger): + headers = {"Authorization": f"Bearer {di['launch_secret']}"} + assert stranger.get(ENDPOINT, headers=headers).status_code == 200 + + +def test_websocket_without_secret_is_refused(stranger): + with ( + pytest.raises(WebSocketDisconnect), + stranger.websocket_connect("/api/v1/hardware/ws"), + ): + pass + + +def test_api_token_setting_fixes_the_secret(): + assert new_launch_secret("my-fixed-token") == "my-fixed-token" + assert new_launch_secret("") != new_launch_secret("") diff --git a/tests/back/models/conftest.py b/tests/back/models/conftest.py index f9dc1ed9b..70688e404 100644 --- a/tests/back/models/conftest.py +++ b/tests/back/models/conftest.py @@ -37,6 +37,8 @@ def client(test_path: Path): job_queue.set_test_mode(True) test_client = TestClient(app) + # Get this launch's API secret cookie, as the frontend does on start. + test_client.get("/api/v1/auth/launch") yield test_client if job_queue and isinstance(job_queue, HueyJobQueue): diff --git a/tests/back/schemas/test_schemas.py b/tests/back/schemas/test_schemas.py index 8937fded0..ce4d25c1b 100644 --- a/tests/back/schemas/test_schemas.py +++ b/tests/back/schemas/test_schemas.py @@ -161,7 +161,10 @@ def client(test_path: pathlib.Path): enable_seeding=False, ) - yield TestClient(app) + test_client = TestClient(app) + # Get this launch's API secret cookie, as the frontend does on start. + test_client.get("/api/v1/auth/launch") + yield test_client app.container._services["engine"].dispose() remove_dir_with_retry(app.container._services["config"]["LOCAL_PATH"]) diff --git a/tests/back/types/inference_test.py b/tests/back/types/inference_test.py index b51a54b53..27d55bb4a 100644 --- a/tests/back/types/inference_test.py +++ b/tests/back/types/inference_test.py @@ -29,6 +29,8 @@ def _infer(client, file_path: Path, mime: str, params: dict): def client(tmp_path: Path): app = create_app(local_path=tmp_path, logging_level="ERROR", enable_seeding=False) with TestClient(app) as c: + # Get this launch's API secret cookie, as the frontend does on start. + c.get("/api/v1/auth/launch") yield c diff --git a/tests/back/types/load_preview_test.py b/tests/back/types/load_preview_test.py index baa77c8af..80e08240b 100644 --- a/tests/back/types/load_preview_test.py +++ b/tests/back/types/load_preview_test.py @@ -21,6 +21,8 @@ async def nolifespan(_app): app.router.lifespan_context = nolifespan with TestClient(app) as c: + # Get this launch's API secret cookie, as the frontend does on start. + c.get("/api/v1/auth/launch") yield c From d7178b5205022ae1275504d927dc2606b76945d8 Mon Sep 17 00:00:00 2001 From: Creylay Date: Fri, 4 Dec 2026 13:12:28 -0300 Subject: [PATCH 4/5] fix: send the launch secret cookie from the frontend --- DashAI/front/src/api/api.ts | 39 +++++++++++++++++++++++++++++++++++ DashAI/front/src/index.jsx | 41 ++++++++++++++++++++++--------------- 2 files changed, 64 insertions(+), 16 deletions(-) diff --git a/DashAI/front/src/api/api.ts b/DashAI/front/src/api/api.ts index 497d07633..aee16d5c5 100644 --- a/DashAI/front/src/api/api.ts +++ b/DashAI/front/src/api/api.ts @@ -4,6 +4,10 @@ import i18n from "../utils/i18n"; const api: AxiosInstance = axios.create({ baseURL: import.meta.env.VITE_API_URL, + // Send the launch secret cookie on every request, including the dev setup + // where the frontend (port 3000) and the API (port 8000) are different + // origins. + withCredentials: true, paramsSerializer: (params) => { const sp = new URLSearchParams(); for (const [key, val] of Object.entries(params)) { @@ -24,4 +28,39 @@ api.interceptors.request.use((config) => { return config; }); +// The backend refuses API requests that lack this launch's secret cookie +// (HttpOnly, SameSite=Strict). It sets the cookie when it serves /app/; the +// dev frontend is served by Vite, so it asks for it explicitly. +const LAUNCH_SECRET_ERROR = "launch_secret_required"; +let pendingLaunchSession: Promise | null = null; + +export function startLaunchSession(): Promise { + if (!pendingLaunchSession) { + pendingLaunchSession = api + .get("/v1/auth/launch") + .then(() => undefined) + .finally(() => { + pendingLaunchSession = null; + }); + } + return pendingLaunchSession; +} + +// After a backend restart the cookie holds the previous launch's secret: get +// the new one and retry the request once. +api.interceptors.response.use(undefined, async (error) => { + const config = error.config; + if ( + config && + !config._launchRetried && + error.response?.status === 401 && + error.response.data?.code === LAUNCH_SECRET_ERROR + ) { + config._launchRetried = true; + await startLaunchSession(); + return api(config); + } + return Promise.reject(error); +}); + export default api; diff --git a/DashAI/front/src/index.jsx b/DashAI/front/src/index.jsx index 1462d5b58..84507e191 100644 --- a/DashAI/front/src/index.jsx +++ b/DashAI/front/src/index.jsx @@ -7,22 +7,31 @@ import App from "./App"; import { SnackbarProvider } from "notistack"; import { CustomThemeProvider } from "./contexts/ThemeContext"; import "./utils/i18n"; +import { startLaunchSession } from "./api/api"; const root = ReactDOM.createRoot(document.getElementById("root")); -root.render( - - - - - - - - , -); +const renderApp = () => + root.render( + + + + + + + + , + ); + +// Get this launch's API secret cookie before anything (including tags +// pointing at the API) calls the backend. If the backend is not reachable yet, +// render anyway: the app already reports backend errors on its own. +startLaunchSession() + .catch(() => {}) + .then(renderApp); From 1dfd0df24335f550d927fe59c1b82316a411b80c Mon Sep 17 00:00:00 2001 From: Creylay Date: Fri, 4 Dec 2026 13:14:56 -0300 Subject: [PATCH 5/5] docs: document API_TOKEN for scripts and server setups --- README.rst | 13 +++++++++++++ tests/back/api/test_api_token_setting.py | 24 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 tests/back/api/test_api_token_setting.py diff --git a/README.rst b/README.rst index c0c778c88..2d0702cb8 100644 --- a/README.rst +++ b/README.rst @@ -323,6 +323,19 @@ control of that instance: its datasets, models and stored credentials. $ DASHAI_ALLOWED_HOSTS=localhost,dashai.example.org docker compose -f docker-compose.demo.yml up +* **Calling the API from scripts:** every API request must carry a secret that + dashAI generates on each launch. Browsers get it automatically in a cookie + when they open the app, so nothing changes for people using the interface. + Scripts and other non-browser clients need a fixed value: set ``API_TOKEN`` + and send it in an ``Authorization`` header: + + .. code:: bash + + $ docker run -p 127.0.0.1:8000:8000 -e API_TOKEN=change-me dashai + $ curl -H "Authorization: Bearer change-me" http://localhost:8000/api/v1/dataset/ + + Treat ``API_TOKEN`` like a password: anyone who has it can use the API. + Test datasets ============= diff --git a/tests/back/api/test_api_token_setting.py b/tests/back/api/test_api_token_setting.py new file mode 100644 index 000000000..5ba14f54c --- /dev/null +++ b/tests/back/api/test_api_token_setting.py @@ -0,0 +1,24 @@ +"""The API_TOKEN setting fixes the API secret for scripts and server setups. + +Kept in its own module: building a second app replaces the global ``di`` +services, which would leak into the other tests of a shared module. +""" + +from fastapi.testclient import TestClient + +from DashAI.back.app import create_app + + +def test_api_token_setting_authorizes_bearer_requests(tmp_path, monkeypatch): + monkeypatch.setenv("API_TOKEN", "change-me") + app = create_app(local_path=tmp_path, logging_level="ERROR", enable_seeding=False) + try: + scripts = TestClient(app) + endpoint = "/api/v1/dataset/" + assert scripts.get(endpoint).status_code == 401 + wrong = {"Authorization": "Bearer something-else"} + assert scripts.get(endpoint, headers=wrong).status_code == 401 + right = {"Authorization": "Bearer change-me"} + assert scripts.get(endpoint, headers=right).status_code == 200 + finally: + app.container._services["engine"].dispose()