openforce/tests/test_tenant_isolation.py

238 lines
10 KiB
Python

import pytest
from django.contrib.auth.models import User
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_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