Colin-b / httpx_auth

Authentication classes to be used with httpx

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JSONDecodeError due to Improper Handling of Nested JSON Strings in JWT Payloads

pythrick opened this issue · comments

Description

There is an issue in the httpx-auth library where the decoding of base64-encoded JSON within JWT tokens corrupts JSON strings that contain nested JSON. This happens because the double quotes inside the nested JSON string are not correctly handled during the decoding process, leading to a failure when attempting to load the string back into a JSON object.

Steps to Reproduce

The issue can be reproduced with the following test case:

import jwt
import json
from httpx_auth._oauth2.tokens import decode_base64

def test_decode_base64_with_nested_json_string():
    # Encode a JSON inside the JWT
    dummy_token = jwt.encode({"data": json.dumps({"something": ["else"]})}, key="")
    header, body, signature = dummy_token.split(".")
    
    # Decode the body
    decoded_bytes = decode_base64(body)
    
    # Attempt to load JSON
    result = json.loads(decoded_bytes)
    assert result == {"data": '{"something": ["else"]}'}

Running this test results in a json.decoder.JSONDecodeError due to incorrect handling of the nested JSON string.

Expected Behavior

The decoded JSON string should be handled correctly, allowing for proper loading into a Python dictionary without JSON parsing errors.

Actual Behavior

The test raises the following error due to malformed JSON:

json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 12 (char 11)

This error is caused by the way double quotes inside the nested JSON are handled, which corrupts the JSON string during the base64 decoding step.

Environment

Python Version: 3.10.11
httpx-auth version: 0.22.0 (2024-03-02)

Additional Context

This issue impacts scenarios where JWT tokens contain nested JSON strings as part of their payload. A fix would likely involve adjusting the base64 decoding function to correctly handle nested JSON strings without corrupting them.