diff --git a/crm_core/serializers.py b/crm_core/serializers.py index 3ed0903..a8f217b 100644 --- a/crm_core/serializers.py +++ b/crm_core/serializers.py @@ -77,6 +77,14 @@ class OpportunitySerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixi class ActivitySerializer(OwnerScopedRelationMixin, serializers.ModelSerializer): + ALLOWED_TARGET_MODELS = { + ('crm_core', 'account'), + ('crm_core', 'contact'), + ('crm_core', 'lead'), + ('crm_core', 'opportunity'), + ('crm_core', 'activity'), + ('custom_objects', 'customrecord'), + } class Meta: model = Activity fields = '__all__' @@ -84,11 +92,24 @@ class ActivitySerializer(OwnerScopedRelationMixin, serializers.ModelSerializer): 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)) + # For partial updates, check attrs first, then fall back to instance + content_type = attrs['content_type'] if 'content_type' in attrs else getattr(self.instance, 'content_type', None) + object_id = attrs['object_id'] if 'object_id' in attrs else getattr(self.instance, 'object_id', None) - # If both are present, validate that the target object exists and is accessible + # Disallow half-cleared or half-specified polymorphic relationship + if (content_type is not None and object_id is None) or (content_type is None and object_id is not None): + raise serializers.ValidationError({ + 'non_field_errors': ['Polymorphic parent requires both content_type and object_id to be set together, or both cleared.'] + }) + + # If both are present, validate against the allowed model registry and actor-scoped queryset if content_type and object_id: + target_key = (content_type.app_label, content_type.model) + if target_key not in self.ALLOWED_TARGET_MODELS: + raise serializers.ValidationError({ + 'content_type': f'Target model "{content_type.app_label}.{content_type.model}" is not allowed for Activity association.' + }) + model_cls = content_type.model_class() if model_cls is None: raise serializers.ValidationError({'content_type': 'Invalid content type.'}) @@ -104,15 +125,16 @@ class ActivitySerializer(OwnerScopedRelationMixin, serializers.ModelSerializer): qs = qs.filter(created_by=user) elif hasattr(model_cls, 'assigned_to'): qs = qs.filter(assigned_to=user) + else: + # Default-deny for models without tenant ownership fields + raise serializers.ValidationError({ + 'content_type': f'Target model "{content_type.app_label}.{content_type.model}" has no tenant ownership mapping.' + }) 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 diff --git a/tests/test_tenant_isolation.py b/tests/test_tenant_isolation.py index 0555e0d..7aed535 100644 --- a/tests/test_tenant_isolation.py +++ b/tests/test_tenant_isolation.py @@ -549,6 +549,32 @@ class TestTenantAccessIsolation: act = Activity.objects.get(id=bob_act_id) assert act.object_id == account_b.id + # 4. Bob attempts to patch/update the Activity pointing to an unallowed system model (auth.User) + user_ct = ContentType.objects.get_for_model(User) + patch_user_res = self.client_b.patch(f'/api/activities/{bob_act_id}/', { + 'content_type': user_ct.id, + 'object_id': self.user_a.id, + }, format='json') + assert patch_user_res.status_code == 400 + assert 'content_type' in patch_user_res.data + assert 'not allowed' in str(patch_user_res.data['content_type']).lower() + + # 5. Partial update clearing only one of the polymorphic pair is rejected + partial_clear_res = self.client_b.patch(f'/api/activities/{bob_act_id}/', { + 'content_type': None, + }, format='json') + assert partial_clear_res.status_code == 400 + + # Clearing both together succeeds + clear_both_res = self.client_b.patch(f'/api/activities/{bob_act_id}/', { + 'content_type': None, + 'object_id': None, + }, format='json') + assert clear_both_res.status_code == 200 + act.refresh_from_db() + assert act.content_type is None + assert act.object_id is None + def test_flow_execution_atomic_rollback_on_failure(self): """ When manual flow execution encounters an error in a subsequent node, @@ -611,3 +637,90 @@ class TestTenantAccessIsolation: log = FlowExecutionLog.objects.filter(flow=flow).order_by('-started_at').first() assert log is not None assert log.status == 'failed' + + def test_flow_execution_log_audit_integrity_across_runs(self): + """ + Verify that a failed execution does not overwrite or corrupt + a previous successful execution log for the same flow. + """ + from workflows.models import FlowDefinition, FlowExecutionLog + + account_b = Account.objects.create(name='Audit Integrity Test Acc', owner=self.user_b) + initial_name = account_b.name + + # 1. Flow that succeeds + success_dag = { + "nodes": [ + {"id": "start", "type": "trigger", "data": {}}, + ], + "edges": [] + } + flow = FlowDefinition.objects.create( + name="Audit Log Test Flow", + graph=success_dag, + is_active=True, + created_by=self.user_b + ) + + res1 = self.client_b.post(f'/api/workflows/{flow.id}/execute/', {}, format='json') + assert res1.status_code == 200 + assert res1.data['status'] == 'completed' + + logs_after_1 = list(FlowExecutionLog.objects.filter(flow=flow).order_by('id')) + assert len(logs_after_1) == 1 + log1 = logs_after_1[0] + assert log1.status == 'completed' + + # 2. Update flow graph to mutate account and then fail on invalid subflow + fail_dag = { + "nodes": [ + { + "id": "node_update", + "type": "update_record", + "data": { + "model_name": "Account", + "record_id": account_b.id, + "field_updates": {"name": "Should Rollback"} + } + }, + { + "id": "node_subflow_fail", + "type": "subflow", + "data": { + "flow_id": 999999 + } + } + ], + "edges": [ + { + "source": "node_update", + "target": "node_subflow_fail" + } + ] + } + flow.graph = fail_dag + flow.save() + + res2 = self.client_b.post(f'/api/workflows/{flow.id}/execute/', { + 'context': {'account_id': account_b.id} + }, format='json') + assert res2.status_code == 400 + assert res2.data['status'] == 'failed' + + # Mutation must be rolled back + account_b.refresh_from_db() + assert account_b.name == initial_name + + # Verify two distinct logs exist: original success remains completed and intact, + # new log is recorded as failed. + logs_after_2 = list(FlowExecutionLog.objects.filter(flow=flow).order_by('id')) + assert len(logs_after_2) == 2 + + log1_reloaded = FlowExecutionLog.objects.get(id=log1.id) + assert log1_reloaded.status == 'completed' + assert log1_reloaded.error_message == '' or log1_reloaded.error_message is None + + log2 = logs_after_2[1] + assert log2.id != log1.id + assert log2.status == 'failed' + assert '999999' in log2.error_message diff --git a/workflows/engine.py b/workflows/engine.py index 61030cc..5701291 100644 --- a/workflows/engine.py +++ b/workflows/engine.py @@ -151,7 +151,7 @@ def _evaluate_decision_node(node_data, context): return 'default', node_data.get('default_target_node') -def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None, depth=0, user=None): +def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None, depth=0, user=None, execution_log=None): from .models import FlowDefinition, FlowExecutionLog MAX_SUBFLOW_DEPTH = 10 @@ -164,13 +164,13 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None, validate_flow_dag(graph) - if not is_dict and idempotency_key: + if not is_dict and idempotency_key and not execution_log: existing = FlowExecutionLog.objects.filter(flow=flow_def, idempotency_key=idempotency_key).first() if existing: return existing - log = None - if not is_dict and flow_def: + log = execution_log + if log is None and not is_dict and flow_def: log = FlowExecutionLog.objects.create( flow=flow_def, status='running', diff --git a/workflows/views.py b/workflows/views.py index f5c92e1..8cf3ffa 100644 --- a/workflows/views.py +++ b/workflows/views.py @@ -40,56 +40,74 @@ class FlowDefinitionViewSet(viewsets.ModelViewSet): idempotency_key = request.data.get('idempotency_key') user = request.user if request.user and request.user.is_authenticated else None + # Check existing idempotency key before attempting new execution + if idempotency_key: + existing_log = FlowExecutionLog.objects.filter(flow=flow, idempotency_key=idempotency_key).first() + if existing_log: + if existing_log.status == 'failed': + return Response( + { + 'status': 'failed', + 'error': existing_log.error_message, + 'log': FlowExecutionLogSerializer(existing_log).data + }, + status=status.HTTP_400_BAD_REQUEST + ) + data = FlowExecutionLogSerializer(existing_log).data + data['context_data'] = existing_log.context_data + data['status'] = existing_log.status + return Response(data, status=status.HTTP_200_OK) + + # Allocate distinct execution log for this attempt outside the mutation savepoint + current_log = FlowExecutionLog.objects.create( + flow=flow, + status='running', + context_data=initial_context or {}, + idempotency_key=idempotency_key + ) + sid = transaction.savepoint() try: execution_log = execute_flow_dag( flow, initial_context=initial_context, idempotency_key=idempotency_key, - user=user + user=user, + execution_log=current_log ) if execution_log and execution_log.status == 'failed': transaction.savepoint_rollback(sid) - execution_log.save() + current_log.status = 'failed' + current_log.error_message = execution_log.error_message + current_log.save() return Response( { 'status': 'failed', - 'error': execution_log.error_message, - 'log': FlowExecutionLogSerializer(execution_log).data + 'error': current_log.error_message, + 'log': FlowExecutionLogSerializer(current_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 - ) + current_log.status = 'failed' + current_log.error_message = str(e) + current_log.save() return Response( { 'status': 'failed', 'error': str(e), - 'log': FlowExecutionLogSerializer(failed_log).data + 'log': FlowExecutionLogSerializer(current_log).data }, status=status.HTTP_400_BAD_REQUEST ) - data = FlowExecutionLogSerializer(execution_log).data - data['context_data'] = execution_log.context_data - data['status'] = execution_log.status + + # Refetch completed log state + current_log.refresh_from_db() + data = FlowExecutionLogSerializer(current_log).data + data['context_data'] = current_log.context_data + data['status'] = current_log.status return Response( data, status=status.HTTP_200_OK