-
Notifications
You must be signed in to change notification settings - Fork 18
/
models.py
1317 lines (1074 loc) · 45.7 KB
/
models.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
import uuid
import contextvars
from hashlib import md5
import warnings
import numpy as np
import sqlalchemy as sa
import traceback
import requests
from slugify import slugify
from sqlalchemy import func
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import sessionmaker, scoped_session, relationship
from sqlalchemy_utils import EmailType, PhoneNumberType
from .custom_exceptions import AccessError
from .json_util import to_json
from .env import load_env
session_context_id = contextvars.ContextVar('request_id', default=None)
DBSession = scoped_session(sessionmaker(), scopefunc=session_context_id.get)
env, cfg = load_env()
strict = cfg['security.strict']
use_webhook = cfg['security.slack.enabled']
webhook_url = cfg['security.slack.url']
def handle_inaccessible(mode, row_or_rows, accessor):
tb = ''.join(traceback.extract_stack().format())
tb = f'```{tb}```'
# format the error message
original_shape = np.asarray(row_or_rows).shape
standardized = np.atleast_1d(row_or_rows).tolist()
row_typename = type(standardized[0]).__name__
row_id_or_ids = np.asarray([r.id for r in standardized]).reshape(original_shape).tolist()
err_msg = (
f'Insufficient permissions for operation '
f'"{type(accessor).__name__} {accessor.id} '
f'{mode} {row_typename} {row_id_or_ids}".'
)
err_msg_w_traceback = err_msg + f'Original traceback: {tb}'
if use_webhook:
try:
requests.post(webhook_url, json={'text': err_msg_w_traceback})
except requests.HTTPError as e:
post_fail_warn_msg = f'Encountered HTTPError "{e.args[0]}" ' \
f'attempting to post AccessError "{err_msg}"' \
f'to {webhook_url}.'
warnings.warn(post_fail_warn_msg)
else:
warnings.warn(err_msg)
if strict:
raise AccessError(err_msg)
# https://docs.sqlalchemy.org/en/13/dialects/postgresql.html#psycopg2-fast-execution-helpers
# executemany_values_page_size arguments control how many parameter sets
# should be represented in each execution of an INSERT
# 50000 was chosen based on recommendations in the docs and on profiling tests
EXECUTEMANY_PAGESIZE = 50000
utcnow = func.timezone('UTC', func.current_timestamp())
# The db has to be initialized later; this is done by the app itself
# See `app_server.py`
def init_db(user, database, password=None, host=None, port=None, autoflush=True):
url = 'postgresql://{}:{}@{}:{}/{}'
url = url.format(user, password or '', host or '', port or '', database)
conn = sa.create_engine(
url,
client_encoding='utf8',
executemany_mode='values',
executemany_values_page_size=EXECUTEMANY_PAGESIZE,
)
DBSession.configure(bind=conn, autoflush=autoflush)
Base.metadata.bind = conn
return conn
class SlugifiedStr(sa.types.TypeDecorator):
"""Slugified string"""
impl = sa.String
# Used with INSERT
def process_bind_param(self, value, dialect):
return slugify(value)
# Used with SELECT
def process_result_value(self, value, dialect):
return value
class UserAccessControl:
"""Logic for controlling user access to database records. Mapped classes
can set their create, read, update, or delete attributes to subclasses of
this class to ensure they are only accessed by users or tokens with the
requisite permissions.
"""
@staticmethod
def check_cls_for_attributes(cls, attrs):
"""Check that a target class has the specified attributes. If not,
raise a TypeError.
Parameters
----------
cls: `baselayer.app.models.DeclarativeMeta`
The class to check.
attrs: list of str
The names of the attributes to check for.
"""
for attr in attrs:
if not hasattr(cls, attr):
raise TypeError(
f'{cls} does not have the attribute "{attr}", '
f'and thus does not expose the interface that is needed '
f'to check for access.'
)
@staticmethod
def user_id_from_user_or_token(user_or_token):
"""Return the user_id associated with a specified User or Token object.
Parameters
----------
user_or_token: `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
Returns
-------
user_id: int
The user_id associated with the User or Token object.
"""
if isinstance(user_or_token, User):
return user_or_token.id
elif isinstance(user_or_token, Token):
return user_or_token.created_by_id
else:
raise ValueError(
'user_or_token must be an instance of User or Token, '
f'got {user_or_token.__class__.__name__}.'
)
def query_accessible_rows(self, cls, user_or_token, columns=None):
"""Construct a Query object that, when executed, returns the rows of a
specified table that are accessible to a specified user or token.
Parameters
----------
cls: `baselayer.app.models.DeclarativeMeta`
The mapped class of the target table.
user_or_token: `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
columns: list of sqlalchemy.Column, optional, default None
The columns to retrieve from the target table. If None, queries
the mapped class directly and returns mapped instances.
Returns
-------
query: sqlalchemy.Query
Query for the accessible rows.
"""
raise NotImplementedError
def __and__(self, other):
"""Return a policy that is the logical AND of two UserAccessControls.
Parameters
----------
other: UserAccessControl
The access control to combine with this one.
Returns
-------
composed: ComposedAccessControl
The UserAccessControl representing the logical AND of the input access
controls.
Examples
--------
Create an access control that grants access if the querying user is the record
owner AND the user that most recently modified the record
>>>> accessible_if_is_owner = AccessibleIfUserMatches('owner')
>>>> accessible_if_is_last_modifier = AccessibleIfUserMatches('last_modified_by')
>>>> access_control = accessible_if_is_owner & accessible_if_is_last_modifier
"""
try:
retval = ComposedAccessControl(self, other, logic='and')
except TypeError:
raise TypeError(
f"unsupported operand type(s) for &: '{type(self).__name__}' "
f"and '{type(other).__name__}'"
)
return retval
def __or__(self, other):
"""Return a policy that is the logical OR of two UserAccessControls.
Parameters
----------
other: UserAccessControl
The access control to combine with this one.
Returns
-------
composed: ComposedAccessControl
The UserAccessControl representing the logical OR of the input access
controls.
Examples
--------
Create an access control that grants access if the querying user is the record
owner OR the user that most recently modified the record
>>>> accessible_if_is_owner = AccessibleIfUserMatches('owner')
>>>> accessible_if_is_last_modifier = AccessibleIfUserMatches('last_modified_by')
>>>> access_control = accessible_if_is_owner | accessible_if_is_last_modifier
"""
try:
retval = ComposedAccessControl(self, other, logic='or')
except TypeError:
raise TypeError(
f"unsupported operand type(s) for |: '{type(self).__name__}' "
f"and '{type(other).__name__}'"
)
return retval
class Public(UserAccessControl):
"""A record accessible to anyone."""
def query_accessible_rows(self, cls, user_or_token, columns=None):
"""Construct a Query object that, when executed, returns the rows of a
specified table that are accessible to a specified user or token.
Parameters
----------
cls: `baselayer.app.models.DeclarativeMeta`
The mapped class of the target table.
user_or_token: `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
columns: list of sqlalchemy.Column, optional, default None
The columns to retrieve from the target table. If None, queries
the mapped class directly and returns mapped instances.
Returns
-------
query: sqlalchemy.Query
Query for the accessible rows.
"""
if columns is not None:
return DBSession().query(*columns).select_from(cls)
return DBSession().query(cls)
public = Public()
class AccessibleIfUserMatches(UserAccessControl):
def __init__(self, relationship_chain):
"""A class that grants access to users related to a specific record
through a chain of relationships.
Parameters
----------
relationship_chain: str
The chain of relationships to check the User or Token against in
`query_accessible_rows`. Should be specified as
>>>> f'{relationship1_name}.{relationship2_name}...{relationshipN_name}'
The first relationship should be defined on the target class, and
each subsequent relationship should be defined on the class pointed
to by the previous relationship. If the querying user matches any
record pointed to by the final relationship, the logic will grant
access to the querying user.
Examples
--------
Grant access if the querying user matches the user pointed to by
the target class's `author` relationship:
>>>> AccessibleIfUserMatches('author')
Grant access if the querying user is a member of one of the target
class's groups:
>>>> AccessibleIfUserMatches('groups.users')
"""
self.relationship_chain = relationship_chain
def query_accessible_rows(self, cls, user_or_token, columns=None):
"""Construct a Query object that, when executed, returns the rows of a
specified table that are accessible to a specified user or token.
Parameters
----------
cls: `baselayer.app.models.DeclarativeMeta`
The mapped class of the target table.
user_or_token: `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
columns: list of sqlalchemy.Column, optional, default None
The columns to retrieve from the target table. If None, queries
the mapped class directly and returns mapped instances.
Returns
-------
query: sqlalchemy.Query
Query for the accessible rows.
"""
# system admins automatically get full access
if user_or_token.is_admin:
return public.query_accessible_rows(cls, user_or_token, columns=columns)
# return only selected columns if requested
if columns is not None:
query = DBSession().query(*columns).select_from(cls)
else:
query = DBSession().query(cls)
# traverse the relationship chain via sequential JOINs
for relationship_name in self.relationship_names:
self.check_cls_for_attributes(cls, [relationship_name])
relationship = sa.inspect(cls).mapper.relationships[relationship_name]
# not a private attribute, just has an underscore to avoid name
# collision with python keyword
cls = relationship.entity.class_
query = query.join(relationship.class_attribute)
# filter for records with at least one matching user
user_id = self.user_id_from_user_or_token(user_or_token)
query = query.filter(cls.id == user_id)
return query
@property
def relationship_chain(self):
return self._relationship_key
@relationship_chain.setter
def relationship_chain(self, value):
"""Validate the formatting for passed relationship chains, raise when
users attempt to pass incorrectly formatted chain strings."""
if not isinstance(value, str):
raise ValueError(
f'Invalid value for relationship chain: {value}, expected str, '
f'got {value.__class__.__name__}'
)
relationship_names = value.split('.')
if len(relationship_names) < 1:
raise ValueError('Need at least 1 relationship to join on.')
self._relationship_key = value
@property
def relationship_names(self):
"""List of names of each relationship in the chain."""
return self.relationship_chain.split('.')
accessible_by_owner = AccessibleIfUserMatches('owner')
accessible_by_created_by = AccessibleIfUserMatches('created_by')
accessible_by_user = AccessibleIfUserMatches('user')
class AccessibleIfRelatedRowsAreAccessible(UserAccessControl):
def __init__(self, **properties_and_modes):
"""A class that grants access to users only if related rows are also
accessible to those users. This class automatically grants access to
Users with the "System admin" ACL.
Parameters
----------
properties_and_modes: dict
Dict mapping relationship names to access types (e.g., 'create',
'read', 'update', 'delete'). In order for a user to access a record
protected with this logic, they must be able to access the records
pointed to by the relationship with the specified type of access.
Examples
--------
Grant access if the querying user can read the "created_by" record
pointed to by a target record:
>>>> AccessibleIfRelatedRowsAreAccessible(created_by="read")
Grant access if the querying user can read the "created_by" and update
the "last_modified_by" records pointed to by a target record:
>>>> AccessibleIfRelatedRowsAreAccessible(created_by="read", last_modified_by="update")
"""
self.properties_and_modes = properties_and_modes
@property
def properties_and_modes(self):
return self._properties_and_modes
@properties_and_modes.setter
def properties_and_modes(self, value):
"""Validate that properties and modes are correctly specified,
raise if not."""
if not isinstance(value, dict):
raise ValueError(
f'properties_and_modes must be an instance of dict, '
f'got {value.__class__.__name__}'
)
if len(value) == 0:
raise ValueError("Need at least 1 property to check.")
self._properties_and_modes = value
def query_accessible_rows(self, cls, user_or_token, columns=None):
"""Construct a Query object that, when executed, returns the rows of a
specified table that are accessible to a specified user or token.
Parameters
----------
cls: `baselayer.app.models.DeclarativeMeta`
The mapped class of the target table.
user_or_token: `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
columns: list of sqlalchemy.Column, optional, default None
The columns to retrieve from the target table. If None, queries
the mapped class directly and returns mapped instances.
Returns
-------
query: sqlalchemy.Query
Query for the accessible rows.
"""
# only return specified columns if requested
if columns is None:
base = DBSession().query(cls)
else:
base = DBSession().query(*columns).select_from(cls)
# ensure the target class has all the relationships referred to
# in this instance
self.check_cls_for_attributes(cls, self.properties_and_modes)
# construct the list of accessible records by joining the target
# table against accessible related rows via their relationships
# to the target table
for prop in self.properties_and_modes:
# get the kind of access required on the relationship
mode = self.properties_and_modes[prop]
relationship = sa.inspect(cls).mapper.relationships[prop]
# join the target table to the related table on the relationship
base = base.join(relationship.class_attribute)
# get the rows of the target table that are accessible
join_target = relationship.entity.class_
logic = getattr(join_target, mode)
# create a subquery for the accessible rows of the related table
# and join that subquery to the related table on the PK/FK.
# from a performance perspective this should be about as performant
# as aliasing the related table. The subquery is automatically
# de-subbed by postgres and uses all available indices.
accessible_related_rows = logic.query_accessible_rows(
join_target, user_or_token, columns=[join_target.id]
).subquery()
join_condition = accessible_related_rows.c.id == join_target.id
base = base.join(accessible_related_rows, join_condition)
return base
class ComposedAccessControl(UserAccessControl):
def __init__(self, *access_controls, logic="and"):
"""A policy that is the logical AND or logical OR of other
UserAccessControls.
Parameters
----------
access_controls: list of `UserAccessControl`
The access controls to compose.
logic: "and" or "or", default "and"
How to combine the access controls. If "and", all conditions must
be satisfied for access to be granted. If "or", only one of the
conditions must be satisfied for access to be granted.
Examples
--------
Grant access if the querying user matches the 'owner' relationship of
this record or if the querying user is a member of at least one of the
record's groups:
>>>> ComposedAccessControl(AccessibleIfUserMatches('owner'), AccessibleIfUserMatches('groups.users'), logic='or')
"""
self.access_controls = access_controls
self.logic = logic
@property
def access_controls(self):
return self._access_controls
@access_controls.setter
def access_controls(self, value):
"""Validate the input access controls."""
error = ValueError(
f'access_controls must be a list or tuple of '
f'UserAccessControl, got {value.__class__.__name__}'
)
if not isinstance(value, (list, tuple)):
raise error
for v in value:
if not isinstance(v, UserAccessControl):
raise error
self._access_controls = value
@property
def logic(self):
return self._logic
@logic.setter
def logic(self, value):
"""Validate the input logic."""
if value not in ['and', 'or']:
raise ValueError(
f'composition logic must be either "and" or "or", got {value}.'
)
self._logic = value
def query_accessible_rows(self, cls, user_or_token, columns=None):
"""Construct a Query object that, when executed, returns the rows of a
specified table that are accessible to a specified user or token.
Parameters
----------
cls: `baselayer.app.models.DeclarativeMeta`
The mapped class of the target table.
user_or_token: `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
columns: list of sqlalchemy.Column, optional, default None
The columns to retrieve from the target table. If None, queries
the mapped class directly and returns mapped instances.
Returns
-------
query: sqlalchemy.Query
Query for the accessible rows.
"""
# retrieve specified columns if requested
if columns is not None:
query = DBSession().query(*columns).select_from(cls)
else:
query = DBSession().query(cls)
# keep track of columns that will be null in the case of an unsuccessful
# match for OR logic.
accessible_id_cols = []
for access_control in self.access_controls:
# use an alias to avoid name collisions.
target_alias = sa.orm.aliased(cls)
# join against the first access control using a subquery. from a
# performance perspective this should be about as performant as
# aliasing the related table, but is much better for avoiding
# name collisions. The subquery is automatically de-subbed by
# postgres and uses all available indices.
accessible = access_control.query_accessible_rows(
target_alias, user_or_token, columns=[target_alias.id]
).subquery()
# join on the FK
join_condition = accessible.c.id == cls.id
if self.logic == 'and':
# for and logic, we want an INNER join
query = query.join(accessible, join_condition)
elif self.logic == 'or':
# for OR logic we dont want to lose rows where there is no
# for one particular type of access control, so use outer join
# here
query = query.outerjoin(accessible, join_condition)
else:
raise ValueError(
f'Invalid composition logic: {self.logic}, must be either "and" or "or".'
)
accessible_id_cols.append(accessible.c.id)
# in the case of or logic, require that only one of the conditions be
# met for each row
if self.logic == 'or':
query = query.filter(
sa.or_(*[col.isnot(None) for col in accessible_id_cols])
)
return query
class Restricted(UserAccessControl):
"""A record that can only be accessed by a System Admin."""
def query_accessible_rows(self, cls, user_or_token, columns=None):
"""Construct a Query object that, when executed, returns the rows of a
specified table that are accessible to a specified user or token.
Parameters
----------
cls: `baselayer.app.models.DeclarativeMeta`
The mapped class of the target table.
user_or_token: `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
columns: list of sqlalchemy.Column, optional, default None
The columns to retrieve from the target table. If None, queries
the mapped class directly and returns mapped instances.
Returns
-------
query: sqlalchemy.Query
Query for the accessible rows.
"""
# system admins have access to restricted records
if user_or_token.is_admin:
return public.query_accessible_rows(cls, user_or_token, columns=columns)
# otherwise, all records are inaccessible
if columns is not None:
return (
DBSession().query(*columns).select_from(cls).filter(sa.literal(False))
)
return DBSession().query(cls).filter(sa.literal(False))
restricted = Restricted()
class CustomUserAccessControl(UserAccessControl):
def __init__(self, query_or_query_generator):
"""A UserAccessControl that uses explicit, user-provided logic to
designate accessible records.
Parameters
----------
query_or_query_generator: `sqlalchemy.orm.Query` or func
The logic for determining which records are accessible to a
user.
In cases where the access control logic is the same for all
users, this class can be directly initialized from an SQLAlchemy
Query object. The query should render a SELECT on the table on
which access permissions are to be enforced, returning only rows
that are accessible under the policy (See Example 1 below).
In cases where the access control logic is different for
different users, the class should be instantiated with a function
that takes two arguments, cls (the mapped class corresponding to
the table on which access permissions are to be enforced) and
user_or_token, the instance of `baselayer.app.models.User` or
`baselayer.app.models.Token` to check permissions for (See Example 2
below). The function should then return a `sqlalchemy.orm.Query`
object that, when executed, returns the rows accessible to that User
or Token.
Examples
--------
(1) Only permit access to departments in which all employees are
managers
>>>> CustomUserAccessControl(
DBSession().query(Department).join(Employee).group_by(
Department.id
).having(sa.func.bool_and(Employee.is_manager.is_(True)))
)
(2) Permit access to all records for system admins, otherwise, only
permit access to departments in which all employees are managers
>>>> def access_logic(cls, user_or_token):
... if user_or_token.is_system_admin:
... return DBSession().query(cls)
... return DBSession().query(cls).join(Employee).group_by(
... cls.id
... ).having(sa.func.bool_and(Employee.is_manager.is_(True)))
>>>> CustomUserAccessControl(access_logic)
"""
if isinstance(query_or_query_generator, sa.orm.Query):
self.query = query_or_query_generator
self.query_generator = None
elif hasattr(query_or_query_generator, '__call__'):
self.query = None
self.query_generator = query_or_query_generator
else:
raise TypeError(f'Invalid type for query: '
f'{type(query_or_query_generator).__name__}, '
f'expected `sqlalchemy.orm.Query` or func.')
def query_accessible_rows(self, cls, user_or_token, columns=None):
"""Construct a Query object that, when executed, returns the rows of a
specified table that are accessible to a specified user or token.
Parameters
----------
cls: `baselayer.app.models.DeclarativeMeta`
The mapped class of the target table.
user_or_token: `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
columns: list of sqlalchemy.Column, optional, default None
The columns to retrieve from the target table. If None, queries
the mapped class directly and returns mapped instances.
Returns
-------
query: sqlalchemy.Query
Query for the accessible rows.
"""
if self.query is not None:
query = self.query
else:
query = self.query_generator(cls, user_or_token)
# retrieve specified columns if requested
if columns is not None:
query = query.with_entities(*columns)
return query
class BaseMixin:
# permission control logic
create = read = public
update = delete = restricted
def is_accessible_by(self, user_or_token, mode="read"):
"""Check if a User or Token has a specified type of access to this
database record.
Parameters
----------
user_or_token: `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
mode: string
Type of access to check.
Returns
-------
accessible: bool
Whether the User or Token has the specified type of access to
the record.
"""
# get the classmethod that determines whether a record of type `cls` is
# accessible to a user or token
cls = type(self)
logic = getattr(cls, mode)
# Construct the join from which accessibility can be selected.
accessibility_target = (sa.func.count('*') > 0).label(f'{mode}_ok')
accessibility_table = logic.query_accessible_rows(
cls, user_or_token, columns=[accessibility_target]
).filter(cls.id == self.id)
# Query for the value of the access_func for this particular record and
# return the result.
result = accessibility_table.scalar()
if not isinstance(result, bool):
raise RuntimeError(
f'Non-boolean result ({result}) from operation '
f'"{type(user_or_token).__name__} {user_or_token.id} '
f'{mode} {cls.__name__} {self.id}".'
)
return result
@classmethod
def get_if_accessible_by(
cls, cls_id, user_or_token, mode="read", raise_if_none=False, options=[],
):
"""Return a database record if it is accessible to the specified User or
Token. If no record exists, return None. If the record exists but is
inaccessible, raise an `AccessError`.
Parameters
----------
cls_id: int, str, iterable of int, iterable of str
The primary key(s) of the record(s) to query for.
user_or_token: `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
mode: string
Type of access to check. Valid choices are `['create', 'read', 'update',
'delete']`.
options: list of `sqlalchemy.orm.MapperOption`s
Options that will be passed to `options()` in the loader query.
Returns
-------
record: `baselayer.app.models.Base` or list of `baselayer.app.models.Base`
The requested record(s). Has the same shape as `cls_id`.
"""
original_shape = np.asarray(cls_id).shape
standardized = np.atleast_1d(cls_id)
result = []
# TODO: vectorize this
for pk in standardized:
instance = cls.query.options(options).get(pk.item())
if instance is not None:
if not instance.is_accessible_by(user_or_token, mode=mode):
raise AccessError(
f'Insufficient permissions for operation '
f'"{type(user_or_token).__name__} {user_or_token.id} '
f'{mode} {cls.__name__} {instance.id}".'
)
elif raise_if_none:
raise AccessError(f'Invalid {cls.__name__} id: {pk}')
result.append(instance)
return np.asarray(result).reshape(original_shape).tolist()
@classmethod
def get_records_accessible_by(
cls, user_or_token, mode="read", options=[], columns=None
):
"""Retrieve all database records accessible by the specified User or
token.
Parameters
----------
user_or_token: `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
mode: string
Type of access to check. Valid choices are `['create', 'read', 'update',
'delete']`.
options: list of `sqlalchemy.orm.MapperOption`s
Options that will be passed to `options()` in the loader query.
Returns
-------
records: list of `baselayer.app.models.Base`
The records accessible to the specified user or token.
"""
return cls.query_records_accessible_by(
user_or_token, mode=mode, options=options, columns=columns
).all()
@classmethod
def query_records_accessible_by(
cls, user_or_token, mode="read", options=[], columns=None
):
"""Return the query for all database records accessible by the
specified User or token.
Parameters
----------
user_or_token: `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
mode: string
Type of access to check. Valid choices are `['create', 'read', 'update',
'delete']`.
options: list of `sqlalchemy.orm.MapperOption`s
Options that will be passed to `options()` in the loader query.
Returns
-------
query: sqlalchemy.Query
The query for the specified records.
"""
if not isinstance(user_or_token, (User, Token)):
raise ValueError(
'user_or_token must be an instance of User or Token, '
f'got {user_or_token.__class__.__name__}.'
)
logic = getattr(cls, mode)
return logic.query_accessible_rows(cls, user_or_token, columns=columns).options(
options
)
query = DBSession.query_property()
id = sa.Column(sa.Integer, primary_key=True, doc='Unique object identifier.')
created_at = sa.Column(
sa.DateTime,
nullable=False,
default=utcnow,
index=True,
doc="UTC time of insertion of object's row into the database.",
)
modified = sa.Column(
sa.DateTime,
default=utcnow,
onupdate=utcnow,
nullable=False,
doc="UTC time the object's row was last modified in the database.",
)
@declared_attr
def __tablename__(cls):
"""The name of this class's mapped database table."""
return cls.__name__.lower() + 's'
__mapper_args__ = {'confirm_deleted_rows': False}
def __str__(self):
return to_json(self)
def __repr__(self):
attr_list = [
f"{c.name}={getattr(self, c.name)}" for c in self.__table__.columns
]
return f"<{type(self).__name__}({', '.join(attr_list)})>"
def to_dict(self):
"""Serialize this object to a Python dictionary."""
if sa.inspection.inspect(self).expired:
DBSession().refresh(self)
return {k: v for k, v in self.__dict__.items() if not k.startswith('_')}
@classmethod
def get_if_readable_by(cls, ident, user_or_token, options=[]):
"""Return an object from the database if the requesting User or Token
has access to read the object. If the requesting User or Token does not
have access, raise an AccessError.
Parameters
----------
ident : integer or string
Primary key of the requested object.
user_or_token : `baselayer.app.models.User` or `baselayer.app.models.Token`
The requesting `User` or `Token` object.
options : list of `sqlalchemy.orm.MapperOption`s
Options that wil be passed to `options()` in the loader query.
Returns
-------
obj : baselayer.app.models.Base
The requested entity.
"""
obj = cls.query.options(options).get(ident)
if obj is not None and not obj.is_readable_by(user_or_token):
raise AccessError('Insufficient permissions.')
return obj
def is_readable_by(self, user_or_token):
"""Return a boolean indicating whether a User or Token has read access
to this object.
Parameters
----------
user_or_token : `baselayer.app.models.User` or `baselayer.app.models.Token`
The User or Token to check.
Returns
-------
readable : bool
Whether this object is readable to the user.
"""
raise NotImplementedError("Ownership logic is application-specific")
@classmethod
def create_or_get(cls, id):
"""Return a new `cls` if an instance with the specified primary key
does not exist, else return the existing instance."""
obj = cls.query.get(id)
if obj is not None:
return obj
else:
return cls(id=id)