Merge branch '1314-add-batch-permission-checking' into 'develop'

Resolve "Optimize RBAC performance" - batch check_permissions

Closes #1314

See merge request bramw/baserow!1196
This commit is contained in:
Jrmi committed 2023-02-01 09:28:34 +00:00
commit aabc8c2984
84 files changed
+4249 -1112

No files matched your search

@@ -31,6 +31,18 @@ from baserow.core.user.utils import (
User = get_user_model()
class SubjectUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "username", "first_name", "email"]
extra_kwargs = {
"id": {"read_only": True},
"username": {"read_only": True},
"first_name": {"read_only": True},
"email": {"read_only": True},
}
class UserSerializer(serializers.ModelSerializer):
language = serializers.CharField(
source="profile.language",
@@ -631,6 +631,12 @@ class DatabaseConfig(AppConfig):
permission_manager_type_registry.register(TokenPermissionManagerType())
from baserow.core.registries import subject_type_registry
from .tokens.subjects import TokenSubjectType
subject_type_registry.register(TokenSubjectType())
# The signals must always be imported last because they use the registries
# which need to be filled first.
import baserow.contrib.database.ws.signals # noqa: F403, F401
@@ -18,7 +18,7 @@ class FieldObjectScopeType(ObjectScopeType):
return context.table
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related(
return self.get_base_queryset().prefetch_related(
"table", "table__database", "table__database__group"
)
@@ -30,17 +30,17 @@ msgid ""
"in table \"%(table_name)s\" (%(table_id)s) of database \"%(database_name)s"
"\" (%(database_id)s)."
msgstr ""
"dans la table \"%(table_name)s\" (%(table_id)s) de la base de données \""
"%(database_name)s\" (%(database_id)s)."
"dans la table « %(table_name)s » (%(table_id)s) de la base de données « "
"%(database_name)s » (%(database_id)s)."
#: src/baserow/contrib/database/action/scopes.py:19
#, python-format
msgid ""
"in view \"%(view_name)s\" (%(view_id)s) of table \"%(table_name)s"
"\" (%(table_id)s) in database \"%(database_name)s\" (%(database_id)s)."
"in view « %(view_name)s » (%(view_id)s) of table « %(table_name)s"
" » (%(table_id)s) in database « %(database_name)s » (%(database_id)s)."
msgstr ""
"dans la vue \"%(view_name)s\" (%(view_id)s) de la table \"%(table_name)s\" "
"(%(table_id)s) dans la base de données \"%(database_name)s\" "
"dans la vue « %(view_name)s » (%(view_id)s) de la table « %(table_name)s » "
"(%(table_id)s) dans la base de données « %(database_name)s » "
"(%(database_id)s)."
#: src/baserow/contrib/database/application_types.py:190
@@ -53,7 +53,7 @@ msgstr "Mise à jour d'un champ"
#: src/baserow/contrib/database/fields/actions.py:36
#, python-format
msgid "Field \"%(field_name)s\" (%(field_id)s) updated"
msgid "Field « %(field_name)s » (%(field_id)s) updated"
msgstr "Champ « %(field_name)s » (%(field_id)s) mis à jour"
#: src/baserow/contrib/database/fields/actions.py:325
@@ -62,7 +62,7 @@ msgstr "Création d'un champ"
#: src/baserow/contrib/database/fields/actions.py:326
#, python-format
msgid "Field \"%(field_name)s\" (%(field_id)s) created"
msgid "Field « %(field_name)s » (%(field_id)s) created"
msgstr "Champ « %(field_name)s » (%(field_id)s) créé"
#: src/baserow/contrib/database/fields/actions.py:418
@@ -18,7 +18,7 @@ class DatabaseObjectScopeType(ObjectScopeType):
return context.application_ptr
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related("group")
return self.get_base_queryset().prefetch_related("group")
def get_filter_for_scope_type(self, scope_type, scopes):
if scope_type.type == GroupObjectScopeType.type:
@@ -17,7 +17,7 @@ class DatabaseTableObjectScopeType(ObjectScopeType):
return context.database
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related("database", "database__group")
return self.get_base_queryset().prefetch_related("database", "database__group")
def get_filter_for_scope_type(self, scope_type, scopes):
if scope_type.type == GroupObjectScopeType.type:
@@ -8,7 +8,7 @@ from baserow.contrib.database.table.operations import (
ListenToAllDatabaseTableEventsOperationType,
)
from baserow.contrib.database.ws.pages import TablePageType
from baserow.core.exceptions import PermissionDenied
from baserow.core.exceptions import PermissionException
from baserow.core.mixins import TrashableModelMixin
from baserow.core.models import Group
from baserow.core.object_scopes import GroupObjectScopeType
@@ -78,7 +78,7 @@ def unsubscribe_subject_from_tables_currently_subscribed_to(
subject = subject_type_qs.get(pk=subject_id)
scope = scope_type.model_class.objects.get(pk=scope_id)
users = subject_type.get_associated_users(subject)
users = subject_type.get_users_included_in_subject(subject)
tables = DatabaseTableObjectScopeType().get_all_context_objects_in_scope(scope)
channel_group_names_users_dict = defaultdict(set)
@@ -95,7 +95,7 @@ def unsubscribe_subject_from_tables_currently_subscribed_to(
group=group,
context=table,
)
except PermissionDenied:
except PermissionException:
channel_group_names_users_dict[channel_group_name].add(user.id)
channel_layer = get_channel_layer()
@@ -13,6 +13,7 @@ from baserow.contrib.database.tokens.constants import (
)
from baserow.core.handler import CoreHandler
from baserow.core.registries import object_scope_type_registry
from baserow.core.types import PermissionCheck
from baserow.core.utils import random_string
from .exceptions import (
@@ -370,29 +371,24 @@ class TokenHandler:
if token.group_id != table.database.group_id:
return False
# First check the user has the permission to use the token
if not CoreHandler().check_permissions(
token.user, UseTokenOperationType.type, group=token.group, context=token
):
return False
if isinstance(type_name, str):
type_names = [type_name]
else:
type_names = type_name
type_names = type_name if isinstance(type_name, list) else [type_name]
return any(
(
token_operation in TOKEN_TO_OPERATION_MAP
and CoreHandler().check_permissions(
token,
TOKEN_TO_OPERATION_MAP[token_operation],
group=token.group,
context=table,
raise_error=False,
)
for token_operation in type_names
)
)
checks = [
PermissionCheck(token, TOKEN_TO_OPERATION_MAP[token_operation], table)
for token_operation in type_names
if token_operation in TOKEN_TO_OPERATION_MAP
]
token_permission = CoreHandler().check_multiple_permissions(checks, token.group)
# At least one must be True
return any([v is True for v in token_permission.values()])
def check_table_permissions(
self, request_or_token, type_name, table, force_check=False
@@ -1,35 +1,66 @@
from collections import defaultdict
from django.db.models import Q
from baserow.contrib.database.tokens.models import Token, TokenPermission
from baserow.contrib.database.tokens.exceptions import NoPermissionToTable
from baserow.contrib.database.tokens.models import TokenPermission
from baserow.contrib.database.tokens.subjects import TokenSubjectType
from baserow.core.registries import PermissionManagerType
from .constants import OPERATION_TO_TOKEN_MAP
from .constants import OPERATION_TO_TOKEN_MAP, TOKEN_TO_OPERATION_MAP
class TokenPermissionManagerType(PermissionManagerType):
"""
Check the permission of a token.
"""
type = "token"
supported_actor_types = [TokenSubjectType.type]
def check_permissions(
self, actor, operation, group=None, context=None, include_trash=False
):
def check_multiple_permissions(self, checks, group=None, include_trash=False):
"""
Checks multiple permissions for token.
"""
if not isinstance(actor, Token):
return None
token_checks = []
token_checks_by_context = defaultdict(list)
for check in checks:
if check.operation_name not in OPERATION_TO_TOKEN_MAP:
continue
else:
token_checks_by_context[check.context].append(check)
if operation not in OPERATION_TO_TOKEN_MAP:
return False
permission_by_token = {}
table = context
token = actor
# NOTE: we do one query per context because it's simpler but we could probably
# do better. Regarding the way we use tokens for now it should be enough.
for context, token_checks in token_checks_by_context.items():
return TokenPermission.objects.filter(
Q(database__table=table)
| Q(table_id=table.id)
| Q(table__isnull=True, database__isnull=True),
token=token,
type=OPERATION_TO_TOKEN_MAP[operation],
).exists()
query_parts = Q()
for check in token_checks:
query_parts |= Q(token=check.actor) | Q(
type=OPERATION_TO_TOKEN_MAP[check.operation_name]
)
# Query the DB and store allowed operation per token id
operations_by_token_id = defaultdict(set)
for token_id, type in TokenPermission.objects.filter(
query_parts,
Q(database__table=context)
| Q(table_id=context.id)
| Q(table__isnull=True, database__isnull=True),
).values_list("token_id", "type"):
operations_by_token_id[token_id].add(TOKEN_TO_OPERATION_MAP[type])
for check in checks:
if (
check.actor.id not in operations_by_token_id
or check.operation_name
not in operations_by_token_id[check.actor.id]
):
permission_by_token[check] = NoPermissionToTable(
f"The provided token does not have "
f"{OPERATION_TO_TOKEN_MAP.get(check.operation_name, 'unknown')}"
f" permissions to table {check.context.id}."
)
else:
permission_by_token[check] = True
return permission_by_token
@@ -0,0 +1,35 @@
from typing import List
from django.contrib.auth.models import AbstractUser
from baserow.core.models import Group
from baserow.core.registries import SubjectType
from .models import Token
class TokenSubjectType(SubjectType):
type = "core.Token"
model_class = Token
def are_in_group(self, subjects: List[Token], group: Group) -> List[bool]:
"""
Check whether the given subjects are member of the given group.
"""
token_ids_in_group = set(
Token.objects.filter(
id__in=[s.id for s in subjects], group=group
).values_list("id", flat=True)
)
return [s.id in token_ids_in_group for s in subjects]
def get_serializer(self, model_instance, **kwargs):
from baserow.contrib.database.api.tokens.serializers import TokenSerializer
return TokenSerializer(model_instance, **kwargs)
def get_users_included_in_subject(self, subject: Token) -> List[AbstractUser]:
return []
@@ -2040,7 +2040,7 @@ class ViewHandler:
ReadViewOperationType.type,
group=view.table.database.group,
context=view,
raise_error=False,
raise_permission_exceptions=False,
)
if not user_in_group:
if not view.public:
@@ -24,7 +24,7 @@ class DatabaseViewObjectScopeType(ObjectScopeType):
return context.table
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related(
return self.get_base_queryset().prefetch_related(
"table", "table__database", "table__database__group"
)
@@ -56,7 +56,7 @@ class DatabaseViewDecorationObjectScopeType(ObjectScopeType):
return context.view
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related(
return self.get_base_queryset().prefetch_related(
"view",
"view__table",
"view__table__database",
@@ -94,7 +94,7 @@ class DatabaseViewSortObjectScopeType(ObjectScopeType):
return context.view
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related(
return self.get_base_queryset().prefetch_related(
"view",
"view__table",
"view__table__database",
@@ -132,7 +132,7 @@ class DatabaseViewFilterObjectScopeType(ObjectScopeType):
return context.view
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related(
return self.get_base_queryset().prefetch_related(
"view",
"view__table",
"view__table__database",
@@ -1,7 +1,5 @@
from django.conf import settings
from rest_framework.exceptions import NotAuthenticated
from baserow.contrib.database.table.exceptions import TableDoesNotExist
from baserow.contrib.database.table.handler import TableHandler
from baserow.contrib.database.table.operations import (
@@ -13,7 +11,7 @@ from baserow.contrib.database.views.exceptions import (
)
from baserow.contrib.database.views.handler import ViewHandler
from baserow.contrib.database.views.registries import view_type_registry
from baserow.core.exceptions import UserNotInGroup
from baserow.core.exceptions import PermissionDenied, UserNotInGroup
from baserow.core.handler import CoreHandler
from baserow.ws.registries import PageType
@@ -40,7 +38,7 @@ class TablePageType(PageType):
group=table.database.group,
context=table,
)
except (UserNotInGroup, TableDoesNotExist, NotAuthenticated):
except (UserNotInGroup, TableDoesNotExist, PermissionDenied):
return False
return True
+2 -3
View File
@@ -1,6 +1,5 @@
import logging
import traceback
from copy import deepcopy
from datetime import datetime
from typing import List, Optional, Set, Tuple
@@ -75,7 +74,7 @@ class ActionHandler:
# noinspection PyBroadException
action_type = action_type_registry.get(action.type)
# noinspection PyArgumentList
latest_params = action_type.Params(**deepcopy(action.params))
latest_params = action_type.serialized_to_params(action.params)
action_type.undo(user, latest_params, action)
# action.params could be changed, so save the action
@@ -150,7 +149,7 @@ class ActionHandler:
action_being_redone = action
action_type = action_type_registry.get(action.type)
# noinspection PyArgumentList
latest_params = action_type.Params(**deepcopy(action.params))
latest_params = action_type.serialized_to_params(action.params)
action_type.redo(user, latest_params, action_being_redone)
+20 -1
View File
@@ -1,5 +1,6 @@
import abc
import dataclasses
from copy import deepcopy
from datetime import datetime
from typing import Any, Dict, NewType, Optional
@@ -157,6 +158,24 @@ class ActionType(Instance, abc.ABC):
pass
@classmethod
def params_to_serializable(cls, params: Any) -> Any:
"""
Hooks that allows an action to prepare the params object before the
serialization.
"""
return params
@classmethod
def serialized_to_params(cls, serialized_params: Any) -> Any:
"""
Hooks that allow an action to change the way the param object is prepared from
the serialized dict.
"""
return cls.Params(**deepcopy(serialized_params))
@classmethod
@abc.abstractmethod
def scope(cls, *args, **kwargs) -> ActionScopeStr:
@@ -299,7 +318,7 @@ class UndoableActionTypeMixin(abc.ABC):
user=user,
group=group,
type=cls.type,
params=params,
params=cls.params_to_serializable(params),
scope=scope,
session=session,
action_group=action_group,
+2 -1
View File
@@ -61,9 +61,10 @@ class CoreConfig(AppConfig):
from baserow.core.registries import subject_type_registry
from .subjects import UserSubjectType
from .subjects import AnonymousUserSubjectType, UserSubjectType
subject_type_registry.register(UserSubjectType())
subject_type_registry.register(AnonymousUserSubjectType())
from .operations import (
CreateApplicationsGroupOperationType,
+155 -62
View File
@@ -3,7 +3,7 @@ import json
import os
from io import BytesIO
from pathlib import Path
from typing import IO, Any, Dict, List, NewType, Optional, Set, Tuple, TypedDict, cast
from typing import IO, Any, Dict, List, NewType, Optional, Tuple, Union, cast
from urllib.parse import urljoin, urlparse
from zipfile import ZIP_DEFLATED, ZipFile
@@ -16,7 +16,6 @@ from django.db.models import Count, Prefetch, Q, QuerySet
from django.utils import translation
from itsdangerous import URLSafeSerializer
from rest_framework.exceptions import NotAuthenticated
from tqdm import tqdm
from baserow.core.user.utils import normalize_email_address
@@ -94,7 +93,7 @@ from .signals import (
groups_reordered,
)
from .trash.handler import TrashHandler
from .types import ContextObject
from .types import Actor, ContextObject, PermissionCheck, PermissionObjectResult
from .utils import (
ChildProgressBuilder,
atomic_if_not_already,
@@ -107,11 +106,6 @@ User = get_user_model()
GroupForUpdate = NewType("GroupForUpdate", Group)
class PermissionObjectResult(TypedDict):
name: str
permissions: Any
class CoreHandler:
def get_settings(self):
"""
@@ -163,14 +157,119 @@ class CoreHandler:
settings_instance.save()
return settings_instance
def check_permissions(
def check_multiple_permissions(
self,
actor: AbstractUser,
checks: List[PermissionCheck],
group: Optional[Group] = None,
include_trash: bool = False,
return_permissions_exceptions: bool = False,
) -> Dict[PermissionCheck, Union[bool, PermissionException]]:
"""
Given a list of permission to check, returns True for each check for which the
triplet (actor, permission_name, scope) is allowed.
When we check the permissions, all permission managers listed in
`settings.PERMISSION_MANAGERS` are called successively to determine the policy
for each given check.
For each check, each permission manager can answer with `True` if the operation
is permitted, False operation is disallowed and return `None` if it can't take
a definitive answer.
If None of the permission manager replied with a final answer for a check,
the operation is denied by default for this check.
:param checks: The list of check to do. Each check is a triplet of
(actor, permission_name, scope).
:param group: The optional group in which the operations take place.
:param include_trash: If true then also checks if the given group has been
trashed instead of raising a DoesNotExist exception.
:return: A dictionary with one entry for each check of the parameter as key and
whether the operation is allowed or not as value.
"""
result = {}
undetermined_checks = set(checks)
for permission_manager_name in settings.PERMISSION_MANAGERS:
if not undetermined_checks:
break
permission_manager_type = permission_manager_type_registry.get(
permission_manager_name
)
supported_checks = [
c
for c in undetermined_checks
if permission_manager_type.actor_is_supported(c.actor)
]
manager_result = permission_manager_type.check_multiple_permissions(
supported_checks,
group=group,
include_trash=include_trash,
)
for check, check_result in manager_result.items():
if check_result is not None:
if (
isinstance(check_result, PermissionException)
and not return_permissions_exceptions
):
result[check] = False
else:
result[check] = check_result
undetermined_checks.remove(check)
# Permission denied by default to all non handled check
for undetermined_check in undetermined_checks:
result[undetermined_check] = (
PermissionDenied(undetermined_check.actor)
if return_permissions_exceptions
else False
)
return result
def check_permission_for_multiple_actors(
self,
actors: List[Actor],
operation_name: str,
group: Optional[Group] = None,
context: Optional[ContextObject] = None,
include_trash: bool = False,
raise_error: bool = True,
) -> List[Actor]:
"""
Helper method for a common use case with multiple permission checking when you
want to check the same permission for multiple users at once.
:param actor: The actor who wants to execute the operation. Generally a `User`,
but can be a `Token`.
:param operation_name: The operation name the actor wants to execute.
:param group: The optional group in which the operation takes place.
:param context: The optional object affected by the operation. For instance
if you are updating a `Table` object, the context is this `Table` object.
:param include_trash: If true then also checks if the given group has been
trashed instead of raising a DoesNotExist exception.
:return: The list of allowed actors.
"""
checks = [PermissionCheck(actor, operation_name, context) for actor in actors]
checked = self.check_multiple_permissions(
checks, group, include_trash=include_trash
)
return [actor for (actor, _, _), result in checked.items() if result is True]
def check_permissions(
self,
actor: Actor,
operation_name: str,
group: Optional[Group] = None,
context: Optional[ContextObject] = None,
include_trash: bool = False,
raise_permission_exceptions: bool = True,
allow_if_template: bool = False,
) -> bool:
"""
@@ -196,16 +295,14 @@ class CoreHandler:
if you are updating a `Table` object, the context is this `Table` object.
:param include_trash: If true then also checks if the given group has been
trashed instead of raising a DoesNotExist exception.
:param raise_error: Raise an exception when the permission is disallowed when
`True`. Return `False` instead when `False`. `True` by default.
:raise PermissionDenied: If the operation is disallowed a PermissionDenied is
raised.
:param raise_permission_exceptions: Raise an exception when the permission is
disallowed when `True`. Return `False` instead when `False`.
`True` by default.
:param allow_if_template: If true and if the group is related to a template,
then True is always returned and no exception will be raised.
:raise PermissionDenied: If the operation is disallowed and raise_error is
`True` a PermissionDenied is raised.
:raise PermissionException: If the operation is disallowed.
:return: `True` if the operation is permitted or `False` if the operation is
disallowed AND raise_error is `False`.
disallowed AND raise_permission_exceptions is `False`.
"""
if settings.DEBUG or settings.TESTS:
@@ -214,30 +311,27 @@ class CoreHandler:
if allow_if_template and group and group.has_template():
return True
for permission_manager_name in settings.PERMISSION_MANAGERS:
permission_manager_type = permission_manager_type_registry.get(
permission_manager_name
)
try:
allowed = permission_manager_type.check_permissions(
actor,
operation_name,
group=group,
context=context,
include_trash=include_trash,
)
except (PermissionException, NotAuthenticated):
if raise_error:
raise
else:
return False
else:
if allowed is True:
return True
check = PermissionCheck(actor, operation_name, context)
# Here none af the permission managers has allowed the operation so the
# operation is denied by default.
if raise_error:
allowed = self.check_multiple_permissions(
[check],
group,
include_trash=include_trash,
return_permissions_exceptions=True,
).get(check, None)
if allowed is True:
return True
if isinstance(allowed, PermissionException):
if raise_permission_exceptions:
raise allowed
else:
return False
# If we get there, the result of the check is probably None so it should be
# denied.
if raise_permission_exceptions:
raise PermissionDenied(actor=actor)
else:
return False
@@ -259,7 +353,7 @@ class CoreHandler:
)
def get_permissions(
self, actor: AbstractUser, group: Optional[Group] = None
self, actor: Actor, group: Optional[Group] = None
) -> List[PermissionObjectResult]:
"""
Generates the object sent to a client to easily check the actor permissions over
@@ -314,7 +408,7 @@ class CoreHandler:
def filter_queryset(
self,
actor: AbstractUser,
actor: Actor,
operation_name: str,
queryset: QuerySet,
group: Optional[Group] = None,
@@ -354,21 +448,6 @@ class CoreHandler:
return queryset
def get_user_ids_of_permitted_users(
self, users: List[AbstractUser], operation_name: str, group: Group, context=None
) -> Set[int]:
permitted_user_ids = set()
# TODO replace with batch check_permission once it's implemented
for user in users:
if self.check_permissions(
user, operation_name, group, context, raise_error=False
):
permitted_user_ids.add(user.id)
return permitted_user_ids
def get_group_for_update(self, group_id: int) -> GroupForUpdate:
return cast(
GroupForUpdate,
@@ -377,18 +456,15 @@ class CoreHandler:
),
)
def get_group(self, group_id, base_queryset=None) -> Group:
def get_group(self, group_id: int, base_queryset: QuerySet = None) -> Group:
"""
Selects a group with a given id from the database.
:param group_id: The identifier of the group that must be returned.
:type group_id: int
:param base_queryset: The base queryset from where to select the group
object. This can for example be used to do a `prefetch_related`.
:type base_queryset: Queryset
:raises GroupDoesNotExist: When the group with the provided id does not exist.
:return: The requested group instance of the provided id.
:rtype: Group
"""
if base_queryset is None:
@@ -620,6 +696,23 @@ class CoreHandler:
return group_user
def get_group_users(
self, group: Group, users: List[User], include_trash: bool = False
) -> QuerySet:
"""
Returns a queryset to get all GroupUser for the given group for all users.
:param group: The group the GroupUser must belong to.
:param users: The user list we want the GroupUsers for.
:param include_trash: Whether or not we want to include trashed Group in the
result.
"""
group_user_queryset = (
GroupUser.objects_and_trash if include_trash else GroupUser.objects
)
return group_user_queryset.filter(user__in=users, group=group)
def update_group_user(
self,
user: AbstractUser,
-67
View File
@@ -7,8 +7,6 @@ from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.db.models import Q, UniqueConstraint
from rest_framework.exceptions import NotAuthenticated
from baserow.core.jobs.mixins import (
JobWithUndoRedoIds,
JobWithUserIpAddress,
@@ -18,7 +16,6 @@ from baserow.core.jobs.models import Job
from baserow.core.user_files.models import UserFile
from .action.models import Action
from .exceptions import UserInvalidGroupPermissionsError, UserNotInGroup
from .mixins import (
CreatedAndUpdatedOnMixin,
HierarchicalModelMixin,
@@ -144,70 +141,6 @@ class Group(HierarchicalModelMixin, TrashableModelMixin, CreatedAndUpdatedOnMixi
def has_template(self):
return self.template_set.all().exists()
def has_user(
self,
user,
permissions=None,
raise_error=False,
allow_if_template=False,
include_trash=False,
):
"""
Checks if the provided user belongs to the group.
:param user: The user that must be in the group.
:type user: User
:param permissions: One or multiple permissions can optionally be provided
and if so, the user must have one of those permissions.
:type permissions: None, str or list
:param raise_error: If True an error will be raised when the user does not
belong to the group or doesn't have the right permissions.
:type raise_error: bool
:param allow_if_template: If true and if the group is related to a template,
then True is always returned and no exception will be raised.
:type allow_if_template: bool
:param include_trash: If true then also checks if the group has been trashed
instead of raising a DoesNotExist exception.
:type include_trash: bool
:raises UserNotInGroup: If the user does not belong to the group.
:raises UserInvalidGroupPermissionsError: If the user does belong to the group,
but doesn't have the right permissions.
:return: Indicates if the user belongs to the group.
:rtype: bool
"""
if permissions and not isinstance(permissions, list):
permissions = [permissions]
if allow_if_template and self.has_template():
return True
elif not bool(user and user.is_authenticated):
if raise_error:
raise NotAuthenticated()
else:
return False
if include_trash:
manager = GroupUser.objects_and_trash
else:
manager = GroupUser.objects
queryset = manager.filter(user_id=user.id, group_id=self.id)
if raise_error:
try:
group_user = queryset.get()
except GroupUser.DoesNotExist:
raise UserNotInGroup(user, self)
if permissions is not None and group_user.permissions not in permissions:
raise UserInvalidGroupPermissionsError(user, self, permissions)
else:
if permissions is not None:
queryset = queryset.filter(permissions__in=permissions)
return queryset.exists()
def get_group_user(self, user: User, include_trash: bool = False) -> "GroupUser":
"""
Return the GroupUser object for this group for the specified user.
+3 -3
View File
@@ -31,7 +31,7 @@ class ApplicationObjectScopeType(ObjectScopeType):
return context.group
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related("group")
return self.get_base_queryset().prefetch_related("group")
def get_filter_for_scope_type(self, scope_type, scopes):
if scope_type.type == GroupObjectScopeType.type:
@@ -51,7 +51,7 @@ class GroupInvitationObjectScopeType(ObjectScopeType):
return context.group
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related("group")
return self.get_base_queryset().prefetch_related("group")
def get_filter_for_scope_type(self, scope_type, scopes):
if scope_type.type == GroupObjectScopeType.type:
@@ -71,7 +71,7 @@ class GroupUserObjectScopeType(ObjectScopeType):
return context.group
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related("group")
return self.get_base_queryset().prefetch_related("group")
def get_filter_for_scope_type(self, scope_type, scopes):
if scope_type.type == GroupObjectScopeType.type:
+78 -74
View File
@@ -1,12 +1,11 @@
from typing import Union
from rest_framework.exceptions import NotAuthenticated
from django.contrib.auth import get_user_model
from baserow.core.handler import CoreHandler
from baserow.core.models import GroupUser
from .exceptions import (
IsNotAdminError,
PermissionDenied,
UserInvalidGroupPermissionsError,
UserNotInGroup,
)
@@ -26,6 +25,9 @@ from .operations import (
UpdateSettingsOperationType,
)
from .registries import PermissionManagerType
from .subjects import UserSubjectType
User = get_user_model()
class CorePermissionManagerType(PermissionManagerType):
@@ -34,17 +36,20 @@ class CorePermissionManagerType(PermissionManagerType):
"""
type = "core"
supported_actor_types = [UserSubjectType.type]
ALWAYS_ALLOWED_OPERATIONS = [
ListGroupsOperationType.type,
]
def check_permissions(
self, actor, operation, group=None, context=None, include_trash=False
):
def check_multiple_permissions(self, checks, group=None, include_trash=False):
if operation in self.ALWAYS_ALLOWED_OPERATIONS:
return True
result = {}
for check in checks:
if check.operation_name in self.ALWAYS_ALLOWED_OPERATIONS:
result[check] = True
return result
def get_permissions_object(self, actor, group=None):
return self.ALWAYS_ALLOWED_OPERATIONS
@@ -56,23 +61,21 @@ class StaffOnlyPermissionManagerType(PermissionManagerType):
"""
type = "staff"
supported_actor_types = [UserSubjectType.type]
STAFF_ONLY_OPERATIONS = [UpdateSettingsOperationType.type]
def check_permissions(
self, actor, operation, group=None, context=None, include_trash=False
):
def check_multiple_permissions(self, checks, group=None, include_trash=False):
if hasattr(actor, "is_authenticated"):
user = actor
if not user.is_authenticated:
raise NotAuthenticated()
if operation in self.STAFF_ONLY_OPERATIONS:
if actor.is_staff:
return True
result = {}
for check in checks:
if check.operation_name in self.STAFF_ONLY_OPERATIONS:
if check.actor.is_staff:
result[check] = True
else:
raise IsNotAdminError(user)
result[check] = IsNotAdminError(check.actor)
return result
def get_permissions_object(self, actor, group=None):
return {
@@ -87,26 +90,27 @@ class GroupMemberOnlyPermissionManagerType(PermissionManagerType):
"""
type = "member"
supported_actor_types = [UserSubjectType.type]
def check_multiple_permissions(self, checks, group=None, include_trash=False):
def check_permissions(
self, actor, operation, group=None, context=None, include_trash=False
):
if group is None:
return None
return {}
if hasattr(actor, "is_authenticated"):
user = actor
if not user.is_authenticated:
raise NotAuthenticated()
users_to_query = {c.actor for c in checks}
if include_trash:
queryset = GroupUser.objects_and_trash
else:
queryset = GroupUser.objects
user_ids_in_group = set(
CoreHandler()
.get_group_users(group, users_to_query, include_trash=include_trash)
.values_list("user_id", flat=True)
)
# Check if the user is a member of this group
if not queryset.filter(user_id=user.id, group_id=group.id).exists():
raise UserNotInGroup(user, group)
permission_by_check = {}
for check in checks:
if check.actor.id not in user_ids_in_group:
permission_by_check[check] = UserNotInGroup(check.actor, group)
return permission_by_check
def get_permissions_object(self, actor, group=None):
# Check if the user is a member of this group
@@ -125,6 +129,7 @@ class BasicPermissionManagerType(PermissionManagerType):
"""
type = "basic"
supported_actor_types = [UserSubjectType.type]
ADMIN_ONLY_OPERATIONS = [
ListInvitationsGroupOperationType.type,
@@ -139,34 +144,35 @@ class BasicPermissionManagerType(PermissionManagerType):
DeleteGroupUserOperationType.type,
]
def check_permissions(
self, actor, operation, group=None, context=None, include_trash=False
):
def check_multiple_permissions(self, checks, group=None, include_trash=False):
if group is None:
return None
return {}
if hasattr(actor, "is_authenticated"):
user = actor
if not user.is_authenticated:
raise NotAuthenticated()
permission_by_check = {}
users_to_query = set()
for check in checks:
if check.operation_name in self.ADMIN_ONLY_OPERATIONS:
users_to_query.add(check.actor)
else:
permission_by_check[check] = True
if operation in self.ADMIN_ONLY_OPERATIONS:
user_permissions_by_id = dict(
CoreHandler()
.get_group_users(group, users_to_query, include_trash=include_trash)
.values_list("user_id", "permissions")
)
if include_trash:
manager = GroupUser.objects_and_trash
for check in checks:
if check.operation_name in self.ADMIN_ONLY_OPERATIONS:
if user_permissions_by_id.get(check.actor.id, "MEMBER") == "ADMIN":
permission_by_check[check] = True
else:
manager = GroupUser.objects
permission_by_check[check] = UserInvalidGroupPermissionsError(
check.actor, group, check.operation_name
)
queryset = manager.filter(user_id=user.id, group_id=group.id)
# Check if the user is a member of this group
group_user = queryset.get()
if "ADMIN" not in group_user.permissions:
raise UserInvalidGroupPermissionsError(user, group, operation)
return True
return permission_by_check
def get_permissions_object(self, actor, group=None, include_trash=False):
if group is None:
@@ -198,6 +204,7 @@ class StaffOnlySettingOperationPermissionManagerType(PermissionManagerType):
"""
type = "setting_operation"
supported_actor_types = [UserSubjectType.type]
# Maps `CoreOperationType` to `Setting` boolean field.
STAFF_ONLY_SETTING_OPERATION_MAP = {
@@ -234,26 +241,23 @@ class StaffOnlySettingOperationPermissionManagerType(PermissionManagerType):
staff_only_operations.append(staff_operation_type)
return always_allowed_operations, staff_only_operations
def check_permissions(
self, actor, operation, group=None, context=None, include_trash=False
) -> Union[None, bool]:
def check_multiple_permissions(self, checks, group=None, include_trash=False):
(
always_allowed_ops,
staff_only_ops,
) = self.get_permitted_operations_for_settings()
if hasattr(actor, "is_authenticated"):
user = actor
if not user.is_authenticated:
raise NotAuthenticated()
result = {}
for check in checks:
if check.operation_name in self.STAFF_ONLY_SETTING_OPERATION_MAP:
if check.operation_name in always_allowed_ops or (
check.operation_name in staff_only_ops and check.actor.is_staff
):
result[check] = True
else:
result[check] = PermissionDenied()
# Test if the operation is one that's relevant to this manager
# Saves us from unnecessarily fetching the instance Settings.
if operation in self.STAFF_ONLY_SETTING_OPERATION_MAP:
# Get our lists of always allowed / staff only operations.
(
always_allowed_ops,
staff_only_ops,
) = self.get_permitted_operations_for_settings()
return operation in always_allowed_ops or (
operation in staff_only_ops and actor.is_staff
)
return result
def get_permissions_object(self, actor, group=None):
(
+123 -34
View File
@@ -1,7 +1,7 @@
import abc
from collections import defaultdict
from functools import cached_property
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
from xmlrpc.client import Boolean
from zipfile import ZipFile
@@ -24,7 +24,7 @@ from .exceptions import (
ObjectScopeTypeDoesNotExist,
OperationTypeAlreadyRegistered,
OperationTypeDoesNotExist,
PermissionDenied,
PermissionException,
PermissionManagerTypeAlreadyRegistered,
PermissionManagerTypeDoesNotExist,
)
@@ -39,7 +39,7 @@ from .registry import (
ModelRegistryMixin,
Registry,
)
from .types import ContextObject, ScopeObject
from .types import Actor, ContextObject, PermissionCheck, ScopeObject, Subject
if TYPE_CHECKING:
from django.contrib.auth.models import AbstractUser
@@ -372,7 +372,7 @@ class AuthenticationProviderTypeRegistry(
return login_options
class PermissionManagerType(Instance):
class PermissionManagerType(abc.ABC, Instance):
"""
A permission manager is responsible to permit or disallow a specific operation
according to the given context.
@@ -386,26 +386,36 @@ class PermissionManagerType(Instance):
See each PermissionManager method and `CoreHandler` methods for more details.
"""
# A list of subject types that are supported by this permission manager.
supported_actor_types = []
def actor_is_supported(self, actor: Actor):
"""
Returns whether the actor given in parameter is handled by this manager type or
not.
"""
actor_type = subject_type_registry.get_by_model(actor)
return actor_type.type in self.supported_actor_types
def check_permissions(
self,
actor: "AbstractUser",
actor: Actor,
operation_name: str,
group: Optional["Group"] = None,
context: Optional[Any] = None,
include_trash: Boolean = False,
) -> Optional[Boolean]:
"""
This method is called each time a permission on an operation is checked by the
`CoreHandler().check_permissions()` method if the current permission manager is
listed in the `settings.PERMISSION_MANAGERS` list.
This method is a helper to check permission with this permission manager when
you need to do only one check. It calls `.check_multiple_permissions` behind
the scene.
It should:
- return `True` if the operation is permitted given the other parameters
- raise a `PermissionDenied` exception if the operation is disallowed
- return `None` if the condition required by the permission manager are not
met.
By default, this method raises a PermissionDenied exception.
It:
- returns `True` if the operation is permitted given the other parameters
- raise a `PermissionException` exception if the operation is disallowed
- return `None` if the pre-condition required by the permission manager
are not met.
:param actor: The actor who wants to execute the operation. Generally a `User`,
but can be a `Token`.
@@ -415,16 +425,60 @@ class PermissionManagerType(Instance):
if you are updating a `Table` object, the context is this `Table` object.
:param include_trash: If true then also checks if the given group has been
trashed instead of raising a DoesNotExist exception.
:raise PermissionDenied: If the operation is disallowed a PermissionDenied is
raised.
:raise PermissionException: If the operation is disallowed.
:return: `True` if the operation is permitted, None if the permission manager
can't decide.
"""
raise PermissionDenied()
check = PermissionCheck(actor, operation_name, context)
result = self.check_multiple_permissions(
[check],
group,
include_trash=include_trash,
).get(check, None)
if isinstance(result, PermissionException):
raise result
return result
@abc.abstractmethod
def check_multiple_permissions(
self,
checks: List[PermissionCheck],
group: "Group" = None,
include_trash: bool = False,
) -> Dict[PermissionCheck, Union[bool, PermissionException]]:
"""
This method is called each time multiple permissions are checked at once
by the `CoreHandler().check_multiple_permissions()` method if the current
permission manager is listed in the `settings.PERMISSION_MANAGERS` list.
It should return a map (dict) with for each check as key, if the related
triplet (actor, permission_name, scope) is allowed (True) or disallowed
(A permission exception).
If a check is omitted in the result, it means that the check is not supported
by this permission manager.
This method MUST be implemented by each permission manager type.
:param checks: The list of check to do. Each check is a triplet of
(actor, permission_name, scope).
:param group: The optional group in which the operations take place.
:param include_trash: If true then also checks if the given group has been
trashed instead of raising a DoesNotExist exception.
:return: A dictionary with one entry for each check of the parameter as key and
whether the operation is allowed or not as value. Check entries can be
omitted in the response dict if the check allowance can't be decided by this
permission manager.
"""
raise NotImplementedError(
"Must be implemented by the specific application type"
)
def get_permissions_object(
self, actor: "AbstractUser", group: Optional["Group"] = None
self, actor: Actor, group: Optional["Group"] = None
) -> Any:
"""
This method should return the data necessary to easily check a permission from
@@ -450,7 +504,7 @@ class PermissionManagerType(Instance):
def filter_queryset(
self,
actor: "AbstractUser",
actor: Actor,
operation_name: str,
queryset: QuerySet,
group: Optional["Group"] = None,
@@ -505,14 +559,6 @@ class ObjectScopeType(Instance, ModelInstanceMixin):
context.
"""
def get_content_type(self):
from django.contrib.contenttypes.models import ContentType
return ContentType.objects.get_for_model(self.model_class)
def get_object_for_this_type(self, **kwargs):
return self.get_content_type().get_object_for_this_type(**kwargs)
def get_parent_scope(self) -> Optional["ObjectScopeType"]:
"""
Returns the parent scope of the current scope.
@@ -595,14 +641,48 @@ class ObjectScopeType(Instance, ModelInstanceMixin):
f"Must be implemented by the specific type <{self.type}>"
)
def get_enhanced_queryset(self) -> QuerySet:
def get_base_queryset(self) -> QuerySet:
"""
Returns the base queryset for the objects of this scope enhanced for better
performances.
Returns the base queryset for the objects of this scope
"""
return self.model_class.objects.all()
def get_enhanced_queryset(self) -> QuerySet:
"""
Returns the enhanced queryset for the objects of this scope enhanced for better
performances.
"""
return self.get_base_queryset()
def are_objects_child_of(
self, child_objects: List[Any], parent_object: ScopeObject
) -> List[bool]:
"""
Checks whether the given list of objects are all children of the given
parent object.
:param child_objects: The list of objects we want to check the scope belonging.
:param parent_object: The parent object. The parent object must be an instance
of the current model_class.
:return: A boolean list that represents whether the object is child of the given
parent for each object from parameter.
"""
if not all([self.contains(child) for child in child_objects]):
raise TypeError(
f"The given child objects must be instance of {self.model_class}"
)
ids_in_scope = (
self.get_base_queryset()
.filter(self.get_filter_for_scopes(scopes=[parent_object]))
.values_list("id", flat=True)
)
return [o.id in ids_in_scope for o in child_objects]
def get_filter_for_scopes(self, scopes: List[Any]) -> Dict[Any, Any]:
"""
Computes the filter to apply get all the objects instance of `self.model_class`
@@ -798,13 +878,22 @@ class SubjectType(abc.ABC, Instance, ModelInstanceMixin):
can execute an operation.
"""
@abc.abstractmethod
def is_in_group(self, subject_id: int, group: "Group") -> bool:
def is_in_group(self, subject: Subject, group: "Group") -> bool:
"""
This function checks if a subject belongs to a group
:return: If the subject belongs to the group
"""
return self.are_in_group([subject], group)[0]
@abc.abstractmethod
def are_in_group(self, subjects: List[Subject], group: "Group") -> List[bool]:
"""
This function checks if the subjects belongs to a group
:return: a list of bool. For each index whether the user at the same index
belongs to the group or not
"""
pass
@abc.abstractmethod
@@ -820,7 +909,7 @@ class SubjectType(abc.ABC, Instance, ModelInstanceMixin):
pass
@abc.abstractmethod
def get_associated_users(self, subject) -> List["AbstractUser"]:
def get_users_included_in_subject(self, subject) -> List["AbstractUser"]:
"""
Returns a list of Users which are associated with this subject.
And associated user is any user that receives permissions in Baserow based
+59 -12
View File
@@ -1,6 +1,18 @@
import contextlib
import typing
from typing import Any, Dict, Generic, List, Optional, Tuple, Type, TypeVar, ValuesView
from functools import lru_cache
from typing import (
Any,
Dict,
Generic,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
ValuesView,
)
from django.core.exceptions import ImproperlyConfigured
from django.db import models
@@ -15,6 +27,9 @@ if typing.TYPE_CHECKING:
from django.contrib.contenttypes.models import ContentType
T = TypeVar("T")
class Instance(object):
"""
This abstract class represents a custom instance that can be added to the registry.
@@ -29,23 +44,41 @@ class Instance(object):
raise ImproperlyConfigured("The type of an instance must be set.")
class ModelInstanceMixin:
class ModelInstanceMixin(Generic[T]):
"""
This mixin introduces a model_class that will be related to the instance. It is to
be used in combination with a registry that extends the ModelRegistryMixin.
"""
model_class: Type
model_class: Type[T]
def __init__(self):
if not self.model_class:
raise ImproperlyConfigured("The model_class of an instance must be set.")
def get_content_type(self) -> "ContentType":
"""
Returns the content_type related to the model_class.
"""
from django.contrib.contenttypes.models import ContentType
return ContentType.objects.get_for_model(self.model_class)
def get_object_for_this_type(self, **kwargs) -> T:
"""
Returns the object given the filters in parameter.
"""
return self.get_content_type().get_object_for_this_type(**kwargs)
def get_all_objects_for_this_type(self, **kwargs) -> models.QuerySet:
"""
Returns a queryset to get the objects given the filters in parameter.
"""
return self.get_content_type().get_all_objects_for_this_type(**kwargs)
class CustomFieldsInstanceMixin:
"""
@@ -381,25 +414,39 @@ P = TypeVar("P")
class ModelRegistryMixin(Generic[P, T]):
def get_by_model(self, model_instance: P) -> T:
def get_by_model(self, model_instance: Union[P, type]) -> T:
"""
Returns a registered instance of the given model class.
:param model_instance: The value that must be or must be an instance of the
model_class.
:type model_instance: Model or Model()
:param model_instance: The value that must be a Model class or
an instance of any model_class.
:raises InstanceTypeDoesNotExist: When the provided model instance is not
found in the registry.
:return: The registered instance.
"""
if isinstance(model_instance, type):
clazz = model_instance
else:
clazz = type(model_instance)
return self.get_for_class(clazz)
@lru_cache
def get_for_class(self, clazz: type) -> T:
"""
Returns a registered instance of the given model class.
:param model_instance: The value that must be a Model class.
:raises InstanceTypeDoesNotExist: When the provided model instance is not
found in the registry.
:return: The registered instance.
:rtype: Instance
"""
most_specific_value = None
for value in self.registry.values():
value_model_class = value.model_class
if value_model_class == model_instance or isinstance(
model_instance, value_model_class
):
if value_model_class == clazz or issubclass(clazz, value_model_class):
if most_specific_value is None:
most_specific_value = value
else:
@@ -417,7 +464,7 @@ class ModelRegistryMixin(Generic[P, T]):
return most_specific_value
raise self.does_not_exist_exception_class(
f"The {self.name} model instance {model_instance} does not exist."
f"The {self.name} model {clazz} does not exist."
)
def get_all_by_model_isinstance(self, model_instance: P) -> List[T]:
@@ -16,7 +16,7 @@ class SnapshotObjectScopeType(ObjectScopeType):
return context.snapshot_from_application.specific
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related(
return self.get_base_queryset().prefetch_related(
"snapshot_from_application", "snapshot_from_application__group"
)
+39 -8
View File
@@ -1,10 +1,10 @@
from typing import List
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import AbstractUser, AnonymousUser
from baserow.core.models import Group, GroupUser, User
from baserow.core.registries import SubjectType
from baserow_enterprise.api.role.serializers import SubjectUserSerializer
from baserow.core.types import Subject
class UserSubjectType(SubjectType):
@@ -12,16 +12,47 @@ class UserSubjectType(SubjectType):
type = "auth.User"
model_class = User
def is_in_group(self, subject_id: int, group: Group) -> bool:
return GroupUser.objects.filter(
user_id=subject_id,
def are_in_group(self, subjects: List[Subject], group: Group) -> List[bool]:
"""
Check whether the given subjects ar member of the given group.
"""
user_ids_in_group = GroupUser.objects.filter(
user__in=subjects,
group=group,
user__profile__to_be_deleted=False,
user__is_active=True,
).exists()
).values_list("user_id", flat=True)
return [s.id in user_ids_in_group for s in subjects]
def get_serializer(self, model_instance, **kwargs):
from baserow.api.user.serializers import SubjectUserSerializer
return SubjectUserSerializer(model_instance, **kwargs)
def get_associated_users(self, user: AbstractUser) -> List[AbstractUser]:
return [user]
def get_users_included_in_subject(
self, subject: AbstractUser
) -> List[AbstractUser]:
return [subject]
class AnonymousUserSubjectType(SubjectType):
type = "anonymous"
model_class = AnonymousUser
def are_in_group(self, subjects: List[Subject], group: Group) -> List[bool]:
"""
Anonymous users are never member of any group.
"""
return [False for _ in subjects]
def get_serializer(self, model_instance, **kwargs):
return None
def get_users_included_in_subject(
self, subject: AnonymousUser
) -> List[AbstractUser]:
return []
+2 -2
View File
@@ -174,7 +174,7 @@ class TrashHandler:
ReadGroupTrashOperationType.type,
group=group,
context=group,
raise_error=False,
raise_permission_exceptions=False,
include_trash=True,
)
if can_view_group:
@@ -575,7 +575,7 @@ def _get_applications_excluding_perm_deleted(
ReadApplicationTrashOperationType.type,
group=group,
context=application,
raise_error=False,
raise_permission_exceptions=False,
include_trash=True,
)
if can_view_application:
+16 -1
View File
@@ -1,4 +1,4 @@
from typing import Any
from typing import Any, NamedTuple, Optional, TypedDict
# A scope object needs to have a related registered ScopeObjectType
ScopeObject = Any
@@ -8,3 +8,18 @@ ContextObject = Any
# A subject needs to have a related registered SubjectType
Subject = Any
# An actor is an object that can do an operation. For now only AbstractUser or Token
Actor = Any
class PermissionCheck(NamedTuple):
actor: Actor
operation_name: str
context: Optional[ContextObject] = None
class PermissionObjectResult(TypedDict):
name: str
permissions: Any
@@ -74,7 +74,9 @@ def mutable_field_type_registry():
from baserow.contrib.database.fields.registries import field_type_registry
before = field_type_registry.registry.copy()
field_type_registry.get_for_class.cache_clear()
yield field_type_registry
field_type_registry.get_for_class.cache_clear()
field_type_registry.registry = before
@@ -92,7 +94,9 @@ def mutable_application_registry():
from baserow.core.registries import application_type_registry
before = application_type_registry.registry.copy()
application_type_registry.get_for_class.cache_clear()
yield application_type_registry
application_type_registry.get_for_class.cache_clear()
application_type_registry.registry = before
@@ -101,7 +105,9 @@ def mutable_trash_item_type_registry():
from baserow.core.trash.registries import trash_item_type_registry
before = trash_item_type_registry.registry.copy()
trash_item_type_registry.get_for_class.cache_clear()
yield trash_item_type_registry
trash_item_type_registry.get_for_class.cache_clear()
trash_item_type_registry.registry = before
@@ -295,6 +301,7 @@ def application_type_serialized_raising_operationalerror(
def _perform_stub(raise_transaction_exception: bool = True):
stub_application_type = MaxLocksPerTransactionExceededApplicationType()
stub_application_type.raise_transaction_exception = raise_transaction_exception
mutable_application_registry.get_for_class.cache_clear()
mutable_application_registry.registry[
DatabaseApplicationType.type
] = stub_application_type
@@ -319,6 +326,7 @@ def trash_item_type_perm_delete_item_raising_operationalerror(
def _perform_stub(raise_transaction_exception: bool = True):
stub_trash_item_type = MaxLocksPerTransactionExceededGroupTrashableItemType()
stub_trash_item_type.raise_transaction_exception = raise_transaction_exception
mutable_trash_item_type_registry.get_for_class.cache_clear()
mutable_trash_item_type_registry.registry[
GroupTrashableItemType.type
] = stub_trash_item_type
+10 -7
View File
@@ -90,14 +90,16 @@ def broadcast_to_permitted_users(
scope = objects.get(id=scope_id)
user_ids = list(
CoreHandler().get_user_ids_of_permitted_users(
user_ids = [
u.id
for u in CoreHandler().check_permission_for_multiple_actors(
users_in_group,
operation_type,
group,
context=scope,
)
)
]
broadcast_to_users(user_ids, payload, ignore_web_socket_id=ignore_web_socket_id)
@@ -248,14 +250,15 @@ def broadcast_application_created(
for group_user in GroupUser.objects.filter(group=group).select_related("user")
]
user_ids = list(
CoreHandler().get_user_ids_of_permitted_users(
user_ids = [
u.id
for u in CoreHandler().check_permission_for_multiple_actors(
users_in_group,
ReadApplicationOperationType.type,
group,
context=application.specific,
context=application,
)
)
]
users_in_group_id_map = {user.id: user for user in users_in_group}
@@ -84,7 +84,7 @@ def test_list_tables_doesnt_do_n_queries_per_tables(api_client, data_fixture):
response = api_client.get(url, HTTP_AUTHORIZATION=f"JWT {token}")
assert response.status_code == HTTP_200_OK
assert len(query_for_n_tables.captured_queries) == len(
assert len(query_for_n_tables.captured_queries) >= len(
query_for_n_plus_one_tables.captured_queries
)
@@ -807,7 +807,7 @@ def test_form_view_multiple_collaborators_field_options(api_client, data_fixture
@pytest.mark.django_db
def test_get_form_view_field_options(
api_client, data_fixture, django_assert_num_queries
api_client, data_fixture, django_assert_max_num_queries
):
user, token = data_fixture.create_user_and_token()
table = data_fixture.create_database_table(user=user)
@@ -883,7 +883,7 @@ def test_get_form_view_field_options(
field_option=text_field_option_3, field=text_field
)
with django_assert_num_queries(len(captured.captured_queries)):
with django_assert_max_num_queries(len(captured.captured_queries)):
api_client.get(
url,
format="json",
@@ -1256,7 +1256,7 @@ def test_patch_form_view_field_options_conditions_create_invalid_field(
@pytest.mark.django_db
def test_patch_form_view_field_options_conditions_create_num_queries(
api_client, data_fixture, django_assert_num_queries
api_client, data_fixture, django_assert_max_num_queries
):
user, token = data_fixture.create_user_and_token()
table = data_fixture.create_database_table(user=user)
@@ -1293,7 +1293,7 @@ def test_patch_form_view_field_options_conditions_create_num_queries(
# Even though we're adding more conditions, we expect to execute the sam amount
# of queries.
with django_assert_num_queries(len(captured.captured_queries)):
with django_assert_max_num_queries(len(captured.captured_queries)):
api_client.patch(
url,
{
@@ -1447,7 +1447,7 @@ def test_patch_form_view_field_options_conditions_update_num_queries(
@pytest.mark.django_db
def test_patch_form_view_field_options_conditions_delete_num_queries(
api_client, data_fixture, django_assert_num_queries
api_client, data_fixture, django_assert_max_num_queries
):
user, token = data_fixture.create_user_and_token()
table = data_fixture.create_database_table(user=user)
@@ -1498,7 +1498,7 @@ def test_patch_form_view_field_options_conditions_delete_num_queries(
# Even though we're deleting more conditions, we expect to execute the same amount
# of queries.
with django_assert_num_queries(len(captured.captured_queries)):
with django_assert_max_num_queries(len(captured.captured_queries)):
api_client.patch(
url,
{
@@ -22,6 +22,16 @@ from baserow.contrib.database.views.view_types import GridViewType
from baserow.core.trash.handler import TrashHandler
@pytest.fixture(autouse=True)
def clean_registry_cache():
"""
Ensure no patched version stays in cache.
"""
view_type_registry.get_for_class.cache_clear()
yield
@pytest.mark.django_db
def test_list_views(api_client, data_fixture):
user, token = data_fixture.create_user_and_token(
@@ -201,7 +211,7 @@ def test_list_views_doesnt_do_n_queries(api_client, data_fixture):
assert response.status_code == HTTP_200_OK
response_json = response.json()
assert len(query_for_n.captured_queries) == len(
assert len(query_for_n.captured_queries) >= len(
query_for_n_plus_one.captured_queries
)
@@ -462,6 +472,7 @@ def test_get_view_field_options(api_client, data_fixture):
with patch.dict(
view_type_registry.registry, {"grid": GridViewWithNormalViewModel()}
):
view_type_registry.get_for_class.cache_clear()
url = reverse("api:database:views:field_options", kwargs={"view_id": grid.id})
response = api_client.get(url, **{"HTTP_AUTHORIZATION": f"JWT {token}"})
assert response.status_code == HTTP_400_BAD_REQUEST
@@ -49,6 +49,16 @@ from baserow.core.trash.handler import TrashHandler
from baserow.test_utils.helpers import setup_interesting_test_table
@pytest.fixture(autouse=True)
def clean_registry_cache():
"""
Ensure no patched version stays in cache.
"""
field_type_registry.get_for_class.cache_clear()
yield
@pytest.mark.django_db(transaction=True)
@pytest.mark.disabled_in_ci
def test_can_convert_between_all_fields(data_fixture):
@@ -470,13 +480,15 @@ def test_update_field(send_mock, data_fixture):
assert getattr(field_with_max_length_name, "name") == field_name_with_ok_length
# This failing field type triggers the CannotChangeFieldType error if a field is
# changed into this type.
class FailingFieldType(TextFieldType):
def get_alter_column_prepare_new_value(self, connection, from_field, to_field):
return "p_in::NOT_VALID_SQL_SO_IT_WILL_FAIL("
@pytest.mark.django_db
def test_update_field_failing(data_fixture):
# This failing field type triggers the CannotChangeFieldType error if a field is
# changed into this type.
class FailingFieldType(TextFieldType):
def get_alter_column_prepare_new_value(self, connection, from_field, to_field):
return "p_in::NOT_VALID_SQL_SO_IT_WILL_FAIL("
user = data_fixture.create_user()
table = data_fixture.create_database_table(user=user)
@@ -485,6 +497,9 @@ def test_update_field_failing(data_fixture):
handler = FieldHandler()
with patch.dict(field_type_registry.registry, {"text": FailingFieldType()}):
# Need to clear the cache again
field_type_registry.get_for_class.cache_clear()
with pytest.raises(CannotChangeFieldType):
handler.update_field(user=user, field=field, new_type_name="text")
@@ -520,6 +535,9 @@ def test_update_field_when_underlying_sql_type_doesnt_change(data_fixture):
with patch.dict(
field_type_registry.registry, {"lowercase_text": AlwaysLowercaseTextField()}
):
# Need to clear the cache again
field_type_registry.get_for_class.cache_clear()
handler.update_field(
user=user, field=existing_text_field, new_type_name="lowercase_text"
)
@@ -565,6 +583,9 @@ def test_field_which_changes_its_underlying_type_will_have_alter_sql_run(data_fi
field_type_registry.registry,
{"text": ReversingTextFieldUsingBothVarCharAndTextSqlTypes()},
):
# Need to clear the cache again
field_type_registry.get_for_class.cache_clear()
# Update to the same baserow type, but due to this fields implementation of
# get_model_field this will alter the underlying database column from type
# of varchar to text, which should make our reversing alter sql run.
@@ -606,6 +627,9 @@ def test_just_changing_a_fields_name_will_not_run_alter_sql(data_fixture):
with patch.dict(
field_type_registry.registry, {"text": AlwaysReverseOnUpdateField()}
):
# Need to clear the cache again
field_type_registry.get_for_class.cache_clear()
handler.update_field(
user=user, field=existing_text_field, new_type_name="text", name="new_name"
)
@@ -646,6 +670,9 @@ def test_when_field_type_forces_same_type_alter_fields_alter_sql_is_run(data_fix
with patch.dict(
field_type_registry.registry, {"text": SameTypeAlwaysReverseOnUpdateField()}
):
# Need to clear the cache again
field_type_registry.get_for_class.cache_clear()
handler.update_field(
user=user,
field=existing_text_field,
@@ -688,6 +715,9 @@ def test_update_field_with_type_error_on_conversion_should_null_field(data_fixtu
field_type_registry.registry,
{"throws_field": AlwaysThrowsSqlExceptionOnConversionField()},
):
# Need to clear the cache again
field_type_registry.get_for_class.cache_clear()
handler.update_field(
user=user, field=existing_text_field, new_type_name="throws_field"
)
@@ -745,6 +775,9 @@ def test_update_field_when_underlying_sql_type_doesnt_change_with_vars(data_fixt
"long_text": ReversesWhenConvertsAwayTextField(),
},
):
# Need to clear the cache again
field_type_registry.get_for_class.cache_clear()
handler.update_field(
user=user,
field=existing_field_with_old_value_prep,
@@ -801,6 +834,9 @@ def test_update_field_when_underlying_sql_type_doesnt_change_old_prep(data_fixtu
"long_text": ReversesWhenConvertsAwayTextField2(),
},
):
# Need to clear the cache again
field_type_registry.get_for_class.cache_clear()
handler.update_field(
user=user,
field=existing_field_with_old_value_prep,
@@ -50,6 +50,16 @@ from baserow.core.exceptions import PermissionDenied, UserNotInGroup
from baserow.core.trash.handler import TrashHandler
@pytest.fixture(autouse=True)
def clean_registry_cache():
"""
Ensure no patched version stays in cache.
"""
view_type_registry.get_for_class.cache_clear()
yield
@pytest.mark.django_db
def test_get_view(data_fixture):
user = data_fixture.create_user()
@@ -5,8 +5,8 @@ from django.db.models import Q, QuerySet
from django.test.utils import override_settings
import pytest
from rest_framework.exceptions import NotAuthenticated
from baserow.contrib.database.operations import ListTablesDatabaseTableOperationType
from baserow.core.exceptions import (
PermissionDenied,
UserInvalidGroupPermissionsError,
@@ -15,7 +15,15 @@ from baserow.core.exceptions import (
from baserow.core.handler import CoreHandler
from baserow.core.operations import (
ListApplicationsGroupOperationType,
ListGroupsOperationType,
UpdateGroupOperationType,
UpdateSettingsOperationType,
)
from baserow.core.permission_manager import (
BasicPermissionManagerType,
CorePermissionManagerType,
GroupMemberOnlyPermissionManagerType,
StaffOnlyPermissionManagerType,
)
from baserow.core.registries import (
ObjectScopeType,
@@ -24,11 +32,21 @@ from baserow.core.registries import (
operation_type_registry,
permission_manager_type_registry,
)
from baserow.core.types import PermissionCheck
@pytest.mark.django_db
@override_settings(PERMISSION_MANAGERS=["core", "staff", "member", "basic"])
def test_group_check_basic_permissions(data_fixture):
@override_settings(
PERMISSION_MANAGERS=[
"core",
"setting_operation",
"staff",
"member",
"token",
"basic",
]
)
def test_check_permissions(data_fixture):
user = data_fixture.create_user()
user_group = data_fixture.create_user_group(permissions="ADMIN")
user_group_2 = data_fixture.create_user_group(permissions="MEMBER")
@@ -58,7 +76,7 @@ def test_group_check_basic_permissions(data_fixture):
ListApplicationsGroupOperationType.type,
group=user_group.group,
context=user_group.group,
raise_error=False,
raise_permission_exceptions=False,
)
is False
)
@@ -91,7 +109,7 @@ def test_group_check_basic_permissions(data_fixture):
context=user_group_2.group,
)
with pytest.raises(NotAuthenticated):
with pytest.raises(PermissionDenied):
assert CoreHandler().check_permissions(
AnonymousUser(),
ListApplicationsGroupOperationType.type,
@@ -100,9 +118,10 @@ def test_group_check_basic_permissions(data_fixture):
)
basic_permission_manager = permission_manager_type_registry.get("basic")
original_check = basic_permission_manager.check_permissions
basic_permission_manager.check_permissions = lambda *args, **kwargs: None
original_check = basic_permission_manager.check_multiple_permissions
basic_permission_manager.check_multiple_permissions = lambda *args, **kwargs: {}
# should be refused by default if the basic permission manager doesn't answer.
with pytest.raises(PermissionDenied):
CoreHandler().check_permissions(
user_group.user,
@@ -111,7 +130,7 @@ def test_group_check_basic_permissions(data_fixture):
context=user_group.group,
)
basic_permission_manager.check_permissions = original_check
basic_permission_manager.check_multiple_permissions = original_check
with pytest.raises(UserInvalidGroupPermissionsError):
assert CoreHandler().check_permissions(
@@ -130,7 +149,7 @@ def test_group_check_basic_permissions(data_fixture):
allow_if_template=True,
)
with pytest.raises(NotAuthenticated):
with pytest.raises(PermissionDenied):
assert CoreHandler().check_permissions(
AnonymousUser(),
ListApplicationsGroupOperationType.type,
@@ -140,6 +159,419 @@ def test_group_check_basic_permissions(data_fixture):
)
@pytest.mark.django_db
def test_check_multiple_permissions(data_fixture):
admin = data_fixture.create_user(is_staff=True)
user_2 = data_fixture.create_user()
user_3 = data_fixture.create_user()
user_4 = data_fixture.create_user()
group = data_fixture.create_group(
user=admin,
custom_permissions=[(user_2, "MEMBER"), (user_3, "MEMBER")],
)
database = data_fixture.create_database_application(user=admin, group=group)
checks = []
result = CoreHandler().check_multiple_permissions(checks, group)
assert result == {}
checks = []
for user in [admin, user_2, user_3, user_4, AnonymousUser()]:
for type, scope in [
(UpdateSettingsOperationType.type, None),
(ListGroupsOperationType.type, group),
(UpdateGroupOperationType.type, group),
(ListApplicationsGroupOperationType.type, group),
(ListTablesDatabaseTableOperationType.type, database),
]:
checks.append(PermissionCheck(user, type, scope))
perm_manager = CorePermissionManagerType()
result = perm_manager.check_multiple_permissions(
[c for c in checks if perm_manager.actor_is_supported(c.actor)], group
)
assert [result[c] if c in result else None for c in checks] == [
None,
True,
None,
None,
None,
None,
True,
None,
None,
None,
None,
True,
None,
None,
None,
None,
True,
None,
None,
None,
None,
None,
None,
None,
None,
]
perm_manager = StaffOnlyPermissionManagerType()
result = perm_manager.check_multiple_permissions(
[c for c in checks if perm_manager.actor_is_supported(c.actor)], group
)
assert [
(result[c] if result[c] is True else False) if c in result else None
for c in checks
] == [
True,
None,
None,
None,
None,
False,
None,
None,
None,
None,
False,
None,
None,
None,
None,
False,
None,
None,
None,
None,
None,
None,
None,
None,
None,
]
perm_manager = GroupMemberOnlyPermissionManagerType()
result = perm_manager.check_multiple_permissions(
[c for c in checks if perm_manager.actor_is_supported(c.actor)], group
)
assert [
(result[c] if result[c] is True else False) if c in result else None
for c in checks
] == [
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
False,
False,
False,
False,
False,
None,
None,
None,
None,
None,
]
perm_manager = BasicPermissionManagerType()
result = perm_manager.check_multiple_permissions(
[c for c in checks if perm_manager.actor_is_supported(c.actor)], group
)
assert [
(result[c] if result[c] is True else False) if c in result else None
for c in checks
] == [
True,
True,
True,
True,
True,
True,
True,
False,
True,
True,
True,
True,
False,
True,
True,
True,
True,
False,
True,
True,
None,
None,
None,
None,
None,
]
# All together
result = CoreHandler().check_multiple_permissions(checks, group)
permission_result = [result[check] for check in checks]
assert permission_result == [
True,
True,
True,
True,
True,
False,
True,
False,
True,
True,
False,
True,
False,
True,
True,
False,
True,
False,
False,
False,
False,
False,
False,
False,
False,
]
@pytest.mark.django_db
def test_get_permissions(data_fixture):
admin = data_fixture.create_user(is_staff=True)
user_2 = data_fixture.create_user()
user_3 = data_fixture.create_user()
user_4 = data_fixture.create_user()
group = data_fixture.create_group(
user=admin,
custom_permissions=[(user_2, "ADMIN"), (user_3, "MEMBER")],
)
result = CoreHandler().get_permissions(admin)
print(result)
assert result == [
{"name": "core", "permissions": ["list_groups"]},
{
"name": "setting_operation",
"permissions": {
"staff_only_operations": [],
"always_allowed_operations": ["create_group"],
},
},
{
"name": "staff",
"permissions": {
"staff_only_operations": ["settings.update"],
"is_staff": True,
},
},
{"name": "member", "permissions": False},
]
result = CoreHandler().get_permissions(admin, group)
print(result)
assert result == [
{"name": "core", "permissions": ["list_groups"]},
{
"name": "setting_operation",
"permissions": {
"staff_only_operations": [],
"always_allowed_operations": ["create_group"],
},
},
{
"name": "staff",
"permissions": {
"staff_only_operations": ["settings.update"],
"is_staff": True,
},
},
{
"name": "basic",
"permissions": {
"admin_only_operations": [
"group.list_invitations",
"group.create_invitation",
"invitation.read",
"invitation.update",
"invitation.delete",
"group.list_group_users",
"group.update",
"group.delete",
"group_user.update",
"group_user.delete",
],
"is_admin": True,
},
},
]
result = CoreHandler().get_permissions(user_2)
assert result == [
{"name": "core", "permissions": ["list_groups"]},
{
"name": "setting_operation",
"permissions": {
"staff_only_operations": [],
"always_allowed_operations": ["create_group"],
},
},
{
"name": "staff",
"permissions": {
"staff_only_operations": ["settings.update"],
"is_staff": False,
},
},
{"name": "member", "permissions": False},
]
result = CoreHandler().get_permissions(user_2, group)
assert result == [
{"name": "core", "permissions": ["list_groups"]},
{
"name": "setting_operation",
"permissions": {
"staff_only_operations": [],
"always_allowed_operations": ["create_group"],
},
},
{
"name": "staff",
"permissions": {
"staff_only_operations": ["settings.update"],
"is_staff": False,
},
},
{
"name": "basic",
"permissions": {
"admin_only_operations": [
"group.list_invitations",
"group.create_invitation",
"invitation.read",
"invitation.update",
"invitation.delete",
"group.list_group_users",
"group.update",
"group.delete",
"group_user.update",
"group_user.delete",
],
"is_admin": True,
},
},
]
result = CoreHandler().get_permissions(user_3)
assert result == [
{"name": "core", "permissions": ["list_groups"]},
{
"name": "setting_operation",
"permissions": {
"staff_only_operations": [],
"always_allowed_operations": ["create_group"],
},
},
{
"name": "staff",
"permissions": {
"staff_only_operations": ["settings.update"],
"is_staff": False,
},
},
{"name": "member", "permissions": False},
]
result = CoreHandler().get_permissions(user_3, group)
assert result == [
{"name": "core", "permissions": ["list_groups"]},
{
"name": "setting_operation",
"permissions": {
"staff_only_operations": [],
"always_allowed_operations": ["create_group"],
},
},
{
"name": "staff",
"permissions": {
"staff_only_operations": ["settings.update"],
"is_staff": False,
},
},
{
"name": "basic",
"permissions": {
"admin_only_operations": [
"group.list_invitations",
"group.create_invitation",
"invitation.read",
"invitation.update",
"invitation.delete",
"group.list_group_users",
"group.update",
"group.delete",
"group_user.update",
"group_user.delete",
],
"is_admin": False,
},
},
]
result = CoreHandler().get_permissions(user_4, group)
assert result == [
{"name": "core", "permissions": ["list_groups"]},
{
"name": "setting_operation",
"permissions": {
"staff_only_operations": [],
"always_allowed_operations": ["create_group"],
},
},
{
"name": "staff",
"permissions": {
"staff_only_operations": ["settings.update"],
"is_staff": False,
},
},
{"name": "member", "permissions": False},
]
@pytest.mark.django_db
def test_all_operations_are_registered():
def get_all_subclasses(cls):
@@ -228,6 +660,7 @@ def test_all_scope_types_query_methods():
if scope_type.type == "core":
continue
assert isinstance(scope_type.get_base_queryset(), QuerySet)
assert isinstance(scope_type.get_enhanced_queryset(), QuerySet)
for parent in scope_type.get_parent_scopes():
@@ -1273,14 +1273,14 @@ def test_raise_if_user_is_last_admin_of_group(data_fixture):
@pytest.mark.django_db
def test_get_user_ids_of_permitted_users(data_fixture):
def test_check_permission_for_multiple_actors(data_fixture):
user = data_fixture.create_user()
user_of_another_group = data_fixture.create_user()
group = data_fixture.create_group(user=user)
assert CoreHandler().get_user_ids_of_permitted_users(
assert CoreHandler().check_permission_for_multiple_actors(
[user, user_of_another_group], ReadGroupOperationType.type, group, context=group
) == {user.id}
) == [user]
@pytest.mark.django_db
@@ -3,10 +3,8 @@ from datetime import datetime
import pytest
from freezegun import freeze_time
from pytz import timezone
from rest_framework.exceptions import NotAuthenticated
from baserow.contrib.database.models import Database
from baserow.core.exceptions import UserInvalidGroupPermissionsError, UserNotInGroup
from baserow.core.models import Group, GroupUser
@@ -40,48 +38,6 @@ def test_group_user_get_next_order(data_fixture):
assert GroupUser.get_last_order(group_user_2_1.user) == 12
@pytest.mark.django_db
def test_group_has_user(data_fixture):
user = data_fixture.create_user()
user_group = data_fixture.create_user_group(permissions="ADMIN")
user_group_2 = data_fixture.create_user_group(permissions="MEMBER")
user_group_3 = data_fixture.create_user_group()
data_fixture.create_template(group=user_group_3.group)
assert user_group.group.has_user(user_group.user)
assert not user_group.group.has_user(user)
assert not user_group.group.has_user(user, "ADMIN")
assert not user_group.group.has_user(user, ["ADMIN", "MEMBER"])
assert not user_group.group.has_user(user_group.user, "MEMBER")
assert user_group.group.has_user(user_group.user, "ADMIN")
assert user_group.group.has_user(user_group.user, ["ADMIN", "MEMBER"])
user_group.group.has_user(user_group.user, raise_error=True)
with pytest.raises(UserNotInGroup):
user_group.group.has_user(user, raise_error=True)
with pytest.raises(UserNotInGroup):
user_group.group.has_user(user, "ADMIN", raise_error=True)
with pytest.raises(UserInvalidGroupPermissionsError):
user_group_2.group.has_user(user_group_2.user, "ADMIN", raise_error=True)
user_group.group.has_user(user_group.user, "ADMIN", raise_error=True)
user_group_2.group.has_user(user_group_2.user, "MEMBER", raise_error=True)
assert user_group_3.group.has_user(None) is False
assert user_group_2.group.has_user(None, allow_if_template=True) is False
assert user_group_3.group.has_user(None, allow_if_template=True) is True
with pytest.raises(NotAuthenticated):
user_group_3.group.has_user(None, raise_error=True)
with pytest.raises(NotAuthenticated):
user_group_2.group.has_user(None, raise_error=True, allow_if_template=True)
@pytest.mark.django_db
def test_application_content_type_init(data_fixture):
group = data_fixture.create_group()
@@ -1,5 +1,6 @@
import pytest
from baserow.core.exceptions import PermissionException
from baserow.core.operations import CreateGroupOperationType
from baserow.core.permission_manager import (
StaffOnlySettingOperationPermissionManagerType,
@@ -44,7 +45,9 @@ def test_staff_setting_permission_manager_non_staff_with_allow_global_group_crea
perm_manager = StaffOnlySettingOperationPermissionManagerType()
user = data_fixture.create_user(is_staff=False)
data_fixture.update_settings(allow_global_group_creation=False)
assert not perm_manager.check_permissions(user, CreateGroupOperationType.type)
with pytest.raises(PermissionException):
perm_manager.check_permissions(user, CreateGroupOperationType.type)
assert perm_manager.get_permissions_object(user) == {
"staff_only_operations": [CreateGroupOperationType.type],
"always_allowed_operations": [],
@@ -1,3 +1,5 @@
from typing import NamedTuple
import pytest
from baserow.core.subjects import UserSubjectType
@@ -11,14 +13,30 @@ def test_user_subject_type_is_in_group(data_fixture):
inactive_user = data_fixture.create_user(group=group, is_active=False)
to_be_deleted_user = data_fixture.create_user(group=group, to_be_deleted=True)
assert UserSubjectType().is_in_group(user_not_in_group.id, group) is False
assert UserSubjectType().is_in_group(user_in_group.id, group) is True
assert UserSubjectType().is_in_group(9999, group) is False
assert UserSubjectType().is_in_group(inactive_user.id, group) is False
assert UserSubjectType().is_in_group(to_be_deleted_user.id, group) is False
class FakeUser(NamedTuple):
id: int
fake_user = FakeUser(9999999)
assert UserSubjectType().is_in_group(user_not_in_group, group) is False
assert UserSubjectType().is_in_group(user_in_group, group) is True
assert UserSubjectType().is_in_group(fake_user, group) is False
assert UserSubjectType().is_in_group(inactive_user, group) is False
assert UserSubjectType().is_in_group(to_be_deleted_user, group) is False
assert UserSubjectType().are_in_group(
[
user_not_in_group,
user_in_group,
fake_user,
inactive_user,
to_be_deleted_user,
],
group,
) == [False, True, False, False, False]
@pytest.mark.django_db
def test_user_subject_get_associated_users(data_fixture):
def test_user_subject_get_users_included_in_subject(data_fixture):
user = data_fixture.create_user()
assert UserSubjectType().get_associated_users(user) == [user]
assert UserSubjectType().get_users_included_in_subject(user) == [user]
@@ -1,4 +1,3 @@
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.utils.functional import lazy
@@ -12,20 +11,6 @@ from baserow.core.registries import object_scope_type_registry, subject_type_reg
from baserow_enterprise.exceptions import RoleNotExist, ScopeNotExist, SubjectNotExist
from baserow_enterprise.models import Role, RoleAssignment, Team
User = get_user_model()
class SubjectUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "username", "first_name", "email"]
extra_kwargs = {
"id": {"read_only": True},
"username": {"read_only": True},
"first_name": {"read_only": True},
"email": {"read_only": True},
}
class SubjectTeamSerializer(serializers.ModelSerializer):
subject_count = serializers.SerializerMethodField(
@@ -1,4 +1,3 @@
import uuid
from typing import Any, Dict
from urllib.request import Request
@@ -18,7 +17,6 @@ from baserow.api.decorators import (
)
from baserow.api.errors import ERROR_GROUP_DOES_NOT_EXIST, ERROR_USER_NOT_IN_GROUP
from baserow.api.schemas import get_error_schema
from baserow.api.sessions import set_client_undo_redo_action_group_id
from baserow.core.action.registries import action_type_registry
from baserow.core.exceptions import (
GroupDoesNotExist,
@@ -37,17 +35,20 @@ from baserow_enterprise.api.errors import (
ERROR_SCOPE_DOES_NOT_EXIST,
ERROR_SUBJECT_DOES_NOT_EXIST,
ERROR_SUBJECT_TYPE_DOES_NOT_EXIST,
ERROR_SUBJECT_TYPE_UNSUPPORTED,
)
from baserow_enterprise.exceptions import (
RoleNotExist,
ScopeNotExist,
SubjectNotExist,
SubjectTypeNotExist,
SubjectUnsupported,
)
from baserow_enterprise.features import RBAC
from baserow_enterprise.role.actions import AssignRoleActionType
from baserow_enterprise.role.actions import BatchAssignRoleActionType
from baserow_enterprise.role.constants import ROLE_ASSIGNABLE_OBJECT_MAP
from baserow_enterprise.role.handler import RoleAssignmentHandler
from baserow_enterprise.role.types import NewRoleAssignment
from .exceptions import DuplicateRoleAssignments
from .serializers import (
@@ -109,6 +110,7 @@ class RoleAssignmentsView(APIView):
ObjectScopeTypeDoesNotExist: ERROR_OBJECT_SCOPE_TYPE_DOES_NOT_EXIST,
SubjectTypeNotExist: ERROR_SUBJECT_TYPE_DOES_NOT_EXIST,
SubjectNotExist: ERROR_SUBJECT_DOES_NOT_EXIST,
SubjectUnsupported: ERROR_SUBJECT_TYPE_UNSUPPORTED,
ScopeNotExist: ERROR_SCOPE_DOES_NOT_EXIST,
RoleNotExist: ERROR_ROLE_DOES_NOT_EXIST,
LastAdminOfGroup: ERROR_LAST_ADMIN_OF_GROUP,
@@ -122,37 +124,31 @@ class RoleAssignmentsView(APIView):
group_id: int,
data,
) -> Response:
"""Assign or remove a role to the user."""
"""Assign or remove a role to the user on the given scope."""
group = CoreHandler().get_group(group_id)
role = data.get("role", None)
scope = data.get("scope", None)
subject = data.get("subject", None)
scope = data.get("scope", None)
if role is not None:
# We set the role
role_assignment = action_type_registry.get_by_type(AssignRoleActionType).do(
request.user,
subject,
group,
role,
scope=scope,
)
new_role_assignments = [NewRoleAssignment(subject, role, scope)]
roles_assignments = action_type_registry.get_by_type(
BatchAssignRoleActionType
).do(
request.user,
new_role_assignments,
group,
)
role_assignment = roles_assignments[0]
if role_assignment:
serializer = RoleAssignmentSerializer(role_assignment)
return Response(serializer.data)
else:
# We remove the role
action_type_registry.get_by_type(AssignRoleActionType).do(
request.user,
data["subject"],
group,
role=None,
scope=data["scope"],
)
return Response(status=204)
return Response(status=204)
@extend_schema(
parameters=[
@@ -256,8 +252,8 @@ class BatchRoleAssignmentsView(APIView):
operation_id="batch_assign_role",
description=(
"You can assign a role to a multiple subjects into the given group for "
"the given scope with this endpoint. If you want to remove the role you can"
"omit the role property."
"the given scopes with this endpoint. If you want to remove the role you "
"can omit the role property."
),
request=BatchCreateRoleAssignmentSerializer,
responses={
@@ -288,6 +284,7 @@ class BatchRoleAssignmentsView(APIView):
ObjectScopeTypeDoesNotExist: ERROR_OBJECT_SCOPE_TYPE_DOES_NOT_EXIST,
SubjectTypeNotExist: ERROR_SUBJECT_TYPE_DOES_NOT_EXIST,
SubjectNotExist: ERROR_SUBJECT_DOES_NOT_EXIST,
SubjectUnsupported: ERROR_SUBJECT_TYPE_UNSUPPORTED,
ScopeNotExist: ERROR_SCOPE_DOES_NOT_EXIST,
RoleNotExist: ERROR_ROLE_DOES_NOT_EXIST,
DuplicateRoleAssignments: ERROR_DUPLICATE_ROLE_ASSIGNMENTS,
@@ -303,7 +300,10 @@ class BatchRoleAssignmentsView(APIView):
group_id: int,
data,
) -> Response:
"""Assign or remove a role to the user."""
"""
Assigns or removes a role to multiple subjects on multiple scope at the same
time.
"""
data = data.get("items", [])
user = request.user
@@ -316,19 +316,20 @@ class BatchRoleAssignmentsView(APIView):
indexes = [data.index(duplicate) for duplicate in duplicates]
raise DuplicateRoleAssignments(indexes)
LicenseHandler.raise_if_user_doesnt_have_feature(RBAC, request.user, group)
set_client_undo_redo_action_group_id(user, uuid.uuid4())
role_assignments = [
action_type_registry.get_by_type(AssignRoleActionType).do(
user,
role_assignment["subject"],
group,
role_assignment["role"],
scope=role_assignment["scope"],
)
for role_assignment in data
new_role_assignments = [
NewRoleAssignment(elt["subject"], elt["role"], elt["scope"]) for elt in data
]
return Response(RoleAssignmentSerializer(role_assignments, many=True).data)
role_assignments = action_type_registry.get_by_type(
BatchAssignRoleActionType
).do(
user,
new_role_assignments,
group,
)
response = [
RoleAssignmentSerializer(ra).data if ra else None for ra in role_assignments
]
return Response(response)
@@ -27,7 +27,7 @@ class BaserowEnterpriseConfig(AppConfig):
from baserow_enterprise.api.member_data_types import (
EnterpriseMemberTeamsDataType,
)
from baserow_enterprise.role.actions import AssignRoleActionType
from baserow_enterprise.role.actions import BatchAssignRoleActionType
from baserow_enterprise.scopes import TeamsActionScopeType
from baserow_enterprise.teams.actions import (
CreateTeamActionType,
@@ -73,7 +73,7 @@ class BaserowEnterpriseConfig(AppConfig):
action_type_registry.register(DeleteTeamActionType())
action_type_registry.register(CreateTeamSubjectActionType())
action_type_registry.register(DeleteTeamSubjectActionType())
action_type_registry.register(AssignRoleActionType())
action_type_registry.register(BatchAssignRoleActionType())
trash_item_type_registry.register(TeamTrashableItemType())
@@ -23,12 +23,16 @@ class SubjectTypeNotExist(Exception):
class SubjectNotExist(Exception):
"""Raised when trying to retrieve a subject that does not exist"""
"""Raised when trying to retrieve a subject that does not exist."""
class SubjectUnsupported(Exception):
"""Raised when trying to use an unsupported subject type."""
class ScopeNotExist(Exception):
"""Raised when trying to retrieve a scope that does not exist"""
"""Raised when trying to retrieve a scope that does not exist."""
class RoleNotExist(Exception):
"""Raised when trying to retrieve a role that does not exist"""
"""Raised when trying to retrieve a role that does not exist."""
@@ -0,0 +1,129 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-26 15:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=4; plural=(n == 1 && n % 1 == 0) ? 0 : (n >= 2 && n "
"<= 4 && n % 1 == 0) ? 1: (n % 1 != 0 ) ? 2 : 3;\n"
#: audit_log/job_types.py:143
msgid "User Email"
msgstr ""
#: audit_log/job_types.py:144
msgid "User ID"
msgstr ""
#: audit_log/job_types.py:145
msgid "Group Name"
msgstr ""
#: audit_log/job_types.py:146
msgid "Group ID"
msgstr ""
#: audit_log/job_types.py:147
msgid "Action Type"
msgstr ""
#: audit_log/job_types.py:148
msgid "Description"
msgstr ""
#: audit_log/job_types.py:149
msgid "Timestamp"
msgstr ""
#: audit_log/job_types.py:150
msgid "IP Address"
msgstr ""
#: audit_log/models.py:30
msgid "DONE"
msgstr ""
#: audit_log/models.py:31
msgid "UNDONE"
msgstr ""
#: audit_log/models.py:32
msgid "REDONE"
msgstr ""
#: role/actions.py:28
msgid "Assign multiple roles"
msgstr ""
#: role/actions.py:29
msgid "Multiple roles have been assigned"
msgstr ""
#: role/actions.py:32
#, python-format
msgid ""
"Role %(role_uid)s assigned to subject type \"%(subject_type_name)s"
"\" (%(subject_id)s) on scope type \"%(scope_type_name)s\" (%(scope_id)s)."
msgstr ""
#: teams/actions.py:21
#, python-format
msgid "in team \"%(team_name)s\" (%(team_id)s) "
msgstr ""
#: teams/actions.py:27
msgid "Create team"
msgstr ""
#: teams/actions.py:28
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) created."
msgstr ""
#: teams/actions.py:101
msgid "Update team"
msgstr ""
#: teams/actions.py:102
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) updated."
msgstr ""
#: teams/actions.py:193
msgid "Delete team"
msgstr ""
#: teams/actions.py:194
#, python-format
msgid "Team \"%(team_name)s\" (%(team_id)s) deleted."
msgstr ""
#: teams/actions.py:240
msgid "Create team subject"
msgstr ""
#: teams/actions.py:240
#, python-format
msgid "Subject (%(subject_id)s) created"
msgstr ""
#: teams/actions.py:320
msgid "Delete team subject"
msgstr ""
#: teams/actions.py:321
#, python-format
msgid "Subject (%(subject_id)s) deleted"
msgstr ""
@@ -0,0 +1,128 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-26 15:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: audit_log/job_types.py:143
msgid "User Email"
msgstr ""
#: audit_log/job_types.py:144
msgid "User ID"
msgstr ""
#: audit_log/job_types.py:145
msgid "Group Name"
msgstr ""
#: audit_log/job_types.py:146
msgid "Group ID"
msgstr ""
#: audit_log/job_types.py:147
msgid "Action Type"
msgstr ""
#: audit_log/job_types.py:148
msgid "Description"
msgstr ""
#: audit_log/job_types.py:149
msgid "Timestamp"
msgstr ""
#: audit_log/job_types.py:150
msgid "IP Address"
msgstr ""
#: audit_log/models.py:30
msgid "DONE"
msgstr ""
#: audit_log/models.py:31
msgid "UNDONE"
msgstr ""
#: audit_log/models.py:32
msgid "REDONE"
msgstr ""
#: role/actions.py:28
msgid "Assign multiple roles"
msgstr ""
#: role/actions.py:29
msgid "Multiple roles have been assigned"
msgstr ""
#: role/actions.py:32
#, python-format
msgid ""
"Role %(role_uid)s assigned to subject type \"%(subject_type_name)s"
"\" (%(subject_id)s) on scope type \"%(scope_type_name)s\" (%(scope_id)s)."
msgstr ""
#: teams/actions.py:21
#, python-format
msgid "in team \"%(team_name)s\" (%(team_id)s) "
msgstr ""
#: teams/actions.py:27
msgid "Create team"
msgstr ""
#: teams/actions.py:28
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) created."
msgstr ""
#: teams/actions.py:101
msgid "Update team"
msgstr ""
#: teams/actions.py:102
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) updated."
msgstr ""
#: teams/actions.py:193
msgid "Delete team"
msgstr ""
#: teams/actions.py:194
#, python-format
msgid "Team \"%(team_name)s\" (%(team_id)s) deleted."
msgstr ""
#: teams/actions.py:240
msgid "Create team subject"
msgstr ""
#: teams/actions.py:240
#, python-format
msgid "Subject (%(subject_id)s) created"
msgstr ""
#: teams/actions.py:320
msgid "Delete team subject"
msgstr ""
#: teams/actions.py:321
#, python-format
msgid "Subject (%(subject_id)s) deleted"
msgstr ""
@@ -0,0 +1,128 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-26 15:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: audit_log/job_types.py:143
msgid "User Email"
msgstr ""
#: audit_log/job_types.py:144
msgid "User ID"
msgstr ""
#: audit_log/job_types.py:145
msgid "Group Name"
msgstr ""
#: audit_log/job_types.py:146
msgid "Group ID"
msgstr ""
#: audit_log/job_types.py:147
msgid "Action Type"
msgstr ""
#: audit_log/job_types.py:148
msgid "Description"
msgstr ""
#: audit_log/job_types.py:149
msgid "Timestamp"
msgstr ""
#: audit_log/job_types.py:150
msgid "IP Address"
msgstr ""
#: audit_log/models.py:30
msgid "DONE"
msgstr ""
#: audit_log/models.py:31
msgid "UNDONE"
msgstr ""
#: audit_log/models.py:32
msgid "REDONE"
msgstr ""
#: role/actions.py:28
msgid "Assign multiple roles"
msgstr ""
#: role/actions.py:29
msgid "Multiple roles have been assigned"
msgstr ""
#: role/actions.py:32
#, python-format
msgid ""
"Role %(role_uid)s assigned to subject type \"%(subject_type_name)s"
"\" (%(subject_id)s) on scope type \"%(scope_type_name)s\" (%(scope_id)s)."
msgstr ""
#: teams/actions.py:21
#, python-format
msgid "in team \"%(team_name)s\" (%(team_id)s) "
msgstr ""
#: teams/actions.py:27
msgid "Create team"
msgstr ""
#: teams/actions.py:28
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) created."
msgstr ""
#: teams/actions.py:101
msgid "Update team"
msgstr ""
#: teams/actions.py:102
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) updated."
msgstr ""
#: teams/actions.py:193
msgid "Delete team"
msgstr ""
#: teams/actions.py:194
#, python-format
msgid "Team \"%(team_name)s\" (%(team_id)s) deleted."
msgstr ""
#: teams/actions.py:240
msgid "Create team subject"
msgstr ""
#: teams/actions.py:240
#, python-format
msgid "Subject (%(subject_id)s) created"
msgstr ""
#: teams/actions.py:320
msgid "Delete team subject"
msgstr ""
#: teams/actions.py:321
#, python-format
msgid "Subject (%(subject_id)s) deleted"
msgstr ""
@@ -0,0 +1,130 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-26 15:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: audit_log/job_types.py:143
msgid "User Email"
msgstr "Email de l'utilisateur"
#: audit_log/job_types.py:144
msgid "User ID"
msgstr "Identifiant"
#: audit_log/job_types.py:145
msgid "Group Name"
msgstr "Nom du groupe"
#: audit_log/job_types.py:146
msgid "Group ID"
msgstr "Identifiant"
#: audit_log/job_types.py:147
msgid "Action Type"
msgstr "Type d'action"
#: audit_log/job_types.py:148
msgid "Description"
msgstr "Description"
#: audit_log/job_types.py:149
msgid "Timestamp"
msgstr "Heure"
#: audit_log/job_types.py:150
msgid "IP Address"
msgstr "Addresse IP"
#: audit_log/models.py:30
msgid "DONE"
msgstr "Fait"
#: audit_log/models.py:31
msgid "UNDONE"
msgstr "Annulée"
#: audit_log/models.py:32
msgid "REDONE"
msgstr "Fait"
#: role/actions.py:28
msgid "Assign multiple roles"
msgstr "Assignation de roles"
#: role/actions.py:29
msgid "Multiple roles have been assigned"
msgstr "Plusieurs rôles assignés"
#: role/actions.py:32
#, python-format
msgid ""
"Role %(role_uid)s assigned to subject type \"%(subject_type_name)s"
"\" (%(subject_id)s) on scope type \"%(scope_type_name)s\" (%(scope_id)s)."
msgstr ""
"Role %(role_uid)s assigné au sujet de type « %(subject_type_name)s » "
"(%(subject_id)s) sur l'objet de type « %(scope_type_name)s » (%(scope_id)s)."
#: teams/actions.py:21
#, python-format
msgid "in team \"%(team_name)s\" (%(team_id)s) "
msgstr "dans l'équipe \"%(team_name)s\" (%(team_id)s)"
#: teams/actions.py:27
msgid "Create team"
msgstr "Création d'un équipe"
#: teams/actions.py:28
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) created."
msgstr "Équipe \"%(name)s\" (%(team_id)s) créée."
#: teams/actions.py:101
msgid "Update team"
msgstr "Mise à jour d'une équipe"
#: teams/actions.py:102
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) updated."
msgstr "Équipe \"%(name)s\" (%(team_id)s) mise à jour."
#: teams/actions.py:193
msgid "Delete team"
msgstr "Suppression d'une équipe"
#: teams/actions.py:194
#, python-format
msgid "Team \"%(team_name)s\" (%(team_id)s) deleted."
msgstr "Équipe \"%(team_name)s\" (%(team_id)s) supprimée."
#: teams/actions.py:240
msgid "Create team subject"
msgstr "Création d'une équipe"
#: teams/actions.py:240
#, python-format
msgid "Subject (%(subject_id)s) created"
msgstr "Sujet (%(subject_id)s) créé"
#: teams/actions.py:320
msgid "Delete team subject"
msgstr "Suppression du sujet d'une équipe"
#: teams/actions.py:321
#, python-format
msgid "Subject (%(subject_id)s) deleted"
msgstr "Sujet (%(subject_id)s) supprimé"
@@ -0,0 +1,128 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-26 15:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: audit_log/job_types.py:143
msgid "User Email"
msgstr ""
#: audit_log/job_types.py:144
msgid "User ID"
msgstr ""
#: audit_log/job_types.py:145
msgid "Group Name"
msgstr ""
#: audit_log/job_types.py:146
msgid "Group ID"
msgstr ""
#: audit_log/job_types.py:147
msgid "Action Type"
msgstr ""
#: audit_log/job_types.py:148
msgid "Description"
msgstr ""
#: audit_log/job_types.py:149
msgid "Timestamp"
msgstr ""
#: audit_log/job_types.py:150
msgid "IP Address"
msgstr ""
#: audit_log/models.py:30
msgid "DONE"
msgstr ""
#: audit_log/models.py:31
msgid "UNDONE"
msgstr ""
#: audit_log/models.py:32
msgid "REDONE"
msgstr ""
#: role/actions.py:28
msgid "Assign multiple roles"
msgstr ""
#: role/actions.py:29
msgid "Multiple roles have been assigned"
msgstr ""
#: role/actions.py:32
#, python-format
msgid ""
"Role %(role_uid)s assigned to subject type \"%(subject_type_name)s"
"\" (%(subject_id)s) on scope type \"%(scope_type_name)s\" (%(scope_id)s)."
msgstr ""
#: teams/actions.py:21
#, python-format
msgid "in team \"%(team_name)s\" (%(team_id)s) "
msgstr ""
#: teams/actions.py:27
msgid "Create team"
msgstr ""
#: teams/actions.py:28
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) created."
msgstr ""
#: teams/actions.py:101
msgid "Update team"
msgstr ""
#: teams/actions.py:102
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) updated."
msgstr ""
#: teams/actions.py:193
msgid "Delete team"
msgstr ""
#: teams/actions.py:194
#, python-format
msgid "Team \"%(team_name)s\" (%(team_id)s) deleted."
msgstr ""
#: teams/actions.py:240
msgid "Create team subject"
msgstr ""
#: teams/actions.py:240
#, python-format
msgid "Subject (%(subject_id)s) created"
msgstr ""
#: teams/actions.py:320
msgid "Delete team subject"
msgstr ""
#: teams/actions.py:321
#, python-format
msgid "Subject (%(subject_id)s) deleted"
msgstr ""
@@ -0,0 +1,128 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-26 15:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: audit_log/job_types.py:143
msgid "User Email"
msgstr ""
#: audit_log/job_types.py:144
msgid "User ID"
msgstr ""
#: audit_log/job_types.py:145
msgid "Group Name"
msgstr ""
#: audit_log/job_types.py:146
msgid "Group ID"
msgstr ""
#: audit_log/job_types.py:147
msgid "Action Type"
msgstr ""
#: audit_log/job_types.py:148
msgid "Description"
msgstr ""
#: audit_log/job_types.py:149
msgid "Timestamp"
msgstr ""
#: audit_log/job_types.py:150
msgid "IP Address"
msgstr ""
#: audit_log/models.py:30
msgid "DONE"
msgstr ""
#: audit_log/models.py:31
msgid "UNDONE"
msgstr ""
#: audit_log/models.py:32
msgid "REDONE"
msgstr ""
#: role/actions.py:28
msgid "Assign multiple roles"
msgstr ""
#: role/actions.py:29
msgid "Multiple roles have been assigned"
msgstr ""
#: role/actions.py:32
#, python-format
msgid ""
"Role %(role_uid)s assigned to subject type \"%(subject_type_name)s"
"\" (%(subject_id)s) on scope type \"%(scope_type_name)s\" (%(scope_id)s)."
msgstr ""
#: teams/actions.py:21
#, python-format
msgid "in team \"%(team_name)s\" (%(team_id)s) "
msgstr ""
#: teams/actions.py:27
msgid "Create team"
msgstr ""
#: teams/actions.py:28
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) created."
msgstr ""
#: teams/actions.py:101
msgid "Update team"
msgstr ""
#: teams/actions.py:102
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) updated."
msgstr ""
#: teams/actions.py:193
msgid "Delete team"
msgstr ""
#: teams/actions.py:194
#, python-format
msgid "Team \"%(team_name)s\" (%(team_id)s) deleted."
msgstr ""
#: teams/actions.py:240
msgid "Create team subject"
msgstr ""
#: teams/actions.py:240
#, python-format
msgid "Subject (%(subject_id)s) created"
msgstr ""
#: teams/actions.py:320
msgid "Delete team subject"
msgstr ""
#: teams/actions.py:321
#, python-format
msgid "Subject (%(subject_id)s) deleted"
msgstr ""
@@ -0,0 +1,127 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-26 15:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: audit_log/job_types.py:143
msgid "User Email"
msgstr ""
#: audit_log/job_types.py:144
msgid "User ID"
msgstr ""
#: audit_log/job_types.py:145
msgid "Group Name"
msgstr ""
#: audit_log/job_types.py:146
msgid "Group ID"
msgstr ""
#: audit_log/job_types.py:147
msgid "Action Type"
msgstr ""
#: audit_log/job_types.py:148
msgid "Description"
msgstr ""
#: audit_log/job_types.py:149
msgid "Timestamp"
msgstr ""
#: audit_log/job_types.py:150
msgid "IP Address"
msgstr ""
#: audit_log/models.py:30
msgid "DONE"
msgstr ""
#: audit_log/models.py:31
msgid "UNDONE"
msgstr ""
#: audit_log/models.py:32
msgid "REDONE"
msgstr ""
#: role/actions.py:28
msgid "Assign multiple roles"
msgstr ""
#: role/actions.py:29
msgid "Multiple roles have been assigned"
msgstr ""
#: role/actions.py:32
#, python-format
msgid ""
"Role %(role_uid)s assigned to subject type \"%(subject_type_name)s"
"\" (%(subject_id)s) on scope type \"%(scope_type_name)s\" (%(scope_id)s)."
msgstr ""
#: teams/actions.py:21
#, python-format
msgid "in team \"%(team_name)s\" (%(team_id)s) "
msgstr ""
#: teams/actions.py:27
msgid "Create team"
msgstr ""
#: teams/actions.py:28
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) created."
msgstr ""
#: teams/actions.py:101
msgid "Update team"
msgstr ""
#: teams/actions.py:102
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) updated."
msgstr ""
#: teams/actions.py:193
msgid "Delete team"
msgstr ""
#: teams/actions.py:194
#, python-format
msgid "Team \"%(team_name)s\" (%(team_id)s) deleted."
msgstr ""
#: teams/actions.py:240
msgid "Create team subject"
msgstr ""
#: teams/actions.py:240
#, python-format
msgid "Subject (%(subject_id)s) created"
msgstr ""
#: teams/actions.py:320
msgid "Delete team subject"
msgstr ""
#: teams/actions.py:321
#, python-format
msgid "Subject (%(subject_id)s) deleted"
msgstr ""
@@ -0,0 +1,128 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-26 15:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: audit_log/job_types.py:143
msgid "User Email"
msgstr ""
#: audit_log/job_types.py:144
msgid "User ID"
msgstr ""
#: audit_log/job_types.py:145
msgid "Group Name"
msgstr ""
#: audit_log/job_types.py:146
msgid "Group ID"
msgstr ""
#: audit_log/job_types.py:147
msgid "Action Type"
msgstr ""
#: audit_log/job_types.py:148
msgid "Description"
msgstr ""
#: audit_log/job_types.py:149
msgid "Timestamp"
msgstr ""
#: audit_log/job_types.py:150
msgid "IP Address"
msgstr ""
#: audit_log/models.py:30
msgid "DONE"
msgstr ""
#: audit_log/models.py:31
msgid "UNDONE"
msgstr ""
#: audit_log/models.py:32
msgid "REDONE"
msgstr ""
#: role/actions.py:28
msgid "Assign multiple roles"
msgstr ""
#: role/actions.py:29
msgid "Multiple roles have been assigned"
msgstr ""
#: role/actions.py:32
#, python-format
msgid ""
"Role %(role_uid)s assigned to subject type \"%(subject_type_name)s"
"\" (%(subject_id)s) on scope type \"%(scope_type_name)s\" (%(scope_id)s)."
msgstr ""
#: teams/actions.py:21
#, python-format
msgid "in team \"%(team_name)s\" (%(team_id)s) "
msgstr ""
#: teams/actions.py:27
msgid "Create team"
msgstr ""
#: teams/actions.py:28
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) created."
msgstr ""
#: teams/actions.py:101
msgid "Update team"
msgstr ""
#: teams/actions.py:102
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) updated."
msgstr ""
#: teams/actions.py:193
msgid "Delete team"
msgstr ""
#: teams/actions.py:194
#, python-format
msgid "Team \"%(team_name)s\" (%(team_id)s) deleted."
msgstr ""
#: teams/actions.py:240
msgid "Create team subject"
msgstr ""
#: teams/actions.py:240
#, python-format
msgid "Subject (%(subject_id)s) created"
msgstr ""
#: teams/actions.py:320
msgid "Delete team subject"
msgstr ""
#: teams/actions.py:321
#, python-format
msgid "Subject (%(subject_id)s) deleted"
msgstr ""
@@ -0,0 +1,130 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-26 15:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=4; plural=(n==1 ? 0 : (n%10>=2 && n%10<=4) && (n"
"%100<12 || n%100>14) ? 1 : n!=1 && (n%10>=0 && n%10<=1) || (n%10>=5 && n"
"%10<=9) || (n%100>=12 && n%100<=14) ? 2 : 3);\n"
#: audit_log/job_types.py:143
msgid "User Email"
msgstr ""
#: audit_log/job_types.py:144
msgid "User ID"
msgstr ""
#: audit_log/job_types.py:145
msgid "Group Name"
msgstr ""
#: audit_log/job_types.py:146
msgid "Group ID"
msgstr ""
#: audit_log/job_types.py:147
msgid "Action Type"
msgstr ""
#: audit_log/job_types.py:148
msgid "Description"
msgstr ""
#: audit_log/job_types.py:149
msgid "Timestamp"
msgstr ""
#: audit_log/job_types.py:150
msgid "IP Address"
msgstr ""
#: audit_log/models.py:30
msgid "DONE"
msgstr ""
#: audit_log/models.py:31
msgid "UNDONE"
msgstr ""
#: audit_log/models.py:32
msgid "REDONE"
msgstr ""
#: role/actions.py:28
msgid "Assign multiple roles"
msgstr ""
#: role/actions.py:29
msgid "Multiple roles have been assigned"
msgstr ""
#: role/actions.py:32
#, python-format
msgid ""
"Role %(role_uid)s assigned to subject type \"%(subject_type_name)s"
"\" (%(subject_id)s) on scope type \"%(scope_type_name)s\" (%(scope_id)s)."
msgstr ""
#: teams/actions.py:21
#, python-format
msgid "in team \"%(team_name)s\" (%(team_id)s) "
msgstr ""
#: teams/actions.py:27
msgid "Create team"
msgstr ""
#: teams/actions.py:28
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) created."
msgstr ""
#: teams/actions.py:101
msgid "Update team"
msgstr ""
#: teams/actions.py:102
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) updated."
msgstr ""
#: teams/actions.py:193
msgid "Delete team"
msgstr ""
#: teams/actions.py:194
#, python-format
msgid "Team \"%(team_name)s\" (%(team_id)s) deleted."
msgstr ""
#: teams/actions.py:240
msgid "Create team subject"
msgstr ""
#: teams/actions.py:240
#, python-format
msgid "Subject (%(subject_id)s) created"
msgstr ""
#: teams/actions.py:320
msgid "Delete team subject"
msgstr ""
#: teams/actions.py:321
#, python-format
msgid "Subject (%(subject_id)s) deleted"
msgstr ""
@@ -0,0 +1,128 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-26 15:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: audit_log/job_types.py:143
msgid "User Email"
msgstr ""
#: audit_log/job_types.py:144
msgid "User ID"
msgstr ""
#: audit_log/job_types.py:145
msgid "Group Name"
msgstr ""
#: audit_log/job_types.py:146
msgid "Group ID"
msgstr ""
#: audit_log/job_types.py:147
msgid "Action Type"
msgstr ""
#: audit_log/job_types.py:148
msgid "Description"
msgstr ""
#: audit_log/job_types.py:149
msgid "Timestamp"
msgstr ""
#: audit_log/job_types.py:150
msgid "IP Address"
msgstr ""
#: audit_log/models.py:30
msgid "DONE"
msgstr ""
#: audit_log/models.py:31
msgid "UNDONE"
msgstr ""
#: audit_log/models.py:32
msgid "REDONE"
msgstr ""
#: role/actions.py:28
msgid "Assign multiple roles"
msgstr ""
#: role/actions.py:29
msgid "Multiple roles have been assigned"
msgstr ""
#: role/actions.py:32
#, python-format
msgid ""
"Role %(role_uid)s assigned to subject type \"%(subject_type_name)s"
"\" (%(subject_id)s) on scope type \"%(scope_type_name)s\" (%(scope_id)s)."
msgstr ""
#: teams/actions.py:21
#, python-format
msgid "in team \"%(team_name)s\" (%(team_id)s) "
msgstr ""
#: teams/actions.py:27
msgid "Create team"
msgstr ""
#: teams/actions.py:28
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) created."
msgstr ""
#: teams/actions.py:101
msgid "Update team"
msgstr ""
#: teams/actions.py:102
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) updated."
msgstr ""
#: teams/actions.py:193
msgid "Delete team"
msgstr ""
#: teams/actions.py:194
#, python-format
msgid "Team \"%(team_name)s\" (%(team_id)s) deleted."
msgstr ""
#: teams/actions.py:240
msgid "Create team subject"
msgstr ""
#: teams/actions.py:240
#, python-format
msgid "Subject (%(subject_id)s) created"
msgstr ""
#: teams/actions.py:320
msgid "Delete team subject"
msgstr ""
#: teams/actions.py:321
#, python-format
msgid "Subject (%(subject_id)s) deleted"
msgstr ""
@@ -0,0 +1,130 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-26 15:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
"%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n"
"%100>=11 && n%100<=14)? 2 : 3);\n"
#: audit_log/job_types.py:143
msgid "User Email"
msgstr ""
#: audit_log/job_types.py:144
msgid "User ID"
msgstr ""
#: audit_log/job_types.py:145
msgid "Group Name"
msgstr ""
#: audit_log/job_types.py:146
msgid "Group ID"
msgstr ""
#: audit_log/job_types.py:147
msgid "Action Type"
msgstr ""
#: audit_log/job_types.py:148
msgid "Description"
msgstr ""
#: audit_log/job_types.py:149
msgid "Timestamp"
msgstr ""
#: audit_log/job_types.py:150
msgid "IP Address"
msgstr ""
#: audit_log/models.py:30
msgid "DONE"
msgstr ""
#: audit_log/models.py:31
msgid "UNDONE"
msgstr ""
#: audit_log/models.py:32
msgid "REDONE"
msgstr ""
#: role/actions.py:28
msgid "Assign multiple roles"
msgstr ""
#: role/actions.py:29
msgid "Multiple roles have been assigned"
msgstr ""
#: role/actions.py:32
#, python-format
msgid ""
"Role %(role_uid)s assigned to subject type \"%(subject_type_name)s"
"\" (%(subject_id)s) on scope type \"%(scope_type_name)s\" (%(scope_id)s)."
msgstr ""
#: teams/actions.py:21
#, python-format
msgid "in team \"%(team_name)s\" (%(team_id)s) "
msgstr ""
#: teams/actions.py:27
msgid "Create team"
msgstr ""
#: teams/actions.py:28
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) created."
msgstr ""
#: teams/actions.py:101
msgid "Update team"
msgstr ""
#: teams/actions.py:102
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) updated."
msgstr ""
#: teams/actions.py:193
msgid "Delete team"
msgstr ""
#: teams/actions.py:194
#, python-format
msgid "Team \"%(team_name)s\" (%(team_id)s) deleted."
msgstr ""
#: teams/actions.py:240
msgid "Create team subject"
msgstr ""
#: teams/actions.py:240
#, python-format
msgid "Subject (%(subject_id)s) created"
msgstr ""
#: teams/actions.py:320
msgid "Delete team subject"
msgstr ""
#: teams/actions.py:321
#, python-format
msgid "Subject (%(subject_id)s) deleted"
msgstr ""
@@ -0,0 +1,127 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-26 15:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: audit_log/job_types.py:143
msgid "User Email"
msgstr ""
#: audit_log/job_types.py:144
msgid "User ID"
msgstr ""
#: audit_log/job_types.py:145
msgid "Group Name"
msgstr ""
#: audit_log/job_types.py:146
msgid "Group ID"
msgstr ""
#: audit_log/job_types.py:147
msgid "Action Type"
msgstr ""
#: audit_log/job_types.py:148
msgid "Description"
msgstr ""
#: audit_log/job_types.py:149
msgid "Timestamp"
msgstr ""
#: audit_log/job_types.py:150
msgid "IP Address"
msgstr ""
#: audit_log/models.py:30
msgid "DONE"
msgstr ""
#: audit_log/models.py:31
msgid "UNDONE"
msgstr ""
#: audit_log/models.py:32
msgid "REDONE"
msgstr ""
#: role/actions.py:28
msgid "Assign multiple roles"
msgstr ""
#: role/actions.py:29
msgid "Multiple roles have been assigned"
msgstr ""
#: role/actions.py:32
#, python-format
msgid ""
"Role %(role_uid)s assigned to subject type \"%(subject_type_name)s"
"\" (%(subject_id)s) on scope type \"%(scope_type_name)s\" (%(scope_id)s)."
msgstr ""
#: teams/actions.py:21
#, python-format
msgid "in team \"%(team_name)s\" (%(team_id)s) "
msgstr ""
#: teams/actions.py:27
msgid "Create team"
msgstr ""
#: teams/actions.py:28
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) created."
msgstr ""
#: teams/actions.py:101
msgid "Update team"
msgstr ""
#: teams/actions.py:102
#, python-format
msgid "Team \"%(name)s\" (%(team_id)s) updated."
msgstr ""
#: teams/actions.py:193
msgid "Delete team"
msgstr ""
#: teams/actions.py:194
#, python-format
msgid "Team \"%(team_name)s\" (%(team_id)s) deleted."
msgstr ""
#: teams/actions.py:240
msgid "Create team subject"
msgstr ""
#: teams/actions.py:240
#, python-format
msgid "Subject (%(subject_id)s) created"
msgstr ""
#: teams/actions.py:320
msgid "Delete team subject"
msgstr ""
#: teams/actions.py:321
#, python-format
msgid "Subject (%(subject_id)s) deleted"
msgstr ""
@@ -1,12 +1,11 @@
import dataclasses
from typing import Any, Optional
from collections import defaultdict
from copy import deepcopy
from typing import Any, Dict, List, Optional
from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext_lazy as _
from baserow_premium.license.handler import LicenseHandler
from baserow.contrib.database.views.models import ViewFilter
from baserow.core.action.models import Action
from baserow.core.action.registries import (
ActionScopeStr,
@@ -14,170 +13,189 @@ from baserow.core.action.registries import (
UndoableActionType,
)
from baserow.core.action.scopes import GroupActionScopeType
from baserow.core.handler import CoreHandler
from baserow.core.models import Group
from baserow.core.registries import object_scope_type_registry, subject_type_registry
from baserow_enterprise.features import RBAC
from baserow_enterprise.role.handler import RoleAssignmentHandler
from baserow_enterprise.role.models import Role
from baserow_enterprise.role.types import NewRoleAssignment
from .constants import ROLE_ASSIGNABLE_OBJECT_MAP
from .models import RoleAssignment
from .types import AssignmentTuple
class AssignRoleActionType(UndoableActionType):
type = "assign_role"
class BatchAssignRoleActionType(UndoableActionType):
type = "batch_assign_role"
description = ActionTypeDescription(
_("Assign role"),
_(
"Role %(role_uid)s assigned to %(subject_type)s %(subject_id)s "
"on %(scope_type)s %(scope_id)s"
),
_("Assign multiple roles"),
_("Multiple roles have been assigned"),
)
long_desc_if_one_assignment = _(
'Role %(role_uid)s assigned to subject type "%(subject_type_name)s" (%(subject_id)s) '
'on scope type "%(scope_type_name)s" (%(scope_id)s).'
)
@dataclasses.dataclass
class Params:
subject_id: int
subject_type: str
group_id: int
role_uid: Optional[str]
original_role_uid: Optional[str]
scope_id: int
scope_type: str
assignments: List[AssignmentTuple]
@classmethod
def get_long_description(cls, params_dict: Dict[str, Any], *args, **kwargs) -> str:
if len(params_dict["assignments"]) == 1:
return (
cls.long_desc_if_one_assignment
% AssignmentTuple(*params_dict["assignments"][0])._asdict()
)
else:
return super().get_long_description(params_dict, *args, **kwargs)
@classmethod
def serialized_to_params(cls, serialized_params):
"""
Replace the assignment items by a named tuple for easier use.
"""
serialized_params_copy = deepcopy(serialized_params)
serialized_params_copy["assignments"] = [
AssignmentTuple(*at) for at in serialized_params_copy["assignments"]
]
return cls.Params(**serialized_params_copy)
@classmethod
def do(
cls,
user,
subject,
new_role_assignments: List[NewRoleAssignment],
group: Group,
role: Optional[Role] = None,
scope: Optional[Any] = None,
) -> ViewFilter:
) -> List[Optional[RoleAssignment]]:
"""
Assigns a role to a subject into a group over a given scope.
Apply the given role assignments in an undoable action.
:param subject: The subject targeted by the role.
:param group: The group in which we want to assign the role.
:param role: The role we want to assign. If the role is `None` then we remove
the current role of the subject in the group for the given scope.
:param scope: An optional scope on which the role applies. If no scope is given
the group is used as scope.
:return: The created RoleAssignment if role is not `None` else `None`.
:param user: The user who do the action.
:param new_role_assignments: A list a new role assignments. A role assignment is
a triplet of (subject, role, scope).
:return: The result role assignment object related to the new_role_assignment.
If the role has been deleted the value is None instead of a role assignment.
"""
if scope is None:
scope = group
LicenseHandler.raise_if_user_doesnt_have_feature(RBAC, user, group)
scope_type = object_scope_type_registry.get_by_model(scope)
CoreHandler().check_permissions(
user,
ROLE_ASSIGNABLE_OBJECT_MAP[scope_type.type]["UPDATE"],
group=group,
context=scope,
)
role_assignment_handler = RoleAssignmentHandler()
previous_role = role_assignment_handler.get_current_role_assignment(
subject, group, scope=scope
user_and_scope_set = {
(subject, scope) for subject, _, scope in new_role_assignments
}
# get current roles to be able to store them alongside with action
# for a later undo/redo
previous_roles = role_assignment_handler.get_current_role_assignments(
group, user_and_scope_set
)
role_assignment = role_assignment_handler.assign_role(
subject, group, role, scope=scope
role_assignments = role_assignment_handler.assign_role_batch_for_user(
user, group, new_role_assignments
)
scope_type = object_scope_type_registry.get_by_model(scope).type
subject_type = subject_type_registry.get_by_model(subject).type
# Build the list of assignment tuples we want to save in the action to be able
# to [un|re]do it later
param_assignments = []
for (subject, role, scope) in new_role_assignments:
subject_type = subject_type_registry.get_by_model(subject)
scope_type = object_scope_type_registry.get_by_model(scope)
previous_role_assignment = previous_roles[(subject, scope)]
previous_role_uid = (
previous_role_assignment.role.uid if previous_role_assignment else None
)
param_assignments.append(
AssignmentTuple(
subject_type.type,
subject.id,
previous_role_uid,
role.uid if role else None,
scope_type.type,
scope.id,
)
)
cls.register_action(
user=user,
params=cls.Params(
subject.id,
subject_type,
group.id,
role.uid if role else None,
previous_role.role.uid if previous_role else None,
scope.id,
scope_type,
),
params=cls.Params(group.id, param_assignments),
scope=cls.scope(group.id),
group=group,
)
return role_assignment
return role_assignments
@classmethod
def scope(cls, group_id: int) -> ActionScopeStr:
return GroupActionScopeType.value(group_id)
@classmethod
def undo(cls, user: AbstractUser, params: Params, action_to_undo: Action):
def undo_redo(cls, user: AbstractUser, params: Params, undo=True):
"""
Undo or redo the action depending of the undo parameter.
:param user: The user that tries to [un|re]do the action.
:param params: The params of the original action.
:param undo: True by default. If True then it's an undo action otherwise it's a
redo action.
"""
role_assignment_handler = RoleAssignmentHandler()
group = Group.objects.get(id=params.group_id)
scope_type = object_scope_type_registry.get(params.scope_type)
scope = scope_type.get_object_for_this_type(id=params.scope_id)
# Gather all scopes ids and subjects ids grouped by their type to query them
# all at once per type
scope_ids_by_type = defaultdict(set)
subject_ids_by_type = defaultdict(set)
for assignment in params.assignments:
scope_ids_by_type[assignment.scope_type_name].add(assignment.scope_id)
subject_ids_by_type[assignment.subject_type_name].add(assignment.subject_id)
LicenseHandler.raise_if_user_doesnt_have_feature(RBAC, user, group)
# Query all scopes
scope_by_type_and_id = {}
for scope_type_name, scope_ids in scope_ids_by_type.items():
for scope in object_scope_type_registry.get(
scope_type_name
).get_all_objects_for_this_type(id__in=scope_ids):
scope_by_type_and_id[(scope_type_name, scope.id)] = scope
scope_type = object_scope_type_registry.get_by_model(scope)
CoreHandler().check_permissions(
user,
ROLE_ASSIGNABLE_OBJECT_MAP[scope_type.type]["UPDATE"],
group=group,
context=scope,
)
# Query all subjects
subject_by_type_and_id = {}
for subject_type_name, subject_ids in subject_ids_by_type.items():
for subject in subject_type_registry.get(
subject_type_name
).get_all_objects_for_this_type(id__in=subject_ids):
subject_by_type_and_id[(subject_type_name, subject.id)] = subject
subject = role_assignment_handler.get_subject(
params.subject_id, params.subject_type
)
# Build new role list from the action param
roles_to_assign = []
for (
subject_type_name,
subject_id,
original_role_uid,
role_uid,
scope_type_name,
scope_id,
) in params.assignments:
role = (
role_assignment_handler.get_role_by_uid(params.original_role_uid)
if params.original_role_uid
else None
)
subject = subject_by_type_and_id[(subject_type_name, subject_id)]
role_assignment_handler.assign_role(
subject,
group,
role,
scope=scope,
)
role_uid = original_role_uid if undo else role_uid
role = (
role_assignment_handler.get_role_by_uid(role_uid) if role_uid else None
)
scope = scope_by_type_and_id[(scope_type_name, scope_id)]
roles_to_assign.append(NewRoleAssignment(subject, role, scope))
# And finally assign roles
role_assignment_handler.assign_role_batch_for_user(user, group, roles_to_assign)
@classmethod
def undo(cls, user: AbstractUser, params: Params, action_to_undo: Action):
cls.undo_redo(user, params)
@classmethod
def redo(cls, user: AbstractUser, params: Params, action_to_redo: Action):
role_assignment_handler = RoleAssignmentHandler()
group = Group.objects.get(id=params.group_id)
scope_type = object_scope_type_registry.get(params.scope_type)
scope = scope_type.get_object_for_this_type(id=params.scope_id)
LicenseHandler.raise_if_user_doesnt_have_feature(RBAC, user, group)
CoreHandler().check_permissions(
user,
ROLE_ASSIGNABLE_OBJECT_MAP[scope_type.type]["UPDATE"],
group=group,
context=scope,
)
subject = role_assignment_handler.get_subject(
params.subject_id, params.subject_type
)
role = (
role_assignment_handler.get_role_by_uid(params.role_uid)
if params.role_uid
else None
)
role_assignment_handler.assign_role(
subject,
group,
role,
scope=scope,
)
cls.undo_redo(user, params, undo=False)
@@ -21,6 +21,7 @@ EDITOR_ROLE_UID = "EDITOR"
COMMENTER_ROLE_UID = "COMMENTER"
VIEWER_ROLE_UID = "VIEWER"
NO_ACCESS_ROLE_UID = getattr(settings, "NO_ACCESS_ROLE_UID", "NO_ACCESS")
READ_ONLY_ROLE_UID = getattr(settings, "READ_ONLY_ROLE_UID", "VIEWER")
NO_ROLE_LOW_PRIORITY_ROLE_UID = getattr(
settings, "NO_ROLE_LOW_PRIORITY_UID", "NO_ROLE_LOW_PRIORITY"
)
@@ -31,6 +32,8 @@ ROLE_ASSIGNABLE_OBJECT_MAP = getattr(
"GET_ROLE_ASSIGNABLE_OBJECT_MAP",
DEFAULT_ROLE_ASSIGNABLE_OBJECT_MAP,
)
SUBJECT_PRIORITY = getattr(
settings, "SUBJECT_PRIORITY", ["auth.User", "baserow_enterprise.Team"]
ALLOWED_SUBJECT_TYPE_BY_PRIORITY = getattr(
settings,
"ALLOWED_SUBJECT_TYPE_BY_PRIORITY",
["auth.User", "baserow_enterprise.Team"],
)
@@ -1,17 +1,31 @@
from typing import Any, List, Optional, Tuple, TypedDict, Union
from collections import defaultdict
from typing import Any, Dict, List, Optional, Tuple, Union
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractUser
from django.contrib.contenttypes.models import ContentType
from django.db.models import Case, IntegerField, Q, QuerySet, Value, When
from baserow_premium.license.handler import LicenseHandler
from baserow.core.exceptions import PermissionDenied
from baserow.core.handler import CoreHandler
from baserow.core.mixins import TrashableModelMixin
from baserow.core.models import Group, GroupUser
from baserow.core.object_scopes import CoreObjectScopeType
from baserow.core.registries import object_scope_type_registry, subject_type_registry
from baserow.core.types import ScopeObject, Subject
from baserow_enterprise.exceptions import ScopeNotExist, SubjectNotExist
from baserow.core.registries import (
SubjectType,
object_scope_type_registry,
subject_type_registry,
)
from baserow.core.subjects import UserSubjectType
from baserow.core.types import PermissionCheck, ScopeObject, Subject
from baserow_enterprise.exceptions import (
ScopeNotExist,
SubjectNotExist,
SubjectUnsupported,
)
from baserow_enterprise.features import RBAC
from baserow_enterprise.models import RoleAssignment
from baserow_enterprise.role.models import Role
from baserow_enterprise.signals import (
@@ -22,25 +36,17 @@ from baserow_enterprise.signals import (
from baserow_enterprise.teams.models import Team, TeamSubject
from .constants import (
ALLOWED_SUBJECT_TYPE_BY_PRIORITY,
NO_ACCESS_ROLE_UID,
NO_ROLE_LOW_PRIORITY_ROLE_UID,
READ_ONLY_ROLE_UID,
ROLE_ASSIGNABLE_OBJECT_MAP,
SUBJECT_PRIORITY,
)
from .types import NewRoleAssignment
User = get_user_model()
class RoleAssignmentDict(TypedDict):
scope: Any
scope_id: int
scope_type: ContentType
subject: Any
subject_id: int
subject_type: ContentType
role: Role
class RoleAssignmentHandler:
def _get_role_assignments_for_valid_subjects_qs(self) -> QuerySet:
"""
@@ -118,7 +124,7 @@ class RoleAssignmentHandler:
self,
subject: Union[AbstractUser, Team],
group: Group,
scope: Optional[Any] = None,
scope: Optional[ScopeObject] = None,
) -> Union[RoleAssignment, None]:
"""
Returns the current assigned role for the given Group/Subject/Scope.
@@ -133,54 +139,131 @@ class RoleAssignmentHandler:
if scope is None:
scope = group
content_types = ContentType.objects.get_for_models(scope, subject)
key = (subject, scope)
# If we are assigning a role to a group, we store the role uid in
# the `.permissions` property of the `GroupUser` object instead to stay
# compatible with other permission manager. This make it easy to switch from
# one permission manager to another without losing nor duplicating information
if (
isinstance(scope, Group)
and scope.id == group.id
and isinstance(subject, User)
):
try:
group_user = group.get_group_user(subject)
role = self.get_role_by_uid(group_user.permissions, use_fallback=True)
return self.get_current_role_assignments(group, [key])[key]
def get_current_role_assignments(
self,
group: Group,
for_subject_scope: List[Tuple[Subject, ScopeObject]],
include_trash=False,
) -> Dict[Tuple[Subject, ScopeObject], Optional[RoleAssignment]]:
"""
Returns the current assigned role for the given Subject/Scope tuples.
:param group: The group in which you want the role assignments.
:param for_subject_scope: A list of (subject, scope) with want the role for.
:return: The current `RoleAssignment` or `None` if no role is defined for the
scope each of the given tuples.
"""
user_subject_type = subject_type_registry.get(UserSubjectType.type)
# Group all scopes and subjects to get their content_type
scope_types = set([Group])
subject_types = set()
for (subject, scope) in for_subject_scope:
scope_types.add(type(scope))
subject_types.add(type(subject))
content_types = ContentType.objects.get_for_models(
*subject_types,
*scope_types,
)
# Generate the query to get all the current role assignments for the given
# tuples
# Exception for user subject for group scope as we read the permission
# from the group_users object
subject_scope_q = Q()
user_subject_with_group_scope_by_id = dict()
for (subject, scope) in for_subject_scope:
if isinstance(subject, user_subject_type.model_class) and scope == group:
# Exception for users with group scope
user_subject_with_group_scope_by_id[subject.id] = subject
else:
subject_scope_q |= Q(
subject_type=content_types[type(subject)],
subject_id=subject.id,
scope_id=scope.id,
scope_type=content_types[type(scope)],
)
role_assignments = (
self._get_role_assignments_for_valid_subjects_qs()
.prefetch_related("role")
.filter(group=group)
.filter(subject_scope_q)
)
# Create a map to easily match the given tuples at the end
# without triggering the django query for the related content
role_assignments_by_user_id_scope_id = {
(ra.subject_type, ra.subject_id, ra.scope_type, ra.scope_id): ra
for ra in role_assignments
}
# If we are get the role of a user at a group scope level,
# we get it from the role uid in the `.permissions` property of the `GroupUser`
# object instead to remain compatible with other permission managers.
# This makes it easy to switch from one permission manager to another without
# loosing nor duplicating information
if user_subject_with_group_scope_by_id:
for user_id, permissions in (
CoreHandler()
.get_group_users(
group,
user_subject_with_group_scope_by_id.values(),
include_trash=include_trash,
)
.values_list("user_id", "permissions")
):
role = self.get_role_by_uid(permissions, use_fallback=True)
key = (
user_subject_type.get_content_type(),
user_id,
content_types[Group],
group.id,
)
subject = user_subject_with_group_scope_by_id[user_id]
# We need to fake a RoleAssignment instance here to keep the same
# return interface
return RoleAssignment(
fake_role_assignment = RoleAssignment(
subject=subject,
subject_id=subject.id,
subject_type=content_types[subject],
subject_type=content_types[type(subject)],
role=role,
group=group,
scope=scope,
scope_type=content_types[scope],
scope=group,
scope_type=content_types[Group],
)
except GroupUser.DoesNotExist:
return None
role_assignments_by_user_id_scope_id[key] = fake_role_assignment
try:
role_assignment = (
self._get_role_assignments_for_valid_subjects_qs()
.select_related("role")
.get(
scope_id=scope.id,
scope_type=content_types[scope],
group=group,
subject_id=subject.id,
subject_type=content_types[subject],
)
# Dispatch each role assignments to the (subject, scope) tuple it belongs to
# if there is one for this tuple otherwise None which means no previous
# role existed for the (subject, scope) tuple.
roles_by_user_scope = {}
for subject, scope in for_subject_scope:
key = (
content_types[type(subject)],
subject.id,
content_types[type(scope)],
scope.id,
)
return role_assignment
except RoleAssignment.DoesNotExist:
return None
if key in role_assignments_by_user_id_scope_id:
roles_by_user_scope[
(subject, scope)
] = role_assignments_by_user_id_scope_id[key]
else:
roles_by_user_scope[(subject, scope)] = None
return roles_by_user_scope
def get_roles_per_scope(
self, group: Group, actor: AbstractUser, include_trash=False
) -> List[Tuple[Any, List[Role]]]:
) -> List[Tuple[ScopeObject, List[Role]]]:
"""
Returns the RoleAssignments for the given actor in the given group. The roles
are ordered by position of the role scope in the object hierarchy: the highest
@@ -196,29 +279,61 @@ class RoleAssignmentHandler:
"""
actor_subject_type = subject_type_registry.get_by_model(actor)
return self.get_roles_per_scope_for_actors(
group, actor_subject_type, [actor], include_trash=include_trash
)[actor]
def get_roles_per_scope_for_actors(
self,
group: Group,
actor_subject_type: SubjectType,
actors: List[Subject],
include_trash=False,
) -> Dict[Subject, Tuple[ScopeObject, List[Role]]]:
"""
Returns the role assignments for for all given actors who are all of the
actor_subject_type.
:param group: The group in which we want the role assignments for.
:param actor_subject_type: The type of the actors.
:param actors: The actors we want the role per scope map.
:return: A dict with actor as keys and a list of (scope, list[role]) as value.
The roles per scope are sorted by priority: the more the scope is high in
the object hierarchy, the earlier the tuple is in the list.
"""
content_types = ContentType.objects.get_for_models(
*[s.model_class for s in subject_type_registry.get_all()], Group
actor_subject_type.model_class, Team, Group
)
actor_by_id = {a.id: a for a in actors}
subjects_q = Q(
subject_type=content_types[actor_subject_type.model_class],
subject_id=actor.id,
subject_id__in=actor_by_id.keys(),
)
# Add team roles
user_teams_qs = TeamSubject.objects.filter(
users_teams_qs = TeamSubject.objects.filter(
subject_type=content_types[actor_subject_type.model_class],
subject_id=actor.id,
subject_id__in=actor_by_id.keys(),
)
user_teams_ids = user_teams_qs.values_list("team_id", flat=True)
teams_subjects = users_teams_qs.values_list("team_id", "subject_id")
# Populate double map for later use
subjects_per_team = defaultdict(list)
teams_per_subject = defaultdict(list)
for (team_id, subject_id) in teams_subjects:
subjects_per_team[team_id].append(subject_id)
teams_per_subject[subject_id].append(team_id)
subjects_q |= Q(
subject_type=content_types[Team],
subject_id__in=user_teams_ids,
subject_id__in=subjects_per_team.keys(),
)
# Allow to order assignment by scope level
scope_cases = [
When(
scope_type=ContentType.objects.get_for_model(scope_type.model_class),
@@ -231,6 +346,7 @@ class RoleAssignmentHandler:
if scope_type.type != CoreObjectScopeType.type
]
# Allow to order assignment by subject priority
role_priority_cases = [
When(
subject_type=content_types[subject_type.model_class],
@@ -239,11 +355,12 @@ class RoleAssignmentHandler:
for order, subject_type in enumerate(
[
subject_type_registry.get(subject_name)
for subject_name in SUBJECT_PRIORITY
for subject_name in ALLOWED_SUBJECT_TYPE_BY_PRIORITY
]
)
]
# Final query
role_assignments = (
RoleAssignment.objects.filter(
group=group,
@@ -267,86 +384,133 @@ class RoleAssignmentHandler:
.select_related("subject_type")
)
group_scope_param = (group.id, content_types[Group].id)
# we are using a tuple of (scope.id, content_type.id) to prevent the query
# automatically done when accessing the property from the role assignments
# to query them all at once later
roles_by_scope = {group_scope_param: []}
priorities_by_scope = {}
group_scope_param = (content_types[Group].id, group.id)
# Track the latest role priority for each scope of each subject
priorities_by_scope_per_actor_id = defaultdict(dict)
# Keep a list of scope params to query later
scopes_to_query = defaultdict(set)
roles_by_scope = defaultdict(lambda: {group_scope_param: []})
for role_assignment in role_assignments:
scope_param = (role_assignment.scope_id, role_assignment.scope_type_id)
scope_param = (role_assignment.scope_type_id, role_assignment.scope_id)
role = self.get_role_by_id(role_assignment.role_id)
priority = role_assignment.role_priority
role_assignment_priority = role_assignment.role_priority
subject_id = role_assignment.subject_id
# We don't use defaultdict here to be sure we have the right key order
if scope_param not in roles_by_scope:
roles_by_scope[scope_param] = []
scopes_to_query[role_assignment.scope_type_id].add(role_assignment.scope_id)
existing_priority = priorities_by_scope.setdefault(scope_param, priority)
if priority < existing_priority:
roles_by_scope[scope_param] = [role]
elif existing_priority == priority:
roles_by_scope[scope_param].append(role)
# Get the group level role by reading the GroupUser permissions property for
# User actors.
if isinstance(actor, User):
# We want to get the group user even if the group is trashed as we still
# want to support checking permissions on a trashed scope (the group).
group_user = group.get_group_user(actor, include_trash=include_trash)
group_level_role = self.get_role_by_uid(
group_user.permissions,
use_fallback=True,
)
if group_level_role.uid == NO_ROLE_LOW_PRIORITY_ROLE_UID:
# Low priority role -> Use team role or NO_ACCESS if no team role
if not roles_by_scope.get(group_scope_param):
roles_by_scope[group_scope_param] = [
self.get_role_by_uid(NO_ACCESS_ROLE_UID)
]
# Is it a simple actor or a team?
# If it's a team we need to iterate over all the actor that are
# subject of the team
if role_assignment.subject_type == content_types[Team]:
actor_ids = subjects_per_team[subject_id]
else:
# Otherwise user role wins
roles_by_scope[group_scope_param] = [group_level_role]
actor_ids = [subject_id]
roles_by_scope = [
(self.get_scope(*key), value) for (key, value) in roles_by_scope.items()
]
for actor_id in actor_ids:
if not roles_by_scope[actor_id].get(scope_param, []):
# If there is no role yet for the scope of the role assignment
# We can define one from the assignment.
# We don't use defaultdict here to be sure we have the right key
# order for role_by_scope. We need to keep it ordered as expected
# by the caller.
roles_by_scope[actor_id][scope_param] = [role]
priorities_by_scope_per_actor_id[actor_id][
scope_param
] = role_assignment_priority
else:
# If the priority is the same we add the role to the
# current role list.
# Otherwise, we ignore the role as the following roles can only
# have a lower priority because of the priority ordering
current_priority = priorities_by_scope_per_actor_id[actor_id][
scope_param
]
if (
current_priority == role_assignment_priority
and role not in roles_by_scope[actor_id][scope_param]
):
roles_by_scope[actor_id][scope_param].append(role)
return roles_by_scope
# For user actor, we need to get the group level role by reading the
# GroupUser permissions property
if actor_subject_type.type == UserSubjectType.type:
# Get all group users at once
user_permissions_by_id = dict(
CoreHandler()
.get_group_users(
group, actor_by_id.values(), include_trash=include_trash
)
.values_list("user_id", "permissions")
)
for actor in actors:
group_level_role = self.get_role_by_uid(
user_permissions_by_id[actor.id], use_fallback=True
)
if group_level_role.uid == NO_ROLE_LOW_PRIORITY_ROLE_UID:
# Low priority role -> Use team role or NO_ACCESS if no team role
if not roles_by_scope[actor.id].get(group_scope_param):
roles_by_scope[actor.id][group_scope_param] = [
self.get_role_by_uid(NO_ACCESS_ROLE_UID)
]
else:
# Otherwise user role wins
roles_by_scope[actor.id][group_scope_param] = [group_level_role]
# Populate scope cache by querying all scopes type by type
scope_cache = {group_scope_param: group}
for content_type_id, content_ids in scopes_to_query.items():
for scope in self.get_scopes(content_type_id, content_ids):
scope_cache[(content_type_id, scope.id)] = scope
# Finally replace scope_params by real scope
roles_per_scope_per_user = defaultdict(list)
for actor in actors:
for (key, value) in roles_by_scope[actor.id].items():
roles_per_scope_per_user[actor].append((scope_cache[key], value))
return roles_per_scope_per_user
def get_computed_roles(
self, group: Group, actor: AbstractUser, context: Any, include_trash=False
self, roles_per_scopes, context: Any, cache: Optional[Dict] = None
) -> List[Role]:
"""
Returns the computed roles for the given actor on the given context.
:param group: The group in which we want the roles.
:param actor: The actor for whom we want the roles.
:param group: The group in which we want the roles for.
:param actor: The actor for whom we want the roles for.
:param context: The context on which we want to now the role.
:param include_trash: If true then also checks even if given group has been
trashed instead of raising a DoesNotExist exception.
:return: A list of roles that applies on this context.
"""
roles_by_scopes = self.get_roles_per_scope(
group, actor, include_trash=include_trash
)
most_precise_roles = [
RoleAssignmentHandler().get_role_by_uid(NO_ACCESS_ROLE_UID)
]
most_precise_roles = [self.get_role_by_uid(NO_ACCESS_ROLE_UID)]
for (scope, roles) in roles_by_scopes:
if object_scope_type_registry.scope_includes_context(scope, context):
cache = cache or {}
def scope_includes_context(scope, context):
key = (type(scope).__name__, scope.id, type(context).__name__, context.id)
if key not in cache:
cache[key] = object_scope_type_registry.scope_includes_context(
scope, context
)
return cache[key]
for (scope, roles) in roles_per_scopes:
if scope_includes_context(scope, context):
# Check if this scope includes the context. As the role assignments
# are sorted, the new scope is more precise than the previous one.
# So we keep this new role.
most_precise_roles = roles
elif object_scope_type_registry.scope_includes_context(
context, scope
) and any([r.uid != NO_ACCESS_ROLE_UID for r in roles]):
most_precise_roles = list(roles)
elif scope_includes_context(context, scope) and any(
[r.uid != NO_ACCESS_ROLE_UID for r in roles]
):
# Here the user has a permission on a scope that is a child of the
# context, then we grant the user permission on all read operations
# for all parents of that scope and hence this context should be
@@ -355,7 +519,7 @@ class RoleAssignmentHandler:
# and the context here is the parent database of this table the
# user should be able to read this database object so they can
# actually have access to lower down.
most_precise_roles.append(self.get_role_by_uid("VIEWER"))
most_precise_roles.append(self.get_role_by_uid(READ_ONLY_ROLE_UID))
return most_precise_roles
@@ -387,16 +551,10 @@ class RoleAssignmentHandler:
self.remove_role(subject, group, scope=scope)
return
subject_type = subject_type_registry.get_by_model(subject)
if not subject_type.is_in_group(subject.id, group):
raise SubjectNotExist()
if not object_scope_type_registry.scope_includes_context(group, scope):
raise ScopeNotExist()
content_types = ContentType.objects.get_for_models(scope, subject)
# Group level permissions are not stored as RoleAssignment records
# Group level permissions are not stored as RoleAssignment records but
# in the GroupUser.permissions property.
if RoleAssignmentHandler.is_group_level_assignment(group, scope, subject):
group_user = group.get_group_user(subject)
new_permissions = "MEMBER" if role.uid == "BUILDER" else role.uid
@@ -425,6 +583,7 @@ class RoleAssignmentHandler:
defaults={"role": role},
)
# TODO remove signaling from here
if created:
role_assignment_created.send(
self, subject=subject, group=group, scope=scope, role=role
@@ -469,19 +628,106 @@ class RoleAssignmentHandler:
).delete()
role_assignment_deleted.send(self, subject=subject, group=group, scope=scope)
def get_subject(self, subject_id: int, subject_type: str):
def assign_role_batch(
self,
group: Group,
new_role_assignments: List[NewRoleAssignment],
):
"""
Helper method that returns the actual subject object given the subject_id and
the subject type.
TODO: this function is not yet a real batch. Should be implemented properly.
:param subject_id: The subject id.
:param subject_type: The subject type.
Creates role assignments in batch, this should be used if many role assignments
are created at once, to be more efficient.
:return: The list of role assignments. Some can be None if the role assignment
has been deleted.
"""
content_type = subject_type_registry.get(subject_type).get_content_type()
return content_type.get_object_for_this_type(id=subject_id)
return [
self.assign_role(
role_assignment.subject,
group,
role=role_assignment.role,
scope=role_assignment.scope,
)
for role_assignment in new_role_assignments
]
def get_scope(self, scope_id: int, content_type_id: int) -> Any:
def assign_role_batch_for_user(
self,
user: AbstractUser,
group: Group,
new_role_assignments: List[NewRoleAssignment],
) -> List[Optional[RoleAssignment]]:
"""
Assign multiple roles to multiple users at once. This method do all the Licence
and permission checking before calling the real batch assign.
:param user: The user who assigns roles.
:param group: The group in which the role assignments take place.
:param new_role_assignments: A list of triplet (subject, role_uid, scope) for
each assignment the user wants to do.
:raise SubjectNotExist: If at least one of the subjects is not member of the
group.
:raise SubjectUnsupported: If at least one of the subjects is unsupported by
role assignments.
:raise ScopeNotExist: If at least one of the scopes is not a child of the
group.
:return: A list of the result of each assignment. Each result can be a
RoleAssignment object or None if the assignment has been removed.
"""
# First check licence
LicenseHandler.raise_if_user_doesnt_have_feature(RBAC, user, group)
# Create a dict of unique scope and subject by type to allow performants
# preliminary checks
permission_to_check = []
unique_scopes_by_type = defaultdict(set)
unique_subjects_by_type = defaultdict(set)
for subject, _, scope in new_role_assignments:
scope_type = object_scope_type_registry.get_by_model(scope)
if scope not in unique_scopes_by_type[scope_type]:
permission_to_check.append(
PermissionCheck(
user,
ROLE_ASSIGNABLE_OBJECT_MAP[scope_type.type]["UPDATE"],
context=scope,
)
)
unique_scopes_by_type[scope_type].add(scope)
subject_type = subject_type_registry.get_by_model(subject)
unique_subjects_by_type[subject_type].add(subject)
# Check if all subjects are in the group
for subject_type, subjects in unique_subjects_by_type.items():
if subject_type.type not in ALLOWED_SUBJECT_TYPE_BY_PRIORITY:
raise SubjectUnsupported(
f"The subject type {subject_type.type} is unsupported for role "
"assignments."
)
are_subjects_in_group = subject_type.are_in_group(subjects, group)
if not all(are_subjects_in_group):
raise SubjectNotExist()
# Check if all scopes are child of the group
for scope_type, scopes in unique_scopes_by_type.items():
are_scopes_in_group = scope_type.are_objects_child_of(scopes, group)
if not all(are_scopes_in_group):
raise ScopeNotExist()
# Do we have the permission to change roles for all scopes
user_permission_for_scopes = CoreHandler().check_multiple_permissions(
permission_to_check,
group=group,
)
if not all(user_permission_for_scopes.values()):
raise PermissionDenied()
return self.assign_role_batch(group, new_role_assignments)
def get_scopes(self, content_type_id, scope_ids) -> List[ScopeObject]:
"""
Helper method that returns the actual scope object given the scope ID and
the scope type.
@@ -491,32 +737,7 @@ class RoleAssignmentHandler:
"""
content_type = ContentType.objects.get_for_id(content_type_id)
return content_type.get_object_for_this_type(id=scope_id)
def assign_role_batch(
self,
user: AbstractUser,
group: Group,
new_role_assignments: List[RoleAssignmentDict],
):
"""
TODO: this function is orphaned until we have implemented it properly
Creates role assignments in batch, this should be used if many role assignments
are created at once, to be more efficient.
:return:
"""
return [
self.assign_role(
role_assignment["subject"],
group,
role=role_assignment["role"],
scope=role_assignment["scope"],
)
for role_assignment in new_role_assignments
]
return content_type.get_all_objects_for_this_type(id__in=scope_ids)
def get_role_assignments(self, group: Group, scope=None):
"""
@@ -536,8 +757,8 @@ class RoleAssignmentHandler:
role = self.get_role_by_uid(role_uid, use_fallback=True)
subject = group_user.user
# TODO we probably shouldn't do this in a loop (performance)
content_types = ContentType.objects.get_for_models(scope, subject)
# We need to fake a RoleAssignment instance here to keep the same
# return interface
role_assignments.append(
@@ -6,7 +6,6 @@ from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractUser
from baserow_premium.license.handler import LicenseHandler
from rest_framework.exceptions import NotAuthenticated
from baserow.core.exceptions import PermissionDenied
from baserow.core.models import Group
@@ -15,7 +14,10 @@ from baserow.core.registries import (
PermissionManagerType,
object_scope_type_registry,
operation_type_registry,
subject_type_registry,
)
from baserow.core.subjects import UserSubjectType
from baserow.core.types import PermissionCheck
from baserow_enterprise.features import RBAC
from baserow_enterprise.role.handler import RoleAssignmentHandler
@@ -31,6 +33,7 @@ class OperationPermissionContent(TypedDict):
class RolePermissionManagerType(PermissionManagerType):
type = "role"
supported_actor_types = [UserSubjectType.type]
def is_enabled(self, group: Group):
"""
@@ -63,42 +66,60 @@ class RolePermissionManagerType(PermissionManagerType):
for op in RoleAssignmentHandler().get_role_by_uid("VIEWER").operations.all()
)
def check_permissions(
self,
actor: AbstractUser,
operation_name: str,
group: Optional[Group] = None,
context: Optional[Any] = None,
include_trash: bool = False,
def check_multiple_permissions(
self, checks: List[PermissionCheck], group=None, include_trash=False
):
"""
Checks the permissions given the roles assigned to the actor.
Checks the permissions for each check.
"""
if group is None or not self.is_enabled(group):
return
return {}
if hasattr(actor, "is_authenticated"):
# Group actor by subject_type
actors_by_subject_type = defaultdict(set)
for actor, _, _ in checks:
s_type = subject_type_registry.get_by_model(actor)
actors_by_subject_type[s_type].add(actor)
user = actor
if not user.is_authenticated:
raise NotAuthenticated()
operation_type = operation_type_registry.get(operation_name)
computed_roles = RoleAssignmentHandler().get_computed_roles(
group, actor, context, include_trash=include_trash
result = {}
scope_includes_cache = {}
for actor_subject_type, actors in actors_by_subject_type.items():
computed_role_cache = {}
roles_per_scope_by_actor = (
RoleAssignmentHandler().get_roles_per_scope_for_actors(
group, actor_subject_type, actors, include_trash=include_trash
)
)
if any(
[
operation_type.type in self.get_role_operations(r)
for r in computed_roles
]
):
return True
for check in checks:
actor, operation_name, context = check
cache_key = (
actor.id,
f"{type(context).__name__}__{context.id}",
)
if cache_key not in computed_role_cache:
# Compute the actual role for this check
computed_role_cache[
cache_key
] = RoleAssignmentHandler().get_computed_roles(
roles_per_scope_by_actor[actor],
context,
scope_includes_cache,
)
computed_roles = computed_role_cache[cache_key]
raise PermissionDenied()
if any(
[
operation_name in self.get_role_operations(r)
for r in computed_roles
]
):
result[check] = True
else:
result[check] = PermissionDenied()
return result
def get_operation_policy(
self,
@@ -51,7 +51,7 @@ def notify_users_about_updated_permissions(
sender, subject: Subject, group: Group, **kwargs
):
subject_type = subject_type_registry.get_by_model(subject)
associated_users = subject_type.get_associated_users(subject)
associated_users = subject_type.get_users_included_in_subject(subject)
associated_user_ids = [user.id for user in associated_users]
transaction.on_commit(
@@ -0,0 +1,19 @@
from typing import NamedTuple, Optional
from baserow.core.types import ScopeObject, Subject
from baserow_enterprise.role.models import Role
class AssignmentTuple(NamedTuple):
subject_type_name: str
subject_id: int
original_role_uid: Optional[str]
role_uid: Optional[str]
scope_type_name: str
scope_id: int
class NewRoleAssignment(NamedTuple):
subject: Subject
role: Role
scope: ScopeObject
@@ -16,7 +16,7 @@ class TeamObjectScopeType(ObjectScopeType):
return context.group
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related("group")
return self.get_base_queryset().prefetch_related("group")
def get_filter_for_scope_type(self, scope_type, scopes):
@@ -37,7 +37,7 @@ class TeamSubjectObjectScopeType(ObjectScopeType):
return context.team
def get_enhanced_queryset(self):
return self.model_class.objects.prefetch_related("team", "team__group")
return self.get_base_queryset().prefetch_related("team", "team__group")
def get_filter_for_scope_type(self, scope_type, scopes):
@@ -6,6 +6,7 @@ from django.contrib.contenttypes.models import ContentType
from baserow.core.models import Group
from baserow.core.registries import SubjectType
from baserow.core.types import Subject
from baserow_enterprise.api.role.serializers import SubjectTeamSerializer
from baserow_enterprise.teams.models import Team, TeamSubject
@@ -16,21 +17,25 @@ class TeamSubjectType(SubjectType):
type = "baserow_enterprise.Team"
model_class = Team
def is_in_group(self, subject_id: int, group: Group) -> bool:
return Team.objects.filter(
id=subject_id,
group=group,
trashed=False,
).exists()
def are_in_group(self, subjects: List[Subject], group: Group) -> List[bool]:
team_ids_in_group = set(
Team.objects.filter(
id__in=[s.id for s in subjects],
group=group,
trashed=False,
).values_list("id", flat=True)
)
return [t.id in team_ids_in_group for t in subjects]
def get_serializer(self, model_instance, **kwargs):
return SubjectTeamSerializer(model_instance, **kwargs)
def get_associated_users(self, team: Team) -> List[AbstractUser]:
def get_users_included_in_subject(self, subject: Team) -> List[AbstractUser]:
return list(
User.objects.filter(
pk__in=TeamSubject.objects_and_trash.filter(
team_id=team.id,
team_id=subject.id,
subject_type=ContentType.objects.get_for_model(User),
).values_list("subject_id", flat=True)
)
@@ -3,7 +3,7 @@ from unittest.mock import patch
from django.shortcuts import reverse
from django.test.utils import override_settings
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
import pytest
from freezegun import freeze_time
@@ -284,7 +284,7 @@ def test_audit_log_entries_are_not_created_without_a_license(
@pytest.mark.django_db
@override_settings(DEBUG=True)
def test_audit_log_entries_are_created_from_actions_and_returned_in_order(
api_client, enterprise_data_fixture
api_client, enterprise_data_fixture, synced_roles
):
session_id = "session_id"
(
@@ -248,8 +248,8 @@ def test_create_role_assignment_invalid_requests(api_client, data_fixture):
**{"HTTP_AUTHORIZATION": f"JWT {token}"},
)
assert response.status_code == HTTP_400_BAD_REQUEST
assert response.json()["error"] == "ERROR_USER_NOT_IN_GROUP"
assert response.status_code == HTTP_404_NOT_FOUND
assert response.json()["error"] == "ERROR_SUBJECT_DOES_NOT_EXIST"
response = api_client.post(
reverse("api:enterprise:role:list", kwargs={"group_id": 999999}),
@@ -458,17 +458,24 @@ def test_get_role_assignments_table_level(data_fixture, api_client):
def test_batch_assign_role(data_fixture, api_client):
user, token = data_fixture.create_user_and_token()
user2 = data_fixture.create_user()
group = data_fixture.create_group(user=user, members=[user2])
user3 = data_fixture.create_user()
group = data_fixture.create_group(user=user, members=[user2, user3])
database = data_fixture.create_database_application(group=group)
table = data_fixture.create_database_table(user=user, database=database)
builder_role = Role.objects.get(uid="BUILDER")
viewer_role = Role.objects.get(uid="VIEWER")
assert len(RoleAssignment.objects.all()) == 0
url = reverse("api:enterprise:role:batch", kwargs={"group_id": group.id})
RoleAssignmentHandler().assign_role(
user3, group, viewer_role, scope=database.application_ptr
)
RoleAssignmentHandler().assign_role(user3, group, viewer_role, scope=table)
# Can add a first roleAssignment
response = api_client.post(
url,
@@ -481,6 +488,20 @@ def test_batch_assign_role(data_fixture, api_client):
"subject_type": UserSubjectType.type,
"role": builder_role.uid,
},
{
"scope_id": table.id,
"scope_type": "database_table",
"subject_id": user3.id,
"subject_type": UserSubjectType.type,
"role": None,
},
{
"scope_id": database.application_ptr.id,
"scope_type": "application",
"subject_id": user3.id,
"subject_type": UserSubjectType.type,
"role": None,
},
]
},
format="json",
@@ -513,7 +534,9 @@ def test_batch_assign_role(data_fixture, api_client):
"id": user2.id,
"username": user2.username,
},
}
},
None,
None,
]
@@ -1868,7 +1868,11 @@ def test_orphaned_paid_role_assignments_dont_get_counted(
)
subject_cts = ContentType.objects.get_for_models(
*[t.model_class for t in subject_type_registry.get_all()]
*[
t.model_class
for t in subject_type_registry.get_all()
if hasattr(t.model_class, "_meta")
]
).values()
# RA's on subjects which no longer exist
@@ -1,14 +1,13 @@
from unittest.mock import patch
import pytest
from baserow.core.action.handler import ActionHandler
from baserow.core.action.registries import action_type_registry
from baserow.core.action.scopes import GroupActionScopeType
from baserow.test_utils.helpers import assert_undo_redo_actions_are_valid
from baserow_enterprise.role.actions import AssignRoleActionType
from baserow_enterprise.audit_log.models import AuditLogEntry
from baserow_enterprise.role.actions import BatchAssignRoleActionType
from baserow_enterprise.role.handler import NewRoleAssignment, RoleAssignmentHandler
from baserow_enterprise.role.models import Role, RoleAssignment
from baserow_enterprise.role.operations import UpdateRoleTableOperationType
@pytest.fixture(autouse=True)
@@ -18,83 +17,138 @@ def enable_enterprise_and_roles_for_all_tests_here(enable_enterprise, synced_rol
@pytest.mark.django_db
@pytest.mark.undo_redo
@patch("baserow.core.handler.CoreHandler.check_permissions")
def test_can_undo_assign_role(mock_check_permissions, data_fixture):
def test_can_undo_batch_assign_role(data_fixture, enterprise_data_fixture):
session_id = "session-id"
user = data_fixture.create_user(session_id=session_id)
user2 = data_fixture.create_user()
user3 = data_fixture.create_user()
group = data_fixture.create_group(
user=user,
custom_permissions=[(user2, "VIEWER")],
members=[user2, user3],
)
database = data_fixture.create_database_application(group=group)
table = data_fixture.create_database_table(database=database, user=user)
team1 = enterprise_data_fixture.create_team(group=group, members=[])
builder_role = Role.objects.get(uid="BUILDER")
commenter_role = Role.objects.get(uid="COMMENTER")
viewer_role = Role.objects.get(uid="VIEWER")
action_type_registry.get_by_type(AssignRoleActionType).do(
user, user2, group, builder_role, scope=table
new_role_assignments = [
NewRoleAssignment(user2, commenter_role, group),
NewRoleAssignment(user2, builder_role, table),
NewRoleAssignment(user2, viewer_role, database.application_ptr),
NewRoleAssignment(user3, builder_role, group),
NewRoleAssignment(user3, viewer_role, database.application_ptr),
NewRoleAssignment(user3, builder_role, table),
NewRoleAssignment(team1, viewer_role, group),
NewRoleAssignment(team1, builder_role, table),
NewRoleAssignment(team1, builder_role, database.application_ptr),
]
action_type_registry.get_by_type(BatchAssignRoleActionType).do(
user, new_role_assignments, group
)
mock_check_permissions.assert_any_call(
user, UpdateRoleTableOperationType.type, group=group, context=table
)
assert RoleAssignment.objects.count() == 7
assert RoleAssignment.objects.count() == 1
mock_check_permissions.reset_mock()
assert AuditLogEntry.objects.count() == 1
log_entry = AuditLogEntry.objects.first()
assert log_entry.description.startswith("Multiple roles")
actions_undone = ActionHandler.undo(
user, [GroupActionScopeType.value(group_id=group.id)], session_id
)
mock_check_permissions.assert_any_call(
user, UpdateRoleTableOperationType.type, group=group, context=table
)
assert_undo_redo_actions_are_valid(actions_undone, [AssignRoleActionType])
assert_undo_redo_actions_are_valid(actions_undone, [BatchAssignRoleActionType])
assert RoleAssignment.objects.count() == 0
@pytest.mark.django_db
@pytest.mark.undo_redo
@patch("baserow.core.handler.CoreHandler.check_permissions")
def test_can_undo_redo_assign_table(mock_check_permissions, data_fixture):
def test_batch_assign_role_description_for_one_item(
data_fixture, enterprise_data_fixture
):
session_id = "session-id"
user = data_fixture.create_user(session_id=session_id)
user2 = data_fixture.create_user()
user3 = data_fixture.create_user()
group = data_fixture.create_group(
user=user,
custom_permissions=[(user2, "VIEWER")],
members=[user2, user3],
)
commenter_role = Role.objects.get(uid="COMMENTER")
new_role_assignments = [
NewRoleAssignment(user2, commenter_role, group),
]
action_type_registry.get_by_type(BatchAssignRoleActionType).do(
user, new_role_assignments, group
)
assert AuditLogEntry.objects.count() == 1
log_entry = AuditLogEntry.objects.first()
assert log_entry.description.startswith("Role ")
@pytest.mark.django_db
@pytest.mark.undo_redo
def test_can_redo_batch_assign_role(data_fixture, enterprise_data_fixture):
session_id = "session-id"
user = data_fixture.create_user(session_id=session_id)
user2 = data_fixture.create_user()
user3 = data_fixture.create_user()
group = data_fixture.create_group(
user=user,
members=[user2, user3],
)
database = data_fixture.create_database_application(group=group)
table = data_fixture.create_database_table(database=database, user=user)
builder_role = Role.objects.get(uid="BUILDER")
team1 = enterprise_data_fixture.create_team(group=group, members=[])
action_type_registry.get_by_type(AssignRoleActionType).do(
user, user2, group, builder_role, table
builder_role = Role.objects.get(uid="BUILDER")
commenter_role = Role.objects.get(uid="COMMENTER")
viewer_role = Role.objects.get(uid="VIEWER")
RoleAssignmentHandler().assign_role(
user2, group, builder_role, scope=database.application_ptr
)
RoleAssignmentHandler().assign_role(user2, group, commenter_role, scope=table)
new_role_assignments = [
NewRoleAssignment(user2, commenter_role, group),
NewRoleAssignment(user2, builder_role, table),
NewRoleAssignment(user2, viewer_role, database.application_ptr),
NewRoleAssignment(user3, builder_role, group),
NewRoleAssignment(user3, viewer_role, database.application_ptr),
NewRoleAssignment(user3, None, table),
NewRoleAssignment(team1, viewer_role, group),
NewRoleAssignment(team1, builder_role, table),
NewRoleAssignment(team1, builder_role, database.application_ptr),
]
action_type_registry.get_by_type(BatchAssignRoleActionType).do(
user, new_role_assignments, group
)
assert RoleAssignment.objects.count() == 1
assert RoleAssignment.objects.count() == 6
ActionHandler.undo(
actions_undone = ActionHandler.undo(
user, [GroupActionScopeType.value(group_id=group.id)], session_id
)
assert RoleAssignment.objects.count() == 0
mock_check_permissions.reset_mock()
assert_undo_redo_actions_are_valid(actions_undone, [BatchAssignRoleActionType])
assert RoleAssignment.objects.count() == 2
actions_redone = ActionHandler.redo(
user, [GroupActionScopeType.value(group_id=group.id)], session_id
)
assert_undo_redo_actions_are_valid(actions_redone, [AssignRoleActionType])
assert_undo_redo_actions_are_valid(actions_redone, [BatchAssignRoleActionType])
mock_check_permissions.assert_called_with(
user, UpdateRoleTableOperationType.type, group=group, context=table
)
assert RoleAssignment.objects.count() == 1
assert RoleAssignment.objects.count() == 6
@@ -1,19 +1,25 @@
from unittest.mock import patch
from django.contrib.contenttypes.models import ContentType
from django.db import IntegrityError, connection
from django.db import IntegrityError, connection, reset_queries
from django.db.models import Q
from django.test.utils import CaptureQueriesContext
import pytest
from pyinstrument import Profiler
from tqdm import tqdm
from baserow.contrib.database.object_scopes import DatabaseObjectScopeType
from baserow.core.models import GroupUser
from baserow.core.registries import subject_type_registry
from baserow.core.subjects import UserSubjectType
from baserow_enterprise.exceptions import ScopeNotExist, SubjectNotExist
from baserow_enterprise.exceptions import (
ScopeNotExist,
SubjectNotExist,
SubjectUnsupported,
)
from baserow_enterprise.role.constants import ALLOWED_SUBJECT_TYPE_BY_PRIORITY
from baserow_enterprise.role.handler import RoleAssignmentHandler
from baserow_enterprise.role.models import Role, RoleAssignment
from baserow_enterprise.role.types import NewRoleAssignment
@pytest.fixture(autouse=True)
@@ -124,6 +130,81 @@ def test_get_current_role_assignment(data_fixture):
assert role_assignment.group == group
@pytest.mark.django_db
def test_get_current_role_assignments(data_fixture, enterprise_data_fixture):
user = data_fixture.create_user(email="user@email.com")
user1 = data_fixture.create_user(email="user1@email.com")
user2 = data_fixture.create_user(email="user2@email.com")
group = data_fixture.create_group(user=user, members=[user1, user2])
database = data_fixture.create_database_application(user=user, group=group)
table = data_fixture.create_database_table(user=user, database=database)
team1 = enterprise_data_fixture.create_team(group=group, members=[user2])
admin_role = Role.objects.get(uid="ADMIN")
builder_role = Role.objects.get(uid="BUILDER")
commenter_role = Role.objects.get(uid="COMMENTER")
viewer_role = Role.objects.get(uid="VIEWER")
RoleAssignmentHandler().assign_role(user, group, role=admin_role)
RoleAssignmentHandler().assign_role(user1, group, role=builder_role)
RoleAssignmentHandler().assign_role(user2, group, role=viewer_role)
RoleAssignmentHandler().assign_role(team1, group, role=commenter_role)
RoleAssignmentHandler().assign_role(
user, group, role=viewer_role, scope=database.application_ptr
)
RoleAssignmentHandler().assign_role(
user2, group, role=admin_role, scope=database.application_ptr
)
RoleAssignmentHandler().assign_role(user, group, role=builder_role, scope=table)
RoleAssignmentHandler().assign_role(user1, group, role=admin_role, scope=table)
RoleAssignmentHandler().assign_role(team1, group, role=viewer_role, scope=table)
for_subject_scope = [
(user, group),
(user1, group),
(user2, group),
(team1, group),
(user, database.application_ptr),
(user1, database.application_ptr),
(user2, database.application_ptr),
(team1, database.application_ptr),
(user, table),
(user1, table),
(user2, table),
(team1, table),
]
role_assignments = RoleAssignmentHandler().get_current_role_assignments(
group, for_subject_scope
)
for (subject, scope), ra in role_assignments.items():
if ra:
assert ra.subject == subject
assert ra.scope == scope
role_assignment_tuples = [
(k[0], k[1], v.role.uid if v else None) for k, v in role_assignments.items()
]
assert role_assignment_tuples == [
(user, group, admin_role.uid),
(user1, group, builder_role.uid),
(user2, group, viewer_role.uid),
(team1, group, commenter_role.uid),
(user, database.application_ptr, viewer_role.uid),
(user1, database.application_ptr, None),
(user2, database.application_ptr, admin_role.uid),
(team1, database.application_ptr, None),
(user, table, builder_role.uid),
(user1, table, admin_role.uid),
(user2, table, None),
(team1, table, viewer_role.uid),
]
@pytest.mark.django_db
def test_remove_role(data_fixture):
user = data_fixture.create_user()
@@ -178,33 +259,6 @@ def test_assign_role(mock_broadcast_to_group, data_fixture):
assert role_assignment_table.role == role
@pytest.mark.django_db
def test_assign_role_unrelated_group(data_fixture):
user = data_fixture.create_user()
user_2 = data_fixture.create_user()
group = data_fixture.create_group(user=user, members=[user_2])
group_unrelated = data_fixture.create_group(user=user, members=[user_2])
database = data_fixture.create_database_application(group=group, user=user)
admin_role = Role.objects.get(uid="ADMIN")
with pytest.raises(ScopeNotExist):
RoleAssignmentHandler().assign_role(user, group_unrelated, admin_role, database)
@pytest.mark.django_db
def test_assign_role_subject_not_in_group(data_fixture):
user = data_fixture.create_user()
user_2 = data_fixture.create_user()
group = data_fixture.create_group(user=user)
database = data_fixture.create_database_application(group=group, user=user)
admin_role = Role.objects.get(uid="ADMIN")
with pytest.raises(SubjectNotExist):
RoleAssignmentHandler().assign_role(user_2, group, admin_role, database)
@pytest.mark.django_db
def test_get_role_assignments(data_fixture):
user = data_fixture.create_user()
@@ -294,23 +348,17 @@ def test_assign_role_batch_group_level(data_fixture):
user_2 = data_fixture.create_user()
group = data_fixture.create_group(user=user, members=[user_2])
user_type = ContentType.objects.get_for_model(user)
group_type = ContentType.objects.get_for_model(group)
admin_role = Role.objects.get(uid="ADMIN")
values = [
{
"subject": user_2,
"subject_id": user_2.id,
"subject_type": user_type,
"role": admin_role,
"scope": group,
"scope_id": group.id,
"scope_type": group_type,
}
NewRoleAssignment(
user_2,
admin_role,
group,
)
]
RoleAssignmentHandler().assign_role_batch(user, group, values)
RoleAssignmentHandler().assign_role_batch_for_user(user, group, values)
assert GroupUser.objects.get(user=user_2).permissions == admin_role.uid
@@ -322,23 +370,17 @@ def test_assign_role_batch_create_role_assignments(data_fixture):
group = data_fixture.create_group(user=user, members=[user_2])
database = data_fixture.create_database_application(group=group)
user_type = ContentType.objects.get_for_model(user)
database_type = ContentType.objects.get_for_model(database)
admin_role = Role.objects.get(uid="ADMIN")
values = [
{
"subject": user_2,
"subject_id": user_2.id,
"subject_type": user_type,
"role": admin_role,
"scope": database,
"scope_id": database.id,
"scope_type": database_type,
}
NewRoleAssignment(
user_2,
admin_role,
database.application_ptr,
)
]
RoleAssignmentHandler().assign_role_batch(user, group, values)
RoleAssignmentHandler().assign_role_batch_for_user(user, group, values)
role_assignments = RoleAssignment.objects.all()
@@ -357,26 +399,22 @@ def test_assign_role_batch_update_role_assignments(data_fixture):
group = data_fixture.create_group(user=user, members=[user_2])
database = data_fixture.create_database_application(group=group)
user_type = ContentType.objects.get_for_model(user)
database_type = ContentType.objects.get_for_model(database)
admin_role = Role.objects.get(uid="ADMIN")
builder_role = Role.objects.get(uid="BUILDER")
RoleAssignmentHandler().assign_role(user_2, group, admin_role, scope=database)
RoleAssignmentHandler().assign_role(
user_2, group, admin_role, scope=database.application_ptr
)
values = [
{
"subject": user_2,
"subject_id": user_2.id,
"subject_type": user_type,
"role": builder_role,
"scope": database,
"scope_id": database.id,
"scope_type": database_type,
}
NewRoleAssignment(
user_2,
builder_role,
database.application_ptr,
)
]
RoleAssignmentHandler().assign_role_batch(user, group, values)
RoleAssignmentHandler().assign_role_batch_for_user(user, group, values)
role_assignments = RoleAssignment.objects.all()
@@ -395,23 +433,17 @@ def test_assign_role_batch_delete_role_assignments(data_fixture):
group = data_fixture.create_group(user=user, members=[user_2])
database = data_fixture.create_database_application(group=group)
user_type = ContentType.objects.get_for_model(user)
database_type = ContentType.objects.get_for_model(database)
admin_role = Role.objects.get(uid="ADMIN")
values = [
{
"subject": user_2,
"subject_id": user_2.id,
"subject_type": user_type,
"role": admin_role,
"scope": database,
"scope_id": database.id,
"scope_type": database_type,
}
NewRoleAssignment(
user_2,
admin_role,
database.application_ptr,
)
]
RoleAssignmentHandler().assign_role_batch(user, group, values)
RoleAssignmentHandler().assign_role_batch_for_user(user, group, values)
role_assignments = RoleAssignment.objects.all()
@@ -420,18 +452,14 @@ def test_assign_role_batch_delete_role_assignments(data_fixture):
assert role_assignments[0].role == admin_role
values = [
{
"subject": user_2,
"subject_id": user_2.id,
"subject_type": user_type,
"role": None,
"scope": database,
"scope_id": database.id,
"scope_type": database_type,
}
NewRoleAssignment(
user_2,
None,
database.application_ptr,
)
]
RoleAssignmentHandler().assign_role_batch(user, group, values)
RoleAssignmentHandler().assign_role_batch_for_user(user, group, values)
role_assignments = RoleAssignment.objects.all()
@@ -444,41 +472,31 @@ def test_assign_role_batch_delete_group_user(data_fixture):
user_2 = data_fixture.create_user()
group = data_fixture.create_group(user=user, members=[user_2])
user_type = ContentType.objects.get_for_model(user)
group_type = ContentType.objects.get_for_model(group)
admin_role = Role.objects.get(uid="ADMIN")
no_access_role = Role.objects.get(uid="NO_ACCESS")
values = [
{
"subject": user_2,
"subject_id": user_2.id,
"subject_type": user_type,
"role": admin_role,
"scope": group,
"scope_id": group.id,
"scope_type": group_type,
}
NewRoleAssignment(
user_2,
admin_role,
group,
)
]
RoleAssignmentHandler().assign_role_batch(user, group, values)
RoleAssignmentHandler().assign_role_batch(group, values)
group_user_2 = GroupUser.objects.get(group=group, user=user_2)
assert group_user_2.permissions == admin_role.uid
values = [
{
"subject": user_2,
"subject_id": user_2.id,
"subject_type": user_type,
"role": None,
"scope": group,
"scope_id": group.id,
"scope_type": group_type,
}
NewRoleAssignment(
user_2,
None,
group,
)
]
RoleAssignmentHandler().assign_role_batch(user, group, values)
RoleAssignmentHandler().assign_role_batch_for_user(user, group, values)
group_user_2 = GroupUser.objects.get(group=group, user=user_2)
assert group_user_2.permissions == no_access_role.uid
@@ -492,24 +510,20 @@ def test_assign_role_batch_unrelated_group(data_fixture):
group_unrelated = data_fixture.create_group(user=user, members=[user_2])
database = data_fixture.create_database_application(group=group, user=user)
user_type = ContentType.objects.get_for_model(user)
database_type = ContentType.objects.get_for_model(database)
builder_role = Role.objects.get(uid="BUILDER")
values = [
{
"subject": user_2,
"subject_id": user_2.id,
"subject_type": user_type,
"role": builder_role,
"scope": database,
"scope_id": database.id,
"scope_type": database_type,
}
NewRoleAssignment(
user_2,
builder_role,
database.application_ptr,
)
]
with pytest.raises(ScopeNotExist):
RoleAssignmentHandler().assign_role_batch(user, group_unrelated, values)
RoleAssignmentHandler().assign_role_batch_for_user(
user, group_unrelated, values
)
@pytest.mark.django_db
@@ -519,24 +533,41 @@ def test_assign_role_batch_subject_not_in_group(data_fixture):
group = data_fixture.create_group(user=user)
database = data_fixture.create_database_application(group=group, user=user)
user_type = ContentType.objects.get_for_model(user)
database_type = ContentType.objects.get_for_model(database)
admin_role = Role.objects.get(uid="ADMIN")
values = [
{
"subject": user_2,
"subject_id": user_2.id,
"subject_type": user_type,
"role": admin_role,
"scope": database,
"scope_id": database.id,
"scope_type": database_type,
}
NewRoleAssignment(
user_2,
admin_role,
database.application_ptr,
)
]
with pytest.raises(SubjectNotExist):
RoleAssignmentHandler().assign_role_batch(user, group, values)
RoleAssignmentHandler().assign_role_batch_for_user(user, group, values)
for subject_type in subject_type_registry.get_all():
if subject_type.type not in ALLOWED_SUBJECT_TYPE_BY_PRIORITY:
# create a fake instance of subject type
if subject_type.type == "anonymous":
actor = subject_type.model_class()
if subject_type.type == "core.token":
actor = subject_type.model_class(group=group)
actor.save()
values = [
(
NewRoleAssignment(
actor,
admin_role,
database.application_ptr,
)
)
]
with pytest.raises(SubjectUnsupported):
RoleAssignmentHandler().assign_role_batch_for_user(user, group, values)
@pytest.mark.django_db
@@ -545,61 +576,62 @@ def test_assign_role_batch_subject_not_in_group(data_fixture):
# intellij by editing the run config for this test and adding --run-disabled-in-ci -s
# to additional args.
# pytest -k "test_assign_role_batch_performance" -s --run-disabled-in-ci
def test_assign_role_batch_performance(data_fixture):
user = data_fixture.create_user()
group = data_fixture.create_group(user=user)
def test_assign_role_batch_performance(data_fixture, profiler):
admin = data_fixture.create_user()
group = data_fixture.create_group(user=admin)
database = data_fixture.create_database_application(group=group)
admin_role = Role.objects.get(uid="ADMIN")
no_access_role = Role.objects.get(uid="NO_ACCESS")
user_type = ContentType.objects.get_for_model(user)
group_type = ContentType.objects.get_for_model(group)
database_type = ContentType.objects.get_for_model(database)
sample_size = 500
group_level_updates = []
for i in range(sample_size):
user_new = data_fixture.create_user()
GroupUser.objects.create(
group=group, user=user_new, order=0, permissions="MEMBER"
)
group_level_updates.append(
{
"subject": user_new,
"subject_id": user_new.id,
"subject_type": user_type,
"role": admin_role,
"scope": group,
"scope_id": group.id,
"scope_type": group_type,
}
for _ in tqdm(range(sample_size), desc="Users creation"):
try:
user_new = data_fixture.create_user()
except IntegrityError:
continue
else:
GroupUser.objects.create(
group=group, user=user_new, order=0, permissions="MEMBER"
)
group_level_updates.append(
NewRoleAssignment(
user_new,
admin_role,
group,
)
)
print("----------GROUP LEVEL------------")
with profiler(html_report_name="enterprise_batch_assign_group_level"):
RoleAssignmentHandler().assign_role_batch_for_user(
admin, group, group_level_updates
)
profiler = Profiler()
profiler.start()
RoleAssignmentHandler().assign_role_batch(user, group, group_level_updates)
profiler.stop()
not_initial_user_filter = Q(user__id=user.id)
not_initial_user_filter = Q(user__id=admin.id)
group_users = GroupUser.objects.filter(~not_initial_user_filter)
assert len(group_users) == sample_size
for group_user in group_users:
assert group_user.permissions == admin_role.uid
print("----------GROUP LEVEL UPDATES------------")
print(profiler.output_text(unicode=True, color=True))
group_level_deletions = []
for value in group_level_updates:
value["role"] = None
group_level_deletions.append(value)
for (user, _, scope) in group_level_updates:
group_level_deletions.append(
NewRoleAssignment(
user,
None,
scope,
)
)
profiler = Profiler()
profiler.start()
RoleAssignmentHandler().assign_role_batch(user, group, group_level_deletions)
profiler.stop()
print("----------GROUP LEVEL DELETIONS------------")
with profiler(html_report_name="enterprise_batch_assign_group_level_deletions"):
RoleAssignmentHandler().assign_role_batch_for_user(
admin, group, group_level_deletions
)
group_users = GroupUser.objects.filter(~not_initial_user_filter)
assert len(group_users) == sample_size
@@ -607,49 +639,49 @@ def test_assign_role_batch_performance(data_fixture):
for group_user in group_users:
assert group_user.permissions == no_access_role.uid
print("----------GROUP LEVEL DELETIONS------------")
print(profiler.output_text(unicode=True, color=True))
database_level_assignments = []
for value in group_level_updates:
value["role"] = admin_role
value["scope"] = database
value["scope_id"] = database.id
value["scope_type"] = database_type
database_level_assignments.append(value)
for (user, _, _) in group_level_updates:
database_level_assignments.append(
NewRoleAssignment(
user,
admin_role,
database.application_ptr,
)
)
profiler = Profiler()
profiler.start()
RoleAssignmentHandler().assign_role_batch(user, group, database_level_assignments)
profiler.stop()
print("----------Database Level Assignments------------")
with profiler(html_report_name="enterprise_batch_assign_database_level"):
RoleAssignmentHandler().assign_role_batch_for_user(
admin, group, database_level_assignments
)
role_assignments = RoleAssignment.objects.all()
assert len(role_assignments) == sample_size
for role_assignment in role_assignments:
assert role_assignment.scope == database
assert role_assignment.scope == database.application_ptr
assert role_assignment.role == admin_role
print("----------Database Level Assignments------------")
print(profiler.output_text(unicode=True, color=True))
database_level_deletions = []
for value in database_level_assignments:
value["role"] = None
database_level_deletions.append(value)
for (user, _, scope) in database_level_assignments:
database_level_deletions.append(
NewRoleAssignment(
user,
None,
scope,
)
)
profiler = Profiler()
profiler.start()
RoleAssignmentHandler().assign_role_batch(user, group, database_level_deletions)
profiler.stop()
print("----------Database Level Deletions------------")
with profiler(html_report_name="enterprise_batch_assign_database_level_deletions"):
RoleAssignmentHandler().assign_role_batch_for_user(
admin, group, database_level_deletions
)
assert RoleAssignment.objects.count() == 0
print("----------Database Level Deletions------------")
print(profiler.output_text(unicode=True, color=True))
@pytest.mark.django_db(transaction=True)
def test_get_sorted_subject_scope_roles(data_fixture, enterprise_data_fixture):
def test_get_roles_per_scope(data_fixture, enterprise_data_fixture):
user = data_fixture.create_user()
user2 = data_fixture.create_user()
group = data_fixture.create_group(user=user, members=[user2])
@@ -757,6 +789,72 @@ def test_get_sorted_subject_scope_roles(data_fixture, enterprise_data_fixture):
]
@pytest.mark.django_db
def test_get_role_per_scope_per_actors(data_fixture, enterprise_data_fixture):
admin = data_fixture.create_user()
user_2 = data_fixture.create_user()
user_3 = data_fixture.create_user()
user_4 = data_fixture.create_user()
group = data_fixture.create_group(user=admin, members=[user_2, user_3, user_4])
database1 = data_fixture.create_database_application(user=admin, group=group)
table11 = data_fixture.create_database_table(user=admin, database=database1)
table12 = data_fixture.create_database_table(user=admin, database=database1)
database2 = data_fixture.create_database_application(user=admin, group=group)
table21 = data_fixture.create_database_table(user=admin, database=database2)
table22 = data_fixture.create_database_table(user=admin, database=database2)
team1 = enterprise_data_fixture.create_team(group=group, members=[user_3])
team2 = enterprise_data_fixture.create_team(group=group, members=[user_4])
team3 = enterprise_data_fixture.create_team(group=group, members=[user_3, user_4])
editor_role = Role.objects.get(uid="EDITOR")
builder_role = Role.objects.get(uid="BUILDER")
viewer_role = Role.objects.get(uid="VIEWER")
no_role_role = Role.objects.get(uid="NO_ACCESS")
low_priority_role = Role.objects.get(uid="NO_ROLE_LOW_PRIORITY")
RoleAssignmentHandler().assign_role(user_2, group, role=builder_role, scope=group)
RoleAssignmentHandler().assign_role(user_3, group, role=no_role_role, scope=group)
RoleAssignmentHandler().assign_role(
user_4, group, role=low_priority_role, scope=group
)
# User 2 assignments
RoleAssignmentHandler().assign_role(
user_2, group, role=editor_role, scope=database1
)
RoleAssignmentHandler().assign_role(user_2, group, role=no_role_role, scope=table12)
RoleAssignmentHandler().assign_role(user_2, group, role=viewer_role, scope=table22)
# User 4 assignments
RoleAssignmentHandler().assign_role(
user_4, group, role=no_role_role, scope=database1
)
RoleAssignmentHandler().assign_role(user_4, group, role=builder_role, scope=table11)
RoleAssignmentHandler().assign_role(user_4, group, role=no_role_role, scope=table22)
# Team assignments
RoleAssignmentHandler().assign_role(team1, group, role=builder_role, scope=group)
RoleAssignmentHandler().assign_role(team1, group, role=viewer_role, scope=database2)
RoleAssignmentHandler().assign_role(team2, group, role=editor_role, scope=group)
RoleAssignmentHandler().assign_role(team2, group, role=viewer_role, scope=database2)
RoleAssignmentHandler().assign_role(team3, group, role=builder_role, scope=group)
RoleAssignmentHandler().assign_role(team3, group, role=viewer_role, scope=database2)
result = RoleAssignmentHandler().get_roles_per_scope_for_actors(
group, subject_type_registry.get("auth.User"), [user_2, user_3, user_4]
)
assert len(result) == 3
assert len(result[user_2]) == 4
assert result[user_2][0] == (group, [builder_role])
assert result[user_2][1] == (database1, [editor_role])
assert result[user_2][2] == (table12, [no_role_role])
assert result[user_2][3] == (table22, [viewer_role])
assert len(result[user_3]) == 2
assert len(result[user_4]) == 5
@pytest.mark.django_db
def test_get_roles_per_scope_trashed_teams(data_fixture, enterprise_data_fixture):
user = data_fixture.create_user()
@@ -843,3 +941,115 @@ def test_check_get_role_per_scope_performance(
with profiler(html_report_name="enterprise_get_roles_per_scope"):
for i in range(1000):
role_assignment_handler.get_roles_per_scope(group, user)
@pytest.mark.disabled_in_ci
# You must add --run-disabled-in-ci -s to pytest to run this test, you can do this in
# intellij by editing the run config for this test and adding --run-disabled-in-ci -s
# to additional args.
# pytest -k "test_get_role_per_scope_for_actors_perf" -s --run-disabled-in-ci
def test_get_role_per_scope_for_actors_perf(
data_fixture, enterprise_data_fixture, profiler
):
admin = data_fixture.create_user()
users = []
print("Populating database...")
for _ in tqdm(range(100), desc="Users creation"):
users.append(data_fixture.create_user())
group = data_fixture.create_group(user=admin, members=users)
data = {}
for _ in tqdm(range(10), desc="Database"):
database = data_fixture.create_database_application(user=admin, group=group)
data[database] = []
for _ in range(10):
data[database].append(
data_fixture.create_database_table(user=admin, database=database)
)
teams = []
for max in range(10):
teams.append(
enterprise_data_fixture.create_team(
group=group, members=users[max * 100 : (max + 1) * 100 - 50]
)
)
editor_role = Role.objects.get(uid="EDITOR")
builder_role = Role.objects.get(uid="BUILDER")
viewer_role = Role.objects.get(uid="VIEWER")
no_role_role = Role.objects.get(uid="NO_ACCESS")
low_priority_role = Role.objects.get(uid="NO_ROLE_LOW_PRIORITY")
role_assignment_handler = RoleAssignmentHandler()
def role_gen():
while True:
yield editor_role
yield None
yield viewer_role
yield None
yield no_role_role
yield None
yield builder_role
yield None
role_generator = role_gen()
for user in tqdm(users, "User roles"):
group_role = next(role_generator)
if group_role is None:
group_role = low_priority_role
role_assignment_handler.assign_role(user, group, role=group_role, scope=group)
for database, tables in data.items():
role_assignment_handler.assign_role(
user, group, role=next(role_generator), scope=database
)
for table in tables:
role_assignment_handler.assign_role(
user, group, role=next(role_generator), scope=table
)
for team in tqdm(teams, "Team roles"):
for database, tables in data.items():
role_assignment_handler.assign_role(
team, group, role=next(role_generator), scope=database
)
for table in tables:
role_assignment_handler.assign_role(
team, group, role=next(role_generator), scope=table
)
user_subject_type = subject_type_registry.get("auth.User")
reset_queries()
with CaptureQueriesContext(connection) as captured:
role_assignment_handler.get_roles_per_scope_for_actors(
group, user_subject_type, users
)
for q in captured.captured_queries:
print(q)
print(len(captured.captured_queries))
with CaptureQueriesContext(connection) as captured:
role_assignment_handler.get_roles_per_scope_for_actors(
group, user_subject_type, users
)
print("----------- Second time ---------------")
for q in captured.captured_queries:
print(q)
print(len(captured.captured_queries))
with profiler(html_report_name="enterprise_get_roles_per_scope_for_actors"):
for i in range(100):
role_assignment_handler.get_roles_per_scope_for_actors(
group, user_subject_type, users
)
@@ -1,8 +1,9 @@
from django.db import connection
from django.db import IntegrityError, connection, reset_queries
from django.test import override_settings
from django.test.utils import CaptureQueriesContext
import pytest
from tqdm import tqdm
from baserow.contrib.database.fields.operations import (
ReadFieldOperationType,
@@ -30,6 +31,7 @@ from baserow.core.exceptions import PermissionException
from baserow.core.models import Application
from baserow.core.operations import (
CreateGroupOperationType,
DeleteApplicationOperationType,
DeleteGroupOperationType,
ListApplicationsGroupOperationType,
ListGroupsOperationType,
@@ -40,6 +42,7 @@ from baserow.core.operations import (
UpdateSettingsOperationType,
)
from baserow.core.registries import operation_type_registry
from baserow.core.types import PermissionCheck
from baserow_enterprise.role.default_roles import default_roles
from baserow_enterprise.role.handler import RoleAssignmentHandler
from baserow_enterprise.role.models import Role
@@ -780,6 +783,118 @@ def test_check_permissions_with_teams(
)
@pytest.mark.django_db
def test_check_multiple_permissions(data_fixture, enterprise_data_fixture):
admin = data_fixture.create_user()
user_2 = data_fixture.create_user()
user_3 = data_fixture.create_user()
user_4 = data_fixture.create_user()
group = data_fixture.create_group(user=admin, members=[user_2, user_3, user_4])
database1 = data_fixture.create_database_application(user=admin, group=group)
table11 = data_fixture.create_database_table(user=admin, database=database1)
table12 = data_fixture.create_database_table(user=admin, database=database1)
database2 = data_fixture.create_database_application(user=admin, group=group)
table21 = data_fixture.create_database_table(user=admin, database=database2)
table22 = data_fixture.create_database_table(user=admin, database=database2)
team1 = enterprise_data_fixture.create_team(group=group, members=[user_3])
team2 = enterprise_data_fixture.create_team(group=group, members=[user_4])
team3 = enterprise_data_fixture.create_team(group=group, members=[user_3, user_4])
editor_role = Role.objects.get(uid="EDITOR")
builder_role = Role.objects.get(uid="BUILDER")
viewer_role = Role.objects.get(uid="VIEWER")
no_role_role = Role.objects.get(uid="NO_ACCESS")
low_priority_role = Role.objects.get(uid="NO_ROLE_LOW_PRIORITY")
RoleAssignmentHandler().assign_role(user_2, group, role=builder_role, scope=group)
RoleAssignmentHandler().assign_role(user_3, group, role=no_role_role, scope=group)
RoleAssignmentHandler().assign_role(
user_4, group, role=low_priority_role, scope=group
)
# User 2 assignments
RoleAssignmentHandler().assign_role(
user_2, group, role=editor_role, scope=database1
)
RoleAssignmentHandler().assign_role(user_2, group, role=no_role_role, scope=table12)
RoleAssignmentHandler().assign_role(user_2, group, role=viewer_role, scope=table22)
# User 4 assignments
RoleAssignmentHandler().assign_role(
user_4, group, role=no_role_role, scope=database1
)
RoleAssignmentHandler().assign_role(user_4, group, role=builder_role, scope=table11)
RoleAssignmentHandler().assign_role(user_4, group, role=no_role_role, scope=table22)
# Team assignments
RoleAssignmentHandler().assign_role(team1, group, role=builder_role, scope=group)
RoleAssignmentHandler().assign_role(team1, group, role=viewer_role, scope=database2)
RoleAssignmentHandler().assign_role(team2, group, role=editor_role, scope=group)
RoleAssignmentHandler().assign_role(team2, group, role=viewer_role, scope=database2)
RoleAssignmentHandler().assign_role(team3, group, role=builder_role, scope=group)
RoleAssignmentHandler().assign_role(team3, group, role=viewer_role, scope=database2)
permission_manager = RolePermissionManagerType()
checks = [
PermissionCheck(
actor=user_2,
operation_name=ReadApplicationOperationType.type,
context=database1,
),
PermissionCheck(
actor=user_2,
operation_name=ReadDatabaseTableOperationType.type,
context=table12,
),
PermissionCheck(
actor=user_2,
operation_name=ReadDatabaseTableOperationType.type,
context=table21,
),
PermissionCheck(
actor=user_3,
operation_name=DeleteApplicationOperationType.type,
context=group,
),
PermissionCheck(
actor=user_3,
operation_name=ReadApplicationOperationType.type,
context=database2,
),
PermissionCheck(
actor=user_4,
operation_name=ReadApplicationOperationType.type,
context=database1,
),
PermissionCheck(
actor=user_4,
operation_name=ReadDatabaseTableOperationType.type,
context=table12,
),
PermissionCheck(
actor=user_4,
operation_name=ReadDatabaseTableOperationType.type,
context=table21,
),
]
result = permission_manager.check_multiple_permissions(checks, group=group)
assert len(result) == len(checks)
assert [v is True for v in result.values()] == [
True,
False,
True,
False,
True,
True,
False,
True,
]
@pytest.mark.django_db(transaction=True)
@override_settings(
PERMISSION_MANAGERS=["core", "staff", "member", "role", "basic"],
@@ -1141,11 +1256,11 @@ def test_check_permission_performance(data_fixture, enterprise_data_fixture, pro
low_priority_role = Role.objects.get(uid="NO_ROLE_LOW_PRIORITY")
RoleAssignmentHandler().assign_role(
user, group, role=low_priority_role, scope=group
user2, group, role=low_priority_role, scope=group
)
RoleAssignmentHandler().assign_role(user, group, role=editor_role, scope=database1)
RoleAssignmentHandler().assign_role(user, group, role=no_role_role, scope=table12)
RoleAssignmentHandler().assign_role(user, group, role=viewer_role, scope=table22)
RoleAssignmentHandler().assign_role(user2, group, role=editor_role, scope=database1)
RoleAssignmentHandler().assign_role(user2, group, role=no_role_role, scope=table12)
RoleAssignmentHandler().assign_role(user2, group, role=viewer_role, scope=table22)
RoleAssignmentHandler().assign_role(team1, group, role=builder_role, scope=group)
RoleAssignmentHandler().assign_role(team1, group, role=viewer_role, scope=database2)
@@ -1159,7 +1274,7 @@ def test_check_permission_performance(data_fixture, enterprise_data_fixture, pro
print("----------- first call queries ---------------")
with CaptureQueriesContext(connection) as captured:
permission_manager.check_permissions(
user, ReadDatabaseTableOperationType.type, group=group, context=table11
user2, ReadDatabaseTableOperationType.type, group=group, context=table11
)
for q in captured.captured_queries:
@@ -1169,7 +1284,7 @@ def test_check_permission_performance(data_fixture, enterprise_data_fixture, pro
print("----------- second call queries ---------------")
with CaptureQueriesContext(connection) as captured:
permission_manager.check_permissions(
user, ReadDatabaseTableOperationType.type, group=group, context=table11
user2, ReadDatabaseTableOperationType.type, group=group, context=table11
)
for q in captured.captured_queries:
@@ -1180,7 +1295,7 @@ def test_check_permission_performance(data_fixture, enterprise_data_fixture, pro
with profiler(html_report_name="enterprise_check_permissions"):
for i in range(1000):
permission_manager.check_permissions(
user, ReadDatabaseTableOperationType.type, group=group, context=table11
user2, ReadDatabaseTableOperationType.type, group=group, context=table11
)
@@ -1214,11 +1329,11 @@ def test_get_permission_object_performance(
low_priority_role = Role.objects.get(uid="NO_ROLE_LOW_PRIORITY")
RoleAssignmentHandler().assign_role(
user, group, role=low_priority_role, scope=group
user2, group, role=low_priority_role, scope=group
)
RoleAssignmentHandler().assign_role(user, group, role=editor_role, scope=database1)
RoleAssignmentHandler().assign_role(user, group, role=no_role_role, scope=table12)
RoleAssignmentHandler().assign_role(user, group, role=viewer_role, scope=table22)
RoleAssignmentHandler().assign_role(user2, group, role=editor_role, scope=database1)
RoleAssignmentHandler().assign_role(user2, group, role=no_role_role, scope=table12)
RoleAssignmentHandler().assign_role(user2, group, role=viewer_role, scope=table22)
RoleAssignmentHandler().assign_role(team1, group, role=builder_role, scope=group)
RoleAssignmentHandler().assign_role(team1, group, role=viewer_role, scope=database2)
@@ -1231,7 +1346,7 @@ def test_get_permission_object_performance(
print("----------- first call queries ---------------")
with CaptureQueriesContext(connection) as captured:
permission_manager.get_permissions_object(user, group=group)
permission_manager.get_permissions_object(user2, group=group)
for q in captured.captured_queries:
print(q)
@@ -1239,7 +1354,7 @@ def test_get_permission_object_performance(
print("----------- second call queries ---------------")
with CaptureQueriesContext(connection) as captured:
permission_manager.get_permissions_object(user, group=group)
permission_manager.get_permissions_object(user2, group=group)
for q in captured.captured_queries:
print(q)
@@ -1248,4 +1363,129 @@ def test_get_permission_object_performance(
print("----------- get_permission_object perfs ---------------")
with profiler(html_report_name="enterprise_get_permissions_object"):
for i in range(1000):
permission_manager.get_permissions_object(user, group=group)
permission_manager.get_permissions_object(user2, group=group)
@pytest.mark.disabled_in_ci
# You must add --run-disabled-in-ci -s to pytest to run this test, you can do this in
# intellij by editing the run config for this test and adding --run-disabled-in-ci -s
# to additional args.
# pytest -k "test_check_multiple_permissions_perf" -s --run-disabled-in-ci
# 166 second for 3 710 000 checks on Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz -
# 7200 bogomips
def test_check_multiple_permissions_perf(
data_fixture, enterprise_data_fixture, profiler
):
admin = data_fixture.create_user()
users = []
print("Populating database...")
for _ in tqdm(range(1000), desc="Users creation"):
try:
users.append(data_fixture.create_user())
except IntegrityError:
pass
group = data_fixture.create_group(user=admin, members=users)
data = {}
for _ in tqdm(range(10), desc="Database"):
database = data_fixture.create_database_application(user=admin, group=group)
data[database] = []
for _ in range(10):
data[database].append(
data_fixture.create_database_table(user=admin, database=database)
)
teams = []
for max in range(10):
teams.append(
enterprise_data_fixture.create_team(
group=group,
members=users, # members=users[max * 10 : (max + 1) * 10 - 5]
)
)
editor_role = Role.objects.get(uid="EDITOR")
builder_role = Role.objects.get(uid="BUILDER")
viewer_role = Role.objects.get(uid="VIEWER")
no_role_role = Role.objects.get(uid="NO_ACCESS")
low_priority_role = Role.objects.get(uid="NO_ROLE_LOW_PRIORITY")
role_assignment_handler = RoleAssignmentHandler()
def role_gen():
while True:
yield editor_role
yield None
yield viewer_role
yield None
yield no_role_role
yield None
yield builder_role
yield None
role_generator = role_gen()
for user in tqdm(users, "User roles"):
group_role = next(role_generator)
if group_role is None:
group_role = low_priority_role
role_assignment_handler.assign_role(user, group, role=group_role, scope=group)
for database, tables in data.items():
role_assignment_handler.assign_role(
user, group, role=next(role_generator), scope=database.application_ptr
)
for table in tables:
role_assignment_handler.assign_role(
user, group, role=next(role_generator), scope=table
)
for team in tqdm(teams, "Team roles"):
for database, tables in data.items():
role_assignment_handler.assign_role(
team, group, role=next(role_generator), scope=database
)
for table in tables:
role_assignment_handler.assign_role(
team, group, role=next(role_generator), scope=table
)
reset_queries()
perm_manager = RolePermissionManagerType()
all_op = operation_type_registry.get_all()
db_op = [op for op in all_op if op.context_scope_name == "application"]
table_op = [op for op in all_op if op.context_scope_name == "database_table"]
checks = []
for user in tqdm(users, "Creating checks"):
for db, tables in data.items():
for op in db_op:
checks.append(
PermissionCheck(
actor=user, operation_name=op.type, context=db.application_ptr
)
)
for table in tables:
for op in table_op:
checks.append(
PermissionCheck(
actor=user, operation_name=op.type, context=table
)
)
print(f"------------ For {len(checks)} checks! ----------")
with CaptureQueriesContext(connection) as captured:
with profiler(html_report_name="enterprise_check_multiple_permissions"):
perm_manager.check_multiple_permissions(checks, group=group)
for q in captured.captured_queries:
print(q)
print(len(captured.captured_queries))
@@ -1,3 +1,5 @@
from typing import NamedTuple
import pytest
from baserow_enterprise.teams.handler import TeamHandler
@@ -16,14 +18,29 @@ def test_team_subject_type_is_in_group(enterprise_data_fixture):
team_in_group = enterprise_data_fixture.create_team(group=group)
trashed_team = enterprise_data_fixture.create_team(group=group, trashed=True)
assert TeamSubjectType().is_in_group(team_not_in_group.id, group) is False
assert TeamSubjectType().is_in_group(team_in_group.id, group) is True
assert TeamSubjectType().is_in_group(9999, group) is False
assert TeamSubjectType().is_in_group(trashed_team.id, group) is False
class FakeTeam(NamedTuple):
id: int
fake_team = FakeTeam(99999)
assert TeamSubjectType().is_in_group(team_not_in_group, group) is False
assert TeamSubjectType().is_in_group(team_in_group, group) is True
assert TeamSubjectType().is_in_group(fake_team, group) is False
assert TeamSubjectType().is_in_group(trashed_team, group) is False
assert TeamSubjectType().are_in_group(
[
team_not_in_group,
team_in_group,
fake_team,
trashed_team,
],
group,
) == [False, True, False, False]
@pytest.mark.django_db
def test_team_subject_get_associated_users(enterprise_data_fixture):
def test_team_subject_get_users_included_in_subject(enterprise_data_fixture):
user_1 = enterprise_data_fixture.create_user()
user_2 = enterprise_data_fixture.create_user()
group = enterprise_data_fixture.create_group(user=user_1, members=[user_2])
@@ -32,7 +49,7 @@ def test_team_subject_get_associated_users(enterprise_data_fixture):
TeamHandler().create_subject(user_1, {"id": user_1.id}, "auth.User", team)
TeamHandler().create_subject(user_1, {"id": user_2.id}, "auth.User", team)
associated_users = TeamSubjectType().get_associated_users(team)
associated_users = TeamSubjectType().get_users_included_in_subject(team)
assert user_1 in associated_users
assert user_2 in associated_users
@@ -35,7 +35,7 @@ async def test_database_updated_message_not_leaking(data_fixture):
no_access_role = Role.objects.get(uid="NO_ACCESS")
await sync_to_async(RoleAssignmentHandler().assign_role)(
user_excluded, group, no_access_role, database
user_excluded, group, no_access_role, database.application_ptr
)
# Establish websocket connection and subscribe to table
@@ -65,7 +65,7 @@ async def test_database_deleted_message_not_leaking(data_fixture):
no_access_role = Role.objects.get(uid="NO_ACCESS")
await sync_to_async(RoleAssignmentHandler().assign_role)(
user_excluded, group, no_access_role, database
user_excluded, group, no_access_role, database.application_ptr
)
# Establish websocket connection and subscribe to table
@@ -95,7 +95,7 @@ async def test_database_created_message_not_leaking(data_fixture):
no_access_role = Role.objects.get(uid="NO_ACCESS")
await sync_to_async(RoleAssignmentHandler().assign_role)(
user_excluded, group, no_access_role, database
user_excluded, group, no_access_role, database.application_ptr
)
# Establish websocket connection and subscribe to table
@@ -1,4 +1,4 @@
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from django.contrib.auth import get_user_model
from django.db.models import Q, QuerySet
@@ -8,12 +8,14 @@ from baserow_premium.license.handler import LicenseHandler
from baserow_premium.views.models import OWNERSHIP_TYPE_PERSONAL
from baserow.contrib.database.views.operations import ListViewsOperationType
from baserow.core.exceptions import PermissionDenied
from baserow.core.exceptions import PermissionDenied, PermissionException
from baserow.core.registries import (
PermissionManagerType,
object_scope_type_registry,
operation_type_registry,
)
from baserow.core.subjects import UserSubjectType
from baserow.core.types import PermissionCheck
User = get_user_model()
@@ -26,6 +28,7 @@ if TYPE_CHECKING:
class ViewOwnershipPermissionManagerType(PermissionManagerType):
type = "view_ownership"
supported_actor_types = [UserSubjectType.type]
def __init__(self):
view_scope_type = object_scope_type_registry.get("database_view")
@@ -40,69 +43,50 @@ class ViewOwnershipPermissionManagerType(PermissionManagerType):
super().__init__()
def check_permissions(
def check_multiple_permissions(
self,
actor: "AbstractUser",
operation_name: str,
group: Optional["Group"] = None,
context: Optional[Any] = None,
checks: List[PermissionCheck],
group: "Group",
include_trash: bool = False,
) -> Optional[bool]:
) -> Dict[PermissionCheck, Union[bool, PermissionException]]:
"""
check_permissions() impl for view ownership checks.
check_multiple_permissions() impl for view ownership checks.
There are other instances that this method cannot check:
- CreateViewDecorationOperationType is currently implemented via view_created
signal since the permission system doesn't allow to pass richer context.
- OrderViewsOperationType is currently implemented via views_reordered signal
since the permission system doesn't allow to pass richer context.
- ListViewsOperationType and ReadViewsOrderOperationType operations invoke
filter_queryset() method and hence don't need to be checked.
:param actor: The actor who wants to execute the operation. Generally a `User`,
but can be a `Token`.
:param operation_name: The operation name the actor wants to execute.
:param group: The optional group in which the operation takes place.
:param context: The optional object affected by the operation. For instance
if you are updating a `Table` object, the context is this `Table` object.
:param include_trash: If true then also checks if the given group has been
trashed instead of raising a DoesNotExist exception.
:raise PermissionDenied: If the operation is disallowed a PermissionDenied is
raised.
:return: `True` if the operation is permitted, None if the permission manager
can't decide.
"""
if not isinstance(actor, User):
return
result_by_check = {}
for check in checks:
actor, operation_name, context = check
if operation_name not in self.operations or not group or not context:
continue
if operation_name not in self.operations:
return
premium = LicenseHandler.user_has_feature(PREMIUM, actor, group)
if not group:
return
view_scope_type = object_scope_type_registry.get("database_view")
view = object_scope_type_registry.get_parent(
context, at_scope_type=view_scope_type
)
if not context:
return
if premium:
if (
view.ownership_type == OWNERSHIP_TYPE_PERSONAL
and view.created_by_id != actor.id
):
result_by_check[check] = PermissionDenied(
"The user doesn't own this personal view"
)
else:
if view.ownership_type == OWNERSHIP_TYPE_PERSONAL:
result_by_check[check] = PermissionDenied(
"The user doesn't have the authorization to see personal views"
)
premium = LicenseHandler.user_has_feature(PREMIUM, actor, group)
view_scope_type = object_scope_type_registry.get("database_view")
view = object_scope_type_registry.get_parent(
context, at_scope_type=view_scope_type
)
if premium:
if (
view.ownership_type == OWNERSHIP_TYPE_PERSONAL
and view.created_by != actor
):
raise PermissionDenied()
else:
if view.ownership_type == OWNERSHIP_TYPE_PERSONAL:
raise PermissionDenied()
return
return result_by_check
def filter_queryset(
self,