Skip to content

Commit 031348a

Browse files
authored
feat: add check for closed requests (#162)
## Checklist - [x] I have ensured my pull request is not behind the main or master branch of the original repository. - [x] I have rebased all commits where necessary so that reviewing this pull request can be done without having to merge it first. - [x] I have written a commit message that passes commitlint linting. - [x] I have ensured that my code changes pass linting tests. - [x] I have ensured that my code changes pass unit tests. - [x] I have described my pull request and the reasons for code changes along with context if necessary. ## Changes Added a check for `req.ctx.closed` to ensure that, when a request is closed (canceled) before reaching the bodyparser middleware, the body of the closed request is not attempted to be parsed (which would result in an error). Instead, if the request is closed, then the middleware returns a `499 Client Closed Request` status. ## Reason Errors can occur when parsing bodies of closed requests - `stream not readable`. This indicates the request was cancelled. This can happen when body parser is not on the "synchronous path" of a request - e.g. if Auth is verified asynchronously from headers before bothering to parse the bodies. This allows time for users to occasionally close the request, resulting in a `500 'stream not readable'` error.
1 parent e6fe74d commit 031348a

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/body-parser.ts

+6
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,12 @@ export function bodyParserWrapper(opts: BodyParserOptions = {}) {
9595
return next();
9696
}
9797

98+
if (ctx.req.closed) {
99+
ctx.status = 499;
100+
ctx.body = 'Request already closed';
101+
return;
102+
}
103+
98104
try {
99105
const response = await parseBody(ctx);
100106
// patch node

test/middleware.test.ts

+15
Original file line numberDiff line numberDiff line change
@@ -558,4 +558,19 @@ describe("test/body-parser.test.ts", () => {
558558
.expect({ foo: "bar" });
559559
});
560560
});
561+
562+
describe("request closed", () => {
563+
it("should return 499 on request closed", async () => {
564+
const app = new Koa();
565+
566+
app.use(async (ctx, next) => {
567+
Object.defineProperty(ctx.req, "closed", { value: true });
568+
await next();
569+
});
570+
app.use(bodyParser());
571+
server = app.listen();
572+
573+
await request(server).post("/").send({ foo: "bar" }).expect(499);
574+
});
575+
});
561576
});

0 commit comments

Comments
 (0)