From 264d2a575eabf691432f404ff573ac3367034def Mon Sep 17 00:00:00 2001 From: Goose Date: Sat, 26 Sep 2026 23:26:06 +0000 Subject: [PATCH] fix(security): scope polymorphic Activity relationships and enforce atomic rollback on flow execution --- crm_core/serializers.py | 34 +++++++++++ tests/test_tenant_isolation.py | 105 +++++++++++++++++++++++++++++++++ workflows/views.py | 46 +++++++++++---- 3 files changed, 174 insertions(+), 11 deletions(-) diff --git a/crm_core/serializers.py b/crm_core/serializers.py index b80b239..3ed0903 100644 --- a/crm_core/serializers.py +++ b/crm_core/serializers.py @@ -82,6 +82,40 @@ class ActivitySerializer(OwnerScopedRelationMixin, serializers.ModelSerializer): fields = '__all__' read_only_fields = ['id', 'assigned_to', 'completed_at', 'created_at', 'updated_at'] + def validate(self, attrs): + attrs = super().validate(attrs) + content_type = attrs.get('content_type', getattr(self.instance, 'content_type', None)) + object_id = attrs.get('object_id', getattr(self.instance, 'object_id', None)) + + # If both are present, validate that the target object exists and is accessible + if content_type and object_id: + model_cls = content_type.model_class() + if model_cls is None: + raise serializers.ValidationError({'content_type': 'Invalid content type.'}) + + request = self.context.get('request') + user = getattr(request, 'user', None) if request else None + + qs = model_cls.objects.all() + if user and user.is_authenticated and not (user.is_superuser or user.is_staff): + if hasattr(model_cls, 'owner'): + qs = qs.filter(owner=user) + elif hasattr(model_cls, 'created_by'): + qs = qs.filter(created_by=user) + elif hasattr(model_cls, 'assigned_to'): + qs = qs.filter(assigned_to=user) + + if not qs.filter(id=object_id).exists(): + raise serializers.ValidationError({ + 'object_id': f'Invalid pk "{object_id}" - object does not exist or unauthorized.' + }) + elif (content_type and not object_id) or (object_id and not content_type): + # If one is provided without the other (or changed to null), ensure consistency + if content_type is None or object_id is None: + pass + + return attrs + class LeadConvertSerializer(serializers.Serializer): create_opportunity = serializers.BooleanField(required=False, default=False) diff --git a/tests/test_tenant_isolation.py b/tests/test_tenant_isolation.py index f9e23f5..0555e0d 100644 --- a/tests/test_tenant_isolation.py +++ b/tests/test_tenant_isolation.py @@ -506,3 +506,108 @@ class TestTenantAccessIsolation: assert bob_tmpl is not None assert bob_tmpl.id != alice_tmpl.id assert bob_tmpl.created_by == self.user_b + + def test_activity_polymorphic_generic_foreign_key_isolated(self): + """ + Bob cannot attach an Activity to Alice's Account via polymorphic (content_type, object_id). + """ + from django.contrib.contenttypes.models import ContentType + from crm_core.models import Activity + + account_a = Account.objects.create(name='Alice Account', owner=self.user_a) + account_b = Account.objects.create(name='Bob Account', owner=self.user_b) + account_ct = ContentType.objects.get_for_model(Account) + + # 1. Bob attempts to create an Activity pointing to Alice's Account + create_res = self.client_b.post('/api/activities/', { + 'subject': 'Infiltrate Alice Account', + 'activity_type': 'Task', + 'content_type': account_ct.id, + 'object_id': account_a.id, + }, format='json') + assert create_res.status_code == 400 + assert 'object_id' in create_res.data + + # 2. Bob creates a valid Activity on his own Account + bob_valid = self.client_b.post('/api/activities/', { + 'subject': 'Bob Task', + 'activity_type': 'Task', + 'content_type': account_ct.id, + 'object_id': account_b.id, + }, format='json') + assert bob_valid.status_code == 201 + bob_act_id = bob_valid.data['id'] + + # 3. Bob attempts to patch/update the Activity to repoint to Alice's Account + patch_res = self.client_b.patch(f'/api/activities/{bob_act_id}/', { + 'object_id': account_a.id, + }, format='json') + assert patch_res.status_code == 400 + assert 'object_id' in patch_res.data + + # Verify in DB that the Activity was NOT repointed to Alice's Account + act = Activity.objects.get(id=bob_act_id) + assert act.object_id == account_b.id + + def test_flow_execution_atomic_rollback_on_failure(self): + """ + When manual flow execution encounters an error in a subsequent node, + earlier record mutations are rolled back atomically while the failed log is preserved. + """ + from workflows.models import FlowDefinition, FlowExecutionLog + + account_b = Account.objects.create(name='Bob Account Prior', owner=self.user_b) + initial_name = account_b.name + + # Create a DAG with two nodes: + # Node 1: update Bob's account name + # Node 2: call nonexistent child subflow (fails) + dag = { + "nodes": [ + { + "id": "node_update", + "type": "update_record", + "data": { + "model_name": "Account", + "record_id_path": "account_id", + "field_updates": {"name": "Should Be Rolled Back"} + } + }, + { + "id": "node_subflow_fail", + "type": "subflow", + "data": { + "subflow_id": 999999 + } + } + ], + "edges": [ + { + "source": "node_update", + "target": "node_subflow_fail" + } + ] + } + + flow = FlowDefinition.objects.create( + name="Rollback Test Flow", + graph=dag, + is_active=True, + created_by=self.user_b + ) + + res = self.client_b.post(f'/api/workflows/{flow.id}/execute/', { + 'context': {'account_id': account_b.id} + }, format='json') + + assert res.status_code == 400 + assert res.data['status'] == 'failed' + + # Verify Account B's name was rolled back and NOT persisted + account_b.refresh_from_db() + assert account_b.name == initial_name + + # Verify execution log was saved with status 'failed' + log = FlowExecutionLog.objects.filter(flow=flow).order_by('-started_at').first() + assert log is not None + assert log.status == 'failed' diff --git a/workflows/views.py b/workflows/views.py index 3d84b2b..f5c92e1 100644 --- a/workflows/views.py +++ b/workflows/views.py @@ -1,4 +1,4 @@ -from django.db import models +from django.db import models, transaction from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.decorators import action @@ -39,6 +39,8 @@ class FlowDefinitionViewSet(viewsets.ModelViewSet): initial_context = request.data.get('context', {}) idempotency_key = request.data.get('idempotency_key') user = request.user if request.user and request.user.is_authenticated else None + + sid = transaction.savepoint() try: execution_log = execute_flow_dag( flow, @@ -46,20 +48,42 @@ class FlowDefinitionViewSet(viewsets.ModelViewSet): idempotency_key=idempotency_key, user=user ) + if execution_log and execution_log.status == 'failed': + transaction.savepoint_rollback(sid) + execution_log.save() + return Response( + { + 'status': 'failed', + 'error': execution_log.error_message, + 'log': FlowExecutionLogSerializer(execution_log).data + }, + status=status.HTTP_400_BAD_REQUEST + ) + transaction.savepoint_commit(sid) except Exception as e: + transaction.savepoint_rollback(sid) + # Re-fetch or record the execution log failure so audit trail is preserved + if idempotency_key: + failed_log = FlowExecutionLog.objects.filter(flow=flow, idempotency_key=idempotency_key).first() + else: + failed_log = FlowExecutionLog.objects.filter(flow=flow).order_by('-started_at').first() + if failed_log: + failed_log.status = 'failed' + failed_log.error_message = str(e) + failed_log.save() + else: + failed_log = FlowExecutionLog.objects.create( + flow=flow, + status='failed', + error_message=str(e), + context_data=initial_context or {}, + idempotency_key=idempotency_key + ) return Response( { 'status': 'failed', - 'error': str(e) - }, - status=status.HTTP_400_BAD_REQUEST - ) - if execution_log.status == 'failed': - return Response( - { - 'status': 'failed', - 'error': execution_log.error_message, - 'log': FlowExecutionLogSerializer(execution_log).data + 'error': str(e), + 'log': FlowExecutionLogSerializer(failed_log).data }, status=status.HTTP_400_BAD_REQUEST )