Repository navigation
Expand file tree
/
Copy pathmodels.py
More file actions
414 lines (356 loc) · 15.5 KB
/
Copy pathmodels.py
File metadata and controls
414 lines (356 loc) · 15.5 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
import logging
from collections.abc import Iterable
from typing import Any, NamedTuple
from django.apps import apps
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.db.models.base import ModelBase
from django.utils import timezone
from django.utils.translation import pgettext_lazy as _
from cognito.utils.client import Client, OrganizationGroup, UnitGroup
from config.authorization import VPRole
from user.extra_audience import remove_extra_audience
from utils.exceptions import ConflictError
from utils.fields import CustomSlugField
from verified_permissions.utils.client import Client as VPClient
logger = logging.getLogger(__name__)
class Role(NamedTuple):
role_id: str
name: str
description: str
policy_template_id: str | None = None
@classmethod
def all(cls) -> list[Role]:
policy_template_ids = settings.ROLE_POLICY_TEMPLATE_IDS
return [
cls(
role_id=VPRole.ORG_ADMIN.value,
name="Organization Admin",
description="Organization administrator with full access to all resources.",
policy_template_id=policy_template_ids.get(VPRole.ORG_ADMIN),
),
cls(
role_id=VPRole.DATASET_ADMIN.value,
name="Dataset Admin",
description="Dataset administrator with full access to all datasets of their Unit.",
policy_template_id=policy_template_ids.get(VPRole.DATASET_ADMIN),
),
cls(
role_id=VPRole.DATASET_CONTRIBUTOR.value,
name="Dataset Contributor",
description="Dataset contributor with limited access to datasets of their Unit.",
policy_template_id=policy_template_ids.get(VPRole.DATASET_CONTRIBUTOR),
),
]
class CustomUser(AbstractBaseUser, PermissionsMixin):
"""CustomUser replaces the Django default User model and is set as AUTH_USER_MODEL in settings.
A user can either be a human or a machine. Human users are stored as users in cognito, machine
users are client apps in cognito.
For basic human user attributes (email, first_name, last_name), cognito is the source of truth.
Service-control is the source of truth for organizations, roles and their relations to users.
"""
_original_roles = None
_original_unit_id = None
_original_organization_id = None
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._original_roles = self.roles
self._original_unit_id = getattr(self, "unit_id", None)
self._original_organization_id = getattr(self, "organization_id", None)
_context = "User model"
class UserType(models.TextChoices):
HUMAN = "HUMAN", _("User model", "Human")
MACHINE = "MACHINE", _("User model", "Machine")
# sub is the unique identifier for both human and machine users. For human users, this is the
# cognito user ID, for machine users this is the app client ID.
sub = models.CharField(
_(_context, "Sub"),
max_length=150,
unique=True,
help_text=_(_context, "Cognito subject. Either user id or app client id."),
)
is_staff = models.BooleanField(
_(_context, "Staff Status"),
default=False,
help_text=_(_context, "Designates whether the user can log into this admin site."),
)
is_active = models.BooleanField(
_(_context, "Active"),
default=True,
help_text=_(
_context,
"Designates whether this user should be treated as active. "
"Unselect this instead of deleting accounts.",
),
)
date_joined = models.DateTimeField(_(_context, "Date Joined"), default=timezone.now)
# User can exist without an organization -> nullable
organization = models.ForeignKey(
"organization.Organization", null=True, blank=True, on_delete=models.SET_NULL
)
# User can exist without a unit -> nullable
unit = models.ForeignKey("organization.Unit", null=True, blank=True, on_delete=models.SET_NULL)
# user_type is an enum to differentiate human users from machine users
user_type = models.CharField(
_(_context, "User Type"), max_length=10, choices=UserType.choices, default=UserType.HUMAN
)
# --
# -- Human user specific fields --
# --
# first_name of human users as is stored in cognito.
first_name = models.CharField(_(_context, "First Name"), max_length=150, blank=True)
# last_name of human users as is stored in cognito.
last_name = models.CharField(_(_context, "Last Name"), max_length=150, blank=True)
email = models.EmailField(_(_context, "Email Address"), blank=True)
# cognito_username is only set for human users. This is the username as stored in cognito,
# usually the external (eIAM) reference. This is required as cognito expects this username as
# identifier in most API calls (e.g. AdminUpdateUserAttributes).
# The cognito_username is taken from the preferred_username header set by oauth2-proxy. It is
# only set on the first user login and never updated as this value never changes in cognito.
cognito_username = models.CharField(
_(_context, "Cognito Username"),
max_length=100,
null=True,
blank=True,
unique=True,
)
roles = ArrayField(
base_field=models.CharField(max_length=32, choices=VPRole.choices()),
default=list,
blank=True,
)
# --
# -- Machine user specific fields --
# --
# App client name of machine user.
name = models.CharField(_(_context, "Name"), max_length=150, blank=True)
# Only set for machine users.
created_by_user = models.ForeignKey(
"CustomUser", null=True, blank=True, on_delete=models.SET_NULL
)
vp_machine_user_policy_id = models.CharField(
_(_context, "Verified Permissions Policy ID"),
max_length=100,
null=True,
blank=True,
)
# password is set in inherited AbstractBaseUser, but not used as authentication is done
# externally.
password = None # ty: ignore[invalid-assignment]
# NOTE:
# - `groups` and `user_permissions` are set in inherited PermissionsMixin.
# For API calls the permissions and groups are handled by Verified Permissions and both
# fields, `groups` and `user_permissions`, could be removed. However those two fields are
# still used internally in django admin interface.
# This is the case when a user not belongign to the OAUTH2_PROXY_DJANGO_ADMIN_GROUPS group
# tries to access the admin interface.
USERNAME_FIELD = "sub"
@property
def unit_changed(self) -> bool:
return self.organization_changed or self._original_unit_id != getattr(self, "unit_id", None)
@property
def organization_changed(self) -> bool:
return self._original_organization_id != getattr(self, "organization_id", None)
def __str__(self) -> str:
return str(self.sub)
def save(
self,
*args: Any, # noqa: ARG002 unused arguments
force_insert: bool | tuple[ModelBase, ...] = False,
force_update: bool = False,
using: str | None = None,
update_fields: Iterable[str] | None = None,
) -> None:
if self.unit and self.unit.organization != self.organization:
raise ValueError("Unit must belong to the same organization as the user")
result = super().save(
force_insert=force_insert,
force_update=force_update,
using=using,
update_fields=update_fields,
)
# Update original values to reflect the state after save
self._original_roles = self.roles
self._original_unit_id = getattr(self, "unit_id", None)
self._original_organization_id = getattr(self, "organization_id", None)
return result
def delete(
self,
using: str | None = None,
keep_parents: bool = False,
) -> tuple[int, dict[str, int]]:
return super().delete(using=using, keep_parents=keep_parents)
class MachineUserManager(models.Manager):
def get_queryset(self) -> models.QuerySet:
return super().get_queryset().filter(user_type=CustomUser.UserType.MACHINE)
class HumanUserManager(models.Manager):
def get_queryset(self) -> models.QuerySet:
return super().get_queryset().filter(user_type=CustomUser.UserType.HUMAN)
class MachineUser(CustomUser):
objects = MachineUserManager()
class Meta:
proxy = True
verbose_name = "Machine User"
verbose_name_plural = "Machine Users"
ordering = ("name",)
def save(
self,
*args: Any, # noqa: ARG002 unused arguments
force_insert: bool | tuple[ModelBase, ...] = False,
force_update: bool = False,
using: str | None = None,
update_fields: Iterable[str] | None = None,
) -> None:
self.user_type = self.UserType.MACHINE
if self._state.adding:
client = VPClient()
self.vp_machine_user_policy_id = client.create_machine_user_policy(
client_id=self.sub, organization_id=self.organization.organization_id
)
elif self.organization_changed or self.unit_changed:
raise ValueError(
"Changing organization or unit of a machine user is not allowed. "
"Remove it and create a new one instead."
)
return super().save(
force_insert=force_insert,
force_update=force_update,
using=using,
update_fields=update_fields,
)
def delete(
self,
using: str | None = None,
keep_parents: bool = False,
) -> tuple[int, dict[str, int]]:
"""Deletes the corresponding app client in cognito."""
client = Client()
if not client.delete_app_client(self.sub):
logger.warning("cognito app client '%s' not found, not deleted", self.sub)
remove_extra_audience(self.sub)
vp_client = VPClient()
vp_client.delete_policy(self.vp_machine_user_policy_id)
return super().delete(using=using, keep_parents=keep_parents)
class HumanUser(CustomUser):
objects = HumanUserManager()
def save(
self,
*args: Any, # noqa: ARG002 unused arguments
force_insert: bool | tuple[ModelBase, ...] = False,
force_update: bool = False,
using: str | None = None,
update_fields: Iterable[str] | None = None,
) -> None:
self.user_type = self.UserType.HUMAN
if self.unit and self.unit.organization != self.organization:
raise ValueError("Unit must belong to the same organization as the user")
client = Client()
if (
not self._state.adding
and self.cognito_username is not None
and set(self.roles or []) != set(self._original_roles or [])
):
# Custom user will be created by RemoteCustomUserBackend when the user logs in for
# first time. At this point the user will never have roles set yet, so we can skip
# the call to cognito to update user roles. For subsequent updates of human users,
# we need to update the roles in cognito if they have changed.
client.update_user_roles(
self.cognito_username,
self.roles,
)
if (
self.unit_changed
and self._original_unit_id is not None
and self._original_organization_id is not None
):
# Use apps to get model due to circular import
Organization = apps.get_model("organization", "Organization")
Unit = apps.get_model("organization", "Unit")
original_unit = Unit.objects.filter(pk=self._original_unit_id).get()
client.remove_user_from_group(
self.cognito_username,
UnitGroup(original_unit.unit_id, original_unit.organization.organization_id),
)
if self.organization_changed and self._original_organization_id is not None:
# Use apps to get model due to circular import
Organization = apps.get_model("organization", "Organization")
original_org = Organization.objects.filter(pk=self._original_organization_id).get()
client.remove_user_from_group(
self.cognito_username,
OrganizationGroup(original_org.organization_id),
)
if self.organization_changed and self.organization:
client.add_user_to_group(
self.cognito_username,
OrganizationGroup(self.organization.organization_id),
)
if self.unit_changed and self.unit:
client.add_user_to_group(
self.cognito_username,
UnitGroup(self.unit.unit_id, self.organization.organization_id),
)
return super().save(
force_insert=force_insert,
force_update=force_update,
using=using,
update_fields=update_fields,
)
class Meta:
proxy = True
verbose_name = "Human User"
verbose_name_plural = "Human Users"
class AccessRequest(models.Model):
_context = "Access Request model"
class AccessRequestState(models.TextChoices):
"""
New access requests have state PENDING. An admin can either APPROVE or DECLINE
an access request. The user can also CANCEL a pending access request.
"""
PENDING = "PENDING", _("Access Request model", "Pending")
APPROVED = "APPROVED", _("Access Request model", "Approved")
DECLINED = "DECLINED", _("Access Request model", "Declined")
CANCELLED = "CANCELLED", _("Access Request model", "Cancelled")
access_request_id = CustomSlugField(
_(_context, "Access Request ID"),
max_length=100,
unique=True,
db_index=True,
default=CustomSlugField.generate_unique_slug,
)
created = models.DateTimeField(_(_context, "Created"), auto_now_add=True)
updated = models.DateTimeField(_(_context, "Updated"), auto_now=True)
user = models.ForeignKey(HumanUser, on_delete=models.CASCADE)
organization = models.ForeignKey("organization.Organization", on_delete=models.CASCADE)
state = models.CharField(
_(_context, "State"),
max_length=20,
choices=AccessRequestState.choices,
default=AccessRequestState.PENDING,
)
def __str__(self) -> str:
return self.access_request_id
def save(
self,
*args: Any, # noqa: ARG002 unused arguments
force_insert: bool | tuple[ModelBase, ...] = False,
force_update: bool = False,
using: str | None = None,
update_fields: Iterable[str] | None = None,
) -> None:
if self._state.adding:
# Check user does not already have a pending access request
if AccessRequest.objects.filter(
user=self.user, state=AccessRequest.AccessRequestState.PENDING
).exists():
raise ConflictError("User already has a pending access request")
# Check user does not already belong to an organization
if self.user.organization is not None:
raise ConflictError("User already belongs to an organization")
return super().save(
force_insert=force_insert,
force_update=force_update,
using=using,
update_fields=update_fields,
)