Coverage for eligibility_api/server.py: 0%
29 statements
« prev ^ index » next coverage.py v7.6.8, created at 2024-11-26 22:46 +0000
« prev ^ index » next coverage.py v7.6.8, created at 2024-11-26 22:46 +0000
1import datetime
2import json
3import logging
5from jwcrypto import jwe, jws, jwt
7from .tokens import _create_jwk
9logger = logging.getLogger(__name__)
12def get_token_payload(
13 token: str,
14 jwe_encryption_alg: str,
15 jwe_cek_enc: str,
16 server_private_key,
17 jws_signing_alg: str,
18 client_public_key,
19) -> dict:
20 """Decode a token (JWE(JWS))."""
21 try:
22 # decrypt
23 decrypted_token = jwe.JWE(algs=[jwe_encryption_alg, jwe_cek_enc])
24 decrypted_token.deserialize(token, key=_create_jwk(server_private_key))
25 decrypted_payload = str(decrypted_token.payload, "utf-8")
26 # verify signature
27 signed_token = jws.JWS()
28 signed_token.deserialize(decrypted_payload, key=_create_jwk(client_public_key), alg=jws_signing_alg)
29 # return final payload
30 payload = str(signed_token.payload, "utf-8")
31 return json.loads(payload)
32 except Exception:
33 return False
36def create_response_payload(token_payload: dict, issuer: str) -> dict:
37 """Crafts a response payload. Does not include the eligibility or error fields."""
38 # craft the response payload using parsed request token
39 resp_payload = dict(
40 jti=token_payload["jti"],
41 iss=issuer,
42 iat=int(datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).timestamp()),
43 )
45 return resp_payload
48def make_token(
49 payload: dict,
50 jws_signing_alg: str,
51 server_private_key,
52 jwe_encryption_alg: str,
53 jwe_cek_enc: str,
54 client_public_key,
55) -> str:
56 """Wrap payload in a signed and encrypted JWT for response."""
57 # sign the payload with server's private key
58 header = {"typ": "JWS", "alg": jws_signing_alg}
59 signed_token = jwt.JWT(header=header, claims=payload)
60 signed_token.make_signed_token(_create_jwk(server_private_key))
61 signed_payload = signed_token.serialize()
62 # encrypt the signed payload with client's public key
63 header = {
64 "typ": "JWE",
65 "alg": jwe_encryption_alg,
66 "enc": jwe_cek_enc,
67 }
68 encrypted_token = jwt.JWT(header=header, claims=signed_payload)
69 encrypted_token.make_encrypted_token(_create_jwk(client_public_key))
70 return encrypted_token.serialize()