Skip to content

fix(reports): catch JSONDecodeError in report extra validation (dashboard position_json/json_metadata) - #44204

Merged
eschutho merged 1 commit into
masterfrom
fix-unguarded-json-loads-report-base
Sep 14, 2026
Merged

eschutho merged 1 commit into
masterfrom
fix-unguarded-json-loads-report-base

Conversation

@eschutho

Copy link
Copy Markdown
Member

SUMMARY

BaseReportScheduleCommand._validate_report_extra and _validate_native_filters
(in superset/commands/report/base.py) call json.loads on a dashboard's
position_json and json_metadata without guarding against malformed JSON.

Both methods are reached from CreateReportScheduleCommand.validate() and
UpdateReportScheduleCommand.validate(), invoked from POST /api/v1/report/
and PUT /api/v1/report/{id}. When the referenced dashboard (via
extra.dashboard) has a position_json or json_metadata that is not valid
JSON, json.loads raises simplejson.JSONDecodeError. The report API's
except clauses only catch ReportScheduleNotFoundError,
ReportScheduleInvalidError, ReportScheduleCreateFailedError,
ReportScheduleForbiddenError/ReportScheduleUpdateFailedError and
marshmallow's ValidationError — JSONDecodeError is none of those, so it
escapes as a raw, opaque HTTP 500 instead of a clean validation error.

Dashboards should not normally reach this state given write-time validation,
but legacy/imported dashboards predating stricter validation can (see issue/PR
history around #43574 / #43575).

PROBLEM

Two unguarded json.loads sites:

  • _validate_report_extra: position_data = json.loads(dashboard.position_json or "{}")
  • _validate_native_filters: json_metadata = json.loads(dashboard.json_metadata or "{}")

The same method already demonstrates the correct pattern for the anchor
field (try/except json.JSONDecodeError), so this fix simply mirrors it.

FIX

Wrap both json.loads calls in try/except json.JSONDecodeError and append a
marshmallow ValidationError to the exceptions list (surfaced as a
ReportScheduleInvalidError → 422) instead of letting the raw exception
propagate:

  • position_json: append ValidationError("extra.dashboard.position_json is not valid JSON", "extra") and return early (mirroring the existing
    not isinstance(dashboard_state, dict) early-return branch, since
    position_data is required by everything below).
  • json_metadata: append ValidationError("extra.nativeFilters could not be validated: dashboard metadata is not valid JSON", "extra") and break out
    of the native-filter loop (since valid_filter_ids can no longer be
    computed).

This touches two sites in the same file for the identical bug class, mirroring
how #42401 covered four sites in one file.

This is part of the same recurring raw-exception-leak cleanup pipeline as
#42366 and #42401 (raw system/library exception escaping instead of a proper
Superset/marshmallow validation error).

TESTING INSTRUCTIONS

Added two regression tests in
tests/unit_tests/commands/report/create_test.py
(test_validate_report_extra_malformed_position_json,
test_validate_report_extra_malformed_json_metadata), following the existing
house style in that file. Each drives validation with a dashboard whose
position_json / json_metadata is non-JSON and asserts a ValidationError
(field extra) is collected rather than a raw JSONDecodeError escaping.

Verified fail-before / pass-after: on pre-fix code both tests fail with an
escaping simplejson.errors.JSONDecodeError; after the fix both pass. Full
tests/unit_tests/commands/report/ suite (381 tests) passes. ruff check,
ruff format --check, and mypy are green on the changed files.

pytest tests/unit_tests/commands/report/create_test.py -k malformed

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

…oard position_json/json_metadata)

BaseReportScheduleCommand._validate_report_extra and _validate_native_filters
call json.loads on a dashboard's position_json and json_metadata without
guarding against malformed JSON. A dashboard in a legacy/imported state whose
position_json or json_metadata is not valid JSON, referenced via extra.dashboard
when creating or updating a report/alert schedule, causes a raw JSONDecodeError
to escape as an opaque 500 (the report API only catches ReportScheduleNotFound/
Invalid/CreateFailed and marshmallow ValidationError).

