Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions api_app/interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
39 changes: 23 additions & 16 deletions api_app/serializers/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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


Expand Down
138 changes: 138 additions & 0 deletions tests/api_app/test_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down
Loading