Skip to content

Commit 5f089f5

Browse files
committed
Adding negative test cases in the unit test
1 parent dc359de commit 5f089f5

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

bmh_admin_portal_backend/tests/test_lambda_authorizer.py

+41
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
import io
33
import json
44
import jwt
5+
import time
6+
from jwt.exceptions import InvalidAudienceError, ExpiredSignatureError
57
from unittest.mock import patch
68
from lambdas.lambda_authorizer import lambda_authorizer
79
from cryptography.hazmat.primitives.asymmetric import rsa
@@ -53,3 +55,42 @@ def test_validate_token():
5355
payload = lambda_authorizer.validate_token(mock_jwt_token)
5456

5557
assert payload == mock_payload
58+
59+
# Verifying for invalid audience error
60+
mock_payload = {"name": "Test name", "aud": "Random test audience"}
61+
62+
# Encode the payload using the private key generated above while sharing the public key info as a header
63+
mock_jwt_token = jwt.encode(
64+
payload=mock_payload,
65+
algorithm="RS256",
66+
key=private_key_pem,
67+
headers={"kid": public_key_jwk["kid"]},
68+
)
69+
mock_keys_from_well_known_jwks = io.BytesIO(json.dumps({"keys": keys}).encode())
70+
71+
with patch.object(
72+
lambda_authorizer, "urlopen", return_value=mock_keys_from_well_known_jwks
73+
):
74+
with pytest.raises(InvalidAudienceError):
75+
payload = lambda_authorizer.validate_token(mock_jwt_token)
76+
77+
# Verifying for a payload with a expiration less than the current time
78+
mock_payload = {
79+
"name": "Test name",
80+
"aud": "Valid test audience",
81+
"exp": int(time.time()) - 1,
82+
}
83+
# Encode the payload using the private key generated above while sharing the public key info as a header
84+
mock_jwt_token = jwt.encode(
85+
payload=mock_payload,
86+
algorithm="RS256",
87+
key=private_key_pem,
88+
headers={"kid": public_key_jwk["kid"]},
89+
)
90+
mock_keys_from_well_known_jwks = io.BytesIO(json.dumps({"keys": keys}).encode())
91+
92+
with patch.object(
93+
lambda_authorizer, "urlopen", return_value=mock_keys_from_well_known_jwks
94+
):
95+
with pytest.raises(ExpiredSignatureError):
96+
payload = lambda_authorizer.validate_token(mock_jwt_token)

0 commit comments

Comments
 (0)