Repository navigation
fix: normalize set cookies domain host - SFS-3034 - #3190
Conversation
- Introduced functions to normalize cookie domains based on request host. - Added checks to ensure cookies are set with the correct domain for allowed hosts. - Replaced the previous domain replacement logic with a more robust implementation to improve cookie handling in development and production environments.
WalkthroughThe GraphQL API endpoint's Set-Cookie handling was refactored to introduce host-based domain normalization. A validation pipeline (hostname extraction, eligibility check, allowed-suffix match) now drives unconditional normalization of Set-Cookie headers when conditions are met, replacing the previous environment-gated replacement. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Client as Client
participant API as GraphQL API (packages/core/src/pages/api/graphql.ts)
participant Upstream as Upstream Service/Origin
Client->>API: HTTP request (Host header)
API->>Upstream: Proxy / fetch GraphQL request
Upstream-->>API: HTTP response (may include Set-Cookie headers)
API->>API: getRequestHostname(host header)
API->>API: shouldReplaceCookieDomain(cookie, hostname)
API->>API: isAllowedHost(hostname, ALLOWED_HOST_SUFFIXES)
API->>API: normalizeSetCookieDomain(if allowed & different)
API-->>Client: HTTP response with normalized or original Set-Cookie headers
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/core/src/pages/api/graphql.ts`:
- Around line 58-84: normalizeSetCookieDomain can trigger a 500 if
getRequestHostname (which uses new URL internally) throws for empty/malformed
Host; wrap the host extraction in a try/catch or otherwise validate the host and
on error or invalid host simply return the original setCookie to skip
normalization. Specifically, in normalizeSetCookieDomain (and/or in
getRequestHostname) guard the call to getRequestHostname({ request }) so that
any exception results in returning setCookie unchanged, and only proceed to call
isAllowedHost and shouldReplaceCookieDomain when host is a well-formed,
non-empty string.
| MATCH_DOMAIN_REGEXP, | ||
| `; domain=${faststoreAPIHostname}` | ||
| ) | ||
| const getRequestHostname = ({ request }: { request: NextApiRequest }) => |
There was a problem hiding this comment.
pq não usar o $request.headers.host diretamente sem montar e desconstruir uma url?
There was a problem hiding this comment.
Usamos new URL(...).hostname para normalizar o host e remover porta/ruído. request.headers.host pode vir como localhost:3000 ou incluir porta no caso de testes que alteram o apontamento do localhost no arquivo de hosts, e o cookie Domain não aceita porta. A extração via URL garante um hostname consistente e evita comparar example.com:3000 com example.com.
|
|
||
| const DEFAULT_MAX_AGE = 5 * 60 // 5 minutes | ||
| const DEFAULT_STALE_WHILE_REVALIDATE = 60 * 60 // 1 hour | ||
| const ALLOWED_HOST_SUFFIXES = ['localhost', '.vtex.app', '.localhost'] |
There was a problem hiding this comment.
pra que serve exatamenta a allow list? como fica o cenário do dominio de produção do cliente?
- Enhanced the `getRequestHostname` function to handle missing or malformed host headers gracefully. - Added error handling to ensure the function returns null when the host is invalid, improving robustness in cookie domain normalization.
## What's the purpose of this pull request? - This PR fixes a historical issue with setCookie across domains other than the production domain. <img width="500" alt="Screenshot 2026-01-28 at 17 56 17" src="https://github.com/user-attachments/assets/677f9f03-d4fd-41cc-96d2-922c16cb358f" /> <img width="300" alt="Screenshot 2026-01-28 at 17 59 17" src="https://github.com/user-attachments/assets/d958548c-8f15-41c6-8451-bf5789544ef0" /> - It also fixes the bug that keeps `validateCartMutation` in a loop on preview URLs due to setCookie issues.  ## How does it work? - Introduced functions to normalize cookie domains based on the request host. - Added checks to ensure cookies are set with the correct domain for allowed hosts, including localhost and preview URLs. - Replaced the previous domain replacement logic with a more robust implementation to improve cookie handling in development and production environments. ## How to test it? ### Starters Deploy Preview - Double check if the `set-cookie` from the response header of `validateCartMutation` across the different URLs: localhost, preview (ending with `vtex.app`), and production are working as expected. - Also check that the `validateCartMutation` is not looping anymore. | Environment | | |--------|--------| | localhost ✅ | <img width="761" height="72" alt="Screenshot 2026-01-28 at 18 57 58" src="https://github.com/user-attachments/assets/3cbe66af-40b8-4e6e-8de0-051514b0bcfc" /> | | [preview](https://sfj-827e0df--b2bfaststoredev.preview.vtex.app/) ✅ | <img width="917" height="71" alt="Screenshot 2026-01-28 at 19 12 39" src="https://github.com/user-attachments/assets/784c42ee-b618-412f-8220-5063886ef166" /> | | [prod](https://b2bfaststore.vtexfaststore.com/) ✅ | <img width="890" height="47" alt="Screenshot 2026-01-28 at 19 23 27" src="https://github.com/user-attachments/assets/4b445d96-0839-47cc-88df-d73281b3b180" />| <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved Set-Cookie domain handling: cookie domains are now normalized based on the request host to prevent mismatched cookie scopes when accessing the app from different hosts. * Domain normalization is applied consistently (no longer toggled by environment), reducing inconsistent cookie behavior across deployments. <sub>✏️ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…ts (SFS-3034) ## Root Cause Two factors combined to create an infinite loop in preview environments (*.preview.vtex.app): 1. Cookie domain normalization in BFF ignored `x-forwarded-host` header: In preview infrastructure, the public hostname is delivered in `x-forwarded-host`, not `request.headers.host`. The cookie normalization logic failed silently, returning cookies with the wrong domain. Browsers rejected them due to domain mismatch (RFC 6265), leaving no session cookie. 2. Fallback to `order?.orderNumber` was removed in PR vtex#3178: Without a cookie, the resolver had no fallback and passed `id: undefined` to create a new orderForm on every request. Each response provided a new orderFormId, triggering an infinite validation loop (~94 requests in 26s). ## Fixes 1. **Header priority fix** (`@faststore/core`): Check `x-forwarded-host` before `request.headers.host` when normalizing cookie domains. This ensures preview environments (where the public hostname is in `x-forwarded-host`) correctly rewrite cookie domains. 2. **Defensive fallback** (`@faststore/api`): Reintroduce fallback to `order?.orderNumber` when `orderFormIdFromCookie` is absent. This protects against cookie delivery issues and provides resilience in environments with cookie restrictions. ## Impact - Fixes infinite loop in preview/QA environments - No impact on production (custom domains continue to work) - Minimal risk: both changes restore defensive patterns that existed in v3.93.x ## References - Regression introduced by: PR vtex#3178 (Jan 21, 2026) - Incomplete fix attempt: PR vtex#3190 (Feb 2, 2026 - didn't handle x-forwarded-host) - Related issue: vtex#3188 (prematurely closed) - Customer ticket: #1467584 / SO-686
What's the purpose of this pull request?
validateCartMutationin a loop on preview URLs due to setCookie issues.How does it work?
How to test it?
Starters Deploy Preview
set-cookiefrom the response header ofvalidateCartMutationacross the different URLs: localhost, preview (ending withvtex.app), and production are working as expected.validateCartMutationis not looping anymore.Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.