From eb00f8e900ed5a65e331e2c88c4bc26ec69c8e4d Mon Sep 17 00:00:00 2001 From: James Demery Date: Tue, 21 Jul 2026 14:29:52 -0400 Subject: [PATCH 1/4] BB2-4865: Support for OIDC4IDA token format - confirmed both formats work with client_credentials_validation off - cant test new format for now --- apps/dot_ext/constants.py | 27 +++++ .../dot_ext/tests/test_authorization_token.py | 6 +- apps/dot_ext/views/authorization.py | 112 ++++++++++++------ requirements/requirements.dev.txt | 6 +- requirements/requirements.txt | 6 +- 5 files changed, 111 insertions(+), 46 deletions(-) diff --git a/apps/dot_ext/constants.py b/apps/dot_ext/constants.py index 418509107..f408954ca 100644 --- a/apps/dot_ext/constants.py +++ b/apps/dot_ext/constants.py @@ -1650,3 +1650,30 @@ SECONDS_IN_ONE_HOUR = 3600 AUDIT_EVENT_SCOPE_ERROR_MESSAGE = 'Requesting an AuditEvent scope is only valid in token requests through CMS Aligned Networks. For more information, go to this page: https://bluebutton.cms.gov/cms-aligned-networks-documentation/' + +PRIOR_IAL_TOKEN_REQUIRE_LIST_FOR_JWT_DECODE = [ + 'iss', + 'sub', + 'aud', + 'jti', + 'exp', + 'iat', + 'identity_assurance_level', + 'auth_time', + 'family_name', + 'given_name', + 'birthdate', +] + +OIDC4IDC_TOKEN_REQUIRE_LIST_FOR_JWT_DECODE = [ + 'iss', + 'sub', + 'aud', + 'jti', + 'exp', + 'iat', + 'verified_claims', + 'uuid', + 'auth_time', + 'at_hash', +] diff --git a/apps/dot_ext/tests/test_authorization_token.py b/apps/dot_ext/tests/test_authorization_token.py index 7567d4c74..7557a46b6 100644 --- a/apps/dot_ext/tests/test_authorization_token.py +++ b/apps/dot_ext/tests/test_authorization_token.py @@ -700,7 +700,7 @@ def test_validate_ial_jwt_success( } # Call succeeds - result = self.token_view._validate_ial_jwt('token', self.mock_jwks_client) + result = self.token_view._validate_ial_jwt('token', self.mock_jwks_client, False) assert result == self.mock_ial_jwt_payload # Assert cache has the key we'd expect and that the result is what we'd expect @@ -725,7 +725,7 @@ def test_validate_ial_jwt_cache_replay( } # First call succeeds - self.token_view._validate_ial_jwt('token', self.mock_jwks_client) + self.token_view._validate_ial_jwt('token', self.mock_jwks_client, False) # Assert cache contains expected key cache_key = f'{self.mock_ial_jwt_payload.get("iss")}-{self.mock_ial_jwt_payload.get("jti")}' @@ -733,7 +733,7 @@ def test_validate_ial_jwt_cache_replay( # Second call with same jti/iss fails with pytest.raises(InvalidRequestError): - self.token_view._validate_ial_jwt('token', self.mock_jwks_client) + self.token_view._validate_ial_jwt('token', self.mock_jwks_client, False) def test_validate_time_comparison_succeeds( self, diff --git a/apps/dot_ext/views/authorization.py b/apps/dot_ext/views/authorization.py index 653f12568..96e27b768 100644 --- a/apps/dot_ext/views/authorization.py +++ b/apps/dot_ext/views/authorization.py @@ -92,8 +92,10 @@ IDME_HIGHER_ISS, IDME_LOWER_ISS, JWKS_URLS, + OIDC4IDC_TOKEN_REQUIRE_LIST_FOR_JWT_DECODE, PARAMETERS_ID_MATCH_META, PATIENT_ID_MATCH_META, + PRIOR_IAL_TOKEN_REQUIRE_LIST_FOR_JWT_DECODE, YYYY_MM_DD_REGEX, ) from apps.dot_ext.forms import SimpleAllowForm @@ -867,12 +869,13 @@ def _validate_idme_url_for_id_token_and_environment(self, issuer: str) -> bool: return True - def _validate_ial_jwt(self, id_token: str, jwks_client: PyJWKClient) -> dict: + def _validate_ial_jwt(self, id_token: str, jwks_client: PyJWKClient, oidc4ida_token_format: bool) -> dict: """Validates an IAL JWT from a trusted CSP Args: id_token (str): base64 encoded id_token jwt from cms_smart extension jwks_client (PyJWKClient): instantiated client for the authorization jwt + oidc4ida_token_format (bool): Flag for if the token is in OIDC4IDA format Raises: InvalidRequestError: if any validation step fails, log and raise @@ -882,25 +885,17 @@ def _validate_ial_jwt(self, id_token: str, jwks_client: PyJWKClient) -> dict: """ if waffle.switch_is_active('client_credentials_validation'): signing_key = jwks_client.get_signing_key_from_jwt(id_token) + + require_list = PRIOR_IAL_TOKEN_REQUIRE_LIST_FOR_JWT_DECODE + if oidc4ida_token_format: + require_list = OIDC4IDC_TOKEN_REQUIRE_LIST_FOR_JWT_DECODE try: data = jwt.decode_complete( id_token, signing_key, # leeway=timedelta(minutes=5), options={ - 'require': [ - 'iss', - 'sub', - 'aud', - 'jti', - 'exp', - 'iat', - 'identity_assurance_level', - 'auth_time', - 'family_name', - 'given_name', - 'birthdate', - ], + 'require': require_list, 'verify_aud': False, }, algorithms=CSP_IAL_ACCEPTED_JWT_ALGORITHMS, @@ -908,15 +903,23 @@ def _validate_ial_jwt(self, id_token: str, jwks_client: PyJWKClient) -> dict: except jwt.PyJWTError as e: log.warning(f'jwt.decode_complete() failed because {type(e)}') raise InvalidRequestError - payload, header = data.get('payload'), data.get('header') + payload_to_return, header = data.get('payload'), data.get('header') + + payload = payload_to_return + if oidc4ida_token_format: + payload = payload_to_return.get('verified_claims') if not payload or not header or header.get('typ') != 'JWT': log.warning('Malformed header / payload') raise InvalidRequestError # Validate iat and auth_time - self._validate_time_comparison(payload, 'iat', 300) - self._validate_time_comparison(payload, 'auth_time', 300) + if oidc4ida_token_format: + self._validate_time_comparison(payload_to_return, 'iat', 300) + self._validate_time_comparison(payload_to_return, 'auth_time', 300) + else: + self._validate_time_comparison(payload, 'iat', 300) + self._validate_time_comparison(payload, 'auth_time', 300) if not self._validate_idme_url_for_id_token_and_environment(payload.get('iss', '')): log.warning('The issuer of the token is not valid for this environment') @@ -926,9 +929,21 @@ def _validate_ial_jwt(self, id_token: str, jwks_client: PyJWKClient) -> dict: log.warning('jti/iss combo replay') raise InvalidRequestError - if payload.get('identity_assurance_level') < 2: - log.warning(f'identity_assurance_level was invalid: {payload.get("identity_assurance_level")}') - raise InvalidRequestError + if oidc4ida_token_format: + if payload.get('verification', {}).get('trust_framework', '') != 'nist_800_63a': + log.warning( + f'trust_framework was invalid: {payload.get("verification", {}).get("trust_framework")}' + ) + raise InvalidRequestError + if payload.get('verification', {}).get('assurance_level', '') not in ['ial2', 'ial3']: + log.warning( + f'assurance_level was invalid: {payload.get("verification", {}).get("assurance_level")}' + ) + raise InvalidRequestError + else: + if payload.get('identity_assurance_level') < 2: + log.warning(f'identity_assurance_level was invalid: {payload.get("identity_assurance_level")}') + raise InvalidRequestError if not validate_latin_extended_string(payload.get('family_name')): log.warning( @@ -947,15 +962,15 @@ def _validate_ial_jwt(self, id_token: str, jwks_client: PyJWKClient) -> dict: raise InvalidRequestError else: try: - payload = jwt.decode(id_token, options={'verify_signature': False}) + payload_to_return = jwt.decode(id_token, options={'verify_signature': False}) except jwt.PyJWTError as e: log.warning(f'jwt.decode_complete() failed because {type(e)}') raise InvalidRequestError - if not self._validate_idme_url_for_id_token_and_environment(payload.get('iss', '')): + if not self._validate_idme_url_for_id_token_and_environment(payload_to_return.get('iss', '')): log.warning('The issuer of the token is not valid for this environment') raise InvalidRequestError - return payload + return payload_to_return def _validate_time_comparison( self, payload_data: dict[str, Any], jwt_key: str, max_age_seconds: int @@ -996,15 +1011,19 @@ def _validate_time_comparison( raise InvalidRequestError return True - def _parse_ial_into_parameter(self, payload: dict) -> dict: + def _parse_ial_into_parameter(self, payload: dict, oidc4ida_token_format: bool) -> dict: """Parses an IAL token into a Patient and Parameters resource Args: payload (dict): the IAL token + oidc4ida_token_format (bool): Flag for if the token is in OIDC4IDA format Returns: Parameters: a json dump of the Parameters object """ + if oidc4ida_token_format: + payload = payload.get('verified_claims') + patient_name = HumanName( use='official', family=payload.get('family_name'), @@ -1012,22 +1031,38 @@ def _parse_ial_into_parameter(self, payload: dict) -> dict: ) telecoms = [] - if payload.get('phone_number') and payload.get('phone_number_verified'): - telecoms.append( - ContactPoint( - system='phone', - value=payload.get('phone_number'), - use='mobile', - rank=1, + # To support both token types we need this check here, as OIDC4IDA does not have a phone_number_verified + # attribute + if oidc4ida_token_format: + if payload.get('phone_number'): + telecoms.append( + ContactPoint( + system='phone', + value=payload.get('phone_number'), + use='mobile', + rank=1, + ) + ) + else: + if payload.get('phone_number') and payload.get('phone_number_verified'): + telecoms.append( + ContactPoint( + system='phone', + value=payload.get('phone_number'), + use='mobile', + rank=1, + ) ) - ) if payload.get('email'): telecoms.append(ContactPoint(system='email', value=payload.get('email'), use='home', rank=2)) - gender_map = {'f': 'female', 'm': 'male', 'o': 'other', 'u': 'unknown'} - gender = payload.get('gender', 'u').lower() - patient_gender = gender_map.get(gender[0], 'unknown') + if oidc4ida_token_format: + patient_gender = payload.get('gender', 'unknown').lower() + else: + gender_map = {'f': 'female', 'm': 'male', 'o': 'other', 'u': 'unknown'} + gender = payload.get('gender', 'u').lower() + patient_gender = gender_map.get(gender[0], 'unknown') patient_birthdate = payload.get('birthdate') @@ -1217,12 +1252,15 @@ def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: log.warning('id_token did not have a valid iss') raise InvalidRequestError - ial_valid = self._validate_ial_jwt(id_token, PyJWKClient(csp_jwks)) + oidc4token_format = 'verified_claims' in pre_verified_ial.keys() + + ial_valid = self._validate_ial_jwt(id_token, PyJWKClient(csp_jwks), oidc4token_format) if not ial_valid: log.error('_validate_ial_jwt returned None') raise ServerError - id_match_payload = self._parse_ial_into_parameter(ial_valid) + id_match_payload = self._parse_ial_into_parameter(ial_valid, oidc4token_format) + # log.info(id_match_payload) headers = { 'X-CLIENT-ID': app.client_id, diff --git a/requirements/requirements.dev.txt b/requirements/requirements.dev.txt index dc364b1e0..ef2d0e23b 100644 --- a/requirements/requirements.dev.txt +++ b/requirements/requirements.dev.txt @@ -1056,9 +1056,9 @@ oauthlib==3.2.2 \ # -r /code/requirements/requirements.in # django-oauth-toolkit # requests-oauthlib -opentelemetry-api==1.43.0 \ - --hash=sha256:107d0d03857ea8fc7c5fcbbbd83f800c281f0d560553d61c1d675fccfd1761c1 \ - --hash=sha256:20acf45e9b21851926835292e4045d290acade1edd2ff3de86d2f069687ba1fd +opentelemetry-api==1.44.0 \ + --hash=sha256:67647e5e9566edcf421166fdf022b3537f818635daa852b289e34604dc6fb33a \ + --hash=sha256:94b98c893a91b88657eaac1e3ba89618cdb85be6918196705354f34728b2cdef # via ddtrace outcome==1.3.0.post0 \ --hash=sha256:9dcf02e65f2971b80047b377468e72a268e15c0af3cf1238e6ff14f7f91143b8 \ diff --git a/requirements/requirements.txt b/requirements/requirements.txt index b63368962..4f7b2ff55 100644 --- a/requirements/requirements.txt +++ b/requirements/requirements.txt @@ -464,9 +464,9 @@ oauthlib==3.2.2 \ # -r /code/requirements/requirements.in # django-oauth-toolkit # requests-oauthlib -opentelemetry-api==1.43.0 \ - --hash=sha256:107d0d03857ea8fc7c5fcbbbd83f800c281f0d560553d61c1d675fccfd1761c1 \ - --hash=sha256:20acf45e9b21851926835292e4045d290acade1edd2ff3de86d2f069687ba1fd +opentelemetry-api==1.44.0 \ + --hash=sha256:67647e5e9566edcf421166fdf022b3537f818635daa852b289e34604dc6fb33a \ + --hash=sha256:94b98c893a91b88657eaac1e3ba89618cdb85be6918196705354f34728b2cdef # via ddtrace packaging==26.0 \ --hash=sha256:00243ae351a257117b6a241061796684b084ed1c516a08c48a3f7e147a9d80b4 \ From c3e30c327d5f061a702b8b2a01293868b4a421ab Mon Sep 17 00:00:00 2001 From: James Demery Date: Tue, 28 Jul 2026 11:06:07 -0400 Subject: [PATCH 2/4] Add unit test --- .../dot_ext/tests/test_authorization_token.py | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) diff --git a/apps/dot_ext/tests/test_authorization_token.py b/apps/dot_ext/tests/test_authorization_token.py index 70707c075..1fd876449 100644 --- a/apps/dot_ext/tests/test_authorization_token.py +++ b/apps/dot_ext/tests/test_authorization_token.py @@ -1,6 +1,7 @@ import datetime import json import os +import uuid from base64 import b64encode from datetime import timezone from http import HTTPStatus @@ -603,6 +604,154 @@ def test_client_credentials_token_and_refresh( assert '"req_grant_type": "client_credentials"' in request_logs.output[0] assert '"req_app_name": "CC App"' in request_logs.output[0] + @patch.dict(os.environ, {'TARGET_ENV': 'local'}) + @patch('apps.dot_ext.views.authorization.get_and_update_from_refresh') + @patch('apps.dot_ext.views.authorization.TokenView._validate_authorization_jwt') + @patch('apps.dot_ext.views.authorization.TokenView._validate_ial_jwt') + @patch('apps.dot_ext.views.authorization.TokenView._create_or_retrieve_user') + @patch('apps.dot_ext.views.authorization.get_patient_match_response_json') + @override_switch('v3_endpoints', active=True) + @override_switch('enable_auditevents', active=True) + def test_client_credentials_token_and_refresh_with_oidc4da_token_format( + self, mock_get_patient, mock_create_user, mock_validate_ial, mock_validate_auth, mock_get_and_update + ): + """Verify that a client_credentials token response includes "patient" and "refresh_token", and that the refresh_token can be used to refresh the access token.""" + + # Mocking the matched user + mock_create_user.return_value = self.user + + mock_get_and_update.return_value = None + + # Create fake JWT for first validation step + internal_id_token = jwt.encode( + { + 'iss': IDME_LOWER_ISS, + 'sub': '123', + 'aud': 'https://fake.bluebutton.cms.gov', + 'jti': 'jti-1', + 'exp': 9999999999, + 'iat': 1775317326, + }, + 'secret', + algorithm='HS256', + ) + mock_validate_auth.return_value = internal_id_token + + # min necessary fields (apart from address.) + mock_validate_ial.return_value = { + 'iss': IDME_LOWER_ISS, + 'sub': '123', + 'aud': ['urn:oid:12345'], + 'jti': 'jti-2', + 'exp': 9999999999, + 'iat': 1775317326, + 'uuid': uuid.uuid4, + 'auth_time': 9999999999, + 'at_hash': '12345689', + 'verified_claims': { + 'verification': {'trust_framework': 'nist_800_63a', 'assurance_level': 'ial2'}, + 'family_name': 'Smith', + 'given_name': 'John', + 'name_historical': { + 'family_name': 'Smith', + 'given_name': 'John', + }, + 'birthdate': '1970-01-01', + 'gender': 'Male', + 'phone_number': '15124592223', + 'phone_number_historical': ['15124592223', '15124592224'], + 'ssn_itin': 123456789, + 'ssn_itin_last_4': '6789', + }, + 'address': { + 'formatted': '123 Any Rd., Indianapolis, IN, 46250', + 'street_address': '123 Any Rd.', + 'locality': 'Indianapolis', + 'region': 'IN', + 'postal_code': '46250', + 'country': 'USA', + }, + } + + # Mock patient match result + # is_patient_match_found expects at least 2 entries in successful match + mock_get_patient.return_value = { + 'type': 'searchset', + 'entry': [ + {'resource': {'id': 'org-example', 'resourceType': 'Organization'}}, + { + 'resource': { + 'resourceType': 'Patient', + 'id': self.patient_fhir_v3, + 'identifier': [ + { + 'system': CC_SYSTEM_MEDICARE_NUMBER, + 'value': self.test_mbi, + } + ], + } + }, + ], + } + + assertion = jwt.encode({'iss': self.application.client_id}, 'secret', algorithm='HS256') + + token_request_data = { + 'grant_type': CLIENT_CREDENTIALS, + 'client_assertion_type': CLIENT_ASSERTION_TYPE_VALUE, + 'client_assertion': assertion, + 'scope': 'patient/ExplanationOfBenefit.rs openid', + } + + response = self.client.post( + f'/v{Versions.V3}/o/token/', + data=urlencode(token_request_data), + content_type='application/x-www-form-urlencoded', + ) + + self.assertEqual(response.status_code, HTTPStatus.OK, response.content) + data = response.json() + + self.assertIn('patient', data) + self.assertEqual(data['patient'], self.patient_fhir_v3) + self.assertIn('access_token', data) + # see authorization.py -> we can revisit this, but UserInfo will not return anything in the client_credentials flow. + self.assertNotIn('openid', data['scope']) + # other scopes ought to be fine, however. + self.assertIn('patient/ExplanationOfBenefit.rs', data['scope']) + self.assertIn('refresh_token', data) + + # BB2-4965: Even though patient/AuditEvent.rs was not in the requested scopes, it was automatically added + # to the token scope as all client_credentials auth flows should result in a token with patient/AuditEvent.rs + # on it + access_token = get_access_token_model().objects.get(token=data['access_token']) + assert AUDIT_EVENT_SCOPE in access_token.scope + + refresh_request_data = { + 'grant_type': REFRESH_TOKEN, + 'refresh_token': data['refresh_token'], + 'client_id': TEST_APP_CLIENT_ID, + 'client_secret': TEST_APP_CLIENT_SECRET, + } + + response = self.client.post( + f'/v{Versions.V3}/o/token/', + data=urlencode(refresh_request_data), + content_type='application/x-www-form-urlencoded', + ) + + self.assertEqual(response.status_code, HTTPStatus.OK, response.content) + data = response.json() + + self.assertIn('patient', data) + self.assertEqual(data['patient'], self.patient_fhir_v3) + self.assertIn('access_token', data) + # see authorization.py -> we can revisit this, but UserInfo will not return anything in the client_credentials flow. + self.assertNotIn('openid', data['scope']) + # other scopes ought to be fine, however. + self.assertIn('patient/ExplanationOfBenefit.rs', data['scope']) + self.assertIn('refresh_token', data) + class TestTokenPrivateMethods(BaseApiTest): def setUp(self): From 77b1f1542a4dfd4cd050b45caf47f5a81748508f Mon Sep 17 00:00:00 2001 From: James Demery Date: Fri, 7 Aug 2026 15:13:07 -0400 Subject: [PATCH 3/4] Fix issue with rebase --- apps/dot_ext/tests/test_authorization_token.py | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/dot_ext/tests/test_authorization_token.py b/apps/dot_ext/tests/test_authorization_token.py index 5916d2992..1fba2a78b 100644 --- a/apps/dot_ext/tests/test_authorization_token.py +++ b/apps/dot_ext/tests/test_authorization_token.py @@ -753,6 +753,7 @@ def test_client_credentials_token_and_refresh_with_oidc4da_token_format( self.assertIn('patient/ExplanationOfBenefit.rs', data['scope']) self.assertIn('refresh_token', data) + @patch.dict(os.environ, {'TARGET_ENV': 'local'}) @patch('apps.dot_ext.views.authorization.TokenView._validate_authorization_jwt') @patch('apps.dot_ext.views.authorization.TokenView._validate_ial_jwt') @patch('apps.dot_ext.views.authorization.get_patient_match_response_json') From 71c5946adc53e97d5f0b47daebe5cfc63ec89f86 Mon Sep 17 00:00:00 2001 From: James Demery Date: Thu, 13 Aug 2026 11:26:59 -0400 Subject: [PATCH 4/4] Modify unit test --- .../dot_ext/tests/test_authorization_token.py | 282 +++++++++--------- 1 file changed, 134 insertions(+), 148 deletions(-) diff --git a/apps/dot_ext/tests/test_authorization_token.py b/apps/dot_ext/tests/test_authorization_token.py index 1fba2a78b..5c64d2c4f 100644 --- a/apps/dot_ext/tests/test_authorization_token.py +++ b/apps/dot_ext/tests/test_authorization_token.py @@ -31,6 +31,7 @@ from apps.dot_ext.constants import ( APPLICATION_DOES_NOT_HAVE_CLIENT_CREDENTIALS_ENABLED, APPLICATION_HAS_CLIENT_CREDENTIALS_ENABLED_NON_CLIENT_CREDENTIALS_AUTH_CALL_MADE, + AUTH_CODE_AND_CLIENT_CREDENTIALS_TYPE, AUTH_CODE_TYPE, CC_SYSTEM_MEDICARE_NUMBER, CLEAR_HIGHER_ISS, @@ -605,154 +606,6 @@ def test_client_credentials_token_and_refresh( assert '"req_grant_type": "client_credentials"' in request_logs.output[0] assert '"req_app_name": "CC App"' in request_logs.output[0] - @patch.dict(os.environ, {'TARGET_ENV': 'local'}) - @patch('apps.dot_ext.views.authorization.get_and_update_from_refresh') - @patch('apps.dot_ext.views.authorization.TokenView._validate_authorization_jwt') - @patch('apps.dot_ext.views.authorization.TokenView._validate_ial_jwt') - @patch('apps.dot_ext.views.authorization.TokenView._create_or_retrieve_user') - @patch('apps.dot_ext.views.authorization.get_patient_match_response_json') - @override_switch('v3_endpoints', active=True) - @override_switch('enable_auditevents', active=True) - def test_client_credentials_token_and_refresh_with_oidc4da_token_format( - self, mock_get_patient, mock_create_user, mock_validate_ial, mock_validate_auth, mock_get_and_update - ): - """Verify that a client_credentials token response includes "patient" and "refresh_token", and that the refresh_token can be used to refresh the access token.""" - - # Mocking the matched user - mock_create_user.return_value = self.user - - mock_get_and_update.return_value = None - - # Create fake JWT for first validation step - internal_id_token = jwt.encode( - { - 'iss': IDME_LOWER_ISS, - 'sub': '123', - 'aud': 'https://fake.bluebutton.cms.gov', - 'jti': 'jti-1', - 'exp': 9999999999, - 'iat': 1775317326, - }, - 'secret', - algorithm='HS256', - ) - mock_validate_auth.return_value = internal_id_token - - # min necessary fields (apart from address.) - mock_validate_ial.return_value = { - 'iss': IDME_LOWER_ISS, - 'sub': '123', - 'aud': ['urn:oid:12345'], - 'jti': 'jti-2', - 'exp': 9999999999, - 'iat': 1775317326, - 'uuid': uuid.uuid4, - 'auth_time': 9999999999, - 'at_hash': '12345689', - 'verified_claims': { - 'verification': {'trust_framework': 'nist_800_63a', 'assurance_level': 'ial2'}, - 'family_name': 'Smith', - 'given_name': 'John', - 'name_historical': { - 'family_name': 'Smith', - 'given_name': 'John', - }, - 'birthdate': '1970-01-01', - 'gender': 'Male', - 'phone_number': '15124592223', - 'phone_number_historical': ['15124592223', '15124592224'], - 'ssn_itin': 123456789, - 'ssn_itin_last_4': '6789', - }, - 'address': { - 'formatted': '123 Any Rd., Indianapolis, IN, 46250', - 'street_address': '123 Any Rd.', - 'locality': 'Indianapolis', - 'region': 'IN', - 'postal_code': '46250', - 'country': 'USA', - }, - } - - # Mock patient match result - # is_patient_match_found expects at least 2 entries in successful match - mock_get_patient.return_value = { - 'type': 'searchset', - 'entry': [ - {'resource': {'id': 'org-example', 'resourceType': 'Organization'}}, - { - 'resource': { - 'resourceType': 'Patient', - 'id': self.patient_fhir_v3, - 'identifier': [ - { - 'system': CC_SYSTEM_MEDICARE_NUMBER, - 'value': self.test_mbi, - } - ], - } - }, - ], - } - - assertion = jwt.encode({'iss': self.application.client_id}, 'secret', algorithm='HS256') - - token_request_data = { - 'grant_type': CLIENT_CREDENTIALS, - 'client_assertion_type': CLIENT_ASSERTION_TYPE_VALUE, - 'client_assertion': assertion, - 'scope': 'patient/ExplanationOfBenefit.rs openid', - } - - response = self.client.post( - f'/v{Versions.V3}/o/token/', - data=urlencode(token_request_data), - content_type='application/x-www-form-urlencoded', - ) - - self.assertEqual(response.status_code, HTTPStatus.OK, response.content) - data = response.json() - - self.assertIn('patient', data) - self.assertEqual(data['patient'], self.patient_fhir_v3) - self.assertIn('access_token', data) - # see authorization.py -> we can revisit this, but UserInfo will not return anything in the client_credentials flow. - self.assertNotIn('openid', data['scope']) - # other scopes ought to be fine, however. - self.assertIn('patient/ExplanationOfBenefit.rs', data['scope']) - self.assertIn('refresh_token', data) - - # BB2-4965: Even though patient/AuditEvent.rs was not in the requested scopes, it was automatically added - # to the token scope as all client_credentials auth flows should result in a token with patient/AuditEvent.rs - # on it - access_token = get_access_token_model().objects.get(token=data['access_token']) - assert AUDIT_EVENT_SCOPE in access_token.scope - - refresh_request_data = { - 'grant_type': REFRESH_TOKEN, - 'refresh_token': data['refresh_token'], - 'client_id': TEST_APP_CLIENT_ID, - 'client_secret': TEST_APP_CLIENT_SECRET, - } - - response = self.client.post( - f'/v{Versions.V3}/o/token/', - data=urlencode(refresh_request_data), - content_type='application/x-www-form-urlencoded', - ) - - self.assertEqual(response.status_code, HTTPStatus.OK, response.content) - data = response.json() - - self.assertIn('patient', data) - self.assertEqual(data['patient'], self.patient_fhir_v3) - self.assertIn('access_token', data) - # see authorization.py -> we can revisit this, but UserInfo will not return anything in the client_credentials flow. - self.assertNotIn('openid', data['scope']) - # other scopes ought to be fine, however. - self.assertIn('patient/ExplanationOfBenefit.rs', data['scope']) - self.assertIn('refresh_token', data) - @patch.dict(os.environ, {'TARGET_ENV': 'local'}) @patch('apps.dot_ext.views.authorization.TokenView._validate_authorization_jwt') @patch('apps.dot_ext.views.authorization.TokenView._validate_ial_jwt') @@ -1040,3 +893,136 @@ def test_client_credentials_returns_patient_match_not_found_401_integration( ) assert response.status_code == HTTPStatus.UNAUTHORIZED assert response.json()['message'] == PATIENT_DATA_CANNOT_BE_FOUND + + +@patch.dict(os.environ, {'TARGET_ENV': 'local'}) +@patch('apps.dot_ext.views.authorization.get_and_update_from_refresh') +@patch('apps.dot_ext.views.authorization.TokenView._validate_authorization_jwt') +@patch('apps.dot_ext.views.authorization.TokenView._validate_ial_jwt') +@patch('apps.dot_ext.views.authorization.TokenView._create_or_retrieve_user') +@patch('apps.dot_ext.views.authorization.get_patient_match_response_json') +@override_switch('v3_endpoints', active=True) +@override_switch('enable_auditevents', active=True) +def test_client_credentials_token_and_refresh_with_oidc4da_token_format( + mock_get_patient, + mock_create_user, + mock_validate_ial, + mock_validate_auth, + mock_get_and_update, + basic_user, + create_application, + create_capability, +): + """Verify that an ID token with the OIDC4IDA token format can successfully make it through a CAN request with the + client_credentials_validation switch inactive""" + + # Mocking the matched user + # self.patient_fhir_v3 = 'patient-123-v3' + # self.user = self._create_user('patient_user', 'password123', fhir_id_v3=self.patient_fhir_v3) + user = basic_user(username='patient_user', fhir_id_v3='patient-123-v3') + mock_create_user.return_value = user + + eob_capability = create_capability(name=EOB_SCOPE, urls=[['GET', '/v[123]/fhir/ExplanationOfBenefit[/]?$']]) + application = create_application( + name='Test App', + jwks_uri='http://localhost:8000/.well-known/jwks.json', + capability=eob_capability, + allowed_auth_type=AUTH_CODE_AND_CLIENT_CREDENTIALS_TYPE, + ) + + mock_get_and_update.return_value = None + + # Create fake JWT for first validation step + internal_id_token = jwt.encode( + { + 'iss': IDME_LOWER_ISS, + 'sub': '123', + 'aud': 'https://fake.bluebutton.cms.gov', + 'jti': 'jti-1', + 'exp': 9999999999, + 'iat': 1775317326, + }, + 'secret', + algorithm='HS256', + ) + mock_validate_auth.return_value = internal_id_token + + # min necessary fields (apart from address.) + mock_validate_ial.return_value = { + 'iss': IDME_LOWER_ISS, + 'sub': '123', + 'aud': ['urn:oid:12345'], + 'jti': 'jti-2', + 'exp': 9999999999, + 'iat': 1775317326, + 'uuid': uuid.uuid4, + 'auth_time': 9999999999, + 'at_hash': '12345689', + 'verified_claims': { + 'verification': {'trust_framework': 'nist_800_63a', 'assurance_level': 'ial2'}, + 'family_name': 'Smith', + 'given_name': 'John', + 'name_historical': { + 'family_name': 'Smith', + 'given_name': 'John', + }, + 'birthdate': '1970-01-01', + 'gender': 'Male', + 'phone_number': '15124592223', + 'phone_number_historical': ['15124592223', '15124592224'], + 'ssn_itin': 123456789, + 'ssn_itin_last_4': '6789', + }, + 'address': { + 'formatted': '123 Any Rd., Indianapolis, IN, 46250', + 'street_address': '123 Any Rd.', + 'locality': 'Indianapolis', + 'region': 'IN', + 'postal_code': '46250', + 'country': 'USA', + }, + } + + # Mock patient match result + # is_patient_match_found expects at least 2 entries in successful match + mock_get_patient.return_value = { + 'type': 'searchset', + 'entry': [ + {'resource': {'id': 'org-example', 'resourceType': 'Organization'}}, + { + 'resource': { + 'resourceType': 'Patient', + 'id': 'patient-123-v3', + 'identifier': [ + { + 'system': CC_SYSTEM_MEDICARE_NUMBER, + 'value': '1SA0A00AA00', + } + ], + } + }, + ], + } + + assertion = jwt.encode({'iss': application.client_id}, 'secret', algorithm='HS256') + + token_request_data = { + 'grant_type': CLIENT_CREDENTIALS, + 'client_assertion_type': CLIENT_ASSERTION_TYPE_VALUE, + 'client_assertion': assertion, + 'scope': 'patient/ExplanationOfBenefit.rs openid', + } + + response = Client().post( + f'/v{Versions.V3}/o/token/', + data=urlencode(token_request_data), + content_type='application/x-www-form-urlencoded', + ) + + assert response.status_code == HTTPStatus.OK + data = response.json() + + assert 'patient' in data + assert data['patient'] == 'patient-123-v3' + assert 'access_token' in data + assert 'refresh_token' in data