Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions DashAI/back/api/api_v1/api.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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")
33 changes: 33 additions & 0 deletions DashAI/back/api/api_v1/endpoints/auth.py
Original file line number Diff line number Diff line change
@@ -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}
4 changes: 4 additions & 0 deletions DashAI/back/api/front_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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


Expand Down
135 changes: 135 additions & 0 deletions DashAI/back/api/launch_secret.py
Original file line number Diff line number Diff line change
@@ -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)
18 changes: 18 additions & 0 deletions DashAI/back/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@

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
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 (
Expand Down Expand Up @@ -145,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(",")
Expand All @@ -157,6 +169,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.")

Expand Down
13 changes: 13 additions & 0 deletions DashAI/back/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,19 @@ 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"

# 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.
Expand Down
39 changes: 39 additions & 0 deletions DashAI/front/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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<void> | null = null;

export function startLaunchSession(): Promise<void> {
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;
41 changes: 25 additions & 16 deletions DashAI/front/src/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<React.StrictMode>
<CustomThemeProvider>
<SnackbarProvider
anchorOrigin={{
vertical: "top",
horizontal: "right",
}}
variant="error"
>
<CssBaseline />
<App />
</SnackbarProvider>
</CustomThemeProvider>
</React.StrictMode>,
);
const renderApp = () =>
root.render(
<React.StrictMode>
<CustomThemeProvider>
<SnackbarProvider
anchorOrigin={{
vertical: "top",
horizontal: "right",
}}
variant="error"
>
<CssBaseline />
<App />
</SnackbarProvider>
</CustomThemeProvider>
</React.StrictMode>,
);

// Get this launch's API secret cookie before anything (including <img> 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);
3 changes: 3 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
3 changes: 3 additions & 0 deletions Dockerfile.cuda
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Loading
Loading