Files
anonymous_github/test/external-request-logging.test.js
T
Thomas DurieuxandClaude Opus 5.5 c9342e4b7d fix(logging): tell our cancellations from upstream resets, keep codes, catch cut bodies
- A request we destroy ourselves is ABORT_ERR, not ECONNRESET, and a
  fetch abort is ABORT_ERR rather than upstream_error.
- undici and DNS codes the schema lacks (UND_ERR_SOCKET, EAI_AGAIN, ...)
  fold into the closest kept code, so a failure always has one.
- node:http records are written when the body ends: a stream cut after
  its headers logs ECONNRESET with its status instead of a plain 200.
- Successful storage reads log at debug to keep info volume down.

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

168 lines
9.1 KiB
JavaScript

const { strict: assert } = require("node:assert");
const http = require("node:http");
const { randomUUID } = require("node:crypto");
const { setTimeout } = require("node:timers");
const { Agent } = require("undici");
const got = require("got");
require("ts-node/register/transpile-only");
const { logContext } = require("../src/core/log-context");
const { installExternalRequestLogging, githubEndpoint, externalErrorCode } = require("../src/core/external-request-logging");
const localAgent = new http.Agent({ lookup: (host, options, callback) => lookup(host, options, callback) });
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Resolve every name to the local fixture so requests look like they go to GitHub.
const lookup = (_host, options, callback) => {
if (typeof options === "function") callback = options;
if (options && options.all) callback(null, [{ address: "127.0.0.1", family: 4 }]);
else callback(null, "127.0.0.1", 4);
};
async function captureLogs(run) {
const records = [];
const write = process.stdout.write;
process.stdout.write = function (chunk, ...rest) {
for (const line of String(chunk).split("\n")) {
try { const record = JSON.parse(line); if (record && record.severity) { records.push(record); continue; } } catch { /* not a record */ }
if (line) write.call(process.stdout, line + "\n");
}
const callback = rest.find((arg) => typeof arg === "function");
if (callback) callback();
return true;
};
try { await run(); await wait(50); } finally { process.stdout.write = write; }
return records.filter((record) => record.event === "external_request");
}
describe("external request logging", function () {
this.timeout(10000);
let server, port;
before(async () => {
installExternalRequestLogging();
server = http.createServer((req, res) => {
req.resume();
if (req.url.startsWith("/login/oauth")) { res.writeHead(200, { "content-type": "application/json" }); res.end("{}"); return; }
if (req.url.startsWith("/slow")) return; // never answers
if (req.url.startsWith("/reset")) { req.socket.destroy(); return; }
if (req.url.startsWith("/cut")) { res.writeHead(200, { "content-length": "100" }); res.write("partial"); setTimeout(() => req.socket.destroy(), 20); return; }
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ message: "Not Found" }));
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
port = server.address().port;
});
after(() => new Promise((resolve) => server.close(resolve)));
it("labels GitHub endpoints without owners, repositories, paths or identifiers", () => {
assert.equal(githubEndpoint("/repos/secret-owner/secret-repo/contents/private/notes.md?ref=main"), "/repos/{owner}/{repo}/contents/*");
assert.equal(githubEndpoint("/repos/secret-owner/secret-repo"), "/repos/{owner}/{repo}");
assert.equal(githubEndpoint("/repos/o/r/git/trees/abc123?recursive=1"), "/repos/{owner}/{repo}/git/trees/*");
assert.equal(githubEndpoint("/repos/o/r/pulls/12"), "/repos/{owner}/{repo}/pulls/{id}");
assert.equal(githubEndpoint("/user/repos?per_page=100&page=2"), "/user/repos");
assert.equal(githubEndpoint("/applications/Iv1.client/token"), "/applications/{id}/token");
assert.equal(githubEndpoint("/app/installations/42/access_tokens"), "/app/installations/{id}/access_tokens");
assert.equal(githubEndpoint("/login/oauth/access_token"), "/login/oauth/access_token");
assert.equal(githubEndpoint("/secret-owner/secret-repo.git/info/refs"), "/{id}/{id}/{id}/refs");
});
it("keeps only fixed endpoint labels in the logger and the collector", () => {
const { logRecord } = require("../src/core/log-record");
const { UPSTREAM_ENDPOINT_SEGMENTS } = require("../src/core/log-schema");
const endpoint = (value) => logRecord("info", "external-request", ["external request", { upstreamEndpoint: value }]).upstreamEndpoint;
assert.equal(endpoint("/repos/{owner}/{repo}/contents/*"), "/repos/{owner}/{repo}/contents/*");
assert.equal(endpoint("/repos/secretowner/secretrepo"), undefined);
assert.equal(endpoint("/user/reposx"), undefined);
const vrl = require("node:fs").readFileSync(require("node:path").join(__dirname, "../deploy/logging/sanitize.vrl"), "utf8");
const segments = /record\.upstreamEndpoint\), r'\^\/\(\?:\(\?:([a-z_|]+)\|/.exec(vrl);
assert.ok(segments, "collector rule for upstreamEndpoint");
assert.deepEqual(segments[1].split("|"), UPSTREAM_ENDPOINT_SEGMENTS);
});
it("logs a got request to GitHub with its status and the caller's requestId", async () => {
const requestId = randomUUID();
let status;
const records = await captureLogs(() => logContext.run({ requestId }, async () => {
const response = await got(`http://api.github.com:${port}/repos/secret-owner/secret-repo/contents/private.md?ref=main`,
{ agent: { http: localAgent }, throwHttpErrors: false, retry: 0 });
status = response.statusCode;
}));
assert.equal(status, 404);
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].severity, "info");
assert.equal(records[0].requestId, requestId);
assert.equal(records[0].upstreamHost, "api.github.com");
assert.equal(records[0].upstreamMethod, "GET");
assert.equal(records[0].upstreamStatus, 404);
assert.equal(records[0].upstreamEndpoint, "/repos/{owner}/{repo}/contents/*");
assert.equal(typeof records[0].ms, "number");
assert.ok(!JSON.stringify(records).includes("secret"), JSON.stringify(records));
});
it("logs a fetch request (the Octokit transport)", async () => {
const requestId = randomUUID();
const records = await captureLogs(() => logContext.run({ requestId }, async () => {
const response = await globalThis.fetch(`http://github.com:${port}/login/oauth/access_token?code=secret-code`,
{ method: "POST", body: "client_secret=secret", dispatcher: new Agent({ connect: { lookup } }) });
await response.text();
}));
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].requestId, requestId);
assert.equal(records[0].upstreamHost, "github.com");
assert.equal(records[0].upstreamMethod, "POST");
assert.equal(records[0].upstreamStatus, 200);
assert.equal(records[0].upstreamEndpoint, "/login/oauth/access_token");
assert.ok(!JSON.stringify(records).includes("secret"), JSON.stringify(records));
});
it("logs a connection failure with its code and no status", async () => {
const closed = http.createServer();
await new Promise((resolve) => closed.listen(0, "127.0.0.1", resolve));
const closedPort = closed.address().port;
await new Promise((resolve) => closed.close(resolve));
const records = await captureLogs(() => got(`http://codeload.github.com:${closedPort}/o/r/zip/main`,
{ agent: { http: localAgent }, retry: 0 }).catch(() => undefined));
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].upstreamHost, "codeload.github.com");
assert.equal(records[0].errorCode, "ECONNREFUSED");
assert.equal(records[0].upstreamStatus, undefined);
assert.equal(records[0].upstreamEndpoint, undefined);
});
it("logs our own cancellation as ABORT_ERR, not a reset by GitHub", async () => {
const records = await captureLogs(async () => {
const stream = got.stream(`http://api.github.com:${port}/slow`, { agent: { http: localAgent }, retry: 0 });
stream.on("error", () => {});
await wait(50);
stream.destroy();
});
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].errorCode, "ABORT_ERR");
});
it("keeps a code for undici socket errors", async () => {
const records = await captureLogs(() => globalThis.fetch(`http://api.github.com:${port}/reset`,
{ dispatcher: new Agent({ connect: { lookup } }) }).catch(() => undefined));
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].errorCode, "ECONNRESET");
assert.equal(externalErrorCode({ code: "UND_ERR_HEADERS_TIMEOUT" }), "ETIMEDOUT");
assert.equal(externalErrorCode({ code: "EAI_AGAIN" }), "ENOTFOUND");
assert.equal(externalErrorCode({ code: "SOMETHING_NEW" }), "upstream_error");
assert.equal(externalErrorCode({ name: "AbortError" }), "ABORT_ERR");
});
it("reports a body cut after its headers as a failure, not a 200", async () => {
const records = await captureLogs(() => got(`http://codeload.github.com:${port}/cut`,
{ agent: { http: localAgent }, retry: 0 }).catch(() => undefined));
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].upstreamStatus, 200);
assert.equal(records[0].errorCode, "ECONNRESET");
});
it("skips internal hops such as the streamer", async () => {
const records = await captureLogs(async () => {
await got(`http://127.0.0.1:${port}/api/file`, { throwHttpErrors: false, retry: 0 });
await got(`http://streamer:${port}/api/file`, { agent: { http: localAgent }, throwHttpErrors: false, retry: 0 });
});
assert.deepEqual(records, []);
});
});