Skip to content

Studio: stop leaking internal exceptions to API clients; harden sandbox path - #6072

Merged
danielhanchen merged 13 commits into
mainfrom
studio-error-hardening
Jun 8, 2026
Merged

danielhanchen merged 13 commits into
mainfrom
studio-error-hardening

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What

Security hardening for the Studio FastAPI backend, fixing the pre-existing CodeQL
alerts (2 high py/path-injection, 7 medium py/stack-trace-exposure) and
extending the error fix repo-wide across the route layer.

Why

CodeQL flagged studio/backend/routes/inference.py for returning raw exception
text 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: raw
caught-exception text reaching clients can leak internal filesystem paths and
stack detail.

Changes

Stop leaking internal exceptions (py/stack-trace-exposure)

  • Add two shared helpers in studio/backend/utils/utils.py:
    • safe_error_detail(exc, fallback = "An internal error occurred") — returns a
      generic, client-safe message (never raw str(exc)), with friendlier hints for
      connection/OOM cases.
    • log_and_http_error(exc, status_code, public_message, *, event, log) — logs
      the full exception server-side (exc_info = True) and returns an
      HTTPException whose detail is only public_message.
  • Sweep the route layer to use them: 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, and routes/data_recipe/{jobs,seed,validate,mcp}.py.
  • Kept intentionally: user-facing validation messages (e.g. "Invalid gpu_ids
    [99]", "Model not found"), the existing _friendly_error SSE paths, and
    upstream-service response-body passthrough (llama-server / OpenAI), which is the
    upstream's own truncated message, not Python internals.
  • routes/models.py browse/read errors that echoed absolute server paths are now
    redacted (basename).

Harden sandbox file serving (py/path-injection)

serve_sandbox_file already did os.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 to
give the analyzer a clear sanitizer.

Verification

  • python -m compileall -q -j 0 studio and ruff check studio pass.
  • Grep self-check: no remaining client-facing detail = ... str(e) / {e} /
    {exc} of a caught Python exception (only the kept upstream-body passthrough and
    server-side logger.error(..., exc_info = True) calls remain).
  • Backend test suite: 2418 passed; the only failures are 14 pre-existing
    test_training_worker_flash_attn tests that fail identically on main in this
    environment (unrelated; they pass in CI).
  • The definitive CodeQL check is this PR's CI run; the path-injection and
    stack-trace-exposure alerts should clear.

No behavior change beyond error-message text; HTTP status codes are preserved.

danielhanchen and others added 2 commits June 7, 2026 07:32
…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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread studio/backend/routes/datasets.py Outdated
Comment on lines +74 to +75
# Client-safe error helpers
from utils.utils import safe_error_detail, log_and_http_error

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Both safe_error_detail and log_and_http_error are imported but never used in this file. Removing unused imports keeps the codebase clean and maintainable.

Comment thread studio/backend/routes/export.py Outdated
Comment on lines +29 to +30
# Client-safe error helpers
from utils.utils import safe_error_detail, log_and_http_error

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The helper log_and_http_error is imported but never used in this file. Removing unused imports keeps the codebase clean and maintainable.

Suggested change
# 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The helper log_and_http_error is imported but never used in this file. Removing unused imports keeps the codebase clean and maintainable.

Suggested change
from utils.utils import safe_error_detail, log_and_http_error
from utils.utils import safe_error_detail

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The helper safe_error_detail is imported but never used in this file. Removing unused imports keeps the codebase clean and maintainable.

Suggested change
from utils.utils import safe_error_detail, log_and_http_error
from utils.utils import log_and_http_error

Comment thread studio/backend/routes/models.py Outdated
from typing import List, Optional
import structlog
from loggers import get_logger
from utils.utils import safe_error_detail, log_and_http_error

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The helper safe_error_detail is imported but never used in this file. Removing unused imports keeps the codebase clean and maintainable.

Suggested change
from utils.utils import safe_error_detail, log_and_http_error
from utils.utils import log_and_http_error

Comment thread studio/backend/routes/training.py Outdated
Comment on lines +54 to +55
# Client-safe error helpers
from utils.utils import safe_error_detail, log_and_http_error

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The helper safe_error_detail is imported but never used in this file. Removing unused imports keeps the codebase clean and maintainable.

Suggested change
# 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

Comment thread studio/backend/routes/models.py Outdated
raise HTTPException(
status_code = 403,
detail = f"Permission denied reading {current}",
detail = f"Permission denied reading {os.path.basename(str(current))}",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since current is a pathlib.Path object, you can use its .name property directly instead of converting it to a string and calling os.path.basename. This is more idiomatic and readable.

Suggested change
detail = f"Permission denied reading {os.path.basename(str(current))}",
detail = f

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +3857 to +3858
if not _re.fullmatch(r"[A-Za-z0-9._-]{1,255}", safe_filename):
raise HTTPException(status_code = 404, detail = "Not found")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

danielhanchen and others added 6 commits June 7, 2026 10:20
- 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread studio/backend/routes/inference.py Outdated
raise log_and_http_error(
exc,
400,
safe_error_detail(exc),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread studio/backend/utils/utils.py Outdated
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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."),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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}.",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@danielhanchen
danielhanchen merged commit 8ccdf59 into main Jun 8, 2026
33 checks passed
@danielhanchen
danielhanchen deleted the studio-error-hardening branch June 8, 2026 10:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants