Skip to content

fix: forward auth token only via account-scoped cookie - #3294

Merged
lemagnetic merged 2 commits into
3.xfrom
fix/my-account-auth-validation
May 6, 2026
Merged

lemagnetic merged 2 commits into
3.xfrom
fix/my-account-auth-validation

Conversation

@lemagnetic

@lemagnetic lemagnetic commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

What's the purpose of this pull request?

Logged-in shoppers were unable to access the FastStore My Account area: any navigation to /pvt/account/* resulted in an immediate redirect to /pvt/account/403?from=..., where the page entered an infinite refresh-token loop.

The root cause was on the API side. Every @auth-protected GraphQL query relies on vtexid.validate, and the request that backs that call was forwarding the auth token in two ways at once: once through the standard account-scoped cookie and again under a duplicated, top-level header. The duplicated header was being rejected by the platform with 401, even though the user's session was perfectly valid.

How it works?

This PR removes the duplication. The auth token is now forwarded exclusively through the account-scoped cookie (VtexIdclientAutCookie_{account}) — exactly like every other authenticated path in the codebase already does (see getAuthCookie, getJWTAutCookie, getIsRepresentative).

How to test it?

Pre-conditions: a logged-in shopper on a store that has FastStore My Account enabled (experimental.enableFaststoreMyAccount = true).

  • Navigate to /pvt/account/profile — should render the profile page directly, without redirecting to /pvt/account/403.

  • Run the package tests:

    pnpm --filter @faststore/api test

Starters Deploy Preview

Before

Gravacao.de.Tela.2026-05-05.as.19.26.38.mov

References

Summary by CodeRabbit

  • Bug Fixes

    • More reliable VTEX authentication: prefer updated account-scoped auth token when available and stop setting the unscoped auth header.
    • Simplified outgoing headers: only forward necessary headers and preserve base headers when no auth cookie is present.
  • Tests

    • Added integration tests covering cookie merging, auth token resolution, and forwarding behavior.

@lemagnetic lemagnetic added the hotfix Address critical bugs that need to be fixed immediately label May 4, 2026
@coderabbitai

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

VTEX auth handling now derives the validation token from the merged cookie set using getAuthCookie(getUpdatedCookie(ctx) ?? '', account) and sends it in the /api/vtexid/credential/validate POST body. getWithAutCookie was simplified to stop injecting VtexIdclientAutCookie and only forwards base headers while relying on the cookie header. Integration tests were added for both behaviors.

Changes

Auth Cookie Token Handling

Layer / File(s) Summary
Data / Helpers
packages/api/src/platforms/vtex/utils/cookies.ts
getWithAutCookie implementation changed; returned withAutCookie(forwardedHost: string, _account?: string) no longer sets VtexIdclientAutCookie and returns only content-type and X-FORWARDED-HOST, relying on cookie forwarding for auth.
Core Integration
packages/api/src/platforms/vtex/clients/commerce/index.ts
Imports getAuthCookie and getUpdatedCookie; vtexid.validate now computes token via getAuthCookie(getUpdatedCookie(ctx) ?? '', account) and sends body: JSON.stringify({ token }) instead of sourcing token from headers['VtexIdclientAutCookie'].
Tests / Verification
packages/api/test/integration/vtex.cookies.test.ts
Adds describe('getWithAutCookie', ...) asserting account-scoped auth cookie forwarded in cookie, unscoped VtexIdclientAutCookie header is not set, and base headers preserved. Adds describe('Auth token resolution from merged cookie set', ...) verifying getAuthCookie prefers storage-updated token and falls back to request cookie otherwise.

Sequence Diagram

sequenceDiagram
    participant Client
    participant API as FastStore API (ctx)
    participant Store as Cookie Store (getUpdatedCookie)
    participant Commerce as VTEX Commerce (vtexid.validate)

    Client->>API: HTTP request with cookie header
    API->>Store: getUpdatedCookie(ctx)
    Store-->>API: updated cookie set (maybe null)
    API->>API: getAuthCookie(mergedCookies, account)
    API->>Commerce: POST /api/vtexid/credential/validate { token }
    Commerce-->>API: validation response
    API-->>Client: response
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested Labels

bug

Suggested Reviewers

  • eduardoformiga
  • ommeirelles

Poem

🍪 Cookies shift and tokens wake,
Merged from storage for validation's sake;
Headers trimmed to only what's due,
A body token sent, clean and true —
Small changes keep the flow awake.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the core change: removing duplicate auth token forwarding and using only the account-scoped cookie instead.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/my-account-auth-validation

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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 and usage tips.

@codesandbox-ci

codesandbox-ci Bot commented May 4, 2026 •

Copy link
Copy Markdown

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.

@lemagnetic
lemagnetic marked this pull request as ready for review May 4, 2026 22:29
@lemagnetic
lemagnetic requested a review from a team as a code owner May 4, 2026 22:29
@lemagnetic
lemagnetic requested review from eduardoformiga and lucasfp13 and removed request for a team May 4, 2026 22:29

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/api/src/platforms/vtex/clients/commerce/index.ts`:
- Around line 740-748: The token is being extracted from the original request
cookies (ctx.headers?.cookie) but headers are created with withAutCookie(...)
and may contain an updated auth cookie; update the call to getAuthCookie to read
the merged cookie string from the headers created by withAutCookie (the same
HeadersInit used in the fetch) instead of ctx.headers?.cookie so
vtexid.validate() sends the current token; specifically, in the block where
headers is assigned and token is computed, replace using ctx.headers?.cookie
with the cookie value from headers (e.g., headers['cookie'] or
headers.get('cookie') depending on the HeadersInit shape) before passing it to
getAuthCookie.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b633c73f-79f5-4da0-8093-a5b4012d4d94

📥 Commits

Reviewing files that changed from the base of the PR and between 5a04cd8 and fafe6f7.

📒 Files selected for processing (3)
  • packages/api/src/platforms/vtex/clients/commerce/index.ts
  • packages/api/src/platforms/vtex/utils/cookies.ts
  • packages/api/test/integration/vtex.cookies.test.ts

@lemagnetic
lemagnetic changed the base branch from dev to main May 5, 2026 17:36
@lemagnetic
lemagnetic changed the base branch from main to dev May 5, 2026 17:38
@pkg-pr-new

pkg-pr-new Bot commented May 5, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/cli

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/components

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/core

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/graphql-utils

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/lighthouse

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/sdk

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/ui

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

commit: c699cfa

@lemagnetic
lemagnetic changed the base branch from dev to 3.x May 5, 2026 22:23
@lemagnetic
lemagnetic force-pushed the fix/my-account-auth-validation branch from 439acaa to c699cfa Compare May 5, 2026 23:31

@coderabbitai coderabbitai Bot left a comment

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.

🧹 Nitpick comments (1)
packages/api/test/integration/vtex.cookies.test.ts (1)

115-118: ⚡ Quick win

Avoid asserting the concrete HeadersInit shape in these tests.

The as Record<string, string> casts couple the suite to today’s implementation detail. Wrapping the result in new Headers(...) and asserting with .get() / .has() keeps the tests valid even if getWithAutCookie later returns a Headers instance instead of a plain object.

Example adjustment
-    const headers = withAutCookie(FORWARDED_HOST, ACCOUNT) as Record<
-      string,
-      string
-    >
+    const headers = new Headers(withAutCookie(FORWARDED_HOST, ACCOUNT))

-    expect(headers).toEqual({
-      'content-type': 'application/json',
-      'X-FORWARDED-HOST': FORWARDED_HOST,
-      cookie,
-    })
+    expect(headers.get('content-type')).toBe('application/json')
+    expect(headers.get('X-FORWARDED-HOST')).toBe(FORWARDED_HOST)
+    expect(headers.get('cookie')).toBe(cookie)

-    expect(headers).not.toHaveProperty('VtexIdclientAutCookie')
+    expect(headers.has('VtexIdclientAutCookie')).toBe(false)

As per coding guidelines, "Ensure type safety and avoid type assertions when possible".

Also applies to: 136-139, 151-154

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/api/test/integration/vtex.cookies.test.ts` around lines 115 - 118,
The tests currently cast the result of withAutCookie(FORWARDED_HOST, ACCOUNT) to
Record<string,string>, coupling tests to a concrete HeadersInit shape; instead,
construct a Headers object from the result (new Headers(...)) and assert using
headers.get(name) / headers.has(name) so the tests work whether withAutCookie
returns a plain object or a Headers instance—apply this change for the
occurrences around the withAutCookie call and the similar casts referenced (the
other usages in the same file).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/api/test/integration/vtex.cookies.test.ts`:
- Around line 115-118: The tests currently cast the result of
withAutCookie(FORWARDED_HOST, ACCOUNT) to Record<string,string>, coupling tests
to a concrete HeadersInit shape; instead, construct a Headers object from the
result (new Headers(...)) and assert using headers.get(name) / headers.has(name)
so the tests work whether withAutCookie returns a plain object or a Headers
instance—apply this change for the occurrences around the withAutCookie call and
the similar casts referenced (the other usages in the same file).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d4519e5c-2da3-430a-8104-9f3fcd3d0118

📥 Commits

Reviewing files that changed from the base of the PR and between 439acaa and c699cfa.

📒 Files selected for processing (3)
  • packages/api/src/platforms/vtex/clients/commerce/index.ts
  • packages/api/src/platforms/vtex/utils/cookies.ts
  • packages/api/test/integration/vtex.cookies.test.ts

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.

💯

* Headers for authenticated VtexID requests. The auth token is carried by
* the forwarded `cookie` header — not duplicated as a separate header.
*/
export const getWithAutCookie = (ctx: ContextForCookies) => {

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.

Does this function make sense yet? Looks like it does the same as getWithCookie now

@lemagnetic
lemagnetic merged commit f48c34b into 3.x May 6, 2026
5 checks passed
@lemagnetic
lemagnetic deleted the fix/my-account-auth-validation branch May 6, 2026 18:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hotfix Address critical bugs that need to be fixed immediately

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants