5
5
import subprocess # nosec
6
6
import time
7
7
from tempfile import NamedTemporaryFile
8
- from typing import TYPE_CHECKING
8
+ from typing import TYPE_CHECKING , overload
9
9
10
10
import requests
11
11
import six
56
56
AnyCookiesType ,
57
57
AnyResolvedSettings ,
58
58
AnyResponseType ,
59
+ AnySettingsContainer ,
59
60
CombinedConfig ,
60
61
CookiesOrSessionType ,
61
62
GroupsConfig ,
62
63
GroupsSettings ,
64
+ Literal ,
63
65
MultiConfigs ,
64
66
PermissionConfigItem ,
65
67
PermissionsConfig ,
66
68
ServicesConfig ,
67
69
ServicesSettings ,
68
70
Str ,
69
71
UsersConfig ,
70
- UsersSettings
72
+ UsersSettings ,
73
+ WebhooksConfig
71
74
)
72
75
73
76
@@ -572,6 +575,36 @@ def _load_config(path_or_dict, section, allow_missing=False):
572
575
CONFIG_KNOWN_EXTENSIONS = frozenset ([".cfg" , ".json" , ".yml" , ".yaml" ])
573
576
574
577
578
+ @overload
579
+ def get_all_configs (path_or_dict , section , allow_missing = False ):
580
+ # type: (Union[Str, CombinedConfig], Literal["groups"], bool) -> GroupsConfig
581
+ ...
582
+
583
+
584
+ @overload
585
+ def get_all_configs (path_or_dict , section , allow_missing = False ):
586
+ # type: (Union[Str, CombinedConfig], Literal["users"], bool) -> UsersConfig
587
+ ...
588
+
589
+
590
+ @overload
591
+ def get_all_configs (path_or_dict , section , allow_missing = False ):
592
+ # type: (Union[Str, CombinedConfig], Literal["permissions"], bool) -> PermissionsConfig
593
+ ...
594
+
595
+
596
+ @overload
597
+ def get_all_configs (path_or_dict , section , allow_missing = False ):
598
+ # type: (Union[Str, CombinedConfig], Literal["services"], bool) -> ServicesConfig
599
+ ...
600
+
601
+
602
+ @overload
603
+ def get_all_configs (path_or_dict , section , allow_missing = False ):
604
+ # type: (Union[Str, CombinedConfig], Literal["webhooks"], bool) -> WebhooksConfig
605
+ ...
606
+
607
+
575
608
def get_all_configs (path_or_dict , section , allow_missing = False ):
576
609
# type: (Union[Str, CombinedConfig], Str, bool) -> MultiConfigs
577
610
"""
@@ -776,10 +809,9 @@ def _parse_resource_path(permission_config_entry, # type: PermissionConfigItem
776
809
777
810
res_path = None
778
811
if _use_request (cookies_or_session ):
779
- res_path = get_magpie_url () + ServiceResourcesAPI .path .format (service_name = svc_name )
812
+ res_path = magpie_url + ServiceResourcesAPI .path .format (service_name = svc_name )
780
813
res_resp = requests .get (res_path , cookies = cookies_or_session , timeout = 5 )
781
- svc_json = get_json (res_resp )[svc_name ] # type: JSON
782
- res_dict = svc_json ["resources" ]
814
+ res_dict = get_json (res_resp )[svc_name ] # type: JSON
783
815
else :
784
816
from magpie .api .management .service .service_formats import format_service_resources
785
817
svc = models .Service .by_service_name (svc_name , db_session = cookies_or_session )
@@ -860,16 +892,16 @@ def _apply_request(_usr_name=None, _grp_name=None):
860
892
Apply operation using HTTP request.
861
893
"""
862
894
action_oper = None
863
- if usr_name :
864
- action_oper = UserResourcePermissionsAPI .format (user_name = _usr_name , resource_id = resource_id )
865
- if grp_name :
866
- action_oper = GroupResourcePermissionsAPI .format (group_name = _grp_name , resource_id = resource_id )
895
+ if _usr_name :
896
+ action_oper = UserResourcePermissionsAPI .path . format (user_name = _usr_name , resource_id = resource_id )
897
+ if _grp_name :
898
+ action_oper = GroupResourcePermissionsAPI .path . format (group_name = _grp_name , resource_id = resource_id )
867
899
if not action_oper :
868
900
return None
869
901
action_func = requests .post if create_perm else requests .delete
870
902
action_body = {"permission" : perm .json ()}
871
903
action_path = "{url}{path}" .format (url = magpie_url , path = action_oper )
872
- action_resp = action_func (action_path , json = action_body , cookies = cookies_or_session )
904
+ action_resp = action_func (action_path , json = action_body , cookies = cookies_or_session , timeout = 5 )
873
905
return action_resp
874
906
875
907
def _apply_session (_usr_name = None , _grp_name = None ):
@@ -921,10 +953,10 @@ def _apply_profile(_usr_name=None, _grp_name=None):
921
953
if _use_request (cookies_or_session ):
922
954
if _usr_name :
923
955
path = "{url}{path}" .format (url = magpie_url , path = UsersAPI .path )
924
- return requests .post (path , json = usr_data , timeout = 5 )
956
+ return requests .post (path , json = usr_data , cookies = cookies_or_session , timeout = 5 )
925
957
if _grp_name :
926
958
path = "{url}{path}" .format (url = magpie_url , path = GroupsAPI .path )
927
- return requests .post (path , json = grp_data , timeout = 5 )
959
+ return requests .post (path , json = grp_data , cookies = cookies_or_session , timeout = 5 )
928
960
else :
929
961
if _usr_name :
930
962
from magpie .api .management .user .user_utils import create_user
@@ -988,13 +1020,19 @@ def _validate_response(operation, is_create, item_type="Permission"):
988
1020
_validate_response (lambda : _apply_session (usr_name , None ), is_create = create_perm )
989
1021
990
1022
991
- def magpie_register_permissions_from_config (permissions_config , magpie_url = None , db_session = None , raise_errors = False ):
992
- # type: (Union[Str, PermissionsConfig], Optional[Str], Optional[Session], bool) -> None
1023
+ def magpie_register_permissions_from_config (
1024
+ permissions_config , # type: Union[Str, PermissionsConfig]
1025
+ settings = None , # type: Optional[AnySettingsContainer]
1026
+ db_session = None , # type: Optional[Session]
1027
+ raise_errors = False , # type: bool
1028
+ ): # type: (...) -> None
993
1029
"""
994
1030
Applies `permissions` specified in configuration(s) defined as file, directory with files or literal configuration.
995
1031
996
1032
:param permissions_config: file/dir path to `permissions` config or JSON/YAML equivalent pre-loaded.
997
- :param magpie_url: URL to magpie instance (when using requests; default: `magpie.url` from this app's config).
1033
+ :param settings: Magpie settings to resolve an instance session when using requests instead of DB session.
1034
+ Will look for ``magpie.url``, ``magpie.admin_user`` and ``magpie.admin_password`` by default, or any
1035
+ corresponding environment variable resolution if omitted in the settings.
998
1036
:param db_session: db session to use instead of requests to directly create/remove permissions with config.
999
1037
:param raise_errors: raises errors related to permissions, instead of just logging the info.
1000
1038
@@ -1003,9 +1041,9 @@ def magpie_register_permissions_from_config(permissions_config, magpie_url=None,
1003
1041
"""
1004
1042
LOGGER .info ("Starting permissions processing." )
1005
1043
1044
+ magpie_url = None
1006
1045
if _use_request (db_session ):
1007
- magpie_url = magpie_url or get_magpie_url ()
1008
- settings = {"magpie.url" : magpie_url }
1046
+ magpie_url = get_magpie_url (settings )
1009
1047
LOGGER .debug ("Editing permissions using requests to [%s]..." , magpie_url )
1010
1048
err_msg = "Invalid credentials to register Magpie permissions."
1011
1049
cookies_or_session = get_admin_cookies (settings , raise_message = err_msg )
@@ -1014,19 +1052,36 @@ def magpie_register_permissions_from_config(permissions_config, magpie_url=None,
1014
1052
cookies_or_session = db_session
1015
1053
1016
1054
LOGGER .debug ("Loading configurations." )
1017
- permissions = get_all_configs (permissions_config , "permissions" ) # type: List[PermissionsConfig]
1055
+ if isinstance (permissions_config , list ):
1056
+ permissions = [permissions_config ]
1057
+ else :
1058
+ permissions = get_all_configs (permissions_config , "permissions" )
1018
1059
perms_cfg_count = len (permissions )
1019
1060
LOGGER .log (logging .INFO if perms_cfg_count else logging .WARNING ,
1020
1061
"Found %s permissions configurations." , perms_cfg_count )
1021
1062
users_settings = groups_settings = None
1022
1063
if perms_cfg_count :
1023
- users = get_all_configs (permissions_config , "users" , allow_missing = True ) # type: List[UsersConfig]
1024
- groups = get_all_configs (permissions_config , "groups" , allow_missing = True ) # type: List[GroupsConfig]
1064
+ if isinstance (permissions_config , str ):
1065
+ users = get_all_configs (permissions_config , "users" , allow_missing = True )
1066
+ else :
1067
+ users = []
1068
+ if isinstance (permissions_config , str ):
1069
+ groups = get_all_configs (permissions_config , "groups" , allow_missing = True )
1070
+ else :
1071
+ groups = []
1025
1072
users_settings = _resolve_config_registry (users , "username" ) or {}
1026
1073
groups_settings = _resolve_config_registry (groups , "name" ) or {}
1027
1074
for i , perms in enumerate (permissions ):
1028
1075
LOGGER .info ("Processing permissions from configuration (%s/%s)." , i + 1 , perms_cfg_count )
1029
- _process_permissions (perms , magpie_url , cookies_or_session , users_settings , groups_settings , raise_errors )
1076
+ _process_permissions (
1077
+ perms ,
1078
+ magpie_url ,
1079
+ cookies_or_session ,
1080
+ users_settings ,
1081
+ groups_settings ,
1082
+ settings ,
1083
+ raise_errors ,
1084
+ )
1030
1085
LOGGER .info ("All permissions processed." )
1031
1086
1032
1087
@@ -1055,16 +1110,23 @@ def _resolve_config_registry(config_files, key):
1055
1110
return config_map
1056
1111
1057
1112
1058
- def _process_permissions (permissions , magpie_url , cookies_or_session , users = None , groups = None , raise_errors = False ):
1059
- # type: (PermissionsConfig, Str, Session, Optional[UsersSettings], Optional[GroupsSettings], bool) -> None
1113
+ def _process_permissions (
1114
+ permissions , # type: PermissionsConfig
1115
+ magpie_url , # type: Str
1116
+ cookies_or_session , # type: Session
1117
+ users = None , # type: Optional[UsersSettings]
1118
+ groups = None , # type: Optional[GroupsSettings]
1119
+ settings = None , # type: Optional[AnySettingsContainer]
1120
+ raise_errors = False , # type: bool
1121
+ ): # type: (...) -> None
1060
1122
"""
1061
1123
Processes a single `permissions` configuration.
1062
1124
"""
1063
1125
if not permissions :
1064
1126
LOGGER .warning ("Permissions configuration are empty." )
1065
1127
return
1066
1128
1067
- anon_user = get_constant ("MAGPIE_ANONYMOUS_USER" )
1129
+ anon_user = get_constant ("MAGPIE_ANONYMOUS_USER" , settings )
1068
1130
perm_count = len (permissions )
1069
1131
LOGGER .log (logging .INFO if perm_count else logging .WARNING ,
1070
1132
"Found %s permissions to evaluate from configuration." , perm_count )
@@ -1103,7 +1165,8 @@ def _process_permissions(permissions, magpie_url, cookies_or_session, users=None
1103
1165
if svc_resp .status_code != 200 :
1104
1166
_handle_permission ("Unknown service [{!s}]" .format (svc_name ), i , raise_errors = raise_errors )
1105
1167
continue
1106
- service_info = get_json (svc_resp )[svc_name ]
1168
+ service_json = get_json (svc_resp )
1169
+ service_info = service_json .get (svc_name ) or service_json .get ("service" ) # format depends on magpie version
1107
1170
else :
1108
1171
transaction .commit () # force any pending transaction to be applied to find possible dependencies
1109
1172
svc = models .Service .by_service_name (svc_name , db_session = cookies_or_session )
0 commit comments