You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/09/04 22:59:28 UTC
(superset) branch master updated: feat(semantic-layers): hide Samples tab and disable drill-to-detail for semantic views (#42534)
This is an automated email from the ASF dual-hosted git repository.
rusackas pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new 01b8eb50a0d feat(semantic-layers): hide Samples tab and disable drill-to-detail for semantic views (#42534)
01b8eb50a0d is described below
commit 01b8eb50a0d5c9d0daba425be3eb5247535162a8
Author: Mike Bridge <mi...@preset.io>
AuthorDate: Fri Sep 4 16:59:18 2026 -0600
feat(semantic-layers): hide Samples tab and disable drill-to-detail for semantic views (#42534)
Co-authored-by: Mike Bridge <mi...@ext.preset.io>
Co-authored-by: Claude Fable 5 <no...@anthropic.com>
---
.../Chart/DrillDetail/DrillDetailPane.test.tsx | 15 +-
.../Chart/DrillDetail/DrillDetailPane.tsx | 7 +-
.../ErrorMessage/PreformattedErrorDescription.tsx | 32 +++++
.../DataTablesPane/components/SamplesPane.tsx | 7 +-
.../DataTablesPane/components/useResultsPane.tsx | 7 +-
.../DataTablesPane/test/DataTablesPane.test.tsx | 18 ++-
.../DataTablesPane/test/SamplesPane.test.tsx | 3 +-
.../DataTablesPane/test/useResultsPane.test.tsx | 18 +++
superset/models/sql_lab.py | 13 ++
superset/views/datasource/views.py | 96 ++++++++-----
tests/unit_tests/views/datasource/views_test.py | 157 ++++++++++++++++++++-
11 files changed, 322 insertions(+), 51 deletions(-)
diff --git a/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.test.tsx b/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.test.tsx
index 3bf8fb6b36b..e92e6de17d6 100644
--- a/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.test.tsx
+++ b/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.test.tsx
@@ -214,15 +214,22 @@ test('should render the metadata bar', async () => {
test('should render the error', async () => {
jest
.spyOn(SupersetClient, 'post')
- .mockRejectedValue(new Error('Something went wrong'));
+ .mockRejectedValue(new Error('Something went wrong\nPlease retry'));
await waitForRender();
- // The error is wrapped in an Alert component with a stable headline and the
- // raw error text in the description — no more bare ``<pre>`` elements.
+ // The error is wrapped in an Alert component with a stable headline; the
+ // raw error text renders as the description with its line breaks
+ // preserved (via the shared PreformattedErrorDescription).
expect(await screen.findByRole('alert')).toBeVisible();
expect(
await screen.findByText('Failed to load drill-to-detail rows'),
).toBeVisible();
- expect(screen.getByText('Error: Something went wrong')).toBeInTheDocument();
+ const errorDescription = screen.getByText(
+ 'Error: Something went wrong Please retry',
+ );
+ expect(errorDescription.textContent).toBe(
+ 'Error: Something went wrong\nPlease retry',
+ );
+ expect(errorDescription).toHaveStyle({ whiteSpace: 'pre-wrap' });
});
describe('download actions', () => {
diff --git a/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.tsx b/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.tsx
index d7378fc3904..ea41b55d941 100644
--- a/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.tsx
+++ b/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.tsx
@@ -44,6 +44,7 @@ import TimeCell from '@superset-ui/core/components/Table/cell-renderers/TimeCell
import { EmptyState, Loading } from '@superset-ui/core/components';
import { Alert } from '@apache-superset/core/components';
import { getDatasourceSamples } from 'src/components/Chart/chartAction';
+import { PreformattedErrorDescription } from 'src/components/ErrorMessage/PreformattedErrorDescription';
import Table, {
ColumnsType,
TableSize,
@@ -372,7 +373,11 @@ export default function DrillDetailPane({
type="error"
showIcon
message={t('Failed to load drill-to-detail rows')}
- description={responseError}
+ description={
+ <PreformattedErrorDescription>
+ {responseError}
+ </PreformattedErrorDescription>
+ }
/>
</div>
);
diff --git a/superset-frontend/src/components/ErrorMessage/PreformattedErrorDescription.tsx b/superset-frontend/src/components/ErrorMessage/PreformattedErrorDescription.tsx
new file mode 100644
index 00000000000..3e0187777f0
--- /dev/null
+++ b/superset-frontend/src/components/ErrorMessage/PreformattedErrorDescription.tsx
@@ -0,0 +1,32 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { styled } from '@apache-superset/core/theme';
+
+/**
+ * Preformatted error detail for an Alert description: preserves the server
+ * error's line breaks, wraps long unbroken tokens (SQL, URIs, payloads)
+ * instead of overflowing the Alert, and uses the theme's code font so it
+ * matches other preformatted errors in the app.
+ */
+export const PreformattedErrorDescription = styled.pre`
+ margin: 0;
+ font-family: ${({ theme }) => theme.fontFamilyCode};
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+`;
diff --git a/superset-frontend/src/explore/components/DataTablesPane/components/SamplesPane.tsx b/superset-frontend/src/explore/components/DataTablesPane/components/SamplesPane.tsx
index 6624d3c3488..7437d5e742a 100644
--- a/superset-frontend/src/explore/components/DataTablesPane/components/SamplesPane.tsx
+++ b/superset-frontend/src/explore/components/DataTablesPane/components/SamplesPane.tsx
@@ -24,6 +24,7 @@ import { styled } from '@apache-superset/core/theme';
import { Alert } from '@apache-superset/core/components';
import { EmptyState, Loading } from '@superset-ui/core/components';
import { GenericDataType } from '@apache-superset/core/common';
+import { PreformattedErrorDescription } from 'src/components/ErrorMessage/PreformattedErrorDescription';
import { GridTable } from 'src/components/GridTable';
import { GridSize } from 'src/components/GridTable/constants';
import { getDatasourceSamples } from 'src/components/Chart/chartAction';
@@ -175,7 +176,11 @@ export const SamplesPane = ({
type="error"
showIcon
message={t('Failed to load samples')}
- description={responseError}
+ description={
+ <PreformattedErrorDescription>
+ {responseError}
+ </PreformattedErrorDescription>
+ }
/>
</ErrorAlertWrapper>
</>
diff --git a/superset-frontend/src/explore/components/DataTablesPane/components/useResultsPane.tsx b/superset-frontend/src/explore/components/DataTablesPane/components/useResultsPane.tsx
index 29c4f4bca94..e68084b5df8 100644
--- a/superset-frontend/src/explore/components/DataTablesPane/components/useResultsPane.tsx
+++ b/superset-frontend/src/explore/components/DataTablesPane/components/useResultsPane.tsx
@@ -30,6 +30,7 @@ import { styled } from '@apache-superset/core/theme';
import { Alert } from '@apache-superset/core/components';
import { EmptyState, Loading } from '@superset-ui/core/components';
import { getChartDataRequest } from 'src/components/Chart/chartAction';
+import { PreformattedErrorDescription } from 'src/components/ErrorMessage/PreformattedErrorDescription';
import { ResultsPaneProps, QueryResultInterface } from '../types';
import { SingleQueryResultPane } from './SingleQueryResultPane';
import { TableControls, ROW_LIMIT_OPTIONS } from './DataTableControls';
@@ -216,7 +217,11 @@ export const useResultsPane = ({
type="error"
showIcon
message={t('Failed to load results')}
- description={responseError}
+ description={
+ <PreformattedErrorDescription>
+ {responseError}
+ </PreformattedErrorDescription>
+ }
/>
</ErrorAlertWrapper>
</>
diff --git a/superset-frontend/src/explore/components/DataTablesPane/test/DataTablesPane.test.tsx b/superset-frontend/src/explore/components/DataTablesPane/test/DataTablesPane.test.tsx
index 65b3b8423c2..55ba34afa29 100644
--- a/superset-frontend/src/explore/components/DataTablesPane/test/DataTablesPane.test.tsx
+++ b/superset-frontend/src/explore/components/DataTablesPane/test/DataTablesPane.test.tsx
@@ -24,6 +24,7 @@ import {
screen,
userEvent,
waitFor,
+ within,
} from 'spec/helpers/testing-library';
import { setupAGGridModules } from '@superset-ui/core/components/ThemedAgGridReact';
import { setItem, LocalStorageKeys } from 'src/utils/localStorageHelpers';
@@ -131,9 +132,22 @@ describe('DataTablesPane', () => {
await waitFor(() => {
expect(screen.queryByText('Samples')).not.toBeInTheDocument();
});
- expect(screen.getByText('Results')).toBeVisible();
- // Panel stays expanded and renders Results content rather than going blank.
+ // The Results tab must be the ACTIVE pane, not merely present — the
+ // original bug left the removed Samples key active, rendering a blank
+ // panel while the Results tab label was still visible.
+ expect(screen.getByRole('tab', { selected: true })).toHaveTextContent(
+ 'Results',
+ );
+ // Panel stays expanded and the active tabpanel renders actual Results
+ // content — the row-count readout — rather than going blank (the
+ // orphaned-key bug mounted no pane at all).
expect(screen.getByLabelText('Collapse data panel')).toBeVisible();
+ const activePanel = screen.getByRole('tabpanel');
+ expect(
+ await within(activePanel).findByText('0 rows', undefined, {
+ timeout: 5000,
+ }),
+ ).toBeVisible();
});
test('Should copy data table content correctly', async () => {
diff --git a/superset-frontend/src/explore/components/DataTablesPane/test/SamplesPane.test.tsx b/superset-frontend/src/explore/components/DataTablesPane/test/SamplesPane.test.tsx
index b358701f59c..19839688e5d 100644
--- a/superset-frontend/src/explore/components/DataTablesPane/test/SamplesPane.test.tsx
+++ b/superset-frontend/src/explore/components/DataTablesPane/test/SamplesPane.test.tsx
@@ -113,7 +113,8 @@ describe('SamplesPane', () => {
// headline message and the raw error text as the description.
expect(await findByRole('alert')).toBeVisible();
expect(await findByText('Failed to load samples')).toBeVisible();
- expect(await findByText('Error: Bad request')).toBeVisible();
+ const errorDescription = await findByText('Error: Bad request');
+ expect(errorDescription).toHaveStyle({ whiteSpace: 'pre-wrap' });
});
test('force query, render', async () => {
diff --git a/superset-frontend/src/explore/components/DataTablesPane/test/useResultsPane.test.tsx b/superset-frontend/src/explore/components/DataTablesPane/test/useResultsPane.test.tsx
index 471d375087b..953b7bd6155 100644
--- a/superset-frontend/src/explore/components/DataTablesPane/test/useResultsPane.test.tsx
+++ b/superset-frontend/src/explore/components/DataTablesPane/test/useResultsPane.test.tsx
@@ -240,3 +240,21 @@ describe('useResultsPane query data reuse', () => {
expect(mockedGetChartDataRequest).not.toHaveBeenCalled();
});
});
+
+test('preserves multiline formatting in results errors', async () => {
+ mockedGetChartDataRequest.mockRejectedValue(
+ new Error('Query failed\nCheck the datasource'),
+ );
+ const props = createResultsPaneOnDashboardProps({ sliceId: 208 });
+
+ render(<ResultsPaneOnDashboard {...props} />, { useRedux: true });
+
+ expect(await screen.findByText('Failed to load results')).toBeVisible();
+ const errorDescription = screen.getByText(
+ 'Query failed Check the datasource',
+ );
+ expect(errorDescription.textContent).toBe(
+ 'Query failed\nCheck the datasource',
+ );
+ expect(errorDescription).toHaveStyle({ whiteSpace: 'pre-wrap' });
+});
diff --git a/superset/models/sql_lab.py b/superset/models/sql_lab.py
index 192dace275f..2f728820bd0 100644
--- a/superset/models/sql_lab.py
+++ b/superset/models/sql_lab.py
@@ -127,6 +127,12 @@ class Query(
__tablename__ = "query"
type = "query"
+
+ # Query results are raw rows, so samples are meaningful. Declared
+ # explicitly (rather than relying on a fail-open ``getattr`` default)
+ # so every member of ``DatasourceDAO.sources`` carries the capability.
+ supports_samples: bool = True
+
id = Column(Integer, primary_key=True)
client_id = Column(String(11), unique=True, nullable=False)
query_language = "sql"
@@ -493,6 +499,13 @@ class SavedQuery(
"""ORM model for SQL query"""
__tablename__ = "saved_query"
+
+ # Saved queries are backed by raw rows, so samples are meaningful.
+ # Declared explicitly (rather than relying on a fail-open ``getattr``
+ # default) so every member of ``DatasourceDAO.sources`` carries the
+ # capability.
+ supports_samples: bool = True
+
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey("ab_user.id"), nullable=True)
db_id = Column(Integer, ForeignKey("dbs.id"), nullable=True)
diff --git a/superset/views/datasource/views.py b/superset/views/datasource/views.py
index 551c781af28..fcfee22c1ff 100644
--- a/superset/views/datasource/views.py
+++ b/superset/views/datasource/views.py
@@ -34,7 +34,7 @@ from superset.connectors.sqla.models import SqlaTable
from superset.connectors.sqla.utils import get_physical_table_metadata
from superset.daos.dashboard import DashboardDAO
from superset.daos.dataset import DatasetDAO
-from superset.daos.datasource import DatasourceDAO
+from superset.daos.datasource import Datasource as DatasourceModel, DatasourceDAO
from superset.daos.exceptions import DatasourceNotFound, DatasourceTypeNotSupportedError
from superset.exceptions import SupersetException, SupersetSecurityException
from superset.models.core import Database
@@ -54,6 +54,38 @@ from superset.views.datasource.utils import get_samples
from superset.views.error_handling import handle_api_exception
from superset.views.utils import sanitize_datasource_data
+# Datasource types whose ``datasource_id`` refers to a dataset row.
+_DATASET_TYPES = frozenset({DatasourceType.TABLE.value, DatasourceType.DATASET.value})
+
+
+def _load_dataset_for_samples(
+ view: BaseSupersetView, params: dict[str, Any]
+) -> tuple[DatasourceModel | None, FlaskResponse | None]:
+ """Pre-fetch and access-check the dataset for an authenticated request.
+
+ Only dataset-backed types are pre-fetched. Non-table types (query,
+ saved_query) use a different access model; passing them to
+ ``raise_for_access(datasource=...)`` would check the wrong attributes,
+ so ``get_samples()`` handles the lookup for those types.
+
+ Returns ``(dataset, None)`` on success and ``(None, error_response)``
+ when the caller should return the error response.
+ """
+ if params["datasource_type"] not in _DATASET_TYPES:
+ return None, None
+ try:
+ dataset = DatasourceDAO.get_datasource(
+ datasource_type=params["datasource_type"],
+ database_id_or_uuid=params["datasource_id"],
+ )
+ except (DatasourceNotFound, DatasourceTypeNotSupportedError):
+ return None, view.response_404()
+ try:
+ security_manager.raise_for_access(datasource=dataset)
+ except SupersetSecurityException:
+ return None, json_error_response(_("Forbidden"), status=403)
+ return dataset, None
+
class Datasource(BaseSupersetView):
"""Datasource-related views"""
@@ -223,26 +255,17 @@ class Datasource(BaseSupersetView):
except ValidationError as err:
return json_error_response(err.messages, status=400)
- # Refuse early for datasource types that don't model raw rows
- # (e.g. semantic views, which only expose pre-defined metrics and
- # dimensions). Without this gate the request would still go through
- # the standard query pipeline and fail with an opaque 500.
- # ``supports_samples`` defaults to True for any datasource class that
- # doesn't explicitly opt out, so SqlaTable/Query/SavedQuery continue
- # to work without needing the attribute declared on each class.
- ds_class = DatasourceDAO.sources.get(
- DatasourceType(params["datasource_type"]),
- )
- if ds_class is not None and not getattr(ds_class, "supports_samples", True):
- return json_error_response(
- _("Samples are not available for this datasource type."),
- status=400,
- )
-
dashboard_id = None
if security_manager.is_guest_user():
if not params["dashboard_id"]:
return json_error_response(_("Forbidden"), status=403)
+ # Guest drill access is only defined for dataset-backed charts.
+ # Refuse other datasource types before the DatasetDAO lookup:
+ # ``datasource_id`` values for those types live in unrelated id
+ # spaces, so the lookup below would validate whichever unrelated
+ # SqlaTable happens to share the integer id.
+ if params["datasource_type"] not in _DATASET_TYPES:
+ return self.response_404()
dashboard_id = params["dashboard_id"]
dataset = DatasetDAO.find_by_id(
params["datasource_id"], skip_base_filter=True
@@ -256,27 +279,24 @@ class Datasource(BaseSupersetView):
):
return json_error_response(_("Forbidden"), status=403)
else:
- # Pre-fetch and access-check only for table-type datasources.
- # Non-table types (query, saved_query) use a different access model;
- # passing them to raise_for_access(datasource=...) would check the
- # wrong attributes. Let get_samples() handle the lookup for those types.
- if params["datasource_type"] in {
- DatasourceType.TABLE.value,
- DatasourceType.DATASET.value,
- }:
- try:
- dataset = DatasourceDAO.get_datasource(
- datasource_type=params["datasource_type"],
- database_id_or_uuid=params["datasource_id"],
- )
- except (DatasourceNotFound, DatasourceTypeNotSupportedError):
- return self.response_404()
- try:
- security_manager.raise_for_access(datasource=dataset)
- except SupersetSecurityException:
- return json_error_response(_("Forbidden"), status=403)
- else:
- dataset = None
+ dataset, error_response = _load_dataset_for_samples(self, params)
+ if error_response is not None:
+ return error_response
+
+ # Refuse datasource types that don't model raw rows only after the
+ # authorization checks above, keeping authorization-before-capability
+ # ordering: guests get 403/404 from the guest branch, while
+ # authenticated users hit this purely type-level gate (a 400 that is a
+ # function of the requested ``datasource_type`` alone -- no per-object
+ # lookup happens for non-table types, by design).
+ ds_class = DatasourceDAO.sources.get(
+ DatasourceType(params["datasource_type"]),
+ )
+ if ds_class is not None and not ds_class.supports_samples:
+ return json_error_response(
+ _("Samples are not available for this datasource type."),
+ status=400,
+ )
rv = get_samples(
datasource_type=params["datasource_type"],
diff --git a/tests/unit_tests/views/datasource/views_test.py b/tests/unit_tests/views/datasource/views_test.py
index 025bdc3b3c7..5ba3860e27b 100644
--- a/tests/unit_tests/views/datasource/views_test.py
+++ b/tests/unit_tests/views/datasource/views_test.py
@@ -30,6 +30,11 @@ from superset.exceptions import SupersetSecurityException
from superset.utils import json as superset_json
+def _identity_gettext(message: str) -> str:
+ """Typed stand-in for flask-babel's ``_`` in request-less unit tests."""
+ return message
+
+
def _security_exception() -> SupersetSecurityException:
return SupersetSecurityException(
SupersetError(
@@ -501,7 +506,7 @@ def test_save_checks_access_against_requested_table_not_stale_one(
# ---------------------------------------------------------------------------
-@patch("superset.views.datasource.views._", lambda s: s)
+@patch("superset.views.datasource.views._", _identity_gettext)
@patch("superset.views.datasource.views.get_samples")
@patch("superset.views.datasource.views.json_error_response")
@patch("superset.views.datasource.views.security_manager", new_callable=MagicMock)
@@ -516,14 +521,13 @@ def test_samples_returns_400_for_unsupported_datasource_type(
mock_security_manager.is_guest_user.return_value = False
mock_json_error_response.return_value = "error-response"
- raw_samples = _get_view_func("samples")
app = Flask(__name__)
with app.test_request_context(
"/datasource/samples?datasource_type=semantic_view&datasource_id=1",
method="POST",
json={},
):
- result = raw_samples(_view_self())
+ result = _get_view_func("samples")(_view_self())
assert result == "error-response"
mock_json_error_response.assert_called_once()
@@ -533,6 +537,110 @@ def test_samples_returns_400_for_unsupported_datasource_type(
mock_get_samples.assert_not_called()
+@patch("superset.views.datasource.views._", _identity_gettext)
+@patch("superset.views.datasource.views.get_samples")
+@patch("superset.views.datasource.views.json_error_response")
+@patch("superset.views.datasource.views.security_manager", new_callable=MagicMock)
+def test_samples_checks_guest_access_before_datasource_capability(
+ mock_security_manager: MagicMock,
+ mock_json_error_response: MagicMock,
+ mock_get_samples: MagicMock,
+) -> None:
+ """An unauthorized guest gets 403 before semantic-view capability errors."""
+ from flask import Flask
+
+ mock_security_manager.is_guest_user.return_value = True
+ mock_json_error_response.return_value = "forbidden-response"
+
+ app = Flask(__name__)
+ with app.test_request_context(
+ "/datasource/samples?datasource_type=semantic_view&datasource_id=1",
+ method="POST",
+ json={},
+ ):
+ result = _get_view_func("samples")(_view_self())
+
+ assert result == "forbidden-response"
+ mock_json_error_response.assert_called_once_with("Forbidden", status=403)
+ mock_get_samples.assert_not_called()
+
+
+@patch("superset.views.datasource.views._", _identity_gettext)
+@patch("superset.views.datasource.views.get_samples")
+@patch("superset.views.datasource.views.DatasetDAO")
+@patch("superset.views.datasource.views.json_error_response")
+@patch("superset.views.datasource.views.security_manager", new_callable=MagicMock)
+def test_samples_guest_with_dashboard_gets_404_for_non_dataset_type(
+ mock_security_manager: MagicMock,
+ mock_json_error_response: MagicMock,
+ mock_dataset_dao: MagicMock,
+ mock_get_samples: MagicMock,
+) -> None:
+ """A guest with a dashboard_id gets 404 for a semantic view, not the 400.
+
+ The 404 must win over the capability 400, and the dataset lookup must not
+ run at all: ``datasource_id`` values for non-dataset types live in
+ unrelated id spaces, so ``DatasetDAO.find_by_id`` would validate whichever
+ unrelated table shares the integer id.
+ """
+ from flask import Flask
+
+ mock_security_manager.is_guest_user.return_value = True
+
+ view = _view_self()
+ app = Flask(__name__)
+ with app.test_request_context(
+ "/datasource/samples?datasource_type=semantic_view&datasource_id=1"
+ "&dashboard_id=5",
+ method="POST",
+ json={},
+ ):
+ result = _get_view_func("samples")(view)
+
+ assert result == view.response_404.return_value
+ view.response_404.assert_called_once()
+ mock_dataset_dao.find_by_id.assert_not_called()
+ mock_json_error_response.assert_not_called()
+ mock_get_samples.assert_not_called()
+
+
+@patch("superset.views.datasource.views._", _identity_gettext)
+@patch("superset.views.datasource.views.get_samples")
+@patch("superset.views.datasource.views.DashboardDAO")
+@patch("superset.views.datasource.views.DatasetDAO")
+@patch("superset.views.datasource.views.json_error_response")
+@patch("superset.views.datasource.views.security_manager", new_callable=MagicMock)
+def test_samples_guest_drill_denial_returns_403(
+ mock_security_manager: MagicMock,
+ mock_json_error_response: MagicMock,
+ mock_dataset_dao: MagicMock,
+ mock_dashboard_dao: MagicMock,
+ mock_get_samples: MagicMock,
+) -> None:
+ """A guest failing the drill-access check gets 403 from that gate."""
+ from flask import Flask
+
+ mock_security_manager.is_guest_user.return_value = True
+ mock_security_manager.can_drill_dataset_via_dashboard_access.return_value = False
+ mock_json_error_response.return_value = "forbidden-response"
+
+ app = Flask(__name__)
+ with app.test_request_context(
+ "/datasource/samples?datasource_type=table&datasource_id=1&dashboard_id=5",
+ method="POST",
+ json={},
+ ):
+ result = _get_view_func("samples")(_view_self())
+
+ assert result == "forbidden-response"
+ mock_security_manager.can_drill_dataset_via_dashboard_access.assert_called_once_with(
+ mock_dataset_dao.find_by_id.return_value,
+ mock_dashboard_dao.find_by_id.return_value,
+ )
+ mock_json_error_response.assert_called_once_with("Forbidden", status=403)
+ mock_get_samples.assert_not_called()
+
+
@patch("superset.views.datasource.views.get_samples")
@patch("superset.views.datasource.views.security_manager", new_callable=MagicMock)
def test_samples_proceeds_for_supported_datasource_type(
@@ -557,3 +665,46 @@ def test_samples_proceeds_for_supported_datasource_type(
mock_get_samples.assert_called_once()
view.json_response.assert_called_once_with({"result": {"rows": []}})
+
+
+@patch("superset.views.datasource.views._", _identity_gettext)
+@patch("superset.views.datasource.views.get_samples")
+@patch("superset.views.datasource.views.DatasourceDAO.get_datasource")
+@patch("superset.views.datasource.views.json_error_response")
+@patch("superset.views.datasource.views.security_manager", new_callable=MagicMock)
+def test_samples_authenticated_dataset_access_denied_returns_403_before_fetch(
+ mock_security_manager: MagicMock,
+ mock_json_error_response: MagicMock,
+ mock_get_datasource: MagicMock,
+ mock_get_samples: MagicMock,
+) -> None:
+ """An authenticated user denied access to a dataset short-circuits to 403
+ from ``raise_for_access`` on the pre-fetched dataset, and ``get_samples`` is
+ never reached — authorization runs before any sample fetch. (The
+ authenticated per-object check only runs for dataset-backed types, which
+ always support samples, so this pins authorization-before-fetch rather than
+ a race against the ``supports_samples`` gate.)"""
+ from flask import Flask
+
+ mock_security_manager.is_guest_user.return_value = False
+ mock_dataset = MagicMock()
+ mock_get_datasource.return_value = mock_dataset
+ mock_security_manager.raise_for_access.side_effect = _security_exception()
+ mock_json_error_response.return_value = "error-response"
+
+ app = Flask(__name__)
+ with app.test_request_context(
+ "/datasource/samples?datasource_type=table&datasource_id=1",
+ method="POST",
+ json={},
+ ):
+ result = _get_view_func("samples")(_view_self())
+
+ assert result == "error-response"
+ # The per-object gate runs on the pre-fetched dataset, and its denial
+ # short-circuits to a single 403 before any sample fetching.
+ mock_security_manager.raise_for_access.assert_called_once_with(
+ datasource=mock_dataset
+ )
+ mock_json_error_response.assert_called_once_with("Forbidden", status=403)
+ mock_get_samples.assert_not_called()