fix(isolation): enforce trigger execution identity, per-flow idempotency scoping, and tenant-scoped email templates

This commit is contained in:
Goose 2026-09-26 22:31:31 +00:00
parent e81d4339c3
commit eb3a85586a
8 changed files with 176 additions and 17 deletions

View file

@ -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'),
),
]

View file

@ -8,7 +8,7 @@ User = get_user_model()
class EmailTemplate(models.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) subject = models.CharField(max_length=255)
body_html = models.TextField(help_text="HTML content supporting merge tags like {{first_name}}") body_html = models.TextField(help_text="HTML content supporting merge tags like {{first_name}}")
body_text = models.TextField(blank=True, default='') body_text = models.TextField(blank=True, default='')
@ -17,6 +17,15 @@ class EmailTemplate(models.Model):
created_at = models.DateTimeField(auto_now_add=True) created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=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): def render(self, context):
""" """
Safely renders template variables with {{var_name}} merge tags. Safely renders template variables with {{var_name}} merge tags.

View file

@ -1,4 +1,5 @@
from rest_framework import serializers from rest_framework import serializers
from crm_core.serializers import OwnerScopedRelationMixin
from .models import EmailTemplate, Campaign, CampaignRecipient 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'] 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) recipients = CampaignRecipientSerializer(many=True, read_only=True)
template = serializers.PrimaryKeyRelatedField( template = serializers.PrimaryKeyRelatedField(
queryset=EmailTemplate.objects.all(), queryset=EmailTemplate.objects.all(),
required=False, required=False,
allow_null=True allow_null=True
) )
subject = serializers.CharField(write_only=True, required=False, allow_blank=True)
sent_count = serializers.SerializerMethodField() sent_count = serializers.SerializerMethodField()
open_count = serializers.SerializerMethodField() open_count = serializers.SerializerMethodField()
click_count = serializers.SerializerMethodField() click_count = serializers.SerializerMethodField()
@ -33,20 +35,21 @@ class CampaignSerializer(serializers.ModelSerializer):
read_only_fields = ['id', 'created_at', 'updated_at'] read_only_fields = ['id', 'created_at', 'updated_at']
def create(self, validated_data): def create(self, validated_data):
user_subject = validated_data.pop('subject', None)
template = validated_data.get('template') template = validated_data.get('template')
if not 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') name = validated_data.get('name', 'Default Campaign')
subject = validated_data.get('subject', name) subject = user_subject or name
request = self.context.get('request') request = self.context.get('request')
created_by = request.user if request and request.user and request.user.is_authenticated else None created_by = request.user if request and request.user and request.user.is_authenticated else None
template, _ = EmailTemplate.objects.get_or_create( template, _ = EmailTemplate.objects.get_or_create(
name=f"{name} Template", name=f"{name} Template",
created_by=created_by,
defaults={ defaults={
'subject': subject, 'subject': subject,
'body_html': '<p>Hello {{first_name}},</p><p>We are reaching out to you regarding your account.</p>', '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.', 'body_text': 'Hello {{first_name}},\nWe are reaching out to you regarding your account.',
'created_by': created_by
} }
) )
validated_data['template'] = template validated_data['template'] = template

View file

@ -136,3 +136,103 @@ class TestTenantAccessIsolation:
is_authenticated = False is_authenticated = False
req.user = AnonUser() req.user = AnonUser()
assert not perm.has_permission(req, None) 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

View file

@ -19,13 +19,14 @@ def _set_active_flow_depth(val):
MAX_SIGNAL_REENTRANCY_DEPTH = 1 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: if context is None:
context = {} 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): def snapshot_model(instance):
data = {} 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), # Under Salesforce transactional contract (docs/SALESFORCE_FLOW_ENGINE_SPEC.md:108),
# an unhandled failure in a synchronous record-triggered flow must fail # an unhandled failure in a synchronous record-triggered flow must fail
# the transaction and roll back the triggering record modification. # 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: finally:
_set_active_flow_depth(depth) _set_active_flow_depth(depth)

View file

@ -1,6 +1,6 @@
from collections import deque from collections import deque
from django.utils import timezone from django.utils import timezone
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError, PermissionDenied
def validate_flow_dag(graph): 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) validate_flow_dag(graph)
if not is_dict and idempotency_key: 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: if existing:
return existing return existing
@ -261,16 +261,18 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None,
if not model_cls: if not model_cls:
model_cls = apps.get_model('custom_objects', record_type) model_cls = apps.get_model('custom_objects', record_type)
if model_cls: 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) qs = model_cls.objects.filter(pk=record_id)
if user and not (user.is_superuser or user.is_staff): if user and not (user.is_superuser or user.is_staff):
if hasattr(model_cls, 'owner'): if hasattr(model_cls, 'owner'):
qs = qs.filter(owner=user) qs = qs.filter(owner=user)
elif hasattr(model_cls, 'created_by'): elif hasattr(model_cls, 'created_by'):
qs = qs.filter(created_by=user) qs = qs.filter(created_by=user)
inst = qs.first() inst = qs.first()
if not inst and user and not (user.is_superuser or user.is_staff): if not inst:
raise ValidationError(f"Permission denied: cannot update unauthorized record {record_type}:{record_id}") raise PermissionDenied(f"Permission denied: cannot update unauthorized record {record_type}:{record_id}")
else:
inst = qs.first()
if inst: if inst:
for f_name, f_val in updates.items(): for f_name, f_val in updates.items():
if hasattr(inst, f_name): if hasattr(inst, f_name):

View file

@ -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'),
),
]

View file

@ -67,8 +67,8 @@ class FlowExecutionLog(models.Model):
ordering = ['-started_at'] ordering = ['-started_at']
constraints = [ constraints = [
models.UniqueConstraint( models.UniqueConstraint(
fields=['idempotency_key'], fields=['flow', 'idempotency_key'],
name='unique_idempotency_key_when_not_null', name='unique_flow_idempotency_key_when_not_null',
condition=models.Q(idempotency_key__isnull=False) condition=models.Q(idempotency_key__isnull=False)
) )
] ]