From ae8088736e6df949e3c3781dfa7adc9591cfe56c Mon Sep 17 00:00:00 2001 From: Creylay Date: Wed, 2 Dec 2026 11:28:58 -0300 Subject: [PATCH 1/5] fix: sanitize uploaded file name in job endpoint --- DashAI/back/api/api_v1/endpoints/jobs.py | 18 ++++++++- tests/back/api/test_jobs_upload_security.py | 45 +++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 tests/back/api/test_jobs_upload_security.py diff --git a/DashAI/back/api/api_v1/endpoints/jobs.py b/DashAI/back/api/api_v1/endpoints/jobs.py index 881e93420..f2e2d1924 100644 --- a/DashAI/back/api/api_v1/endpoints/jobs.py +++ b/DashAI/back/api/api_v1/endpoints/jobs.py @@ -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( diff --git a/tests/back/api/test_jobs_upload_security.py b/tests/back/api/test_jobs_upload_security.py new file mode 100644 index 000000000..0211b901f --- /dev/null +++ b/tests/back/api/test_jobs_upload_security.py @@ -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" From 4a36dd1726fb63c0b2f263f730de2ce27946cfab Mon Sep 17 00:00:00 2001 From: Creylay Date: Wed, 2 Dec 2026 11:58:29 -0300 Subject: [PATCH 2/5] fix: stop returning stored credential keys from the API --- .../back/api/api_v1/endpoints/credentials.py | 23 +++++++----------- .../credentials/CredentialsDialog.jsx | 5 +++- DashAI/front/src/types/credential.ts | 1 - tests/back/api/test_credentials_api.py | 24 ++++++++++++++++++- 4 files changed, 35 insertions(+), 18 deletions(-) diff --git a/DashAI/back/api/api_v1/endpoints/credentials.py b/DashAI/back/api/api_v1/endpoints/credentials.py index b99ad1eab..a7825d969 100644 --- a/DashAI/back/api/api_v1/endpoints/credentials.py +++ b/DashAI/back/api/api_v1/endpoints/credentials.py @@ -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 ---------- @@ -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) @@ -106,7 +104,6 @@ def _status_payload( "display_name": display_name or name, "description": description or "", "is_authenticated": is_authenticated, - "key": key, } @@ -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() ] @@ -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") diff --git a/DashAI/front/src/components/credentials/CredentialsDialog.jsx b/DashAI/front/src/components/credentials/CredentialsDialog.jsx index 7452b0e7c..27848355c 100644 --- a/DashAI/front/src/components/credentials/CredentialsDialog.jsx +++ b/DashAI/front/src/components/credentials/CredentialsDialog.jsx @@ -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); diff --git a/DashAI/front/src/types/credential.ts b/DashAI/front/src/types/credential.ts index 9426156f6..4ceeeaaf3 100644 --- a/DashAI/front/src/types/credential.ts +++ b/DashAI/front/src/types/credential.ts @@ -3,5 +3,4 @@ export interface ICredential { display_name: string; description: string; is_authenticated: boolean; - key: string | null; } diff --git a/tests/back/api/test_credentials_api.py b/tests/back/api/test_credentials_api.py index bc318eb5f..976a74eda 100644 --- a/tests/back/api/test_credentials_api.py +++ b/tests/back/api/test_credentials_api.py @@ -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): From 98eac3902280a34ade9021c36472b56d79919f66 Mon Sep 17 00:00:00 2001 From: Creylay Date: Wed, 2 Dec 2026 12:28:18 -0300 Subject: [PATCH 3/5] fix: reject static file paths outside the build directory --- DashAI/back/api/front_api.py | 8 +++- tests/back/api/test_front_api_security.py | 47 +++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 tests/back/api/test_front_api_security.py diff --git a/DashAI/back/api/front_api.py b/DashAI/back/api/front_api.py index 110356755..b5b4e64ce 100644 --- a/DashAI/back/api/front_api.py +++ b/DashAI/back/api/front_api.py @@ -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: diff --git a/tests/back/api/test_front_api_security.py b/tests/back/api/test_front_api_security.py new file mode 100644 index 000000000..413c8fd01 --- /dev/null +++ b/tests/back/api/test_front_api_security.py @@ -0,0 +1,47 @@ +"""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. +""" + +import os +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, tmp_path): + """A ``..`` traversal must not expose a file outside the build dir.""" + secret = tmp_path / "secret.txt" + secret.write_text("TOP_SECRET_FRONT_TRAVERSAL") + + base = _build_path(client) + rel = os.path.relpath(secret, base) + # Encode the slashes so the HTTP client does not collapse the ".." + # segments before they reach the server (the raw ".." vector gets + # normalized away client-side). + encoded = rel.replace(os.sep, "/").replace("/", "%2F") + + response = client.get(f"/{encoded}") + + assert "TOP_SECRET_FRONT_TRAVERSAL" not in response.text + + +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) From 6066a6df6532dee23f73ffa8dc731826ef87e998 Mon Sep 17 00:00:00 2001 From: Creylay Date: Wed, 2 Dec 2026 12:48:20 -0300 Subject: [PATCH 4/5] fix: restrict API CORS to known origins --- DashAI/back/app.py | 7 ++++++- DashAI/back/config.py | 8 ++++++++ tests/back/api/test_cors_security.py | 22 ++++++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 tests/back/api/test_cors_security.py diff --git a/DashAI/back/app.py b/DashAI/back/app.py index 4aa28a54a..bee897724 100644 --- a/DashAI/back/app.py +++ b/DashAI/back/app.py @@ -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=["*"], diff --git a/DashAI/back/config.py b/DashAI/back/config.py index db35e31c8..05a435559 100644 --- a/DashAI/back/config.py +++ b/DashAI/back/config.py @@ -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. diff --git a/tests/back/api/test_cors_security.py b/tests/back/api/test_cors_security.py new file mode 100644 index 000000000..352da5852 --- /dev/null +++ b/tests/back/api/test_cors_security.py @@ -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 From 6d73fd7b75278f6f3e6650d5a68c9c43a3607ab7 Mon Sep 17 00:00:00 2001 From: Creylay Date: Wed, 2 Dec 2026 16:18:55 -0300 Subject: [PATCH 5/5] test: make static-file traversal test drive-independent for Windows CI --- tests/back/api/test_front_api_security.py | 33 +++++++++++++---------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/tests/back/api/test_front_api_security.py b/tests/back/api/test_front_api_security.py index 413c8fd01..51ef064fb 100644 --- a/tests/back/api/test_front_api_security.py +++ b/tests/back/api/test_front_api_security.py @@ -7,7 +7,6 @@ target that does not resolve inside the build dir. """ -import os from pathlib import Path @@ -16,21 +15,27 @@ def _build_path(client) -> Path: return Path(config["FRONT_BUILD_PATH"]).resolve() -def test_static_file_cannot_escape_build_dir(client, tmp_path): +def test_static_file_cannot_escape_build_dir(client): """A ``..`` traversal must not expose a file outside the build dir.""" - secret = tmp_path / "secret.txt" - secret.write_text("TOP_SECRET_FRONT_TRAVERSAL") - base = _build_path(client) - rel = os.path.relpath(secret, base) - # Encode the slashes so the HTTP client does not collapse the ".." - # segments before they reach the server (the raw ".." vector gets - # normalized away client-side). - encoded = rel.replace(os.sep, "/").replace("/", "%2F") - - response = client.get(f"/{encoded}") - - assert "TOP_SECRET_FRONT_TRAVERSAL" not in response.text + 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):