Merge pull request #32 from saleor/refactor-middlewares

Refactor and test middleware
This commit is contained in:
Krzysztof Wolski 2022-08-26 12:29:19 +02:00 committed by GitHub
commit 4a514103b6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 414 additions and 233 deletions

View file

@ -1,206 +0,0 @@
import crypto from "crypto";
import * as jose from "jose";
import type { Middleware, Request } from "retes";
import { Response } from "retes/response";
import { APL } from "./APL";
import { SALEOR_AUTHORIZATION_BEARER_HEADER, SALEOR_SIGNATURE_HEADER } from "./const";
import { getSaleorHeaders } from "./headers";
import { getJwksUrl } from "./urls";
export const withBaseURL: Middleware = (handler) => async (request) => {
const { host, "x-forwarded-proto": protocol = "http" } = request.headers;
request.context.baseURL = `${protocol}://${host}`;
return handler(request);
};
export const withSaleorDomainPresent: Middleware = (handler) => async (request) => {
const { domain } = getSaleorHeaders(request.headers);
if (!domain) {
return Response.BadRequest({
success: false,
message: "Missing Saleor domain header.",
});
}
return handler(request);
};
export const withSaleorEventMatch =
<E extends string>(expectedEvent: `${Lowercase<E>}`): Middleware =>
(handler) =>
async (request) => {
const { event } = getSaleorHeaders(request.headers);
if (event !== expectedEvent) {
return Response.BadRequest({
success: false,
message: `Invalid Saleor event. Expecting ${expectedEvent}.`,
});
}
return handler(request);
};
export const withAuthTokenRequired: Middleware = (handler) => async (request) => {
const authToken = request.params.auth_token;
if (!authToken) {
return Response.BadRequest({
success: false,
message: "Missing auth token.",
});
}
return handler(request);
};
export const withWebhookSignatureVerified =
(secretKey: string | undefined = undefined): Middleware =>
(handler) =>
async (request) => {
const ERROR_MESSAGE = "Webhook signature verification failed:";
if (request.rawBody === undefined) {
return Response.InternalServerError({
success: false,
message: `${ERROR_MESSAGE} Request payload already parsed.`,
});
}
const { domain: saleorDomain, signature: payloadSignature } = getSaleorHeaders(request.headers);
if (!payloadSignature) {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Missing ${SALEOR_SIGNATURE_HEADER} header.`,
});
}
if (secretKey !== undefined) {
const calculatedSignature = crypto
.createHmac("sha256", secretKey)
.update(request.rawBody)
.digest("hex");
if (calculatedSignature !== payloadSignature) {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Verification using secret key has failed.`,
});
}
} else {
const [header, , signature] = payloadSignature.split(".");
const jws = {
protected: header,
payload: request.rawBody,
signature,
};
const remoteJwks = jose.createRemoteJWKSet(
new URL(getJwksUrl(saleorDomain))
) as jose.FlattenedVerifyGetKey;
try {
await jose.flattenedVerify(jws, remoteJwks);
} catch {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Verification using public key has failed.`,
});
}
}
return handler(request);
};
export interface DashboardTokenPayload extends jose.JWTPayload {
app: string;
}
export const withJWTVerified =
(getAppId: (request: Request) => Promise<string | undefined>): Middleware =>
(handler) =>
async (request) => {
const { domain, authorizationBearer: token } = getSaleorHeaders(request.headers);
const ERROR_MESSAGE = "JWT verification failed:";
if (token === undefined) {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Missing ${SALEOR_AUTHORIZATION_BEARER_HEADER} header.`,
});
}
let tokenClaims: DashboardTokenPayload;
try {
tokenClaims = jose.decodeJwt(token as string) as DashboardTokenPayload;
} catch (e) {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Could not decode authorization token.`,
});
}
if (tokenClaims.iss !== domain) {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Token iss property is different than domain header.`,
});
}
let appId: string | undefined;
try {
appId = await getAppId(request);
} catch (error) {
return Response.InternalServerError({
success: false,
message: `${ERROR_MESSAGE} Could not obtain the app ID.`,
});
}
if (!appId) {
return Response.InternalServerError({
success: false,
message: `${ERROR_MESSAGE} No value for app ID.`,
});
}
if (tokenClaims.app !== appId) {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Token's app property is different than app ID.`,
});
}
try {
const JWKS = jose.createRemoteJWKSet(new URL(getJwksUrl(domain)));
await jose.jwtVerify(token, JWKS);
} catch (e) {
console.error(e);
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} JWT signature verification failed.`,
});
}
return handler(request);
};
export const withRegisteredSaleorDomainHeader =
({ apl }: { apl: APL }): Middleware =>
(handler) =>
async (request) => {
const { domain: saleorDomain } = getSaleorHeaders(request.headers);
const authData = await apl.get(saleorDomain);
if (!authData) {
return Response.Forbidden({
success: false,
message: `Domain ${saleorDomain} not registered.`,
});
}
return handler(request);
};

6
src/middleware/index.ts Normal file
View file

@ -0,0 +1,6 @@
export * from "./with-auth-token-required";
export * from "./with-base-url";
export * from "./with-registered-saleor-domain-header";
export * from "./with-saleor-domain-present";
export * from "./with-saleor-event-match";
export * from "./with-webhook-signature-verified";

View file

@ -0,0 +1,44 @@
import { Handler, Request } from "retes";
import { Response } from "retes/response";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { withAuthTokenRequired } from "./with-auth-token-required";
const getMockSuccessResponse = async () => Response.OK({});
describe("middleware", () => {
describe("withAuthTokenRequired", () => {
let mockHandlerFn: Handler = vi.fn(getMockSuccessResponse);
beforeEach(() => {
mockHandlerFn = vi.fn(getMockSuccessResponse);
});
it("Pass request when request has token prop", async () => {
const mockRequest = {
context: {},
headers: {},
params: {
auth_token: "token",
},
} as unknown as Request;
const response = await withAuthTokenRequired(mockHandlerFn)(mockRequest);
expect(response.status).toBe(200);
expect(mockHandlerFn).toHaveBeenCalledOnce();
});
it("Reject request without auth token", async () => {
const mockRequest = {
context: {},
headers: {},
params: {},
} as unknown as Request;
const response = await withAuthTokenRequired(mockHandlerFn)(mockRequest);
expect(response.status).eq(400);
expect(mockHandlerFn).toBeCalledTimes(0);
});
});
});

View file

@ -0,0 +1,14 @@
import { Middleware } from "retes";
import { Response } from "retes/response";
export const withAuthTokenRequired: Middleware = (handler) => async (request) => {
const authToken = request.params.auth_token;
if (!authToken) {
return Response.BadRequest({
success: false,
message: "Missing auth token.",
});
}
return handler(request);
};

View file

@ -0,0 +1,32 @@
import { Handler, Request } from "retes";
import { Response } from "retes/response";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { withBaseURL } from "./with-base-url";
const getMockEmptyResponse = async () => ({} as Response);
describe("middleware", () => {
describe("withBaseURL", () => {
let mockHandlerFn: Handler = vi.fn(getMockEmptyResponse);
beforeEach(() => {
mockHandlerFn = vi.fn();
});
it("Adds base URL from request header to context and calls handler", async () => {
const mockRequest = {
context: {},
headers: {
host: "my-saleor-env.saleor.cloud",
"x-forwarded-proto": "https",
},
} as unknown as Request;
await withBaseURL(mockHandlerFn)(mockRequest);
expect(mockRequest.context.baseURL).toBe("https://my-saleor-env.saleor.cloud");
expect(mockHandlerFn).toHaveBeenCalledOnce();
});
});
});

View file

@ -0,0 +1,9 @@
import { Middleware } from "retes";
export const withBaseURL: Middleware = (handler) => async (request) => {
const { host, "x-forwarded-proto": protocol = "http" } = request.headers;
request.context.baseURL = `${protocol}://${host}`;
return handler(request);
};

