This is an automated email from the ASF dual-hosted git repository. villebro pushed a commit to branch 7.0 in repository https://gitbox.apache.org/repos/asf/superset.git
commit 2962df4effad69c3340bb6bff00481e396838307 Author: Ville Brofeldt <[email protected]> AuthorDate: Sat Nov 14 10:34:37 2026 -0800 fix(security): bind promiscuous viewer access to the dashboard's and chart's own requests (reduced backport of #44215) The security manager change applies as is. On 7.0 the copy and native-filter checks build on the reduced #45538 layout check rather than master's #44028 and #45800 helpers: a copy checks the source charts it carries (all of them when duplicating or without a layout, else those its layout places) and its native-filter targets, and the update command checks new filter targets before its side effects. The dashboard datasets endpoint passes the grant to the serializer, since 7.0's DAO takes no access callback. Tests for files absent on 7.0 are left out, and 7.0's copy test now expects the refusal. (cherry picked from commit 2645396b7a8ea1f5b1978f94b2ac0ec0c1b1397b, reduced) --- SECURITY.md | 1 + UPDATING.md | 19 +- docs/admin_docs/security/security.mdx | 11 +- superset/commands/dashboard/update.py | 8 +- superset/config.py | 9 +- superset/daos/dashboard.py | 127 +++++- superset/dashboards/api.py | 46 +- superset/security/manager.py | 114 +++-- tests/integration_tests/dashboards/api_tests.py | 158 +++++++ tests/unit_tests/dao/dashboard_test.py | 32 +- .../security/typed_datasource_access_test.py | 2 + .../subjects/test_creator_group_call_sites.py | 12 + .../subjects/test_promiscuous_dashboard_access.py | 487 +++++++++++++++++++++ tests/unit_tests/subjects/test_raise_for_access.py | 10 +- 14 files changed, 972 insertions(+), 64 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index b863623b8eb..8e5b8a6076f 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -129,6 +129,7 @@ If yes, it is in scope. If no, it is out of scope. The lists below apply that te - Brute force, rate limiting, denial of service, or resource exhaustion that does not bypass a documented control. - Missing security headers, banner or version disclosure, user or object enumeration through error messages or timing, and similar low-impact information disclosure that does not enable a further concrete exploit. - Bypasses of configurable defense-in-depth hardening that Apache Superset does not document as a security boundary. Apache Superset is not a SQL or database firewall: operator-deployable filters such as SQL function or table denylists, URI restrictions on already-authorized database connectors, and similar belt-and-braces controls are provided to let operators layer hardening on top of the role and capability matrix, not as firewall-grade guarantees the codebase commits to. Findings aga [...] +- Access granted by `VIEWER_PROMISCUOUS_MODE`. It is an operator opt-in that deliberately relaxes the role and capability matrix, following the legacy `DASHBOARD_RBAC` model: with `ENABLE_VIEWERS` on, the listed viewers of a published dashboard can read its member charts and their datasets' data, on requests bound to that dashboard, and the listed viewers of a chart can read that chart's data on requests for it, without the dataset access the regular model requires. A dashboard's or char [...] - Hardening suggestions that improve defense in depth but do not violate the security model. Findings in third-party dependencies fall into two cases. A finding in a transitive dependency, or in an operator-selected dependency that Apache Superset does not ship, is out of scope and should be reported to the dependency's maintainers. A finding caused by Apache Superset pinning a known-vulnerable version of a direct dependency it ships, or using a dependency in a way that creates a vulnerability the dependency itself does not have, remains in scope. Dependency findings in the offi [...] diff --git a/UPDATING.md b/UPDATING.md index 86ac4cc19aa..ed5e245bffb 100644 --- a/UPDATING.md +++ b/UPDATING.md @@ -26,6 +26,20 @@ assists people when migrating to a new version. ## 7.0.0 +- With `ENABLE_VIEWERS` and `VIEWER_PROMISCUOUS_MODE` on, the dashboard grant + follows the legacy `DASHBOARD_RBAC` model: only the listed viewers of a + published dashboard read its charts and datasets without dataset permissions, + and only while viewing that dashboard (its chart data, `/charts`, `/datasets` + and drill). Dashboard editors who aren't also listed viewers no longer get the + grant and need regular access to the data; add them as viewers to restore it. + The chart grant follows the same rule: only a chart's listed viewers load its + data without dataset permissions, and its editors need regular access. + Copying a dashboard, with or without duplicating its charts, now requires + access to each of its charts and native-filter target datasets in their own + right, and saving a native filter (through the dashboard or the filters API) + with a new target requires access to that dataset; otherwise both return + HTTP 422 naming the charts or datasets. + - Dashboard and chart `viewers` can no longer be added through the API or the MCP `manage_dashboard_roles` tool while the `ENABLE_VIEWERS` feature flag is off; such requests are rejected with a 422. Enforcement of existing viewers is unchanged (a @@ -36,8 +50,9 @@ assists people when migrating to a new version. read: `PUT /api/v1/dashboard/<pk>`, `POST /api/v1/dashboard/` and `POST /api/v1/dashboard/<id_or_slug>/copy/`. The error names the refused chart IDs and nothing is saved. Charts already on the dashboard, archived ones - included, are not checked, nor are a copy's source charts. Remove the tile - from the layout, or get access to the chart, and save again. + included, are not checked. A copy's source charts are checked too (see the + `VIEWER_PROMISCUOUS_MODE` entry above). Remove the tile from the layout, or + get access to the chart, and save again. - With a Redis Sentinel coordination backend (`DISTRIBUTED_COORDINATION_CONFIG` using `RedisSentinelCache`), coordination commands now honor `CACHE_REDIS_DB` and diff --git a/docs/admin_docs/security/security.mdx b/docs/admin_docs/security/security.mdx index 0d9feb9757c..9a88fc6aaf9 100644 --- a/docs/admin_docs/security/security.mdx +++ b/docs/admin_docs/security/security.mdx @@ -324,8 +324,15 @@ going forward; the implicit fallback may be deprecated and removed in a later ma **Important considerations:** - Viewer access uses normal dataset checks unless `VIEWER_PROMISCUOUS_MODE` is enabled -- With `VIEWER_PROMISCUOUS_MODE`, dashboard viewer access can bypass dataset-level checks for - charts and datasets in that dashboard +- With `VIEWER_PROMISCUOUS_MODE`, the listed viewers of a published dashboard can read its + charts and their datasets while viewing that dashboard, without dataset-level permissions, + as with the legacy `DASHBOARD_RBAC`. The grant stays on the dashboard: it doesn't give + access to the charts or datasets elsewhere (for example in Explore or SQL Lab), and it + doesn't extend to editors, who need regular access to the data. Likewise, the listed viewers + of a chart can load that chart's data, and only that chart's, without dataset-level + permissions; the chart's editors need regular access. Because editors control the viewer + list, they can share the data with anyone they add as a viewer. Enable it only if that is + acceptable for every dashboard and chart in the deployment. - Dashboards and charts without assigned viewers fall back to dataset-based access - The dashboard must still be published to be visible diff --git a/superset/commands/dashboard/update.py b/superset/commands/dashboard/update.py index 14afdc256cf..60753019b63 100644 --- a/superset/commands/dashboard/update.py +++ b/superset/commands/dashboard/update.py @@ -180,8 +180,8 @@ class UpdateDashboardCommand(UpdateMixin, BaseCommand): self._validate_layout_chart_access() def _validate_layout_chart_access(self) -> None: - """Refuse a layout chart the caller cannot read before ``run`` - deactivates reports and emails their owners.""" + """Refuse a layout chart or a new native-filter target the caller cannot + read before ``run`` deactivates reports and emails their owners.""" assert self._model is not None json_metadata: str | None positions: object @@ -191,6 +191,10 @@ class UpdateDashboardCommand(UpdateMixin, BaseCommand): positions := metadata.get("positions"), dict ): DashboardDAO.validate_layout_chart_access(self._model, positions) + if isinstance(metadata, dict) and "native_filter_configuration" in metadata: + DashboardDAO.validate_native_filter_targets( + self._model, metadata["native_filter_configuration"] + ) @staticmethod def _send_deactivated_report_email( diff --git a/superset/config.py b/superset/config.py index 7ba79599647..76c4453aae7 100644 --- a/superset/config.py +++ b/superset/config.py @@ -3206,8 +3206,13 @@ class ExtraRelatedQueryFilters(TypedDict, total=False): EXTRA_RELATED_QUERY_FILTERS: ExtraRelatedQueryFilters = {} -# When True, viewers of a dashboard/chart bypass dataset-level RBAC checks. -# Only effective when ENABLE_VIEWERS is on. +# When True, the listed viewers of a published dashboard may read its member +# charts and their datasets on requests bound to that dashboard, and the listed +# viewers of a chart may read that chart's data, without dataset-level RBAC (the +# legacy DASHBOARD_RBAC model). Editors keep their regular access only, but +# control the viewer list. Only effective when +# ENABLE_VIEWERS is on. This deliberately relaxes the security model; see +# SECURITY.md. VIEWER_PROMISCUOUS_MODE = False # Default Subject types shown in editor/viewer/subject pickers. diff --git a/superset/daos/dashboard.py b/superset/daos/dashboard.py index 55ac543a96a..e7b9fbd0474 100644 --- a/superset/daos/dashboard.py +++ b/superset/daos/dashboard.py @@ -153,6 +153,100 @@ def _raise_for_unreadable_new_charts( ) +def _native_filter_targets(configuration: Any) -> set[tuple[int, str]]: + """The ``(datasource id, type)`` pairs a native-filter configuration targets.""" + targets: set[tuple[int, str]] = set() + if not isinstance(configuration, list): + return targets + for fltr in configuration: + if not isinstance(fltr, dict): + continue + for target in fltr.get("targets") or []: + if not isinstance(target, dict): + continue + try: + datasource_id = int(target["datasetId"]) + except (KeyError, TypeError, ValueError): + continue + targets.add((datasource_id, str(target.get("datasourceType") or "table"))) + return targets + + +def _raise_for_unreadable_new_filter_targets( + configuration: Any, previous_configuration: Any +) -> None: + """Refuse native filters that newly target a datasource the caller can't read. + + The ``VIEWER_PROMISCUOUS_MODE`` grant lets a dashboard's viewers query its + filter targets, so, as with charts in the layout, a filter must not be a way + to attach a datasource the caller has no access to. Targets the dashboard + already had are accepted as is, so a save never fails over a filter it + doesn't change; a target that doesn't resolve to a datasource holds no data + and is skipped. + """ + # pylint: disable=import-outside-toplevel + from superset.daos.datasource import DatasourceDAO + from superset.daos.exceptions import ( + DatasourceNotFound, + DatasourceTypeNotSupportedError, + DatasourceValueIsIncorrect, + ) + + new_targets = _native_filter_targets(configuration) - _native_filter_targets( + previous_configuration + ) + if not new_targets or security_manager.is_admin(): + return + denied: list[int] = [] + for datasource_id, datasource_type in sorted(new_targets): + try: + datasource = DatasourceDAO.get_datasource(datasource_type, datasource_id) + except ( + DatasourceNotFound, + DatasourceTypeNotSupportedError, + DatasourceValueIsIncorrect, + ): + continue + if not security_manager.can_access_datasource(datasource): + denied.append(datasource_id) + if denied: + raise DashboardLayoutInvalidError( + exceptions=[ + ValidationError( + "The native filters reference datasets that are not " + "available: " + ", ".join(str(i) for i in denied), + field_name="native_filter_configuration", + ) + ] + ) + + +def _raise_for_unreadable_copy_content( + original_dash: Dashboard, data: dict[str, Any], metadata: dict[str, Any] +) -> None: + """Refuse a copy that carries a source chart or native-filter target the + caller cannot read. + + The copy (and any cloned charts) is the caller's, so it would keep them + after the caller loses access to the source: whatever it carries over takes + access in its own right. A copy that duplicates charts, or has no layout, + carries all of the source's charts; a layout copy carries the source charts + its layout places. + """ + if not data.get("replace_metadata", False): + _raise_for_unreadable_new_filter_targets( + original_dash.params_dict.get("native_filter_configuration"), None + ) + positions: object = metadata.get("positions") + if data.get("duplicate_slices") or positions is None: + _raise_for_unreadable_new_charts(list(original_dash.slices), set()) + elif isinstance(positions, dict): + layout_ids: set[Any] = set(_layout_chart_ids(positions)) + _raise_for_unreadable_new_charts( + [slc for slc in original_dash.slices if slc.id in layout_ids], set() + ) + + class DashboardDAO(BaseDAO[Dashboard]): base_filter = DashboardAccessFilter # Column used by MCP tools for title-based identifier fallback, so a @@ -449,6 +543,20 @@ class DashboardDAO(BaseDAO[Dashboard]): ) _raise_for_unreadable_new_charts(charts, _member_chart_ids(dashboard.id)) + @staticmethod + def validate_native_filter_targets( + dashboard: Dashboard, configuration: Any + ) -> None: + """Refuse *configuration* if it newly targets a datasource the caller + cannot read. + + ``set_dash_metadata`` runs the same check; this lets a command refuse + the filters before any of its own side effects. + """ + _raise_for_unreadable_new_filter_targets( + configuration, dashboard.params_dict.get("native_filter_configuration") + ) + @staticmethod def set_dash_metadata( # noqa: C901 dashboard: Dashboard, @@ -473,6 +581,11 @@ class DashboardDAO(BaseDAO[Dashboard]): # reach ``dashboard.json_metadata`` -- any other field edited via # the Advanced JSON editor would silently revert to its stored # value on save (sadpandajoe, #42142). + if "native_filter_configuration" in data: + _raise_for_unreadable_new_filter_targets( + data["native_filter_configuration"], + md.get("native_filter_configuration"), + ) md.update( {k: v for k, v in data.items() if k not in _SET_DASH_METADATA_SPECIAL_KEYS} ) @@ -773,6 +886,8 @@ class DashboardDAO(BaseDAO[Dashboard]): ) -> Dashboard: if not security_manager.is_editor(original_dash): raise DashboardForbiddenError() + metadata = json.loads(data["json_metadata"]) + _raise_for_unreadable_copy_content(original_dash, data, metadata) dash = Dashboard() # The copied dashboard and every chart cloned below share one creator, @@ -794,7 +909,6 @@ class DashboardDAO(BaseDAO[Dashboard]): dash.dashboard_title = data["dashboard_title"] dash.css = data.get("css") - metadata = json.loads(data["json_metadata"]) old_to_new_slice_ids: dict[int, int] = {} if data.get("duplicate_slices"): # Duplicating slices as well, mapping old ids to new ones @@ -823,11 +937,9 @@ class DashboardDAO(BaseDAO[Dashboard]): dash, metadata, old_to_new_slice_ids, - allowed_chart_ids=( - set(old_to_new_slice_ids.values()) - if old_to_new_slice_ids - else _member_chart_ids(original_dash.id) - ), + # Clones are new charts the caller edits, whose sources were checked + # above, as were a layout copy's source charts. + allowed_chart_ids=set(old_to_new_slice_ids.values()), ) db.session.add(dash) # Flush so the returned dashboard always has a real, persisted @@ -915,6 +1027,9 @@ class DashboardDAO(BaseDAO[Dashboard]): if filter_id in filter_map ] + _raise_for_unreadable_new_filter_targets( + updated_configuration, native_filter_configuration + ) metadata["native_filter_configuration"] = updated_configuration dashboard.json_metadata = json.dumps(metadata) diff --git a/superset/dashboards/api.py b/superset/dashboards/api.py index c493776304a..d15d1c82125 100644 --- a/superset/dashboards/api.py +++ b/superset/dashboards/api.py @@ -710,10 +710,11 @@ class DashboardRestApi( # charts sub-resources. The check reads each chart's editors and # viewers, so load them for the whole set first. DashboardDAO.prefetch_chart_access(dash) + dashboard_grant = security_manager.has_promiscuous_dashboard_access(dash) result["charts"] = [ slc.chart for slc in dash.slices - if security_manager.can_access_chart(slc) + if dashboard_grant or security_manager.can_access_chart(slc) ] if current_app.config.get("EXTRA_EDITORS_RESOLVER"): result["extra_editors"] = get_extra_editor_subject_ids(dash) @@ -769,9 +770,16 @@ class DashboardRestApi( $ref: '#/components/responses/404' """ try: + # Every dataset here belongs to the dashboard, so a promiscuous + # viewer of it may read them all. + dashboard_grant = security_manager.has_promiscuous_dashboard_access( + DashboardDAO.get_by_id_or_slug(id_or_slug) + ) datasets = DashboardDAO.get_datasets_for_dashboard(id_or_slug) result = [ - self._serialize_dashboard_dataset(datasource, payload) + self._serialize_dashboard_dataset( + datasource, payload, dashboard_grant=dashboard_grant + ) for datasource, payload in datasets ] return self.response(200, result=result) @@ -779,23 +787,37 @@ class DashboardRestApi( raise DatasetValidationError(err) from err def _serialize_dashboard_dataset( - self, datasource: Any, payload: dict[str, Any] + self, + datasource: Any, + payload: dict[str, Any], + *, + dashboard_grant: bool = False, ) -> dict[str, Any]: - """Dump a member dataset, narrowed when the caller cannot access it.""" + """Dump a member dataset, narrowed when the caller cannot access it. + + :param dashboard_grant: Whether the dashboard grants its member + datasets to the caller (``VIEWER_PROMISCUOUS_MODE``) + """ serialized = self.dashboard_dataset_schema.dump(payload) if isinstance(datasource, SemanticView): # Redux keys dashboard datasets by Slice.form_data["datasource"], # whereas SemanticView.uid is the provider's independent identity. serialized["uid"] = f"{datasource.id}__{datasource.type}" - if not security_manager.can_access_datasource(datasource): + if not (dashboard_grant or security_manager.can_access_datasource(datasource)): for key in DASHBOARD_DATASET_INACCESSIBLE_FIELDS: serialized.pop(key, None) return serialized - def _serialize_dashboard_chart(self, chart: Any) -> dict[str, Any]: - """Dump a member chart, narrowed when the caller cannot access it.""" + def _serialize_dashboard_chart( + self, chart: Any, *, dashboard_grant: bool = False + ) -> dict[str, Any]: + """Dump a member chart, narrowed when the caller cannot access it. + + :param dashboard_grant: Whether the dashboard grants its member charts + to the caller (``VIEWER_PROMISCUOUS_MODE``) + """ serialized = self.chart_entity_response_schema.dump(chart) - if not security_manager.can_access_chart(chart): + if not (dashboard_grant or security_manager.can_access_chart(chart)): serialized.pop("form_data", None) return serialized @@ -902,7 +924,13 @@ class DashboardRestApi( """ try: charts = DashboardDAO.get_charts_for_dashboard(id_or_slug) - result = [self._serialize_dashboard_chart(chart) for chart in charts] + dashboard_grant = security_manager.has_promiscuous_dashboard_access( + DashboardDAO.get_by_id_or_slug(id_or_slug) + ) + result = [ + self._serialize_dashboard_chart(chart, dashboard_grant=dashboard_grant) + for chart in charts + ] return self.response(200, result=result) except DashboardAccessDeniedError: return self.response_403() diff --git a/superset/security/manager.py b/superset/security/manager.py index 5244ec7fa42..e26e1ea5466 100644 --- a/superset/security/manager.py +++ b/superset/security/manager.py @@ -2587,12 +2587,7 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods and self.is_guest_user() and self.has_guest_access(dashboard) ) - or ( - is_feature_enabled("ENABLE_VIEWERS") - and current_app.config.get("VIEWER_PROMISCUOUS_MODE") - and self.is_viewer(dashboard) - and dashboard.published - ) + or self.has_promiscuous_dashboard_access(dashboard) ) and dashboard.has_member_datasource(datasource): return True @@ -5456,25 +5451,21 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods self.raise_for_unsupported_guest_rls(datasource) def has_promiscuous_chart_access() -> bool: - if not ( + # Bound to the request's chart: the datasource must be its own. + return bool( form_data - and is_feature_enabled("ENABLE_VIEWERS") - and current_app.config.get("VIEWER_PROMISCUOUS_MODE") + and self._promiscuous_mode_applies() and (viewer_slice_id := form_data.get("slice_id")) and ( viewer_slc := self.session.query(Slice) .filter(Slice.id == viewer_slice_id) .one_or_none() ) - ): - return False - - if not _datasource_matches( - datasource, viewer_slc.datasource_id, viewer_slc.datasource_type - ): - return False - - return self.is_viewer(viewer_slc) or self.is_editor(viewer_slc) + and _datasource_matches( + datasource, viewer_slc.datasource_id, viewer_slc.datasource_type + ) + and self.has_promiscuous_chart_access(viewer_slc) + ) if not ( self.can_access_schema(datasource) @@ -5505,11 +5496,7 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods is_feature_enabled("EMBEDDED_SUPERSET") and self.is_guest_user() ) - or ( - is_feature_enabled("ENABLE_VIEWERS") - and current_app.config.get("VIEWER_PROMISCUOUS_MODE") - and self.is_viewer(dashboard_) - ) + or self.has_promiscuous_dashboard_access(dashboard_) ) and ( ( @@ -6666,19 +6653,10 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods :param resource: The dashboard, chart, etc. resource :returns: Whether the current user can view the resource """ - from superset.subjects.utils import get_user_subject_ids, subjects_from_roles - if self.is_admin(): return True - if user_id := get_user_id(): - subject_ids = set(get_user_subject_ids(user_id)) - elif self.is_guest_user(): - subject_ids = { - s.id for s in subjects_from_roles(getattr(g.user, "roles", [])) - } - else: - subject_ids = set() + subject_ids = self._current_subject_ids() if not subject_ids: return False @@ -6695,6 +6673,76 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods return False + def _current_subject_ids(self) -> set[int]: + """The subject IDs of the current user, or of the guest's roles.""" + from superset.subjects.utils import get_user_subject_ids, subjects_from_roles + + if user_id := get_user_id(): + return set(get_user_subject_ids(user_id)) + if self.is_guest_user(): + return {s.id for s in subjects_from_roles(getattr(g.user, "roles", []))} + return set() + + def is_listed_viewer(self, resource: Model) -> bool: + """ + Returns True if the current user is on the resource's viewer list, + directly or through a role or group. Unlike :meth:`is_viewer`, being an + editor of the resource doesn't count. + + :param resource: The dashboard, chart, etc. resource + :returns: Whether the current user is a listed viewer of the resource + """ + viewers: list[Any] = getattr(resource, "viewers", None) or [] + if not viewers: + return False + return bool(self._current_subject_ids() & {s.id for s in viewers}) + + def _promiscuous_mode_applies(self) -> bool: + """Whether ``VIEWER_PROMISCUOUS_MODE`` grants can apply to the current + user: both flags are on and the user isn't an embedded guest.""" + from superset import is_feature_enabled + + return bool( + is_feature_enabled("ENABLE_VIEWERS") + and current_app.config.get("VIEWER_PROMISCUOUS_MODE") + and not self.is_guest_user() + ) + + def has_promiscuous_dashboard_access(self, dashboard: "Dashboard") -> bool: + """ + Returns True if ``VIEWER_PROMISCUOUS_MODE`` grants the current user the + data behind ``dashboard``: its member charts and their datasources. + + The grant mirrors the legacy ``DASHBOARD_RBAC`` model. It covers listed + viewers of a published dashboard only (editors need regular access), + and callers apply it only to requests bound to this dashboard, so it + never becomes access to a chart or datasource outside it. Embedded + guests use their own token-scoped grant. + + :param dashboard: The dashboard + :returns: Whether the dashboard grants its data to the current user + """ + return bool( + self._promiscuous_mode_applies() + and dashboard.published + and self.is_listed_viewer(dashboard) + ) + + def has_promiscuous_chart_access(self, chart: "Slice") -> bool: + """ + Returns True if ``VIEWER_PROMISCUOUS_MODE`` grants the current user the + data behind ``chart``: its datasource. + + The chart counterpart of :meth:`has_promiscuous_dashboard_access`, on the + same terms: listed viewers of the chart only (editors need regular + access), never embedded guests, and callers apply it only to chart-data + requests naming this chart on its own datasource. + + :param chart: The chart + :returns: Whether the chart grants its data to the current user + """ + return self._promiscuous_mode_applies() and self.is_listed_viewer(chart) + def is_admin(self) -> bool: """ Returns True if the current user is an admin user, False otherwise. diff --git a/tests/integration_tests/dashboards/api_tests.py b/tests/integration_tests/dashboards/api_tests.py index ef6ec123ab6..01aafead79e 100644 --- a/tests/integration_tests/dashboards/api_tests.py +++ b/tests/integration_tests/dashboards/api_tests.py @@ -380,6 +380,62 @@ class TestDashboardApi(ApiEditorsTestCaseMixin, InsertChartMixin, SupersetTestCa # The identifying fields the dashboard needs to render are kept. assert {"id", "uid", "table_name", "type"} <= set(dataset) + @pytest.mark.usefixtures("create_dashboards") + @with_feature_flags(ENABLE_VIEWERS=True) + @with_config({"VIEWER_PROMISCUOUS_MODE": True}) + def test_get_dashboard_datasets_inherited_by_promiscuous_viewer(self): + """A viewer of a published dashboard inherits full dataset metadata under + VIEWER_PROMISCUOUS_MODE, without an explicit datasource grant.""" + from superset.subjects.utils import get_or_create_role_subject + + dashboard = self.dashboards[0] + dashboard.published = True + gamma_subject = get_or_create_role_subject( + security_manager.find_role("Gamma").id + ) + dashboard.viewers.append(gamma_subject) + db.session.commit() + try: + self.login(GAMMA_USERNAME) + uri = f"api/v1/dashboard/{dashboard.id}/datasets" + response = self.get_assert_metric(uri, "get_datasets") + assert response.status_code == 200 + data = json.loads(response.data.decode("utf-8")) + assert data["result"] + for dataset in data["result"]: + assert {"sql", "columns", "database"} <= set(dataset) + finally: + dashboard.viewers.remove(gamma_subject) + db.session.commit() + + @pytest.mark.usefixtures("create_dashboards") + @with_feature_flags(ENABLE_VIEWERS=True) + @with_config({"VIEWER_PROMISCUOUS_MODE": False}) + def test_get_dashboard_datasets_not_inherited_without_promiscuous_mode(self): + """A dashboard viewer without promiscuous mode still gets the dataset + definition narrowed, matching the no-inheritance behaviour.""" + from superset.subjects.utils import get_or_create_role_subject + + dashboard = self.dashboards[0] + dashboard.published = True + gamma_subject = get_or_create_role_subject( + security_manager.find_role("Gamma").id + ) + dashboard.viewers.append(gamma_subject) + db.session.commit() + try: + self.login(GAMMA_USERNAME) + uri = f"api/v1/dashboard/{dashboard.id}/datasets" + response = self.get_assert_metric(uri, "get_datasets") + assert response.status_code == 200 + data = json.loads(response.data.decode("utf-8")) + assert data["result"] + for dataset in data["result"]: + assert "sql" not in dataset + finally: + dashboard.viewers.remove(gamma_subject) + db.session.commit() + @pytest.mark.usefixtures("load_world_bank_dashboard_with_slices") @patch("superset.utils.log.logger") def test_get_dashboard_datasets_not_found(self, logger_mock): @@ -514,6 +570,108 @@ class TestDashboardApi(ApiEditorsTestCaseMixin, InsertChartMixin, SupersetTestCa assert "id" in chart assert "slice_name" in chart + @pytest.mark.usefixtures("create_dashboards") + @with_feature_flags(ENABLE_VIEWERS=True) + @with_config({"VIEWER_PROMISCUOUS_MODE": True}) + def test_get_dashboard_charts_inherited_by_promiscuous_viewer(self): + """A listed viewer of a published dashboard receives its charts' + form_data under VIEWER_PROMISCUOUS_MODE, without explicit chart grants, + so the dashboard can render. An editor who isn't a listed viewer gets no + such grant. The member charts carry an explicit viewer list that + excludes Gamma, so form_data can only come from the dashboard grant, + not from the charts' own dataset-based fallback.""" + from superset.subjects.utils import get_or_create_role_subject + + dashboard = self.dashboards[0] + dashboard.published = True + gamma_subject = get_or_create_role_subject( + security_manager.find_role("Gamma").id + ) + admin_subject = get_or_create_role_subject( + security_manager.find_role("Admin").id + ) + dashboard.editors.append(gamma_subject) + for slc in dashboard.slices: + slc.viewers.append(admin_subject) + db.session.commit() + uri = f"api/v1/dashboard/{dashboard.id}/charts" + try: + self.login(GAMMA_USERNAME) + response = self.get_assert_metric(uri, "get_charts") + assert response.status_code == 200 + data = json.loads(response.data.decode("utf-8")) + assert data["result"] + for chart in data["result"]: + assert "form_data" not in chart + + dashboard.viewers.append(gamma_subject) + db.session.commit() + response = self.get_assert_metric(uri, "get_charts") + assert response.status_code == 200 + data = json.loads(response.data.decode("utf-8")) + assert data["result"] + for chart in data["result"]: + assert "form_data" in chart + finally: + dashboard.editors.remove(gamma_subject) + if gamma_subject in dashboard.viewers: + dashboard.viewers.remove(gamma_subject) + for slc in dashboard.slices: + slc.viewers.remove(admin_subject) + db.session.commit() + + @pytest.mark.usefixtures("create_dashboards") + @with_feature_flags(ENABLE_VIEWERS=True) + @with_config({"VIEWER_PROMISCUOUS_MODE": False}) + def test_get_dashboard_charts_not_inherited_without_promiscuous_mode(self): + """A dashboard viewer without promiscuous mode can still open the + dashboard, but its inaccessible charts keep form_data stripped.""" + from superset.subjects.utils import get_or_create_role_subject + + dashboard = self.dashboards[0] + dashboard.published = True + gamma_subject = get_or_create_role_subject( + security_manager.find_role("Gamma").id + ) + dashboard.viewers.append(gamma_subject) + db.session.commit() + try: + self.login(GAMMA_USERNAME) + uri = f"api/v1/dashboard/{dashboard.id}/charts" + response = self.get_assert_metric(uri, "get_charts") + assert response.status_code == 200 + data = json.loads(response.data.decode("utf-8")) + assert data["result"] + for chart in data["result"]: + assert "form_data" not in chart + finally: + dashboard.viewers.remove(gamma_subject) + db.session.commit() + + @pytest.mark.usefixtures("create_dashboards") + @with_feature_flags(ENABLE_VIEWERS=True) + @with_config({"VIEWER_PROMISCUOUS_MODE": True}) + def test_get_dashboard_charts_unpublished_denies_viewer(self): + """A viewer of an *unpublished* dashboard is denied outright — promiscuous + inheritance never applies, so no chart form_data leaks.""" + from superset.subjects.utils import get_or_create_role_subject + + dashboard = self.dashboards[0] + dashboard.published = False + gamma_subject = get_or_create_role_subject( + security_manager.find_role("Gamma").id + ) + dashboard.viewers.append(gamma_subject) + db.session.commit() + try: + self.login(GAMMA_USERNAME) + uri = f"api/v1/dashboard/{dashboard.id}/charts" + response = self.get_assert_metric(uri, "get_charts") + assert response.status_code in (403, 404) + finally: + dashboard.viewers.remove(gamma_subject) + db.session.commit() + @pytest.mark.usefixtures("create_dashboards") def test_get_dashboard_charts_by_slug(self): """ diff --git a/tests/unit_tests/dao/dashboard_test.py b/tests/unit_tests/dao/dashboard_test.py index c4a02f705b6..894e6b1b3f3 100644 --- a/tests/unit_tests/dao/dashboard_test.py +++ b/tests/unit_tests/dao/dashboard_test.py @@ -634,6 +634,8 @@ def test_copy_dashboard_duplicate_slices_remaps_native_filters( with ( patch.object(security_manager, "is_editor", return_value=True), + patch.object(security_manager, "can_access_chart", return_value=True), + patch.object(security_manager, "is_admin", return_value=False), patch("superset.daos.dashboard.g") as mock_g, ): mock_g.user = None @@ -694,6 +696,8 @@ def test_copy_dashboard_handles_dividers_and_unscoped_filters( with ( patch.object(security_manager, "is_editor", return_value=True), + patch.object(security_manager, "can_access_chart", return_value=True), + patch.object(security_manager, "is_admin", return_value=False), patch("superset.daos.dashboard.g") as mock_g, ): mock_g.user = None @@ -759,6 +763,8 @@ def test_copy_dashboard_remaps_cross_filters_and_chart_configuration( with ( patch.object(security_manager, "is_editor", return_value=True), + patch.object(security_manager, "can_access_chart", return_value=True), + patch.object(security_manager, "is_admin", return_value=False), patch("superset.daos.dashboard.g") as mock_g, ): mock_g.user = None @@ -917,6 +923,8 @@ def test_issue_44983_consolidated_evidence_gate(session: Session) -> None: with ( patch.object(security_manager, "is_editor", return_value=True), + patch.object(security_manager, "can_access_chart", return_value=True), + patch.object(security_manager, "is_admin", return_value=False), patch("superset.daos.dashboard.g") as mock_g, ): mock_g.user = None @@ -1067,6 +1075,8 @@ def test_copy_dashboard_does_not_double_remap_overlapping_ids( with ( patch.object(security_manager, "is_editor", return_value=True), + patch.object(security_manager, "can_access_chart", return_value=True), + patch.object(security_manager, "is_admin", return_value=False), patch("superset.daos.dashboard.g") as mock_g, ): mock_g.user = None @@ -1196,11 +1206,15 @@ def test_set_dash_metadata_accepts_existing_members_the_caller_cannot_read( assert {chart.id for chart in dashboard.slices} == {chart1.id, chart2.id} -def test_copy_dashboard_accepts_the_source_dashboards_charts( +def test_copy_dashboard_refuses_unreadable_source_charts( session: Session, ) -> None: - """A copy keeps the source dashboard's charts even when the caller can't - read them, as the source dashboard already had them.""" + """A copy is the caller's and keeps the source dashboard's charts, so it + is refused when the caller can't read them in their own right.""" + import pytest + + from superset.commands.dashboard.exceptions import DashboardLayoutInvalidError + dashboard, (chart1, chart2) = _make_dashboard_with_slices(session) copy_data = { "dashboard_title": "copied_dash", @@ -1214,9 +1228,15 @@ def test_copy_dashboard_accepts_the_source_dashboards_charts( patch("superset.daos.dashboard.g") as mock_g, ): mock_g.user = None - copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data) - - assert {chart.id for chart in copied_dash.slices} == {chart1.id, chart2.id} + with pytest.raises(DashboardLayoutInvalidError) as excinfo: + DashboardDAO.copy_dashboard(dashboard, copy_data) + + refused: str = ", ".join(str(i) for i in sorted([chart1.id, chart2.id])) + assert excinfo.value.normalized_messages() == { + "json_metadata": [ + f"The layout references charts that are not available: {refused}" + ] + } def test_update_command_refuses_an_unreadable_layout_chart_before_side_effects( diff --git a/tests/unit_tests/security/typed_datasource_access_test.py b/tests/unit_tests/security/typed_datasource_access_test.py index daa17a1233e..86c598d310b 100644 --- a/tests/unit_tests/security/typed_datasource_access_test.py +++ b/tests/unit_tests/security/typed_datasource_access_test.py @@ -73,6 +73,8 @@ def manager(app_context: None, mocker: MockerFixture) -> SupersetSecurityManager mocker.patch.object(sm, "can_access", return_value=False) mocker.patch.object(sm, "is_editor", return_value=False) mocker.patch.object(sm, "is_viewer", return_value=True) + mocker.patch.object(sm, "has_promiscuous_dashboard_access", return_value=True) + mocker.patch.object(sm, "is_listed_viewer", return_value=True) mocker.patch.object(sm, "is_guest_user", return_value=False) mocker.patch.object(sm, "get_current_guest_user_if_guest", return_value=None) mocker.patch.object(sm, "can_access_dashboard", return_value=True) diff --git a/tests/unit_tests/subjects/test_creator_group_call_sites.py b/tests/unit_tests/subjects/test_creator_group_call_sites.py index 2d2f6b13080..32c128e9ba3 100644 --- a/tests/unit_tests/subjects/test_creator_group_call_sites.py +++ b/tests/unit_tests/subjects/test_creator_group_call_sites.py @@ -277,6 +277,10 @@ def test_dashboard_copy_dao_attaches_default_viewers(app_context) -> None: with ( patch.object(dashboard_dao.security_manager, "is_editor", return_value=True), + patch.object( + dashboard_dao.security_manager, "can_access_chart", return_value=True + ), + patch.object(dashboard_dao.security_manager, "is_admin", return_value=False), patch.object(dashboard_dao, "g", MagicMock(user=_user())), patch.object(dashboard_dao, "db"), patch.object(dashboard_dao.DashboardDAO, "set_dash_metadata"), @@ -313,6 +317,10 @@ def test_dashboard_copy_dao_attaches_default_viewers_to_cloned_charts( with ( patch.object(dashboard_dao.security_manager, "is_editor", return_value=True), + patch.object( + dashboard_dao.security_manager, "can_access_chart", return_value=True + ), + patch.object(dashboard_dao.security_manager, "is_admin", return_value=False), patch.object(dashboard_dao, "g", MagicMock(user=_user())), patch.object(dashboard_dao, "db"), patch.object(dashboard_dao.DashboardDAO, "set_dash_metadata"), @@ -483,6 +491,10 @@ def test_dashboard_copy_dao_resolves_creator_subjects_once(app_context) -> None: with ( patch.object(dashboard_dao.security_manager, "is_editor", return_value=True), + patch.object( + dashboard_dao.security_manager, "can_access_chart", return_value=True + ), + patch.object(dashboard_dao.security_manager, "is_admin", return_value=False), patch.object(dashboard_dao, "g", MagicMock(user=_user())), patch.object(dashboard_dao, "db"), patch.object(dashboard_dao.DashboardDAO, "set_dash_metadata"), diff --git a/tests/unit_tests/subjects/test_promiscuous_dashboard_access.py b/tests/unit_tests/subjects/test_promiscuous_dashboard_access.py new file mode 100644 index 00000000000..2ec02cfd582 --- /dev/null +++ b/tests/unit_tests/subjects/test_promiscuous_dashboard_access.py @@ -0,0 +1,487 @@ +# 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. + +"""``VIEWER_PROMISCUOUS_MODE`` dashboard grants, exercised against real rows. + +The grant follows the legacy ``DASHBOARD_RBAC`` model: listed viewers of a +published dashboard may read its member charts and their datasources, but only +on requests bound to that dashboard. Editors get nothing beyond their regular +access, and nothing outside a dashboard-bound request counts the grant, so it +can't become lasting access to a chart or datasource. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from types import SimpleNamespace +from typing import Any, Iterator + +import pytest +from flask import current_app, g +from sqlalchemy.orm.session import Session + + [email protected] +def inheritance_fixtures(app_context: None, session: Session) -> SimpleNamespace: + """Four dashboards covering the editor/viewer x published/draft matrix, plus + a chart on no dashboard that the editor edits and the viewer is listed on.""" + # pylint: disable=import-outside-toplevel + from flask_appbuilder.security.sqla.models import User + + from superset.connectors.sqla.models import SqlaTable + from superset.models.core import Database + from superset.models.dashboard import Dashboard + from superset.models.slice import Slice + from superset.subjects.models import Subject + from superset.subjects.types import SubjectType + + engine = session.get_bind() + Dashboard.metadata.create_all(engine) # pylint: disable=no-member + + database = Database(id=10, database_name="examples", sqlalchemy_uri="sqlite://") + session.add(database) + session.flush() + + table = SqlaTable( + id=1, + table_name="birth_names", + database_id=database.id, + perm="[examples].[birth_names](id:1)", + ) + session.add(table) + session.flush() + + def make_slice(name: str) -> Slice: + return Slice( + slice_name=name, + datasource_id=table.id, + datasource_type="table", + datasource_name="birth_names", + viz_type="table", + ) + + editor_published_slice = make_slice("editor published chart") + editor_draft_slice = make_slice("editor draft chart") + viewer_published_slice = make_slice("viewer published chart") + viewer_draft_slice = make_slice("viewer draft chart") + unrelated_slice = make_slice("unrelated chart") + session.add_all( + [ + editor_published_slice, + editor_draft_slice, + viewer_published_slice, + viewer_draft_slice, + unrelated_slice, + ] + ) + session.flush() + + def make_user(id_: int, username: str) -> User: + return User( + id=id_, + username=username, + first_name=username, + last_name="user", + email=f"{username}@example.com", + ) + + editor_user = make_user(1, "editor") + viewer_user = make_user(2, "viewer") + stranger_user = make_user(3, "stranger") + session.add_all([editor_user, viewer_user, stranger_user]) + session.flush() + + def make_subject(user: User) -> Subject: + subject = Subject( + label=user.username, + type=SubjectType.USER, + user_id=user.id, + ) + session.add(subject) + session.flush() + return subject + + editor_subject = make_subject(editor_user) + viewer_subject = make_subject(viewer_user) + + shared_slice = make_slice("shared chart") + shared_slice.editors = [editor_subject] + shared_slice.viewers = [viewer_subject] + session.add(shared_slice) + session.flush() + + editor_published = Dashboard( + dashboard_title="editor published", + slug="editor-published", + published=True, + slices=[editor_published_slice], + editors=[editor_subject], + ) + editor_draft = Dashboard( + dashboard_title="editor draft", + slug="editor-draft", + published=False, + slices=[editor_draft_slice], + editors=[editor_subject], + ) + viewer_published = Dashboard( + dashboard_title="viewer published", + slug="viewer-published", + published=True, + slices=[viewer_published_slice], + viewers=[viewer_subject], + ) + viewer_draft = Dashboard( + dashboard_title="viewer draft", + slug="viewer-draft", + published=False, + slices=[viewer_draft_slice], + viewers=[viewer_subject], + ) + unrelated = Dashboard( + dashboard_title="unrelated", + slug="unrelated", + published=True, + slices=[unrelated_slice], + ) + session.add_all( + [editor_published, editor_draft, viewer_published, viewer_draft, unrelated] + ) + session.flush() + + return SimpleNamespace( + session=session, + table=table, + editor_user=editor_user, + viewer_user=viewer_user, + stranger_user=stranger_user, + editor_published=editor_published, + editor_draft=editor_draft, + viewer_published=viewer_published, + viewer_draft=viewer_draft, + unrelated=unrelated, + editor_published_slice=editor_published_slice, + editor_draft_slice=editor_draft_slice, + viewer_published_slice=viewer_published_slice, + viewer_draft_slice=viewer_draft_slice, + unrelated_slice=unrelated_slice, + shared_slice=shared_slice, + ) + + [email protected] +def promiscuous(monkeypatch: pytest.MonkeyPatch) -> None: + """Enable the deployment flag and config the inheritance is gated on.""" + from superset import feature_flag_manager + + monkeypatch.setitem(current_app.config, "VIEWER_PROMISCUOUS_MODE", True) + flags = feature_flag_manager._feature_flags # pylint: disable=protected-access + monkeypatch.setitem(flags, "ENABLE_VIEWERS", True) + monkeypatch.setitem(flags, "EMBEDDED_SUPERSET", False) + + +@contextmanager +def acting_as(user: object) -> Iterator[None]: + """Run the block as ``user``, the way a request would.""" + previous = getattr(g, "user", None) + g.user = user + try: + yield + finally: + g.user = previous + + +def _chart_request(chart: Any, datasource: Any) -> Any: + """A chart-data request for ``chart`` on its own, outside any dashboard.""" + return SimpleNamespace(datasource=datasource, form_data={"slice_id": chart.id}) + + +def _bound_to(dashboard: Any, chart: Any, datasource: Any) -> Any: + """A chart-data request for ``chart`` as rendered on ``dashboard``.""" + return SimpleNamespace( + datasource=datasource, + form_data={"dashboardId": dashboard.id, "slice_id": chart.id}, + ) + + +def test_viewer_reads_a_published_dashboard_only_through_its_requests( + inheritance_fixtures: SimpleNamespace, promiscuous: None +) -> None: + """A listed viewer of a published dashboard reads its member charts' data + on requests bound to it, and nothing else: not the charts or the dataset + themselves, not a chart off the dashboard, not an unpublished dashboard. + A chart's listed viewer likewise reads that chart's data, and no other's.""" + from superset import security_manager + from superset.exceptions import SupersetSecurityException + + fx = inheritance_fixtures + with acting_as(fx.viewer_user): + assert security_manager.has_promiscuous_dashboard_access(fx.viewer_published) + assert not security_manager.has_promiscuous_dashboard_access(fx.viewer_draft) + + security_manager.raise_for_access( + query_context=_bound_to( + fx.viewer_published, fx.viewer_published_slice, fx.table + ) + ) + assert security_manager.can_drill_dataset_via_dashboard_access( + fx.table, fx.viewer_published + ) + + assert security_manager.has_promiscuous_chart_access(fx.shared_slice) + security_manager.raise_for_access( + query_context=_chart_request(fx.shared_slice, fx.table) + ) + + for denied in ( + {"query_context": _chart_request(fx.unrelated_slice, fx.table)}, + {"chart": fx.viewer_published_slice}, + {"datasource": fx.table}, + { + "query_context": _bound_to( + fx.viewer_published, fx.unrelated_slice, fx.table + ) + }, + { + "query_context": _bound_to( + fx.viewer_draft, fx.viewer_draft_slice, fx.table + ) + }, + ): + with pytest.raises(SupersetSecurityException): + security_manager.raise_for_access(**denied) + + +def test_editors_strangers_guests_and_flag_off_get_no_grant( + inheritance_fixtures: SimpleNamespace, + promiscuous: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Editors keep their regular access only, even on their own published + dashboard or chart; strangers and embedded guests get nothing; and the + grant is off without ``VIEWER_PROMISCUOUS_MODE``.""" + from superset import security_manager + from superset.exceptions import SupersetSecurityException + + fx = inheritance_fixtures + with acting_as(fx.editor_user): + assert not security_manager.has_promiscuous_dashboard_access( + fx.editor_published + ) + with pytest.raises(SupersetSecurityException): + security_manager.raise_for_access( + query_context=_bound_to( + fx.editor_published, fx.editor_published_slice, fx.table + ) + ) + assert not security_manager.can_drill_dataset_via_dashboard_access( + fx.table, fx.editor_published + ) + assert not security_manager.has_promiscuous_chart_access(fx.shared_slice) + with pytest.raises(SupersetSecurityException): + security_manager.raise_for_access( + query_context=_chart_request(fx.shared_slice, fx.table) + ) + + with acting_as(fx.stranger_user): + assert not security_manager.has_promiscuous_dashboard_access(fx.unrelated) + + with acting_as(fx.viewer_user): + monkeypatch.setattr(security_manager, "is_guest_user", lambda: True) + assert not security_manager.has_promiscuous_dashboard_access( + fx.viewer_published + ) + assert not security_manager.has_promiscuous_chart_access(fx.shared_slice) + monkeypatch.setattr(security_manager, "is_guest_user", lambda: False) + + monkeypatch.setitem(current_app.config, "VIEWER_PROMISCUOUS_MODE", False) + assert not security_manager.has_promiscuous_dashboard_access( + fx.viewer_published + ) + assert not security_manager.has_promiscuous_chart_access(fx.shared_slice) + + +def test_carrying_charts_or_filter_targets_onto_a_dashboard_takes_access( + inheritance_fixtures: SimpleNamespace, promiscuous: None +) -> None: + """The promiscuous grant lets a dashboard's viewers read its charts and + native-filter targets, and an editor can add themselves as a viewer. So + whatever a dashboard newly gains must be readable by the editor in their own + right: a copy's charts (with or without duplicating them) and filter + targets, and a new filter target saved through the dashboard or the filters + API. Targets the dashboard already had stay accepted.""" + from flask_appbuilder.security.sqla.models import Role + + from superset import security_manager + from superset.commands.dashboard.exceptions import DashboardLayoutInvalidError + from superset.connectors.sqla.models import SqlaTable + from superset.daos.dashboard import DashboardDAO + from superset.utils import json + + fx = inheritance_fixtures + unreadable = SqlaTable( + id=3, table_name="unreadable", database_id=10, perm="[examples].[x](id:3)" + ) + fx.session.add(unreadable) + fx.session.flush() + + def native_filters(datasource_id: int) -> list[dict[str, Any]]: + return [ + { + "id": "NATIVE_FILTER-1", + "targets": [{"datasetId": datasource_id, "column": {"name": "x"}}], + } + ] + + layout = { + "positions": { + "CHART-1": { + "type": "CHART", + "id": "CHART-1", + "children": [], + "meta": {"chartId": fx.editor_published_slice.id}, + } + } + } + + def copy_editor_published( + metadata: dict[str, Any] | None = None, **data: Any + ) -> Any: + return DashboardDAO.copy_dashboard( + fx.editor_published, + { + "dashboard_title": "copy", + "json_metadata": json.dumps(metadata or {}), + **data, + }, + ) + + with acting_as(fx.editor_user): + # Without a layout, with one, and duplicating the layout's charts. + for metadata, data in ( + (None, {}), + (layout, {}), + (layout, {"duplicate_slices": True}), + ): + with pytest.raises(DashboardLayoutInvalidError): + copy_editor_published(metadata, **data) + + grant = security_manager.add_permission_view_menu( + "datasource_access", fx.table.perm + ) + fx.editor_user.roles = [Role(name="dataset reader", permissions=[grant])] + fx.session.flush() + copy = copy_editor_published() + assert {chart.id for chart in copy.slices} == {fx.editor_published_slice.id} + + with pytest.raises(DashboardLayoutInvalidError) as refused: + DashboardDAO.set_dash_metadata( + fx.editor_published, + {"native_filter_configuration": native_filters(unreadable.id)}, + ) + assert str(unreadable.id) in str(refused.value.normalized_messages()) + with pytest.raises(DashboardLayoutInvalidError): + DashboardDAO.update_native_filters_config( + fx.editor_published, {"modified": native_filters(unreadable.id)} + ) + DashboardDAO.set_dash_metadata( + fx.editor_published, + {"native_filter_configuration": native_filters(fx.table.id)}, + ) + + # A target the dashboard already has is accepted on save, but a copy + # would carry it over, so the copy needs access to it. + fx.editor_published.json_metadata = json.dumps( + {"native_filter_configuration": native_filters(unreadable.id)} + ) + DashboardDAO.set_dash_metadata( + fx.editor_published, + {"native_filter_configuration": native_filters(unreadable.id)}, + ) + with pytest.raises(DashboardLayoutInvalidError): + copy_editor_published() + + +def test_operator_override_with_the_original_signature_keeps_working( + inheritance_fixtures: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +) -> None: + """Internal checks call ``raise_for_access`` with its original arguments, so + an operator override that has that signature and delegates to the stock + method still serves an ordinary chart check, even with viewers off.""" + from unittest.mock import patch + + from superset import feature_flag_manager, security_manager + from superset.security.manager import SupersetSecurityManager + + monkeypatch.setitem( + feature_flag_manager._feature_flags, # pylint: disable=protected-access + "ENABLE_VIEWERS", + False, + ) + stock = SupersetSecurityManager.raise_for_access + + def raise_for_access( # pylint: disable=too-many-arguments + self: SupersetSecurityManager, + dashboard: Any = None, + chart: Any = None, + database: Any = None, + datasource: Any = None, + query: Any = None, + query_context: Any = None, + table: Any = None, + sql: Any = None, + catalog: Any = None, + schema: Any = None, + template_params: Any = None, + force_dataset_match: bool = False, + allow_query_authorship_bypass: bool = False, + allow_editorship: bool = True, + ) -> None: + stock( + self, + dashboard=dashboard, + chart=chart, + database=database, + datasource=datasource, + query=query, + query_context=query_context, + table=table, + sql=sql, + catalog=catalog, + schema=schema, + template_params=template_params, + force_dataset_match=force_dataset_match, + allow_query_authorship_bypass=allow_query_authorship_bypass, + allow_editorship=allow_editorship, + ) + + from flask_appbuilder.security.sqla.models import Role + + fx = inheritance_fixtures + grant = security_manager.add_permission_view_menu( + "datasource_access", fx.table.perm + ) + fx.stranger_user.roles = [Role(name="dataset reader", permissions=[grant])] + fx.session.flush() + + with ( + acting_as(fx.stranger_user), + patch.object(SupersetSecurityManager, "raise_for_access", raise_for_access), + ): + # The chart has no viewers, so access comes from the dataset grant + # through the chart fallback. + assert security_manager.can_access_chart(fx.unrelated_slice) diff --git a/tests/unit_tests/subjects/test_raise_for_access.py b/tests/unit_tests/subjects/test_raise_for_access.py index cd70cd79d39..765ca7e575e 100644 --- a/tests/unit_tests/subjects/test_raise_for_access.py +++ b/tests/unit_tests/subjects/test_raise_for_access.py @@ -408,6 +408,7 @@ def test_raise_for_access_datasource_chart_viewer_promiscuous(app_context, monke patch.object(sm, "can_access", return_value=False), patch.object(sm, "is_editor", return_value=False), patch.object(sm, "is_viewer", return_value=True), + patch.object(sm, "is_listed_viewer", return_value=True), patch( "superset.is_feature_enabled", side_effect=lambda flag: flag == "ENABLE_VIEWERS", @@ -425,8 +426,11 @@ def test_raise_for_access_datasource_chart_viewer_promiscuous(app_context, monke ) -def test_raise_for_access_datasource_chart_editor_promiscuous(app_context, monkeypatch): - """Chart editor also bypasses datasource access via promiscuous mode.""" +def test_raise_for_access_datasource_chart_editor_gets_no_promiscuous_grant( + app_context, monkeypatch +): + """A chart editor who isn't a listed viewer gets no promiscuous grant: like + dashboard editors, they need regular access to the chart's datasource.""" sm = _make_sm() datasource: MagicMock = MagicMock(id=42, type="table") chart: MagicMock = MagicMock(datasource_id=42, datasource_type="table") @@ -441,6 +445,7 @@ def test_raise_for_access_datasource_chart_editor_promiscuous(app_context, monke patch.object(sm, "can_access", return_value=False), patch.object(sm, "is_editor", side_effect=lambda resource: resource is chart), patch.object(sm, "is_viewer", return_value=False), + patch.object(sm, "is_listed_viewer", return_value=False), patch( "superset.is_feature_enabled", side_effect=lambda flag: flag == "ENABLE_VIEWERS", @@ -448,6 +453,7 @@ def test_raise_for_access_datasource_chart_editor_promiscuous(app_context, monke patch.object( type(sm), "session", new_callable=PropertyMock, return_value=mock_session ), + pytest.raises(SupersetSecurityException), ): sm.raise_for_access( datasource=datasource,
