Skip to content

oauth2: chunk large token cookies - #43135

Closed
shashankram wants to merge 11 commits into
envoyproxy:mainfrom
shashankram:oauth-cookie-chunk
Closed

shashankram wants to merge 11 commits into
envoyproxy:mainfrom
shashankram:oauth-cookie-chunk

Conversation

@shashankram

Copy link
Copy Markdown

Token cookies can be quite large and cause problems when they can't be stored by the browser due to size restrictions. Most modern browsers enforce a size limit of 4096 characters for the entire cookie, including name and value separator. When the cookies can't be stored, using the filter will result in redirection loops.

This chunks large token cookies by default, and combines them when the request token cookies are already chunked.

Risk Level: n/a
Testing: Unit tests
Fixes #27875

@repokitteh-read-only

Copy link
Copy Markdown

Hi @shashankram, welcome and thank you for your contribution.

We will try to review your Pull Request as quickly as possible.

In the meantime, please take a look at the contribution guidelines if you have not done so already.

🐱

Caused by: #43135 was opened by shashankram.

see: more, trace.

@shashankram

Copy link
Copy Markdown
Author

/coverage

@repokitteh-read-only

Copy link
Copy Markdown

Coverage for this Pull Request will be rendered here:

https://storage.googleapis.com/envoy-cncf-pr/43135/coverage/index.html

For comparison, current coverage on main branch is here:

https://storage.googleapis.com/envoy-cncf-postsubmit/main/coverage/index.html

The coverage results are (re-)rendered each time the CI Envoy/Checks (coverage) job completes.

🐱

Caused by: a #43135 (comment) was created by @shashankram.

see: more, trace.

@shashankram

Copy link
Copy Markdown
Author

/coverage

@repokitteh-read-only

Copy link
Copy Markdown

Coverage for this Pull Request will be rendered here:

https://storage.googleapis.com/envoy-cncf-pr/43135/coverage/index.html

For comparison, current coverage on main branch is here:

https://storage.googleapis.com/envoy-cncf-postsubmit/main/coverage/index.html

The coverage results are (re-)rendered each time the CI Envoy/Checks (coverage) job completes.

🐱

Caused by: a #43135 (comment) was created by @shashankram.

see: more, trace.

@shashankram

Copy link
Copy Markdown
Author

cc @phlax @wbpcode

Token cookies can be quite large and cause problems when they
can't be stored by the browser due to size restrictions. Most
modern browsers enforce a size limit of 4096 characters for the
entire cookie, including name and value separator. When
the cookies can't be stored, using the filter will result in
redirection loops.

This change chunks large token cookies by default, and combines
them when the request token cookies are already chunked.

Resolves envoyproxy#27875

Signed-off-by: Shashank Ram <[email protected]>
@shashankram

Copy link
Copy Markdown
Author

/retest

@KBaichoo

KBaichoo commented Feb 5, 2026

Copy link
Copy Markdown
Contributor

/assign @bplotnick

As codeowner to take a look

@yanavlasov

Copy link
Copy Markdown
Contributor

@shashankram thanks for making this change. Since this is user visible change, can you make it based on configuration option, please? In this way only users which are impacted by large cookie sizes will need to switch to the new behavior.

/wait-any

@repokitteh-read-only

Copy link
Copy Markdown

🙀 Error while processing event:

evaluation error
error: function _github_call error: github error: POST https://api.github.com/repos/envoyproxy/envoy/issues/43135/labels: 401 Requires authentication []:
 Traceback (most recent call last):
  bootstrap:143: in <toplevel>
  bootstrap:135: in _main
  bootstrap:62: in _call
  bootstrap:15: in _call1
  github.com/repokitteh/modules/wait.star:23: in _wait_any
  github:237: in issue_label
  github:155: in call
Error: function _github_call error: github error: POST https://api.github.com/repos/envoyproxy/envoy/issues/43135/labels: 401 Requires authentication []
🐱

Caused by: a #43135 (comment) was created by @yanavlasov.

see: more, trace.

@shashankram

Copy link
Copy Markdown
Author

@shashankram thanks for making this change. Since this is user visible change, can you make it based on configuration option, please? In this way only users which are impacted by large cookie sizes will need to switch to the new behavior.

/wait-any

Is there a reason to not implicitly chunk large token cookies, because without it, the functionality breaks. Alternatively, we could make this an API field to control chunking.

@yanavlasov yanavlasov self-assigned this Feb 12, 2026
@yanavlasov

Copy link
Copy Markdown
Contributor

@shashankram thanks for making this change. Since this is user visible change, can you make it based on configuration option, please? In this way only users which are impacted by large cookie sizes will need to switch to the new behavior.
/wait-any

Is there a reason to not implicitly chunk large token cookies, because without it, the functionality breaks. Alternatively, we could make this an API field to control chunking.

If this change breaks someone's app, how would they address the problem? Given the complexity of this behavior I think config option is appropriate. You can default it to true to make splitting cookies to be the default.

@botengyao

Copy link
Copy Markdown
Member

waiting for addressing Yan's feedback.

/wait

@andy-fong

Copy link
Copy Markdown
Contributor

I am kind of taking over this PR and I have addressed yanavlasov's comment but then I saw kanurag94's comments and they are valid. So, working to address them as well but taking a bit of time.

@kanurag94

Copy link
Copy Markdown
Member

I am kind of taking over this PR and I have addressed yanavlasov's comment but then I saw kanurag94's comments and they are valid. So, working to address them as well but taking a bit of time.

thanks @andy-fong! lmk if you need any help. This PR itself was originally #28799

@isZumpo

isZumpo commented Aug 21, 2026 •

Copy link
Copy Markdown

I tried this out and it seems to work quite well. The tokens are being chunked as expected. However, maybe other places of the codebase needs support for the chunking too?

