Skip to content

Commit

Permalink
feat(backend): webconsole增加鉴权逻辑 #5455
Browse files Browse the repository at this point in the history
  • Loading branch information
iSecloud authored and zhangzhw8 committed Jul 10, 2024
1 parent 3dcb3a9 commit 8096ed9
Show file tree
Hide file tree
Showing 12 changed files with 205 additions and 21 deletions.
2 changes: 2 additions & 0 deletions dbm-ui/backend/db_services/dbbase/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
)
from backend.db_services.ipchooser.query.resource import ResourceQueryHelper
from backend.iam_app.handlers.drf_perm.base import DBManagePermission
from backend.iam_app.handlers.drf_perm.cluster import ClusterWebconsolePermission

SWAGGER_TAG = _("集群通用接口")

Expand All @@ -62,6 +63,7 @@ class DBBaseViewSet(viewsets.SystemViewSet):
"simple_query_cluster",
"common_query_cluster",
): [DBManagePermission()],
("webconsole",): [ClusterWebconsolePermission()],
}
default_permission_class = [DBManagePermission()]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ class SpiderViewSet(viewsets.ResourceViewSet):
ActionEnum.TENDBCLUSTER_SPIDER_MNT_DESTROY,
ActionEnum.TENDBCLUSTER_NODE_REBALANCE,
ActionEnum.TENDBCLUSTER_DUMP_DATA,
ActionEnum.TENDBCLUSTER_WEBCONSOLE,
]
list_instance_perm_actions = [ActionEnum.TENDBCLUSTER_VIEW]
list_external_perm_actions = [ActionEnum.ACCESS_ENTRY_EDIT]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ class DBHAViewSet(viewsets.ResourceViewSet):
ActionEnum.MYSQL_VIEW,
ActionEnum.TBINLOGDUMPER_INSTALL,
ActionEnum.MYSQL_DUMP_DATA,
ActionEnum.MYSQL_WEBCONSOLE,
]
list_instance_perm_actions = [ActionEnum.MYSQL_VIEW]
list_external_perm_actions = [ActionEnum.ACCESS_ENTRY_EDIT]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ class DBSingleViewSet(viewsets.ResourceViewSet):
ActionEnum.MYSQL_DESTROY,
ActionEnum.MYSQL_VIEW,
ActionEnum.MYSQL_DUMP_DATA,
ActionEnum.MYSQL_WEBCONSOLE,
]
list_instance_perm_actions = [ActionEnum.MYSQL_VIEW]
list_external_perm_actions = [ActionEnum.ACCESS_ENTRY_EDIT]
Expand Down
10 changes: 6 additions & 4 deletions dbm-ui/backend/db_services/mysql/sqlparse/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,15 @@ def parse_select_statement(self, sql: str, need_keywords: list = None):
if len(parsed_sqls) > 1:
raise SQLParseBaseException(_("请保证一次只解析一条select语句"))

# 允许show databases, desc, use语句
# 允许show databases, show tables, desc, use语句
def parse_show_desc_tokens(tokens):
identifiers = [item.value.upper() for item in tokens if isinstance(item, sqlparse.sql.Identifier)]
keyword = next((token.value for token in tokens if token.is_keyword), "")
if keyword.upper() in ["DESC", "DESCRIBE", "USE"]:
keyword = [token.value for token in tokens if token.is_keyword] or [""]
if keyword[0].upper() in ["DESC", "DESCRIBE", "USE"]:
return True
if keyword.upper() == "SHOW" and identifiers == ["DATABASES"]:
if keyword[0].upper() == "SHOW" and identifiers == ["DATABASES"]:
return True
if len(keyword) > 1 and keyword[0].upper() == "SHOW" and keyword[1].upper() == "TABLES":
return True
return False

Expand Down
7 changes: 4 additions & 3 deletions dbm-ui/backend/flow/engine/bamboo/scene/mysql/dbconsole.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""

import logging.config
import time
from dataclasses import asdict
from typing import Dict, Optional

Expand Down Expand Up @@ -43,11 +43,12 @@ def __init__(self, root_id: str, data: Optional[Dict]):
self.data["uid"] = self.data.get("uid") or self.root_id
self.uid = self.data["uid"]
self.cluster_id = self.data["cluster_id"]
self.dbconsole_dump_file_name = f"{self.root_id}_dbm_console_dump.sql"
self.cluster = Cluster.objects.get(id=self.cluster_id)
self.dbconsole_dump_file_name = f"{self.cluster.immute_domain}_{int(time.time())}_dbm_console_dump.sql"

def dump_flow(self):
p = Builder(root_id=self.root_id, data=self.data, need_random_pass_cluster_ids=[self.cluster_id])
ro_instance_info = self.__get_read_instance(Cluster.objects.filter(id=self.cluster_id).first())
ro_instance_info = self.__get_read_instance(self.cluster)
bk_cloud_id = ro_instance_info["bk_cloud_id"]
exec_ip = ro_instance_info["ip"]
# 此处可以根据延迟来考虑是否需要抛出错误
Expand Down
4 changes: 2 additions & 2 deletions dbm-ui/backend/iam_app/dataclass/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def generate_iam_migration_json(json_name: str = ""):
f.write(json.dumps(dbm_iam_json, ensure_ascii=False, indent=4))


def generate_iam_biz_maintain_json(json_name: str = ""):
def generate_iam_biz_maintain_json(label: str = CommonActionLabel.BIZ_MAINTAIN, json_name: str = ""):
"""
根据dataclass的定义自动生成业务运维的用户组迁移json
"""
Expand All @@ -174,7 +174,7 @@ def get_resource_path_info(resource: ResourceMeta):

# 聚合相同资源的动作
for action in _all_actions.values():
if CommonActionLabel.BIZ_MAINTAIN not in action.common_labels:
if label not in action.common_labels:
continue
resource_ids = ",".join(sorted([resource.id for resource in action.related_resource_types]))
resources__actions_map[resource_ids].append(action.id)
Expand Down
46 changes: 35 additions & 11 deletions dbm-ui/backend/iam_app/dataclass/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,19 @@ class ActionEnum:
related_resource_types=[ResourceEnum.MYSQL],
group=_("MySQL"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_MAINTAIN],
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

MYSQL_WEBCONSOLE = ActionMeta(
id="mysql_webconsole",
name=_("MySQL Webconsole执行"),
name_en="mysql_webconsole",
type="exec",
related_actions=[DB_MANAGE.id],
related_resource_types=[ResourceEnum.MYSQL],
group=_("MySQL"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

MYSQL_ADMIN_PWD_MODIFY = ActionMeta(
Expand Down Expand Up @@ -565,7 +577,19 @@ class ActionEnum:
related_resource_types=[ResourceEnum.TENDBCLUSTER],
group=_("TenDBCluster"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_MAINTAIN],
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

TENDBCLUSTER_WEBCONSOLE = ActionMeta(
id="tendbcluster_webconsole",
name=_("TendbCluster Webconsole执行"),
name_en="tendbcluster_webconsole",
type="exec",
related_actions=[DB_MANAGE.id],
related_resource_types=[ResourceEnum.TENDBCLUSTER],
group=_("TenDBCluster"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

TENDBCLUSTER_ADMIN_PWD_MODIFY = ActionMeta(
Expand Down Expand Up @@ -811,7 +835,7 @@ class ActionEnum:
related_resource_types=[ResourceEnum.REDIS],
group=_("Redis"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_MAINTAIN],
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

REDIS_ACCESS_ENTRY_VIEW = ActionMeta(
Expand Down Expand Up @@ -904,7 +928,7 @@ class ActionEnum:
related_resource_types=[ResourceEnum.ES],
group=_("ES"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_MAINTAIN],
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

ES_ACCESS_ENTRY_VIEW = ActionMeta(
Expand Down Expand Up @@ -948,7 +972,7 @@ class ActionEnum:
related_resource_types=[ResourceEnum.DORIS],
group=_("Doris"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_MAINTAIN],
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

DORIS_ACCESS_ENTRY_VIEW = ActionMeta(
Expand Down Expand Up @@ -984,7 +1008,7 @@ class ActionEnum:
related_resource_types=[ResourceEnum.KAFKA],
group=_("Kafka"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_MAINTAIN],
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

KAFKA_ACCESS_ENTRY_VIEW = ActionMeta(
Expand Down Expand Up @@ -1036,7 +1060,7 @@ class ActionEnum:
related_resource_types=[ResourceEnum.HDFS],
group=_("HDFS"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_MAINTAIN],
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

HDFS_ACCESS_ENTRY_VIEW = ActionMeta(
Expand Down Expand Up @@ -1080,7 +1104,7 @@ class ActionEnum:
related_resource_types=[ResourceEnum.PULSAR],
group=_("Pulsar"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_MAINTAIN],
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

PULSAR_ACCESS_ENTRY_VIEW = ActionMeta(
Expand Down Expand Up @@ -1125,7 +1149,7 @@ class ActionEnum:
related_resource_types=[ResourceEnum.RIAK],
group=_("Riak"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_MAINTAIN],
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

RIAK_ACCESS_ENTRY_VIEW = ActionMeta(
Expand Down Expand Up @@ -1161,7 +1185,7 @@ class ActionEnum:
related_resource_types=[ResourceEnum.MONGODB],
group=_("MongoDB"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_MAINTAIN],
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

MONGODB_APPLY = ActionMeta(
Expand Down Expand Up @@ -1266,7 +1290,7 @@ class ActionEnum:
related_resource_types=[ResourceEnum.SQLSERVER],
group=_("SQLServer"),
subgroup=_("集群管理"),
common_labels=[CommonActionLabel.BIZ_MAINTAIN],
common_labels=[CommonActionLabel.BIZ_READ_ONLY, CommonActionLabel.BIZ_MAINTAIN],
)

SQLSERVER_ADMIN_PWD_MODIFY = ActionMeta(
Expand Down
26 changes: 26 additions & 0 deletions dbm-ui/backend/iam_app/handlers/drf_perm/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ def __init__(self):


class QueryClusterPasswordPermission(MoreResourceActionPermission):
"""
集群admin密码查询相关动作鉴权
"""

@staticmethod
def instance_ids_getters(request, view):
data = request.data or request.query_params
Expand All @@ -162,3 +166,25 @@ def __init__(self):
resource_metes=[ResourceEnum.BUSINESS, ResourceEnum.DBTYPE],
instance_ids_getters=self.instance_ids_getters,
)


class ClusterWebconsolePermission(ResourceActionPermission):
"""
集群webconsole相关鉴权
"""

def inst_ids_getter(self, request, view):
data = request.data
cluster = Cluster.objects.get(id=data["cluster_id"])
db_type = ClusterType.cluster_type_to_db_type(cluster.cluster_type)
# 根据不同的组件类型获得对应的动作和资源类型
try:
self.actions = [getattr(ActionEnum, f"{db_type}_webconsole".upper())]
self.resource_meta = getattr(ResourceEnum, db_type.upper())
except AttributeError:
raise NotImplementedError

return [cluster.id]

def __init__(self):
super().__init__(actions=None, resource_meta=None, instance_ids_getter=self.inst_ids_getter)
Loading

0 comments on commit 8096ed9

Please sign in to comment.