-
Notifications
You must be signed in to change notification settings - Fork 0
feat(api): CORS restrito a origens confiáveis (ENG-1666) #427
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
limaronaldo
merged 1 commit into
main
from
rm/eng-1666-medium-restringir-cors-para-origens-confiaveis
Aug 11, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import { describe, it, expect, beforeEach, afterAll } from "bun:test"; | ||
| import { addCorsHeaders, corsHeadersFor } from "./cors"; | ||
|
|
||
| const ORIGINAL_ALLOWED = process.env.ALLOWED_ORIGINS; | ||
|
|
||
| function makeReq(origin?: string): Request { | ||
| return new Request("http://localhost/api/tasks", { | ||
| headers: origin ? { origin } : {}, | ||
| }); | ||
| } | ||
|
|
||
| describe("ENG-1666 CORS conformance", () => { | ||
| beforeEach(() => { | ||
| delete process.env.ALLOWED_ORIGINS; | ||
| }); | ||
|
|
||
| afterAll(() => { | ||
| if (ORIGINAL_ALLOWED === undefined) { | ||
| delete process.env.ALLOWED_ORIGINS; | ||
| } else { | ||
| process.env.ALLOWED_ORIGINS = ORIGINAL_ALLOWED; | ||
| } | ||
| }); | ||
|
|
||
| describe("corsHeadersFor", () => { | ||
| it("never emits wildcard by default", () => { | ||
| const headers = corsHeadersFor(makeReq("https://evil.example.com")); | ||
| expect(headers["Access-Control-Allow-Origin"]).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("echoes origin when in the allowlist", () => { | ||
| process.env.ALLOWED_ORIGINS = | ||
| "https://app.example.com,https://admin.example.com"; | ||
| const headers = corsHeadersFor(makeReq("https://app.example.com")); | ||
| expect(headers["Access-Control-Allow-Origin"]).toBe( | ||
| "https://app.example.com", | ||
| ); | ||
| }); | ||
|
|
||
| it("omits Allow-Origin for origins not in the allowlist", () => { | ||
| process.env.ALLOWED_ORIGINS = "https://app.example.com"; | ||
| const headers = corsHeadersFor(makeReq("https://evil.example.com")); | ||
| expect(headers["Access-Control-Allow-Origin"]).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("trims whitespace in the comma-separated list", () => { | ||
| process.env.ALLOWED_ORIGINS = | ||
| " https://app.example.com , https://admin.example.com "; | ||
| const headers = corsHeadersFor(makeReq("https://admin.example.com")); | ||
| expect(headers["Access-Control-Allow-Origin"]).toBe( | ||
| "https://admin.example.com", | ||
| ); | ||
| }); | ||
|
|
||
| it("supports explicit wildcard opt-in", () => { | ||
| process.env.ALLOWED_ORIGINS = "*"; | ||
| const headers = corsHeadersFor(makeReq("https://anything.example.com")); | ||
| expect(headers["Access-Control-Allow-Origin"]).toBe("*"); | ||
| }); | ||
|
|
||
| it("omits Allow-Origin for requests without Origin header", () => { | ||
| process.env.ALLOWED_ORIGINS = "https://app.example.com"; | ||
| const headers = corsHeadersFor(makeReq()); | ||
| expect(headers["Access-Control-Allow-Origin"]).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("always includes Vary: Origin and method/header allowances", () => { | ||
| const headers = corsHeadersFor(makeReq("https://app.example.com")); | ||
| expect(headers.Vary).toBe("Origin"); | ||
| expect(headers["Access-Control-Allow-Methods"]).toContain("OPTIONS"); | ||
| expect(headers["Access-Control-Allow-Headers"]).toContain( | ||
| "Authorization", | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe("addCorsHeaders", () => { | ||
| it("adds CORS headers to a response preserving status and body", async () => { | ||
| process.env.ALLOWED_ORIGINS = "https://app.example.com"; | ||
| const res = addCorsHeaders( | ||
| Response.json({ ok: true }, { status: 201 }), | ||
| makeReq("https://app.example.com"), | ||
| ); | ||
| expect(res.status).toBe(201); | ||
| expect(res.headers.get("Access-Control-Allow-Origin")).toBe( | ||
| "https://app.example.com", | ||
| ); | ||
| expect(res.headers.get("Vary")).toBe("Origin"); | ||
| expect(await res.json()).toEqual({ ok: true }); | ||
| }); | ||
|
|
||
| it("does not add Allow-Origin for untrusted origins", () => { | ||
| process.env.ALLOWED_ORIGINS = "https://app.example.com"; | ||
| const res = addCorsHeaders( | ||
| Response.json({ ok: true }), | ||
| makeReq("https://evil.example.com"), | ||
| ); | ||
| expect(res.headers.get("Access-Control-Allow-Origin")).toBeNull(); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| // ============================================ | ||
| // CORS — restrito a origens confiáveis (ENG-1666) | ||
| // ============================================ | ||
| // | ||
| // ALLOWED_ORIGINS: lista comma-separated de origens confiáveis. | ||
| // Ex.: ALLOWED_ORIGINS="https://app.example.com,https://admin.example.com" | ||
| // "*" pode ser incluído explicitamente para opt-in de wildcard (não recomendado). | ||
| // Sem match (ou sem ALLOWED_ORIGINS configurado), nenhum | ||
| // Access-Control-Allow-Origin é emitido — secure by default. | ||
|
|
||
| function getAllowedOrigins(): string[] { | ||
| return (process.env.ALLOWED_ORIGINS ?? "") | ||
| .split(",") | ||
| .map((o) => o.trim()) | ||
| .filter(Boolean); | ||
| } | ||
|
|
||
| export function corsHeadersFor(req: Request): Record<string, string> { | ||
| const headers: Record<string, string> = { | ||
| "Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS", | ||
| "Access-Control-Allow-Headers": "Content-Type, Authorization", | ||
| Vary: "Origin", | ||
| }; | ||
| const origin = req.headers.get("origin"); | ||
| if (!origin) return headers; | ||
| const allowed = getAllowedOrigins(); | ||
| if (allowed.includes("*")) { | ||
| headers["Access-Control-Allow-Origin"] = "*"; | ||
| } else if (allowed.includes(origin)) { | ||
| headers["Access-Control-Allow-Origin"] = origin; | ||
| } | ||
| return headers; | ||
| } | ||
|
|
||
| export function addCorsHeaders(response: Response, req: Request): Response { | ||
| const newHeaders = new Headers(response.headers); | ||
| for (const [key, value] of Object.entries(corsHeadersFor(req))) { | ||
| newHeaders.set(key, value); | ||
| } | ||
| return new Response(response.body, { | ||
| status: response.status, | ||
| statusText: response.statusText, | ||
| headers: newHeaders, | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When deploying with the checked-in Fly workflow, neither
fly.tomlnorpackages/api/.env.exampleconfigures the newALLOWED_ORIGINSvariable, while the separately deployed dashboard callshttps://multiplai.fly.dev(packages/web/.env.production:1). This empty default therefore omitsAccess-Control-Allow-Originfrom every dashboard API and SSE response, causing browsers to block the application unless an untracked Fly secret is manually provisioned; the documented Vite-on-5173 development setup is similarly affected by pages that call port 3000 directly. Add the trusted production/development origins to the deployment and sample configuration, or fail startup when the required setting is absent.Useful? React with 👍 / 👎.