Debian Codegraph @

guardian/utils.py

raw
1 """
2 django-guardian helper functions.
3
4 Functions defined within this module are a part of django-guardian's internal functionality
5 and be considered unstable; their APIs may change in any future releases.
6 """
7
8 import gc
9 from itertools import chain
10 import logging
11 from math import ceil
12 import os
13 import time
14 from typing import Any
15
16 from django.apps import apps as django_apps
17 from django.conf import settings
18 from django.contrib.auth import REDIRECT_FIELD_NAME, get_user_model
19 from django.contrib.auth.models import AnonymousUser
20 from django.core.cache import cache
21 from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist, PermissionDenied
22 from django.db.models import Model, QuerySet
23 from django.http import HttpRequest, HttpResponse, HttpResponseForbidden, HttpResponseNotFound, HttpResponseRedirect
24 from django.shortcuts import render
25
26 from guardian.conf import settings as guardian_settings
27 from guardian.ctypes import get_content_type
28 from guardian.exceptions import NotUserNorGroup
29
30 logger = logging.getLogger(__name__)
31
32
33 def abspath(*args):
34 """Join path arguments and return their absolute path"""
35 return os.path.abspath(os.path.join(*args))
36
37
38 def _get_anonymous_user_cached() -> Any:
39 """Internal cached version of get_anonymous_user using Django's cache system."""
40 cache_key = f"guardian:anonymous_user:{guardian_settings.ANONYMOUS_USER_NAME}"
41
42 # Try to get from cache first
43 user = cache.get(cache_key)
44 if user is not None:
45 return user
46
47 # If not in cache, get from database and cache it
48 user_model = get_user_model()
49 lookup = {user_model.USERNAME_FIELD: guardian_settings.ANONYMOUS_USER_NAME} # type: ignore[attr-defined]
50 user = user_model.objects.get(**lookup)
51
52 # Cache with TTL from settings
53 # -1 means cache indefinitely (None), positive number is TTL in seconds
54 ttl = None if guardian_settings.ANONYMOUS_USER_CACHE_TTL == -1 else guardian_settings.ANONYMOUS_USER_CACHE_TTL
55 cache.set(cache_key, user, ttl)
56 return user
57
58
59 def _get_anonymous_user_uncached() -> Any:
60 """Internal uncached version of get_anonymous_user."""
61 user_model = get_user_model()
62 lookup = {user_model.USERNAME_FIELD: guardian_settings.ANONYMOUS_USER_NAME} # type: ignore[attr-defined]
63 return user_model.objects.get(**lookup)
64
65
66 def get_anonymous_user() -> Any:
67 """Get the django-guardian equivalent of the anonymous user.
68
69 It returns a `User` model instance (not `AnonymousUser`) depending on
70 `ANONYMOUS_USER_NAME` configuration.
71
72 This function can be cached to avoid repetitive database queries based on the
73 `GUARDIAN_ANONYMOUS_USER_CACHE_TTL` setting:
74 - 0 (default): No caching, each call performs a fresh database query
75 - Positive number: Cache for that many seconds
76 - -1: Cache indefinitely (not recommended)
77
78 See Also:
79 See the configuration docs that explain that the Guardian anonymous user is
80 not equivalent to Django's AnonymousUser.
81
82 - [Guardian Configuration](https://django-guardian.readthedocs.io/en/stable/configuration.html)
83 - [ANONYMOUS_USER_NAME configuration](https://django-guardian.readthedocs.io/en/stable/configuration.html#anonymous-user-nam)
84 - [ANONYMOUS_USER_CACHE_TTL configuration](https://django-guardian.readthedocs.io/en/stable/configuration.html#anonymous-user-cache-ttl)
85 """
86 if guardian_settings.ANONYMOUS_USER_CACHE_TTL > 0 or guardian_settings.ANONYMOUS_USER_CACHE_TTL == -1:
87 return _get_anonymous_user_cached()
88 else:
89 return _get_anonymous_user_uncached()
90
91
92 def get_identity(identity: Model) -> tuple[Any | None, Any | None]:
93 """Get a tuple with the identity of the given input.
94
95 Returns a tuple with one of the members set to `None` depending on whether the input is
96 a `Group` instance or a `User` instance.
97 Also accepts AnonymousUser instance but would return `User` instead.
98 It is convenient and needed for authorization backend to support anonymous users.
99
100 Returns:
101 Either (user_obj, None) or (None, group_obj) depending on the input type.
102
103 Parameters:
104 identity (User | Group): Instance of `User` or `Group` to get identity from.
105
106 Raises:
107 NotUserNorGroup: If the function cannot return proper identity instance
108
109 Examples:
110 ```shell
111 >>> from django.contrib.auth.models import User, Group
112 >>> user = User.objects.create(username='joe')
113 >>> get_identity(user)
114 (<User: joe>, None)
115
116 >>> group = Group.objects.create(name='users')
117 >>> get_identity(group)
118 (None, <Group: users>)
119
120 >>> anon = AnonymousUser()
121 >>> get_identity(anon)
122 (<User: AnonymousUser>, None)
123
124 >>> get_identity("not instance")
125 ...
126 NotUserNorGroup: User/AnonymousUser or Group instance is required (got )
127 ```
128 """
129 if isinstance(identity, AnonymousUser):
130 identity = get_anonymous_user()
131
132 group_model = get_group_obj_perms_model().group.field.related_model # type: ignore[attr-defined]
133
134 # get identity from queryset model type
135 if isinstance(identity, QuerySet):
136 identity_model_type = identity.model
137 if issubclass(identity_model_type, get_user_model()):
138 return identity, None
139 elif issubclass(identity_model_type, group_model):
140 return None, identity
141
142 # get identity from the first element in the list
143 if isinstance(identity, list):
144 if not identity:
145 return None, None
146 if isinstance(identity[0], get_user_model()):
147 return identity, None
148 if isinstance(identity[0], group_model):
149 return None, identity
150
151 if isinstance(identity, get_user_model()):
152 return identity, None
153 if isinstance(identity, group_model):
154 return None, identity
155
156 raise NotUserNorGroup("User/AnonymousUser or Group instance is required (got %s)" % identity)
157
158
159 def get_40x_or_None(
160 request: HttpRequest,
161 perms: list[str],
162 obj: Any | None = None,
163 login_url: Any | None = None,
164 redirect_field_name: str | None = None,
165 return_403: bool = False,
166 return_404: bool = False,
167 permission_denied_message: str = "",
168 accept_global_perms: bool = False,
169 any_perm: bool = False,
170 ) -> HttpResponseForbidden | HttpResponseNotFound | HttpResponseRedirect | HttpResponse | None:
171 login_url = login_url or settings.LOGIN_URL
172 redirect_field_name = redirect_field_name or REDIRECT_FIELD_NAME
173
174 # Handles both original and with object provided permission check
175 # as `obj` defaults to None
176
177 has_permissions = False
178 # global perms check first (if accept_global_perms)
179 if accept_global_perms:
180 has_permissions = all(request.user.has_perm(perm) for perm in perms) # type: ignore[union-attr]
181 # if still no permission granted, try obj perms
182 if not has_permissions:
183 if any_perm:
184 has_permissions = any(request.user.has_perm(perm, obj) for perm in perms) # type: ignore[union-attr]
185 else:
186 has_permissions = all(request.user.has_perm(perm, obj) for perm in perms) # type: ignore[union-attr]
187
188 if not has_permissions:
189 if return_403:
190 if guardian_settings.RENDER_403:
191 response = render(
192 request,
193 guardian_settings.TEMPLATE_403,
194 context={"exception": permission_denied_message},
195 )
196 response.status_code = 403
197 return response
198 elif guardian_settings.RAISE_403:
199 raise PermissionDenied(permission_denied_message)
200 return HttpResponseForbidden()
201 if return_404:
202 if guardian_settings.RENDER_404:
203 response = render(request, guardian_settings.TEMPLATE_404)
204 response.status_code = 404
205 return response
206 elif guardian_settings.RAISE_404:
207 raise ObjectDoesNotExist
208 return HttpResponseNotFound()
209 else:
210 from django.contrib.auth.views import redirect_to_login
211
212 return redirect_to_login(request.get_full_path(), login_url, redirect_field_name)
213 return None
214
215
216 def get_obj_perm_model_by_conf(setting_name: str) -> type[Model]:
217 """Return the model that matches the guardian settings.
218
219 Parameters:
220 setting_name (str): The name of the setting to get the model from.
221
222 Returns:
223 The model class that matches the guardian settings.
224
225 Raises:
226 ImproperlyConfigured: If the setting value is not an installed model or
227 does not follow the format 'app_label.model_name'.
228 """
229 setting_value: str = getattr(guardian_settings, setting_name)
230 try:
231 return django_apps.get_model(setting_value, require_ready=False) # type: ignore
232 except ValueError as e:
233 raise ImproperlyConfigured(f"{setting_value} must be of the form 'app_label.model_name'") from e
234 except LookupError as e:
235 raise ImproperlyConfigured(
236 f"{setting_name} refers to model '{setting_value}' that has not been installed"
237 ) from e
238
239
240 def clean_orphan_obj_perms(
241 batch_size: int | None = None,
242 max_batches: int | None = None,
243 max_duration_secs: int | None = None,
244 skip_batches: int = 0,
245 ) -> int:
246 """
247 Removes orphan object permissions using queryset slice-based batching,
248 batch skipping, batch limit, and time-based interruption.
249 """
250
251 UserObjectPermission = get_user_obj_perms_model()
252 GroupObjectPermission = get_group_obj_perms_model()
253
254 deleted = 0
255 scanned = 0
256 processed_batches = 0
257 batch_count = 0
258 start_time = time.monotonic()
259
260 if batch_size is None:
261 all_objs = list(
262 chain(
263 UserObjectPermission.objects.order_by("pk"),
264 GroupObjectPermission.objects.order_by("pk"),
265 )
266 )
267
268 for obj in all_objs:
269 if max_duration_secs is not None and (time.monotonic() - start_time >= max_duration_secs):
270 logger.info(f"Time limit of {max_duration_secs}s reached.")
271 break
272
273 scanned += 1
274 if obj.content_object is None:
275 logger.debug("Removing %s (pk=%d)", obj, obj.pk)
276 obj.delete()
277 deleted += 1
278 processed_batches = 1
279 else:
280 total_user = UserObjectPermission.objects.count()
281 total_group = GroupObjectPermission.objects.count()
282 total_records = total_user + total_group
283
284 total_batches_possible = ceil(total_records / batch_size)
285
286 remaining_batches = total_batches_possible - skip_batches
287 if max_batches is not None:
288 remaining_batches = min(remaining_batches, max_batches)
289
290 logger.info(
291 f"Starting orphan object permissions cleanup with batch_size={batch_size}, "
292 f"max_batches={max_batches}, max_duration_secs={max_duration_secs}, skip_batches={skip_batches}"
293 )
294
295 # Process User permissions first
296 user_processed = 0
297 user_total = UserObjectPermission.objects.count()
298
299 # Skip user batches if needed
300 user_skip_records = min(skip_batches * batch_size, user_total)
301 user_remaining = user_total - user_skip_records
302
303 while user_remaining > 0 and remaining_batches > 0:
304 if max_duration_secs is not None and (time.monotonic() - start_time >= max_duration_secs):
305 logger.info(f"Time limit of {max_duration_secs}s reached.")
306 break
307
308 gc.collect()
309
310 current_batch_size = min(batch_size, user_remaining)
311 user_batch = list(
312 UserObjectPermission.objects.order_by("pk")[
313 user_skip_records + user_processed : user_skip_records + user_processed + current_batch_size
314 ]
315 )
316
317 if not user_batch:
318 break
319
320 scanned += len(user_batch)
321 user_processed += len(user_batch)
322 user_remaining -= len(user_batch)
323
324 orphan_pks = [obj.pk for obj in user_batch if obj.content_object is None]
325
326 if orphan_pks:
327 logger.info(
328 f"!!! Found {len(orphan_pks)} orphan user permissions in batch {processed_batches + 1}. !!!"
329 )
330 UserObjectPermission.objects.filter(pk__in=orphan_pks).delete()
331 deleted += len(orphan_pks)
332
333 processed_batches += 1
334 batch_count += 1
335 remaining_batches -= 1
336
337 logger.info(f"Processed user batch {processed_batches}, scanned {scanned} objects.")
338
339 # Process Group permissions
340 if remaining_batches > 0:
341 group_processed = 0
342 group_total = GroupObjectPermission.objects.count()
343
344 # Calculate skip for group permissions
345 total_user_batches = ceil(user_total / batch_size) if user_total > 0 else 0
346 group_skip_batches = max(0, skip_batches - total_user_batches)
347 group_skip_records = min(group_skip_batches * batch_size, group_total)
348 group_remaining = group_total - group_skip_records
349
350 while group_remaining > 0 and remaining_batches > 0:
351 if max_duration_secs is not None and (time.monotonic() - start_time >= max_duration_secs):
352 logger.info(f"Time limit of {max_duration_secs}s reached.")
353 break
354
355 gc.collect()
356
357 current_batch_size = min(batch_size, group_remaining)
358 group_batch = list(
359 GroupObjectPermission.objects.order_by("pk")[
360 group_skip_records + group_processed : group_skip_records + group_processed + current_batch_size
361 ]
362 )
363
364 if not group_batch:
365 break
366
367 scanned += len(group_batch)
368 group_processed += len(group_batch)
369 group_remaining -= len(group_batch)
370
371 orphan_pks = [obj.pk for obj in group_batch if obj.content_object is None]
372
373 if orphan_pks:
374 logger.info(
375 f"!!! Found {len(orphan_pks)} orphan group permissions in batch {processed_batches + 1}. !!!"
376 )
377 GroupObjectPermission.objects.filter(pk__in=orphan_pks).delete()
378 deleted += len(orphan_pks)
379
380 processed_batches += 1
381 batch_count += 1
382 remaining_batches -= 1
383
384 logger.info(f"Processed group batch {processed_batches}, scanned {scanned} objects.")
385
386 logger.info(
387 f"Finished orphan object permissions cleanup. "
388 f"Scanned: {scanned} | Removed: {deleted} | "
389 f"Batches processed: {processed_batches}"
390 )
391
392 if batch_size:
393 suggestion = (
394 f"To resume cleanup, call:\n"
395 f"clean_orphan_obj_perms(batch_size={batch_size}, "
396 f"skip_batches={skip_batches + processed_batches}, "
397 )
398 if max_batches is not None:
399 suggestion += f"max_batches={max_batches - batch_count}, "
400 if max_duration_secs is not None:
401 suggestion += f"max_duration_secs={max_duration_secs}, "
402 suggestion = suggestion.rstrip(", ") + ")"
403 logger.info(suggestion)
404
405 return deleted
406
407
408 # TODO: should raise error when multiple UserObjectPermission direct relations
409 # are defined
410
411
412 def get_obj_perms_model(obj: Model | None, base_cls: type[Model], generic_cls: type[Model]) -> type[Model]:
413 """Return the matching object permission model for the obj class.
414
415 Defaults to returning the generic object permission when no direct foreignkey is defined, or obj is None.
416 """
417 # Default to the generic object permission model
418 # when None obj is provided
419 if obj is None:
420 return generic_cls
421
422 if isinstance(obj, Model):
423 obj = obj.__class__
424
425 fields = (
426 f
427 for f in obj._meta.get_fields() # type: ignore[union-attr] # obj is already checked for None
428 if (f.one_to_many or f.one_to_one) and f.auto_created
429 )
430
431 for attr in fields:
432 model = getattr(attr, "related_model", None)
433 if model and issubclass(model, base_cls) and model is not generic_cls and getattr(model, "enabled", True):
434 # if model is generic one it would be returned anyway
435 if not model.objects.is_generic():
436 # make sure that content_object's content_type is the same as
437 # the one of given obj
438 fk = model._meta.get_field("content_object")
439 if get_content_type(obj) == get_content_type(fk.remote_field.model):
440 return model
441 return generic_cls
442
443
444 def get_user_obj_perms_model(obj: Model | None = None) -> type[Model]:
445 """Returns model class that connects given `obj` and User class.
446
447 If obj is not specified, then the user generic object permission model
448 that is returned is determined by the guardian settings for 'USER_OBJ_PERMS_MODEL'.
449 """
450 from guardian.models import UserObjectPermissionBase
451
452 UserObjectPermission = get_obj_perm_model_by_conf("USER_OBJ_PERMS_MODEL")
453 return get_obj_perms_model(obj, UserObjectPermissionBase, UserObjectPermission)
454
455
456 def get_group_obj_perms_model(obj: Model | None = None) -> type[Model]:
457 """Returns model class that connects given `obj` and Group class.
458
459 If obj is not specified, then the group generic object permission model
460 that is returned is determined by the guardian settings for 'GROUP_OBJ_PERMS_MODEL'.
461 """
462 from guardian.models import GroupObjectPermissionBase
463
464 GroupObjectPermission = get_obj_perm_model_by_conf("GROUP_OBJ_PERMS_MODEL")
465 return get_obj_perms_model(obj, GroupObjectPermissionBase, GroupObjectPermission)
466
467
468 def evict_obj_perms_cache(obj: Any) -> bool:
469 if hasattr(obj, "_guardian_perms_cache"):
470 delattr(obj, "_guardian_perms_cache")
471 return True
472 return False