django-cedar 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- django_cedar-0.1.0/LICENSE +202 -0
- django_cedar-0.1.0/PKG-INFO +190 -0
- django_cedar-0.1.0/README.md +163 -0
- django_cedar-0.1.0/pyproject.toml +75 -0
- django_cedar-0.1.0/src/django_cedar/__init__.py +29 -0
- django_cedar-0.1.0/src/django_cedar/apps.py +10 -0
- django_cedar-0.1.0/src/django_cedar/authz.py +299 -0
- django_cedar-0.1.0/src/django_cedar/checks.py +91 -0
- django_cedar-0.1.0/src/django_cedar/py.typed +0 -0
- django_cedar-0.1.0/src/django_cedar/views.py +189 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: django-cedar
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cedar policy-based authorization for Django
|
|
5
|
+
Keywords: django,cedar,authorization,authz,policy
|
|
6
|
+
Author: Andy Caine
|
|
7
|
+
Author-email: Andy Caine <andy@hyperscale.consulting>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Framework :: Django
|
|
12
|
+
Classifier: Framework :: Django :: 5.2
|
|
13
|
+
Classifier: Framework :: Django :: 6.0
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Security
|
|
20
|
+
Requires-Dist: cedarpy>=4.8.1
|
|
21
|
+
Requires-Dist: django>=5.2
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Project-URL: Homepage, https://github.com/hyperscale-consulting/django-cedar
|
|
24
|
+
Project-URL: Changelog, https://github.com/hyperscale-consulting/django-cedar/blob/main/CHANGELOG.md
|
|
25
|
+
Project-URL: Issues, https://github.com/hyperscale-consulting/django-cedar/issues
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# django-cedar
|
|
29
|
+
|
|
30
|
+
[Cedar](https://www.cedarpolicy.com/) policy-based authorization for Django.
|
|
31
|
+
|
|
32
|
+
Cedar is an open-source policy language for expressive, analyzable
|
|
33
|
+
permissions. django-cedar lets you express *who can do what* in Cedar policy
|
|
34
|
+
files instead of scattering permission logic through your views, and enforces
|
|
35
|
+
those policies with class-based-view mixins.
|
|
36
|
+
|
|
37
|
+
## Requirements
|
|
38
|
+
|
|
39
|
+
- Python 3.12+
|
|
40
|
+
- Django 5.2+
|
|
41
|
+
|
|
42
|
+
Your user model must subclass
|
|
43
|
+
`django.contrib.auth.models.AbstractUser`. The Cedar principal type is always
|
|
44
|
+
`User`, regardless of the model's class name.
|
|
45
|
+
|
|
46
|
+
## Installation
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install django-cedar
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Add the app (optional, but recommended — it enables startup-time
|
|
53
|
+
configuration checks via Django's system check framework):
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
INSTALLED_APPS = [
|
|
57
|
+
# ...
|
|
58
|
+
"django_cedar",
|
|
59
|
+
]
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Quickstart
|
|
63
|
+
|
|
64
|
+
**1. Write a policy file** (`policies.cedar` next to `manage.py`):
|
|
65
|
+
|
|
66
|
+
```cedar
|
|
67
|
+
// Staff can do anything
|
|
68
|
+
permit(principal, action, resource)
|
|
69
|
+
when { principal.is_staff };
|
|
70
|
+
|
|
71
|
+
// Anyone signed in can view widgets
|
|
72
|
+
permit(principal is User, action == Action::"ViewWidget", resource);
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
**2. Point Django at it:**
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
CEDAR_POLICY_PATH = "policies.cedar" # relative paths resolve against BASE_DIR
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
**3. Enforce it in your views:**
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from django_cedar.views import AuthorizedDetailView
|
|
85
|
+
|
|
86
|
+
from .models import Widget
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class WidgetDetailView(AuthorizedDetailView):
|
|
90
|
+
model = Widget
|
|
91
|
+
action_names = {"GET": "ViewWidget"}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Every request is authorized in `dispatch()`. The Cedar request is built as:
|
|
95
|
+
|
|
96
|
+
- **principal** — `User::"<pk>"` for authenticated users, `Anonymous::"guest"`
|
|
97
|
+
otherwise. User entities carry `id`, `is_staff` and `is_superuser`
|
|
98
|
+
attributes, and the user's Django groups become parent entities
|
|
99
|
+
(`Group::"<name>"`), so `principal in Group::"editors"` works out of the box.
|
|
100
|
+
- **action** — `Action::"<name>"` from the view's `action_names` mapping
|
|
101
|
+
(HTTP method → action name). HEAD requests are authorized using the view's
|
|
102
|
+
`"GET"` action mapping; a `"HEAD"` key in `action_names` is not consulted.
|
|
103
|
+
- **resource** — the object returned by the view's `get_resource()` hook, as
|
|
104
|
+
`<ModelClass>::"<pk>"`; `System::"global"` when there is no resource.
|
|
105
|
+
|
|
106
|
+
Denied requests raise `django.core.exceptions.PermissionDenied` (HTTP 403).
|
|
107
|
+
|
|
108
|
+
## Views and mixins
|
|
109
|
+
|
|
110
|
+
| Class | Resource used for the check |
|
|
111
|
+
|---|---|
|
|
112
|
+
| `AuthorizedDetailView` / `AuthorizedUpdateView` / `AuthorizedDeleteView` | `self.get_object()` |
|
|
113
|
+
| `AuthorizedListView` / `AuthorizedCreateView` / `AuthorizedTemplateView` / `AuthorizedFormView` | `System::"global"` (override `get_resource()`) |
|
|
114
|
+
|
|
115
|
+
Compose the behavior yourself with `CedarAuthorizationMixin` plus:
|
|
116
|
+
|
|
117
|
+
- `ResourceIsCurrentObjectMixin` — authorize against `self.get_object()`.
|
|
118
|
+
- `CurrentUserScopedMixin` — authorize against the current user and filter
|
|
119
|
+
the queryset to `user=<request.user>`.
|
|
120
|
+
- `AsyncLoginRequiredMixin` — a `LoginRequiredMixin` that works on async
|
|
121
|
+
views. `CedarAuthorizationMixin` itself supports async views too.
|
|
122
|
+
|
|
123
|
+
Custom scoping is one method:
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
class ProjectScopedView(CedarAuthorizationMixin, ListView):
|
|
127
|
+
action_names = {"GET": "ListTasks"}
|
|
128
|
+
|
|
129
|
+
def get_resource(self, request):
|
|
130
|
+
return Project.objects.get(pk=self.kwargs["project_pk"])
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Exposing model attributes to policies
|
|
134
|
+
|
|
135
|
+
Models opt in to exposing attributes with `authz_fields()`, and pull related
|
|
136
|
+
entities into the request with `authz_related_entities()`:
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
class Task(models.Model):
|
|
140
|
+
project = models.ForeignKey(Project, on_delete=models.CASCADE)
|
|
141
|
+
status = models.CharField(max_length=20)
|
|
142
|
+
|
|
143
|
+
def authz_fields(self):
|
|
144
|
+
return {"status": self.status, "project": str(self.project_id)}
|
|
145
|
+
|
|
146
|
+
def authz_related_entities(self):
|
|
147
|
+
return [self.project]
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
```cedar
|
|
151
|
+
permit(principal, action == Action::"CloseTask", resource is Task)
|
|
152
|
+
when { resource.status == "open" };
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Settings
|
|
156
|
+
|
|
157
|
+
| Setting | Required | Description |
|
|
158
|
+
|---|---|---|
|
|
159
|
+
| `CEDAR_POLICY_PATH` | yes | Path to the Cedar policy file. Relative paths resolve against `BASE_DIR`. |
|
|
160
|
+
| `CEDAR_PRINCIPAL_ATTRIBUTE_PROVIDERS` | no | List of dotted paths to classes with `get_attributes(user) -> dict` (extra principal attributes) and optionally `get_entities(user) -> iterable[Entity]` (extra entities). |
|
|
161
|
+
| `CEDAR_CONTEXT_PROVIDERS` | no | List of dotted paths to classes with `get_context(user, action, resource) -> dict`. Results are deep-merged into the Cedar request context in list order; a per-call `context=` argument merges last and wins. |
|
|
162
|
+
|
|
163
|
+
Example context provider:
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
class FeatureFlagContext:
|
|
167
|
+
def get_context(self, user, action, resource):
|
|
168
|
+
return {"allow": {"self_signup": settings.ALLOW_SELF_SIGNUP}}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Using the engine directly
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
from django_cedar import create_authz
|
|
175
|
+
|
|
176
|
+
authz = create_authz() # loads policies + providers from settings (cached)
|
|
177
|
+
authz.authorize(request.user, "ExportReport", report) # raises PermissionDenied on deny
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
## System checks
|
|
181
|
+
|
|
182
|
+
With `django_cedar` in `INSTALLED_APPS`, `manage.py check` (and every server
|
|
183
|
+
start) verifies that `CEDAR_POLICY_PATH` is set and the file exists
|
|
184
|
+
(`django_cedar.E001`/`E002`), that it parses as Cedar (`E003`), that the
|
|
185
|
+
provider settings are lists or tuples (`E006`), and that all configured
|
|
186
|
+
providers import and have the right methods (`E004`/`E005`).
|
|
187
|
+
|
|
188
|
+
## License
|
|
189
|
+
|
|
190
|
+
Apache-2.0
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
# django-cedar
|
|
2
|
+
|
|
3
|
+
[Cedar](https://www.cedarpolicy.com/) policy-based authorization for Django.
|
|
4
|
+
|
|
5
|
+
Cedar is an open-source policy language for expressive, analyzable
|
|
6
|
+
permissions. django-cedar lets you express *who can do what* in Cedar policy
|
|
7
|
+
files instead of scattering permission logic through your views, and enforces
|
|
8
|
+
those policies with class-based-view mixins.
|
|
9
|
+
|
|
10
|
+
## Requirements
|
|
11
|
+
|
|
12
|
+
- Python 3.12+
|
|
13
|
+
- Django 5.2+
|
|
14
|
+
|
|
15
|
+
Your user model must subclass
|
|
16
|
+
`django.contrib.auth.models.AbstractUser`. The Cedar principal type is always
|
|
17
|
+
`User`, regardless of the model's class name.
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install django-cedar
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Add the app (optional, but recommended — it enables startup-time
|
|
26
|
+
configuration checks via Django's system check framework):
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
INSTALLED_APPS = [
|
|
30
|
+
# ...
|
|
31
|
+
"django_cedar",
|
|
32
|
+
]
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Quickstart
|
|
36
|
+
|
|
37
|
+
**1. Write a policy file** (`policies.cedar` next to `manage.py`):
|
|
38
|
+
|
|
39
|
+
```cedar
|
|
40
|
+
// Staff can do anything
|
|
41
|
+
permit(principal, action, resource)
|
|
42
|
+
when { principal.is_staff };
|
|
43
|
+
|
|
44
|
+
// Anyone signed in can view widgets
|
|
45
|
+
permit(principal is User, action == Action::"ViewWidget", resource);
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
**2. Point Django at it:**
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
CEDAR_POLICY_PATH = "policies.cedar" # relative paths resolve against BASE_DIR
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
**3. Enforce it in your views:**
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from django_cedar.views import AuthorizedDetailView
|
|
58
|
+
|
|
59
|
+
from .models import Widget
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class WidgetDetailView(AuthorizedDetailView):
|
|
63
|
+
model = Widget
|
|
64
|
+
action_names = {"GET": "ViewWidget"}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Every request is authorized in `dispatch()`. The Cedar request is built as:
|
|
68
|
+
|
|
69
|
+
- **principal** — `User::"<pk>"` for authenticated users, `Anonymous::"guest"`
|
|
70
|
+
otherwise. User entities carry `id`, `is_staff` and `is_superuser`
|
|
71
|
+
attributes, and the user's Django groups become parent entities
|
|
72
|
+
(`Group::"<name>"`), so `principal in Group::"editors"` works out of the box.
|
|
73
|
+
- **action** — `Action::"<name>"` from the view's `action_names` mapping
|
|
74
|
+
(HTTP method → action name). HEAD requests are authorized using the view's
|
|
75
|
+
`"GET"` action mapping; a `"HEAD"` key in `action_names` is not consulted.
|
|
76
|
+
- **resource** — the object returned by the view's `get_resource()` hook, as
|
|
77
|
+
`<ModelClass>::"<pk>"`; `System::"global"` when there is no resource.
|
|
78
|
+
|
|
79
|
+
Denied requests raise `django.core.exceptions.PermissionDenied` (HTTP 403).
|
|
80
|
+
|
|
81
|
+
## Views and mixins
|
|
82
|
+
|
|
83
|
+
| Class | Resource used for the check |
|
|
84
|
+
|---|---|
|
|
85
|
+
| `AuthorizedDetailView` / `AuthorizedUpdateView` / `AuthorizedDeleteView` | `self.get_object()` |
|
|
86
|
+
| `AuthorizedListView` / `AuthorizedCreateView` / `AuthorizedTemplateView` / `AuthorizedFormView` | `System::"global"` (override `get_resource()`) |
|
|
87
|
+
|
|
88
|
+
Compose the behavior yourself with `CedarAuthorizationMixin` plus:
|
|
89
|
+
|
|
90
|
+
- `ResourceIsCurrentObjectMixin` — authorize against `self.get_object()`.
|
|
91
|
+
- `CurrentUserScopedMixin` — authorize against the current user and filter
|
|
92
|
+
the queryset to `user=<request.user>`.
|
|
93
|
+
- `AsyncLoginRequiredMixin` — a `LoginRequiredMixin` that works on async
|
|
94
|
+
views. `CedarAuthorizationMixin` itself supports async views too.
|
|
95
|
+
|
|
96
|
+
Custom scoping is one method:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
class ProjectScopedView(CedarAuthorizationMixin, ListView):
|
|
100
|
+
action_names = {"GET": "ListTasks"}
|
|
101
|
+
|
|
102
|
+
def get_resource(self, request):
|
|
103
|
+
return Project.objects.get(pk=self.kwargs["project_pk"])
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Exposing model attributes to policies
|
|
107
|
+
|
|
108
|
+
Models opt in to exposing attributes with `authz_fields()`, and pull related
|
|
109
|
+
entities into the request with `authz_related_entities()`:
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
class Task(models.Model):
|
|
113
|
+
project = models.ForeignKey(Project, on_delete=models.CASCADE)
|
|
114
|
+
status = models.CharField(max_length=20)
|
|
115
|
+
|
|
116
|
+
def authz_fields(self):
|
|
117
|
+
return {"status": self.status, "project": str(self.project_id)}
|
|
118
|
+
|
|
119
|
+
def authz_related_entities(self):
|
|
120
|
+
return [self.project]
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
```cedar
|
|
124
|
+
permit(principal, action == Action::"CloseTask", resource is Task)
|
|
125
|
+
when { resource.status == "open" };
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Settings
|
|
129
|
+
|
|
130
|
+
| Setting | Required | Description |
|
|
131
|
+
|---|---|---|
|
|
132
|
+
| `CEDAR_POLICY_PATH` | yes | Path to the Cedar policy file. Relative paths resolve against `BASE_DIR`. |
|
|
133
|
+
| `CEDAR_PRINCIPAL_ATTRIBUTE_PROVIDERS` | no | List of dotted paths to classes with `get_attributes(user) -> dict` (extra principal attributes) and optionally `get_entities(user) -> iterable[Entity]` (extra entities). |
|
|
134
|
+
| `CEDAR_CONTEXT_PROVIDERS` | no | List of dotted paths to classes with `get_context(user, action, resource) -> dict`. Results are deep-merged into the Cedar request context in list order; a per-call `context=` argument merges last and wins. |
|
|
135
|
+
|
|
136
|
+
Example context provider:
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
class FeatureFlagContext:
|
|
140
|
+
def get_context(self, user, action, resource):
|
|
141
|
+
return {"allow": {"self_signup": settings.ALLOW_SELF_SIGNUP}}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## Using the engine directly
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
from django_cedar import create_authz
|
|
148
|
+
|
|
149
|
+
authz = create_authz() # loads policies + providers from settings (cached)
|
|
150
|
+
authz.authorize(request.user, "ExportReport", report) # raises PermissionDenied on deny
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
## System checks
|
|
154
|
+
|
|
155
|
+
With `django_cedar` in `INSTALLED_APPS`, `manage.py check` (and every server
|
|
156
|
+
start) verifies that `CEDAR_POLICY_PATH` is set and the file exists
|
|
157
|
+
(`django_cedar.E001`/`E002`), that it parses as Cedar (`E003`), that the
|
|
158
|
+
provider settings are lists or tuples (`E006`), and that all configured
|
|
159
|
+
providers import and have the right methods (`E004`/`E005`).
|
|
160
|
+
|
|
161
|
+
## License
|
|
162
|
+
|
|
163
|
+
Apache-2.0
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "django-cedar"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Cedar policy-based authorization for Django"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "Andy Caine", email = "andy@hyperscale.consulting" }]
|
|
9
|
+
requires-python = ">=3.12"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"cedarpy>=4.8.1",
|
|
12
|
+
"django>=5.2",
|
|
13
|
+
]
|
|
14
|
+
keywords = ["django", "cedar", "authorization", "authz", "policy"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Framework :: Django",
|
|
18
|
+
"Framework :: Django :: 5.2",
|
|
19
|
+
"Framework :: Django :: 6.0",
|
|
20
|
+
"Intended Audience :: Developers",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Programming Language :: Python :: 3.14",
|
|
25
|
+
"Topic :: Security",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://github.com/hyperscale-consulting/django-cedar"
|
|
30
|
+
Changelog = "https://github.com/hyperscale-consulting/django-cedar/blob/main/CHANGELOG.md"
|
|
31
|
+
Issues = "https://github.com/hyperscale-consulting/django-cedar/issues"
|
|
32
|
+
|
|
33
|
+
[dependency-groups]
|
|
34
|
+
dev = [
|
|
35
|
+
"pyright>=1.1.400",
|
|
36
|
+
"pytest>=8.0",
|
|
37
|
+
"pytest-cov>=6.0",
|
|
38
|
+
"pytest-django>=4.9",
|
|
39
|
+
"ruff>=0.15.21",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
[build-system]
|
|
43
|
+
requires = ["uv_build>=0.9,<1.0"]
|
|
44
|
+
build-backend = "uv_build"
|
|
45
|
+
|
|
46
|
+
[tool.ruff]
|
|
47
|
+
fix = true
|
|
48
|
+
show-fixes = true
|
|
49
|
+
output-format = "full"
|
|
50
|
+
|
|
51
|
+
[tool.ruff.lint]
|
|
52
|
+
select = [
|
|
53
|
+
"B", # flake8-bugbear
|
|
54
|
+
"E", # pycodestyle error
|
|
55
|
+
"F", # pyflakes
|
|
56
|
+
"I", # isort
|
|
57
|
+
"UP", # pyupgrade
|
|
58
|
+
"W", # pycodestyle warning
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
[tool.ruff.lint.isort]
|
|
62
|
+
force-single-line = true
|
|
63
|
+
order-by-type = false
|
|
64
|
+
|
|
65
|
+
[tool.pyright]
|
|
66
|
+
pythonVersion = "3.12"
|
|
67
|
+
typeCheckingMode = "basic"
|
|
68
|
+
include = ["src", "tests"]
|
|
69
|
+
venvPath = "."
|
|
70
|
+
venv = ".venv"
|
|
71
|
+
|
|
72
|
+
[tool.pytest.ini_options]
|
|
73
|
+
DJANGO_SETTINGS_MODULE = "tests.settings"
|
|
74
|
+
testpaths = ["tests"]
|
|
75
|
+
pythonpath = ["."]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Cedar policy-based authorization for Django."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
from typing import Any
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from django_cedar.authz import Authz
|
|
11
|
+
from django_cedar.authz import create_authz
|
|
12
|
+
from django_cedar.authz import Entity
|
|
13
|
+
from django_cedar.authz import EntityRef
|
|
14
|
+
|
|
15
|
+
__all__: list[str] = ["Authz", "Entity", "EntityRef", "create_authz"]
|
|
16
|
+
|
|
17
|
+
# PEP 562 lazy exports: Django imports this package during app loading, when
|
|
18
|
+
# models are not yet ready — so django_cedar.authz (which imports auth models)
|
|
19
|
+
# must not be imported until an attribute is actually accessed.
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def __getattr__(name: str) -> Any:
|
|
23
|
+
if name in __all__:
|
|
24
|
+
return getattr(importlib.import_module("django_cedar.authz"), name)
|
|
25
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def __dir__() -> list[str]:
|
|
29
|
+
return sorted(set(globals()) | set(__all__))
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from django.apps import AppConfig
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class DjangoCedarConfig(AppConfig):
|
|
5
|
+
name = "django_cedar"
|
|
6
|
+
verbose_name = "Django Cedar"
|
|
7
|
+
|
|
8
|
+
def ready(self) -> None:
|
|
9
|
+
# Importing the module registers the system checks.
|
|
10
|
+
from django_cedar import checks # noqa: F401
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from dataclasses import field
|
|
10
|
+
from functools import lru_cache
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
from typing import cast
|
|
14
|
+
|
|
15
|
+
from cedarpy import is_authorized
|
|
16
|
+
from django.conf import settings
|
|
17
|
+
from django.contrib.auth.models import AbstractUser
|
|
18
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
19
|
+
from django.core.exceptions import PermissionDenied
|
|
20
|
+
from django.core.signals import setting_changed
|
|
21
|
+
from django.db.models import Model as DjangoModel
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _cedar_uid(entity_type: str, entity_id: str) -> str:
|
|
27
|
+
"""Build a Cedar entity UID string with the id safely escaped.
|
|
28
|
+
|
|
29
|
+
Cedar string literals use ``\\`` and ``"`` as escape characters, so an id
|
|
30
|
+
containing either would otherwise produce a malformed request string.
|
|
31
|
+
Only the request string is escaped; the entity dicts keep RAW ids because
|
|
32
|
+
cedarpy unescapes the request string before matching.
|
|
33
|
+
"""
|
|
34
|
+
escaped = entity_id.replace("\\", "\\\\").replace('"', '\\"')
|
|
35
|
+
return f'{entity_type}::"{escaped}"'
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _resolve_policy_path() -> Path:
|
|
39
|
+
raw = settings.CEDAR_POLICY_PATH
|
|
40
|
+
p = Path(raw).expanduser()
|
|
41
|
+
if not p.is_absolute():
|
|
42
|
+
base = Path(getattr(settings, "BASE_DIR", Path.cwd()))
|
|
43
|
+
p = base / p
|
|
44
|
+
return p.resolve()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _get_policy_path() -> Path:
|
|
48
|
+
p = _resolve_policy_path()
|
|
49
|
+
if not p.is_file():
|
|
50
|
+
raise FileNotFoundError(f"Policy file not found at {p}")
|
|
51
|
+
return p
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@lru_cache(maxsize=1)
|
|
55
|
+
def get_policies() -> str:
|
|
56
|
+
return _get_policy_path().read_text()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def import_from_path(path: str):
|
|
60
|
+
try:
|
|
61
|
+
module_path, attr = path.rsplit(".", 1)
|
|
62
|
+
except ValueError as e:
|
|
63
|
+
raise ImproperlyConfigured(
|
|
64
|
+
f"Invalid provider path '{path}'. Expected 'some.module.ClassName'."
|
|
65
|
+
) from e
|
|
66
|
+
|
|
67
|
+
module = importlib.import_module(module_path)
|
|
68
|
+
try:
|
|
69
|
+
return getattr(module, attr)
|
|
70
|
+
except AttributeError as e:
|
|
71
|
+
raise ImproperlyConfigured(
|
|
72
|
+
f"Provider '{path}' not found (no attribute '{attr}' in '{module_path}')."
|
|
73
|
+
) from e
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _load_providers(setting_name: str) -> list[Any]:
|
|
77
|
+
paths = getattr(settings, setting_name, [])
|
|
78
|
+
if not isinstance(paths, (list, tuple)):
|
|
79
|
+
raise ImproperlyConfigured(f"{setting_name} must be a list/tuple.")
|
|
80
|
+
return [import_from_path(p)() for p in paths]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@lru_cache(maxsize=1)
|
|
84
|
+
def get_principal_attr_providers() -> list[Any]:
|
|
85
|
+
return _load_providers("CEDAR_PRINCIPAL_ATTRIBUTE_PROVIDERS")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@lru_cache(maxsize=1)
|
|
89
|
+
def get_context_providers() -> list[Any]:
|
|
90
|
+
return _load_providers("CEDAR_CONTEXT_PROVIDERS")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
_SETTING_CACHES = {
|
|
94
|
+
"CEDAR_POLICY_PATH": (get_policies,),
|
|
95
|
+
"BASE_DIR": (get_policies,),
|
|
96
|
+
"CEDAR_PRINCIPAL_ATTRIBUTE_PROVIDERS": (get_principal_attr_providers,),
|
|
97
|
+
"CEDAR_CONTEXT_PROVIDERS": (get_context_providers,),
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _clear_caches_on_setting_change(*, setting, **kwargs) -> None:
|
|
102
|
+
for fn in _SETTING_CACHES.get(setting, ()):
|
|
103
|
+
fn.cache_clear()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
setting_changed.connect(
|
|
107
|
+
_clear_caches_on_setting_change,
|
|
108
|
+
dispatch_uid="django_cedar.authz.clear_caches",
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def create_authz() -> Authz:
|
|
113
|
+
return Authz(
|
|
114
|
+
policies=get_policies(),
|
|
115
|
+
principal_attribute_providers=get_principal_attr_providers(),
|
|
116
|
+
context_providers=get_context_providers(),
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class Authz:
|
|
121
|
+
def __init__(
|
|
122
|
+
self,
|
|
123
|
+
policies: str,
|
|
124
|
+
principal_attribute_providers: list[Any] | None = None,
|
|
125
|
+
context_providers: list[Any] | None = None,
|
|
126
|
+
):
|
|
127
|
+
self.policies = policies
|
|
128
|
+
self.principal_attribute_providers = principal_attribute_providers or []
|
|
129
|
+
self.context_providers = context_providers or []
|
|
130
|
+
|
|
131
|
+
def authorize(
|
|
132
|
+
self,
|
|
133
|
+
user: AbstractUser | None,
|
|
134
|
+
action: str,
|
|
135
|
+
resource: DjangoModel | None,
|
|
136
|
+
*,
|
|
137
|
+
context: dict[str, Any] | None = None,
|
|
138
|
+
) -> None:
|
|
139
|
+
entities = _make_principal_entities(
|
|
140
|
+
user, principal_attribute_providers=self.principal_attribute_providers
|
|
141
|
+
)
|
|
142
|
+
if resource:
|
|
143
|
+
entities.update(
|
|
144
|
+
_make_entities(resource, self.principal_attribute_providers)
|
|
145
|
+
)
|
|
146
|
+
entity_dicts = [e.to_dict() for e in entities]
|
|
147
|
+
cedar_resource = (
|
|
148
|
+
resource
|
|
149
|
+
and _cedar_uid(type(resource).__name__, str(resource.pk))
|
|
150
|
+
or 'System::"global"'
|
|
151
|
+
)
|
|
152
|
+
principal = 'Anonymous::"guest"'
|
|
153
|
+
if user and user.is_authenticated:
|
|
154
|
+
principal = _cedar_uid("User", str(user.pk))
|
|
155
|
+
cedar_action = _cedar_uid("Action", action)
|
|
156
|
+
cedar_context: dict[str, Any] = {}
|
|
157
|
+
for provider in self.context_providers:
|
|
158
|
+
_deep_merge(cedar_context, provider.get_context(user, action, resource))
|
|
159
|
+
if context:
|
|
160
|
+
_deep_merge(cedar_context, context)
|
|
161
|
+
authz_request = dict(
|
|
162
|
+
principal=principal,
|
|
163
|
+
action=cedar_action,
|
|
164
|
+
resource=cedar_resource,
|
|
165
|
+
context=cedar_context,
|
|
166
|
+
)
|
|
167
|
+
logger.debug(f"Entities:\n {json.dumps(entity_dicts, indent=2)}")
|
|
168
|
+
logger.debug(f"AuthRequest:\n {json.dumps(authz_request, indent=2)}")
|
|
169
|
+
authz_result = is_authorized(authz_request, self.policies, entity_dicts)
|
|
170
|
+
if not authz_result.allowed:
|
|
171
|
+
logger.debug(f"AuthzResult errors: {authz_result.diagnostics.errors}")
|
|
172
|
+
logger.info(
|
|
173
|
+
f"Authz denied: principal={principal} action={cedar_action} "
|
|
174
|
+
f"resource={cedar_resource}"
|
|
175
|
+
)
|
|
176
|
+
raise PermissionDenied("Forbidden")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@dataclass(frozen=True)
|
|
180
|
+
class EntityRef:
|
|
181
|
+
type: str
|
|
182
|
+
id: str
|
|
183
|
+
|
|
184
|
+
def to_dict(self) -> dict:
|
|
185
|
+
return dict(type=self.type, id=self.id)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
@dataclass(frozen=True)
|
|
189
|
+
class Entity:
|
|
190
|
+
ref: EntityRef
|
|
191
|
+
attrs: dict[str, Any] = field(default_factory=dict)
|
|
192
|
+
parents: set[EntityRef] = field(default_factory=set)
|
|
193
|
+
|
|
194
|
+
def __hash__(self):
|
|
195
|
+
return hash((self.ref.type, self.ref.id))
|
|
196
|
+
|
|
197
|
+
def __eq__(self, value):
|
|
198
|
+
return isinstance(value, Entity) and self.ref == value.ref
|
|
199
|
+
|
|
200
|
+
@staticmethod
|
|
201
|
+
def create(type: str, id: str) -> Entity:
|
|
202
|
+
return Entity(EntityRef(type, id))
|
|
203
|
+
|
|
204
|
+
def to_dict(self) -> dict:
|
|
205
|
+
return {
|
|
206
|
+
"uid": {"__entity": self.ref.to_dict()},
|
|
207
|
+
"attrs": self.attrs,
|
|
208
|
+
"parents": [p.to_dict() for p in self.parents],
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _make_user_entities(
|
|
213
|
+
user: AbstractUser, principal_attribute_providers: list[Any]
|
|
214
|
+
) -> set[Entity]:
|
|
215
|
+
user_groups: Any = user.groups
|
|
216
|
+
groups = list(user_groups.all())
|
|
217
|
+
result = set()
|
|
218
|
+
attrs = {
|
|
219
|
+
"id": str(user.pk),
|
|
220
|
+
"is_staff": user.is_staff,
|
|
221
|
+
"is_superuser": user.is_superuser,
|
|
222
|
+
}
|
|
223
|
+
for provider in principal_attribute_providers:
|
|
224
|
+
attrs.update(provider.get_attributes(user))
|
|
225
|
+
if hasattr(provider, "get_entities"):
|
|
226
|
+
result.update(provider.get_entities(user))
|
|
227
|
+
|
|
228
|
+
result.add(
|
|
229
|
+
Entity(
|
|
230
|
+
EntityRef("User", str(user.pk)),
|
|
231
|
+
attrs=attrs,
|
|
232
|
+
parents={EntityRef("Group", group.name) for group in groups},
|
|
233
|
+
)
|
|
234
|
+
)
|
|
235
|
+
for group in groups:
|
|
236
|
+
result.add(
|
|
237
|
+
Entity(
|
|
238
|
+
EntityRef("Group", group.name),
|
|
239
|
+
attrs={"id": str(group.pk)},
|
|
240
|
+
)
|
|
241
|
+
)
|
|
242
|
+
return result
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _make_principal_entities(
|
|
246
|
+
user: AbstractUser | None, principal_attribute_providers: list[Any]
|
|
247
|
+
) -> set[Entity]:
|
|
248
|
+
if not user or not user.is_authenticated:
|
|
249
|
+
return {Entity(EntityRef("Anonymous", "guest"))}
|
|
250
|
+
|
|
251
|
+
return _make_user_entities(user, principal_attribute_providers)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _make_entities(
|
|
255
|
+
entity: Any,
|
|
256
|
+
principal_attribute_providers: list[Any],
|
|
257
|
+
seen: set[EntityRef] | None = None,
|
|
258
|
+
) -> set[Entity]:
|
|
259
|
+
if isinstance(entity, AbstractUser):
|
|
260
|
+
return _make_principal_entities(entity, principal_attribute_providers)
|
|
261
|
+
|
|
262
|
+
if seen is None:
|
|
263
|
+
seen = set()
|
|
264
|
+
|
|
265
|
+
ref = EntityRef(type(entity).__name__, str(entity.pk))
|
|
266
|
+
if ref in seen:
|
|
267
|
+
return set()
|
|
268
|
+
seen.add(ref)
|
|
269
|
+
|
|
270
|
+
result = set()
|
|
271
|
+
|
|
272
|
+
attrs: dict[str, Any] = {}
|
|
273
|
+
authz_fields = getattr(entity, "authz_fields", None)
|
|
274
|
+
if callable(authz_fields):
|
|
275
|
+
attrs = cast("dict[str, Any]", authz_fields())
|
|
276
|
+
|
|
277
|
+
attrs["id"] = str(entity.pk)
|
|
278
|
+
result.add(Entity(ref, attrs=attrs))
|
|
279
|
+
|
|
280
|
+
# Transitively include any entities the model declares as related so Cedar
|
|
281
|
+
# can resolve `resource.foo.bar` attribute chains. Models opt in by
|
|
282
|
+
# defining `authz_related_entities()` → iterable of related Django models.
|
|
283
|
+
# ``seen`` guards against cycles (A → B → A) that would otherwise recurse
|
|
284
|
+
# unboundedly.
|
|
285
|
+
related_fn = getattr(entity, "authz_related_entities", None)
|
|
286
|
+
if callable(related_fn):
|
|
287
|
+
for related in cast("Iterable[Any]", related_fn() or ()):
|
|
288
|
+
result.update(_make_entities(related, principal_attribute_providers, seen))
|
|
289
|
+
|
|
290
|
+
return result
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _deep_merge(dst: dict[str, Any], src: Mapping[str, Any]) -> dict[str, Any]:
|
|
294
|
+
for k, v in src.items():
|
|
295
|
+
if isinstance(v, Mapping) and isinstance(dst.get(k), Mapping):
|
|
296
|
+
_deep_merge(dst[k], v)
|
|
297
|
+
else:
|
|
298
|
+
dst[k] = v
|
|
299
|
+
return dst
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from cedarpy import format_policies
|
|
6
|
+
from django.conf import settings
|
|
7
|
+
from django.core.checks import CheckMessage
|
|
8
|
+
from django.core.checks import Error
|
|
9
|
+
from django.core.checks import register
|
|
10
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
11
|
+
|
|
12
|
+
from django_cedar.authz import _resolve_policy_path
|
|
13
|
+
from django_cedar.authz import import_from_path
|
|
14
|
+
|
|
15
|
+
_PROVIDER_SETTINGS = (
|
|
16
|
+
("CEDAR_PRINCIPAL_ATTRIBUTE_PROVIDERS", "get_attributes"),
|
|
17
|
+
("CEDAR_CONTEXT_PROVIDERS", "get_context"),
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@register()
|
|
22
|
+
def check_cedar_config(app_configs: Any, **kwargs: Any) -> list[CheckMessage]:
|
|
23
|
+
errors: list[CheckMessage] = []
|
|
24
|
+
errors.extend(_check_policy_file())
|
|
25
|
+
errors.extend(_check_providers())
|
|
26
|
+
return errors
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _check_policy_file() -> list[CheckMessage]:
|
|
30
|
+
if not getattr(settings, "CEDAR_POLICY_PATH", None):
|
|
31
|
+
return [
|
|
32
|
+
Error(
|
|
33
|
+
"The CEDAR_POLICY_PATH setting is not set.",
|
|
34
|
+
hint="Set CEDAR_POLICY_PATH to the path of your Cedar policy "
|
|
35
|
+
"file (relative paths resolve against BASE_DIR).",
|
|
36
|
+
id="django_cedar.E001",
|
|
37
|
+
)
|
|
38
|
+
]
|
|
39
|
+
path = _resolve_policy_path()
|
|
40
|
+
if not path.is_file():
|
|
41
|
+
return [
|
|
42
|
+
Error(
|
|
43
|
+
f"Cedar policy file not found at {path}.",
|
|
44
|
+
hint="Check the CEDAR_POLICY_PATH setting.",
|
|
45
|
+
id="django_cedar.E002",
|
|
46
|
+
)
|
|
47
|
+
]
|
|
48
|
+
try:
|
|
49
|
+
format_policies(path.read_text())
|
|
50
|
+
except Exception as e: # cedarpy raises on any parse failure
|
|
51
|
+
return [
|
|
52
|
+
Error(
|
|
53
|
+
f"Cedar policy file at {path} failed to parse: {e}",
|
|
54
|
+
id="django_cedar.E003",
|
|
55
|
+
)
|
|
56
|
+
]
|
|
57
|
+
return []
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _check_providers() -> list[CheckMessage]:
|
|
61
|
+
errors: list[CheckMessage] = []
|
|
62
|
+
for setting_name, required_method in _PROVIDER_SETTINGS:
|
|
63
|
+
configured = getattr(settings, setting_name, [])
|
|
64
|
+
if not isinstance(configured, (list, tuple)):
|
|
65
|
+
errors.append(
|
|
66
|
+
Error(
|
|
67
|
+
f"{setting_name} must be a list or tuple.",
|
|
68
|
+
id="django_cedar.E006",
|
|
69
|
+
)
|
|
70
|
+
)
|
|
71
|
+
continue
|
|
72
|
+
for dotted_path in configured:
|
|
73
|
+
try:
|
|
74
|
+
provider_cls = import_from_path(dotted_path)
|
|
75
|
+
except (ImportError, ImproperlyConfigured) as e:
|
|
76
|
+
errors.append(
|
|
77
|
+
Error(
|
|
78
|
+
f"Could not import '{dotted_path}' from {setting_name}: {e}",
|
|
79
|
+
id="django_cedar.E004",
|
|
80
|
+
)
|
|
81
|
+
)
|
|
82
|
+
continue
|
|
83
|
+
if not callable(getattr(provider_cls, required_method, None)):
|
|
84
|
+
errors.append(
|
|
85
|
+
Error(
|
|
86
|
+
f"'{dotted_path}' in {setting_name} does not define a "
|
|
87
|
+
f"callable '{required_method}' method.",
|
|
88
|
+
id="django_cedar.E005",
|
|
89
|
+
)
|
|
90
|
+
)
|
|
91
|
+
return errors
|
|
File without changes
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Any
|
|
5
|
+
from typing import cast
|
|
6
|
+
|
|
7
|
+
from asgiref.sync import sync_to_async
|
|
8
|
+
from django.contrib.auth.mixins import LoginRequiredMixin
|
|
9
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
10
|
+
from django.views.generic import CreateView
|
|
11
|
+
from django.views.generic import DeleteView
|
|
12
|
+
from django.views.generic import DetailView
|
|
13
|
+
from django.views.generic import FormView
|
|
14
|
+
from django.views.generic import ListView
|
|
15
|
+
from django.views.generic import TemplateView
|
|
16
|
+
from django.views.generic import UpdateView
|
|
17
|
+
|
|
18
|
+
from django_cedar.authz import create_authz
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class CedarAuthorizationMixin:
|
|
24
|
+
"""
|
|
25
|
+
Mixin that performs Cedar authorization on every request via dispatch().
|
|
26
|
+
|
|
27
|
+
Subclasses must define ``action_names`` mapping HTTP methods to Cedar action
|
|
28
|
+
strings. Override ``get_resource`` to control the Cedar resource used for
|
|
29
|
+
the authorization check (defaults to ``None`` → ``System::"global"``).
|
|
30
|
+
|
|
31
|
+
Usage::
|
|
32
|
+
|
|
33
|
+
class MyView(LoginRequiredMixin, CedarAuthorizationMixin, DetailView):
|
|
34
|
+
action_names = {"GET": "ViewWidget"}
|
|
35
|
+
model = Widget
|
|
36
|
+
|
|
37
|
+
Async views: ``authorize_request`` calls into the ORM (group membership,
|
|
38
|
+
``get_resource`` may load a parent object). For async views we hop into
|
|
39
|
+
a sync thread via ``sync_to_async`` so those queries don't trip
|
|
40
|
+
``SynchronousOnlyOperation``.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
action_names: dict[str, str] = {}
|
|
44
|
+
|
|
45
|
+
def dispatch(self, request, *args, **kwargs) -> Any: # type: ignore[override]
|
|
46
|
+
if self.view_is_async: # type: ignore[attr-defined]
|
|
47
|
+
return self._cedar_async_dispatch(request, *args, **kwargs)
|
|
48
|
+
self.authorize_request(request)
|
|
49
|
+
return super().dispatch(request, *args, **kwargs) # type: ignore[misc]
|
|
50
|
+
|
|
51
|
+
async def _cedar_async_dispatch(self, request, *args, **kwargs):
|
|
52
|
+
# Unique method name (rather than ``_adispatch``) so multiple
|
|
53
|
+
# dispatch-overriding mixins in the same MRO don't shadow each
|
|
54
|
+
# other — ``self._adispatch`` would always resolve to the first
|
|
55
|
+
# one and recurse.
|
|
56
|
+
await sync_to_async(self.authorize_request, thread_sensitive=True)(request)
|
|
57
|
+
return await super().dispatch(request, *args, **kwargs) # type: ignore[misc]
|
|
58
|
+
|
|
59
|
+
def authorize_request(self, request) -> None:
|
|
60
|
+
method = request.method.upper()
|
|
61
|
+
if method == "OPTIONS":
|
|
62
|
+
return
|
|
63
|
+
# Keep the original method's handler name for the fail-closed guard
|
|
64
|
+
# below: a view may define a custom head() with no get() at all, and
|
|
65
|
+
# that handler must still be caught by the guard even though the
|
|
66
|
+
# action_names lookup (just below) is done against the translated
|
|
67
|
+
# "GET" method.
|
|
68
|
+
handler_name = method.lower()
|
|
69
|
+
# Django's View.setup() aliases head=get, so a HEAD request executes
|
|
70
|
+
# the full GET code path. Authorize it with the GET action rather than
|
|
71
|
+
# letting it bypass authorization.
|
|
72
|
+
if method == "HEAD":
|
|
73
|
+
method = "GET"
|
|
74
|
+
action = self.action_names.get(method)
|
|
75
|
+
if action is None:
|
|
76
|
+
if hasattr(self, handler_name):
|
|
77
|
+
raise ImproperlyConfigured(
|
|
78
|
+
f"{type(self).__name__} has a {handler_name}() handler but no "
|
|
79
|
+
f"action_names entry for '{method}'. Add "
|
|
80
|
+
f"action_names['{method}'] to enable Cedar authorization "
|
|
81
|
+
f"for this method."
|
|
82
|
+
)
|
|
83
|
+
return
|
|
84
|
+
authz = create_authz()
|
|
85
|
+
resource = self.get_resource(request)
|
|
86
|
+
logger.debug(
|
|
87
|
+
f"Authorizing action '{action}' on resource '{resource}' "
|
|
88
|
+
f"for user '{request.user}'"
|
|
89
|
+
)
|
|
90
|
+
authz.authorize(request.user, action, resource)
|
|
91
|
+
|
|
92
|
+
def get_resource(self, request) -> Any:
|
|
93
|
+
"""Return the Cedar resource for this request.
|
|
94
|
+
|
|
95
|
+
Default is ``None``, which maps to ``System::"global"`` in Cedar.
|
|
96
|
+
"""
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ResourceIsCurrentObjectMixin:
|
|
101
|
+
"""Use ``self.get_object()`` as the Cedar resource.
|
|
102
|
+
|
|
103
|
+
For detail/update/delete views where the resource being authorized is the
|
|
104
|
+
object being acted on.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def get_resource(self, request) -> Any:
|
|
108
|
+
self.object = cast(Any, self).get_object()
|
|
109
|
+
return self.object
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class CurrentUserScopedMixin:
|
|
113
|
+
"""Use the current user as the Cedar resource and filter the queryset to
|
|
114
|
+
objects belonging to that user."""
|
|
115
|
+
|
|
116
|
+
def get_resource(self, request) -> Any:
|
|
117
|
+
return request.user
|
|
118
|
+
|
|
119
|
+
def get_queryset(self):
|
|
120
|
+
qs = cast(Any, super()).get_queryset()
|
|
121
|
+
request: Any = cast(Any, self).request
|
|
122
|
+
if not request.user or not request.user.is_authenticated:
|
|
123
|
+
return qs.none()
|
|
124
|
+
return qs.filter(user=request.user)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class AuthorizedDetailView(
|
|
128
|
+
ResourceIsCurrentObjectMixin, CedarAuthorizationMixin, DetailView
|
|
129
|
+
):
|
|
130
|
+
pass
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class AuthorizedListView(CedarAuthorizationMixin, ListView):
|
|
134
|
+
pass
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class AuthorizedCreateView(CedarAuthorizationMixin, CreateView):
|
|
138
|
+
pass
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class AuthorizedUpdateView(
|
|
142
|
+
ResourceIsCurrentObjectMixin, CedarAuthorizationMixin, UpdateView
|
|
143
|
+
):
|
|
144
|
+
pass
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class AuthorizedDeleteView(
|
|
148
|
+
ResourceIsCurrentObjectMixin, CedarAuthorizationMixin, DeleteView
|
|
149
|
+
):
|
|
150
|
+
pass
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class AuthorizedTemplateView(CedarAuthorizationMixin, TemplateView):
|
|
154
|
+
pass
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class AuthorizedFormView(CedarAuthorizationMixin, FormView):
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class AsyncLoginRequiredMixin(LoginRequiredMixin):
|
|
162
|
+
"""LoginRequiredMixin that works on async views.
|
|
163
|
+
|
|
164
|
+
Django's stock ``LoginRequiredMixin.dispatch`` reads
|
|
165
|
+
``request.user.is_authenticated`` synchronously; on an async view that
|
|
166
|
+
triggers a sync ORM lookup through ``SimpleLazyObject`` and
|
|
167
|
+
``SynchronousOnlyOperation`` is raised. We resolve the user via the
|
|
168
|
+
async helper ``request.auser()`` first, then populate
|
|
169
|
+
``request._cached_user`` so any later sync access (LoginRequiredMixin's
|
|
170
|
+
own check, downstream mixins) sees the cached value and skips the
|
|
171
|
+
lookup entirely.
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
def dispatch(self, request, *args, **kwargs) -> Any: # type: ignore[override]
|
|
175
|
+
if self.view_is_async: # type: ignore[attr-defined]
|
|
176
|
+
return self._login_async_dispatch(request, *args, **kwargs)
|
|
177
|
+
return super().dispatch(request, *args, **kwargs)
|
|
178
|
+
|
|
179
|
+
async def _login_async_dispatch(self, request, *args, **kwargs):
|
|
180
|
+
# Unique method name (rather than the generic ``_adispatch``) so
|
|
181
|
+
# we don't shadow ``CedarAuthorizationMixin``'s async helper when
|
|
182
|
+
# both mixins land in the same view's MRO.
|
|
183
|
+
user = await request.auser()
|
|
184
|
+
request._cached_user = user
|
|
185
|
+
if not user.is_authenticated:
|
|
186
|
+
return self.handle_no_permission()
|
|
187
|
+
return await cast(Any, super(LoginRequiredMixin, self)).dispatch(
|
|
188
|
+
request, *args, **kwargs
|
|
189
|
+
)
|