View file

@ -0,0 +1,80 @@
import * as jose from "jose";
import type { Middleware, Request } from "retes";
import { Response } from "retes/response";
import { SALEOR_AUTHORIZATION_BEARER_HEADER } from "../const";
import { getSaleorHeaders } from "../headers";
import { getJwksUrl } from "../urls";
export interface DashboardTokenPayload extends jose.JWTPayload {
app: string;
}
export const withJWTVerified =
(getAppId: (request: Request) => Promise<string | undefined>): Middleware =>
(handler) =>
async (request) => {
const { domain, authorizationBearer: token } = getSaleorHeaders(request.headers);
const ERROR_MESSAGE = "JWT verification failed:";
if (token === undefined) {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Missing ${SALEOR_AUTHORIZATION_BEARER_HEADER} header.`,
});
}
let tokenClaims: DashboardTokenPayload;
try {
tokenClaims = jose.decodeJwt(token as string) as DashboardTokenPayload;
} catch (e) {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Could not decode authorization token.`,
});
}
if (tokenClaims.iss !== domain) {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Token iss property is different than domain header.`,
});
}
let appId: string | undefined;
try {
appId = await getAppId(request);
} catch (error) {
return Response.InternalServerError({
success: false,
message: `${ERROR_MESSAGE} Could not obtain the app ID.`,
});
}
if (!appId) {
return Response.InternalServerError({
success: false,
message: `${ERROR_MESSAGE} No value for app ID.`,
});
}
if (tokenClaims.app !== appId) {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Token's app property is different than app ID.`,
});
}
try {
const JWKS = jose.createRemoteJWKSet(new URL(getJwksUrl(domain)));
await jose.jwtVerify(token, JWKS);
} catch (e) {
console.error(e);
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} JWT signature verification failed.`,
});
}
return handler(request);
};

View file

@ -2,36 +2,13 @@ import { Handler, Request } from "retes";
import { Response } from "retes/response";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { APL } from "./APL";
import { SALEOR_DOMAIN_HEADER } from "./const";
import { withBaseURL, withRegisteredSaleorDomainHeader } from "./middleware";
import { APL } from "../APL";
import { SALEOR_DOMAIN_HEADER } from "../const";
import { withRegisteredSaleorDomainHeader } from "./with-registered-saleor-domain-header";
const getMockSuccessResponse = async () => Response.OK({});
describe("middleware.test.ts", () => {
describe("withBaseURL", () => {
let mockHandlerFn: Handler = vi.fn(getMockSuccessResponse);
beforeEach(() => {
mockHandlerFn = vi.fn(getMockSuccessResponse);
});
it("Adds base URL from request header to context and calls handler", async () => {
const mockRequest = {
context: {},
headers: {
host: "my-saleor-env.saleor.cloud",
"x-forwarded-proto": "https",
},
} as unknown as Request;
await withBaseURL(mockHandlerFn)(mockRequest);
expect(mockRequest.context.baseURL).toBe("https://my-saleor-env.saleor.cloud");
expect(mockHandlerFn).toHaveBeenCalledOnce();
});
});
describe("middleware", () => {
describe("withRegisteredSaleorDomainHeader", () => {
let mockHandlerFn: Handler = vi.fn(getMockSuccessResponse);

View file

@ -0,0 +1,21 @@
import { Middleware } from "retes";
import { Response } from "retes/response";
import { APL } from "../APL";
import { getSaleorHeaders } from "../headers";
export const withRegisteredSaleorDomainHeader =
({ apl }: { apl: APL }): Middleware =>
(handler) =>
async (request) => {
const { domain: saleorDomain } = getSaleorHeaders(request.headers);
const authData = await apl.get(saleorDomain);
if (!authData) {
return Response.Forbidden({
success: false,
message: `Domain ${saleorDomain} not registered.`,
});
}
return handler(request);
};

View file

@ -0,0 +1,43 @@
import { Handler, Request } from "retes";
import { Response } from "retes/response";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { SALEOR_DOMAIN_HEADER } from "../const";
import { withSaleorDomainPresent } from "./with-saleor-domain-present";
const getMockSuccessResponse = async () => Response.OK({});
describe("middleware", () => {
describe("withSaleorDomainPresent", () => {
let mockHandlerFn: Handler = vi.fn(getMockSuccessResponse);
beforeEach(() => {
mockHandlerFn = vi.fn(getMockSuccessResponse);
});
it("Pass request when request has Saleor Domain header", async () => {
const mockRequest = {
context: {},
headers: {
[SALEOR_DOMAIN_HEADER]: "example.com",
},
} as unknown as Request;
const response = await withSaleorDomainPresent(mockHandlerFn)(mockRequest);
expect(response.status).toBe(200);
expect(mockHandlerFn).toHaveBeenCalledOnce();
});
it("Reject request when Saleor domain header is not present", async () => {
const mockRequest = {
context: {},
headers: {},
} as unknown as Request;
const response = await withSaleorDomainPresent(mockHandlerFn)(mockRequest);
expect(response.status).eq(400);
expect(mockHandlerFn).toBeCalledTimes(0);
});
});
});

View file

@ -0,0 +1,17 @@
import { Middleware } from "retes";
import { Response } from "retes/response";
import { getSaleorHeaders } from "../headers";
export const withSaleorDomainPresent: Middleware = (handler) => async (request) => {
const { domain } = getSaleorHeaders(request.headers);
if (!domain) {
return Response.BadRequest({
success: false,
message: "Missing Saleor domain header.",
});
}
return handler(request);
};

View file

@ -0,0 +1,57 @@
import { Handler, Request } from "retes";
import { Response } from "retes/response";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { SALEOR_EVENT_HEADER } from "../const";
import { withSaleorEventMatch } from "./with-saleor-event-match";
const getMockSuccessResponse = async () => Response.OK({});
describe("middleware", () => {
describe("withSaleorEventMatch", () => {
let mockHandlerFn: Handler = vi.fn(getMockSuccessResponse);
beforeEach(() => {
mockHandlerFn = vi.fn(getMockSuccessResponse);
});
it("Pass request when request has expected event header", async () => {
const eventName = "product-updated";
const mockRequest = {
context: {},
headers: {
[SALEOR_EVENT_HEADER]: eventName,
},
} as unknown as Request;
const response = await withSaleorEventMatch(eventName)(mockHandlerFn)(mockRequest);
expect(response.status).toBe(200);
expect(mockHandlerFn).toHaveBeenCalledOnce();
});
it("Reject request when event header is not present", async () => {
const mockRequest = {
context: {},
headers: {},
} as unknown as Request;
const response = await withSaleorEventMatch("product-updated")(mockHandlerFn)(mockRequest);
expect(response.status).eq(400);
expect(mockHandlerFn).toBeCalledTimes(0);
});
it("Reject request when event header does not match", async () => {
const mockRequest = {
context: {},
headers: {
[SALEOR_EVENT_HEADER]: "wrong-event",
},
} as unknown as Request;
const response = await withSaleorEventMatch("product-updated")(mockHandlerFn)(mockRequest);
expect(response.status).eq(400);
expect(mockHandlerFn).toBeCalledTimes(0);
});
});
});

View file

@ -0,0 +1,20 @@
import { Middleware } from "retes";
import { Response } from "retes/response";
import { getSaleorHeaders } from "../headers";
export const withSaleorEventMatch =
<E extends string>(expectedEvent: `${Lowercase<E>}`): Middleware =>
(handler) =>
async (request) => {
const { event } = getSaleorHeaders(request.headers);
if (event !== expectedEvent) {
return Response.BadRequest({
success: false,
message: `Invalid Saleor event. Expecting ${expectedEvent}.`,
});
}
return handler(request);
};

View file

@ -0,0 +1,67 @@
import crypto from "crypto";
import * as jose from "jose";
import { Middleware } from "retes";
import { Response } from "retes/response";
import { SALEOR_SIGNATURE_HEADER } from "../const";
import { getSaleorHeaders } from "../headers";
import { getJwksUrl } from "../urls";
export const withWebhookSignatureVerified =
(secretKey: string | undefined = undefined): Middleware =>
(handler) =>
async (request) => {
const ERROR_MESSAGE = "Webhook signature verification failed:";
if (request.rawBody === undefined) {
return Response.InternalServerError({
success: false,
message: `${ERROR_MESSAGE} Request payload already parsed.`,
});
}
const { domain: saleorDomain, signature: payloadSignature } = getSaleorHeaders(request.headers);
if (!payloadSignature) {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Missing ${SALEOR_SIGNATURE_HEADER} header.`,
});
}
if (secretKey !== undefined) {
const calculatedSignature = crypto
.createHmac("sha256", secretKey)
.update(request.rawBody)
.digest("hex");
if (calculatedSignature !== payloadSignature) {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Verification using secret key has failed.`,
});
}
} else {
const [header, , signature] = payloadSignature.split(".");
const jws = {
protected: header,
payload: request.rawBody,
signature,
};
const remoteJwks = jose.createRemoteJWKSet(
new URL(getJwksUrl(saleorDomain))
) as jose.FlattenedVerifyGetKey;
try {
await jose.flattenedVerify(jws, remoteJwks);
} catch {
return Response.BadRequest({
success: false,
message: `${ERROR_MESSAGE} Verification using public key has failed.`,
});
}
}
return handler(request);
};