-
Notifications
You must be signed in to change notification settings - Fork 13.2k
/
manager.py
2715 lines (2349 loc) · 96.1 KB
/
manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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.
# pylint: disable=too-many-lines
"""A set of constants and methods to manage permissions and security"""
import logging
import re
import time
from collections import defaultdict
from typing import Any, Callable, cast, NamedTuple, Optional, TYPE_CHECKING
from flask import current_app, Flask, g, Request
from flask_appbuilder import Model
from flask_appbuilder.security.sqla.manager import SecurityManager
from flask_appbuilder.security.sqla.models import (
assoc_permissionview_role,
assoc_user_role,
Permission,
PermissionView,
Role,
User,
ViewMenu,
)
from flask_appbuilder.security.views import (
PermissionModelView,
PermissionViewModelView,
RoleModelView,
UserModelView,
ViewMenuModelView,
)
from flask_appbuilder.widgets import ListWidget
from flask_babel import lazy_gettext as _
from flask_login import AnonymousUserMixin, LoginManager
from jwt.api_jwt import _jwt_global_obj
from sqlalchemy import and_, inspect, or_
from sqlalchemy.engine.base import Connection
from sqlalchemy.orm import eagerload
from sqlalchemy.orm.mapper import Mapper
from sqlalchemy.orm.query import Query as SqlaQuery
from superset.constants import RouteMethod
from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
from superset.exceptions import (
DatasetInvalidPermissionEvaluationException,
SupersetSecurityException,
)
from superset.security.guest_token import (
GuestToken,
GuestTokenResources,
GuestTokenResourceType,
GuestTokenRlsRule,
GuestTokenUser,
GuestUser,
)
from superset.sql_parse import extract_tables_from_jinja_sql, Table
from superset.utils import json
from superset.utils.core import (
DatasourceName,
DatasourceType,
get_user_id,
RowLevelSecurityFilterType,
)
from superset.utils.filters import get_dataset_access_filters
from superset.utils.urls import get_url_host
if TYPE_CHECKING:
from superset.common.query_context import QueryContext
from superset.connectors.sqla.models import (
BaseDatasource,
RowLevelSecurityFilter,
SqlaTable,
)
from superset.models.core import Database
from superset.models.dashboard import Dashboard
from superset.models.slice import Slice
from superset.models.sql_lab import Query
from superset.viz import BaseViz
logger = logging.getLogger(__name__)
DATABASE_PERM_REGEX = re.compile(r"^\[.+\]\.\(id\:(?P<id>\d+)\)$")
class DatabaseCatalogSchema(NamedTuple):
database: str
catalog: Optional[str]
schema: str
class SupersetSecurityListWidget(ListWidget): # pylint: disable=too-few-public-methods
"""
Redeclaring to avoid circular imports
"""
template = "superset/fab_overrides/list.html"
class SupersetRoleListWidget(ListWidget): # pylint: disable=too-few-public-methods
"""
Role model view from FAB already uses a custom list widget override
So we override the override
"""
template = "superset/fab_overrides/list_role.html"
def __init__(self, **kwargs: Any) -> None:
kwargs["appbuilder"] = current_app.appbuilder
super().__init__(**kwargs)
UserModelView.list_widget = SupersetSecurityListWidget
RoleModelView.list_widget = SupersetRoleListWidget
PermissionViewModelView.list_widget = SupersetSecurityListWidget
PermissionModelView.list_widget = SupersetSecurityListWidget
# Limiting routes on FAB model views
UserModelView.include_route_methods = RouteMethod.CRUD_SET | {
RouteMethod.ACTION,
RouteMethod.API_READ,
RouteMethod.ACTION_POST,
"userinfo",
}
RoleModelView.include_route_methods = RouteMethod.CRUD_SET
PermissionViewModelView.include_route_methods = {RouteMethod.LIST}
PermissionModelView.include_route_methods = {RouteMethod.LIST}
ViewMenuModelView.include_route_methods = {RouteMethod.LIST}
RoleModelView.list_columns = ["name"]
RoleModelView.edit_columns = ["name", "permissions", "user"]
RoleModelView.related_views = []
def freeze_value(value: Any) -> str:
"""
Used to compare column and metric sets.
"""
return json.dumps(value, sort_keys=True)
def query_context_modified(query_context: "QueryContext") -> bool:
"""
Check if a query context has been modified.
This is used to ensure guest users don't modify the payload and fetch data
different from what was shared with them in dashboards.
"""
form_data = query_context.form_data
stored_chart = query_context.slice_
# native filter requests
if form_data is None or stored_chart is None:
return False
# cannot request a different chart
if form_data.get("slice_id") != stored_chart.id:
return True
stored_query_context = (
json.loads(cast(str, stored_chart.query_context))
if stored_chart.query_context
else None
)
# compare columns and metrics in form_data with stored values
for key in ["metrics", "columns", "groupby"]:
requested_values = {freeze_value(value) for value in form_data.get(key) or []}
stored_values = {
freeze_value(value) for value in stored_chart.params_dict.get(key) or []
}
if not requested_values.issubset(stored_values):
return True
# compare queries in query_context
queries_values = {
freeze_value(value)
for query in query_context.queries
for value in getattr(query, key, []) or []
}
if stored_query_context:
for query in stored_query_context.get("queries") or []:
stored_values.update(
{freeze_value(value) for value in query.get(key) or []}
)
if not queries_values.issubset(stored_values):
return True
return False
class SupersetSecurityManager( # pylint: disable=too-many-public-methods
SecurityManager
):
userstatschartview = None
READ_ONLY_MODEL_VIEWS = {"Database", "DynamicPlugin"}
USER_MODEL_VIEWS = {
"RegisterUserModelView",
"UserDBModelView",
"UserLDAPModelView",
"UserInfoEditView",
"UserOAuthModelView",
"UserOIDModelView",
"UserRemoteUserModelView",
}
GAMMA_READ_ONLY_MODEL_VIEWS = {
"Dataset",
"Datasource",
} | READ_ONLY_MODEL_VIEWS
ADMIN_ONLY_VIEW_MENUS = {
"Access Requests",
"Action Log",
"Log",
"List Users",
"List Roles",
"ResetPasswordView",
"RoleModelView",
"Row Level Security",
"Row Level Security Filters",
"RowLevelSecurityFiltersModelView",
"Security",
"SQL Lab",
"User Registrations",
"User's Statistics",
} | USER_MODEL_VIEWS
ALPHA_ONLY_VIEW_MENUS = {
"Alerts & Report",
"Annotation Layers",
"Annotation",
"CSS Templates",
"ColumnarToDatabaseView",
"CssTemplate",
"ExcelToDatabaseView",
"Import dashboards",
"ImportExportRestApi",
"Manage",
"Queries",
"ReportSchedule",
"TableSchemaView",
}
ALPHA_ONLY_PMVS = {
("can_csv_upload", "Database"),
("can_excel_upload", "Database"),
}
ADMIN_ONLY_PERMISSIONS = {
"can_update_role",
"all_query_access",
"can_grant_guest_token",
"can_set_embedded",
"can_warm_up_cache",
}
READ_ONLY_PERMISSION = {
"can_show",
"can_list",
"can_get",
"can_external_metadata",
"can_external_metadata_by_name",
"can_read",
}
ALPHA_ONLY_PERMISSIONS = {
"muldelete",
"all_database_access",
"all_datasource_access",
}
OBJECT_SPEC_PERMISSIONS = {
"database_access",
"catalog_access",
"schema_access",
"datasource_access",
}
ACCESSIBLE_PERMS = {"can_userinfo", "resetmypassword", "can_recent_activity"}
SQLLAB_ONLY_PERMISSIONS = {
("can_read", "SavedQuery"),
("can_write", "SavedQuery"),
("can_export", "SavedQuery"),
("can_read", "Query"),
("can_export_csv", "Query"),
("can_get_results", "SQLLab"),
("can_execute_sql_query", "SQLLab"),
("can_estimate_query_cost", "SQL Lab"),
("can_export_csv", "SQLLab"),
("can_read", "SQLLab"),
("can_sqllab_history", "Superset"),
("can_sqllab", "Superset"),
("can_test_conn", "Superset"), # Deprecated permission remove on 3.0.0
("can_activate", "TabStateView"),
("can_get", "TabStateView"),
("can_delete_query", "TabStateView"),
("can_post", "TabStateView"),
("can_delete", "TabStateView"),
("can_put", "TabStateView"),
("can_migrate_query", "TabStateView"),
("menu_access", "SQL Lab"),
("menu_access", "SQL Editor"),
("menu_access", "Saved Queries"),
("menu_access", "Query Search"),
}
SQLLAB_EXTRA_PERMISSION_VIEWS = {
("can_csv", "Superset"), # Deprecated permission remove on 3.0.0
("can_read", "Superset"),
("can_read", "Database"),
}
data_access_permissions = (
"database_access",
"schema_access",
"datasource_access",
"all_datasource_access",
"all_database_access",
"all_query_access",
)
guest_user_cls = GuestUser
pyjwt_for_guest_token = _jwt_global_obj
def create_login_manager(self, app: Flask) -> LoginManager:
lm = super().create_login_manager(app)
lm.request_loader(self.request_loader)
return lm
def request_loader(self, request: Request) -> Optional[User]:
# pylint: disable=import-outside-toplevel
from superset.extensions import feature_flag_manager
if feature_flag_manager.is_feature_enabled("EMBEDDED_SUPERSET"):
return self.get_guest_user_from_request(request)
return None
def get_catalog_perm(
self,
database: str,
catalog: Optional[str] = None,
) -> Optional[str]:
"""
Return the database specific catalog permission.
:param database: The Superset database or database name
:param catalog: The database catalog name
:return: The database specific schema permission
"""
if catalog is None:
return None
return f"[{database}].[{catalog}]"
def get_schema_perm(
self,
database: str,
catalog: Optional[str] = None,
schema: Optional[str] = None,
) -> Optional[str]:
"""
Return the database specific schema permission.
Catalogs were added in SIP-95, and not all databases support them. Because of
this, the format used for permissions is different depending on whether a
catalog is passed or not:
[database].[schema]
[database].[catalog].[schema]
:param database: The database name
:param catalog: The database catalog name
:param schema: The database schema name
:return: The database specific schema permission
"""
if schema is None:
return None
if catalog:
return f"[{database}].[{catalog}].[{schema}]"
return f"[{database}].[{schema}]"
@staticmethod
def get_database_perm(database_id: int, database_name: str) -> Optional[str]:
return f"[{database_name}].(id:{database_id})"
@staticmethod
def get_dataset_perm(
dataset_id: int,
dataset_name: str,
database_name: str,
) -> Optional[str]:
return f"[{database_name}].[{dataset_name}](id:{dataset_id})"
def can_access(self, permission_name: str, view_name: str) -> bool:
"""
Return True if the user can access the FAB permission/view, False otherwise.
Note this method adds protection from has_access failing from missing
permission/view entries.
:param permission_name: The FAB permission name
:param view_name: The FAB view-menu name
:returns: Whether the user can access the FAB permission/view
"""
user = g.user
if user.is_anonymous:
return self.is_item_public(permission_name, view_name)
return self._has_view_access(user, permission_name, view_name)
def can_access_all_queries(self) -> bool:
"""
Return True if the user can access all SQL Lab queries, False otherwise.
:returns: Whether the user can access all queries
"""
return self.can_access("all_query_access", "all_query_access")
def can_access_all_datasources(self) -> bool:
"""
Return True if the user can access all the datasources, False otherwise.
:returns: Whether the user can access all the datasources
"""
return self.can_access_all_databases() or self.can_access(
"all_datasource_access", "all_datasource_access"
)
def can_access_all_databases(self) -> bool:
"""
Return True if the user can access all the databases, False otherwise.
:returns: Whether the user can access all the databases
"""
return self.can_access("all_database_access", "all_database_access")
def can_access_database(self, database: "Database") -> bool:
"""
Return True if the user can access the specified database, False otherwise.
:param database: The database
:returns: Whether the user can access the database
"""
return (
self.can_access_all_datasources()
or self.can_access_all_databases()
or self.can_access("database_access", database.perm) # type: ignore
)
def can_access_catalog(self, database: "Database", catalog: str) -> bool:
"""
Return if the user can access the specified catalog.
"""
catalog_perm = self.get_catalog_perm(database.database_name, catalog)
return bool(
self.can_access_all_datasources()
or self.can_access_database(database)
or (catalog_perm and self.can_access("catalog_access", catalog_perm))
)
def can_access_schema(self, datasource: "BaseDatasource") -> bool:
"""
Return True if the user can access the schema associated with specified
datasource, False otherwise.
:param datasource: The datasource
:returns: Whether the user can access the datasource's schema
"""
return (
self.can_access_all_datasources()
or self.can_access_database(datasource.database)
or (
datasource.catalog
and self.can_access_catalog(datasource.database, datasource.catalog)
)
or self.can_access("schema_access", datasource.schema_perm or "")
)
def can_access_datasource(self, datasource: "BaseDatasource") -> bool:
"""
Return True if the user can access the specified datasource, False otherwise.
:param datasource: The datasource
:returns: Whether the user can access the datasource
"""
try:
self.raise_for_access(datasource=datasource)
except SupersetSecurityException:
return False
return True
def can_access_dashboard(self, dashboard: "Dashboard") -> bool:
"""
Return True if the user can access the specified dashboard, False otherwise.
:param dashboard: The dashboard
:returns: Whether the user can access the dashboard
"""
try:
self.raise_for_access(dashboard=dashboard)
except SupersetSecurityException:
return False
return True
def can_access_chart(self, chart: "Slice") -> bool:
"""
Return True if the user can access the specified chart, False otherwise.
:param chart: The chart
:return: Whether the user can access the chart
"""
try:
self.raise_for_access(chart=chart)
except SupersetSecurityException:
return False
return True
def get_dashboard_access_error_object( # pylint: disable=invalid-name
self,
dashboard: "Dashboard", # pylint: disable=unused-argument
) -> SupersetError:
"""
Return the error object for the denied Superset dashboard.
:param dashboard: The denied Superset dashboard
:returns: The error object
"""
return SupersetError(
error_type=SupersetErrorType.DASHBOARD_SECURITY_ACCESS_ERROR,
message="You don't have access to this dashboard.",
level=ErrorLevel.WARNING,
)
def get_chart_access_error_object(
self,
dashboard: "Dashboard", # pylint: disable=unused-argument
) -> SupersetError:
"""
Return the error object for the denied Superset dashboard.
:param dashboard: The denied Superset dashboard
:returns: The error object
"""
return SupersetError(
error_type=SupersetErrorType.CHART_SECURITY_ACCESS_ERROR,
message="You don't have access to this chart.",
level=ErrorLevel.WARNING,
)
@staticmethod
def get_datasource_access_error_msg(datasource: "BaseDatasource") -> str:
"""
Return the error message for the denied Superset datasource.
:param datasource: The denied Superset datasource
:returns: The error message
"""
return (
f"This endpoint requires the datasource {datasource.id}, "
"database or `all_datasource_access` permission"
)
@staticmethod
def get_datasource_access_link( # pylint: disable=unused-argument
datasource: "BaseDatasource",
) -> Optional[str]:
"""
Return the link for the denied Superset datasource.
:param datasource: The denied Superset datasource
:returns: The access URL
"""
return current_app.config.get("PERMISSION_INSTRUCTIONS_LINK")
def get_datasource_access_error_object( # pylint: disable=invalid-name
self, datasource: "BaseDatasource"
) -> SupersetError:
"""
Return the error object for the denied Superset datasource.
:param datasource: The denied Superset datasource
:returns: The error object
"""
return SupersetError(
error_type=SupersetErrorType.DATASOURCE_SECURITY_ACCESS_ERROR,
message=self.get_datasource_access_error_msg(datasource),
level=ErrorLevel.WARNING,
extra={
"link": self.get_datasource_access_link(datasource),
"datasource": datasource.id,
},
)
def get_table_access_error_msg(self, tables: set["Table"]) -> str:
"""
Return the error message for the denied SQL tables.
:param tables: The set of denied SQL tables
:returns: The error message
"""
quoted_tables = [f"`{table}`" for table in tables]
return f"""You need access to the following tables: {", ".join(quoted_tables)},
`all_database_access` or `all_datasource_access` permission"""
def get_table_access_error_object(self, tables: set["Table"]) -> SupersetError:
"""
Return the error object for the denied SQL tables.
:param tables: The set of denied SQL tables
:returns: The error object
"""
return SupersetError(
error_type=SupersetErrorType.TABLE_SECURITY_ACCESS_ERROR,
message=self.get_table_access_error_msg(tables),
level=ErrorLevel.WARNING,
extra={
"link": self.get_table_access_link(tables),
"tables": [str(table) for table in tables],
},
)
def get_table_access_link( # pylint: disable=unused-argument
self, tables: set["Table"]
) -> Optional[str]:
"""
Return the access link for the denied SQL tables.
:param tables: The set of denied SQL tables
:returns: The access URL
"""
return current_app.config.get("PERMISSION_INSTRUCTIONS_LINK")
def get_user_datasources(self) -> list["BaseDatasource"]:
"""
Collect datasources which the user has explicit permissions to.
:returns: The list of datasources
"""
user_datasources = set()
# pylint: disable=import-outside-toplevel
from superset.connectors.sqla.models import SqlaTable
user_datasources.update(
self.get_session.query(SqlaTable)
.filter(get_dataset_access_filters(SqlaTable))
.all()
)
# group all datasources by database
all_datasources = SqlaTable.get_all_datasources()
datasources_by_database: dict["Database", set["SqlaTable"]] = defaultdict(set)
for datasource in all_datasources:
datasources_by_database[datasource.database].add(datasource)
# add datasources with implicit permission (eg, database access)
for database, datasources in datasources_by_database.items():
if self.can_access_database(database):
user_datasources.update(datasources)
return list(user_datasources)
def can_access_table(self, database: "Database", table: "Table") -> bool:
"""
Return True if the user can access the SQL table, False otherwise.
:param database: The SQL database
:param table: The SQL table
:returns: Whether the user can access the SQL table
"""
try:
self.raise_for_access(database=database, table=table)
except SupersetSecurityException:
return False
return True
def user_view_menu_names(self, permission_name: str) -> set[str]:
base_query = (
self.get_session.query(self.viewmenu_model.name)
.join(self.permissionview_model)
.join(self.permission_model)
.join(assoc_permissionview_role)
.join(self.role_model)
)
if not g.user.is_anonymous:
# filter by user id
view_menu_names = (
base_query.join(assoc_user_role)
.join(self.user_model)
.filter(self.user_model.id == get_user_id())
.filter(self.permission_model.name == permission_name)
).all()
return {s.name for s in view_menu_names}
# Properly treat anonymous user
if public_role := self.get_public_role():
# filter by public role
view_menu_names = (
base_query.filter(self.role_model.id == public_role.id).filter(
self.permission_model.name == permission_name
)
).all()
return {s.name for s in view_menu_names}
return set()
def get_accessible_databases(self) -> list[int]:
"""
Return the list of databases accessible by the user.
:return: The list of accessible Databases
"""
perms = self.user_view_menu_names("database_access")
return [
int(match.group("id"))
for perm in perms
if (match := DATABASE_PERM_REGEX.match(perm))
]
def get_schemas_accessible_by_user(
self,
database: "Database",
catalog: Optional[str],
schemas: set[str],
hierarchical: bool = True,
) -> set[str]:
"""
Returned a filtered list of the schemas accessible by the user.
If not catalog is specified, the default catalog is used.
:param database: The SQL database
:param catalog: An optional database catalog
:param schemas: A set of candidate schemas
:param hierarchical: Whether to check using the hierarchical permission logic
:returns: The set of accessible database schemas
"""
# pylint: disable=import-outside-toplevel
from superset.connectors.sqla.models import SqlaTable
if hierarchical and (
self.can_access_database(database)
or (catalog and self.can_access_catalog(database, catalog))
):
return schemas
# schema_access
accessible_schemas: set[str] = set()
schema_access = self.user_view_menu_names("schema_access")
default_catalog = database.get_default_catalog()
default_schema = database.get_default_schema(default_catalog)
for perm in schema_access:
parts = [part[1:-1] for part in perm.split(".")]
if parts[0] != database.database_name:
continue
# [database].[schema] matches when no catalog is specified, or when the user
# specifies the default catalog
if len(parts) == 2 and (catalog is None or catalog == default_catalog):
accessible_schemas.add(parts[1])
# [database].[catalog].[schema] matches when the catalog is equal to the
# requested catalog or, when no catalog specified, it's equal to the default
# catalog.
elif len(parts) == 3 and parts[1] == (catalog or default_catalog):
accessible_schemas.add(parts[2])
# datasource_access
if perms := self.user_view_menu_names("datasource_access"):
tables = (
self.get_session.query(SqlaTable.schema)
.filter(SqlaTable.database_id == database.id)
.filter(or_(SqlaTable.perm.in_(perms)))
.distinct()
)
accessible_schemas.update(
{
table.schema or default_schema # type: ignore
for table in tables
if (table.schema or default_schema)
}
)
return schemas & accessible_schemas
def get_catalogs_accessible_by_user(
self,
database: "Database",
catalogs: set[str],
hierarchical: bool = True,
) -> set[str]:
"""
Returned a filtered list of the catalogs accessible by the user.
:param database: The SQL database
:param catalogs: A set of candidate catalogs
:param hierarchical: Whether to check using the hierarchical permission logic
:returns: The set of accessible database catalogs
"""
# pylint: disable=import-outside-toplevel
from superset.connectors.sqla.models import SqlaTable
if hierarchical and self.can_access_database(database):
return catalogs
# catalog access
accessible_catalogs: set[str] = set()
catalog_access = self.user_view_menu_names("catalog_access")
default_catalog = database.get_default_catalog()
for perm in catalog_access:
parts = [part[1:-1] for part in perm.split(".")]
if parts[0] == database.database_name:
accessible_catalogs.add(parts[1])
# schema access
schema_access = self.user_view_menu_names("schema_access")
for perm in schema_access:
parts = [part[1:-1] for part in perm.split(".")]
if parts[0] != database.database_name:
continue
if len(parts) == 2 and default_catalog:
accessible_catalogs.add(default_catalog)
elif len(parts) == 3:
accessible_catalogs.add(parts[1])
# datasource_access
if perms := self.user_view_menu_names("datasource_access"):
tables = (
self.get_session.query(SqlaTable.schema)
.filter(SqlaTable.database_id == database.id)
.filter(or_(SqlaTable.perm.in_(perms)))
.distinct()
)
accessible_catalogs.update(
{
table.catalog or default_catalog # type: ignore
for table in tables
if (table.catalog or default_catalog)
}
)
return catalogs & accessible_catalogs
def get_datasources_accessible_by_user( # pylint: disable=invalid-name
self,
database: "Database",
datasource_names: list[DatasourceName],
catalog: Optional[str] = None,
schema: Optional[str] = None,
) -> list[DatasourceName]:
"""
Filter list of SQL tables to the ones accessible by the user.
When catalog and/or schema are specified, it's assumed that all datasources in
`datasource_names` are in the given catalog/schema.
:param database: The SQL database
:param datasource_names: The list of eligible SQL tables w/ schema
:param catalog: The fallback SQL catalog if not present in the table name
:param schema: The fallback SQL schema if not present in the table name
:returns: The list of accessible SQL tables w/ schema
"""
# pylint: disable=import-outside-toplevel
from superset.connectors.sqla.models import SqlaTable
if self.can_access_database(database):
return datasource_names
if catalog:
catalog_perm = self.get_catalog_perm(database.database_name, catalog)
if catalog_perm and self.can_access("catalog_access", catalog_perm):
return datasource_names
if schema:
default_catalog = database.get_default_catalog()
schema_perm = self.get_schema_perm(
database.database_name,
catalog or default_catalog,
schema,
)
if schema_perm and self.can_access("schema_access", schema_perm):
return datasource_names
user_perms = self.user_view_menu_names("datasource_access")
catalog_perms = self.user_view_menu_names("catalog_access")
schema_perms = self.user_view_menu_names("schema_access")
user_datasources = {
DatasourceName(table.table_name, table.schema, table.catalog)
for table in SqlaTable.query_datasources_by_permissions(
database,
user_perms,
catalog_perms,
schema_perms,
)
}
return [
datasource
for datasource in datasource_names
if datasource in user_datasources
]
def merge_perm(self, permission_name: str, view_menu_name: str) -> None:
"""
Add the FAB permission/view-menu.
:param permission_name: The FAB permission name
:param view_menu_name: The FAB view-menu name
:see: SecurityManager.add_permission_view_menu
"""
logger.warning(
"This method 'merge_perm' is deprecated use add_permission_view_menu"
)
self.add_permission_view_menu(permission_name, view_menu_name)
def _is_user_defined_permission(self, perm: Model) -> bool:
"""
Return True if the FAB permission is user defined, False otherwise.
:param perm: The FAB permission
:returns: Whether the FAB permission is user defined
"""
return perm.permission.name in self.OBJECT_SPEC_PERMISSIONS
def create_custom_permissions(self) -> None:
"""
Create custom FAB permissions.
"""
self.add_permission_view_menu("all_datasource_access", "all_datasource_access")
self.add_permission_view_menu("all_database_access", "all_database_access")
self.add_permission_view_menu("all_query_access", "all_query_access")
self.add_permission_view_menu("can_csv", "Superset")
self.add_permission_view_menu("can_share_dashboard", "Superset")
self.add_permission_view_menu("can_share_chart", "Superset")
self.add_permission_view_menu("can_sqllab", "Superset")
self.add_permission_view_menu("can_view_query", "Dashboard")
self.add_permission_view_menu("can_view_chart_as_table", "Dashboard")
self.add_permission_view_menu("can_drill", "Dashboard")
self.add_permission_view_menu("can_tag", "Chart")
self.add_permission_view_menu("can_tag", "Dashboard")
def create_missing_perms(self) -> None:
"""
Creates missing FAB permissions for datasources, schemas and metrics.
"""
# pylint: disable=import-outside-toplevel
from superset.connectors.sqla.models import SqlaTable
from superset.models import core as models
logger.info("Fetching a set of all perms to lookup which ones are missing")
all_pvs = set()
for pv in self._get_all_pvms():
if pv.permission and pv.view_menu:
all_pvs.add((pv.permission.name, pv.view_menu.name))
def merge_pv(view_menu: str, perm: Optional[str]) -> None:
"""Create permission view menu only if it doesn't exist"""