Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(charts): security perm simplification #11981

Merged
merged 15 commits into from
Dec 15, 2020
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const mockUser = {
};

fetchMock.get(chartsInfoEndpoint, {
permissions: ['can_list', 'can_edit', 'can_delete'],
permissions: ['can_read', 'can_write'],
});

fetchMock.get(chartssOwnersEndpoint, {
Expand Down
8 changes: 4 additions & 4 deletions superset-frontend/src/views/CRUD/chart/ChartList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -143,11 +143,11 @@ function ChartList(props: ChartListProps) {
refreshData();
};

const canCreate = hasPerm('can_add');
const canEdit = hasPerm('can_edit');
const canDelete = hasPerm('can_delete');
const canCreate = hasPerm('can_write');
const canEdit = hasPerm('can_write');
const canDelete = hasPerm('can_write');
const canExport =
hasPerm('can_mulexport') && isFeatureEnabled(FeatureFlag.VERSIONED_EXPORT);
hasPerm('can_read') && isFeatureEnabled(FeatureFlag.VERSIONED_EXPORT);
const initialSort = [{ id: 'changed_on_delta_humanized', desc: true }];

function handleBulkChartDelete(chartsToDelete: Chart[]) {
Expand Down
5 changes: 3 additions & 2 deletions superset/charts/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
)
from superset.commands.exceptions import CommandInvalidError
from superset.commands.importers.v1.utils import remove_root
from superset.constants import RouteMethod
from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP, RouteMethod
from superset.exceptions import SupersetSecurityException
from superset.extensions import event_logger
from superset.models.slice import Slice
Expand Down Expand Up @@ -95,7 +95,8 @@ class ChartRestApi(BaseSupersetModelRestApi):
"data",
"favorite_status",
}
class_permission_name = "SliceModelView"
class_permission_name = "Chart"
method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
show_columns = [
"cache_timeout",
"dashboards.dashboard_title",
Expand Down
6 changes: 6 additions & 0 deletions superset/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,10 @@ class RouteMethod: # pylint: disable=too-few-public-methods
"post": "write",
"put": "write",
"related": "read",
"favorite_status": "write",
"import_": "write",
"cache_screenshot": "read",
"screenshot": "read",
"data": "read",
"thumbnail": "read",
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# 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.
"""security converge charts

Revision ID: ccb74baaa89b
Revises: 811494c0cc23
Create Date: 2020-12-09 14:13:48.058003

"""

# revision identifiers, used by Alembic.
revision = "ccb74baaa89b"
down_revision = "811494c0cc23"


from alembic import op
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session

from superset.migrations.shared.security_converge import (
add_pvms,
get_reversed_new_pvms,
get_reversed_pvm_map,
migrate_roles,
Pvm,
)

NEW_PVMS = {"Chart": ("can_read", "can_write",)}
PVM_MAP = {
Pvm("SliceModelView", "can_list"): (Pvm("Chart", "can_read"),),
Pvm("SliceModelView", "can_show"): (Pvm("Chart", "can_read"),),
Pvm("SliceModelView", "can_edit",): (Pvm("Chart", "can_write"),),
Pvm("SliceModelView", "can_delete",): (Pvm("Chart", "can_write"),),
Pvm("SliceModelView", "can_add",): (Pvm("Chart", "can_write"),),
Pvm("SliceModelView", "can_download",): (Pvm("Chart", "can_read"),),
Pvm("SliceModelView", "muldelete",): (Pvm("Chart", "can_write"),),
Pvm("SliceModelView", "can_mulexport",): (Pvm("Chart", "can_read"),),
Pvm("SliceModelView", "can_favorite_status",): (Pvm("Chart", "can_write"),),
Copy link
Member

Choose a reason for hiding this comment

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

Hmm...should this be "can_read"? Does favoriting a chart do anything other than create a record of the favorite?

Copy link
Member Author

Choose a reason for hiding this comment

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

it should, actually that's a GET so it's really a mistake. Very nice catch

Pvm("SliceModelView", "can_cache_screenshot",): (Pvm("Chart", "can_read"),),
Pvm("SliceModelView", "can_screenshot",): (Pvm("Chart", "can_read"),),
Pvm("SliceAsync", "can_list",): (Pvm("Chart", "can_read"),),
Pvm("SliceAsync", "muldelete",): (Pvm("Chart", "can_read"),),
}


def upgrade():
bind = op.get_bind()
session = Session(bind=bind)

# Add the new permissions on the migration itself
add_pvms(session, NEW_PVMS)
migrate_roles(session, PVM_MAP)
try:
session.commit()
except SQLAlchemyError as ex:
print(f"An error occurred while upgrading permissions: {ex}")
session.rollback()


def downgrade():
bind = op.get_bind()
session = Session(bind=bind)

# Add the old permissions on the migration itself
add_pvms(session, get_reversed_new_pvms(PVM_MAP))
migrate_roles(session, get_reversed_pvm_map(PVM_MAP))
try:
session.commit()
except SQLAlchemyError as ex:
print(f"An error occurred while downgrading permissions: {ex}")
session.rollback()
pass
4 changes: 3 additions & 1 deletion superset/views/chart/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

from superset import db, is_feature_enabled
from superset.connectors.connector_registry import ConnectorRegistry
from superset.constants import RouteMethod
from superset.constants import MODEL_VIEW_RW_METHOD_PERMISSION_MAP, RouteMethod
from superset.models.slice import Slice
from superset.typing import FlaskResponse
from superset.utils import core as utils
Expand All @@ -45,6 +45,8 @@ class SliceModelView(
RouteMethod.API_READ,
RouteMethod.API_DELETE,
}
class_permission_name = "Chart"
method_permission_name = MODEL_VIEW_RW_METHOD_PERMISSION_MAP

def pre_add(self, item: "SliceModelView") -> None:
utils.validate_json(item.params)
Expand Down
2 changes: 1 addition & 1 deletion superset/views/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -655,7 +655,7 @@ def explore( # pylint: disable=too-many-locals,too-many-return-statements
return redirect(datasource.default_endpoint)

# slc perms
slice_add_perm = security_manager.can_access("can_add", "SliceModelView")
slice_add_perm = security_manager.can_access("can_write", "Chart")
slice_overwrite_perm = is_owner(slc, g.user) if slc else False
slice_download_perm = security_manager.can_access(
"can_download", "SliceModelView"
Expand Down
14 changes: 14 additions & 0 deletions tests/charts/api_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,20 @@ def add_dashboard_to_chart(self):
db.session.delete(self.chart)
db.session.commit()

def test_info_security_chart(self):
"""
Chart API: Test info security
"""
self.login(username="admin")
params = {"keys": ["permissions"]}
uri = f"api/v1/chart/_info?q={prison.dumps(params)}"
rv = self.get_assert_metric(uri, "info")
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 200
assert "can_read" in data["permissions"]
assert "can_write" in data["permissions"]
assert len(data["permissions"]) == 2

def test_delete_chart(self):
"""
Chart API: Test delete
Expand Down
32 changes: 7 additions & 25 deletions tests/security_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
)
from .fixtures.unicode_dashboard import load_unicode_dashboard_with_slice

NEW_SECURITY_CONVERGE_VIEWS = ("CssTemplate", "SavedQuery")
NEW_SECURITY_CONVERGE_VIEWS = ("CssTemplate", "SavedQuery", "Chart")


def get_perm_tuples(role_name):
Expand Down Expand Up @@ -646,7 +646,7 @@ def assert_can_gamma(self, perm_set):
self.assert_can_read("TableModelView", perm_set)

# make sure that user can create slices and dashboards
self.assert_can_all("SliceModelView", perm_set)
self.assert_can_all("Chart", perm_set)
self.assert_can_all("DashboardModelView", perm_set)

self.assertIn(("can_add_slices", "Superset"), perm_set)
Expand Down Expand Up @@ -831,37 +831,19 @@ def test_granter_permissions(self):
self.assert_cannot_alpha(granter_set)

def test_gamma_permissions(self):
def assert_can_read(view_menu):
self.assertIn(("can_list", view_menu), gamma_perm_set)

def assert_can_write(view_menu):
self.assertIn(("can_add", view_menu), gamma_perm_set)
self.assertIn(("can_delete", view_menu), gamma_perm_set)
self.assertIn(("can_edit", view_menu), gamma_perm_set)

def assert_cannot_write(view_menu):
self.assertNotIn(("can_add", view_menu), gamma_perm_set)
self.assertNotIn(("can_delete", view_menu), gamma_perm_set)
self.assertNotIn(("can_edit", view_menu), gamma_perm_set)
self.assertNotIn(("can_save", view_menu), gamma_perm_set)

def assert_can_all(view_menu):
assert_can_read(view_menu)
assert_can_write(view_menu)

gamma_perm_set = set()
for perm in security_manager.find_role("Gamma").permissions:
gamma_perm_set.add((perm.permission.name, perm.view_menu.name))

# check read only perms
assert_can_read("TableModelView")
self.assert_can_read("TableModelView", gamma_perm_set)

# make sure that user can create slices and dashboards
assert_can_all("SliceModelView")
assert_can_all("DashboardModelView")
self.assert_can_all("Chart", gamma_perm_set)
self.assert_can_all("DashboardModelView", gamma_perm_set)

assert_cannot_write("UserDBModelView")
assert_cannot_write("RoleModelView")
self.assert_cannot_write("UserDBModelView", gamma_perm_set)
self.assert_cannot_write("RoleModelView", gamma_perm_set)

self.assertIn(("can_add_slices", "Superset"), gamma_perm_set)
self.assertIn(("can_copy_dash", "Superset"), gamma_perm_set)
Expand Down