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
23 changes: 8 additions & 15 deletions DashAI/back/api/api_v1/endpoints/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,16 @@ def _status_payload(
name: str,
component_dict: Dict[str, Any],
is_authenticated: bool,
key: Union[str, None],
language: Union[str, None] = None,
) -> Dict[str, Any]:
"""Build the status payload for a credential.

The payload bundles the catalog fields (display name, description) with the
authentication state in a single object so the configuration modal can be
populated with one request. The stored key is included so the modal can
display it, which is acceptable for DashAI's local-first, single-user
desktop model where the database already lives on the user's machine.
authentication state. The stored key is deliberately NOT returned: with
``is_authenticated`` the frontend already knows whether a key is saved, and
an unauthenticated API served to any origin (CORS) would otherwise hand the
decrypted key to a web page the user merely visits, undoing the Fernet
encryption at rest.

Parameters
----------
Expand All @@ -89,15 +89,13 @@ def _status_payload(
The registry component dict.
is_authenticated : bool
Whether the credential is currently verified.
key : Union[str, None]
The stored decrypted key, or None if nothing is stored.
language : Union[str, None]
The ``Accept-Language`` header used to localize text fields.

Returns
-------
Dict[str, Any]
Status payload including localized display name, description and key.
Status payload with localized display name and description.
"""
display_name = _localize(component_dict.get("display_name"), language)
description = _localize(component_dict.get("description"), language)
Expand All @@ -106,7 +104,6 @@ def _status_payload(
"display_name": display_name or name,
"description": description or "",
"is_authenticated": is_authenticated,
"key": key,
}


