From 93eeb19dcb634544934d346008a970f70acb7a22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9mie=20Pardou?= <571533+jrmi@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:38:57 +0200 Subject: [PATCH] feat: run Local Baserow integrations as Agents (#6064) * Run Local Baserow integrations as Agents * fix tests * feat(core): add reusable subject options endpoint * Add beta badge * fix(audit-log): require actor type with actor id * fix(audit-log): avoid duplicate actor export columns * fix(audit-log): guard deprecated actor fields * Restore the feature flag * fix tab alignement * fix(integrations): reject trashed authorized agents * Fix migration conflict * fix(audit-log): assert structured validation error * fix(database): support agent row deletion trash entries * fix(database): support agent row notifications * fix(core): enforce subject option permissions * chore: fix formatting after rebase * fix(core): include agents in member totals * fix(database): batch row history actor migration * fix(integrations): handle trashed authorized agents * fix(core): remove untranslated subject labels * chore: move nodes around * test: mock integration registry in AI agent service tests * fix: resolve database migration conflict * Add changelog entry * feat: use typed subjects for local Baserow integrations * fix: make audit actor migration retry-safe * fix: retain historical audit actors * Please linting * fix: use canonical local integration subjects * fix: order listed workspaces * fix: validate current user integration authorization * fix: preserve integration authorization on update * docs: clarify migration deployment compatibility * fix: paginate local baserow agent selection * fix: validate selectable subject options * fix: preserve integration authorization on update * fix: show saved integration user in subject dropdown * fix(enterprise): protect team subject options * fix(builder): redispatch data sources for trashed agents * fix(database): split row history actor backfill * fix(enterprise): require audit log actor type * fix(enterprise): use audit log actor options * fix(core): prevent blank agent names * fix(integrations): resolve migration conflict * fix(integrations): pass SMTP preparation context * docs: clarify migration rollout guidance * fix: handle trashed integration subjects * fix: reuse local integration authorization column * fix: allow unconfigured local integrations * fix: only update changed integration values * fix: cache local integration subjects * fix: sort field permission subjects by name * fix: include historical audit log actors * fix: center grow tab labels * chore: remove unused AI providers flag * fix: support agent file uploads * Please linter * fix: initialize integration edit values * fix: preserve integration authorization updates * fix: bound audit log actor pagination * fix: support legacy local integration fixtures --- AGENTS.md | 1 + backend/src/baserow/api/agents/serializers.py | 2 +- backend/src/baserow/api/subjects/__init__.py | 1 + .../src/baserow/api/subjects/serializers.py | 39 +++ backend/src/baserow/api/subjects/urls.py | 7 + backend/src/baserow/api/subjects/views.py | 68 +++++ backend/src/baserow/api/urls.py | 2 + .../api/workspaces/users/serializers.py | 8 + backend/src/baserow/api/workspaces/views.py | 1 + .../contrib/automation/application_types.py | 3 + .../contrib/automation/history/handler.py | 4 +- .../contrib/builder/application_types.py | 3 + .../builder/builder_beta_init_application.py | 3 +- .../contrib/builder/domains/job_types.py | 5 + .../src/baserow/contrib/builder/populate.py | 6 +- .../contrib/dashboard/application_types.py | 3 +- .../contrib/database/api/rows/serializers.py | 25 +- .../database/fields/notification_types.py | 19 +- .../migrations/0226_rowhistory_actor.py | 59 ++++ ...ackfill_rowhistory_anonymous_actor_type.py | 37 +++ .../baserow/contrib/database/rows/handler.py | 28 +- .../baserow/contrib/database/rows/helpers.py | 30 +- .../baserow/contrib/database/rows/models.py | 17 +- .../integrations/ai/integration_types.py | 12 +- .../integrations/core/integration_types.py | 12 +- .../local_baserow/integration_types.py | 228 +++++++++++--- .../integrations/local_baserow/models.py | 57 +++- .../integrations/local_baserow/receivers.py | 30 ++ .../local_baserow/service_types.py | 53 +++- .../integrations/local_baserow/utils.py | 22 +- ...ocalbaserowintegration_authorized_agent.py | 47 +++ .../baserow/contrib/integrations/signals.py | 6 +- .../integrations/slack/integration_types.py | 5 +- backend/src/baserow/core/action/registries.py | 17 ++ backend/src/baserow/core/agents/handler.py | 25 ++ backend/src/baserow/core/agents/subjects.py | 71 +++++ backend/src/baserow/core/handler.py | 3 +- .../baserow/core/integrations/exceptions.py | 4 + .../src/baserow/core/integrations/handler.py | 3 + .../baserow/core/integrations/registries.py | 10 +- .../src/baserow/core/integrations/service.py | 8 +- backend/src/baserow/core/posthog.py | 7 + backend/src/baserow/core/registries.py | 61 +++- .../src/baserow/core/services/registries.py | 9 + backend/src/baserow/core/subject_options.py | 94 ++++++ backend/src/baserow/core/subjects.py | 83 +++++ .../test_utils/fixtures/integration.py | 16 +- .../baserow/test_utils/fixtures/service.py | 15 +- .../baserow/api/agents/test_agent_views.py | 21 -- .../api/groups/test_workspace_views.py | 18 +- .../integrations/test_integration_views.py | 121 +++++++- .../tests/baserow/api/subjects/__init__.py | 1 + .../api/subjects/test_subject_views.py | 132 ++++++++ .../history/test_history_handler.py | 22 ++ .../test_automation_application_types.py | 5 +- .../workflows/test_workflow_handler.py | 22 ++ .../builder/domains/test_domain_handler.py | 42 +++ .../builder/test_builder_application_type.py | 5 +- .../builder/test_core_handler_builder.py | 2 +- .../builder/test_snapshot_handler_builder.py | 2 +- .../test_dashboard_application_types.py | 8 +- .../database/api/rows/test_row_views.py | 65 ++++ .../field/test_field_notification_types.py | 70 ++++- .../field/test_password_field_type.py | 5 +- .../test_row_history_actor_migration.py | 69 +++++ .../contrib/database/rows/test_row_history.py | 288 +++++++++++------- .../database/ws/test_ws_rows_signals.py | 14 + .../service_types/test_actor_dispatch.py | 46 ++- .../test_delete_row_service_type.py | 34 +++ .../test_list_rows_service_type.py | 40 +++ .../test_upsert_row_service_type.py | 38 ++- .../local_baserow/test_integration_types.py | 134 +++++++- .../local_baserow/test_migrations.py | 45 +++ .../integrations/local_baserow/test_utils.py | 21 ++ .../baserow/core/agents/test_agent_handler.py | 62 ++++ .../baserow/core/agents/test_agent_subject.py | 1 + .../integrations/test_integration_handler.py | 7 +- .../baserow/core/service/test_service_type.py | 18 ++ backend/tests/baserow/core/test_posthog.py | 23 ++ .../core/user/test_user_subject_type.py | 1 + ...users_endpoint_with_the_new_actors_en.json | 9 + .../api/admin/audit_log/urls.py | 4 +- .../api/audit_log/serializers.py | 63 +++- .../baserow_enterprise/api/audit_log/urls.py | 4 +- .../baserow_enterprise/api/audit_log/views.py | 101 +++--- .../api/field_permissions/serializers.py | 6 +- .../baserow_enterprise/audit_log/handler.py | 19 +- .../baserow_enterprise/audit_log/job_types.py | 113 +++++-- .../baserow_enterprise/audit_log/models.py | 44 ++- .../baserow_enterprise/audit_log/signals.py | 4 +- .../field_permissions/handler.py | 69 +---- .../local_baserow/user_source_types.py | 4 +- .../migrations/0068_auditlogentry_agent.py | 170 +++++++++++ .../src/baserow_enterprise/role/actions.py | 14 +- .../src/baserow_enterprise/teams/subjects.py | 38 +++ .../audit_log/test_audit_log_admin_views.py | 283 +++++++++++++++-- .../test_audit_log_workspace_views.py | 144 +++++---- .../test_field_permissions_handler.py | 27 ++ .../api/subjects/test_subject_views.py | 86 ++++++ .../audit_log/test_audit_log_export_job.py | 80 +++-- .../audit_log/test_audit_log_handler.py | 77 +++++ .../audit_log/test_audit_log_migrations.py | 27 ++ .../role/test_role_actions.py | 5 +- .../auditLog/AuditLogActorDropdown.vue | 74 +++++ .../auditLog/AuditLogActorField.vue | 34 +++ .../auditLog/AuditLogActorTypeField.vue | 32 ++ .../baserow_enterprise/locales/en.json | 10 +- .../baserow_enterprise/pages/auditLog.vue | 55 ++-- .../baserow_enterprise/services/auditLog.js | 21 +- .../auditLogActorDropdown.spec.js.snap | 42 +++ .../auditLog/auditLogActorDropdown.spec.js | 66 ++++ .../auditLog/auditLogActorField.spec.js | 41 +++ .../auditLog/auditLogActorTypeField.spec.js | 51 ++++ .../memberRoles/selectAgentsList.spec.js | 22 -- .../unit/enterprise/services/auditLog.spec.js | 15 + justfile | 1 + .../row_comments/row_metadata_types.py | 5 +- ...test_dashboard_application_types_charts.py | 22 +- .../dashboard/test_pie_chart_widget_type.py | 8 +- web-frontend/modules/builder/realtime.js | 38 +++ .../core/assets/scss/components/tabs.scss | 6 +- .../core/components/PaginatedDropdown.vue | 38 +-- web-frontend/modules/core/components/Tab.vue | 6 + web-frontend/modules/core/components/Tabs.vue | 7 + .../AllWorkspacesWorkspaceBox.vue | 10 +- .../IntegrationCreateEditModal.vue | 22 +- .../agents/AgentGeneralSettingsForm.vue | 2 +- .../settings/agents/ManageAgentModal.vue | 12 +- .../settings/members/MembersTable.vue | 13 +- .../core/components/sidebar/SidebarMenu.vue | 18 +- web-frontend/modules/core/integrationTypes.js | 20 ++ web-frontend/modules/core/locales/en.json | 1 + web-frontend/modules/core/pages/settings.vue | 2 + web-frontend/modules/core/plugin.js | 2 + web-frontend/modules/core/serviceTypes.js | 18 +- web-frontend/modules/core/services/subject.js | 21 ++ web-frontend/modules/core/store/agent.js | 17 +- .../modules/core/store/integration.js | 9 +- web-frontend/modules/core/store/workspace.js | 9 + web-frontend/modules/core/subjectTypes.js | 34 ++- web-frontend/modules/core/utils/workspace.js | 4 + .../core/workspaceSettingsPageTypes.js | 8 + .../components/row/RowHistoryEntry.vue | 19 +- web-frontend/modules/database/locales/en.json | 1 + .../modules/integrations/core/serviceTypes.js | 8 + .../integrations/LocalBaserowForm.vue | 103 ++++++- .../localBaserow/integrationTypes.js | 52 +++- .../integrations/localBaserow/serviceTypes.js | 4 + .../modules/integrations/locales/en.json | 7 +- .../test/unit/automation/nodeTypes.spec.js | 4 +- .../test/unit/builder/realtime.spec.js | 63 ++++ .../integrationCreateEditModal.spec.js | 82 +++++ .../settings/agents/manageAgentModal.spec.js | 40 +++ .../test/unit/core/components/tabs.spec.js | 13 + .../test/unit/core/store/agent.spec.js | 28 ++ .../test/unit/core/store/integration.spec.js | 36 +++ .../test/unit/core/subjectTypes.spec.js | 6 + .../test/unit/core/utils/workspace.spec.js | 18 ++ .../core/workspaceSettingsPageTypes.spec.js | 14 +- .../dataSync/configureDataSyncHistory.spec.js | 27 +- .../rowHistoryEntry.spec.js.snap | 22 ++ .../components/row/rowHistoryEntry.spec.js | 80 +++++ .../ai/aiAgentServiceForm.spec.js | 5 +- .../localBaserow/localBaserowForm.spec.js | 144 +++++++++ .../localBaserow/serviceTypes.spec.js | 43 +++ 165 files changed, 4958 insertions(+), 719 deletions(-) create mode 100644 backend/src/baserow/api/subjects/__init__.py create mode 100644 backend/src/baserow/api/subjects/serializers.py create mode 100644 backend/src/baserow/api/subjects/urls.py create mode 100644 backend/src/baserow/api/subjects/views.py create mode 100644 backend/src/baserow/contrib/database/migrations/0226_rowhistory_actor.py create mode 100644 backend/src/baserow/contrib/database/migrations/0227_backfill_rowhistory_anonymous_actor_type.py create mode 100644 backend/src/baserow/contrib/integrations/migrations/0039_localbaserowintegration_authorized_agent.py create mode 100644 backend/src/baserow/core/subject_options.py create mode 100644 backend/tests/baserow/api/subjects/__init__.py create mode 100644 backend/tests/baserow/api/subjects/test_subject_views.py create mode 100644 backend/tests/baserow/contrib/database/migrations/test_row_history_actor_migration.py create mode 100644 backend/tests/baserow/core/agents/test_agent_handler.py create mode 100644 changelog/entries/unreleased/breaking_change/5781_replaces_the_audit_log_users_endpoint_with_the_new_actors_en.json create mode 100644 enterprise/backend/src/baserow_enterprise/migrations/0068_auditlogentry_agent.py create mode 100644 enterprise/backend/tests/baserow_enterprise_tests/api/subjects/test_subject_views.py create mode 100644 enterprise/backend/tests/baserow_enterprise_tests/audit_log/test_audit_log_migrations.py create mode 100644 enterprise/web-frontend/modules/baserow_enterprise/components/auditLog/AuditLogActorDropdown.vue create mode 100644 enterprise/web-frontend/modules/baserow_enterprise/components/auditLog/AuditLogActorField.vue create mode 100644 enterprise/web-frontend/modules/baserow_enterprise/components/auditLog/AuditLogActorTypeField.vue create mode 100644 enterprise/web-frontend/test/unit/enterprise/auditLog/__snapshots__/auditLogActorDropdown.spec.js.snap create mode 100644 enterprise/web-frontend/test/unit/enterprise/auditLog/auditLogActorDropdown.spec.js create mode 100644 enterprise/web-frontend/test/unit/enterprise/auditLog/auditLogActorField.spec.js create mode 100644 enterprise/web-frontend/test/unit/enterprise/auditLog/auditLogActorTypeField.spec.js create mode 100644 enterprise/web-frontend/test/unit/enterprise/services/auditLog.spec.js create mode 100644 web-frontend/modules/core/services/subject.js create mode 100644 web-frontend/test/unit/core/components/integrations/integrationCreateEditModal.spec.js create mode 100644 web-frontend/test/unit/core/utils/workspace.spec.js create mode 100644 web-frontend/test/unit/database/components/row/__snapshots__/rowHistoryEntry.spec.js.snap create mode 100644 web-frontend/test/unit/database/components/row/rowHistoryEntry.spec.js create mode 100644 web-frontend/test/unit/integrations/localBaserow/localBaserowForm.spec.js diff --git a/AGENTS.md b/AGENTS.md index 84098d6b70..2a063aaf82 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -67,6 +67,7 @@ Do not commit secrets or local overrides. Use `.env.local` for development, keep - Django migrations must be executed with zero downtime. This means the new database schema must remain compatible with the previous application version during the deployment. - Every new field must define a `db_default` or accept `null` values if they are created on a previously existing model. - Do not remove fields unless you are certain they are no longer used by the previous application version. Instead, keep the field and add a `# TODO ZDM: remove this field in the next version` comment so it can be safely removed in a subsequent release. + - In production, migrations run before the backend rollout. Old and new backends may overlap for up to three minutes. Mixed-version compatibility is only required when that overlap could cause data loss or corruption; otherwise, do not add compatibility solely for it. If such a risk is found, ask the user whether it should be mitigated. - CSS classes respect BEM methodology. - When working on translations, only update english unless told otherwise. Other languages are handled with Weblate. Don't nest keys too much, just keep one level of nesting. - Prefer composition API for new frontend components diff --git a/backend/src/baserow/api/agents/serializers.py b/backend/src/baserow/api/agents/serializers.py index f16892327d..413db5149d 100644 --- a/backend/src/baserow/api/agents/serializers.py +++ b/backend/src/baserow/api/agents/serializers.py @@ -11,7 +11,7 @@ from baserow.core.models import Agent class AgentSubjectSerializer(serializers.ModelSerializer): class Meta: model = Agent - fields = ("id", "name") + fields = ("id", "name", "trashed") class AgentSerializer(serializers.ModelSerializer): diff --git a/backend/src/baserow/api/subjects/__init__.py b/backend/src/baserow/api/subjects/__init__.py new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/backend/src/baserow/api/subjects/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/src/baserow/api/subjects/serializers.py b/backend/src/baserow/api/subjects/serializers.py new file mode 100644 index 0000000000..8a1bc5d73d --- /dev/null +++ b/backend/src/baserow/api/subjects/serializers.py @@ -0,0 +1,39 @@ +from rest_framework import serializers + +from baserow.core.registries import subject_type_registry + + +class SubjectOptionsQueryParamsSerializer(serializers.Serializer): + page = serializers.IntegerField(min_value=1, required=False, default=1) + size = serializers.IntegerField(min_value=1, max_value=100, required=False) + search = serializers.CharField( + required=False, allow_blank=True, allow_null=True, default=None + ) + workspace_id = serializers.IntegerField(min_value=1, required=False, default=None) + subject_types = serializers.CharField(required=False, allow_blank=False) + + def validate_subject_types(self, value): + """Parse and validate a comma-separated list of registered subject types.""" + + requested_types = set(value.split(",")) + unknown_types = requested_types - set(subject_type_registry.get_types()) + if unknown_types: + raise serializers.ValidationError( + f"Unknown subject types: {', '.join(sorted(unknown_types))}." + ) + return requested_types + + +class SubjectOptionSerializer(serializers.Serializer): + id = serializers.SerializerMethodField() + subject_id = serializers.IntegerField(read_only=True) + subject_type = serializers.CharField(read_only=True) + name = serializers.CharField(source="subject_name", read_only=True) + label = serializers.CharField(source="subject_label", read_only=True) + email = serializers.EmailField( + source="subject_email", read_only=True, allow_null=True + ) + subject_count = serializers.IntegerField(read_only=True, allow_null=True) + + def get_id(self, instance): + return f"{instance['subject_type']}:{instance['subject_id']}" diff --git a/backend/src/baserow/api/subjects/urls.py b/backend/src/baserow/api/subjects/urls.py new file mode 100644 index 0000000000..7831ff668b --- /dev/null +++ b/backend/src/baserow/api/subjects/urls.py @@ -0,0 +1,7 @@ +from django.urls import path + +from .views import SubjectOptionsView + +app_name = "baserow.api.subjects" + +urlpatterns = [path("", SubjectOptionsView.as_view(), name="list")] diff --git a/backend/src/baserow/api/subjects/views.py b/backend/src/baserow/api/subjects/views.py new file mode 100644 index 0000000000..e6293fd7ac --- /dev/null +++ b/backend/src/baserow/api/subjects/views.py @@ -0,0 +1,68 @@ +from drf_spectacular.utils import extend_schema +from rest_framework.exceptions import PermissionDenied, ValidationError +from rest_framework.permissions import IsAuthenticated +from rest_framework.views import APIView + +from baserow.api.decorators import map_exceptions, validate_query_parameters +from baserow.api.errors import ERROR_GROUP_DOES_NOT_EXIST +from baserow.api.pagination import PageNumberPagination +from baserow.core.exceptions import WorkspaceDoesNotExist +from baserow.core.handler import CoreHandler +from baserow.core.registries import subject_type_registry +from baserow.core.subject_options import SubjectOptionsHandler +from baserow.core.types import PermissionCheck + +from .serializers import SubjectOptionSerializer, SubjectOptionsQueryParamsSerializer + + +class SubjectOptionsView(APIView): + permission_classes = (IsAuthenticated,) + + @extend_schema( + tags=["Subjects"], + operation_id="list_subject_options", + parameters=[SubjectOptionsQueryParamsSerializer], + responses={200: SubjectOptionSerializer(many=True)}, + description="Returns searchable options supplied by registered subject types.", + ) + @map_exceptions({WorkspaceDoesNotExist: ERROR_GROUP_DOES_NOT_EXIST}) + @validate_query_parameters( + SubjectOptionsQueryParamsSerializer, return_validated=True + ) + def get(self, request, query_params): + """Return subject options after checking the requested disclosure scope.""" + + workspace_id = query_params.get("workspace_id") + workspace = None + if workspace_id is not None: + workspace = CoreHandler().get_workspace(workspace_id) + requested_types = query_params.get("subject_types") or set( + subject_type_registry.get_types() + ) + operation_types = { + subject_type_registry.get(subject_type_name).options_list_operation_type + for subject_type_name in requested_types + } + checks = [ + PermissionCheck(request.user, operation_type, workspace) + for operation_type in operation_types + if operation_type is not None + ] + CoreHandler().check_multiple_permissions( + checks, workspace=workspace, raise_exception=True + ) + elif not request.user.is_staff: + raise PermissionDenied() + + try: + queryset = SubjectOptionsHandler.get_options( + workspace=workspace, + search=query_params.get("search") or "", + subject_types=query_params.get("subject_types"), + ) + except ValueError as exc: + raise ValidationError({"subject_types": str(exc)}) + paginator = PageNumberPagination(limit_page_size=100) + page = paginator.paginate_queryset(queryset, request, view=self) + serializer = SubjectOptionSerializer(page, many=True) + return paginator.get_paginated_response(serializer.data) diff --git a/backend/src/baserow/api/urls.py b/backend/src/baserow/api/urls.py index 69b2567e48..6e1be804eb 100755 --- a/backend/src/baserow/api/urls.py +++ b/backend/src/baserow/api/urls.py @@ -25,6 +25,7 @@ from .search import urls as search_urls from .settings import urls as settings_urls from .snapshots import urls as snapshots_urls from .spectacular.views import CachedSpectacularJSONAPIView +from .subjects import urls as subjects_urls from .templates import urls as templates_urls from .trash import urls as trash_urls from .two_factor_auth import urls as two_factor_urls @@ -57,6 +58,7 @@ urlpatterns = ( path("trash/", include(trash_urls, namespace="trash")), path("jobs/", include(jobs_urls, namespace="jobs")), path("snapshots/", include(snapshots_urls, namespace="snapshots")), + path("subjects/", include(subjects_urls, namespace="subjects")), path("_health/", include(health_urls, namespace="health")), path("notifications/", include(notifications_urls, namespace="notifications")), path("search/", include(search_urls, namespace="search")), diff --git a/backend/src/baserow/api/workspaces/users/serializers.py b/backend/src/baserow/api/workspaces/users/serializers.py index bcaa9451c6..69595f86fa 100644 --- a/backend/src/baserow/api/workspaces/users/serializers.py +++ b/backend/src/baserow/api/workspaces/users/serializers.py @@ -133,6 +133,9 @@ class WorkspaceUserWorkspaceSerializer(serializers.Serializer): read_only=True, help_text="List of all workspace users.", ) + agents_count = serializers.SerializerMethodField( + help_text="The number of agents in the workspace." + ) # WorkspaceUser fields order = serializers.IntegerField( @@ -151,6 +154,11 @@ class WorkspaceUserWorkspaceSerializer(serializers.Serializer): ) ai_features = serializers.SerializerMethodField(read_only=True) + def get_agents_count(self, workspace_user): + """Return the annotated agent count without issuing another query.""" + + return getattr(workspace_user, "workspace_agent_count", 0) + def _get_ai_provider_state(self, workspace_user): """ Resolve this workspace's AI provider state once for both AI fields. diff --git a/backend/src/baserow/api/workspaces/views.py b/backend/src/baserow/api/workspaces/views.py index 12ce0966c7..42f038516f 100755 --- a/backend/src/baserow/api/workspaces/views.py +++ b/backend/src/baserow/api/workspaces/views.py @@ -111,6 +111,7 @@ class WorkspacesView(RealtimeRecoveryPrimaryReadMixin, APIView): CoreHandler() .get_workspaceuser_workspace_queryset() .filter(user=request.user) + .order_by("order", "id") ) workspaceuser_workspaces = ( diff --git a/backend/src/baserow/contrib/automation/application_types.py b/backend/src/baserow/contrib/automation/application_types.py index e2a519e75f..756125c6db 100644 --- a/backend/src/baserow/contrib/automation/application_types.py +++ b/backend/src/baserow/contrib/automation/application_types.py @@ -137,6 +137,7 @@ class AutomationApplicationType(ApplicationType): files_zip: Optional[ZipFile] = None, storage: Optional[Storage] = None, progress_builder: Optional[ChildProgressBuilder] = None, + import_export_config: Optional[ImportExportConfig] = None, ) -> List[Integration]: """ Import integrations to builder. This method has to be compatible with the output @@ -163,6 +164,7 @@ class AutomationApplicationType(ApplicationType): automation, serialized_integration, id_mapping, + import_export_config=import_export_config, cache=self.cache, files_zip=files_zip, storage=storage, @@ -226,6 +228,7 @@ class AutomationApplicationType(ApplicationType): files_zip, storage, progress.create_child_builder(represents_progress=integration_progress), + import_export_config=import_export_config, ) if not serialized_workflows: diff --git a/backend/src/baserow/contrib/automation/history/handler.py b/backend/src/baserow/contrib/automation/history/handler.py index e9694c6106..02c0529510 100644 --- a/backend/src/baserow/contrib/automation/history/handler.py +++ b/backend/src/baserow/contrib/automation/history/handler.py @@ -102,9 +102,7 @@ class AutomationHistoryHandler: triggered_by_values = { "triggered_by_id": triggered_by.id, "triggered_by_type": subject_type.type, - # TODO: use `subject_type.get_display_name` once agents are - # subjects (#6064). Users are the only subject starting a run. - "triggered_by_name": triggered_by.first_name, + "triggered_by_name": subject_type.get_display_name(triggered_by), } return AutomationWorkflowHistory.objects.create( diff --git a/backend/src/baserow/contrib/builder/application_types.py b/backend/src/baserow/contrib/builder/application_types.py index 9ed00f26ac..11c96327ac 100755 --- a/backend/src/baserow/contrib/builder/application_types.py +++ b/backend/src/baserow/contrib/builder/application_types.py @@ -298,6 +298,7 @@ class BuilderApplicationType(ApplicationType): files_zip: Optional[ZipFile] = None, storage: Optional[Storage] = None, progress_builder: Optional[ChildProgressBuilder] = None, + import_export_config: Optional[ImportExportConfig] = None, ) -> List[Integration]: """ Import integrations to builder. This method has to be compatible with the output @@ -323,6 +324,7 @@ class BuilderApplicationType(ApplicationType): builder, serialized_integration, id_mapping, + import_export_config=import_export_config, cache=self.cache, files_zip=files_zip, storage=storage, @@ -451,6 +453,7 @@ class BuilderApplicationType(ApplicationType): files_zip, storage, progress.create_child_builder(represents_progress=integration_progress), + import_export_config=import_export_config, ) if not serialized_user_sources: diff --git a/backend/src/baserow/contrib/builder/builder_beta_init_application.py b/backend/src/baserow/contrib/builder/builder_beta_init_application.py index 078ab4fb41..2ab6722622 100644 --- a/backend/src/baserow/contrib/builder/builder_beta_init_application.py +++ b/backend/src/baserow/contrib/builder/builder_beta_init_application.py @@ -91,7 +91,8 @@ class BuilderApplicationTypeInitApplication: return IntegrationHandler().create_integration( integration_type_registry.get("local_baserow"), self.application, - authorized_user=self.user, + authorized_subject_type="auth.User", + authorized_subject_id=self.user.id, name=self.first_integration_name, ) diff --git a/backend/src/baserow/contrib/builder/domains/job_types.py b/backend/src/baserow/contrib/builder/domains/job_types.py index 4a93747540..c7832f357e 100755 --- a/backend/src/baserow/contrib/builder/domains/job_types.py +++ b/backend/src/baserow/contrib/builder/domains/job_types.py @@ -1,6 +1,7 @@ from baserow.api.errors import ERROR_USER_NOT_IN_GROUP from baserow.contrib.builder.api.domains.errors import ERROR_DOMAIN_DOES_NOT_EXIST from baserow.core.exceptions import UserNotInWorkspace +from baserow.core.integrations.exceptions import IntegrationImproperlyConfigured from baserow.core.jobs.registries import JobType from baserow.core.registries import application_type_registry @@ -16,6 +17,10 @@ class PublishDomainJobType(JobType): type = "publish_domain" model_class = PublishDomainJob max_count = 2 + job_exceptions_map = { + IntegrationImproperlyConfigured: "The application contains an improperly " + "configured integration: {e}" + } api_exceptions_map = { UserNotInWorkspace: ERROR_USER_NOT_IN_GROUP, diff --git a/backend/src/baserow/contrib/builder/populate.py b/backend/src/baserow/contrib/builder/populate.py index c9979d386b..f367c40459 100644 --- a/backend/src/baserow/contrib/builder/populate.py +++ b/backend/src/baserow/contrib/builder/populate.py @@ -80,7 +80,11 @@ def load_test_data(): ) except Integration.DoesNotExist: integration = IntegrationHandler().create_integration( - integration_type, builder, name="Local baserow", authorized_user=user + integration_type, + builder, + name="Local baserow", + authorized_subject_type="auth.User", + authorized_subject_id=user.id, ) heading_element_type = element_type_registry.get("heading") diff --git a/backend/src/baserow/contrib/dashboard/application_types.py b/backend/src/baserow/contrib/dashboard/application_types.py index 6a40155d72..0d5a7495e0 100644 --- a/backend/src/baserow/contrib/dashboard/application_types.py +++ b/backend/src/baserow/contrib/dashboard/application_types.py @@ -47,7 +47,8 @@ class DashboardApplicationType(ApplicationType): LocalBaserowIntegrationType.type ), application=application, - authorized_user=user, + authorized_subject_type="auth.User", + authorized_subject_id=user.id, ) def pre_delete(self, dashboard): diff --git a/backend/src/baserow/contrib/database/api/rows/serializers.py b/backend/src/baserow/contrib/database/api/rows/serializers.py index dded2405c3..e9c522ffec 100644 --- a/backend/src/baserow/contrib/database/api/rows/serializers.py +++ b/backend/src/baserow/contrib/database/api/rows/serializers.py @@ -17,6 +17,7 @@ from baserow.contrib.database.rows.registries import ( RowMetadataType, row_metadata_registry, ) +from baserow.core.subjects import UserSubjectType class RowSerializer(serializers.ModelSerializer): @@ -622,22 +623,32 @@ class GetRowAdjacentSerializer( class RowHistoryUserSerializer(serializers.Serializer): id = serializers.IntegerField( - source="user_id", + source="actor_id", + allow_null=True, help_text="The id of the user.", ) name = serializers.CharField( - source="user_name", + source="actor_name", help_text="The first name of the user.", ) +class RowHistoryActorSerializer(serializers.Serializer): + id = serializers.IntegerField(source="actor_id", allow_null=True) + type = serializers.CharField(source="actor_type") + name = serializers.CharField(source="actor_name") + + class RowHistorySerializer(serializers.ModelSerializer): timestamp = serializers.DateTimeField( source="action_timestamp", help_text="The timestamp of the action that was performed.", ) - user = RowHistoryUserSerializer( - source="*", help_text="The user that performed the action." + user = serializers.SerializerMethodField( + help_text="Deprecated. Use actor instead. Null for non-user actors.", + ) + actor = RowHistoryActorSerializer( + source="*", help_text="The actor that performed the action." ) before = serializers.JSONField( source="before_values", @@ -648,6 +659,11 @@ class RowHistorySerializer(serializers.ModelSerializer): help_text="The mapping between field_ids and values for the row after the action was performed.", ) + def get_user(self, instance): + if instance.actor_type != UserSubjectType.type: + return None + return RowHistoryUserSerializer(instance).data + class Meta: model = RowHistory fields = [ @@ -655,6 +671,7 @@ class RowHistorySerializer(serializers.ModelSerializer): "action_type", "action_command_type", "user", + "actor", "timestamp", "before", "after", diff --git a/backend/src/baserow/contrib/database/fields/notification_types.py b/backend/src/baserow/contrib/database/fields/notification_types.py index 88de18da02..859b41211e 100644 --- a/backend/src/baserow/contrib/database/fields/notification_types.py +++ b/backend/src/baserow/contrib/database/fields/notification_types.py @@ -12,7 +12,10 @@ from baserow.contrib.database.fields.field_types import ( LongTextFieldType, MultipleCollaboratorsFieldType, ) -from baserow.contrib.database.rows.handler import RowM2MChangeTracker +from baserow.contrib.database.rows.handler import ( + RowM2MChangeTracker, + user_for_row_audit_columns, +) from baserow.contrib.database.rows.signals import rows_created, rows_updated from baserow.contrib.database.table.models import RichTextFieldMention from baserow.core.notifications.handler import ( @@ -182,7 +185,9 @@ class UserMentionInRichTextFieldNotificationType( return _( "%(sender)s mentioned you in %(field_name)s in row %(row_name)s in %(table_name)s." ) % { - "sender": notification.sender.first_name, + "sender": notification.sender.first_name + if notification.sender + else _("An unknown user"), "field_name": notification.data["field_name"], "row_name": notification.data.get("row_name", notification.data["row_id"]), "table_name": notification.data["table_name"], @@ -374,13 +379,14 @@ def notify_users_when_rows_created( m2m_change_tracker=None, **kwargs, ): + notification_sender = user_for_row_audit_columns(user) if m2m_change_tracker is not None: CollaboratorAddedToRowNotificationType.create_notifications_grouped_by_user( - user, m2m_change_tracker, rows + notification_sender, m2m_change_tracker, rows ) UserMentionInRichTextFieldNotificationType.create_notifications_grouped_by_user( - user, rows + notification_sender, rows ) @@ -396,11 +402,12 @@ def notify_users_when_rows_updated( m2m_change_tracker=None, **kwargs, ): + notification_sender = user_for_row_audit_columns(user) if m2m_change_tracker is not None: CollaboratorAddedToRowNotificationType.create_notifications_grouped_by_user( - user, m2m_change_tracker, rows + notification_sender, m2m_change_tracker, rows ) UserMentionInRichTextFieldNotificationType.create_notifications_grouped_by_user( - user, rows, updated_field_ids + notification_sender, rows, updated_field_ids ) diff --git a/backend/src/baserow/contrib/database/migrations/0226_rowhistory_actor.py b/backend/src/baserow/contrib/database/migrations/0226_rowhistory_actor.py new file mode 100644 index 0000000000..0afb7340b7 --- /dev/null +++ b/backend/src/baserow/contrib/database/migrations/0226_rowhistory_actor.py @@ -0,0 +1,59 @@ +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("database", "0225_rich_text_file_uniques"), + ] + + operations = [ + migrations.SeparateDatabaseAndState( + database_operations=[ + migrations.AlterField( + model_name="rowhistory", + name="user_name", + field=models.CharField( + blank=True, + help_text="The name of the user that performed the action.", + max_length=160, + ), + ), + ], + state_operations=[ + migrations.RenameField( + model_name="rowhistory", + old_name="user_id", + new_name="actor_id", + ), + migrations.AlterField( + model_name="rowhistory", + name="actor_id", + field=models.PositiveIntegerField( + db_column="user_id", + help_text="The ID of the actor that performed the action.", + null=True, + ), + ), + migrations.RenameField( + model_name="rowhistory", + old_name="user_name", + new_name="actor_name", + ), + migrations.AlterField( + model_name="rowhistory", + name="actor_name", + field=models.CharField( + blank=True, + db_column="user_name", + help_text="The name of the actor that performed the action.", + max_length=160, + ), + ), + ], + ), + migrations.AddField( + model_name="rowhistory", + name="actor_type", + field=models.CharField(db_default="auth.User", max_length=255), + ), + ] diff --git a/backend/src/baserow/contrib/database/migrations/0227_backfill_rowhistory_anonymous_actor_type.py b/backend/src/baserow/contrib/database/migrations/0227_backfill_rowhistory_anonymous_actor_type.py new file mode 100644 index 0000000000..9fa18844d1 --- /dev/null +++ b/backend/src/baserow/contrib/database/migrations/0227_backfill_rowhistory_anonymous_actor_type.py @@ -0,0 +1,37 @@ +from django.db import migrations, transaction + + +ROW_HISTORY_BACKFILL_BATCH_SIZE = 10_000 + + +def set_anonymous_actor_type(apps, schema_editor): + """Backfill anonymous actors in short, primary-key-ordered transactions.""" + + RowHistory = apps.get_model("database", "RowHistory") + database_alias = schema_editor.connection.alias + last_id = 0 + + while row_history_ids := list( + RowHistory.objects.using(database_alias) + .filter(id__gt=last_id, actor_id__isnull=True) + .order_by("id") + .values_list("id", flat=True)[:ROW_HISTORY_BACKFILL_BATCH_SIZE] + ): + with transaction.atomic(using=database_alias): + RowHistory.objects.using(database_alias).filter( + id__in=row_history_ids, + actor_id__isnull=True, + ).update(actor_type="anonymous") + last_id = row_history_ids[-1] + + +class Migration(migrations.Migration): + atomic = False + + dependencies = [ + ("database", "0226_rowhistory_actor"), + ] + + operations = [ + migrations.RunPython(set_anonymous_actor_type, migrations.RunPython.noop), + ] diff --git a/backend/src/baserow/contrib/database/rows/handler.py b/backend/src/baserow/contrib/database/rows/handler.py index ee5b443974..3ac86187a5 100644 --- a/backend/src/baserow/contrib/database/rows/handler.py +++ b/backend/src/baserow/contrib/database/rows/handler.py @@ -121,6 +121,13 @@ from .types import ( UpdatedRowsData, ) + +def user_for_row_audit_columns(actor): + """Return a real user for generated-table user foreign keys.""" + + return actor if isinstance(actor, AbstractUser) and actor.id else None + + if TYPE_CHECKING: from django.db.backends.utils import CursorWrapper @@ -1252,7 +1259,7 @@ class RowHandler: if signal_params is None: signal_params = {} - user_id = user and user.id + audit_user = user_for_row_audit_columns(user) unique_orders = self.get_unique_orders_before_row( before_row, model, amount=len(rows_values) @@ -1287,10 +1294,10 @@ class RowHandler: row_values["order"] = unique_orders[index] if getattr(model, CREATED_BY_COLUMN_NAME, None): - row_values[CREATED_BY_COLUMN_NAME] = user if user_id else None + row_values[CREATED_BY_COLUMN_NAME] = audit_user if getattr(model, LAST_MODIFIED_BY_COLUMN_NAME, None): - row_values[LAST_MODIFIED_BY_COLUMN_NAME] = user if user_id else None + row_values[LAST_MODIFIED_BY_COLUMN_NAME] = audit_user instance = model(**row_values) field_rules_handler.validate_row(instance) @@ -2338,7 +2345,7 @@ class RowHandler: if model is None: model = table.get_model() - user_id = user and user.id + audit_user = user_for_row_audit_columns(user) if values_already_prepared: # Row IDs are removed below, so do not mutate the caller's dictionaries. @@ -2427,7 +2434,7 @@ class RowHandler: setattr(obj, name, value) if getattr(model, LAST_MODIFIED_BY_COLUMN_NAME, None): - setattr(obj, LAST_MODIFIED_BY_COLUMN_NAME, user if user_id else None) + setattr(obj, LAST_MODIFIED_BY_COLUMN_NAME, audit_user) relations = { field_name: value @@ -3038,7 +3045,9 @@ class RowHandler: ) workspace = table.database.workspace - TrashHandler.trash(user, workspace, table.database, row) + TrashHandler.trash( + user_for_row_audit_columns(user), workspace, table.database, row + ) rows_deleted_counter.add(1) ( @@ -3254,7 +3263,12 @@ class RowHandler: # for example used when storing the names in the trash. trashed_rows.rows = rows - TrashHandler.trash(user, workspace, table.database, trashed_rows) + TrashHandler.trash( + user_for_row_audit_columns(user), + workspace, + table.database, + trashed_rows, + ) rows_deleted_counter.add(len(row_ids)) diff --git a/backend/src/baserow/contrib/database/rows/helpers.py b/backend/src/baserow/contrib/database/rows/helpers.py index be0ba7cebc..1fc1dd56e9 100644 --- a/backend/src/baserow/contrib/database/rows/helpers.py +++ b/backend/src/baserow/contrib/database/rows/helpers.py @@ -1,7 +1,5 @@ from typing import Any, Callable, Dict, List, Optional -from django.contrib.auth.models import AbstractUser, AnonymousUser - from opentelemetry import trace from baserow.contrib.database.fields.registries import field_type_registry @@ -11,22 +9,28 @@ from baserow.contrib.database.rows.types import ( RelatedRowsDiff, RowChangeDiff, ) +from baserow.core.registries import subject_type_registry +from baserow.core.types import Subject tracer = trace.get_tracer(__name__) +def get_row_history_actor_values(actor: Subject) -> tuple[int | None, str, str]: + subject_type = subject_type_registry.get_by_model(actor) + return actor.id, subject_type.type, subject_type.get_display_name(actor) + + def construct_entry_from_action_and_diff( - user: AbstractUser, + actor: Subject, action: ActionData, fields_metadata: Dict[str, Any], row_diff: RowChangeDiff, ): - if isinstance(user, AnonymousUser): - user.first_name = "Anonymous" - user.last_name = "User" + actor_id, actor_type, actor_name = get_row_history_actor_values(actor) return RowHistory( - user_id=user.id, - user_name=user.first_name, + actor_id=actor_id, + actor_type=actor_type, + actor_name=actor_name, table_id=row_diff.table_id, row_id=row_diff.row_id, field_names=row_diff.changed_field_names, @@ -183,7 +187,7 @@ def update_related_tables_entries( def construct_related_rows_entries( related_rows_diff: RelatedRowsDiff, - user: AbstractUser, + actor: Subject, action: ActionData, ) -> List[RowHistory]: """ @@ -195,7 +199,7 @@ def construct_related_rows_entries( :param related_rows_diff: A nested dictionary that tracks changes for each affected related row. It includes details about rows added or removed from link_row relationships. - :param user: The user who performed the action that triggered the changes. + :param actor: The subject that performed the action that triggered the changes. :param action: The action metadata that describes the operation performed. :return: A list of RowHistory entries representing the changes for the related rows. @@ -213,9 +217,11 @@ def construct_related_rows_entries( before_values[field_name] = row_field_changes["removed"] after_values[field_name] = row_field_changes["added"] + actor_id, actor_type, actor_name = get_row_history_actor_values(actor) linked_entry = RowHistory( - user_id=user.id, - user_name=user.first_name, + actor_id=actor_id, + actor_type=actor_type, + actor_name=actor_name, table_id=linked_table_id, row_id=linked_row_id, field_names=field_names, diff --git a/backend/src/baserow/contrib/database/rows/models.py b/backend/src/baserow/contrib/database/rows/models.py index 075e08cfab..d019201046 100644 --- a/backend/src/baserow/contrib/database/rows/models.py +++ b/backend/src/baserow/contrib/database/rows/models.py @@ -3,17 +3,24 @@ from django.db import models from baserow.core.action.signals import ActionCommandType from baserow.core.encoders import JSONEncoderSupportingDataClasses +from baserow.core.subjects import UserSubjectType class RowHistory(models.Model): - user_id = models.PositiveIntegerField( + # Reuse the former user columns so existing entries become User actors without a + # data migration. The actor type must always be used together with the actor ID + # because User and Agent primary keys can overlap. + actor_id = models.PositiveIntegerField( + db_column="user_id", null=True, - help_text="The id of the user that performed the action.", + help_text="The ID of the actor that performed the action.", ) - user_name = models.CharField( - max_length=150, + actor_type = models.CharField(max_length=255, db_default=UserSubjectType.type) + actor_name = models.CharField( + db_column="user_name", + max_length=160, blank=True, - help_text="The name of the user that performed the action.", + help_text="The name of the actor that performed the action.", ) table = models.ForeignKey( "database.Table", diff --git a/backend/src/baserow/contrib/integrations/ai/integration_types.py b/backend/src/baserow/contrib/integrations/ai/integration_types.py index 753a3f6335..76fd3dc413 100644 --- a/backend/src/baserow/contrib/integrations/ai/integration_types.py +++ b/backend/src/baserow/contrib/integrations/ai/integration_types.py @@ -49,7 +49,11 @@ class AIIntegrationType(IntegrationType): } def prepare_values( - self, values: Dict[str, Any], user: AbstractUser + self, + values: Dict[str, Any], + user: AbstractUser, + application: Application | None = None, + instance: AIIntegration | None = None, ) -> Dict[str, Any]: """Validate explicit per-integration provider settings before saving. @@ -71,7 +75,9 @@ class AIIntegrationType(IntegrationType): ) values["ai_settings"] = validated_settings - return super().prepare_values(values, user) + return super().prepare_values( + values, user, application=application, instance=instance + ) def get_integration_provider_settings( self, integration: AIIntegration, provider_type: str @@ -131,6 +137,7 @@ class AIIntegrationType(IntegrationType): files_zip=None, storage=None, cache=None, + import_export_config=None, ) -> AIIntegration: if cache is None: cache = {} @@ -142,6 +149,7 @@ class AIIntegrationType(IntegrationType): application, serialized_values, id_mapping, + import_export_config=import_export_config, files_zip=files_zip, storage=storage, cache=cache, diff --git a/backend/src/baserow/contrib/integrations/core/integration_types.py b/backend/src/baserow/contrib/integrations/core/integration_types.py index d9e9f67eff..b4aec9eb58 100644 --- a/backend/src/baserow/contrib/integrations/core/integration_types.py +++ b/backend/src/baserow/contrib/integrations/core/integration_types.py @@ -1,4 +1,4 @@ -from typing import Any, Dict +from typing import Any, Dict, Optional from django.contrib.auth.models import AbstractUser @@ -54,7 +54,11 @@ class SMTPIntegrationType(IntegrationType): } def prepare_values( - self, values: Dict[str, Any], user: AbstractUser + self, + values: Dict[str, Any], + user: AbstractUser, + application: Optional[Any] = None, + instance: Optional[SMTPIntegration] = None, ) -> Dict[str, Any]: """ STARTTLS and implicit SSL/TLS are two ways of encrypting the same @@ -72,7 +76,9 @@ class SMTPIntegrationType(IntegrationType): elif values.get("use_tls"): values["use_ssl"] = False - return super().prepare_values(values, user) + return super().prepare_values( + values, user, application=application, instance=instance + ) def deserialize_property( self, diff --git a/backend/src/baserow/contrib/integrations/local_baserow/integration_types.py b/backend/src/baserow/contrib/integrations/local_baserow/integration_types.py index 862eaa0c28..dfcc925ff8 100644 --- a/backend/src/baserow/contrib/integrations/local_baserow/integration_types.py +++ b/backend/src/baserow/contrib/integrations/local_baserow/integration_types.py @@ -5,20 +5,34 @@ from typing import Any, Dict, List, Optional from django.contrib.auth import get_user_model from django.contrib.auth.models import AbstractUser -from baserow.api.user.serializers import SubjectUserSerializer +from rest_framework import serializers + from baserow.contrib.database.table.handler import TableHandler from baserow.contrib.database.views.handler import ViewHandler from baserow.contrib.integrations.api.local_baserow.serializers import ( LocalBaserowContextDataSerializer, ) from baserow.contrib.integrations.local_baserow.models import LocalBaserowIntegration +from baserow.core.integrations.exceptions import IntegrationImproperlyConfigured from baserow.core.integrations.models import Integration from baserow.core.integrations.registries import IntegrationType from baserow.core.integrations.types import IntegrationDict from baserow.core.models import Application +from baserow.core.registries import ImportExportConfig, subject_type_registry -User = get_user_model() logger = logging.getLogger(__name__) +User = get_user_model() + + +class AuthorizedSubjectSerializerField(serializers.Field): + """Serialize a Local Baserow integration's authorization subject.""" + + def to_representation(self, subject): + if subject is None: + return None + serialized = subject_type_registry.get_serializer(subject).data + serialized["type"] = subject_type_registry.get_by_model(subject).type + return serialized class LocalBaserowIntegrationType(IntegrationType): @@ -26,28 +40,96 @@ class LocalBaserowIntegrationType(IntegrationType): model_class = LocalBaserowIntegration class SerializedDict(IntegrationDict): - authorized_user: str + authorized_subject_type: Optional[str] + authorized_subject_id: Optional[int] - serializer_field_names = ["context_data", "authorized_user"] - allowed_fields = ["authorized_user"] - sensitive_fields = ["authorized_user"] + serializer_field_names = [ + "context_data", + "authorized_subject", + ] + allowed_fields = [ + "authorized_subject_type", + "authorized_subject_id", + ] + sensitive_fields = ["authorized_subject_type", "authorized_subject_id"] serializer_field_overrides = { "context_data": LocalBaserowContextDataSerializer(read_only=True), - "authorized_user": SubjectUserSerializer(read_only=True), + # Include a trashed agent so clients can show the integration in error. + "authorized_subject": AuthorizedSubjectSerializerField( + source="authorized_subject_including_trash", read_only=True + ), } - request_serializer_field_names = [] - request_serializer_field_overrides = {} + request_serializer_field_names = [ + "authorized_subject_id", + "authorized_subject_type", + ] + request_serializer_field_overrides = { + "authorized_subject_id": serializers.IntegerField( + required=False, + allow_null=True, + help_text="The ID of the subject whose permissions authenticate the integration.", + ), + "authorized_subject_type": serializers.ChoiceField( + choices=["auth.User", "core.Agent"], required=False, allow_null=True + ), + } def prepare_values( - self, values: Dict[str, Any], user: AbstractUser + self, + values: Dict[str, Any], + user: AbstractUser, + application: Optional[Application] = None, + instance: Optional[LocalBaserowIntegration] = None, ) -> Dict[str, Any]: - """Add the logged in user by default""" + """Resolve and validate the typed authorization subject in this workspace.""" - values["authorized_user"] = user + subject_id = values.get("authorized_subject_id") + subject_type_name = values.get("authorized_subject_type") + if subject_id is None and subject_type_name is None: + authorization_not_updated = not { + "authorized_subject_id", + "authorized_subject_type", + }.intersection(values) + has_existing_authorization = instance is not None and ( + instance.authorized_subject_type and instance.authorized_subject_id + ) + if authorization_not_updated and has_existing_authorization: + return super().prepare_values( + values, user, application=application, instance=instance + ) + subject_type = subject_type_registry.get_by_model(user) + values["authorized_subject_type"] = subject_type.type + values["authorized_subject_id"] = user.id + elif subject_id is None or subject_type_name is None: + raise serializers.ValidationError( + "authorized_subject_id and authorized_subject_type must be provided together." + ) + else: + if subject_type_name == "auth.User" and subject_id != user.id: + raise serializers.ValidationError( + { + "authorized_subject_id": ( + "Only the current user can authorize this integration." + ) + } + ) + subject_type = subject_type_registry.get(subject_type_name) + subject = subject_type_registry.get_subject(subject_type_name, subject_id) + workspace = application.workspace + if subject is None or not subject_type.is_in_workspace(subject, workspace): + raise serializers.ValidationError( + {"authorized_subject_id": "The subject does not exist."} + ) + if getattr(subject, "trashed", False): + raise serializers.ValidationError( + {"authorized_subject_id": "The agent is trashed."} + ) - return super().prepare_values(values, user) + return super().prepare_values( + values, user, application=application, instance=instance + ) def serialize_property( self, @@ -58,19 +140,61 @@ class LocalBaserowIntegrationType(IntegrationType): cache=None, ): """ - Replace the authorized user property with it's username. Better when loading the - data later. + Serialize the canonical subject pair for import/export. """ - if prop_name == "authorized_user": - if integration.authorized_user: - return integration.authorized_user.username + if prop_name == "authorized_subject": return None + if prop_name == "authorized_subject_type": + return integration.authorized_subject_type + + if prop_name == "authorized_subject_id": + return integration.authorized_subject_id + return super().serialize_property( integration, prop_name, files_zip=files_zip, storage=storage, cache=cache ) + def export_serialized( + self, + instance: LocalBaserowIntegration, + import_export_config: Optional[ImportExportConfig] = None, + files_zip=None, + storage=None, + cache=None, + ): + """Preserve canonical authorization only in same-workspace publications.""" + + if import_export_config and import_export_config.is_publishing: + subject = None + if instance.authorized_subject_type and instance.authorized_subject_id: + subject_type = subject_type_registry.get( + instance.authorized_subject_type + ) + manager = getattr( + subject_type.model_class, + "objects_and_trash", + subject_type.model_class.objects, + ) + subject = manager.filter(id=instance.authorized_subject_id).first() + if getattr(subject, "trashed", False): + raise IntegrationImproperlyConfigured( + "The authorized subject is trashed." + ) + + serialized = super().export_serialized( + instance, + import_export_config=import_export_config, + files_zip=files_zip, + storage=storage, + cache=cache, + ) + if import_export_config and import_export_config.is_publishing: + serialized["authorized_subject_type"] = instance.authorized_subject_type + serialized["authorized_subject_id"] = instance.authorized_subject_id + return serialized + def after_import( self, user: AbstractUser, instance: LocalBaserowIntegration ) -> None: @@ -79,11 +203,22 @@ class LocalBaserowIntegrationType(IntegrationType): specific post-import logic. """ - # The authorized_user is a sensitive field that is excluded from the - # the exported workspace. Since this value is needed for the integration - # to work, it is manually set here using the current user. - instance.authorized_user = user - instance.save() + if ( + instance.application.workspace_id is None + and instance.authorized_subject_type + and instance.authorized_subject_id + ): + return + + # Imports from another workspace are always reauthorized to the importer. + instance.authorized_subject_type = subject_type_registry.get_by_model(user).type + instance.authorized_subject_id = user.id + instance.save( + update_fields=[ + "authorized_subject_type", + "authorized_subject_id", + ] + ) def import_serialized( self, @@ -93,44 +228,49 @@ class LocalBaserowIntegrationType(IntegrationType): files_zip=None, storage=None, cache=None, + import_export_config: Optional[ImportExportConfig] = None, ) -> LocalBaserowIntegration: """ - Imports a serialized integration. Handles the user part with a cache for - better performances. + Import a serialized integration, accepting legacy user authorization. + + Workspace exports made before typed subjects stored the user email in + ``authorized_user``. Resolve it to the matching workspace user and convert + it to the canonical subject pair before importing. """ if cache is None: cache = {} - if "workspace_users" not in cache: - # In order to prevent a lot of lookup queries in the through table, we want - # to fetch all the users and add it to a temporary in memory cache - # containing a mapping of user per email - cache["workspace_users"] = { - user.username: user - for user in User.objects.filter( - workspaceuser__workspace_id=id_mapping["import_workspace_id"] - ) - } - + serialized_values = serialized_values.copy() username = serialized_values.pop("authorized_user", None) - if username: - serialized_values["authorized_user"] = cache["workspace_users"].get( - username, None + workspace_users = cache.setdefault( + "local_baserow_workspace_users", + { + user.username: user + for user in User.objects.filter( + workspaceuser__workspace_id=id_mapping["import_workspace_id"] + ) + }, ) + legacy_authorized_user = workspace_users.get(username) + if legacy_authorized_user: + serialized_values["authorized_subject_type"] = "auth.User" + serialized_values["authorized_subject_id"] = legacy_authorized_user.id - return super().import_serialized( + integration = super().import_serialized( application, serialized_values, id_mapping, + import_export_config=import_export_config, files_zip=files_zip, storage=storage, cache=cache, ) + return integration def enhance_queryset(self, queryset): - return queryset.select_related("authorized_user") + return queryset def get_context_data(self, instance: LocalBaserowIntegration) -> Optional[Dict]: try: @@ -161,12 +301,12 @@ class LocalBaserowIntegrationType(IntegrationType): if not integration.application.workspace_id: return [] - user = integration.specific.authorized_user + subject = integration.specific.authorized_subject workspace = integration.application.workspace - tables = TableHandler().list_workspace_tables(user, workspace) + tables = TableHandler().list_workspace_tables(subject, workspace) - views = ViewHandler().list_workspace_views(user, workspace, specific=False) + views = ViewHandler().list_workspace_views(subject, workspace, specific=False) views = list( views.only( diff --git a/backend/src/baserow/contrib/integrations/local_baserow/models.py b/backend/src/baserow/contrib/integrations/local_baserow/models.py index 9eabdbe7de..55c21e0725 100644 --- a/backend/src/baserow/contrib/integrations/local_baserow/models.py +++ b/backend/src/baserow/contrib/integrations/local_baserow/models.py @@ -1,4 +1,3 @@ -from django.contrib.auth import get_user_model from django.db import models from django.db.models import F, OrderBy @@ -11,6 +10,8 @@ from baserow.contrib.database.views.models import ( SORT_ORDER_CHOICES, View, ) +from baserow.core.cache import local_cache +from baserow.core.exceptions import SubjectTypeNotExist from baserow.core.formula.field import FormulaField from baserow.core.integrations.models import Integration from baserow.core.services.models import ( @@ -21,8 +22,6 @@ from baserow.core.services.models import ( ServiceSort, ) -User = get_user_model() - class LocalBaserowIntegration(Integration): """ @@ -30,7 +29,57 @@ class LocalBaserowIntegration(Integration): accessible by the associated user can be accessed with this integration. """ - authorized_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) + authorized_subject_type = models.CharField( + max_length=255, + null=True, + blank=True, + default="auth.User", + db_default="auth.User", + ) + authorized_subject_id = models.BigIntegerField( + null=True, blank=True, db_column="authorized_user_id" + ) + + def get_authorized_subject(self, include_trash: bool = False): + """ + Return the subject whose permissions are used by this integration. + + :param include_trash: Whether a trashed subject (e.g. a trashed agent) is + returned. It must never be used to act, only to report why the + integration can't be used. + """ + + if self.authorized_subject_type and self.authorized_subject_id: + from baserow.core.registries import subject_type_registry + + def get_subject(): + try: + return subject_type_registry.get_subject( + self.authorized_subject_type, + self.authorized_subject_id, + include_trash=include_trash, + ) + except SubjectTypeNotExist: + return None + + return local_cache.get( + "local_baserow_authorized_subject_" + f"{self.authorized_subject_type}_{self.authorized_subject_id}_" + f"{include_trash}", + get_subject, + ) + + @property + def authorized_subject(self): + """Return the usable subject, so None when it has been trashed.""" + + return self.get_authorized_subject() + + @property + def authorized_subject_including_trash(self): + """Return the subject even when trashed, to report its trashed state.""" + + return self.get_authorized_subject(include_trash=True) class LocalBaserowTableService(Service): diff --git a/backend/src/baserow/contrib/integrations/local_baserow/receivers.py b/backend/src/baserow/contrib/integrations/local_baserow/receivers.py index 0f5d0f9aab..8edad3568d 100644 --- a/backend/src/baserow/contrib/integrations/local_baserow/receivers.py +++ b/backend/src/baserow/contrib/integrations/local_baserow/receivers.py @@ -1,7 +1,12 @@ from django.dispatch import receiver from baserow.contrib.database.table.signals import table_schema_changed +from baserow.contrib.integrations.local_baserow.models import LocalBaserowIntegration from baserow.core.cache import global_cache, local_cache +from baserow.core.models import Agent +from baserow.core.registries import subject_type_registry +from baserow.core.signals import user_permanently_deleted +from baserow.core.trash.signals import before_permanently_deleted @receiver(table_schema_changed) @@ -9,3 +14,28 @@ def invalidate_table_cache(sender, table_id, **kwargs): # Invalidate local cache when the table schema is updated global_cache.invalidate(invalidate_key=f"table_{table_id}__service_invalidate_key") local_cache.delete(f"integration_service_{table_id}_table_model") + + +def _clear_authorized_subject(subject_type, subject_id): + """Invalidate integrations whose canonical authorization was deleted.""" + + LocalBaserowIntegration.objects.filter( + authorized_subject_type=subject_type, + authorized_subject_id=subject_id, + ).update(authorized_subject_type=None, authorized_subject_id=None) + + +@receiver(user_permanently_deleted) +def clear_permanently_deleted_user_authorization(sender, user_id, **kwargs): + """Retain integrations but invalidate those authorized by a deleted user.""" + + _clear_authorized_subject("auth.User", user_id) + + +@receiver(before_permanently_deleted) +def clear_permanently_deleted_agent_authorization(sender, trash_item, **kwargs): + """Retain integrations when an agent is permanently deleted from trash.""" + + if isinstance(trash_item, Agent): + subject_type = subject_type_registry.get_by_model(trash_item).type + _clear_authorized_subject(subject_type, trash_item.id) diff --git a/backend/src/baserow/contrib/integrations/local_baserow/service_types.py b/backend/src/baserow/contrib/integrations/local_baserow/service_types.py index 398f031f48..62df260ea6 100644 --- a/backend/src/baserow/contrib/integrations/local_baserow/service_types.py +++ b/backend/src/baserow/contrib/integrations/local_baserow/service_types.py @@ -120,6 +120,7 @@ from baserow.core.formula.validator import ( from baserow.core.handler import CoreHandler from baserow.core.integrations.models import Integration from baserow.core.models import Workspace +from baserow.core.registries import subject_type_registry from baserow.core.registry import Instance from baserow.core.services.dispatch_context import DispatchContext from baserow.core.services.exceptions import ( @@ -141,7 +142,7 @@ from baserow.core.services.types import ( ServiceSubClass, ) from baserow.core.trash.handler import TrashHandler -from baserow.core.types import PermissionCheck +from baserow.core.types import PermissionCheck, Subject if TYPE_CHECKING: from baserow.contrib.database.table.models import GeneratedTableModel, Table @@ -159,32 +160,37 @@ class LocalBaserowServiceType(ServiceType): def get_acting_user( self, service: ServiceSubClass, dispatch_context: DispatchContext - ) -> AbstractUser: + ) -> Subject: """ - Returns the user whose permissions and identity this dispatch runs under. + Returns the subject whose permissions and identity this dispatch runs under. - With an integration, that integration's `authorized_user` acts, as in the + With an integration, that integration's `authorized_subject` acts, as in the builder, automation and dashboard. Without one, the dispatch context's actor acts instead. This is the only place a Local Baserow service type - may resolve its user. + may resolve its subject. :param service: The service being dispatched. :param dispatch_context: The context this dispatch runs in. :raises ServiceImproperlyConfiguredDispatchException: When neither an - integration nor an actor supplies a user. - :return: The acting user. + integration nor an actor supplies a subject. + :return: The acting subject. """ if service.integration_id: - authorized_user = service.integration.specific.authorized_user - # Nullable, and an import leaves it null when the exported username - # is not in the target workspace. Refuse rather than let a `None` - # reach a permission check as anonymous. - if authorized_user is None: + integration = service.integration.specific + authorized_subject = integration.authorized_subject_including_trash + if getattr(authorized_subject, "trashed", False): raise ServiceImproperlyConfiguredDispatchException( - "The integration has no authorized user" + "The integration's authorized agent is trashed" ) - return authorized_user + + # Nullable, and an import can leave the authorized user null. Refuse + # rather than let a `None` reach a permission check as anonymous. + if authorized_subject is None: + raise ServiceImproperlyConfiguredDispatchException( + "The integration has no authorized subject" + ) + return authorized_subject if dispatch_context.actor is None: raise ServiceImproperlyConfiguredDispatchException( @@ -205,6 +211,25 @@ class LocalBaserowServiceType(ServiceType): return False + def before_dispatch( + self, + service: ServiceSubClass, + dispatch_context: DispatchContext, + ) -> None: + """Record when this service uses an authorized agent.""" + + if not service.integration_id: + return + + integration = service.integration.specific + if not integration.authorized_subject_type: + return + + subject_type = subject_type_registry.get(integration.authorized_subject_type) + subject = integration.authorized_subject + if subject is not None: + subject_type.track_usage(subject) + def get_schema_for_return_type( self, service: ServiceSubClass, properties: Dict[str, Any] ) -> Dict[str, Any]: diff --git a/backend/src/baserow/contrib/integrations/local_baserow/utils.py b/backend/src/baserow/contrib/integrations/local_baserow/utils.py index bebaf60e09..bb9065a60a 100644 --- a/backend/src/baserow/contrib/integrations/local_baserow/utils.py +++ b/backend/src/baserow/contrib/integrations/local_baserow/utils.py @@ -1,7 +1,5 @@ from typing import Any, Callable, List, Optional, Union -from django.contrib.auth.models import AbstractUser - from loguru import logger from rest_framework.fields import Field from rest_framework.serializers import Serializer @@ -18,9 +16,11 @@ from baserow.core.formula.validator import ( ensure_integer, ensure_string, ) +from baserow.core.registries import subject_type_registry from baserow.core.services.exceptions import ( ServiceImproperlyConfiguredDispatchException, ) +from baserow.core.types import Subject from baserow.core.user_files.exceptions import ( FileSizeTooLargeError, FileURLCouldNotBeReached, @@ -29,16 +29,20 @@ from baserow.core.user_files.exceptions import ( def prepare_files_for_db( value: Any, - user: AbstractUser, + actor: Subject, ) -> List[dict]: """ Transforms the generic files from the frontend into files that can be associated with rows. :param value: The value from the request. - :param user: The user to store the file with. + :param actor: The subject dispatching the service. """ + uploading_user = ( + actor if subject_type_registry.get_by_model(actor).is_interactive_user else None + ) + # It must be an array data = ensure_array(value) result = [] @@ -46,7 +50,7 @@ def prepare_files_for_db( for f in data: if isinstance(f, ServiceFile): try: - result.append(f.to_file_field_dict(user)) + result.append(f.to_file_field_dict(uploading_user)) except FileURLCouldNotBeReached as exc: file_name = f.visible_name or f.name or "unnamed" raise ServiceImproperlyConfiguredDispatchException( @@ -68,7 +72,7 @@ def prepare_files_for_db( file_name = f.get("name", "unnamed") try: service_file = ServiceFile.from_serialized(f) - result.append(service_file.to_file_field_dict(user)) + result.append(service_file.to_file_field_dict(uploading_user)) except FileURLCouldNotBeReached as exc: raise ServiceImproperlyConfiguredDispatchException( f"The file {file_name} couldn't be reached." @@ -91,13 +95,13 @@ def prepare_files_for_db( def guess_cast_function_from_response_serializer_field( - serializer_field: Union[Field, Serializer], user: AbstractUser + serializer_field: Union[Field, Serializer], actor: Subject ) -> Optional[Callable]: """ Return the appropriate cast function for a serializer type. :param serializer_field: The serializer field. - :param user: The user the uploaded files are attributed to. + :param actor: The subject dispatching the service. :return: A function that can be used to cast a value to this serializer field type. """ @@ -109,7 +113,7 @@ def guess_cast_function_from_response_serializer_field( # Special case for file field serializer, we want to convert files data to # match expected value. We have to upload the files first before we can # includes them in the row. - return lambda value: prepare_files_for_db(value, user) + return lambda value: prepare_files_for_db(value, actor) json_type = guess_json_type_from_response_serializer_field(serializer_field) diff --git a/backend/src/baserow/contrib/integrations/migrations/0039_localbaserowintegration_authorized_agent.py b/backend/src/baserow/contrib/integrations/migrations/0039_localbaserowintegration_authorized_agent.py new file mode 100644 index 0000000000..23643396a1 --- /dev/null +++ b/backend/src/baserow/contrib/integrations/migrations/0039_localbaserowintegration_authorized_agent.py @@ -0,0 +1,47 @@ +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("core", "0121_agent"), + ("integrations", "0038_smtpintegration_use_ssl"), + ] + + operations = [ + migrations.AddField( + model_name="localbaserowintegration", + name="authorized_subject_type", + field=models.CharField( + blank=True, + db_default="auth.User", + default="auth.User", + max_length=255, + null=True, + ), + ), + migrations.SeparateDatabaseAndState( + database_operations=[ + migrations.AlterField( + model_name="localbaserowintegration", + name="authorized_user", + field=models.BigIntegerField( + blank=True, db_column="authorized_user_id", null=True + ), + ), + ], + state_operations=[ + migrations.RenameField( + model_name="localbaserowintegration", + old_name="authorized_user", + new_name="authorized_subject_id", + ), + migrations.AlterField( + model_name="localbaserowintegration", + name="authorized_subject_id", + field=models.BigIntegerField( + blank=True, db_column="authorized_user_id", null=True + ), + ), + ], + ), + ] diff --git a/backend/src/baserow/contrib/integrations/signals.py b/backend/src/baserow/contrib/integrations/signals.py index 0180c90cc5..0f91aa8c22 100644 --- a/backend/src/baserow/contrib/integrations/signals.py +++ b/backend/src/baserow/contrib/integrations/signals.py @@ -1,4 +1,8 @@ -from baserow.contrib.integrations.local_baserow.receivers import invalidate_table_cache +from baserow.contrib.integrations.local_baserow.receivers import ( # noqa: F401 + clear_permanently_deleted_agent_authorization, + clear_permanently_deleted_user_authorization, + invalidate_table_cache, +) from baserow.contrib.integrations.local_baserow.signals import ( handle_local_baserow_field_updated_changes, ) diff --git a/backend/src/baserow/contrib/integrations/slack/integration_types.py b/backend/src/baserow/contrib/integrations/slack/integration_types.py index 2f71c4b3df..559fe7fac9 100644 --- a/backend/src/baserow/contrib/integrations/slack/integration_types.py +++ b/backend/src/baserow/contrib/integrations/slack/integration_types.py @@ -1,9 +1,10 @@ -from typing import Any, Dict +from typing import Any, Dict, Optional from baserow.contrib.integrations.slack.models import SlackBotIntegration from baserow.core.integrations.registries import IntegrationType from baserow.core.integrations.types import IntegrationDict from baserow.core.models import Application +from baserow.core.registries import ImportExportConfig class SlackBotIntegrationType(IntegrationType): @@ -36,6 +37,7 @@ class SlackBotIntegrationType(IntegrationType): files_zip=None, storage=None, cache=None, + import_export_config: Optional[ImportExportConfig] = None, ) -> SlackBotIntegration: """ Imports a serialized integration. Ensures that if we're importing an exported @@ -49,6 +51,7 @@ class SlackBotIntegrationType(IntegrationType): application, serialized_values, id_mapping, + import_export_config=import_export_config, files_zip=files_zip, storage=storage, cache=cache, diff --git a/backend/src/baserow/core/action/registries.py b/backend/src/baserow/core/action/registries.py index 5758243526..ad0fce6977 100755 --- a/backend/src/baserow/core/action/registries.py +++ b/backend/src/baserow/core/action/registries.py @@ -1,5 +1,6 @@ import abc import dataclasses +import json from copy import deepcopy from datetime import datetime, timezone from typing import Any, Dict, List, NewType, Optional @@ -15,6 +16,7 @@ from baserow.api.sessions import ( get_client_undo_redo_action_group_id, get_untrusted_client_session_id, ) +from baserow.core.encoders import JSONEncoderSupportingDataClasses from baserow.core.models import Workspace from baserow.core.registry import Instance, Registry from baserow.core.telemetry.utils import ( @@ -397,6 +399,21 @@ class UndoableActionTypeMixin: :return: The created action. """ + from baserow.core.registries import subject_type_registry + + subject_type = subject_type_registry.get_by_model(user) + # Non-interactive subjects must not create an Action, but still emit + # action_done so consumers such as the audit log record the action. + if not subject_type.is_interactive_user: + serialized_params = json.loads( + json.dumps( + cls.params_to_serializable(params), + cls=JSONEncoderSupportingDataClasses, + ) + ) + cls.send_action_done_signal(user, serialized_params, scope, workspace) + return None + session = get_untrusted_client_session_id(user) action_group = get_client_undo_redo_action_group_id(user) diff --git a/backend/src/baserow/core/agents/handler.py b/backend/src/baserow/core/agents/handler.py index e5e8a85de4..269fcdf19d 100644 --- a/backend/src/baserow/core/agents/handler.py +++ b/backend/src/baserow/core/agents/handler.py @@ -1,12 +1,17 @@ from typing import Any from django.db.models import QuerySet +from django.utils import timezone from baserow.core.agents.exceptions import AgentDoesNotExist from baserow.core.agents.registries import agent_extension_type_registry +from baserow.core.cache import global_cache from baserow.core.models import Agent, Workspace from baserow.core.trash.handler import TrashHandler +AGENT_LAST_ACTIVE_CACHE_TTL_SECONDS = 60 +AGENT_LAST_ACTIVE_CACHE_KEY = "agent_{agent_id}_last_active" + class AgentHandler: """Handles agent persistence and domain-level queries.""" @@ -76,6 +81,26 @@ class AgentHandler: agent.save(update_fields=[*update_fields, "updated_on"]) return agent + def update_last_active(self, agent: Agent) -> Agent: + """ + Sets the agent's last active time at most once per cache interval. + + :param agent: The agent whose last active time should be updated. + :return: The updated agent. + """ + + def update_timestamp(): + agent.last_active = timezone.now() + agent.save(update_fields=["last_active"]) + return True + + global_cache.get( + AGENT_LAST_ACTIVE_CACHE_KEY.format(agent_id=agent.id), + default=update_timestamp, + timeout=AGENT_LAST_ACTIVE_CACHE_TTL_SECONDS, + ) + return agent + def delete_agent(self, user, agent: Agent) -> None: """ Moves an agent to the trash. diff --git a/backend/src/baserow/core/agents/subjects.py b/backend/src/baserow/core/agents/subjects.py index 06788f8772..a3e4f8b0e1 100644 --- a/backend/src/baserow/core/agents/subjects.py +++ b/backend/src/baserow/core/agents/subjects.py @@ -2,7 +2,11 @@ from typing import List from django.conf import settings from django.contrib.auth.models import AbstractUser +from django.db.models import CharField, F, IntegerField, Value +from django.db.models.functions import Cast +from baserow.core.agents.handler import AgentHandler +from baserow.core.agents.operations import ListAgentsWorkspaceOperationType from baserow.core.models import Agent, Workspace from baserow.core.registries import SubjectType from baserow.core.types import Subject @@ -12,9 +16,76 @@ class AgentSubjectType(SubjectType): type = "core.Agent" model_class = Agent display_name_field = "name" + options_list_operation_type = ListAgentsWorkspaceOperationType.type has_direct_workspace_roles = True + def track_usage(self, subject: Agent) -> None: + """Track agent service usage by updating its last-active timestamp.""" + + AgentHandler().update_last_active(subject) + + def get_type_display_name(self): + return "Agent" + + def get_display_name(self, subject: Agent) -> str: + return subject.name + + def get_queryset(self, workspace_id=None): + queryset = Agent.objects.all() + if workspace_id is not None: + queryset = queryset.filter(workspace_id=workspace_id) + return queryset.order_by("name") + + def get_options_queryset( + self, + workspace: Workspace | None = None, + search: str = "", + exclude_ids: List[int] | None = None, + include_trash: bool = False, + ): + """Return searchable agent options, optionally scoped to a workspace. + + :param include_trash: Whether trashed agents should be included. + """ + + manager = Agent.objects_and_trash if include_trash else Agent.objects + queryset = manager.exclude(id__in=exclude_ids or []) + if workspace is not None: + queryset = queryset.filter(workspace=workspace) + if search: + queryset = queryset.filter(name__icontains=search) + return queryset.annotate( + subject_id=F("id"), + subject_type=Value(self.type, output_field=CharField()), + subject_name=F("name"), + subject_label=F("name"), + subject_email=Value(None, output_field=CharField()), + subject_count=Cast(Value(None), output_field=IntegerField()), + ).values( + "subject_id", + "subject_type", + "subject_name", + "subject_label", + "subject_email", + "subject_count", + ) + + def get_historical_options_queryset( + self, + workspace: Workspace | None = None, + search: str = "", + exclude_ids: List[int] | None = None, + ): + """Return agents retained for historical records after being trashed.""" + + return self.get_options_queryset( + workspace=workspace, + search=search, + exclude_ids=exclude_ids, + include_trash=True, + ) + def _get_workspace_agents(self, workspace: Workspace, include_trash: bool): """Return agents using the requested agent and parent-workspace visibility.""" diff --git a/backend/src/baserow/core/handler.py b/backend/src/baserow/core/handler.py index 2c9c5f2c9f..23feb6a72b 100755 --- a/backend/src/baserow/core/handler.py +++ b/backend/src/baserow/core/handler.py @@ -790,7 +790,8 @@ class CoreHandler: ) workspaceuser_workspaces = WorkspaceUser.objects.select_related( "workspace" - ).prefetch_related( + ).annotate(workspace_agent_count=Count("workspace__agents", distinct=True)) + workspaceuser_workspaces = workspaceuser_workspaces.prefetch_related( Prefetch( "workspace__workspaceuser_set", queryset=workspaceusers_with_user_and_profile, diff --git a/backend/src/baserow/core/integrations/exceptions.py b/backend/src/baserow/core/integrations/exceptions.py index a4a05514da..c8add179c5 100644 --- a/backend/src/baserow/core/integrations/exceptions.py +++ b/backend/src/baserow/core/integrations/exceptions.py @@ -14,3 +14,7 @@ class IntegrationCredentialRequired(Exception): Raised when a field that controls where a request goes is changed without the credential it protects being re-supplied in the same request. """ + + +class IntegrationImproperlyConfigured(Exception): + """Raised when an integration cannot be used with its saved configuration.""" diff --git a/backend/src/baserow/core/integrations/handler.py b/backend/src/baserow/core/integrations/handler.py index f31c029db7..4f1a8a3bbb 100644 --- a/backend/src/baserow/core/integrations/handler.py +++ b/backend/src/baserow/core/integrations/handler.py @@ -267,6 +267,7 @@ class IntegrationHandler: cache: Optional[Dict] = None, files_zip: Optional[ZipFile] = None, storage: Optional[Storage] = None, + import_export_config: Optional[ImportExportConfig] = None, ) -> Optional[Integration]: """ Imports a serialized integration into an application. @@ -277,6 +278,7 @@ class IntegrationHandler: :param cache: Shared across one import, for values worth reusing. :param files_zip: The archive the export's files came in, if any. :param storage: Where those files are written. + :param import_export_config: Options controlling how integrations are imported. :return: The imported integration, or None when the application does not accept its type. `DatabaseApplicationType` is the only one that narrows what it accepts, and it ignores what this returns, so @@ -312,6 +314,7 @@ class IntegrationHandler: application, serialized_integration, id_mapping, + import_export_config=import_export_config, files_zip=files_zip, storage=storage, cache=cache, diff --git a/backend/src/baserow/core/integrations/registries.py b/backend/src/baserow/core/integrations/registries.py index b20187e59c..2e0488c2b3 100644 --- a/backend/src/baserow/core/integrations/registries.py +++ b/backend/src/baserow/core/integrations/registries.py @@ -4,6 +4,7 @@ from typing import Any, Dict, List, Optional, Type, TypeVar from django.contrib.auth.models import AbstractUser from baserow.api.integrations.fields import HasSecretField +from baserow.core.registries import ImportExportConfig from baserow.core.registry import ( CustomFieldsInstanceMixin, CustomFieldsRegistryMixin, @@ -66,7 +67,11 @@ class IntegrationType( return queryset def prepare_values( - self, values: Dict[str, Any], user: AbstractUser + self, + values: Dict[str, Any], + user: AbstractUser, + application: Optional[Any] = None, + instance: Optional[IntegrationSubClass] = None, ) -> Dict[str, Any]: """ The prepare_values hook gives the possibility to change the provided values @@ -77,6 +82,7 @@ class IntegrationType( :param values: The provided values. :param user: The user on whose behalf the change is made. + :param instance: The current instance if it exists. :return: The updated values. """ @@ -173,11 +179,13 @@ class IntegrationType( files_zip=None, storage=None, cache=None, + import_export_config: Optional[ImportExportConfig] = None, ) -> IntegrationSubClass: return super().import_serialized( parent, serialized_values, id_mapping, + import_export_config=import_export_config, files_zip=files_zip, storage=storage, cache=cache, diff --git a/backend/src/baserow/core/integrations/service.py b/backend/src/baserow/core/integrations/service.py index a5d007fb42..b6a55d96f9 100644 --- a/backend/src/baserow/core/integrations/service.py +++ b/backend/src/baserow/core/integrations/service.py @@ -110,7 +110,9 @@ class IntegrationService: context=application, ) - prepared_values = integration_type.prepare_values(kwargs, user) + prepared_values = integration_type.prepare_values( + kwargs, user, application=application + ) try: new_integration = self.handler.create_integration( @@ -200,7 +202,9 @@ class IntegrationService: integration, kwargs, integration_type.get_action_log_excluded_fields() ) - prepared_values = integration_type.prepare_values(kwargs, user) + prepared_values = integration_type.prepare_values( + kwargs, user, application=integration.application, instance=integration + ) integration = self.handler.update_integration( integration_type, integration, **prepared_values diff --git a/backend/src/baserow/core/posthog.py b/backend/src/baserow/core/posthog.py index a1bdf5ee6a..9ca2351f29 100644 --- a/backend/src/baserow/core/posthog.py +++ b/backend/src/baserow/core/posthog.py @@ -10,6 +10,7 @@ from loguru import logger from baserow.core.action.signals import ActionCommandType, action_done from baserow.core.models import Workspace +from baserow.core.registries import subject_type_registry from baserow.core.utils import exception_capturer _posthog = None @@ -112,6 +113,12 @@ def capture_event_action_done( session, **kwargs, ): + subject_type = ( + subject_type_registry.get_by_model(user) if user is not None else None + ) + if subject_type is not None and not subject_type.is_interactive_user: + return + # Only capture do commands for now because the undo might make it more difficult # to do analytics on the data. if ( diff --git a/backend/src/baserow/core/registries.py b/backend/src/baserow/core/registries.py index b1ec95fb56..ca159eeff2 100755 --- a/backend/src/baserow/core/registries.py +++ b/backend/src/baserow/core/registries.py @@ -1355,8 +1355,11 @@ class SubjectType(abc.ABC, Instance, ModelInstanceMixin): can execute an operation. """ + # Interactive users can persist undoable actions and emit product analytics. + is_interactive_user = False display_name_field: Optional[str] = None lookup_fields = ("id", "pk") + options_list_operation_type: Optional[str] = None def supports_lookup_field(self, field_name: str) -> bool: """Return whether this subject type supports lookup by the given field.""" @@ -1368,6 +1371,11 @@ class SubjectType(abc.ABC, Instance, ModelInstanceMixin): # set_workspace_role_uid. Other types keep using RoleAssignment records. has_direct_workspace_roles: bool = False + def track_usage(self, subject: Subject) -> None: + """Record usage when a subject dispatches a service through an integration.""" + + pass + def get_workspace_subjects(self, workspace: "Workspace", include_trash=False): """Return the subjects whose direct roles belong to a workspace. @@ -1394,6 +1402,48 @@ class SubjectType(abc.ABC, Instance, ModelInstanceMixin): """ raise NotImplementedError() + def get_display_name(self, subject: Subject) -> str: + """Return the snapshot-friendly name used to identify a subject.""" + + return str(subject) + + def get_type_display_name(self) -> str: + """Return the human-readable name of this subject type.""" + + return self.type + + def get_queryset(self, workspace_id: Optional[int] = None) -> Optional[QuerySet]: + """Return subjects matching the workspace scope, if listable.""" + + return None + + def get_options_queryset( + self, + workspace: Optional["Workspace"] = None, + search: str = "", + exclude_ids: Optional[List[int]] = None, + ) -> Optional[QuerySet]: + """Return a standardized queryset of selectable subject options.""" + + return None + + def get_historical_options_queryset( + self, + workspace: Optional["Workspace"] = None, + search: str = "", + exclude_ids: Optional[List[int]] = None, + ) -> Optional[QuerySet]: + """Return options including subjects retained for historical records.""" + + return self.get_options_queryset( + workspace=workspace, search=search, exclude_ids=exclude_ids + ) + + def get_label(self, subject: Subject) -> str: + """Return the label shown when this subject is presented as an option.""" + + return self.get_display_name(subject) + def get_workspace_role_uids( self, subjects: List[Subject], @@ -1513,17 +1563,24 @@ class SubjectTypeRegistry(Registry[SubjectType], ModelRegistryMixin[Any, Subject instance_type = self.get_by_model(model_instance) return instance_type.get_serializer(model_instance, **kwargs) - def get_subject(self, type_name: str, subject_id: int) -> Optional[Subject]: + def get_subject( + self, type_name: str, subject_id: int, include_trash: bool = False + ) -> Optional[Subject]: """ Returns the subject stored as a type and id pair. :param type_name: The subject type, for example `auth.User`. :param subject_id: The id of the subject. + :param include_trash: Whether a trashed subject is returned as well, for + subject types that can be trashed. :return: The subject, or None when it no longer exists or its type is not stored in the database. """ - manager = getattr(self.get(type_name).model_class, "objects", None) + model_class = self.get(type_name).model_class + manager = getattr(model_class, "objects", None) + if include_trash: + manager = getattr(model_class, "objects_and_trash", manager) if manager is None: return None return manager.filter(id=subject_id).first() diff --git a/backend/src/baserow/core/services/registries.py b/backend/src/baserow/core/services/registries.py index 6d0f2464a9..3935eb6bc0 100644 --- a/backend/src/baserow/core/services/registries.py +++ b/backend/src/baserow/core/services/registries.py @@ -451,6 +451,13 @@ class ServiceType( data = self.dispatch_data(service, resolved_values, dispatch_context) return self.dispatch_transform(data) + def before_dispatch( + self, + service: ServiceSubClass, + dispatch_context: DispatchContext, + ) -> None: + """Hook called immediately before a service executes.""" + def after_dispatch( self, service: ServiceSubClass, @@ -497,6 +504,8 @@ class ServiceType( ): return DispatchResult(**sample_data) + self.before_dispatch(service, dispatch_context) + # Formula resolution always runs inside this savepoint. `dispatch_data` # and `dispatch_transform` run inside it too, unless the service is # external and the dispatch context says its caller sends outside a diff --git a/backend/src/baserow/core/subject_options.py b/backend/src/baserow/core/subject_options.py new file mode 100644 index 0000000000..c1831a2a8d --- /dev/null +++ b/backend/src/baserow/core/subject_options.py @@ -0,0 +1,94 @@ +from django.db.models import QuerySet + +from baserow.core.models import Workspace +from baserow.core.registries import subject_type_registry + + +class SubjectOptionsHandler: + """Builds searchable subject option querysets from registered subject types.""" + + @classmethod + def get_options( + cls, + workspace: Workspace | None = None, + search: str = "", + subject_types: set[str] | None = None, + exclude_ids: dict[str, list[int]] | None = None, + subject_type_options_kwargs: dict[str, dict] | None = None, + order_by: tuple[str, ...] = ("subject_label", "subject_type", "subject_id"), + ) -> QuerySet: + """Return a unified queryset supplied by listable subject types. + + Permission checks remain with the caller because consumers expose subject + options under different capabilities. + + :param order_by: The shared option fields used to order the combined queryset. + """ + + return cls._get_options( + "get_options_queryset", + workspace=workspace, + search=search, + subject_types=subject_types, + exclude_ids=exclude_ids, + subject_type_options_kwargs=subject_type_options_kwargs, + order_by=order_by, + ) + + @classmethod + def get_historical_options( + cls, + workspace: Workspace | None = None, + search: str = "", + subject_types: set[str] | None = None, + exclude_ids: dict[str, list[int]] | None = None, + order_by: tuple[str, ...] = ("subject_label", "subject_type", "subject_id"), + ) -> QuerySet: + """Return subject options that include subjects retained for historical use.""" + + return cls._get_options( + "get_historical_options_queryset", + workspace=workspace, + search=search, + subject_types=subject_types, + exclude_ids=exclude_ids, + order_by=order_by, + ) + + @classmethod + def _get_options( + cls, + options_queryset_method: str, + workspace: Workspace | None = None, + search: str = "", + subject_types: set[str] | None = None, + exclude_ids: dict[str, list[int]] | None = None, + subject_type_options_kwargs: dict[str, dict] | None = None, + order_by: tuple[str, ...] = ("subject_label", "subject_type", "subject_id"), + ) -> QuerySet: + """Return options from the named SubjectType queryset method.""" + + search = (search or "").strip() + exclude_ids = exclude_ids or {} + subject_type_options_kwargs = subject_type_options_kwargs or {} + requested_types = subject_types or set(subject_type_registry.get_types()) + option_querysets = [] + for subject_type in subject_type_registry.get_all(): + if subject_type.type not in requested_types: + continue + queryset = getattr(subject_type, options_queryset_method)( + workspace=workspace, + search=search, + exclude_ids=exclude_ids.get(subject_type.type, []), + **subject_type_options_kwargs.get(subject_type.type, {}), + ) + if queryset is not None: + option_querysets.append(queryset) + + if not option_querysets: + raise ValueError("No listable subject types were requested.") + + queryset = option_querysets[0] + for option_queryset in option_querysets[1:]: + queryset = queryset.union(option_queryset, all=True) + return queryset.order_by(*order_by) diff --git a/backend/src/baserow/core/subjects.py b/backend/src/baserow/core/subjects.py index 2edd631ed8..1a99173edf 100755 --- a/backend/src/baserow/core/subjects.py +++ b/backend/src/baserow/core/subjects.py @@ -2,8 +2,11 @@ from typing import List from django.conf import settings from django.contrib.auth.models import AbstractUser, AnonymousUser +from django.db.models import Case, CharField, F, IntegerField, Q, Value, When +from django.db.models.functions import Cast from baserow.core.models import User, Workspace, WorkspaceUser +from baserow.core.operations import ListWorkspaceUsersWorkspaceOperationType from baserow.core.registries import SubjectType from baserow.core.types import Subject @@ -11,8 +14,10 @@ from baserow.core.types import Subject class UserSubjectType(SubjectType): type = "auth.User" model_class = User + is_interactive_user = True display_name_field = "first_name" lookup_fields = (*SubjectType.lookup_fields, "email") + options_list_operation_type = ListWorkspaceUsersWorkspaceOperationType.type has_direct_workspace_roles = True @@ -43,6 +48,76 @@ class UserSubjectType(SubjectType): None, workspace_user, permissions=permissions ) + def get_type_display_name(self): + return "User" + + def get_display_name(self, subject: AbstractUser) -> str: + return subject.first_name + + def get_queryset(self, workspace_id=None): + queryset = User.objects.all() + if workspace_id is not None: + queryset = queryset.filter(workspaceuser__workspace_id=workspace_id) + return queryset.order_by("email") + + def get_label(self, subject: AbstractUser) -> str: + return subject.email + + def get_options_queryset( + self, + workspace: Workspace | None = None, + search: str = "", + exclude_ids: List[int] | None = None, + include_inactive_and_scheduled_for_deletion: bool = False, + ): + """Return searchable user options, optionally scoped to a workspace.""" + + queryset = User.objects.exclude(id__in=exclude_ids or []) + if not include_inactive_and_scheduled_for_deletion: + queryset = queryset.filter(is_active=True, profile__to_be_deleted=False) + if workspace is not None: + queryset = queryset.filter(workspaceuser__workspace=workspace) + if search: + queryset = queryset.filter( + Q(first_name__icontains=search) + | Q(username__icontains=search) + | Q(email__icontains=search) + ) + return queryset.annotate( + subject_id=F("id"), + subject_type=Value(self.type, output_field=CharField()), + subject_name=Case( + When(first_name="", then=F("email")), + default=F("first_name"), + output_field=CharField(), + ), + subject_label=F("email"), + subject_email=F("email"), + subject_count=Cast(Value(None), output_field=IntegerField()), + ).values( + "subject_id", + "subject_type", + "subject_name", + "subject_label", + "subject_email", + "subject_count", + ) + + def get_historical_options_queryset( + self, + workspace: Workspace | None = None, + search: str = "", + exclude_ids: List[int] | None = None, + ): + """Return users retained for historical records after access is removed.""" + + return self.get_options_queryset( + workspace=workspace, + search=search, + exclude_ids=exclude_ids, + include_inactive_and_scheduled_for_deletion=True, + ) + def get_workspace_role_uids( self, subjects: List[Subject], @@ -132,6 +207,14 @@ class AnonymousUserSubjectType(SubjectType): type = "anonymous" model_class = AnonymousUser + def get_type_display_name(self): + return "Anonymous user" + + def get_display_name(self, subject: AnonymousUser) -> str: + # Row history persists this as a stable fallback. Clients translate the + # anonymous actor label at render time so it uses the viewer's language. + return "Anonymous User" + def are_in_workspace( self, subjects: List[Subject], diff --git a/backend/src/baserow/test_utils/fixtures/integration.py b/backend/src/baserow/test_utils/fixtures/integration.py index 02e05124c3..19c6924bca 100644 --- a/backend/src/baserow/test_utils/fixtures/integration.py +++ b/backend/src/baserow/test_utils/fixtures/integration.py @@ -6,11 +6,19 @@ from baserow.core.integrations.registries import integration_type_registry class IntegrationFixtures: def create_local_baserow_integration(self, **kwargs): - if not kwargs.get("authorized_user", None): - if not kwargs.get("user", None): - kwargs["user"] = self.create_user() + authorized_agent = kwargs.pop("authorized_agent", None) + authorized_user = kwargs.pop("authorized_user", None) + if authorized_agent is not None: + kwargs["authorized_subject_type"] = "core.Agent" + kwargs["authorized_subject_id"] = authorized_agent.id + else: + if authorized_user is None: + if not kwargs.get("user", None): + kwargs["user"] = self.create_user() - kwargs["authorized_user"] = kwargs["user"] + authorized_user = kwargs["user"] + kwargs["authorized_subject_type"] = "auth.User" + kwargs["authorized_subject_id"] = authorized_user.id integration = self.create_integration(LocalBaserowIntegration, **kwargs) return integration diff --git a/backend/src/baserow/test_utils/fixtures/service.py b/backend/src/baserow/test_utils/fixtures/service.py index 399d2143e5..e75470e4b9 100644 --- a/backend/src/baserow/test_utils/fixtures/service.py +++ b/backend/src/baserow/test_utils/fixtures/service.py @@ -21,6 +21,7 @@ from baserow.contrib.integrations.local_baserow.models import ( LocalBaserowDeleteRow, LocalBaserowFieldsUpdated, LocalBaserowGetRow, + LocalBaserowIntegration, LocalBaserowListRows, LocalBaserowRowsCreated, LocalBaserowRowsDeleted, @@ -217,10 +218,16 @@ class ServiceFixtures: integration = None integrations_args = kwargs.pop("integration_args", {}) service_type = service_type_registry.get_by_model(model_class) - if service_type.get_integration_type(): - integration = self.create_integration( - service_type.get_integration_type().model_class, **integrations_args - ) + integration_type = service_type.get_integration_type() + if integration_type: + if integration_type.model_class is LocalBaserowIntegration: + integration = self.create_local_baserow_integration( + **integrations_args + ) + else: + integration = self.create_integration( + integration_type.model_class, **integrations_args + ) else: integration = kwargs.pop("integration", None) kwargs.pop("integration_args", None) diff --git a/backend/tests/baserow/api/agents/test_agent_views.py b/backend/tests/baserow/api/agents/test_agent_views.py index 6fdd0c101d..c357fccaa8 100644 --- a/backend/tests/baserow/api/agents/test_agent_views.py +++ b/backend/tests/baserow/api/agents/test_agent_views.py @@ -191,27 +191,6 @@ def test_agent_openapi_operations_have_stable_ids_and_explicit_path_parameters( assert path_parameters[0]["schema"]["type"] == "integer" -@pytest.mark.django_db -def test_cannot_create_agent_when_feature_flag_is_disabled( - data_fixture, api_client, settings -): - user, token = data_fixture.create_user_and_token() - workspace = data_fixture.create_workspace(user=user) - url = reverse("api:agents:workspace", kwargs={"workspace_id": workspace.id}) - settings.FEATURE_FLAGS = [] - - response = api_client.post( - url, - {"name": "Writer", "role_uid": "MEMBER"}, - format="json", - HTTP_AUTHORIZATION=f"JWT {token}", - ) - - assert response.status_code == 403 - assert response.json()["error"] == "ERROR_FEATURE_DISABLED" - assert not Agent.objects.filter(workspace=workspace).exists() - - @pytest.mark.django_db def test_duplicate_agent_names_and_model_defaults(data_fixture): workspace = data_fixture.create_workspace() diff --git a/backend/tests/baserow/api/groups/test_workspace_views.py b/backend/tests/baserow/api/groups/test_workspace_views.py index d65fddcc0b..6c64181446 100755 --- a/backend/tests/baserow/api/groups/test_workspace_views.py +++ b/backend/tests/baserow/api/groups/test_workspace_views.py @@ -19,7 +19,7 @@ from baserow.core.ai_provider.models import ( AIProviderWorkspaceOverride, ) from baserow.core.handler import CoreHandler -from baserow.core.models import Workspace, WorkspaceUser +from baserow.core.models import Agent, Workspace, WorkspaceUser from baserow.test_utils.helpers import is_dict_subset @@ -290,6 +290,22 @@ def test_list_workspaces(api_client, data_fixture): assert response_json[0]["unread_notifications_count"] == 0 +@pytest.mark.django_db +def test_list_workspaces_includes_agent_count(api_client, data_fixture): + user, token = data_fixture.create_user_and_token() + workspace = data_fixture.create_workspace(user=user) + data_fixture.create_user_workspace(workspace=workspace) + Agent.objects.create(workspace=workspace, name="Writer") + + response = api_client.get( + reverse("api:workspaces:list"), + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert response.json()[0]["agents_count"] == 1 + + @pytest.mark.django_db def test_list_workspaces_with_users(api_client, data_fixture): user, token = data_fixture.create_user_and_token( diff --git a/backend/tests/baserow/api/integrations/test_integration_views.py b/backend/tests/baserow/api/integrations/test_integration_views.py index b9d065f6d5..7e3a563878 100644 --- a/backend/tests/baserow/api/integrations/test_integration_views.py +++ b/backend/tests/baserow/api/integrations/test_integration_views.py @@ -17,7 +17,9 @@ from baserow.api.integrations.serializers import ( ) from baserow.core.integrations.models import Integration from baserow.core.integrations.registries import integration_type_registry +from baserow.core.models import Agent from baserow.core.registries import application_type_registry +from baserow.core.trash.handler import TrashHandler @pytest.mark.django_db @@ -51,7 +53,8 @@ def test_get_integrations(api_client, data_fixture): assert response_json[0]["id"] == integration1.id assert response_json[0]["type"] == "local_baserow" assert response_json[0]["context_data"]["databases"][0]["id"] == database.id - assert "authorized_user" in response_json[0] + assert response_json[0]["authorized_subject"]["id"] == user.id + assert response_json[0]["authorized_subject"]["type"] == "auth.User" assert response_json[1]["id"] == integration2.id assert response_json[1]["type"] == "local_baserow" assert response_json[1]["context_data"]["databases"][0]["id"] == database.id @@ -79,7 +82,7 @@ def test_create_integration(api_client, data_fixture): response_json = response.json() assert response.status_code == HTTP_200_OK assert response_json["type"] == "local_baserow" - assert response_json["authorized_user"]["username"] == user.username + assert response_json["authorized_subject"]["username"] == user.username assert response_json["context_data"]["databases"][0]["id"] == database.id response = api_client.post( @@ -87,7 +90,8 @@ def test_create_integration(api_client, data_fixture): { "type": "local_baserow", "name": "test", - "authorized_user_id": 17, + "authorized_subject_id": user.id, + "authorized_subject_type": "auth.User", }, format="json", HTTP_AUTHORIZATION=f"JWT {token}", @@ -95,7 +99,111 @@ def test_create_integration(api_client, data_fixture): response_json = response.json() assert response.status_code == HTTP_200_OK - assert response_json["authorized_user"]["username"] == user.username + assert response_json["authorized_subject"]["username"] == user.username + + +@pytest.mark.django_db +def test_create_and_update_local_baserow_integration_with_agent( + api_client, data_fixture +): + user, token = data_fixture.create_user_and_token() + workspace = data_fixture.create_workspace(user=user) + application = data_fixture.create_builder_application(workspace=workspace) + agent = Agent.objects.create(workspace=workspace, name="Row writer") + url = reverse("api:integrations:list", kwargs={"application_id": application.id}) + + response = api_client.post( + url, + { + "type": "local_baserow", + "name": "Agent connection", + "authorized_subject_id": agent.id, + "authorized_subject_type": "core.Agent", + }, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert response.json()["authorized_subject"] == { + "id": agent.id, + "name": "Row writer", + "trashed": False, + "type": "core.Agent", + } + + integration = Integration.objects.get(id=response.json()["id"]).specific + assert integration.authorized_subject == agent + + item_url = reverse( + "api:integrations:item", kwargs={"integration_id": integration.id} + ) + response = api_client.patch( + item_url, + {"authorized_subject_id": user.id, "authorized_subject_type": "auth.User"}, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert response.json()["authorized_subject"]["id"] == user.id + integration.refresh_from_db() + assert integration.authorized_subject == user + + +@pytest.mark.django_db +def test_local_baserow_integration_serializes_a_trashed_agent(api_client, data_fixture): + user, token = data_fixture.create_user_and_token() + workspace = data_fixture.create_workspace(user=user) + application = data_fixture.create_builder_application(workspace=workspace) + agent = Agent.objects.create(workspace=workspace, name="Row writer") + integration = data_fixture.create_local_baserow_integration( + application=application, user=user, authorized_agent=agent + ) + TrashHandler.trash(user, workspace, None, agent) + + response = api_client.get( + reverse("api:integrations:list", kwargs={"application_id": application.id}), + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + [response_integration] = [ + item for item in response.json() if item["id"] == integration.id + ] + assert response_integration["authorized_subject"] == { + "id": agent.id, + "name": "Row writer", + "trashed": True, + "type": "core.Agent", + } + + +@pytest.mark.django_db +def test_local_baserow_integration_rejects_agent_from_another_workspace( + api_client, data_fixture +): + user, token = data_fixture.create_user_and_token() + application = data_fixture.create_builder_application(user=user) + other_agent = Agent.objects.create( + workspace=data_fixture.create_workspace(), name="Other agent" + ) + url = reverse("api:integrations:list", kwargs={"application_id": application.id}) + + response = api_client.post( + url, + { + "type": "local_baserow", + "name": "Invalid connection", + "authorized_subject_id": other_agent.id, + "authorized_subject_type": "core.Agent", + }, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_400_BAD_REQUEST + assert response.json()["authorized_subject_id"] == "The subject does not exist." @pytest.mark.django_db @@ -173,7 +281,10 @@ def test_update_integration(api_client, data_fixture): ) assert response.status_code == HTTP_200_OK - assert response.json()["authorized_user"]["username"] == user.username + assert ( + response.json()["authorized_subject"]["username"] + == integration1.authorized_subject.username + ) @pytest.mark.django_db diff --git a/backend/tests/baserow/api/subjects/__init__.py b/backend/tests/baserow/api/subjects/__init__.py new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/backend/tests/baserow/api/subjects/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/tests/baserow/api/subjects/test_subject_views.py b/backend/tests/baserow/api/subjects/test_subject_views.py new file mode 100644 index 0000000000..4acc7ad4e4 --- /dev/null +++ b/backend/tests/baserow/api/subjects/test_subject_views.py @@ -0,0 +1,132 @@ +from django.shortcuts import reverse + +import pytest +from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN + +from baserow.core.agents.subjects import AgentSubjectType +from baserow.core.models import Agent +from baserow.core.subjects import AnonymousUserSubjectType, UserSubjectType + + +@pytest.mark.django_db +def test_staff_can_search_global_subject_options(api_client, data_fixture): + staff, token = data_fixture.create_user_and_token( + email="staff@example.com", is_staff=True + ) + matching_user = data_fixture.create_user(email="matching@example.com") + data_fixture.create_user(email="other@example.com") + workspace = data_fixture.create_workspace(user=staff) + matching_agent = Agent.objects.create(workspace=workspace, name="Matching robot") + + response = api_client.get( + reverse("api:subjects:list"), + { + "search": "matching", + "subject_types": f"{UserSubjectType.type},{AgentSubjectType.type}", + }, + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert response.json()["results"] == [ + { + "id": f"{UserSubjectType.type}:{matching_user.id}", + "subject_id": matching_user.id, + "subject_type": UserSubjectType.type, + "name": matching_user.first_name, + "label": matching_user.email, + "email": matching_user.email, + "subject_count": None, + }, + { + "id": f"{AgentSubjectType.type}:{matching_agent.id}", + "subject_id": matching_agent.id, + "subject_type": AgentSubjectType.type, + "name": matching_agent.name, + "label": matching_agent.name, + "email": None, + "subject_count": None, + }, + ] + + +@pytest.mark.django_db +def test_non_staff_cannot_list_global_subject_options(api_client, data_fixture): + _, token = data_fixture.create_user_and_token() + + response = api_client.get( + reverse("api:subjects:list"), HTTP_AUTHORIZATION=f"JWT {token}" + ) + + assert response.status_code == HTTP_403_FORBIDDEN + + +@pytest.mark.django_db +def test_workspace_subject_options_are_scoped(api_client, data_fixture): + admin, token = data_fixture.create_user_and_token(email="admin@example.com") + workspace = data_fixture.create_workspace(user=admin) + agent = Agent.objects.create(workspace=workspace, name="Workspace robot") + other_workspace = data_fixture.create_workspace() + Agent.objects.create(workspace=other_workspace, name="Other robot") + + response = api_client.get( + reverse("api:subjects:list"), + { + "workspace_id": workspace.id, + "subject_types": AgentSubjectType.type, + }, + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert [result["subject_id"] for result in response.json()["results"]] == [agent.id] + + +@pytest.mark.django_db +def test_workspace_subject_options_reject_non_listable_subject_types( + api_client, data_fixture +): + admin, token = data_fixture.create_user_and_token(email="admin@example.com") + workspace = data_fixture.create_workspace(user=admin) + + response = api_client.get( + reverse("api:subjects:list"), + { + "workspace_id": workspace.id, + "subject_types": AnonymousUserSubjectType.type, + }, + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_400_BAD_REQUEST + assert response.json() == { + "subject_types": "No listable subject types were requested." + } + + +@pytest.mark.django_db +def test_workspace_subject_options_exclude_inactive_and_deletion_scheduled_users( + api_client, data_fixture +): + """Normal subject options remain limited to users who can receive access.""" + + admin, token = data_fixture.create_user_and_token(email="admin@example.com") + workspace = data_fixture.create_workspace(user=admin) + data_fixture.create_user( + workspace=workspace, email="disabled@example.com", is_active=False + ) + data_fixture.create_user( + workspace=workspace, email="scheduled@example.com", to_be_deleted=True + ) + + response = api_client.get( + reverse("api:subjects:list"), + { + "workspace_id": workspace.id, + "subject_types": UserSubjectType.type, + }, + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert [result["subject_id"] for result in response.json()["results"]] == [admin.id] diff --git a/backend/tests/baserow/contrib/automation/history/test_history_handler.py b/backend/tests/baserow/contrib/automation/history/test_history_handler.py index 71808b6063..c1214f6039 100644 --- a/backend/tests/baserow/contrib/automation/history/test_history_handler.py +++ b/backend/tests/baserow/contrib/automation/history/test_history_handler.py @@ -23,6 +23,7 @@ from baserow.contrib.automation.history.models import ( from baserow.contrib.automation.history.service import AutomationHistoryService from baserow.contrib.automation.workflows.constants import WorkflowState from baserow.contrib.integrations.core.constants import RESPONSE_BODY_TYPE +from baserow.core.models import Agent class FakeMonotonicClock: @@ -865,6 +866,27 @@ def test_create_workflow_history_records_who_triggered_it(data_fixture): assert history.triggered_by_name == user.first_name +@pytest.mark.django_db +def test_create_workflow_history_records_agent_who_triggered_it(data_fixture): + workflow = data_fixture.create_automation_workflow() + agent = Agent.objects.create( + workspace=workflow.automation.workspace, + name="Workflow agent", + ) + + history = AutomationHistoryHandler().create_workflow_history( + original_workflow=workflow, + workflow=workflow, + started_on=timezone.now(), + is_test_run=False, + triggered_by=agent, + ) + + assert history.triggered_by_id == agent.id + assert history.triggered_by_type == "core.Agent" + assert history.triggered_by_name == agent.name + + @pytest.mark.django_db def test_create_workflow_history_defaults_to_nobody(data_fixture): workflow = data_fixture.create_automation_workflow() diff --git a/backend/tests/baserow/contrib/automation/test_automation_application_types.py b/backend/tests/baserow/contrib/automation/test_automation_application_types.py index 554bdd271d..cf0b171415 100644 --- a/backend/tests/baserow/contrib/automation/test_automation_application_types.py +++ b/backend/tests/baserow/contrib/automation/test_automation_application_types.py @@ -96,7 +96,8 @@ def test_automation_export_serialized(data_fixture): "name": integration.name, "order": str(integration.order), "type": "local_baserow", - "authorized_user": None, + "authorized_subject_type": None, + "authorized_subject_id": None, } ], "workflows": [ @@ -207,7 +208,7 @@ def test_automation_application_import(data_fixture): assert automation.integrations.count() == 1 first_integration = automation.integrations.first().specific - assert first_integration.authorized_user.id == user.id + assert first_integration.authorized_subject == user assert automation.workflows.count() == 1 workflow = automation.workflows.first() diff --git a/backend/tests/baserow/contrib/automation/workflows/test_workflow_handler.py b/backend/tests/baserow/contrib/automation/workflows/test_workflow_handler.py index fe3f6fbdbb..d2a1a27e08 100644 --- a/backend/tests/baserow/contrib/automation/workflows/test_workflow_handler.py +++ b/backend/tests/baserow/contrib/automation/workflows/test_workflow_handler.py @@ -41,6 +41,7 @@ from baserow.contrib.automation.workflows.exceptions import ( from baserow.contrib.automation.workflows.handler import AutomationWorkflowHandler from baserow.core.action.handler import ActionHandler from baserow.core.cache import global_cache, local_cache +from baserow.core.models import Agent from baserow.core.notifications.models import Notification, NotificationRecipient from baserow.core.registries import ImportExportConfig from baserow.core.subjects import UserSubjectType @@ -451,6 +452,27 @@ def test_publish_returns_published_workflow(data_fixture): assert published_workflow.state == WorkflowState.LIVE +@pytest.mark.django_db +def test_publish_preserves_local_baserow_authorized_subject(data_fixture): + user = data_fixture.create_user() + workspace = data_fixture.create_workspace(user=user) + automation = data_fixture.create_automation_application(workspace=workspace) + workflow = data_fixture.create_automation_workflow( + automation=automation, create_trigger=False + ) + agent = Agent.objects.create(workspace=workspace, name="Automation agent") + data_fixture.create_local_baserow_integration( + application=automation, + authorized_user=user, + authorized_agent=agent, + ) + + published_workflow = AutomationWorkflowHandler().publish(workflow) + + published_integration = published_workflow.automation.integrations.get().specific + assert published_integration.authorized_subject == agent + + @pytest.mark.django_db def test_publish_cleans_up_old_workflows(data_fixture): workflow = data_fixture.create_automation_workflow() diff --git a/backend/tests/baserow/contrib/builder/domains/test_domain_handler.py b/backend/tests/baserow/contrib/builder/domains/test_domain_handler.py index f4e6b83985..f60e421fc5 100644 --- a/backend/tests/baserow/contrib/builder/domains/test_domain_handler.py +++ b/backend/tests/baserow/contrib/builder/domains/test_domain_handler.py @@ -16,6 +16,8 @@ from baserow.contrib.builder.models import Builder from baserow.contrib.builder.pages.models import Page from baserow.contrib.builder.workflow_actions.models import BuilderWorkflowAction from baserow.core.cache import global_cache +from baserow.core.integrations.exceptions import IntegrationImproperlyConfigured +from baserow.core.models import Agent from baserow.core.user_sources.constants import DEFAULT_USER_ROLE_PREFIX from baserow.core.utils import Progress @@ -248,6 +250,46 @@ def test_domain_publishing(data_fixture): assert Builder.objects.count() == 2 +@pytest.mark.django_db +def test_domain_publishing_preserves_local_baserow_authorized_agent(data_fixture): + user = data_fixture.create_user() + workspace = data_fixture.create_workspace(user=user) + builder = data_fixture.create_builder_application(workspace=workspace) + agent = Agent.objects.create(workspace=workspace, name="Builder agent") + data_fixture.create_local_baserow_integration( + application=builder, + authorized_user=user, + authorized_agent=agent, + ) + domain = data_fixture.create_builder_custom_domain(builder=builder) + + domain = DomainHandler().publish(domain) + + published_integration = domain.published_to.integrations.get().specific + assert published_integration.authorized_subject == agent + + +@pytest.mark.django_db +def test_domain_publishing_rejects_trashed_local_baserow_agent(data_fixture): + user = data_fixture.create_user() + workspace = data_fixture.create_workspace(user=user) + builder = data_fixture.create_builder_application(workspace=workspace) + agent = Agent.objects.create( + workspace=workspace, name="Trashed agent", trashed=True + ) + data_fixture.create_local_baserow_integration( + application=builder, + authorized_user=user, + authorized_agent=agent, + ) + domain = data_fixture.create_builder_custom_domain(builder=builder) + + with pytest.raises( + IntegrationImproperlyConfigured, match="authorized subject is trashed" + ): + DomainHandler().publish(domain) + + @pytest.mark.django_db def test_get_domain_for_builder(data_fixture): user = data_fixture.create_user() diff --git a/backend/tests/baserow/contrib/builder/test_builder_application_type.py b/backend/tests/baserow/contrib/builder/test_builder_application_type.py index be86ee0b5c..4b5cc063b8 100644 --- a/backend/tests/baserow/contrib/builder/test_builder_application_type.py +++ b/backend/tests/baserow/contrib/builder/test_builder_application_type.py @@ -627,7 +627,8 @@ def test_builder_application_export(data_fixture): ], "integrations": [ { - "authorized_user": None, + "authorized_subject_type": None, + "authorized_subject_id": None, "id": integration.id, "name": "test", "order": "1.00000000000000000000", @@ -1142,7 +1143,7 @@ def test_builder_application_import(data_fixture): assert builder.integrations.count() == 1 first_integration = builder.integrations.first().specific - assert first_integration.authorized_user.id == user.id + assert first_integration.authorized_subject == user assert builder.user_sources.count() == 1 diff --git a/backend/tests/baserow/contrib/builder/test_core_handler_builder.py b/backend/tests/baserow/contrib/builder/test_core_handler_builder.py index 4b684bc68b..6b9d8420d1 100644 --- a/backend/tests/baserow/contrib/builder/test_core_handler_builder.py +++ b/backend/tests/baserow/contrib/builder/test_core_handler_builder.py @@ -45,4 +45,4 @@ def test_duplicated_application_imports_integration(data_fixture): new_builder = CoreHandler().duplicate_application(user, builder) - assert new_builder.integrations.all()[0].specific.authorized_user == user + assert new_builder.integrations.all()[0].specific.authorized_subject == user diff --git a/backend/tests/baserow/contrib/builder/test_snapshot_handler_builder.py b/backend/tests/baserow/contrib/builder/test_snapshot_handler_builder.py index 42fe0e945e..bf47a12d2f 100644 --- a/backend/tests/baserow/contrib/builder/test_snapshot_handler_builder.py +++ b/backend/tests/baserow/contrib/builder/test_snapshot_handler_builder.py @@ -67,4 +67,4 @@ def test_can_restore_a_snapshot_with_integration(data_fixture): ) snapshot_restored = SnapshotHandler().perform_restore(snapshot, Progress(total=100)) - assert snapshot_restored.integrations.all()[0].specific.authorized_user == user + assert snapshot_restored.integrations.all()[0].specific.authorized_subject == user diff --git a/backend/tests/baserow/contrib/dashboard/test_dashboard_application_types.py b/backend/tests/baserow/contrib/dashboard/test_dashboard_application_types.py index d893d10a36..d357e3b9f4 100644 --- a/backend/tests/baserow/contrib/dashboard/test_dashboard_application_types.py +++ b/backend/tests/baserow/contrib/dashboard/test_dashboard_application_types.py @@ -98,7 +98,8 @@ def test_dashboard_export_serialized_with_widgets(data_fixture): "type": "dashboard", "integrations": [ { - "authorized_user": user.email, + "authorized_subject_type": "auth.User", + "authorized_subject_id": user.id, "id": integration.id, "name": "", "order": "1.00000000000000000000", @@ -271,7 +272,8 @@ def test_dashboard_import_serialized_with_legacy_widgets(data_fixture): "type": "dashboard", "integrations": [ { - "authorized_user": user.email, + "authorized_subject_type": "auth.User", + "authorized_subject_id": user.id, "id": 1, "name": "IntegrationName", "order": "1.00000000000000000000", @@ -358,7 +360,7 @@ def test_dashboard_import_serialized_with_legacy_widgets(data_fixture): assert integration.content_type == ContentType.objects.get_for_model( LocalBaserowIntegration ) - assert integration.authorized_user.id == user.id + assert integration.authorized_subject == user assert integration.name == "IntegrationName" assert integration.order == Decimal("1.0") diff --git a/backend/tests/baserow/contrib/database/api/rows/test_row_views.py b/backend/tests/baserow/contrib/database/api/rows/test_row_views.py index 22d1d86524..9b71d230c1 100644 --- a/backend/tests/baserow/contrib/database/api/rows/test_row_views.py +++ b/backend/tests/baserow/contrib/database/api/rows/test_row_views.py @@ -3899,6 +3899,11 @@ def test_list_row_history_for_different_rows(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2021-01-01T12:01:00Z", "before": { f"field_{name_field.id}": "New 1", @@ -3921,6 +3926,11 @@ def test_list_row_history_for_different_rows(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2021-01-01T12:00:00Z", "before": { f"field_{name_field.id}": "Original 1", @@ -3971,6 +3981,11 @@ def test_list_row_history_for_different_rows(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2021-01-01T12:00:00Z", "before": { f"field_{name_field.id}": "Original 2", @@ -4140,6 +4155,11 @@ def test_list_row_history_for_different_fields(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2021-01-01T12:00:00Z", "before": { f"field_{name_field.id}": "Original 1", @@ -4381,6 +4401,11 @@ def test_undo_redo_create_new_entries_in_row_history(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2021-01-01T12:01:00Z", "before": { f"field_{name_field.id}": "New 1", @@ -4403,6 +4428,11 @@ def test_undo_redo_create_new_entries_in_row_history(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2021-01-01T12:00:00Z", "before": { f"field_{name_field.id}": "Original 1", @@ -4449,6 +4479,11 @@ def test_undo_redo_create_new_entries_in_row_history(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2021-01-01T12:02:00Z", "before": { f"field_{name_field.id}": "Original 1", @@ -4471,6 +4506,11 @@ def test_undo_redo_create_new_entries_in_row_history(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2021-01-01T12:01:00Z", "before": { f"field_{name_field.id}": "New 1", @@ -4493,6 +4533,11 @@ def test_undo_redo_create_new_entries_in_row_history(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2021-01-01T12:00:00Z", "before": { f"field_{name_field.id}": "Original 1", @@ -4614,6 +4659,11 @@ def test_list_row_history_endpoint_is_paginated(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2023-01-01T12:04:00Z", "before": { f"field_{name_field.id}": "New 1.3", @@ -4636,6 +4686,11 @@ def test_list_row_history_endpoint_is_paginated(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2023-01-01T12:03:00Z", "before": { f"field_{name_field.id}": "New 1.2", @@ -4677,6 +4732,11 @@ def test_list_row_history_endpoint_is_paginated(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2023-01-01T12:01:00Z", "before": { f"field_{name_field.id}": "New 1.0", @@ -4699,6 +4759,11 @@ def test_list_row_history_endpoint_is_paginated(data_fixture, api_client): "id": user.id, "name": user.first_name, }, + "actor": { + "id": user.id, + "type": "auth.User", + "name": user.first_name, + }, "timestamp": "2023-01-01T12:00:00Z", "before": { f"field_{name_field.id}": "Original 1", diff --git a/backend/tests/baserow/contrib/database/field/test_field_notification_types.py b/backend/tests/baserow/contrib/database/field/test_field_notification_types.py index 42d6641583..96a407c086 100644 --- a/backend/tests/baserow/contrib/database/field/test_field_notification_types.py +++ b/backend/tests/baserow/contrib/database/field/test_field_notification_types.py @@ -22,8 +22,9 @@ from baserow.contrib.database.rows.handler import RowHandler from baserow.contrib.database.table.models import RichTextFieldMention from baserow.core.action.handler import ActionHandler from baserow.core.action.registries import action_type_registry +from baserow.core.models import Agent from baserow.core.notifications.handler import NotificationHandler -from baserow.core.notifications.models import NotificationRecipient +from baserow.core.notifications.models import Notification, NotificationRecipient from baserow.core.trash.handler import TrashHandler from baserow.test_utils.helpers import ( AnyInt, @@ -37,6 +38,73 @@ pytestmark = pytest.mark.enable_signals( ) +@pytest.mark.django_db(transaction=True) +def test_agent_row_create_collaborator_notification_has_no_user_sender(data_fixture): + owner = data_fixture.create_user() + collaborator = data_fixture.create_user() + workspace = data_fixture.create_workspace(members=[owner, collaborator]) + agent = Agent.objects.create( + workspace=workspace, + name="Row writer", + role_uid="ADMIN", + ) + database = data_fixture.create_database_application(workspace=workspace) + table = data_fixture.create_database_table(database=database) + collaborator_field = data_fixture.create_multiple_collaborators_field( + table=table, + notify_user_when_added=True, + ) + + RowHandler().create_row( + user=agent, + table=table, + values={collaborator_field.id: [{"id": collaborator.id}]}, + ) + + notification = Notification.objects.get( + type=CollaboratorAddedToRowNotificationType.type + ) + assert notification.sender is None + + +@pytest.mark.django_db(transaction=True) +def test_agent_row_update_mention_notification_has_no_user_sender(data_fixture): + owner = data_fixture.create_user() + mentioned_user = data_fixture.create_user() + workspace = data_fixture.create_workspace(members=[owner, mentioned_user]) + agent = Agent.objects.create( + workspace=workspace, + name="Row writer", + role_uid="ADMIN", + ) + database = data_fixture.create_database_application(workspace=workspace) + table = data_fixture.create_database_table(database=database) + rich_text_field = data_fixture.create_long_text_field( + table=table, + long_text_enable_rich_text=True, + ) + with transaction.atomic(): + row = RowHandler().create_row(user=agent, table=table) + RowHandler().update_row( + user=agent, + table=table, + row=row, + values={rich_text_field.id: f"Hello @{mentioned_user.id}"}, + ) + + notification = Notification.objects.get( + type=UserMentionInRichTextFieldNotificationType.type + ) + assert notification.sender is None + assert ( + UserMentionInRichTextFieldNotificationType.get_notification_title_for_email( + notification, {} + ) + == f"An unknown user mentioned you in {rich_text_field.name} in row " + f"{row} in {table.name}." + ) + + @pytest.mark.django_db(transaction=True) @patch("baserow.ws.tasks.broadcast_to_users.apply") def test_notification_creation_on_adding_users_on_collaborator_fields( diff --git a/backend/tests/baserow/contrib/database/field/test_password_field_type.py b/backend/tests/baserow/contrib/database/field/test_password_field_type.py index 6cd602dd86..cd1eb84078 100644 --- a/backend/tests/baserow/contrib/database/field/test_password_field_type.py +++ b/backend/tests/baserow/contrib/database/field/test_password_field_type.py @@ -430,8 +430,9 @@ def test_check_history_content_for_password_field(data_fixture): history_entries = list( RowHistory.objects.order_by("row_id").values( - "user_id", - "user_name", + "actor_id", + "actor_type", + "actor_name", "table_id", "row_id", "action_timestamp", diff --git a/backend/tests/baserow/contrib/database/migrations/test_row_history_actor_migration.py b/backend/tests/baserow/contrib/database/migrations/test_row_history_actor_migration.py new file mode 100644 index 0000000000..af21eb8a15 --- /dev/null +++ b/backend/tests/baserow/contrib/database/migrations/test_row_history_actor_migration.py @@ -0,0 +1,69 @@ +from datetime import datetime, timezone +from importlib import import_module + +import pytest + + +@pytest.mark.once_per_day_in_ci +def test_row_history_actor_types_are_backfilled_in_batches(migrator, monkeypatch): + """Existing row history keeps users and identifies anonymous actors.""" + + migration = import_module( + "baserow.contrib.database.migrations.0227_backfill_rowhistory_anonymous_actor_type" + ) + monkeypatch.setattr(migration, "ROW_HISTORY_BACKFILL_BATCH_SIZE", 2) + + old_state = migrator.migrate([("database", "0223_gridview_group_by_layout")]) + + ContentType = old_state.apps.get_model("contenttypes", "ContentType") + Workspace = old_state.apps.get_model("core", "Workspace") + Database = old_state.apps.get_model("database", "Database") + Table = old_state.apps.get_model("database", "Table") + RowHistory = old_state.apps.get_model("database", "RowHistory") + + workspace = Workspace.objects.create(name="workspace") + database = Database.objects.create( + content_type=ContentType.objects.get_for_model(Database), + order=1, + name="database", + workspace_id=workspace.id, + trashed=False, + ) + table = Table.objects.create( + database_id=database.id, name="table", order=1, trashed=False + ) + common_values = { + "table_id": table.id, + "row_id": 1, + "field_names": [], + "fields_metadata": {}, + "action_uuid": "00000000-0000-0000-0000-000000000001", + "action_command_type": "DO", + "action_timestamp": datetime(2026, 1, 1, tzinfo=timezone.utc), + "action_type": "update_row", + "before_values": {}, + "after_values": {}, + } + user_entry = RowHistory.objects.create( + user_id=1, user_name="User", **common_values + ) + anonymous_entries = [ + RowHistory.objects.create( + user_id=None, + user_name=f"Anonymous User {index}", + **common_values, + ) + for index in range(3) + ] + + new_state = migrator.migrate( + [("database", "0227_backfill_rowhistory_anonymous_actor_type")] + ) + RowHistory = new_state.apps.get_model("database", "RowHistory") + + assert RowHistory.objects.get(id=user_entry.id).actor_type == "auth.User" + assert list( + RowHistory.objects.filter( + id__in=[entry.id for entry in anonymous_entries] + ).values_list("actor_type", flat=True) + ) == ["anonymous"] * 3 diff --git a/backend/tests/baserow/contrib/database/rows/test_row_history.py b/backend/tests/baserow/contrib/database/rows/test_row_history.py index 64d9611503..d73b23dd12 100644 --- a/backend/tests/baserow/contrib/database/rows/test_row_history.py +++ b/backend/tests/baserow/contrib/database/rows/test_row_history.py @@ -9,6 +9,7 @@ from freezegun import freeze_time from baserow.api.sessions import get_untrusted_client_session_id from baserow.contrib.database.action.scopes import TableActionScopeType +from baserow.contrib.database.api.rows.serializers import RowHistorySerializer from baserow.contrib.database.fields.registries import FieldType from baserow.contrib.database.rows.actions import ( CreateRowActionType, @@ -28,6 +29,9 @@ from baserow.contrib.database.rows.registries import ( from baserow.contrib.database.trash.trash_types import RowTrashableItemType from baserow.core.action.handler import ActionHandler from baserow.core.action.registries import ActionType, action_type_registry +from baserow.core.agents.subjects import AgentSubjectType +from baserow.core.models import Agent +from baserow.core.subjects import UserSubjectType from baserow.core.trash.actions import RestoreFromTrashActionType from baserow.test_utils.helpers import setup_interesting_test_table @@ -61,8 +65,8 @@ def test_update_rows_insert_multiple_entries_in_row_history(data_fixture): assert RowHistory.objects.count() == 2 history_entries = RowHistory.objects.order_by("row_id").values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -74,8 +78,8 @@ def test_update_rows_insert_multiple_entries_in_row_history(data_fixture): assert list(history_entries) == [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row_one.id, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -90,8 +94,8 @@ def test_update_rows_insert_multiple_entries_in_row_history(data_fixture): }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row_two.id, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -108,6 +112,66 @@ def test_update_rows_insert_multiple_entries_in_row_history(data_fixture): ] +@pytest.mark.django_db +@pytest.mark.row_history +def test_agent_is_stored_as_typed_row_history_actor(data_fixture): + user = data_fixture.create_user() + database = data_fixture.create_database_application(user=user) + table = data_fixture.create_database_table(user=user, database=database) + field = data_fixture.create_text_field(table=table, name="Name") + agent = Agent.objects.create( + workspace=database.workspace, + name="A" * 160, + role_uid="ADMIN", + ) + row = RowHandler().force_create_row(user, table, {field.id: "Before"}) + + UpdateRowsActionType.do( + agent, + table, + [{"id": row.id, f"field_{field.id}": "After"}], + ) + + entry = RowHistory.objects.get() + assert entry.actor_id == agent.id + assert entry.actor_type == AgentSubjectType.type + assert entry.actor_name == agent.name + assert RowHistorySerializer(entry).data["actor"] == { + "id": agent.id, + "type": AgentSubjectType.type, + "name": agent.name, + } + assert RowHistorySerializer(entry).data["user"] is None + + +@pytest.mark.django_db +def test_existing_row_history_columns_are_reused_for_user_actors(data_fixture): + user = data_fixture.create_user() + table = data_fixture.create_database_table(user=user) + entry = RowHistory.objects.create( + actor_id=user.id, + actor_name=user.first_name, + table=table, + row_id=1, + field_names=[], + fields_metadata={}, + action_uuid="00000000-0000-0000-0000-000000000000", + action_type="update_row", + action_timestamp=datetime.now(timezone.utc), + before_values={}, + after_values={}, + ) + entry.refresh_from_db() + + assert RowHistory._meta.get_field("actor_id").column == "user_id" + assert RowHistory._meta.get_field("actor_name").column == "user_name" + assert entry.actor_type == UserSubjectType.type + assert RowHistorySerializer(entry).data["user"] == { + "id": user.id, + "name": user.first_name, + } + + @pytest.mark.django_db @pytest.mark.row_history def test_history_handler_only_save_changed_fields(data_fixture): @@ -143,8 +207,8 @@ def test_history_handler_only_save_changed_fields(data_fixture): assert RowHistory.objects.count() == 1 history_entries = RowHistory.objects.values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -156,8 +220,8 @@ def test_history_handler_only_save_changed_fields(data_fixture): assert list(history_entries) == [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -214,8 +278,8 @@ def test_update_rows_action_doesnt_insert_entries_if_row_doesnt_change(data_fixt assert RowHistory.objects.count() == 1 history_entries = RowHistory.objects.order_by("row_id").values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -226,8 +290,8 @@ def test_update_rows_action_doesnt_insert_entries_if_row_doesnt_change(data_fixt ) assert list(history_entries) == [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row_one.id, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -255,7 +319,7 @@ def test_row_history_handler_list_history_filters_with_registry(data_fixture): type = "row_history_op_stub" def apply_to_list_queryset(self, queryset, workspace, table_id, row_id): - return queryset.filter(user_id__lt=2) + return queryset.filter(actor_id__lt=2) user = data_fixture.create_user() database = data_fixture.create_database_application(user=user) @@ -274,7 +338,7 @@ def test_row_history_handler_list_history_filters_with_registry(data_fixture): "after_values": {}, "action_timestamp": datetime(2021, 1, 3, 23, 59, tzinfo=timezone.utc), } - entries = [RowHistory(**common_params, user_id=i) for i in range(0, 10)] + entries = [RowHistory(**common_params, actor_id=i) for i in range(0, 10)] RowHistory.objects.bulk_create(entries) assert ( len( @@ -412,8 +476,8 @@ def test_update_rows_insert_entries_in_linked_rows_history(data_fixture): assert RowHistory.objects.count() == 3 history_entries = RowHistory.objects.order_by("table_id", "row_id").values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -426,8 +490,8 @@ def test_update_rows_insert_entries_in_linked_rows_history(data_fixture): expected_entries = [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_a.id, "row_id": 1, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -447,8 +511,8 @@ def test_update_rows_insert_entries_in_linked_rows_history(data_fixture): }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_b.id, "row_id": 1, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -465,8 +529,8 @@ def test_update_rows_insert_entries_in_linked_rows_history(data_fixture): }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_b.id, "row_id": 2, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -500,8 +564,8 @@ def test_update_rows_insert_entries_in_linked_rows_history(data_fixture): history_entries = RowHistory.objects.order_by( "-action_timestamp", "table_id", "row_id" ).values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -516,8 +580,8 @@ def test_update_rows_insert_entries_in_linked_rows_history(data_fixture): last_entries = list(history_entries)[:2] expected_entries = [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_a.id, "row_id": 1, "action_timestamp": datetime(2021, 1, 1, 12, 30, tzinfo=timezone.utc), @@ -537,8 +601,8 @@ def test_update_rows_insert_entries_in_linked_rows_history(data_fixture): }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_b.id, "row_id": 1, "action_timestamp": datetime(2021, 1, 1, 12, 30, tzinfo=timezone.utc), @@ -590,8 +654,8 @@ def test_update_rows_dont_insert_entries_in_linked_rows_history_without_related_ assert RowHistory.objects.count() == 1 history_entries = RowHistory.objects.values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -604,8 +668,8 @@ def test_update_rows_dont_insert_entries_in_linked_rows_history_without_related_ expected_entries = [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_a.id, "row_id": 1, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -685,8 +749,8 @@ def test_update_rows_insert_entries_in_linked_rows_history_in_multiple_tables( assert RowHistory.objects.count() == 6 history_entries = RowHistory.objects.order_by("table_id", "row_id").values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -724,8 +788,8 @@ def test_update_rows_insert_entries_in_linked_rows_history_in_multiple_tables( expected_entries = [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_a.id, "row_id": 1, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -756,8 +820,8 @@ def test_update_rows_insert_entries_in_linked_rows_history_in_multiple_tables( }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_a.id, "row_id": 2, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -788,8 +852,8 @@ def test_update_rows_insert_entries_in_linked_rows_history_in_multiple_tables( }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_b.id, "row_id": 1, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -806,8 +870,8 @@ def test_update_rows_insert_entries_in_linked_rows_history_in_multiple_tables( }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_b.id, "row_id": 2, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -824,8 +888,8 @@ def test_update_rows_insert_entries_in_linked_rows_history_in_multiple_tables( }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_c.id, "row_id": 1, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -842,8 +906,8 @@ def test_update_rows_insert_entries_in_linked_rows_history_in_multiple_tables( }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_c.id, "row_id": 2, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -894,8 +958,8 @@ def test_update_rows_insert_entries_in_linked_rows_history_with_values(data_fixt assert RowHistory.objects.count() == 3 history_entries = RowHistory.objects.order_by("table_id", "row_id").values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -907,8 +971,8 @@ def test_update_rows_insert_entries_in_linked_rows_history_with_values(data_fixt expected_entries = [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_a.id, "row_id": 1, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -927,8 +991,8 @@ def test_update_rows_insert_entries_in_linked_rows_history_with_values(data_fixt }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_b.id, "row_id": 1, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -944,8 +1008,8 @@ def test_update_rows_insert_entries_in_linked_rows_history_with_values(data_fixt }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table_b.id, "row_id": 2, "action_timestamp": datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc), @@ -999,8 +1063,8 @@ def test_create_rows_action_row_history_with_undo_redo( assert RowHistory.objects.count() == 1 history_entries = RowHistory.objects.order_by("row_id", "action_timestamp").values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -1013,8 +1077,8 @@ def test_create_rows_action_row_history_with_undo_redo( assert list(history_entries) == [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp_do, @@ -1041,8 +1105,8 @@ def test_create_rows_action_row_history_with_undo_redo( assert undone history_entries = RowHistory.objects.order_by("row_id", "action_timestamp").values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -1055,8 +1119,8 @@ def test_create_rows_action_row_history_with_undo_redo( assert list(history_entries) == [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp_do, @@ -1072,8 +1136,8 @@ def test_create_rows_action_row_history_with_undo_redo( }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp_undo, @@ -1095,8 +1159,8 @@ def test_create_rows_action_row_history_with_undo_redo( assert redone history_entries = RowHistory.objects.order_by("row_id", "action_timestamp").values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -1109,8 +1173,8 @@ def test_create_rows_action_row_history_with_undo_redo( assert list(history_entries) == [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp_do, @@ -1126,8 +1190,8 @@ def test_create_rows_action_row_history_with_undo_redo( }, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp_undo, @@ -1138,8 +1202,8 @@ def test_create_rows_action_row_history_with_undo_redo( "fields_metadata": {}, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp_redo, @@ -1193,8 +1257,8 @@ def test_delete_rows_action_row_history_with_undo_redo( assert RowHistory.objects.count() == 1 history_entries = RowHistory.objects.order_by("row_id").values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -1207,8 +1271,8 @@ def test_delete_rows_action_row_history_with_undo_redo( assert list(history_entries) == [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, @@ -1229,8 +1293,8 @@ def test_delete_rows_action_row_history_with_undo_redo( assert undone history_entries = RowHistory.objects.order_by("row_id", "id").values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -1243,8 +1307,8 @@ def test_delete_rows_action_row_history_with_undo_redo( assert list(history_entries) == [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, @@ -1255,8 +1319,8 @@ def test_delete_rows_action_row_history_with_undo_redo( "fields_metadata": {}, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, @@ -1277,8 +1341,8 @@ def test_delete_rows_action_row_history_with_undo_redo( assert redone history_entries = RowHistory.objects.order_by("row_id", "id").values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -1291,8 +1355,8 @@ def test_delete_rows_action_row_history_with_undo_redo( assert list(history_entries) == [ { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, @@ -1303,8 +1367,8 @@ def test_delete_rows_action_row_history_with_undo_redo( "fields_metadata": {}, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, @@ -1315,8 +1379,8 @@ def test_delete_rows_action_row_history_with_undo_redo( "fields_metadata": {}, }, { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, @@ -1429,8 +1493,8 @@ def test_create_rows_action_row_history_with_undo_redo_related_tables( RowHistory.objects.filter(**kwargs) .order_by("row_id") .values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -1452,8 +1516,8 @@ def test_create_rows_action_row_history_with_undo_redo_related_tables( f["name"]: None if f["type"].type != "password" else False for f in fields } expected = { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, @@ -1494,8 +1558,8 @@ def test_create_rows_action_row_history_with_undo_redo_related_tables( history = get_row_history_entries(table_id=table.id, row_id=row.id) expected = { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, @@ -1533,8 +1597,8 @@ def test_create_rows_action_row_history_with_undo_redo_related_tables( history = get_row_history_entries(table_id=table.id, row_id=row.id) expected = { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, @@ -1638,8 +1702,8 @@ def test_delete_rows_action_row_history_with_undo_redo_related_tables( RowHistory.objects.filter(**kwargs) .order_by("row_id") .values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -1658,8 +1722,8 @@ def test_delete_rows_action_row_history_with_undo_redo_related_tables( metadata.pop("id", None) # delete actions don't produce values diff expected = { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, @@ -1700,8 +1764,8 @@ def test_delete_rows_action_row_history_with_undo_redo_related_tables( history = get_row_history_entries(table_id=table.id, row_id=row.id) expected = { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, @@ -1739,8 +1803,8 @@ def test_delete_rows_action_row_history_with_undo_redo_related_tables( history = get_row_history_entries(table_id=table.id, row_id=row.id) expected = { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, @@ -1836,8 +1900,8 @@ def test_restore_rows_action_with_related_tables( RowHistory.objects.filter(**kwargs) .order_by("row_id") .values( - "user_id", - "user_name", + "actor_id", + "actor_name", "table_id", "row_id", "action_timestamp", @@ -1855,8 +1919,8 @@ def test_restore_rows_action_with_related_tables( ) metadata.pop("id", None) expected = { - "user_id": user.id, - "user_name": user.first_name, + "actor_id": user.id, + "actor_name": user.first_name, "table_id": table.id, "row_id": row.id, "action_timestamp": freezed_timestamp, diff --git a/backend/tests/baserow/contrib/database/ws/test_ws_rows_signals.py b/backend/tests/baserow/contrib/database/ws/test_ws_rows_signals.py index 1682a5ff0d..a26894cf45 100644 --- a/backend/tests/baserow/contrib/database/ws/test_ws_rows_signals.py +++ b/backend/tests/baserow/contrib/database/ws/test_ws_rows_signals.py @@ -435,6 +435,13 @@ def test_rows_history_updated( "user": OrderedDict( [("id", user.id), ("name", user.first_name)] ), + "actor": OrderedDict( + [ + ("id", user.id), + ("type", "auth.User"), + ("name", user.first_name), + ] + ), "timestamp": "2023-03-30T00:00:00Z", "before": {f"field_{field.id}": "row 1"}, "after": {f"field_{field.id}": "row 1 updated"}, @@ -457,6 +464,13 @@ def test_rows_history_updated( "user": OrderedDict( [("id", user.id), ("name", user.first_name)] ), + "actor": OrderedDict( + [ + ("id", user.id), + ("type", "auth.User"), + ("name", user.first_name), + ] + ), "timestamp": "2023-03-30T00:00:00Z", "before": {f"field_{field.id}": "row 2"}, "after": {f"field_{field.id}": "row 2 updated"}, diff --git a/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_actor_dispatch.py b/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_actor_dispatch.py index 275f1e3916..6b9ca58dbd 100644 --- a/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_actor_dispatch.py +++ b/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_actor_dispatch.py @@ -6,6 +6,7 @@ from baserow.contrib.integrations.local_baserow.service_types import ( LocalBaserowUpsertRowServiceType, ) from baserow.core.exceptions import UserNotInWorkspace +from baserow.core.models import Agent from baserow.core.services.exceptions import ( ServiceImproperlyConfiguredDispatchException, ) @@ -55,13 +56,12 @@ def test_get_acting_user_raises_without_an_integration_or_an_actor(data_fixture) @pytest.mark.django_db -def test_get_acting_user_raises_when_the_integration_has_no_authorized_user( +def test_get_acting_user_raises_when_the_integration_has_no_authorized_subject( data_fixture, ): """ - An import leaves `authorized_user` null when the exported username is not in - the target workspace. The actor must not stand in for it, and a `None` must - not reach a permission check as an anonymous user. + The actor must not stand in for missing integration authorization, and a + `None` must not reach a permission check as an anonymous user. """ clicker = data_fixture.create_user() @@ -70,7 +70,8 @@ def test_get_acting_user_raises_when_the_integration_has_no_authorized_user( integration = data_fixture.create_local_baserow_integration( application=page.builder, user=user ) - integration.authorized_user = None + integration.authorized_subject_type = None + integration.authorized_subject_id = None integration.save() service = data_fixture.create_local_baserow_upsert_row_service( integration=integration @@ -82,6 +83,41 @@ def test_get_acting_user_raises_when_the_integration_has_no_authorized_user( ) +@pytest.mark.django_db +def test_dispatch_rejects_a_trashed_authorized_agent(data_fixture): + user = data_fixture.create_user() + page = data_fixture.create_builder_page(user=user) + agent = Agent.objects.create( + workspace=page.builder.workspace, + name="Row writer", + role_uid="ADMIN", + trashed=True, + ) + integration = data_fixture.create_local_baserow_integration( + application=page.builder, + user=user, + authorized_agent=agent, + ) + table, name_field = _table_with_name_field(data_fixture, user) + service = data_fixture.create_local_baserow_upsert_row_service( + integration=integration, + table=table, + ) + service.field_mappings.create(field=name_field, value="'Ada'", enabled=True) + + with pytest.raises( + ServiceImproperlyConfiguredDispatchException, + match="authorized agent is trashed", + ): + ServiceHandler().dispatch_service(service, FakeDispatchContext()) + + assert table.get_model().objects.count() == 0 + # Only the trash-inclusive lookup returns the agent, so it can never act. + integration.refresh_from_db() + assert integration.authorized_subject is None + assert integration.authorized_subject_including_trash == agent + + @pytest.mark.django_db def test_get_permission_workspace_uses_the_integration_application(data_fixture): user = data_fixture.create_user() diff --git a/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_delete_row_service_type.py b/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_delete_row_service_type.py index 596b76f5b8..04245ffe38 100644 --- a/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_delete_row_service_type.py +++ b/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_delete_row_service_type.py @@ -9,6 +9,7 @@ from baserow.contrib.integrations.local_baserow.models import LocalBaserowDelete from baserow.contrib.integrations.local_baserow.service_types import ( LocalBaserowDeleteRowServiceType, ) +from baserow.core.models import Agent, TrashEntry from baserow.core.services.exceptions import ( DoesNotExist, InvalidContextContentDispatchException, @@ -190,6 +191,39 @@ def test_local_baserow_delete_row_service_dispatch_data_with_multiple_ids(data_f assert model.objects.filter(id__in=[row_1.id, row_3.id]).exists() is False +@pytest.mark.django_db +def test_local_baserow_delete_row_service_dispatch_data_as_agent(data_fixture): + user = data_fixture.create_user() + page = data_fixture.create_builder_page(user=user) + database = data_fixture.create_database_application( + workspace=page.builder.workspace + ) + table = data_fixture.create_database_table(database=database) + agent = Agent.objects.create( + workspace=page.builder.workspace, + name="Row deleter", + role_uid="ADMIN", + ) + integration = data_fixture.create_local_baserow_integration( + application=page.builder, + user=user, + authorized_agent=agent, + ) + model = table.get_model() + row = model.objects.create() + service = data_fixture.create_local_baserow_delete_row_service( + integration=integration, + table=table, + row_id=str(row.id), + ) + + ServiceHandler().dispatch_service(service, FakeDispatchContext()) + + assert not model.objects.filter(id=row.id).exists() + trash_entry = TrashEntry.objects.get(trash_item_type="rows") + assert trash_entry.user_who_trashed is None + + @pytest.mark.django_db @override_settings(INTEGRATION_LOCAL_BASEROW_BATCH_OPERATION_SIZE_LIMIT=1) def test_local_baserow_delete_row_service_rejects_too_many_ids(data_fixture): diff --git a/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_list_rows_service_type.py b/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_list_rows_service_type.py index d904998dd9..b195a77e0f 100644 --- a/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_list_rows_service_type.py +++ b/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_list_rows_service_type.py @@ -4,6 +4,7 @@ from unittest.mock import MagicMock, Mock, patch from django.db import connection from django.test import override_settings from django.test.utils import CaptureQueriesContext +from django.utils import timezone import pytest @@ -21,11 +22,13 @@ from baserow.contrib.integrations.local_baserow.service_types import ( LocalBaserowListRowsUserServiceType, ) from baserow.core.exceptions import PermissionException +from baserow.core.models import Agent from baserow.core.services.exceptions import ( ServiceImproperlyConfiguredDispatchException, ) from baserow.core.services.handler import ServiceHandler from baserow.core.services.registries import service_type_registry +from baserow.core.subjects import UserSubjectType from baserow.core.utils import MirrorDict from baserow.test_utils.helpers import AnyStr, setup_interesting_test_table from baserow.test_utils.pytest_conftest import FakeDispatchContext, fake_import_formula @@ -57,6 +60,43 @@ def test_create_local_baserow_list_rows_service(data_fixture): assert service.table.id == view.table_id +@pytest.mark.django_db +def test_before_dispatch_updates_authorized_agent_last_active(data_fixture): + user = data_fixture.create_user() + workspace = data_fixture.create_workspace(user=user) + agent = Agent.objects.create(workspace=workspace, name="Reader") + integration = data_fixture.create_local_baserow_integration( + authorized_agent=agent, + application=data_fixture.create_builder_application(workspace=workspace), + ) + service = data_fixture.create_local_baserow_list_rows_service( + integration=integration + ) + + before = timezone.now() + service.get_type().before_dispatch(service, FakeDispatchContext()) + agent.refresh_from_db() + + assert agent.last_active is not None + assert agent.last_active >= before + + +@pytest.mark.django_db +def test_before_dispatch_tracks_an_authorized_user(data_fixture): + user = data_fixture.create_user() + integration = data_fixture.create_local_baserow_integration( + application=data_fixture.create_builder_application(user=user), user=user + ) + service = data_fixture.create_local_baserow_list_rows_service( + integration=integration + ) + + with patch.object(UserSubjectType, "track_usage") as track_usage: + service.get_type().before_dispatch(service, FakeDispatchContext()) + + track_usage.assert_called_once_with(user) + + @pytest.mark.django_db def test_export_import_local_baserow_list_rows_service(data_fixture): user = data_fixture.create_user() diff --git a/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_upsert_row_service_type.py b/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_upsert_row_service_type.py index a8386152ac..70ccef5cb3 100644 --- a/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_upsert_row_service_type.py +++ b/backend/tests/baserow/contrib/integrations/local_baserow/service_types/test_upsert_row_service_type.py @@ -20,10 +20,12 @@ from baserow.contrib.integrations.local_baserow.models import ( from baserow.contrib.integrations.local_baserow.service_types import ( LocalBaserowUpsertRowServiceType, ) +from baserow.core.action.models import Action from baserow.core.formula import BaserowFormulaObject from baserow.core.formula.field import BASEROW_FORMULA_VERSION_INITIAL from baserow.core.formula.types import BASEROW_FORMULA_MODE_SIMPLE from baserow.core.handler import CoreHandler +from baserow.core.models import Agent from baserow.core.registries import ImportExportConfig from baserow.core.services.exceptions import ( InvalidContextContentDispatchException, @@ -36,12 +38,18 @@ from baserow.test_utils.pytest_conftest import FakeDispatchContext @pytest.mark.django_db -def test_local_baserow_create_rows_service_dispatch_data(data_fixture): +def test_local_baserow_create_rows_service_dispatch_data( + data_fixture, django_capture_on_commit_callbacks +): user = data_fixture.create_user() page = data_fixture.create_builder_page(user=user) integration = data_fixture.create_local_baserow_integration( application=page.builder, user=user ) + agent = Agent.objects.create(workspace=page.builder.workspace, name="Row writer") + integration.authorized_subject_type = "core.Agent" + integration.authorized_subject_id = agent.id + integration.save(update_fields=["authorized_subject_type", "authorized_subject_id"]) database = data_fixture.create_database_application( workspace=page.builder.workspace ) @@ -68,9 +76,14 @@ def test_local_baserow_create_rows_service_dispatch_data(data_fixture): dispatch_context = FakeDispatchContext(context=formula_context) dispatch_values = service_type.resolve_service_formulas(service, dispatch_context) - dispatch_data = service_type.dispatch_data( - service, dispatch_values, dispatch_context - ) + with ( + patch("baserow.ws.registries.PageType.broadcast"), + patch("baserow.ws.registries.PageType.broadcast_many"), + django_capture_on_commit_callbacks(execute=True), + ): + dispatch_data = service_type.dispatch_data( + service, dispatch_values, dispatch_context + ) assert [getattr(row, ingredient.db_column) for row in dispatch_data["data"]] == [ "Bread", @@ -81,6 +94,7 @@ def test_local_baserow_create_rows_service_dispatch_data(data_fixture): assert dispatch_result.data["results"][0]["Ingredient"] == "Bread" assert dispatch_result.data["results"][1]["Ingredient"] == "Butter" + assert not Action.objects.filter(type="create_rows").exists() @pytest.mark.django_db @@ -646,13 +660,14 @@ def test_local_baserow_update_rows_service_dispatch_data_rejects_duplicate_ids( @pytest.mark.django_db -def test_local_baserow_upsert_row_service_dispatch_data_without_row_id( +def test_local_baserow_upsert_row_service_dispatch_data_with_published_agent( data_fixture, ): user = data_fixture.create_user() page = data_fixture.create_builder_page(user=user) + agent = Agent.objects.create(workspace=page.builder.workspace, name="Row writer") integration = data_fixture.create_local_baserow_integration( - application=page.builder, user=user + application=page.builder, user=user, authorized_agent=agent ) database = data_fixture.create_database_application( workspace=page.builder.workspace @@ -671,6 +686,10 @@ def test_local_baserow_upsert_row_service_dispatch_data_without_row_id( integration=integration, table=table, ) + page.builder.workspace = None + page.builder.save(update_fields=["workspace"]) + service.refresh_from_db() + assert service.integration.application.workspace is None service_type = service.get_type() service.field_mappings.create(field=ingredient, value='get("page_parameter.id")') @@ -678,9 +697,10 @@ def test_local_baserow_upsert_row_service_dispatch_data_without_row_id( dispatch_context = FakeDispatchContext(context=formula_context) dispatch_values = service_type.resolve_service_formulas(service, dispatch_context) - dispatch_data = service_type.dispatch_data( - service, dispatch_values, dispatch_context - ) + with override_settings(PERMISSION_MANAGERS=["write_field_values", "basic"]): + dispatch_data = service_type.dispatch_data( + service, dispatch_values, dispatch_context + ) assert getattr(dispatch_data["data"], ingredient.db_column) == str( formula_context["page_parameter"]["id"] diff --git a/backend/tests/baserow/contrib/integrations/local_baserow/test_integration_types.py b/backend/tests/baserow/contrib/integrations/local_baserow/test_integration_types.py index 217074970d..8c19b08ad0 100644 --- a/backend/tests/baserow/contrib/integrations/local_baserow/test_integration_types.py +++ b/backend/tests/baserow/contrib/integrations/local_baserow/test_integration_types.py @@ -3,14 +3,17 @@ from django.test.utils import CaptureQueriesContext from django.urls import reverse import pytest +from rest_framework import serializers from rest_framework.status import HTTP_200_OK from tqdm import tqdm from baserow.contrib.integrations.local_baserow.integration_types import ( LocalBaserowIntegrationType, ) +from baserow.core.cache import local_cache from baserow.core.integrations.registries import integration_type_registry from baserow.core.integrations.service import IntegrationService +from baserow.core.models import Agent @pytest.mark.django_db @@ -24,7 +27,104 @@ def test_create_local_baserow_integration_with_user(data_fixture): user, integration_type, application=application ) - assert integration.authorized_user.id == user.id + assert integration.authorized_subject == user + assert integration.authorized_subject_type == "auth.User" + assert integration.authorized_subject_id == user.id + + +@pytest.mark.django_db +def test_authorized_subject_is_locally_cached(data_fixture): + user = data_fixture.create_user() + application = data_fixture.create_builder_application(user=user) + integration = data_fixture.create_local_baserow_integration( + application=application, user=user + ) + + with local_cache.context(), CaptureQueriesContext(connection) as queries: + assert integration.authorized_subject == user + assert integration.authorized_subject == user + + assert len(queries) == 1 + + +@pytest.mark.django_db +def test_update_local_baserow_integration_authorizes_current_user_only(data_fixture): + user = data_fixture.create_user() + other_user = data_fixture.create_user() + application = data_fixture.create_builder_application(user=user) + agent = Agent.objects.create( + workspace=application.workspace, name="Writer", role_uid="ADMIN" + ) + integration = data_fixture.create_local_baserow_integration( + application=application, authorized_agent=agent + ) + + updated_integration = ( + IntegrationService() + .update_integration( + user, + integration, + authorized_subject_type="auth.User", + authorized_subject_id=user.id, + ) + .integration + ) + + assert updated_integration.authorized_subject == user + + with pytest.raises(serializers.ValidationError): + IntegrationService().update_integration( + user, + updated_integration, + authorized_subject_type="auth.User", + authorized_subject_id=other_user.id, + ) + + +@pytest.mark.django_db +def test_update_local_baserow_integration_keeps_existing_authorization(data_fixture): + user = data_fixture.create_user() + application = data_fixture.create_builder_application(user=user) + agent = Agent.objects.create( + workspace=application.workspace, name="Writer", role_uid="ADMIN" + ) + integration = data_fixture.create_local_baserow_integration( + application=application, authorized_agent=agent + ) + + updated_integration = ( + IntegrationService() + .update_integration(user, integration, name="Renamed integration") + .integration + ) + + assert updated_integration.name == "Renamed integration" + assert updated_integration.authorized_subject == agent + + +@pytest.mark.django_db +def test_import_legacy_authorized_user_reauthorizes_the_importing_user(data_fixture): + importing_user = data_fixture.create_user() + application = data_fixture.create_builder_application(user=importing_user) + integration_type = integration_type_registry.get("local_baserow") + + imported = integration_type.import_serialized( + application, + { + "id": 1, + "name": "Legacy local Baserow", + "order": "1.00000000000000000000", + "type": "local_baserow", + "authorized_user": "former-user@example.com", + }, + {"import_workspace_id": application.workspace_id}, + ) + integration_type.after_import(importing_user, imported) + imported.refresh_from_db() + + assert imported.authorized_subject == importing_user + assert imported.authorized_subject_type == "auth.User" + assert imported.authorized_subject_id == importing_user.id @pytest.mark.django_db @@ -37,6 +137,25 @@ def test_get_local_baserow_databases_no_databases(data_fixture): assert len(databases) == 0 +@pytest.mark.django_db +def test_get_local_baserow_databases_with_agent(data_fixture): + user = data_fixture.create_user() + workspace = data_fixture.create_workspace(user=user) + agent = Agent.objects.create(workspace=workspace, name="Reader", role_uid="ADMIN") + builder = data_fixture.create_builder_application(workspace=workspace) + integration = data_fixture.create_local_baserow_integration( + authorized_user=user, + authorized_agent=agent, + application=builder, + ) + database = data_fixture.create_database_application(workspace=workspace) + data_fixture.create_database_table(database=database) + + databases = LocalBaserowIntegrationType.get_local_baserow_databases(integration) + + assert [item.id for item in databases] == [database.id] + + @pytest.mark.django_db def test_get_local_baserow_databases(data_fixture): user = data_fixture.create_user() @@ -90,7 +209,7 @@ def test_get_local_baserow_databases_number_of_queries( database = data_fixture.create_database_application(user=user, workspace=workspace) table = data_fixture.create_database_table(database=database) - with CaptureQueriesContext(connection) as queries: + with local_cache.context(), CaptureQueriesContext(connection) as queries: LocalBaserowIntegrationType.get_local_baserow_databases(integration) data_fixture.create_database_table(database=database) @@ -99,7 +218,7 @@ def test_get_local_baserow_databases_number_of_queries( ) data_fixture.create_database_table(database=database_2) - with CaptureQueriesContext(connection) as queries_2: + with local_cache.context(), CaptureQueriesContext(connection) as queries_2: LocalBaserowIntegrationType.get_local_baserow_databases(integration) assert len(queries.captured_queries) == len(queries_2.captured_queries) @@ -265,13 +384,14 @@ def test_after_import(data_fixture): user, integration_type, application=application ) - integration.authorized_user = None + integration.authorized_subject_type = None + integration.authorized_subject_id = None integration.save() - assert integration.authorized_user is None - integration.get_type().after_import(user, integration) integration.refresh_from_db() - assert integration.authorized_user == user + assert integration.authorized_subject == user + assert integration.authorized_subject_type == "auth.User" + assert integration.authorized_subject_id == user.id diff --git a/backend/tests/baserow/contrib/integrations/local_baserow/test_migrations.py b/backend/tests/baserow/contrib/integrations/local_baserow/test_migrations.py index ba6279a6aa..31b7fb61b7 100644 --- a/backend/tests/baserow/contrib/integrations/local_baserow/test_migrations.py +++ b/backend/tests/baserow/contrib/integrations/local_baserow/test_migrations.py @@ -431,3 +431,48 @@ def test_0034_migrate_local_baserow_filter_value_mode_forwards( assert first_raw_filter.value["mode"] == "raw" assert last_raw_filter.value["mode"] == "raw" assert formula_filter.value["mode"] == "simple" + + +@pytest.mark.once_per_day_in_ci +def test_0039_reuses_authorized_user_column_for_typed_subjects(migrator): + migrate_from = [ + ("core", "0121_agent"), + ("integrations", "0038_smtpintegration_use_ssl"), + ] + migrate_to = [("integrations", "0039_localbaserowintegration_authorized_agent")] + + old_state = migrator.migrate(migrate_from) + ContentType = old_state.apps.get_model("contenttypes", "ContentType") + User = old_state.apps.get_model("core", "User") + Workspace = old_state.apps.get_model("core", "Workspace") + Application = old_state.apps.get_model("core", "Application") + LocalBaserowIntegration = old_state.apps.get_model( + "integrations", "LocalBaserowIntegration" + ) + + user = User.objects.create(username="legacy-user", email="legacy@example.com") + workspace = Workspace.objects.create(name="Workspace") + application = Application.objects.create( + name="Application", + order=1, + workspace=workspace, + content_type=ContentType.objects.get_for_model(Application), + ) + integration = LocalBaserowIntegration.objects.create( + application=application, + content_type=ContentType.objects.get_for_model(LocalBaserowIntegration), + authorized_user=user, + ) + + new_state = migrator.migrate(migrate_to) + LocalBaserowIntegration = new_state.apps.get_model( + "integrations", "LocalBaserowIntegration" + ) + integration = LocalBaserowIntegration.objects.get(id=integration.id) + + assert integration.authorized_subject_type == "auth.User" + assert integration.authorized_subject_id == user.id + assert ( + LocalBaserowIntegration._meta.get_field("authorized_subject_id").column + == "authorized_user_id" + ) diff --git a/backend/tests/baserow/contrib/integrations/local_baserow/test_utils.py b/backend/tests/baserow/contrib/integrations/local_baserow/test_utils.py index aaf39f023d..d015fa6e08 100644 --- a/backend/tests/baserow/contrib/integrations/local_baserow/test_utils.py +++ b/backend/tests/baserow/contrib/integrations/local_baserow/test_utils.py @@ -36,6 +36,7 @@ from baserow.core.formula.validator import ( ensure_integer, ensure_string, ) +from baserow.core.models import Agent from baserow.core.services.exceptions import ( ServiceImproperlyConfiguredDispatchException, ) @@ -278,6 +279,26 @@ def test_prepare_file_for_db_with_service_file(data_fixture): ] +@pytest.mark.django_db +def test_prepare_file_for_db_with_agent_creates_an_anonymous_user_file(data_fixture): + user = data_fixture.create_user() + agent = Agent.objects.create( + workspace=data_fixture.create_workspace(user=user), name="File writer" + ) + service_file = ServiceFile( + name="people.csv", + file=SimpleUploadedFile( + name="people.csv", + content=b"Name\nAda\n", + content_type="text/csv", + ), + ) + + file_name = prepare_files_for_db(service_file, agent)[0]["name"] + + assert UserFileHandler().get_user_file_by_name(file_name).uploaded_by is None + + @pytest.mark.django_db def test_prepare_file_for_db_with_uploaded_file_named_like_user_file(data_fixture): user = data_fixture.create_user() diff --git a/backend/tests/baserow/core/agents/test_agent_handler.py b/backend/tests/baserow/core/agents/test_agent_handler.py new file mode 100644 index 0000000000..6f9fa18fb6 --- /dev/null +++ b/backend/tests/baserow/core/agents/test_agent_handler.py @@ -0,0 +1,62 @@ +from datetime import datetime, timezone + +from django.core.cache import cache + +import pytest +from freezegun import freeze_time + +from baserow.core.agents.handler import ( + AGENT_LAST_ACTIVE_CACHE_KEY, + AGENT_LAST_ACTIVE_CACHE_TTL_SECONDS, + AgentHandler, +) +from baserow.core.cache import global_cache +from baserow.core.models import Agent + + +@pytest.mark.django_db +def test_update_last_active(data_fixture): + cache.clear() + agent = Agent.objects.create( + workspace=data_fixture.create_workspace(), + name="Writer", + ) + + updated_agent = AgentHandler().update_last_active(agent) + + assert updated_agent is agent + assert agent.last_active is not None + last_active = agent.last_active + agent.refresh_from_db() + assert agent.last_active == last_active + + +@pytest.mark.django_db +def test_update_last_active_is_throttled_until_cache_expires(data_fixture): + agent = Agent.objects.create( + workspace=data_fixture.create_workspace(), + name="Writer", + ) + cache.clear() + + first_activity = datetime(2026, 1, 1, 12, tzinfo=timezone.utc) + with freeze_time(first_activity): + AgentHandler().update_last_active(agent) + + with freeze_time("2026-01-01 12:00:59"): + AgentHandler().update_last_active(agent) + + agent.refresh_from_db() + assert agent.last_active == first_activity + + global_cache.invalidate( + AGENT_LAST_ACTIVE_CACHE_KEY.format(agent_id=agent.id), + ) + + second_activity = datetime(2026, 1, 1, 12, 1, tzinfo=timezone.utc) + with freeze_time(second_activity): + AgentHandler().update_last_active(agent) + + agent.refresh_from_db() + assert agent.last_active == second_activity + assert AGENT_LAST_ACTIVE_CACHE_TTL_SECONDS == 60 diff --git a/backend/tests/baserow/core/agents/test_agent_subject.py b/backend/tests/baserow/core/agents/test_agent_subject.py index 0c727feef3..75ee07eca3 100644 --- a/backend/tests/baserow/core/agents/test_agent_subject.py +++ b/backend/tests/baserow/core/agents/test_agent_subject.py @@ -21,6 +21,7 @@ def test_agent_subject_is_workspace_scoped_and_contains_no_users(data_fixture): subject_type = subject_type_registry.get_by_model(agent) assert isinstance(subject_type, AgentSubjectType) + assert not subject_type.is_interactive_user assert subject_type.is_in_workspace(agent, workspace) assert not subject_type.is_in_workspace(agent, other_workspace) assert subject_type.get_users_included_in_subject(agent) == [] diff --git a/backend/tests/baserow/core/integrations/test_integration_handler.py b/backend/tests/baserow/core/integrations/test_integration_handler.py index bfdf803481..a5222b934c 100644 --- a/backend/tests/baserow/core/integrations/test_integration_handler.py +++ b/backend/tests/baserow/core/integrations/test_integration_handler.py @@ -111,10 +111,13 @@ def test_update_integration(data_fixture): integration_type = integration_type_registry.get("local_baserow") integration_updated = IntegrationHandler().update_integration( - integration_type, integration, authorized_user=user2 + integration_type, + integration, + authorized_subject_type="auth.User", + authorized_subject_id=user2.id, ) - assert integration_updated.authorized_user.id == user2.id + assert integration_updated.authorized_subject == user2 @pytest.mark.django_db diff --git a/backend/tests/baserow/core/service/test_service_type.py b/backend/tests/baserow/core/service/test_service_type.py index d3b9a0bd03..d0d245eb3d 100644 --- a/backend/tests/baserow/core/service/test_service_type.py +++ b/backend/tests/baserow/core/service/test_service_type.py @@ -282,6 +282,24 @@ def test_dispatch_returns_sample_data_when_simulated(): assert result.data == {"foo": "bar"} +@pytest.mark.django_db +def test_dispatch_calls_before_dispatch_hook(): + service_type_cls = ServiceType + service_type_cls.model_class = MagicMock() + service_type = service_type_cls() + service_type.resolve_service_formulas = MagicMock(return_value={}) + service_type.dispatch_data = MagicMock() + service_type.dispatch_transform = MagicMock() + service_type.before_dispatch = MagicMock() + + service = MagicMock() + dispatch_context = FakeDispatchContext(use_sample_data=False) + + service_type.dispatch(service, dispatch_context) + + service_type.before_dispatch.assert_called_once_with(service, dispatch_context) + + @pytest.mark.django_db def test_dispatch_even_if_simulated_when_updated(): """ diff --git a/backend/tests/baserow/core/test_posthog.py b/backend/tests/baserow/core/test_posthog.py index 882fd2fb1b..5207ebb6b8 100644 --- a/backend/tests/baserow/core/test_posthog.py +++ b/backend/tests/baserow/core/test_posthog.py @@ -6,6 +6,7 @@ import pytest from baserow.core.action.registries import ActionType from baserow.core.action.signals import ActionCommandType +from baserow.core.models import Agent from baserow.core.posthog import ( capture_event_action_done, capture_user_event, @@ -123,3 +124,25 @@ def test_capture_event_action_done_skips_opted_out_types( ) mock_capture_event.assert_not_called() + + +@pytest.mark.django_db +@patch("baserow.core.posthog.capture_user_event") +def test_capture_event_action_done_ignores_non_interactive_subject( + mock_capture_event, data_fixture +): + workspace = data_fixture.create_workspace() + agent = Agent.objects.create(workspace=workspace, name="Writer") + + capture_event_action_done( + sender=None, + user=agent, + action_type=TestActionType(), + action_params={"must_be_kept": "yes"}, + action_timestamp=None, + action_command_type=ActionCommandType.DO, + workspace=workspace, + session=None, + ) + + mock_capture_event.assert_not_called() diff --git a/backend/tests/baserow/core/user/test_user_subject_type.py b/backend/tests/baserow/core/user/test_user_subject_type.py index 81faabbce6..608bd7b338 100644 --- a/backend/tests/baserow/core/user/test_user_subject_type.py +++ b/backend/tests/baserow/core/user/test_user_subject_type.py @@ -21,6 +21,7 @@ def test_user_subject_type_is_in_workspace(data_fixture): fake_user = FakeUser(9999999) + assert UserSubjectType().is_interactive_user assert UserSubjectType().is_in_workspace(user_not_in_workspace, workspace) is False assert UserSubjectType().is_in_workspace(user_in_workspace, workspace) is True assert UserSubjectType().is_in_workspace(fake_user, workspace) is False diff --git a/changelog/entries/unreleased/breaking_change/5781_replaces_the_audit_log_users_endpoint_with_the_new_actors_en.json b/changelog/entries/unreleased/breaking_change/5781_replaces_the_audit_log_users_endpoint_with_the_new_actors_en.json new file mode 100644 index 0000000000..28e7cdf23e --- /dev/null +++ b/changelog/entries/unreleased/breaking_change/5781_replaces_the_audit_log_users_endpoint_with_the_new_actors_en.json @@ -0,0 +1,9 @@ +{ + "type": "breaking_change", + "message": "Replaces the audit log users endpoint with the new actors endpoint", + "issue_origin": "github", + "issue_number": 5781, + "domain": "core", + "bullet_points": [], + "created_at": "2026-10-06" +} diff --git a/enterprise/backend/src/baserow_enterprise/api/admin/audit_log/urls.py b/enterprise/backend/src/baserow_enterprise/api/admin/audit_log/urls.py index 3144a96724..35f3944980 100755 --- a/enterprise/backend/src/baserow_enterprise/api/admin/audit_log/urls.py +++ b/enterprise/backend/src/baserow_enterprise/api/admin/audit_log/urls.py @@ -3,7 +3,7 @@ from django.urls import re_path from baserow_enterprise.api.audit_log.views import ( AsyncAuditLogExportView, AuditLogActionTypeFilterView, - AuditLogUserFilterView, + AuditLogActorFilterView, AuditLogView, ) @@ -11,7 +11,7 @@ app_name = "baserow_enterprise.api.audit_log" urlpatterns = [ re_path(r"^$", AuditLogView.as_view(), name="list"), - re_path(r"users/$", AuditLogUserFilterView.as_view(), name="users"), + re_path(r"actors/$", AuditLogActorFilterView.as_view(), name="actors"), re_path( r"action-types/$", AuditLogActionTypeFilterView.as_view(), name="action_types" ), diff --git a/enterprise/backend/src/baserow_enterprise/api/audit_log/serializers.py b/enterprise/backend/src/baserow_enterprise/api/audit_log/serializers.py index e73f93f0fd..4d6687d703 100644 --- a/enterprise/backend/src/baserow_enterprise/api/audit_log/serializers.py +++ b/enterprise/backend/src/baserow_enterprise/api/audit_log/serializers.py @@ -1,4 +1,3 @@ -from django.contrib.auth import get_user_model from django.utils import translation from django.utils.functional import lazy @@ -8,15 +7,10 @@ from rest_framework import serializers from baserow.core.action.registries import action_type_registry from baserow.core.jobs.registries import job_type_registry +from baserow.core.registries import subject_type_registry from baserow_enterprise.audit_log.job_types import AuditLogExportJobType from baserow_enterprise.audit_log.models import AuditLogEntry -User = get_user_model() - - -def render_user(user_id, user_email): - return f"{user_email} ({user_id})" if user_id else "" - def render_workspace(workspace_id, workspace_name): return f"{workspace_name} ({workspace_id})" if workspace_id else "" @@ -26,10 +20,22 @@ def render_action_type(action_type): return action_type_registry.get(action_type).get_short_description() +class AuditLogActorSerializer(serializers.Serializer): + id = serializers.IntegerField(allow_null=True) + type = serializers.CharField(allow_null=True) + name = serializers.CharField(allow_null=True) + + class AuditLogQueryParamsSerializer(serializers.Serializer): page = serializers.IntegerField(required=False, default=1) sorts = serializers.CharField(required=False, default=None) user_id = serializers.IntegerField(min_value=1, required=False, default=None) + actor_id = serializers.IntegerField(min_value=1, required=False, default=None) + actor_type = serializers.ChoiceField( + choices=lazy(subject_type_registry.get_types, list)(), + required=False, + default=None, + ) workspace_id = serializers.IntegerField(min_value=1, required=False, default=None) action_type = serializers.ChoiceField( choices=lazy(action_type_registry.get_types, list)(), @@ -39,13 +45,33 @@ class AuditLogQueryParamsSerializer(serializers.Serializer): from_timestamp = serializers.DateTimeField(required=False, default=None) to_timestamp = serializers.DateTimeField(required=False, default=None) + def validate(self, attrs): + """Require an actor type whenever filtering by a polymorphic actor ID.""" + + if attrs.get("actor_id") is not None and attrs.get("actor_type") is None: + raise serializers.ValidationError( + {"actor_type": "This field is required when actor_id is provided."} + ) + return attrs + class AuditLogWorkspaceFilterQueryParamsSerializer(serializers.Serializer): workspace_id = serializers.IntegerField(min_value=1, required=False, default=None) +class AuditLogActorFilterQueryParamsSerializer( + AuditLogWorkspaceFilterQueryParamsSerializer +): + page = serializers.IntegerField(min_value=1, required=False, default=1) + size = serializers.IntegerField(min_value=1, required=False) + search = serializers.CharField( + required=False, allow_blank=True, allow_null=True, default=None + ) + + class AuditLogSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() + actor = serializers.SerializerMethodField() workspace = serializers.SerializerMethodField() type = serializers.SerializerMethodField() description = serializers.SerializerMethodField() @@ -53,7 +79,15 @@ class AuditLogSerializer(serializers.ModelSerializer): @extend_schema_field(OpenApiTypes.STR) def get_user(self, instance): - return render_user(instance.user_id, instance.user_email) + return instance.actor_display + + @extend_schema_field(AuditLogActorSerializer) + def get_actor(self, instance): + return { + "id": instance.actor_id, + "type": instance.actor_type, + "name": instance.actor_name, + } @extend_schema_field(OpenApiTypes.STR) def get_type(self, instance): @@ -73,6 +107,7 @@ class AuditLogSerializer(serializers.ModelSerializer): "id", "action_type", "user", + "actor", "workspace", "type", "description", @@ -82,12 +117,14 @@ class AuditLogSerializer(serializers.ModelSerializer): read_only_fields = fields -class AuditLogUserSerializer(serializers.ModelSerializer): - value = serializers.CharField(source="email") +class AuditLogActorFilterSerializer(serializers.Serializer): + id = serializers.SerializerMethodField() + actor_id = serializers.IntegerField(source="subject_id") + actor_type = serializers.CharField(source="subject_type") + value = serializers.CharField(source="subject_label") - class Meta: - model = User - fields = ("id", "value") + def get_id(self, instance): + return f"{instance['subject_type']}:{instance['subject_id']}" class AuditLogActionTypeSerializer(serializers.Serializer): diff --git a/enterprise/backend/src/baserow_enterprise/api/audit_log/urls.py b/enterprise/backend/src/baserow_enterprise/api/audit_log/urls.py index a3a85d1f8b..8b91b98707 100755 --- a/enterprise/backend/src/baserow_enterprise/api/audit_log/urls.py +++ b/enterprise/backend/src/baserow_enterprise/api/audit_log/urls.py @@ -3,7 +3,7 @@ from django.urls import re_path from .views import ( AsyncAuditLogExportView, AuditLogActionTypeFilterView, - AuditLogUserFilterView, + AuditLogActorFilterView, AuditLogView, ) @@ -11,7 +11,7 @@ app_name = "baserow_enterprise.api.audit_log" urlpatterns = [ re_path(r"^$", AuditLogView.as_view(), name="list"), - re_path(r"users/$", AuditLogUserFilterView.as_view(), name="users"), + re_path(r"actors/$", AuditLogActorFilterView.as_view(), name="actors"), re_path( r"action-types/$", AuditLogActionTypeFilterView.as_view(), name="action_types" ), diff --git a/enterprise/backend/src/baserow_enterprise/api/audit_log/views.py b/enterprise/backend/src/baserow_enterprise/api/audit_log/views.py index a127ef45b1..232804886a 100755 --- a/enterprise/backend/src/baserow_enterprise/api/audit_log/views.py +++ b/enterprise/backend/src/baserow_enterprise/api/audit_log/views.py @@ -17,14 +17,20 @@ from baserow.api.decorators import ( from baserow.api.errors import ERROR_GROUP_DOES_NOT_EXIST from baserow.api.jobs.errors import ERROR_MAX_JOB_COUNT_EXCEEDED from baserow.api.jobs.serializers import JobSerializer -from baserow.api.pagination import PageNumberPaginationWithApproximateCount +from baserow.api.pagination import ( + PageNumberPagination, + PageNumberPaginationWithApproximateCount, +) from baserow.api.schemas import CLIENT_SESSION_ID_SCHEMA_PARAMETER, get_error_schema from baserow.core.actions import DeleteWorkspaceActionType, OrderWorkspacesActionType +from baserow.core.agents.subjects import AgentSubjectType from baserow.core.exceptions import WorkspaceDoesNotExist +from baserow.core.handler import CoreHandler from baserow.core.jobs.exceptions import MaxJobCountExceeded from baserow.core.jobs.handler import JobHandler from baserow.core.jobs.registries import job_type_registry -from baserow.core.models import User +from baserow.core.subject_options import SubjectOptionsHandler +from baserow.core.subjects import UserSubjectType from baserow_enterprise.audit_log.job_types import AuditLogExportJobType from baserow_enterprise.audit_log.models import AuditLogEntry from baserow_enterprise.audit_log.utils import ( @@ -33,11 +39,12 @@ from baserow_enterprise.audit_log.utils import ( from .serializers import ( AuditLogActionTypeSerializer, + AuditLogActorFilterQueryParamsSerializer, + AuditLogActorFilterSerializer, AuditLogExportJobRequestSerializer, AuditLogExportJobResponseSerializer, AuditLogQueryParamsSerializer, AuditLogSerializer, - AuditLogUserSerializer, AuditLogWorkspaceFilterQueryParamsSerializer, serialize_filtered_action_types, ) @@ -50,7 +57,9 @@ class AuditLogView(APIListingView): # Every filter here is backed by an index leading with that column, so that a # filtered page stays a seek instead of a scan of the whole table. filters_field_mapping = { - "user_id": "user_id", + "user_id": "actor_id", + "actor_id": "actor_id", + "actor_type": "actor_type", "workspace_id": "workspace_id", "action_type": "action_type", "from_timestamp": "action_timestamp__gte", @@ -63,7 +72,10 @@ class AuditLogView(APIListingView): default_order_by = "-action_timestamp" def get_queryset(self, request): - return AuditLogEntry.objects.all() + queryset = AuditLogEntry.objects.all() + if request.GET.get("user_id"): + queryset = queryset.filter(actor_type=UserSubjectType.type) + return queryset def get_serializer(self, request, *args, **kwargs): return super().get_serializer( @@ -89,6 +101,18 @@ class AuditLogView(APIListingView): type=OpenApiTypes.INT, description="Filter the audit log entries by user id.", ), + OpenApiParameter( + name="actor_id", + location=OpenApiParameter.QUERY, + type=OpenApiTypes.INT, + description="Filter the audit log entries by actor id.", + ), + OpenApiParameter( + name="actor_type", + location=OpenApiParameter.QUERY, + type=OpenApiTypes.STR, + description="Filter the audit log entries by actor type.", + ), OpenApiParameter( name="workspace_id", location=OpenApiParameter.QUERY, @@ -197,48 +221,51 @@ class AuditLogActionTypeFilterView(APIView): ) -class AuditLogUserFilterView(APIListingView): +class AuditLogActorFilterView(APIView): permission_classes = (IsAuthenticated,) - serializer_class = AuditLogUserSerializer - filters_field_mapping = {"workspace_id": "workspaceuser__workspace_id"} - search_fields = ["email"] - default_order_by = "email" + serializer_class = AuditLogActorFilterSerializer - def get_queryset(self, request): - return User.objects.all() + def paginate_queryset(self, queryset, request): + paginator = PageNumberPagination(limit_page_size=100) + page = paginator.paginate_queryset(queryset, request, view=self) + return page, paginator @extend_schema( tags=["Audit log"], - operation_id="audit_log_users", + operation_id="audit_log_actors", description=( - "List all users that have performed an action in the audit log." - "\n\nThis is a **enterprise** feature." - ), - **APIListingView.get_extend_schema_parameters( - "users", - serializer_class, - search_fields, - {}, - extra_parameters=[ - OpenApiParameter( - name="workspace_id", - location=OpenApiParameter.QUERY, - type=OpenApiTypes.INT, - description=("Return users belonging to the given workspace_id."), - ), - ], + "List users and agents available as audit log actor filters." + "\n\nThis is an **enterprise** feature." ), + parameters=[ + OpenApiParameter( + name="workspace_id", + location=OpenApiParameter.QUERY, + type=OpenApiTypes.INT, + description="Only return actors belonging to the workspace.", + ), + ], + responses={200: serializer_class(many=True)}, ) - @map_exceptions( - { - WorkspaceDoesNotExist: ERROR_GROUP_DOES_NOT_EXIST, - } - ) - @validate_query_parameters(AuditLogWorkspaceFilterQueryParamsSerializer) + @map_exceptions({WorkspaceDoesNotExist: ERROR_GROUP_DOES_NOT_EXIST}) + @validate_query_parameters(AuditLogActorFilterQueryParamsSerializer) def get(self, request, query_params): - workspace_id = query_params.get("workspace_id", None) + """Return searchable users and agents as audit-log actor options.""" + + workspace_id = query_params.get("workspace_id") check_for_license_and_permissions_or_raise(request.user, workspace_id) - return super().get(request) + workspace = None + if workspace_id is not None: + workspace = CoreHandler().get_workspace(workspace_id) + queryset = SubjectOptionsHandler.get_historical_options( + workspace=workspace, + search=query_params.get("search") or "", + subject_types={UserSubjectType.type, AgentSubjectType.type}, + ) + page, paginator = self.paginate_queryset(queryset, request) + return paginator.get_paginated_response( + self.serializer_class(page, many=True).data + ) class AsyncAuditLogExportView(APIView): diff --git a/enterprise/backend/src/baserow_enterprise/api/field_permissions/serializers.py b/enterprise/backend/src/baserow_enterprise/api/field_permissions/serializers.py index d535309bf9..b7a26ee26c 100644 --- a/enterprise/backend/src/baserow_enterprise/api/field_permissions/serializers.py +++ b/enterprise/backend/src/baserow_enterprise/api/field_permissions/serializers.py @@ -60,8 +60,10 @@ class FieldPermissionSubjectOptionResponseSerializer(serializers.Serializer): read_only=True, choices=[UserSubjectType.type, TeamSubjectType.type, AgentSubjectType.type], ) - name = serializers.CharField(read_only=True) - email = serializers.EmailField(read_only=True, allow_null=True) + name = serializers.CharField(source="subject_name", read_only=True) + email = serializers.EmailField( + source="subject_email", read_only=True, allow_null=True + ) subject_count = serializers.IntegerField(read_only=True, allow_null=True) diff --git a/enterprise/backend/src/baserow_enterprise/audit_log/handler.py b/enterprise/backend/src/baserow_enterprise/audit_log/handler.py index b521370f50..3b3af87d8d 100755 --- a/enterprise/backend/src/baserow_enterprise/audit_log/handler.py +++ b/enterprise/backend/src/baserow_enterprise/audit_log/handler.py @@ -1,12 +1,13 @@ from datetime import datetime from typing import Any, Dict, Optional, Type -from django.contrib.auth.models import AbstractUser - from baserow.api.sessions import get_user_remote_addr_ip from baserow.core.action.registries import ActionType from baserow.core.action.signals import ActionCommandType from baserow.core.models import Workspace +from baserow.core.registries import subject_type_registry +from baserow.core.subjects import UserSubjectType +from baserow.core.types import Actor from .models import AuditLogEntry @@ -15,7 +16,7 @@ class AuditLogHandler: @classmethod def log_action( cls, - user: AbstractUser, + user: Optional[Actor], action_type: Type[ActionType], action_params: Dict[str, Any], action_timestamp: datetime, @@ -48,11 +49,19 @@ class AuditLogHandler: workspace_id = workspace.id workspace_name = workspace.name + if user is None: + actor_type = UserSubjectType.type + actor_name = None + else: + subject_type = subject_type_registry.get_by_model(user) + actor_type = subject_type.type + actor_name = subject_type.get_label(user) ip_address = get_user_remote_addr_ip(user) return AuditLogEntry.objects.create( - user_id=getattr(user, "id", None), - user_email=getattr(user, "email", None), + actor_id=getattr(user, "id", None), + actor_type=actor_type, + actor_name=actor_name, workspace_id=workspace_id, workspace_name=workspace_name, action_uuid=action_uuid, diff --git a/enterprise/backend/src/baserow_enterprise/audit_log/job_types.py b/enterprise/backend/src/baserow_enterprise/audit_log/job_types.py index 07be8ed23d..063349235d 100755 --- a/enterprise/backend/src/baserow_enterprise/audit_log/job_types.py +++ b/enterprise/backend/src/baserow_enterprise/audit_log/job_types.py @@ -23,6 +23,7 @@ from baserow.contrib.database.export.handler import ( ) from baserow.core.action.registries import action_type_registry from baserow.core.jobs.registries import JobType +from baserow.core.registries import subject_type_registry from baserow.core.storage import get_default_storage from baserow.core.utils import ChildProgressBuilder @@ -31,14 +32,6 @@ from .utils import check_for_license_and_permissions_or_raise AUDIT_LOG_CSV_COLUMN_NAMES = OrderedDict( { - "user_email": { - "field": "user_email", - "descr": _("User Email"), - }, - "user_id": { - "field": "user_id", - "descr": _("User ID"), - }, "workspace_name": { "field": "workspace_name", "descr": _("Group Name"), @@ -63,26 +56,76 @@ AUDIT_LOG_CSV_COLUMN_NAMES = OrderedDict( "field": "ip_address", "descr": _("IP Address"), }, + "actor_type": { + "field": "actor_type", + "descr": _("Actor Type"), + }, + "actor_name": { + "field": "actor_name", + "descr": _("Actor Name"), + }, + "actor_id": { + "field": "actor_id", + "descr": _("Actor ID"), + }, } ) +LEGACY_AUDIT_LOG_CSV_COLUMN_ALIASES = { + "user_email": "actor_name", + "user_id": "actor_id", +} + class CommaSeparatedCsvColumnsField(serializers.CharField): - def validate_values(self, value): + def to_internal_value(self, data): + value = super().to_internal_value(data) items = value.split(",") + valid_column_names = { + *AUDIT_LOG_CSV_COLUMN_NAMES, + *LEGACY_AUDIT_LOG_CSV_COLUMN_ALIASES, + } + for item in items: + if item not in valid_column_names: + raise serializers.ValidationError(f"{item} is not a valid choice.") + + items = [LEGACY_AUDIT_LOG_CSV_COLUMN_ALIASES.get(item, item) for item in items] + if len(set(items)) != len(items): raise serializers.ValidationError("Duplicate items are not allowed.") - if len(items) > 0: - for item in items: - if item not in AUDIT_LOG_CSV_COLUMN_NAMES.keys(): - raise serializers.ValidationError(f"{item} is not a valid choice.") - - if len(items) == len(self.child.choices): + if len(items) == len(AUDIT_LOG_CSV_COLUMN_NAMES): raise serializers.ValidationError("At least one column must be included.") - return value + return ",".join(items) + + +class RemovedFilterUserIdField(serializers.Field): + def to_internal_value(self, data): + raise serializers.ValidationError( + "This filter has been removed. Use filter_actor_id and " + "filter_actor_type instead." + ) + + +class AuditLogExportRequestSerializerMixin: + """Require the type component when filtering by a polymorphic actor ID.""" + + def validate(self, attrs): + attrs = super().validate(attrs) + if ( + attrs.get("filter_actor_id") is not None + and attrs.get("filter_actor_type") is None + ): + raise serializers.ValidationError( + { + "filter_actor_type": ( + "This field is required when filter_actor_id is provided." + ) + } + ) + return attrs class AuditLogExportJobType(JobType): @@ -95,6 +138,8 @@ class AuditLogExportJobType(JobType): "csv_column_separator", "csv_first_row_header", "export_charset", + "filter_actor_id", + "filter_actor_type", "filter_user_id", "filter_workspace_id", "filter_action_type", @@ -128,11 +173,17 @@ class AuditLogExportJobType(JobType): default=True, help_text="Whether or not to generate a header row at the top of the csv file.", ), - "filter_user_id": serializers.IntegerField( + "filter_actor_id": serializers.IntegerField( min_value=0, required=False, - help_text="Optional: The user to filter the audit log by.", + help_text="Optional: The actor to filter the audit log by.", ), + "filter_actor_type": serializers.ChoiceField( + choices=lazy(subject_type_registry.get_types, list)(), + required=False, + help_text="Optional: The actor type to filter the audit log by.", + ), + "filter_user_id": RemovedFilterUserIdField(required=False), "filter_workspace_id": serializers.IntegerField( min_value=0, required=False, @@ -156,13 +207,13 @@ class AuditLogExportJobType(JobType): required=False, help_text=( "Optional: A comma separated list of column names to exclude from the export. " - f"Available options are `{', '.join(AUDIT_LOG_CSV_COLUMN_NAMES.keys())}`." + f"Available options are `{', '.join(AUDIT_LOG_CSV_COLUMN_NAMES.keys())}`. " + "The legacy `user_email` and `user_id` names are accepted as aliases " + "for `actor_name` and `actor_id`." ), ), } - request_serializer_field_overrides = { - **base_serializer_field_overrides, - } + request_serializer_field_overrides = base_serializer_field_overrides serializer_field_overrides = { # Map to the python encoding aliases at the same time by using a # DisplayChoiceField @@ -180,6 +231,16 @@ class AuditLogExportJobType(JobType): ), } + def get_serializer_class(self, *args, **kwargs): + serializer_class = super().get_serializer_class(*args, **kwargs) + if not kwargs.get("request_serializer"): + return serializer_class + return type( + "AuditLogExportRequestSerializer", + (AuditLogExportRequestSerializerMixin, serializer_class), + {}, + ) + def before_delete(self, job): """ Try to delete the data file of a job before deleting the job. @@ -190,7 +251,6 @@ class AuditLogExportJobType(JobType): storage = get_default_storage() storage_location = ExportHandler.export_file_path(job.exported_file_name) - print("before delete ===", storage) try: storage.delete(storage_location) except FileNotFoundError: @@ -244,7 +304,6 @@ class AuditLogExportJobType(JobType): def get_filtered_queryset(self, job): queryset = AuditLogEntry.objects.order_by("-action_timestamp") filters_field_mapping: Dict[str, str] = { - "filter_user_id": "user_id", "filter_workspace_id": "workspace_id", "filter_action_type": "action_type", "filter_from_timestamp": "action_timestamp__gte", @@ -255,6 +314,12 @@ class AuditLogExportJobType(JobType): if (value := getattr(job, field)) is not None: queryset = queryset.filter(**{qs_filter: value}) + if job.filter_actor_type is not None: + queryset = queryset.filter(actor_type=job.filter_actor_type) + + if job.filter_actor_id is not None: + queryset = queryset.filter(actor_id=job.filter_actor_id) + return queryset def run(self, job, progress): diff --git a/enterprise/backend/src/baserow_enterprise/audit_log/models.py b/enterprise/backend/src/baserow_enterprise/audit_log/models.py index 47f767120a..f8755fd4e1 100755 --- a/enterprise/backend/src/baserow_enterprise/audit_log/models.py +++ b/enterprise/backend/src/baserow_enterprise/audit_log/models.py @@ -14,6 +14,7 @@ from baserow.core.action.registries import ( from baserow.core.encoders import JSONEncoderSupportingDataClasses from baserow.core.jobs.models import Job from baserow.core.mixins import CreatedAndUpdatedOnMixin +from baserow.core.subjects import UserSubjectType class IgnoreMissingKeyDict(dict): @@ -31,8 +32,16 @@ class AuditLogEntry(CreatedAndUpdatedOnMixin, models.Model): UNDO = ActionCommandType.REDO.name, _("UNDONE") REDO = ActionCommandType.UNDO.name, _("REDONE") - user_id = models.PositiveIntegerField(null=True) - user_email = models.EmailField(null=True, blank=True) + # Reuse the former user columns so existing entries are immediately available + # through the actor fields and old application versions remain ZDM-compatible. + # This is safe only while actor_type is always used with actor_id (User and Agent + # primary keys can overlap), auth.User remains the database default for writes + # made by an old version, and actor names fit the existing user_email column. + actor_id = models.PositiveIntegerField(db_column="user_id", null=True) + actor_type = models.CharField(max_length=255, db_default=UserSubjectType.type) + actor_name = models.CharField( + db_column="user_email", max_length=254, null=True, blank=True + ) workspace_id = models.PositiveIntegerField(null=True) workspace_name = models.CharField(max_length=165, null=True, blank=True) @@ -58,6 +67,17 @@ class AuditLogEntry(CreatedAndUpdatedOnMixin, models.Model): ip_address = models.GenericIPAddressField(null=True) + @property + def user_id(self): + """Compatibility alias for integrations still reading the former field.""" + return self.actor_id + + @property + def actor_display(self): + if not self.actor_id: + return "" + return f"{self.actor_name} ({self.actor_id})" + @property def type(self): try: @@ -98,14 +118,14 @@ class AuditLogEntry(CreatedAndUpdatedOnMixin, models.Model): # # A single leading equality column is enough to bound a query that combines # several filters: the scan can never be larger than the number of entries - # for that user, workspace or action type. + # for that actor, workspace or action type. indexes = [ models.Index( fields=["-action_timestamp"], name="auditlogentry_ts_idx", ), models.Index( - fields=["user_id", "-action_timestamp"], + fields=["actor_id", "-action_timestamp"], name="auditlogentry_user_ts_idx", ), models.Index( @@ -116,6 +136,10 @@ class AuditLogEntry(CreatedAndUpdatedOnMixin, models.Model): fields=["action_type", "-action_timestamp"], name="auditlogentry_type_ts_idx", ), + models.Index( + fields=["actor_type", "actor_id", "-action_timestamp"], + name="baserow_ent_actor_ts_idx", + ), ] @@ -140,9 +164,17 @@ class AuditLogExportJob(Job): default=True, help_text="Whether or not to generate a header row at the top of the csv file.", ) - filter_user_id = models.PositiveIntegerField( + filter_actor_id = models.PositiveIntegerField( + db_column="filter_user_id", null=True, - help_text="Optional: The user to filter the audit log by.", + help_text="Optional: The actor to filter the audit log by.", + ) + filter_actor_type = models.CharField( + max_length=255, + null=True, + default=None, + db_default=UserSubjectType.type, + help_text="Optional: The actor type to filter the audit log by.", ) filter_workspace_id = models.PositiveIntegerField( null=True, diff --git a/enterprise/backend/src/baserow_enterprise/audit_log/signals.py b/enterprise/backend/src/baserow_enterprise/audit_log/signals.py index 0ee19002d6..2a59111690 100755 --- a/enterprise/backend/src/baserow_enterprise/audit_log/signals.py +++ b/enterprise/backend/src/baserow_enterprise/audit_log/signals.py @@ -1,12 +1,12 @@ from datetime import datetime from typing import Any, Dict, Optional, Type -from django.contrib.auth.models import AbstractUser from django.dispatch import receiver from baserow.core.action.registries import ActionType from baserow.core.action.signals import ActionCommandType, action_done from baserow.core.models import Workspace +from baserow.core.types import Actor from .handler import AuditLogHandler @@ -14,7 +14,7 @@ from .handler import AuditLogHandler @receiver(action_done) def log_action( sender, - user: AbstractUser, + user: Actor, action_type: Type[ActionType], action_params: Dict[str, Any], action_timestamp: datetime, diff --git a/enterprise/backend/src/baserow_enterprise/field_permissions/handler.py b/enterprise/backend/src/baserow_enterprise/field_permissions/handler.py index fa9a833d8b..bc3c133a70 100644 --- a/enterprise/backend/src/baserow_enterprise/field_permissions/handler.py +++ b/enterprise/backend/src/baserow_enterprise/field_permissions/handler.py @@ -5,28 +5,19 @@ from typing import TypedDict from django.contrib.auth.models import AbstractUser from django.contrib.contenttypes.models import ContentType from django.db import transaction -from django.db.models import ( - Case, - CharField, - Count, - F, - IntegerField, - Q, - QuerySet, - Value, - When, -) +from django.db.models import QuerySet from baserow.contrib.database.fields.models import Field from baserow.contrib.database.fields.operations import WriteFieldValuesOperationType from baserow.core.agents.subjects import AgentSubjectType from baserow.core.cache import local_cache from baserow.core.handler import CoreHandler -from baserow.core.models import Agent, Workspace, WorkspaceUser +from baserow.core.models import Agent, Workspace from baserow.core.registries import ( permission_manager_type_registry, subject_type_registry, ) +from baserow.core.subject_options import SubjectOptionsHandler from baserow.core.subjects import UserSubjectType from baserow_enterprise.exceptions import SubjectNotExist, SubjectUnsupported from baserow_enterprise.field_permissions.models import ( @@ -101,52 +92,16 @@ class FieldPermissionsHandler: :return: A queryset of user, agent, and team option dictionaries. """ - search = (search or "").strip() - users = WorkspaceUser.objects.filter( + return SubjectOptionsHandler.get_options( workspace=workspace, - user__is_active=True, - user__profile__to_be_deleted=False, - ).exclude(user_id__in=exclude_user_ids or []) - teams = Team.objects.filter(workspace=workspace).exclude( - id__in=exclude_team_ids or [] - ) - agents = Agent.objects.filter(workspace=workspace).exclude( - id__in=exclude_agent_ids or [] - ) - if search: - users = users.filter( - Q(user__first_name__icontains=search) - | Q(user__username__icontains=search) - | Q(user__email__icontains=search) - ) - teams = teams.filter(name__icontains=search) - agents = agents.filter(name__icontains=search) - - user_options = users.annotate( - subject_id=F("user_id"), - subject_type=Value(UserSubjectType.type, output_field=CharField()), - name=Case( - When(user__first_name="", then=F("user__email")), - default=F("user__first_name"), - output_field=CharField(), - ), - email=F("user__email"), - subject_count=Value(None, output_field=IntegerField()), - ).values("subject_id", "subject_type", "name", "email", "subject_count") - team_options = teams.annotate( - subject_id=F("id"), - subject_type=Value(TeamSubjectType.type, output_field=CharField()), - email=Value(None, output_field=CharField()), - subject_count=Count("subjects"), - ).values("subject_id", "subject_type", "name", "email", "subject_count") - agent_options = agents.annotate( - subject_id=F("id"), - subject_type=Value(AgentSubjectType.type, output_field=CharField()), - email=Value(None, output_field=CharField()), - subject_count=Value(None, output_field=IntegerField()), - ).values("subject_id", "subject_type", "name", "email", "subject_count") - return user_options.union(team_options, agent_options, all=True).order_by( - "name", "subject_type", "subject_id" + search=search, + subject_types=cls.allowed_subject_types, + exclude_ids={ + UserSubjectType.type: exclude_user_ids or [], + TeamSubjectType.type: exclude_team_ids or [], + AgentSubjectType.type: exclude_agent_ids or [], + }, + order_by=("subject_name", "subject_type", "subject_id"), ) @classmethod diff --git a/enterprise/backend/src/baserow_enterprise/integrations/local_baserow/user_source_types.py b/enterprise/backend/src/baserow_enterprise/integrations/local_baserow/user_source_types.py index 220479b18c..c8a3e104f6 100644 --- a/enterprise/backend/src/baserow_enterprise/integrations/local_baserow/user_source_types.py +++ b/enterprise/backend/src/baserow_enterprise/integrations/local_baserow/user_source_types.py @@ -490,7 +490,7 @@ class LocalBaserowUserSourceType(UserSourceType): ) CoreHandler().check_permissions( - integration.authorized_user, + integration.authorized_subject, ReadDatabaseRowOperationType.type, workspace=table.database.workspace, context=table, @@ -709,7 +709,7 @@ class LocalBaserowUserSourceType(UserSourceType): try: # Use the action to keep track on what's going on (user,) = CreateRowsActionType.do( - user=integration.authorized_user, + user=integration.authorized_subject, table=user_source.table, rows_values=[values], model=model, diff --git a/enterprise/backend/src/baserow_enterprise/migrations/0068_auditlogentry_agent.py b/enterprise/backend/src/baserow_enterprise/migrations/0068_auditlogentry_agent.py new file mode 100644 index 0000000000..8ab2a40c74 --- /dev/null +++ b/enterprise/backend/src/baserow_enterprise/migrations/0068_auditlogentry_agent.py @@ -0,0 +1,170 @@ +from django.db import migrations, models + +TABLE = "baserow_enterprise_auditlogentry" +ACTOR_INDEX_NAME = "baserow_ent_actor_ts_idx" + + +def create_actor_index(apps, schema_editor): + """Create the actor index, rebuilding an interrupted concurrent index.""" + + with schema_editor.connection.cursor() as cursor: + cursor.execute( + """ + SELECT 1 + FROM pg_index i + JOIN pg_class c ON c.oid = i.indexrelid + JOIN pg_class t ON t.oid = i.indrelid + WHERE c.relname = %s AND t.relname = %s + AND NOT (i.indisvalid AND i.indisready) + """, + [ACTOR_INDEX_NAME, TABLE], + ) + if cursor.fetchone() is not None: + cursor.execute(f'DROP INDEX CONCURRENTLY "{ACTOR_INDEX_NAME}"') + + cursor.execute( + f'CREATE INDEX CONCURRENTLY IF NOT EXISTS "{ACTOR_INDEX_NAME}" ' + f'ON "{TABLE}" ("actor_type", "user_id", "action_timestamp" DESC)' + ) + + +def drop_actor_index(apps, schema_editor): + with schema_editor.connection.cursor() as cursor: + cursor.execute(f'DROP INDEX CONCURRENTLY IF EXISTS "{ACTOR_INDEX_NAME}"') + + +class Migration(migrations.Migration): + # The actor index is created concurrently, so this migration cannot be wrapped + # in one transaction. actor_id and actor_name only rename Django's model state; + # their existing database columns are reused and require no data backfill. + atomic = False + + dependencies = [ + ("baserow_enterprise", "0067_graph_element"), + ] + + operations = [ + migrations.SeparateDatabaseAndState( + database_operations=[], + state_operations=[ + migrations.RemoveIndex( + model_name="auditlogentry", + name="auditlogentry_user_ts_idx", + ), + migrations.RenameField( + model_name="auditlogentry", + old_name="user_id", + new_name="actor_id", + ), + migrations.AlterField( + model_name="auditlogentry", + name="actor_id", + field=models.PositiveIntegerField(db_column="user_id", null=True), + ), + migrations.RenameField( + model_name="auditlogentry", + old_name="user_email", + new_name="actor_name", + ), + migrations.AlterField( + model_name="auditlogentry", + name="actor_name", + field=models.CharField( + blank=True, + db_column="user_email", + max_length=254, + null=True, + ), + ), + migrations.AddIndex( + model_name="auditlogentry", + index=models.Index( + fields=["actor_id", "-action_timestamp"], + name="auditlogentry_user_ts_idx", + ), + ), + ], + ), + migrations.SeparateDatabaseAndState( + database_operations=[ + migrations.RunSQL( + 'ALTER TABLE "baserow_enterprise_auditlogentry" ' + 'ADD COLUMN IF NOT EXISTS "actor_type" varchar(255) ' + "NOT NULL DEFAULT 'auth.User'", + 'ALTER TABLE "baserow_enterprise_auditlogentry" ' + 'DROP COLUMN IF EXISTS "actor_type"', + ) + ], + state_operations=[ + migrations.AddField( + model_name="auditlogentry", + name="actor_type", + field=models.CharField( + db_default="auth.User", + max_length=255, + ), + ) + ], + ), + migrations.SeparateDatabaseAndState( + database_operations=[], + state_operations=[ + migrations.RenameField( + model_name="auditlogexportjob", + old_name="filter_user_id", + new_name="filter_actor_id", + ), + migrations.AlterField( + model_name="auditlogexportjob", + name="filter_actor_id", + field=models.PositiveIntegerField( + db_column="filter_user_id", + help_text="Optional: The actor to filter the audit log by.", + null=True, + ), + ), + ], + ), + migrations.SeparateDatabaseAndState( + database_operations=[ + migrations.RunSQL( + 'ALTER TABLE "baserow_enterprise_auditlogexportjob" ' + 'ADD COLUMN IF NOT EXISTS "filter_actor_type" varchar(255) ' + "DEFAULT 'auth.User'", + 'ALTER TABLE "baserow_enterprise_auditlogexportjob" ' + 'DROP COLUMN IF EXISTS "filter_actor_type"', + ) + ], + state_operations=[ + migrations.AddField( + model_name="auditlogexportjob", + name="filter_actor_type", + field=models.CharField( + default=None, + db_default="auth.User", + help_text="Optional: The actor type to filter the audit log by.", + max_length=255, + null=True, + ), + ) + ], + ), + migrations.SeparateDatabaseAndState( + database_operations=[ + migrations.RunPython( + create_actor_index, + drop_actor_index, + atomic=False, + ), + ], + state_operations=[ + migrations.AddIndex( + model_name="auditlogentry", + index=models.Index( + fields=["actor_type", "actor_id", "-action_timestamp"], + name="baserow_ent_actor_ts_idx", + ), + ) + ], + ), + ] diff --git a/enterprise/backend/src/baserow_enterprise/role/actions.py b/enterprise/backend/src/baserow_enterprise/role/actions.py index bfe270267f..679eba2ebd 100755 --- a/enterprise/backend/src/baserow_enterprise/role/actions.py +++ b/enterprise/backend/src/baserow_enterprise/role/actions.py @@ -44,10 +44,16 @@ class BatchAssignRoleActionType(UndoableActionType): @classmethod def get_long_description(cls, params_dict: Dict[str, Any], *args, **kwargs) -> str: if len(params_dict["assignments"]) == 1: - return ( - cls.long_desc_if_one_assignment - % AssignmentTuple(*params_dict["assignments"][0])._asdict() - ) + assignment = AssignmentTuple(*params_dict["assignments"][0])._asdict() + try: + subject_type = subject_type_registry.get( + assignment["subject_type_name"] + ) + except subject_type_registry.does_not_exist_exception_class: + pass + else: + assignment["subject_type_name"] = subject_type.get_type_display_name() + return cls.long_desc_if_one_assignment % assignment else: return super().get_long_description(params_dict, *args, **kwargs) diff --git a/enterprise/backend/src/baserow_enterprise/teams/subjects.py b/enterprise/backend/src/baserow_enterprise/teams/subjects.py index 3506a73724..3247b07054 100644 --- a/enterprise/backend/src/baserow_enterprise/teams/subjects.py +++ b/enterprise/backend/src/baserow_enterprise/teams/subjects.py @@ -3,12 +3,14 @@ from typing import List from django.contrib.auth import get_user_model from django.contrib.auth.models import AbstractUser from django.contrib.contenttypes.models import ContentType +from django.db.models import CharField, Count, F, Value from baserow.core.models import Workspace from baserow.core.registries import SubjectType from baserow.core.types import Subject from baserow_enterprise.api.role.serializers import SubjectTeamSerializer from baserow_enterprise.teams.models import Team, TeamSubject +from baserow_enterprise.teams.operations import ListTeamsOperationType User = get_user_model() @@ -16,6 +18,42 @@ User = get_user_model() class TeamSubjectType(SubjectType): type = "baserow_enterprise.Team" model_class = Team + options_list_operation_type = ListTeamsOperationType.type + + def get_type_display_name(self): + return "Team" + + def get_display_name(self, subject: Team) -> str: + return subject.name + + def get_options_queryset( + self, + workspace: Workspace | None = None, + search: str = "", + exclude_ids: List[int] | None = None, + ): + """Return searchable team options, optionally scoped to a workspace.""" + + queryset = Team.objects.exclude(id__in=exclude_ids or []) + if workspace is not None: + queryset = queryset.filter(workspace=workspace) + if search: + queryset = queryset.filter(name__icontains=search) + return queryset.annotate( + subject_id=F("id"), + subject_type=Value(self.type, output_field=CharField()), + subject_name=F("name"), + subject_label=F("name"), + subject_email=Value(None, output_field=CharField()), + subject_count=Count("subjects"), + ).values( + "subject_id", + "subject_type", + "subject_name", + "subject_label", + "subject_email", + "subject_count", + ) def are_in_workspace( self, diff --git a/enterprise/backend/tests/baserow_enterprise_tests/api/audit_log/test_audit_log_admin_views.py b/enterprise/backend/tests/baserow_enterprise_tests/api/audit_log/test_audit_log_admin_views.py index 952b937f88..989a5f1226 100755 --- a/enterprise/backend/tests/baserow_enterprise_tests/api/audit_log/test_audit_log_admin_views.py +++ b/enterprise/backend/tests/baserow_enterprise_tests/api/audit_log/test_audit_log_admin_views.py @@ -23,15 +23,22 @@ from baserow.core.action.registries import ( action_type_registry, ) from baserow.core.actions import CreateWorkspaceActionType +from baserow.core.agents.subjects import AgentSubjectType +from baserow.core.models import Agent +from baserow.core.subjects import UserSubjectType from baserow.test_utils.helpers import AnyInt from baserow_enterprise.audit_log.models import AuditLogEntry +def expected_user_actor(user): + return {"id": user.id, "type": UserSubjectType.type, "name": user.email} + + @pytest.mark.django_db @pytest.mark.parametrize( "method,url_name", [ - ("get", "users"), + ("get", "actors"), ("get", "action_types"), ("get", "list"), ("post", "async_export"), @@ -52,7 +59,7 @@ def test_admins_cannot_access_audit_log_endpoints_without_an_enterprise_license( @pytest.mark.django_db -@pytest.mark.parametrize("url_name", ["users", "action_types", "list"]) +@pytest.mark.parametrize("url_name", ["actors", "action_types", "list"]) @override_settings(DEBUG=True) def test_non_admins_cannot_access_audit_log_endpoints( api_client, enterprise_data_fixture, url_name @@ -86,49 +93,148 @@ def test_non_admins_cannot_export_audit_log_to_csv(api_client, enterprise_data_f @pytest.mark.django_db @override_settings(DEBUG=True) -def test_audit_log_user_filter_returns_users_correctly( +def test_audit_log_actor_filter_returns_users_and_agents_in_separate_types( api_client, enterprise_data_fixture ): - ( - admin_user, - admin_token, - ) = enterprise_data_fixture.create_enterprise_admin_user_and_token( + admin, token = enterprise_data_fixture.create_enterprise_admin_user_and_token( email="admin@test.com" ) - user = enterprise_data_fixture.create_user(email="user@test.com") + workspace = enterprise_data_fixture.create_workspace(user=admin) + agent = Agent.objects.create(workspace=workspace, name="Audit robot") - # no search query should return all users response = api_client.get( - reverse("api:enterprise:audit_log:users"), + reverse("api:enterprise:audit_log:actors"), format="json", - HTTP_AUTHORIZATION=f"JWT {admin_token}", + HTTP_AUTHORIZATION=f"JWT {token}", ) + assert response.status_code == HTTP_200_OK assert response.json() == { "count": 2, "next": None, "previous": None, "results": [ - {"id": admin_user.id, "value": admin_user.email}, - {"id": user.id, "value": user.email}, + { + "id": f"{UserSubjectType.type}:{admin.id}", + "actor_id": admin.id, + "actor_type": UserSubjectType.type, + "value": admin.email, + }, + { + "id": f"{AgentSubjectType.type}:{agent.id}", + "actor_id": agent.id, + "actor_type": AgentSubjectType.type, + "value": agent.name, + }, ], } - # searching by email should return only the correct user - response = api_client.get( - reverse("api:enterprise:audit_log:users") + "?search=admin", - format="json", - HTTP_AUTHORIZATION=f"JWT {admin_token}", + +@pytest.mark.django_db +@override_settings(DEBUG=True) +def test_audit_log_actor_filter_searches_users_and_agents( + api_client, enterprise_data_fixture +): + admin, token = enterprise_data_fixture.create_enterprise_admin_user_and_token( + email="admin@test.com" ) + workspace = enterprise_data_fixture.create_workspace(user=admin) + matching_user = enterprise_data_fixture.create_user(email="matching@test.com") + matching_agent = Agent.objects.create(workspace=workspace, name="Matching robot") + Agent.objects.create(workspace=workspace, name="Other robot") + + response = api_client.get( + reverse("api:enterprise:audit_log:actors") + "?search=matching", + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + assert response.status_code == HTTP_200_OK - assert response.json() == { - "count": 1, - "next": None, - "previous": None, - "results": [{"id": admin_user.id, "value": admin_user.email}], + assert { + (result["actor_type"], result["actor_id"]) + for result in response.json()["results"] + } == { + (UserSubjectType.type, matching_user.id), + (AgentSubjectType.type, matching_agent.id), } +@pytest.mark.django_db +@override_settings(DEBUG=True) +def test_audit_log_actor_filter_returns_pagination_links( + api_client, enterprise_data_fixture +): + admin, token = enterprise_data_fixture.create_enterprise_admin_user_and_token( + email="admin@test.com" + ) + workspace = enterprise_data_fixture.create_workspace(user=admin) + other_user = enterprise_data_fixture.create_user(email="other@test.com") + agent = Agent.objects.create(workspace=workspace, name="Audit robot") + url = reverse("api:enterprise:audit_log:actors") + + response = api_client.get( + f"{url}?size=1", + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert response.json()["count"] == 3 + assert response.json()["next"].endswith(f"{url}?page=2&size=1") + assert response.json()["previous"] is None + + response = api_client.get( + f"{url}?page=2&size=1", + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert response.json()["next"].endswith(f"{url}?page=3&size=1") + assert response.json()["previous"].endswith(f"{url}?size=1") + assert response.json()["results"] == [ + { + "id": f"{AgentSubjectType.type}:{agent.id}", + "actor_id": agent.id, + "actor_type": AgentSubjectType.type, + "value": agent.name, + } + ] + + response = api_client.get( + f"{url}?page=3&size=1", + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert response.json()["next"] is None + assert response.json()["previous"].endswith(f"{url}?page=2&size=1") + assert response.json()["results"] == [ + { + "id": f"{UserSubjectType.type}:{other_user.id}", + "actor_id": other_user.id, + "actor_type": UserSubjectType.type, + "value": other_user.email, + } + ] + + +@pytest.mark.django_db +@override_settings(DEBUG=True) +def test_audit_log_actor_filter_limits_page_size(api_client, enterprise_data_fixture): + _, token = enterprise_data_fixture.create_enterprise_admin_user_and_token() + + response = api_client.get( + reverse("api:enterprise:audit_log:actors") + "?size=101", + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_400_BAD_REQUEST + assert response.json()["error"] == "ERROR_PAGE_SIZE_LIMIT" + + @pytest.mark.django_db @override_settings(DEBUG=True) def test_audit_log_action_type_filter_returns_action_types_correctly( @@ -258,6 +364,7 @@ def test_audit_log_entries_are_created_from_actions_and_returned_in_order( "ip_address": None, "type": "Create group", "user": f"{admin_user.email} ({admin_user.id})", + "actor": expected_user_actor(admin_user), } response = api_client.get( @@ -334,6 +441,7 @@ def test_audit_log_entries_are_translated_in_the_user_language( "timestamp": "2023-01-01T12:00:01Z", "type": "Crea progetto", "user": f"{admin_user.email} ({admin_user.id})", + "actor": expected_user_actor(admin_user), }, { "action_type": "create_group", @@ -344,6 +452,7 @@ def test_audit_log_entries_are_translated_in_the_user_language( "timestamp": "2023-01-01T12:00:00Z", "type": "Crea progetto", "user": f"{admin_user.email} ({admin_user.id})", + "actor": expected_user_actor(admin_user), }, ], } @@ -374,6 +483,7 @@ def test_audit_log_entries_can_be_filtered(api_client, enterprise_data_fixture): "timestamp": "2023-01-01T12:00:00Z", "type": "Create group", "user": f"{admin_user.email} ({admin_user.id})", + "actor": expected_user_actor(admin_user), } json_workspace_2 = { "action_type": "create_group", @@ -384,8 +494,18 @@ def test_audit_log_entries_can_be_filtered(api_client, enterprise_data_fixture): "timestamp": "2023-01-01T12:00:01Z", "type": "Create group", "user": f"{user.email} ({user.id})", + "actor": expected_user_actor(user), } + # An Agent can have the same numeric ID as a user because they use different + # tables. The user filter must include the SubjectType to avoid mixing them. + agent_entry = AuditLogEntry.objects.get(actor_id=admin_user.id) + agent_entry.pk = None + agent_entry.actor_id = user.id + agent_entry.actor_type = AgentSubjectType.type + agent_entry.actor_name = "Agent with colliding ID" + agent_entry.save() + # by user_id response = api_client.get( reverse("api:enterprise:audit_log:list") + "?user_id=" + str(user.id), @@ -400,6 +520,47 @@ def test_audit_log_entries_can_be_filtered(api_client, enterprise_data_fixture): "results": [json_workspace_2], } + # by actor type and id + response = api_client.get( + reverse("api:enterprise:audit_log:list") + + f"?actor_id={user.id}&actor_type={AgentSubjectType.type}", + format="json", + HTTP_AUTHORIZATION=f"JWT {admin_token}", + ) + assert response.status_code == HTTP_200_OK + assert response.json()["count"] == 1 + assert response.json()["results"][0]["actor"] == { + "id": user.id, + "type": AgentSubjectType.type, + "name": "Agent with colliding ID", + } + + # actor_id is ambiguous without its polymorphic actor type + response = api_client.get( + reverse("api:enterprise:audit_log:list") + f"?actor_id={user.id}", + format="json", + HTTP_AUTHORIZATION=f"JWT {admin_token}", + ) + assert response.status_code == HTTP_400_BAD_REQUEST + assert response.json()["detail"]["actor_type"] == [ + { + "error": "This field is required when actor_id is provided.", + "code": "invalid", + } + ] + + # actor_type remains independently filterable + response = api_client.get( + reverse("api:enterprise:audit_log:list") + + f"?actor_type={AgentSubjectType.type}", + format="json", + HTTP_AUTHORIZATION=f"JWT {admin_token}", + ) + assert response.status_code == HTTP_200_OK + assert response.json()["count"] == 1 + assert response.json()["results"][0]["actor"]["type"] == AgentSubjectType.type + agent_entry.delete() + # by workspace_id response = api_client.get( reverse("api:enterprise:audit_log:list") @@ -569,18 +730,82 @@ def test_audit_log_can_export_to_csv_all_entries( for key, value in csv_settings.items(): assert job[key] == value for key in [ - "filter_user_id", + "filter_actor_id", "filter_workspace_id", "filter_action_type", "filter_from_timestamp", "filter_to_timestamp", ]: assert job[key] is None + assert job["filter_actor_type"] is None assert job["exported_file_name"].endswith(".csv") assert job["url"].startswith("http://localhost:8000/media/export_files/") assert job["created_on"] == "2023-01-01T12:00:00Z" +@pytest.mark.django_db +@override_settings(DEBUG=True) +def test_audit_log_export_rejects_removed_filter_user_id( + api_client, enterprise_data_fixture, synced_roles +): + """The removed user filter must not be silently ignored.""" + + admin_user, admin_token = ( + enterprise_data_fixture.create_enterprise_admin_user_and_token() + ) + + response = api_client.post( + reverse("api:enterprise:audit_log:async_export"), + data={ + "csv_column_separator": ",", + "csv_first_row_header": True, + "export_charset": "utf-8", + "filter_user_id": admin_user.id, + }, + format="json", + HTTP_AUTHORIZATION=f"JWT {admin_token}", + ) + + assert response.status_code == HTTP_400_BAD_REQUEST + assert response.json()["detail"]["filter_user_id"] == [ + { + "error": "This filter has been removed. Use filter_actor_id and " + "filter_actor_type instead.", + "code": "invalid", + } + ] + + +@pytest.mark.django_db +@override_settings(DEBUG=True) +def test_audit_log_export_requires_actor_type_with_actor_id( + api_client, enterprise_data_fixture, synced_roles +): + admin_user, admin_token = ( + enterprise_data_fixture.create_enterprise_admin_user_and_token() + ) + + response = api_client.post( + reverse("api:enterprise:audit_log:async_export"), + data={ + "csv_column_separator": ",", + "csv_first_row_header": True, + "export_charset": "utf-8", + "filter_actor_id": admin_user.id, + }, + format="json", + HTTP_AUTHORIZATION=f"JWT {admin_token}", + ) + + assert response.status_code == HTTP_400_BAD_REQUEST + assert response.json()["detail"]["filter_actor_type"] == [ + { + "error": "This field is required when filter_actor_id is provided.", + "code": "invalid", + } + ] + + @pytest.mark.django_db @override_settings(DEBUG=True) def test_audit_log_can_export_to_csv_filtered_entries( @@ -602,7 +827,8 @@ def test_audit_log_can_export_to_csv_filtered_entries( "exclude_columns": "ip_address", } filters = { - "filter_user_id": admin_user.id, + "filter_actor_id": admin_user.id, + "filter_actor_type": UserSubjectType.type, "filter_workspace_id": workspace.id, "filter_action_type": "create_application", "filter_from_timestamp": "2023-01-01T00:00:00Z", @@ -650,7 +876,8 @@ def test_audit_log_can_export_to_csv_filtered_entries( for key, value in csv_settings.items(): assert job[key] == value for key in [ - "filter_user_id", + "filter_actor_id", + "filter_actor_type", "filter_workspace_id", "filter_action_type", "filter_from_timestamp", @@ -719,6 +946,7 @@ def test_log_entries_still_work_correctly_if_the_action_type_is_removed( "timestamp": "2023-01-01T12:00:00Z", "type": "Temporary action", "user": f"{admin.email} ({admin.id})", + "actor": expected_user_actor(admin), } for key, value in expected_data.items(): assert entry[key] == value @@ -766,6 +994,7 @@ def test_log_entries_still_work_correctly_if_the_action_type_is_removed( "timestamp": "2023-01-01T12:00:00Z", "type": "Temporary action", "user": f"{admin.email} ({admin.id})", + "actor": expected_user_actor(admin), } for key, value in expected_data.items(): assert entry[key] == value @@ -793,6 +1022,7 @@ def test_log_entries_still_work_correctly_if_the_action_type_is_removed( "timestamp": "2023-01-01T12:01:00Z", "type": "Temporary action", "user": f"{admin.email} ({admin.id})", + "actor": expected_user_actor(admin), }, { "action_type": "temporary", @@ -802,6 +1032,7 @@ def test_log_entries_still_work_correctly_if_the_action_type_is_removed( "timestamp": "2023-01-01T12:00:00Z", "type": "Temporary action", "user": f"{admin.email} ({admin.id})", + "actor": expected_user_actor(admin), }, ] for entry, expected_data in zip(response_json["results"], expected_data): diff --git a/enterprise/backend/tests/baserow_enterprise_tests/api/audit_log/test_audit_log_workspace_views.py b/enterprise/backend/tests/baserow_enterprise_tests/api/audit_log/test_audit_log_workspace_views.py index 0e114ebc8c..bf36e2f104 100644 --- a/enterprise/backend/tests/baserow_enterprise_tests/api/audit_log/test_audit_log_workspace_views.py +++ b/enterprise/backend/tests/baserow_enterprise_tests/api/audit_log/test_audit_log_workspace_views.py @@ -12,11 +12,14 @@ from rest_framework.status import ( HTTP_404_NOT_FOUND, ) +from baserow.core.agents.subjects import AgentSubjectType +from baserow.core.models import Agent +from baserow.core.subjects import UserSubjectType from baserow_enterprise.license_types import EnterpriseLicenseType @pytest.mark.django_db -@pytest.mark.parametrize("url_name", ["users", "action_types", "list"]) +@pytest.mark.parametrize("url_name", ["actors", "action_types", "list"]) @override_settings(DEBUG=True) def test_workspace_admins_cannot_access_workspace_audit_log_endpoints_without_an_enterprise_license( api_client, enterprise_data_fixture, url_name @@ -51,7 +54,7 @@ def test_workspace_admins_cannot_export_workspace_audit_log_without_an_enterpris @pytest.mark.django_db -@pytest.mark.parametrize("url_name", ["users", "action_types", "list"]) +@pytest.mark.parametrize("url_name", ["actors", "action_types", "list"]) @override_settings(DEBUG=True) def test_non_admins_cannot_access_workspace_audit_log_endpoints( api_client, enterprise_data_fixture, synced_roles, url_name @@ -96,7 +99,7 @@ def test_non_admins_cannot_export_workspace_audit_log_to_csv( @pytest.mark.django_db -@pytest.mark.parametrize("url_name", ["users", "action_types", "list"]) +@pytest.mark.parametrize("url_name", ["actors", "action_types", "list"]) @override_settings(DEBUG=True) def test_workspace_audit_log_endpoints_raise_404_if_workspace_doesnt_exist( api_client, enterprise_data_fixture, url_name @@ -135,71 +138,108 @@ def test_workspace_audit_log_export_raise_404_if_workspace_doesnt_exist( @pytest.mark.django_db @override_settings(DEBUG=True) -def test_workspace_audit_log_user_filter_returns_only_workspace_users( +def test_workspace_audit_log_actor_filter_returns_only_workspace_actors( api_client, enterprise_data_fixture ): enterprise_data_fixture.enable_enterprise() - admin, token = enterprise_data_fixture.create_user_and_token(email="admin@test.com") - user_wp1 = enterprise_data_fixture.create_user(email="user_wp1@test.com") - user_wp2 = enterprise_data_fixture.create_user(email="user_wp2@test.com") + other_user = enterprise_data_fixture.create_user(email="other@test.com") + workspace = enterprise_data_fixture.create_workspace(user=admin) + other_workspace = enterprise_data_fixture.create_workspace(user=other_user) + agent = Agent.objects.create(workspace=workspace, name="Workspace robot") + Agent.objects.create(workspace=other_workspace, name="Other robot") - workspace_1 = enterprise_data_fixture.create_workspace(users=[admin, user_wp1]) - workspace_2 = enterprise_data_fixture.create_workspace(users=[admin, user_wp2]) - - # no search query should return all users for worspace 1 response = api_client.get( - reverse("api:enterprise:audit_log:users") + f"?workspace_id={workspace_1.id}", + reverse("api:enterprise:audit_log:actors") + f"?workspace_id={workspace.id}", format="json", HTTP_AUTHORIZATION=f"JWT {token}", ) - assert response.status_code == HTTP_200_OK - assert response.json() == { - "count": 2, - "next": None, - "previous": None, - "results": [ - {"id": admin.id, "value": admin.email}, - {"id": user_wp1.id, "value": user_wp1.email}, - ], - } - # no search query should return all users for worspace 2 + assert response.status_code == HTTP_200_OK + assert response.json()["results"] == [ + { + "id": f"{UserSubjectType.type}:{admin.id}", + "actor_id": admin.id, + "actor_type": UserSubjectType.type, + "value": admin.email, + }, + { + "id": f"{AgentSubjectType.type}:{agent.id}", + "actor_id": agent.id, + "actor_type": AgentSubjectType.type, + "value": agent.name, + }, + ] + + +@pytest.mark.django_db +@override_settings(DEBUG=True) +def test_workspace_audit_log_actor_filter_includes_disabled_and_deletion_scheduled_users( + api_client, enterprise_data_fixture +): + """Historical user actors remain selectable when their access is removed.""" + + enterprise_data_fixture.enable_enterprise() + admin, token = enterprise_data_fixture.create_user_and_token(email="admin@test.com") + disabled_user = enterprise_data_fixture.create_user( + email="disabled@test.com", is_active=False + ) + scheduled_user = enterprise_data_fixture.create_user( + email="scheduled@test.com", to_be_deleted=True + ) + workspace = enterprise_data_fixture.create_workspace( + user=admin, + members=[disabled_user, scheduled_user], + ) + response = api_client.get( - reverse("api:enterprise:audit_log:users") + f"?workspace_id={workspace_2.id}", + reverse("api:enterprise:audit_log:actors") + f"?workspace_id={workspace.id}", format="json", HTTP_AUTHORIZATION=f"JWT {token}", ) - assert response.status_code == HTTP_200_OK - assert response.json() == { - "count": 2, - "next": None, - "previous": None, - "results": [ - {"id": admin.id, "value": admin.email}, - {"id": user_wp2.id, "value": user_wp2.email}, - ], - } - # searching by email should return only the correct user - response = api_client.get( - reverse("api:enterprise:audit_log:users") - + f"?workspace_id={workspace_1.id}&search=user", - format="json", - HTTP_AUTHORIZATION=f"JWT {token}", - ) assert response.status_code == HTTP_200_OK - assert response.json() == { - "count": 1, - "next": None, - "previous": None, - "results": [{"id": user_wp1.id, "value": "user_wp1@test.com"}], + assert { + (actor["actor_type"], actor["actor_id"]) for actor in response.json()["results"] + } == { + (UserSubjectType.type, admin.id), + (UserSubjectType.type, disabled_user.id), + (UserSubjectType.type, scheduled_user.id), } @pytest.mark.django_db @override_settings(DEBUG=True) -@pytest.mark.parametrize("url_name", ["users", "action_types", "list"]) +def test_workspace_audit_log_actor_filter_includes_trashed_agents( + api_client, enterprise_data_fixture +): + """Historical agent actors remain selectable after being trashed.""" + + enterprise_data_fixture.enable_enterprise() + admin, token = enterprise_data_fixture.create_user_and_token(email="admin@test.com") + workspace = enterprise_data_fixture.create_workspace(user=admin) + agent = Agent.objects.create( + workspace=workspace, name="Trashed robot", trashed=True + ) + + response = api_client.get( + reverse("api:enterprise:audit_log:actors") + f"?workspace_id={workspace.id}", + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_200_OK + assert { + (actor["actor_type"], actor["actor_id"]) for actor in response.json()["results"] + } == { + (UserSubjectType.type, admin.id), + (AgentSubjectType.type, agent.id), + } + + +@pytest.mark.django_db +@override_settings(DEBUG=True) +@pytest.mark.parametrize("url_name", ["actors", "action_types", "list"]) def test_staff_member_can_access_audit_log_for_their_own_workspace( api_client, enterprise_data_fixture, @@ -224,7 +264,7 @@ def test_staff_member_can_access_audit_log_for_their_own_workspace( @pytest.mark.django_db @override_settings(DEBUG=True) -@pytest.mark.parametrize("url_name", ["users", "action_types", "list"]) +@pytest.mark.parametrize("url_name", ["actors", "action_types", "list"]) def test_staff_member_can_access_audit_log_for_any_workspace( api_client, enterprise_data_fixture, @@ -247,7 +287,7 @@ def test_staff_member_can_access_audit_log_for_any_workspace( @pytest.mark.django_db @override_settings(DEBUG=True) -@pytest.mark.parametrize("url_name", ["users", "action_types", "list"]) +@pytest.mark.parametrize("url_name", ["actors", "action_types", "list"]) def test_staff_member_cant_access_audit_log_for_own_workspace_without_license( api_client, enterprise_data_fixture, @@ -288,7 +328,8 @@ def test_workspace_audit_log_can_export_to_csv_filtered_entries( "export_charset": "utf-8", } filters = { - "filter_user_id": admin_user.id, + "filter_actor_id": admin_user.id, + "filter_actor_type": UserSubjectType.type, "filter_action_type": "create_application", "filter_from_timestamp": "2023-01-01T00:00:00Z", "filter_to_timestamp": "2023-01-03T00:00:00Z", @@ -346,7 +387,8 @@ def test_workspace_audit_log_can_export_to_csv_filtered_entries( for key, value in csv_settings.items(): assert job[key] == value for key in [ - "filter_user_id", + "filter_actor_id", + "filter_actor_type", "filter_action_type", "filter_from_timestamp", "filter_to_timestamp", diff --git a/enterprise/backend/tests/baserow_enterprise_tests/api/field_permissions/test_field_permissions_handler.py b/enterprise/backend/tests/baserow_enterprise_tests/api/field_permissions/test_field_permissions_handler.py index fdbcdb3d24..8ab66cdf3d 100644 --- a/enterprise/backend/tests/baserow_enterprise_tests/api/field_permissions/test_field_permissions_handler.py +++ b/enterprise/backend/tests/baserow_enterprise_tests/api/field_permissions/test_field_permissions_handler.py @@ -335,6 +335,33 @@ def test_get_subject_options_returns_searchable_workspace_users_and_teams( ) +@pytest.mark.django_db +def test_get_subject_options_orders_users_by_displayed_name(enterprise_data_fixture): + admin = enterprise_data_fixture.create_user() + first_by_email = enterprise_data_fixture.create_user( + first_name="Zoe", email="a@example.com" + ) + first_by_name = enterprise_data_fixture.create_user( + first_name="Ada", email="z@example.com" + ) + workspace = enterprise_data_fixture.create_workspace(user=admin) + enterprise_data_fixture.create_user_workspace( + user=first_by_email, workspace=workspace, permissions="EDITOR" + ) + enterprise_data_fixture.create_user_workspace( + user=first_by_name, workspace=workspace, permissions="EDITOR" + ) + + options = FieldPermissionsHandler.get_subject_options( + workspace, exclude_user_ids=[admin.id] + ) + + assert [option["subject_id"] for option in options] == [ + first_by_name.id, + first_by_email.id, + ] + + @pytest.mark.django_db def test_sync_empty_field_permission_subjects_uses_single_delete_query( enterprise_data_fixture, django_assert_num_queries diff --git a/enterprise/backend/tests/baserow_enterprise_tests/api/subjects/test_subject_views.py b/enterprise/backend/tests/baserow_enterprise_tests/api/subjects/test_subject_views.py new file mode 100644 index 0000000000..6f7d4b4dbf --- /dev/null +++ b/enterprise/backend/tests/baserow_enterprise_tests/api/subjects/test_subject_views.py @@ -0,0 +1,86 @@ +from django.shortcuts import reverse + +import pytest +from rest_framework.status import HTTP_200_OK, HTTP_401_UNAUTHORIZED + +from baserow.core.agents.subjects import AgentSubjectType +from baserow.core.models import Agent +from baserow.core.subjects import UserSubjectType +from baserow_enterprise.role.handler import RoleAssignmentHandler +from baserow_enterprise.teams.subjects import TeamSubjectType + + +@pytest.mark.django_db +def test_subject_options_cannot_list_teams_from_another_workspace( + api_client, data_fixture, enterprise_data_fixture, enable_enterprise, synced_roles +): + user, token = data_fixture.create_user_and_token() + workspace = data_fixture.create_workspace() + enterprise_data_fixture.create_team(workspace=workspace) + + response = api_client.get( + reverse("api:subjects:list"), + { + "workspace_id": workspace.id, + "subject_types": TeamSubjectType.type, + }, + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_401_UNAUTHORIZED + + +@pytest.mark.django_db +def test_subject_options_check_each_requested_type_permission( + api_client, data_fixture, enable_enterprise, synced_roles +): + admin = data_fixture.create_user() + editor, editor_token = data_fixture.create_user_and_token() + builder, builder_token = data_fixture.create_user_and_token() + workspace = data_fixture.create_workspace(user=admin, members=[editor, builder]) + roles = RoleAssignmentHandler() + roles.assign_role(editor, workspace, roles.get_role_by_uid("EDITOR")) + roles.assign_role(builder, workspace, roles.get_role_by_uid("BUILDER")) + agent = Agent.objects.create(workspace=workspace, name="Private agent") + url = reverse("api:subjects:list") + + editor_users_response = api_client.get( + url, + { + "workspace_id": workspace.id, + "subject_types": UserSubjectType.type, + }, + HTTP_AUTHORIZATION=f"JWT {editor_token}", + ) + editor_agents_response = api_client.get( + url, + { + "workspace_id": workspace.id, + "subject_types": AgentSubjectType.type, + }, + HTTP_AUTHORIZATION=f"JWT {editor_token}", + ) + editor_all_response = api_client.get( + url, + {"workspace_id": workspace.id}, + HTTP_AUTHORIZATION=f"JWT {editor_token}", + ) + builder_all_response = api_client.get( + url, + {"workspace_id": workspace.id}, + HTTP_AUTHORIZATION=f"JWT {builder_token}", + ) + + assert editor_users_response.status_code == HTTP_200_OK + assert all( + result["subject_type"] == UserSubjectType.type + for result in editor_users_response.json()["results"] + ) + assert editor_agents_response.status_code == HTTP_401_UNAUTHORIZED + assert editor_all_response.status_code == HTTP_401_UNAUTHORIZED + assert builder_all_response.status_code == HTTP_200_OK + assert any( + result["subject_type"] == AgentSubjectType.type + and result["subject_id"] == agent.id + for result in builder_all_response.json()["results"] + ) diff --git a/enterprise/backend/tests/baserow_enterprise_tests/audit_log/test_audit_log_export_job.py b/enterprise/backend/tests/baserow_enterprise_tests/audit_log/test_audit_log_export_job.py index 9b38597f77..5ab1e528f3 100755 --- a/enterprise/backend/tests/baserow_enterprise_tests/audit_log/test_audit_log_export_job.py +++ b/enterprise/backend/tests/baserow_enterprise_tests/audit_log/test_audit_log_export_job.py @@ -6,12 +6,19 @@ from django.test.utils import override_settings import pytest from freezegun import freeze_time +from rest_framework import serializers from baserow.contrib.database.export.handler import ExportHandler from baserow.core.actions import CreateApplicationActionType, CreateWorkspaceActionType +from baserow.core.agents.subjects import AgentSubjectType from baserow.core.jobs.constants import JOB_FINISHED from baserow.core.jobs.handler import JobHandler -from baserow_enterprise.audit_log.job_types import AuditLogExportJobType +from baserow.core.subjects import UserSubjectType +from baserow_enterprise.audit_log.job_types import ( + AuditLogExportJobType, + CommaSeparatedCsvColumnsField, +) +from baserow_enterprise.audit_log.models import AuditLogEntry from baserow_premium.license.exceptions import FeaturesNotAvailableError @@ -53,12 +60,12 @@ def test_audit_log_export_csv_correctly( assert data == ( bom - + "User Email,User ID,Group Name,Group ID,Action Type,Description,Timestamp,IP Address\r\n" - + f"{user.email},{user.id},{workspace_2.name},{workspace_2.id},Create group," - f'"Group ""{workspace_2.name}"" ({workspace_2.id}) created.",2023-01-01 12:00:10+00:00,\r\n' - + f"{user.email},{user.id},{workspace_1.name},{workspace_1.id},Create group," + + "Group Name,Group ID,Action Type,Description,Timestamp,IP Address,Actor Type,Actor Name,Actor ID\r\n" + + f"{workspace_2.name},{workspace_2.id},Create group," + f'"Group ""{workspace_2.name}"" ({workspace_2.id}) created.",2023-01-01 12:00:10+00:00,,{UserSubjectType.type},{user.email},{user.id}\r\n' + + f"{workspace_1.name},{workspace_1.id},Create group," f'"Group ""{workspace_1.name}"" ({workspace_1.id}) created.",2023-01-01 ' - f"12:00:00+00:00,\r\n" + f"12:00:00+00:00,,{UserSubjectType.type},{user.email},{user.id}\r\n" ) close() @@ -85,17 +92,26 @@ def test_audit_log_export_csv_correctly( bom = "\ufeff" assert data == ( - bom + f"{user.email}|{user.id}|{workspace_2.name}|{workspace_2.id}|Create " + bom + f"{workspace_2.name}|{workspace_2.id}|Create " f'group|"Group ""{workspace_2.name}"" ({workspace_2.id}) ' - f'created."|2023-01-01 12:00:10+00:00|\r\n' - + f"{user.email}|{user.id}|{workspace_1.name}|{workspace_1.id}|Create " + f'created."|2023-01-01 12:00:10+00:00||{UserSubjectType.type}|{user.email}|{user.id}\r\n' + + f"{workspace_1.name}|{workspace_1.id}|Create " f'group|"Group ""{workspace_1.name}"" ({workspace_1.id}) ' - f'created."|2023-01-01 12:00:00+00:00|\r\n' + f'created."|2023-01-01 12:00:00+00:00||{UserSubjectType.type}|{user.email}|{user.id}\r\n' ) close() +def test_audit_log_export_legacy_user_columns_are_actor_column_aliases(): + field = CommaSeparatedCsvColumnsField() + + assert field.run_validation("user_email,user_id") == "actor_name,actor_id" + + with pytest.raises(serializers.ValidationError, match="Duplicate items"): + field.run_validation("user_email,actor_name") + + @pytest.mark.django_db @patch("baserow.core.storage.get_default_storage") @override_settings(DEBUG=True) @@ -134,7 +150,8 @@ def test_audit_log_export_csv_in_the_user_language( assert data == ( bom - + f'{user.email},{user.id},{workspace_1.name},{workspace_1.id},Crea progetto,"Progetto ""{workspace_1.name}"" ({workspace_1.id}) creato.",2023-01-01 12:00:00+00:00,\r\n' + + f"{workspace_1.name},{workspace_1.id},Crea progetto," + + f'"Progetto ""{workspace_1.name}"" ({workspace_1.id}) creato.",2023-01-01 12:00:00+00:00,,{UserSubjectType.type},{user.email},{user.id}\r\n' ) close() @@ -210,11 +227,26 @@ def test_audit_log_export_filters_work_correctly( job.refresh_from_db() job_type = AuditLogExportJobType() - assert job_type.get_filtered_queryset(job).count() == 2 + agent_entry = AuditLogEntry.objects.first() + agent_entry.pk = None + agent_entry.actor_type = AgentSubjectType.type + agent_entry.save() - job.filter_user_id = user.id + 1 + assert job.filter_actor_type is None + assert job_type.get_filtered_queryset(job).count() == 3 + + job.filter_actor_id = user.id + 1 assert job_type.get_filtered_queryset(job).count() == 0 - job.filter_user_id = None + job.filter_actor_id = None + + job.filter_actor_id = user.id + job.filter_actor_type = AgentSubjectType.type + assert job_type.get_filtered_queryset(job).count() == 1 + job.filter_actor_id = None + assert job_type.get_filtered_queryset(job).count() == 1 + job.filter_actor_type = UserSubjectType.type + assert job_type.get_filtered_queryset(job).count() == 2 + agent_entry.delete() job.filter_workspace_id = workspace_1.id assert job_type.get_filtered_queryset(job).count() == 1 @@ -281,11 +313,11 @@ def test_audit_log_export_workspace_csv_correctly( assert data == ( bom - + "User Email,User ID,Action Type,Description,Timestamp,IP Address\r\n" - + f'{user.email},{user.id},Create application,"""{app_2.name}"" ({app_2.id}) database created ' - + f'in group ""{workspace.name}"" ({workspace.id}).",2023-01-01 12:00:10+00:00,\r\n' - + f'{user.email},{user.id},Create application,"""{app_1.name}"" ({app_1.id}) database created ' - + f'in group ""{workspace.name}"" ({workspace.id}).",2023-01-01 12:00:00+00:00,\r\n' + + "Action Type,Description,Timestamp,IP Address,Actor Type,Actor Name,Actor ID\r\n" + + f'Create application,"""{app_2.name}"" ({app_2.id}) database created ' + + f'in group ""{workspace.name}"" ({workspace.id}).",2023-01-01 12:00:10+00:00,,{UserSubjectType.type},{user.email},{user.id}\r\n' + + f'Create application,"""{app_1.name}"" ({app_1.id}) database created ' + + f'in group ""{workspace.name}"" ({workspace.id}).",2023-01-01 12:00:00+00:00,,{UserSubjectType.type},{user.email},{user.id}\r\n' ) close() @@ -367,11 +399,11 @@ def test_audit_log_export_workspace_csv_correctly_if_feature_is_enable_for_the_u assert data == ( bom - + "User Email,User ID,Action Type,Description,Timestamp,IP Address\r\n" - + f'{user.email},{user.id},Create application,"""{app_2.name}"" ({app_2.id}) database created ' - + f'in group ""{workspace.name}"" ({workspace.id}).",2023-01-01 12:00:10+00:00,\r\n' - + f'{user.email},{user.id},Create application,"""{app_1.name}"" ({app_1.id}) database created ' - + f'in group ""{workspace.name}"" ({workspace.id}).",2023-01-01 12:00:00+00:00,\r\n' + + "Action Type,Description,Timestamp,IP Address,Actor Type,Actor Name,Actor ID\r\n" + + f'Create application,"""{app_2.name}"" ({app_2.id}) database created ' + + f'in group ""{workspace.name}"" ({workspace.id}).",2023-01-01 12:00:10+00:00,,{UserSubjectType.type},{user.email},{user.id}\r\n' + + f'Create application,"""{app_1.name}"" ({app_1.id}) database created ' + + f'in group ""{workspace.name}"" ({workspace.id}).",2023-01-01 12:00:00+00:00,,{UserSubjectType.type},{user.email},{user.id}\r\n' ) close() diff --git a/enterprise/backend/tests/baserow_enterprise_tests/audit_log/test_audit_log_handler.py b/enterprise/backend/tests/baserow_enterprise_tests/audit_log/test_audit_log_handler.py index 1b55d24c46..75234ee5cf 100755 --- a/enterprise/backend/tests/baserow_enterprise_tests/audit_log/test_audit_log_handler.py +++ b/enterprise/backend/tests/baserow_enterprise_tests/audit_log/test_audit_log_handler.py @@ -5,12 +5,47 @@ from django.test.utils import override_settings import pytest from freezegun import freeze_time +from baserow.contrib.database.rows.actions import CreateRowsActionType from baserow.core.action.handler import ActionHandler +from baserow.core.action.models import Action +from baserow.core.action.signals import ActionCommandType from baserow.core.actions import CreateWorkspaceActionType +from baserow.core.agents.subjects import AgentSubjectType +from baserow.core.models import Agent +from baserow.core.subjects import UserSubjectType +from baserow_enterprise.api.audit_log.serializers import AuditLogSerializer from baserow_enterprise.audit_log.handler import AuditLogHandler from baserow_enterprise.audit_log.models import AuditLogEntry +@pytest.mark.django_db +@override_settings(DEBUG=True) +def test_agent_action_is_recorded_in_audit_log( + api_client, enterprise_data_fixture, synced_roles +): + user = enterprise_data_fixture.create_user() + table = enterprise_data_fixture.create_database_table(user=user) + agent = Agent.objects.create( + workspace=table.database.workspace, + name="Automation writer", + role_uid="ADMIN", + ) + + CreateRowsActionType.do(agent, table, [{}]) + + entry = AuditLogEntry.objects.get(action_type="create_rows") + assert entry.actor_id == agent.id + assert entry.actor_type == AgentSubjectType.type + assert entry.actor_name == agent.name + assert AuditLogSerializer(entry).data["actor"] == { + "id": agent.id, + "type": AgentSubjectType.type, + "name": agent.name, + } + assert AuditLogSerializer(entry).data["user"] == f"Automation writer ({agent.id})" + assert not Action.objects.filter(type="create_rows").exists() + + @pytest.mark.django_db @override_settings(DEBUG=True) def test_actions_are_inserted_as_audit_log_entries_and_can_be_deleted_even_without_license( @@ -25,12 +60,54 @@ def test_actions_are_inserted_as_audit_log_entries_and_can_be_deleted_even_witho CreateWorkspaceActionType.do(user, "workspace 2") assert AuditLogEntry.objects.count() == 2 + assert set(AuditLogEntry.objects.values_list("actor_type", flat=True)) == { + UserSubjectType.type + } + assert set(AuditLogEntry.objects.values_list("actor_name", flat=True)) == { + user.email + } AuditLogHandler.delete_entries_older_than(datetime(2023, 1, 1, 13, 0, 0)) assert AuditLogEntry.objects.count() == 0 +@pytest.mark.django_db +def test_actor_fields_reuse_the_legacy_user_columns(enterprise_data_fixture): + user = enterprise_data_fixture.create_user() + entry = AuditLogEntry.objects.create( + actor_id=user.id, + actor_name=user.email, + action_type=CreateWorkspaceActionType.type, + action_params={}, + action_timestamp=datetime.now(timezone.utc), + ) + entry.refresh_from_db() + + assert AuditLogEntry._meta.get_field("actor_id").column == "user_id" + assert AuditLogEntry._meta.get_field("actor_name").column == "user_email" + assert entry.actor_id == user.id + assert entry.user_id == user.id + assert entry.actor_type == UserSubjectType.type + assert entry.actor_name == user.email + + +@pytest.mark.django_db +def test_audit_log_handler_records_an_action_without_a_user(): + entry = AuditLogHandler.log_action( + None, + CreateWorkspaceActionType, + {}, + datetime.now(timezone.utc), + ActionCommandType.DO, + action_uuid="00000000-0000-0000-0000-000000000000", + ) + + assert entry.actor_id is None + assert entry.actor_type == UserSubjectType.type + assert entry.actor_name is None + + @pytest.mark.django_db @override_settings(DEBUG=True) def test_audit_log_handler_can_clear_entries_older_than( diff --git a/enterprise/backend/tests/baserow_enterprise_tests/audit_log/test_audit_log_migrations.py b/enterprise/backend/tests/baserow_enterprise_tests/audit_log/test_audit_log_migrations.py new file mode 100644 index 0000000000..56fe06d5ae --- /dev/null +++ b/enterprise/backend/tests/baserow_enterprise_tests/audit_log/test_audit_log_migrations.py @@ -0,0 +1,27 @@ +from django.db import connection + +import pytest + + +@pytest.mark.once_per_day_in_ci +def test_audit_log_actor_migration_retries_after_column_addition(migrator): + """An interrupted non-atomic migration can recreate its actor index on retry.""" + + migrator.migrate([("baserow_enterprise", "0067_graph_element")]) + + with connection.cursor() as cursor: + cursor.execute( + 'ALTER TABLE "baserow_enterprise_auditlogentry" ' + "ADD COLUMN \"actor_type\" varchar(255) NOT NULL DEFAULT 'auth.User'" + ) + cursor.execute( + 'ALTER TABLE "baserow_enterprise_auditlogexportjob" ' + "ADD COLUMN \"filter_actor_type\" varchar(255) DEFAULT 'auth.User'" + ) + + state = migrator.migrate([("baserow_enterprise", "0068_auditlogentry_agent")]) + AuditLogEntry = state.apps.get_model("baserow_enterprise", "AuditLogEntry") + AuditLogExportJob = state.apps.get_model("baserow_enterprise", "AuditLogExportJob") + + assert AuditLogEntry._meta.get_field("actor_type").db_default is not None + assert AuditLogExportJob._meta.get_field("filter_actor_type").db_default is not None diff --git a/enterprise/backend/tests/baserow_enterprise_tests/role/test_role_actions.py b/enterprise/backend/tests/baserow_enterprise_tests/role/test_role_actions.py index ee00258227..88e4a6fa0b 100644 --- a/enterprise/backend/tests/baserow_enterprise_tests/role/test_role_actions.py +++ b/enterprise/backend/tests/baserow_enterprise_tests/role/test_role_actions.py @@ -92,7 +92,10 @@ def test_batch_assign_role_description_for_one_item( assert AuditLogEntry.objects.count() == 1 log_entry = AuditLogEntry.objects.first() - assert log_entry.description.startswith("Role ") + assert log_entry.description == ( + f'Role EDITOR assigned to subject type "User" ({user2.id}) ' + f'on scope type "workspace" ({workspace.id}).' + ) @pytest.mark.django_db diff --git a/enterprise/web-frontend/modules/baserow_enterprise/components/auditLog/AuditLogActorDropdown.vue b/enterprise/web-frontend/modules/baserow_enterprise/components/auditLog/AuditLogActorDropdown.vue new file mode 100644 index 0000000000..1893057375 --- /dev/null +++ b/enterprise/web-frontend/modules/baserow_enterprise/components/auditLog/AuditLogActorDropdown.vue @@ -0,0 +1,74 @@ + + + diff --git a/enterprise/web-frontend/modules/baserow_enterprise/components/auditLog/AuditLogActorField.vue b/enterprise/web-frontend/modules/baserow_enterprise/components/auditLog/AuditLogActorField.vue new file mode 100644 index 0000000000..efc72c99e2 --- /dev/null +++ b/enterprise/web-frontend/modules/baserow_enterprise/components/auditLog/AuditLogActorField.vue @@ -0,0 +1,34 @@ + + + diff --git a/enterprise/web-frontend/modules/baserow_enterprise/components/auditLog/AuditLogActorTypeField.vue b/enterprise/web-frontend/modules/baserow_enterprise/components/auditLog/AuditLogActorTypeField.vue new file mode 100644 index 0000000000..60bdb709bc --- /dev/null +++ b/enterprise/web-frontend/modules/baserow_enterprise/components/auditLog/AuditLogActorTypeField.vue @@ -0,0 +1,32 @@ + + + diff --git a/enterprise/web-frontend/modules/baserow_enterprise/locales/en.json b/enterprise/web-frontend/modules/baserow_enterprise/locales/en.json index 8cc71c5dfd..0be567c985 100644 --- a/enterprise/web-frontend/modules/baserow_enterprise/locales/en.json +++ b/enterprise/web-frontend/modules/baserow_enterprise/locales/en.json @@ -207,13 +207,15 @@ "adminTitle": "Audit log", "workspaceTitle": "Audit log - {workspaceName}", "filterUserTitle": "User", + "filterActorTitle": "Actor", "filterWorkspaceTitle": "Workspace", "filterActionTypeTitle": "Event Type", "filterFromTimestampTitle": "From Date", "filterFromTimestamp": "From Date", "filterToTimestampTitle": "To Date", "filterToTimestamp": "To Date", - "user": "User", + "user": "Actor", + "actorType": "Actor type", "workspace": "Workspace", "actionType": "Event Type", "description": "Description", @@ -223,8 +225,12 @@ "exportModalTitle": "Export to CSV", "clearFilters": "Clear", "allUsers": "All Users", + "allActors": "All Actors", + "usersSection": "Users", + "agentsSection": "Agents", "allWorkspaces": "All Workspaces", - "allActionTypes": "All Event Types" + "allActionTypes": "All Event Types", + "actorDisplay": "{name} ({id})" }, "auditLogExportModal": { "title": "Export to CSV", diff --git a/enterprise/web-frontend/modules/baserow_enterprise/pages/auditLog.vue b/enterprise/web-frontend/modules/baserow_enterprise/pages/auditLog.vue index 316738aaaf..75792f7b45 100644 --- a/enterprise/web-frontend/modules/baserow_enterprise/pages/auditLog.vue +++ b/enterprise/web-frontend/modules/baserow_enterprise/pages/auditLog.vue @@ -34,15 +34,13 @@ class="audit-log__filters" :class="{ 'audit-log__filters--workspace': workspaceId }" > - - + + $t('auditLog.user'), - SimpleField, + AuditLogActorField, false, false, false, {}, '15' ), + new CrudTableColumn( + 'actor_type', + () => $t('auditLog.actorType'), + AuditLogActorTypeField, + false, + false, + false, + {}, + '10' + ), ] if (!workspaceId) { @@ -263,7 +274,7 @@ columns.push( false, false, {}, - '40' + '30' ), new CrudTableColumn( 'timestamp', @@ -310,6 +321,13 @@ const selectedWorkspaceId = computed(() => { return selected?.id || null }) +const selectedActor = computed(() => { + if (!filters.value.actor_id || !filters.value.actor_type) { + return null + } + return { id: filters.value.actor_id, type: filters.value.actor_type } +}) + // Watch watch(selectedWorkspaceId, (newValue, oldValue) => { if (newValue !== oldValue && workspaceId) { @@ -333,7 +351,7 @@ function setFilter(key, value) { } function clearFilters() { - userFilter.value?.clear() + actorFilter.value?.clear() workspaceFilter.value?.clear() typeFilter.value?.clear() fromTimestampFilter.value?.clear() @@ -341,12 +359,15 @@ function clearFilters() { filters.value = initFilters(workspaceId) } -function filterUser(userId) { - setFilter('user_id', userId) +function filterActor(actor) { + const nextFilters = _.omit(filters.value, ['actor_id', 'actor_type']) + filters.value = actor + ? { ...nextFilters, actor_id: actor.id, actor_type: actor.type } + : nextFilters } -function fetchUsers(page, search) { - return service.fetchUsers(page, search, workspaceId) +function fetchActors(page, search) { + return service.fetchActors(page, search, workspaceId) } function filterWorkspace(wsId) { diff --git a/enterprise/web-frontend/modules/baserow_enterprise/services/auditLog.js b/enterprise/web-frontend/modules/baserow_enterprise/services/auditLog.js index d77c0f659b..ef51dd9c75 100644 --- a/enterprise/web-frontend/modules/baserow_enterprise/services/auditLog.js +++ b/enterprise/web-frontend/modules/baserow_enterprise/services/auditLog.js @@ -2,16 +2,18 @@ import baseService from '@baserow/modules/core/crudTable/baseService' import jobService from '@baserow/modules/core/services/job' import { fetchWorkspaceOptions } from '@baserow/modules/core/services/admin/workspaces' -export default (client) => { - return Object.assign(baseService(client, `/audit-log/`), { - fetchUsers(page, search, workspaceId = null) { - const usersUrl = `/audit-log/users/` - const userPaginatedService = baseService(client, usersUrl) - const filters = {} - if (workspaceId) { - filters.workspace_id = workspaceId +export default (client) => + Object.assign(baseService(client, `/audit-log/`), { + fetchActors(page, search, workspaceId = null) { + const actorsUrl = `/audit-log/actors/` + const params = { + page, + search, } - return userPaginatedService.fetch(usersUrl, page, search, [], filters) + if (workspaceId) { + params.workspace_id = workspaceId + } + return client.get(actorsUrl, { params }) }, fetchWorkspaces(page, search) { return fetchWorkspaceOptions(client, page, search) @@ -47,4 +49,3 @@ export default (client) => { .slice(0, maxCount) }, }) -} diff --git a/enterprise/web-frontend/test/unit/enterprise/auditLog/__snapshots__/auditLogActorDropdown.spec.js.snap b/enterprise/web-frontend/test/unit/enterprise/auditLog/__snapshots__/auditLogActorDropdown.spec.js.snap new file mode 100644 index 0000000000..bc31a9e90a --- /dev/null +++ b/enterprise/web-frontend/test/unit/enterprise/auditLog/__snapshots__/auditLogActorDropdown.spec.js.snap @@ -0,0 +1,42 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`AuditLogActorDropdown > renders users and agents in separate sections and selects an agent 1`] = ` +"" +`; diff --git a/enterprise/web-frontend/test/unit/enterprise/auditLog/auditLogActorDropdown.spec.js b/enterprise/web-frontend/test/unit/enterprise/auditLog/auditLogActorDropdown.spec.js new file mode 100644 index 0000000000..bb31bae5ec --- /dev/null +++ b/enterprise/web-frontend/test/unit/enterprise/auditLog/auditLogActorDropdown.spec.js @@ -0,0 +1,66 @@ +import { mountSuspended } from '@nuxt/test-utils/runtime' +import flushPromises from 'flush-promises' + +import PaginatedDropdown from '@baserow/modules/core/components/PaginatedDropdown' +import AuditLogActorDropdown from '@baserow_enterprise/components/auditLog/AuditLogActorDropdown' + +const actors = [ + { + id: 'auth.User:1', + actor_id: 1, + actor_type: 'auth.User', + value: 'user@example.com', + }, + { + id: 'core.Agent:1', + actor_id: 1, + actor_type: 'core.Agent', + value: 'Row writer', + }, +] + +async function mountComponent(fetchPage = null) { + return await mountSuspended(AuditLogActorDropdown, { + props: { + fetchPage: + fetchPage || + (() => + Promise.resolve({ data: { count: actors.length, results: actors } })), + }, + global: { + mocks: { + $t(key) { + return { + 'auditLog.allActors': 'All Actors', + }[key] + }, + }, + }, + }) +} + +describe('AuditLogActorDropdown', () => { + test('renders users and agents in separate sections and selects an agent', async () => { + const wrapper = await mountComponent() + await wrapper.findComponent(PaginatedDropdown).vm.fetch() + await flushPromises() + + expect(wrapper.html()).toMatchSnapshot() + + await wrapper.findAll('.select__item-link')[2].trigger('click') + + expect(wrapper.emitted('input')).toEqual([[{ id: 1, type: 'core.Agent' }]]) + }) + + test('forwards the search query to the actor endpoint', async () => { + const fetchPage = vi.fn(() => + Promise.resolve({ data: { count: 0, results: [] } }) + ) + const wrapper = await mountComponent(fetchPage) + const dropdown = wrapper.findComponent(PaginatedDropdown) + + await dropdown.vm.fetch(1, 'robot') + + expect(fetchPage).toHaveBeenCalledWith(1, 'robot') + }) +}) diff --git a/enterprise/web-frontend/test/unit/enterprise/auditLog/auditLogActorField.spec.js b/enterprise/web-frontend/test/unit/enterprise/auditLog/auditLogActorField.spec.js new file mode 100644 index 0000000000..8bcc09685f --- /dev/null +++ b/enterprise/web-frontend/test/unit/enterprise/auditLog/auditLogActorField.spec.js @@ -0,0 +1,41 @@ +import { mountSuspended } from '@nuxt/test-utils/runtime' + +import AuditLogActorField from '@baserow_enterprise/components/auditLog/AuditLogActorField' + +async function mountComponent(actor, user = '') { + return await mountSuspended(AuditLogActorField, { + props: { + row: { actor, user }, + column: { key: 'user' }, + }, + global: { + mocks: { + $t(key, params) { + if (key === 'auditLog.actorDisplay') { + return `${params.name} (${params.id})` + } + return key + }, + }, + }, + }) +} + +describe('AuditLogActorField', () => { + test.each([ + ['auth.User', 'user@example.com', 12, 'user@example.com (12)'], + ['core.Agent', 'Row writer', 34, 'Row writer (34)'], + ['custom.Robot', 'Robot', 56, 'Robot (56)'], + ])('renders the %s actor type', async (type, name, id, expected) => { + const wrapper = await mountComponent({ type, name, id }) + + expect(wrapper.text()).toBe(expected) + expect(wrapper.attributes('title')).toBe(expected) + }) + + test('keeps the legacy display while an actor is unavailable', async () => { + const wrapper = await mountComponent(null, 'Legacy actor') + + expect(wrapper.text()).toBe('Legacy actor') + }) +}) diff --git a/enterprise/web-frontend/test/unit/enterprise/auditLog/auditLogActorTypeField.spec.js b/enterprise/web-frontend/test/unit/enterprise/auditLog/auditLogActorTypeField.spec.js new file mode 100644 index 0000000000..bfb56b5d7a --- /dev/null +++ b/enterprise/web-frontend/test/unit/enterprise/auditLog/auditLogActorTypeField.spec.js @@ -0,0 +1,51 @@ +import { mountSuspended } from '@nuxt/test-utils/runtime' + +import AuditLogActorTypeField from '@baserow_enterprise/components/auditLog/AuditLogActorTypeField' + +const actorTypeNames = { + 'auth.User': 'User', + 'core.Agent': 'Agent', +} + +async function mountComponent(type) { + return await mountSuspended(AuditLogActorTypeField, { + props: { + row: { actor: type ? { type } : null }, + column: { key: 'actor_type' }, + }, + global: { + mocks: { + $registry: { + exists(namespace, registeredType) { + return namespace === 'subject' && registeredType in actorTypeNames + }, + get(namespace, registeredType) { + return { + getTypeDisplayName: () => actorTypeNames[registeredType], + } + }, + }, + }, + }, + }) +} + +describe('AuditLogActorTypeField', () => { + test.each([ + ['auth.User', 'User'], + ['core.Agent', 'Agent'], + ['custom.Robot', 'custom.Robot'], + ])('renders the %s actor type', async (type, expected) => { + const wrapper = await mountComponent(type) + + expect(wrapper.text()).toBe(expected) + expect(wrapper.attributes('title')).toBe(expected) + }) + + test('renders an empty value for a legacy actor', async () => { + const wrapper = await mountComponent(null) + + expect(wrapper.text()).toBe('') + expect(wrapper.attributes('title')).toBe('') + }) +}) diff --git a/enterprise/web-frontend/test/unit/enterprise/memberRoles/selectAgentsList.spec.js b/enterprise/web-frontend/test/unit/enterprise/memberRoles/selectAgentsList.spec.js index d6559a53b7..1a76c947a2 100644 --- a/enterprise/web-frontend/test/unit/enterprise/memberRoles/selectAgentsList.spec.js +++ b/enterprise/web-frontend/test/unit/enterprise/memberRoles/selectAgentsList.spec.js @@ -127,9 +127,6 @@ describe('SelectAgentsList', () => { const wrapper = await mountSuspended(RoleAssignmentModal, { props: { agents: [agent], scopeType: 'application' }, global: { - mocks: { - $featureFlagIsEnabled: (flag) => flag === 'agents', - }, stubs: { Modal: { methods: { hide() {} }, @@ -157,23 +154,4 @@ describe('SelectAgentsList', () => { await wrapper.find('.select-agent').trigger('click') expect(wrapper.emitted('invite-agents')).toEqual([[[agent], role]]) }) - - test('hides the Agents tab when the feature flag is disabled', async () => { - const wrapper = await mountSuspended(RoleAssignmentModal, { - props: { scopeType: 'application' }, - global: { - mocks: { - $featureFlagIsEnabled: () => false, - }, - stubs: { - Modal: { template: '
' }, - SelectMembersList: true, - SelectTeamsList: true, - SelectAgentsList: true, - }, - }, - }) - - expect(wrapper.text()).not.toContain('roleAssignmentModal.agentsTab') - }) }) diff --git a/enterprise/web-frontend/test/unit/enterprise/services/auditLog.spec.js b/enterprise/web-frontend/test/unit/enterprise/services/auditLog.spec.js new file mode 100644 index 0000000000..6cf34b7197 --- /dev/null +++ b/enterprise/web-frontend/test/unit/enterprise/services/auditLog.spec.js @@ -0,0 +1,15 @@ +import { describe, expect, test, vi } from 'vitest' + +import AuditLogService from '@baserow_enterprise/services/auditLog' + +describe('audit log service', () => { + test('fetchActors uses the dedicated audit log actor endpoint', () => { + const client = { get: vi.fn() } + + AuditLogService(client).fetchActors(2, 'robot', 5) + + expect(client.get).toHaveBeenCalledWith('/audit-log/actors/', { + params: { page: 2, search: 'robot', workspace_id: 5 }, + }) + }) +}) diff --git a/justfile b/justfile index 6bafd61432..f99052a703 100644 --- a/justfile +++ b/justfile @@ -582,6 +582,7 @@ _dc_help: [doc("Docker compose (dev): just dc-dev ")] dc-dev *ARGS: #!/usr/bin/env bash + {{ _load_env }} if [ -z "{{ ARGS }}" ]; then just _dc_help else diff --git a/premium/backend/src/baserow_premium/row_comments/row_metadata_types.py b/premium/backend/src/baserow_premium/row_comments/row_metadata_types.py index 4506631e97..50a1bf6100 100644 --- a/premium/backend/src/baserow_premium/row_comments/row_metadata_types.py +++ b/premium/backend/src/baserow_premium/row_comments/row_metadata_types.py @@ -1,5 +1,6 @@ from typing import Any, Dict, List +from django.contrib.auth.models import AbstractUser from django.db.models import Count from rest_framework import serializers @@ -47,10 +48,10 @@ class RowCommentsNotificationModeMetadataType(RowMetadataType): """ Returns a dictionary keyed by row id with the value being the notification mode for the user and row. - If no or an anonymous user is provided then an empty dict is returned. + If no Django user is provided then an empty dict is returned. """ - if not user or not user.id: + if not isinstance(user, AbstractUser) or not user.id: return {} return { diff --git a/premium/backend/tests/baserow_premium_tests/dashboard/test_dashboard_application_types_charts.py b/premium/backend/tests/baserow_premium_tests/dashboard/test_dashboard_application_types_charts.py index 7b3bbfcfa2..696671a7be 100644 --- a/premium/backend/tests/baserow_premium_tests/dashboard/test_dashboard_application_types_charts.py +++ b/premium/backend/tests/baserow_premium_tests/dashboard/test_dashboard_application_types_charts.py @@ -81,7 +81,8 @@ def test_dashboard_export_serialized_with_chart_widget(premium_data_fixture): "type": "dashboard", "integrations": [ { - "authorized_user": user.email, + "authorized_subject_type": "auth.User", + "authorized_subject_id": user.id, "id": integration.id, "name": "", "order": "1.00000000000000000000", @@ -167,7 +168,8 @@ def test_dashboard_import_serialized_with_widgets(premium_data_fixture): "type": "dashboard", "integrations": [ { - "authorized_user": user.email, + "authorized_subject_type": "auth.User", + "authorized_subject_id": user.id, "id": 1, "name": "IntegrationName", "order": "1.00000000000000000000", @@ -239,7 +241,7 @@ def test_dashboard_import_serialized_with_widgets(premium_data_fixture): assert integration.content_type == ContentType.objects.get_for_model( LocalBaserowIntegration ) - assert integration.authorized_user.id == user.id + assert integration.authorized_subject == user assert integration.name == "IntegrationName" assert integration.order == Decimal("1.0") @@ -341,7 +343,8 @@ def test_dashboard_export_serialized_with_chart_widget_config(premium_data_fixtu "type": "dashboard", "integrations": [ { - "authorized_user": user.email, + "authorized_subject_type": "auth.User", + "authorized_subject_id": user.id, "id": integration.id, "name": "", "order": "1.00000000000000000000", @@ -427,7 +430,8 @@ def test_dashboard_import_serialized_with_widget_config(premium_data_fixture): "type": "dashboard", "integrations": [ { - "authorized_user": user.email, + "authorized_subject_type": "auth.User", + "authorized_subject_id": user.id, "id": 1, "name": "IntegrationName", "order": "1.00000000000000000000", @@ -495,7 +499,7 @@ def test_dashboard_import_serialized_with_widget_config(premium_data_fixture): assert integration.content_type == ContentType.objects.get_for_model( LocalBaserowIntegration ) - assert integration.authorized_user.id == user.id + assert integration.authorized_subject == user assert integration.name == "IntegrationName" assert integration.order == Decimal("1.0") @@ -583,7 +587,8 @@ def test_dashboard_export_serialized_with_default_chart_type(premium_data_fixtur "type": "dashboard", "integrations": [ { - "authorized_user": user.email, + "authorized_subject_type": "auth.User", + "authorized_subject_id": user.id, "id": integration.id, "name": "", "order": "1.00000000000000000000", @@ -655,7 +660,8 @@ def test_dashboard_import_serialized_with_default_chart_type(premium_data_fixtur "type": "dashboard", "integrations": [ { - "authorized_user": user.email, + "authorized_subject_type": None, + "authorized_subject_id": None, "id": 1, "name": "IntegrationName", "order": "1.00000000000000000000", diff --git a/premium/backend/tests/baserow_premium_tests/dashboard/test_pie_chart_widget_type.py b/premium/backend/tests/baserow_premium_tests/dashboard/test_pie_chart_widget_type.py index 36d7924043..b9c1a9e9c3 100644 --- a/premium/backend/tests/baserow_premium_tests/dashboard/test_pie_chart_widget_type.py +++ b/premium/backend/tests/baserow_premium_tests/dashboard/test_pie_chart_widget_type.py @@ -137,7 +137,8 @@ def test_dashboard_export_serialized_with_pie_chart_widget_config(premium_data_f "type": "dashboard", "integrations": [ { - "authorized_user": user.email, + "authorized_subject_type": "auth.User", + "authorized_subject_id": user.id, "id": integration.id, "name": "", "order": "1.00000000000000000000", @@ -223,7 +224,8 @@ def test_dashboard_import_serialized_with_pie_chart_widget_config(premium_data_f "type": "dashboard", "integrations": [ { - "authorized_user": user.email, + "authorized_subject_type": "auth.User", + "authorized_subject_id": user.id, "id": 1, "name": "IntegrationName", "order": "1.00000000000000000000", @@ -291,7 +293,7 @@ def test_dashboard_import_serialized_with_pie_chart_widget_config(premium_data_f assert integration.content_type == ContentType.objects.get_for_model( LocalBaserowIntegration ) - assert integration.authorized_user.id == user.id + assert integration.authorized_subject == user assert integration.name == "IntegrationName" assert integration.order == Decimal("1.0") diff --git a/web-frontend/modules/builder/realtime.js b/web-frontend/modules/builder/realtime.js index 18d40132bb..b3774791b3 100644 --- a/web-frontend/modules/builder/realtime.js +++ b/web-frontend/modules/builder/realtime.js @@ -28,7 +28,45 @@ const getApplicationContext = (store, applicationId) => { return { application } } +const redispatchForAuthorizedAgent = (store, { workspaceId, agentId }) => { + store.getters['application/getAll'] + .filter( + (application) => + application.type === 'builder' && + application.workspace?.id === workspaceId + ) + .forEach((builder) => { + builder.integrations + .filter( + (integration) => + integration.type === 'local_baserow' && + integration.authorized_subject?.type === 'core.Agent' && + integration.authorized_subject.id === agentId + ) + .forEach((integration) => { + store.dispatch('dataSource/redispatchForIntegration', { + builder, + integrationId: integration.id, + }) + }) + }) +} + export const registerRealtimeEvents = (realtime) => { + realtime.registerEvent('agent_created', ({ store }, data) => { + redispatchForAuthorizedAgent(store, { + workspaceId: data.workspace_id, + agentId: data.agent.id, + }) + }) + + realtime.registerEvent('agent_deleted', ({ store }, data) => { + redispatchForAuthorizedAgent(store, { + workspaceId: data.workspace_id, + agentId: data.agent_id, + }) + }) + // Page events realtime.registerEvent('page_created', ({ store }, data) => { const builder = store.getters['application/get'](data.page.builder_id) diff --git a/web-frontend/modules/core/assets/scss/components/tabs.scss b/web-frontend/modules/core/assets/scss/components/tabs.scss index e96e000e34..152e4a3ec1 100644 --- a/web-frontend/modules/core/assets/scss/components/tabs.scss +++ b/web-frontend/modules/core/assets/scss/components/tabs.scss @@ -61,8 +61,12 @@ } .tabs__link { - display: block; + display: flex; + align-items: center; + justify-content: center; + gap: 6px; padding: 12px 0; + line-height: 20px; color: $palette-neutral-900; .tabs--large & { diff --git a/web-frontend/modules/core/components/PaginatedDropdown.vue b/web-frontend/modules/core/components/PaginatedDropdown.vue index 2b1598e531..bb72b53a04 100644 --- a/web-frontend/modules/core/components/PaginatedDropdown.vue +++ b/web-frontend/modules/core/components/PaginatedDropdown.vue @@ -53,24 +53,26 @@ :name="emptyItemDisplayName" :value="null" > - - + + + +
diff --git a/web-frontend/modules/core/components/Tab.vue b/web-frontend/modules/core/components/Tab.vue index a1f8b00a19..f7ef4b7929 100644 --- a/web-frontend/modules/core/components/Tab.vue +++ b/web-frontend/modules/core/components/Tab.vue @@ -46,6 +46,12 @@ export default { required: false, default: null, }, + developmentStage: { + type: String, + required: false, + default: null, + validator: (value) => value === null || ['alpha', 'beta'].includes(value), + }, highlight: { type: [String, null], required: false, diff --git a/web-frontend/modules/core/components/Tabs.vue b/web-frontend/modules/core/components/Tabs.vue index a537aa23ac..7c6eb883b5 100644 --- a/web-frontend/modules/core/components/Tabs.vue +++ b/web-frontend/modules/core/components/Tabs.vue @@ -36,6 +36,10 @@ > {{ tab.title }} + @@ -46,8 +50,11 @@ diff --git a/web-frontend/modules/integrations/localBaserow/integrationTypes.js b/web-frontend/modules/integrations/localBaserow/integrationTypes.js index 8ce7b16e3b..0c0bf58564 100644 --- a/web-frontend/modules/integrations/localBaserow/integrationTypes.js +++ b/web-frontend/modules/integrations/localBaserow/integrationTypes.js @@ -20,13 +20,24 @@ export class LocalBaserowIntegrationType extends IntegrationType { } getSummary(integration) { - if (!integration.authorized_user) { + const subject = integration.authorized_subject + // A trashed agent can't authenticate, so the integration isn't configured. + if (!subject || subject.trashed) { return this.app.$i18n.t('localBaserowIntegrationType.localBaserowNoUser') } + const subjectType = this.app.$registry.get('subject', subject.type) + const displayName = subjectType.getDisplayName(subject) + if (!subjectType.isUser()) { + return this.app.$i18n.t( + 'localBaserowIntegrationType.localBaserowSubjectSummary', + { type: subjectType.getTypeDisplayName(), name: displayName } + ) + } + return this.app.$i18n.t('localBaserowIntegrationType.localBaserowSummary', { - name: integration.authorized_user.first_name, - username: integration.authorized_user.username, + name: displayName, + username: subject.username, }) } @@ -41,10 +52,43 @@ export class LocalBaserowIntegrationType extends IntegrationType { getDefaultValues() { const user = this.app.$store.getters['auth/getUserObject'] return { - authorized_user: { username: user.username, first_name: user.first_name }, + authorized_subject: { + id: user.id, + type: 'auth.User', + username: user.username, + first_name: user.first_name, + }, + authorized_subject_id: user.id, + authorized_subject_type: 'auth.User', } } + getUpdatedValues(values, initialValues) { + const updatedValues = super.getUpdatedValues(values, initialValues) + const authorizationKeys = [ + 'authorized_subject_id', + 'authorized_subject_type', + ] + + if (authorizationKeys.some((key) => key in updatedValues)) { + for (const key of authorizationKeys) { + updatedValues[key] = values[key] + } + } + + return updatedValues + } + + getErrorMessage(integration) { + if ( + integration.authorized_subject?.type === 'core.Agent' && + integration.authorized_subject.trashed + ) { + return this.app.$i18n.t('localBaserowIntegrationType.errorTrashedAgent') + } + return super.getErrorMessage(integration) + } + getOrder() { return 10 } diff --git a/web-frontend/modules/integrations/localBaserow/serviceTypes.js b/web-frontend/modules/integrations/localBaserow/serviceTypes.js index 294afd8d90..c7b5d3ca12 100644 --- a/web-frontend/modules/integrations/localBaserow/serviceTypes.js +++ b/web-frontend/modules/integrations/localBaserow/serviceTypes.js @@ -90,6 +90,10 @@ export class LocalBaserowTableServiceType extends ServiceType { return this.app.$i18n.t('serviceType.errorMisconfiguredIntegration') } } + const inheritedError = super.getErrorMessage({ service, application }) + if (inheritedError) { + return inheritedError + } if (!service.table_id) { return this.app.$i18n.t('serviceType.errorNoTableSelected') } diff --git a/web-frontend/modules/integrations/locales/en.json b/web-frontend/modules/integrations/locales/en.json index 1a2c781b2d..a714445977 100644 --- a/web-frontend/modules/integrations/locales/en.json +++ b/web-frontend/modules/integrations/locales/en.json @@ -11,7 +11,9 @@ }, "localBaserowIntegrationType": { "localBaserowSummary": "Local Baserow - {name}, {username}", + "localBaserowSubjectSummary": "Local Baserow - {type}: {name}", "localBaserowNoUser": "Local Baserow - Not configured", + "errorTrashedAgent": "The authorized agent has been trashed", "localBaserowWarning": "Authorizing your account gives everyone who has edit permissions to the application full access to the data you have access to. It's possible to create a second user, give the right permissions and use that one." }, "aiIntegrationType": { @@ -118,8 +120,9 @@ "localBaserow": "Baserow table authentication" }, "localBaserowForm": { - "user": "User", - "userMessage": "By creating this connection, you're authorizing the application to use your account to make changes in your local Baserow workspace." + "subject": "Authenticate as", + "currentUser": "My user account", + "subjectMessage": "Actions use the permissions of the selected user or agent. Agent actions are identified as such in the audit log." }, "aiForm": { "description": "Configure AI provider settings for this integration. By default, workspace AI settings are inherited.", diff --git a/web-frontend/test/unit/automation/nodeTypes.spec.js b/web-frontend/test/unit/automation/nodeTypes.spec.js index 9afe35254a..f5d68fc4d5 100644 --- a/web-frontend/test/unit/automation/nodeTypes.spec.js +++ b/web-frontend/test/unit/automation/nodeTypes.spec.js @@ -178,10 +178,10 @@ describe('Automation node types', () => { const registry = testApp.getRegistry() expect( - ['start_workflow', 'iterator', 'router'].map( + ['start_workflow', 'response', 'iterator', 'router', 'goto'].map( (type) => registry.get('node', type).group.id ) - ).toEqual(['workflow', 'workflow', 'workflow']) + ).toEqual(['workflow', 'workflow', 'workflow', 'workflow', 'workflow']) }) test('exposes search aliases for the Iterator and Go to nodes', () => { diff --git a/web-frontend/test/unit/builder/realtime.spec.js b/web-frontend/test/unit/builder/realtime.spec.js index 17828f2dd8..1f745cc741 100644 --- a/web-frontend/test/unit/builder/realtime.spec.js +++ b/web-frontend/test/unit/builder/realtime.spec.js @@ -310,6 +310,69 @@ describe('builder realtime integration events', () => { }) }) +describe('builder realtime agent events', () => { + const matchingIntegration = { + id: 5, + type: 'local_baserow', + authorized_subject: { id: 10, type: 'core.Agent' }, + } + const builder = { + id: 1, + type: 'builder', + workspace: { id: 2 }, + integrations: [matchingIntegration], + } + + const buildAppStore = () => ({ + getters: { + 'application/getAll': [ + builder, + { + id: 2, + type: 'builder', + workspace: { id: 3 }, + integrations: [matchingIntegration], + }, + { + id: 3, + type: 'automation', + workspace: { id: 2 }, + integrations: [matchingIntegration], + }, + { + id: 4, + type: 'builder', + workspace: { id: 2 }, + integrations: [ + { + ...matchingIntegration, + authorized_subject: { id: 11, type: 'core.Agent' }, + }, + ], + }, + ], + }, + dispatch: vi.fn(), + }) + + test.each([ + ['agent_created', { workspace_id: 2, agent: { id: 10 } }], + ['agent_deleted', { workspace_id: 2, agent_id: 10 }], + ])( + '%s re-dispatches data sources using the authorized agent', + (event, data) => { + const handlers = getHandlers() + const store = buildAppStore() + + handlers[event]({ store }, data) + + expect( + dispatchedWith(store, 'dataSource/redispatchForIntegration') + ).toEqual([{ builder, integrationId: matchingIntegration.id }]) + } + ) +}) + describe('builder realtime user source events', () => { const application = { id: 1 } diff --git a/web-frontend/test/unit/core/components/integrations/integrationCreateEditModal.spec.js b/web-frontend/test/unit/core/components/integrations/integrationCreateEditModal.spec.js new file mode 100644 index 0000000000..e9c704c657 --- /dev/null +++ b/web-frontend/test/unit/core/components/integrations/integrationCreateEditModal.spec.js @@ -0,0 +1,82 @@ +import { TestApp } from '@baserow/test/helpers/testApp' +import IntegrationCreateEditModal from '@baserow/modules/core/components/integrations/IntegrationCreateEditModal' + +describe('IntegrationCreateEditModal', () => { + let testApp = null + + beforeEach(() => { + testApp = new TestApp() + testApp.store.state.auth.user = { id: 1 } + }) + + afterEach(async () => { + await testApp.afterEach() + }) + + test('only sends values changed from the initial form values on update', async () => { + const application = { id: 1, workspace: { id: 1 }, integrations: [] } + const integration = { + id: 1, + type: 'local_baserow', + name: 'Teammate integration', + authorized_subject: { + id: 2, + type: 'auth.User', + first_name: 'Teammate', + username: 'teammate@example.com', + }, + } + application.integrations = [integration] + testApp.mock.onPatch('/integration/1/').reply((config) => { + expect(JSON.parse(config.data)).toEqual({ name: 'Renamed integration' }) + return [200, { ...integration, name: 'Renamed integration' }] + }) + const wrapper = await testApp.mount(IntegrationCreateEditModal, { + props: { application, integration }, + }) + + wrapper.vm.show() + await wrapper.vm.$nextTick() + await wrapper.vm.$nextTick() + await wrapper.vm.submit({ + name: 'Renamed integration', + authorized_subject_id: 2, + authorized_subject_type: 'auth.User', + }) + }) + + test('sends authorization subject values together when either changes', async () => { + const application = { id: 1, workspace: { id: 1 }, integrations: [] } + const integration = { + id: 1, + type: 'local_baserow', + name: 'Teammate integration', + authorized_subject: { + id: 2, + type: 'auth.User', + first_name: 'Teammate', + username: 'teammate@example.com', + }, + } + application.integrations = [integration] + testApp.mock.onPatch('/integration/1/').reply((config) => { + expect(JSON.parse(config.data)).toEqual({ + authorized_subject_id: 1, + authorized_subject_type: 'auth.User', + }) + return [200, integration] + }) + const wrapper = await testApp.mount(IntegrationCreateEditModal, { + props: { application, integration }, + }) + + wrapper.vm.show() + await wrapper.vm.$nextTick() + await wrapper.vm.$nextTick() + await wrapper.vm.submit({ + name: 'Teammate integration', + authorized_subject_id: 1, + authorized_subject_type: 'auth.User', + }) + }) +}) diff --git a/web-frontend/test/unit/core/components/settings/agents/manageAgentModal.spec.js b/web-frontend/test/unit/core/components/settings/agents/manageAgentModal.spec.js index 83370eba9f..faeb93b38c 100644 --- a/web-frontend/test/unit/core/components/settings/agents/manageAgentModal.spec.js +++ b/web-frontend/test/unit/core/components/settings/agents/manageAgentModal.spec.js @@ -325,6 +325,46 @@ describe('ManageAgentModal', () => { wrapper.unmount() }) + test('does not create an agent with a whitespace-only name', async () => { + const dispatch = vi.fn() + const wrapper = await mountSuspended(ManageAgentModal, { + props: { workspace: { id: 12, _: { roles: [] } } }, + global: { + mocks: { + $registry: { getOrderedList: () => [generalSetting] }, + $store: { dispatch }, + $t: (key) => key, + }, + stubs: { + Modal: modalStub, + Error: true, + FormGroup: { template: '
' }, + FormInput: { + props: ['modelValue'], + emits: ['update:modelValue'], + template: + '', + methods: { focus() {} }, + }, + Button: ButtonStub, + WorkspaceRoleSelector: WorkspaceRoleSelectorStub, + }, + }, + }) + + try { + await wrapper.find('.name-input').setValue(' ') + const create = wrapper + .findAll('button') + .find((button) => button.text() === 'agents.create') + expect(create.attributes('disabled')).toBeDefined() + await wrapper.find('form').trigger('submit') + expect(dispatch).not.toHaveBeenCalled() + } finally { + wrapper.unmount() + } + }) + test('hides commercial information in its role selector', async () => { const wrapper = await mountSuspended(ManageAgentModal, { props: { diff --git a/web-frontend/test/unit/core/components/tabs.spec.js b/web-frontend/test/unit/core/components/tabs.spec.js index a43ed5abd5..f97a16e8a6 100644 --- a/web-frontend/test/unit/core/components/tabs.spec.js +++ b/web-frontend/test/unit/core/components/tabs.spec.js @@ -64,4 +64,17 @@ describe('Tabs', () => { expect(tabItem.attributes('data-highlight')).toBe('tour-target') expect(tabItem.get('.tabs__link').text()).toBe('Agents') }) + + it('renders a development badge next to the tab title', async () => { + const wrapper = await mountSuspended(Tabs, { + components: { + Tab, + }, + slots: { + default: 'Content', + }, + }) + + expect(wrapper.get('.tabs__link .badge').text()).toContain('common.beta') + }) }) diff --git a/web-frontend/test/unit/core/store/agent.spec.js b/web-frontend/test/unit/core/store/agent.spec.js index dccc0a3eda..f975550d6c 100644 --- a/web-frontend/test/unit/core/store/agent.spec.js +++ b/web-frontend/test/unit/core/store/agent.spec.js @@ -131,4 +131,32 @@ describe('Agent store', () => { agentId: 1, }) }) + + test('force actions keep the workspace members count in sync', () => { + const state = makeState() + const commit = (type, payload) => mutations[type](state, payload) + const dispatch = vi.fn() + const agent = { id: 1, workspace_id: 42, name: 'Writer' } + + actions.forceCreate({ commit, state, dispatch }, agent) + actions.forceCreate({ commit, state, dispatch }, agent) + actions.forceDelete( + { commit, state, dispatch }, + { workspaceId: 42, agentId: 1 } + ) + + expect(dispatch).toHaveBeenNthCalledWith( + 1, + 'workspace/updateAgentsCount', + { workspaceId: 42, delta: 1 }, + { root: true } + ) + expect(dispatch).toHaveBeenNthCalledWith( + 2, + 'workspace/updateAgentsCount', + { workspaceId: 42, delta: -1 }, + { root: true } + ) + expect(dispatch).toHaveBeenCalledTimes(2) + }) }) diff --git a/web-frontend/test/unit/core/store/integration.spec.js b/web-frontend/test/unit/core/store/integration.spec.js index b76bef3ce0..5a160fbec3 100644 --- a/web-frontend/test/unit/core/store/integration.spec.js +++ b/web-frontend/test/unit/core/store/integration.spec.js @@ -307,4 +307,40 @@ describe('integration store', () => { // It gave up rather than asking forever. expect(created).toBe(3) }) + + test('update merges server-generated fields into the integration', async () => { + const integration = { + id: 1, + type: 'local_baserow', + name: 'Local Baserow', + authorized_subject: { + id: 2, + type: 'auth.User', + username: 'user@example.com', + }, + context_data: { databases: [] }, + } + const application = { id: 10, integrations: [integration] } + const updatedIntegration = { + ...integration, + authorized_subject: { + id: 3, + type: 'core.Agent', + name: 'Writer agent', + }, + context_data: { databases: [{ id: 4, name: 'Agent database' }] }, + } + testApp.mock.onPatch('/integration/1/').reply(200, updatedIntegration) + + await testApp.store.dispatch('integration/update', { + application, + integrationId: integration.id, + values: { + authorized_subject_id: 3, + authorized_subject_type: 'core.Agent', + }, + }) + + expect(application.integrations).toEqual([updatedIntegration]) + }) }) diff --git a/web-frontend/test/unit/core/subjectTypes.spec.js b/web-frontend/test/unit/core/subjectTypes.spec.js index 92349e483a..edcc19977b 100644 --- a/web-frontend/test/unit/core/subjectTypes.spec.js +++ b/web-frontend/test/unit/core/subjectTypes.spec.js @@ -1,11 +1,13 @@ import { AgentSubjectType, + AnonymousUserSubjectType, UserSubjectType, } from '@baserow/modules/core/subjectTypes' const names = { 'subjectType.user': 'User', 'subjectType.users': 'Users', + 'subjectType.anonymousUser': 'Anonymous user', 'subjectType.agent': 'Agent', 'subjectType.agents': 'Agents', } @@ -21,6 +23,7 @@ const context = { describe('SubjectType', () => { test.each([ [new UserSubjectType(context), 'User'], + [new AnonymousUserSubjectType(context), 'Anonymous user'], [new AgentSubjectType(context), 'Agent'], ])('resolves its frontend display name', (subjectType, expected) => { expect(subjectType.getTypeDisplayName()).toBe(expected) @@ -28,6 +31,7 @@ describe('SubjectType', () => { test.each([ [new UserSubjectType(context), 'Users'], + [new AnonymousUserSubjectType(context), 'Anonymous user'], [new AgentSubjectType(context), 'Agents'], ])('resolves its plural frontend display name', (subjectType, expected) => { expect(subjectType.getPluralTypeDisplayName()).toBe(expected) @@ -35,6 +39,7 @@ describe('SubjectType', () => { test.each([ [new UserSubjectType(context), 'blue'], + [new AnonymousUserSubjectType(context), 'blue'], [new AgentSubjectType(context), 'purple'], ])('provides its avatar color', (subjectType, expected) => { expect(subjectType.avatarColor).toBe(expected) @@ -43,6 +48,7 @@ describe('SubjectType', () => { test.each([ [new UserSubjectType(context), { id: 1, user_id: 2 }, 2], [new UserSubjectType(context), { id: 1 }, 1], + [new AnonymousUserSubjectType(context), { id: 1 }, 1], [new AgentSubjectType(context), { id: 1 }, 1], ])('resolves a subject id', (subjectType, subject, expected) => { expect(subjectType.getId(subject)).toBe(expected) diff --git a/web-frontend/test/unit/core/utils/workspace.spec.js b/web-frontend/test/unit/core/utils/workspace.spec.js new file mode 100644 index 0000000000..78fbf4d464 --- /dev/null +++ b/web-frontend/test/unit/core/utils/workspace.spec.js @@ -0,0 +1,18 @@ +import { describe, expect, test } from 'vitest' + +import { getWorkspaceMembersCount } from '@baserow/modules/core/utils/workspace' + +describe('workspace utils', () => { + const workspace = { + users: [{ id: 1 }], + agents_count: 1, + } + + test('includes agents when they are visible', () => { + expect(getWorkspaceMembersCount(workspace, true)).toBe(2) + }) + + test('only includes users when agents are not visible', () => { + expect(getWorkspaceMembersCount(workspace, false)).toBe(1) + }) +}) diff --git a/web-frontend/test/unit/core/workspaceSettingsPageTypes.spec.js b/web-frontend/test/unit/core/workspaceSettingsPageTypes.spec.js index f35b855d1a..ae29a3be7b 100644 --- a/web-frontend/test/unit/core/workspaceSettingsPageTypes.spec.js +++ b/web-frontend/test/unit/core/workspaceSettingsPageTypes.spec.js @@ -3,27 +3,25 @@ import { describe, expect, test, vi } from 'vitest' import { AgentsWorkspaceSettingsPageType } from '@baserow/modules/core/workspaceSettingsPageTypes' describe('AgentsWorkspaceSettingsPageType', () => { - test('is only visible when the feature flag and permission are enabled', () => { - const featureFlagIsEnabled = vi.fn().mockReturnValue(false) + test('is only visible when the permission is enabled', () => { const hasPermission = vi.fn().mockReturnValue(true) const pageType = new AgentsWorkspaceSettingsPageType({ app: { - $featureFlagIsEnabled: featureFlagIsEnabled, + $featureFlagIsEnabled: () => true, $hasPermission: hasPermission, }, }) const workspace = { id: 42 } - expect(pageType.hasPermission(workspace)).toBe(false) - expect(featureFlagIsEnabled).toHaveBeenCalledWith('agents') - expect(hasPermission).not.toHaveBeenCalled() - - featureFlagIsEnabled.mockReturnValue(true) + expect(pageType.developmentStage).toBe('beta') expect(pageType.hasPermission(workspace)).toBe(true) expect(hasPermission).toHaveBeenCalledWith( 'workspace.list_agents', workspace, workspace.id ) + + hasPermission.mockReturnValue(false) + expect(pageType.hasPermission(workspace)).toBe(false) }) }) diff --git a/web-frontend/test/unit/database/components/dataSync/configureDataSyncHistory.spec.js b/web-frontend/test/unit/database/components/dataSync/configureDataSyncHistory.spec.js index 4dea0175fe..a5458884a5 100644 --- a/web-frontend/test/unit/database/components/dataSync/configureDataSyncHistory.spec.js +++ b/web-frontend/test/unit/database/components/dataSync/configureDataSyncHistory.spec.js @@ -150,17 +150,26 @@ describe('ConfigureDataSyncHistory', () => { const firstPage = Array.from({ length: 10 }, (_, index) => createSyncJob({ id: 100 - index, state: 'finished' }) ) - mockServer.mock.onGet('jobs/').replyOnce(200, { - jobs: firstPage, - count: 20, - }) + const requestParams = { + type: 'sync_data_sync_table', + sync_data_sync_table_data_sync_id: table.data_sync.id, + limit: 10, + } mockServer.mock - .onGet('jobs/') + .onGet('jobs/', { params: { ...requestParams, offset: 0 } }) + .reply(200, { + jobs: firstPage, + count: 20, + }) + mockServer.mock + .onGet('jobs/', { params: { ...requestParams, offset: 10 } }) .replyOnce(400, { error: 'ERROR_SOMETHING', detail: '' }) - mockServer.mock.onGet('jobs/').replyOnce(200, { - jobs: [createSyncJob({ id: 1, state: 'finished' })], - count: 20, - }) + mockServer.mock + .onGet('jobs/', { params: { ...requestParams, offset: 10 } }) + .replyOnce(200, { + jobs: [createSyncJob({ id: 1, state: 'finished' })], + count: 20, + }) const wrapper = await testApp.mount(ConfigureDataSyncHistory, { propsData: { database, table }, diff --git a/web-frontend/test/unit/database/components/row/__snapshots__/rowHistoryEntry.spec.js.snap b/web-frontend/test/unit/database/components/row/__snapshots__/rowHistoryEntry.spec.js.snap new file mode 100644 index 0000000000..0bfe7ee39b --- /dev/null +++ b/web-frontend/test/unit/database/components/row/__snapshots__/rowHistoryEntry.spec.js.snap @@ -0,0 +1,22 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`RowHistoryEntry > renders an Agent actor without resolving it as a colliding user 1`] = ` +"
+
RRow writer rowHistorySidebar.updated
+ +
" +`; + +exports[`RowHistoryEntry > resolves a User actor through its registered subject type 1`] = ` +"
+
CColliding user rowHistorySidebar.updated
+ +
" +`; + +exports[`RowHistoryEntry > translates an Anonymous User actor when rendering 1`] = ` +"
+
RrowHistorySidebar.anonymousUser rowHistorySidebar.submitted
+ +
" +`; diff --git a/web-frontend/test/unit/database/components/row/rowHistoryEntry.spec.js b/web-frontend/test/unit/database/components/row/rowHistoryEntry.spec.js new file mode 100644 index 0000000000..5e619f1b9d --- /dev/null +++ b/web-frontend/test/unit/database/components/row/rowHistoryEntry.spec.js @@ -0,0 +1,80 @@ +import { TestApp } from '@baserow/test/helpers/testApp' +import RowHistoryEntry from '@baserow/modules/database/components/row/RowHistoryEntry' + +describe('RowHistoryEntry', () => { + let testApp = null + + beforeEach(() => { + testApp = new TestApp() + testApp.store.state.workspace.items = [ + { users: [{ user_id: 1, name: 'Colliding user' }] }, + ] + }) + + afterEach(async () => { + await testApp.afterEach() + }) + + test('renders an Agent actor without resolving it as a colliding user', async () => { + const wrapper = await testApp.mount(RowHistoryEntry, { + propsData: { + workspaceId: 1, + fields: [], + entry: { + action_type: 'update_row', + action_command_type: 'DO', + timestamp: '2026-08-05T12:00:00Z', + user: { id: 1, name: 'Current user' }, + actor: { id: 1, type: 'core.Agent', name: 'Row writer' }, + before: {}, + after: {}, + fields_metadata: {}, + }, + }, + }) + + expect(wrapper.html()).toMatchSnapshot() + }) + + test('translates an Anonymous User actor when rendering', async () => { + const wrapper = await testApp.mount(RowHistoryEntry, { + propsData: { + workspaceId: 1, + fields: [], + entry: { + action_type: 'submit_form', + action_command_type: 'DO', + timestamp: '2026-08-05T12:00:00Z', + user: { id: null, name: 'Anonymous User' }, + actor: { id: null, type: 'anonymous', name: 'Anonymous User' }, + before: {}, + after: {}, + fields_metadata: {}, + }, + }, + }) + + expect(wrapper.html()).toMatchSnapshot() + }) + + test('resolves a User actor through its registered subject type', async () => { + const wrapper = await testApp.mount(RowHistoryEntry, { + propsData: { + workspaceId: 1, + fields: [], + entry: { + action_type: 'update_row', + action_command_type: 'DO', + timestamp: '2026-08-05T12:00:00Z', + user: { id: 1, name: 'Stored user name' }, + actor: { id: 1, type: 'auth.User', name: 'Stored user name' }, + before: {}, + after: {}, + fields_metadata: {}, + }, + }, + }) + + expect(wrapper.html()).toMatchSnapshot() + }) +}) diff --git a/web-frontend/test/unit/integrations/ai/aiAgentServiceForm.spec.js b/web-frontend/test/unit/integrations/ai/aiAgentServiceForm.spec.js index fd61d2690c..f826e92a25 100644 --- a/web-frontend/test/unit/integrations/ai/aiAgentServiceForm.spec.js +++ b/web-frontend/test/unit/integrations/ai/aiAgentServiceForm.spec.js @@ -438,7 +438,10 @@ describe('AIAgentServiceType', () => { new AIAgentServiceType({ app: { $i18n: { t: (key) => key }, - $registry: { getAll: () => modelTypes }, + $registry: { + getAll: () => modelTypes, + get: () => ({ getErrorMessage: () => null }), + }, $store: { getters: { 'integration/getIntegrationById': () => integration, diff --git a/web-frontend/test/unit/integrations/localBaserow/localBaserowForm.spec.js b/web-frontend/test/unit/integrations/localBaserow/localBaserowForm.spec.js new file mode 100644 index 0000000000..d2d684454e --- /dev/null +++ b/web-frontend/test/unit/integrations/localBaserow/localBaserowForm.spec.js @@ -0,0 +1,144 @@ +import flushPromises from 'flush-promises' + +import LocalBaserowForm from '@baserow/modules/integrations/localBaserow/components/integrations/LocalBaserowForm' +import { TestApp } from '@baserow/test/helpers/testApp' + +describe('LocalBaserowForm', () => { + let testApp = null + + beforeEach(() => { + testApp = new TestApp() + testApp.store.state.auth.user = { id: 1 } + testApp.mock.onGet('/subjects/').reply(200, { + count: 2, + next: null, + previous: null, + results: [ + { + id: 'core.Agent:10', + subject_id: 10, + subject_type: 'core.Agent', + name: 'Writer agent', + }, + { + id: 'core.Agent:11', + subject_id: 11, + subject_type: 'core.Agent', + name: 'Reader agent', + }, + ], + }) + }) + + afterEach(async () => { + await testApp.afterEach() + }) + + async function mountComponent(defaultValues = {}) { + return await testApp.mount(LocalBaserowForm, { + props: { + application: { id: 2, workspace: { id: 1 } }, + defaultValues, + }, + }) + } + + test('lists agents and emits the selected typed subject', async () => { + const wrapper = await mountComponent() + await wrapper.find('.dropdown__selected').trigger('click') + await flushPromises() + + expect(testApp.mock.history.get.at(-1).params).toEqual({ + workspace_id: 1, + page: 1, + search: '', + subject_types: 'core.Agent', + size: 100, + }) + + const items = wrapper.findAllComponents({ name: 'DropdownItem' }) + expect(items.map((item) => item.props('name'))).toEqual([ + 'localBaserowForm.currentUser', + 'Writer agent', + 'Reader agent', + ]) + + await items.at(1).find('.select__item-link').trigger('click') + await flushPromises() + + expect(wrapper.emitted('values-changed').at(-1)[0]).toEqual({ + authorized_subject_id: 10, + authorized_subject_type: 'core.Agent', + }) + }) + + test('shows the saved agent as selected', async () => { + const wrapper = await mountComponent({ + authorized_subject: { id: 11, type: 'core.Agent', name: 'Reader agent' }, + }) + await flushPromises() + + expect(wrapper.find('.dropdown__selected-text').text()).toBe('Reader agent') + }) + + test('shows nothing selected for a saved trashed agent', async () => { + const wrapper = await mountComponent({ + authorized_subject: { + id: 11, + type: 'core.Agent', + name: 'Reader agent', + trashed: true, + }, + }) + await flushPromises() + + expect(wrapper.find('.dropdown__selected-text').exists()).toBe(false) + expect(wrapper.find('.dropdown__selected').text()).toBe('action.makeChoice') + }) + + test('shows the saved current user as selected', async () => { + const wrapper = await mountComponent({ + authorized_subject: { id: 1, type: 'auth.User', first_name: 'Admin' }, + }) + await flushPromises() + + expect(wrapper.find('.dropdown__selected-text').text()).toBe( + 'localBaserowForm.currentUser' + ) + }) + + test('shows a saved different user by name', async () => { + const wrapper = await mountComponent({ + authorized_subject: { + id: 2, + type: 'auth.User', + first_name: 'Other user', + username: 'other@example.com', + }, + }) + await flushPromises() + + expect(wrapper.find('.dropdown__selected-text').text()).toBe('Other user') + expect( + wrapper.findComponent({ name: 'PaginatedDropdown' }).props('value') + ).toBe('auth.User:2') + }) + + test('emits the current user as an explicit authorization subject', async () => { + const wrapper = await mountComponent({ + authorized_subject: { id: 11, type: 'core.Agent', name: 'Reader agent' }, + }) + await flushPromises() + + await wrapper + .findComponent({ name: 'DropdownItem', props: { value: 'user' } }) + .find('.select__item-link') + .trigger('click') + await flushPromises() + + expect(wrapper.emitted('values-changed').at(-1)[0]).toEqual({ + authorized_subject_id: 1, + authorized_subject_type: 'auth.User', + }) + }) +}) diff --git a/web-frontend/test/unit/integrations/localBaserow/serviceTypes.spec.js b/web-frontend/test/unit/integrations/localBaserow/serviceTypes.spec.js index a7783db4cc..79435ee78e 100644 --- a/web-frontend/test/unit/integrations/localBaserow/serviceTypes.spec.js +++ b/web-frontend/test/unit/integrations/localBaserow/serviceTypes.spec.js @@ -338,6 +338,9 @@ describe('Local baserow service types', () => { id === 5 ? { id: 5, type: 'local_baserow' } : undefined, }, }, + $registry: { + get: () => ({ getErrorMessage: () => null }), + }, $i18n: { t: (key) => key }, } const serviceType = new LocalBaserowGetRowServiceType({ app: fakeApp }) @@ -377,6 +380,46 @@ describe('Local baserow service types', () => { ).toBe(null) }) + test('a trashed integration agent marks the integration and service as in error', () => { + const integration = { + id: 5, + type: 'local_baserow', + authorized_subject: { + id: 9, + type: 'core.Agent', + name: 'Writer', + trashed: true, + }, + } + const application = { id: 1, integrations: [integration] } + const registry = testApp.getRegistry() + const integrationType = registry.get('integration', 'local_baserow') + const serviceType = registry.get('service', 'local_baserow_get_row') + + expect(integrationType.isInError(integration)).toBe(true) + expect(integrationType.getSummary(integration)).toBe( + 'localBaserowIntegrationType.localBaserowNoUser' + ) + expect( + integrationType.getSummary({ + ...integration, + authorized_subject: { + ...integration.authorized_subject, + trashed: false, + }, + }) + ).toBe('localBaserowIntegrationType.localBaserowSubjectSummary') + expect( + serviceType.getErrorMessage({ + service: { integration_id: 5, table_id: 99 }, + application, + }) + ).toBe('localBaserowIntegrationType.errorTrashedAgent') + expect(en.localBaserowIntegrationType.errorTrashedAgent).toBe( + 'The authorized agent has been trashed' + ) + }) + test('the update row service is in error without a row ID, the create row service is not', () => { const registry = testApp.getRegistry() const updateRow = registry.get('service', 'local_baserow_update_row')