Skip to content

fix(oauth): parse form-encoded responses in refresh_token() - #4259

Merged
jonpspri merged 2 commits into
IBM:mainfrom
kimsehwan96:fix/oauth-token-refresh-form-encoded
Apr 17, 2026
Merged

jonpspri merged 2 commits into
IBM:mainfrom
kimsehwan96:fix/oauth-token-refresh-form-encoded

Conversation

@kimsehwan96

Copy link
Copy Markdown
Contributor

🔗 Related Issue

Closes #4258


📝 Summary

OAuthManager.refresh_token() in mcpgateway/services/oauth_manager.py assumed the token endpoint always returns JSON, but GitHub's OAuth token endpoint returns application/x-www-form-urlencoded by default. Without an Accept: application/json header, response.json() raised JSONDecodeError: 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_flow at L274, _password_flow at L360, and the two authorization code exchanges at L458 and L1235) so refresh_token() handles both JSON and form-encoded responses uniformly.


🏷️ Type of Change

  • Bug fix
  • Feature / Enhancement
  • Documentation
  • Refactor
  • Chore (deps, CI, tooling)
  • Other (describe below)

🧪 Verification

Check Command Status
Lint suite make lint pass
Unit tests make test pass
Coverage ≥ 80% make coverage

✅ Checklist

  • Code formatted (make black isort pre-commit)
  • Tests added/updated for changes
  • Documentation updated (if applicable)
  • No secrets or credentials committed

📓 Notes (optional)

Root cause (file reference)

mcpgateway/services/oauth_manager.py, OAuthManager.refresh_token(), around L1327:

  # Before
  response = await client.post(token_url, data=token_data, timeout=self.request_timeout)
  if response.status_code == 200:
      token_response = response.json()  # ← raises on GitHub (form-encoded body)

  # After — aligns with _client_credentials_flow / authorization_code paths
  if response.status_code == 200:
      content_type = response.headers.get("content-type", "")
      if "application/x-www-form-urlencoded" in content_type:
          text_response = response.text
          token_response = {}
          for pair in text_response.split("&"):
              if "=" in pair:
                  key, value = pair.split("=", 1)
                  token_response[key] = value
      else:
          try:
              token_response = response.json()
          except Exception as e:
              logger.warning(f"Failed to parse JSON response: {e}")
              token_response = {"raw_response": response.text}
      ...

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]>
…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]>
@jonpspri
jonpspri merged commit d785882 into IBM:main Apr 17, 2026
30 checks passed
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: OAuth token refresh fails for GitHub: form-encoded responses not handled in refresh_token()

2 participants