Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ruff: Add and fix Q000 #10095

Merged
merged 4 commits into from
Jul 12, 2024
Merged
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
6 changes: 3 additions & 3 deletions .github/workflows/release-1-create-pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ jobs:

- name: Update version numbers in key files
run: |
sed -ri "s/__version__ = '.*'/__version__ = '${{ github.event.inputs.release_number }}'/" dojo/__init__.py
sed -ri "s/\"version\": \".*\"/\"version\": \"${{ github.event.inputs.release_number }}\"/" components/package.json
sed -ri "s/appVersion: \".*\"/appVersion: \"${{ github.event.inputs.release_number }}\"/" helm/defectdojo/Chart.yaml
sed -ri 's/__version__ = ".*"/__version__ = "${{ github.event.inputs.release_number }}"/' dojo/__init__.py
sed -ri 's/"version": ".*"/"version": "${{ github.event.inputs.release_number }}"/' components/package.json
sed -ri 's/appVersion: ".*"/appVersion: "${{ github.event.inputs.release_number }}"/' helm/defectdojo/Chart.yaml
if grep "\-dev" helm/defectdojo/Chart.yaml; then
echo "x.y.z-dev found in Chart.yaml, probably releasing a new minor version"
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/release-3-master-into-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ jobs:

- name: Update version numbers in key files
run: |
sed -ri "s/__version__ = '.*'/__version__ = '${{ github.event.inputs.release_number_dev }}'/" dojo/__init__.py
sed -ri "s/appVersion: \".*\"/appVersion: \"${{ github.event.inputs.release_number_dev }}\"/" helm/defectdojo/Chart.yaml
sed -ri "s/\"version\": \".*\"/\"version\": \"${{ github.event.inputs.release_number_dev }}\"/" components/package.json
sed -ri 's/__version__ = ".*"/__version__ = "${{ github.event.inputs.release_number_dev }}"/' dojo/__init__.py
sed -ri 's/"version": ".*"/"version": "${{ github.event.inputs.release_number_dev }}"/' components/package.json
sed -ri 's/appVersion: ".*"/appVersion: "${{ github.event.inputs.release_number_dev }}"/' helm/defectdojo/Chart.yaml
CURRENT_CHART_VERSION=$(grep -oP 'version: (\K\S*)?' helm/defectdojo/Chart.yaml | head -1)
sed -ri "0,/version/s/version: \S+/$(echo "version: $CURRENT_CHART_VERSION" | awk -F. -v OFS=. 'NF==1{print ++$NF}; NF>1{$NF=sprintf("%0*d", length($NF), ($NF+1)); print}')-dev/" helm/defectdojo/Chart.yaml
Expand Down
6 changes: 3 additions & 3 deletions dojo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
# Django starts so that shared_task will use this app.
from .celery import app as celery_app # noqa: F401

__version__ = '2.37.0-dev'
__url__ = 'https://github.com/DefectDojo/django-DefectDojo'
__docs__ = 'https://documentation.defectdojo.com'
__version__ = "2.37.0-dev"
__url__ = "https://github.com/DefectDojo/django-DefectDojo"
__docs__ = "https://documentation.defectdojo.com"
4 changes: 2 additions & 2 deletions dojo/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ class AnswerParentAdmin(PolymorphicParentModelAdmin):
"""

list_display = (
'answered_survey',
'question',
"answered_survey",
"question",
)

base_model = Answer
Expand Down
8 changes: 4 additions & 4 deletions dojo/api_v2/prefetch/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ def get_serializer_ref_name(serializer):
:return: Serializer's ``ref_name`` or ``None`` for inline serializer
:rtype: str or None
"""
serializer_meta = getattr(serializer, 'Meta', None)
serializer_meta = getattr(serializer, "Meta", None)
serializer_name = type(serializer).__name__
if hasattr(serializer_meta, 'ref_name'):
if hasattr(serializer_meta, "ref_name"):
ref_name = serializer_meta.ref_name
else:
ref_name = serializer_name
if ref_name.endswith('Serializer'):
ref_name = ref_name[:-len('Serializer')]
if ref_name.endswith("Serializer"):
ref_name = ref_name[:-len("Serializer")]
return ref_name


Expand Down
24 changes: 12 additions & 12 deletions dojo/api_v2/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def __init__(self, **kwargs):
self.pretty_print = pretty_print

def to_internal_value(self, data):
if isinstance(data, list) and data == [''] and self.allow_empty:
if isinstance(data, list) and data == [""] and self.allow_empty:
return []
if isinstance(data, six.string_types):
if not data:
Expand Down Expand Up @@ -1100,7 +1100,7 @@ def validate(self, data):
name = data.get("name")
# Make sure this will not create a duplicate test type
if Tool_Type.objects.filter(name=name).count() > 0:
msg = 'A Tool Type with the name already exists'
msg = "A Tool Type with the name already exists"
raise serializers.ValidationError(msg)
return data

Expand Down Expand Up @@ -1512,12 +1512,12 @@ def get_engagement(self, obj):

def validate(self, data):
def validate_findings_have_same_engagement(finding_objects: List[Finding]):
engagements = finding_objects.values_list('test__engagement__id', flat=True).distinct().count()
engagements = finding_objects.values_list("test__engagement__id", flat=True).distinct().count()
if engagements > 1:
msg = "You are not permitted to add findings from multiple engagements"
raise PermissionDenied(msg)

findings = data.get('accepted_findings', [])
findings = data.get("accepted_findings", [])
findings_ids = [x.id for x in findings]
finding_objects = Finding.objects.filter(id__in=findings_ids)
authed_findings = get_authorized_findings(Permissions.Finding_Edit).filter(id__in=findings_ids)
Expand All @@ -1526,7 +1526,7 @@ def validate_findings_have_same_engagement(finding_objects: List[Finding]):
raise PermissionDenied(msg)
if self.context["request"].method == "POST":
validate_findings_have_same_engagement(finding_objects)
elif self.context['request'].method in ['PATCH', 'PUT']:
elif self.context["request"].method in ["PATCH", "PUT"]:
existing_findings = Finding.objects.filter(risk_acceptance=self.instance.id)
existing_and_new_findings = existing_findings | finding_objects
validate_findings_have_same_engagement(existing_and_new_findings)
Expand Down Expand Up @@ -2024,12 +2024,12 @@ class Meta:
)

def validate(self, data):
async_updating = getattr(self.instance, 'async_updating', None)
async_updating = getattr(self.instance, "async_updating", None)
if async_updating:
new_sla_config = data.get('sla_configuration', None)
old_sla_config = getattr(self.instance, 'sla_configuration', None)
new_sla_config = data.get("sla_configuration", None)
old_sla_config = getattr(self.instance, "sla_configuration", None)
if new_sla_config and old_sla_config and new_sla_config != old_sla_config:
msg = 'Finding SLA expiration dates are currently being recalculated. The SLA configuration for this product cannot be changed until the calculation is complete.'
msg = "Finding SLA expiration dates are currently being recalculated. The SLA configuration for this product cannot be changed until the calculation is complete."
raise serializers.ValidationError(msg)
return data

Expand Down Expand Up @@ -3002,13 +3002,13 @@ class Meta:
)

def validate(self, data):
async_updating = getattr(self.instance, 'async_updating', None)
async_updating = getattr(self.instance, "async_updating", None)
if async_updating:
for field in ['critical', 'enforce_critical', 'high', 'enforce_high', 'medium', 'enforce_medium', 'low', 'enforce_low']:
for field in ["critical", "enforce_critical", "high", "enforce_high", "medium", "enforce_medium", "low", "enforce_low"]:
old_days = getattr(self.instance, field, None)
new_days = data.get(field, None)
if old_days is not None and new_days is not None and (old_days != new_days):
msg = 'Finding SLA expiration dates are currently being calculated. The SLA days for this SLA configuration cannot be changed until the calculation is complete.'
msg = "Finding SLA expiration dates are currently being calculated. The SLA days for this SLA configuration cannot be changed until the calculation is complete."
raise serializers.ValidationError(msg)
return data

Expand Down
6 changes: 3 additions & 3 deletions dojo/api_v2/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,9 @@

class DojoOpenApiJsonRenderer(OpenApiJsonRenderer2):
def get_indent(self, accepted_media_type, renderer_context):
if accepted_media_type and 'indent' in accepted_media_type:
if accepted_media_type and "indent" in accepted_media_type:
return super().get_indent(accepted_media_type, renderer_context)
return renderer_context.get('indent', None)
return renderer_context.get("indent", None)


class DojoSpectacularAPIView(SpectacularAPIView):
Expand Down Expand Up @@ -206,7 +206,7 @@ class RoleViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticated,)

def get_queryset(self):
return Role.objects.all().order_by('id')
return Role.objects.all().order_by("id")


# Authorization: object-based
Expand Down
22 changes: 11 additions & 11 deletions dojo/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@


class DojoAppConfig(AppConfig):
name = 'dojo'
name = "dojo"
verbose_name = "Defect Dojo"

def ready(self):
Expand All @@ -25,12 +25,12 @@ def ready(self):
# charfields/textfields are the fields that watson indexes by default (but we have to repeat here if we add extra fields)
# and watson likes to have tuples instead of lists

watson.register(self.get_model('Product'), fields=get_model_fields_with_extra(self.get_model('Product'), ('id', 'prod_type__name')), store=('prod_type__name', ))
watson.register(self.get_model("Product"), fields=get_model_fields_with_extra(self.get_model("Product"), ("id", "prod_type__name")), store=("prod_type__name", ))

watson.register(self.get_model('Test'), fields=get_model_fields_with_extra(self.get_model('Test'), ('id', 'engagement__product__name')), store=('engagement__product__name', )) # test_type__name?
watson.register(self.get_model("Test"), fields=get_model_fields_with_extra(self.get_model("Test"), ("id", "engagement__product__name")), store=("engagement__product__name", )) # test_type__name?

watson.register(self.get_model('Finding'), fields=get_model_fields_with_extra(self.get_model('Finding'), ('id', 'url', 'unique_id_from_tool', 'test__engagement__product__name', 'jira_issue__jira_key')),
store=('status', 'jira_issue__jira_key', 'test__engagement__product__name', 'severity', 'severity_display', 'latest_note'))
watson.register(self.get_model("Finding"), fields=get_model_fields_with_extra(self.get_model("Finding"), ("id", "url", "unique_id_from_tool", "test__engagement__product__name", "jira_issue__jira_key")),
store=("status", "jira_issue__jira_key", "test__engagement__product__name", "severity", "severity_display", "latest_note"))

# some thoughts on Finding fields that are not indexed yet:
# CWE can't be indexed as it is an integer
Expand Down Expand Up @@ -58,16 +58,16 @@ def ready(self):
# help_text="Source line number of the attack vector")
# sast_source_file_path = models.CharField(null=True, blank=True, max_length=4000, help_text="Source filepath of the attack vector")

watson.register(self.get_model('Finding_Template'))
watson.register(self.get_model('Endpoint'), store=('product__name', )) # add product name also?
watson.register(self.get_model('Engagement'), fields=get_model_fields_with_extra(self.get_model('Engagement'), ('id', 'product__name')), store=('product__name', ))
watson.register(self.get_model('App_Analysis'))
watson.register(self.get_model('Vulnerability_Id'), store=('finding__test__engagement__product__name', ))
watson.register(self.get_model("Finding_Template"))
watson.register(self.get_model("Endpoint"), store=("product__name", )) # add product name also?
watson.register(self.get_model("Engagement"), fields=get_model_fields_with_extra(self.get_model("Engagement"), ("id", "product__name")), store=("product__name", ))
watson.register(self.get_model("App_Analysis"))
watson.register(self.get_model("Vulnerability_Id"), store=("finding__test__engagement__product__name", ))

