Skip to content

Commit 36f2cea

Browse files
sha174nclauderusackas
authored
fix(dashboard): gate bundle chart reassignment on per-object write permission (#46142)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: Evan Rusackas <evan@preset.io>
1 parent 92a0475 commit 36f2cea

2 files changed

Lines changed: 128 additions & 33 deletions

File tree

‎superset/commands/importers/v1/assets.py‎

Lines changed: 67 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from marshmallow import Schema
2020
from marshmallow.exceptions import ValidationError
2121

22-
from superset import db
22+
from superset import db, security_manager
2323
from superset.annotation_layers.schemas import ImportV1AnnotationLayerSchema
2424
from superset.charts.schemas import ImportV1ChartSchema
2525
from superset.commands.annotation_layer.importers.v1.utils import (
@@ -66,6 +66,7 @@
6666
SemanticReferenceError,
6767
)
6868
from superset.subjects.utils import get_default_viewers_for_current_user
69+
from superset.utils.core import get_user
6970
from superset.utils.decorators import on_error, transaction
7071

7172

@@ -82,6 +83,26 @@ def _on_import_error(ex: Exception) -> None:
8283
on_error(ex, catches=(Exception,), reraise=ImportFailedError)
8384

8485

86+
def _can_write_dashboard(dashboard: Dashboard) -> bool:
87+
"""Return whether the current caller may modify ``dashboard``.
88+
89+
Mirrors the per-object write check that ``import_dashboard`` applies before
90+
updating a dashboard: the caller needs the ``can_write`` grant on Dashboard
91+
and, for an already-persisted dashboard, must be able to access it and be an
92+
editor (or admin). Background / example-loader paths with no request user
93+
established trust at the command level and are allowed, matching
94+
``import_dashboard``'s own ``user is None`` short-circuit, and newly created
95+
dashboards pass because the caller is registered as their editor.
96+
"""
97+
if not security_manager.can_access("can_write", "Dashboard"):
98+
return False
99+
if get_user() is None:
100+
return True
101+
return security_manager.can_access_dashboard(dashboard) and (
102+
security_manager.is_editor(dashboard) or security_manager.is_admin()
103+
)
104+
105+
85106
class ImportAssetsCommand(BaseCommand):
86107
"""
87108
Command for importing databases, datasets, charts, dashboards and saved queries.
@@ -221,38 +242,51 @@ def _import( # noqa: C901
221242
)
222243

223244
# set ref in the dashboard_slices table
224-
# Use ORM-level reassignment instead of Core
225-
# delete()/insert() so SQLAlchemy-Continuum's M2M tracker
226-
# sees per-row changes through the ORM. Bulk DML via Core
227-
# would emit a malformed INSERT into
228-
# ``dashboard_slices_version`` (missing the composite-PK
229-
# columns) — see the parallel rewrite in
230-
# ``DatasetDAO.update_columns`` and the test-factory's
231-
# ``delete_dashboard_slices_associations`` for the same
232-
# reason.
233-
slice_ids: list[int] = []
234-
for uuid in find_chart_uuids(config["position"]):
235-
# Skip charts that weren't part of this import; ``continue``
236-
# (not ``break``) so a single missing/unresolved chart uuid
237-
# doesn't truncate the rest. ``find_chart_uuids`` returns a
238-
# set, so a ``break`` here would drop a non-deterministic
239-
# subset of the dashboard's charts.
240-
if uuid not in chart_ids:
241-
continue
242-
slice_ids.append(chart_ids[uuid])
243-
244-
dashboard.slices = (
245-
db.session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
246-
if slice_ids
247-
else []
248-
)
249-
# Flush eagerly so the M2M rows land in
250-
# ``dashboard_slices`` before any subsequent autoflush
251-
# fires an inner-flush event handler that would reset
252-
# the relationship change (cf. the SAWarning at
253-
# ``superset/models/helpers.py`` re. "attribute history
254-
# events accumulated ... have been reset").
255-
db.session.flush()
245+
#
246+
# Only reassign the chart associations when the caller is
247+
# permitted to write this dashboard. ``import_dashboard`` applies
248+
# a per-object write check and returns an *existing* dashboard
249+
# unchanged when the caller lacks that permission (no
250+
# ``can_write`` grant, or not an editor/admin of the dashboard);
251+
# rewriting ``dashboard.slices`` here regardless would modify an
252+
# existing dashboard's charts from the bundle position without
253+
# going through the same check. Newly created dashboards (the
254+
# caller is their editor) and dashboards the caller may edit are
255+
# unaffected.
256+
if _can_write_dashboard(dashboard):
257+
# Use ORM-level reassignment instead of Core
258+
# delete()/insert() so SQLAlchemy-Continuum's M2M tracker
259+
# sees per-row changes through the ORM. Bulk DML via Core
260+
# would emit a malformed INSERT into
261+
# ``dashboard_slices_version`` (missing the composite-PK
262+
# columns) — see the parallel rewrite in
263+
# ``DatasetDAO.update_columns`` and the test-factory's
264+
# ``delete_dashboard_slices_associations`` for the same
265+
# reason.
266+
slice_ids: list[int] = []
267+
for uuid in find_chart_uuids(config["position"]):
268+
# Skip charts that weren't part of this import;
269+
# ``continue`` (not ``break``) so a single
270+
# missing/unresolved chart uuid doesn't truncate the
271+
# rest. ``find_chart_uuids`` returns a set, so a
272+
# ``break`` here would drop a non-deterministic subset of
273+
# the dashboard's charts.
274+
if uuid not in chart_ids:
275+
continue
276+
slice_ids.append(chart_ids[uuid])
277+
278+
dashboard.slices = (
279+
db.session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
280+
if slice_ids
281+
else []
282+
)
283+
# Flush eagerly so the M2M rows land in
284+
# ``dashboard_slices`` before any subsequent autoflush
285+
# fires an inner-flush event handler that would reset
286+
# the relationship change (cf. the SAWarning at
287+
# ``superset/models/helpers.py`` re. "attribute history
288+
# events accumulated ... have been reset").
289+
db.session.flush()
256290

257291
# Handle tags using import_tag function
258292
if feature_flag_manager.is_feature_enabled("TAGGING_SYSTEM"):

‎tests/unit_tests/commands/importers/v1/assets_test.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,67 @@ def test_prevent_overwrite_queries_only_bundle_uuids(
553553
assert exceptions == []
554554

555555

556+
def test_import_without_write_permission_keeps_existing_dashboard_charts(
557+
mocker: MockerFixture, session: Session
558+
) -> None:
559+
"""
560+
An import performed without write permission must not modify an existing
561+
dashboard's charts.
562+
563+
``import_dashboard`` returns an existing dashboard unchanged when the caller
564+
cannot write it; the bulk-assets chart-association rewrite must honor the
565+
same per-object write check rather than reassigning the dashboard's charts
566+
from the bundle position regardless of permission.
567+
"""
568+
from superset import db, security_manager
569+
from superset.commands.importers.v1.assets import ImportAssetsCommand
570+
from superset.models.dashboard import Dashboard, dashboard_slices
571+
from superset.models.slice import Slice
572+
573+
engine = db.session.get_bind()
574+
Slice.metadata.create_all(engine) # pylint: disable=no-member
575+
576+
base_configs = {
577+
**copy.deepcopy(databases_config),
578+
**copy.deepcopy(datasets_config),
579+
**copy.deepcopy(charts_config_1),
580+
**copy.deepcopy(dashboards_config_1),
581+
}
582+
583+
# Seed an existing dashboard (two charts) as a privileged caller.
584+
can_access = mocker.patch.object(security_manager, "can_access", return_value=True)
585+
ImportAssetsCommand._import(base_configs)
586+
# Two separate transactions, as production does (``run()`` is wrapped in
587+
# ``@transaction``); also avoids the dashboard_slices_version collision the
588+
# other mutation tests hit when add + remove share a Continuum transaction.
589+
db.session.commit()
590+
591+
dashboard = (
592+
db.session.query(Dashboard)
593+
.filter_by(uuid="c7bc10f4-6a2d-7569-caae-bbc91864ee11")
594+
.one()
595+
)
596+
dashboard_id = dashboard.id
597+
original_slice_ids = {s.id for s in dashboard.slices}
598+
assert len(original_slice_ids) == 2
599+
600+
# A caller WITHOUT dashboard write permission imports a sparse bundle whose
601+
# dashboard position drops one chart. The existing dashboard's charts must
602+
# be left untouched.
603+
can_access.return_value = False
604+
sparse_bundle = copy.deepcopy(dashboards_config_2) # same uuid, one chart
605+
ImportAssetsCommand._import(sparse_bundle, sparse=True)
606+
607+
remaining_slice_ids = set(
608+
db.session.scalars(
609+
select(dashboard_slices.c.slice_id).where(
610+
dashboard_slices.c.dashboard_id == dashboard_id
611+
)
612+
).all()
613+
)
614+
assert remaining_slice_ids == original_slice_ids
615+
616+
556617
def test_import_removes_dashboard_charts(
557618
mocker: MockerFixture, session: Session
558619
) -> None:

0 commit comments

Comments
 (0)