diff --git a/apps/dot_ext/tests/test_authorization.py b/apps/dot_ext/tests/test_authorization.py index fba7b8b1e..43d57344d 100644 --- a/apps/dot_ext/tests/test_authorization.py +++ b/apps/dot_ext/tests/test_authorization.py @@ -14,19 +14,24 @@ from django.test import Client from django.urls import reverse from oauth2_provider.models import get_access_token_model, get_refresh_token_model - -# from oauth2_provider.compat import parse_qs, urlparse from oauthlib.oauth2.rfc6749.errors import AccessDeniedError as AccessDeniedTokenCustomError from waffle.testutils import override_switch from apps.authorization.models import ArchivedDataAccessGrant, DataAccessGrant -from apps.constants import CODE_CHALLENGE_METHOD_S256, PATIENT_SCOPE +from apps.constants import ( + CODE_CHALLENGE_METHOD_S256, + EOB_SCOPE, + PATIENT_SCOPE, + TEST_APP_CLIENT_ID, + TEST_APP_CLIENT_SECRET, +) from apps.dot_ext.constants import ( APPLICATION_HAS_CLIENT_CREDENTIALS_ENABLED_NON_CLIENT_CREDENTIALS_AUTH_CALL_MADE, AUDIT_EVENT_SCOPE_ERROR_MESSAGE, CLIENT_CREDENTIALS_TYPE, ) from apps.dot_ext.models import Application, ArchivedToken +from apps.dot_ext.utils import create_authorization_header from apps.dot_ext.views import AuthorizationView, TokenView from apps.fhir.bluebutton.models import Crosswalk from apps.fhir.server.authentication import MatchFhirIdErrorType, MatchFhirIdLookupType, MatchFhirIdResult @@ -206,10 +211,10 @@ def test_post_with_valid_non_standard_scheme_granttype_authcode_clienttype_confi 'client_id': application.client_id, 'code_verifier': 'test123456789123456789123456789123456789123456789', } - # Test that request is unauthorized WITH OUT the client_secret. + # Test that request is bad request WITH OUT the client_secret. token_request_data.update({'code_verifier': 'test123456789123456789123456789123456789123456789'}) response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data) - self.assertEqual(response.status_code, 401) + self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) # Setup application's client_secret token_request_data.update({'client_secret': application.client_secret_plain}) @@ -1979,3 +1984,256 @@ def test_failure_on_authorize_non_v3_with_audit_event_scope( assert response.status_code == HTTPStatus.BAD_REQUEST assert response.json()['message'] == expected_message + + +@pytest.mark.integration +@pytest.mark.parametrize( + 'post_data, header, app_config, expected_result', + [ + ( # Empty post body client secret + no header + empty DB client secret returns bad request + {'client_secret': ''}, + '', + # app configuration saving as an empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': '', + }, + # Expect a bad request + { + 'status_code': HTTPStatus.BAD_REQUEST, + 'message': 'The client secret is empty or missing.', + }, + ), + # Empty client secret in Basic header + no client secret in post body + empty DB client secret returns 400 + ( + {}, + create_authorization_header(TEST_APP_CLIENT_ID, ''), + # app configuration saving as an empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': '', + }, + # Expect a bad request + { + 'status_code': HTTPStatus.BAD_REQUEST, + 'message': 'The client secret is empty or missing.', + }, + ), + # No post body client secret + no header + empty DB secret returns 400 + ( + {}, + '', + # app configuration saving as an empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': '', + }, + # Expect a bad request + { + 'status_code': HTTPStatus.BAD_REQUEST, + 'message': 'The client secret is empty or missing.', + }, + ), + ( # Empty post body client secret + no header + non-empty DB client secret returns 400 + {'client_secret': ''}, + '', + # app configuration saving as a non-empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': TEST_APP_CLIENT_SECRET, + }, + # Expect a bad request + { + 'status_code': HTTPStatus.BAD_REQUEST, + 'message': 'The client secret is empty or missing.', + }, + ), + # Empty client secret in Basic header + no client secret in post body + non-empty DB client secret returns 400 + ( + {}, + create_authorization_header(TEST_APP_CLIENT_ID, ''), + # app configuration saving as a non-empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': TEST_APP_CLIENT_SECRET, + }, + # Expect a bad request + { + 'status_code': HTTPStatus.BAD_REQUEST, + 'message': 'The client secret is empty or missing.', + }, + ), + # No post body client secret + no header + empty DB secret returns 400 + ( + {}, + '', + # app configuration saving as a non-empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': TEST_APP_CLIENT_SECRET, + }, + # Expect a bad request + { + 'status_code': HTTPStatus.BAD_REQUEST, + 'message': 'The client secret is empty or missing.', + }, + ), + # Valid client secret in post body + no header + non empty/valid DB secret returns 200 + ( + {'client_secret': TEST_APP_CLIENT_SECRET}, + '', + # app configuration saving as a non-empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': TEST_APP_CLIENT_SECRET, + }, + # Expect passing + { + 'status_code': HTTPStatus.OK, + 'message': 'access_token', + }, + ), + # No client secret in post body + valid header + non-empty/valid DB client secret returns 200 + ( + {}, + create_authorization_header(TEST_APP_CLIENT_ID, TEST_APP_CLIENT_SECRET), + # app configuration saving as non empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': TEST_APP_CLIENT_SECRET, + }, + # Expect passing + { + 'status_code': HTTPStatus.OK, + 'message': 'access_token', + }, + ), + # Valid header client secret + invalid client secret + non-empty/valid DB client secret in body produces a 400 + ( + {'client_secret': 'invalid-secret'}, + create_authorization_header(TEST_APP_CLIENT_ID, TEST_APP_CLIENT_SECRET), + # app configuration saving as a non-empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': TEST_APP_CLIENT_SECRET, + }, + # Expect a bad request + { + 'status_code': HTTPStatus.BAD_REQUEST, + 'message': 'The client secret in Authorization header and POST body do not match.', + }, + ), + # Invalid header client secret + valid client secret + non-empty/valid DB client secret in body produces a 400 + ( + {'client_secret': TEST_APP_CLIENT_SECRET}, + create_authorization_header(TEST_APP_CLIENT_ID, 'invalid-secret'), + # app configuration saving as non empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': TEST_APP_CLIENT_SECRET, + }, + # Expect a bad request + { + 'status_code': HTTPStatus.BAD_REQUEST, + 'message': 'The client secret in Authorization header and POST body do not match.', + }, + ), + # No header + invalid client secret body + non-empty/valid DB client secret in body produces a 401 + ( + {'client_secret': 'invalid-secret'}, + '', + # app configuration saving as non empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': TEST_APP_CLIENT_SECRET, + }, + # Expect unauthorized + { + 'status_code': HTTPStatus.UNAUTHORIZED, + 'message': 'invalid_client', + }, + ), + # No post body client secret + invalid client secret header + non-empty DB client secret in body produces a 401 + ( + {}, + create_authorization_header(TEST_APP_CLIENT_ID, 'invalid-secret'), + # app configuration saving as non empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': TEST_APP_CLIENT_SECRET, + }, + # Expect unauthorized + { + 'status_code': HTTPStatus.UNAUTHORIZED, + 'message': 'invalid_client', + }, + ), + # Valid secret in BOTH header and body and valid db secret returns 200 + ( + {'client_secret': 'test-client-secret'}, + create_authorization_header(TEST_APP_CLIENT_ID, TEST_APP_CLIENT_SECRET), + # app configuration saving as non empty client secret + { + 'client_type': Application.CLIENT_CONFIDENTIAL, + 'client_secret': TEST_APP_CLIENT_SECRET, + }, + # Expect passing + { + 'status_code': HTTPStatus.OK, + 'message': 'access_token', + }, + ), + # No credentials and empty db client_secret but for public app produces 200 + ( + {}, + '', + # app configuration saving as empty client secret + { + 'client_type': Application.CLIENT_PUBLIC, + 'client_secret': '', + }, + # Expect passing + { + 'status_code': HTTPStatus.OK, + 'message': 'access_token', + }, + ), + ], +) +@override_switch('v3_endpoints', active=True) +def test_validate_symmetric_auth_client_secret( + post_data, header, app_config, expected_result, create_auth_code, client +): + """ + Ensure validate_symmetric_auth_client_secret function works properly by blocking empty or + mismatched client_secrets + """ + # Assign constants for the test + redirect_uri = 'com.custom.bluebutton://example.it' + client_id = TEST_APP_CLIENT_ID + scope_name = EOB_SCOPE + code_challenge = 'sZrievZsrYqxdnu2NVD603EiYBM18CuzZpwB-pOSZjo' + code_verifier = 'test123456789123456789123456789123456789123456789' + grant_type = 'authorization_code' + auth_code = create_auth_code( + client_secret=app_config['client_secret'], + client_type=app_config['client_type'], + redirect_uri=redirect_uri, + client_id=client_id, + scope_name=scope_name, + code_challenge=code_challenge, + grant_type=grant_type, + ) + + token_request_data = { + 'grant_type': grant_type, + 'code': auth_code, + 'redirect_uri': redirect_uri, + 'code_verifier': code_verifier, + 'scope': scope_name, + 'client_id': client_id, + } + token_request_data.update(post_data) + response = client.post('/v3/o/token', data=token_request_data, HTTP_AUTHORIZATION=header) + assert response.status_code == expected_result['status_code'] + assert expected_result['message'] in response.content.decode() diff --git a/apps/dot_ext/tests/test_utils.py b/apps/dot_ext/tests/test_utils.py index 1334e4337..663b65bac 100644 --- a/apps/dot_ext/tests/test_utils.py +++ b/apps/dot_ext/tests/test_utils.py @@ -2,18 +2,26 @@ from unittest.mock import MagicMock, patch import pytest -from django.test import TestCase +from django.test import RequestFactory, TestCase from oauthlib.oauth2.rfc6749.errors import InvalidClientError -from apps.dot_ext.constants import CLEAR_HIGHER_ISS, IDME_HIGHER_ISS, IDME_LOWER_ISS, SUPPORTED_VERSION_TEST_CASES +from apps.constants import TEST_APP_CLIENT_ID, TEST_APP_CLIENT_SECRET +from apps.dot_ext.constants import ( + CLEAR_HIGHER_ISS, + IDME_HIGHER_ISS, + IDME_LOWER_ISS, + SUPPORTED_VERSION_TEST_CASES, +) from apps.dot_ext.utils import ( build_jwks_urls, check_can_token_scope_for_audit_event_scopes, check_session_and_create_access_token_extension, + create_authorization_header, get_api_version_number_from_url, remove_application_user_pair_tokens_data_access, validate_client_id, validate_latin_extended_string, + validate_symmetric_client_secret, ) from apps.versions import VersionNotMatched @@ -246,3 +254,63 @@ def test_build_jwks_urls_returns_lower_environment(settings) -> None: } result = build_jwks_urls() assert result == expected + + +@pytest.mark.django_db +@pytest.mark.parametrize( + 'post_data, headers, expected_result', + [ + # Valid client secret in post body ensures client_secret is not empty and passes validation + ({'client_secret': 'valid_secret_123'}, {}, {'passed': True, 'message': ''}), + # Valid client secret in header ensures client secret is not empty and passes validation + ( + {}, + { + 'HTTP_AUTHORIZATION': create_authorization_header(TEST_APP_CLIENT_ID, TEST_APP_CLIENT_SECRET), + }, + {'passed': True, 'message': ''}, + ), + # Empty client secret being passed in to the post body fails validation + ({'client_secret': ''}, {}, {'passed': False, 'message': 'The client secret is empty or missing.'}), + # Client secret with spaces being passed in fails validation + ({'client_secret': ' '}, {}, {'passed': False, 'message': 'The client secret is empty or missing.'}), + # Empty client secret being passed into the header and fails validation + ( + {}, + { + 'HTTP_AUTHORIZATION': create_authorization_header(TEST_APP_CLIENT_ID, ''), + }, + {'passed': False, 'message': 'The client secret is empty or missing.'}, + ), + # No client secret in header or body fails validation + ({}, {}, {'passed': False, 'message': 'The client secret is empty or missing.'}), + # Mismatched client secrets between post body and header fails validation + ( + {'client_secret': TEST_APP_CLIENT_SECRET}, + { + 'HTTP_AUTHORIZATION': create_authorization_header(TEST_APP_CLIENT_ID, 'invalid-secret'), + }, + {'passed': False, 'message': 'The client secret in Authorization header and POST body do not match.'}, + ), + # Matching client secrets between post body and header passes validation + ( + {'client_secret': TEST_APP_CLIENT_SECRET}, + { + 'HTTP_AUTHORIZATION': create_authorization_header(TEST_APP_CLIENT_ID, TEST_APP_CLIENT_SECRET), + }, + {'passed': True, 'message': ''}, + ), + ], +) +def test_validate_symmetric_client_secret(post_data, headers, expected_result): + """ + Test successful and unsuccessful outcomes of validate_symmetric_client_secret + """ + factory = RequestFactory() + + request = factory.post('/token', data=post_data, **headers) + + passed_validation, error_message = validate_symmetric_client_secret(request) + + assert passed_validation is expected_result['passed'] + assert error_message == expected_result['message'] diff --git a/apps/dot_ext/utils.py b/apps/dot_ext/utils.py index 3566caad4..29f4cb104 100644 --- a/apps/dot_ext/utils.py +++ b/apps/dot_ext/utils.py @@ -1,7 +1,8 @@ +import binascii import logging import os import re -from base64 import b64decode +from base64 import b64decode, b64encode from http import HTTPStatus import jwt @@ -30,6 +31,8 @@ AUDIT_EVENT_SEARCH_SCOPE, HHS_SERVER_LOGNAME_FMT, REFRESH_TOKEN, + TEST_APP_CLIENT_ID, + TEST_APP_CLIENT_SECRET, ) from apps.dot_ext.constants import ( APPLICATION_THIRTEEN_MONTH_DATA_ACCESS_NOT_FOUND_MESG, @@ -65,6 +68,55 @@ def validate_client_id(client_id: str) -> None: ) +def validate_symmetric_client_secret(request: HttpRequest) -> tuple[bool, str]: + """ + Validates that a client secret is not empty for symmetric authentication. + Looks at both the header and the post body. Ensures any mismatch between + post body and header fails validation as well. + + Args: + - request (HttpRequest): Django HttpRequest object + + Returns: + - tuple: True if it passes validation, False if not. Also + returns the string of the error message if it doesn't pass validation. + """ + # Handle the client secret in header case + request_meta = request.META + header_secret = None + body_secret = None + if request_meta: + auth_header = request_meta.get('HTTP_AUTHORIZATION', None) + if not auth_header: + auth_header = request_meta.get('Authorization', None) + if auth_header and auth_header.lower().startswith('basic'): + try: + encoded_credentials = auth_header.partition(' ')[2] # Removes 'Basic ' to isolate credentials + decoded_credentials = b64decode(encoded_credentials).decode('utf-8').partition(':') + header_secret = decoded_credentials[2] + except (binascii.Error, UnicodeDecodeError): + return False, 'Invalid Basic authorization header.' + + if not header_secret.strip(): + return False, 'The client secret is empty or missing.' + + # Handle just the client secret in post body case + if hasattr(request, 'POST') and 'client_secret' in request.POST: + body_secret = request.POST.get('client_secret', '') + if not body_secret.strip(): + return False, 'The client secret is empty or missing.' + + # Handle the case of no secret getting sent + if not header_secret and not body_secret: + return False, 'The client secret is empty or missing.' + + # Handle the case where both header and body client secret are sent but they don't match + if header_secret and body_secret and header_secret != body_secret: + return False, 'The client secret in Authorization header and POST body do not match.' + + return True, '' + + def get_oauth_param(request: HttpRequest, parameter: str, fallback_session_parameter: str = None) -> str | None: """Resolve an OAuth parameter from GET, then session, then session['oauth_params']. If those are not available, use request.POST. @@ -505,3 +557,20 @@ def build_jwks_urls(): CLEAR_HIGHER_ISS: settings.CLEAR_HIGHER_JWKS_URL, # Clear does not yet differentiate between envs IDME_LOWER_ISS: settings.IDME_LOWER_JWKS_URL, } + + +def create_authorization_header( + client_id: str = TEST_APP_CLIENT_ID, client_secret: str = TEST_APP_CLIENT_SECRET +) -> str: + """ + Encodes client_id and client_secret into an HTTP Basic Authorization header. + + Args: + - client_id (str): The id of the client + - client_secret (str): The secret of the client + + Returns: + - str: The encoded auth header in the format of 'Basic ' + """ + encoded = b64encode(f'{client_id}:{client_secret}'.encode('utf-8')).decode('utf-8') + return f'Basic {encoded}' diff --git a/apps/dot_ext/views/authorization.py b/apps/dot_ext/views/authorization.py index b6a97ba0a..0a2df06eb 100644 --- a/apps/dot_ext/views/authorization.py +++ b/apps/dot_ext/views/authorization.py @@ -76,7 +76,7 @@ set_session_auth_flow_trace_value, update_instance_auth_flow_trace_with_code, ) -from apps.dot_ext.models import AccessTokenExtension, Approval +from apps.dot_ext.models import AccessTokenExtension, Application, Approval from apps.dot_ext.scopes import CapabilitiesScopes from apps.dot_ext.signals import beneficiary_authorized_application from apps.dot_ext.utils import ( @@ -89,6 +89,7 @@ json_response_from_oauth2_error, remove_application_user_pair_tokens_data_access, validate_app_is_active, + validate_symmetric_client_secret, ) from apps.dot_ext.validators import ( AsymmetricAuthJWTValidator, @@ -794,6 +795,19 @@ def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: }, status=HTTPStatus.FORBIDDEN, ) + else: + is_confidential = getattr(app, 'client_type', '') == Application.CLIENT_CONFIDENTIAL + # Only validate client secret for confidential apps + if is_confidential: + passes_cs_validation, cs_error_message = validate_symmetric_client_secret(request) + if not passes_cs_validation: + return JsonResponse( + { + 'status_code': HTTPStatus.BAD_REQUEST, + 'message': cs_error_message, + }, + status=HTTPStatus.BAD_REQUEST, + ) elif grant_type == CLIENT_CREDENTIALS: # Set this so we can retrieve the app name in request_logger.py, so the app_name is available # in logs for client_credentials calls. This enables us to track CAN metrics app by app diff --git a/apps/fhir/bluebutton/tests/test_jwt_integration.py b/apps/fhir/bluebutton/tests/test_jwt_integration.py index 57c305fe4..d264ef1ff 100644 --- a/apps/fhir/bluebutton/tests/test_jwt_integration.py +++ b/apps/fhir/bluebutton/tests/test_jwt_integration.py @@ -6,15 +6,13 @@ import urllib import uuid from http import HTTPStatus -from urllib.parse import parse_qs, urlencode, urlparse +from urllib.parse import urlencode import jwt import pytest import requests from cryptography.hazmat.primitives import serialization from django.contrib.auth.models import Group -from django.http import HttpRequest -from django.test.client import Client from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By @@ -24,7 +22,6 @@ from apps.constants import ( CLIENT_CREDENTIALS, - CODE_CHALLENGE_METHOD_S256, COVERAGE_SCOPE, EOB_SCOPE, PATIENT_SCOPE, @@ -38,7 +35,6 @@ CLIENT_ASSERTION_TYPE_VALUE, CLIENT_CREDENTIALS_TYPE, ) -from apps.dot_ext.models import Application from apps.wellknown.views.jwks import _local_private_keys # The v3 token endpoint. This MUST be identical everywhere it appears: it is both @@ -68,7 +64,6 @@ # Convert the raw string to a boolean for easier use in the test is_client_enabled = ENABLE_CLIENT.lower() == 'true' -client = Client() def get_can_private_key() -> bytes | str: @@ -317,7 +312,7 @@ def get_can_payload(driver: webdriver.Chrome, app_client_id: str, scope: str) -> } -def get_access_token_response(json_payload: dict) -> dict: +def get_access_token_response(client, json_payload: dict) -> dict: """ Exchanges the CAN request for an access token from the Blue Button API. @@ -328,6 +323,8 @@ def get_access_token_response(json_payload: dict) -> dict: dict: A dictionary containing the access token and other related information. """ if is_client_enabled: + # client = Client() + url = '/v3/o/token' response = client.post( @@ -349,7 +346,7 @@ def get_access_token_response(json_payload: dict) -> dict: @pytest.mark.django_db @override_switch('client_credentials_validation', active=True) @override_switch('v3_endpoints', active=True) -def test_clear_integration_flow(driver, basic_user, create_application, create_capability): +def test_clear_integration_flow(driver, basic_user, create_application, create_capability, client): """ Integration test specifically against clear that does the following: - Runs through the auth process with a synth user in CLEAR to generate a valid IAL JWT (via selenium) @@ -383,7 +380,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c json_payload = get_can_payload(driver, app_client_id, combined_scopes) - access_token_response = get_access_token_response(json_payload) + access_token_response = get_access_token_response(client, json_payload) assert access_token_response.status_code == 200, ( f'Expected status code 200, got {access_token_response.status_code}' @@ -407,9 +404,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Test a successful case with allowed auth type as just auth_code ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_TYPE, }, { @@ -425,9 +420,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Test a successful case with allowed auth type as both auth code and client credentials ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_AND_CLIENT_CREDENTIALS_TYPE, }, { @@ -443,9 +436,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Test unsuccessful case where invalid code isn't included in request ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_AND_CLIENT_CREDENTIALS_TYPE, }, {'token_url': '/v3/o/token', 'code': None}, # strips 'code' from request_token_data @@ -459,9 +450,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Test unsuccessful case where code_verifier isn't included in request ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_AND_CLIENT_CREDENTIALS_TYPE, }, {'token_url': '/v3/o/token', 'code_verifier': None}, # strips 'code_verifier' from request_token_data @@ -475,9 +464,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Test unsuccessful case where client_assertion isn't included in request ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_TYPE, }, { @@ -494,9 +481,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Test unsuccessful case where scope isn't included in request ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_TYPE, }, { @@ -513,9 +498,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Test unsuccessful case where app's jwks_uri is missing ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': '', # Emulates missing application JWKS URI config on our backend - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_TYPE, }, { @@ -532,9 +515,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Test unsuccessful case where app's client_assertion is missing. ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_TYPE, }, { @@ -554,9 +535,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Test redirect_uri not being included fails ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_TYPE, }, { @@ -573,9 +552,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Ensure v2 call fails ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_TYPE, }, { @@ -591,9 +568,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Ensure v1 call fails ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_TYPE, }, { @@ -609,9 +584,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Ensure different client_assertion_type fails ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_TYPE, }, { @@ -628,9 +601,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Ensure client_secret in request for asymmetric auth fails ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_TYPE, }, { @@ -647,9 +618,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c # Ensure enable_asymmetric_auth waffle switch not enabled returns a 403 ( { - 'client_secret': TEST_APP_CLIENT_SECRET, 'jwks_uri': 'http://localhost:8000/.well-known/jwks.json', - 'redirect_uri': 'com.custom.bluebutton://example.it', 'allowed_auth_type': AUTH_CODE_TYPE, }, { @@ -667,13 +636,7 @@ def test_clear_integration_flow(driver, basic_user, create_application, create_c @override_switch('asymmetric_auth_validation', active=True) @override_switch('v3_endpoints', active=True) def test_asymmetric_auth_flow_integration( - app_config, - request_payload_overrides, - expected, - enable_asymm_auth_switch_active, - basic_user, - create_application, - create_capability, + app_config, request_payload_overrides, expected, enable_asymm_auth_switch_active, create_auth_code, client ): """ Integration test checking validation barriers along the Asymmetric Authentication token path. @@ -686,54 +649,24 @@ def test_asymmetric_auth_flow_integration( enable_asymm_auth_switch_active (bool) : True if enable_asymmetric_auth is active, otherwise False """ with override_switch('enable_asymmetric_auth', active=enable_asymm_auth_switch_active): - user = basic_user() - eob_capability = create_capability(name=EOB_SCOPE, urls=[['GET', '/v/fhir/ExplanationOfBenefit[/]?$']]) - - application = create_application( - name='test', - grant_type=Application.GRANT_AUTHORIZATION_CODE, - user=user, - client_type=Application.CLIENT_CONFIDENTIAL, - allowed_auth_type=app_config['allowed_auth_type'], + # Assign constants for the test + redirect_uri = 'com.custom.bluebutton://example.it' + client_id = TEST_APP_CLIENT_ID + scope_name = EOB_SCOPE + code_challenge = 'sZrievZsrYqxdnu2NVD603EiYBM18CuzZpwB-pOSZjo' + code_verifier = 'test123456789123456789123456789123456789123456789' + grant_type = 'authorization_code' + authorization_code = create_auth_code( jwks_uri=app_config['jwks_uri'], - client_id=TEST_APP_CLIENT_ID, - client_secret=app_config['client_secret'], - redirect_uris=app_config['redirect_uri'], - capability=eob_capability, + redirect_uri=redirect_uri, + client_id=client_id, + scope_name=scope_name, + code_challenge=code_challenge, + allowed_auth_type=app_config['allowed_auth_type'], + grant_type=grant_type, ) - request = HttpRequest() - client.login(request=request, username='john', password='123456') - - code_challenge = 'sZrievZsrYqxdnu2NVD603EiYBM18CuzZpwB-pOSZjo' - auth_url = '/v3/o/authorize' - auth_payload = { - 'client_id': application.client_id, - 'response_type': 'code', - 'redirect_uri': app_config['redirect_uri'], - 'code_challenge': code_challenge, - 'code_challenge_method': CODE_CHALLENGE_METHOD_S256, - } - response = client.get(auth_url, data=auth_payload) - - consent_payload = { - 'client_id': application.client_id, - 'response_type': 'code', - 'redirect_uri': app_config['redirect_uri'], - 'scope': [EOB_SCOPE], - 'expires_in': 86400, - 'allow': True, - 'state': '0123456789abcdef', - 'code_challenge': code_challenge, - 'code_challenge_method': CODE_CHALLENGE_METHOD_S256, - } - consent_response = client.post(response['Location'], data=consent_payload) - assert consent_response.status_code == HTTPStatus.FOUND - - query_dict = parse_qs(urlparse(consent_response['Location']).query) - authorization_code = query_dict.get('code')[0] - - ial_payload = construct_asymmetric_auth_payload(application.client_id) + ial_payload = construct_asymmetric_auth_payload(client_id) client_assertion = jwt.encode( ial_payload, get_can_private_key(), @@ -748,16 +681,17 @@ def test_asymmetric_auth_flow_integration( token_request_data = { 'client_assertion': client_assertion, 'client_assertion_type': CLIENT_ASSERTION_TYPE_VALUE, - 'grant_type': 'authorization_code', - 'scope': EOB_SCOPE, + 'grant_type': grant_type, + 'scope': scope_name, 'code': authorization_code, - 'redirect_uri': app_config['redirect_uri'], - 'code_verifier': 'test123456789123456789123456789123456789123456789', + 'redirect_uri': redirect_uri, + 'code_verifier': code_verifier, } overrides = request_payload_overrides.copy() token_url = overrides.pop('token_url', '/v3/o/token') # Updates token request data dict based upon the test + # Removes any items that are 'None' in the parametrization token_request_data.update(overrides) token_request_data = {k: v for k, v in token_request_data.items() if v is not None} diff --git a/conftest.py b/conftest.py index ed4312fb6..d771563d3 100644 --- a/conftest.py +++ b/conftest.py @@ -6,19 +6,24 @@ from selenium import webdriver try: + from urllib.parse import parse_qs, urlparse + from django.contrib.auth.models import Group, User from django.core.management import call_command + from django.http import HttpRequest from django.utils.text import slugify from oauth2_provider.models import get_access_token_model from apps.authorization.models import DataAccessGrant from apps.capabilities.models import ProtectedCapability from apps.constants import ( + CODE_CHALLENGE_METHOD_S256, COVERAGE_SCOPE, DEFAULT_SAMPLE_FHIR_ID_V2, DEFAULT_SAMPLE_FHIR_ID_V3, EOB_SCOPE, PATIENT_SCOPE, + TEST_APP_CLIENT_ID, ) from apps.dot_ext.models import Application, InternalApplicationLabels from apps.fhir.bluebutton.models import Crosswalk @@ -444,3 +449,131 @@ def _bene_access_token( return create_token(first_name, last_name, **kwargs) return _bene_access_token + + +@pytest.fixture +def create_auth_code(basic_user, create_application, create_capability, get_auth_code): + """ + Factory fixture producing a complete OAuth PKCE authorization setup: + user + capability + application + authorization code. Returns the auth code string. + + Any extra keyword arguments (**app_kwargs) are forwarded directly to + create_application. Reach for get_auth_code directly when you already have + a custom user or application and only need a code. + + Usage: + Defaults: + def test_something(create_auth_code): + auth_code = create_auth_code() + + Overrides: + def test_something(create_auth_code): + auth_code = create_auth_code( + client_id='client_id', + client_secret='client_secret', + redirect_uri='redirect_uri', + client_type='client_type', + ) + """ + + def _create_auth_code( + client_id: str = TEST_APP_CLIENT_ID, + redirect_uri: str = 'com.custom.bluebutton://example.it', + version: int = 3, + scope_name: str = EOB_SCOPE, + urls: list[list[str]] = [['GET', '/v/fhir/ExplanationOfBenefit[/]?$']], + code_challenge: str = 'sZrievZsrYqxdnu2NVD603EiYBM18CuzZpwB-pOSZjo', + **app_kwargs, + ): + user = basic_user() + capability = create_capability(name=scope_name, urls=urls) + application = create_application( + name=f'{user.first_name}_{user.last_name}_test', + user=user, + capability=capability, + client_id=client_id, + redirect_uris=redirect_uri, + **app_kwargs, + ) + return get_auth_code( + client_id=application.client_id, + redirect_uri=application.redirect_uris, + version=version, + scope_name=scope_name, + code_challenge=code_challenge, + username=user.username, + ) + + return _create_auth_code + + +@pytest.fixture +def get_auth_code(db, client): + """ + Factory fixture that gets an OAuth authorization code. + + Simulates a user logging in, initiating an authorization request, and approving + the consent form to produce a valid single-use authorization code. + + This assumes that an application, capability, and a user have already been created + as a part of the test. + + Usage: + # Use all defaults + def test_something(get_auth_code): + user = get_auth_code() + + # Override specific values + def test_something(get_auth_code): + user = get_auth_code( + client_id='my-client-id', + redirect_uri='my-redirect-uri.com', + scope_name='patient/Coverage.rs', + username='gerome', + ) + """ + + def _get_auth_code( + client_id: str = TEST_APP_CLIENT_ID, + redirect_uri: str = 'com.custom.bluebutton://example.it', + version: int = Versions.V3, + scope_name: str = EOB_SCOPE, + code_challenge: str = 'sZrievZsrYqxdnu2NVD603EiYBM18CuzZpwB-pOSZjo', + username: str = 'john', + password: str = '123456', + state: str = '0123456789abcdef', + ): + + # User logs in + request = HttpRequest() + client.login(request=request, username=username, password=password) + # User initiates authorization request + payload = { + 'client_id': client_id, + 'response_type': 'code', + 'redirect_uri': redirect_uri, + 'code_challenge': code_challenge, + 'code_challenge_method': CODE_CHALLENGE_METHOD_S256, + } + response = client.get(f'/v{version}/o/authorize', data=payload) + # User approves consent form + payload = { + 'client_id': client_id, + 'response_type': 'code', + 'redirect_uri': redirect_uri, + 'scope': [scope_name], + 'expires_in': 86400, + 'allow': True, + 'state': state, + 'code_challenge': code_challenge, + 'code_challenge_method': CODE_CHALLENGE_METHOD_S256, + } + response = client.post(response['Location'], data=payload) + + # Extract the authorization code + query_dict = parse_qs(urlparse(response['Location']).query) + authorization_code = query_dict.get('code')[0] + + return authorization_code + + return _get_auth_code