Wrap both json.loads sites in try/except json.JSONDecodeError and append a
marshmallow ValidationError to the exceptions list, mirroring the existing
guarded 'anchor' sibling in the same method. Same bug class as PR #42366 and
#42401.
@bito-code-review

bito-code-review Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #488f2d

Actionable Suggestions - 0
Review Details
  • Files reviewed - 2 · Commit Range: 9968556..9968556
    • superset/commands/report/base.py
    • tests/unit_tests/commands/report/create_test.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo


position_data = json.loads(dashboard.position_json or "{}")
try:
position_data = json.loads(dashboard.position_json or "{}")

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.

Suggestion: Valid JSON such as [] or null is not rejected here, so the later position_data.keys() call raises AttributeError and still produces an HTTP 500. [type error]

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/commands/report/base.py
**Line:** 204:204
**Comment:**
	*Type Error: Valid JSON such as `[]` or `null` is not rejected here, so the later `position_data.keys()` call raises `AttributeError` and still produces an HTTP 500.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

if valid_filter_ids is None:
json_metadata = json.loads(dashboard.json_metadata or "{}")
try:
json_metadata = json.loads(dashboard.json_metadata or "{}")

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.

Suggestion: Valid JSON such as [] or null is not rejected here, so json_metadata.get(...) raises AttributeError instead of returning a validation error. [type error]

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/commands/report/base.py
**Line:** 308:308
**Comment:**
	*Type Error: Valid JSON such as `[]` or `null` is not rejected here, so `json_metadata.get(...)` raises `AttributeError` instead of returning a validation error.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

@codecov

codecov Bot commented Sep 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.16%. Comparing base (16fc356) to head (9968556).

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #44204      +/-   ##
==========================================
- Coverage   80.16%   80.16%   -0.01%     
==========================================
  Files        2925     2925              
  Lines      172563   172571       +8     
  Branches    40058    40058              
==========================================
+ Hits       138339   138345       +6     
- Misses      31627    31629       +2     
  Partials     2597     2597              
Flag Coverage Δ
hive 37.33% <16.66%> (-0.01%) ⬇️
mysql 56.86% <50.00%> (-0.01%) ⬇️
postgres 56.89% <50.00%> (-0.01%) ⬇️
presto 39.22% <16.66%> (-0.01%) ⬇️
python 84.55% <100.00%> (-0.01%) ⬇️
sqlite 56.59% <50.00%> (-0.01%) ⬇️
unit 75.88% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@richardfogaca richardfogaca 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.

Richard's agent here: approving this one. The fix is correct, mirrors the existing anchor guard in the same method, and all checks are green on 9968556. One small suggestion and a couple of optional notes below, none of them blocking.

Small suggestion: could we also guard the shape, not just the syntax? position_json of "[]"/"null" or json_metadata of "[]" parses fine and then fails on .keys() / .get(...), so it still escapes as a 500 through the same paths. An isinstance(..., dict) check after each loads (the method already does this for dashboard_state) would close that. Happy to keep as-is if you'd rather scope this PR to decode errors only.

Totally optional: the two try/except blocks are near-identical, and a tiny _load_dashboard_json helper would dedupe them, house the shape check, and probably drop the two new # noqa: C901.

Nit: the first message says extra.dashboard.position_json, but position_json lives on the dashboard model rather than in the request's extra. The second message ("dashboard metadata is not valid JSON") reads more accurately. WDYT?

Approving as-is; the suggestions above are fine as a follow-up.

@eschutho
eschutho merged commit 4db78ba into master Sep 14, 2026
81 checks passed
@eschutho
eschutho deleted the fix-unguarded-json-loads-report-base branch September 14, 2026 22:03
villebro pushed a commit that referenced this pull request Sep 16, 2026
…oard position_json/json_metadata) (#44204)

(cherry picked from commit 4db78ba)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants