Repository navigation
fix(mcp): check chart access before adding dashboard charts - #45535
Conversation
Check chart visibility before linking selected charts, while retaining datasource validation. Pin viewer restrictions and readable table/semantic-view cases, and clarify permission refusal guidance.
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #45535 +/- ##
==========================================
+ Coverage 84.10% 84.15% +0.04%
==========================================
Files 3056 3056
Lines 201254 201747 +493
Branches 47061 47174 +113
==========================================
+ Hits 169265 169776 +511
+ Misses 28746 28728 -18
Partials 3243 3243
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:
|
| from superset.mcp_service.auth import check_chart_data_access | ||
|
|
||
| for chart in chart_objects: | ||
| if not security_manager.can_access_chart(chart): |
There was a problem hiding this comment.
Suggestion: For non-admin users, can_access_chart lazily loads each chart’s editors and viewers, adding up to two database queries per chart when generating a dashboard.
Assessment: 🟠 Major · 🔁 Occurrence: Often · 🏷️ Performance
Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** superset/mcp_service/dashboard/tool/generate_dashboard.py
**Line:** 272:272
**Comment:**
*Performance: For non-admin users, `can_access_chart` lazily loads each chart’s editors and viewers, adding up to two database queries per chart when generating a dashboard.
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 fixThere was a problem hiding this comment.
Fixed in ba71a24. generate_dashboard now loads each chart's editors and viewers in the same bounded query that fetches the charts (selectinload), so the per-chart access check no longer issues lazy relationship queries.
A new test counts the relationship SELECTs using real mapped tables: with 5 charts, an editor went from 5 to at most 2, and an explicit viewer, or a user denied only on the last chart, went from 10 to at most 2. The access decisions themselves are unchanged.
add_chart_to_existing_dashboard checks a single chart once, so eager loading wouldn't reduce queries there; it's left as is.
There was a problem hiding this comment.
✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of ba71a24.
The chart query now uses selectinload for Slice.editors and Slice.viewers, avoiding per-chart lazy-loading queries during access checks.
If that's not right, unresolve this thread and CodeAnt will leave it open.
CodeAnt PR Risk: Medium Risk
Assessed commit: |
fitzee
left a comment
There was a problem hiding this comment.
One gap worth closing; nothing else blocking.
The new checks are correct and run before any write in both tools. generate_dashboard still persists chart IDs from a caller-supplied position_json without checking them, and the new permission_denied description contradicts the existing dashboard-edit denial message.
What I verified
can_access_chart→raise_for_access(chart=...)passes for admins and chart editors. For a viewer-restricted chart it requiresis_viewer, and a datasource grant doesn't count. Otherwise it requires access to the chart's datasource (resolved_datasource, so it works for semantic views). Both tools still runcheck_chart_data_accessafterwards. So a chart editor without datasource access is still refused, and a datasource-only reader can't link a viewer-restricted chart. That's the intended "both kinds of access".add_chart_to_existing_dashboard: order is dashboard lookup →raise_for_editorship→ managed refusal → chart lookup →can_access_chart→ data check →UpdateDashboardCommand. Nothing is written on any refusal path.generate_dashboard: every chart inchart_idsis checked before the layout or theDashboard()is built. A denial returns early, so a mixed allowed/denied list writes nothing.chart_idsisList[int], so pydantic coerces string IDs, and duplicates go throughIN (...), so neither can skip a check. The re-query atfresh_chartsuses the same IDs, so there's no meaningful TOCTOU.- Other MCP paths that touch dashboard charts:
update_dashboardrequires the reachable charts in the replacement layout to equaldashboard.slices(validate_dashboard_layout), so it can't add charts.manage_dashboard_markdownonly edits MARKDOWN/HEADER nodes.duplicate_dashboardcopies the charts of a dashboard the caller can already read, the same as REST copy. - Mutation tests: disabling the guard in
add_chart_to_existing_dashboardmakes 4 tests fail. Disabling it ingenerate_dashboardmakes 6 fail. Checking only the first chart ingenerate_dashboardmakes 1 fail (the last-chart-denied case). The 116 tests in the four touched files pass at the PR head.
Findings
-
superset/mcp_service/dashboard/tool/generate_dashboard.py:295-301: chart IDs inposition_jsonaren't checked (non-blocking, but it leaves a gap in the guarantee this PR is adding). Whenposition_jsonis supplied, it's stored afterrepair_position/rebuild_parent_chains, with no check that itsCHARTnodes matchrequest.chart_ids. Example: a caller sendschart_ids=[A](accessible) and aposition_jsonwith aCHARTnode{"chartId": X}, where X is viewer-restricted. All checks pass,dashboard.slices = [A], and X is persisted in the layout. I confirmed this with a local probe:can_access_chartwas called only for chart 1, and the stored layout contained chart IDs[1, 999]. The next normal save from the dashboard UI sendsjson_metadata.positions, andDashboardDAO.set_dash_metadatarebuildsdashboard.slicesfrom those positions with no per-chart check. X then becomes a member chart. RESTPUTalready lets a dashboard editor do this directly, so this isn't a new escalation. But the MCP refusal can be routed around with the same tool. Fix: reuse whatupdate_dashboarddoes, i.e.validate_dashboard_layout(request.position_json, request.chart_ids), or at least rejectCHARTnodes whosechartIdisn't inchart_ids. Add a test for it. -
superset/mcp_service/dashboard/schemas.py:712-719contradictsadd_chart_to_existing_dashboard.py:201-206. The newpermission_denieddescription says "Ask the user to grant access; do not retry or create another dashboard to bypass the denial." The same flag is also set when the caller can't edit the target dashboard, and that error message still says "Ask the user if they would like a new dashboard created with this chart instead". For a dashboard-edit denial, offering a new dashboard is legitimate (the chart is readable). For a chart denial it isn't. The model now gets opposite instructions under one flag. Either word the description for both cases, e.g. "if the chart is inaccessible, do not create another dashboard to work around it", or add a separate flag/reason for chart denial. -
Nit,
add_chart_to_existing_dashboard.py:264andgenerate_dashboard.py:274: for a non-admin, non-editor caller, a chart whose dataset or semantic view was deleted (resolved_datasource is None, no viewers) now failscan_access_chartfirst. It's reported as "You don't have permission to access chart N" withpermission_denied=True, instead of the earlier "Dataset (ID: …) has been deleted" fromcheck_chart_data_access, and the agent is told to ask for access that can't be granted. Runningcheck_chart_data_accessfirst andcan_access_chartsecond keeps the informative message and gives the same authorization result. -
Nit,
generate_dashboard.py:274-279: a chart denial here has no structured signal (GenerateDashboardResponsehas nopermission_denied).add_chart_to_existing_dashboardhas one. That's fine to leave out of scope; just noting the inconsistency. -
Not an issue: "not found" and "forbidden" are now separate messages, so callers can learn whether a chart ID exists. That distinction already existed (
check_chart_data_accessreturned "is not accessible"). Only the ID is echoed, never the chart name, which is acceptable.
Tests
The parametrized tests run the real SupersetSecurityManager.can_access_chart against mocked is_viewer/can_access_datasource. They cover restricted-without-grant, restricted-with-datasource-grant and unrestricted, for table and semantic-view charts. They assert UpdateDashboardCommand is not called (add) or the response is an error (generate). The SQL-count test uses real mapped tables and covers denial on the last of 5 charts, which shows the loop checks every chart, not just the first. Missing: a test for the position_json gap in finding 1.
gabotorresruiz
left a comment
There was a problem hiding this comment.
Thanks @mikebridge, the access check itself holds up. I exercised both tools against a real metadata DB as Admin, Alpha, Gamma, a Gamma listed in a chart's viewers, and a chart editor with no viewers entry: the only decisions that flip against master are the ones that should, and nothing legitimate got newly refused. Embedded guests cannot reach either tool at all (MCP_GUEST_ALLOWED_TOOLS), so there is no guest shape in play here.
Commenting rather than approving for one reason: the perf(mcp) commit comes out as a net regression when I measure it, notes on the line. I also reproduced @fitzee's position_json point independently and agree with it. CI is green on ba71a24, with unit, postgres, mysql, sqlite and playwright all run on this head.
| with event_logger.log_context(action="mcp.generate_dashboard.chart_validation"): | ||
| chart_objects = ( | ||
| db.session.query(Slice) | ||
| .options(selectinload(Slice.editors), selectinload(Slice.viewers)) |
There was a problem hiding this comment.
This block worries me a bit: measured, the selectinload is a net regression rather than a saving. The log_context wrapping this query commits on exit (DBEventLogger is the default EVENT_LOGGER), which expires every chart, and SQLAlchemy re-applies the saved loader options when _create_dashboard_layout reads chart.slice_name, so chart_editors and chart_viewers end up selected per chart anyway.
One generate_dashboard call with 20 charts on this branch: 392 statements as an Admin and 680 as an explicit chart viewer, versus 350 and 679 with just this line removed (master is 350 and 599). Would you consider dropping it, or moving the chart query and the access loop out of the committing log_context so the batched load actually survives?
There was a problem hiding this comment.
Thanks for measuring this; I reproduced it. The log context commits on exit and the expired charts re-apply the loader options on refresh, so the eager load cost more than it saved on every successful path. I removed it in 0b5342b and left the access check as it was. The permission relationships now load lazily: none for admins, one read per chart for editors, and two for viewers. Moving the chart query and the access loop out of the committing context, as you suggest, should let a batched load survive. I'd rather do that as a separate follow-up than restructure the tool in an access-check PR, if that works for you.
There was a problem hiding this comment.
Thanks for turning this around so fast. Confirmed on 2f93648c with the same harness: a 20 chart generate_dashboard is 300 statements as an Admin, which is exactly what master costs at this merge base, and the explicit chart viewer path now pays 2 relationship reads per chart instead of those plus a refresh each. Both columns moved down from the 350 and 599 I quoted, because of the tag work that came in with the master merge rather than anything here. Doing the batched load as a separate follow-up is fine by me, and the number to beat there is those 40 reads for 20 charts.
| ) | ||
| layout: MagicMock = mocker.patch( | ||
| "superset.mcp_service.dashboard.tool.generate_dashboard._create_dashboard_layout", | ||
| side_effect=RuntimeError("access checks completed"), |
There was a problem hiding this comment.
Not a blocker, but this stub raises before anything reads a column off the charts, and that read is what triggers the refresh. If I make the stub do what the real builder does, read slice_name and uuid per chart and then raise, this same test reports 12 relationship SELECTs for 5 charts instead of <= 2. Letting the tool run through the real layout step would make the bound mean what it says.
There was a problem hiding this comment.
Good catch. The stub now calls the real layout builder after the validation context has committed, then stops, so the column reads and the refresh are counted. It also covers an admin path and 20 charts. The bound is per path: none for admins, one relationship read per chart for editors, and two for viewers or a denied caller. With the eager load put back, 9 of the 12 cases fail.
There was a problem hiding this comment.
This went further than I asked for, thanks. I put the selectinload back on top of this head and 9 of the 12 cases fail; with it off, the actual counts land exactly on the bound in every case (0 for admins, 1 per chart for editors, 2 per chart for viewers and for the denied caller), so the <= has no slack left in it.
| # --------------------------------------------------------------------------- | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("datasource_type", ["table", "semantic_view"]) |
There was a problem hiding this comment.
Just a small NIT: I think the semantic_view half of this parametrization is inert. resolved_datasource is set to a Mock() on line 171 and can_access_datasource is patched, so Slice.resolved_datasource, the only place datasource_type is read, never runs. I swapped both values for nonsense strings and all 87 tests across this file and test_dashboard_generation.py still passed. Real semantic-view coverage needs a chart whose resolved_datasource actually resolves, which test_chart_access_query_count.py is already wired for. Same shape at test_dashboard_generation.py:210.
There was a problem hiding this comment.
Agreed, it never reached resolved_datasource. I dropped the parametrization from both tests rather than keep a case that couldn't fail.
There was a problem hiding this comment.
Dropping it from both files rather than keeping a case that could not fail is the right call, thanks.
The chart validation log context commits on exit, which expires the charts, and the layout step's column reads re-apply the saved loader options, re-selecting editors and viewers per chart. The eager load therefore cost more than it saved on every successful path. Keep the access check and let the relationships load lazily. Make the query-count test run the real layout step after the commit so it counts those reloads, cover the admin path, and drop the inert datasource_type parametrization from the mocked access tests. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
fitzee
left a comment
There was a problem hiding this comment.
Re-reviewed at 2f93648c: the position_json gap is still open, and nothing else in the PR blocks merge.
The PR's own changes since ba71a24d are three commits: 0b5342b8 removes the selectinload, df96fcd9 adds type annotations to a test, and 2f93648c is an empty CI retrigger. They respond to @gabotorresruiz's measurement and test notes, and they are correct. The access logic is the same as before.
Prior items
-
position_jsonchart IDs are not checked: still open.generate_dashboard.py:293-301is unchanged. I re-ran the probe withchart_ids=[1]and a layout that also contains chart 999, which the caller cannot read.can_access_chartwas called only for chart 1, the call succeeded, and chart 999 was stored in every variant I tried:chartId: 999"999"(string)999.0(float)- inside
TABS > TAB > ROW - a detached
CHARTnode that nochildrenlist points to
All of these matter.
DashboardDAO.set_dash_metadataturns digit strings and integral floats into ints (_layout_chart_id,daos/dashboard.py:101). It also scans every node inpositions.values(), reachable or not. So the next UI save adds 999 todashboard.slices.A node with only
meta.uuidis not a real path: it has nochartId, soset_dash_metadatatreats it as an empty slot and never links a chart.Correction to our earlier fix suggestion: calling
validate_dashboard_layout(request.position_json, request.chart_ids)as-is breaks 3 existing tests (test_generate_dashboard_position_json_override,..._repairs_truncated_tabs,..._root_children_not_a_list). Its structural checks are stricter than whatgenerate_dashboardaccepts today; for example, it requiresDASHBOARD_VERSION_KEY.A narrower check works. After
rebuild_parent_chains(repair_position(...)), collect_layout_chart_id(node)for every node and refuse if any ID is not inchart_ids. With that check, all 5 probe variants are refused and nothing is persisted, and all 70 tests intest_dashboard_generation.pystill pass. Reusing_layout_chart_idkeeps the coercion identical to whatset_dash_metadatawill link later. @gabotorresruiz reproduced this gap independently, and no one has replied to it on the PR yet. -
Conflicting
permission_deniedguidance: still open.schemas.py:732-738tells the agent "do not … create another dashboard".add_chart_to_existing_dashboard.py:201-206sets the same flag for a dashboard-edit denial, where the error message suggests creating a new dashboard. -
Nit: a deleted dataset is reported as a permission denial. Still open.
can_access_chartstill runs beforecheck_chart_data_access, atadd_chart_to_existing_dashboard.py:264andgenerate_dashboard.py:272. -
Nit:
GenerateDashboardResponsehas nopermission_deniedfield. Unchanged, and fine to leave out of scope. -
Not found vs. forbidden: this already happened before the PR, and the PR doesn't change it. Nothing to do.
New findings
None that block merge. Removing the eager load is correct for the reason the author gives: the log_context commit expires the charts, and the loader options run again on refresh.
The query-count test is more honest now. It runs the real layout builder after the commit, and its bound changed from "≤ 2 total" to a per-chart bound: 0 queries for admin, 1 for an editor, 2 for a viewer or a denied caller. That bound is per chart, so it accepts the N+1 rather than preventing it. The fix the reviewer suggested, moving the query and the access loop out of the committing context so a batched load survives, is deferred to a follow-up. That's reasonable for this PR.
Tests / CI
- 1218 tests pass under
tests/unit_tests/mcp_service/dashboard/, plus my probe file. - There is still no test with a
position_jsonthat names a chart outsidechart_ids. Prior-item 1 needs one. - CI on
2f93648c: 57 checks pass and 15 are skipped. Nothing failing or pending.
Address Matt's position_json review: match DAO chart ID coercion across every repaired node before persisting a dashboard. Pin integer, string, float, nested and detached cases. Clarify that dashboard-edit denial may offer a user-confirmed alternative without bypassing chart access.
gabotorresruiz
left a comment
There was a problem hiding this comment.
Thanks @mikebridge, and thanks for turning the measurement around within a few hours.
Approving. The eager load is gone and the Admin path is back to parity with master, and the access decisions at this head are identical to ba71a24 across Admin, Alpha, Gamma, a Gamma listed in a chart's viewers, and a chart editor with no viewers entry, for both tools, with nothing legitimate newly refused. MCP_GUEST_ALLOWED_TOOLS is untouched by the master merge, so embedded guests still cannot reach either tool. I also ran the full tests/unit_tests/mcp_service suite on this head: 11,373 passed, 12 skipped, and the only failures were the three local-timezone ones that fail the same way on master without TZ=UTC.
CI is complete on 2f93648c: 23 workflow runs, all on the first attempt, 20 successful and 3 skipped, including unit, integration, Presto/Hive and E2E, so the retrigger did produce a full run.
The one thread I would still call open is @fitzee's position_json point, which he re-confirmed at this head and which I reproduce too. It is not a regression from this change, so I am not holding the PR on it, though I would rather see it closed here than after merge.
|
AI-assisted reply on Mike's behalf. @fitzee: fixed the layout gap in 468b094. After repair and parent rebuilding, generation checks every layout node with the DAO's chart-ID coercion, and refuses references outside the access-checked
@gabotorresruiz: thanks for reproducing it. The guard covers detached nodes and string or float IDs too. The eager-load removal and the existing query-count test are unchanged. |
…cess part of #45535) Reduced backport of #45535 for 7.0: generate_dashboard and add_chart_to_existing_dashboard refuse charts the caller can't access (security_manager.can_access_chart), with their tests. Left out because they depend on code that only exists on master: - the layout-chart check in generate_dashboard, which needs superset.daos.dashboard._layout_chart_id from #44028, and its test_generate_dashboard_refuses_unlisted_layout_chart test; - test_chart_access_query_count.py, which calls the tool through inspect.unwrap and needs master's FastMCP 4 tool wrapping (#45639); - the docs change (docs deploy from master). (cherry picked from commit eee2c16, reduced)
SUMMARY
Make the dashboard composition tools use the existing chart access check as
well as their datasource validation. Requests return a permission message before
changing the dashboard when a selected chart is unavailable to the caller.
The add-chart response description explains that both kinds of access are needed.
BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
Not applicable; MCP responses only.
TESTING INSTRUCTIONS
Run the MCP unit tests. The new parametrized tests exercise both dashboard
composition tools for table and semantic-view charts, checking permission
refusals and successful additions. They assert no dashboard mutation on refusal.
For manual verification, use a caller with dashboard write capability and
compare a readable chart with one whose viewers exclude that caller.
python -m pytest -q tests/unit_tests/mcp_service: 10,930 passed, 12 skipped.Changed-file pre-commit checks, including MyPy, Ruff and pylint, pass.
Removing the new guards produces 8 failing denial cases while 4 readable-chart
cases still pass; restoring the guards passes the focused checks.
ADDITIONAL INFORMATION