Skip to content

fix(web): keep exception messages out of API responses (py/stack-trace-exposure) - #778

Open
ChuckBuilds wants to merge 1 commit into
mainfrom
fix/stack-trace-exposure
Open

ChuckBuilds wants to merge 1 commit into
mainfrom
fix/stack-trace-exposure

Conversation

@ChuckBuilds

@ChuckBuilds ChuckBuilds commented Oct 5, 2026 •

Copy link
Copy Markdown
Owner

Closes the ~40 open CodeQL py/stack-trace-exposure alerts on main. I took the source → sink flows from the main CodeQL SARIF and fixed each source, not each sink.

Sources fixed

  • describe_exception() (src/web_interface/error_handler.py): this fed nearly every alert, in starlark, misc, plugins, plugin_calendar, the system catch-all, wifi, and create_error_response via config.py. It now returns a reason code: the exception type plus the errno symbol for an OSError (OSError:EIO, PermissionError:EACCES, RuntimeError). The redacted message is logged instead. A failing disk still says EIO in the response, which is the reason feat(starlark,on-demand): the third-party fixes worth taking, plus a Home Assistant MQTT bridge #538 added the helper. Every call site is fixed at once, and test_no_api_v3_handler_discards_its_exception still holds.
  • Display service status / systemctl (api_v3/__init__.py):
    • _get_display_service_status now returns active/returncode only.
    • _ensure_display_service_running and _stop_display_service keep returncode/active/started/status but drop stdout/stderr. They log stderr on failure.
    • _run_systemctl_command no longer puts str(err) in stderr.
    • I grepped web_interface/static, the templates and the MQTT bridge. None of them read stdout/stderr. The bridge reads service.active and message.
  • WiFiManager: 9 return False, str(e) became e.g. "Could not enable AP mode (OSError); see logs for details".
  • unit_refresh: the two {e} interpolations are gone. Same change for _save_config's str(e) and the plugin-removal {remove_err} in api_v3/__init__.py.
  • system.py: install_base_requirements output uses the reason code. The sudo hint is still matched against str(e) but returns only its fixed text.
  • starlark.py: the SIGKILL-restart error no longer returns systemctl stderr as details.

display.py is untouched, because draft #773 edits it. Its alerts close through the source fixes in __init__.py.

Tests

  • New test/test_api_v3_no_exception_text.py: one route per affected file (display, wifi + WiFiManager, system ×2, plugin_calendar, misc, config → error_handler, plugins, starlark, unit_refresh). Each puts a marker in the exception message and asserts it never reaches the body.
    • All 13 tests fail on origin/main.
    • Targeted mutations on this branch each fail at least one test: drop the service filter, put stderr back in status, str(e) back in WiFiManager, {e} in unit_refresh, {install_err} in system.py, message back in describe_exception.
  • Tests that asserted the old message-in-details contract now assert the reason code. The redaction and bounds suites now test redact_text, which still carries subprocess output.
  • Full suite on Windows, this branch vs an origin/main baseline worktree: the same 68 FAILED/ERROR ids on both, none new and none fixed. They are pre-existing Windows failures.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Security & Privacy
    • Error responses now show exception types—and applicable system error codes—instead of exception messages. Sensitive details remain in logs.
    • Service status and action results no longer include system command output.
  • Error Handling
    • Wi-Fi, configuration, and unit-refresh failures identify the issue and direct you to the logs for details.
    • Service status results retain their status fields when command output is omitted.

…e-exposure)

CodeQL had ~40 open py/stack-trace-exposure alerts on main. Almost all
flowed through describe_exception(), which returned "TypeName: message"
(redacted, capped); the rest through _run_systemctl_command's str(err),
WiFiManager's `return False, str(e)`, unit_refresh's f-strings and two
str(e)/f"{err}" messages in api_v3/__init__.py.

describe_exception() now returns a reason code -- the type, plus the
errno symbol for an OSError ("OSError:EIO", "PermissionError:EACCES") --
and logs the redacted message itself. That keeps what #538 wanted (a
failing disk still says EIO in the response) without quoting paths,
URLs or library internals, and fixes every call site at once; the
test_no_api_v3_handler_discards_its_exception policy still holds.

Service results: _get_display_service_status returns active/returncode
only, and the on-demand start/stop `service` result keeps
returncode/active/started/status but drops systemctl stdout/stderr
(logged on failure). Nothing in web_interface/static, the templates or
the MQTT bridge reads those fields. The Starlark SIGKILL-restart error
no longer returns systemctl stderr as `details`.

