Repository navigation
oauth2: chunk large token cookies - #43135
shashankram wants to merge 11 commits into
Conversation
|
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. |
|
/coverage |
|
Coverage for this Pull Request will be rendered here: For comparison, current coverage on The coverage results are (re-)rendered each time the CI |
7d32431 to
6f17072
Compare
|
/coverage |
|
Coverage for this Pull Request will be rendered here: For comparison, current coverage on The coverage results are (re-)rendered each time the CI |
6f17072 to
0d6f26d
Compare
0d6f26d to
9f71400
Compare
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]>
9f71400 to
b4cd0b3
Compare
|
/retest |
|
/assign @bplotnick As codeowner to take a look |
|
@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 |
|
🙀 Error while processing event: |
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. |
|
waiting for addressing Yan's feedback. /wait |
|
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 |
|
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: Sending it to the upstream/jwt filter as a header instead of cookie works around the cookie chunking. |
Signed-off-by: Andy Fong <[email protected]>
Signed-off-by: Andy Fong <[email protected]>
|
Changes:
(Disclaimer: most of these are AI generated but I did go through each item and made sure I understood what's changed) |
Signed-off-by: Andy Fong <[email protected]>
|
@kanurag94 do you mind taking a look at the update when you get a chance? Thank you! |
| // 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); |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
WDYT about adding some stats counters on this?
| if (data.size() <= max_allowed_data_size.value()) { | ||
| setCookie(headers, key, data, cookie_tail); | ||
| return; |
There was a problem hiding this comment.
I think it splits even when the cookie size is 4094 as it subtracts 3 byte chunk. Is it intended?
kanurag94
left a comment
There was a problem hiding this comment.
overall lgtm, thanks for working on this!
|
Gentle ping from maintainer oncall @bplotnick @yanavlasov , since you are assigned to this PR |
wbpcode
left a comment
There was a problem hiding this comment.
Thanks for your contribution. This requirement self is reasonable. I added some comments. And @kanurag94 's comments also make sense for me.
/wait
| // 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); |
There was a problem hiding this comment.
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.
| 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"); | ||
| } |
There was a problem hiding this comment.
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; |
| std::string findTokenCookie(const absl::flat_hash_map<std::string, std::string>& cookies, | ||
| const std::string& key_prefix) const; |
There was a problem hiding this comment.
Seems this needn't to be a member of this class?
| // 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_; |
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
Please add a new function for this error. sendSecretsNotReadyResponse is not appropriate for it.
| 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_)); |
There was a problem hiding this comment.
These code are redundant and I guess we have a format string for the cookie delete. Please don't use the plain string here.
| 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_)); |
| cookies.erase(cookie_names.refresh_token_); | ||
| eraseTokenCookies(cookies, cookie_names.refresh_token_); |
There was a problem hiding this comment.
after the decryptAndUpdateOAuthTokenCookies, the chunked cookies should have been merged. Do we actually need this changes?
| 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_); |
There was a problem hiding this comment.
ditto. do we need this changes?
|
@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. |
|
I'd like to explore the separate cookie chunking filter. Is this worth exploring here, or would you prefer a separate design issue? |
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]>
|
@kanurag94 Thank you very much for picking this up in #48086. |
|
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! |
|
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! |
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