forked from openedx/openedx-authz
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
807 lines (619 loc) · 30.1 KB
/
data.py
File metadata and controls
807 lines (619 loc) · 30.1 KB
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
"""Data classes and enums for representing roles, permissions, and policies."""
from __future__ import annotations
import re
from abc import abstractmethod
from enum import Enum
from typing import Any, ClassVar, Literal, Type
from attrs import define
from opaque_keys import InvalidKeyError
from opaque_keys.edx.locator import LibraryLocatorV2
try:
from openedx.core.djangoapps.content_libraries.models import ContentLibrary
except ImportError:
ContentLibrary = None
__all__ = [
"UserData",
"PermissionData",
"GroupingPolicyIndex",
"PolicyIndex",
"ActionData",
"RoleAssignmentData",
"RoleData",
"ScopeData",
"SubjectData",
"ContentLibraryData",
]
AUTHZ_POLICY_ATTRIBUTES_SEPARATOR = "^"
EXTERNAL_KEY_SEPARATOR = ":"
GLOBAL_SCOPE_WILDCARD = "*"
NAMESPACED_KEY_PATTERN = rf"^.+{re.escape(AUTHZ_POLICY_ATTRIBUTES_SEPARATOR)}.+$"
class GroupingPolicyIndex(Enum):
"""Index positions for fields in a Casbin grouping policy (g or g2).
Grouping policies represent role assignments that link subjects to roles within scopes.
Format: [subject, role, scope, ...]
Attributes:
SUBJECT: Position 0 - The subject identifier (e.g., 'user^john_doe').
ROLE: Position 1 - The role identifier (e.g., 'role^instructor').
SCOPE: Position 2 - The scope identifier (e.g., 'lib^lib:DemoX:CSPROB').
Note:
Additional fields beyond position 2 are optional and currently ignored.
"""
SUBJECT = 0
ROLE = 1
SCOPE = 2
# The rest of the fields are optional and can be ignored for now
class PolicyIndex(Enum):
"""Index positions for fields in a Casbin policy (p).
Policies define permissions by linking roles to actions within scopes with an effect.
Format: [role, action, scope, effect, ...]
Attributes:
ROLE: Position 0 - The role identifier (e.g., 'role^instructor').
ACT: Position 1 - The action identifier (e.g., 'act^read').
SCOPE: Position 2 - The scope identifier (e.g., 'lib^lib:DemoX:CSPROB').
EFFECT: Position 3 - The effect, either 'allow' or 'deny'.
Note:
Additional fields beyond position 3 are optional and currently ignored.
"""
ROLE = 0
ACT = 1
SCOPE = 2
EFFECT = 3
# The rest of the fields are optional and can be ignored for now
class AuthzBaseClass:
"""Base class for all authz classes.
Attributes:
SEPARATOR: The separator between the namespace and the identifier (default: '^').
NAMESPACE: The namespace prefix for the data type (e.g., 'user', 'role', 'act', 'lib').
"""
SEPARATOR: ClassVar[str] = AUTHZ_POLICY_ATTRIBUTES_SEPARATOR
NAMESPACE: ClassVar[str] = None
@define
class AuthZData(AuthzBaseClass):
"""Base class for all authz data classes.
Attributes:
NAMESPACE: The namespace prefix for the data type (e.g., 'user', 'role', 'act', 'lib').
SEPARATOR: The separator between the namespace and the identifier (default: '^').
external_key: The ID for the object outside of the authz system (e.g., 'john_doe' for a user,
'instructor' for a role, 'lib:DemoX:CSPROB' for a content library).
namespaced_key: The ID for the object within the authz system, combining namespace and external_key
(e.g., 'user^john_doe', 'role^instructor', 'lib^lib:DemoX:CSPROB').
Examples:
>>> user = UserData(external_key='john_doe')
>>> user.namespaced_key
'user^john_doe'
>>> role = RoleData(namespaced_key='role^instructor')
>>> role.external_key
'instructor'
"""
external_key: str = ""
namespaced_key: str = ""
def __attrs_post_init__(self):
"""Post-initialization processing for attributes.
This method ensures that either external_key or namespaced_key is provided,
and derives the other attribute based on the NAMESPACE and SEPARATOR.
"""
if not self.NAMESPACE:
# No namespace defined, nothing to do
return
if not self.external_key and not self.namespaced_key:
raise ValueError("Either external_key or namespaced_key must be provided.")
# Case 1: Initialized with external_key only, derive namespaced_key
if not self.namespaced_key:
self.namespaced_key = f"{self.NAMESPACE}{self.SEPARATOR}{self.external_key}"
# Case 2: Initialized with namespaced_key only, derive external_key. Assume valid format for
# namespaced_key at this point.
if not self.external_key:
self.external_key = self.namespaced_key.split(self.SEPARATOR, 1)[1]
class ScopeMeta(type):
"""Metaclass for ScopeData to handle dynamic subclass instantiation based on namespace."""
scope_registry: ClassVar[dict[str, Type["ScopeData"]]] = {}
def __init__(cls, name, bases, attrs):
"""Initialize the metaclass and register subclasses."""
super().__init__(name, bases, attrs)
if not hasattr(cls, "scope_registry"):
cls.scope_registry = {}
cls.scope_registry[cls.NAMESPACE] = cls
def __call__(cls, *args, **kwargs):
"""Instantiate the appropriate ScopeData subclass dynamically.
This metaclass enables polymorphic instantiation based on either the external_key
format or the namespaced_key prefix, automatically returning the correct subclass.
Instantiation modes:
1. external_key: Determines subclass from the key format. The namespace prefix
before the first ':' is used to look up the appropriate subclass.
Example: ScopeData(external_key='lib:DemoX:CSPROB') → ContentLibraryData
2. namespaced_key: Determines subclass from the namespace prefix before '^'.
Example: ScopeData(namespaced_key='lib^lib:DemoX:CSPROB') → ContentLibraryData
Usage patterns:
- namespaced_key: Used when retrieving objects from the policy store
- external_key: Used when initializing from user input or API calls
Examples:
>>> # From external key (e.g., API input)
>>> scope = ScopeData(external_key='lib:DemoX:CSPROB')
>>> isinstance(scope, ContentLibraryData)
True
>>> # From namespaced key (e.g., policy store)
>>> scope = ScopeData(namespaced_key='lib^lib:DemoX:CSPROB')
>>> isinstance(scope, ContentLibraryData)
True
"""
if cls is not ScopeData:
return super().__call__(*args, **kwargs)
# When working with global scopes, we can't determine subclass with an external_key since
# a global scope it's not attached to a specific resource type. So we only use * as
# an external_key to mean generic scope which maps to base ScopeData class.
# The only remaining issue is that internally the namespace key used in policies will be
# The global scope namespace (global^*), so we need to handle that case here.
if kwargs.get("external_key") == GLOBAL_SCOPE_WILDCARD:
return super().__call__(*args, **kwargs)
if "namespaced_key" in kwargs:
scope_cls = cls.get_subclass_by_namespaced_key(kwargs["namespaced_key"])
return super(ScopeMeta, scope_cls).__call__(*args, **kwargs)
if "external_key" in kwargs:
scope_cls = cls.get_subclass_by_external_key(kwargs["external_key"])
return super(ScopeMeta, scope_cls).__call__(*args, **kwargs)
return super().__call__(*args, **kwargs)
@classmethod
def get_subclass_by_namespaced_key(mcs, namespaced_key: str) -> Type["ScopeData"]:
"""Get the appropriate ScopeData subclass from the namespaced key.
Extracts the namespace prefix (before '^') and returns the registered subclass.
Args:
namespaced_key: The namespaced key (e.g., 'lib^lib:DemoX:CSPROB', 'global^generic').
Returns:
The ScopeData subclass for the namespace, or ScopeData if namespace not recognized.
Examples:
>>> ScopeMeta.get_subclass_by_namespaced_key('lib^lib:DemoX:CSPROB')
<class 'ContentLibraryData'>
>>> ScopeMeta.get_subclass_by_namespaced_key('global^generic')
<class 'ScopeData'>
"""
# TODO: Default separator, can't access directly from class so made it a constant
if not re.match(NAMESPACED_KEY_PATTERN, namespaced_key):
raise ValueError(f"Invalid namespaced_key format: {namespaced_key}")
namespace = namespaced_key.split(AUTHZ_POLICY_ATTRIBUTES_SEPARATOR, 1)[0]
return mcs.scope_registry.get(namespace, ScopeData)
@classmethod
def get_subclass_by_external_key(mcs, external_key: str) -> Type["ScopeData"]:
"""Get the appropriate ScopeData subclass from the external key format.
Extracts the namespace from the external key (before the first ':') and validates
the key format using the subclass's validate_external_key method.
Args:
external_key: The external key (e.g., 'lib:DemoX:CSPROB', 'global:generic').
Returns:
The ScopeData subclass corresponding to the namespace.
Raises:
ValueError: If the external_key format is invalid or namespace is not recognized.
Examples:
>>> ScopeMeta.get_subclass_by_external_key('lib:DemoX:CSPROB')
<class 'ContentLibraryData'>
Notes:
- The external_key format should be 'namespace:some-identifier' (e.g., 'lib:DemoX:CSPROB').
- The namespace prefix before ':' is used to determine the subclass.
- Each subclass must implement validate_external_key() to verify the full key format.
- This won't work for org scopes that don't have explicit namespace prefixes.
TODO: Handle org scopes differently.
"""
if EXTERNAL_KEY_SEPARATOR not in external_key:
raise ValueError(f"Invalid external_key format: {external_key}")
namespace = external_key.split(EXTERNAL_KEY_SEPARATOR, 1)[0]
scope_subclass = mcs.scope_registry.get(namespace)
if not scope_subclass:
raise ValueError(f"Unknown scope: {namespace} for external_key: {external_key}")
if not scope_subclass.validate_external_key(external_key):
raise ValueError(f"Invalid external_key format: {external_key}")
return scope_subclass
@classmethod
def get_all_namespaces(mcs) -> dict[str, Type["ScopeData"]]:
"""Get all registered scope namespaces.
Returns:
dict[str, Type["ScopeData"]]: A dictionary of all namespace prefixes registered in the scope registry.
Each namespace corresponds to a ScopeData subclass (e.g., 'lib', 'global').
Examples:
>>> ScopeMeta.get_all_namespaces()
{'global': ScopeData, 'lib': ContentLibraryData, 'org': OrganizationData}
"""
return mcs.scope_registry
@classmethod
def validate_external_key(mcs, external_key: str) -> bool:
"""Validate the external_key format for the subclass.
Args:
external_key: The external key to validate.
Returns:
bool: True if valid, False otherwise.
"""
raise NotImplementedError("Subclasses must implement validate_external_key method.")
@define
class ScopeData(AuthZData, metaclass=ScopeMeta):
"""A scope is a context in which roles and permissions are assigned.
This is the base class for scope types. Specific scope types (like ContentLibraryData)
are subclasses with their own namespace prefixes. This class is supposed to be generic
and not tied to any specific scope type, holding attributes common to all scopes.
Attributes:
NAMESPACE: 'global' for generic scopes.
external_key: The scope identifier without namespace (e.g., 'generic_scope').
namespaced_key: The scope identifier with namespace (e.g., 'global^generic_scope').
Examples:
>>> scope = ScopeData(external_key='generic_scope')
>>> scope.namespaced_key
'global^generic_scope'
"""
# The 'global' namespace is used for scopes that aren't tied to a specific resource type.
# This base class supports:
# 1. Global wildcard scopes (external_key='*') that apply across all resource types
# 2. Custom global scopes that don't map to specific domain objects (e.g., 'global:some_scope')
# Subclasses like ContentLibraryData ('lib') represent concrete resource types with their own namespaces.
NAMESPACE: ClassVar[str] = "global"
@classmethod
def validate_external_key(cls, _: str) -> bool:
"""Validate the external_key format for ScopeData.
For the base ScopeData class, we accept any external_key works. This
is only implemented for the sake of completeness. Subclasses should
implement their own validation logic.
Args:
external_key: The external key to validate.
Returns:
bool: True if valid, False otherwise.
"""
return True
@abstractmethod
def get_object(self) -> Any | None:
"""Retrieve the underlying domain object that this scope represents.
This method fetches the actual Open edX object (e.g., ContentLibrary, Organization)
associated with this scope's external_key. Subclasses should implement this to return
their specific object types.
Returns:
Any | None: The domain object associated with this scope, or None if the object
does not exist or cannot be retrieved.
"""
raise NotImplementedError("Subclasses must implement get_object method.")
@abstractmethod
def exists(self) -> bool:
"""Check if the scope exists.
Returns:
bool: True if the scope exists, False otherwise.
"""
raise NotImplementedError("Subclasses must implement exists method.")
@define
class ContentLibraryData(ScopeData):
"""A content library scope for authorization in the Open edX platform.
Content libraries use the LibraryLocatorV2 format for identification.
Attributes:
NAMESPACE: 'lib' for content library scopes.
external_key: The content library identifier (e.g., 'lib:DemoX:CSPROB').
Must be a valid LibraryLocatorV2 format.
namespaced_key: The library identifier with namespace (e.g., 'lib^lib:DemoX:CSPROB').
library_id: Property alias for external_key.
Examples:
>>> library = ContentLibraryData(external_key='lib:DemoX:CSPROB')
>>> library.namespaced_key
'lib^lib:DemoX:CSPROB'
>>> library.library_id
'lib:DemoX:CSPROB'
Note:
TODO: this class should live alongside library definitions and not here.
"""
NAMESPACE: ClassVar[str] = "lib"
@property
def library_id(self) -> str:
"""The library identifier as used in Open edX (e.g., 'lib:DemoX:CSPROB').
This is an alias for external_key that represents the library ID without the namespace prefix.
Returns:
str: The library identifier without namespace.
"""
return self.external_key
@property
def library_key(self) -> LibraryLocatorV2:
"""The LibraryLocatorV2 object for the content library.
Returns:
LibraryLocatorV2: The library locator object.
"""
return LibraryLocatorV2.from_string(self.library_id)
@classmethod
def validate_external_key(cls, external_key: str) -> bool:
"""Validate the external_key format for ContentLibraryData.
Args:
external_key: The external key to validate.
Returns:
bool: True if valid, False otherwise.
"""
try:
LibraryLocatorV2.from_string(external_key)
return True
except InvalidKeyError:
return False
def get_object(self) -> ContentLibrary | None:
"""Retrieve the ContentLibrary instance associated with this scope.
This method converts the library_id to a LibraryLocatorV2 key and queries the
database to fetch the corresponding ContentLibrary object.
Returns:
ContentLibrary | None: The ContentLibrary instance if found in the database,
or None if the library does not exist or has an invalid key format.
Examples:
>>> library_scope = ContentLibraryData(external_key='lib:DemoX:CSPROB')
>>> library_obj = library_scope.get_object() # ContentLibrary object
"""
try:
library_obj = ContentLibrary.objects.get_by_key(self.library_key)
# Validate canonical key: get_by_key is case-insensitive, but we require exact match
# This ensures authorization uses canonical library IDs consistently
if library_obj.library_key != self.library_key:
raise ContentLibrary.DoesNotExist
except (InvalidKeyError, ContentLibrary.DoesNotExist):
return None
return library_obj
def exists(self) -> bool:
"""Check if the content library exists.
Returns:
bool: True if the content library exists, False otherwise.
"""
return self.get_object() is not None
def __str__(self):
"""Human readable string representation of the content library."""
return self.library_id
def __repr__(self):
"""Developer friendly string representation of the content library."""
return self.namespaced_key
class SubjectMeta(type):
"""Metaclass for SubjectData to handle dynamic subclass instantiation based on namespace."""
subject_registry: ClassVar[dict[str, Type["SubjectData"]]] = {}
def __init__(cls, name, bases, attrs):
"""Initialize the metaclass and register subclasses."""
super().__init__(name, bases, attrs)
if not hasattr(cls, "subject_registry"):
cls.subject_registry = {}
cls.subject_registry[cls.NAMESPACE] = cls
def __call__(cls, *args, **kwargs):
"""Instantiate the appropriate SubjectData subclass dynamically.
This metaclass enables polymorphic instantiation based on the namespaced_key prefix,
automatically returning the correct subclass.
Instantiation mode:
- namespaced_key: Determines subclass from the namespace prefix before '^'.
Example: SubjectData(namespaced_key='user^john_doe') → UserData
Examples:
>>> subject = SubjectData(namespaced_key='user^alice')
>>> isinstance(subject, UserData)
True
>>> subject = SubjectData(namespaced_key='sub^generic')
>>> isinstance(subject, SubjectData)
True
Note:
Currently, we cannot instantiate by external_key alone because we don't have
a way to determine the subclass from the external_key format. Use the specific
subclass directly (e.g., UserData(external_key='alice')) when needed.
"""
if cls is SubjectData and "namespaced_key" in kwargs:
subject_cls = cls.get_subclass_by_namespaced_key(kwargs["namespaced_key"])
return super(SubjectMeta, subject_cls).__call__(*args, **kwargs)
return super().__call__(*args, **kwargs)
@classmethod
def get_subclass_by_namespaced_key(mcs, namespaced_key: str) -> Type["SubjectData"]:
"""Get the appropriate SubjectData subclass from the namespaced key.
Extracts the namespace prefix (before '^') and returns the registered subclass.
Args:
namespaced_key: The namespaced key (e.g., 'user^alice', 'sub^generic').
Returns:
The SubjectData subclass for the namespace, or SubjectData if namespace not recognized.
Examples:
>>> SubjectMeta.get_subclass_by_namespaced_key('user^alice')
<class 'UserData'>
>>> SubjectMeta.get_subclass_by_namespaced_key('sub^generic')
<class 'SubjectData'>
"""
namespace = namespaced_key.split(AUTHZ_POLICY_ATTRIBUTES_SEPARATOR, 1)[0]
return mcs.subject_registry.get(namespace, SubjectData)
@define
class SubjectData(AuthZData, metaclass=SubjectMeta):
"""A subject is an entity that can be assigned roles and permissions.
This is the base class for subject types. Specific subject types (like UserData)
are subclasses with their own namespace prefixes.
Attributes:
NAMESPACE: 'sub' for generic subjects.
external_key: The subject identifier without namespace (e.g., 'generic').
namespaced_key: The subject identifier with namespace (e.g., 'sub^generic').
Examples:
>>> subject = SubjectData(external_key='generic')
>>> subject.namespaced_key
'sub^generic'
"""
NAMESPACE: ClassVar[str] = "sub"
@define
class UserData(SubjectData):
"""A user subject for authorization in the Open edX platform.
This class represents individual users who can be assigned roles and permissions.
Can be initialized with either external_key or namespaced_key parameter.
Attributes:
NAMESPACE: 'user' for user subjects.
external_key: The username (e.g., 'john_doe').
namespaced_key: The username with namespace prefix (e.g., 'user^john_doe').
username: Property alias for external_key.
Examples:
>>> user = UserData(external_key='john_doe')
>>> user.namespaced_key
'user^john_doe'
>>> user.username
'john_doe'
>>> user2 = UserData(namespaced_key='user^jane_smith')
>>> user2.username
'jane_smith'
"""
NAMESPACE: ClassVar[str] = "user"
@property
def username(self) -> str:
"""The username for the user (e.g., 'john_doe').
This is an alias for external_key that represents the username without the namespace prefix.
Returns:
str: The username without namespace.
"""
return self.external_key
def __str__(self):
"""Human readable string representation of the user."""
return self.username
def __repr__(self):
"""Developer friendly string representation of the user."""
return self.namespaced_key
@define
class ActionData(AuthZData):
"""An action represents an operation that can be performed in the authorization system.
Actions are the operations that can be allowed or denied in authorization policies.
Attributes:
NAMESPACE: 'act' for actions.
external_key: The action identifier (e.g., 'content_libraries.view_library').
namespaced_key: The action identifier with namespace (e.g., 'act^content_libraries.view_library').
name: Property that returns a human-readable action name (e.g., 'Content Libraries > View Library').
Examples:
>>> action = ActionData(external_key='content_libraries.delete_library')
>>> action.namespaced_key
'act^content_libraries.delete_library'
>>> action.name
'Content Libraries > Delete Library'
"""
NAMESPACE: ClassVar[str] = "act"
@property
def name(self) -> str:
"""The human-readable name of the action (e.g., 'Content Libraries > Delete Library').
This property transforms the external_key into a human-readable display name
by replacing dots with ' > ' and capitalizing each word.
Returns:
str: The human-readable action name (e.g., 'Content Libraries > Delete Library').
"""
parts = self.external_key.split(".")
return " > ".join(part.replace("_", " ").title() for part in parts)
def __str__(self):
"""Human readable string representation of the action."""
return self.name
def __repr__(self):
"""Developer friendly string representation of the action."""
return self.namespaced_key
@define
class PermissionData:
"""A permission combines an action with an effect (allow or deny).
Permissions define whether a specific action should be allowed or denied.
They are typically associated with roles in the authorization system.
Attributes:
action: The action being permitted or denied (ActionData instance).
effect: The effect of the permission, either 'allow' or 'deny' (default: 'allow').
Examples:
>>> read_action = ActionData(external_key='read')
>>> permission = PermissionData(action=read_action, effect='allow')
>>> str(permission)
'Read - allow'
>>> write_action = ActionData(external_key='write')
>>> deny_perm = PermissionData(action=write_action, effect='deny')
>>> str(deny_perm)
'Write - deny'
"""
action: ActionData = None
effect: Literal["allow", "deny"] = "allow"
@property
def identifier(self) -> str:
"""Get the permission identifier.
Returns:
str: The permission identifier (e.g., 'content_libraries.delete_library').
"""
return self.action.external_key
def __eq__(self, other: "PermissionData") -> bool:
"""Compare permissions based on their action identifier.
Two PermissionData instances are considered equal if they have the same action's
external_key and effect.
Args:
other: Another PermissionData instance or any object.
Returns:
bool: True if the actions match, False otherwise.
Example:
>>> perm1 = PermissionData(action=ActionData(external_key='view'), effect='allow')
>>> perm2 = PermissionData(action=ActionData(external_key='view'), effect='allow')
>>> perm1 == perm2 # True - same action and effect
True
>>> perm1 in [perm2] # Uses __eq__
True
"""
if self.action is None or other.action is None:
return False
return self.action.external_key == other.action.external_key and self.effect == other.effect
def __str__(self):
"""Human readable string representation of the permission and its effect."""
return f"{self.action} - {self.effect}"
def __repr__(self):
"""Developer friendly string representation of the permission."""
return f"{self.action.namespaced_key} => {self.effect}"
@define(eq=False)
class RoleData(AuthZData):
"""A role is a named collection of permissions that can be assigned to subjects.
Roles group related permissions together for easier authorization management.
Attributes:
NAMESPACE: 'role' for roles.
external_key: The role identifier (e.g., 'instructor', 'library_admin').
namespaced_key: The role identifier with namespace (e.g., 'role^instructor').
permissions: A list of PermissionData instances associated with this role.
name: Property that returns a human-readable role name (e.g., 'Instructor', 'Library Admin').
Examples:
>>> role = RoleData(external_key='instructor')
>>> role.namespaced_key
'role^instructor'
>>> role.name
'Instructor'
>>> action = ActionData(external_key='read')
>>> perm = PermissionData(action=action, effect='allow')
>>> role_with_perms = RoleData(external_key='instructor', permissions=[perm])
>>> str(role_with_perms)
'Instructor: Read - allow'
"""
NAMESPACE: ClassVar[str] = "role"
permissions: list[PermissionData] = []
def __eq__(self, other):
"""Compare roles based on their namespaced_key."""
if not isinstance(other, RoleData):
return False
return self.namespaced_key == other.namespaced_key
@property
def name(self) -> str:
"""The human-readable name of the role (e.g., 'Library Admin', 'Course Instructor').
This property transforms the external_key into a human-readable display name
by replacing underscores with spaces and capitalizing each word.
Returns:
str: The human-readable role name (e.g., 'Library Admin').
"""
return self.external_key.replace("_", " ").title()
def get_permission_identifiers(self) -> list[str]:
"""Get the technical identifiers for all permissions in this role.
Returns:
list[str]: Permission identifiers
(e.g., ['content_libraries.delete_library', 'content_libraries.edit_library_content']).
"""
return [permission.identifier for permission in self.permissions]
def __str__(self):
"""Human readable string representation of the role and its permissions."""
return f"{self.name}: {', '.join(str(p) for p in self.permissions)}"
def __repr__(self):
"""Developer friendly string representation of the role."""
return self.namespaced_key
@define
class RoleAssignmentData:
"""A role assignment links a subject, roles, and a scope together.
Role assignments represent the authorization grants in the system. They specify
that a particular subject (e.g., a user) has certain roles within a specific scope
(e.g., a content library).
Attributes:
subject: The subject (e.g., UserData) to whom roles are assigned.
roles: A list of RoleData instances being assigned to the subject.
scope: The scope (e.g., ContentLibraryData) in which the roles apply.
Examples:
>>> user = UserData(external_key='john_doe')
>>> role = RoleData(external_key='instructor')
>>> library = ContentLibraryData(external_key='lib:DemoX:CSPROB')
>>> assignment = RoleAssignmentData(subject=user, roles=[role], scope=library)
>>> str(assignment)
'john_doe => Instructor @ lib:DemoX:CSPROB'
>>> repr(assignment)
'user^john_doe => [role^instructor] @ lib^lib:DemoX:CSPROB'
"""
subject: SubjectData = None # Needs defaults to avoid value error from attrs
roles: list[RoleData] = []
scope: ScopeData = None
def __str__(self):
"""Human readable string representation of the role assignment."""
role_names = ", ".join(role.name for role in self.roles)
return f"{self.subject} => {role_names} @ {self.scope}"
def __repr__(self):
"""Developer friendly string representation of the role assignment."""
role_keys = ", ".join(role.namespaced_key for role in self.roles)
return f"{self.subject.namespaced_key} => [{role_keys}] @ {self.scope.namespaced_key}"