Repository navigation
fix(reports): catch JSONDecodeError in report extra validation (dashboard position_json/json_metadata) - #44204
Conversation
…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.
Code Review Agent Run #488f2dActionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
|
|
||
| position_data = json.loads(dashboard.position_json or "{}") | ||
| try: | ||
| position_data = json.loads(dashboard.position_json or "{}") |
There was a problem hiding this comment.
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
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 "{}") |
There was a problem hiding this comment.
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
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 Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
richardfogaca
left a comment
There was a problem hiding this comment.
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.
SUMMARY
BaseReportScheduleCommand._validate_report_extraand_validate_native_filters(in
superset/commands/report/base.py) calljson.loadson a dashboard'sposition_jsonandjson_metadatawithout guarding against malformed JSON.Both methods are reached from
CreateReportScheduleCommand.validate()andUpdateReportScheduleCommand.validate(), invoked fromPOST /api/v1/report/and
PUT /api/v1/report/{id}. When the referenced dashboard (viaextra.dashboard) has aposition_jsonorjson_metadatathat is not validJSON,
json.loadsraisessimplejson.JSONDecodeError. The report API'sexceptclauses only catchReportScheduleNotFoundError,ReportScheduleInvalidError,ReportScheduleCreateFailedError,ReportScheduleForbiddenError/ReportScheduleUpdateFailedErrorandmarshmallow's
ValidationError—JSONDecodeErroris none of those, so itescapes 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.loadssites:_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
anchorfield (
try/except json.JSONDecodeError), so this fix simply mirrors it.FIX
Wrap both
json.loadscalls intry/except json.JSONDecodeErrorand append amarshmallow
ValidationErrorto theexceptionslist (surfaced as aReportScheduleInvalidError→ 422) instead of letting the raw exceptionpropagate:
position_json: appendValidationError("extra.dashboard.position_json is not valid JSON", "extra")andreturnearly (mirroring the existingnot isinstance(dashboard_state, dict)early-return branch, sinceposition_datais required by everything below).json_metadata: appendValidationError("extra.nativeFilters could not be validated: dashboard metadata is not valid JSON", "extra")andbreakoutof the native-filter loop (since
valid_filter_idscan no longer becomputed).
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 existinghouse style in that file. Each drives validation with a dashboard whose
position_json/json_metadatais non-JSON and asserts aValidationError(field
extra) is collected rather than a rawJSONDecodeErrorescaping.Verified fail-before / pass-after: on pre-fix code both tests fail with an
escaping
simplejson.errors.JSONDecodeError; after the fix both pass. Fulltests/unit_tests/commands/report/suite (381 tests) passes.ruff check,ruff format --check, andmypyare green on the changed files.ADDITIONAL INFORMATION