Skip to content

feat: Add support for signing and verifying nested JWTs - #712

Open
ydah wants to merge 2 commits into
jwt:mainfrom
ydah:nested-jwt
Open

ydah wants to merge 2 commits into
jwt:mainfrom
ydah:nested-jwt

Conversation

@ydah

@ydah ydah commented Jan 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

Implements Nested JWT functionality as defined in RFC 7519 Section 5.2, 7.1, 7.2, and Appendix A.2.

A Nested JWT is a JWT used as the payload of another JWT, allowing multiple layers of signing with different keys/algorithms.

see: https://datatracker.ietf.org/doc/html/rfc7519#section-5.2
see: https://datatracker.ietf.org/doc/html/rfc7519#section-7.1
see: https://datatracker.ietf.org/doc/html/rfc7519#section-7.2

Checklist

Before the PR can be merged be sure the following are checked:

  • There are tests for the fix or feature added/changed
  • A description of the changes and a reference to the PR has been added to CHANGELOG.md. More details in the CONTRIBUTING.md

@ydah
ydah force-pushed the nested-jwt branch 5 times, most recently from 62bbb58 to 952d95f Compare January 29, 2026 13:40
@ydah ydah changed the title Add support for Nested JWTs per RFC 7519 Implements Nested JWT functionality as defined in RFC 7519 Section 5.2, 7.1, 7.2, and Appendix A.2. Jan 29, 2026
@anakinj

anakinj commented Feb 3, 2026

Copy link
Copy Markdown
Member

Thanks for the addition @ydah, looks interesting. I need to take a look at this with a fresh mind. But its on my todo list.

Comment thread lib/jwt/encoded_token.rb Resolved
Comment thread lib/jwt/encoded_token.rb Resolved
Comment thread lib/jwt/token.rb Resolved
Comment thread lib/jwt/nested_token.rb Resolved
Comment thread lib/jwt/nested_token.rb Resolved
@ydah
ydah force-pushed the nested-jwt branch 3 times, most recently from 029b46f to 3850bd0 Compare February 24, 2026 12:06
@ydah
ydah requested a review from anakinj February 24, 2026 12:13
Comment thread lib/jwt/encoded_token.rb Outdated
# encoded_token.verify_signature!(algorithm: 'HS256', key: 'secret')
# encoded_token.payload # => {'pay' => 'load'}
class EncodedToken
class EncodedToken # rubocop:disable Metrics/ClassLength

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be super nice if we could avoid polluting the EncodedToken with the nested token logic. Could we have a pair: NestedToken and EncodedNestedToken

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I vibed together a rough sketch of what I'm visualizing: #721

@github-actions

Copy link
Copy Markdown
Contributor

This pull request has had no activity for 60 days, so it has been marked as stale. It will be closed in 14 days unless something happens. If you are still working on it, push a commit or leave a comment and it will stay open.

@github-actions github-actions Bot added the stale label Nov 28, 2026
…2, 7.1, 7.2, and Appendix A.2.

Implements Nested JWT functionality as defined in RFC 7519 Section 5.2, 7.1, 7.2, and Appendix A.2.

A Nested JWT is a JWT used as the payload of another JWT, allowing multiple layers of signing with different keys/algorithms.
@ydah

ydah commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

@anakinj Thanks for putting together #721. I’ve updated my branch to follow the split you suggested: NestedToken handles signing, and EncodedNestedToken handles unwrapping and verification. That keeps the nesting logic out of EncodedToken.

One difference from your sketch is that I kept verify!(keys: [...]). It lets the caller specify which key and algorithm to accept at each layer, from the outermost token to the innermost. Does that API work for you?

@ydah ydah changed the title Implements Nested JWT functionality as defined in RFC 7519 Section 5.2, 7.1, 7.2, and Appendix A.2. feat: Add support for signing and verifying nested JWTs Nov 29, 2026

@anakinj anakinj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for reworking this along the lines of #721, @ydah. The core holds up well:

  • each layer is verified with its own algorithm and key;
  • stripping the outer layer is caught, because the number of layers has to match the key configurations;
  • none is rejected on every layer;
  • claims are checked on the innermost token;
  • the existing APIs don't change, and JWT.decode on a nested token still raises MalformedTokenError.