Expand Down Expand Up @@ -136,9 +133,7 @@ async def list_credentials(
store = di["credential_store"]
statuses = store.all_statuses()
return [
_status_payload(
name, cdict, statuses.get(name, False), store.load(name), accept_language
)
_status_payload(name, cdict, statuses.get(name, False), accept_language)
for name, cdict in creds.items()
]

Expand Down Expand Up @@ -177,9 +172,7 @@ async def get_credential_status(
detail=f"Credential '{name}' not found.",
)
store = di["credential_store"]
return _status_payload(
name, creds[name], store.is_verified(name), store.load(name), accept_language
)
return _status_payload(name, creds[name], store.is_verified(name), accept_language)


@router.post("/{name}/auth")
Expand Down
18 changes: 17 additions & 1 deletion DashAI/back/api/api_v1/endpoints/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,25 @@ async def enqueue_job(

# parse multipart/form-data with file
if "multipart/form-data" in content_type and "filename" in request.headers:
filename = request.headers.get("filename", "uploaded_file")
raw_filename = request.headers.get("filename", "uploaded_file")
# Never trust the client-supplied name as a path. Keep only the
# final path component so an absolute path or ".." in the header
# cannot make the upload land outside temp_dir (os.path.join drops
# temp_dir entirely when handed an absolute path).
filename = os.path.basename(raw_filename)
if filename in ("", ".", ".."):
filename = "uploaded_file"
temp_dir = tempfile.mkdtemp()
file_path = os.path.join(temp_dir, filename)
# Defense in depth: refuse anything that still resolves outside
# temp_dir before a single byte is written.
if os.path.commonpath(
[os.path.realpath(file_path), os.path.realpath(temp_dir)]
) != os.path.realpath(temp_dir):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid filename",
)

parser = StreamingFormDataParser(headers=request.headers)
parser.register(
Expand Down
8 changes: 7 additions & 1 deletion DashAI/back/api/front_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,13 @@ async def serve_files(
try:
if file == "":
return RedirectResponse(url="/app/")
path = Path(f"{front_build_path}/{file}").absolute()
base = Path(front_build_path).resolve()
# resolve() collapses any ".." so we see the real target; absolute()
# would leave them in the string and let the OS walk out of base when
# the file is opened (path traversal). Refuse anything outside base.
path = (base / file).resolve()
if not path.is_relative_to(base):
return RedirectResponse(url="/app/")
os.stat(path)
return FileResponse(path)
except FileNotFoundError:
Expand Down
7 changes: 6 additions & 1 deletion DashAI/back/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,14 @@ def create_app(

app.include_router(app_router)

allowed_origins = [
origin.strip()
for origin in config["CORS_ALLOWED_ORIGINS"].split(",")
if origin.strip()
]
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_origins=allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
Expand Down
8 changes: 8 additions & 0 deletions DashAI/back/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ class DefaultSettings(BaseSettings):
# updater be tried end to end without touching the official releases.
UPDATE_CHECK_REPOSITORY: str = "DashAISoftware/DashAI"

# Browser origins allowed to call the API with credentials (CORS), as a
# comma-separated list. Defaults to the dev frontend (Vite on port 3000).
# Production is served from the same origin as the API, so it needs no
# entry here. Set CORS_ALLOWED_ORIGINS to add others (e.g. a remote host
# serving the frontend). Never set it to "*": that, with credentials,
# 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"

# 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
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ import { setCredentialStatus, setCredentialStatuses } from "./credentialStatus";
function CredentialRow({ credential, onChanged }) {
const { t } = useTranslation("credentials");
const { enqueueSnackbar } = useSnackbar();
const [key, setKey] = useState(credential.key ?? "");
// The API never returns the stored key (it stays encrypted at rest), so the
// field always starts empty. The "authenticated" label tells the user a key
// is saved; to change it they type a new one.
const [key, setKey] = useState("");
const [showKey, setShowKey] = useState(false);
const [busy, setBusy] = useState(false);

Expand Down
1 change: 0 additions & 1 deletion DashAI/front/src/types/credential.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,4 @@ export interface ICredential {
display_name: string;
description: string;
is_authenticated: boolean;
key: string | null;
}
22 changes: 22 additions & 0 deletions tests/back/api/test_cors_security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""Security test for the CORS configuration.

The API used to run with ``allow_origins=["*"]`` and ``allow_credentials=True``.
Starlette answers that by echoing back whatever Origin the caller sent, so any
web page the user visits could call the (unauthenticated) API on their behalf.
The API must only grant CORS to its own known origins.
"""

ENDPOINT = "/api/v1/credential/"


def test_cors_rejects_unknown_origin(client):
"""An untrusted origin must not be granted access."""
response = client.get(ENDPOINT, headers={"Origin": "https://evil.example"})
assert response.headers.get("access-control-allow-origin") != "https://evil.example"


def test_cors_allows_dev_frontend_origin(client):
"""The dev frontend origin is still allowed so local development works."""
origin = "http://localhost:3000"
response = client.get(ENDPOINT, headers={"Origin": origin})
assert response.headers.get("access-control-allow-origin") == origin
24 changes: 23 additions & 1 deletion tests/back/api/test_credentials_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,29 @@ def test_list_credentials(client):
# catalog + status returned together in one request
assert "display_name" in cred
assert "description" in cred
assert "key" in cred
# the stored key must never be returned by the API
assert "key" not in cred


def test_stored_key_is_never_returned(client):
"""Saving a key must not make it readable through the credential API."""
secret = "hf_SECRET_never_leak_1234"
with patch(
"DashAI.back.credentials.huggingface_credential.HuggingFaceCredential.verify",
return_value=True,
):
client.post(
"/api/v1/credential/HuggingFaceCredential/auth",
json={"key": secret},
)

list_response = client.get("/api/v1/credential/")
assert secret not in list_response.text

status_response = client.get("/api/v1/credential/HuggingFaceCredential")
assert status_response.json()["is_authenticated"] is True
assert secret not in status_response.text
assert "key" not in status_response.json()


def test_auth_success_marks_authenticated(client):
Expand Down
52 changes: 52 additions & 0 deletions tests/back/api/test_front_api_security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Security test for the static-file endpoint.

``GET /{file:path}`` serves the compiled frontend. It used to join the raw
request path onto the build dir with ``Path(...).absolute()``, which does not
collapse ``..`` segments, so a crafted path escaped the build dir and let the
server read arbitrary files (path traversal). The endpoint must refuse any
target that does not resolve inside the build dir.
"""

from pathlib import Path


def _build_path(client) -> Path:
config = client.app.container._services["config"]
return Path(config["FRONT_BUILD_PATH"]).resolve()


def test_static_file_cannot_escape_build_dir(client):
"""A ``..`` traversal must not expose a file outside the build dir."""
base = _build_path(client)
base.mkdir(parents=True, exist_ok=True)
# Keep the sentinel on the same drive as the build dir, so the traversal is
# expressible on Windows too (a ".." path cannot cross drives, and
# os.path.relpath across drives raises).
secret = base.parent / "secret_traversal_probe.txt"
secret.write_text("TOP_SECRET_FRONT_TRAVERSAL")
try:
# Climb to the drive root with plenty of "..", then descend to the
# sentinel by its path from the root. The slashes are encoded so the
# HTTP client does not collapse the ".." segments before they reach
# the server (the raw ".." vector gets normalized away client-side).
from_root = secret.relative_to(secret.anchor).as_posix()
traversal = "../" * 40 + from_root
encoded = traversal.replace("/", "%2F")
response = client.get(f"/{encoded}")
assert "TOP_SECRET_FRONT_TRAVERSAL" not in response.text
finally:
secret.unlink(missing_ok=True)


def test_static_file_inside_build_dir_is_served(client):
"""A legitimate file inside the build dir is still served normally."""
base = _build_path(client)
base.mkdir(parents=True, exist_ok=True)
asset = base / "probe.txt"
asset.write_text("LEGIT_ASSET_BODY")
try:
response = client.get("/probe.txt")
assert response.status_code == 200
assert response.text == "LEGIT_ASSET_BODY"
finally:
asset.unlink(missing_ok=True)
45 changes: 45 additions & 0 deletions tests/back/api/test_jobs_upload_security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""Security test for the job upload endpoint.

The ``POST /api/v1/job/`` endpoint takes the uploaded file's name from a
``filename`` request header. A malicious client used to be able to send an
absolute path (or ``..`` segments) there and have the file written outside the
server-created temp dir, overwriting arbitrary files the user can write. The
endpoint must keep only the basename so the upload never escapes temp_dir.
"""

import os

from fastapi.testclient import TestClient


def test_upload_filename_header_cannot_escape_temp_dir(client: TestClient, tmp_path):
"""An absolute ``filename`` header must not write outside the temp dir."""
target = tmp_path / "PWNED.txt"
assert not target.exists()

response = client.post(
"/api/v1/job/",
files={"file": ("ignored", b"malicious payload")},
headers={"filename": str(target)},
)

# The request is rejected for other reasons (no job_type/kwargs), but the
# point is that the attacker-controlled absolute path was never written.
assert not target.exists(), "upload escaped temp_dir via the filename header"
assert response.status_code != 500


def test_upload_filename_header_cannot_traverse_with_dotdot(
client: TestClient, tmp_path
):
"""A ``..`` traversal in the ``filename`` header must be neutralized."""
sentinel = tmp_path / "traversed.txt"
assert not sentinel.exists()

client.post(
"/api/v1/job/",
files={"file": ("ignored", b"payload")},
headers={"filename": f"../../../../../../../..{os.fspath(sentinel)}"},
)

assert not sentinel.exists(), "upload escaped temp_dir via .. traversal"
Loading