diff --git a/src/consents/tests/test_views.py b/src/consents/tests/test_views.py index 5d1fcda24..bf99001db 100644 --- a/src/consents/tests/test_views.py +++ b/src/consents/tests/test_views.py @@ -4,11 +4,14 @@ from src.consents.models import Consent, Term, TermOption, TermOptionChoices from src.consents.tests.base import ConsentTestBase from src.workshops.models import Person +from src.workshops.tests.base import consent_to_all_required_consents class ConsentsUpdateTest(ConsentTestBase): def setUp(self) -> None: super().setUp() + self._setUpSuperuser() + self._logSuperuserIn() self.person = Person.objects.create(personal="Harry", family="Potter", email="hp@magic.uk") def test_consents_update(self) -> None: @@ -104,3 +107,96 @@ def test_consents_update(self) -> None: (term2, original_term2_consent.term_option), ], ) + + +class ConsentsUpdateAccessTest(ConsentTestBase): + """Regression tests for #3068: ConsentsUpdate was reachable without authentication.""" + + def setUp(self) -> None: + super().setUp() + self.person = Person.objects.create( + personal="Harry", family="Potter", email="hp@magic.uk", username="potter_harry" + ) + consent_to_all_required_consents(self.person) + + self.other = Person.objects.create( + personal="Ron", family="Weasley", email="rw@magic.uk", username="weasley_ron" + ) + consent_to_all_required_consents(self.other) + + self.term = Term.objects.create(content="Access test term", slug="access-test-term") + self.agree = TermOption.objects.create(term=self.term, option_type=TermOptionChoices.AGREE) + self.decline = TermOption.objects.create(term=self.term, option_type=TermOptionChoices.DECLINE) + self.reconsent(term=self.term, term_option=self.agree, person=self.person) + + def url(self, person: Person, next_url: str | None = None) -> str: + url = reverse("consents_add", kwargs={"person_id": person.pk}) + return f"{url}?next={next_url}" if next_url is not None else url + + def post_data(self, person: Person, option: TermOption) -> dict[str, int]: + data = {"consents-person": person.pk, f"consents-{self.term.slug}": option.pk} + for consent in Consent.objects.filter(person=person, term__required_type=Term.PROFILE_REQUIRE_TYPE).active(): + assert consent.term_option_id # for mypy + data[f"consents-{consent.term.slug}"] = consent.term_option_id + return data + + def current_option(self, person: Person) -> TermOption | None: + consent = Consent.objects.filter(person=person, term=self.term).active().first() + return consent.term_option if consent else None + + def test_anonymous_post_redirects_to_login(self) -> None: + url = self.url(self.person, next_url="/") + result = self.client.post(url, self.post_data(self.person, self.decline)) + self.assertEqual(result.status_code, status.HTTP_302_FOUND) + self.assertTrue(result["Location"].startswith(reverse("login"))) + self.assertEqual(self.current_option(self.person), self.agree) + + def test_anonymous_get_redirects_to_login(self) -> None: + result = self.client.get(self.url(self.person, next_url="/")) + self.assertEqual(result.status_code, status.HTTP_302_FOUND) + self.assertTrue(result["Location"].startswith(reverse("login"))) + + def test_get_not_allowed(self) -> None: + self.client.force_login(self.person) + result = self.client.get(self.url(self.person, next_url="/")) + self.assertEqual(result.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) + + def test_user_cannot_change_other_persons_consents(self) -> None: + self.client.force_login(self.other) + result = self.client.post(self.url(self.person, next_url="/"), self.post_data(self.person, self.decline)) + self.assertEqual(result.status_code, status.HTTP_403_FORBIDDEN) + self.assertEqual(self.current_option(self.person), self.agree) + + def test_posted_person_is_ignored(self) -> None: + """Consents are saved for the person in the URL, not the one in the form data.""" + self.client.force_login(self.other) + data = self.post_data(self.other, self.decline) + data["consents-person"] = self.person.pk + result = self.client.post(self.url(self.other, next_url="/"), data) + self.assertEqual(result.status_code, status.HTTP_302_FOUND) + self.assertEqual(self.current_option(self.person), self.agree) + self.assertEqual(self.current_option(self.other), self.decline) + + def test_user_can_change_own_consents(self) -> None: + self.client.force_login(self.person) + result = self.client.post(self.url(self.person, next_url="/"), self.post_data(self.person, self.decline)) + self.assertRedirects(result, "/", fetch_redirect_response=False) + self.assertEqual(self.current_option(self.person), self.decline) + + def test_unsafe_or_missing_next_falls_back_to_person_edit(self) -> None: + self.client.force_login(self.person) + person_edit = reverse("person_edit", kwargs={"person_id": self.person.pk}) + for next_url in ["https://evil.example.com/", None]: + with self.subTest(next_url=next_url): + result = self.client.post( + self.url(self.person, next_url=next_url), self.post_data(self.person, self.decline) + ) + self.assertRedirects(result, person_edit, fetch_redirect_response=False) + + def test_invalid_form_redirects_back_with_error(self) -> None: + self.client.force_login(self.person) + data = self.post_data(self.person, self.decline) + data[f"consents-{self.term.slug}"] = 999999 # not a valid option + result = self.client.post(self.url(self.person, next_url="/"), data, follow=False) + self.assertRedirects(result, "/", fetch_redirect_response=False) + self.assertEqual(self.current_option(self.person), self.agree) diff --git a/src/consents/views.py b/src/consents/views.py index c94033f1f..2eacd0997 100644 --- a/src/consents/views.py +++ b/src/consents/views.py @@ -1,42 +1,62 @@ from typing import Any from django.contrib import messages -from django.contrib.auth.mixins import LoginRequiredMixin -from django.forms import HiddenInput -from django.http import HttpRequest, HttpResponse +from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin +from django.forms import BaseForm, HiddenInput +from django.http import HttpRequest, HttpResponse, HttpResponseRedirect from django.http.response import Http404, HttpResponseBase +from django.shortcuts import get_object_or_404 from rest_framework.reverse import reverse from src.consents.forms import ActiveTermConsentsForm, RequiredConsentsForm from src.consents.models import Consent from src.consents.util import person_has_consented_to_required_terms -from src.workshops.base_views import ( - AMYCreateView, - AMYFormView, - RedirectSupportMixin, -) +from src.workshops.base_views import AMYCreateView, AMYFormView +from src.workshops.models import Person from src.workshops.utils.urls import safe_next_or_default_url -class ConsentsUpdate(RedirectSupportMixin, AMYCreateView[ActiveTermConsentsForm, Consent], LoginRequiredMixin): +class ConsentsUpdate(LoginRequiredMixin, UserPassesTestMixin, AMYCreateView[ActiveTermConsentsForm, Consent]): + """Save consents for the person from the URL. The form is rendered on the person edit page + (PersonUpdate) and only POSTs here, so this view has no template of its own.""" + model = Consent form_class = ActiveTermConsentsForm + http_method_names = ["post"] - def get_success_url(self) -> str: - # Currently can only be called via redirect. - # There is no direct view for Consents. - next_url = self.request.GET["next"] - return next_url + def test_func(self) -> bool: + # Same access rule as PersonUpdate, which renders this form. + user = self.request.user + return user.has_perm("workshops.change_person") or user.pk == self.kwargs["person_id"] + + def get_person(self) -> Person: + if not hasattr(self, "person"): + self.person = get_object_or_404(Person, pk=self.kwargs["person_id"]) + return self.person def get_form_kwargs(self) -> dict[str, Any]: kwargs = super().get_form_kwargs() - person = kwargs["data"]["consents-person"] - kwargs.update({"prefix": "consents", "initial": {"person": person}}) + person = self.get_person() + # Always save consents for the person from the URL (on which the permission check was + # done), ignoring any person ID submitted in the form. + data = kwargs["data"].copy() + data["consents-person"] = str(person.pk) + kwargs.update({"data": data, "prefix": "consents", "initial": {"person": person}}) return kwargs + def get_success_url(self) -> str: + default_url = reverse("person_edit", kwargs={"person_id": self.get_person().pk}) + return safe_next_or_default_url(self.request.GET.get("next"), default=default_url) + def get_success_message(self, *args: Any, **kwargs: Any) -> str: return "Consents were successfully updated." + def form_invalid(self, form: BaseForm) -> HttpResponse: + # No template to re-render the form with; report errors and go back. + errors = "; ".join(f"{field}: {', '.join(str(e) for e in errs)}" for field, errs in form.errors.items()) + messages.error(self.request, f"Consents were not updated. {errors}") + return HttpResponseRedirect(self.get_success_url()) + class ActionRequiredTerms(LoginRequiredMixin, AMYFormView[RequiredConsentsForm]): form_class = RequiredConsentsForm