fix(security, flows, outreach): enforce flow execution authorization, schema scoping, relational isolation, and complete campaign launch
This commit is contained in:
parent
9318bb3736
commit
f579400ac5
16 changed files with 370 additions and 50 deletions
|
|
@ -19,7 +19,24 @@ class CustomFieldsValidationMixin:
|
|||
return attrs
|
||||
|
||||
|
||||
class AccountSerializer(CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
class OwnerScopedRelationMixin:
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
request = self.context.get('request')
|
||||
if request and hasattr(request, 'user') and request.user.is_authenticated:
|
||||
user = request.user
|
||||
if not (user.is_superuser or user.is_staff):
|
||||
for field_name, field in self.fields.items():
|
||||
if isinstance(field, serializers.PrimaryKeyRelatedField):
|
||||
model = getattr(field.queryset, 'model', None)
|
||||
if model:
|
||||
if hasattr(model, 'owner'):
|
||||
field.queryset = field.queryset.filter(owner=user)
|
||||
elif hasattr(model, 'created_by'):
|
||||
field.queryset = field.queryset.filter(created_by=user)
|
||||
|
||||
|
||||
class AccountSerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
entity_name = 'Account'
|
||||
|
||||
class Meta:
|
||||
|
|
@ -28,7 +45,7 @@ class AccountSerializer(CustomFieldsValidationMixin, serializers.ModelSerializer
|
|||
read_only_fields = ['id', 'created_at', 'updated_at']
|
||||
|
||||
|
||||
class ContactSerializer(CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
class ContactSerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
entity_name = 'Contact'
|
||||
|
||||
class Meta:
|
||||
|
|
@ -37,7 +54,7 @@ class ContactSerializer(CustomFieldsValidationMixin, serializers.ModelSerializer
|
|||
read_only_fields = ['id', 'created_at', 'updated_at']
|
||||
|
||||
|
||||
class LeadSerializer(CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
class LeadSerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
entity_name = 'Lead'
|
||||
|
||||
class Meta:
|
||||
|
|
@ -50,7 +67,7 @@ class LeadSerializer(CustomFieldsValidationMixin, serializers.ModelSerializer):
|
|||
]
|
||||
|
||||
|
||||
class OpportunitySerializer(CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
class OpportunitySerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixin, serializers.ModelSerializer):
|
||||
entity_name = 'Opportunity'
|
||||
|
||||
class Meta:
|
||||
|
|
@ -59,7 +76,7 @@ class OpportunitySerializer(CustomFieldsValidationMixin, serializers.ModelSerial
|
|||
read_only_fields = ['id', 'expected_revenue', 'created_at', 'updated_at']
|
||||
|
||||
|
||||
class ActivitySerializer(serializers.ModelSerializer):
|
||||
class ActivitySerializer(OwnerScopedRelationMixin, serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Activity
|
||||
fields = '__all__'
|
||||
|
|
|
|||
|
|
@ -3,7 +3,24 @@ from .models import CustomObjectDefinition, CustomFieldDefinition, CustomRecord
|
|||
from .schema_engine import validate_record_data
|
||||
|
||||
|
||||
class CustomFieldDefinitionSerializer(serializers.ModelSerializer):
|
||||
class OwnerScopedRelationMixin:
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
request = self.context.get('request')
|
||||
if request and hasattr(request, 'user') and request.user.is_authenticated:
|
||||
user = request.user
|
||||
if not (user.is_superuser or user.is_staff):
|
||||
for field_name, field in self.fields.items():
|
||||
if isinstance(field, serializers.PrimaryKeyRelatedField):
|
||||
model = getattr(field.queryset, 'model', None)
|
||||
if model:
|
||||
if hasattr(model, 'owner'):
|
||||
field.queryset = field.queryset.filter(owner=user)
|
||||
elif hasattr(model, 'created_by'):
|
||||
field.queryset = field.queryset.filter(created_by=user)
|
||||
|
||||
|
||||
class CustomFieldDefinitionSerializer(OwnerScopedRelationMixin, serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = CustomFieldDefinition
|
||||
fields = '__all__'
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
from django.db import models, transaction
|
||||
from rest_framework import viewsets, status
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.exceptions import NotFound
|
||||
from rest_framework.exceptions import NotFound, PermissionDenied
|
||||
|
||||
from .models import CustomObjectDefinition, CustomFieldDefinition, CustomRecord
|
||||
from .serializers import (
|
||||
|
|
@ -13,22 +13,48 @@ from openforce.permissions import ScopedOwnerAccessPermission
|
|||
|
||||
|
||||
class CustomObjectDefinitionViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
permission_classes = [ScopedOwnerAccessPermission]
|
||||
queryset = CustomObjectDefinition.objects.all()
|
||||
serializer_class = CustomObjectDefinitionSerializer
|
||||
|
||||
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
|
||||
return qs.filter(created_by=user)
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
serializer.save(created_by=self.request.user)
|
||||
|
||||
|
||||
class CustomFieldDefinitionViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
permission_classes = [ScopedOwnerAccessPermission]
|
||||
queryset = CustomFieldDefinition.objects.all()
|
||||
serializer_class = CustomFieldDefinitionSerializer
|
||||
|
||||
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
|
||||
return qs.filter(
|
||||
models.Q(custom_object__created_by=user) | models.Q(entity_name__isnull=False)
|
||||
)
|
||||
|
||||
def perform_create(self, serializer):
|
||||
with transaction.atomic():
|
||||
# Validate that if custom_object is supplied, user owns it
|
||||
obj = serializer.validated_data.get('custom_object')
|
||||
user = self.request.user
|
||||
if obj and not (user.is_superuser or user.is_staff):
|
||||
if obj.created_by and obj.created_by != user:
|
||||
raise PermissionDenied("Cannot add fields to another user's custom object.")
|
||||
serializer.save()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -144,6 +144,37 @@ export const useCrmStore = defineStore('crm', {
|
|||
},
|
||||
async createCampaign(campaignData) {
|
||||
const res = await api.post('/campaigns/', campaignData)
|
||||
const campaignId = res.data.id
|
||||
|
||||
// Auto-populate recipients from target object (Leads or Contacts) if store has them
|
||||
let recipients = []
|
||||
if (campaignData.target_object === 'Lead' && this.leads.length > 0) {
|
||||
recipients = this.leads.filter(l => l.email).map(l => ({
|
||||
email: l.email,
|
||||
first_name: l.first_name || '',
|
||||
last_name: l.last_name || '',
|
||||
merge_data: { first_name: l.first_name, company: l.company }
|
||||
}))
|
||||
} else if (campaignData.target_object === 'Contact' && this.contacts.length > 0) {
|
||||
recipients = this.contacts.filter(c => c.email).map(c => ({
|
||||
email: c.email,
|
||||
first_name: c.first_name || '',
|
||||
last_name: c.last_name || '',
|
||||
merge_data: { first_name: c.first_name }
|
||||
}))
|
||||
}
|
||||
|
||||
if (recipients.length > 0) {
|
||||
await api.post(`/campaigns/${campaignId}/add-recipients/`, { recipients })
|
||||
}
|
||||
|
||||
// Auto-dispatch campaign
|
||||
try {
|
||||
await api.post(`/campaigns/${campaignId}/dispatch/`)
|
||||
} catch (err) {
|
||||
console.warn('Dispatch failed or pending:', err)
|
||||
}
|
||||
|
||||
await this.fetchCampaigns()
|
||||
return res.data
|
||||
},
|
||||
|
|
|
|||
|
|
@ -36,10 +36,11 @@
|
|||
</button>
|
||||
<button
|
||||
@click="runFlow"
|
||||
:disabled="isRunning"
|
||||
:disabled="isRunning || !currentFlowId"
|
||||
:title="!currentFlowId ? 'Please save the flow before running' : 'Run Flow'"
|
||||
class="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-semibold rounded-md shadow-sm transition disabled:opacity-50"
|
||||
>
|
||||
{{ isRunning ? 'Running...' : 'Run Flow' }}
|
||||
{{ isRunning ? 'Running...' : (currentFlowId ? `Run Flow (#${currentFlowId})` : 'Run Flow (Save First)') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -259,9 +260,18 @@ async function saveFlow() {
|
|||
}
|
||||
|
||||
async function runFlow() {
|
||||
if (!currentFlowId.value) {
|
||||
executionResult.value = {
|
||||
status: 'failed',
|
||||
error: 'Cannot run flow: flow must be saved before execution. Please click "Save Flow".',
|
||||
steps_executed: [],
|
||||
context_data: {}
|
||||
}
|
||||
return
|
||||
}
|
||||
isRunning.value = true
|
||||
try {
|
||||
const flowId = currentFlowId.value || 1
|
||||
const flowId = currentFlowId.value
|
||||
const res = await api.post(`/workflows/${flowId}/execute/`, {
|
||||
context: {
|
||||
record: { id: 101, name: 'Acme Corp', amount: 75000 },
|
||||
|
|
@ -273,7 +283,7 @@ async function runFlow() {
|
|||
console.error('Execute API error:', err)
|
||||
executionResult.value = {
|
||||
status: 'failed',
|
||||
error: err.response?.data?.detail || err.message || 'Execution failed',
|
||||
error: err.response?.data?.error || err.response?.data?.detail || err.message || 'Execution failed',
|
||||
steps_executed: [],
|
||||
context_data: {}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ 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.
|
||||
Default-denies access if object ownership is absent or not matched.
|
||||
"""
|
||||
def has_permission(self, request, view):
|
||||
return request.user and request.user.is_authenticated
|
||||
|
|
@ -21,4 +22,11 @@ class ScopedOwnerAccessPermission(permissions.BasePermission):
|
|||
created_by = getattr(obj, 'created_by', None)
|
||||
if created_by is not None:
|
||||
return created_by == user
|
||||
return True
|
||||
# In CustomFieldDefinition, check custom_object's creator
|
||||
custom_obj = getattr(obj, 'custom_object', None)
|
||||
if custom_obj is not None:
|
||||
c_created_by = getattr(custom_obj, 'created_by', None)
|
||||
if c_created_by is not None:
|
||||
return c_created_by == user
|
||||
# Default-deny if no ownership fields exist or if unowned
|
||||
return False
|
||||
|
|
|
|||
|
|
@ -18,6 +18,11 @@ class CampaignRecipientSerializer(serializers.ModelSerializer):
|
|||
|
||||
class CampaignSerializer(serializers.ModelSerializer):
|
||||
recipients = CampaignRecipientSerializer(many=True, read_only=True)
|
||||
template = serializers.PrimaryKeyRelatedField(
|
||||
queryset=EmailTemplate.objects.all(),
|
||||
required=False,
|
||||
allow_null=True
|
||||
)
|
||||
sent_count = serializers.SerializerMethodField()
|
||||
open_count = serializers.SerializerMethodField()
|
||||
click_count = serializers.SerializerMethodField()
|
||||
|
|
@ -27,6 +32,26 @@ class CampaignSerializer(serializers.ModelSerializer):
|
|||
fields = '__all__'
|
||||
read_only_fields = ['id', 'created_at', 'updated_at']
|
||||
|
||||
def create(self, validated_data):
|
||||
template = validated_data.get('template')
|
||||
if not template:
|
||||
# Fallback or create a default template matching campaign subject/name
|
||||
name = validated_data.get('name', 'Default Campaign')
|
||||
subject = validated_data.get('subject', name)
|
||||
request = self.context.get('request')
|
||||
created_by = request.user if request and request.user and request.user.is_authenticated else None
|
||||
template, _ = EmailTemplate.objects.get_or_create(
|
||||
name=f"{name} Template",
|
||||
defaults={
|
||||
'subject': subject,
|
||||
'body_html': '<p>Hello {{first_name}},</p><p>We are reaching out to you regarding your account.</p>',
|
||||
'body_text': 'Hello {{first_name}},\nWe are reaching out to you regarding your account.',
|
||||
'created_by': created_by
|
||||
}
|
||||
)
|
||||
validated_data['template'] = template
|
||||
return super().create(validated_data)
|
||||
|
||||
def get_sent_count(self, obj):
|
||||
return obj.recipients.filter(status__in=['sent', 'delivered', 'opened', 'clicked']).count()
|
||||
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ class EmailTemplateViewSet(viewsets.ModelViewSet):
|
|||
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.filter(created_by=user)
|
||||
return qs
|
||||
|
||||
def perform_create(self, serializer):
|
||||
|
|
@ -56,7 +56,7 @@ class CampaignViewSet(viewsets.ModelViewSet):
|
|||
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.filter(created_by=user)
|
||||
return qs
|
||||
|
||||
def perform_create(self, serializer):
|
||||
|
|
@ -65,6 +65,20 @@ class CampaignViewSet(viewsets.ModelViewSet):
|
|||
kwargs['created_by'] = self.request.user
|
||||
serializer.save(**kwargs)
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='add-recipients')
|
||||
def add_recipients(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)
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='dispatch')
|
||||
def dispatch_action(self, request, pk=None):
|
||||
campaign = self.get_object()
|
||||
|
|
@ -82,8 +96,13 @@ class TrackEmailOpenView(APIView):
|
|||
|
||||
def get(self, request, token=None):
|
||||
if token:
|
||||
CampaignRecipient.objects.filter(
|
||||
tracking_token=token,
|
||||
opened_at__isnull=True
|
||||
).update(opened_at=timezone.now() if 'timezone' in globals() else None)
|
||||
now = timezone.now()
|
||||
# Update opened_at and advance status to 'opened' if not already opened/clicked
|
||||
recipients = CampaignRecipient.objects.filter(tracking_token=token)
|
||||
for recipient in recipients:
|
||||
if not recipient.opened_at:
|
||||
recipient.opened_at = now
|
||||
if recipient.status in ('pending', 'sent', 'delivered'):
|
||||
recipient.status = 'opened'
|
||||
recipient.save()
|
||||
return HttpResponse(PIXEL_GIF_BYTES, content_type='image/gif')
|
||||
|
|
|
|||
|
|
@ -60,3 +60,10 @@ def test_diamond_rejoin_execution():
|
|||
assert ctx.get("executed_a") is True, "Branch A should have executed"
|
||||
assert ctx.get("executed_b") is not True, "Branch B must NEVER execute"
|
||||
assert ctx.get("executed_join") is True, "Diamond join node MUST execute when reached via Branch A"
|
||||
|
||||
# Opposite branch test: status == 'B'
|
||||
result_b = execute_flow_dag(graph, initial_context={"status": "B"})
|
||||
ctx_b = result_b if isinstance(result_b, dict) else result_b.context
|
||||
assert ctx_b.get("executed_b") is True, "Branch B should have executed when status is B"
|
||||
assert ctx_b.get("executed_a") is not True, "Branch A must NEVER execute when status is B"
|
||||
assert ctx_b.get("executed_join") is True, "Diamond join node MUST execute when reached via Branch B"
|
||||
|
|
|
|||
|
|
@ -14,45 +14,61 @@ def test_vue_flow_initial_graph_executes_successfully():
|
|||
{
|
||||
"id": "start-trigger",
|
||||
"type": "input",
|
||||
"data": {"type": "trigger"}
|
||||
"label": "⚡ Trigger: Account Created",
|
||||
"position": {"x": 100, "y": 150},
|
||||
"class": "bg-emerald-600 text-white font-semibold text-xs p-3 rounded-lg shadow-md border-0"
|
||||
},
|
||||
{
|
||||
"id": "decision-tier",
|
||||
"type": "decision",
|
||||
"label": "⚖️ Decision: VIP Tier Check",
|
||||
"position": {"x": 340, "y": 150},
|
||||
"data": {
|
||||
"type": "decision",
|
||||
"conditions": [
|
||||
{"field": "amount", "op": "gte", "value": 50000, "target_node": "assign-vip"},
|
||||
{"field": "amount", "op": "gte", "value": 10000, "target_node": "assign-standard"}
|
||||
],
|
||||
"default_target": "assign-standard"
|
||||
}
|
||||
},
|
||||
"class": "bg-indigo-600 text-white font-semibold text-xs p-3 rounded-lg shadow-md border-0"
|
||||
},
|
||||
{
|
||||
"id": "assign-vip",
|
||||
"type": "assignment",
|
||||
"label": "💎 Assignment: VIP Customer",
|
||||
"position": {"x": 600, "y": 80},
|
||||
"data": {
|
||||
"type": "assignment",
|
||||
"assignments": [
|
||||
{"variable": "account_tier", "op": "equals", "value": "VIP"},
|
||||
{"variable": "priority_score", "op": "add", "value": 100}
|
||||
]
|
||||
}
|
||||
},
|
||||
"class": "bg-blue-600 text-white font-semibold text-xs p-3 rounded-lg shadow-md border-0"
|
||||
},
|
||||
{
|
||||
"id": "assign-standard",
|
||||
"type": "assignment",
|
||||
"label": "📦 Assignment: Standard Customer",
|
||||
"position": {"x": 600, "y": 220},
|
||||
"data": {
|
||||
"type": "assignment",
|
||||
"assignments": [
|
||||
{"variable": "account_tier", "op": "equals", "value": "Standard"},
|
||||
{"variable": "priority_score", "op": "add", "value": 10}
|
||||
]
|
||||
}
|
||||
},
|
||||
"class": "bg-slate-600 text-white font-semibold text-xs p-3 rounded-lg shadow-md border-0"
|
||||
},
|
||||
{
|
||||
"id": "subflow-sync",
|
||||
"type": "subflow",
|
||||
"label": "🔄 Subflow: Sync to Billing",
|
||||
"position": {"x": 860, "y": 150},
|
||||
"data": {
|
||||
"subflow_id": subflow.id
|
||||
}
|
||||
"type": "subflow",
|
||||
"subflow_id": subflow.id,
|
||||
"input_mapping": {"customer_id": "record.id"},
|
||||
"output_mapping": {"sync_status": "status"}
|
||||
},
|
||||
"class": "bg-violet-600 text-white font-semibold text-xs p-3 rounded-lg shadow-md border-0"
|
||||
}
|
||||
],
|
||||
"edges": [
|
||||
|
|
|
|||
|
|
@ -21,7 +21,8 @@ class TestOutreachAndWorkflowEndpoints(TestCase):
|
|||
campaign = Campaign.objects.create(
|
||||
name='Summer Campaign',
|
||||
template=template,
|
||||
status='draft'
|
||||
status='draft',
|
||||
created_by=self.user
|
||||
)
|
||||
CampaignRecipient.objects.create(
|
||||
campaign=campaign,
|
||||
|
|
@ -48,6 +49,7 @@ class TestOutreachAndWorkflowEndpoints(TestCase):
|
|||
def test_workflow_execute_api(self):
|
||||
flow = FlowDefinition.objects.create(
|
||||
name='Lead Scoring Flow',
|
||||
created_by=self.user,
|
||||
graph={
|
||||
'nodes': [{'id': 'n1', 'type': 'action', 'data': {'action': 'increment_score', 'points': 10}}],
|
||||
'edges': []
|
||||
|
|
|
|||
|
|
@ -106,3 +106,49 @@ class TestOutreachEngine:
|
|||
assert email2.to == ['bob@example.com']
|
||||
assert email2.subject == 'Special Offer for Bob'
|
||||
assert str(rec2.tracking_token) in email2.alternatives[0][0]
|
||||
|
||||
def test_campaign_launch_modal_payload_and_tracking_open(self):
|
||||
from rest_framework.test import APIClient
|
||||
from django.contrib.auth.models import User
|
||||
user = User.objects.create_user('outreach_user', 'outreach@test.com', 'pw')
|
||||
client = APIClient()
|
||||
client.force_authenticate(user=user)
|
||||
|
||||
# 1. UI payload with only {name, subject, target_object} without explicit template
|
||||
res = client.post('/api/campaigns/', {
|
||||
'name': 'UI Launched Campaign',
|
||||
'subject': 'Special Offer For You',
|
||||
'target_object': 'Lead'
|
||||
}, format='json')
|
||||
assert res.status_code == 201
|
||||
campaign_id = res.data['id']
|
||||
assert res.data['template'] is not None
|
||||
|
||||
# 2. Add recipient
|
||||
add_res = client.post(f'/api/campaigns/{campaign_id}/add-recipients/', {
|
||||
'recipients': [{'email': 'prospect@example.com', 'first_name': 'Prospect'}]
|
||||
}, format='json')
|
||||
assert add_res.status_code == 201
|
||||
assert add_res.data['count'] == 1
|
||||
|
||||
# 3. Dispatch
|
||||
dispatch_res = client.post(f'/api/campaigns/{campaign_id}/dispatch/')
|
||||
assert dispatch_res.status_code == 200
|
||||
|
||||
# Check metrics before open
|
||||
camp_res = client.get(f'/api/campaigns/{campaign_id}/')
|
||||
assert camp_res.data['sent_count'] == 1
|
||||
assert camp_res.data['open_count'] == 0
|
||||
|
||||
# 4. Open tracking pixel
|
||||
recipient = CampaignRecipient.objects.get(campaign_id=campaign_id)
|
||||
open_res = client.get(f'/api/outreach/track/open/{recipient.tracking_token}/')
|
||||
assert open_res.status_code == 200
|
||||
|
||||
recipient.refresh_from_db()
|
||||
assert recipient.opened_at is not None
|
||||
assert recipient.status == 'opened'
|
||||
|
||||
# Check metrics after open
|
||||
camp_res = client.get(f'/api/campaigns/{campaign_id}/')
|
||||
assert camp_res.data['open_count'] == 1
|
||||
|
|
|
|||
|
|
@ -49,10 +49,57 @@ class TestTenantAccessIsolation:
|
|||
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')
|
||||
obj = CustomObjectDefinition.objects.create(name='Gadget__c', label='Gadget', created_by=self.user_a)
|
||||
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'
|
||||
|
||||
def test_tenant_cannot_patch_other_tenant_custom_object_definition(self):
|
||||
obj = CustomObjectDefinition.objects.create(name='Invoice__c', label='Invoice', created_by=self.user_a)
|
||||
res_b = self.client_b.patch(f'/api/custom-objects/{obj.id}/', {'label': 'Hacked Invoice'})
|
||||
assert res_b.status_code == 404
|
||||
obj.refresh_from_db()
|
||||
assert obj.label == 'Invoice'
|
||||
|
||||
def test_tenant_cannot_attach_foreign_relation(self):
|
||||
acct_a = Account.objects.create(name='Tenant A Account', owner=self.user_a)
|
||||
res_b = self.client_b.post('/api/contacts/', {
|
||||
'first_name': 'Sneaky',
|
||||
'last_name': 'Contact',
|
||||
'account': acct_a.id
|
||||
}, format='json')
|
||||
assert res_b.status_code == 400
|
||||
assert 'account' in res_b.data
|
||||
|
||||
def test_tenant_cannot_modify_foreign_record_via_flow_execution(self):
|
||||
from workflows.models import FlowDefinition
|
||||
acct_a = Account.objects.create(name='Untouchable Account', owner=self.user_a)
|
||||
|
||||
hack_graph = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'update', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Account',
|
||||
'record_id_source': 'context.record_id',
|
||||
'field_updates': {'name': 'Changed by Bob'}
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'update'}]
|
||||
}
|
||||
flow_b = FlowDefinition.objects.create(
|
||||
name='Bob Flow',
|
||||
created_by=self.user_b,
|
||||
trigger_type='manual',
|
||||
graph=hack_graph,
|
||||
is_active=True
|
||||
)
|
||||
|
||||
res_b = self.client_b.post(f'/api/workflows/{flow_b.id}/execute/', {
|
||||
'context': {'record_id': acct_a.id}
|
||||
}, format='json')
|
||||
assert res_b.status_code == 400
|
||||
acct_a.refresh_from_db()
|
||||
assert acct_a.name == 'Untouchable Account'
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import threading
|
||||
import logging
|
||||
from django.db import models
|
||||
from django.db.models.signals import pre_save, post_save
|
||||
from django.dispatch import receiver
|
||||
from .models import FlowDefinition, FlowExecutionLog
|
||||
|
|
@ -90,6 +91,13 @@ def on_record_post_save(sender, instance, created, **kwargs):
|
|||
trigger_object__iexact=model_name
|
||||
)
|
||||
|
||||
# Scope flows to the record's owner/creator if multi-tenancy applies
|
||||
owner = getattr(instance, 'owner', None) or getattr(instance, 'created_by', None)
|
||||
if owner and hasattr(FlowDefinition, 'created_by'):
|
||||
flows = flows.filter(models.Q(created_by=owner) | models.Q(created_by__isnull=True))
|
||||
elif hasattr(FlowDefinition, 'created_by'):
|
||||
flows = flows.filter(created_by__isnull=True)
|
||||
|
||||
current_state = snapshot_model(instance)
|
||||
prior_state = getattr(instance, '_prior_state', {})
|
||||
|
||||
|
|
|
|||
|
|
@ -111,7 +111,7 @@ def evaluate_condition(cond, context):
|
|||
|
||||
|
||||
def evaluate_outcome(outcome, context):
|
||||
conditions = outcome.get('conditions', [])
|
||||
conditions = outcome.get('conditions') or outcome.get('rules') or []
|
||||
if not conditions:
|
||||
return True # Default / Else branch
|
||||
logic = outcome.get('logic', 'AND').upper()
|
||||
|
|
@ -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):
|
||||
def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None, depth=0, user=None):
|
||||
from .models import FlowDefinition, FlowExecutionLog
|
||||
|
||||
MAX_SUBFLOW_DEPTH = 10
|
||||
|
|
@ -245,19 +245,36 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None,
|
|||
for k, v in node_data.items():
|
||||
context[k] = v
|
||||
# Check if this flow was triggered by a model record and update DB record if field/value specified
|
||||
field = node_data.get('field')
|
||||
val = node_data.get('value')
|
||||
record_id = context.get('record_id')
|
||||
record_type = context.get('record_type')
|
||||
if field and val is not None and record_id and record_type:
|
||||
record_type = context.get('record_type') or node_data.get('target_model')
|
||||
|
||||
# Check for direct field/value or field_updates dict
|
||||
updates = {}
|
||||
if node_data.get('field') and node_data.get('value') is not None:
|
||||
updates[node_data.get('field')] = node_data.get('value')
|
||||
if isinstance(node_data.get('field_updates'), dict):
|
||||
updates.update(node_data.get('field_updates'))
|
||||
|
||||
if updates and record_id and record_type:
|
||||
from django.apps import apps
|
||||
model_cls = apps.get_model('crm_core', record_type)
|
||||
if not model_cls:
|
||||
model_cls = apps.get_model('custom_objects', record_type)
|
||||
if model_cls:
|
||||
inst = model_cls.objects.filter(pk=record_id).first()
|
||||
if inst and hasattr(inst, field):
|
||||
setattr(inst, field, val)
|
||||
# Authorize record lookup by user principal if user is provided and not staff
|
||||
qs = model_cls.objects.filter(pk=record_id)
|
||||
if user 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)
|
||||
inst = qs.first()
|
||||
if not inst and user and not (user.is_superuser or user.is_staff):
|
||||
raise ValidationError(f"Permission denied: cannot update unauthorized record {record_type}:{record_id}")
|
||||
if inst:
|
||||
for f_name, f_val in updates.items():
|
||||
if hasattr(inst, f_name):
|
||||
setattr(inst, f_name, f_val)
|
||||
inst.save()
|
||||
|
||||
elif node_type == 'assignment':
|
||||
|
|
@ -356,14 +373,18 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None,
|
|||
child_flow_id = node_data.get('flow_id') or node_data.get('subflow_id')
|
||||
if not child_flow_id:
|
||||
raise ValidationError("Subflow node requires flow_id.")
|
||||
child_flow = FlowDefinition.objects.filter(pk=child_flow_id).first()
|
||||
child_qs = FlowDefinition.objects.filter(pk=child_flow_id)
|
||||
if user and not (user.is_superuser or user.is_staff):
|
||||
child_qs = child_qs.filter(created_by=user)
|
||||
child_flow = child_qs.first()
|
||||
if not child_flow:
|
||||
raise ValidationError(f"Referenced child flow {child_flow_id} not found.")
|
||||
raise ValidationError(f"Referenced child flow {child_flow_id} not found or unauthorized.")
|
||||
|
||||
child_res = execute_flow_dag(
|
||||
child_flow.graph,
|
||||
initial_context=context,
|
||||
depth=depth + 1
|
||||
depth=depth + 1,
|
||||
user=user
|
||||
)
|
||||
if isinstance(child_res, dict):
|
||||
context.update(child_res)
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ class FlowDefinitionViewSet(viewsets.ModelViewSet):
|
|||
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.filter(created_by=user)
|
||||
return qs
|
||||
|
||||
def perform_create(self, serializer):
|
||||
|
|
@ -38,11 +38,31 @@ class FlowDefinitionViewSet(viewsets.ModelViewSet):
|
|||
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
|
||||
)
|
||||
user = request.user if request.user and request.user.is_authenticated else None
|
||||
try:
|
||||
execution_log = execute_flow_dag(
|
||||
flow,
|
||||
initial_context=initial_context,
|
||||
idempotency_key=idempotency_key,
|
||||
user=user
|
||||
)
|
||||
except Exception as e:
|
||||
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
|
||||
},
|
||||
status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
data = FlowExecutionLogSerializer(execution_log).data
|
||||
data['context_data'] = execution_log.context_data
|
||||
data['status'] = execution_log.status
|
||||
|
|
|
|||
Loading…
Reference in a new issue