Repository navigation
fix(charts): avoid loading semantic provider metadata before denying chart data access - #45060
Conversation
✅ 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 #45060 +/- ##
==========================================
+ Coverage 82.84% 82.86% +0.01%
==========================================
Files 3017 3017
Lines 192709 192936 +227
Branches 44914 44978 +64
==========================================
+ Hits 159642 159867 +225
+ Misses 30033 30029 -4
- Partials 3034 3040 +6
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:
|
Co-Authored-By: Claude Opus 5.5 <[email protected]>
CodeAnt PR Risk: Low Risk
Assessed commit: |
gabotorresruiz
left a comment
There was a problem hiding this comment.
Hi @mikebridge, thanks for this. The ordering is the right fix, and I confirmed the two denial tests genuinely fail on the parent commit at provider.get_dimensions.assert_not_called() rather than on import, so the regression test is real. Four notes inline; the test-file one is the only thing I would want changed before merge.
I ran the new file plus tests/integration_tests/charts and the security suites against both this head and its parent. CI is fully green.
| db.session.delete(layer) | ||
| db.session.commit() | ||
|
|
||
| def test_sql_dataset_chart_data_is_unchanged(self) -> None: |
There was a problem hiding this comment.
This one does not declare a birth-names fixture, so the command in the testing instructions, pytest tests/integration_tests/charts/semantic_metadata_authz_tests.py -q, fails for me at line 274 with assert None is not None. It passes in a full run only because an earlier test already loaded the data. With the fixture declared all 5 pass:
| def test_sql_dataset_chart_data_is_unchanged(self) -> None: | |
| @pytest.mark.usefixtures("load_birth_names_dashboard_with_slices") | |
| def test_sql_dataset_chart_data_is_unchanged(self) -> None: |
plus from tests.integration_tests.fixtures.birth_names_dashboard import load_birth_names_dashboard_with_slices, load_birth_names_data.
There was a problem hiding this comment.
Good catch, thanks. That test relied on another one having loaded birth names. It now declares load_birth_names_dashboard_with_slices, and passes when run alone. Addressed in 7c29cf978d.
| if not security_manager.is_guest_user(): | ||
| QueryContext( | ||
| datasource=datasource_model_instance, | ||
| queries=[], |
There was a problem hiding this comment.
This block worries me a bit. raise_for_access hands the whole context to the EXTRA_RAISE_FOR_ACCESS_BYPASS hook at superset/security/manager.py:4972, and that hook is operator code sitting outside the guest guard, so here it receives a context whose queries is empty. I tried it with a hook that grants based on query_context.queries: the identical request returns 200 on master and 403 on this branch, because the preflight raises before the hook ever sees the real payload. Nothing widens, but a caller that used to be allowed is now denied.
Are we sure no deployment reads queries in that hook? If not, skipping the preflight when it is configured is cheap insurance:
and not current_app.config.get("EXTRA_RAISE_FOR_ACCESS_BYPASS")Either way I would land your first follow-up here rather than after: inside Superset's own code the invariant does hold, but it holds because of exactly one is_guest_user() guard at superset/security/manager.py:5334, and a unit test asserting that raise_for_access never reads query_context.queries for a non-guest caller is what keeps it true.
There was a problem hiding this comment.
Agreed. I reproduced it with a hook that grants based on query_context.queries: 403 on this branch, 200 without the early check. The early check is now skipped whenever EXTRA_RAISE_FOR_ACCESS_BYPASS is configured, so the hook always sees the full request (test_payload_based_access_bypass_still_sees_queries). The config.py comment for the setting now says so.
I also landed the invariant test here rather than as a follow-up: for a non-guest caller, raise_for_access never reads query_context.queries. The 11 cases cover the direct path; the native-filter, chart, multi-layer, drill-to-detail and drill-by branches, each refused at its own last check; and successful drills through to the final dashboard check, both allowed and denied. Two changes make it fail: removing the is_guest_user() guard, or adding a queries read anywhere along those branches, including just before can_access_dashboard. Addressed in efe852c7c5, f018b74a9a, 70b56c94b7 and b5eeb463f1.
| _authorize_semantic_before_metadata: bool | ||
|
|
||
| def __init__(self) -> None: | ||
| def __init__(self, authorize_semantic_before_metadata: bool = False) -> None: |
There was a problem hiding this comment.
Not a blocker, and the UI does not use it, but POST /api/v1/query/ (superset/views/api.py:71) builds the context first and calls raise_for_access() after, so with the default False it still loads dimensions before the 403. I saw one get_dimensions() call there on this branch. Worth opting it in too, or deliberately out of scope?
There was a problem hiding this comment.
Opted it in. POST /api/v1/query/ now uses the same early check. A denied request on a semantic view returns 403 with no get_dimensions() call, where before there was one (test_denied_legacy_query_api_skips_provider_metadata). The remaining default-factory callers (MCP chart data and chart SQL, Slice.get_query_context, the native-filter cache task and Excel export) are listed as a follow-up in the description. Addressed in efe852c7c5.
| result_type=result_type, | ||
| result_format=result_format, | ||
| cache_values={}, | ||
| ).raise_for_access() |
There was a problem hiding this comment.
Small accuracy note for the description: a denied request can still load metadata. With ENABLE_VIEWERS and VIEWER_PROMISCUOUS_MODE on, has_drill_access reaches SemanticView.has_drill_by_columns, which calls implementation.get_dimensions() (superset/semantic_layers/models.py:767) inside this check. A denied drill-by measured one call here against two on the parent, so it improves but does not reach zero.
There was a problem hiding this comment.
You're right. In that mode the drill-by decision itself needs the view's dimension names (has_drill_by_columns), so a denied drill still makes one provider call, down from two. That call is part of the authorization decision, not metadata loaded ahead of it, so I've kept the code as is and corrected the description: denied requests skip provider metadata except where the access decision depends on it, i.e. viewer drill-by. Addressed in the PR description, updated with b5eeb463f1.
Running the file alone failed: the SQL dataset test relied on another test having loaded the birth-names data. Declare the fixture. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…query route Skip the metadata-free preflight when EXTRA_RAISE_FOR_ACCESS_BYPASS is configured, so an operator hook that reads query_context.queries still sees the real request. Opt the legacy POST /api/v1/query/ route into the preflight, and pin that raise_for_access never reads queries for a non-guest caller. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cover the native-filter, chart, multi-layer, drill-to-detail and drill-by branches with viewer promiscuous mode on, and note in config that a bypass hook turns off the semantic chart-data preflight. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es invariant Each case now passes every earlier check on its branch and is refused only by the branch's final check, with a spy proving it ran (drill-by reaches has_drill_by_columns), and the denial must be the datasource-access error. Annotate the new test locals. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…l to the final dashboard check Drill-to-detail and drill-by now succeed, so the shared final can_access_dashboard check alone decides the outcome, both allowed and denied. A spy proves the final check was reached, and the queries trap stays armed throughout. Co-Authored-By: Claude Opus 5.5 <[email protected]>
fitzee
left a comment
There was a problem hiding this comment.
Verdict: approve. For non-guest callers the early check gets the same datasource, slice_ and form_data as the full check, which still runs unchanged, so it can neither allow anyone new nor deny anyone who passed before. The notes below are non-blocking.
Equivalence (checked, no issue)
- For a non-guest caller, the
query_contextbranch ofraise_for_access(superset/security/manager.py, theif datasource or query_context:block, plus the dashboard/chart tails) reads onlyquery_context.datasourceandquery_context.form_data. The calls it makes from there (can_access_schema,_semantic_layer_grant_allows,is_editor, the native-filter / chart / multi-layer / drill branches,can_access_dashboard,has_promiscuous_chart_access) don't touchqueries.query_context_modifiedand the tokendatasetsallowlist are guest-only, and guests skip the early check. The early context is built from the sameform_datadict andslice_as the final one, and_process_query_objectdoesn't write toform_data. So the two decisions are the same for owners,all_datasource_access, layer grants, viewer/promiscuous dashboard and chart access, native filters, drill-to-detail and drill-by. - The early check doesn't replace the later one.
ChartDataCommand.validate()/query_context.raise_for_access()still run on the full context on every patched route (charts/data/api.pyPOST andGET /<pk>/data,views/api.py:/v1/query/). - The early denial raises
SupersetSecurityExceptioninsideschema.load(). That is inside the existingtryin both chart-data handlers and under@handle_api_exceptionon/api/v1/query/, so the status and body are still the same 403. Missing vs denied is unchanged:_convert_to_modelstill raisesDatasourceNotFound(404) before either check. This PR adds no new existence oracle. - The gate is
DatasourceType(datasource["type"]) == SEMANTIC_VIEW, and_convert_to_modelresolves the model by that same type. A SQL dataset or Query can't reach the new branch. - Mutation results: removing the early block fails the 3 denial tests. Removing the
EXTRA_RAISE_FOR_ACCESS_BYPASSexclusion fails the bypass test. Opting/api/v1/query/back out fails the legacy test. Adding aquery_context.queriesread to the non-guest dashboard path fails 9 of the 11never_reads_queriescases.
Non-blocking
-
superset/common/query_context_factory.py:78-97: the bypass-hook problem raised earlier in review also applies toCUSTOM_SECURITY_MANAGER. Excluding the early check whenEXTRA_RAISE_FOR_ACCESS_BYPASSis set covers the config hook, but a custom security manager that overridesraise_for_accessalso gets the preflight context withqueries=[]. If the override grants based on the requested queries (the same pattern you reproduced with the hook), the request now gets a 403. If it indexesquery_context.queries[0], it raisesIndexError, which isn't caught next toSupersetSecurityExceptionand comes back as a 500. Thenever_reads_queriesinvariant only pins the stock manager. At minimum, theconfig.pycomment / UPDATING note could say the semantic chart-data path now callsraise_for_accesstwice, first with an emptyqueries. A tighter option would be to skip the early check whentype(security_manager).raise_for_access is not SupersetSecurityManager.raise_for_access. -
query_context_factory.py:86: the guest exclusion isn't pinned by any test. Withsecurity_manager.is_guest_user() andremoved, all 7 integration tests still pass.test_guest_dashboard_filter_access_is_unchangedasserts a 200 and thatget_dimensionswas called, and both hold whether or not the early check runs for guests. Asserting that the earlyQueryContext(...).raise_for_accessisn't invoked for a guest (for example by spying onQueryContextProcessor.raise_for_accessand checking the call count) would lock down the "guest requests are unchanged" claim. -
superset/charts/data/api.py:221(GET /api/v1/chart/<pk>/data/) is opted in through the shared_create_query_context_from_form, but no test covers a semantic-view chart on that route. A denied case would be cheap to add next totest_denied_chart_data_skips_provider_metadata. -
As the description already notes, allowed semantic requests now run the full access decision twice: the Dashboard/Slice lookups,
has_drill_access,can_access_dashboardand anyEXTRA_EDITORS_RESOLVER. For viewer drill-by that also meanshas_drill_by_columnscallsget_dimensions()once more on the allowed path. This is fine for a fix like this. Just noting the per-request cost.
Paths still building a context before the access check (outside this PR's scope)
- Already listed in the description: the MCP
get_chart_data/get_chart_sqlcallers,Slice.get_query_context,tasks/native_filter_cache.py:239anddashboards/excel_export/workbook.py:219, all on the default factory. - I checked
views/datasource/utils.py:get_samples,/api/v1/datasource/<type>/<id>/query,.../column/<col>/values,commands/explore/get.pyandcommon/tabular_query.py:resolve_explorable. For semantic views, each one either authorizes before it readscolumns/metrics, or refuses earlier (supports_samples = Falsegives a 400 beforeget_samples).
Tests run locally
tests/integration_tests/charts/semantic_metadata_authz_tests.py: 7 passed, including the birth-names test run on its own.tests/unit_tests/security/manager_test.py -k never_read: 11 passed.tests/unit_tests/security/manager_test.py,tests/unit_tests/common/andtests/unit_tests/semantic_layers/: 1343 passed.tests/integration_tests/charts/data/api_tests.pyon sqlite: 24 passed, 70 skipped because the example data isn't loaded.
| "result_type": "query", | ||
| }, | ||
| ) | ||
| assert response.status_code == 200, response.json |
There was a problem hiding this comment.
This logs in as admin, who passes the access check whether it runs once or twice. If the DatasourceType.SEMANTIC_VIEW condition in QueryContextFactory.create were dropped, the early check would also run for the birth_names table and this test would still return 200, so it would not catch SQL datasets being pulled into the new path. Could this wrap security_manager.raise_for_access in a spy and assert it is called exactly once here (versus twice in the allowed semantic test)?
There was a problem hiding this comment.
Good catch, thanks. The admin response alone could not distinguish one access decision from two. The SQL dataset test now spies on security_manager.raise_for_access and asserts exactly one call with query_context; the allowed semantic-view test asserts two (preflight and final check).
I verified the regression locally: replacing the SEMANTIC_VIEW condition with True makes the SQL test fail with assert 2 == 1, while the other six tests pass. The restored branch passes all seven. Addressed in af8bf960ef.
…ight The SQL chart-data test logs in as admin, who passes the access check however often it runs. Count the query-context access decisions instead: one for a SQL dataset, two (preflight and final) for an allowed semantic view, so dropping the semantic-view condition fails the SQL test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for the careful equivalence review and mutation checks. Joe's SQL-dataset test concern is addressed in Your non-blocking points remain valid. A custom security manager can see the first |
| # Guest dashboard and payload checks need the completed query context, | ||
| # and an operator EXTRA_RAISE_FOR_ACCESS_BYPASS hook may read the | ||
| # request's queries; keep their authorization path and timing unchanged. | ||
| if not security_manager.is_guest_user() and not current_app.config.get( |
There was a problem hiding this comment.
The bypass-hook carve-out covers EXTRA_RAISE_FOR_ACCESS_BYPASS, but a CUSTOM_SECURITY_MANAGER that overrides raise_for_access also receives this queries=[] context. An override that reads query_context.queries[0] (for example for column or metric level checks) would raise IndexError here, giving a 500 on every non-guest semantic-view chart-data request before the real check runs. Is it worth documenting that overrides must not read queries, or skipping the early check when raise_for_access is overridden?
There was a problem hiding this comment.
I think this needs a guard before merge. A custom raise_for_access that checks the requested metrics/columns gets queries=[] here, so a previously valid semantic chart request can fail before the full check. Could we skip the preflight when the security manager overrides this method? The stock-manager tests won’t cover that path.
There was a problem hiding this comment.
Agreed, thanks. Fixed in 88df4e2: the early check now runs only when the configured security manager keeps the stock raise_for_access. An override receives the complete query context through the existing final check, as with the EXTRA_RAISE_FOR_ACCESS_BYPASS carve-out.
- The new regression test installs a manager that refuses a query context without queries. It returns 403 on the previous head and 200 with the guard.
- The stock-manager tests still pin the early check: denied requests skip provider metadata, and an allowed request makes two query-context decisions.
- Class-level lookup follows inherited methods and mixin resolution while preserving instance spies. The
CUSTOM_SECURITY_MANAGERcomment documents that overriding this method opts out of the early metadata check.
Codex independently verified all 8 integration cases, 255 focused unit tests, and the branch pre-commit checks.
…for_access The early semantic-view access check builds a query context with no queries. A custom security manager whose raise_for_access authorizes the requested columns or metrics could refuse that context, or fail indexing it, before the complete check runs. Run the early check only when the configured manager keeps the stock raise_for_access, as is already done for EXTRA_RAISE_FOR_ACCESS_BYPASS. Co-Authored-By: Claude Opus 5.5 <[email protected]>
geido
left a comment
There was a problem hiding this comment.
The custom security-manager guard addresses my concern, and the regression test covers it. Looks good from my code-owner review.
…-20261009 # Conflicts: # tests/unit_tests/security/manager_test.py
SUMMARY
For chart-data requests on a semantic view, the query context is built (which asks the semantic-layer provider for dimension and metric metadata) before the access check runs. A caller without access therefore still triggers provider calls before receiving a 403. This change avoids those unnecessary calls.
/api/v1/chart/data,/api/v1/chart/<pk>/data/and the legacy/api/v1/query/, a metadata-free access check now runs before the query context is built. A caller without access gets the same 403 without the provider being called, except where the access decision itself depends on provider metadata (see below).ENABLE_VIEWERSandVIEWER_PROMISCUOUS_MODE) still callsget_dimensions()once on denial, down from twice, because the decision depends on the view's dimension names.EXTRA_RAISE_FOR_ACCESS_BYPASSkeep the previous ordering (no early check), so the hook always receives the complete query context. The setting's comment inconfig.pysays so.raise_for_access, including instance wrappers and base-class reassignment, keep the previous ordering and receive the completed query context.BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
N/A (server-side change; the response is identical). Before, a denied ordinary request called the provider's metadata methods and then returned 403. After, it returns the same 403 with no provider metadata calls, apart from the viewer drill-by case above.
TESTING INSTRUCTIONS
Run:
pytest tests/integration_tests/charts/semantic_metadata_authz_tests.py -q(11 tests)pytest tests/unit_tests/security/manager_test.py -k never_read -q(11 cases)pre-commit runThe denial tests (a direct denied request, a denied dashboard native-filter request and a denied legacy
/api/v1/query/request) fail on the old code because the provider's metadata call happens before the 403. They pass now with zero provider dimension or metric calls.The other integration tests check four things:
EXTRA_RAISE_FOR_ACCESS_BYPASShook that readsquery_context.queriesstill sees the full requestThe unit cases pin the invariant the early check relies on: for a non-guest caller,
raise_for_accessnever readsquery_context.queries. They cover the direct path, plus the native-filter, chart, multi-layer, drill-to-detail and drill-by branches, through to the final dashboard check, both allowed and denied.ADDITIONAL INFORMATION
Known follow-ups:
EXTRA_EDITORS_RESOLVER. Both are read-only.Slice.get_query_context, the native-filter cache task and Excel export still use the default factory without the early check. The request-facing ones sit behind chart-level filters.can_access_dashboard(pre-existing).🤖 Generated with Claude Code