|
| 1 | +import os |
| 2 | + |
| 3 | +from django.test import Client |
| 4 | + |
| 5 | + |
| 6 | +from coldfront_plugin_api.tests.functional import utils |
| 7 | +from coldfront_plugin_api.tests.base import TestBase |
| 8 | + |
| 9 | + |
| 10 | +class TestAuthOIDC(TestBase): |
| 11 | + @classmethod |
| 12 | + def setUpClass(self): |
| 13 | + super().setUpClass() |
| 14 | + self.kc_client = utils.UpdatedKeycloakClient() |
| 15 | + # Only initialize Coldfront client if running in Github action |
| 16 | + if os.getenv("CI") == "true": |
| 17 | + self.kc_client.create_client( |
| 18 | + "master", |
| 19 | + "coldfront", |
| 20 | + "nomoresecret", |
| 21 | + ["http://foo/signup/oidc_redirect_uri"], |
| 22 | + ) |
| 23 | + self. kc_client. create_user( "master", "[email protected]", "staff", "staff") |
| 24 | + self. kc_client. create_user( "master", "[email protected]", "user", "user") |
| 25 | + |
| 26 | + def setUp(self): |
| 27 | + super().setUp() |
| 28 | + self. staff_user = self. new_user( "[email protected]") |
| 29 | + self. normal_user = self. new_user( "[email protected]") |
| 30 | + |
| 31 | + self.staff_user.is_staff = True |
| 32 | + self.staff_user.save() |
| 33 | + |
| 34 | + def test_oidc_authenticated(self): |
| 35 | + # Test for both staff and normal authenticated users |
| 36 | + def impersonate_and_get_endpoint( |
| 37 | + user_to_impersonate, endpoint_url, expected_status_code |
| 38 | + ): |
| 39 | + user_token = self.kc_client.impersonate_access_token(user_to_impersonate) |
| 40 | + |
| 41 | + cf_client = Client() |
| 42 | + r = cf_client.get( |
| 43 | + endpoint_url, |
| 44 | + HTTP_AUTHORIZATION=f"Bearer {user_token}", |
| 45 | + ) |
| 46 | + self.assertEqual(r.status_code, expected_status_code) |
| 47 | + |
| 48 | + for endpoint_url in [ |
| 49 | + "/api/scim/v2/Users", |
| 50 | + "/api/scim/v2/Groups", |
| 51 | + "/api/allocations", |
| 52 | + ]: |
| 53 | + impersonate_and_get_endpoint(self.staff_user.username, endpoint_url, 200) |
| 54 | + impersonate_and_get_endpoint(self.normal_user.username, endpoint_url, 403) |
| 55 | + |
| 56 | + def test_oidc_unauthenticated(self): |
| 57 | + # Test for unauthenticated user case |
| 58 | + cf_client = Client() |
| 59 | + for endpoint_url in [ |
| 60 | + "/api/scim/v2/Users", |
| 61 | + "/api/scim/v2/Groups", |
| 62 | + "/api/allocations", |
| 63 | + ]: |
| 64 | + r = cf_client.get(endpoint_url) |
| 65 | + self.assertEqual(r.status_code, 401) |
0 commit comments