Support comma-delimited x-forwarded-proto (#227)

* Support comma-delimited x-forwarded-proto

* Changeset
This commit is contained in:
Michał Miszczyszyn 2023-04-11 15:03:50 +02:00 committed by GitHub
parent ab24968b67
commit 5057d3491e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
"@saleor/app-sdk": patch
---
Support comma-delimited x-forwarded-proto

View file

@ -18,6 +18,14 @@ export const getSaleorHeaders = (headers: { [name: string]: string | string[] |
}); });
export const getBaseUrl = (headers: { [name: string]: string | string[] | undefined }): string => { export const getBaseUrl = (headers: { [name: string]: string | string[] | undefined }): string => {
const { host, "x-forwarded-proto": protocol = "http" } = headers; const { host, "x-forwarded-proto": xForwardedProto = "http" } = headers;
const xForwardedProtos = Array.isArray(xForwardedProto)
? xForwardedProto.join(",")
: xForwardedProto;
const protocols = xForwardedProtos.split(",");
// prefer https over other protocols
const protocol = protocols.find((el) => el === "https") || protocols[0];
return `${protocol}://${host}`; return `${protocol}://${host}`;
}; };

View file

@ -28,5 +28,35 @@ describe("middleware", () => {
expect(mockRequest.context.baseURL).toBe("https://my-saleor-env.saleor.cloud"); expect(mockRequest.context.baseURL).toBe("https://my-saleor-env.saleor.cloud");
expect(mockHandlerFn).toHaveBeenCalledOnce(); expect(mockHandlerFn).toHaveBeenCalledOnce();
}); });
it("supports multiple comma-delimited values in x-forwarded-proto", async () => {
const mockRequest = {
context: {},
headers: {
host: "my-saleor-env.saleor.cloud",
"x-forwarded-proto": "https,http",
},
} as unknown as Request;
await withBaseURL(mockHandlerFn)(mockRequest);
expect(mockRequest.context.baseURL).toBe("https://my-saleor-env.saleor.cloud");
expect(mockHandlerFn).toHaveBeenCalledOnce();
});
it("supports multiple x-forwarded-proto headers", async () => {
const mockRequest = {
context: {},
headers: {
host: "my-saleor-env.saleor.cloud",
"x-forwarded-proto": ["http", "ftp,https"],
},
} as unknown as Request;
await withBaseURL(mockHandlerFn)(mockRequest);
expect(mockRequest.context.baseURL).toBe("https://my-saleor-env.saleor.cloud");
expect(mockHandlerFn).toHaveBeenCalledOnce();
});
}); });
}); });