A few things to change before it goes in.

1. Verify each layer before decoding the next one (lib/jwt/encoded_nested_token.rb:49-63)

verify_signatures! calls unwrap_all first. That decodes up to 10 layers, and counts them using cty headers nobody has verified, before any signature is checked. RFC 7519 section 7.2 verifies the JWS first and only then looks at cty. For a forged token, the error then depends on what the sender put inside it, and the count error shows how many key configurations the server expects:

outer signed with the wrong key, malformed inner layer: JWT::MalformedTokenError: Token header not a JSON object
outer signed with the wrong key, one key config given:  JWT::DecodeError: Expected 2 key configurations, got 1

Looping over the key configurations would fix this:

  • verify the current layer;
  • decode the next layer only if this one's cty says so;
  • raise if the layers and the configurations run out at different times.

That also limits the depth to the number of configurations. On your question about verify!(keys: [...]): one entry per layer fits this well.

2. Use the current error classes (lines 27, 52, 70, 86)

These raise the bare JWT::DecodeError, which is deprecated. Nothing on main raises it any more, and an application that rescues JWT::TokenError won't catch it. Suggested classes:

  • MalformedTokenError for the depth, empty payload and layer count errors;
  • TokenError for "verify signatures first", as in EncodedToken#payload.

3. Make NestedToken behave like Token (lib/jwt/nested_token.rb)

  • #jwt before sign! returns the inner token, where Token#jwt raises Token is not signed. An issuer who forgets sign! sends out the inner token unwrapped.
  • Calling sign! twice adds another layer, where Token raises Token already signed.
  • It repeats the header and signing code from Token#sign!, and has no header, signature or encoded_* readers.

A subclass of Token, as in #721, would get the guards and readers for free. It would set the cty header and override encoded_payload, so the inner token is base64url-encoded without JSON encoding.

4. Treat cty: application/jwt as nested (line 81)

RFC 7515 section 4.1.10 says a recipient treats a cty without a / as if application/ were in front of it, so application/jwt and JWT mean the same. Today application/jwt isn't seen as nested. It fails safely, but tokens from issuers that send it won't verify.

5. Drop the b64: false branch (line 88)

RFC 7797 doesn't allow a . in an unencoded payload in the compact form, and a JWT always contains one, so a valid token can't reach this branch. It also skips the crit: ["b64"] check that EncodedToken does. Always base64url-decoding the payload, or rejecting b64: false on a cty: JWT layer, would be simpler.

6. Check the per-layer options (lines 54-59)

  • Unknown keys are ignored. A claims: in a layer's hash is accepted and does nothing, so a caller can think they checked claims on that layer.
  • A typo like algorithms: gives No algorithm provided.
  • A Hash instead of an Array raises a plain TypeError.

Passing the hash on with token.verify_signature!(**key_config) would make unknown keys raise, and keys could be checked to be an Array.

7. Tests

  • No spec passes claims:. With claim verification removed from verify!, all the new specs still pass. The spec at encoded_nested_token_spec.rb:70 says it checks claims, but its payload has no exp.
  • integration/nested_jwt_spec.rb:45 builds the outer token with JWT::Token.new(payload: inner_jwt). That JSON-encodes the inner token, so the result isn't a valid nested token. The spec only passes because it checks nested?.
  • Cases worth adding:
    • an expired inner token, with claims: as an Array and as a Hash;
    • none on a layer;
    • the outer layer stripped off;
    • the depth limit through verify!;
    • application/jwt;
    • a bad outer signature around a malformed inner token.

8. CHANGELOG

release-please writes the CHANGELOG from the PR title (see CONTRIBUTING.md), so the edit can go.

Smaller things:

  • "Expected 1 key configurations, got 2" reads the wrong way round: the first number is the token's layer count.
  • max_depth can be given to unwrap_all but not to verify!.
  • MAX_DEPTH and CTY_JWT could be private_constant, as in EncodedToken.
  • The README could say that inner_token and unwrap_all return unverified tokens, and that only JWS layers are supported.
  • The "(NEST-01)" tags in the spec names look like leftovers.

Posted by Claude on behalf of @anakinj.

@anakinj anakinj removed the stale label Nov 29, 2026

This branch has not been deployed

No deployments
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.

2 participants