Skip to content

Commit

Permalink
Validate URL - must be a link to Notify docs taht goes to a section
Browse files Browse the repository at this point in the history
in those docs.
  • Loading branch information
CrystalPea committed Oct 2, 2024
1 parent 5f07d26 commit 9addf91
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
12 changes: 11 additions & 1 deletion app/main/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down
28 changes: 28 additions & 0 deletions tests/app/main/views/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 9addf91

Please sign in to comment.