44import jwt
55import pytest
66from flask import g , request
7+ from jwt .exceptions import InvalidIssuerError , MissingRequiredClaimError
78from notifications_python_client .authentication import create_jwt_token
89
910from app import db
@@ -231,10 +232,9 @@ def test_decode_jwt_token_returns_error_with_no_secrets(client):
231232 assert exc .value .short_message == "Invalid token: API key not found"
232233
233234
234- @pytest .mark .parametrize ("service_id" , ["not-a-valid-id" , 1234 ])
235- def test_requires_auth_should_not_allow_service_id_with_the_wrong_data_type (client , service_jwt_secret , service_id ):
235+ def test_requires_auth_should_not_allow_service_id_which_is_not_uuid_string (client , service_jwt_secret ):
236236 token = create_jwt_token (
237- client_id = service_id ,
237+ client_id = "not-a-valid-id" ,
238238 secret = service_jwt_secret ,
239239 )
240240
@@ -244,6 +244,30 @@ def test_requires_auth_should_not_allow_service_id_with_the_wrong_data_type(clie
244244 assert exc .value .short_message == "Invalid token: service id is not the right data type"
245245
246246
247+ @pytest .mark .parametrize (
248+ "exception" ,
249+ (
250+ # Possible exceptions which could be raised here:
251+ # https://github.com/jpadilla/pyjwt/blob/b85050f1d444c6828bb4618ee764443b0a3f5d18/jwt/api_jwt.py#L560-L583
252+ MissingRequiredClaimError ,
253+ InvalidIssuerError ,
254+ ),
255+ )
256+ def test_requires_auth_should_not_allow_non_string_service_id (client , sample_api_key , exception , mocker ):
257+ mocker .patch ("notifications_python_client.authentication.decode_token" , raises = exception )
258+ token = create_jwt_token (
259+ secret = str (sample_api_key .id ),
260+ client_id = str (sample_api_key .service_id ), # Our code never see this value
261+ )
262+
263+ request .headers = {"Authorization" : f"Bearer { token } " }
264+ with pytest .raises (AuthError ) as exc :
265+ requires_auth ()
266+
267+ # This is not a very helpful error message but the user would be having to try something weird to get here
268+ assert exc .value .short_message == "Invalid token: iss field not provided"
269+
270+
247271def test_requires_auth_returns_error_when_service_doesnt_exist (client , sample_api_key ):
248272 # get service ID and secret the wrong way around
249273 token = create_jwt_token (
0 commit comments