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="

Alice

", 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