From 79b5de23863b7f3796a5eedbf579cf65b2397585 Mon Sep 17 00:00:00 2001 From: Joe Heffer <60133133+Joe-Heffer-Shef@users.noreply.github.com> Date: Thu, 2 Oct 2025 15:35:21 +0100 Subject: [PATCH] Potential fix for code scanning alert no. 4: URL redirection from remote source Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- survey/views.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/survey/views.py b/survey/views.py index 5f23a473..f49131cb 100644 --- a/survey/views.py +++ b/survey/views.py @@ -11,6 +11,7 @@ from django.core.files.uploadhandler import UploadFileException from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed from django.shortcuts import get_object_or_404, redirect, render +from django.utils.http import url_has_allowed_host_and_scheme from django.template.context_processors import csrf from django.urls import reverse, reverse_lazy from django.views import View @@ -417,15 +418,26 @@ def post(self, request: HttpRequest, pk: int, section_id: int): request.user, survey, improve_section, data ) - return redirect( - request.META.get( - "HTTP_REFERER", + referer_url = request.META.get( + "HTTP_REFERER", + reverse_lazy( + "survey_improvement_plan", + kwargs={"pk": survey.pk, "section_id": improve_section.section_id}, + ), + ) + # Only allow redirecting to safe URLs + if url_has_allowed_host_and_scheme( + referer_url, + allowed_hosts={request.get_host()}, + ): + return redirect(referer_url) + else: + return redirect( reverse_lazy( "survey_improvement_plan", kwargs={"pk": survey.pk, "section_id": improve_section.section_id}, - ), + ) ) - ) class SurveyReportView(LoginRequiredMixin, View):