| 1 |
import json |
| 2 |
from json.decoder import JSONDecodeError |
| 3 |
from typing import Union |
| 4 |
|
| 5 |
from .base64url_to_bytes import base64url_to_bytes |
| 6 |
from .byteslike_to_bytes import byteslike_to_bytes |
| 7 |
from .exceptions import InvalidJSONStructure |
| 8 |
from .structs import CollectedClientData, TokenBinding |
| 9 |
|
| 10 |
|
| 11 |
def parse_client_data_json(val: bytes) -> CollectedClientData: |
| 12 |
""" |
| 13 |
Break apart `response.clientDataJSON` buffer into structured data |
| 14 |
""" |
| 15 |
val = byteslike_to_bytes(val) |
| 16 |
|
| 17 |
try: |
| 18 |
json_dict = json.loads(val) |
| 19 |
except JSONDecodeError: |
| 20 |
raise InvalidJSONStructure("Unable to decode client_data_json bytes as JSON") |
| 21 |
|
| 22 |
# Ensure required values are present in client data |
| 23 |
if "type" not in json_dict: |
| 24 |
raise InvalidJSONStructure('client_data_json missing required property "type"') |
| 25 |
if "challenge" not in json_dict: |
| 26 |
raise InvalidJSONStructure('client_data_json missing required property "challenge"') |
| 27 |
if "origin" not in json_dict: |
| 28 |
raise InvalidJSONStructure('client_data_json missing required property "origin"') |
| 29 |
|
| 30 |
client_data = CollectedClientData( |
| 31 |
type=json_dict["type"], |
| 32 |
challenge=base64url_to_bytes(json_dict["challenge"]), |
| 33 |
origin=json_dict["origin"], |
| 34 |
) |
| 35 |
|
| 36 |
# Populate optional values if set |
| 37 |
if "crossOrigin" in json_dict: |
| 38 |
cross_origin = bool(json_dict["crossOrigin"]) |
| 39 |
client_data.cross_origin = cross_origin |
| 40 |
|
| 41 |
if "tokenBinding" in json_dict: |
| 42 |
token_binding_dict = json_dict["tokenBinding"] |
| 43 |
|
| 44 |
# Some U2F devices set a string to `token_binding`, in which case ignore it |
| 45 |
if type(token_binding_dict) is dict: |
| 46 |
if "status" not in token_binding_dict: |
| 47 |
raise InvalidJSONStructure('token_binding missing required property "status"') |
| 48 |
|
| 49 |
status = token_binding_dict["status"] |
| 50 |
try: |
| 51 |
# This will raise ValidationError on an unexpected status |
| 52 |
token_binding = TokenBinding(status=status) |
| 53 |
|
| 54 |
# Handle optional values |
| 55 |
if "id" in token_binding_dict: |
| 56 |
id = token_binding_dict["id"] |
| 57 |
token_binding.id = f"{id}" |
| 58 |
|
| 59 |
client_data.token_binding = token_binding |
| 60 |
except Exception: |
| 61 |
# If we encounter a status we don't expect then ignore token_binding |
| 62 |
# completely |
| 63 |
pass |
| 64 |
|
| 65 |
return client_data |