fix: keep a session reply intact when the streamer reports an error

With a session cookie, express-session's res.end writes all but the last
body byte and sends that byte after the Redis touch. In between,
headersSent is true and writableEnded is false, so the res.destroy()
that followed handleError cut the API's own 404 reply. Nginx then saw
no response header and returned 502 to logged-in visitors of repos
whose source is gone.

Decide whether to cut the response from headersSent before handleError
replies, as the zip proxy already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Thomas DurieuxandClaude Opus 5.5 committed 2026-11-29 08:59:50 +00:00
1 parent a4f65e7d30
commit 111870b6e2
3 files changed
+80 -3

No files matched your search

+5 -1
View File
@@ -548,8 +548,12 @@ export default class AnonymizedFile {
);
void notifyOwnerAccessProblem(this.repository.owner.id, error, { kind: "repository", id: String(this.repository.model._id) });
error.value = this;
// Only a response that was already streaming body bytes must be
// cut. handleError's own reply can be mid-write: express-session
// holds back its last byte until the session store touch ends.
const streaming = res.headersSent;
handleError(error, res);
if (res.headersSent && !res.writableEnded) res.destroy();
if (streaming && !res.writableEnded) res.destroy();
});
resolve();
return;
+4 -2
View File
@@ -41,8 +41,9 @@ router.post(
res
);
} catch (error) {
const streaming = res.headersSent;
handleError(error, res);
if (res.headersSent && !res.writableEnded) res.destroy();
if (streaming && !res.writableEnded) res.destroy();
}
}
);
@@ -121,8 +122,9 @@ router.post("/", async (req: express.Request, res: express.Response) => {
if (!content.closed && !content.destroyed) {
content.destroy();
}
const streaming = res.headersSent;
handleError(error, res);
if (res.headersSent && !res.writableEnded) res.destroy();
if (streaming && !res.writableEnded) res.destroy();
anonymizer.destroy();
}
content
+71
View File
@@ -0,0 +1,71 @@
const { strict: assert } = require("node:assert");
const http = require("node:http");
const { setTimeout } = require("node:timers");
const express = require("express");
const session = require("express-session");
require("ts-node/register/transpile-only");
const config = require("../src/config").default;
const File = require("../src/core/AnonymizedFile").default;
const { AnonymizeTransformer } = require("../src/core/anonymize-utils");
const got = require("got");
// connect-redis implements touch(), so every request that carries a session
// cookie goes through express-session's split write: all but the last body
// byte is written at once and the last byte follows the asynchronous touch.
class TouchingStore extends session.MemoryStore {
touch(sid, sess, callback) {
setTimeout(() => super.touch(sid, sess, callback), 20);
}
}
const listen = (handler) => new Promise((resolve) => {
const server = http.createServer(handler);
server.listen(0, "127.0.0.1", () => resolve(server));
});
const close = (server) => new Promise((resolve) => server.close(resolve));
describe("streamer error responses with a session cookie", function () {
this.timeout(10000);
let old, streamer, api, base;
beforeEach(async () => {
old = { ...config };
streamer = await listen((req, res) => {
req.resume();
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ error: "repo_not_found" }));
});
Object.assign(config, {
STREAMER_ENTRYPOINT: `http://127.0.0.1:${streamer.address().port}/`,
SHARED_CACHE_ENABLED: false,
});
const app = express();
app.use(session({ secret: "test", store: new TouchingStore(), resave: false,
saveUninitialized: false, rolling: true }));
app.get("/login", (req, res) => { req.session.visited = true; res.end("ok"); });
app.get("/file", async (_req, res) => {
const file = new File({ repository: {
repoId: "anon", owner: { id: "507f1f77bcf86cd799439011" }, options: { terms: [] },
model: { _id: "507f1f77bcf86cd799439012", source: { repositoryName: "owner/gone" } },
getToken: async () => "token",
generateAnonymizeTransformer: (filePath) => new AnonymizeTransformer({ terms: [], filePath }),
}, anonymizedPath: "README.md" });
file._file = { name: "README.md", path: "", sha: "sha", size: 10 };
await file.send(res);
});
api = await new Promise((resolve) => { const s = app.listen(0, "127.0.0.1", () => resolve(s)); });
base = `http://127.0.0.1:${api.address().port}`;
});
afterEach(async () => {
await close(api);
await close(streamer);
Object.assign(config, old);
});
it("delivers the whole 404 body instead of cutting the connection", async () => {
const login = await got(`${base}/login`, { retry: 0 });
const cookie = login.headers["set-cookie"].map((value) => value.split(";")[0]).join("; ");
const response = await got(`${base}/file`, { headers: { cookie }, throwHttpErrors: false, retry: 0 });
assert.equal(response.statusCode, 404);
assert.equal(response.body, JSON.stringify({ error: "repo_not_found" }));
});
});