Files
anonymous_github/src/streamer/route.ts
T
Thomas DurieuxandClaude Opus 5.5 c761fc6c17 fix: log each failed file request once, expected outcomes at info
A streamer error such as repo_not_found produced three warnings: the
streamer's handleError, the API's streamer_fetch_failed and the API's
handleError. Expected client outcomes (repo_not_found, repository_expired,
file_not_found, github_app_access_required, ...) were all logged at warn,
which filled the admin Errors page.

- handleError picks the level with errorLogLevel: codes in
  EXPECTED_CLIENT_ERRORS with a 4xx status log at info; other 4xx (rate
  limits, token_expired, validation) stay warn and 5xx stay error.
- The streamer passes { internal: true }: expected outcomes drop to debug
  there because the API logs the request's end state. Faults keep their
  level and the streamer-side stack. Its direct 400 replies now go through
  handleError so they are logged too.
- The API no longer logs streamer_fetch_failed or streamer_zip_fetch_failed.
  The relayed error carries upstreamStatus, and when the streamer's coded
  reply shows it already logged the failure, the API logs it at info.

Every record keeps requestId, so the chain can still be found by request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 09:29:14 +00:00

161 lines
6.0 KiB
TypeScript

import { recordResponseFailure } from "../core/request-evidence";
import { sendSharedContent } from "../core/cached-response";
import * as express from "express";
import GitHubStream from "../core/source/GitHubStream";
import {
AnonymizeTransformer,
isTextFile,
} from "../core/anonymize-utils";
import AnonymousError from "../core/AnonymousError";
import { handleError } from "../server/routes/route-utils";
import { lookup } from "mime-types";
import { streamAnonymizedZip } from "../core/zipStream";
// The API relays these replies and logs each request's end state, so expected
// outcomes are only debug here. Faults keep their level and streamer stack.
function replyError(error: unknown, res: express.Response) {
handleError(error, res, undefined, { internal: true });
}
export const router = express.Router();
router.post(
"/download",
async (req: express.Request, res: express.Response) => {
req.body = req.body || {};
const token: string = req.body.token;
if (typeof req.body.repoFullName !== "string" || typeof token !== "string") {
return replyError(new AnonymousError("invalid_request", { httpStatus: 400 }), res);
}
const repoFullName = req.body.repoFullName.split("/");
const repoId = req.body.repoId;
const commit = req.body.commit;
const anonymizerOptions = req.body.anonymizerOptions;
const contentOptions = req.body.contentOptions;
try {
await streamAnonymizedZip(
{
repoId,
organization: repoFullName[0],
repoName: repoFullName[1],
commit,
getToken: () => token,
anonymizerOptions: { ...anonymizerOptions, repoId },
contentOptions,
submodules: req.body.submodules,
},
res
);
} catch (error) {
const streaming = res.headersSent;
replyError(error, res);
if (streaming && !res.writableEnded) res.destroy();
}
}
);
router.post("/", async (req: express.Request, res: express.Response) => {
req.body = req.body || {};
const token: string = req.body.token;
if (typeof req.body.repoFullName !== "string" || typeof token !== "string") {
return replyError(new AnonymousError("invalid_request", { httpStatus: 400 }), res);
}
const repoFullName = req.body.repoFullName.split("/");
const repoId = req.body.repoId;
const fileSha = req.body.sha;
const fileSize: number | undefined =
typeof req.body.size === "number" ? req.body.size : undefined;
const commit = req.body.commit;
const filePath: string = req.body.filePath;
const anonymizerOptions = req.body.anonymizerOptions;
const anonymizer = new AnonymizeTransformer({ ...anonymizerOptions, repoId,
cacheGeneration: typeof req.body.cacheGeneration === "string" ? req.body.cacheGeneration : anonymizerOptions?.cacheGeneration,
});
// Defence in depth: the parent server validates filePath against
// FileModel before calling us, but the streamer joins this directly
// into the storage path on disk. Reject any segment that could escape
// the repo root, in case the streamer is ever exposed beyond the
// internal network or a buggy caller forwards an unvalidated path.
if (
typeof filePath !== "string" ||
filePath.length === 0 ||
filePath
.split(/[\\/]/)
.some((segment) => segment === ".." || segment === "")
) {
return replyError(new AnonymousError("invalid_file_path", { httpStatus: 400 }), res);
}
const source = new GitHubStream({
repoId,
organization: repoFullName[0],
repoName: repoFullName[1],
commit: commit,
cacheGeneration: typeof req.body.cacheGeneration === "string" ? req.body.cacheGeneration : undefined,
cacheRevision: typeof req.body.cacheRevision === "string" ? req.body.cacheRevision : anonymizerOptions?.cacheRevision,
getToken: () => token,
});
try {
const content = await source.getFileContentCache(
filePath,
repoId,
() => ({ sha: fileSha, size: fileSize, upstream: req.body.upstream }),
req.body.cacheOnly === true
);
if (res.destroyed || res.writableEnded) { content.destroy(); anonymizer.destroy(); return; }
const mime = lookup(filePath);
if (mime && !filePath.endsWith(".ts")) {
res.contentType(mime);
} else if (isTextFile(filePath)) {
res.contentType("text/plain");
}
if (await sendSharedContent(content, res, anonymizer.opt)) { anonymizer.destroy(); return; }
// Only declare Accept-Ranges: none for text files — they get rewritten on
// the fly so byte ranges aren't meaningful. For binary entries the
// transformer is a passthrough; let <video>/<audio> fall back to a full
// download instead of refusing to play (#538).
if (isTextFile(filePath)) {
res.header("Accept-Ranges", "none");
}
anonymizer.once("transform", (data) => {
if (!mime && data.isText) {
res.contentType("text/plain");
} else if (!mime && !data.isText) {
res.contentType("application/octet-stream");
}
});
function handleStreamError(error: Error) {
if (!content.closed && !content.destroyed) {
content.destroy();
}
const streaming = res.headersSent;
replyError(error, res);
if (streaming && !res.writableEnded) res.destroy();
anonymizer.destroy();
}
content
.on("error", error => { if (!res.destroyed) recordResponseFailure(res, "unknown", "local_abort"); handleStreamError(error); })
.pipe(anonymizer)
.on("error", error => { if (!res.destroyed) recordResponseFailure(res, "streamer", "local_abort"); handleStreamError(error); })
.pipe(res)
.on("error", handleStreamError)
.on("close", () => {
anonymizer.destroy();
if (!content.closed && !content.destroyed) {
content.destroy();
}
});
} catch (error) {
anonymizer.destroy();
if (req.body.cacheOnly === true && error instanceof Error && error.message === "cache_miss") {
res.setHeader("X-Anonymous-Cache-Miss", "1");
res.status(409).end();
return;
}
replyError(error, res);
}
});
export default router;