|
| 1 | +import json |
| 2 | + |
| 3 | +from django.conf import settings |
| 4 | +from django.contrib.auth.models import AnonymousUser |
| 5 | +from django.http import HttpResponse |
| 6 | +from django.test import RequestFactory, SimpleTestCase, override_settings |
| 7 | + |
| 8 | +from core.middlewares.middlewares import RequireAuthenticationMiddleware |
| 9 | + |
| 10 | + |
| 11 | +@override_settings( |
| 12 | + REQUIRE_AUTHENTICATION=True, |
| 13 | + APPROVED_ANONYMOUS_CLIENTS=['test-client'], |
| 14 | + APPROVED_ANONYMOUS_API_KEYS=['test-api-key'], |
| 15 | + APPROVED_ANONYMOUS_IPS=['10.0.0.1'], |
| 16 | +) |
| 17 | +class RequireAuthenticationMiddlewareTest(SimpleTestCase): |
| 18 | + """Verify anonymous authentication enforcement and approved bypasses.""" |
| 19 | + |
| 20 | + def setUp(self): |
| 21 | + """Create a request factory and middleware instance for each test.""" |
| 22 | + self.factory = RequestFactory() |
| 23 | + self.middleware = RequireAuthenticationMiddleware(lambda request: HttpResponse('ok')) |
| 24 | + |
| 25 | + def make_request(self, path='/orgs/', method='get', user=None, **meta): |
| 26 | + """Build a request object with a controllable authenticated user state.""" |
| 27 | + request_method = getattr(self.factory, method.lower()) |
| 28 | + request = request_method(path, **meta) |
| 29 | + request.user = user or AnonymousUser() |
| 30 | + return request |
| 31 | + |
| 32 | + def test_allows_authenticated_request(self): |
| 33 | + """Authenticated requests should bypass the anonymous access gate.""" |
| 34 | + user = type('AuthenticatedUser', (), {'is_authenticated': True})() |
| 35 | + |
| 36 | + response = self.middleware(self.make_request(user=user)) |
| 37 | + |
| 38 | + self.assertEqual(response.status_code, 200) |
| 39 | + |
| 40 | + def test_blocks_anonymous_request_for_protected_path(self): |
| 41 | + """Anonymous traffic to protected API paths should receive a 403 response.""" |
| 42 | + response = self.middleware(self.make_request('/orgs/OCL/')) |
| 43 | + |
| 44 | + self.assertEqual(response.status_code, 403) |
| 45 | + self.assertEqual( |
| 46 | + json.loads(response.content), |
| 47 | + { |
| 48 | + 'detail': 'Authentication required. Anonymous API access is disabled.', |
| 49 | + 'upgrade_url': 'https://app.openconceptlab.org/pricing', |
| 50 | + } |
| 51 | + ) |
| 52 | + |
| 53 | + def test_allows_anonymous_request_for_approved_client_header(self): |
| 54 | + """Approved X-OCL-CLIENT values should retain anonymous access.""" |
| 55 | + response = self.middleware(self.make_request('/orgs/OCL/', HTTP_X_OCL_CLIENT='test-client')) |
| 56 | + |
| 57 | + self.assertEqual(response.status_code, 200) |
| 58 | + |
| 59 | + def test_blocks_anonymous_request_for_unapproved_client_header(self): |
| 60 | + """Unknown X-OCL-CLIENT values should still be rejected.""" |
| 61 | + response = self.middleware(self.make_request('/orgs/OCL/', HTTP_X_OCL_CLIENT='unknown-client')) |
| 62 | + |
| 63 | + self.assertEqual(response.status_code, 403) |
| 64 | + |
| 65 | + def test_blocks_anonymous_request_for_whitespace_client_header(self): |
| 66 | + """Whitespace-only client header values should be rejected after normalization.""" |
| 67 | + response = self.middleware(self.make_request('/orgs/OCL/', HTTP_X_OCL_CLIENT=' ')) |
| 68 | + |
| 69 | + self.assertEqual(response.status_code, 403) |
| 70 | + |
| 71 | + def test_allows_anonymous_request_for_approved_api_key_header(self): |
| 72 | + """Allowlisted anonymous API keys should bypass the gate.""" |
| 73 | + response = self.middleware(self.make_request('/orgs/OCL/', HTTP_X_API_KEY='test-api-key')) |
| 74 | + |
| 75 | + self.assertEqual(response.status_code, 200) |
| 76 | + |
| 77 | + def test_allows_anonymous_request_for_approved_authorization_token(self): |
| 78 | + """Allowlisted bearer or token credentials should bypass the gate.""" |
| 79 | + response = self.middleware(self.make_request('/orgs/OCL/', HTTP_AUTHORIZATION='Token test-api-key')) |
| 80 | + |
| 81 | + self.assertEqual(response.status_code, 200) |
| 82 | + |
| 83 | + def test_blocks_anonymous_request_for_query_string_api_key(self): |
| 84 | + """Query string API keys should not bypass the authentication gate.""" |
| 85 | + response = self.middleware(self.make_request('/orgs/OCL/?api_key=test-api-key')) |
| 86 | + |
| 87 | + self.assertEqual(response.status_code, 403) |
| 88 | + |
| 89 | + def test_allows_anonymous_request_for_approved_ip(self): |
| 90 | + """Allowlisted source IPs should keep anonymous access.""" |
| 91 | + response = self.middleware(self.make_request('/orgs/OCL/', REMOTE_ADDR='10.0.0.1')) |
| 92 | + |
| 93 | + self.assertEqual(response.status_code, 200) |
| 94 | + |
| 95 | + def test_blocks_anonymous_request_for_forwarded_ip_only(self): |
| 96 | + """Forwarded IP headers alone should not bypass the authentication gate.""" |
| 97 | + response = self.middleware( |
| 98 | + self.make_request('/orgs/OCL/', HTTP_X_FORWARDED_FOR='10.0.0.1', REMOTE_ADDR='203.0.113.5') |
| 99 | + ) |
| 100 | + |
| 101 | + self.assertEqual(response.status_code, 403) |
| 102 | + |
| 103 | + def test_allows_options_request(self): |
| 104 | + """CORS preflight requests should not be blocked.""" |
| 105 | + response = self.middleware(self.make_request('/orgs/OCL/', method='options')) |
| 106 | + |
| 107 | + self.assertEqual(response.status_code, 200) |
| 108 | + |
| 109 | + def test_allows_elb_health_checker_request(self): |
| 110 | + """Infrastructure health checks should bypass the gate.""" |
| 111 | + response = self.middleware( |
| 112 | + self.make_request('/orgs/OCL/', HTTP_USER_AGENT='ELB-HealthChecker/2.0') |
| 113 | + ) |
| 114 | + |
| 115 | + self.assertEqual(response.status_code, 200) |
| 116 | + |
| 117 | + def test_allows_exempt_exact_paths(self): |
| 118 | + """Public root-level utility endpoints should remain anonymous.""" |
| 119 | + for path in ['/', '/version/', '/changelog/', '/feedback/', '/toggles/', '/locales/', '/events/']: |
| 120 | + with self.subTest(path=path): |
| 121 | + response = self.middleware(self.make_request(path)) |
| 122 | + self.assertEqual(response.status_code, 200) |
| 123 | + |
| 124 | + def test_allows_exempt_path_prefixes(self): |
| 125 | + """Auth, docs, admin, and FHIR prefixes should remain anonymous.""" |
| 126 | + paths = [ |
| 127 | + '/healthcheck/', |
| 128 | + '/users/api-token/', |
| 129 | + '/users/login/', |
| 130 | + '/users/logout/', |
| 131 | + '/users/signup/', |
| 132 | + '/users/password/reset/', |
| 133 | + '/users/oidc/code-exchange/', |
| 134 | + '/oidc/authenticate/', |
| 135 | + '/fhir/', |
| 136 | + '/swagger/', |
| 137 | + '/swagger.json', |
| 138 | + '/redoc/', |
| 139 | + '/admin/login/', |
| 140 | + ] |
| 141 | + |
| 142 | + for path in paths: |
| 143 | + with self.subTest(path=path): |
| 144 | + response = self.middleware(self.make_request(path)) |
| 145 | + self.assertEqual(response.status_code, 200) |
| 146 | + |
| 147 | + def test_allows_exempt_dynamic_user_paths(self): |
| 148 | + """Public user verification and following endpoints should remain anonymous.""" |
| 149 | + paths = [ |
| 150 | + '/users/alice/verify/token-123/', |
| 151 | + '/users/alice/sso-migrate/', |
| 152 | + '/users/alice/following/', |
| 153 | + ] |
| 154 | + |
| 155 | + for path in paths: |
| 156 | + with self.subTest(path=path): |
| 157 | + response = self.middleware(self.make_request(path)) |
| 158 | + self.assertEqual(response.status_code, 200) |
| 159 | + |
| 160 | + |
| 161 | +@override_settings(REQUIRE_AUTHENTICATION=False) |
| 162 | +class RequireAuthenticationSettingsTest(SimpleTestCase): |
| 163 | + """Verify auth-enforcement middleware configuration toggles cleanly.""" |
| 164 | + |
| 165 | + def test_authentication_middleware_not_inserted_when_disabled(self): |
| 166 | + """RequireAuthenticationMiddleware should be absent when the feature is disabled.""" |
| 167 | + self.assertNotIn('core.middlewares.middlewares.RequireAuthenticationMiddleware', settings.MIDDLEWARE) |
0 commit comments