Skip to content

Commit

Permalink
Ruff: fix some SIM
Browse files Browse the repository at this point in the history
  • Loading branch information
kiblik committed Jul 2, 2024
1 parent ba6269a commit f41f751
Show file tree
Hide file tree
Showing 164 changed files with 719 additions and 1,291 deletions.
5 changes: 2 additions & 3 deletions dojo/api_v2/prefetch/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ def _get_path_to_GET_serializer_map(generator):
view,
) in generator._get_paths_and_endpoints():
# print(path, path_pattern, method, view)
if method == "GET":
if hasattr(view, "get_serializer_class"):
path_to_GET_serializer[path] = view.get_serializer_class()
if method == "GET" and hasattr(view, "get_serializer_class"):
path_to_GET_serializer[path] = view.get_serializer_class()

return path_to_GET_serializer

Expand Down
71 changes: 28 additions & 43 deletions dojo/api_v2/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,9 +275,8 @@ def _pop_tags(self, validated_data):

for key in list(self.fields.keys()):
field = self.fields[key]
if isinstance(field, TagListSerializerField):
if key in validated_data:
to_be_tagged[key] = validated_data.pop(key)
if isinstance(field, TagListSerializerField) and key in validated_data:
to_be_tagged[key] = validated_data.pop(key)

return (to_be_tagged, validated_data)

Expand Down Expand Up @@ -368,20 +367,16 @@ def to_internal_value(self, data):
return data

def to_representation(self, value):
if not isinstance(value, RequestResponseDict):
if not isinstance(value, list):
# this will trigger when a queryset is found...
if self.order_by:
burps = value.all().order_by(*self.order_by)
else:
burps = value.all()
value = [
{
"request": burp.get_request(),
"response": burp.get_response(),
}
for burp in burps
]
if not isinstance(value, RequestResponseDict) and not isinstance(value, list):
# this will trigger when a queryset is found...
burps = value.all().order_by(*self.order_by) if self.order_by else value.all()
value = [
{
"request": burp.get_request(),
"response": burp.get_response(),
}
for burp in burps
]

return value

Expand Down Expand Up @@ -508,10 +503,7 @@ def update(self, instance, validated_data):
return instance

def create(self, validated_data):
if "password" in validated_data:
password = validated_data.pop("password")
else:
password = None
password = validated_data.pop("password") if "password" in validated_data else None