I am trying to add authorization ( https://gateway.envoyproxy.io/docs/tasks/security/jwt-claim-authorization/) and want fields from the idToken to gate access (such as group membership). From what I understand https://gateway.envoyproxy.io/latest/api/extension_types/#jwtextractor may be used for this, but I think it struggles with the chunked cookies. Maybe there is some other approach that I am not aware of?

Edit: The following works:

oidc:
forwardIDToken:
header: Authorization

Sending it to the upstream/jwt filter as a header instead of cookie works around the cookie chunking.

@andy-fong

Copy link
Copy Markdown
Contributor

Changes:

  • Addressed spammy log concerns
  • Default to disable for this release
  • Reassemble chunks before decrypting and HMAC validation.
  • Normalize bearer/ID tokens into base cookies, and remove all refresh-token and chunk metadata cookies before forwarding.
  • When switching between chunked and non-chunked storage, expire the previous browser cookies before setting the new representation.
  • Preserve the normalized refresh token when the provider omits a replacement.
  • Calculate all encrypted token sizes and return 503 before emitting session cookies.
  • Consider cookie name and attribute overhead when calculating the available token payload size, and reject cookies when no payload capacity remains.
  • Explicitly enable the guard in positive chunking tests and cover disabled-guard rollback.
  • Detect token cookies even when only the chunk-count marker or individual chunks are present, so omitted tokens still trigger client-side deletion.
  • Emit bounded deletion headers for all 15 possible chunks plus base and marker cookies when cleaning up (eg malformed chunk count).
  • Add a real-validator round-trip test covering emission, browser return, reassembly, decryption, validation, and forwarding.

(Disclaimer: most of these are AI generated but I did go through each item and made sure I understood what's changed)

@andy-fong
andy-fong had a problem deploying to external-contributors September 11, 2026 18:10 — with GitHub Actions Failure
@andy-fong

Copy link
Copy Markdown
Contributor

@kanurag94 do you mind taking a look at the update when you get a chance? Thank you!

Comment on lines +314 to +317
// TODO: Flip to true after 1 release. This is default to false to allow users to upgrade
// without mixing old and new behavior in a large deployment. Once all instances are upgraded,
// this can be flipped to true to enable the new behavior.
FALSE_RUNTIME_GUARD(envoy_reloadable_features_oauth2_chunk_large_token_cookies);

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.

Can we instead not change the behavior for someone having <4kb cookies, and for anyone else, this never worked. So we can enable it by default

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I am pretty sure the behavior for <4kb cookies has not changed. It's default to false because during deployment in large cluster with many envoy instances, >4k cookies behavior from new instance may break old instance. I understand for browsers, >4kb cookie never work but the concern is for custom client that does not have the 4kb cookie limit. Things might break during the deployment.

Ideally, the strategy is that after deployment is complete, flip this on "all at once" to minimize impact.

COUNTER(oauth_refreshtoken_success) \
COUNTER(oauth_refreshtoken_failure) \
COUNTER(oauth_allow_failed_passthrough) \
COUNTER(oauth_legacy_cbc_decrypt)

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.

WDYT about adding some stats counters on this?

Comment on lines +1522 to +1524
if (data.size() <= max_allowed_data_size.value()) {
setCookie(headers, key, data, cookie_tail);
return;

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 think it splits even when the cookie size is 4094 as it subtracts 3 byte chunk. Is it intended?

@kanurag94 kanurag94 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.

overall lgtm, thanks for working on this!

@tyxia

tyxia commented Sep 24, 2026

Copy link
Copy Markdown
Member

Gentle ping from maintainer oncall @bplotnick @yanavlasov , since you are assigned to this PR

@wbpcode wbpcode 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 your contribution. This requirement self is reasonable. I added some comments. And @kanurag94 's comments also make sense for me.

/wait

Comment on lines +314 to +317
// TODO: Flip to true after 1 release. This is default to false to allow users to upgrade
// without mixing old and new behavior in a large deployment. Once all instances are upgraded,
// this can be flipped to true to enable the new behavior.
FALSE_RUNTIME_GUARD(envoy_reloadable_features_oauth2_chunk_large_token_cookies);

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.

Rather than runtime flag, please implement it with a new token_chunk_config to enable this feature explicitly and also could allow users to configure the max chunks and also the per chunk size limit. Because this feature is only necessary for part users, it's unnecessary to let all users to pay for it.

Comment on lines +95 to +101
bool oauth2ChunkLargeTokenCookiesEnabled() {
// This guard controls only whether Envoy emits chunked token cookies.
// Parsing and deletion of chunked cookies must always remain enabled to
// handle cookies created by earlier responses while this guard was true.
return Runtime::runtimeFeatureEnabled(
"envoy.reloadable_features.oauth2_chunk_large_token_cookies");
}

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.

Note, if we do need to use runtime flag, evaluate this flag once at the decodeHeaders to avoid the inconsistent values at runtime.

But as I suggested, we prefer an explicit API.

const Http::LowerCaseString OAuthFailureReason{absl::StrCat(prefix(), "-oauth-failure-reason")};
};

const size_t MaxCookieSize = 4096;

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.

constexpr rather than const

Comment on lines +392 to +393
std::string findTokenCookie(const absl::flat_hash_map<std::string, std::string>& cookies,
const std::string& key_prefix) const;

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.

Seems this needn't to be a member of this class?

Comment on lines +488 to +490
// Populated once while normalizing each request's token cookies so response writes can delete
// the chunked representation that was present on that request.
absl::flat_hash_map<std::string, int> token_cookie_chunk_counts_;

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.

Rather than a map, I prefer to use three state structure to record all state of the incoming token cookies, for example:

// The forms of a token cookie a request carries.
struct TokenCookieState {
  // The token is present as a single cookie.
  bool single_{false};
  // The chunk count cookie is present.
  bool chunks_{false};
  // The chunk count cookie is malformed, or a chunk it counts is missing or all of them are empty.
  bool malformed_{false};
  // The chunk count from a valid chunk count cookie, 0 when it is missing or malformed.
  size_t count_{0};
};
  // What decryptAndUpdateOAuthTokenCookies() found on the request for each token cookie, so
  // response writes delete the forms the client has without reading the rewritten request again.
  TokenCookieState bearer_token_cookie_state_;
  TokenCookieState id_token_cookie_state_;
  TokenCookieState refresh_token_cookie_state_;

By this way, then we could clearly know how to update the cookies

}

if (!tokenCookiesFit()) {
sendSecretsNotReadyResponse("OAuth token exceeds the cookie chunk limit");

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.

Please add a new function for this error. sendSecretsNotReadyResponse is not appropriate for it.

Comment on lines +1992 to +2011
const std::string encrypted_token = encryptToken(access_token_);
const std::string cookie_tail =
buildCookieTail(config_->bearerTokenCookieSettings(), expires_in_);
deleteRecordedTokenChunks(headers, cookie_names.bearer_token_,
config_->bearerTokenCookieSettings().path_, cookie_domain,
mayAddSecureAttributeForCookie(cookie_names.bearer_token_));
const std::optional<size_t> chunk_size =
tokenCookieDataSize(cookie_names.bearer_token_, cookie_tail, MaxCookieSize);
if (oauth2ChunkLargeTokenCookiesEnabled() && chunk_size.has_value() &&
encrypted_token.size() > chunk_size.value()) {
setCookie(headers, cookie_names.bearer_token_, "deleted",
fmt::format("; path={}; expires=Thu, 01 Jan 1970 00:00:00 GMT{}{}",
config_->bearerTokenCookieSettings().path_, cookie_domain,
mayAddSecureAttributeForCookie(cookie_names.bearer_token_)));
}
setTokenCookie(headers, cookie_names.bearer_token_, encrypted_token, cookie_tail);
} else if (hasTokenCookie(request_cookies, cookie_names.bearer_token_)) {
deleteTokenCookie(*request_headers_, headers, cookie_names.bearer_token_,
config_->bearerTokenCookieSettings().path_, cookie_domain,
mayAddSecureAttributeForCookie(cookie_names.bearer_token_));

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.

These code are redundant and I guess we have a format string for the cookie delete. Please don't use the plain string here.

Comment on lines +2015 to +2034
const std::string encrypted_token = encryptToken(id_token_);
const std::string cookie_tail =
buildCookieTail(config_->idTokenCookieSettings(), expires_id_token_in_);
deleteRecordedTokenChunks(headers, cookie_names.id_token_,
config_->idTokenCookieSettings().path_, cookie_domain,
mayAddSecureAttributeForCookie(cookie_names.id_token_));
const std::optional<size_t> chunk_size =
tokenCookieDataSize(cookie_names.id_token_, cookie_tail, MaxCookieSize);
if (oauth2ChunkLargeTokenCookiesEnabled() && chunk_size.has_value() &&
encrypted_token.size() > chunk_size.value()) {
setCookie(headers, cookie_names.id_token_, "deleted",
fmt::format("; path={}; expires=Thu, 01 Jan 1970 00:00:00 GMT{}{}",
config_->idTokenCookieSettings().path_, cookie_domain,
mayAddSecureAttributeForCookie(cookie_names.id_token_)));
}
setTokenCookie(headers, cookie_names.id_token_, encrypted_token, cookie_tail);
} else if (hasTokenCookie(request_cookies, cookie_names.id_token_)) {
deleteTokenCookie(*request_headers_, headers, cookie_names.id_token_,
config_->idTokenCookieSettings().path_, cookie_domain,
mayAddSecureAttributeForCookie(cookie_names.id_token_));

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.

see, similar code.

Comment on lines -1981 to +2293
cookies.erase(cookie_names.refresh_token_);
eraseTokenCookies(cookies, cookie_names.refresh_token_);

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.

after the decryptAndUpdateOAuthTokenCookies, the chunked cookies should have been merged. Do we actually need this changes?

Comment on lines -2017 to +2333
cookies.erase(cookie_names.bearer_token_);
cookies.erase(cookie_names.id_token_);
eraseTokenCookies(cookies, cookie_names.bearer_token_);
eraseTokenCookies(cookies, cookie_names.id_token_);
cookies.erase(cookie_names.oauth_hmac_);
cookies.erase(cookie_names.oauth_expires_);
cookies.erase(cookie_names.refresh_token_);
eraseTokenCookies(cookies, cookie_names.refresh_token_);

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.

ditto. do we need this changes?

@andy-fong

Copy link
Copy Markdown
Contributor

@wbpcode Thank you for the review. I may not have time to address the comment within a reasonable time frame and because of #43135 (comment), I start to feel may be it's better to do this chunking in a more generic way but also handle the typical token expires/refresh cases in a separate filter (probably dynamic module) at the top of the chain so it chunks on the way out and de-chunk first thing on the way in and all filters will work normally without being affected by the chunking.

@wbpcode

wbpcode commented Oct 6, 2026

Copy link
Copy Markdown
Member

@wbpcode Thank you for the review. I may not have time to address the comment within a reasonable time frame and because of #43135 (comment), I start to feel may be it's better to do this chunking in a more generic way but also handle the typical token expires/refresh cases in a separate filter (probably dynamic module) at the top of the chain so it chunks on the way out and de-chunk first thing on the way in and all filters will work normally without being affected by the chunking.

Thanks for all the great work! I or my colleague may could pick this up.

@kilitr

kilitr commented Oct 7, 2026 •

Copy link
Copy Markdown

I'd like to explore the separate cookie chunking filter.

Is this worth exploring here, or would you prefer a separate design issue?

htuch pushed a commit that referenced this pull request Oct 13, 2026
Browsers do not store a cookie larger than 4096 bytes. When an IdP
issues a large access, ID or refresh token, the browser silently drops
that cookie, the HMAC check fails on the next request, and the user is
redirected to the IdP again and again (#27875).

This adds an opt-in `OAuth2Config.token_cookie_chunking`. Setting it
turns chunking on; both limits are optional:

```yaml
config:
  token_cookie_chunking:
    max_cookie_size: 4096   # default; largest cookie written, name + value + attributes (512..4096)
    max_chunks: 8           # default; most cookies per token (2..16)
```

**Writing (only when `token_cookie_chunking` is set)**

1. A token that fits in one cookie is written as before, byte for byte.
2. A larger token is split into `<name>_0` .. `<name>_N-1` plus a
`<name>_chunks=N` count cookie. Every cookie stays within
`max_cookie_size`, including its name and attributes.
3. A token that needs more than `max_chunks` chunks gets a `503` before
any cookie is set, so the browser never stores a session it cannot send
back.

**Reading (always on)**

```mermaid
flowchart LR
  A["Cookie: X_0, X_1, X_chunks=2"] --> B["rejoin"]
  B --> C["decrypt"]
  C --> D["HMAC check"]
  D --> E["upstream sees X=token"]
```

1. Chunks are rejoined first in `decodeHeaders`, before decryption and
HMAC validation. The HMAC covers the decrypted value, so the rejoin has
to happen before decryption.
2. The chunk cookies are then replaced by a single cookie, so the rest
of the filter and the upstream do not need to know about chunks.
3. A malformed set (bad count, missing or empty chunk) is dropped and
the single cookie is used if there is one.
4. Up to 16 chunks (the API maximum) are read whatever `max_chunks` is
set to, so lowering it or removing the setting never breaks existing
sessions.

**Replacing old cookies:** every response deletes whatever form of a
token cookie the client sent that the new value does not overwrite:
stale chunks, a single cookie that is now chunked, or chunks that are
now a single cookie. Sign-out deletes chunks too. When the count is
malformed, it deletes all 16 possible indexes.

Notes:
- **Why opt-in config rather than a runtime guard:** as @yanavlasov
pointed out on #43135, chunking by default breaks rolling upgrades
because an older Envoy cannot read the chunks, and a runtime guard is
removed after a few releases, taking away the safe upgrade path. With
the field unset, nothing changes for existing users. Operators set it
once the whole fleet has this change. Removing it later is safe because
reading never depends on it.
- Several large tokens can together exceed the default
`max_request_headers_kb`. The API doc says so.
- Small fix along the way: deleting a token cookie named
`__Secure-`/`__Host-` now carries the `Secure` attribute, as sign-out
already did; browsers ignore the deletion otherwise.
- New counters: `oauth_token_cookie_chunked`,
`oauth_token_cookie_reassembled`, `oauth_token_cookie_malformed_chunks`,
`oauth_token_cookie_oversized`.

Supersedes #43135 and #47185. Thanks to @shashankram and @andy-fong for
the earlier work, and to @wbpcode for the implementation this is ported
from.

Risk Level: Low (opt-in; with the field unset, Envoy only additionally
reads chunked cookies, which it never wrote before, and adds `Secure` to
`__Secure-`/`__Host-` token cookie deletions)
Testing: Unit tests (chunking threshold, configured size/chunk limits,
chunk limit/503 on login and refresh, rejoin+decrypt, malformed sets,
sign-out deletion with domain/Secure, refresh replacing old cookie
forms, round trip through the real HMAC validator). Integration test for
a full login and replay with a 6000-byte token under both CBC and GCM.
Docs Changes: API docs for the new message; OAuth2 filter docs note and
stats.
Release Notes: Added under `new_features`.
Platform Specific Features: N/A
Fixes #27875
[Optional API Considerations:] New `TokenCookieChunking` message on
`OAuth2Config` (unset = off) with optional `max_cookie_size` (512..4096)
and `max_chunks` (2..16) limits.

AI assistance: this change was prepared with help from an AI coding
assistant. I reviewed and understand all of it.

---------

Signed-off-by: Anurag Aggarwal <[email protected]>
@andy-fong

Copy link
Copy Markdown
Contributor

@kanurag94 Thank you very much for picking this up in #48086.
This PR can be closed now.

@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had activity in the last 30 days. It will be closed in 7 days if no further activity occurs. Please feel free to give a status update now, ping for review, or re-open when it's ready. Thank you for your contributions!

@github-actions github-actions Bot added the stale stalebot believes this issue/PR has not been touched recently label Nov 12, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because it has not had activity in the last 37 days. Please feel free to give a status update now, ping for review, or re-open when it's ready. Thank you for your contributions!

@github-actions github-actions Bot closed this Nov 19, 2026

This branch had an error being deployed

1 failed deployment
external-contributors — c0cb79db Deployed Sep 11, 2026 by andy-fong via authorize #56036
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale stalebot believes this issue/PR has not been touched recently waiting

Projects

None yet

Development

Successfully merging this pull request may close these issues.

oauth2 filter: browser blocks BearerToken cookie because its size too large