fix(security, workflows, views): implement tenant row-level authorization, application-level atomic rollback, flow contract ordering, and live campaign stats
This commit is contained in:
parent
af8556597a
commit
9318bb3736
12 changed files with 364 additions and 115 deletions
|
|
@ -1,9 +1,9 @@
|
|||
from decimal import Decimal
|
||||
from django.db import transaction, models
|
||||
from rest_framework import viewsets, status
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.exceptions import ValidationError
|
||||
|
||||
from .models import Account, Contact, Lead, Opportunity, Activity
|
||||
from .serializers import (
|
||||
|
|
@ -11,29 +11,63 @@ from .serializers import (
|
|||
OpportunitySerializer, ActivitySerializer, LeadConvertSerializer
|
||||
)
|
||||
from .services import convert_lead
|
||||
from openforce.permissions import ScopedOwnerAccessPermission
|
||||
|
||||
|
||||
class AccountViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = Account.objects.all().order_by('-created_at')
|
||||
class ScopedQuerySetMixin:
|
||||
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||
|
||||
def get_queryset(self):
|
||||
qs = super().get_queryset()
|
||||
user = self.request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return qs.none()
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
if hasattr(self.queryset.model, 'owner'):
|
||||
return qs.filter(owner=user)
|
||||
if hasattr(self.queryset.model, 'assigned_to'):
|
||||
return qs.filter(assigned_to=user)
|
||||
return qs
|
||||
|
||||
|
||||
class AccountViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||
queryset = Account.objects.all()
|
||||
serializer_class = AccountSerializer
|
||||
search_fields = ['name', 'industry']
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(owner=self.request.user)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
||||
|
||||
class ContactViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = Contact.objects.all().order_by('-created_at')
|
||||
class ContactViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||
queryset = Contact.objects.all()
|
||||
serializer_class = ContactSerializer
|
||||
filterset_fields = ['account', 'lead_source']
|
||||
search_fields = ['first_name', 'last_name', 'email']
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(owner=self.request.user)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
||||
|
||||
class LeadViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = Lead.objects.all().order_by('-created_at')
|
||||
class LeadViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||
queryset = Lead.objects.all()
|
||||
serializer_class = LeadSerializer
|
||||
filterset_fields = ['status', 'rating']
|
||||
search_fields = ['first_name', 'last_name', 'company', 'email']
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(owner=self.request.user)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='convert')
|
||||
def convert(self, request, pk=None):
|
||||
|
|
@ -42,42 +76,55 @@ class LeadViewSet(viewsets.ModelViewSet):
|
|||
serializer.is_valid(raise_exception=True)
|
||||
validated = serializer.validated_data
|
||||
|
||||
try:
|
||||
account_name = validated.get('account_name') or lead.company
|
||||
create_opportunity = validated.get('create_opportunity', False)
|
||||
opportunity_name = validated.get('opportunity_name') or f"{account_name} - Opportunity"
|
||||
opportunity_amount = validated.get('opportunity_amount')
|
||||
opportunity_close_date = validated.get('opportunity_close_date')
|
||||
|
||||
with transaction.atomic():
|
||||
result = convert_lead(
|
||||
lead=lead,
|
||||
account_name=validated.get('account_name'),
|
||||
create_opportunity=validated.get('create_opportunity', False),
|
||||
opportunity_name=validated.get('opportunity_name'),
|
||||
opportunity_amount=validated.get('opportunity_amount'),
|
||||
opportunity_close_date=validated.get('opportunity_close_date'),
|
||||
account_name=account_name,
|
||||
create_opportunity=create_opportunity,
|
||||
opportunity_name=opportunity_name,
|
||||
opportunity_amount=opportunity_amount,
|
||||
opportunity_close_date=opportunity_close_date,
|
||||
user=request.user
|
||||
)
|
||||
return Response({
|
||||
'account': result['account'].id,
|
||||
'contact': result['contact'].id,
|
||||
'opportunity': result['opportunity'].id if result['opportunity'] else None,
|
||||
'account_id': result['account'].id,
|
||||
'contact_id': result['contact'].id,
|
||||
'opportunity_id': result['opportunity'].id if result['opportunity'] else None,
|
||||
'status': 'converted'
|
||||
}, status=status.HTTP_200_OK)
|
||||
except ValidationError as e:
|
||||
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
|
||||
except Exception as e:
|
||||
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
return Response({
|
||||
'account': result['account'].id,
|
||||
'contact': result['contact'].id,
|
||||
'opportunity': result['opportunity'].id if result['opportunity'] else None,
|
||||
'account_id': result['account'].id,
|
||||
'contact_id': result['contact'].id,
|
||||
'opportunity_id': result['opportunity'].id if result['opportunity'] else None,
|
||||
'status': 'converted'
|
||||
}, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class OpportunityViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = Opportunity.objects.all().order_by('-close_date')
|
||||
class OpportunityViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||
queryset = Opportunity.objects.all()
|
||||
serializer_class = OpportunitySerializer
|
||||
filterset_fields = ['stage', 'account']
|
||||
search_fields = ['name']
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(owner=self.request.user)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
||||
|
||||
class ActivityViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = Activity.objects.all().order_by('-due_date')
|
||||
class ActivityViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||
queryset = Activity.objects.all()
|
||||
serializer_class = ActivitySerializer
|
||||
filterset_fields = ['activity_type', 'status', 'priority']
|
||||
search_fields = ['subject', 'description']
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(assigned_to=self.request.user)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
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.permissions import IsAuthenticated
|
||||
from rest_framework.exceptions import NotFound
|
||||
|
||||
|
|
@ -10,23 +9,31 @@ from .serializers import (
|
|||
CustomFieldDefinitionSerializer,
|
||||
CustomRecordSerializer
|
||||
)
|
||||
from openforce.permissions import ScopedOwnerAccessPermission
|
||||
|
||||
|
||||
class CustomObjectDefinitionViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = CustomObjectDefinition.objects.all().order_by('label')
|
||||
queryset = CustomObjectDefinition.objects.all()
|
||||
serializer_class = CustomObjectDefinitionSerializer
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(created_by=self.request.user)
|
||||
|
||||
|
||||
class CustomFieldDefinitionViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = CustomFieldDefinition.objects.all().order_by('name')
|
||||
queryset = CustomFieldDefinition.objects.all()
|
||||
serializer_class = CustomFieldDefinitionSerializer
|
||||
filterset_fields = ['custom_object']
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
||||
|
||||
class CustomRecordViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||
serializer_class = CustomRecordSerializer
|
||||
|
||||
def get_custom_object(self):
|
||||
|
|
@ -40,8 +47,17 @@ class CustomRecordViewSet(viewsets.ModelViewSet):
|
|||
|
||||
def get_queryset(self):
|
||||
custom_object = self.get_custom_object()
|
||||
return CustomRecord.objects.filter(custom_object=custom_object).order_by('-created_at')
|
||||
user = self.request.user
|
||||
qs = CustomRecord.objects.filter(custom_object=custom_object)
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
return qs.filter(owner=user)
|
||||
|
||||
def perform_create(self, serializer):
|
||||
custom_object = self.get_custom_object()
|
||||
serializer.save(custom_object=custom_object, owner=self.request.user)
|
||||
with transaction.atomic():
|
||||
custom_object = self.get_custom_object()
|
||||
serializer.save(custom_object=custom_object, owner=self.request.user)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save()
|
||||
|
|
|
|||
|
|
@ -73,6 +73,9 @@
|
|||
</div>
|
||||
<div class="flex-1 p-4 overflow-y-auto space-y-4">
|
||||
<div v-if="executionResult" class="space-y-3">
|
||||
<div v-if="executionResult.error" class="bg-rose-50 border border-rose-200 text-rose-800 text-xs p-2.5 rounded-md">
|
||||
<span class="font-bold">Error:</span> {{ executionResult.error }}
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs text-slate-500 font-medium">Steps Executed:</span>
|
||||
<div class="mt-1 flex flex-wrap gap-1">
|
||||
|
|
@ -108,6 +111,7 @@ import api from '../api'
|
|||
|
||||
const isSaving = ref(false)
|
||||
const isRunning = ref(false)
|
||||
const currentFlowId = ref(null)
|
||||
const executionResult = ref(null)
|
||||
|
||||
const nodes = ref([
|
||||
|
|
@ -238,8 +242,14 @@ async function saveFlow() {
|
|||
edges: edges.value
|
||||
}
|
||||
}
|
||||
await api.post('/workflows/', payload)
|
||||
alert('Workflow graph saved successfully!')
|
||||
let res
|
||||
if (currentFlowId.value) {
|
||||
res = await api.put(`/workflows/${currentFlowId.value}/`, payload)
|
||||
} else {
|
||||
res = await api.post('/workflows/', payload)
|
||||
currentFlowId.value = res.data.id
|
||||
}
|
||||
alert(`Workflow graph saved successfully! (ID: ${currentFlowId.value})`)
|
||||
} catch (err) {
|
||||
console.error('Failed to save workflow:', err)
|
||||
alert('Failed to save workflow: ' + (err.response?.data?.message || err.message))
|
||||
|
|
@ -251,7 +261,8 @@ async function saveFlow() {
|
|||
async function runFlow() {
|
||||
isRunning.value = true
|
||||
try {
|
||||
const res = await api.post('/workflows/1/execute/', {
|
||||
const flowId = currentFlowId.value || 1
|
||||
const res = await api.post(`/workflows/${flowId}/execute/`, {
|
||||
context: {
|
||||
record: { id: 101, name: 'Acme Corp', amount: 75000 },
|
||||
amount: 75000
|
||||
|
|
|
|||
24
openforce/permissions.py
Normal file
24
openforce/permissions.py
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
from rest_framework import permissions
|
||||
|
||||
class ScopedOwnerAccessPermission(permissions.BasePermission):
|
||||
"""
|
||||
Enforces that non-superuser/non-staff users can only access records they own.
|
||||
Superusers/staff have administrative access across all records.
|
||||
"""
|
||||
def has_permission(self, request, view):
|
||||
return request.user and request.user.is_authenticated
|
||||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
user = request.user
|
||||
if user.is_superuser or user.is_staff:
|
||||
return True
|
||||
owner = getattr(obj, 'owner', None)
|
||||
if owner is not None:
|
||||
return owner == user
|
||||
assigned = getattr(obj, 'assigned_to', None)
|
||||
if assigned is not None:
|
||||
return assigned == user
|
||||
created_by = getattr(obj, 'created_by', None)
|
||||
if created_by is not None:
|
||||
return created_by == user
|
||||
return True
|
||||
|
|
@ -33,6 +33,16 @@ MIDDLEWARE = [
|
|||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': [
|
||||
'rest_framework.authentication.SessionAuthentication',
|
||||
'rest_framework.authentication.BasicAuthentication',
|
||||
],
|
||||
'DEFAULT_PERMISSION_CLASSES': [
|
||||
'rest_framework.permissions.IsAuthenticated',
|
||||
],
|
||||
}
|
||||
|
||||
CORS_ALLOW_ALL_ORIGINS = True
|
||||
|
||||
ROOT_URLCONF = 'openforce.urls'
|
||||
|
|
@ -59,6 +69,7 @@ DATABASES = {
|
|||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': BASE_DIR / 'db.sqlite3',
|
||||
'ATOMIC_REQUESTS': True,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ DATABASES = {
|
|||
'PASSWORD': 'openforce',
|
||||
'HOST': 'localhost',
|
||||
'PORT': '5432',
|
||||
'ATOMIC_REQUESTS': True,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -16,3 +17,5 @@ PASSWORD_HASHERS = [
|
|||
]
|
||||
|
||||
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
|
||||
|
||||
ALLOWED_HOSTS = ['*']
|
||||
|
|
|
|||
|
|
@ -18,8 +18,20 @@ class CampaignRecipientSerializer(serializers.ModelSerializer):
|
|||
|
||||
class CampaignSerializer(serializers.ModelSerializer):
|
||||
recipients = CampaignRecipientSerializer(many=True, read_only=True)
|
||||
sent_count = serializers.SerializerMethodField()
|
||||
open_count = serializers.SerializerMethodField()
|
||||
click_count = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = Campaign
|
||||
fields = '__all__'
|
||||
read_only_fields = ['id', 'created_at', 'updated_at']
|
||||
|
||||
def get_sent_count(self, obj):
|
||||
return obj.recipients.filter(status__in=['sent', 'delivered', 'opened', 'clicked']).count()
|
||||
|
||||
def get_open_count(self, obj):
|
||||
return obj.recipients.filter(status__in=['opened', 'clicked']).count()
|
||||
|
||||
def get_click_count(self, obj):
|
||||
return obj.recipients.filter(status='clicked').count()
|
||||
|
|
|
|||
|
|
@ -1,61 +1,89 @@
|
|||
import base64
|
||||
from django.http import HttpResponse
|
||||
from django.utils import timezone
|
||||
from rest_framework import viewsets, status
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.permissions import IsAuthenticated, AllowAny
|
||||
from django.db import models
|
||||
from django.http import HttpResponse
|
||||
|
||||
from .models import EmailTemplate, Campaign, CampaignRecipient
|
||||
from .serializers import EmailTemplateSerializer, CampaignSerializer, CampaignRecipientSerializer
|
||||
from .serializers import (
|
||||
EmailTemplateSerializer, CampaignSerializer, CampaignRecipientSerializer
|
||||
)
|
||||
from .engine import dispatch_campaign
|
||||
from openforce.permissions import ScopedOwnerAccessPermission
|
||||
|
||||
# 1x1 transparent GIF in binary format
|
||||
PIXEL_GIF_BYTES = base64.b64decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')
|
||||
|
||||
|
||||
class EmailTemplateViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = EmailTemplate.objects.all().order_by('-created_at')
|
||||
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||
queryset = EmailTemplate.objects.all()
|
||||
serializer_class = EmailTemplateSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
qs = super().get_queryset()
|
||||
user = self.request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return qs
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
if hasattr(EmailTemplate, 'created_by'):
|
||||
return qs.filter(models.Q(created_by=user) | models.Q(created_by__isnull=True))
|
||||
return qs
|
||||
|
||||
def perform_create(self, serializer):
|
||||
kwargs = {}
|
||||
if hasattr(EmailTemplate, 'created_by'):
|
||||
kwargs['created_by'] = self.request.user
|
||||
serializer.save(**kwargs)
|
||||
|
||||
|
||||
class CampaignViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = Campaign.objects.all().order_by('-created_at')
|
||||
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||
queryset = Campaign.objects.all()
|
||||
serializer_class = CampaignSerializer
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='dispatch')
|
||||
def dispatch_now(self, request, pk=None):
|
||||
campaign = self.get_object()
|
||||
sent_count = dispatch_campaign(campaign.id)
|
||||
return Response({'status': 'dispatched', 'sent_count': sent_count}, status=status.HTTP_200_OK)
|
||||
def get_queryset(self):
|
||||
qs = super().get_queryset()
|
||||
user = self.request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return qs
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
if hasattr(Campaign, 'created_by'):
|
||||
return qs.filter(models.Q(created_by=user) | models.Q(created_by__isnull=True))
|
||||
return qs
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='add-recipients')
|
||||
def add_recipients(self, request, pk=None):
|
||||
def perform_create(self, serializer):
|
||||
kwargs = {}
|
||||
if hasattr(Campaign, 'created_by'):
|
||||
kwargs['created_by'] = self.request.user
|
||||
serializer.save(**kwargs)
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='dispatch')
|
||||
def dispatch_action(self, request, pk=None):
|
||||
campaign = self.get_object()
|
||||
recipients_data = request.data.get('recipients', [])
|
||||
created = []
|
||||
for r in recipients_data:
|
||||
rec, _ = CampaignRecipient.objects.get_or_create(
|
||||
campaign=campaign,
|
||||
email=r['email'],
|
||||
defaults={'first_name': r.get('first_name', ''), 'last_name': r.get('last_name', ''), 'merge_data': r.get('merge_data', {})}
|
||||
)
|
||||
created.append(rec)
|
||||
return Response({'count': len(created)}, status=status.HTTP_201_CREATED)
|
||||
dispatched_count = dispatch_campaign(campaign.id)
|
||||
return Response({
|
||||
'status': 'dispatched',
|
||||
'dispatched_count': dispatched_count,
|
||||
'sent_count': dispatched_count,
|
||||
'campaign_id': campaign.id
|
||||
}, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class TrackEmailOpenView(APIView):
|
||||
permission_classes = [AllowAny]
|
||||
|
||||
def get(self, request, token=None):
|
||||
try:
|
||||
recipient = CampaignRecipient.objects.get(tracking_token=token)
|
||||
if not recipient.opened_at:
|
||||
recipient.opened_at = timezone.now()
|
||||
recipient.status = 'opened'
|
||||
recipient.save(update_fields=['opened_at', 'status'])
|
||||
except CampaignRecipient.DoesNotExist:
|
||||
pass
|
||||
if token:
|
||||
CampaignRecipient.objects.filter(
|
||||
tracking_token=token,
|
||||
opened_at__isnull=True
|
||||
).update(opened_at=timezone.now() if 'timezone' in globals() else None)
|
||||
return HttpResponse(PIXEL_GIF_BYTES, content_type='image/gif')
|
||||
|
|
|
|||
|
|
@ -1,19 +1,19 @@
|
|||
import pytest
|
||||
from django.db import transaction
|
||||
from rest_framework.test import APIClient
|
||||
from django.contrib.auth.models import User
|
||||
from crm_core.models import Account
|
||||
from workflows.models import FlowDefinition
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
def test_flow_failure_rolls_back_triggering_record():
|
||||
def test_flow_failure_rolls_back_account_via_viewset_endpoint():
|
||||
"""
|
||||
Test that an active record-triggered flow failure rolls back the triggering record
|
||||
outside of implicit test transactions.
|
||||
when calling the AccountViewSet POST endpoint directly, WITHOUT any manual transaction.atomic wrapper in test!
|
||||
"""
|
||||
# Create an active flow that intentionally fails
|
||||
failing_dag = {
|
||||
"nodes": [
|
||||
{"id": "start", "type": "trigger", "data": {}},
|
||||
{"id": "step_fail", "type": "subflow", "data": {"flow_id": 999999}} # Will raise ValidationError
|
||||
{"id": "step_fail", "type": "subflow", "data": {"flow_id": 999999}}
|
||||
],
|
||||
"edges": [
|
||||
{"source": "start", "target": "step_fail"}
|
||||
|
|
@ -27,12 +27,15 @@ def test_flow_failure_rolls_back_triggering_record():
|
|||
graph=failing_dag
|
||||
)
|
||||
|
||||
account_name = "Doomed Transaction Account"
|
||||
# Attempt to create Account in an atomic block
|
||||
with pytest.raises(Exception):
|
||||
with transaction.atomic():
|
||||
Account.objects.create(name=account_name)
|
||||
user = User.objects.create_user(username="test_rollback_user", password="password")
|
||||
client = APIClient()
|
||||
client.force_authenticate(user=user)
|
||||
|
||||
# Verify that the Account was rolled back and does not exist in the database
|
||||
account_name = "Doomed Endpoint Account"
|
||||
# Call the actual DRF endpoint without any transaction wrapper in the test
|
||||
with pytest.raises(Exception):
|
||||
client.post('/api/accounts/', {'name': account_name}, format='json')
|
||||
|
||||
# Verify that the Account was rolled back and does not exist in the database!
|
||||
exists = Account.objects.filter(name=account_name).exists()
|
||||
assert not exists, "Account creation MUST be rolled back when record-triggered flow fails!"
|
||||
assert not exists, "Account creation via API endpoint MUST roll back when record-triggered flow fails!"
|
||||
|
|
|
|||
58
tests/test_tenant_isolation.py
Normal file
58
tests/test_tenant_isolation.py
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
import pytest
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework.test import APIClient
|
||||
from crm_core.models import Account, Contact, Lead, Opportunity
|
||||
from custom_objects.models import CustomObjectDefinition, CustomRecord
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestTenantAccessIsolation:
|
||||
|
||||
def setup_method(self):
|
||||
self.user_a = User.objects.create_user(username='tenant_a', password='password123')
|
||||
self.user_b = User.objects.create_user(username='tenant_b', password='password123')
|
||||
self.client_a = APIClient()
|
||||
self.client_a.force_authenticate(user=self.user_a)
|
||||
self.client_b = APIClient()
|
||||
self.client_b.force_authenticate(user=self.user_b)
|
||||
|
||||
def test_tenant_cannot_read_other_tenant_account(self):
|
||||
acct_a = Account.objects.create(name='Tenant A Account', owner=self.user_a)
|
||||
|
||||
# Tenant A can read
|
||||
res_a = self.client_a.get(f'/api/accounts/{acct_a.id}/')
|
||||
assert res_a.status_code == 200
|
||||
|
||||
# Tenant B gets 404
|
||||
res_b = self.client_b.get(f'/api/accounts/{acct_a.id}/')
|
||||
assert res_b.status_code == 404
|
||||
|
||||
def test_tenant_cannot_update_other_tenant_account(self):
|
||||
acct_a = Account.objects.create(name='Tenant A Account', owner=self.user_a)
|
||||
|
||||
# Tenant B attempts write
|
||||
res_b = self.client_b.patch(f'/api/accounts/{acct_a.id}/', {'name': 'Hacked Name'})
|
||||
assert res_b.status_code == 404
|
||||
acct_a.refresh_from_db()
|
||||
assert acct_a.name == 'Tenant A Account'
|
||||
|
||||
def test_tenant_cannot_read_other_tenant_custom_records(self):
|
||||
obj = CustomObjectDefinition.objects.create(name='Widget__c', label='Widget')
|
||||
rec_a = CustomRecord.objects.create(custom_object=obj, owner=self.user_a, data={'title': 'Secret A'})
|
||||
|
||||
# Tenant A can list and retrieve
|
||||
res_a = self.client_a.get(f'/api/custom/Widget__c/{rec_a.id}/')
|
||||
assert res_a.status_code == 200
|
||||
|
||||
# Tenant B is blocked
|
||||
res_b = self.client_b.get(f'/api/custom/Widget__c/{rec_a.id}/')
|
||||
assert res_b.status_code == 404
|
||||
|
||||
def test_tenant_cannot_update_other_tenant_custom_records(self):
|
||||
obj = CustomObjectDefinition.objects.create(name='Gadget__c', label='Gadget')
|
||||
rec_a = CustomRecord.objects.create(custom_object=obj, owner=self.user_a, data={'title': 'Protected'})
|
||||
|
||||
res_b = self.client_b.patch(f'/api/custom/Gadget__c/{rec_a.id}/', {'data': {'title': 'Overwritten'}}, format='json')
|
||||
assert res_b.status_code == 404
|
||||
rec_a.refresh_from_db()
|
||||
assert rec_a.data.get('title') == 'Protected'
|
||||
|
|
@ -220,8 +220,8 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None,
|
|||
continue
|
||||
|
||||
node = node_map.get(node_id, {})
|
||||
node_type = node.get('type') or node_data.get('type')
|
||||
node_data = node.get('data', {})
|
||||
node_type = node.get('type') or node_data.get('type')
|
||||
|
||||
step_record = {
|
||||
'node_id': node_id,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
from django.db import models
|
||||
from rest_framework import viewsets, status
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
|
|
@ -6,28 +8,62 @@ from rest_framework.permissions import IsAuthenticated
|
|||
from .models import FlowDefinition, FlowExecutionLog
|
||||
from .serializers import FlowDefinitionSerializer, FlowExecutionLogSerializer
|
||||
from .engine import execute_flow_dag
|
||||
from openforce.permissions import ScopedOwnerAccessPermission
|
||||
|
||||
|
||||
class FlowDefinitionViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = FlowDefinition.objects.all().order_by('-created_at')
|
||||
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||
queryset = FlowDefinition.objects.all()
|
||||
serializer_class = FlowDefinitionSerializer
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='run')
|
||||
def run_flow(self, request, pk=None):
|
||||
flow = self.get_object()
|
||||
context_data = request.data.get('context', {})
|
||||
idempotency_key = request.data.get('idempotency_key')
|
||||
log = execute_flow_dag(flow, initial_context=context_data, idempotency_key=idempotency_key)
|
||||
return Response(FlowExecutionLogSerializer(log).data, status=status.HTTP_200_OK)
|
||||
def get_queryset(self):
|
||||
qs = super().get_queryset()
|
||||
user = self.request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return qs
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
if hasattr(FlowDefinition, 'created_by'):
|
||||
return qs.filter(models.Q(created_by=user) | models.Q(created_by__isnull=True))
|
||||
return qs
|
||||
|
||||
def perform_create(self, serializer):
|
||||
kwargs = {}
|
||||
if hasattr(FlowDefinition, 'created_by'):
|
||||
kwargs['created_by'] = self.request.user
|
||||
serializer.save(**kwargs)
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='execute')
|
||||
def execute_flow(self, request, pk=None):
|
||||
return self.run_flow(request, pk)
|
||||
def execute(self, request, pk=None):
|
||||
flow = self.get_object()
|
||||
initial_context = request.data.get('context', {})
|
||||
idempotency_key = request.data.get('idempotency_key')
|
||||
execution_log = execute_flow_dag(
|
||||
flow,
|
||||
initial_context=initial_context,
|
||||
idempotency_key=idempotency_key
|
||||
)
|
||||
data = FlowExecutionLogSerializer(execution_log).data
|
||||
data['context_data'] = execution_log.context_data
|
||||
data['status'] = execution_log.status
|
||||
return Response(
|
||||
data,
|
||||
status=status.HTTP_200_OK
|
||||
)
|
||||
|
||||
|
||||
class FlowExecutionLogViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
queryset = FlowExecutionLog.objects.all().order_by('-started_at')
|
||||
queryset = FlowExecutionLog.objects.all()
|
||||
serializer_class = FlowExecutionLogSerializer
|
||||
filterset_fields = ['flow', 'status']
|
||||
|
||||
def get_queryset(self):
|
||||
qs = super().get_queryset()
|
||||
user = self.request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return qs
|
||||
if user.is_superuser or user.is_staff:
|
||||
return qs
|
||||
if hasattr(FlowDefinition, 'created_by'):
|
||||
return qs.filter(flow__created_by=user)
|
||||
return qs
|
||||
|
|
|
|||
Loading…
Reference in a new issue