Repository navigation
fix(oauth): parse form-encoded responses in refresh_token() - #4259
Merged
jonpspri merged 2 commits intoApr 17, 2026
Merged
Conversation
Token endpoints that respond with application/x-www-form-urlencoded (e.g. GitHub's /login/oauth/access_token) caused response.json() to raise JSONDecodeError, silently failing token refresh and driving gateways offline after access-token expiry. Apply the same content-type branch used in the three other token fetching paths in this module (_client_credentials_flow, _password_flow, and the two authorization code exchanges) so refresh_token() handles both JSON and form-encoded responses. Add unit tests covering: - happy path for form-encoded responses (asserts response.json() is not invoked to prove the form-encoded branch is actually taken) - negative path for unexpected content-type (raw fallback then OAuthError for missing access_token) - regression guard: set content-type on the existing success test Signed-off-by: kimsehwan96 <[email protected]>
kimsehwan96
requested review from
brian-hussey,
crivetimihai,
kevalmahajan and
madhav165
as code owners
April 16, 2026 23:18
…t leaks
Pull the JSON / form-encoded response parsing duplicated across five
token-fetching paths (_client_credentials_flow, _password_flow, both
authorization-code exchanges, and refresh_token) into a single
_parse_token_response() helper, and add a _redact_token_response()
helper that all five "No access_token" OAuthError sites and the
refresh_token 4xx path use to bound what reaches logs and exception
messages.
Parsing improvements (apply to all five paths via the helper):
- Treat the content-type header case-insensitively per RFC 7231 §3.1.1.1
so providers sending "Application/X-WWW-Form-Urlencoded" no longer
fall through to the JSON branch.
- URL-decode form-encoded values via urllib.parse.parse_qsl, so a value
like "scope=repo%3Astatus" is delivered to callers as "repo:status".
- Narrow the parse-failure except clause from bare Exception to
ValueError (covers JSONDecodeError and UnicodeDecodeError) so that
unrelated failures such as httpx.ResponseNotRead surface instead of
being silently captured as raw_response.
- Log parse failures with diagnostic context (status, content-type,
body bytes) and exc_info=True to aid operator debugging.
- Detect garbage form bodies: parse_qsl runs without keep_blank_values
so an HTML page with no "=" parses to {} and falls through to the
raw_response capture, and any non-empty parse whose keys aren't
OAuth-parameter shaped (e.g. <meta charset=...>) is rejected the
same way.
- Tolerate undecodable bodies via a new _safe_response_text() helper
that returns "<undecodable body, N bytes>" when response.text raises
UnicodeDecodeError or LookupError.
Secret-leak prevention (everywhere a token-shaped dict reaches an
OAuthError or log line):
- Redact known credential-bearing keys (access_token, refresh_token,
id_token, client_secret, password) to "[REDACTED]".
- Scrub URL/form-style "<key>=<value>" patterns inline so that secrets
embedded in HTML hrefs, form actions, or stack traces are neutered
even when the surrounding string fits inside the truncation window.
- Cap any string value at 256 chars with a "... [truncated, N chars
total]" marker so HTML error pages and verbose stack traces don't
swamp logs.
- Route the refresh_token 4xx error path through the same parse +
redact pipeline (it previously surfaced raw response.text in both
the OAuthError and the failure-status warning).
- refresh_token's "No access_token" OAuthError now matches the sibling
flows by echoing the (redacted) parsed payload for diagnostics.
Tests cover mixed-case content-type, URL-decoded values, JSON-branch
JSONDecodeError + UnicodeDecodeError fallbacks, missing content-type
header, empty form body, garbage form bodies, undecodable bodies,
sensitive-key redaction, raw_response truncation, URL-param scrubbing,
4xx echoed-secret redaction, and 4xx oversized HTML truncation. The
two pre-existing 4xx tests are tightened to assert the parsed error
field appears in the OAuthError so a regression that loses the body
would be caught.
Signed-off-by: Jonathan Springer <[email protected]>
gcgoncalves
pushed a commit
that referenced
this pull request
Apr 23, 2026
* fix(oauth): parse form-encoded responses in refresh_token() Token endpoints that respond with application/x-www-form-urlencoded (e.g. GitHub's /login/oauth/access_token) caused response.json() to raise JSONDecodeError, silently failing token refresh and driving gateways offline after access-token expiry. Apply the same content-type branch used in the three other token fetching paths in this module (_client_credentials_flow, _password_flow, and the two authorization code exchanges) so refresh_token() handles both JSON and form-encoded responses. Add unit tests covering: - happy path for form-encoded responses (asserts response.json() is not invoked to prove the form-encoded branch is actually taken) - negative path for unexpected content-type (raw fallback then OAuthError for missing access_token) - regression guard: set content-type on the existing success test Signed-off-by: kimsehwan96 <[email protected]> * refactor(oauth): consolidate token-response parsing and prevent secret leaks Pull the JSON / form-encoded response parsing duplicated across five token-fetching paths (_client_credentials_flow, _password_flow, both authorization-code exchanges, and refresh_token) into a single _parse_token_response() helper, and add a _redact_token_response() helper that all five "No access_token" OAuthError sites and the refresh_token 4xx path use to bound what reaches logs and exception messages. Parsing improvements (apply to all five paths via the helper): - Treat the content-type header case-insensitively per RFC 7231 §3.1.1.1 so providers sending "Application/X-WWW-Form-Urlencoded" no longer fall through to the JSON branch. - URL-decode form-encoded values via urllib.parse.parse_qsl, so a value like "scope=repo%3Astatus" is delivered to callers as "repo:status". - Narrow the parse-failure except clause from bare Exception to ValueError (covers JSONDecodeError and UnicodeDecodeError) so that unrelated failures such as httpx.ResponseNotRead surface instead of being silently captured as raw_response. - Log parse failures with diagnostic context (status, content-type, body bytes) and exc_info=True to aid operator debugging. - Detect garbage form bodies: parse_qsl runs without keep_blank_values so an HTML page with no "=" parses to {} and falls through to the raw_response capture, and any non-empty parse whose keys aren't OAuth-parameter shaped (e.g. <meta charset=...>) is rejected the same way. - Tolerate undecodable bodies via a new _safe_response_text() helper that returns "<undecodable body, N bytes>" when response.text raises UnicodeDecodeError or LookupError. Secret-leak prevention (everywhere a token-shaped dict reaches an OAuthError or log line): - Redact known credential-bearing keys (access_token, refresh_token, id_token, client_secret, password) to "[REDACTED]". - Scrub URL/form-style "<key>=<value>" patterns inline so that secrets embedded in HTML hrefs, form actions, or stack traces are neutered even when the surrounding string fits inside the truncation window. - Cap any string value at 256 chars with a "... [truncated, N chars total]" marker so HTML error pages and verbose stack traces don't swamp logs. - Route the refresh_token 4xx error path through the same parse + redact pipeline (it previously surfaced raw response.text in both the OAuthError and the failure-status warning). - refresh_token's "No access_token" OAuthError now matches the sibling flows by echoing the (redacted) parsed payload for diagnostics. Tests cover mixed-case content-type, URL-decoded values, JSON-branch JSONDecodeError + UnicodeDecodeError fallbacks, missing content-type header, empty form body, garbage form bodies, undecodable bodies, sensitive-key redaction, raw_response truncation, URL-param scrubbing, 4xx echoed-secret redaction, and 4xx oversized HTML truncation. The two pre-existing 4xx tests are tightened to assert the parsed error field appears in the OAuthError so a regression that loses the body would be caught. Signed-off-by: Jonathan Springer <[email protected]> --------- Signed-off-by: kimsehwan96 <[email protected]> Signed-off-by: Jonathan Springer <[email protected]> Co-authored-by: Jonathan Springer <[email protected]>
msureshkumar88
pushed a commit
that referenced
this pull request
May 13, 2026
* fix(oauth): parse form-encoded responses in refresh_token() Token endpoints that respond with application/x-www-form-urlencoded (e.g. GitHub's /login/oauth/access_token) caused response.json() to raise JSONDecodeError, silently failing token refresh and driving gateways offline after access-token expiry. Apply the same content-type branch used in the three other token fetching paths in this module (_client_credentials_flow, _password_flow, and the two authorization code exchanges) so refresh_token() handles both JSON and form-encoded responses. Add unit tests covering: - happy path for form-encoded responses (asserts response.json() is not invoked to prove the form-encoded branch is actually taken) - negative path for unexpected content-type (raw fallback then OAuthError for missing access_token) - regression guard: set content-type on the existing success test Signed-off-by: kimsehwan96 <[email protected]> * refactor(oauth): consolidate token-response parsing and prevent secret leaks Pull the JSON / form-encoded response parsing duplicated across five token-fetching paths (_client_credentials_flow, _password_flow, both authorization-code exchanges, and refresh_token) into a single _parse_token_response() helper, and add a _redact_token_response() helper that all five "No access_token" OAuthError sites and the refresh_token 4xx path use to bound what reaches logs and exception messages. Parsing improvements (apply to all five paths via the helper): - Treat the content-type header case-insensitively per RFC 7231 §3.1.1.1 so providers sending "Application/X-WWW-Form-Urlencoded" no longer fall through to the JSON branch. - URL-decode form-encoded values via urllib.parse.parse_qsl, so a value like "scope=repo%3Astatus" is delivered to callers as "repo:status". - Narrow the parse-failure except clause from bare Exception to ValueError (covers JSONDecodeError and UnicodeDecodeError) so that unrelated failures such as httpx.ResponseNotRead surface instead of being silently captured as raw_response. - Log parse failures with diagnostic context (status, content-type, body bytes) and exc_info=True to aid operator debugging. - Detect garbage form bodies: parse_qsl runs without keep_blank_values so an HTML page with no "=" parses to {} and falls through to the raw_response capture, and any non-empty parse whose keys aren't OAuth-parameter shaped (e.g. <meta charset=...>) is rejected the same way. - Tolerate undecodable bodies via a new _safe_response_text() helper that returns "<undecodable body, N bytes>" when response.text raises UnicodeDecodeError or LookupError. Secret-leak prevention (everywhere a token-shaped dict reaches an OAuthError or log line): - Redact known credential-bearing keys (access_token, refresh_token, id_token, client_secret, password) to "[REDACTED]". - Scrub URL/form-style "<key>=<value>" patterns inline so that secrets embedded in HTML hrefs, form actions, or stack traces are neutered even when the surrounding string fits inside the truncation window. - Cap any string value at 256 chars with a "... [truncated, N chars total]" marker so HTML error pages and verbose stack traces don't swamp logs. - Route the refresh_token 4xx error path through the same parse + redact pipeline (it previously surfaced raw response.text in both the OAuthError and the failure-status warning). - refresh_token's "No access_token" OAuthError now matches the sibling flows by echoing the (redacted) parsed payload for diagnostics. Tests cover mixed-case content-type, URL-decoded values, JSON-branch JSONDecodeError + UnicodeDecodeError fallbacks, missing content-type header, empty form body, garbage form bodies, undecodable bodies, sensitive-key redaction, raw_response truncation, URL-param scrubbing, 4xx echoed-secret redaction, and 4xx oversized HTML truncation. The two pre-existing 4xx tests are tightened to assert the parsed error field appears in the OAuthError so a regression that loses the body would be caught. Signed-off-by: Jonathan Springer <[email protected]> --------- Signed-off-by: kimsehwan96 <[email protected]> Signed-off-by: Jonathan Springer <[email protected]> Co-authored-by: Jonathan Springer <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
🔗 Related Issue
Closes #4258
📝 Summary
OAuthManager.refresh_token()inmcpgateway/services/oauth_manager.pyassumed the token endpoint always returns JSON, but GitHub's OAuth token endpoint returnsapplication/x-www-form-urlencodedby default. Without anAccept: application/jsonheader,response.json()raisedJSONDecodeError: Expecting value: line 1 column 1 (char 0), silently failing the refresh, letting the access token expire, and driving gateways offline on the next health check.This PR applies the same content-type branch already used in the three other token-fetching paths in the same file (
_client_credentials_flowat L274,_password_flowat L360, and the two authorization code exchanges at L458 and L1235) sorefresh_token()handles both JSON and form-encoded responses uniformly.🏷️ Type of Change
🧪 Verification
make lintmake testmake coverage✅ Checklist
make black isort pre-commit)📓 Notes (optional)
Root cause (file reference)
mcpgateway/services/oauth_manager.py,OAuthManager.refresh_token(), around L1327: