-
Notifications
You must be signed in to change notification settings - Fork 14.3k
/
Copy pathapi.py
368 lines (352 loc) · 11.4 KB
/
api.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
# 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.
import logging
from typing import Any
from flask import request, Response
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import ngettext
from marshmallow import ValidationError
from sqlalchemy.exc import SQLAlchemyError
from superset.commands.exceptions import (
DatasourceNotFoundValidationError,
RolesNotFoundValidationError,
)
from superset.commands.security.create import CreateRLSRuleCommand
from superset.commands.security.delete import DeleteRLSRuleCommand
from superset.commands.security.exceptions import RLSRuleNotFoundError
from superset.commands.security.update import UpdateRLSRuleCommand
from superset.connectors.sqla.models import RowLevelSecurityFilter
from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP, RouteMethod
from superset.extensions import event_logger
from superset.row_level_security.schemas import (
get_delete_ids_schema,
openapi_spec_methods_override,
RLSListSchema,
RLSPostSchema,
RLSPutSchema,
RLSShowSchema,
)
from superset.views.base import DatasourceFilter
from superset.views.base_api import (
BaseSupersetModelRestApi,
RelatedFieldFilter,
requires_json,
statsd_metrics,
)
from superset.views.filters import (
BaseFilterRelatedRoles,
BaseFilterRelatedUsers,
FilterRelatedOwners,
)
logger = logging.getLogger(__name__)
class RLSRestApi(BaseSupersetModelRestApi):
datamodel = SQLAInterface(RowLevelSecurityFilter)
include_route_methods = RouteMethod.REST_MODEL_VIEW_CRUD_SET | {
RouteMethod.RELATED,
"bulk_delete",
}
resource_name = "rowlevelsecurity"
class_permission_name = "Row Level Security"
openapi_spec_tag = "Row Level Security"
method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
allow_browser_login = True
list_columns = [
"id",
"name",
"filter_type",
"tables.id",
"tables.table_name",
"roles.id",
"roles.name",
"clause",
"changed_on_delta_humanized",
"changed_by.first_name",
"changed_by.last_name",
"changed_by.id",
"group_key",
]
order_columns = [
"name",
"filter_type",
"clause",
"changed_on_delta_humanized",
"group_key",
]
add_columns = [
"name",
"description",
"filter_type",
"tables",
"roles",
"group_key",
"clause",
]
show_columns = [
"name",
"description",
"filter_type",
"tables.id",
"tables.schema",
"tables.table_name",
"roles.id",
"roles.name",
"group_key",
"clause",
]
search_columns = (
"name",
"description",
"filter_type",
"tables",
"roles",
"group_key",
"clause",
"created_by",
"changed_by",
)
edit_columns = add_columns
show_model_schema = RLSShowSchema()
list_model_schema = RLSListSchema()
add_model_schema = RLSPostSchema()
edit_model_schema = RLSPutSchema()
allowed_rel_fields = {"tables", "roles", "created_by", "changed_by"}
related_field_filters = {
"changed_by": RelatedFieldFilter("first_name", FilterRelatedOwners),
}
base_related_field_filters = {
"tables": [["id", DatasourceFilter, lambda: []]],
"roles": [["id", BaseFilterRelatedRoles, lambda: []]],
"changed_by": [["id", BaseFilterRelatedUsers, lambda: []]],
}
openapi_spec_methods = openapi_spec_methods_override
""" Overrides GET methods OpenApi descriptions """
@expose("/", methods=("POST",))
@protect()
@safe
@statsd_metrics
@requires_json
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
log_to_statsd=False,
)
def post(self) -> Response:
"""Create a new RLS rule.
---
post:
summary: Create a new RLS rule
requestBody:
description: RLS schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
responses:
201:
description: RLS Rule added
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
try:
item = self.add_model_schema.load(request.json)
except ValidationError as error:
return self.response_400(message=error.messages)
try:
new_model = CreateRLSRuleCommand(item).run()
return self.response(201, id=new_model.id, result=item)
except RolesNotFoundValidationError as ex:
logger.error(
"Role not found while creating RLS rule %s: %s",
self.__class__.__name__,
str(ex),
exc_info=True,
)
return self.response_422(message=str(ex))
except DatasourceNotFoundValidationError as ex:
logger.error(
"Table not found while creating RLS rule %s: %s",
self.__class__.__name__,
str(ex),
exc_info=True,
)
return self.response_422(message=str(ex))
except SQLAlchemyError as ex:
logger.error(
"Error creating RLS rule %s: %s",
self.__class__.__name__,
str(ex),
exc_info=True,
)
return self.response_422(message=str(ex))
@expose("/<int:pk>", methods=("PUT",))
@protect()
@safe
@statsd_metrics
@requires_json
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.put",
log_to_statsd=False,
)
def put(self, pk: int) -> Response:
"""Update an RLS rule.
---
put:
summary: Update an RLS rule
parameters:
- in: path
schema:
type: integer
name: pk
description: The Rule pk
requestBody:
description: RLS schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
responses:
200:
description: Rule changed
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
try:
item = self.edit_model_schema.load(request.json)
except ValidationError as error:
return self.response_400(message=error.messages)
try:
new_model = UpdateRLSRuleCommand(pk, item).run()
return self.response(201, id=new_model.id, result=item)
except RolesNotFoundValidationError as ex:
logger.error(
"Role not found while updating RLS rule %s: %s",
self.__class__.__name__,
str(ex),
exc_info=True,
)
return self.response_422(message=str(ex))
except DatasourceNotFoundValidationError as ex:
logger.error(
"Table not found while updating RLS rule %s: %s",
self.__class__.__name__,
str(ex),
exc_info=True,
)
return self.response_422(message=str(ex))
except SQLAlchemyError as ex:
logger.error(
"Error updating RLS rule %s: %s",
self.__class__.__name__,
str(ex),
exc_info=True,
)
return self.response_422(message=str(ex))
except RLSRuleNotFoundError:
return self.response_404()
@expose("/", methods=("DELETE",))
@protect()
@safe
@statsd_metrics
@rison(get_delete_ids_schema)
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.bulk_delete",
log_to_statsd=False,
)
def bulk_delete(self, **kwargs: Any) -> Response:
"""Bulk delete RLS rules.
---
delete:
summary: Bulk delete RLS rules
parameters:
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_delete_ids_schema'
responses:
200:
description: RLS Rule bulk delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
item_ids = kwargs["rison"]
try:
DeleteRLSRuleCommand(item_ids).run()
return self.response(
200,
message=ngettext(
"Deleted %(num)d rules",
"Deleted %(num)d rules",
num=len(item_ids),
),
)
except RLSRuleNotFoundError:
return self.response_404()