const { expect } = require("chai"); require("ts-node/register/transpile-only"); const http = require("node:http"); const { PassThrough } = require("node:stream"); const AnonymousError = require("../src/core/AnonymousError").default; const { codeUpstreamError } = require("../src/core/upstream-error"); const { handleError } = require("../src/server/routes/route-utils"); const { streamAnonymizedZip } = require("../src/core/zipStream"); function octokitError(status) { return Object.assign(new Error("Resource not accessible"), { name: "HttpError", status }); } describe("upstream error codes", () => { it("codes raw GitHub replies and leaves bugs alone", () => { const denied = codeUpstreamError(octokitError(403)); expect(denied).to.be.instanceOf(AnonymousError); expect(denied.message).to.equal("repo_not_accessible"); expect(denied.httpStatus).to.equal(403); const gotError = Object.assign(new Error("Response code 503"), { name: "HTTPError", response: { statusCode: 503 } }); expect(codeUpstreamError(gotError).message).to.equal("github_unavailable"); expect(codeUpstreamError(octokitError(429)).message).to.equal("github_rate_limit_exceeded"); const reset = Object.assign(new Error("socket hang up"), { name: "RequestError", code: "ECONNRESET" }); expect(codeUpstreamError(reset).message).to.equal("upstream_error"); const bug = new TypeError("x is undefined"); expect(codeUpstreamError(bug)).to.equal(bug); }); it("answers an Octokit failure with its code instead of internal_error", () => { let status, body; const res = { headersSent: false, status(code) { status = code; return this; }, json(value) { body = value; } }; handleError(octokitError(403), res); expect(status).to.equal(403); expect(body).to.deep.equal({ error: "repo_not_accessible" }); }); it("replies to a refused archive with a code before any ZIP byte", async () => { const server = http.createServer((req, res) => { res.statusCode = 404; res.end("Not Found"); }); await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); const { port } = server.address(); const GitHubDownload = require("../src/core/source/GitHubDownload").default; const original = GitHubDownload.prototype.getZipUrl; GitHubDownload.prototype.getZipUrl = async () => ({ url: `http://127.0.0.1:${port}/archive.zip` }); const response = new PassThrough(); let replied; response.headersSent = false; response.status = code => ({ json: body => { replied = { code, body }; response.end(); } }); try { await streamAnonymizedZip({ repoId: "test", organization: "owner", repoName: "private", commit: "c0ffee", getToken: () => "ghs_token", anonymizerOptions: { terms: [] } }, response); await new Promise(resolve => response.once("finish", resolve).resume()); } finally { GitHubDownload.prototype.getZipUrl = original; server.close(); } expect(replied).to.deep.equal({ code: 404, body: { error: "repo_not_accessible" } }); }); });