Skip to content

Commit

Permalink
Merge pull request #32 from saleor/refactor-middlewares
Browse files Browse the repository at this point in the history
Refactor and test middleware
  • Loading branch information
krzysztofwolski authored Aug 26, 2022
2 parents f84d534 + e1dc4c0 commit 4a51410
Show file tree
Hide file tree
Showing 14 changed files with 414 additions and 233 deletions.
206 changes: 0 additions & 206 deletions src/middleware.ts

This file was deleted.

6 changes: 6 additions & 0 deletions src/middleware/index.ts
Original file line number Diff line number Diff line change
@@ -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";
44 changes: 44 additions & 0 deletions src/middleware/with-auth-token-required.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
});
14 changes: 14 additions & 0 deletions src/middleware/with-auth-token-required.ts
Original file line number Diff line number Diff line change
@@ -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);
};
32 changes: 32 additions & 0 deletions src/middleware/with-base-url.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
});
9 changes: 9 additions & 0 deletions src/middleware/with-base-url.ts
Original file line number Diff line number Diff line change
@@ -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);
};
80 changes: 80 additions & 0 deletions src/middleware/with-jwt-verified.ts
Original file line number Diff line number Diff line change
@@ -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);
};
Loading

0 comments on commit 4a51410

Please sign in to comment.