726 lines
29 KiB
Python
726 lines
29 KiB
Python
import pytest
|
|
from django.core.exceptions import PermissionDenied
|
|
from django.contrib.auth.models import User
|
|
from workflows.engine import execute_flow_dag
|
|
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', 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'
|
|
|
|
def test_tenant_permissions_and_helpers(self):
|
|
# Cover ScopedOwnerAccessPermission lines
|
|
from openforce.permissions import ScopedOwnerAccessPermission
|
|
from rest_framework.request import Request
|
|
from django.test.client import RequestFactory
|
|
from custom_objects.models import CustomFieldDefinition
|
|
|
|
perm = ScopedOwnerAccessPermission()
|
|
rf = RequestFactory()
|
|
req = rf.get('/')
|
|
req.user = self.user_a
|
|
|
|
# Object with no owner, assigned_to, or created_by
|
|
class DummyObj:
|
|
pass
|
|
assert not perm.has_object_permission(req, None, DummyObj())
|
|
|
|
# Object with assigned_to matching
|
|
class AssignedObj:
|
|
assigned_to = self.user_a
|
|
assert perm.has_object_permission(req, None, AssignedObj())
|
|
|
|
# CustomFieldDefinition ownership via custom_object
|
|
custom_obj_a = CustomObjectDefinition.objects.create(name='TestA_c', label='Test A', created_by=self.user_a)
|
|
field_a = CustomFieldDefinition.objects.create(custom_object=custom_obj_a, name='fld_a_c', label='Fld A', field_type='text')
|
|
assert perm.has_object_permission(req, None, field_a)
|
|
|
|
# Unauthenticated user
|
|
class AnonUser:
|
|
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_flow_cannot_patch_created_by_to_forge_staff_identity(self):
|
|
from workflows.models import FlowDefinition
|
|
flow = FlowDefinition.objects.create(
|
|
name='Bob Own Flow',
|
|
created_by=self.user_b,
|
|
graph={'nodes': [{'id': 'start', 'type': 'trigger', 'data': {}}], 'edges': []}
|
|
)
|
|
staff_user = User.objects.create_user('staff_victim', 'staff@test.com', 'pw', is_staff=True)
|
|
res = self.client_b.patch(f'/api/workflows/{flow.id}/', {'created_by': staff_user.id}, format='json')
|
|
# created_by is read-only, so PATCHing it cannot alter authority
|
|
flow.refresh_from_db()
|
|
assert flow.created_by == self.user_b
|
|
|
|
def test_flow_cannot_modify_foreign_activity(self):
|
|
from workflows.models import FlowDefinition
|
|
from crm_core.models import Activity
|
|
from django.contrib.contenttypes.models import ContentType
|
|
ct = ContentType.objects.get_for_model(Account)
|
|
acct_a = Account.objects.create(name='Alice Acct For Act', owner=self.user_a)
|
|
act_alice = Activity.objects.create(
|
|
subject='Alice Secret Task',
|
|
activity_type='task',
|
|
content_type=ct,
|
|
object_id=acct_a.id,
|
|
assigned_to=self.user_a
|
|
)
|
|
|
|
hack_graph = {
|
|
'nodes': [
|
|
{'id': 'start', 'type': 'trigger', 'data': {}},
|
|
{'id': 'upd', 'type': 'update_record', 'data': {
|
|
'target_model': 'Activity',
|
|
'field_updates': {'subject': 'Hacked Activity Task'}
|
|
}}
|
|
],
|
|
'edges': [{'source': 'start', 'target': 'upd'}]
|
|
}
|
|
flow = FlowDefinition.objects.create(
|
|
name='Bob Hack Activity',
|
|
created_by=self.user_b,
|
|
graph=hack_graph
|
|
)
|
|
|
|
res = self.client_b.post(f'/api/workflows/{flow.id}/execute/', {
|
|
'context': {'record_id': act_alice.id, 'record_type': 'Activity'}
|
|
}, format='json')
|
|
assert res.status_code == 400
|
|
assert 'Permission denied' in res.data.get('error', '')
|
|
act_alice.refresh_from_db()
|
|
assert act_alice.subject == 'Alice Secret Task'
|
|
|
|
def test_execute_flow_dag_with_missing_user_fails_closed(self):
|
|
from workflows.engine import execute_flow_dag
|
|
from django.core.exceptions import PermissionDenied
|
|
acct_a = Account.objects.create(name='Alice Unmodified', owner=self.user_a)
|
|
dag = {
|
|
'nodes': [
|
|
{'id': 'start', 'type': 'trigger', 'data': {}},
|
|
{'id': 'upd', 'type': 'update_record', 'data': {
|
|
'target_model': 'Account',
|
|
'field_updates': {'name': 'Forged No-User Update'}
|
|
}}
|
|
],
|
|
'edges': [{'source': 'start', 'target': 'upd'}]
|
|
}
|
|
with pytest.raises(PermissionDenied):
|
|
execute_flow_dag(dag, initial_context={'record_id': acct_a.id, 'record_type': 'Account'}, user=None)
|
|
acct_a.refresh_from_db()
|
|
assert acct_a.name == 'Alice Unmodified'
|
|
|
|
def test_flow_cannot_rewrite_primary_key_or_authority_fields(self):
|
|
from workflows.models import FlowDefinition
|
|
acct_alice = Account.objects.create(name='Alice Original', owner=self.user_a)
|
|
acct_bob = Account.objects.create(name='Bob Original', owner=self.user_b)
|
|
|
|
# Bob attempts to rewrite primary key to overwrite Alice's account
|
|
id_rewrite_graph = {
|
|
'nodes': [
|
|
{'id': 'start', 'type': 'trigger', 'data': {}},
|
|
{'id': 'update', 'type': 'update_record', 'data': {
|
|
'target_model': 'Account',
|
|
'field_updates': {'id': acct_alice.id, 'name': 'OVERWRITTEN'}
|
|
}}
|
|
],
|
|
'edges': [{'source': 'start', 'target': 'update'}]
|
|
}
|
|
flow = FlowDefinition.objects.create(
|
|
name='Bob ID Rewrite Flow',
|
|
created_by=self.user_b,
|
|
graph=id_rewrite_graph
|
|
)
|
|
self.client_b.force_authenticate(user=self.user_b)
|
|
res = self.client_b.post(f'/api/workflows/{flow.id}/execute/', {
|
|
'context': {'record_id': acct_bob.id, 'record_type': 'Account'}
|
|
}, format='json')
|
|
assert res.status_code == 400
|
|
assert 'Permission denied' in res.data['error']
|
|
|
|
# Both Alice's and Bob's accounts must remain completely unchanged
|
|
acct_alice.refresh_from_db()
|
|
acct_bob.refresh_from_db()
|
|
assert acct_alice.name == 'Alice Original'
|
|
assert acct_alice.owner == self.user_a
|
|
assert acct_bob.name == 'Bob Original'
|
|
assert acct_bob.owner == self.user_b
|
|
|
|
# Setup contacts for relationship & allowlist tests
|
|
contact_bob = Contact.objects.create(first_name='Bob', last_name='Contact', owner=self.user_b)
|
|
flow_update_contact = FlowDefinition.objects.create(
|
|
name='Update Contact Flow',
|
|
created_by=self.user_b,
|
|
graph={
|
|
'nodes': [
|
|
{'id': 'start', 'type': 'trigger', 'data': {}},
|
|
{'id': 'update', 'type': 'update_record', 'data': {
|
|
'target_model': 'Contact',
|
|
'field_updates': {'account': acct_alice.id}
|
|
}}
|
|
],
|
|
'edges': [{'source': 'start', 'target': 'update'}]
|
|
}
|
|
)
|
|
|
|
# Verify: foreign relationship write via update_record is rejected
|
|
from django.core.exceptions import ValidationError as DjangoValidationError
|
|
from rest_framework.exceptions import ValidationError as DRFValidationError
|
|
with pytest.raises((PermissionDenied, DRFValidationError, DjangoValidationError)):
|
|
execute_flow_dag(
|
|
flow_update_contact,
|
|
initial_context={'record_id': contact_bob.id, 'record_type': 'Contact'},
|
|
user=self.user_b
|
|
)
|
|
contact_bob.refresh_from_db()
|
|
assert contact_bob.account is None
|
|
|
|
# Verify: raw FK alias (account_id) is rejected
|
|
hack_fk_graph = {
|
|
'nodes': [
|
|
{'id': 'start', 'type': 'trigger', 'data': {}},
|
|
{'id': 'update', 'type': 'update_record', 'data': {
|
|
'target_model': 'Contact',
|
|
'field_updates': {'account_id': acct_alice.id}
|
|
}}
|
|
],
|
|
'edges': [{'source': 'start', 'target': 'update'}]
|
|
}
|
|
flow_hack_fk = FlowDefinition.objects.create(
|
|
name='Hack FK Flow',
|
|
created_by=self.user_b,
|
|
graph=hack_fk_graph
|
|
)
|
|
with pytest.raises(PermissionDenied):
|
|
execute_flow_dag(
|
|
flow_hack_fk,
|
|
initial_context={'record_id': contact_bob.id, 'record_type': 'Contact'},
|
|
user=self.user_b
|
|
)
|
|
contact_bob.refresh_from_db()
|
|
assert contact_bob.account is None
|
|
|
|
# Verify: internal attribute (__dict__) is rejected
|
|
hack_internal_graph = {
|
|
'nodes': [
|
|
{'id': 'start', 'type': 'trigger', 'data': {}},
|
|
{'id': 'update', 'type': 'update_record', 'data': {
|
|
'target_model': 'Contact',
|
|
'field_updates': {'__dict__': {}}
|
|
}}
|
|
],
|
|
'edges': [{'source': 'start', 'target': 'update'}]
|
|
}
|
|
flow_hack_internal = FlowDefinition.objects.create(
|
|
name='Hack Internal Flow',
|
|
created_by=self.user_b,
|
|
graph=hack_internal_graph
|
|
)
|
|
with pytest.raises(PermissionDenied):
|
|
execute_flow_dag(
|
|
flow_hack_internal,
|
|
initial_context={'record_id': contact_bob.id, 'record_type': 'Contact'},
|
|
user=self.user_b
|
|
)
|
|
|
|
# Verify: invalid business value is rejected
|
|
hack_invalid_val_graph = {
|
|
'nodes': [
|
|
{'id': 'start', 'type': 'trigger', 'data': {}},
|
|
{'id': 'update', 'type': 'update_record', 'data': {
|
|
'target_model': 'Account',
|
|
'field_updates': {'rating': 'NON_EXISTENT_RATING'}
|
|
}}
|
|
],
|
|
'edges': [{'source': 'start', 'target': 'update'}]
|
|
}
|
|
flow_hack_invalid_val = FlowDefinition.objects.create(
|
|
name='Hack Invalid Val Flow',
|
|
created_by=self.user_b,
|
|
graph=hack_invalid_val_graph
|
|
)
|
|
with pytest.raises((PermissionDenied, DRFValidationError, DjangoValidationError)):
|
|
execute_flow_dag(
|
|
flow_hack_invalid_val,
|
|
initial_context={'record_id': acct_bob.id, 'record_type': 'Account'},
|
|
user=self.user_b
|
|
)
|
|
acct_bob.refresh_from_db()
|
|
assert acct_bob.rating != 'NON_EXISTENT_RATING'
|
|
|
|
# Verify: allowed own-record update succeeds
|
|
valid_update_graph = {
|
|
'nodes': [
|
|
{'id': 'start', 'type': 'trigger', 'data': {}},
|
|
{'id': 'update', 'type': 'update_record', 'data': {
|
|
'target_model': 'Contact',
|
|
'field_updates': {'first_name': 'Bobby'}
|
|
}}
|
|
],
|
|
'edges': [{'source': 'start', 'target': 'update'}]
|
|
}
|
|
flow_valid_update = FlowDefinition.objects.create(
|
|
name='Valid Update Flow',
|
|
created_by=self.user_b,
|
|
graph=valid_update_graph
|
|
)
|
|
execute_flow_dag(
|
|
flow_valid_update,
|
|
initial_context={'record_id': contact_bob.id, 'record_type': 'Contact'},
|
|
user=self.user_b
|
|
)
|
|
contact_bob.refresh_from_db()
|
|
assert contact_bob.first_name == 'Bobby'
|
|
|
|
def test_ownerless_trigger_flow_fails_closed_without_superuser_elevation(self):
|
|
from workflows.models import FlowDefinition
|
|
from django.core.exceptions import PermissionDenied
|
|
acct_alice = Account.objects.create(name='Alice Safe', owner=self.user_a)
|
|
|
|
# Create trigger flow with no created_by
|
|
trigger_graph = {
|
|
'nodes': [
|
|
{'id': 'start', 'type': 'trigger', 'data': {}},
|
|
{'id': 'update', 'type': 'update_record', 'data': {
|
|
'target_model': 'Account',
|
|
'field': 'name',
|
|
'value': 'Trigger Hack'
|
|
}}
|
|
],
|
|
'edges': [{'source': 'start', 'target': 'update'}]
|
|
}
|
|
FlowDefinition.objects.create(
|
|
name='Ownerless Trigger Flow',
|
|
trigger_type='record_created',
|
|
trigger_object='Account',
|
|
is_active=True,
|
|
created_by=None,
|
|
graph=trigger_graph
|
|
)
|
|
from workflows.dispatcher import dispatch_flow
|
|
# If dispatched with no user, must raise PermissionDenied and not elevate to superuser
|
|
with pytest.raises(PermissionDenied):
|
|
dispatch_flow(
|
|
FlowDefinition.objects.get(name='Ownerless Trigger Flow'),
|
|
context={'record_id': acct_alice.id, 'record_type': 'Account'},
|
|
user=None
|
|
)
|
|
acct_alice.refresh_from_db()
|
|
assert acct_alice.name == 'Alice Safe'
|
|
|
|
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
|
|
|
|
def test_activity_polymorphic_generic_foreign_key_isolated(self):
|
|
"""
|
|
Bob cannot attach an Activity to Alice's Account via polymorphic (content_type, object_id).
|
|
"""
|
|
from django.contrib.contenttypes.models import ContentType
|
|
from crm_core.models import Activity
|
|
|
|
account_a = Account.objects.create(name='Alice Account', owner=self.user_a)
|
|
account_b = Account.objects.create(name='Bob Account', owner=self.user_b)
|
|
account_ct = ContentType.objects.get_for_model(Account)
|
|
|
|
# 1. Bob attempts to create an Activity pointing to Alice's Account
|
|
create_res = self.client_b.post('/api/activities/', {
|
|
'subject': 'Infiltrate Alice Account',
|
|
'activity_type': 'Task',
|
|
'content_type': account_ct.id,
|
|
'object_id': account_a.id,
|
|
}, format='json')
|
|
assert create_res.status_code == 400
|
|
assert 'object_id' in create_res.data
|
|
|
|
# 2. Bob creates a valid Activity on his own Account
|
|
bob_valid = self.client_b.post('/api/activities/', {
|
|
'subject': 'Bob Task',
|
|
'activity_type': 'Task',
|
|
'content_type': account_ct.id,
|
|
'object_id': account_b.id,
|
|
}, format='json')
|
|
assert bob_valid.status_code == 201
|
|
bob_act_id = bob_valid.data['id']
|
|
|
|
# 3. Bob attempts to patch/update the Activity to repoint to Alice's Account
|
|
patch_res = self.client_b.patch(f'/api/activities/{bob_act_id}/', {
|
|
'object_id': account_a.id,
|
|
}, format='json')
|
|
assert patch_res.status_code == 400
|
|
assert 'object_id' in patch_res.data
|
|
|
|
# Verify in DB that the Activity was NOT repointed to Alice's Account
|
|
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,
|
|
earlier record mutations are rolled back atomically while the failed log is preserved.
|
|
"""
|
|
from workflows.models import FlowDefinition, FlowExecutionLog
|
|
|
|
account_b = Account.objects.create(name='Bob Account Prior', owner=self.user_b)
|
|
initial_name = account_b.name
|
|
|
|
# Create a DAG with two nodes:
|
|
# Node 1: update Bob's account name
|
|
# Node 2: call nonexistent child subflow (fails)
|
|
dag = {
|
|
"nodes": [
|
|
{
|
|
"id": "node_update",
|
|
"type": "update_record",
|
|
"data": {
|
|
"model_name": "Account",
|
|
"record_id_path": "account_id",
|
|
"field_updates": {"name": "Should Be Rolled Back"}
|
|
}
|
|
},
|
|
{
|
|
"id": "node_subflow_fail",
|
|
"type": "subflow",
|
|
"data": {
|
|
"subflow_id": 999999
|
|
}
|
|
}
|
|
],
|
|
"edges": [
|
|
{
|
|
"source": "node_update",
|
|
"target": "node_subflow_fail"
|
|
}
|
|
]
|
|
}
|
|
|
|
flow = FlowDefinition.objects.create(
|
|
name="Rollback Test Flow",
|
|
graph=dag,
|
|
is_active=True,
|
|
created_by=self.user_b
|
|
)
|
|
|
|
res = self.client_b.post(f'/api/workflows/{flow.id}/execute/', {
|
|
'context': {'account_id': account_b.id}
|
|
}, format='json')
|
|
|
|
assert res.status_code == 400
|
|
assert res.data['status'] == 'failed'
|
|
|
|
# Verify Account B's name was rolled back and NOT persisted
|
|
account_b.refresh_from_db()
|
|
assert account_b.name == initial_name
|
|
|
|
# Verify execution log was saved with status 'failed'
|
|
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
|