fix(security): replace arbitrary setattr with model-serializer validation registry and explicit field allowlists
This commit is contained in:
parent
2d41c964d2
commit
cba612622e
2 changed files with 189 additions and 35 deletions
|
|
@ -1,5 +1,7 @@
|
|||
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
|
||||
|
|
@ -280,6 +282,132 @@ class TestTenantAccessIsolation:
|
|||
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
|
||||
|
|
|
|||
|
|
@ -256,45 +256,71 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None,
|
|||
updates.update(node_data.get('field_updates'))
|
||||
|
||||
if updates and record_id and record_type:
|
||||
from django.apps import apps
|
||||
model_cls = apps.get_model('crm_core', record_type)
|
||||
if not model_cls:
|
||||
model_cls = apps.get_model('custom_objects', record_type)
|
||||
if model_cls:
|
||||
if not user:
|
||||
# Fail-closed: unauthenticated / missing identity cannot perform DB writes
|
||||
raise PermissionDenied("Missing execution identity for update_record.")
|
||||
from crm_core.serializers import (
|
||||
AccountSerializer, ContactSerializer, LeadSerializer,
|
||||
OpportunitySerializer, ActivitySerializer
|
||||
)
|
||||
from custom_objects.serializers import CustomRecordSerializer
|
||||
from rest_framework.test import APIRequestFactory
|
||||
|
||||
qs = model_cls.objects.filter(pk=record_id)
|
||||
if not (user.is_superuser or user.is_staff):
|
||||
if hasattr(model_cls, 'owner'):
|
||||
qs = qs.filter(owner=user)
|
||||
elif hasattr(model_cls, 'assigned_to'):
|
||||
qs = qs.filter(assigned_to=user)
|
||||
elif hasattr(model_cls, 'created_by'):
|
||||
qs = qs.filter(created_by=user)
|
||||
else:
|
||||
raise PermissionDenied(f"Permission denied: no ownership policy defined for model {record_type}")
|
||||
SUPPORTED_SERIALIZER_REGISTRY = {
|
||||
'Account': AccountSerializer,
|
||||
'Contact': ContactSerializer,
|
||||
'Lead': LeadSerializer,
|
||||
'Opportunity': OpportunitySerializer,
|
||||
'Activity': ActivitySerializer,
|
||||
'CustomRecord': CustomRecordSerializer,
|
||||
}
|
||||
|
||||
inst = qs.first()
|
||||
if not inst:
|
||||
raise PermissionDenied(f"Permission denied: cannot update unauthorized record {record_type}:{record_id}")
|
||||
serializer_cls = SUPPORTED_SERIALIZER_REGISTRY.get(record_type)
|
||||
if not serializer_cls:
|
||||
raise PermissionDenied(f"Permission denied: model '{record_type}' is not registered for flow updates.")
|
||||
|
||||
model_cls = serializer_cls.Meta.model
|
||||
if not user:
|
||||
# Fail-closed: unauthenticated / missing identity cannot perform DB writes
|
||||
raise PermissionDenied("Missing execution identity for update_record.")
|
||||
|
||||
qs = model_cls.objects.filter(pk=record_id)
|
||||
if not (user.is_superuser or user.is_staff):
|
||||
if hasattr(model_cls, 'owner'):
|
||||
qs = qs.filter(owner=user)
|
||||
elif hasattr(model_cls, 'assigned_to'):
|
||||
qs = qs.filter(assigned_to=user)
|
||||
elif hasattr(model_cls, 'created_by'):
|
||||
qs = qs.filter(created_by=user)
|
||||
else:
|
||||
inst = qs.first()
|
||||
if inst:
|
||||
IMMUTABLE_FIELDS = {
|
||||
'id', 'pk', 'owner', 'owner_id', 'created_by', 'created_by_id',
|
||||
'assigned_to', 'assigned_to_id', 'created_at', 'updated_at'
|
||||
}
|
||||
# Check for any attempts to rewrite primary key or ownership/authority fields
|
||||
forbidden_fields = set(updates.keys()) & IMMUTABLE_FIELDS
|
||||
if forbidden_fields:
|
||||
raise PermissionDenied(f"Permission denied: cannot mutate protected authority fields {forbidden_fields}")
|
||||
raise PermissionDenied(f"Permission denied: no ownership policy defined for model {record_type}")
|
||||
|
||||
for f_name, f_val in updates.items():
|
||||
if hasattr(inst, f_name):
|
||||
setattr(inst, f_name, f_val)
|
||||
inst.save()
|
||||
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:
|
||||
factory = APIRequestFactory()
|
||||
req = factory.post('/')
|
||||
req.user = user
|
||||
|
||||
# Use dummy serializer instance to inspect declared editable business fields
|
||||
inspect_serializer = serializer_cls(inst, data={}, partial=True, context={'request': req})
|
||||
allowed_business_fields = {
|
||||
fname for fname, f in inspect_serializer.fields.items() if not f.read_only
|
||||
}
|
||||
|
||||
# Reject any unknown fields, internal attributes, or raw FK aliases (e.g. account_id)
|
||||
disallowed_fields = set(updates.keys()) - allowed_business_fields
|
||||
if disallowed_fields:
|
||||
raise PermissionDenied(
|
||||
f"Permission denied: field(s) {disallowed_fields} are not declared editable business fields on {record_type}."
|
||||
)
|
||||
|
||||
# Validate updates via the model serializer with actor-scoped request context
|
||||
serializer = serializer_cls(inst, data=updates, partial=True, context={'request': req})
|
||||
if not serializer.is_valid():
|
||||
raise ValidationError(serializer.errors)
|
||||
serializer.save()
|
||||
|
||||
elif node_type == 'assignment':
|
||||
# Handle single assignment fields or assignments array
|
||||
|
|
|
|||
Loading…
Reference in a new issue