Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion lib/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,14 @@ export default function middleware(config: Types.MiddlewareConfig): Middleware {
}
})();

if (!validateSignature(body, secret, signature)) {
// Check if signature verification should be skipped
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

variable name represents this enough, so inline comment seems unnecessary!

const shouldSkipVerification =
config.skipSignatureVerification && config.skipSignatureVerification();

if (
!shouldSkipVerification &&
!validateSignature(body, secret, signature)
) {
next(
new SignatureValidationFailed("signature validation failed", {
signature,
Expand Down
8 changes: 8 additions & 0 deletions lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ export interface ClientConfig extends Config {

export interface MiddlewareConfig extends Config {
channelSecret: string;

// skipSignatureValidation is a function that determines whether to skip
// webhook signature verification.
//
// If the function returns true, the signature verification step is skipped.
// This can be useful in scenarios such as when you're in the process of updating
// the channel secret and need to temporarily bypass verification to avoid disruptions.
skipSignatureVerification?: () => boolean;
}

export type Profile = {
Expand Down
38 changes: 31 additions & 7 deletions test/helpers/test-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import {
} from "../../lib/exceptions.js";
import * as finalhandler from "finalhandler";

let server: Server | null = null;
// Use a map to store multiple server instances
let servers: Map<number, Server> = new Map();

function listen(port: number, middleware?: express.RequestHandler) {
const app = express();
Expand Down Expand Up @@ -77,17 +78,40 @@ function listen(port: number, middleware?: express.RequestHandler) {
);

return new Promise(resolve => {
server = app.listen(port, () => resolve(undefined));
const server = app.listen(port, () => resolve(undefined));
servers.set(port, server);
});
}

function close() {
function close(port?: number) {
return new Promise(resolve => {
if (!server) {
return resolve(undefined);
}
if (port !== undefined) {
const server = servers.get(port);
if (!server) {
return resolve(undefined);
}

server.close(() => {
servers.delete(port);
resolve(undefined);
});
} else {
// Close all servers if no port is specified
if (servers.size === 0) {
return resolve(undefined);
}

const promises = Array.from(servers.entries()).map(([port, server]) => {
return new Promise(resolveServer => {
server.close(() => {
servers.delete(port);
resolveServer(undefined);
});
});
});

server.close(() => resolve(undefined));
Promise.all(promises).then(() => resolve(undefined));
}
});
}

Expand Down
102 changes: 101 additions & 1 deletion test/middleware.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ const TEST_PORT = parseInt(process.env.TEST_PORT || "1234", 10);

const m = middleware({ channelSecret: "test_channel_secret" });

// Middleware with skipSignatureVerification function (always true)
const mWithSkipAlwaysTrue = middleware({
channelSecret: "test_channel_secret",
skipSignatureVerification: () => true,
});

// Middleware with skipSignatureVerification function (dynamic behavior based on environment variable)
let shouldSkipSignature = false;
const mWithDynamicSkip = middleware({
channelSecret: "test_channel_secret",
skipSignatureVerification: () => shouldSkipSignature,
});

const getRecentReq = (): { body: Types.WebhookRequestBody } =>
JSON.parse(readFileSync(join(__dirname, "helpers/request.json")).toString());

Expand Down Expand Up @@ -53,8 +66,95 @@ describe("middleware test", () => {
beforeAll(() => {
listen(TEST_PORT, m);
});

describe("With skipSignatureVerification functionality", () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aren't these tests run in parallel?

To avoid flaky tests, can we design the tests so they don't share state?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought it would be fine just to have something like mWithDynamicSkip or others within the test. Each test should be able to define its own before~ and after~.

// Port for always-true skip function
let alwaysTruePort: number;
// Port for dynamic skip function
let dynamicSkipPort: number;

beforeAll(() => {
alwaysTruePort = TEST_PORT + 1;
dynamicSkipPort = TEST_PORT + 2;
listen(alwaysTruePort, mWithSkipAlwaysTrue);
return listen(dynamicSkipPort, mWithDynamicSkip);
});

afterAll(() => {
close(alwaysTruePort);
return close(dynamicSkipPort);
});

it("should skip signature verification when skipSignatureVerification returns true", async () => {
const client = new HTTPClient({
baseURL: `http://localhost:${alwaysTruePort}`,
defaultHeaders: {
"X-Line-Signature": "invalid_signature",
},
});

// This should work even with invalid signature because verification is skipped
await client.post("/webhook", {
events: [webhook],
destination: DESTINATION,
});

const req = getRecentReq();
deepEqual(req.body.destination, DESTINATION);
deepEqual(req.body.events, [webhook]);
});

it("should respect dynamic skipSignatureVerification behavior - when true", async () => {
// Set to skip verification
shouldSkipSignature = true;

const client = new HTTPClient({
baseURL: `http://localhost:${dynamicSkipPort}`,
defaultHeaders: {
"X-Line-Signature": "invalid_signature",
},
});

// This should work even with invalid signature because verification is skipped
await client.post("/webhook", {
events: [webhook],
destination: DESTINATION,
});

const req = getRecentReq();
deepEqual(req.body.destination, DESTINATION);
deepEqual(req.body.events, [webhook]);
});

it("should respect dynamic skipSignatureVerification behavior - when false", async () => {
// Set to NOT skip verification
shouldSkipSignature = false;

const client = new HTTPClient({
baseURL: `http://localhost:${dynamicSkipPort}`,
defaultHeaders: {
"X-Line-Signature": "invalid_signature",
},
});

try {
// This should fail because signature verification is not skipped
await client.post("/webhook", {
events: [webhook],
destination: DESTINATION,
});
ok(false, "Expected to throw an error due to invalid signature");
} catch (err) {
if (err instanceof HTTPError) {
equal(err.statusCode, 401);
} else {
throw err;
}
}
});
});
afterAll(() => {
close();
close(TEST_PORT);
});

describe("Succeeds on parsing valid request", () => {
Expand Down