WiFi, unit-refresh, config-save and plugin-removal failures now say
what failed with the reason code and point at the log. display.py is
untouched (draft #773 edits it).

Tests: test_api_v3_no_exception_text.py drives one route per affected
file with a marker in the exception message and asserts it never
reaches the body; all 13 fail on origin/main, and targeted mutations
(drop the service filter, put stderr back, str(e) in WiFiManager,
{e} in unit_refresh, {install_err} in system.py, message back in
describe_exception) each fail at least one. Tests that asserted the old
message-in-details contract now assert the reason code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 05f7bee5-3ce3-4f86-acec-82d5b6451733
📥 Commits

Reviewing files that changed from the base of the PR and between e40bc47 and 8879886.

📒 Files selected for processing (14)
  • CHANGELOG.md
  • src/web_interface/error_handler.py
  • src/wifi_manager.py
  • test/test_api_v3_display_modes.py
  • test/test_api_v3_no_exception_text.py
  • test/test_api_v3_registry_endpoints.py
  • test/test_web_error_detail.py
  • test/web_interface/test_api_v3_unhandled_errors.py
  • test/web_interface/test_starlark_pixlet_routes.py
  • web_interface/blueprints/api_v3/__init__.py
  • web_interface/blueprints/api_v3/starlark.py
  • web_interface/blueprints/api_v3/system.py
  • web_interface/blueprints/api_v3/wifi.py
  • web_interface/unit_refresh.py
💤 Files with no reviewable changes (1)
  • web_interface/blueprints/api_v3/starlark.py

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The change removes exception messages and systemctl output from selected Web API responses and failure messages. Exception details now use the exception type and, for valid OSError errno values, the standard errno name. The change also updates tests and the Unreleased changelog.

Changes

API Error Reporting

Layer / File(s) Summary
Exception reason codes and API errors
src/web_interface/error_handler.py, web_interface/blueprints/api_v3/*.py, test/test_web_error_detail.py, test/test_api_v3_no_exception_text.py, test/test_api_v3_registry_endpoints.py, test/web_interface/test_api_v3_unhandled_errors.py, test/web_interface/test_starlark_pixlet_routes.py, CHANGELOG.md
describe_exception returns the exception type and adds a standard errno name for valid OSError errno values. API error paths use this detail, while sanitized exception messages are logged. Tests assert that responses omit exception messages.
Systemd result filtering
web_interface/blueprints/api_v3/__init__.py, web_interface/blueprints/api_v3/starlark.py, test/test_api_v3_display_modes.py, test/test_api_v3_no_exception_text.py
Display-service results omit stdout and stderr while retaining status fields. The force-stop restart-failure response omits systemctl stderr. Tests check the filtered results and response bodies.
Wi-Fi and unit-refresh failures
src/wifi_manager.py, web_interface/blueprints/api_v3/wifi.py, web_interface/unit_refresh.py, test/test_api_v3_no_exception_text.py
Wi-Fi failure messages report the exception type instead of its message. Unit-refresh failures direct users to logs. Tests check that these results omit injected exception text.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 88798

The configuration-save failure retains a diagnostic log, and no unresolved issue identified here prevents merging after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 88798

The inspected changes reduce diagnostic information in ordinary API responses without changing command privileges or state-transition controls. Detailed logs remain accessible through existing log views, and coverage of all error paths is incomplete. No material security regression was established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated exposure scope is the device's Web API and its display/web-service diagnostics. The inspected changes alter returned and logged data, not command targets, sudo authority or tenant isolation. Deployment-wide network reachability was not established.

Security Findings and Attack Paths

  • inferred — New formatter warnings can flow into journal-backed HTTP log responses where journal access is available. This is a remaining diagnostic export path, not an established new vulnerability: broad traceback logging and log export predate the PR, and the former formatter already returned message text directly.

Trust Boundaries and Controls

  • observed — The unchanged optional-login gate covers both log endpoints: they are not health, static or AP-setup exemptions. With login enabled, remote readers need a valid session or bearer token; direct local requests are exempt. Without a configured password, the gate permits requests. The new formatter warning uses credential-pattern redaction and a single-line length cap.

Hardening Proposals

  • proposed — If the intended guarantee is to suppress sensitive diagnostics across all HTTP surfaces, define an explicit confidentiality policy for journal export, including access requirements and output filtering. Moving text from an error response into logs does not by itself provide that broader guarantee.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.54% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 65 functions across 12 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: preventing exception messages from appearing in API responses. The technical suffix does not obscure the purpose.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 61.54% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 65 functions across 12 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 7 complexity

Metric Results
Complexity 7

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

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.

1 participant