From 9addf91f4e5fa2801e82a1d3b78ad85c6fd5c714 Mon Sep 17 00:00:00 2001 From: Pea Tyczynska Date: Tue, 1 Oct 2024 18:09:59 +0100 Subject: [PATCH] Validate URL - must be a link to Notify docs taht goes to a section in those docs. --- app/main/forms.py | 12 +++++++++++- tests/app/main/views/test_index.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/app/main/forms.py b/app/main/forms.py index 79b2cf8b870..2868800402f 100644 --- a/app/main/forms.py +++ b/app/main/forms.py @@ -5,6 +5,7 @@ from functools import partial from itertools import chain from numbers import Number +from urllib.parse import urlparse import pytz from flask import request @@ -2290,7 +2291,16 @@ class UrlForm(StripWhitespaceForm): ) def validate(self, *args, **kwargs): - return super().validate(*args, **kwargs) or self.url.data == "" + self.url.validators.append(self.check_url) + return super().validate(*args, **kwargs) + + def check_url(self, *args, **kwargs): + parsed_url = urlparse(self.url.data) + + if parsed_url.hostname == "docs.notifications.service.gov.uk" and parsed_url.fragment: + return parsed_url + else: + raise ValidationError("Must be a valid https URL, pointing to a section within the GOV.UK Notify API docs.") class SMSPrefixForm(StripWhitespaceForm): diff --git a/tests/app/main/views/test_index.py b/tests/app/main/views/test_index.py index df8e2b84d5c..2ba0435485b 100644 --- a/tests/app/main/views/test_index.py +++ b/tests/app/main/views/test_index.py @@ -402,3 +402,31 @@ def test_POST_guidance_api_documentation_section(client_request): section_tag="send-a-file-by-email", ), ) + + +@pytest.mark.parametrize( + "url, expected_error_message", + [ + ["", "Cannot be empty"], # empty string + [ + "https://docs.notifications.service.gov.uk/python.html", + "Must be a valid https URL, pointing to a section within the GOV.UK Notify API docs.", + ], # no section + [ + "https://docs.payments.service.gov.uk/making_payments/#creating-a-payment", + "Must be a valid https URL, pointing to a section within the GOV.UK Notify API docs.", + ], # URL is notfor Notify's docs + [ + "http://docs.notifications.service.gov.uk/python.html#send-a-file-by-email", + "Must be a valid https URL", + ], # http instead of https + ], +) +def test_POST_guidance_api_documentation_section_with_incorrect_url(client_request, url, expected_error_message): + page = client_request.post( + "main.guidance_api_documentation_section", + _data={"url": url}, + _expected_status=200, + ) + + assert expected_error_message in page.select_one(".govuk-error-message").text