Skip to content

fix(charts): avoid loading semantic provider metadata before denying chart data access - #45060

Merged
aminghadersohi merged 14 commits into
apache:masterfrom
mikebridge:sc-123441-authz-before-metadata
Oct 10, 2026
Merged

aminghadersohi merged 14 commits into
apache:masterfrom
mikebridge:sc-123441-authz-before-metadata

Conversation

@mikebridge

@mikebridge mikebridge commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

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.

  • For ordinary (non-guest) requests on a semantic view to /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).
  • The full access check still runs before execution, exactly as before, so an early allow never widens access.
  • Viewer drill-by (with ENABLE_VIEWERS and VIEWER_PROMISCUOUS_MODE) still calls get_dimensions() once on denial, down from twice, because the decision depends on the view's dimension names.
  • Deployments that configure EXTRA_RAISE_FOR_ACCESS_BYPASS keep the previous ordering (no early check), so the hook always receives the complete query context. The setting's comment in config.py says so.
  • Configured security managers that override or wrap raise_for_access, including instance wrappers and base-class reassignment, keep the previous ordering and receive the completed query context.
  • Embedded-guest requests are unchanged in this PR. Their access is derived from the dashboard and is handled separately.
  • SQL datasets are unaffected.
  • The error response is unchanged.

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)
  • changed-file pre-commit run

The 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:

  • an allowed caller still succeeds
  • an embedded guest with dashboard access still succeeds
  • SQL dataset chart-data requests are unaffected
  • an EXTRA_RAISE_FOR_ACCESS_BYPASS hook that reads query_context.queries still sees the full request

The unit cases pin the invariant the early check relies on: for a non-guest caller, raise_for_access never reads query_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

  • Has associated issue
  • Required feature flags
  • Changes UI
  • Includes DB Migration
  • Introduces new feature or API
  • Removes existing feature or API

Known follow-ups:

  • Allowed semantic requests now evaluate the access lookups twice (once in the early check, once in the full check), including any EXTRA_EDITORS_RESOLVER. Both are read-only.
  • MCP chart data and chart SQL, 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.
  • Drill-by metadata is evaluated before can_access_dashboard (pre-existing).

🤖 Generated with Claude Code

@github-actions github-actions Bot added the api Related to the REST API label Oct 7, 2026
@netlify

netlify Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 482dfc0
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ac9294882271500088b4ea4
😎 Deploy Preview https://deploy-preview-45060--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Oct 7, 2026
@codecov

codecov Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.86%. Comparing base (ab2c69f) to head (4aac316).
⚠️ Report is 16 commits behind head on master.

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     
Flag Coverage Δ
hive 35.30% <43.75%> (-0.06%) ⬇️
mysql 53.77% <100.00%> (-0.04%) ⬇️
postgres 53.78% <100.00%> (-0.04%) ⬇️
presto 37.13% <68.75%> (-0.06%) ⬇️
python 86.50% <100.00%> (+0.02%) ⬆️
sqlite 53.52% <100.00%> (-0.04%) ⬇️
unit 80.15% <87.50%> (+0.03%) ⬆️

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.

@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Oct 7, 2026
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mikebridge
mikebridge marked this pull request as ready for review October 8, 2026 04:51
@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt PR Risk: Low Risk

  • The PR appears safe to merge; the authorization preflight is limited to semantic-view requests using the stock access check.
  • The added tests cover denied and allowed requests, dashboard filters, guest access, and custom or wrapped access checks.

Assessed commit: 7c80af95d986

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

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:

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.

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:

Suggested change
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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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=[],

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

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.

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

mikebridge and others added 5 commits October 8, 2026 13:33
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 fitzee 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.

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_context branch of raise_for_access (superset/security/manager.py, the if datasource or query_context: block, plus the dashboard/chart tails) reads only query_context.datasource and query_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 touch queries. query_context_modified and the token datasets allowlist are guest-only, and guests skip the early check. The early context is built from the same form_data dict and slice_ as the final one, and _process_query_object doesn't write to form_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.py POST and GET /<pk>/data, views/api.py:/v1/query/).
  • The early denial raises SupersetSecurityException inside schema.load(). That is inside the existing try in both chart-data handlers and under @handle_api_exception on /api/v1/query/, so the status and body are still the same 403. Missing vs denied is unchanged: _convert_to_model still raises DatasourceNotFound (404) before either check. This PR adds no new existence oracle.
  • The gate is DatasourceType(datasource["type"]) == SEMANTIC_VIEW, and _convert_to_model resolves 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_BYPASS exclusion fails the bypass test. Opting /api/v1/query/ back out fails the legacy test. Adding a query_context.queries read to the non-guest dashboard path fails 9 of the 11 never_reads_queries cases.

Non-blocking

  1. superset/common/query_context_factory.py:78-97: the bypass-hook problem raised earlier in review also applies to CUSTOM_SECURITY_MANAGER. Excluding the early check when EXTRA_RAISE_FOR_ACCESS_BYPASS is set covers the config hook, but a custom security manager that overrides raise_for_access also gets the preflight context with queries=[]. 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 indexes query_context.queries[0], it raises IndexError, which isn't caught next to SupersetSecurityException and comes back as a 500. The never_reads_queries invariant only pins the stock manager. At minimum, the config.py comment / UPDATING note could say the semantic chart-data path now calls raise_for_access twice, first with an empty queries. A tighter option would be to skip the early check when type(security_manager).raise_for_access is not SupersetSecurityManager.raise_for_access.

  2. query_context_factory.py:86: the guest exclusion isn't pinned by any test. With security_manager.is_guest_user() and removed, all 7 integration tests still pass. test_guest_dashboard_filter_access_is_unchanged asserts a 200 and that get_dimensions was called, and both hold whether or not the early check runs for guests. Asserting that the early QueryContext(...).raise_for_access isn't invoked for a guest (for example by spying on QueryContextProcessor.raise_for_access and checking the call count) would lock down the "guest requests are unchanged" claim.

  3. 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 to test_denied_chart_data_skips_provider_metadata.

  4. As the description already notes, allowed semantic requests now run the full access decision twice: the Dashboard/Slice lookups, has_drill_access, can_access_dashboard and any EXTRA_EDITORS_RESOLVER. For viewer drill-by that also means has_drill_by_columns calls get_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_sql callers, Slice.get_query_context, tasks/native_filter_cache.py:239 and dashboards/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.py and common/tabular_query.py:resolve_explorable. For semantic views, each one either authorizes before it reads columns/metrics, or refuses earlier (supports_samples = False gives a 400 before get_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/ and tests/unit_tests/semantic_layers/: 1343 passed.
  • tests/integration_tests/charts/data/api_tests.py on sqlite: 24 passed, 70 skipped because the example data isn't loaded.

"result_type": "query",
},
)
assert response.status_code == 200, response.json

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@mikebridge

Copy link
Copy Markdown
Member Author

Thanks for the careful equivalence review and mutation checks. Joe's SQL-dataset test concern is addressed in af8bf960ef: the test now counts query-context access decisions and fails if the semantic preflight also runs for SQL datasets.

Your non-blocking points remain valid. A custom security manager can see the first raise_for_access call with queries=[], and allowed semantic requests still pay for two decisions. The guest exclusion and semantic GET /api/v1/chart/<pk>/data/ path would benefit from direct regression tests. This test-only commit does not change those behaviors; I have kept them visible as follow-up review items rather than claiming they are covered here.

# 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(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_MANAGER comment 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 geido left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@aminghadersohi
aminghadersohi merged commit fd2740b into apache:master Oct 10, 2026
71 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Related to the REST API size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants