Repository navigation
Studio: stop leaking internal exceptions to API clients; harden sandbox path - #6072
Conversation
…ox path
Security hardening for the FastAPI backend.
Error exposure (CodeQL py/stack-trace-exposure): many route handlers returned
raw caught-exception text to clients via HTTPException detail / response bodies,
which can leak internal filesystem paths and stack detail. Add shared helpers in
utils/utils.py (safe_error_detail, log_and_http_error) that log the full
exception server-side and return a generic message, and sweep the route layer
(inference, models, export, training, datasets, chat_history, providers,
mcp_servers, settings, data_recipe/{jobs,seed,validate,mcp}) to use them.
Intentionally user-facing validation messages, the existing _friendly_error SSE
paths, and upstream-service body passthrough (llama-server / OpenAI) are kept;
absolute server paths echoed in models.py browse/read errors are redacted.
Path injection (CodeQL py/path-injection): serve_sandbox_file already does
basename + realpath containment; add a strict filename allowlist
(^[A-Za-z0-9._-]{1,255}$) before the path is built as defense-in-depth and to
give the analyzer a clear sanitizer.
No behavior change beyond error-message text; status codes preserved.
There was a problem hiding this comment.
Code Review
This pull request introduces client-safe error helpers (safe_error_detail and log_and_http_error) to prevent raw exception details from leaking to API clients, updating various routes to log errors server-side and return sanitized messages. It also adds path-traversal defense-in-depth when serving sandbox files. Feedback on the changes highlights several unused imports of the new helpers across multiple route files, as well as an opportunity to use the more idiomatic .name property on pathlib.Path objects instead of os.path.basename in models.py.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| # Client-safe error helpers | ||
| from utils.utils import safe_error_detail, log_and_http_error |
| # Client-safe error helpers | ||
| from utils.utils import safe_error_detail, log_and_http_error |
There was a problem hiding this comment.
The helper log_and_http_error is imported but never used in this file. Removing unused imports keeps the codebase clean and maintainable.
| # Client-safe error helpers | |
| from utils.utils import safe_error_detail, log_and_http_error | |
| # Client-safe error helpers | |
| from utils.utils import safe_error_detail |
| McpToolsListResponse, | ||
| McpToolsProviderResult, | ||
| ) | ||
| from utils.utils import safe_error_detail, log_and_http_error |
| from core.data_recipe.jsonable import to_preview_jsonable | ||
| from loggers import get_logger | ||
| from utils.paths import ensure_dir, seed_uploads_root, unstructured_uploads_root | ||
| from utils.utils import safe_error_detail, log_and_http_error |
| from typing import List, Optional | ||
| import structlog | ||
| from loggers import get_logger | ||
| from utils.utils import safe_error_detail, log_and_http_error |
| # Client-safe error helpers | ||
| from utils.utils import safe_error_detail, log_and_http_error |
There was a problem hiding this comment.
The helper safe_error_detail is imported but never used in this file. Removing unused imports keeps the codebase clean and maintainable.
| # Client-safe error helpers | |
| from utils.utils import safe_error_detail, log_and_http_error | |
| # Client-safe error helpers | |
| from utils.utils import log_and_http_error |
| raise HTTPException( | ||
| status_code = 403, | ||
| detail = f"Permission denied reading {current}", | ||
| detail = f"Permission denied reading {os.path.basename(str(current))}", |
There was a problem hiding this comment.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: deeaa5fa31
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if not _re.fullmatch(r"[A-Za-z0-9._-]{1,255}", safe_filename): | ||
| raise HTTPException(status_code = 404, detail = "Not found") |
There was a problem hiding this comment.
Allow ordinary sandbox image filenames
When sandboxed Python saves an image with a legal basename such as loss curve.png or plot (1).png, core/inference/tools.py still detects it by extension and emits that exact basename in __IMAGES__, and the frontend URL-encodes it for this endpoint. This new regex rejects those names with 404 before the existing basename/realpath containment checks run, so user-generated images with spaces or parentheses no longer render even though they are inside the sandbox.
Useful? React with 👍 / 👎.
- inference.py /load non-native path: redact str(e) instead of leaking it (matched the native branch which already redacted). - llama_extra_args validation: return the curated, path-redacted message instead of the generic fallback so users see the offending flag. - sandbox file serving: allowlist now forbids only separators/control chars via fullmatch, so generated images like 'loss curve.png' render again while traversal is still blocked by basename + extension + realpath. - Add safe_curated_detail() for domain/validation exceptions whose message is intentionally user-facing; apply it to data_recipe job/validate, chat conflict, provider test, and MCP probe paths (these were collapsing to 'An internal error occurred', and 'connection' even mis-mapped to an upstream-service message). Generic Exception paths keep safe_error_detail. - log_and_http_error: tolerate stdlib loggers (no structlog kwargs). - delete_openai_container: log transport errors with exc_info like list/create. - Drop helper/HTTPException imports this change left unused.
…dio-error-hardening
…dio-error-hardening
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cde4f57e97
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| raise log_and_http_error( | ||
| exc, | ||
| 400, | ||
| safe_error_detail(exc), |
There was a problem hiding this comment.
Preserve actionable native lease errors
When a desktop native-path lease is expired, already used, has the wrong operation, or points at an unsupported file type, verify_native_path_lease raises a NativePathLeaseError with the specific recovery clue, but safe_error_detail() maps all of these 400s to the fallback "An internal error occurred". In the native GGUF load/validate flow this leaves the user with no indication that they need to re-select the file or choose a .gguf, even though these are client-correctable validation failures; use the curated/redacted detail path for this exception type instead of the generic internal-error helper.
Useful? React with 👍 / 👎.
| log.error(event, error = str(error), exc_info = True) | ||
| except TypeError: | ||
| # stdlib logging.Logger rejects structlog kwargs; pass the error as exc_info. | ||
| log.error("%s: %s", event, error, exc_info = error) |
There was a problem hiding this comment.
Just create a string before and pass to log.error instead?
The try except seems unnecessary here
- inference.py: keep the actionable NativePathLeaseError detail (path-redacted) instead of collapsing it to the generic message, matching the other curated validation paths in this file. - utils.py: log via a single formatted log.error(exc_info=error) call that works for structlog and stdlib loggers; drop the now-unneeded try/except helper. - models.py: use Path.name instead of os.path.basename(str(current)).
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b9f1333419
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| McpToolsProviderResult( | ||
| name = provider.name or provider_name, | ||
| error = str(exc).strip() or "Failed to load tools.", | ||
| error = safe_error_detail(exc, fallback = "Failed to load tools."), |
There was a problem hiding this comment.
Preserve MCP tool probe failure details
For recipe MCP providers, this endpoint feeds provider.error directly into the tool-profile dialog so users can fix server setup problems. With a reachable server that rejects auth, returns an MCP protocol error, or otherwise raises a non-connection exception, safe_error_detail falls back to the generic "Failed to load tools.", whereas the previous response included the actionable exception text; this leaves users unable to tell whether they need to fix credentials, URL/transport, or server configuration. Consider returning a redacted curated message here rather than the generic fallback.
Useful? React with 👍 / 👎.
| raise log_and_http_error( | ||
| exc, | ||
| 422, | ||
| "seed inspect failed", |
There was a problem hiding this comment.
Preserve seed upload parse errors
When a user uploads a malformed CSV/JSON seed file, pandas raises a ValueError with the row/format problem, and this 422 is shown by the seed dialog so the user can correct the file. This replacement always returns only "seed inspect failed", so client-correctable parse issues like bad JSON lines or inconsistent CSV columns no longer tell the user what to fix; use a redacted curated detail for these local preview validation failures instead of the generic message.
Useful? React with 👍 / 👎.
| raise HTTPException( | ||
| status_code = 400, | ||
| detail = f"Invalid model: {str(e)}", | ||
| detail = "Invalid model", |
There was a problem hiding this comment.
Preserve model validation failure reasons
For non-native model IDs, this /api/inference/validate preflight runs before the chat UI unloads the currently working model, and its error is surfaced to the user. Collapsing all failures to "Invalid model" hides actionable Hugging Face/config causes such as repository not found, gated/unauthorized access, or missing config, so users can no longer tell whether to fix the repo id, token, or model choice; return a redacted user-facing reason here as the native path branch still does.
Useful? React with 👍 / 👎.
| raise log_and_http_error( | ||
| exc, | ||
| 502, | ||
| f"Failed to list models from {payload.provider_type}.", |
There was a problem hiding this comment.
Preserve provider model-list errors
The chat provider dialog shows this endpoint's detail in the Could not load models toast when users fetch a provider's model catalog. For provider responses like 401/403 from a bad key, a malformed custom base URL, or a provider-side /models error, this now always returns only "Failed to list models from <provider>.", whereas the previous detail included the actionable upstream exception; users can no longer tell whether to update credentials, fix the URL, or retry the provider. Return a redacted provider error here instead of discarding the cause.
Useful? React with 👍 / 👎.
What
Security hardening for the Studio FastAPI backend, fixing the pre-existing CodeQL
alerts (2 high
py/path-injection, 7 mediumpy/stack-trace-exposure) andextending the error fix repo-wide across the route layer.
Why
CodeQL flagged
studio/backend/routes/inference.pyfor returning raw exceptiontext to clients and for user-controlled path construction. A wider review showed
the exception-leak pattern (
raise HTTPException(detail = str(e)),f"...: {exc}",{"error": str(exc)}) repeated across most route files: rawcaught-exception text reaching clients can leak internal filesystem paths and
stack detail.
Changes
Stop leaking internal exceptions (py/stack-trace-exposure)
studio/backend/utils/utils.py:safe_error_detail(exc, fallback = "An internal error occurred")— returns ageneric, client-safe message (never raw
str(exc)), with friendlier hints forconnection/OOM cases.
log_and_http_error(exc, status_code, public_message, *, event, log)— logsthe full exception server-side (
exc_info = True) and returns anHTTPExceptionwhosedetailis onlypublic_message.routes/inference.py,routes/models.py,routes/export.py,routes/training.py,routes/datasets.py,routes/chat_history.py,routes/providers.py,routes/mcp_servers.py,routes/settings.py, androutes/data_recipe/{jobs,seed,validate,mcp}.py.[99]", "Model not found"), the existing
_friendly_errorSSE paths, andupstream-service response-body passthrough (llama-server / OpenAI), which is the
upstream's own truncated message, not Python internals.
routes/models.pybrowse/read errors that echoed absolute server paths are nowredacted (basename).
Harden sandbox file serving (py/path-injection)
serve_sandbox_filealready didos.path.basename+ realpath containment +extension allowlist. Added a strict filename allowlist
(
^[A-Za-z0-9._-]{1,255}$) before the path is built, as defense-in-depth and togive the analyzer a clear sanitizer.
Verification
python -m compileall -q -j 0 studioandruff check studiopass.detail = ... str(e)/{e}/{exc}of a caught Python exception (only the kept upstream-body passthrough andserver-side
logger.error(..., exc_info = True)calls remain).test_training_worker_flash_attntests that fail identically onmainin thisenvironment (unrelated; they pass in CI).
stack-trace-exposure alerts should clear.
No behavior change beyond error-message text; HTTP status codes are preserved.