# YourModel = self.get_model("YourModel")
# watson.register(YourModel)

register_check(check_configuration_deduplication, 'dojo')
register_check(check_configuration_deduplication, "dojo")

# Load any signals here that will be ready for runtime
# Importing the signals file is good enough if using the reciever decorator
Expand Down
8 changes: 4 additions & 4 deletions dojo/celery.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,20 @@
logger = logging.getLogger(__name__)

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dojo.settings.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dojo.settings.settings")

app = Celery('dojo')
app = Celery("dojo")

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings', namespace='CELERY')
app.config_from_object("django.conf:settings", namespace="CELERY")

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)


@app.task(bind=True)
def debug_task(self):
print(f'Request: {self.request!r}')
print(f"Request: {self.request!r}")


@setup_logging.connect
Expand Down
2 changes: 1 addition & 1 deletion dojo/components/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def components(request):
.order_by("component_name")
.annotate(
component_version=StringAgg(
"component_version", delimiter=separator, distinct=True, default=Value(''),
"component_version", delimiter=separator, distinct=True, default=Value(""),
),
)
)
Expand Down
8 changes: 4 additions & 4 deletions dojo/cred/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,19 @@ def get_authorized_cred_mappings(permission, queryset=None):

roles = get_roles_for_permission(permission)
authorized_product_type_roles = Product_Type_Member.objects.filter(
product_type=OuterRef('product__prod_type_id'),
product_type=OuterRef("product__prod_type_id"),
user=user,
role__in=roles)
authorized_product_roles = Product_Member.objects.filter(
product=OuterRef('product_id'),
product=OuterRef("product_id"),
user=user,
role__in=roles)
authorized_product_type_groups = Product_Type_Group.objects.filter(
product_type=OuterRef('product__prod_type_id'),
product_type=OuterRef("product__prod_type_id"),
group__users=user,
role__in=roles)
authorized_product_groups = Product_Group.objects.filter(
product=OuterRef('product_id'),
product=OuterRef("product_id"),
group__users=user,
role__in=roles)
cred_mappings = cred_mappings.annotate(
Expand Down
44 changes: 22 additions & 22 deletions dojo/cred/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,26 @@
from . import views

urlpatterns = [
re_path(r'^cred/add', views.new_cred, name='add_cred'),
re_path(r'^cred/(?P<ttid>\d+)/view$', views.view_cred_details, name='view_cred_details'),
re_path(r'^cred/(?P<ttid>\d+)/edit$', views.edit_cred, name='edit_cred'),
re_path(r'^cred/(?P<ttid>\d+)/delete$', views.delete_cred, name='delete_cred'),
re_path(r'^cred$', views.cred, name='cred'),
re_path(r'^product/(?P<pid>\d+)/cred/add$', views.new_cred_product, name='new_cred_product'),
re_path(r'^product/(?P<pid>\d+)/cred/all$', views.all_cred_product, name='all_cred_product'),
re_path(r'^product/(?P<pid>\d+)/cred/(?P<ttid>\d+)/edit$', views.edit_cred_product, name='edit_cred_product'),
re_path(r'^product/(?P<pid>\d+)/cred/(?P<ttid>\d+)/view$', views.view_cred_product, name='view_cred_product'),
re_path(r'^product/(?P<pid>\d+)/cred/(?P<ttid>\d+)/delete$', views.delete_cred_product, name='delete_cred_product'),
re_path(r'^engagement/(?P<eid>\d+)/cred/add$', views.new_cred_product_engagement, name='new_cred_product_engagement'),
re_path(r'^engagement/(?P<eid>\d+)/cred/(?P<ttid>\d+)/view$', views.view_cred_product_engagement,
name='view_cred_product_engagement'),
re_path(r'^engagement/(?P<eid>\d+)/cred/(?P<ttid>\d+)/delete$', views.delete_cred_engagement,
name='delete_cred_engagement'),
re_path(r'^test/(?P<tid>\d+)/cred/add$', views.new_cred_engagement_test, name='new_cred_engagement_test'),
re_path(r'^test/(?P<tid>\d+)/cred/(?P<ttid>\d+)/view$', views.view_cred_engagement_test,
name='view_cred_engagement_test'),
re_path(r'^test/(?P<tid>\d+)/cred/(?P<ttid>\d+)/delete$', views.delete_cred_test, name='delete_cred_test'),
re_path(r'^finding/(?P<fid>\d+)/cred/add$', views.new_cred_finding, name='new_cred_finding'),
re_path(r'^finding/(?P<fid>\d+)/cred/(?P<ttid>\d+)/view$', views.view_cred_finding, name='view_cred_finding'),
re_path(r'^finding/(?P<fid>\d+)/cred/(?P<ttid>\d+)/delete$', views.delete_cred_finding, name='delete_cred_finding'),
re_path(r"^cred/add", views.new_cred, name="add_cred"),
re_path(r"^cred/(?P<ttid>\d+)/view$", views.view_cred_details, name="view_cred_details"),
re_path(r"^cred/(?P<ttid>\d+)/edit$", views.edit_cred, name="edit_cred"),
re_path(r"^cred/(?P<ttid>\d+)/delete$", views.delete_cred, name="delete_cred"),
re_path(r"^cred$", views.cred, name="cred"),
re_path(r"^product/(?P<pid>\d+)/cred/add$", views.new_cred_product, name="new_cred_product"),
re_path(r"^product/(?P<pid>\d+)/cred/all$", views.all_cred_product, name="all_cred_product"),
re_path(r"^product/(?P<pid>\d+)/cred/(?P<ttid>\d+)/edit$", views.edit_cred_product, name="edit_cred_product"),
re_path(r"^product/(?P<pid>\d+)/cred/(?P<ttid>\d+)/view$", views.view_cred_product, name="view_cred_product"),
re_path(r"^product/(?P<pid>\d+)/cred/(?P<ttid>\d+)/delete$", views.delete_cred_product, name="delete_cred_product"),
re_path(r"^engagement/(?P<eid>\d+)/cred/add$", views.new_cred_product_engagement, name="new_cred_product_engagement"),
re_path(r"^engagement/(?P<eid>\d+)/cred/(?P<ttid>\d+)/view$", views.view_cred_product_engagement,
name="view_cred_product_engagement"),
re_path(r"^engagement/(?P<eid>\d+)/cred/(?P<ttid>\d+)/delete$", views.delete_cred_engagement,
name="delete_cred_engagement"),
re_path(r"^test/(?P<tid>\d+)/cred/add$", views.new_cred_engagement_test, name="new_cred_engagement_test"),
re_path(r"^test/(?P<tid>\d+)/cred/(?P<ttid>\d+)/view$", views.view_cred_engagement_test,
name="view_cred_engagement_test"),
re_path(r"^test/(?P<tid>\d+)/cred/(?P<ttid>\d+)/delete$", views.delete_cred_test, name="delete_cred_test"),
re_path(r"^finding/(?P<fid>\d+)/cred/add$", views.new_cred_finding, name="new_cred_finding"),
re_path(r"^finding/(?P<fid>\d+)/cred/(?P<ttid>\d+)/view$", views.view_cred_finding, name="view_cred_finding"),
re_path(r"^finding/(?P<fid>\d+)/cred/(?P<ttid>\d+)/delete$", views.delete_cred_finding, name="delete_cred_finding"),
]
Loading
Loading