Skip to content

fix(auth): return AuthInvalidJwtError when a JWT header or payload is not a JSON object - #2720

Closed
iamhuman-cheolheelee wants to merge 1 commit into
supabase:masterfrom
iamhuman-cheolheelee:fix/auth-getclaims-malformed-jwt
Closed

iamhuman-cheolheelee wants to merge 1 commit into
supabase:masterfrom
iamhuman-cheolheelee:fix/auth-getclaims-malformed-jwt

Conversation

@iamhuman-cheolheelee

Copy link
Copy Markdown

🔍 Description

What changed?

decodeJWT (packages/core/auth-js/src/lib/helpers.ts) now guards the two JSON.parse calls on the decoded header and payload:

  • If either segment is not valid JSON, it throws AuthInvalidJwtError('JWT header or payload is not valid JSON').
  • If either segment parses to something other than a plain object (null, an array, a number), it throws AuthInvalidJwtError('JWT header or payload is not a JSON object').

Tests:

  • test/helpers.test.ts: two new decodeJWT cases.
  • test/GoTrueClient.getClaims.test.ts (new): an offline test with mocked fetch. It checks that getClaims() returns { data: null, error: AuthInvalidJwtError } for all three malformed shapes and never calls the network.

Why was this change needed?

decodeJWT already rejects tokens that don't have three base64url segments, but it passed the decoded segments straight to JSON.parse. A token like base64url("not json").e30.c2ln passes the segment check. The SyntaxError from JSON.parse is not an AuthError, so callers that only map AuthErrors rethrow it:

  • getClaims() (GoTrueClient.ts ~L6727): its catch returns { error } only for isAuthError(error). Otherwise it rethrows, so await supabase.auth.getClaims(token) rejects instead of resolving.
  • _setSession (~L3627) and _getAuthenticatorAssuranceLevel(jwt) (~L6094) follow the same pattern.

A payload of null is valid JSON, so it gets past JSON.parse. It then fails later with Cannot read properties of null (reading 'exp').

Behaviour on master (6d21e3f):

token before after
header not json getClaims rejects with SyntaxError { data: null, error: AuthInvalidJwtError }
payload {bad getClaims rejects with SyntaxError { data: null, error: AuthInvalidJwtError }
payload null AuthInvalidJwtError: Cannot read properties of null (reading 'exp') { data: null, error: AuthInvalidJwtError } with a clear message

This is the same contract #2395 established for expired JWTs: getClaims reports bad input through error, not by throwing.

Flow (mermaid)
flowchart TD
  A[getClaims token] --> B[decodeJWT]
  B --> C{3 base64url segments?}
  C -- no --> E[AuthInvalidJwtError]
  C -- yes --> D{JSON.parse header and payload}
  D -- throws --> F[before: SyntaxError escapes, getClaims rejects]
  D -- throws --> E2[after: AuthInvalidJwtError]
  D -- ok --> G{both plain objects?}
  G -- no --> H[before: TypeError on payload.exp]
  G -- no --> E2
  G -- yes --> I[verify signature / claims]
  E2 --> J[getClaims returns data null, error]
  E --> J
Loading

📸 Screenshots/Examples

const token = `${b64('{"alg":"HS256"}')}.${b64('{bad')}.c2ln`
const { data, error } = await supabase.auth.getClaims(token)
// before: throws SyntaxError: Expected property name or '}' in JSON
// after:  data === null, error.name === 'AuthInvalidJwtError', error.code === 'invalid_jwt'

🔄 Breaking changes

  • This PR contains no breaking changes

Well-formed tokens behave exactly as before. Malformed tokens that used to throw now return an AuthInvalidJwtError, which is what the getClaims / setSession return type already promises.

📋 Checklist

  • I have read the Contributing Guidelines
  • My PR title follows the conventional commit format: <type>(<scope>): <description>
  • I have run pnpm nx format to ensure consistent code formatting
  • I have added tests for new functionality (if applicable)
  • I have updated documentation (if applicable) (not applicable)

📝 Additional notes

Testing (packages/core/auth-js, npx jest --config jest.config.cli.js test/helpers.test.ts test/GoTrueClient.getClaims.test.ts):

  • Before the fix, on master: 5 failed, 50 passed.
  • After the fix: 55 passed.
  • Other offline auth-js suites (12 suites, 219 tests) pass, tsc --noEmit is clean for tsconfig.json and tsconfig.test.json, and the build succeeds.

cc @mandarini, since this extends the getClaims error contract you tightened in #2395.

I used an AI assistant (Claude Code) while investigating and writing this change, and I reviewed and tested it by hand.

🤖 Generated with Claude Code

… not a JSON object

decodeJWT called JSON.parse on the decoded header and payload without a guard,
so a token whose segments are valid base64url but not JSON made getClaims(),
setSession() and getAuthenticatorAssuranceLevel(jwt) throw a raw SyntaxError
instead of returning { data: null, error }. A JSON null payload surfaced as
"Cannot read properties of null (reading 'exp')".
@coderabbitai

coderabbitai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 8a309710-002b-4100-80cc-6588c4489bbc

📥 Commits

Reviewing files that changed from the base of the PR and between 6d21e3f and 64957f1.

📒 Files selected for processing (3)
  • packages/core/auth-js/src/lib/helpers.ts
  • packages/core/auth-js/test/GoTrueClient.getClaims.test.ts
  • packages/core/auth-js/test/helpers.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.


📝 Summary

Summary by CodeRabbit

  • Bug Fixes
    • Invalid JWT headers or payloads now return a consistent authentication error instead of being accepted or causing an unexpected parsing failure.
    • Claims requests with invalid tokens return an error without making a network request.

Walkthrough

decodeJWT now converts JSON parsing failures and non-object header or payload values into AuthInvalidJwtError. Tests cover malformed JWTs in decodeJWT and getClaims. For malformed tokens, getClaims returns null data and does not call fetch.

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 64957

The JWT validation change appears ready to merge after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 64957

Malformed JWT sections now produce a consistent authentication error instead of an uncaught parsing error. The reviewed paths reject those tokens before returning claims or making a verification request. No introduced security issue was identified, though downstream coverage is incomplete.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The identified effect is within auth-library consumers of decodeJWT, including getClaims and session and assurance-level handling. The changed tests do not create a production entrypoint.

Trust Boundaries and Controls

  • observed — For an explicitly supplied token, getClaims decodes the attacker-controlled JWT before key lookup or user verification. The tested malformed sections fail at decoding, while successfully decoded claims remain subject to the existing verification path.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@iamhuman-cheolheelee iamhuman-cheolheelee closed this by deleting the head repository Oct 23, 2026
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.

1 participant