Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(http): handle wrong request method correctly #5643

Merged
merged 2 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 8 additions & 0 deletions http/file_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,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 @@ -635,6 +639,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