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
This commit is contained in:
Jérémie Pardou authored and GitHub committed 2026-10-19 10:38:57 +02:00
1 parent 5d19eab8de
commit 93eeb19dcb
165 files changed
+4958 -719

No files matched your search

+1
View File
@@ -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
@@ -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):
@@ -0,0 +1 @@
@@ -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']}"
+7
View File
@@ -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")]
+68
View File
@@ -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)
+2
View File
@@ -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")),
@@ -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.
@@ -111,6 +111,7 @@ class WorkspacesView(RealtimeRecoveryPrimaryReadMixin, APIView):
CoreHandler()
.get_workspaceuser_workspace_queryset()
.filter(user=request.user)
.order_by("order", "id")
)
workspaceuser_workspaces = (
@@ -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:
@@ -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(
@@ -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:
@@ -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,
)
@@ -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,
@@ -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")
@@ -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):
@@ -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",
@@ -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
)
@@ -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),
),
]
@@ -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),
]
@@ -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))
@@ -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,
@@ -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",
@@ -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,
@@ -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,
@@ -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(
@@ -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):
@@ -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)
@@ -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]:
@@ -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)
@@ -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
),
),
],
),
]
@@ -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,
)
@@ -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,
@@ -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)
@@ -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.
@@ -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."""
+2 -1
View File
@@ -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,
@@ -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."""
@@ -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,
@@ -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,
@@ -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
+7
View File
@@ -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 (
+59 -2
View File
@@ -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()
@@ -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
@@ -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)
+83
View File
@@ -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],
@@ -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
@@ -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)
@@ -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()
@@ -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(
@@ -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
@@ -0,0 +1 @@
@@ -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]
@@ -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()
@@ -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()
@@ -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()
@@ -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()
@@ -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
@@ -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
@@ -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
@@ -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")
@@ -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",
@@ -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(
@@ -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",
@@ -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
@@ -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,
@@ -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"},
@@ -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()
@@ -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):
@@ -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()
@@ -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"]
@@ -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
@@ -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"
)
@@ -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()
@@ -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
@@ -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) == []
@@ -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
@@ -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():
"""
@@ -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()
@@ -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
@@ -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"
}
@@ -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"
),
@@ -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):
@@ -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"
),
@@ -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):
@@ -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)
@@ -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,
@@ -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):
@@ -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,
@@ -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,
@@ -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
@@ -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,
@@ -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",
),
)
],
),
]
@@ -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)
@@ -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,
@@ -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):
@@ -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",
@@ -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
@@ -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"]
)
@@ -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()
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff. Show more