From 6292e528fd9b633cc7f8a8b6b6cde774b5f0e784 Mon Sep 17 00:00:00 2001
From: Kesara Rathnayake <krathnayake@ietf.org>
Date: Fri, 24 Sep 2021 10:01:03 +0000
Subject: [PATCH] Improves API authentication tests. Relates to #3412. Commit
 ready for merge.  - Legacy-Id: 19392

---
 ietf/ietfauth/tests.py | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)

diff --git a/ietf/ietfauth/tests.py b/ietf/ietfauth/tests.py
index dba379c73..647384fa0 100644
--- a/ietf/ietfauth/tests.py
+++ b/ietf/ietfauth/tests.py
@@ -633,7 +633,7 @@ class IetfAuthTests(TestCase):
 
             # bad method
             r = self.client.put(key.endpoint, {'apikey':key.hash()})
-            self.assertEqual(r.status_code, 405)
+            self.assertContains(r, 'Method not allowed', status_code=405)
 
             # missing apikey
             r = self.client.post(key.endpoint, {'dummy':'dummy',})
@@ -643,6 +643,22 @@ class IetfAuthTests(TestCase):
             r = self.client.post(key.endpoint, {'apikey':BAD_KEY, 'dummy':'dummy',})
             self.assertContains(r, 'Invalid apikey', status_code=403)
 
+            # invalid garbage apikey (decode error)
+            r = self.client.post(key.endpoint, {'apikey':'foobar', 'dummy':'dummy',})
+            self.assertContains(r, 'Invalid apikey', status_code=403)
+
+            # invalid garbage apikey (struct unpack error)
+            # number of characters in apikey must be divisible by 4
+            r = self.client.post(key.endpoint, {'apikey':'foob', 'dummy':'dummy',})
+            self.assertContains(r, 'Invalid apikey', status_code=403)
+
+            # invalid apikey (invalidated api key)
+            unauthorized_url = urlreverse('ietf.api.views.author_tools')
+            invalidated_apikey = PersonalApiKey.objects.create(
+                        endpoint=unauthorized_url, person=person, valid=False)
+            r = self.client.post(unauthorized_url, {'apikey': invalidated_apikey})
+            self.assertContains(r, 'Invalid apikey', status_code=403)
+
             # too long since regular login
             person.user.last_login = datetime.datetime.now() - datetime.timedelta(days=settings.UTILS_APIKEY_GUI_LOGIN_LIMIT_DAYS+1)
             person.user.save()