Skip to content

fix(api): apply @auth and @cacheControl to store schema extensions - #3524

Merged
lemagnetic merged 5 commits into
devfrom
fix/store-schema-directives
Nov 4, 2026
Merged

lemagnetic merged 5 commits into
devfrom
fix/store-schema-directives

Conversation

@lemagnetic

@lemagnetic lemagnetic commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

What's the purpose of this pull request?

Since v4, the @auth and @cacheControl directives have no effect on fields declared by a store in its GraphQL extensions (src/graphql/{vtex,thirdParty}/typeDefs). The annotation compiles and shows up in the schema, but the store resolver is never wrapped:

  • @auth doesn't validate the shopper session, so the field answers any caller;
  • @cacheControl doesn't contribute to the response cache-control header, so the route falls back to its default rule even when the field is annotated private.

Native FastStore fields are not affected. In v3 both directives worked on store fields, and the public guides (Authentication in API extensions, Displaying an order summary for the signed-in shopper) rely on that behavior.

The regression came with the v4 schema assembly (#3111): GraphqlVtexSchema applies the directive transformers to the native schema and merges the store schema afterwards, so store fields are never visited by the transformers.

How it works?

packages/api/src/platforms/vtex/index.ts — GraphqlVtexSchema

  1. Build the native executable schema with the directive definitions but without applying the transformers.
  2. If a store schema is passed, merge it (mergeSchemas, unchanged).
  3. Apply the transformers (cacheControl, then auth, same order as before so @auth runs first at request time) once, on the final schema.

This is the v3 semantics (one transformation over native + store fields). Two wrong variants were ruled out, and the tests catch both:

  • transforming the store schema before the merge: it carries the native type definitions but no native resolvers, so its wrappers would override the real native resolvers;
  • transforming again after the merge while keeping the pre-merge transformation: native fields would be wrapped twice (@auth would call VTEX ID twice per field).

packages/api/src/directives/{auth,cacheControl}.ts

The wrappers called originalResolver?.(...), so an annotated field with no explicit resolver always resolved to undefined. They now fall back to defaultFieldResolver. Native annotated fields all have resolvers (no change); this keeps store fields read from the parent object (e.g. a field of a store-owned type) working once the directives apply.

No public API change: GraphqlVtexSchema keeps its signature and call sites (@faststore/core, CLI type generation, api local server and tests are untouched). withDirectives stays exported and unchanged.

⚠️ Behavior change for stores

Stores that already annotate their fields will see the annotations take effect after upgrading, as in v3 and as documented:

  • @auth fields start returning 401 UnauthorizedError to signed-out callers;
  • @cacheControl fields start driving the cache-control header (still forced private when the auth cookie is present).

This should go in the release notes.

Authentication mechanism change — explicit human approval required

Per AGENTS.md (Security & Data Handling) and packages/api/AGENTS.md, changes to authentication mechanisms require explicit human approval recorded in the PR description.

  • Approved by: reviewer name / date

How to test it?

Automated — new packages/api/test/integration/directives.test.ts builds the final schema the same way getFinalAPISchema does in @faststore/core (native type defs + store type defs, store resolvers only, then GraphqlVtexSchema(storeSchema)) and checks:

  • store @auth: rejected without session (resolver not called), resolves with session;
  • store field with @auth and no resolver: returns the parent value once authorized;
  • store @cacheControl: sets the field policy; aggregates with a native field (min values, most restrictive scope);
  • @auth runs before @cacheControl on the same field;
  • native validateUser (with and without a store schema): keeps its resolver, rejects without session, validates the session exactly once.
cd packages/api
pnpm vitest run test/integration/directives.test.ts
pnpm test

Results:

  • on the current dev code, the 6 store tests fail and the 4 native tests pass (bug reproduced);
  • with the fix, all 10 pass and the full api suite is green (362 unit, 88 integration, no snapshot changes);
  • the tests fail against each of the wrong variants described above.

Manual (store) — in a store using the CodeSandbox build of this PR, add to src/graphql/thirdParty/typeDefs:

extend type Query {
  directiveProbeAuth: String @auth
  directiveProbeCache: String
    @cacheControl(scope: "private", sMaxAge: 7, staleWhileRevalidate: 11)
}

with resolvers returning any string, run faststore dev and POST /api/graphql without cookies:

Request Before (4.10.x) Expected with this PR
{ directiveProbeAuth } 200 with the resolver value 401 UnauthorizedError
{ directiveProbeCache } cache-control: no-cache, no-store cache-control: private, s-maxage=7, stale-while-revalidate=11
{ listCreditCards { ... } } (native control) 401 401 (unchanged)

Starters Deploy Preview

Validated on brandless.store with the CodeSandbox build of this PR (50f91f6a) against 4.10.0: all results matched the expected table above. Full before/after results: #3524 (comment)

References

  • Jira: SO-696
  • Regression origin: #3111 (v4 schema assembly); design introduced on canary in #3063
  • v3 reference: getFinalAPISchema in packages/core/src/server/index.ts applied [cacheControlDirective, authDirective] to the single native + store schema (last unaffected tag v3.100.5)

@lemagnetic
lemagnetic requested a review from a team as a code owner October 18, 2026 21:41
@lemagnetic
lemagnetic requested review from renatamottam and removed request for a team October 18, 2026 21:41
@lemagnetic lemagnetic added the bug Something isn't working label Oct 18, 2026
@lemagnetic lemagnetic added the bug Something isn't working label Oct 18, 2026
@coderabbitai

coderabbitai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: vtex/faststore/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Essentials
  • Run ID: d3cc0fb8-e55b-4bf3-8eca-d7a58cff6011
📥 Commits

Reviewing files that changed from the base of the PR and between 3f09177 and 50f91f6.

📒 Files selected for processing: 4
  • packages/api/src/directives/auth.ts
  • packages/api/src/directives/cacheControl.ts
  • packages/api/src/platforms/vtex/index.ts
  • packages/api/test/integration/directives.test.ts

Included review availability: This review used your included allowance. 4 included reviews remain after this review. Your included PR review attempts over the past 7 days set your current allowance at 5 reviews per hour.

Walkthrough

The auth and cache-control directives now resolve fields without custom resolvers through GraphQL’s default field resolver. The VTEX schema applies directive transformers after an optional schema merge. Integration tests cover store-extended and native fields.

Changes

GraphQL directives and schema composition

Layer / File(s) Summary
Directive resolver fallbacks
packages/api/src/directives/auth.ts, packages/api/src/directives/cacheControl.ts
Both directive wrappers use GraphQL’s default field resolver when a field has no custom resolver.
Schema composition and directive integration tests
packages/api/src/platforms/vtex/index.ts, packages/api/test/integration/directives.test.ts
The VTEX schema applies directive transformers after an optional schema merge. Integration tests cover authorization and cache-control behavior on store-extended and native fields.

Priority: ⬆️ High

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: eduardoformiga, matheusps

Merge Risk: ⚪ Minimal · up to 50f91

There is no established code issue blocking merge. Obtain the identified human approval for the intended authentication change.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
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.
Title check Passed The title clearly and concisely describes the main change: applying @auth and @cacheControl to store schema extensions.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@codesandbox-ci

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.

return (originalResolver ?? defaultFieldResolver)(
root,
args,
context,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[AGENTS.md:security-data-handling] 🟡 RESTRICT

This PR changes the behavior of the @auth directive's resolver-wrapping logic (falling back to defaultFieldResolver) and changes when/how the auth transformer is composed relative to schema merging in packages/api/src/platforms/vtex/index.ts. The repository's AGENTS.md states that 'Modifications to authentication, CSRF, or CSP mechanisms require explicit human approval recorded in the PR description.' There is no indication in the provided diff/PR context that this approval was recorded.

Action: Confirm explicit human approval for the authentication-mechanism change is recorded in the PR description per AGENTS.md before merging.
Source: AGENTS.md § Security & Data Handling

To dismiss: reply /dk-review dismiss [reason] under this comment

@dk-pr-review

dk-pr-review Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

DK Review — Audit Summary

Verdict: ⚠️ RESTRICTED

Severity Count
BLOCK 0
RESTRICT 3
SUGGEST 1

Only BLOCK and RESTRICT findings anchored to a changed line are commented inline on the diff. The other finding below opens no review thread.

Scenarios evaluated: feature-flags, general-review, quality-ratchet
Scenarios skipped: dependency-governance (no matching files), pipeline-config (no matching files), agent-skills-review (no matching files)

⚠️ Governance warnings: Large PR detected (12 files) — review coverage may be incomplete


📋 Findings (4)

RESTRICT

  1. [agents-md.security-approval] packages/api/src/platforms/vtex/utils/auth.ts:74 — This PR changes core authentication behavior — it adds per-request caching of the VTEX ID validation result (ctx.storage.userAuthentication) and restructures how the @auth directive wraps resolvers (packages/api/src/directives/auth.ts). AGENTS.md's Security & Data Handling section states: 'Modifications to authentication, CSRF, or CSP mechanisms require explicit human approval recorded in the PR description.' Nothing in the diff indicates that approval was recorded.
    → Confirm the PR description records explicit human approval for the authentication changes in auth.ts and utils/auth.ts, per the root AGENTS.md governance rule.
    Source: AGENTS.md#security--data-handling
  2. [agents-md.security-approval-required] packages/api/src/directives/auth.ts:21 — This PR substantively changes how the @auth directive is applied and enforced: it fixes a prior bug where @auth on store-schema-extended fields (extend type Query, custom types) was never enforced because directives were transformed before merging with the store schema (see packages/api/src/platforms/vtex/index.ts), adds a dedup/marking mechanism for resolver wrapping (applied.ts), and introduces per-request memoization of session validation (utils/auth.ts). AGENTS.md's Security & Data Handling section states 'Modifications to authentication, CSRF, or CSP mechanisms require explicit human approval recorded in the PR description,' and this is exactly such a modification.
    → Confirm explicit human approval for this authentication-behavior change is recorded in the PR description before merging, per the root AGENTS.md governance rule.
  3. [agents-md.security-approval] packages/api/test/integration/directives.test.ts:1 — This new test suite exercises authorization semantics in depth (ordering of @auth vs @CacheControl, idempotent directive re-application, session-validation caching across multiple protected fields), which strongly implies the @auth/authorization directive implementation itself was modified in this PR (the actual source files aren't in the reviewed diff slice). AGENTS.md's Security & Data Handling section requires that 'modifications to authentication, CSRF, or CSP mechanisms require explicit human approval recorded in the PR description,' and the Agent Autonomy Boundaries section lists modifying authentication/authorization as forbidden without explicit human approval.
    → Confirm in the PR description that the auth-directive implementation changes were reviewed and explicitly approved by a human maintainer, per AGENTS.md's Security & Data Handling and Agent Autonomy Boundaries sections.

SUGGEST

  1. [Evolvability.SolutionApproach] packages/api/src/directives/applied.ts:9 — The 'already applied' marker uses a local Symbol('faststore.appliedDirectives'). If two separate module instances of @faststore/api ever get loaded in the same process (e.g. the package's own dual ESM/CJS output being pulled in two different ways, or a dependency-hoisting mismatch), each instance creates its own distinct Symbol, so hasAppliedDirective would always return false across that boundary — silently reintroducing the double-wrapping / double VTEX-ID-validation bug this mechanism exists to prevent.
    → Use Symbol.for('faststore.appliedDirectives') (the global symbol registry) so the marker is shared across any module realm.

DK Review v1.0.0 | To contest a finding, reply in its thread

@lemagnetic

Copy link
Copy Markdown
Contributor Author

✅ Store validation (brandless.store)

Validated on a real store, comparing the published 4.10.0 with this PR's CodeSandbox build (50f91f6a, 4.10.1-dev.0). @faststore/cli, core and api all resolved to pkg.csb.dev/vtex/faststore/commit/50f91f6a/... (no npm copies), and the installed code contains the fix.

Setup: store extension in src/graphql/thirdParty/typeDefs/directiveProbe.graphql, yarn dev, POST /api/graphql without cookies or tokens.

type DirectiveProbeObject {
  secret: String @auth # no field resolver on purpose
  plain: String
}

extend type Query {
  directiveProbeAuth: String @auth
  directiveProbeCache: String
    @cacheControl(scope: "private", sMaxAge: 7, staleWhileRevalidate: 11)
  directiveProbeObject: DirectiveProbeObject
}
Request 4.10.0 (before) This PR (after)
{ directiveProbeAuth } 200 {"directiveProbeAuth":"auth-ok"}, no-cache, no-store, no VTEX ID call 401 UnauthorizedError, no-store, one VTEX ID validate call
{ directiveProbeCache } 200, no-cache, no-store 200, private, s-maxage=7, stale-while-revalidate=11
{ directiveProbeObject { secret plain } } 200 with "secret":"parent-secret" 401 UnauthorizedError, secret not returned
{ directiveProbeObject { plain } } — 200 {"plain":"parent-plain"}
{ listCreditCards { __typename } } (native @auth) 401, one VTEX ID call 401, one VTEX ID call (unchanged)
{ allProducts(first: 1) { ... } } (native catalog) 200, public, s-maxage=300, stale-while-revalidate=3600 identical
{ allProducts(first: 1) { ... } directiveProbeCache } 200, public, s-maxage=300, stale-while-revalidate=3600 200, private, s-maxage=7, stale-while-revalidate=11

Notes:

  • The mixed query is the clearest symptom of the regression: on 4.10.0 a store field annotated private was served with a public shared-cache policy when selected together with a catalog field. With this PR the most restrictive policy wins, as for native fields.
  • When a protected field fails, the whole response is 401 (not a partial error). That is the existing route behavior for any FastStoreError and matches native @auth fields; not changed here.
  • Native fields: same responses and exactly one VTEX ID validate call per protected request (no double wrapping).
  • Home and a PLP (/computadores-e-software) render identically on both sides (same products, order and prices), with no new errors in the yarn dev output.

@@ -21,7 +21,12 @@ const directive: Directive = {
await validateUserAuthentication(context)

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.

With this change @auth works on nested store fields (the new test covers ProbeObject.secret), but validateUserAuthentication calls commerce.vtexid.validate() on every resolve and nothing memoizes it per request.

If a store has orders: [Order] with @auth on Order.secret, a query returning 50 orders makes 50 POSTs to /api/vtexid/credential/validate. Each extra root @auth field in the same operation adds another call. Could we cache the validation promise on the request context (e.g. in ctx.storage) and reuse it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 303e4b884. validateUserAuthentication stores its promise on ctx.storage.userAuthentication and every later @auth field in the same request awaits that promise. The assignment happens before the first await, so sibling fields started in the same tick share one call.

The new api test selects probeAuth, validateUser and three probeOrders.secret fields (no field resolver) and expects a single validate call. The core test sees one POST /api/vtexid/credential/validate for probeAuth.

// schema first overrides native resolvers with wrappers around nothing.
const schema =
mergeSchema && isSchema(mergeSchema)
? mergeSchemas({ schemas: [platformSchema, mergeSchema] })

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.

If mergeSchema was already transformed, mergeSchemas keeps its wrapped resolvers and the reduce below wraps them again. That happens with GraphqlVtexSchema(GraphqlVtexSchema()), or when a consumer builds its extension schema with withDirectives, which is still public and was a plausible v4 workaround for this exact bug. Every @auth field then validates the session twice per resolve. Before this PR the resolvers from the second schema won, so they were wrapped only once.

It's probably enough to document that mergeSchema must be untransformed, or to mark wrapped resolvers so they aren't wrapped twice.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 303e4b884. Each wrapper marks the resolver with the directive name (directives/applied.ts). A second pass, including GraphqlVtexSchema(GraphqlVtexSchema(schema)), sees the mark and leaves the resolver as it is. mergeSchemas keeps the function reference, so the mark survives the merge.

The test asserts @auth stays wrapped once, @auth + @cacheControl twice, and validateUser still returns { isValid: true } with one validation call.


// Continue with the original resolver
return originalResolver?.(root, args, context, info)
return (originalResolver ?? defaultFieldResolver)(

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.

Rollout concern: stores that already annotate fields (as the docs say to) and use them in getStaticProps or other server-side queries will start throwing UnauthorizedError there, since those requests have no auth cookie. So the build or ISR revalidation fails and the page returns 500, which is worse than a 401 on a client call.

A release note may not be enough here. Would an opt-in flag or a documented migration step work? A ! / BREAKING CHANGE marker would also get it into the Lerna changelog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I would not add an opt-in flag. Stores that don't turn it on would keep the v4 bug, which is an @auth annotation that compiles and does nothing. The behavior this restores is the one v3 had and the one the public guides already describe.

A ! / BREAKING CHANGE footer would also make lerna version --conventional-commits cut 5.0.0 for every package, since versions are synchronized. The release note is the right place. The migration for the case you described: a getStaticProps / ISR query must not select a store field annotated @auth, because that request has no shopper cookie. Those fields belong on a client request that sends the cookie. I'll put that in the release note.

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.

Not introduced here, but now more visible: both transformers only map MapperKind.OBJECT_FIELD, so a directive on an interface field never reaches the object types that implement it.

A store that writes interface Secretive { secret: String @auth } and type Foo implements Secretive { secret: String } gets no protection on Foo.secret, and nothing warns about it. Since this PR makes store directives work again, it may be worth propagating interface field directives to the implementers or documenting the limitation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Documented on applyDirectives in directives/index.ts, rather than copying the directive onto implementors. GraphQL does not inherit a field directive from an interface field to the object fields that implement it, and copying it here would be a new behavior (a store could implement the field and not want the annotation). The note says to put @auth / @cacheControl on the object field. Happy to do the propagation in a follow-up if we decide we want it.

const validate = vi.fn()

/** Builds the final schema the same way `getFinalAPISchema` does in `@faststore/core`. */
const buildStoreSchema = () => {

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.

buildStoreSchema copies the assembly from core's getFinalAPISchema, so the real path (generated typeDefs, envelop + graphql-jit, extensions.cacheControl and the cache-control header) still has no regression test. If getFinalAPISchema changes later, say it starts transforming the store schema itself, these tests keep passing while store directives stop applying again, the same way the v4 regression slipped through.

A test in packages/core/test/server that runs a store @auth / @cacheControl field through execute would cover it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added packages/core/test/server/storeDirectives.test.ts. It feeds a store extension through the real loadFilesSync + third-party resolvers path and runs both fields through server execute (envelop and graphql-jit).

probeCache comes back with extensions.cacheControl of { private, sMaxAge: 7, staleWhileRevalidate: 11 }, and stringifyCacheControl of that value is the header the route sets. probeAuth returns null, does not run the store resolver, and makes one POST /api/vtexid/credential/validate.

const directives = [cacheControlDirective, authDirective]

const platformSchema = withCacheControl(getResolvers(), typeDefs)
export function GraphqlVtexSchema(mergeSchema?: GraphQLSchema) {

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.

This now repeats what withDirectives does (merge the directive typeDefs, makeExecutableSchema, reduce over the transformers), and withDirectives stays exported with no internal user. The two copies already differ a bit (transformer?.(schema) ?? schema vs transformer(finalSchema)).

Suggestion: split directives/index.ts into a build step and an applyDirectives(schema, directives) step, let withDirectives compose them, and call applyDirectives here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 303e4b884. directives/index.ts now has executableSchemaWithDirectiveDefinitions (SDL + makeExecutableSchema, no transformers) and applyDirectives. withDirectives composes the two, and GraphqlVtexSchema calls them separately so the merge can sit in between. withDirectives stays exported with the same signature.

: platformSchema

return platformSchema
return directives.reduce(

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.

Minor perf note: core calls GraphqlVtexSchema() only to get the native typeDefs for mergeTypeDefs, so this runs makeExecutableSchema and two full mapSchema passes whose result is thrown away. Then GraphqlVtexSchema(schema) builds the native schema again. The same happens in the CLI generate-types.

If core merged an untransformed source instead (the directive typeDefs plus the already exported typeDefs), the transform would only run once, in the final call.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 303e4b884. platformTypeDefs is the native SDL plus the directive definitions, with no resolvers and no transformers. getFinalAPISchema merges that with the generated schema, and generate-types prints it. The transformers run only in the final GraphqlVtexSchema(schema) call.

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.

Process note: this changes where and how @auth is enforced. Root AGENTS.md says "Modifications to authentication, CSRF, or CSP mechanisms require explicit human approval recorded in the PR description", and packages/api/AGENTS.md repeats it. Could you add that approval to the description?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added a section to the description, "Authentication mechanism change — explicit human approval required", with an "Approved by" checkbox. I can't check it myself. Could you (or Renata) record the approval there when the review is done?

lemagnetic and others added 2 commits October 29, 2026 12:41
Since v4, GraphqlVtexSchema applied the directive transformers to the
native schema only and merged the store schema afterwards, so store
fields annotated with @auth or @CacheControl were never wrapped: @auth
did not validate the shopper session and @CacheControl did not
contribute to the response cache-control header.

The native schema is now built without transformers, merged with the
store schema, and the transformers run once on the final schema (the v3
behavior). The transformers also fall back to the default field
resolver, so annotated fields without an explicit resolver keep
returning the parent value.

Behavior change for stores: @auth and @CacheControl annotations on store
fields are enforced again, as in v3 and as the docs describe.

Co-authored-by: Cursor <[email protected]>
…once

Review follow-up. @auth now shares one VTEX ID validation promise on the
request context, so a list of protected fields does not call credential/validate
once per item. Resolvers that are already wrapped are not wrapped again.
The native SDL is exported as platformTypeDefs so core and the CLI do not
build and discard a transformed schema just to read type definitions.

Co-authored-by: Cursor <[email protected]>
@lemagnetic
lemagnetic force-pushed the fix/store-schema-directives branch from 50f91f6 to 303e4b8 Compare October 29, 2026 17:39
@pkg-pr-new

pkg-pr-new Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

npm i https://pkg.pr.new/vtex/faststore/@faststore/api@f428b72

@faststore/cli

npm i https://pkg.pr.new/vtex/faststore/@faststore/cli@f428b72

@faststore/components

npm i https://pkg.pr.new/vtex/faststore/@faststore/components@f428b72

@faststore/core

npm i https://pkg.pr.new/vtex/faststore/@faststore/core@f428b72

@faststore/diagnostics

npm i https://pkg.pr.new/vtex/faststore/@faststore/diagnostics@f428b72

@faststore/lighthouse

npm i https://pkg.pr.new/vtex/faststore/@faststore/lighthouse@f428b72

@faststore/sdk

npm i https://pkg.pr.new/vtex/faststore/@faststore/sdk@f428b72

@faststore/ui

npm i https://pkg.pr.new/vtex/faststore/@faststore/ui@f428b72

commit: f428b72

@@ -1,5 +1,5 @@
import { saveFile } from './file'
import { GraphqlVtexSchema } from '@faststore/api'
import { platformTypeDefs } from '@faststore/api'

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.

This import breaks the CLI tests: generate-types.test.ts still mocks @faststore/api with only GraphqlVtexSchema, so the 3 genTsTypes tests fail with No "platformTypeDefs" export is defined on the "@faststore/api" mock (Linux and Windows jobs). Returning platformTypeDefs: parse('type Query { ping: Boolean }') from the vi.mock factory should fix it, and the GraphqlVtexSchema entry can go.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in b8b7e2f8b. The vi.mock factory now returns only platformTypeDefs: parse('type Query { ping: Boolean }'), with no GraphqlVtexSchema entry. The full CLI suite passes locally (19 files, 200 tests, 13 of them in generate-types). Thanks for catching it.

@lariciamota

Copy link
Copy Markdown
Contributor

@lemagnetic code looks good to me now. Before I approve, could you rerun the brandless.store smoke test on the final commit (2a10b7d, pkg.pr.new build)? The earlier run was on 50f91f6a, and 303e4b884 changed getFinalAPISchema in core and the CLI type generation (both now use platformTypeDefs), so I'd like to see the same before/after table on the build we're merging. A query that selects two @auth fields would also be useful, to confirm a single VTEX ID validate call in a real store.

@sonar-workflows

Copy link
Copy Markdown

}

ctx.storage.userAuthentication ??= validateUserAuthenticationOnce(ctx)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[agents-md.security-approval] 🟡 RESTRICT

This PR changes core authentication behavior — it adds per-request caching of the VTEX ID validation result (ctx.storage.userAuthentication) and restructures how the @auth directive wraps resolvers (packages/api/src/directives/auth.ts). AGENTS.md's Security & Data Handling section states: 'Modifications to authentication, CSRF, or CSP mechanisms require explicit human approval recorded in the PR description.' Nothing in the diff indicates that approval was recorded.

Action: Confirm the PR description records explicit human approval for the authentication changes in auth.ts and utils/auth.ts, per the root AGENTS.md governance rule.
Source: AGENTS.md#security--data-handling

To contest this finding, reply in this thread

const authDirective = getDirective(schema, fieldConfig, NAME)?.[0]

if (authDirective) {
if (hasAppliedDirective(fieldConfig.resolve, NAME)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[agents-md.security-approval-required] 🟡 RESTRICT

This PR substantively changes how the @auth directive is applied and enforced: it fixes a prior bug where @auth on store-schema-extended fields (extend type Query, custom types) was never enforced because directives were transformed before merging with the store schema (see packages/api/src/platforms/vtex/index.ts), adds a dedup/marking mechanism for resolver wrapping (applied.ts), and introduces per-request memoization of session validation (utils/auth.ts). AGENTS.md's Security & Data Handling section states 'Modifications to authentication, CSRF, or CSP mechanisms require explicit human approval recorded in the PR description,' and this is exactly such a modification.

Action: Confirm explicit human approval for this authentication-behavior change is recorded in the PR description before merging, per the root AGENTS.md governance rule.

To contest this finding, reply in this thread

@@ -0,0 +1,237 @@
import { mergeTypeDefs } from '@graphql-tools/merge'
import { makeExecutableSchema } from '@graphql-tools/schema'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[agents-md.security-approval] 🟡 RESTRICT

This new test suite exercises authorization semantics in depth (ordering of @auth vs @CacheControl, idempotent directive re-application, session-validation caching across multiple protected fields), which strongly implies the @auth/authorization directive implementation itself was modified in this PR (the actual source files aren't in the reviewed diff slice). AGENTS.md's Security & Data Handling section requires that 'modifications to authentication, CSRF, or CSP mechanisms require explicit human approval recorded in the PR description,' and the Agent Autonomy Boundaries section lists modifying authentication/authorization as forbidden without explicit human approval.

Action: Confirm in the PR description that the auth-directive implementation changes were reviewed and explicitly approved by a human maintainer, per AGENTS.md's Security & Data Handling and Agent Autonomy Boundaries sections.

To contest this finding, reply in this thread

@lemagnetic

Copy link
Copy Markdown
Contributor Author

@lariciamota reran the brandless.store smoke test on the PR head, f428b728d (pkg.pr.new, 4.11.1-dev.0). That's 2a10b7d plus the dev merge, which doesn't touch any file of this fix. Baseline is the published 4.11.0. @faststore/cli, core and api all resolved to pkg.pr.new/.../@f428b728d… with no npm copies, and the installed code has platformTypeDefs (used by core's getFinalAPISchema and by the CLI), the per-request ctx.storage.userAuthentication and the faststore.appliedDirectives mark.

Generation: on both sides, the store fields are in .faststore/@generated/schema.graphql and graphql.ts, and @auth / @cacheControl are defined once.

Same store extension as before (directiveProbeAuth @auth, directiveProbeCache @cacheControl(private, 7, 11), DirectiveProbeObject.secret @auth with no field resolver). No cookies. validate = calls to /api/vtexid/credential/validate in the yarn dev log during the request.

Query 4.11.0 f428b728d
{ directiveProbeAuth } 200 auth-ok, 0 validate 401 UnauthorizedError, 1 validate
{ directiveProbeCache } no-cache, no-store private, s-maxage=7, stale-while-revalidate=11
{ directiveProbeObject { secret plain } } 200 parent-secret, 0 validate 401, no parent-secret, 1 validate
{ listCreditCards } (control) 401, 1 validate 401, 1 validate
{ allProducts } (control) 200, public, s-maxage=300, stale-while-revalidate=3600 same
{ allProducts directiveProbeCache } public, s-maxage=300, … private, s-maxage=7, stale-while-revalidate=11
{ listCreditCards validateUser } 401, 2 validate 401, 1 validate
{ directiveProbeAuth directiveProbeObject { secret } } 200 auth-ok + parent-secret, 0 validate 401, 1 validate
{ directiveProbeAuth validateUser } 401, 1 validate (native field only) 401, 1 validate

With two @auth fields in one request (native, store or mixed), the build makes exactly one VTEX ID validate call, and both fields fail from that shared result (two UnauthorizedError in the log). Home and a PLP render the same on both sides, with no new errors. The earlier run on 50f91f6a is here.

@lemagnetic
lemagnetic merged commit f6abd0d into dev Nov 4, 2026
14 of 16 checks passed
@lemagnetic
lemagnetic deleted the fix/store-schema-directives branch November 4, 2026 14:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants