Skip to content

chore(deps): update dependency pyjwt to v2.13.0 [security]#181

Merged
renovate[bot] merged 1 commit into
mainfrom
renovate/pypi-pyjwt-vulnerability
Jun 16, 2026
Merged

chore(deps): update dependency pyjwt to v2.13.0 [security]#181
renovate[bot] merged 1 commit into
mainfrom
renovate/pypi-pyjwt-vulnerability

Conversation

@renovate

@renovate renovate Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

This PR contains the following updates:

Package Change Age Confidence
PyJWT 2.12.12.13.0 age confidence

Warning

Some dependencies could not be looked up. Check the Dependency Dashboard for more information.


PyJWKClient unbounded JWKS endpoint requests via attacker-controlled kid values (DoS)

CVE-2026-48524 / GHSA-fhv5-28vv-h8m8

More information

Details

[!NOTE]
The vulnerability surfaces only when a JWKS fetch fails; an attacker can attempt to provoke that with sustained unknown-kid traffic, but the outcome depends on upstream JWKS-endpoint behavior (rate limiting, transient errors) which is beyond the attacker's control. Impact is reduced auth availability until the next successful fetch, not complete denial of service.

Summary

PyJWKClient.get_signing_key() forces a fresh HTTP request to the JWKS endpoint for every JWT with an unknown kid value, with no rate limiting. Since kid comes from the unverified token header, an attacker can trigger unlimited outbound requests.

Additionally, fetch_data() finally block clears the JWKS cache on network error.

Root Cause

jwt/jwks_client.py:172-198 - get_signing_key(kid) calls get_signing_keys(refresh=True) for unknown kids, bypassing TTL cache with no cooldown.
jwt/jwks_client.py:120-122 - finally block writes None to cache on error, clearing valid data.

Impact
  • DoS against JWKS endpoint (unlimited requests per invalid token)
  • DoS against application (network I/O latency)
  • Cascading failure (rate limiting clears cache, breaking legitimate auth)
Suggested Fix
  1. Add refresh cooldown (refuse refresh more than once per TTL period)
  2. Move cache write from finally to else block
Affected Versions

All versions with PyJWKClient (2.4.0 through 2.12.1)

Severity

  • CVSS Score: 3.7 / 10 (Low)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:L

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


PyJWT: Algorithm allow-list bypass when decoding with PyJWK / PyJWKClient keys

CVE-2026-48523 / GHSA-jq35-7prp-9v3f

More information

Details

[!NOTE]
Scored assuming a deployment where algorithm policy functions as an authentication/authorization boundary. In deployments where the algorithm policy enforces crypto agility only, the practical confidentiality impact is lower and the issue is closer to an integrity-of-policy-enforcement bug.

PyJWT 2.9.0 through 2.12.1 allows a verifier-side algorithm allow-list bypass when jwt.decode() or jwt.decode_complete() are called with a PyJWK key. The token header alg is checked against the caller-supplied algorithms allow-list, but signature verification is performed with the algorithm bound to the PyJWK object instead of the header algorithm. An attacker who controls a registered JWK/JWKS private key can sign with a disallowed algorithm, advertise an allowed algorithm in the JWT header, and still be accepted. The issue affects the documented PyJWKClient.get_signing_key_from_jwt(...) flow.

Summary

PyJWT's PyJWK verification path allows a verifier-side algorithm allow-list bypass.

In affected versions, when a JWT is decoded with a PyJWK object, PyJWT verifies that the header alg string is present in the caller's algorithms=[...] list, but it does not actually use the header algorithm to verify the signature. Instead, it verifies with the algorithm already bound to the PyJWK object.

This lets an attacker who controls a registered JWK/JWKS private key sign with a disallowed algorithm and have the token accepted as long as the JWT header advertises an allowed algorithm. This affects the documented PyJWKClient usage flow and does not require any non-default flags or unsafe configuration.

Details

In jwt/api_jws.py in 2.12.1, _verify_signature() treats PyJWK keys differently from normal PEM/public-key inputs:

if algorithms is None and isinstance(key, PyJWK):
    algorithms = [key.algorithm_name]

...

if not alg or (algorithms is not None and alg not in algorithms):
    raise InvalidAlgorithmError("The specified alg value is not allowed")

if isinstance(key, PyJWK):
    alg_obj = key.Algorithm
    prepared_key = key.key
else:
    alg_obj = self.get_algorithm_by_name(alg)
    prepared_key = alg_obj.prepare_key(key)

This logic means:

  1. The JWT header alg is checked only as a string against the caller-supplied allow-list.
  2. If the key is a PyJWK, the actual verifier is not selected from the header algorithm.
  3. Instead, PyJWT always verifies with key.Algorithm, which is fixed when the PyJWK object is created.

PyJWK binds its algorithm in jwt/api_jwk.py from the JWK's alg field or from key-type defaults:

if not algorithm and isinstance(self._jwk_data, dict):
    algorithm = self._jwk_data.get("alg", None)

...

self.algorithm_name = algorithm
self.Algorithm = get_default_algorithms()[algorithm]
self.key = self.Algorithm.from_jwk(self._jwk_data)

So once a PyJWK is constructed, the verifier uses the PyJWK's bound algorithm, not the JWT header algorithm.

The issue is reachable through the documented JWKS flow. In docs/usage.rst, the project documents:

signing_key = jwks_client.get_signing_key_from_jwt(token)
jwt.decode(
    token,
    signing_key,
    audience="https://expenses-api",
    options={"verify_exp": False},
    algorithms=["RS256"],
)

PyJWKClient.get_signing_key_from_jwt() returns a PyJWK, so this documented path is affected.

This is not a "no-key forgery" issue. The attacker still needs control of an accepted JWK/JWKS private key. However, that is realistic in deployments such as:

  • self-service OAuth client assertions
  • multi-tenant key registration
  • federation / BYO-JWKS trust models
  • any system where external parties sign JWTs with their own registered keys

In those cases, the attacker can bypass verifier-side algorithm policy. For example, if the server intends to only accept PS256, an attacker controlling an accepted RSA JWK can sign with RS256, set alg=PS256 in the JWT header, and still be accepted through the PyJWK path.

The same forged token is rejected through the normal PEM/public-key verification path, which shows the bug is specific to PyJWK verification rather than expected JWT behavior.

This behavior was introduced by commit ab8176abe21e550dbc1c9a6bb7e78ad80853bfb1 (Decode with PyJWK (#​886)), which is present in tagged releases 2.9.0, 2.10.0, 2.10.1, 2.11.0, 2.12.0, and 2.12.1.

PoC

Tested locally against PyJWT 2.12.1 on Python 3.12.10 with cryptography 45.0.6.

Install dependencies:

python -m pip install pyjwt==2.12.1 cryptography

Run the following script:

import json
import jwt
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
from jwt.api_jwk import PyJWK
from jwt.algorithms import RSAAlgorithm
from jwt.utils import base64url_encode

##### Generate an RSA keypair controlled by the attacker.
priv = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pub = priv.public_key()
pub_pem = pub.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)

##### Build a PyJWK from the public key.

##### With an RSA JWK and no explicit alg, PyJWK binds to RS256 by default.
jwk = PyJWK.from_json(RSAAlgorithm.to_jwk(pub))

##### Create a token whose protected header claims RS512.
header = {"typ": "JWT", "alg": "RS512"}
payload = {"sub": "alice"}

header_b64 = base64url_encode(
    json.dumps(header, separators=(",", ":"), sort_keys=True).encode()
)
payload_b64 = base64url_encode(
    json.dumps(payload, separators=(",", ":")).encode()
)
signing_input = b".".join([header_b64, payload_b64])

##### Sign the RS512-labelled token with RS256 instead.
sig = RSAAlgorithm(RSAAlgorithm.SHA256).sign(signing_input, priv)
token = b".".join([header_b64, payload_b64, base64url_encode(sig)]).decode()

print("token:", token)
print("PyJWK path:")
print(jwt.decode(token, jwk, algorithms=["RS512"]))

print("PEM path:")
try:
    print(jwt.decode(token, pub_pem, algorithms=["RS512"]))
except Exception as e:
    print(f"{type(e).__name__}: {e}")

Observed output:

PyJWK path:
{'sub': 'alice'}
PEM path:
InvalidSignatureError: Signature verification failed

The token is accepted when the verification key is a PyJWK, even though:

  • the caller restricted allowed algorithms to ["RS512"]
  • the signature was actually generated with RS256

The same token is rejected when verified through the normal PEM/public-key path.

Impact

This is an algorithm allow-list bypass affecting jwt.decode() and jwt.decode_complete() when the verification key is a PyJWK, including keys returned by PyJWKClient.

The impact depends on the deployment model:

  • If attackers cannot control any accepted JWK/JWKS private key, practical exploitability is limited.
  • If attackers can legitimately control a registered key, this is exploitable.

Impacted deployments include:

  • JWT client assertion flows where each client uses its own key
  • multitenant systems where tenants register JWK/JWKS material
  • federation-style trust models
  • any application that relies on algorithms=[...] to enforce a crypto policy against externally controlled signing keys

What an attacker can do:

  • bypass a server-side requirement such as "only PS256" or "only RS512"
  • continue using a deprecated or blocked algorithm after the server thought it had disabled it
  • authenticate successfully as their own client / tenant / federation principal even though they do not satisfy the configured algorithm policy

What this issue does not do by itself:

  • it does not let an attacker forge tokens without access to a valid signing key or signing oracle
  • it does not automatically enable cross-tenant impersonation unless the surrounding application trust model adds another flaw

Severity

  • CVSS Score: 5.4 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


PyJWT: Unauthenticated DoS via unbounded Base64URL decoding of unused payload segment in b64=false detached JWS

CVE-2026-48525 / GHSA-w7vc-732c-9m39

More information

Details

[!NOTE]
Practical impact depends on whether request body-size limits are enforced upstream (proxy/web-server/framework). Deployments with typical body-size caps (≤2 MB) bound the amplifier significantly; deployments accepting larger token inputs are more exposed.

When verifying detached JWS tokens using the unencoded-payload option ("b64": false, RFC 7797), PyJWT performs Base64URL decoding of the compact-serialization payload segment before enforcing the detached-payload rules.

For b64=false, PyJWT later discards that decoded payload and replaces it with the caller-provided detached_payload. In practice, this turns the middle segment into an attacker-controlled “work amplifier”: a remote client can supply an arbitrarily large Base64URL payload segment that forces CPU work + memory allocations even if the signature is invalid.

This creates an unauthenticated DoS vector against any endpoint that verifies detached JWS using PyJWT.


Affected Component(s)
  • jwt/api_jws.py

    • PyJWS.decode() / PyJWS.decode_complete()
    • _load() (parsing and Base64URL decoding)

Root Cause (exact logic flaw)
What happens in the code

In jwt/api_jws.py, decode_complete() does the following (order matters):

  • Calls _load(jwt) first, which decodes the token segments
  • Only after that, checks header.get("b64") and if False, it replaces payload = detached_payload and rebuilds the signing input

This behavior is visible in decode_complete():

  • _load(jwt) happens before the b64=false handling
  • then payload = detached_payload and signing_input = ... detached_payload happens afterward ([GitHub][1])

Inside _load(), PyJWT unconditionally performs:

  • payload = base64url_decode(payload_segment)
    This is the expensive step the attacker can amplify ([GitHub][1])
Why this becomes a vulnerability

For b64=false detached JWS, the payload segment in compact form is effectively not needed for verification in PyJWT’s own logic (since the library uses detached_payload as the real payload). Yet PyJWT still decodes it first, meaning:

  • cost is paid even when signature is invalid
  • the decoded bytes are discarded
  • attacker controls the size of this cost via token length

Impact (evidence-driven)
Security impact
  • Unauthenticated remote DoS: decoding work happens before signature rejection → attacker does not need signing key.
  • CPU amplification: Base64URL decode time scales linearly with payload segment size.
  • Memory amplification: decoded output allocates large byte buffers (tens of MB per request).
  • Operational impact: request queueing / worker starvation under modest concurrency bursts.
Standards context (RFC 7797)

RFC 7797 explicitly notes this option is used when payload is large and/or detached, and discusses interoperability requirements around marking it critical (“crit” with “b64”). ([IETF Datatracker][2])
(PyJWT supports crit validation, but the issue here is decode order / unbounded decode of an unused segment.)


Affected Versions
  • Confirmed affected: PyJWT 2.12.1 (tested from your local editable install and repo).
  • Likely affected: all versions that include detached payload support for JWS decoding, which was introduced in 2.4.0 (“Add detached payload support for JWS encoding and decoding”). ([pyjwt.readthedocs.io][3])

(For GHSA, this phrasing is strong: “confirmed” + “likely since feature introduction”.)


Threat Model
Typical real deployment

A service verifies signed HTTP requests or webhooks using detached JWS:

  • token is provided in JSON body / query / header
  • actual payload is the HTTP request body passed as detached_payload
Attacker
  • remote unauthenticated client
  • can send requests to verify endpoint
  • does not need a valid signature (invalid signature still triggers the expensive decode path)
Attack chain
  1. Attacker crafts a JWS compact token with header containing "b64": false and crit:["b64"].
  2. Attacker inflates the payload segment (middle segment) to millions of Base64URL characters.
  3. Server calls PyJWS.decode(...detached_payload=...).
  4. PyJWT decodes the inflated segment (CPU + memory).
  5. Signature is rejected afterward (401) — but resources already consumed.
  6. Repeated requests or bursts cause queueing/worker starvation → DoS.

Proof of Concept - file names + results
PoC placement

PoC # 1 - Localhost verification server

File: server_localhost.py

Purpose: real HTTP endpoint (POST /verify) that calls PyJWT detached verification and prints:
ok / time_ms / peak_bytes / token_len / error.

Results (server console output)
[+] Listening on http://127.0.0.1:8000
[+] POST /verify  JSON: {"token": "..."}

[127.0.0.1] ok=True  time_ms=0.102 peak_bytes=2624     token_len=117      err=None
[127.0.0.1] ok=False time_ms=2.012 peak_bytes=2000983  token_len=500078   err=InvalidSignatureError
[127.0.0.1] ok=True  time_ms=1.591 peak_bytes=2001061  token_len=500117   err=None

[127.0.0.1] ok=True  time_ms=0.065 peak_bytes=2304     token_len=117      err=None
[127.0.0.1] ok=False time_ms=7.534 peak_bytes=8000983  token_len=2000078  err=InvalidSignatureError
[127.0.0.1] ok=True  time_ms=6.347 peak_bytes=8001061  token_len=2000117  err=None

[127.0.0.1] ok=True  time_ms=0.066 peak_bytes=2304     token_len=117      err=None
[127.0.0.1] ok=False time_ms=23.034 peak_bytes=32000983 token_len=8000078 err=InvalidSignatureError
[127.0.0.1] ok=True  time_ms=22.097 peak_bytes=32001061 token_len=8000117 err=None

Key takeaways from these results

  • At 8,000,000 chars, a single invalid-signature request still causes:

    • ~23 ms server work
    • ~32 MB peak allocations
    • returns 401 (invalid signature) → attacker does not need key.

PoC # 2 - Localhost network client

File: client_localhost.py
Purpose: generates baseline + (invalid signature) + (valid signature) tokens and sends them over HTTP to localhost server.

Results (client output)
payload-chars = 500,000
=== BASELINE (valid b64=false token) ===
HTTP: 200
client_wall_ms: 6.3499...
server_time_ms: 0.10197...
server_peak_bytes: 2624

=== ATTACK (INVALID signature - attacker needs no key) ===
HTTP: 401
client_wall_ms: 4.1010...
server_time_ms: 2.01217...
server_peak_bytes: 2000983
error: InvalidSignatureError

=== ATTACK (VALID signature - accepted path still wastes) ===
HTTP: 200
client_wall_ms: 3.6586...
server_time_ms: 1.59092...
server_peak_bytes: 2001061
payload-chars = 2,000,000
=== BASELINE ===
HTTP: 200
server_time_ms: 0.06527...
server_peak_bytes: 2304

=== ATTACK (INVALID signature) ===
HTTP: 401
server_time_ms: 7.53430...
server_peak_bytes: 8000983

=== ATTACK (VALID signature) ===
HTTP: 200
server_time_ms: 6.34682...
server_peak_bytes: 8001061
payload-chars = 8,000,000
=== BASELINE ===
HTTP: 200
server_time_ms: 0.06573...
server_peak_bytes: 2304

=== ATTACK (INVALID signature) ===
HTTP: 401
server_time_ms: 23.03403...
server_peak_bytes: 32000983

=== ATTACK (VALID signature) ===
HTTP: 200
server_time_ms: 22.09702...
server_peak_bytes: 32001061

Why this is strong evidence

  • The server clearly does heavy work before rejecting invalid signatures.
  • The “valid signature” case shows even accepted requests waste resources due to unused payload segment.

PoC # 3 - Localhost flood / burst concurrency

File: flood_localhost.py
Purpose: sends N concurrent invalid-signature requests over HTTP to demonstrate queueing/worker starvation.

Results (your run: 20 concurrent @​ 8,000,000 chars)
total_wall_ms: 1374.5405770000616

(16, 401, 1156.4504789998864, 21.350951999920653, 32000983, 'InvalidSignatureError')
(19, 401, 1151.2852699997893, 21.208721999755653, 32000983, 'InvalidSignatureError')
(18, 401, 1102.7211239997996, 21.685218999664357, 32000983, 'InvalidSignatureError')
(13, 401, 1102.0718189997751, 21.26572200040755, 32000983, 'InvalidSignatureError')
(11, 401, 1095.9345460000804, 20.586017000368884, 32000983, 'InvalidSignatureError')
(17, 401, 1085.2552810001725, 22.893039000337012, 32000983, 'InvalidSignatureError')
(10, 401, 1078.3629560000918, 22.737160999895423, 32000983, 'InvalidSignatureError')
(7,  401, 1048.2011740000416, 22.476282000297942, 32000983, 'InvalidSignatureError')
(8,  401, 378.93017700025666, 21.377330999712285, 32000983, 'InvalidSignatureError')
(1,  401, 281.45106800002395, 21.34223099983501, 32000983, 'InvalidSignatureError')

Interpretation

  • Each request still costs ~20–23 ms server processing and ~32 MB peak allocations.
  • But client-observed latency rises up to ~1.15 seconds because requests queue behind each other → clear worker starvation/HoL blocking.
  • All were rejected with 401 InvalidSignatureError → still unauthenticated.

Fix
Goal

Prevent unbounded resource consumption from an attacker-controlled payload segment that is unused in b64=false detached flow.

Minimal change strategy

In _load() (or by refactoring parse order), do not Base64-decode payload_segment until after you know whether b64=false applies.

Two safe options:

  1. Reject non-empty payload segment when b64=false

    • Parse header first
    • If b64 is false and payload_segment is non-empty → raise DecodeError before decoding
    • Then verification uses detached_payload only
  2. Skip decoding payload segment entirely when b64=false

    • Keep payload segment as raw bytes or empty
    • Use detached payload for signing input

This aligns with the idea that detached payload is the trusted payload input for verification; the compact payload segment should not become a resource amplification vector.

(Implementation context: the current decode order and unconditional base64url_decode(payload_segment) are visible in the file and line region around _load() and decode_complete() ([GitHub][1]).)


Workarounds
  • Enforce strict max token length at the HTTP boundary (proxy/gateway).
  • Apply rate limiting on verification endpoints.
  • If detached JWS (b64=false) is not needed in your app, reject tokens where header includes "b64": false.

Severity

  • CVSS Score: 5.3 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Release Notes

jpadilla/pyjwt (PyJWT)

v2.13.0

Compare Source


Configuration

📅 Schedule: (in timezone Asia/Kolkata)

  • Branch creation
    • At any time (no schedule defined)
  • Automerge
    • At any time (no schedule defined)

🚦 Automerge: Enabled.

Rebasing: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 Ignore: Close this PR and you won't be reminded about this update again.


  • If you want to rebase/retry this PR, check this box

This PR was generated by Mend Renovate. View the repository job log.

@sonarqubecloud

Copy link
Copy Markdown

@renovate renovate Bot merged commit 0c539bf into main Jun 16, 2026
8 checks passed
@renovate renovate Bot deleted the renovate/pypi-pyjwt-vulnerability branch June 16, 2026 18:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants