From ac67f1f33f86484ec73f9be353084e90bab51c72 Mon Sep 17 00:00:00 2001 From: Ross Perry Date: Thu, 18 Jan 2024 11:31:01 -0700 Subject: [PATCH] Catch invalid organization id preventing 500s (#4475) * eeej small files * return -1 if org id is invalid type --------- Co-authored-by: Katherine Fleming <2205659+kflemin@users.noreply.github.com> --- seed/lib/superperms/orgs/permissions.py | 15 +++++++++------ seed/tests/test_permissions.py | 21 +++++++++++++++++++++ seed/tests/test_views.py | 7 +++++++ 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/seed/lib/superperms/orgs/permissions.py b/seed/lib/superperms/orgs/permissions.py index 14b9d41e96..2d1abc8efb 100644 --- a/seed/lib/superperms/orgs/permissions.py +++ b/seed/lib/superperms/orgs/permissions.py @@ -50,12 +50,15 @@ def get_org_or_id(dictlike: dict) -> Union[int, None]: # Check if there are any assigned organization values org_id = None for org_str in org_query_strings: - org_id = dictlike.get(org_str) - if org_id: - # Type case the organization_id as a integer - if '_id' in org_str: - org_id = int(org_id) - break + try: + org_id = dictlike.get(org_str) + if org_id: + # Type case the organization_id as a integer + if '_id' in org_str: + org_id = int(org_id) + break + except (ValueError, TypeError): + return -1 return org_id diff --git a/seed/tests/test_permissions.py b/seed/tests/test_permissions.py index 44f7eb18a5..ab28acd83d 100644 --- a/seed/tests/test_permissions.py +++ b/seed/tests/test_permissions.py @@ -138,6 +138,27 @@ def test_get_org_id(self): result = get_org_id(mock_request) self.assertEqual(None, result) + # invalid ids are returned as -1 (not found) + mock_request = mock_request_factory( + view_authz_org_id_kwarg=None, + parser_kwargs={'not_org_id': 1}, + path='/api/v3/nope/2/', + query_params={'organization_id': 'invalid_id'}, + data={'organization_id': 4} + ) + result = get_org_id(mock_request) + self.assertEqual(-1, result) + + mock_request = mock_request_factory( + view_authz_org_id_kwarg=None, + parser_kwargs={'not_org_id': 1}, + path='/api/v3/nope/2/', + query_params={'not_org_id': 2}, + data={'organization_id': 'invalid_id'} + ) + result = get_org_id(mock_request) + self.assertEqual(-1, result) + def test_get_user_org(self): """Test getting org from user""" fake_user = User.objects.create(username='test') diff --git a/seed/tests/test_views.py b/seed/tests/test_views.py index 99083a1286..c09b147215 100644 --- a/seed/tests/test_views.py +++ b/seed/tests/test_views.py @@ -1560,6 +1560,13 @@ def test_get_cycles(self): self.assertEqual(cycle['id'], self.cycle.pk) self.assertEqual(cycle['name'], self.cycle.name) + # invalid organization id returns 403 error + params['organization_id'] = 'invalid' + response = self.client.get( + reverse('api:v3:cycles-list'), params + ) + self.assertEqual(403, response.status_code) + def test_postoffice(self): # Create a template response = self.client.post('/api/v3/postoffice/', {