From d36fc12e105d99112fb455b7c482d214903fe70f Mon Sep 17 00:00:00 2001 From: Peter Evans Date: Wed, 4 Nov 2026 16:39:36 +0000 Subject: [PATCH] feat: let admins create scoped invite links (#6530) * feat: let admins create invite links that give a role on an application, table or view * test: cover invite links to applications and views and add their strings to the translation catalogs * fix: validate scoped invitation link roles in handler * fix: show scoped destination when invite creator is absent * fix: limit view invitation links to restricted views * fix: avoid auth provider ID collisions in OAuth tests --------- Co-authored-by: Jeremie Pardou <571533+jrmi@users.noreply.github.com> --- .../invitation_links/serializers.py | 39 +- backend/src/baserow/core/actions.py | 47 +- backend/src/baserow/core/handler.py | 111 ++- .../core/locale/en/LC_MESSAGES/django.po | 56 +- .../0135_workspaceinvitationlink_scope.py | 45 + backend/src/baserow/core/models.py | 20 +- backend/src/baserow/core/registries.py | 67 ++ .../test_workspace_invitation_link_views.py | 3 + .../api/role/serializers.py | 93 +++ .../src/baserow_enterprise/api/role/urls.py | 12 + .../src/baserow_enterprise/api/role/views.py | 273 ++++++ .../backend/src/baserow_enterprise/apps.py | 17 + .../locale/en/LC_MESSAGES/django.po | 36 + .../src/baserow_enterprise/role/actions.py | 212 ++++- .../src/baserow_enterprise/role/handler.py | 217 ++++- .../role/invitation_link_scope_types.py | 51 ++ .../src/baserow_enterprise/role/receivers.py | 8 +- .../common/oauth2/test_common_oauth2_views.py | 19 +- .../role/test_scoped_invitation_links.py | 786 ++++++++++++++++++ .../invitationTargetTypes.js | 55 ++ .../baserow_enterprise/locales/en.json | 4 +- .../services/roleAssignments.js | 25 + .../scopeInvitationTargetType.spec.js | 80 ++ .../core/components/auth/PasswordRegister.vue | 15 +- .../invitation/InvitationLinkDeleteModal.vue | 6 +- .../invitation/LinkInvitationRoute.vue | 2 +- .../modules/core/invitationTargetTypes.js | 17 + web-frontend/modules/core/locales/en.json | 3 + .../modules/core/pages/invitationLink.vue | 53 +- 29 files changed, 2303 insertions(+), 69 deletions(-) create mode 100644 backend/src/baserow/core/migrations/0135_workspaceinvitationlink_scope.py create mode 100644 enterprise/backend/src/baserow_enterprise/role/invitation_link_scope_types.py create mode 100644 enterprise/backend/tests/baserow_enterprise_tests/role/test_scoped_invitation_links.py diff --git a/backend/src/baserow/api/workspaces/invitation_links/serializers.py b/backend/src/baserow/api/workspaces/invitation_links/serializers.py index ce1ff44368..2154e68ef3 100644 --- a/backend/src/baserow/api/workspaces/invitation_links/serializers.py +++ b/backend/src/baserow/api/workspaces/invitation_links/serializers.py @@ -4,6 +4,7 @@ from rest_framework import serializers from baserow.core.handler import CoreHandler from baserow.core.models import WorkspaceInvitationLink +from baserow.core.registries import object_scope_type_registry class WorkspaceInvitationLinkSerializer(serializers.ModelSerializer): @@ -51,14 +52,34 @@ class PublicWorkspaceInvitationLinkSerializer(serializers.ModelSerializer): invited_by = serializers.SerializerMethodField() workspace = serializers.SerializerMethodField() workspace_id = serializers.IntegerField(read_only=True) + scope_type = serializers.SerializerMethodField( + help_text="The type of the object of the workspace the link gives a role on, " + "or null if the link is for the workspace itself." + ) + scope_id = serializers.IntegerField( + read_only=True, help_text="The id of the object the link gives a role on." + ) + scope_name = serializers.SerializerMethodField( + help_text="The name of the object the link gives a role on." + ) role_upgrade = serializers.SerializerMethodField( help_text="Set when the user who opens the link is a member of the workspace " - "and joining through the link would raise their role." + "and joining through the link would raise their role, on the object of the " + "link if it has one." ) class Meta: model = WorkspaceInvitationLink - fields = ("slug", "invited_by", "workspace", "workspace_id", "role_upgrade") + fields = ( + "slug", + "invited_by", + "workspace", + "workspace_id", + "scope_type", + "scope_id", + "scope_name", + "role_upgrade", + ) @extend_schema_field(OpenApiTypes.STR) def get_invited_by(self, object): @@ -68,6 +89,20 @@ class PublicWorkspaceInvitationLinkSerializer(serializers.ModelSerializer): def get_workspace(self, object): return object.workspace.name + @extend_schema_field(OpenApiTypes.STR) + def get_scope_type(self, object): + if object.scope_type_id is None: + return None + return object_scope_type_registry.get_by_model( + object.scope_type.model_class() + ).type + + @extend_schema_field(OpenApiTypes.STR) + def get_scope_name(self, object): + if object.scope_type_id is None: + return None + return object.scope.name + @extend_schema_field(InvitationLinkRoleUpgradeSerializer(allow_null=True)) def get_role_upgrade(self, object): user = self.context.get("user") diff --git a/backend/src/baserow/core/actions.py b/backend/src/baserow/core/actions.py index 566ab82d2a..ef2278e553 100755 --- a/backend/src/baserow/core/actions.py +++ b/backend/src/baserow/core/actions.py @@ -28,7 +28,11 @@ from baserow.core.models import ( WorkspaceInvitationLink, WorkspaceUser, ) -from baserow.core.registries import ImportExportConfig, application_type_registry +from baserow.core.registries import ( + ImportExportConfig, + application_type_registry, + object_scope_type_registry, +) from baserow.core.trash.handler import TrashHandler from baserow.core.user_templates.handler import UserTemplateHandler from baserow.core.utils import ChildProgressBuilder @@ -1313,10 +1317,19 @@ class JoinWorkspaceViaInvitationLinkActionType(ActionType): "(%(invitation_link_id)s) as %(permissions)s." ), ) + scope_description = ActionTypeDescription( + _("Join workspace via invitation link"), + _( + 'Joined "%(group_name)s" (%(group_id)s) through invitation link ' + '(%(invitation_link_id)s) as %(permissions)s on "%(scope_type_name)s" ' + "(%(scope_id)s)." + ), + ) analytics_params = [ "invitation_link_id", "permissions", "workspace_id", + "scope_type_name", ] @dataclasses.dataclass @@ -1325,6 +1338,8 @@ class JoinWorkspaceViaInvitationLinkActionType(ActionType): permissions: str workspace_id: int workspace_name: str + scope_type_name: Optional[str] = None + scope_id: Optional[int] = None @classmethod def do( @@ -1337,33 +1352,49 @@ class JoinWorkspaceViaInvitationLinkActionType(ActionType): """ workspace = invitation_link.workspace - permissions_before = ( - WorkspaceUser.objects.filter(user=user, workspace=workspace) - .values_list("permissions", flat=True) - .first() + handler = CoreHandler() + was_member = WorkspaceUser.objects.filter( + user=user, workspace=workspace + ).exists() + raised_permissions = handler.get_permissions_raised_by_invitation_link( + user, invitation_link ) - workspace_user = CoreHandler().join_workspace_via_invitation_link( + workspace_user = handler.join_workspace_via_invitation_link( user, invitation_link ) # Members open the link on their way into the workspace, so only record # the visits that changed their membership. - if workspace_user.permissions == permissions_before: + if was_member and raised_permissions is None: return workspace_user + scope_type_name = None + if invitation_link.scope_type_id is not None: + scope_type_name = object_scope_type_registry.get_by_model( + invitation_link.scope_type.model_class() + ).type + cls.register_action( user=user, params=cls.Params( invitation_link.id, - workspace_user.permissions, + invitation_link.permissions, workspace.id, workspace.name, + scope_type_name, + invitation_link.scope_id, ), scope=cls.scope(), workspace=workspace, ) return workspace_user + @classmethod + def get_long_description(cls, params_dict: dict[str, Any], *args, **kwargs) -> str: + if params_dict.get("scope_type_name"): + return render_action_type_description(cls.scope_description, params_dict) + return super().get_long_description(params_dict, *args, **kwargs) + @classmethod def scope(cls) -> ActionScopeStr: return RootActionScopeType.value() diff --git a/backend/src/baserow/core/handler.py b/backend/src/baserow/core/handler.py index 237406f64e..877a88f89b 100755 --- a/backend/src/baserow/core/handler.py +++ b/backend/src/baserow/core/handler.py @@ -53,6 +53,7 @@ from .exceptions import ( CannotChangeYourOwnWorkspaceRole, CannotDeleteYourselfFromWorkspace, DuplicateApplicationMaxLocksExceededException, + InstanceTypeDoesNotExist, InvalidPermissionContext, InvalidWorkspaceRole, LastAdminOfWorkspace, @@ -107,7 +108,9 @@ from .operations import ( ) from .registries import ( ImportExportConfig, + InvitationLinkScopeType, application_type_registry, + invitation_link_scope_type_registry, object_scope_type_registry, operation_type_registry, permission_manager_type_registry, @@ -1630,7 +1633,9 @@ class CoreHandler: self, invitation_link_id: int, base_queryset: Optional[QuerySet] = None ) -> WorkspaceInvitationLink: """ - Selects a workspace invitation link with a given id from the database. + Selects a workspace invitation link with a given id from the database. By + default only links to the workspace itself are selected, links to an object + of the workspace are managed where the roles on that object are. :param invitation_link_id: The identifier of the link that must be returned. :param base_queryset: The base queryset from where to select the link. @@ -1639,7 +1644,9 @@ class CoreHandler: """ if base_queryset is None: - base_queryset = WorkspaceInvitationLink.objects + base_queryset = WorkspaceInvitationLink.objects.filter( + scope_type__isnull=True + ) try: return base_queryset.select_related("workspace").get(id=invitation_link_id) @@ -1649,7 +1656,7 @@ class CoreHandler: "not exist." ) from e - def _invitation_link_signups_allowed(self) -> bool: + def invitation_link_signups_allowed(self) -> bool: """ Whether the instance settings let new people sign up through an invitation link, which links need to be created or used. @@ -1678,26 +1685,56 @@ class CoreHandler: feature_flag_is_enabled(FF_RBAC_IMPROVEMENTS, raise_if_disabled=True) - if not self._invitation_link_signups_allowed(): + if not self.invitation_link_signups_allowed(): raise WorkspaceInvitationLinkDoesNotExist( "Invitation links can't be used while signups are disabled." ) try: - return WorkspaceInvitationLink.objects.select_related( - "workspace", "created_by" + invitation_link = WorkspaceInvitationLink.objects.select_related( + "workspace", "created_by", "scope_type" ).get(slug=slug, workspace__trashed=False) except WorkspaceInvitationLink.DoesNotExist as e: raise WorkspaceInvitationLinkDoesNotExist( "The workspace invitation link does not exist." ) from e + if invitation_link.scope_type_id is not None: + scope_type = self.get_invitation_link_scope_type(invitation_link) + if scope_type is None or not scope_type.is_usable(invitation_link): + raise WorkspaceInvitationLinkDoesNotExist( + "The object of the workspace invitation link can't be joined." + ) + + return invitation_link + + def get_invitation_link_scope_type( + self, invitation_link: WorkspaceInvitationLink + ) -> Optional[InvitationLinkScopeType]: + """ + Returns the type that handles the object an invitation link targets. + + :param invitation_link: A link that targets an object of the workspace. + :return: The type of the object of the link, or None if links can't target + objects of that type, for example because the module that handles them + isn't installed. + """ + + model_class = invitation_link.scope_type.model_class() + if model_class is None: + return None + try: + object_scope_type = object_scope_type_registry.get_by_model(model_class) + return invitation_link_scope_type_registry.get(object_scope_type.type) + except InstanceTypeDoesNotExist: + return None + def list_workspace_invitation_links( self, user: AbstractUser, workspace: Workspace ) -> QuerySet[WorkspaceInvitationLink]: """ - Returns the invitation links of the workspace if the user is allowed to - manage them. + Returns the invitation links to the workspace itself if the user is allowed + to manage them. Links to an object of the workspace aren't included. :param user: The user on whose behalf the links are listed. :param workspace: The workspace of which the links must be returned. @@ -1712,7 +1749,9 @@ class CoreHandler: context=workspace, ) - return WorkspaceInvitationLink.objects.filter(workspace=workspace) + return WorkspaceInvitationLink.objects.filter( + workspace=workspace, scope_type__isnull=True + ) def create_workspace_invitation_link( self, @@ -1746,7 +1785,7 @@ class CoreHandler: context=workspace, ) - if not self._invitation_link_signups_allowed(): + if not self.invitation_link_signups_allowed(): raise WorkspaceInvitationLinkSignupsDisabled( "Invitation links can't be created while signups are disabled." ) @@ -1831,7 +1870,8 @@ class CoreHandler: ) -> Optional[str]: """ Returns the current permissions of a member of the workspace of the link - when joining through the link would raise them. + when joining through the link would raise them. For a link to an object of + the workspace, these are the permissions the member has on that object. :param user: The user who opened the link, possibly anonymous. :param invitation_link: The link the user opened. @@ -1849,9 +1889,15 @@ class CoreHandler: .values_list("permissions", flat=True) .first() ) - if permissions is None or not self._invitation_link_raises_permissions( - permissions, invitation_link - ): + if permissions is None: + return None + + if invitation_link.scope_type_id is not None: + return self.get_invitation_link_scope_type(invitation_link).get_raised_role( + user, invitation_link + ) + + if not self._invitation_link_raises_permissions(permissions, invitation_link): return None return permissions @@ -1861,7 +1907,9 @@ class CoreHandler: """ Adds the user to the workspace of the link with the permissions of the link. Someone who is already a member gets the permissions of the link when - they are an upgrade, and otherwise keeps their current permissions. + they are an upgrade, and otherwise keeps their current permissions. A link + to an object of the workspace gives its permissions on that object only, + and with the same rule: they're never lowered. :param user: The user who joins the workspace. :param invitation_link: The link the user joins through. @@ -1871,17 +1919,30 @@ class CoreHandler: feature_flag_is_enabled(FF_RBAC_IMPROVEMENTS, raise_if_disabled=True) - workspace_user = self.add_user_to_workspace( - invitation_link.workspace, user, permissions=invitation_link.permissions - ) - - # A link can raise the role of a member, but never lowers it. - if self._invitation_link_raises_permissions( - workspace_user.permissions, invitation_link - ): - workspace_user = self.force_update_workspace_user( - user, workspace_user, permissions=invitation_link.permissions + if invitation_link.scope_type_id is not None: + scope_type = self.get_invitation_link_scope_type(invitation_link) + workspace_user = self.add_user_to_workspace( + invitation_link.workspace, + user, + permissions=scope_type.get_newcomer_permissions(invitation_link), ) + # A link can raise the role of a member on its object, but never + # lowers it. + if scope_type.get_raised_role(user, invitation_link) is not None: + scope_type.give_role(user, invitation_link) + else: + workspace_user = self.add_user_to_workspace( + invitation_link.workspace, + user, + permissions=invitation_link.permissions, + ) + # A link can raise the role of a member, but never lowers it. + if self._invitation_link_raises_permissions( + workspace_user.permissions, invitation_link + ): + workspace_user = self.force_update_workspace_user( + user, workspace_user, permissions=invitation_link.permissions + ) workspace_user_joined_via_invitation_link.send( sender=self, diff --git a/backend/src/baserow/core/locale/en/LC_MESSAGES/django.po b/backend/src/baserow/core/locale/en/LC_MESSAGES/django.po index c1d6c5e858..2334b4a86b 100644 --- a/backend/src/baserow/core/locale/en/LC_MESSAGES/django.po +++ b/backend/src/baserow/core/locale/en/LC_MESSAGES/django.po @@ -202,6 +202,59 @@ msgid "" "\"%(group_name)s\" (%(group_id)s)." msgstr "" +#: src/baserow/core/actions.py:1119 +msgid "Create workspace invitation link" +msgstr "" + +#: src/baserow/core/actions.py:1121 +#, python-format +msgid "" +"Invitation link (%(invitation_link_id)s) created to join \"%(group_name)s\" " +"(%(group_id)s) as %(permissions)s." +msgstr "" + +#: src/baserow/core/actions.py:1175 +msgid "Update workspace invitation link" +msgstr "" + +#: src/baserow/core/actions.py:1177 +#, python-format +msgid "" +"Invitation link (%(invitation_link_id)s) to join \"%(group_name)s\" " +"(%(group_id)s) changed from \"%(original_name)s\" as " +"%(original_permissions)s to \"%(name)s\" as %(permissions)s." +msgstr "" + +#: src/baserow/core/actions.py:1245 +msgid "Delete workspace invitation link" +msgstr "" + +#: src/baserow/core/actions.py:1247 +#, python-format +msgid "" +"Invitation link \"%(name)s\" (%(invitation_link_id)s) to join " +"\"%(group_name)s\" (%(group_id)s) as %(permissions)s deleted." +msgstr "" + +#: src/baserow/core/actions.py:1298 src/baserow/core/actions.py:1305 +msgid "Join workspace via invitation link" +msgstr "" + +#: src/baserow/core/actions.py:1300 +#, python-format +msgid "" +"Joined \"%(group_name)s\" (%(group_id)s) through invitation link " +"(%(invitation_link_id)s) as %(permissions)s." +msgstr "" + +#: src/baserow/core/actions.py:1307 +#, python-format +msgid "" +"Joined \"%(group_name)s\" (%(group_id)s) through invitation link " +"(%(invitation_link_id)s) as %(permissions)s on \"%(scope_type_name)s\" " +"(%(scope_id)s)." +msgstr "" + #: src/baserow/core/actions.py:1095 msgid "Leave group" msgstr "" @@ -642,7 +695,8 @@ msgstr "" #, python-format msgid "" "User \"%(user_email)s\" (%(user_id)s) created via \"%(auth_provider_type)s\" " -"(%(auth_provider_id)s) auth provider (invitation: %(with_invitation_token)s)" +"(%(auth_provider_id)s) auth provider (invitation: %(with_invitation_token)s, " +"invitation link: %(with_invitation_link)s)" msgstr "" #: src/baserow/core/user/actions.py:122 diff --git a/backend/src/baserow/core/migrations/0135_workspaceinvitationlink_scope.py b/backend/src/baserow/core/migrations/0135_workspaceinvitationlink_scope.py new file mode 100644 index 0000000000..80406acc00 --- /dev/null +++ b/backend/src/baserow/core/migrations/0135_workspaceinvitationlink_scope.py @@ -0,0 +1,45 @@ +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("contenttypes", "0002_remove_content_type_name"), + ("core", "0134_workspaceinvitationlink"), + ] + + operations = [ + migrations.AddField( + model_name="workspaceinvitationlink", + name="scope_id", + field=models.PositiveIntegerField( + blank=True, + help_text="The id of the object the link gives a role on.", + null=True, + ), + ), + migrations.AddField( + model_name="workspaceinvitationlink", + name="scope_type", + field=models.ForeignKey( + blank=True, + help_text="The type of the object the link gives a role on, if it " + "targets an object of the workspace instead of the workspace itself.", + null=True, + on_delete=django.db.models.deletion.CASCADE, + related_name="+", + to="contenttypes.contenttype", + ), + ), + migrations.AlterField( + model_name="workspaceinvitationlink", + name="permissions", + field=models.CharField( + default="MEMBER", + help_text="The permissions that people get within the workspace when " + "they join through the link, or on the scope of the link if it has " + "one.", + max_length=32, + ), + ), + ] diff --git a/backend/src/baserow/core/models.py b/backend/src/baserow/core/models.py index 12a819004b..22723a4e38 100755 --- a/backend/src/baserow/core/models.py +++ b/backend/src/baserow/core/models.py @@ -5,6 +5,7 @@ from functools import lru_cache from django.conf import settings from django.contrib.auth import get_user_model +from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.postgres.fields import ArrayField from django.core.exceptions import ValidationError @@ -549,6 +550,8 @@ class WorkspaceInvitationLink( """ A permanent link that anyone can use to join the workspace with the role of the link. It can be used any number of times and stops working once it's deleted. + A link can also target one object of the workspace, like a table, in which case + the role of the link is given on that object instead of on the workspace. """ workspace = models.ForeignKey( @@ -581,7 +584,22 @@ class WorkspaceInvitationLink( default=WORKSPACE_USER_PERMISSION_MEMBER, max_length=32, help_text="The permissions that people get within the workspace when they " - "join through the link.", + "join through the link, or on the scope of the link if it has one.", + ) + scope = GenericForeignKey("scope_type", "scope_id") + scope_type = models.ForeignKey( + ContentType, + null=True, + blank=True, + on_delete=models.CASCADE, + related_name="+", + help_text="The type of the object the link gives a role on, if it targets " + "an object of the workspace instead of the workspace itself.", + ) + scope_id = models.PositiveIntegerField( + null=True, + blank=True, + help_text="The id of the object the link gives a role on.", ) def get_parent(self): diff --git a/backend/src/baserow/core/registries.py b/backend/src/baserow/core/registries.py index 5ad69c621f..253f338ae2 100755 --- a/backend/src/baserow/core/registries.py +++ b/backend/src/baserow/core/registries.py @@ -57,6 +57,7 @@ if TYPE_CHECKING: Template, Workspace, WorkspaceInvitation, + WorkspaceInvitationLink, WorkspaceUser, ) @@ -1057,6 +1058,69 @@ class PermissionManagerTypeRegistry(Registry[PermissionManagerType]): already_registered_exception_class = PermissionManagerTypeAlreadyRegistered +class InvitationLinkScopeType(Instance, abc.ABC): + """ + Lets a permanent invitation link target one object of the workspace, like a + table, instead of the workspace itself. The type is the name of the object scope + type of the objects it handles. A link to an object whose scope type isn't + registered here can't be used. + """ + + @abc.abstractmethod + def is_usable(self, invitation_link: "WorkspaceInvitationLink") -> bool: + """ + Whether people can join through the link, which they can't anymore once + its object is trashed for example. + + :param invitation_link: The link that targets an object of this type. + """ + + @abc.abstractmethod + def get_newcomer_permissions( + self, invitation_link: "WorkspaceInvitationLink" + ) -> str: + """ + Returns the workspace permissions of someone who joins the workspace through + the link. They only get the role of the link on its object. + + :param invitation_link: The link that targets an object of this type. + """ + + @abc.abstractmethod + def get_raised_role( + self, user: "AbstractUser", invitation_link: "WorkspaceInvitationLink" + ) -> Optional[str]: + """ + Returns the role uid a member of the workspace currently has on the object + of the link, if the role of the link would raise it. + + :param user: The member who opened the link. + :param invitation_link: The link that targets an object of this type. + :return: The current role uid on the object, or None if the role of the link + doesn't give the member more than they already have there. + """ + + @abc.abstractmethod + def give_role( + self, user: "AbstractUser", invitation_link: "WorkspaceInvitationLink" + ): + """ + Gives the member the role of the link on the object of the link. + + :param user: The member who joins through the link. + :param invitation_link: The link that targets an object of this type. + """ + + +class InvitationLinkScopeTypeRegistry(Registry[InvitationLinkScopeType]): + """ + Contains the types of objects inside a workspace that permanent invitation links + can target. + """ + + name = "invitation_link_scope" + + class ObjectScopeType(Instance, ModelInstanceMixin): """ This type describe an object scope in Baserow. This is useful if you need to know @@ -1930,6 +1994,9 @@ auth_provider_type_registry = AuthenticationProviderTypeRegistry() permission_manager_type_registry: PermissionManagerTypeRegistry = ( PermissionManagerTypeRegistry() ) +invitation_link_scope_type_registry: InvitationLinkScopeTypeRegistry = ( + InvitationLinkScopeTypeRegistry() +) object_scope_type_registry: ObjectScopeTypeRegistry = ObjectScopeTypeRegistry() last_viewed_item_type_registry: LastViewedItemTypeRegistry = ( LastViewedItemTypeRegistry() diff --git a/backend/tests/baserow/api/groups/test_workspace_invitation_link_views.py b/backend/tests/baserow/api/groups/test_workspace_invitation_link_views.py index 2665c22fb2..6e312f920b 100644 --- a/backend/tests/baserow/api/groups/test_workspace_invitation_link_views.py +++ b/backend/tests/baserow/api/groups/test_workspace_invitation_link_views.py @@ -285,6 +285,9 @@ def test_get_public_workspace_invitation_link(api_client, data_fixture, settings "invited_by": "Bram", "workspace": "Widelab", "workspace_id": workspace.id, + "scope_type": None, + "scope_id": None, + "scope_name": None, "role_upgrade": None, } diff --git a/enterprise/backend/src/baserow_enterprise/api/role/serializers.py b/enterprise/backend/src/baserow_enterprise/api/role/serializers.py index da95ba228b..8221dbf9ff 100644 --- a/enterprise/backend/src/baserow_enterprise/api/role/serializers.py +++ b/enterprise/backend/src/baserow_enterprise/api/role/serializers.py @@ -8,6 +8,7 @@ from rest_framework import serializers from baserow.api.serializers import NaturalKeyRelatedField from baserow.contrib.database.views.registries import view_type_registry +from baserow.core.models import WorkspaceInvitationLink from baserow.core.registries import ( application_type_registry, object_scope_type_registry, @@ -337,6 +338,98 @@ class UpdateScopedInvitationSerializer(serializers.Serializer): raise RoleNotExist() +class ScopedInvitationLinkSerializer(serializers.ModelSerializer): + """ + Serializer of a permanent invitation link that gives a role on one scope, used + for managing them. + """ + + permissions = serializers.CharField( + read_only=True, + help_text="The uid of the role people get on the scope when they join " + "through the link.", + ) + scope_type = ScopeTypeField( + help_text="The scope object type.", + choices=lazy(object_scope_type_registry.get_types, list)(), + ) + + class Meta: + model = WorkspaceInvitationLink + fields = ( + "id", + "workspace", + "name", + "slug", + "permissions", + "scope_id", + "scope_type", + "created_on", + ) + read_only_fields = fields + + +class CreateScopedInvitationLinkSerializer(serializers.Serializer): + name = serializers.CharField( + required=False, + allow_blank=True, + max_length=255, + help_text="A name that reminds the admins what the link is for.", + ) + permissions = RoleField( + model=Role, + required=True, + help_text="The uid of the role people get on the scope when they join " + "through the link.", + ) + scope_id = serializers.IntegerField( + min_value=1, + help_text="The ID of the scope object the link gives a role on.", + ) + scope_type = ScopeTypeField( + help_text="The scope object type.", + choices=lazy(object_scope_type_registry.get_types, list)(), + ) + + def to_internal_value(self, data): + """ + Populate the scope with the actual object. + """ + + try: + result = super().to_internal_value(data) + except Role.DoesNotExist: + raise RoleNotExist() + try: + result["scope"] = result["scope_type"].get_object_for_this_type( + id=result["scope_id"] + ) + except ObjectDoesNotExist: + raise ScopeNotExist() + return result + + +class UpdateScopedInvitationLinkSerializer(serializers.Serializer): + name = serializers.CharField( + required=False, + allow_blank=True, + max_length=255, + help_text="A name that reminds the admins what the link is for.", + ) + permissions = RoleField( + model=Role, + required=False, + help_text="The uid of the role people get on the scope when they join " + "through the link.", + ) + + def to_internal_value(self, data): + try: + return super().to_internal_value(data) + except Role.DoesNotExist: + raise RoleNotExist() + + class EffectiveAccessTeamSerializer(serializers.ModelSerializer): class Meta: model = Team diff --git a/enterprise/backend/src/baserow_enterprise/api/role/urls.py b/enterprise/backend/src/baserow_enterprise/api/role/urls.py index 80e178fce6..a641a8a792 100755 --- a/enterprise/backend/src/baserow_enterprise/api/role/urls.py +++ b/enterprise/backend/src/baserow_enterprise/api/role/urls.py @@ -4,6 +4,8 @@ from .views import ( BatchRoleAssignmentsView, EffectiveAccessView, RoleAssignmentsView, + ScopedInvitationLinksView, + ScopedInvitationLinkView, ScopedInvitationsView, ScopedInvitationView, SubjectRoleAssignmentsView, @@ -42,4 +44,14 @@ urlpatterns = [ ScopedInvitationView.as_view(), name="scoped_invitation", ), + re_path( + r"^(?P[0-9]+)/invitation-links/$", + ScopedInvitationLinksView.as_view(), + name="scoped_invitation_links", + ), + re_path( + r"^invitation-links/(?P[0-9]+)/$", + ScopedInvitationLinkView.as_view(), + name="scoped_invitation_link", + ), ] diff --git a/enterprise/backend/src/baserow_enterprise/api/role/views.py b/enterprise/backend/src/baserow_enterprise/api/role/views.py index 7e5f96c854..3583156430 100755 --- a/enterprise/backend/src/baserow_enterprise/api/role/views.py +++ b/enterprise/backend/src/baserow_enterprise/api/role/views.py @@ -23,16 +23,24 @@ from baserow.api.errors import ( from baserow.api.pagination import LimitOffsetPagination from baserow.api.schemas import get_error_schema from baserow.api.serializers import get_example_pagination_serializer_class +from baserow.api.workspaces.errors import ERROR_INVALID_WORKSPACE_ROLE +from baserow.api.workspaces.invitation_links.errors import ( + ERROR_WORKSPACE_INVITATION_LINK_DOES_NOT_EXIST, + ERROR_WORKSPACE_INVITATION_LINK_SIGNUPS_DISABLED, +) from baserow.api.workspaces.users.errors import ERROR_GROUP_USER_ALREADY_EXISTS from baserow.core.action.registries import action_type_registry from baserow.core.captcha.exceptions import CaptchaVerificationFailed from baserow.core.captcha.handler import CaptchaHandler from baserow.core.exceptions import ( + InvalidWorkspaceRole, LastAdminOfWorkspace, ObjectScopeTypeDoesNotExist, SubjectTypeNotExist, UserNotInWorkspace, WorkspaceDoesNotExist, + WorkspaceInvitationLinkDoesNotExist, + WorkspaceInvitationLinkSignupsDisabled, WorkspaceUserAlreadyExists, ) from baserow.core.handler import CoreHandler @@ -71,8 +79,11 @@ from baserow_enterprise.features import RBAC from baserow_enterprise.role.actions import ( BatchAssignRoleActionType, CreateScopedInvitationActionType, + CreateScopedInvitationLinkActionType, DeleteScopedInvitationActionType, + DeleteScopedInvitationLinkActionType, UpdateScopedInvitationActionType, + UpdateScopedInvitationLinkActionType, ) from baserow_enterprise.role.constants import ROLE_ASSIGNABLE_OBJECT_MAP from baserow_enterprise.role.handler import RoleAssignmentHandler @@ -84,14 +95,17 @@ from .exceptions import DuplicateRoleAssignments from .serializers import ( BatchCreateRoleAssignmentSerializer, CreateRoleAssignmentSerializer, + CreateScopedInvitationLinkSerializer, CreateScopedInvitationSerializer, EffectiveAccessSerializer, GetRoleAssignmentsQueryParametersSerializer, OpenApiRoleAssignmentSerializer, RoleAssignmentSerializer, + ScopedInvitationLinkSerializer, ScopedInvitationSerializer, SubjectRoleAssignmentSerializer, SubjectRoleAssignmentsQueryParametersSerializer, + UpdateScopedInvitationLinkSerializer, UpdateScopedInvitationSerializer, ) @@ -856,3 +870,262 @@ class ScopedInvitationView(APIView): request.user, scoped_invitation ) return Response(status=204) + + +class ScopedInvitationLinksView(APIView): + """Lists and creates permanent invitation links that give a role on one scope.""" + + permission_classes = (IsAuthenticated,) + + @extend_schema( + parameters=[ + OpenApiParameter( + name="workspace_id", + location=OpenApiParameter.PATH, + type=OpenApiTypes.INT, + description="The workspace the scope belongs to.", + ), + OpenApiParameter( + name="scope_id", + location=OpenApiParameter.QUERY, + type=OpenApiTypes.INT, + description="The id of the scope to list the invitation links of.", + ), + OpenApiParameter( + name="scope_type", + location=OpenApiParameter.QUERY, + type=OpenApiTypes.STR, + description="The type of the scope to list the invitation links of.", + ), + ], + tags=["Role assignments"], + operation_id="list_scoped_invitation_links", + description=( + "Lists the permanent invitation links that give a role on the given " + "scope to everyone who joins through them." + ), + responses={ + 200: ScopedInvitationLinkSerializer(many=True), + 400: get_error_schema( + ["ERROR_USER_NOT_IN_GROUP", "ERROR_REQUEST_BODY_VALIDATION"] + ), + 404: get_error_schema( + [ + "ERROR_SCOPE_DOES_NOT_EXIST", + "ERROR_GROUP_DOES_NOT_EXIST", + "ERROR_OBJECT_SCOPE_TYPE_DOES_NOT_EXIST", + ] + ), + }, + ) + @map_exceptions( + { + UserNotInWorkspace: ERROR_USER_NOT_IN_GROUP, + WorkspaceDoesNotExist: ERROR_GROUP_DOES_NOT_EXIST, + ScopeNotExist: ERROR_SCOPE_DOES_NOT_EXIST, + ObjectScopeTypeDoesNotExist: ERROR_OBJECT_SCOPE_TYPE_DOES_NOT_EXIST, + } + ) + @validate_query_parameters( + GetRoleAssignmentsQueryParametersSerializer, return_validated=True + ) + def get( + self, + request: Request, + workspace_id: int, + query_params: Dict[str, Any], + ) -> Response: + workspace = CoreHandler().get_workspace(workspace_id) + scope = query_params["scope"] + + handler = RoleAssignmentHandler() + handler.check_scoped_invitation_permissions( + request.user, workspace, scope, operation="READ" + ) + invitation_links = handler.get_scoped_invitation_links(workspace, scope) + + return Response( + ScopedInvitationLinkSerializer(invitation_links, many=True).data + ) + + @extend_schema( + parameters=[ + OpenApiParameter( + name="workspace_id", + location=OpenApiParameter.PATH, + type=OpenApiTypes.INT, + description="The workspace the scope belongs to.", + ), + ], + tags=["Role assignments"], + operation_id="create_scoped_invitation_link", + description=( + "Creates a permanent invitation link that gives the chosen role on one " + "scope of the workspace. People who aren't a member yet join the " + "workspace without a workspace role. Admins of the workspace and admins " + "of the scope can create them. Links can't be created while both new " + "signups and signups via workspace invitations are disabled." + ), + request=CreateScopedInvitationLinkSerializer, + responses={ + 200: ScopedInvitationLinkSerializer, + 400: get_error_schema( + [ + "ERROR_USER_NOT_IN_GROUP", + "ERROR_REQUEST_BODY_VALIDATION", + "ERROR_WORKSPACE_INVITATION_LINK_SIGNUPS_DISABLED", + "ERROR_INVALID_WORKSPACE_ROLE", + ] + ), + 403: get_error_schema(["ERROR_FEATURE_DISABLED"]), + 404: get_error_schema( + [ + "ERROR_SCOPE_DOES_NOT_EXIST", + "ERROR_GROUP_DOES_NOT_EXIST", + "ERROR_OBJECT_SCOPE_TYPE_DOES_NOT_EXIST", + "ERROR_ROLE_DOES_NOT_EXIST", + ] + ), + }, + ) + @transaction.atomic + @map_exceptions( + { + WorkspaceDoesNotExist: ERROR_GROUP_DOES_NOT_EXIST, + UserNotInWorkspace: ERROR_USER_NOT_IN_GROUP, + ObjectScopeTypeDoesNotExist: ERROR_OBJECT_SCOPE_TYPE_DOES_NOT_EXIST, + ScopeNotExist: ERROR_SCOPE_DOES_NOT_EXIST, + RoleNotExist: ERROR_ROLE_DOES_NOT_EXIST, + InvalidWorkspaceRole: ERROR_INVALID_WORKSPACE_ROLE, + WorkspaceInvitationLinkSignupsDisabled: ( + ERROR_WORKSPACE_INVITATION_LINK_SIGNUPS_DISABLED + ), + } + ) + @validate_body(CreateScopedInvitationLinkSerializer, return_validated=True) + def post(self, request: Request, workspace_id: int, data) -> Response: + workspace = CoreHandler().get_workspace(workspace_id) + invitation_link = action_type_registry.get_by_type( + CreateScopedInvitationLinkActionType + ).do( + request.user, + workspace, + data["scope"], + data["permissions"], + data.get("name", ""), + ) + + return Response(ScopedInvitationLinkSerializer(invitation_link).data) + + +class ScopedInvitationLinkView(APIView): + """Changes or deletes one permanent invitation link to a scope.""" + + permission_classes = (IsAuthenticated,) + + @extend_schema( + parameters=[ + OpenApiParameter( + name="invitation_link_id", + location=OpenApiParameter.PATH, + type=OpenApiTypes.INT, + description="The invitation link to change.", + ), + ], + tags=["Role assignments"], + operation_id="update_scoped_invitation_link", + description=( + "Changes the name of a permanent invitation link to a scope, or the role " + "people get on the scope when they join through it. People who already " + "joined keep their role." + ), + request=UpdateScopedInvitationLinkSerializer, + responses={ + 200: ScopedInvitationLinkSerializer, + 400: get_error_schema( + [ + "ERROR_USER_NOT_IN_GROUP", + "ERROR_REQUEST_BODY_VALIDATION", + "ERROR_INVALID_WORKSPACE_ROLE", + ] + ), + 404: get_error_schema( + [ + "ERROR_WORKSPACE_INVITATION_LINK_DOES_NOT_EXIST", + "ERROR_SCOPE_DOES_NOT_EXIST", + "ERROR_ROLE_DOES_NOT_EXIST", + ] + ), + }, + ) + @transaction.atomic + @map_exceptions( + { + WorkspaceInvitationLinkDoesNotExist: ( + ERROR_WORKSPACE_INVITATION_LINK_DOES_NOT_EXIST + ), + UserNotInWorkspace: ERROR_USER_NOT_IN_GROUP, + ScopeNotExist: ERROR_SCOPE_DOES_NOT_EXIST, + RoleNotExist: ERROR_ROLE_DOES_NOT_EXIST, + InvalidWorkspaceRole: ERROR_INVALID_WORKSPACE_ROLE, + } + ) + @validate_body(UpdateScopedInvitationLinkSerializer, return_validated=True) + def patch(self, request: Request, invitation_link_id: int, data) -> Response: + invitation_link = RoleAssignmentHandler().get_scoped_invitation_link( + invitation_link_id + ) + invitation_link = action_type_registry.get_by_type( + UpdateScopedInvitationLinkActionType + ).do( + request.user, + invitation_link, + role=data.get("permissions"), + name=data.get("name"), + ) + return Response(ScopedInvitationLinkSerializer(invitation_link).data) + + @extend_schema( + parameters=[ + OpenApiParameter( + name="invitation_link_id", + location=OpenApiParameter.PATH, + type=OpenApiTypes.INT, + description="The invitation link to delete.", + ), + ], + tags=["Role assignments"], + operation_id="delete_scoped_invitation_link", + description=( + "Deletes a permanent invitation link to a scope, after which it can't be " + "used anymore. People who joined through it keep their role." + ), + responses={ + 204: None, + 400: get_error_schema(["ERROR_USER_NOT_IN_GROUP"]), + 404: get_error_schema( + [ + "ERROR_WORKSPACE_INVITATION_LINK_DOES_NOT_EXIST", + "ERROR_SCOPE_DOES_NOT_EXIST", + ] + ), + }, + ) + @transaction.atomic + @map_exceptions( + { + WorkspaceInvitationLinkDoesNotExist: ( + ERROR_WORKSPACE_INVITATION_LINK_DOES_NOT_EXIST + ), + UserNotInWorkspace: ERROR_USER_NOT_IN_GROUP, + ScopeNotExist: ERROR_SCOPE_DOES_NOT_EXIST, + } + ) + def delete(self, request: Request, invitation_link_id: int) -> Response: + invitation_link = RoleAssignmentHandler().get_scoped_invitation_link( + invitation_link_id + ) + action_type_registry.get_by_type(DeleteScopedInvitationLinkActionType).do( + request.user, invitation_link + ) + return Response(status=204) diff --git a/enterprise/backend/src/baserow_enterprise/apps.py b/enterprise/backend/src/baserow_enterprise/apps.py index 6fb1562ca7..a5f45ea236 100755 --- a/enterprise/backend/src/baserow_enterprise/apps.py +++ b/enterprise/backend/src/baserow_enterprise/apps.py @@ -155,8 +155,11 @@ class BaserowEnterpriseConfig(AppConfig): from baserow_enterprise.role.actions import ( BatchAssignRoleActionType, CreateScopedInvitationActionType, + CreateScopedInvitationLinkActionType, DeleteScopedInvitationActionType, + DeleteScopedInvitationLinkActionType, UpdateScopedInvitationActionType, + UpdateScopedInvitationLinkActionType, ) from baserow_enterprise.scopes import TeamsActionScopeType from baserow_enterprise.teams.actions import ( @@ -230,6 +233,9 @@ class BaserowEnterpriseConfig(AppConfig): action_type_registry.register(CreateScopedInvitationActionType()) action_type_registry.register(UpdateScopedInvitationActionType()) action_type_registry.register(DeleteScopedInvitationActionType()) + action_type_registry.register(CreateScopedInvitationLinkActionType()) + action_type_registry.register(UpdateScopedInvitationLinkActionType()) + action_type_registry.register(DeleteScopedInvitationLinkActionType()) action_type_registry.register(UpdateFieldPermissionsActionType()) trash_item_type_registry.register(TeamTrashableItemType()) @@ -286,6 +292,17 @@ class BaserowEnterpriseConfig(AppConfig): permission_manager_type_registry.register(FieldPermissionManagerType()) permission_manager_type_registry.register(RolePermissionManagerType()) + from baserow.core.registries import invitation_link_scope_type_registry + + from .role.constants import ROLE_ASSIGNABLE_OBJECT_MAP + from .role.invitation_link_scope_types import RoleInvitationLinkScopeType + + for scope_type_name in ROLE_ASSIGNABLE_OBJECT_MAP: + if scope_type_name != "workspace": + invitation_link_scope_type_registry.register( + RoleInvitationLinkScopeType(scope_type_name) + ) + from baserow_enterprise.license_types import ( AdvancedLicenseType, EnterpriseLicenseType, diff --git a/enterprise/backend/src/baserow_enterprise/locale/en/LC_MESSAGES/django.po b/enterprise/backend/src/baserow_enterprise/locale/en/LC_MESSAGES/django.po index db3f976be6..07123c235f 100644 --- a/enterprise/backend/src/baserow_enterprise/locale/en/LC_MESSAGES/django.po +++ b/enterprise/backend/src/baserow_enterprise/locale/en/LC_MESSAGES/django.po @@ -567,6 +567,42 @@ msgid "" "revoked." msgstr "" +#: src/baserow_enterprise/role/actions.py:413 +msgid "Create scoped invitation link" +msgstr "" + +#: src/baserow_enterprise/role/actions.py:415 +#, python-format +msgid "" +"Invitation link (%(invitation_link_id)s) created to join \"%(group_name)s\" " +"(%(group_id)s) as %(role_uid)s on \"%(scope_type_name)s\" (%(scope_id)s)." +msgstr "" + +#: src/baserow_enterprise/role/actions.py:480 +msgid "Update scoped invitation link" +msgstr "" + +#: src/baserow_enterprise/role/actions.py:482 +#, python-format +msgid "" +"Invitation link (%(invitation_link_id)s) to join \"%(group_name)s\" " +"(%(group_id)s) on \"%(scope_type_name)s\" (%(scope_id)s) changed from " +"\"%(original_name)s\" as %(original_role_uid)s to \"%(name)s\" as " +"%(role_uid)s." +msgstr "" + +#: src/baserow_enterprise/role/actions.py:554 +msgid "Delete scoped invitation link" +msgstr "" + +#: src/baserow_enterprise/role/actions.py:556 +#, python-format +msgid "" +"Invitation link \"%(name)s\" (%(invitation_link_id)s) to join " +"\"%(group_name)s\" (%(group_id)s) as %(role_uid)s on \"%(scope_type_name)s\" " +"(%(scope_id)s) deleted." +msgstr "" + #: src/baserow_enterprise/teams/actions.py:21 #, python-format msgid "in team \"%(team_name)s\" (%(team_id)s) " diff --git a/enterprise/backend/src/baserow_enterprise/role/actions.py b/enterprise/backend/src/baserow_enterprise/role/actions.py index 8bf0e06769..66c1ace00f 100755 --- a/enterprise/backend/src/baserow_enterprise/role/actions.py +++ b/enterprise/backend/src/baserow_enterprise/role/actions.py @@ -1,5 +1,5 @@ import dataclasses -from typing import Any, Dict, List, Optional +from typing import Any, Dict, List, Optional, Union from django.contrib.auth.models import AbstractUser from django.utils.translation import gettext_lazy as _ @@ -10,7 +10,7 @@ from baserow.core.action.registries import ( ActionTypeDescription, ) from baserow.core.action.scopes import RootActionScopeType, WorkspaceActionScopeType -from baserow.core.models import Workspace +from baserow.core.models import Workspace, WorkspaceInvitationLink from baserow.core.registries import object_scope_type_registry, subject_type_registry from baserow.core.types import ScopeObject from baserow_enterprise.role.handler import RoleAssignmentHandler @@ -321,10 +321,212 @@ class DeleteScopedInvitationActionType(ActionType): return RootActionScopeType.value() -def _scope_type_name(scoped_invitation: WorkspaceScopedInvitation) -> str: +class CreateScopedInvitationLinkActionType(ActionType): + type = "create_scoped_invitation_link" + description = ActionTypeDescription( + _("Create scoped invitation link"), + _( + "Invitation link (%(invitation_link_id)s) created to join " + '"%(group_name)s" (%(group_id)s) as %(role_uid)s on "%(scope_type_name)s" ' + "(%(scope_id)s)." + ), + ) + analytics_params = [ + "invitation_link_id", + "workspace_id", + "role_uid", + "scope_type_name", + ] + + @dataclasses.dataclass + class Params: + invitation_link_id: int + role_uid: str + scope_type_name: str + scope_id: int + workspace_id: int + workspace_name: str + name: str = "" + + @classmethod + def do( + cls, + user: AbstractUser, + workspace: Workspace, + scope: ScopeObject, + role: Role, + name: str = "", + ) -> WorkspaceInvitationLink: + """ + Creates a permanent link to join the workspace with a role on one of its + scopes. Look into `RoleAssignmentHandler.create_scoped_invitation_link` for + further details. + """ + + invitation_link = RoleAssignmentHandler().create_scoped_invitation_link( + user, workspace, scope, role, name + ) + + cls.register_action( + user=user, + params=cls.Params( + invitation_link.id, + role.uid, + object_scope_type_registry.get_by_model(scope).type, + scope.id, + workspace.id, + workspace.name, + name, + ), + scope=cls.scope(), + workspace=workspace, + ) + return invitation_link + + @classmethod + def scope(cls) -> ActionScopeStr: + return RootActionScopeType.value() + + +class UpdateScopedInvitationLinkActionType(ActionType): + type = "update_scoped_invitation_link" + description = ActionTypeDescription( + _("Update scoped invitation link"), + _( + "Invitation link (%(invitation_link_id)s) to join " + '"%(group_name)s" (%(group_id)s) on "%(scope_type_name)s" (%(scope_id)s) ' + 'changed from "%(original_name)s" as %(original_role_uid)s to ' + '"%(name)s" as %(role_uid)s.' + ), + ) + analytics_params = [ + "invitation_link_id", + "workspace_id", + "role_uid", + "original_role_uid", + "scope_type_name", + ] + + @dataclasses.dataclass + class Params: + invitation_link_id: int + role_uid: str + original_role_uid: str + name: str + original_name: str + scope_type_name: str + scope_id: int + workspace_id: int + workspace_name: str + + @classmethod + def do( + cls, + user: AbstractUser, + invitation_link: WorkspaceInvitationLink, + role: Optional[Role] = None, + name: Optional[str] = None, + ) -> WorkspaceInvitationLink: + """ + Changes the name of a link to a scope or the role it gives. Look into + `RoleAssignmentHandler.update_scoped_invitation_link` for further details. + """ + + workspace = invitation_link.workspace + original_role_uid = invitation_link.permissions + original_name = invitation_link.name + invitation_link = RoleAssignmentHandler().update_scoped_invitation_link( + user, invitation_link, role=role, name=name + ) + + cls.register_action( + user=user, + params=cls.Params( + invitation_link.id, + invitation_link.permissions, + original_role_uid, + invitation_link.name, + original_name, + _scope_type_name(invitation_link), + invitation_link.scope_id, + workspace.id, + workspace.name, + ), + scope=cls.scope(), + workspace=workspace, + ) + return invitation_link + + @classmethod + def scope(cls) -> ActionScopeStr: + return RootActionScopeType.value() + + +class DeleteScopedInvitationLinkActionType(ActionType): + type = "delete_scoped_invitation_link" + description = ActionTypeDescription( + _("Delete scoped invitation link"), + _( + 'Invitation link "%(name)s" (%(invitation_link_id)s) to join ' + '"%(group_name)s" (%(group_id)s) as %(role_uid)s on "%(scope_type_name)s" ' + "(%(scope_id)s) deleted." + ), + ) + analytics_params = [ + "invitation_link_id", + "workspace_id", + "role_uid", + "scope_type_name", + ] + + @dataclasses.dataclass + class Params: + invitation_link_id: int + role_uid: str + scope_type_name: str + scope_id: int + workspace_id: int + workspace_name: str + name: str = "" + + @classmethod + def do(cls, user: AbstractUser, invitation_link: WorkspaceInvitationLink): + """ + Deletes a link to a scope. Look into + `RoleAssignmentHandler.delete_scoped_invitation_link` for further details. + """ + + workspace = invitation_link.workspace + params = cls.Params( + invitation_link.id, + invitation_link.permissions, + _scope_type_name(invitation_link), + invitation_link.scope_id, + workspace.id, + workspace.name, + invitation_link.name, + ) + RoleAssignmentHandler().delete_scoped_invitation_link(user, invitation_link) + + cls.register_action( + user=user, + params=params, + scope=cls.scope(), + workspace=workspace, + ) + + @classmethod + def scope(cls) -> ActionScopeStr: + return RootActionScopeType.value() + + +def _scope_type_name( + scoped_invitation: Union[WorkspaceScopedInvitation, WorkspaceInvitationLink], +) -> str: """ - The object scope type name of the scope an invitation grants a role on, read - from the content type so that it is known even when the scope is gone. + The object scope type name of the scope an invitation or an invitation link + grants a role on, read from the content type so that it is known even when the + scope is gone. """ return object_scope_type_registry.get_by_model( diff --git a/enterprise/backend/src/baserow_enterprise/role/handler.py b/enterprise/backend/src/baserow_enterprise/role/handler.py index 3141ef9304..e44112c02b 100755 --- a/enterprise/backend/src/baserow_enterprise/role/handler.py +++ b/enterprise/backend/src/baserow_enterprise/role/handler.py @@ -16,10 +16,20 @@ from django.db.models import ( ) from baserow.core.cache import local_cache -from baserow.core.exceptions import PermissionDenied +from baserow.core.exceptions import ( + InvalidWorkspaceRole, + PermissionDenied, + WorkspaceInvitationLinkSignupsDisabled, +) +from baserow.core.feature_flags import FF_RBAC_IMPROVEMENTS, feature_flag_is_enabled from baserow.core.handler import CoreHandler from baserow.core.mixins import TrashableModelMixin -from baserow.core.models import Workspace, WorkspaceInvitation, WorkspaceUser +from baserow.core.models import ( + Workspace, + WorkspaceInvitation, + WorkspaceInvitationLink, + WorkspaceUser, +) from baserow.core.object_scopes import CoreObjectScopeType, WorkspaceObjectScopeType from baserow.core.registries import ( ObjectScopeType, @@ -1790,11 +1800,13 @@ class RoleAssignmentHandler: ) def _get_live_scope( - self, scoped_invitation: WorkspaceScopedInvitation + self, + scoped_invitation: Union[WorkspaceScopedInvitation, WorkspaceInvitationLink], ) -> ScopeObject: """ - Returns the scope of a scoped invitation, or raises when it was deleted or - trashed in the meantime, because nothing can be managed on it anymore. + Returns the scope of a scoped invitation or invitation link, or raises when + it was deleted or trashed in the meantime, because nothing can be managed on + it anymore. """ scope = scoped_invitation.scope @@ -1959,3 +1971,198 @@ class RoleAssignmentHandler: return [] return self.assign_role_batch(invitation.workspace, new_role_assignments) + + def get_scoped_invitation_links( + self, workspace: Workspace, scope: ScopeObject + ) -> QuerySet[WorkspaceInvitationLink]: + """ + Returns the permanent invitation links that give a role on the given scope. + + :param workspace: The workspace the scope belongs to. + :param scope: The scope the links give a role on. + :return: The invitation links of the scope. + """ + + return WorkspaceInvitationLink.objects.filter( + workspace=workspace, + scope_type=ContentType.objects.get_for_model(scope), + scope_id=scope.id, + ) + + def get_scoped_invitation_link( + self, invitation_link_id: int + ) -> WorkspaceInvitationLink: + """ + Returns the permanent invitation link with the given id that gives a role on + a scope of its workspace. + + :param invitation_link_id: The id of the invitation link. + :raises WorkspaceInvitationLinkDoesNotExist: If there is no such link. + :return: The invitation link. + """ + + return CoreHandler().get_workspace_invitation_link( + invitation_link_id, + base_queryset=WorkspaceInvitationLink.objects.filter( + scope_type__isnull=False + ).select_related("scope_type"), + ) + + def is_supported_invitation_link_scope(self, scope: ScopeObject) -> bool: + """Only restricted views support loading rows with a view-level role.""" + + from baserow_enterprise.view_ownership_types import RestrictedViewOwnershipType + + scope_type = object_scope_type_registry.get_by_model(scope) + return scope_type.type != "database_view" or ( + scope.ownership_type == RestrictedViewOwnershipType.type + ) + + def _validate_scoped_invitation_link_role(self, role: Role, workspace: Workspace): + """Validate workspace availability and require a role granting scoped access.""" + + CoreHandler().raise_if_invalid_workspace_role(role.uid, workspace) + if role.uid in (NO_ACCESS_ROLE_UID, NO_ROLE_LOW_PRIORITY_ROLE_UID): + raise InvalidWorkspaceRole( + f"The role {role.uid} cannot grant access through a scoped invitation link." + ) + + def create_scoped_invitation_link( + self, + user: AbstractUser, + workspace: Workspace, + scope: ScopeObject, + role: Role, + name: str = "", + ) -> WorkspaceInvitationLink: + """ + Creates a permanent link that anyone can use to join the workspace and get + the given role on the scope. People who aren't a member yet join without a + workspace role. Admins of the workspace and admins of the scope can create + them. + + :param user: The user on whose behalf the link is created. + :param workspace: The workspace the scope belongs to. + :param scope: The application, table or view the link gives a role on. + :param role: The role people get on the scope when they join. + :param name: A name that reminds the admins what the link is for. + :raises FeatureDisabledException: If invitation links aren't enabled. + :raises ScopeNotExist: If the scope can't get a role through a link. + :raises InvalidWorkspaceRole: If the role is unavailable or grants no access. + :raises PermissionDenied: If the user can't manage the roles of the scope. + :raises WorkspaceInvitationLinkSignupsDisabled: If the instance settings + don't let anyone sign up through the link. + :return: The created invitation link. + """ + + feature_flag_is_enabled(FF_RBAC_IMPROVEMENTS, raise_if_disabled=True) + + self.check_scoped_invitation_permissions(user, workspace, scope) + + if not self.is_supported_invitation_link_scope(scope): + raise ScopeNotExist() + self._validate_scoped_invitation_link_role(role, workspace) + + if not CoreHandler().invitation_link_signups_allowed(): + raise WorkspaceInvitationLinkSignupsDisabled( + "Invitation links can't be created while signups are disabled." + ) + + return WorkspaceInvitationLink.objects.create( + workspace=workspace, + created_by=user, + permissions=role.uid, + name=name, + scope=scope, + ) + + def update_scoped_invitation_link( + self, + user: AbstractUser, + invitation_link: WorkspaceInvitationLink, + role: Optional[Role] = None, + name: Optional[str] = None, + ) -> WorkspaceInvitationLink: + """ + Changes the name of a link to a scope or the role people get on the scope + when joining through it. People who already joined keep their role. + + :param user: The user on whose behalf the link is updated. + :param invitation_link: The link that must be updated. + :param role: The new role of the link, if it changes. + :param name: The new name of the link, if it changes. + :raises ScopeNotExist: If the scope was deleted or trashed in the meantime. + :raises InvalidWorkspaceRole: If the role is unavailable or grants no access. + :raises PermissionDenied: If the user can't manage the roles of the scope. + :return: The updated invitation link. + """ + + scope = self._get_live_scope(invitation_link) + self.check_scoped_invitation_permissions(user, invitation_link.workspace, scope) + + update_fields = ["updated_on"] + if role is not None: + if not self.is_supported_invitation_link_scope(scope): + raise ScopeNotExist() + self._validate_scoped_invitation_link_role(role, invitation_link.workspace) + invitation_link.permissions = role.uid + update_fields.append("permissions") + if name is not None: + invitation_link.name = name + update_fields.append("name") + invitation_link.save(update_fields=update_fields) + + return invitation_link + + def delete_scoped_invitation_link( + self, user: AbstractUser, invitation_link: WorkspaceInvitationLink + ): + """ + Deletes a link to a scope, after which it can't be used anymore. People who + joined through it keep their role. + + :param user: The user on whose behalf the link is deleted. + :param invitation_link: The link that must be deleted. + :raises ScopeNotExist: If the scope was deleted or trashed in the meantime. + :raises PermissionDenied: If the user can't manage the roles of the scope. + """ + + scope = self._get_live_scope(invitation_link) + self.check_scoped_invitation_permissions(user, invitation_link.workspace, scope) + + invitation_link.delete() + + def get_role_raised_by_invitation_link( + self, user: AbstractUser, invitation_link: WorkspaceInvitationLink + ) -> Optional[str]: + """ + Returns the role a member currently has on the scope of a link, resolved like + the permission checks do, if the role of the link gives them everything that + role does and more. A role that lacks any operation of the current one never + replaces it, so a link can't lower anyone's access. + + :param user: A member of the workspace of the link. + :param invitation_link: A link that gives a role on a scope. + :return: The uid of the current role on the scope, or None if the link + wouldn't raise it. + """ + + try: + link_role = self.get_role_by_uid(invitation_link.permissions) + except Role.DoesNotExist: + return None + + roles_per_scope = self.get_roles_per_scope(invitation_link.workspace, user) + current_roles = self.get_computed_roles(roles_per_scope, invitation_link.scope) + current_operations = { + operation.name + for role in current_roles + for operation in role.operations.all() + } + link_operations = {operation.name for operation in link_role.operations.all()} + + if not link_operations > current_operations: + return None + if not current_operations: + return NO_ACCESS_ROLE_UID + return current_roles[0].uid diff --git a/enterprise/backend/src/baserow_enterprise/role/invitation_link_scope_types.py b/enterprise/backend/src/baserow_enterprise/role/invitation_link_scope_types.py new file mode 100644 index 0000000000..87f61d38d3 --- /dev/null +++ b/enterprise/backend/src/baserow_enterprise/role/invitation_link_scope_types.py @@ -0,0 +1,51 @@ +from django.contrib.auth.models import AbstractUser + +from baserow.core.models import WorkspaceInvitationLink +from baserow.core.registries import InvitationLinkScopeType +from baserow.core.trash.handler import TrashHandler +from baserow_enterprise.features import RBAC +from baserow_premium.license.handler import LicenseHandler + +from .constants import NO_ROLE_LOW_PRIORITY_ROLE_UID +from .handler import RoleAssignmentHandler + + +class RoleInvitationLinkScopeType(InvitationLinkScopeType): + """ + Lets an invitation link give a role on an application, a table or a view through + a role assignment, like the role a member is given on it in the share dialog. + One is registered for every object scope type a role can be assigned on. + """ + + def __init__(self, scope_type_name: str): + self.type = scope_type_name + super().__init__() + + def is_usable(self, invitation_link: WorkspaceInvitationLink) -> bool: + if not LicenseHandler.workspace_has_feature(RBAC, invitation_link.workspace): + return False + scope = invitation_link.scope + return ( + scope is not None + and RoleAssignmentHandler().is_supported_invitation_link_scope(scope) + and not TrashHandler.item_has_a_trashed_parent(scope, check_item_also=True) + ) + + def get_newcomer_permissions(self, invitation_link: WorkspaceInvitationLink) -> str: + return NO_ROLE_LOW_PRIORITY_ROLE_UID + + def get_raised_role( + self, user: AbstractUser, invitation_link: WorkspaceInvitationLink + ): + return RoleAssignmentHandler().get_role_raised_by_invitation_link( + user, invitation_link + ) + + def give_role(self, user: AbstractUser, invitation_link: WorkspaceInvitationLink): + handler = RoleAssignmentHandler() + handler.assign_role( + user, + invitation_link.workspace, + role=handler.get_role_by_uid(invitation_link.permissions), + scope=invitation_link.scope, + ) diff --git a/enterprise/backend/src/baserow_enterprise/role/receivers.py b/enterprise/backend/src/baserow_enterprise/role/receivers.py index 160b1a8d80..a1f5e51dcd 100755 --- a/enterprise/backend/src/baserow_enterprise/role/receivers.py +++ b/enterprise/backend/src/baserow_enterprise/role/receivers.py @@ -114,9 +114,12 @@ def cascade_workspace_user_delete(sender, instance, **kwargs): def cascade_scope_delete(sender, instance, **kwargs): """ - Delete role assignments and pending scoped invitations linked to deleted scope. + Delete role assignments, pending scoped invitations and invitation links linked + to deleted scope. """ + from baserow.core.models import WorkspaceInvitationLink + from .models import RoleAssignment, WorkspaceScopedInvitation scope_ct = ContentType.objects.get_for_model(instance) @@ -124,6 +127,9 @@ def cascade_scope_delete(sender, instance, **kwargs): WorkspaceScopedInvitation.objects.filter( scope_id=instance.id, scope_type=scope_ct ).delete() + WorkspaceInvitationLink.objects.filter( + scope_id=instance.id, scope_type=scope_ct + ).delete() def connect_to_post_delete_signals_to_cascade_deletion_to_role_assignments(): diff --git a/enterprise/backend/tests/baserow_enterprise_tests/integrations/common/oauth2/test_common_oauth2_views.py b/enterprise/backend/tests/baserow_enterprise_tests/integrations/common/oauth2/test_common_oauth2_views.py index c866ad5d13..83a3053202 100644 --- a/enterprise/backend/tests/baserow_enterprise_tests/integrations/common/oauth2/test_common_oauth2_views.py +++ b/enterprise/backend/tests/baserow_enterprise_tests/integrations/common/oauth2/test_common_oauth2_views.py @@ -7,6 +7,7 @@ from urllib.parse import parse_qsl, urlparse from django.conf import settings from django.contrib.contenttypes.models import ContentType +from django.db.models import Max from django.test.utils import override_settings from django.urls import reverse from django.utils.timezone import now @@ -15,6 +16,8 @@ import pytest import responses from rest_framework.status import HTTP_302_FOUND, HTTP_404_NOT_FOUND +from baserow.core.app_auth_providers.models import AppAuthProvider +from baserow.core.auth_provider.models import AuthProviderModel from baserow.core.auth_provider.types import UserInfo from baserow.core.cache import global_cache from baserow.core.registries import plugin_registry @@ -25,6 +28,7 @@ from baserow_enterprise.integrations.common.sso.oauth2.app_auth_provider_types i from baserow_enterprise.integrations.common.sso.oauth2.models import ( OpenIdConnectAppAuthProviderModel, ) +from baserow_enterprise.sso.oauth2.models import OpenIdConnectAuthProviderModel from baserow_premium.application_user_usage.constants import ( DEFAULT_APPLICATION_USERS_LIMIT, ) @@ -532,7 +536,20 @@ def builder_and_core_providers_with_the_same_id( id, and both have the `openid_connect` type. """ + data = populate_local_baserow_test_data(data_fixture) + user_source = data["user_source"] + # The builder fixture creates password providers, so choose an id unused by + # either parent table before creating the two providers with the same id. + shared_id = ( + max( + AuthProviderModel.objects.aggregate(value=Max("id"))["value"] or 0, + AppAuthProvider.objects.aggregate(value=Max("id"))["value"] or 0, + ) + + 1 + ) core_provider = enterprise_data_fixture.create_oauth_provider( + id=shared_id, + content_type=ContentType.objects.get_for_model(OpenIdConnectAuthProviderModel), type="openid_connect", client_id="clientid", secret="secret", @@ -541,8 +558,6 @@ def builder_and_core_providers_with_the_same_id( access_token_url="https://core-idp.example.com/token", user_info_url="https://core-idp.example.com/userinfo", ) - data = populate_local_baserow_test_data(data_fixture) - user_source = data["user_source"] builder_provider = OpenIdConnectAppAuthProviderModel.objects.create( id=core_provider.id, content_type=ContentType.objects.get_for_model( diff --git a/enterprise/backend/tests/baserow_enterprise_tests/role/test_scoped_invitation_links.py b/enterprise/backend/tests/baserow_enterprise_tests/role/test_scoped_invitation_links.py new file mode 100644 index 0000000000..fa8b2d89ce --- /dev/null +++ b/enterprise/backend/tests/baserow_enterprise_tests/role/test_scoped_invitation_links.py @@ -0,0 +1,786 @@ +from unittest.mock import patch + +from django.contrib.contenttypes.models import ContentType +from django.shortcuts import reverse + +import pytest +from rest_framework.status import ( + HTTP_200_OK, + HTTP_204_NO_CONTENT, + HTTP_400_BAD_REQUEST, + HTTP_401_UNAUTHORIZED, + HTTP_404_NOT_FOUND, +) + +from baserow.contrib.database.table.operations import ReadDatabaseTableOperationType +from baserow.core.actions import JoinWorkspaceViaInvitationLinkActionType +from baserow.core.exceptions import ( + FeatureDisabledException, + InvalidWorkspaceRole, + PermissionDenied, + WorkspaceInvitationLinkDoesNotExist, + WorkspaceInvitationLinkSignupsDisabled, +) +from baserow.core.handler import CoreHandler +from baserow.core.models import WorkspaceInvitationLink, WorkspaceUser +from baserow.core.trash.handler import TrashHandler +from baserow.core.user.handler import UserHandler +from baserow_enterprise.exceptions import ScopeNotExist +from baserow_enterprise.role.actions import ( + CreateScopedInvitationLinkActionType, + DeleteScopedInvitationLinkActionType, + UpdateScopedInvitationLinkActionType, +) +from baserow_enterprise.role.constants import NO_ROLE_LOW_PRIORITY_ROLE_UID +from baserow_enterprise.role.handler import RoleAssignmentHandler +from baserow_enterprise.role.models import Role, RoleAssignment +from baserow_premium.license.handler import LicenseHandler + + +@pytest.fixture(autouse=True) +def enable_enterprise_and_roles_for_all_tests_here(enable_enterprise, synced_roles): + pass + + +def setup_workspace(data_fixture): + admin = data_fixture.create_user() + workspace = data_fixture.create_workspace(user=admin) + database = data_fixture.create_database_application(workspace=workspace) + table_a = data_fixture.create_database_table(database=database, user=admin) + table_b = data_fixture.create_database_table(database=database, user=admin) + return admin, workspace, database, table_a, table_b + + +def role(uid): + return Role.objects.get(uid=uid) + + +def add_member(data_fixture, workspace, permissions): + member = data_fixture.create_user() + data_fixture.create_user_workspace( + workspace=workspace, user=member, permissions=permissions + ) + return member + + +def create_link(admin, workspace, scope, role_uid, name=""): + return RoleAssignmentHandler().create_scoped_invitation_link( + admin, workspace, scope, role(role_uid), name + ) + + +def role_on(user, scope): + assignment = RoleAssignment.objects.filter( + subject_id=user.id, + scope_id=scope.id, + scope_type=ContentType.objects.get_for_model(scope), + ).first() + return assignment.role.uid if assignment else None + + +def can_read_table(user, workspace, table): + try: + CoreHandler().check_permissions( + user, + ReadDatabaseTableOperationType.type, + workspace=workspace, + context=table, + ) + except PermissionDenied: + return False + return True + + +@pytest.mark.django_db +def test_workspace_and_object_admins_can_create_links_to_the_object(data_fixture): + admin, workspace, _, table_a, table_b = setup_workspace(data_fixture) + table_admin = add_member(data_fixture, workspace, NO_ROLE_LOW_PRIORITY_ROLE_UID) + table_editor = add_member(data_fixture, workspace, NO_ROLE_LOW_PRIORITY_ROLE_UID) + handler = RoleAssignmentHandler() + handler.assign_role(table_admin, workspace, role("ADMIN"), table_a) + handler.assign_role(table_editor, workspace, role("EDITOR"), table_a) + + by_workspace_admin = create_link(admin, workspace, table_a, "EDITOR", "Sales") + by_table_admin = create_link(table_admin, workspace, table_a, "ADMIN") + + with pytest.raises(PermissionDenied): + create_link(table_editor, workspace, table_a, "VIEWER") + with pytest.raises(PermissionDenied): + create_link(table_admin, workspace, table_b, "VIEWER") + + assert by_workspace_admin.scope == table_a + assert by_workspace_admin.permissions == "EDITOR" + assert by_workspace_admin.name == "Sales" + assert by_table_admin.created_by == table_admin + assert list(handler.get_scoped_invitation_links(workspace, table_a)) == [ + by_workspace_admin, + by_table_admin, + ] + assert list(handler.get_scoped_invitation_links(workspace, table_b)) == [] + + +@pytest.mark.django_db +def test_create_link_to_object_requires_feature_flag_and_signups( + data_fixture, settings +): + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + + settings.FEATURE_FLAGS = [] + with pytest.raises(FeatureDisabledException): + create_link(admin, workspace, table_a, "EDITOR") + + settings.FEATURE_FLAGS = "*" + data_fixture.update_settings( + allow_new_signups=False, allow_signups_via_workspace_invitations=False + ) + with pytest.raises(WorkspaceInvitationLinkSignupsDisabled): + create_link(admin, workspace, table_a, "EDITOR") + + assert WorkspaceInvitationLink.objects.count() == 0 + + +@pytest.mark.django_db +def test_links_to_objects_are_not_workspace_links(data_fixture): + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + workspace_link = data_fixture.create_workspace_invitation_link( + workspace=workspace, created_by=admin, permissions="MEMBER" + ) + table_link = create_link(admin, workspace, table_a, "EDITOR") + + assert list(CoreHandler().list_workspace_invitation_links(admin, workspace)) == [ + workspace_link + ] + with pytest.raises(WorkspaceInvitationLinkDoesNotExist): + CoreHandler().get_workspace_invitation_link(table_link.id) + with pytest.raises(WorkspaceInvitationLinkDoesNotExist): + RoleAssignmentHandler().get_scoped_invitation_link(workspace_link.id) + + +@pytest.mark.django_db +def test_newcomer_joins_with_the_role_of_the_link_on_the_object_only(data_fixture): + admin, workspace, _, table_a, table_b = setup_workspace(data_fixture) + newcomer = data_fixture.create_user() + table_link = create_link(admin, workspace, table_a, "EDITOR") + + workspace_user = CoreHandler().join_workspace_via_invitation_link( + newcomer, table_link + ) + + assert workspace_user.permissions == NO_ROLE_LOW_PRIORITY_ROLE_UID + assert role_on(newcomer, table_a) == "EDITOR" + assert can_read_table(newcomer, workspace, table_a) + assert not can_read_table(newcomer, workspace, table_b) + + +@pytest.mark.django_db +def test_signing_up_through_a_link_to_an_object(data_fixture): + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + table_link = create_link(admin, workspace, table_a, "COMMENTER") + + user = UserHandler().create_user( + "Newcomer", + "newcomer@example.com", + "password", + workspace_invitation_link_slug=table_link.slug, + ) + + assert ( + WorkspaceUser.objects.get(user=user, workspace=workspace).permissions + == NO_ROLE_LOW_PRIORITY_ROLE_UID + ) + assert role_on(user, table_a) == "COMMENTER" + + +@pytest.mark.django_db +@pytest.mark.parametrize( + "database_role_uid,link_role_uid,expected_raised_from,expected_table_role_uid", + [ + # The role on the table comes from the database, Builder already has + # everything a Commenter has. + ("BUILDER", "COMMENTER", None, None), + # Commenter is a Viewer who can also comment, so it's raised on the table. + ("VIEWER", "COMMENTER", "VIEWER", "COMMENTER"), + ("EDITOR", "EDITOR", None, None), + ("NO_ACCESS", "VIEWER", "NO_ACCESS", "VIEWER"), + ], +) +def test_link_raises_the_inherited_role_on_the_object_but_never_lowers_it( + data_fixture, + database_role_uid, + link_role_uid, + expected_raised_from, + expected_table_role_uid, +): + admin, workspace, database, table_a, _ = setup_workspace(data_fixture) + member = add_member(data_fixture, workspace, NO_ROLE_LOW_PRIORITY_ROLE_UID) + RoleAssignmentHandler().assign_role( + member, workspace, role(database_role_uid), database.application_ptr + ) + table_link = create_link(admin, workspace, table_a, link_role_uid) + + assert ( + CoreHandler().get_permissions_raised_by_invitation_link(member, table_link) + == expected_raised_from + ) + + CoreHandler().join_workspace_via_invitation_link(member, table_link) + + assert role_on(member, table_a) == expected_table_role_uid + assert role_on(member, database.application_ptr) == database_role_uid + assert ( + WorkspaceUser.objects.get(user=member).permissions + == NO_ROLE_LOW_PRIORITY_ROLE_UID + ) + + +@pytest.mark.django_db +@pytest.mark.parametrize( + "workspace_role_uid,link_role_uid,expected_table_role_uid", + [ + ("ADMIN", "EDITOR", None), + ("BUILDER", "ADMIN", "ADMIN"), + ("VIEWER", "EDITOR", "EDITOR"), + ("EDITOR", "VIEWER", None), + ], +) +def test_link_to_object_compares_with_the_workspace_role_and_keeps_it( + data_fixture, workspace_role_uid, link_role_uid, expected_table_role_uid +): + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + member = add_member(data_fixture, workspace, workspace_role_uid) + table_link = create_link(admin, workspace, table_a, link_role_uid) + + CoreHandler().join_workspace_via_invitation_link(member, table_link) + + assert role_on(member, table_a) == expected_table_role_uid + assert WorkspaceUser.objects.get(user=member).permissions == workspace_role_uid + + +@pytest.mark.django_db +def test_link_to_object_lifts_no_access_set_on_that_object(data_fixture): + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + member = add_member(data_fixture, workspace, "EDITOR") + RoleAssignmentHandler().assign_role(member, workspace, role("NO_ACCESS"), table_a) + table_link = create_link(admin, workspace, table_a, "VIEWER") + + assert ( + CoreHandler().get_permissions_raised_by_invitation_link(member, table_link) + == "NO_ACCESS" + ) + CoreHandler().join_workspace_via_invitation_link(member, table_link) + + assert role_on(member, table_a) == "VIEWER" + + +@pytest.mark.django_db +def test_link_to_object_raises_a_role_given_through_a_team( + data_fixture, enterprise_data_fixture +): + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + member = add_member(data_fixture, workspace, NO_ROLE_LOW_PRIORITY_ROLE_UID) + team = enterprise_data_fixture.create_team(workspace=workspace, members=[member]) + RoleAssignmentHandler().assign_role(team, workspace, role("EDITOR"), table_a) + viewer_link = create_link(admin, workspace, table_a, "VIEWER") + admin_link = create_link(admin, workspace, table_a, "ADMIN") + + CoreHandler().join_workspace_via_invitation_link(member, viewer_link) + assert role_on(member, table_a) is None + + CoreHandler().join_workspace_via_invitation_link(member, admin_link) + assert role_on(member, table_a) == "ADMIN" + + +@pytest.mark.django_db +def test_link_to_trashed_or_deleted_object_cannot_be_used(data_fixture): + admin, workspace, database, table_a, table_b = setup_workspace(data_fixture) + table_link = create_link(admin, workspace, table_a, "EDITOR") + other_link = create_link(admin, workspace, table_b, "EDITOR") + + assert CoreHandler().get_workspace_invitation_link_by_slug(table_link.slug) + + TrashHandler.trash(admin, workspace, database, table_a) + with pytest.raises(WorkspaceInvitationLinkDoesNotExist): + CoreHandler().get_workspace_invitation_link_by_slug(table_link.slug) + + TrashHandler.trash(admin, workspace, database, database) + with pytest.raises(WorkspaceInvitationLinkDoesNotExist): + CoreHandler().get_workspace_invitation_link_by_slug(other_link.slug) + + TrashHandler.permanently_delete(database) + assert not WorkspaceInvitationLink.objects.filter( + id__in=[table_link.id, other_link.id] + ).exists() + + +@pytest.mark.django_db +def test_links_to_an_application_and_a_view(api_client, data_fixture): + admin, workspace, database, table_a, table_b = setup_workspace(data_fixture) + application = database.application_ptr + # Roles are given on the base view, like on the base application. + view = data_fixture.create_grid_view( + table=table_a, ownership_type="restricted" + ).view_ptr + list_url = reverse( + "api:enterprise:role:scoped_invitation_links", + kwargs={"workspace_id": workspace.id}, + ) + token = data_fixture.generate_token(admin) + + def create(scope_type, scope_id, permissions): + response = api_client.post( + list_url, + { + "permissions": permissions, + "scope_type": scope_type, + "scope_id": scope_id, + }, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + assert response.status_code == HTTP_200_OK, response.json() + return WorkspaceInvitationLink.objects.get(id=response.json()["id"]) + + application_link = create("application", application.id, "EDITOR") + view_link = create("database_view", view.id, "VIEWER") + application_newcomer = data_fixture.create_user() + view_newcomer = data_fixture.create_user() + + for user, link in [ + (application_newcomer, application_link), + (view_newcomer, view_link), + ]: + CoreHandler().join_workspace_via_invitation_link( + user, CoreHandler().get_workspace_invitation_link_by_slug(link.slug) + ) + + assert role_on(application_newcomer, application) == "EDITOR" + assert can_read_table(application_newcomer, workspace, table_a) + assert role_on(view_newcomer, view) == "VIEWER" + assert not can_read_table(view_newcomer, workspace, table_b) + + TrashHandler.trash(admin, workspace, database, database) + for link in [application_link, view_link]: + with pytest.raises(WorkspaceInvitationLinkDoesNotExist): + CoreHandler().get_workspace_invitation_link_by_slug(link.slug) + + TrashHandler.permanently_delete(database) + assert not WorkspaceInvitationLink.objects.filter( + id__in=[application_link.id, view_link.id] + ).exists() + + +@pytest.mark.django_db +def test_link_to_object_cannot_be_used_without_rbac(data_fixture): + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + table_link = create_link(admin, workspace, table_a, "EDITOR") + + with patch.object(LicenseHandler, "workspace_has_feature", return_value=False): + with pytest.raises(WorkspaceInvitationLinkDoesNotExist): + CoreHandler().get_workspace_invitation_link_by_slug(table_link.slug) + + +@pytest.mark.django_db +def test_object_admins_update_and_delete_links_to_the_object(data_fixture): + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + table_admin = add_member(data_fixture, workspace, NO_ROLE_LOW_PRIORITY_ROLE_UID) + table_editor = add_member(data_fixture, workspace, NO_ROLE_LOW_PRIORITY_ROLE_UID) + handler = RoleAssignmentHandler() + handler.assign_role(table_admin, workspace, role("ADMIN"), table_a) + handler.assign_role(table_editor, workspace, role("EDITOR"), table_a) + table_link = create_link(admin, workspace, table_a, "EDITOR") + + with pytest.raises(PermissionDenied): + handler.update_scoped_invitation_link( + table_editor, table_link, role=role("ADMIN") + ) + with pytest.raises(PermissionDenied): + handler.delete_scoped_invitation_link(table_editor, table_link) + + handler.update_scoped_invitation_link( + table_admin, table_link, role=role("VIEWER"), name="Partners" + ) + table_link.refresh_from_db() + assert table_link.permissions == "VIEWER" + assert table_link.name == "Partners" + + handler.delete_scoped_invitation_link(table_admin, table_link) + assert not WorkspaceInvitationLink.objects.filter(id=table_link.id).exists() + + +@pytest.mark.django_db +@patch("baserow.core.action.signals.action_done.send") +def test_link_to_object_actions_are_recorded_with_the_object( + action_done_mock, data_fixture +): + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + member = add_member(data_fixture, workspace, "EDITOR") + newcomer = data_fixture.create_user() + + table_link = CreateScopedInvitationLinkActionType.do( + admin, workspace, table_a, role("VIEWER"), "Partners" + ) + UpdateScopedInvitationLinkActionType.do(admin, table_link, role=role("COMMENTER")) + JoinWorkspaceViaInvitationLinkActionType.do(newcomer, table_link) + # An Editor of the workspace already has more than a Commenter on the table, + # so nothing changes and nothing is recorded. + JoinWorkspaceViaInvitationLinkActionType.do(member, table_link) + table_link_id = table_link.id + DeleteScopedInvitationLinkActionType.do(admin, table_link) + + calls = [call.kwargs for call in action_done_mock.call_args_list] + assert [call["action_type"] for call in calls] == [ + CreateScopedInvitationLinkActionType, + UpdateScopedInvitationLinkActionType, + JoinWorkspaceViaInvitationLinkActionType, + DeleteScopedInvitationLinkActionType, + ] + join = calls[2] + assert join["user"] == newcomer + assert JoinWorkspaceViaInvitationLinkActionType.get_long_description( + join["action_params"] + ) == ( + f'Joined "{workspace.name}" ({workspace.id}) through invitation link ' + f'({table_link_id}) as COMMENTER on "database_table" ({table_a.id}).' + ) + assert calls[1]["action_params"]["original_role_uid"] == "VIEWER" + assert calls[1]["action_params"]["role_uid"] == "COMMENTER" + + +@pytest.mark.django_db +def test_manage_links_to_object_through_the_api(api_client, data_fixture): + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + table_admin = add_member(data_fixture, workspace, NO_ROLE_LOW_PRIORITY_ROLE_UID) + RoleAssignmentHandler().assign_role(table_admin, workspace, role("ADMIN"), table_a) + token = data_fixture.generate_token(table_admin) + list_url = reverse( + "api:enterprise:role:scoped_invitation_links", + kwargs={"workspace_id": workspace.id}, + ) + + response = api_client.post( + list_url, + { + "name": "Partners", + "permissions": "EDITOR", + "scope_type": "database_table", + "scope_id": table_a.id, + }, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + assert response.status_code == HTTP_200_OK, response.json() + created = response.json() + assert created["name"] == "Partners" + assert created["permissions"] == "EDITOR" + assert created["scope_type"] == "database_table" + assert created["scope_id"] == table_a.id + + response = api_client.get( + list_url, + {"scope_type": "database_table", "scope_id": table_a.id}, + HTTP_AUTHORIZATION=f"JWT {token}", + ) + assert response.status_code == HTTP_200_OK + assert [link["id"] for link in response.json()] == [created["id"]] + + item_url = reverse( + "api:enterprise:role:scoped_invitation_link", + kwargs={"invitation_link_id": created["id"]}, + ) + response = api_client.patch( + item_url, + {"permissions": "VIEWER"}, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + assert response.status_code == HTTP_200_OK + assert response.json()["permissions"] == "VIEWER" + assert response.json()["name"] == "Partners" + + response = api_client.patch( + item_url, + {"permissions": "UNKNOWN"}, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + assert response.status_code == HTTP_404_NOT_FOUND + assert response.json()["error"] == "ERROR_ROLE_DOES_NOT_EXIST" + + response = api_client.delete(item_url, HTTP_AUTHORIZATION=f"JWT {token}") + assert response.status_code == HTTP_204_NO_CONTENT + assert not WorkspaceInvitationLink.objects.exists() + + +@pytest.mark.django_db +@pytest.mark.parametrize( + "role_kind", ["NO_ACCESS", "NO_ROLE_LOW_PRIORITY", "hidden", "other_workspace"] +) +def test_handler_rejects_invalid_scoped_link_roles(data_fixture, role_kind): + """Protect internal callers and preserve the link after rejected changes.""" + + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + handler = RoleAssignmentHandler() + if role_kind == "hidden": + invalid_role = role("READ_ONLY") + elif role_kind == "other_workspace": + invalid_role = Role.objects.create( + uid="OTHER_WORKSPACE_ROLE", + name="Other workspace role", + workspace=data_fixture.create_workspace(), + ) + else: + invalid_role = role(role_kind) + + table_link = create_link(admin, workspace, table_a, "VIEWER", "Partners") + + with pytest.raises(InvalidWorkspaceRole): + handler.create_scoped_invitation_link(admin, workspace, table_a, invalid_role) + assert list(WorkspaceInvitationLink.objects.values_list("id", flat=True)) == [ + table_link.id + ] + + with pytest.raises(InvalidWorkspaceRole): + handler.update_scoped_invitation_link( + admin, table_link, role=invalid_role, name="Changed" + ) + table_link.refresh_from_db() + assert table_link.permissions == "VIEWER" + assert table_link.name == "Partners" + + +@pytest.mark.django_db +@pytest.mark.parametrize("role_uid", ["NO_ACCESS", NO_ROLE_LOW_PRIORITY_ROLE_UID]) +def test_link_api_rejects_roles_that_grant_no_access( + api_client, data_fixture, role_uid +): + """Reject unusable link roles without creating or changing a link.""" + + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + token = data_fixture.generate_token(admin) + table_link = create_link(admin, workspace, table_a, "VIEWER", "Partners") + + response = api_client.post( + reverse( + "api:enterprise:role:scoped_invitation_links", + kwargs={"workspace_id": workspace.id}, + ), + { + "permissions": role_uid, + "scope_type": "database_table", + "scope_id": table_a.id, + }, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + assert response.status_code == HTTP_400_BAD_REQUEST + assert response.json()["error"] == "ERROR_INVALID_WORKSPACE_ROLE" + assert list(WorkspaceInvitationLink.objects.values_list("id", flat=True)) == [ + table_link.id + ] + + response = api_client.patch( + reverse( + "api:enterprise:role:scoped_invitation_link", + kwargs={"invitation_link_id": table_link.id}, + ), + {"permissions": role_uid, "name": "Changed"}, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + assert response.status_code == HTTP_400_BAD_REQUEST + assert response.json()["error"] == "ERROR_INVALID_WORKSPACE_ROLE" + table_link.refresh_from_db() + assert table_link.permissions == "VIEWER" + assert table_link.name == "Partners" + + +@pytest.mark.django_db +def test_links_to_object_api_refuses_non_admins_and_workspace_links( + api_client, data_fixture +): + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + editor = add_member(data_fixture, workspace, "EDITOR") + token = data_fixture.generate_token(editor) + workspace_link = data_fixture.create_workspace_invitation_link( + workspace=workspace, created_by=admin, permissions="MEMBER" + ) + + response = api_client.post( + reverse( + "api:enterprise:role:scoped_invitation_links", + kwargs={"workspace_id": workspace.id}, + ), + { + "permissions": "EDITOR", + "scope_type": "database_table", + "scope_id": table_a.id, + }, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + assert response.status_code == HTTP_401_UNAUTHORIZED + assert response.json()["error"] == "PERMISSION_DENIED" + + response = api_client.delete( + reverse( + "api:enterprise:role:scoped_invitation_link", + kwargs={"invitation_link_id": workspace_link.id}, + ), + HTTP_AUTHORIZATION=f"JWT {data_fixture.generate_token(admin)}", + ) + assert response.status_code == HTTP_404_NOT_FOUND + assert response.json()["error"] == "ERROR_WORKSPACE_INVITATION_LINK_DOES_NOT_EXIST" + + +@pytest.mark.django_db +def test_open_and_join_link_to_object_through_the_api(api_client, data_fixture): + admin, workspace, database, table_a, _ = setup_workspace(data_fixture) + member = add_member(data_fixture, workspace, NO_ROLE_LOW_PRIORITY_ROLE_UID) + RoleAssignmentHandler().assign_role( + member, workspace, role("VIEWER"), database.application_ptr + ) + table_link = create_link(admin, workspace, table_a, "COMMENTER") + token = data_fixture.generate_token(member) + slug_url = reverse( + "api:workspaces:invitation_links:slug", kwargs={"slug": table_link.slug} + ) + + response = api_client.get(slug_url) + assert response.status_code == HTTP_200_OK + assert response.json()["scope_type"] == "database_table" + assert response.json()["scope_id"] == table_a.id + assert response.json()["scope_name"] == table_a.name + assert response.json()["role_upgrade"] is None + + response = api_client.get(slug_url, HTTP_AUTHORIZATION=f"JWT {token}") + assert response.json()["role_upgrade"] == { + "current_permissions": "VIEWER", + "permissions": "COMMENTER", + } + + response = api_client.post( + reverse( + "api:workspaces:invitation_links:join", kwargs={"slug": table_link.slug} + ), + HTTP_AUTHORIZATION=f"JWT {token}", + ) + assert response.status_code == HTTP_200_OK + assert response.json()["permissions"] == NO_ROLE_LOW_PRIORITY_ROLE_UID + assert role_on(member, table_a) == "COMMENTER" + + response = api_client.get(slug_url, HTTP_AUTHORIZATION=f"JWT {token}") + assert response.json()["role_upgrade"] is None + + +@pytest.mark.django_db +def test_create_link_to_object_with_signups_disabled_through_the_api( + api_client, data_fixture +): + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + data_fixture.update_settings( + allow_new_signups=False, allow_signups_via_workspace_invitations=False + ) + + response = api_client.post( + reverse( + "api:enterprise:role:scoped_invitation_links", + kwargs={"workspace_id": workspace.id}, + ), + { + "permissions": "EDITOR", + "scope_type": "database_table", + "scope_id": table_a.id, + }, + format="json", + HTTP_AUTHORIZATION=f"JWT {data_fixture.generate_token(admin)}", + ) + assert response.status_code == HTTP_400_BAD_REQUEST + assert ( + response.json()["error"] == "ERROR_WORKSPACE_INVITATION_LINK_SIGNUPS_DISABLED" + ) + + +@pytest.mark.django_db +@pytest.mark.parametrize("ownership_type", ["collaborative", "personal"]) +def test_invitation_links_reject_views_without_view_only_row_access( + api_client, data_fixture, ownership_type +): + """Reject unsupported view targets and disable links saved before validation.""" + + admin, workspace, _, table_a, _ = setup_workspace(data_fixture) + view = data_fixture.create_grid_view( + user=admin, table=table_a, ownership_type=ownership_type + ).view_ptr + token = data_fixture.generate_token(admin) + response = api_client.post( + reverse( + "api:enterprise:role:scoped_invitation_links", + kwargs={"workspace_id": workspace.id}, + ), + {"permissions": "VIEWER", "scope_type": "database_view", "scope_id": view.id}, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + assert response.status_code == HTTP_404_NOT_FOUND + assert response.json()["error"] == "ERROR_SCOPE_DOES_NOT_EXIST" + assert not WorkspaceInvitationLink.objects.filter(workspace=workspace).exists() + + legacy_link = WorkspaceInvitationLink.objects.create( + workspace=workspace, created_by=admin, scope=view, permissions="VIEWER" + ) + response = api_client.post( + reverse( + "api:workspaces:invitation_links:join", kwargs={"slug": legacy_link.slug} + ), + HTTP_AUTHORIZATION=f"JWT {data_fixture.generate_token(data_fixture.create_user())}", + ) + assert response.status_code == HTTP_404_NOT_FOUND + assert response.json()["error"] == "ERROR_WORKSPACE_INVITATION_LINK_DOES_NOT_EXIST" + + handler = RoleAssignmentHandler() + with pytest.raises(ScopeNotExist): + handler.update_scoped_invitation_link(admin, legacy_link, role=role("EDITOR")) + handler.delete_scoped_invitation_link(admin, legacy_link) + assert not WorkspaceInvitationLink.objects.filter(workspace=workspace).exists() + + +@pytest.mark.django_db +def test_restricted_view_invitee_can_load_fields_and_filtered_rows( + api_client, data_fixture +): + """A view-only invite must grant usable data access without exposing other rows.""" + + admin, workspace, _, table_a, table_b = setup_workspace(data_fixture) + field = data_fixture.create_text_field(table=table_a, primary=True) + visible, hidden = data_fixture.create_rows([field], [["Partner"], ["Internal"]]) + view = data_fixture.create_grid_view( + user=admin, table=table_a, ownership_type="restricted" + ) + data_fixture.create_view_filter( + view=view, field=field, type="equal", value="Partner" + ) + link = create_link(admin, workspace, view.view_ptr, "VIEWER") + newcomer = data_fixture.create_user() + auth = {"HTTP_AUTHORIZATION": f"JWT {data_fixture.generate_token(newcomer)}"} + + response = api_client.post( + reverse("api:workspaces:invitation_links:join", kwargs={"slug": link.slug}), + **auth, + ) + assert response.status_code == HTTP_200_OK + assert response.json()["permissions"] == NO_ROLE_LOW_PRIORITY_ROLE_UID + + fields_url = reverse("api:database:fields:list", kwargs={"table_id": table_a.id}) + response = api_client.get(fields_url, {"view": view.id}, **auth) + assert response.status_code == HTTP_200_OK + assert [item["id"] for item in response.json()] == [field.id] + + response = api_client.get( + reverse("api:database:views:grid:list", kwargs={"view_id": view.id}), + **auth, + ) + assert response.status_code == HTTP_200_OK + assert [row["id"] for row in response.json()["results"]] == [visible.id] + assert not can_read_table(newcomer, workspace, table_b) + response = api_client.get(fields_url, **auth) + assert response.status_code == HTTP_401_UNAUTHORIZED diff --git a/enterprise/web-frontend/modules/baserow_enterprise/invitationTargetTypes.js b/enterprise/web-frontend/modules/baserow_enterprise/invitationTargetTypes.js index 6cfb7dfe58..3e4af5049e 100644 --- a/enterprise/web-frontend/modules/baserow_enterprise/invitationTargetTypes.js +++ b/enterprise/web-frontend/modules/baserow_enterprise/invitationTargetTypes.js @@ -1,6 +1,7 @@ import { InvitationTargetType } from '@baserow/modules/core/invitationTargetTypes' import RoleAssignmentsService from '@baserow_enterprise/services/roleAssignments' import { filterRoles } from '@baserow_enterprise/utils/roles' +import { RestrictedViewOwnershipType } from '@baserow_enterprise/viewOwnershipTypes' /** * Invites people to one object of the workspace: an application, a table or a @@ -101,4 +102,58 @@ export class ScopeInvitationTargetType extends InvitationTargetType { }) return data } + + /** + * Links give their role on the object only. Admins of the workspace and of the + * object can manage them, which are the people who can open this dialog. + */ + supportsInvitationLinks(workspace, { scopeType, scope }) { + return ( + scopeType !== 'database_view' || + scope.ownership_type === RestrictedViewOwnershipType.getType() + ) + } + + async fetchInvitationLinks(workspace, { scope, scopeType }) { + const { data } = await RoleAssignmentsService( + this.app.$client + ).getScopedInvitationLinks(workspace.id, scope.id, scopeType) + return data + } + + async createInvitationLink(workspace, { scope, scopeType }, permissions) { + const { data } = await RoleAssignmentsService( + this.app.$client + ).createScopedInvitationLink(workspace.id, { + permissions, + scopeId: scope.id, + scopeType, + }) + return data + } + + async updateInvitationLink(workspace, target, invitationLink, values) { + const { data } = await RoleAssignmentsService( + this.app.$client + ).updateScopedInvitationLink(invitationLink.id, values) + return data + } + + async deleteInvitationLink(workspace, target, invitationLink) { + await RoleAssignmentsService(this.app.$client).deleteScopedInvitationLink( + invitationLink.id + ) + } + + getInvitationLinkAdminWarning(workspace, { scope }) { + return this.$t('scopeInvitationTarget.linkAdminWarning', { + name: scope.name, + }) + } + + getInvitationLinkDeleteWarning(workspace, { scope }) { + return this.$t('scopeInvitationTarget.linkDeleteWarning', { + name: scope.name, + }) + } } diff --git a/enterprise/web-frontend/modules/baserow_enterprise/locales/en.json b/enterprise/web-frontend/modules/baserow_enterprise/locales/en.json index df5fe7f90e..4a5c5c6a39 100644 --- a/enterprise/web-frontend/modules/baserow_enterprise/locales/en.json +++ b/enterprise/web-frontend/modules/baserow_enterprise/locales/en.json @@ -363,7 +363,9 @@ "title": "Share {name}", "application": "Application", "table": "Table", - "view": "View" + "view": "View", + "linkAdminWarning": "Anyone with this link becomes an admin of {name}, and admins can manage everything in it, including who has access to it and its invite links. Only share it with people you trust.", + "linkDeleteWarning": "Are you sure that you want to delete this invite link to {name}? After deleting, it will not be possible to get access through this link. Everyone that you have shared the link with won't be able to use it anymore. People who already joined through it keep their access." }, "shareScope": { "pendingNoWorkspaceRole": "No workspace role", diff --git a/enterprise/web-frontend/modules/baserow_enterprise/services/roleAssignments.js b/enterprise/web-frontend/modules/baserow_enterprise/services/roleAssignments.js index 92ebe9bfba..272bdedf7c 100644 --- a/enterprise/web-frontend/modules/baserow_enterprise/services/roleAssignments.js +++ b/enterprise/web-frontend/modules/baserow_enterprise/services/roleAssignments.js @@ -83,5 +83,30 @@ export default (client) => { deleteScopedInvitation(scopedInvitationId) { return client.delete(`/role/invitations/${scopedInvitationId}/`) }, + getScopedInvitationLinks(workspaceId, scopeId, scopeType) { + return client.get(`/role/${workspaceId}/invitation-links/`, { + params: { + scope_id: scopeId, + scope_type: scopeType, + }, + }) + }, + createScopedInvitationLink( + workspaceId, + { permissions, scopeId, scopeType, name = '' } + ) { + return client.post(`/role/${workspaceId}/invitation-links/`, { + name, + permissions, + scope_id: scopeId, + scope_type: scopeType, + }) + }, + updateScopedInvitationLink(invitationLinkId, values) { + return client.patch(`/role/invitation-links/${invitationLinkId}/`, values) + }, + deleteScopedInvitationLink(invitationLinkId) { + return client.delete(`/role/invitation-links/${invitationLinkId}/`) + }, } } diff --git a/enterprise/web-frontend/test/unit/enterprise/invitation/scopeInvitationTargetType.spec.js b/enterprise/web-frontend/test/unit/enterprise/invitation/scopeInvitationTargetType.spec.js index 89ebf0bfa6..54914ab62e 100644 --- a/enterprise/web-frontend/test/unit/enterprise/invitation/scopeInvitationTargetType.spec.js +++ b/enterprise/web-frontend/test/unit/enterprise/invitation/scopeInvitationTargetType.spec.js @@ -141,6 +141,86 @@ describe('ScopeInvitationTargetType', () => { }) }) +describe('ScopeInvitationTargetType invitation links', () => { + const target = { + scopeType: 'database_table', + scope: { id: 5, name: 'Sales' }, + } + + test('manages the links of the object through the role endpoints', async () => { + const link = { id: 4, slug: 'abc', permissions: 'EDITOR', name: '' } + const client = { + get: vi.fn().mockResolvedValue({ data: [link] }), + post: vi.fn().mockResolvedValue({ data: link }), + patch: vi.fn().mockResolvedValue({ data: { ...link, name: 'Partners' } }), + delete: vi.fn().mockResolvedValue({}), + } + const targetType = new ScopeInvitationTargetType({ app: createApp(client) }) + + expect(targetType.supportsInvitationLinks(workspace, target)).toBe(true) + + expect(await targetType.fetchInvitationLinks(workspace, target)).toEqual([ + link, + ]) + expect(client.get).toHaveBeenCalledWith('/role/12/invitation-links/', { + params: { scope_id: 5, scope_type: 'database_table' }, + }) + + expect( + await targetType.createInvitationLink(workspace, target, 'EDITOR') + ).toEqual(link) + expect(client.post).toHaveBeenCalledWith('/role/12/invitation-links/', { + name: '', + permissions: 'EDITOR', + scope_id: 5, + scope_type: 'database_table', + }) + + const updated = await targetType.updateInvitationLink( + workspace, + target, + link, + { name: 'Partners' } + ) + expect(updated.name).toBe('Partners') + expect(client.patch).toHaveBeenCalledWith('/role/invitation-links/4/', { + name: 'Partners', + }) + + await targetType.deleteInvitationLink(workspace, target, link) + expect(client.delete).toHaveBeenCalledWith('/role/invitation-links/4/') + }) + + test.each([ + ['restricted', true], + ['collaborative', false], + ['personal', false], + ])( + 'offers view links only for restricted views (%s)', + (ownershipType, expected) => { + const targetType = new ScopeInvitationTargetType({ app: createApp() }) + + expect( + targetType.supportsInvitationLinks(workspace, { + scopeType: 'database_view', + scope: { id: 9, ownership_type: ownershipType }, + }) + ).toBe(expected) + } + ) + + test('warns about what a link to the object gives', () => { + const targetType = new ScopeInvitationTargetType({ app: createApp() }) + + expect(targetType.getInvitationLinkAdminWarning(workspace, target)).toBe( + 'scopeInvitationTarget.linkAdminWarning:{"name":"Sales"}' + ) + expect(targetType.getInvitationLinkDeleteWarning(workspace, target)).toBe( + 'scopeInvitationTarget.linkDeleteWarning:{"name":"Sales"}' + ) + }) +}) + describe('MemberInvitationRouteType', () => { test('is only enabled for scope targets with the RBAC feature', () => { const app = createApp() diff --git a/web-frontend/modules/core/components/auth/PasswordRegister.vue b/web-frontend/modules/core/components/auth/PasswordRegister.vue index c587dc8a5d..f0f104b1f2 100644 --- a/web-frontend/modules/core/components/auth/PasswordRegister.vue +++ b/web-frontend/modules/core/components/auth/PasswordRegister.vue @@ -17,7 +17,7 @@ @@ -232,6 +232,19 @@ export default { invitationDetails() { return this.invitation ?? this.invitationLink }, + /** + * The workspace, or the object of the workspace an invitation link gives a + * role on, like "Sales in Acme". + */ + invitationDestination() { + const details = this.invitationDetails + return details.scope_name + ? this.$t('invitationLinkJoin.scopeIn', { + name: details.scope_name, + workspace: details.workspace, + }) + : details.workspace + }, registerComponents() { return Object.values(this.$registry.getAll('plugin')) .map((plugin) => plugin.getRegisterComponent()) diff --git a/web-frontend/modules/core/components/invitation/InvitationLinkDeleteModal.vue b/web-frontend/modules/core/components/invitation/InvitationLinkDeleteModal.vue index a32829ec20..4dcfd1ae8e 100644 --- a/web-frontend/modules/core/components/invitation/InvitationLinkDeleteModal.vue +++ b/web-frontend/modules/core/components/invitation/InvitationLinkDeleteModal.vue @@ -4,11 +4,7 @@

- {{ - $t('invitationLinkDeleteModal.deleteWarning', { - workspaceName: workspace.name, - }) - }} + {{ targetType.getInvitationLinkDeleteWarning(workspace, target) }}

diff --git a/web-frontend/modules/core/components/invitation/LinkInvitationRoute.vue b/web-frontend/modules/core/components/invitation/LinkInvitationRoute.vue index b8b0e1b238..9add7eff62 100644 --- a/web-frontend/modules/core/components/invitation/LinkInvitationRoute.vue +++ b/web-frontend/modules/core/components/invitation/LinkInvitationRoute.vue @@ -88,7 +88,7 @@ {{ invitationLink.invited_by }} + + @@ -114,14 +124,34 @@ const { data: invitationLink, error: fetchError } = await useAsyncData( } ) -const pageTitle = computed(() => { - if (!invitationLink.value) { +/** + * What the link joins: the workspace, or one of its objects such as "Sales in + * Acme" when the link gives a role on that object only. + */ +const destination = computed(() => { + const link = invitationLink.value + if (!link) { return '' } - const params = { workspace: invitationLink.value.workspace } - return roleUpgrade.value - ? t('invitationLinkJoin.upgradeTitle', params) - : t('invitationLinkJoin.title', params) + return link.scope_name + ? t('invitationLinkJoin.scopeIn', { + name: link.scope_name, + workspace: link.workspace, + }) + : link.workspace +}) + +const pageTitle = computed(() => { + const link = invitationLink.value + if (!link) { + return '' + } + if (!roleUpgrade.value) { + return t('invitationLinkJoin.title', { workspace: destination.value }) + } + return link.scope_name + ? t('invitationLinkJoin.upgradeScopeTitle', { name: link.scope_name }) + : t('invitationLinkJoin.upgradeTitle', { workspace: link.workspace }) }) useHead({ title: () => pageTitle.value }) @@ -147,8 +177,9 @@ if (fetchError.value) { { replace: true } ) } else if (invitationLink.value) { - // Members land in the workspace, unless the link raises their role. Then they - // confirm the change first, like newcomers confirm joining. + // Members land in the workspace, unless the link raises their role, on its + // object if it has one. Then they confirm the change first, like newcomers + // confirm joining. await store.dispatch('workspace/loadAll') const workspaceId = invitationLink.value.workspace_id const workspace = store.getters['workspace/get'](workspaceId)