Repository navigation
Conversation
|
I have signed the CLA! |
|
Hi @alexanderMontague, you merged #7164, so I'd appreciate your eyes on this one when you have a moment. This follows up on a regression from that PR (#8259): the proxy's synthetic preflight response never includes CI is green and the diff is small (proxy, its tests, one changeset). Happy to adjust anything. Thanks! |
|
Hi @isaacroldan, sorry for the extra ping. This PR has been open for about five weeks without a review, and I tried @alexanderMontague (who merged #7164) earlier without luck, so I'm reaching out to you as you've been reviewing a lot of recent PRs. It fixes #8259, a regression from #7164: the app dev proxy answers CORS preflights itself without I also checked the #5660 setup (an Express backend without any CORS middleware): the CI is green, and the diff is small (proxy, its tests, one changeset). If someone else on the team is a better fit, a pointer would be very welcome. Thanks! |
8f0c19f to
eceb673
Compare
isaacroldan
left a comment
There was a problem hiding this comment.
Hey @Dylan-GJ, thanks for this and sorry for the wait!
Forwarding the preflight to the app makes sense, only the app knows which origins to trust and that's what happens in production anyway. The fallback is the problem, it brings back #5660 and most likely #7324.
Since 5.4.14 / 4.5.9 Vite's default server.cors only allows localhost origins, and it answers the preflight before server.proxy runs, with a 204 and no Access-Control-Allow-Origin. We relay that as-is and the browser blocks it. That's the web/frontend (shopify-frontend-template-react) of the Node, PHP and Ruby templates, shopify app init doesn't list them anymore but existing apps still use them.
Repro: Vite 5.4.21 with that template's server config, /api proxied to an Express backend whose cors() allows https://extensions.shopifycdn.com, then through the CLI proxy:
curl -i -X OPTIONS <tunnel url>/api/data \
-H 'Origin: https://extensions.shopifycdn.com' \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: authorization,content-type'
On main the proxy answers 204 with the origin reflected and it passes. With this PR you get Vite's own 204 without Access-Control-Allow-Origin and the backend never sees the request. In production there's no Vite in front, the backend's cors() answers and it passes.
Your #5660 check was Express on its own, in #5660 Vite sits in front of Express and answers first.
I'd only relay a 2xx that allows the request's origin and send the proxy's own 204 for everything else, that keeps #8259 fixed (suggestion inline).
About CI, I haven't approved the workflow runs for this head so tests, lint and type-check haven't run yet. I'll approve them after your next push :)
| const statusCode = targetResponse.statusCode ?? 500 | ||
| if (statusCode >= 400) { | ||
| targetResponse.resume() | ||
| respondToPreflight(req, res) | ||
| return | ||
| } |
There was a problem hiding this comment.
a preflight only passes with a 2xx that allows the origin, and this relays anything below 400. So besides Vite we'd also relay Express's automatic 200 + Allow (for a path with routes), the auto-answers in Next.js route handlers, Flask and Django when the app has no CORS handling, and any 3xx (a redirected preflight is a network error). Auth middleware that redirects session-less requests will redirect every preflight, preflights never carry cookies or Authorization.
Those fail in production too, same as the 404 we already fall back on, so I'd treat them all the same. An OPTIONS without Origin isn't a browser preflight, so that 2xx can go through as-is:
| const statusCode = targetResponse.statusCode ?? 500 | |
| if (statusCode >= 400) { | |
| targetResponse.resume() | |
| respondToPreflight(req, res) | |
| return | |
| } | |
| const statusCode = targetResponse.statusCode ?? 500 | |
| const {origin} = req.headers | |
| const allowOrigin = targetResponse.headers['access-control-allow-origin'] | |
| const targetAllowsOrigin = origin === undefined || allowOrigin === '*' || allowOrigin === origin | |
| if (statusCode < 200 || statusCode >= 300 || !targetAllowsOrigin) { | |
| targetResponse.resume() | |
| respondToPreflight(req, res) | |
| return | |
| } |
Apps that grant credentials for the origin still get relayed so #8259 stays fixed, and the fallback is the same 204 main sends today. Downside is that a deliberate allowlist "no" sent as a 2xx gets overridden for non-credentialed requests, same trade-off the doc comment already accepts for a 403.
Can we update that comment to the new rule? the PR description and the commit message also describe the 4xx/5xx rule
| test('keeps the target response when it does not authorize the origin', {retry: 2}, async ({setup}) => { | ||
| const response = await fetch(`${protocol}://localhost:${setup.proxyPort}/path1/test`, { | ||
| method: 'OPTIONS', | ||
| headers: {Origin: 'https://evil.example', 'Access-Control-Request-Method': 'POST'}, | ||
| agent, | ||
| }) | ||
| expect(response.status).toBe(204) | ||
| expect(response.headers.get('access-control-allow-origin')).toBeNull() | ||
| expect(response.headers.get('access-control-allow-credentials')).toBeNull() | ||
| }) |
There was a problem hiding this comment.
with the fix in http-reverse-proxy.ts this test flips: a 2xx without Access-Control-Allow-Origin is also what Vite's default and Express send when the app did nothing, so we can't treat it as a deliberate rejection. It should expect the fallback (origin reflected, no credentials) and get a new name.
Can we also add 200 and 302 to the status loop below? That covers the plain 2xx and redirect cases with the existing target.
Non blocking: every relayed preflight answer in the suite is an empty 204, so removing selfHandleResponse at http-reverse-proxy.ts L74 wouldn't fail anything, even though the proxy library would then pipe the body twice. A relayed 2xx with a chunked body (target calls writeHead and then end('ok')) asserting the exact body would catch that.
The proxy answered every OPTIONS request itself without Access-Control-Allow-Credentials, which broke credentialed cross-origin requests. Preflights now reach the target app, which decides CORS. The target's answer is only relayed when it is a 2xx that allows the request's origin. Otherwise (error or redirect status, no CORS headers as with Vite's default server.cors, or an unreachable target) the proxy responds itself, without credentials, as before.
eceb673 to
5bde938
Compare
|
Thanks @isaacroldan, this is a great catch and a clear explanation, I hadn't considered Vite answering the preflight before I pushed the changes:
I also tested both setups end to end with
Could you approve the workflow runs when you get a chance? Thanks! |
| const targetServer1 = http.createServer((req, res) => { | ||
| if (req.method === 'OPTIONS' && req.url?.endsWith('/with-body')) { | ||
| // Writes the body in several chunks, as a real app would after sending headers. | ||
| res.writeHead(200, req.headers.origin ? {'Access-Control-Allow-Origin': req.headers.origin} : {}) |
There was a problem hiding this comment.
Hi @isaacroldan, this CodeQL alert is a false positive. The flagged line (http-reverse-proxy.test.ts:198) is the target server of a test fixture, for the /with-body path. It reflects the request origin only so the test can check that a body is relayed. It never runs outside the test suite, so it is not shipped in the CLI. That handler does not send Access-Control-Allow-Credentials, and the proxy itself never does either.
Could you dismiss the alert as "Used in tests"? I do not have the permission to do it. Alternatively, I can change the fixture to use the fixed authorizedOrigin constant if you would rather not dismiss it.
WHY are these changes introduced?
Fixes #8259
#7164 made the
shopify app devreverse proxy answer CORSOPTIONSrequests itself, because some dev servers don't handle them. The response never includesAccess-Control-Allow-Credentials, so credentialed cross-origin requests (fetch(..., {credentials: "include"})) fail the preflight even when the app's backend is configured correctly.Adding the header in the proxy isn't safe: it reflects any
Origin, so it would authorize every site. Reverting #7164 (see #8320) would bring back #7324 and #5660 for backends without anOPTIONShandler.WHAT is this pull request doing?
The proxy now forwards
OPTIONSrequests to the target app, which decides CORS, credentials included. The target's answer is relayed only when it is a 2xx that allows the request's origin (or when the request has noOrigin, so it isn't a browser preflight).In every other case the proxy responds itself, with the same response as before and never with credentials: error or redirect statuses, a 2xx without CORS headers (Vite's default
server.cors, Express's automaticAllowresponse, Next.js, Flask, Django), or an unreachable target. A browser would reject all of these in production too. This keeps #5660 and #7324 working with the Vite frontend of the app templates, which answers the preflight before it reaches the backend.A deliberate "no" from the target sent as a 2xx is overridden for non-credentialed requests, which is acceptable for local development.
Hop-by-hop headers are not relayed from the target's preflight response.
How to manually test your changes?
shopify app devwith a backend that answersOPTIONSwithAccess-Control-Allow-OriginandAccess-Control-Allow-Credentials: truefor a trusted origin. Send a preflight to the tunnel URL:curl -i -X OPTIONS -H "Origin: <trusted origin>" -H "Access-Control-Request-Method: POST" <tunnel url>/<path>The backend's headers, including credentials, are returned.
OPTIONShandler (404/405), or a Vite dev server in front of it with the defaultserver.cors. The proxy answers with a 204 reflecting the origin, withoutAccess-Control-Allow-Credentials.Checklist
patchfor bug fixes ·minorfor new features ·majorfor breaking changes) and added a changeset withpnpm changeset add