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 259c9e51bed7a9a1fbf3649cd724903efcb996b9
Author: Mehmet Salih Yavuz <[email protected]>
AuthorDate: Tue Nov 3 15:35:26 2026 +0300

    fix(security): reject new dashboard/chart viewers while ENABLE_VIEWERS is 
off (#45951)
    
    (cherry picked from commit 5aacca7b21b877a2d1ef808f9056232223dac593)
---
 UPDATING.md                                        |   6 +
 docs/static/feature-flags.json                     |   2 +-
 superset/commands/utils.py                         |  39 +++++-
 superset/config.py                                 |   5 +-
 superset/mcp_service/app.py                        |   2 +-
 .../dashboard/tool/manage_dashboard_roles.py       |  55 ++++++---
 superset/subjects/exceptions.py                    |  17 +++
 superset/translations/messages.pot                 |   8 +-
 .../dashboard/tool/test_manage_dashboard_roles.py  | 102 +++++++++++++++-
 .../subjects/test_creator_group_defaults.py        |   9 +-
 tests/unit_tests/subjects/test_utils.py            | 135 ++++++++++++++++++++-
 11 files changed, 346 insertions(+), 34 deletions(-)

diff --git a/UPDATING.md b/UPDATING.md
index bfc7791c6d1..86ac4cc19aa 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -26,6 +26,12 @@ assists people when migrating to a new version.
 
 ## 7.0.0
 
+- 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
+  non-empty viewers list restricts access regardless of the flag), and removing
+  viewers remains possible so stale assignments can be cleared.
+
 - Saving a dashboard layout returns HTTP 422 if it adds a chart the user cannot
   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
diff --git a/docs/static/feature-flags.json b/docs/static/feature-flags.json
index 7a679395464..90691fd827b 100644
--- a/docs/static/feature-flags.json
+++ b/docs/static/feature-flags.json
@@ -193,7 +193,7 @@
         "name": "ENABLE_VIEWERS",
         "default": false,
         "lifecycle": "testing",