new_configuration_permissions = None
if (
Expand All @@ -537,10 +529,7 @@ def create(self, validated_data):
return user

def validate(self, data):
if self.instance is not None:
instance_is_superuser = self.instance.is_superuser
else:
instance_is_superuser = False
instance_is_superuser = self.instance.is_superuser if self.instance is not None else False
data_is_superuser = data.get("is_superuser", False)
if not self.context["request"].user.is_superuser and (
instance_is_superuser or data_is_superuser
Expand Down Expand Up @@ -1028,10 +1017,9 @@ class Meta:
exclude = ("inherited_tags",)

def validate(self, data):
if self.context["request"].method == "POST":
if data.get("target_start") > data.get("target_end"):
msg = "Your target start date exceeds your target end date"
raise serializers.ValidationError(msg)
if self.context["request"].method == "POST" and data.get("target_start") > data.get("target_end"):
msg = "Your target start date exceeds your target end date"
raise serializers.ValidationError(msg)
return data

def build_relational_field(self, field_name, relation_info):
Expand Down Expand Up @@ -1180,7 +1168,7 @@ class Meta:
def validate(self, data):
# print('EndpointSerialize.validate')

if not self.context["request"].method == "PATCH":
if self.context["request"].method != "PATCH":
if "product" not in data:
msg = "Product is required"
raise serializers.ValidationError(msg)
Expand Down Expand Up @@ -1757,12 +1745,11 @@ def validate(self, data):
msg = "False positive findings cannot " "be verified."
raise serializers.ValidationError(msg)

if is_risk_accepted and not self.instance.risk_accepted:
if (
not self.instance.test.engagement.product.enable_simple_risk_acceptance
):
msg = "Simple risk acceptance is disabled for this product, use the UI to accept this finding."
raise serializers.ValidationError(msg)
if is_risk_accepted and not self.instance.risk_accepted and (
not self.instance.test.engagement.product.enable_simple_risk_acceptance
):
msg = "Simple risk acceptance is disabled for this product, use the UI to accept this finding."
raise serializers.ValidationError(msg)

if is_active and is_risk_accepted:
msg = "Active findings cannot be risk accepted."
Expand Down Expand Up @@ -2190,9 +2177,8 @@ def set_context(
# TaggitListSerializer has already removed commas supplied
# by the user, so this operation will consistently return
# a list to be used by the importer
if tags := context.get("tags"):
if isinstance(tags, str):
context["tags"] = tags.split(", ")
if (tags := context.get("tags")) and isinstance(tags, str):
context["tags"] = tags.split(", ")
# have to make the scan_date_time timezone aware otherwise uploads via
# the API would fail (but unit tests for api upload would pass...)
context["scan_date"] = (
Expand Down Expand Up @@ -2444,7 +2430,7 @@ def set_context(
"""
context = dict(data)
# update some vars
context["scan"] = data.get("file", None)
context["scan"] = data.get("file")
context["environment"] = Development_Environment.objects.get(
name=data.get("environment", "Development")
)
Expand All @@ -2466,9 +2452,8 @@ def set_context(
# TaggitListSerializer has already removed commas supplied
# by the user, so this operation will consistently return
# a list to be used by the importer
if tags := context.get("tags"):
if isinstance(tags, str):
context["tags"] = tags.split(", ")
if (tags := context.get("tags")) and isinstance(tags, str):
context["tags"] = tags.split(", ")
# have to make the scan_date_time timezone aware otherwise uploads via
# the API would fail (but unit tests for api upload would pass...)
context["scan_date"] = (
Expand Down
49 changes: 10 additions & 39 deletions dojo/api_v2/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -1473,9 +1473,7 @@ def metadata(self, request, pk=None):
return self._get_metadata(request, finding)
elif request.method == "POST":
return self._add_metadata(request, finding)
elif request.method == "PUT":
return self._edit_metadata(request, finding)
elif request.method == "PATCH":
elif request.method == "PUT" or request.method == "PATCH":
return self._edit_metadata(request, finding)
elif request.method == "DELETE":
return self._remove_metadata(request, finding)
Expand Down Expand Up @@ -3027,24 +3025,15 @@ def report_generate(request, obj, options):
if eng.name:
engagement_name = eng.name
engagement_target_start = eng.target_start
if eng.target_end:
engagement_target_end = eng.target_end
else:
engagement_target_end = "ongoing"
engagement_target_end = eng.target_end if eng.target_end else 'ongoing'
if eng.test_set.all():
for t in eng.test_set.all():
test_type_name = t.test_type.name
if t.environment:
test_environment_name = t.environment.name
test_target_start = t.target_start
if t.target_end:
test_target_end = t.target_end
else:
test_target_end = "ongoing"
if eng.test_strategy:
test_strategy_ref = eng.test_strategy
else:
test_strategy_ref = ""
test_target_end = t.target_end if t.target_end else 'ongoing'
test_strategy_ref = eng.test_strategy if eng.test_strategy else ''
total_findings = len(findings.qs.all())

elif type(obj).__name__ == "Product":
Expand All @@ -3054,59 +3043,41 @@ def report_generate(request, obj, options):
if eng.name:
engagement_name = eng.name
engagement_target_start = eng.target_start
if eng.target_end:
engagement_target_end = eng.target_end
else:
engagement_target_end = "ongoing"
engagement_target_end = eng.target_end if eng.target_end else 'ongoing'

if eng.test_set.all():
for t in eng.test_set.all():
test_type_name = t.test_type.name
if t.environment:
test_environment_name = t.environment.name
if eng.test_strategy:
test_strategy_ref = eng.test_strategy
else:
test_strategy_ref = ""
test_strategy_ref = eng.test_strategy if eng.test_strategy else ''
total_findings = len(findings.qs.all())

elif type(obj).__name__ == "Engagement":
eng = obj
if eng.name:
engagement_name = eng.name
engagement_target_start = eng.target_start
if eng.target_end:
engagement_target_end = eng.target_end
else:
engagement_target_end = "ongoing"
engagement_target_end = eng.target_end if eng.target_end else 'ongoing'

if eng.test_set.all():
for t in eng.test_set.all():
test_type_name = t.test_type.name
if t.environment:
test_environment_name = t.environment.name
if eng.test_strategy:
test_strategy_ref = eng.test_strategy
else:
test_strategy_ref = ""
test_strategy_ref = eng.test_strategy if eng.test_strategy else ''
total_findings = len(findings.qs.all())

elif type(obj).__name__ == "Test":
t = obj
test_type_name = t.test_type.name
test_target_start = t.target_start
if t.target_end:
test_target_end = t.target_end
else:
test_target_end = "ongoing"
test_target_end = t.target_end if t.target_end else 'ongoing'
total_findings = len(findings.qs.all())
if t.engagement.name:
engagement_name = t.engagement.name
engagement_target_start = t.engagement.target_start
if t.engagement.target_end:
engagement_target_end = t.engagement.target_end
else:
engagement_target_end = "ongoing"
engagement_target_end = t.engagement.target_end if t.engagement.target_end else 'ongoing'
else:
pass # do nothing

Expand Down
36 changes: 11 additions & 25 deletions dojo/authorization/authorization.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,10 @@ def user_has_permission(user, obj, permission):
if user.is_superuser:
return True

if isinstance(obj, Product_Type) or isinstance(obj, Product):
# Global roles are only relevant for product types, products and their
# dependent objects
if user_has_global_permission(user, permission):
return True
# Global roles are only relevant for product types, products and their
# dependent objects
if isinstance(obj, (Product_Type, Product)) and user_has_global_permission(user, permission):
return True

if isinstance(obj, Product_Type):
# Check if the user has a role for the product type with the requested
Expand Down Expand Up @@ -98,12 +97,8 @@ def user_has_permission(user, obj, permission):
):
return user_has_permission(user, obj.engagement.product, permission)
elif (
isinstance(obj, Finding) or isinstance(obj, Stub_Finding)
) and permission in Permissions.get_finding_permissions():
return user_has_permission(
user, obj.test.engagement.product, permission
)
elif (
isinstance(obj, (Finding, Stub_Finding))
) and permission in Permissions.get_finding_permissions() or (
isinstance(obj, Finding_Group)
and permission in Permissions.get_finding_group_permissions()
):
Expand All @@ -113,23 +108,17 @@ def user_has_permission(user, obj, permission):
elif (
isinstance(obj, Endpoint)
and permission in Permissions.get_endpoint_permissions()
):
return user_has_permission(user, obj.product, permission)
elif (
) or (
isinstance(obj, Languages)
and permission in Permissions.get_language_permissions()
):
return user_has_permission(user, obj.product, permission)
elif (
) or ((
isinstance(obj, App_Analysis)
and permission in Permissions.get_technology_permissions()
):
return user_has_permission(user, obj.product, permission)
elif (
) or (
isinstance(obj, Product_API_Scan_Configuration)
and permission
in Permissions.get_product_api_scan_configuration_permissions()
):
)):
return user_has_permission(user, obj.product, permission)
elif (
isinstance(obj, Product_Type_Member)
Expand Down Expand Up @@ -354,10 +343,7 @@ def get_product_groups_dict(user):
.select_related("role")
.filter(group__users=user)
):
if pg_dict.get(product_group.product.id) is None:
pgu_list = []
else:
pgu_list = pg_dict[product_group.product.id]
pgu_list = [] if pg_dict.get(product_group.product.id) is None else pg_dict[product_group.product.id]
pgu_list.append(product_group)
pg_dict[product_group.product.id] = pgu_list
return pg_dict
Expand Down
44 changes: 21 additions & 23 deletions dojo/benchmark/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import contextlib
import logging

from crum import get_current_user
Expand Down Expand Up @@ -37,10 +38,8 @@ def add_benchmark(queryset, product):
benchmark_product.control = requirement
requirements.append(benchmark_product)

try:
with contextlib.suppress(Exception):
Benchmark_Product.objects.bulk_create(requirements)
except Exception:
pass


def update_benchmark(request, pid, _type):
Expand Down Expand Up @@ -299,27 +298,26 @@ def delete(request, pid, type):
).first()
form = DeleteBenchmarkForm(instance=benchmark_product_summary)

if request.method == "POST":
if (
"id" in request.POST
and str(benchmark_product_summary.id) == request.POST["id"]
):
form = DeleteBenchmarkForm(
request.POST, instance=benchmark_product_summary
if request.method == "POST" and (
"id" in request.POST
and str(benchmark_product_summary.id) == request.POST["id"]
):
form = DeleteBenchmarkForm(
request.POST, instance=benchmark_product_summary
)
if form.is_valid():
benchmark_product = Benchmark_Product.objects.filter(
product=product, control__category__type=type
)
if form.is_valid():
benchmark_product = Benchmark_Product.objects.filter(
product=product, control__category__type=type
)
benchmark_product.delete()
benchmark_product_summary.delete()
messages.add_message(
request,
messages.SUCCESS,
_("Benchmarks removed."),
extra_tags="alert-success",
)
return HttpResponseRedirect(reverse("product"))
benchmark_product.delete()
benchmark_product_summary.delete()
messages.add_message(
request,
messages.SUCCESS,
_("Benchmarks removed."),
extra_tags="alert-success",
)
return HttpResponseRedirect(reverse("product"))

product_tab = Product_Tab(
product, title=_("Delete Benchmarks"), tab="benchmarks"
Expand Down
Loading

0 comments on commit f41f751

Please sign in to comment.