Skip to content

Commit

Permalink
fix(http): handle wrong request method correctly (#5643)
Browse files Browse the repository at this point in the history
* fix(http): handle incorrect method

* fix
  • Loading branch information
iuioiua authored Aug 7, 2024
1 parent e8aa4df commit d682c6b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
8 changes: 8 additions & 0 deletions http/file_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ export async function serveFile(
filePath: string,
options?: ServeFileOptions,
): Promise<Response> {
if (req.method !== "GET") {
return createStandardResponse(STATUS_CODE.MethodNotAllowed);
}

let { etagAlgorithm: algorithm, fileInfo } = options ?? {};

try {
Expand Down Expand Up @@ -636,6 +640,10 @@ export async function serveDir(
req: Request,
opts: ServeDirOptions = {},
): Promise<Response> {
if (req.method !== "GET") {
return createStandardResponse(STATUS_CODE.MethodNotAllowed);
}

let response: Response;
try {
response = await createServeDirResponse(req, opts);
Expand Down
20 changes: 20 additions & 0 deletions http/file_server_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,15 @@ Deno.test("serveDir() handles not found files", async () => {
assertEquals(res.status, 404);
});

Deno.test("serveDir() handles incorrect method", async () => {
const req = new Request("http://localhost/", { method: "POST" });
const res = await serveDir(req, serveDirOptions);
await res.body?.cancel();

assertEquals(res.status, 405);
assertEquals(res.statusText, "Method Not Allowed");
});

Deno.test("serveDir() traverses path correctly", async () => {
const req = new Request("http://localhost/../../../../../../../..");
const res = await serveDir(req, serveDirOptions);
Expand Down Expand Up @@ -739,6 +748,17 @@ Deno.test("serveFile() handles file not found", async () => {
assertEquals(res.statusText, "Not Found");
});

Deno.test("serveFile() handles method not allowed", async () => {
const req = new Request("http://localhost/testdata/test_file.txt", {
method: "POST",
});
const res = await serveFile(req, TEST_FILE_PATH);
await res.body?.cancel();

assertEquals(res.status, 405);
assertEquals(res.statusText, "Method Not Allowed");
});

Deno.test("serveFile() serves HTTP 404 when the path is a directory", async () => {
const req = new Request("http://localhost/testdata/");
const res = await serveFile(req, testdataDir);
Expand Down

0 comments on commit d682c6b

Please sign in to comment.