fix(isolation): enforce trigger execution identity, per-flow idempotency scoping, and tenant-scoped email templates
This commit is contained in:
parent
e81d4339c3
commit
eb3a85586a
8 changed files with 176 additions and 17 deletions
|
|
@ -0,0 +1,22 @@
|
|||
# Generated by Django 4.2.30 on 2026-09-26 22:26
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('outreach', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='emailtemplate',
|
||||
name='name',
|
||||
field=models.CharField(max_length=255),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='emailtemplate',
|
||||
constraint=models.UniqueConstraint(condition=models.Q(('created_by__isnull', False)), fields=('created_by', 'name'), name='unique_template_name_per_user'),
|
||||
),
|
||||
]
|
||||
|
|
@ -8,7 +8,7 @@ User = get_user_model()
|
|||
|
||||
|
||||
class EmailTemplate(models.Model):
|
||||
name = models.CharField(max_length=255, unique=True)
|
||||
name = models.CharField(max_length=255)
|
||||
subject = models.CharField(max_length=255)
|
||||
body_html = models.TextField(help_text="HTML content supporting merge tags like {{first_name}}")
|
||||
body_text = models.TextField(blank=True, default='')
|
||||
|
|
@ -17,6 +17,15 @@ class EmailTemplate(models.Model):
|
|||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=['created_by', 'name'],
|
||||
name='unique_template_name_per_user',
|
||||
condition=models.Q(created_by__isnull=False)
|
||||
)
|
||||
]
|
||||
|
||||
def render(self, context):
|
||||
"""
|
||||
Safely renders template variables with {{var_name}} merge tags.
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
from rest_framework import serializers
|
||||
from crm_core.serializers import OwnerScopedRelationMixin
|
||||
from .models import EmailTemplate, Campaign, CampaignRecipient
|
||||
|
||||
|
||||
|
|
@ -16,13 +17,14 @@ class CampaignRecipientSerializer(serializers.ModelSerializer):
|
|||
read_only_fields = ['id', 'tracking_token', 'sent_at', 'opened_at', 'clicked_at']
|
||||
|
||||
|
||||
class CampaignSerializer(serializers.ModelSerializer):
|
||||
class CampaignSerializer(OwnerScopedRelationMixin, serializers.ModelSerializer):
|
||||
recipients = CampaignRecipientSerializer(many=True, read_only=True)
|
||||
template = serializers.PrimaryKeyRelatedField(
|
||||
queryset=EmailTemplate.objects.all(),
|
||||
required=False,
|
||||
allow_null=True
|
||||
)
|
||||
subject = serializers.CharField(write_only=True, required=False, allow_blank=True)
|
||||
sent_count = serializers.SerializerMethodField()
|
||||
open_count = serializers.SerializerMethodField()
|
||||
click_count = serializers.SerializerMethodField()
|
||||
|
|
@ -33,20 +35,21 @@ class CampaignSerializer(serializers.ModelSerializer):
|
|||
read_only_fields = ['id', 'created_at', 'updated_at']
|
||||
|
||||
def create(self, validated_data):
|
||||
user_subject = validated_data.pop('subject', None)
|
||||
template = validated_data.get('template')
|
||||
if not template:
|
||||
# Fallback or create a default template matching campaign subject/name
|
||||
# Fallback or create a default template matching campaign subject/name scoped to user
|
||||
name = validated_data.get('name', 'Default Campaign')
|
||||
subject = validated_data.get('subject', name)
|
||||
subject = user_subject or 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",
|
||||
created_by=created_by,
|
||||
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
|
||||
|
|
|
|||
|
|
@ -136,3 +136,103 @@ class TestTenantAccessIsolation:
|
|||
is_authenticated = False
|
||||
req.user = AnonUser()
|
||||
assert not perm.has_permission(req, None)
|
||||
|
||||
def test_record_triggered_flow_cannot_modify_foreign_record(self):
|
||||
from workflows.models import FlowDefinition
|
||||
acct_alice = Account.objects.create(name='Alice Account', owner=self.user_a)
|
||||
|
||||
# Bob creates a record-triggered flow on Account creation that updates Alice's account
|
||||
hack_graph = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'upd', 'type': 'update_record', 'data': {
|
||||
'target_model': 'Account',
|
||||
'field_updates': {'name': 'Compromised by Trigger'}
|
||||
}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'upd'}]
|
||||
}
|
||||
FlowDefinition.objects.create(
|
||||
name='Bob Trigger Flow',
|
||||
created_by=self.user_b,
|
||||
trigger_type='record_created',
|
||||
trigger_object='Account',
|
||||
is_active=True,
|
||||
graph=hack_graph
|
||||
)
|
||||
|
||||
# Bob creates an account via API and attempts to pass Alice's record_id in context
|
||||
# Even if triggered, update_record is evaluated under Bob's execution principal
|
||||
# so it cannot update Alice's record.
|
||||
with pytest.raises(Exception):
|
||||
# When trigger runs under Bob principal targeting Alice's record ID,
|
||||
# it raises PermissionDenied and prevents the modification
|
||||
from workflows.dispatcher import dispatch_flow
|
||||
flow = FlowDefinition.objects.get(name='Bob Trigger Flow')
|
||||
dispatch_flow(flow, context={'record_id': acct_alice.id, 'record_type': 'Account'}, user=self.user_b)
|
||||
|
||||
acct_alice.refresh_from_db()
|
||||
assert acct_alice.name == 'Alice Account'
|
||||
|
||||
def test_idempotency_key_does_not_leak_other_user_execution(self):
|
||||
from workflows.models import FlowDefinition, FlowExecutionLog
|
||||
dag = {
|
||||
'nodes': [
|
||||
{'id': 'start', 'type': 'trigger', 'data': {}},
|
||||
{'id': 'assign', 'type': 'assignment', 'data': {'variable': 'secret', 'value': 'AliceTopSecret'}}
|
||||
],
|
||||
'edges': [{'source': 'start', 'target': 'assign'}]
|
||||
}
|
||||
flow_alice = FlowDefinition.objects.create(
|
||||
name='Alice Secret Flow',
|
||||
created_by=self.user_a,
|
||||
trigger_type='manual',
|
||||
graph=dag,
|
||||
is_active=True
|
||||
)
|
||||
flow_bob = FlowDefinition.objects.create(
|
||||
name='Bob Innocent Flow',
|
||||
created_by=self.user_b,
|
||||
trigger_type='manual',
|
||||
graph=dag,
|
||||
is_active=True
|
||||
)
|
||||
|
||||
# Alice runs with key 'shared-key-123'
|
||||
res_a = self.client_a.post(f'/api/workflows/{flow_alice.id}/execute/', {
|
||||
'idempotency_key': 'shared-key-123'
|
||||
}, format='json')
|
||||
assert res_a.status_code == 200
|
||||
|
||||
# Bob attempts to execute his flow using Alice's idempotency key
|
||||
res_b = self.client_b.post(f'/api/workflows/{flow_bob.id}/execute/', {
|
||||
'idempotency_key': 'shared-key-123'
|
||||
}, format='json')
|
||||
assert res_b.status_code == 200
|
||||
# Bob must get his own run, not Alice's execution log/context
|
||||
assert res_b.data['id'] != res_a.data['id']
|
||||
|
||||
def test_campaign_template_collision_creates_separate_tenant_template(self):
|
||||
from outreach.models import EmailTemplate
|
||||
# Alice creates a template named "Launch Template"
|
||||
alice_tmpl = EmailTemplate.objects.create(
|
||||
name="Launch Template",
|
||||
created_by=self.user_a,
|
||||
subject="Alice Subject",
|
||||
body_html="<p>Alice</p>",
|
||||
body_text="Alice"
|
||||
)
|
||||
|
||||
# Bob creates a campaign named "Launch" with modal fallback
|
||||
res_b = self.client_b.post('/api/campaigns/', {
|
||||
'name': 'Launch',
|
||||
'subject': 'Bob Subject',
|
||||
'target_object': 'Lead'
|
||||
}, format='json')
|
||||
assert res_b.status_code == 201
|
||||
|
||||
# Must have created Bob's own template, not reused Alice's
|
||||
bob_tmpl = EmailTemplate.objects.filter(name="Launch Template", created_by=self.user_b).first()
|
||||
assert bob_tmpl is not None
|
||||
assert bob_tmpl.id != alice_tmpl.id
|
||||
assert bob_tmpl.created_by == self.user_b
|
||||
|
|
|
|||
|
|
@ -19,13 +19,14 @@ def _set_active_flow_depth(val):
|
|||
|
||||
MAX_SIGNAL_REENTRANCY_DEPTH = 1
|
||||
|
||||
def dispatch_flow(flow, context=None, idempotency_key=None):
|
||||
def dispatch_flow(flow, context=None, idempotency_key=None, user=None):
|
||||
"""
|
||||
Dispatches a single flow execution with the given context.
|
||||
Dispatches a single flow execution with the given context and user principal.
|
||||
"""
|
||||
if context is None:
|
||||
context = {}
|
||||
return execute_flow_dag(flow, initial_context=context, idempotency_key=idempotency_key)
|
||||
exec_user = user or getattr(flow, 'created_by', None)
|
||||
return execute_flow_dag(flow, initial_context=context, idempotency_key=idempotency_key, user=exec_user)
|
||||
|
||||
def snapshot_model(instance):
|
||||
data = {}
|
||||
|
|
@ -115,6 +116,7 @@ def on_record_post_save(sender, instance, created, **kwargs):
|
|||
# Under Salesforce transactional contract (docs/SALESFORCE_FLOW_ENGINE_SPEC.md:108),
|
||||
# an unhandled failure in a synchronous record-triggered flow must fail
|
||||
# the transaction and roll back the triggering record modification.
|
||||
dispatch_flow(flow, context=context)
|
||||
exec_user = getattr(flow, 'created_by', None) or owner
|
||||
dispatch_flow(flow, context=context, user=exec_user)
|
||||
finally:
|
||||
_set_active_flow_depth(depth)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
from collections import deque
|
||||
from django.utils import timezone
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.exceptions import ValidationError, PermissionDenied
|
||||
|
||||
|
||||
def validate_flow_dag(graph):
|
||||
|
|
@ -165,7 +165,7 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None,
|
|||
validate_flow_dag(graph)
|
||||
|
||||
if not is_dict and idempotency_key:
|
||||
existing = FlowExecutionLog.objects.filter(idempotency_key=idempotency_key).first()
|
||||
existing = FlowExecutionLog.objects.filter(flow=flow_def, idempotency_key=idempotency_key).first()
|
||||
if existing:
|
||||
return existing
|
||||
|
||||
|
|
@ -261,16 +261,18 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None,
|
|||
if not model_cls:
|
||||
model_cls = apps.get_model('custom_objects', record_type)
|
||||
if model_cls:
|
||||
# Authorize record lookup by user principal if user is provided and not staff
|
||||
# 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}")
|
||||
inst = qs.first()
|
||||
if not inst:
|
||||
raise PermissionDenied(f"Permission denied: cannot update unauthorized record {record_type}:{record_id}")
|
||||
else:
|
||||
inst = qs.first()
|
||||
if inst:
|
||||
for f_name, f_val in updates.items():
|
||||
if hasattr(inst, f_name):
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
# Generated by Django 4.2.30 on 2026-09-26 22:23
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('workflows', '0002_flowdefinition_trigger_object_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveConstraint(
|
||||
model_name='flowexecutionlog',
|
||||
name='unique_idempotency_key_when_not_null',
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='flowexecutionlog',
|
||||
constraint=models.UniqueConstraint(condition=models.Q(('idempotency_key__isnull', False)), fields=('flow', 'idempotency_key'), name='unique_flow_idempotency_key_when_not_null'),
|
||||
),
|
||||
]
|
||||
|
|
@ -67,8 +67,8 @@ class FlowExecutionLog(models.Model):
|
|||
ordering = ['-started_at']
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=['idempotency_key'],
|
||||
name='unique_idempotency_key_when_not_null',
|
||||
fields=['flow', 'idempotency_key'],
|
||||
name='unique_flow_idempotency_key_when_not_null',
|
||||
condition=models.Q(idempotency_key__isnull=False)
|
||||
)
|
||||
]
|
||||
|
|
|
|||
Loading…
Reference in a new issue