Skip to content

Commit

Permalink
Catch errors from badly formatted date strings
Browse files Browse the repository at this point in the history
We’ve been seeing attempts to access regulation versions with the format YEAR-DAY-MONTH. This isn’t a valid date string, and raises a `ValidationError`, which we don’t catch, so the user sees a 500. This change catches that `ValidationError` and raises a 404.
  • Loading branch information
willbarton committed Feb 17, 2022
1 parent 6e3dbfd commit a09f7e1
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
15 changes: 10 additions & 5 deletions cfgov/regulations3k/models/pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from functools import partial
from urllib.parse import urljoin

from django.core.exceptions import ValidationError
from django.core.paginator import InvalidPage, Paginator
from django.db import models
from django.http import Http404, HttpResponse, JsonResponse
Expand Down Expand Up @@ -283,11 +284,15 @@ def get_effective_version(self, request, date_str=None):
if not draft_permission:
query_filter['draft'] = False

effective_version = self.regulation.versions.filter(
**query_filter
).order_by(
'-effective_date'
).first()
try:
effective_version = self.regulation.versions.filter(
**query_filter
).order_by(
'-effective_date'
).first()
except ValidationError:
# This can be raised by an invalid date string
raise Http404

if effective_version is None:
raise Http404
Expand Down
8 changes: 8 additions & 0 deletions cfgov/regulations3k/tests/test_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,11 @@ def test_redirect_uppercase(self):
self.assertEqual(
response.get('location'),
'/reg-landing/1002/interp-2/')

def test_invalid_effective_date(self):
# Try to fetch a date string that's incorrectly formatted.
# It should 404.
response = self.client.get(
'/reg-landing/1002/2014-18-01/'
)
self.assertEqual(response.status_code, 404)

0 comments on commit a09f7e1

Please sign in to comment.