Repository navigation
fix(api): apply @auth and @cacheControl to store schema extensions - #3524
Conversation
|
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, |
There was a problem hiding this comment.
[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 Review — Audit SummaryVerdict:
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
📋 Findings (4)RESTRICT
SUGGEST
DK Review v1.0.0 | To contest a finding, reply in its thread |
✅ Store validation (brandless.store)Validated on a real store, comparing the published 4.10.0 with this PR's CodeSandbox build ( Setup: store extension in 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
}
Notes:
|
| @@ -21,7 +21,12 @@ const directive: Directive = { | |||
| await validateUserAuthentication(context) | |||
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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] }) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 = () => { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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?
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]>
50f91f6 to
303e4b8
Compare
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/diagnostics
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
| @@ -1,5 +1,5 @@ | |||
| import { saveFile } from './file' | |||
| import { GraphqlVtexSchema } from '@faststore/api' | |||
| import { platformTypeDefs } from '@faststore/api' | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
|
@lemagnetic code looks good to me now. Before I approve, could you rerun the brandless.store smoke test on the final commit ( |
|
| } | ||
|
|
||
| ctx.storage.userAuthentication ??= validateUserAuthenticationOnce(ctx) | ||
|
|
There was a problem hiding this comment.
[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)) { |
There was a problem hiding this comment.
[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' | |||
There was a problem hiding this comment.
[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
|
@lariciamota reran the brandless.store smoke test on the PR head, Generation: on both sides, the store fields are in Same store extension as before (
With two |

0 New Issues
0 Fixed Issues
0 Accepted Issues
What's the purpose of this pull request?
Since v4, the
@authand@cacheControldirectives 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:@authdoesn't validate the shopper session, so the field answers any caller;@cacheControldoesn't contribute to the responsecache-controlheader, so the route falls back to its default rule even when the field is annotatedprivate.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):
GraphqlVtexSchemaapplies 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—GraphqlVtexSchemamergeSchemas, unchanged).cacheControl, thenauth, same order as before so@authruns 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:
@authwould call VTEX ID twice per field).packages/api/src/directives/{auth,cacheControl}.tsThe wrappers called
originalResolver?.(...), so an annotated field with no explicit resolver always resolved toundefined. They now fall back todefaultFieldResolver. 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:
GraphqlVtexSchemakeeps its signature and call sites (@faststore/core, CLI type generation, api local server and tests are untouched).withDirectivesstays exported and unchanged.Stores that already annotate their fields will see the annotations take effect after upgrading, as in v3 and as documented:
@authfields start returning401 UnauthorizedErrorto signed-out callers;@cacheControlfields start driving thecache-controlheader (still forcedprivatewhen 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) andpackages/api/AGENTS.md, changes to authentication mechanisms require explicit human approval recorded in the PR description.How to test it?
Automated — new
packages/api/test/integration/directives.test.tsbuilds the final schema the same waygetFinalAPISchemadoes in@faststore/core(native type defs + store type defs, store resolvers only, thenGraphqlVtexSchema(storeSchema)) and checks:@auth: rejected without session (resolver not called), resolves with session;@authand no resolver: returns the parent value once authorized;@cacheControl: sets the field policy; aggregates with a native field (min values, most restrictive scope);@authruns before@cacheControlon the same field;validateUser(with and without a store schema): keeps its resolver, rejects without session, validates the session exactly once.Results:
devcode, the 6 store tests fail and the 4 native tests pass (bug reproduced);Manual (store) — in a store using the CodeSandbox build of this PR, add to
src/graphql/thirdParty/typeDefs:with resolvers returning any string, run
faststore devandPOST /api/graphqlwithout cookies:{ directiveProbeAuth }200with the resolver value401 UnauthorizedError{ directiveProbeCache }cache-control: no-cache, no-storecache-control: private, s-maxage=7, stale-while-revalidate=11{ listCreditCards { ... } }(native control)401401(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
canaryin #3063getFinalAPISchemainpackages/core/src/server/index.tsapplied[cacheControlDirective, authDirective]to the single native + store schema (last unaffected tagv3.100.5)