Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Skip JWT decode probe for opaque OIDC access tokens (#19286)

Lukasz Ostrowskiffeb5e7b9c95
diff --git a/saleor/plugins/openid_connect/tests/test_utils.py b/saleor/plugins/openid_connect/tests/test_utils.py
index 948b0303b5..99508e7d7a 100644
--- a/saleor/plugins/openid_connect/tests/test_utils.py
+++ b/saleor/plugins/openid_connect/tests/test_utils.py
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock, Mock, call, patch
import pytest
import requests
from authlib.jose import JWTClaims
+from django.core.cache import cache
from django.core.exceptions import ValidationError
from freezegun import freeze_time
from requests import Response
@@ -18,10 +19,12 @@ from ....account.search import update_user_search_vector
from ....core.jwt import (
JWT_REFRESH_TYPE,
PERMISSIONS_FIELD,
+ create_access_token,
jwt_decode,
jwt_encode,
jwt_user_payload,
)
+from ....core.jwt_manager import get_jwt_manager
from ....permission.models import Permission
from ..exceptions import AuthenticationError
from ..utils import (
@@ -33,6 +36,7 @@ from ..utils import (
create_jwt_refresh_token,
create_jwt_token,
create_tokens_from_oauth_payload,
+ decode_access_token,
fetch_jwks,
get_domain_from_email,
get_or_create_user_from_payload,
@@ -41,6 +45,7 @@ from ..utils import (
get_user_from_oauth_access_token_in_jwt_format,
get_user_from_token,
get_user_info,
+ is_jwt_shaped,
validate_refresh_token,
)
@@ -73,6 +78,85 @@ def test_fetch_jwks(mocked_cache_set):
mocked_cache_set.assert_called_once_with(JWKS_KEY, keys, JWKS_CACHE_TIME)
+ ("token", "expected"),
+ [
+ # 2 dots -> signed JWT (JWS), 4 dots -> encrypted JWT (JWE).
+ ("header.payload.signature", True),
+ ("header.encrypted_key.iv.ciphertext.tag", True),
+ # A signature-less "alg:none" token still has 2 dots, so it is JWT-shaped.
+ # Rejecting it is the job of the decoder, not the shape check.
+ ("header.payload.", True),
+ # Opaque reference tokens are not JWTs and have nothing to decode.
+ ("FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3", False),
+ ("", False),
+ ("header.payload", False),
+ ("a.b.c.d", False),
+ ("a.b.c.d.e.f", False),
+ ],
+)
+def test_is_jwt_shaped(token, expected):
+ # when
+ result = is_jwt_shaped(token)
+
+ # then
+ assert result is expected
+
+
+def test_decode_access_token_opaque_token_skips_decode_and_logging(monkeypatch, caplog):
+ # given
+ opaque_token = "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3"
+ jwks_url = "https://example.com/.well-known/jwks.json"
+ mocked_get_decoded_token = Mock()
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_decoded_token",
+ mocked_get_decoded_token,
+ )
+
+ # when
+ result = decode_access_token(opaque_token, jwks_url)
+
+ # then
+ assert result is None
+ mocked_get_decoded_token.assert_not_called()
+ assert "Invalid OIDC access token format" not in caplog.text
+
+
+def test_decode_access_token_invalid_signature_returns_none_and_logs(
+ customer_user, caplog
+):
+ # given
+ jwks_url = "https://example.com/.well-known/jwks.json"
+ cache.set(JWKS_KEY, get_jwt_manager().get_jwks()["keys"], JWKS_CACHE_TIME)
+
+ # tamper with the signature of an otherwise valid token so the real decoder
+ # rejects it on signature verification
+ header, payload, signature = create_access_token(customer_user).split(".")
+ tampered_signature = ("A" if signature[0] != "A" else "B") + signature[1:]
+ tampered_token = ".".join([header, payload, tampered_signature])
+
+ # when
+ result = decode_access_token(tampered_token, jwks_url)
+
+ # then
+ assert result is None
+ assert "Invalid OIDC access token format" in caplog.text
+
+
+def test_decode_access_token_valid_jwt_returns_payload(customer_user):
+ # given
+ jwks_url = "https://example.com/.well-known/jwks.json"
+ cache.set(JWKS_KEY, get_jwt_manager().get_jwks()["keys"], JWKS_CACHE_TIME)
+ token = create_access_token(customer_user)
+
+ # when
+ result = decode_access_token(token, jwks_url)
+
+ # then
+ assert result is not None
+ assert result["email"] == customer_user.email
+
+
def test_get_or_create_user_from_token_missing_email(id_payload):
del id_payload["email"]
with pytest.raises(AuthenticationError):
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
index 1573391951..a5c8844836 100644
--- a/saleor/plugins/openid_connect/utils.py
+++ b/saleor/plugins/openid_connect/utils.py
@@ -152,10 +152,35 @@ def get_user_info(user_info_url, access_token) -> dict | None:
return None
+def is_jwt_shaped(token: str) -> bool:
+ """Return whether the token is structurally a compact JWT.
+
+ authlib treats a token with 2 dots as a signed JWT (JWS) and one with 4 dots
+ as an encrypted JWT (JWE); anything else is rejected with a ``DecodeError``
+ (see ``authlib.jose.rfc7519.jwt.JWT.decode``). OIDC access tokens come in two
+ flavours: self-contained JWTs (validated locally against the JWKS) and opaque
+ reference tokens (validated by calling the user info endpoint). An opaque
+ token is just a random string and has nothing to decode, so probing it as a
+ JWT is pointless work that also raises a misleading "Invalid OIDC access
+ token format" log on every request. Mirroring authlib's own segment check
+ here lets us route opaque tokens straight to the user info path and reserve
+ the decode attempt - and its log - for tokens that actually claim to be JWTs.
+ """
+ return token.count(".") in (2, 4)
+
+
def decode_access_token(token, jwks_url):
+ if not is_jwt_shaped(token):
+ # Opaque (non-JWT) access token - there is nothing to decode. The caller
+ # falls back to validating it via the user info endpoint. Return early to
+ # avoid the misleading "Invalid OIDC access token format" log below.
+ return None
try:
return get_decoded_token(token, jwks_url)
except (JoseError, ValueError) as e:
+ # The token looked like a JWT but failed to decode/verify (e.g. bad
+ # signature, unknown key id, malformed segment). This is a genuine
+ # problem worth logging, unlike the opaque-token case handled above.
logger.info(
"Invalid OIDC access token format",
extra={"error": str(e), "jwks_url": jwks_url},