From 6a41065ecd3e59b452916038e32f9f5b1af0fe15 Mon Sep 17 00:00:00 2001 From: Harshit Kudhial Date: Fri, 23 Oct 2026 18:08:24 +0530 Subject: [PATCH] fix(serializers): prevent AttributeError and ObjectDoesNotExist in PluginConfigSerializer secret redaction. Closes #4052 Secret redaction in PluginConfigSerializer dereferenced instance.owner and the owner's membership without checking them, so a config with no owner raised AttributeError and a config whose owner no longer has a membership raised ObjectDoesNotExist, both ending in a 500. Check the request user, the owner and both memberships before deciding whether to redact, and compare organization_id instead of loading the organizations. OwnershipAbstractModel.organization now returns None when the owner is missing or has no membership, and to_representation falls back to None for the organization name. Add regression tests covering secret redaction for organization configs, bulk-created owner-less configs, membership deletion post-creation, and missing request context. Co-authored-by: asucodes Signed-off-by: Harshit Kudhial --- api_app/interfaces.py | 9 +- api_app/serializers/plugin.py | 39 +++++---- tests/api_app/test_serializers.py | 138 ++++++++++++++++++++++++++++++ 3 files changed, 167 insertions(+), 19 deletions(-) diff --git a/api_app/interfaces.py b/api_app/interfaces.py index 2077630c0f..7d3820448b 100644 --- a/api_app/interfaces.py +++ b/api_app/interfaces.py @@ -4,7 +4,7 @@ from typing import TYPE_CHECKING, Any, Generator, Iterable, Optional, Union from django.conf import settings -from django.core.exceptions import ValidationError +from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.db import models from django.db.models import QuerySet from django.utils.functional import cached_property @@ -260,6 +260,9 @@ def organization(self) -> Optional[Organization]: Returns: Optional[Organization]: The organization associated with the owner, or None if not applicable. """ - if self.for_organization: - return self.owner.membership.organization + if self.for_organization and self.owner and self.owner.has_membership(): + try: + return self.owner.membership.organization + except ObjectDoesNotExist: + return None return None diff --git a/api_app/serializers/plugin.py b/api_app/serializers/plugin.py index 3d8362696e..9f338e1c8d 100644 --- a/api_app/serializers/plugin.py +++ b/api_app/serializers/plugin.py @@ -4,7 +4,7 @@ from typing import Any from django.core.cache import cache -from django.core.exceptions import ValidationError as DjangoValidationError +from django.core.exceptions import ObjectDoesNotExist, ValidationError as DjangoValidationError from rest_framework import serializers as rfs from rest_framework.exceptions import ValidationError from rest_framework.fields import SerializerMethodField @@ -47,25 +47,29 @@ def to_internal_value(data): raise ValidationError({"detail": "Value is not JSON-compliant."}) def get_attribute(self, instance: PluginConfig): - # We return `redacted` when + # We return `redacted` when: # 1) is a secret AND # 2) is a value for the organization AND # (NOR OPERATOR) # 3) we are not its owner OR # 4) we are not an admin of the same organization - if ( - instance.is_secret() - and instance.for_organization - and not ( - self.context["request"].user.pk == instance.owner.pk - or ( - self.context["request"].user.has_membership() - and self.context["request"].user.membership.organization.pk - == instance.owner.membership.organization.pk - and self.context["request"].user.membership.is_admin - ) - ) - ): + request = self.context.get("request") + user = getattr(request, "user", None) if request else None + + is_owner = bool( + user and user.is_authenticated and instance.owner and user.pk == instance.owner.pk + ) + is_same_org_admin = bool( + user + and user.is_authenticated + and user.has_membership() + and user.membership.is_admin + and instance.owner + and instance.owner.has_membership() + and user.membership.organization_id == instance.owner.membership.organization_id + ) + + if instance.is_secret() and instance.for_organization and not (is_owner or is_same_org_admin): return "redacted" return super().get_attribute(instance) @@ -170,7 +174,10 @@ def update(self, instance, validated_data): def to_representation(self, instance: PluginConfig): result = super().to_representation(instance) - result["organization"] = instance.organization.name if instance.organization is not None else None + try: + result["organization"] = instance.organization.name if instance.organization is not None else None + except (AttributeError, ObjectDoesNotExist): + result["organization"] = None return result diff --git a/tests/api_app/test_serializers.py b/tests/api_app/test_serializers.py index 98c6b0ab80..0063034c23 100644 --- a/tests/api_app/test_serializers.py +++ b/tests/api_app/test_serializers.py @@ -85,6 +85,111 @@ def test_to_representation(self): org.delete() pc.delete() + def test_to_representation_secret_for_organization(self): + org = Organization.objects.create(name="test_org") + other_org = Organization.objects.create(name="other_org") + owner = User.objects.create_user( + username="config_owner", + email="config_owner@intelowl.com", + password="test", + ) + Membership.objects.create(user=owner, organization=org, is_owner=True) + Membership.objects.create(user=self.admin, organization=org, is_owner=False, is_admin=True) + Membership.objects.create(user=self.user, organization=org, is_owner=False, is_admin=False) + Membership.objects.create(user=self.guest, organization=other_org, is_owner=True) + ac = AnalyzerConfig.objects.get(name="AbuseIPDB") + param = Parameter.objects.create( + is_secret=True, + name="mynewparameter", + python_module=ac.python_module, + required=True, + type="str", + ) + pc = PluginConfig.objects.create( + value="supersecret", + owner=owner, + parameter=param, + analyzer_config=ac, + for_organization=True, + ) + + def get_value(user): + return PluginConfigSerializer(pc, context={"request": MockUpRequest(user=user)}).data["value"] + + # the owner and an admin of the owner's organization can read the value + self.assertEqual(get_value(owner), "supersecret") + self.assertEqual(get_value(self.admin), "supersecret") + # other members of the organization and users of other organizations cannot + self.assertEqual(get_value(self.user), "redacted") + self.assertEqual(get_value(self.guest), "redacted") + + # an owner whose membership was removed after the config was created + # (org deleted / member removed) - the realistic way this state occurs + orphan_owner = User.objects.create_user( + username="orphan_owner", + email="orphan_owner@intelowl.com", + password="test", + ) + Membership.objects.create( + user=orphan_owner, + organization=Organization.objects.create(name="orphan_org"), + is_owner=True, + ) + pc_no_membership = PluginConfig.objects.create( + value="supersecret", + owner=orphan_owner, + parameter=param, + analyzer_config=ac, + for_organization=True, + ) + orphan_owner.membership.delete() + self.assertEqual( + PluginConfigSerializer( + pc_no_membership, + context={"request": MockUpRequest(user=self.admin)}, + ).data["value"], + "redacted", + ) + # the owner can still read their own value + self.assertEqual( + PluginConfigSerializer( + pc_no_membership, + context={"request": MockUpRequest(user=orphan_owner)}, + ).data["value"], + "supersecret", + ) + + # an owner-less org configuration can only arise through bulk writes + # (bulk_create bypasses save/clean) - serializing it must not raise + pc_no_owner = PluginConfig.objects.bulk_create( + [ + PluginConfig( + value="supersecret", + owner=None, + parameter=param, + analyzer_config=ac, + for_organization=True, + ) + ] + )[0] + self.assertEqual( + PluginConfigSerializer( + pc_no_owner, + context={"request": MockUpRequest(user=self.admin)}, + ).data["value"], + "redacted", + ) + + # missing request or request user also results in a redacted value + self.assertEqual(PluginConfigSerializer(pc_no_owner).data["value"], "redacted") + self.assertEqual( + PluginConfigSerializer( + pc_no_owner, + context={"request": MockUpRequest(user=None)}, + ).data["value"], + "redacted", + ) + def test_create(self): org = Organization.objects.create(name="test_org") m1 = Membership.objects.create(user=self.user, organization=org, is_owner=True) @@ -175,6 +280,39 @@ def test_validate(self): m3.delete() org.delete() + def test_secret_no_owner_global_config(self): + # owner=None + for_organization=True is forbidden by clean_for_organization(). + # The real edge-case the defensive code guards against is a global secret + # (owner=None, for_organization=False): serializing it must never raise + # AttributeError on instance.owner.pk. + ac = AnalyzerConfig.objects.get(name="AbuseIPDB") + param = Parameter.objects.create( + is_secret=True, + name="secret_param_null_owner", + python_module=ac.python_module, + required=True, + type="str", + ) + pc = PluginConfig.objects.create( + value="topsecretvalue", + owner=None, + parameter=param, + analyzer_config=ac, + for_organization=False, + ) + + # Not a for_organization secret, so value should be returned directly + # (no redaction path), but critically it must not raise AttributeError. + data = PluginConfigSerializer(pc, context={"request": MockUpRequest(user=self.user)}).data + self.assertIn("value", data) + + # Serializing without a request in context must also be safe. + data_no_req = PluginConfigSerializer(pc, context={}).data + self.assertIn("value", data_no_req) + + pc.delete() + param.delete() + class RestJobSerializerTestCase(CustomTestCase): def test_validate(self):