Skip to content

Commit

Permalink
fix: handle missing Content-Type header with null check (#805)
Browse files Browse the repository at this point in the history
* Bugfix for Unhandled Exception

Bugfix for missing null/undefined check in middleware.ts for the "content-type" header.  Issue introduced by b7aee15.

* Remove extra space

* Add test case for missing content-type header

* Linted

* Use falsy check for cleaner comparison

Co-authored-by: Gregor Martynus <39992+gr2m@users.noreply.github.com>

Co-authored-by: CodeQL Automation <application-security@marriott.com>
Co-authored-by: Gregor Martynus <39992+gr2m@users.noreply.github.com>
  • Loading branch information
3 people authored Jan 17, 2023
1 parent b9a2966 commit 46597e7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/middleware/node/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ export async function middleware(
// Check if the Content-Type header is `application/json` and allow for charset to be specified in it
// Otherwise, return a 415 Unsupported Media Type error
// See https://github.com/octokit/webhooks.js/issues/158
if (!request.headers["content-type"].startsWith("application/json")) {
if (
!request.headers["content-type"] ||
!request.headers["content-type"].startsWith("application/json")
) {
response.writeHead(415, {
"content-type": "application/json",
accept: "application/json",
Expand Down
30 changes: 30 additions & 0 deletions test/integration/node-middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,36 @@ describe("createNodeMiddleware(webhooks)", () => {
server.close();
});

test("Handles Missing Content-Type", async () => {
const webhooks = new Webhooks({
secret: "mySecret",
});

const server = createServer(createNodeMiddleware(webhooks)).listen();

// @ts-expect-error complains about { port } although it's included in returned AddressInfo interface
const { port } = server.address();
const response = await fetch(
`http://localhost:${port}/api/github/webhooks`,
{
method: "POST",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
"X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: pushEventPayload,
}
);

await expect(response.text()).resolves.toBe(
'{"error":"Unsupported \\"Content-Type\\" header value. Must be \\"application/json\\""}'
);
expect(response.status).toEqual(415);

server.close();
});

test("Handles invalid JSON", async () => {
const webhooks = new Webhooks({
secret: "mySecret",
Expand Down

0 comments on commit 46597e7

Please sign in to comment.