-
Notifications
You must be signed in to change notification settings - Fork 47
/
access_policy.py
198 lines (156 loc) · 6.41 KB
/
access_policy.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
import importlib
from typing import List
from django.conf import settings
from rest_access_policy import AccessPolicyException
from rest_framework import permissions
class AccessPolicy(permissions.BasePermission):
statements = []
id = None
group_prefix = "group:"
id_prefix = "id:"
def has_permission(self, request, view) -> bool:
action = self._get_invoked_action(view)
statements = self.get_policy_statements(request, view)
if len(statements) == 0:
return False
return self._evaluate_statements(statements, request, view, action)
def get_policy_statements(self, request, view) -> List[dict]:
return self.statements
def get_user_group_values(self, user) -> List[str]:
return list(user.groups.values_list("name", flat=True))
@classmethod
def scope_queryset(cls, request, qs):
return qs.none()
def _get_invoked_action(self, view) -> str:
"""
If a CBV, the name of the method. If a regular function view,
the name of the function.
"""
if hasattr(view, "action"):
return view.action
elif hasattr(view, "__class__"):
return view.__class__.__name__
raise AccessPolicyException("Could not determine action of request")
def _evaluate_statements(
self, statements: List[dict], request, view, action: str
) -> bool:
statements = self._normalize_statements(statements)
matched = self._get_statements_matching_principal(request, statements)
matched = self._get_statements_matching_action(request, action, matched)
matched = self._get_statements_matching_context_conditions(
request, view, action, matched
)
denied = [_ for _ in matched if _["effect"] != "allow"]
if len(matched) == 0 or len(denied) > 0:
return False
return True
def _normalize_statements(self, statements=[]) -> List[dict]:
for statement in statements:
if isinstance(statement["principal"], str):
statement["principal"] = [statement["principal"]]
if isinstance(statement["action"], str):
statement["action"] = [statement["action"]]
if "condition" not in statement:
statement["condition"] = []
elif isinstance(statement["condition"], str):
statement["condition"] = [statement["condition"]]
return statements
def _get_statements_matching_principal(
self, request, statements: List[dict]
) -> List[dict]:
user = request.user
user_roles = self.get_user_group_values(user)
matched = []
for statement in statements:
principals = statement["principal"]
found = False
if "*" in principals:
found = True
elif "authenticated" in principals:
found = not user.is_anonymous
elif "anonymous" in principals:
found = user.is_anonymous
elif self.id_prefix + str(user.id) in principals:
found = True
else:
for user_role in user_roles:
if self.group_prefix + user_role in principals:
found = True
break
if found:
matched.append(statement)
return matched
def _get_statements_matching_action(
self, request, action: str, statements: List[dict]
):
"""
Filter statements and return only those that match the specified
action.
"""
matched = []
SAFE_METHODS = ("GET", "HEAD", "OPTIONS")
for statement in statements:
if action in statement["action"] or "*" in statement["action"]:
matched.append(statement)
elif (
"<safe_methods>" in statement["action"]
and request.method in SAFE_METHODS
):
matched.append(statement)
return matched
def _get_statements_matching_context_conditions(
self, request, view, action: str, statements: List[dict]
):
"""
Filter statements and only return those that match all of their
custom context conditions; if no conditions are provided then
the statement should be returned.
"""
matched = []
for statement in statements:
if len(statement["condition"]) == 0:
matched.append(statement)
continue
fails = 0
for condition in statement["condition"]:
passed = self._check_condition(condition, request, view, action)
if not passed:
fails += 1
break
if fails == 0:
matched.append(statement)
return matched
def _check_condition(self, condition: str, request, view, action: str):
"""
Evaluate a custom context condition; if method does not exist on
the access policy class, then return False.
Condition value can contain a value that is passed to method, if
formatted as `<method_name>:<arg_value>`.
"""
parts = condition.split(":", 1)
method_name = parts[0]
arg = parts[1] if len(parts) == 2 else None
method = self._get_condition_method(method_name)
if arg is not None:
result = method(request, view, action, arg)
else:
result = method(request, view, action)
if type(result) is not bool:
raise AccessPolicyException(
"condition '%s' must return true/false, not %s"
% (condition, type(result))
)
return result
def _get_condition_method(self, method_name: str):
if hasattr(self, method_name):
return getattr(self, method_name)
if hasattr(settings, "DRF_ACCESS_POLICY"):
module_path = settings.DRF_ACCESS_POLICY.get("reusable_conditions")
if module_path:
module = importlib.import_module(module_path)
if hasattr(module, method_name):
return getattr(module, method_name)
raise AccessPolicyException(
"condition '%s' must be a method on the access policy or be defined in the 'reusable_conditions' module"
% method_name
)