-        "description": "Subject-based viewer access control for dashboards and 
charts. When enabled, resources can have explicit viewer Subject assignments.",
+        "description": "Subject-based viewer access control for dashboards and 
charts. When enabled, viewers can be assigned through the UI and API. A 
non-empty viewers list is always enforced, even when this flag is off (legacy 
DASHBOARD_RBAC roles are migrated into viewers); turning the flag off only 
blocks adding new viewers, while existing ones can still be removed.",
         "category": "security"
       },
       {
diff --git a/superset/commands/utils.py b/superset/commands/utils.py
index f020c1d103a..7caf60c82f6 100644
--- a/superset/commands/utils.py
+++ b/superset/commands/utils.py
@@ -23,7 +23,7 @@ from flask import current_app, has_app_context
 from flask_appbuilder.models.sqla import Model
 from marshmallow import ValidationError
 
-from superset import security_manager
+from superset import is_feature_enabled, security_manager
 from superset.commands.exceptions import (
     DatasourceNotFoundValidationError,
     TagForbiddenError,
@@ -33,7 +33,10 @@ from superset.daos.datasource import DatasourceDAO
 from superset.daos.exceptions import DatasourceNotFound
 from superset.daos.tag import TagDAO
 from superset.exceptions import SupersetSecurityException
-from superset.subjects.exceptions import SubjectsNotFoundValidationError
+from superset.subjects.exceptions import (
+    SubjectsNotFoundValidationError,
+    ViewersDisabledValidationError,
+)
 from superset.subjects.models import Subject
 from superset.subjects.utils import (
     get_default_viewers_for_new_asset,
@@ -170,6 +173,29 @@ def compute_subject_list(
     )
 
 
+def raise_if_adding_viewers_while_disabled(
+    new_viewers: list[Subject],
+    current_viewers: list[Subject] | None = None,
+) -> None:
+    """
+    Reject viewer additions while ``ENABLE_VIEWERS`` is off.
+
+    Viewers are enforced whenever the relationship is non-empty, independent of
+    the flag, but the flag hides them from the UI. Allowing writes while it is
+    off lets an API client lock a dashboard or chart down in a way admins can
+    neither see nor undo in the UI. Removing viewers (or re-sending the current
+    list) remains allowed so stale assignments can always be cleared.
+
+    :raises ViewersDisabledValidationError: when the flag is off and
+        *new_viewers* contains a subject not already in *current_viewers*
+    """
+    if is_feature_enabled("ENABLE_VIEWERS"):
+        return
+    current_ids = {subject.id for subject in current_viewers or []}
+    if any(subject.id not in current_ids for subject in new_viewers):
+        raise ViewersDisabledValidationError()
+
+
 def populate_subjects(
     properties: dict[str, Any],
     exceptions: list[ValidationError],
@@ -197,11 +223,13 @@ def populate_subjects(
 
     if properties.get("viewers") is not None:
         try:
-            properties["viewers"] = populate_subject_list(
+            viewers = populate_subject_list(
                 properties["viewers"],
                 default_to_user=False,
                 field_name="viewers",
             )
+            raise_if_adding_viewers_while_disabled(viewers)
+            properties["viewers"] = viewers
         except ValidationError as ex:
             exceptions.append(ex)
     elif default_viewers := get_default_viewers_for_new_asset(get_user_id()):
@@ -233,11 +261,14 @@ def compute_subjects(
 
     if include_viewers and hasattr(model, "viewers"):
         try:
-            properties["viewers"] = compute_subject_list(
+            viewers = compute_subject_list(
                 model.viewers,
                 properties.get("viewers"),
                 field_name="viewers",
             )
+            if properties.get("viewers") is not None:
+                raise_if_adding_viewers_while_disabled(viewers, model.viewers)
+            properties["viewers"] = viewers
         except ValidationError as ex:
             exceptions.append(ex)
 
diff --git a/superset/config.py b/superset/config.py
index deaf7fe57c6..7ba79599647 100644
--- a/superset/config.py
+++ b/superset/config.py
@@ -872,7 +872,10 @@ DEFAULT_FEATURE_FLAGS: dict[str, bool] = {
     # @category: runtime_config
     "CSS_TEMPLATES": True,
     # Subject-based viewer access control for dashboards and charts.
-    # When enabled, resources can have explicit viewer Subject assignments.
+    # When enabled, viewers can be assigned through the UI and API. A non-empty
+    # viewers list is always enforced, even when this flag is off (legacy
+    # DASHBOARD_RBAC roles are migrated into viewers); turning the flag off 
only
+    # blocks adding new viewers, while existing ones can still be removed.
     # @lifecycle: testing
     # @category: security
     "ENABLE_VIEWERS": False,
diff --git a/superset/mcp_service/app.py b/superset/mcp_service/app.py
index 471936d8735..3371d07f39c 100644
--- a/superset/mcp_service/app.py
+++ b/superset/mcp_service/app.py
@@ -137,7 +137,7 @@ Dashboard Management:
 - remove_chart_from_dashboard: Remove a chart from an existing dashboard 
(requires write access)
 - restore_dashboard: Restore a soft-deleted dashboard from trash by ID/UUID 
(requires editor rights — owner or Admin; only applies to dashboards trashed 
under the SOFT_DELETE feature flag)
 - manage_dashboard_owners: Add/remove dashboard owners by explicit operation 
(requires write access; rejects changes that would leave zero owners)
-- manage_dashboard_roles: Add/remove dashboard access roles by explicit 
operation (requires write access; only affects access when ENABLE_VIEWERS is 
enabled)
+- manage_dashboard_roles: Add/remove dashboard access roles by explicit 
operation (requires write access; applies regardless of the ENABLE_VIEWERS 
flag, but roles can only be removed while it is disabled)
 - manage_dashboard_certification: Set or clear a dashboard's 
certified_by/certification_details badge (requires write access)
 
 Annotation Layers:
diff --git a/superset/mcp_service/dashboard/tool/manage_dashboard_roles.py 
b/superset/mcp_service/dashboard/tool/manage_dashboard_roles.py
index 0ae010c7497..ab5042dc92a 100644
--- a/superset/mcp_service/dashboard/tool/manage_dashboard_roles.py
+++ b/superset/mcp_service/dashboard/tool/manage_dashboard_roles.py
@@ -128,6 +128,32 @@ def _compute_new_role_ids(
     return current_role_ids, new_role_ids, None
 
 
+def _check_viewers_flag(
+    viewers_enabled: bool, current_role_ids: list[int], new_role_ids: list[int]
+) -> tuple[list[str], ManageDashboardRolesResponse | None]:
+    """Refuse role additions while ``ENABLE_VIEWERS`` is off; allow removals.
+
+    Only roles not already assigned count as additions, so re-adding an
+    assigned role stays a no-op, matching the REST update path.
+    """
+    if viewers_enabled:
+        return [], None
+    if set(new_role_ids) - set(current_role_ids):
+        return [], ManageDashboardRolesResponse(
+            viewers_enabled=False,
+            error=(
+                "The ENABLE_VIEWERS feature flag is disabled on this instance; 
"
+                "roles cannot be added to a dashboard until it is enabled. "
+                "Existing roles can still be removed."
+            ),
+        )
+    return [
+        "The ENABLE_VIEWERS feature flag is disabled on this instance; "
+        "dashboard access checks still restrict access to any nonempty "
+        "viewers list, so role removals take effect regardless."
+    ], None
+
+
 def _resolve_role_subjects(
     new_role_ids: list[int],
 ) -> tuple[list["Subject"], list[int]]:
@@ -171,12 +197,15 @@ def manage_dashboard_roles(
     Add or remove dashboard access roles with explicit operations.
 
     Dashboard access roles restrict who can view a dashboard to members of
-    the listed roles, on top of normal Superset permissions. An empty roles
-    list means "no role restriction" — the dashboard is visible per standard
-    permissions instead. This only takes effect when the ``ENABLE_VIEWERS``
-    feature flag is enabled; the response's ``viewers_enabled`` field
-    reports whether it is, and ``warnings`` notes when a change was applied
-    but has no live effect.
+    the listed roles, on top of normal Superset permissions. Removing every
+    role only restores standard permissions if no USER- or GROUP-type
+    viewers remain on the dashboard — ``raise_for_access`` restricts access
+    whenever the ``viewers`` list is nonempty, regardless of subject type.
+    This applies regardless of the ``ENABLE_VIEWERS`` feature flag. While the
+    flag is disabled, roles can only be removed: adding a role not already
+    assigned is rejected, since the UI offers no way to see or undo the
+    resulting restriction. The response's ``viewers_enabled`` field reports
+    the flag's state, and ``warnings`` notes when it is disabled.
 
     Roles are the ROLE-type entries in the dashboard's Subject-based
     ``viewers`` list. Any USER- or GROUP-type viewers already on the
@@ -218,14 +247,6 @@ def manage_dashboard_roles(
     assert dashboard is not None  # narrows for mypy
 
     viewers_enabled = is_feature_enabled("ENABLE_VIEWERS")
-    warnings: list[str] = []
-    if not viewers_enabled:
-        warnings.append(
-            "The ENABLE_VIEWERS feature flag is disabled on this instance; "
-            "dashboard viewers will be stored but have no effect on access "
-            "control until it is enabled."
-        )
-
     current_role_ids, new_role_ids, compute_error = _compute_new_role_ids(
         dashboard, request, viewers_enabled
     )
@@ -234,6 +255,12 @@ def manage_dashboard_roles(
     assert current_role_ids is not None  # narrows for mypy
     assert new_role_ids is not None  # narrows for mypy
 
+    warnings, flag_error = _check_viewers_flag(
+        viewers_enabled, current_role_ids, new_role_ids
+    )
+    if flag_error is not None:
+        return flag_error
+
     # No-op short-circuit: skip the DB write and, more importantly, the
     # full roles list in the response — mirrors manage_dashboard_owners.
     # The roles list is only sanctioned as confirmation of an actual change
diff --git a/superset/subjects/exceptions.py b/superset/subjects/exceptions.py
index ae770a143e0..14b63403846 100644
--- a/superset/subjects/exceptions.py
+++ b/superset/subjects/exceptions.py
@@ -23,3 +23,20 @@ class SubjectsNotFoundValidationError(ValidationError):
 
     def __init__(self, field_name: str = "subjects") -> None:
         super().__init__([_("Subjects are invalid")], field_name=field_name)
+
+
+class ViewersDisabledValidationError(ValidationError):
+    """Viewers cannot be added while ``ENABLE_VIEWERS`` is off."""
+
+    status = 422
+
+    def __init__(self, field_name: str = "viewers") -> None:
+        super().__init__(
+            [
+                _(
+                    "Viewers cannot be added while the ENABLE_VIEWERS feature "
+                    "flag is disabled"
+                )
+            ],
+            field_name=field_name,
+        )
diff --git a/superset/translations/messages.pot 
b/superset/translations/messages.pot
index 06ccbcc9117..294f9459745 100644
--- a/superset/translations/messages.pot
+++ b/superset/translations/messages.pot
@@ -16612,10 +16612,10 @@ msgstr ""
 msgid "Viewers"
 msgstr ""
 
-msgid ""
-"Viewers is a list of subjects who can view the dashboard. If no viewers "
-"are defined, the dashboard is accessible to all users with appropriate "
-"datasource permissions."
+msgid "Viewers cannot be added while the ENABLE_VIEWERS feature flag is 
disabled"
+msgstr ""
+
+msgid "Viewers is a list of subjects who can view the dashboard. If no viewers 
are defined, the dashboard is accessible to all users with appropriate 
datasource permissions."
 msgstr ""
 
 msgid "Viewport"
diff --git 
a/tests/unit_tests/mcp_service/dashboard/tool/test_manage_dashboard_roles.py 
b/tests/unit_tests/mcp_service/dashboard/tool/test_manage_dashboard_roles.py
index 5b09170972c..347d6213c4f 100644
--- a/tests/unit_tests/mcp_service/dashboard/tool/test_manage_dashboard_roles.py
+++ b/tests/unit_tests/mcp_service/dashboard/tool/test_manage_dashboard_roles.py
@@ -246,7 +246,7 @@ class TestManageDashboardRoles:
     @patch(DAO_GET)
     @patch("superset.extensions.db.session")
     @pytest.mark.asyncio
-    async def test_add_role_warns_when_flag_disabled(
+    async def test_add_role_rejected_when_flag_disabled(
         self,
         mock_session: Mock,
         mock_get: Mock,
@@ -254,10 +254,10 @@ class TestManageDashboardRoles:
         mock_flag: Mock,
         mcp_server: object,
     ) -> None:
-        new_subject = _mock_subject(200, 5, "Analyst")
+        """Viewers are enforced regardless of the flag, so adding roles while
+        it is off would restrict the dashboard with no UI to see or undo it."""
         dash = _mock_dashboard(viewers=[])
         mock_get.return_value = dash
-        mock_get_or_create.side_effect = _get_or_create_side_effect({5: 
new_subject})
 
         async with Client(mcp_server) as client:
             result = await client.call_tool(
@@ -267,8 +267,104 @@ class TestManageDashboardRoles:
 
         payload = json.loads(result.content[0].text)
         assert payload["viewers_enabled"] is False
+        assert "ENABLE_VIEWERS" in payload["error"]
+        mock_get_or_create.assert_not_called()
+        mock_session.commit.assert_not_called()
+        assert dash.viewers == []
+
+    @patch(IS_FEATURE_ENABLED, return_value=False)
+    @patch(GET_OR_CREATE_ROLE_SUBJECT)
+    @patch(DAO_GET)
+    @patch("superset.extensions.db.session")
+    @pytest.mark.asyncio
+    async def test_remove_role_allowed_when_flag_disabled(
+        self,
+        mock_session: Mock,
+        mock_get: Mock,
+        mock_get_or_create: Mock,
+        mock_flag: Mock,
+        mcp_server: object,
+    ) -> None:
+        """Stale role viewers can always be cleared, flag or not."""
+        remove = _mock_subject(201, 6, "Sales")
+        dash = _mock_dashboard(viewers=[remove])
+        mock_get.return_value = dash
+        mock_get_or_create.side_effect = _get_or_create_side_effect({})
+
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "manage_dashboard_roles",
+                {"request": {"identifier": 42, "remove_role_ids": [6]}},
+            )
+
+        payload = json.loads(result.content[0].text)
+        assert payload["viewers_enabled"] is False
+        assert payload["removed_role_ids"] == [6]
         assert any("ENABLE_VIEWERS" in w for w in payload["warnings"])
 
+    @patch(IS_FEATURE_ENABLED, return_value=False)
+    @patch(DAO_GET)
+    @patch("superset.extensions.db.session")
+    @pytest.mark.asyncio
+    async def test_readd_assigned_role_is_noop_when_flag_disabled(
+        self,
+        mock_session: Mock,
+        mock_get: Mock,
+        mock_flag: Mock,
+        mcp_server: object,
+    ) -> None:
+        """Re-adding an assigned role adds no viewer, so the flag allows it."""
+        dash = _mock_dashboard(viewers=[_mock_subject(200, 5, "Analyst")])
+        mock_get.return_value = dash
+
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "manage_dashboard_roles",
+                {"request": {"identifier": 42, "add_role_ids": [5]}},
+            )
+
+        payload = json.loads(result.content[0].text)
+        assert payload.get("error") is None
+        assert any("no effective change" in w.lower() for w in 
payload["warnings"])
+        mock_session.commit.assert_not_called()
+
+    @patch(IS_FEATURE_ENABLED, return_value=False)
+    @patch(GET_OR_CREATE_ROLE_SUBJECT)
+    @patch(DAO_GET)
+    @patch("superset.extensions.db.session")
+    @pytest.mark.asyncio
+    async def test_readd_assigned_with_removal_allowed_when_flag_disabled(
+        self,
+        mock_session: Mock,
+        mock_get: Mock,
+        mock_get_or_create: Mock,
+        mock_flag: Mock,
+        mcp_server: object,
+    ) -> None:
+        """A replace-style request that only keeps and drops roles still 
applies."""
+        keep = _mock_subject(200, 5, "Analyst")
+        remove = _mock_subject(201, 6, "Sales")
+        dash = _mock_dashboard(viewers=[keep, remove])
+        mock_get.return_value = dash
+        mock_get_or_create.side_effect = _get_or_create_side_effect({5: keep})
+
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "manage_dashboard_roles",
+                {
+                    "request": {
+                        "identifier": 42,
+                        "add_role_ids": [5],
+                        "remove_role_ids": [6],
+                    }
+                },
+            )
+
+        payload = json.loads(result.content[0].text)
+        assert payload.get("error") is None
+        assert payload["removed_role_ids"] == [6]
+        assert payload["added_role_ids"] == []
+
     @patch(IS_FEATURE_ENABLED, return_value=True)
     @patch(GET_OR_CREATE_ROLE_SUBJECT)
     @patch(DAO_GET)
diff --git a/tests/unit_tests/subjects/test_creator_group_defaults.py 
b/tests/unit_tests/subjects/test_creator_group_defaults.py
index a2951a473b6..e758cf60766 100644
--- a/tests/unit_tests/subjects/test_creator_group_defaults.py
+++ b/tests/unit_tests/subjects/test_creator_group_defaults.py
@@ -175,9 +175,12 @@ def 
test_explicit_viewers_are_not_replaced_by_creator_groups(
     mock_populate.side_effect = [[_group_subject(1)], chosen]
     properties: dict[str, Any] = {"viewers": [99]}
 
-    with patch(
-        "superset.subjects.utils._assigns_creator_groups_as_viewers",
-        return_value=True,
+    with (
+        patch(
+            "superset.subjects.utils._assigns_creator_groups_as_viewers",
+            return_value=True,
+        ),
+        patch("superset.commands.utils.is_feature_enabled", return_value=True),
     ):
         populate_subjects(properties, [])
 
diff --git a/tests/unit_tests/subjects/test_utils.py 
b/tests/unit_tests/subjects/test_utils.py
index e5ebf4323e5..36e5651f90a 100644
--- a/tests/unit_tests/subjects/test_utils.py
+++ b/tests/unit_tests/subjects/test_utils.py
@@ -25,7 +25,10 @@ from superset.commands.utils import (
     populate_subject_list,
     populate_subjects,
 )
-from superset.subjects.exceptions import SubjectsNotFoundValidationError
+from superset.subjects.exceptions import (
+    SubjectsNotFoundValidationError,
+    ViewersDisabledValidationError,
+)
 from superset.subjects.models import Subject
 from superset.subjects.types import SubjectType
 from superset.subjects.utils import (
@@ -515,8 +518,9 @@ def test_compute_subject_list(mock_populate, current_ids, 
new_ids, expected_call
 # --------------------------------------------------------------------------
 
 
+@patch("superset.commands.utils.is_feature_enabled", return_value=True)
 @patch("superset.commands.utils.populate_subject_list")
-def test_populate_subjects_all_variants(mock_populate):
+def test_populate_subjects_all_variants(mock_populate, mock_flag):
     """Editors + viewers; editors only; include_viewers=False."""
     editor_s = [_make_subject(1)]
     viewer_s = [_make_subject(2)]
@@ -567,8 +571,9 @@ def test_populate_subjects_all_variants(mock_populate):
     )
 
 
+@patch("superset.commands.utils.is_feature_enabled", return_value=True)
 @patch("superset.commands.utils.compute_subject_list")
-def test_compute_subjects_all_variants(mock_compute):
+def test_compute_subjects_all_variants(mock_compute, mock_flag):
     """Editors + viewers; no viewers attr; include_viewers=False."""
     model = MagicMock()
     model.editors = [_make_subject(1)]
@@ -611,3 +616,127 @@ def test_compute_subjects_all_variants(mock_compute):
         ensure_no_lockout=True,
         field_name="editors",
     )
+
+
+# --------------------------------------------------------------------------
+# ENABLE_VIEWERS gate on viewer writes
+# --------------------------------------------------------------------------
+
+
+@patch("superset.commands.utils.is_feature_enabled", return_value=False)
+@patch("superset.commands.utils.populate_subject_list")
+def test_populate_subjects_rejects_viewers_when_flag_disabled(mock_populate, 
mock_flag):
+    """Viewers are enforced regardless of the flag, so a create payload must
+    not be able to add them while the flag hides them from the UI."""
+    editor_s = [_make_subject(1)]
+    viewer_s = [_make_subject(2)]
+    mock_populate.side_effect = [editor_s, viewer_s]
+
+    props: dict = {"editors": [1], "viewers": [2]}
+    populate_subjects(props, exceptions := [])
+
+    assert props["editors"] == editor_s
+    assert props["viewers"] == [2]  # left as raw IDs; command raises
+    assert len(exceptions) == 1
+    assert isinstance(exceptions[0], ViewersDisabledValidationError)
+    mock_flag.assert_called_with("ENABLE_VIEWERS")
+
+
+@patch("superset.commands.utils.is_feature_enabled", return_value=False)
+@patch("superset.commands.utils.populate_subject_list")
+def test_populate_subjects_accepts_empty_viewers_when_flag_disabled(
+    mock_populate, mock_flag
+):
+    editor_s = [_make_subject(1)]
+    mock_populate.side_effect = [editor_s, []]
+
+    props: dict = {"editors": [1], "viewers": []}
+    populate_subjects(props, exceptions := [])
+
+    assert props["viewers"] == []
+    assert not exceptions
+
+
+@patch("superset.commands.utils.is_feature_enabled", return_value=True)
+@patch("superset.commands.utils.populate_subject_list")
+def test_populate_subjects_accepts_viewers_when_flag_enabled(mock_populate, 
mock_flag):
+    viewer_s = [_make_subject(2)]
+    mock_populate.side_effect = [[_make_subject(1)], viewer_s]
+
+    props: dict = {"editors": [1], "viewers": [2]}
+    populate_subjects(props, exceptions := [])
+
+    assert props["viewers"] == viewer_s
+    assert not exceptions
+
+
+@patch("superset.commands.utils.is_feature_enabled", return_value=False)
+@patch("superset.commands.utils.compute_subject_list")
+def test_compute_subjects_rejects_new_viewers_when_flag_disabled(
+    mock_compute, mock_flag
+):
+    model = MagicMock()
+    model.editors = [_make_subject(1)]
+    model.viewers = [_make_subject(2)]
+    mock_compute.side_effect = [model.editors, [_make_subject(2), 
_make_subject(3)]]
+
+    props: dict = {"viewers": [2, 3]}
+    compute_subjects(model, props, exceptions := [])
+
+    assert len(exceptions) == 1
+    assert isinstance(exceptions[0], ViewersDisabledValidationError)
+
+
+@patch("superset.commands.utils.is_feature_enabled", return_value=False)
+@patch("superset.commands.utils.compute_subject_list")
+def test_compute_subjects_allows_removing_viewers_when_flag_disabled(
+    mock_compute, mock_flag
+):
+    """Clearing stale viewers (the only way to lift a hidden restriction)
+    must keep working while the flag is off; so must re-sending the current
+    list, which round-tripping API clients do."""
+    model = MagicMock()
+    model.editors = [_make_subject(1)]
+    model.viewers = [_make_subject(2), _make_subject(3)]
+
+    # Clear
+    mock_compute.side_effect = [model.editors, []]
+    props: dict = {"viewers": []}
+    compute_subjects(model, props, exceptions := [])
+    assert props["viewers"] == []
+    assert not exceptions
+
+    # Shrink
+    mock_compute.reset_mock(side_effect=True)
+    mock_compute.side_effect = [model.editors, [_make_subject(2)]]
+    props = {"viewers": [2]}
+    compute_subjects(model, props, exceptions := [])
+    assert [s.id for s in props["viewers"]] == [2]
+    assert not exceptions
+
+    # Unchanged round-trip
+    mock_compute.reset_mock(side_effect=True)
+    mock_compute.side_effect = [model.editors, list(model.viewers)]
+    props = {"viewers": [2, 3]}
+    compute_subjects(model, props, exceptions := [])
+    assert not exceptions
+
+
+@patch("superset.commands.utils.is_feature_enabled", return_value=False)
+@patch("superset.commands.utils.compute_subject_list")
+def test_compute_subjects_preserves_viewers_when_payload_omits_them(
+    mock_compute, mock_flag
+):
+    """An update that does not mention viewers keeps the existing list even
+    while the flag is off; only explicit additions are blocked."""
+    model = MagicMock()
+    model.editors = [_make_subject(1)]
+    model.viewers = [_make_subject(2)]
+    mock_compute.side_effect = [model.editors, list(model.viewers)]
+
+    props: dict = {"editors": [1]}
+    compute_subjects(model, props, exceptions := [])
+
+    assert [s.id for s in props["viewers"]] == [2]
+    assert not exceptions
+    mock_flag.assert_not_called()

Reply via email to