Skip to content

Commit e83b517

Browse files
committed
fix(oauth2): Raise PyJWKClientError for invalid kid instead of ValueError
1 parent 2f65410 commit e83b517

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

packages/google-auth/google/oauth2/id_token.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ def verify_token(
141141
try:
142142
import jwt as jwt_lib
143143
from jwt.api_jwk import PyJWKSet
144+
from jwt.exceptions import PyJWKClientError
144145
except ImportError as caught_exc: # pragma: NO COVER
145146
raise ImportError(
146147
"The pyjwt library is not installed, please install the pyjwt package to use the jwk certs format."
@@ -156,7 +157,7 @@ def verify_token(
156157
break
157158

158159
if signing_key is None:
159-
raise ValueError("Token has an invalid kid")
160+
raise PyJWKClientError(f'Unable to find a signing key that matches: "{kid}"')
160161

161162
return jwt_lib.decode(
162163
id_token,

packages/google-auth/tests/oauth2/test_id_token.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,32 @@ def test_verify_token_jwk(decode, get_unverified_header, py_jwk_set, _fetch_cert
117117
)
118118

119119

120+
@mock.patch("google.oauth2.id_token._fetch_certs", autospec=True)
121+
@mock.patch("jwt.api_jwk.PyJWKSet", autospec=True)
122+
@mock.patch("jwt.get_unverified_header", autospec=True)
123+
@mock.patch("jwt.decode", autospec=True)
124+
def test_verify_token_jwk_missing_kid(decode, get_unverified_header, py_jwk_set, _fetch_certs):
125+
from jwt.exceptions import PyJWKClientError
126+
127+
certs_url = "abc123"
128+
data = {"keys": [{"alg": "RS256"}]}
129+
_fetch_certs.return_value = data
130+
get_unverified_header.return_value = {"kid": "mock-kid"}
131+
132+
mock_key = mock.MagicMock()
133+
mock_key.key_id = "different-kid"
134+
mock_key.public_key_use = "sig"
135+
mock_key.key = mock.sentinel.key
136+
mock_key.algorithm_name = "mock-alg"
137+
py_jwk_set.from_dict.return_value.keys = [mock_key]
138+
139+
with pytest.raises(PyJWKClientError, match='Unable to find a signing key that matches: "mock-kid"'):
140+
id_token.verify_token(
141+
mock.sentinel.token, mock.sentinel.request, certs_url=certs_url
142+
)
143+
144+
145+
120146
@mock.patch("google.auth.jwt.decode", autospec=True)
121147
@mock.patch("google.oauth2.id_token._fetch_certs", autospec=True)
122148
def test_verify_token_args(_fetch_certs, decode):

0 commit comments

Comments
 (0)