mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 17:13:33 +01:00
Merge remote-tracking branch 'origin/main' into feat/repo-list-sync
# Conflicts: # deploy/logging/sanitize.vrl # public/asset-manifest.json # public/script/vendor.min.js
This commit is contained in:
commit
07bdae9252
22 files changed
+394
-66
No files matched your search
@@ -0,0 +1,108 @@
|
||||
const { strict: assert } = require("node:assert");
|
||||
const { promises: fs } = require("node:fs");
|
||||
const http = require("node:http");
|
||||
const { tmpdir } = require("node:os");
|
||||
const { join } = require("node:path");
|
||||
const { PassThrough, Readable, Writable } = require("node:stream");
|
||||
const { pipeline } = require("node:stream/promises");
|
||||
const { setTimeout } = require("node:timers");
|
||||
const { createHash } = require("node:crypto");
|
||||
const express = require("express");
|
||||
require("ts-node/register/transpile-only");
|
||||
const config = require("../src/config").default;
|
||||
const { sharedBlobCache, closeBlobCaches } = require("../src/core/blob-cache");
|
||||
const { watchClientClose, isResponseCancellation } = require("../src/core/response-cancellation");
|
||||
const streamer = require("../src/streamer/route").default;
|
||||
|
||||
const body = Buffer.alloc(8 * 1024 * 1024, 7);
|
||||
const sha = createHash("sha1").update(`blob ${body.length}\0`).update(body).digest("hex");
|
||||
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
/** Collect the structured records a test run writes to stdout. */
|
||||
function captureLogs() {
|
||||
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;
|
||||
};
|
||||
return { records, restore: () => { process.stdout.write = write; } };
|
||||
}
|
||||
|
||||
describe("cached response cancellation", function () {
|
||||
this.timeout(15000);
|
||||
let root, old;
|
||||
beforeEach(async () => {
|
||||
old = { ...config }; closeBlobCaches();
|
||||
root = await fs.mkdtemp(join(tmpdir(), "cached-cancel-"));
|
||||
Object.assign(config, { STORAGE: "filesystem", FOLDER: root, SHARED_CACHE_ENABLED: true,
|
||||
SHARED_CACHE_PATH: join(root, "cache"), SHARED_CACHE_BYTES: 64 * 1024 ** 2,
|
||||
SHARED_CACHE_RESULT_BYTES: 32 * 1024 ** 2, SHARED_CACHE_MAX_FILE_BYTES: 16 * 1024 ** 2,
|
||||
SHARED_CACHE_FREE_BYTES: 0, BILLING_ENABLED: false });
|
||||
});
|
||||
afterEach(async () => {
|
||||
closeBlobCaches(); Object.assign(config, old);
|
||||
await fs.rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("does not log a client that stops a cached download as a server error", async () => {
|
||||
const seeded = await sharedBlobCache().getOrFill(`git-${sha}`, async () => Readable.from([body]), async () => `git-${sha}`, body.length);
|
||||
for await (const chunk of seeded) void chunk;
|
||||
const app = express(); app.use(express.json()); app.use("/api", streamer);
|
||||
const server = await new Promise((resolve) => { const s = app.listen(0, "127.0.0.1", () => resolve(s)); });
|
||||
const logs = captureLogs();
|
||||
try {
|
||||
await new Promise((resolve) => {
|
||||
const req = http.request({ host: "127.0.0.1", port: server.address().port, path: "/api", method: "POST",
|
||||
headers: { "content-type": "application/json" } }, (res) => {
|
||||
res.once("data", () => req.destroy());
|
||||
res.on("error", () => undefined);
|
||||
res.on("close", resolve);
|
||||
});
|
||||
req.on("error", resolve);
|
||||
req.end(JSON.stringify({ token: "", repoFullName: "owner/repo", repoId: "anon", sha, size: body.length,
|
||||
filePath: "video.bin", anonymizerOptions: { terms: [], filePath: "video.bin" } }));
|
||||
});
|
||||
await wait(300);
|
||||
} finally {
|
||||
logs.restore();
|
||||
server.closeAllConnections();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
const faults = logs.records.filter((record) => record.severity === "error" || record.severity === "warn");
|
||||
assert.deepEqual(faults, []);
|
||||
});
|
||||
|
||||
it("names a client disconnect but keeps a source that ended early as a failure", async () => {
|
||||
const attribute = async (closeFirst) => {
|
||||
const source = new PassThrough();
|
||||
// The "late" response never acknowledges its write, like a slow socket.
|
||||
const response = new Writable({ write(_chunk, _encoding, done) { if (closeFirst !== "late") done(); } });
|
||||
const clientClosed = watchClientClose(response, source);
|
||||
const piping = pipeline(source, response);
|
||||
source.write("partial");
|
||||
if (closeFirst === "late") source.end();
|
||||
await wait(5);
|
||||
if (closeFirst !== "source") response.destroy();
|
||||
else source.destroy();
|
||||
const error = await piping.then(() => undefined, (failure) => failure);
|
||||
return { error, clientClosed: clientClosed(), cancellation: isResponseCancellation(error, response) };
|
||||
};
|
||||
const client = await attribute("client");
|
||||
assert.equal(client.error.code, "ERR_STREAM_PREMATURE_CLOSE");
|
||||
assert.equal(client.clientClosed, true);
|
||||
// The source was fully read but the response had not flushed yet.
|
||||
const late = await attribute("late");
|
||||
assert.equal(late.error.code, "ERR_STREAM_PREMATURE_CLOSE");
|
||||
assert.equal(late.clientClosed, true);
|
||||
const source = await attribute("source");
|
||||
assert.equal(source.error.code, "ERR_STREAM_PREMATURE_CLOSE");
|
||||
assert.equal(source.clientClosed, false);
|
||||
assert.equal(source.cancellation, false);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
const {expect}=require('chai');
|
||||
const {setTimeout}=require('node:timers');
|
||||
require('ts-node/register/transpile-only');
|
||||
const mongoose=require('mongoose');
|
||||
const {installDatabaseTiming}=require('../src/core/database-timing');
|
||||
const {monitorRequests,RequestMetrics}=require('../src/core/request-monitoring');
|
||||
const express=require('express');
|
||||
const http=require('node:http');
|
||||
const {setTimeout:delay}=require('node:timers/promises');
|
||||
describe('database execution timing',()=>{
|
||||
it('preserves query receiver, result and failure while measuring execution once',async()=>{
|
||||
const Model=mongoose.model("TimingFixture",new mongoose.Schema({}));
|
||||
@@ -14,7 +14,7 @@ describe('database execution timing',()=>{
|
||||
installDatabaseTiming();const wrapped=mongoose.Query.prototype.exec;installDatabaseTiming();expect(mongoose.Query.prototype.exec).equal(wrapped);
|
||||
app.use(monitorRequests('api',new RequestMetrics(),{info:(_,row)=>logs.push(row),warn:(_,row)=>logs.push(row)}));
|
||||
app.get('/',async(_req,res)=>{
|
||||
const query=Model.find();query._find=async function(){expect(this).equal(query);await new Promise(r=>setTimeout(r,20));return ['ok'];};
|
||||
const query=Model.find();query._find=async function(){expect(this).equal(query);await delay(20);return ['ok'];};
|
||||
expect(await query.exec()).deep.equal(['ok']);
|
||||
const failed=Model.find();const error=new Error('PRIVATE query');failed._find=async()=>{throw error;};
|
||||
try{await failed.exec();throw Error('expected failure');}catch(e){expect(e).equal(error);}
|
||||
|
||||
@@ -361,7 +361,9 @@ const uri = process.env.PERFORMANCE_MONGO_URI;
|
||||
expect(saved.githubAccess.revision).not.to.equal("old-access"); expect(saved.anonymizeDate.getTime()).to.be.greaterThan(1);
|
||||
expect(saved.options.terms).to.deep.equal(["after"]);
|
||||
expect(await File.countDocuments({ repoId: row.repoId })).to.equal(0); expect(await Path.countDocuments({ repoId: row.repoId })).to.equal(0);
|
||||
expect(jobs).to.have.length(1); expect(jobs[0][1]).to.deep.equal({ repoId: row.repoId });
|
||||
expect(jobs).to.have.length(1);
|
||||
const { logJobId, ...jobData } = jobs[0][1];
|
||||
expect(jobData).to.deep.equal({ repoId: row.repoId }); expect(logJobId).to.match(/^[a-f0-9-]{36}$/);
|
||||
});
|
||||
|
||||
for (const [label, change] of [...changedSnapshots, ["settings revision", { settingsSavedAt: new Date(1) }]] ) {
|
||||
|
||||
@@ -996,13 +996,14 @@ const uri = process.env.PERFORMANCE_MONGO_URI;
|
||||
const row = await Repo.create({ repoId: "active-staged", status: "ready", statusDate: new Date(), lastView: new Date(),
|
||||
treeGeneration: "old", source: { type: "GitHubStream" }, options: { expirationMode: "never" } });
|
||||
await File.create({ repoId: row.repoId, treeGeneration: "old", path: "", name: "old.txt" });
|
||||
const repo = new Repository(row), updateMany = File.updateMany;
|
||||
// Completion clears markers through the driver collection (clearStagedRowsInBatches).
|
||||
const repo = new Repository(row), updateMany = File.collection.updateMany;
|
||||
Object.defineProperty(repo, "source", { get: () => ({ getFiles: async () => [{ path: "", name: "active.txt", size: 1 }] }) });
|
||||
File.updateMany = function (filter, ...args) {
|
||||
if (filter.treeStaged) return { exec: async () => { throw Error("marker cleanup interrupted"); } };
|
||||
File.collection.updateMany = function (filter, ...args) {
|
||||
if (filter.treeStaged) return Promise.reject(Error("marker cleanup interrupted"));
|
||||
return updateMany.call(this, filter, ...args);
|
||||
};
|
||||
try { await repo.files({ force: true }); } finally { File.updateMany = updateMany; }
|
||||
try { await repo.files({ force: true }); } finally { File.collection.updateMany = updateMany; }
|
||||
expect(await File.countDocuments({ treeStaged: true })).to.equal(1);
|
||||
await require("../src/server/schedule").runRepositoryStatusCheck();
|
||||
expect((await File.find({ repoId: row.repoId })).map(file => file.name)).to.deep.equal(["active.txt"]);
|
||||
|
||||
@@ -6,7 +6,7 @@ const path = require("node:path");
|
||||
const net = require("node:net");
|
||||
const { randomBytes } = require("node:crypto");
|
||||
const { once } = require("node:events");
|
||||
const { setTimeout } = require("node:timers");
|
||||
const { setTimeout, clearTimeout } = require("node:timers");
|
||||
const { fetch } = globalThis;
|
||||
const mongoose = require("mongoose");
|
||||
require("ts-node/register/transpile-only");
|
||||
@@ -51,10 +51,20 @@ const uri = process.env.PERFORMANCE_MONGO_URI;
|
||||
});
|
||||
const messages = []; child.on("message", message => messages.push(message));
|
||||
const ready = new Promise((resolve, reject) => {
|
||||
// Fail before the mocha timeout so callers' finally blocks always stop the child.
|
||||
const deadline = setTimeout(() => reject(Error("Streamer did not report streamer_started")), 20000);
|
||||
const settle = (fn, value) => { clearTimeout(deadline); fn(value); };
|
||||
let logs = "";
|
||||
child.stdout.on("data", chunk => { logs += chunk; if (logs.includes("streamer started")) resolve(); });
|
||||
child.stdout.on("data", chunk => {
|
||||
logs += chunk; const lines = logs.split("\n"); logs = lines.pop();
|
||||
for (const line of lines) {
|
||||
let record; try { record = JSON.parse(line); } catch { continue; }
|
||||
if (record.event === "streamer_started") settle(resolve);
|
||||
}
|
||||
});
|
||||
child.stderr.on("data", () => {});
|
||||
child.once("error", reject); child.once("exit", code => reject(Error(`Streamer exited ${code} before serving`)));
|
||||
child.once("error", error => settle(reject, error));
|
||||
child.once("exit", code => settle(reject, Error(`Streamer exited ${code} before serving`)));
|
||||
});
|
||||
ready.catch(() => {});
|
||||
return { child, ready, messages, directory, stale, url: `http://127.0.0.1:${port}` };
|
||||
|
||||
@@ -88,7 +88,9 @@ describe("large anonymization resources", function () {
|
||||
maxOutput: 1000000, context: { mask: "XXXX", hostname: "localhost" } }, text.length, controller.signal);
|
||||
} catch (error) { failure = error; }
|
||||
expect(failure).to.be.instanceOf(Error);
|
||||
expect(failure.message).to.match(/timed out after 1000ms/);
|
||||
// Workers report fixed codes only; the elapsed bound proves the 1s regex deadline,
|
||||
// not the 15s pool deadline that reports the same code, stopped the job.
|
||||
expect(failure.message).to.equal("anonymization_deadline_exceeded");
|
||||
expect(Date.now() - started).to.be.lessThan(8000);
|
||||
let exists = true;
|
||||
try { await fs.access(output); } catch (error) { if (error.code === "ENOENT") exists = false; else throw error; }
|
||||
|
||||
@@ -207,11 +207,13 @@ describe("repository activity dates", () => {
|
||||
});
|
||||
}
|
||||
}
|
||||
// FileModel.exists() returns a Mongoose query; production code chains .hint().
|
||||
const missingFile = () => Object.assign(Promise.resolve(null), { hint() { return this; } });
|
||||
it("returns publication and settings dates independently of the older source commit", async () => {
|
||||
const repo = repository(); auth(repo);
|
||||
repo.model.settingsSavedAt = new Date("2026-03-01");
|
||||
repo.model.publishedAt = new Date("2026-02-01");
|
||||
stub(Files, "exists", async () => null);
|
||||
stub(Files, "exists", missingFile);
|
||||
let body;
|
||||
await handler("repository-public", "/:repoId/options", "get")({}, { header: () => {}, json: value => { body = value; } });
|
||||
expect(body.lastUpdateDate).to.deep.equal(repo.model.settingsSavedAt);
|
||||
@@ -220,7 +222,7 @@ describe("repository activity dates", () => {
|
||||
});
|
||||
it("does not invent publication or settings dates for legacy repositories", async () => {
|
||||
const repo = repository(); auth(repo);
|
||||
stub(Files, "exists", async () => null);
|
||||
stub(Files, "exists", missingFile);
|
||||
let body;
|
||||
await handler("repository-public", "/:repoId/options", "get")({}, { header: () => {}, json: value => { body = value; } });
|
||||
expect(body.publishedAt).to.equal(undefined);
|
||||
@@ -232,7 +234,7 @@ describe("repository activity dates", () => {
|
||||
const repo = repository(); auth(repo);
|
||||
repo.model.options.expirationMode = "remove";
|
||||
repo.model.options.expirationDate = new Date("2099-01-01");
|
||||
stub(Files, "exists", async () => null);
|
||||
stub(Files, "exists", missingFile);
|
||||
let body;
|
||||
await handler("repository-public", "/:repoId/options", "get")({}, { header: () => {}, json: value => { body = value; } });
|
||||
expect(body.expirationDate).to.deep.equal(new Date("2099-01-01"));
|
||||
|
||||
@@ -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" }));
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
const {expect}=require('chai');
|
||||
const {setTimeout}=require('node:timers');
|
||||
const express=require('express');
|
||||
const http=require('node:http');
|
||||
const {setTimeout}=require('node:timers');
|
||||
const {Readable}=require('node:stream');
|
||||
require('ts-node/register/transpile-only');
|
||||
const {monitorRequests,RequestMetrics}=require('../src/core/request-monitoring');
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
const { strict: assert } = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const ts = require("typescript");
|
||||
require("ts-node/register/transpile-only");
|
||||
const { logRecord, LOG_ERROR_CODES } = require("../src/core/log-record");
|
||||
const { serializeError } = require("../src/core/logger");
|
||||
const { billingError } = require("../src/core/billing/config");
|
||||
const { consumeFlow } = require("../src/server/routes/github-app");
|
||||
|
||||
const root = path.join(__dirname, "..");
|
||||
const vrl = fs.readFileSync(path.join(root, "deploy/logging/sanitize.vrl"), "utf8");
|
||||
const collectorCodes = new Set(JSON.parse(vrl.match(/if includes\((\[.*?\]), record\.errorCode\)/)[1]));
|
||||
|
||||
// Independent of the generator: string codes passed straight to the error
|
||||
// factories anywhere under src/.
|
||||
function thrownCodes() {
|
||||
const codes = new Map();
|
||||
const literals = (node, file) => {
|
||||
if (!node) return;
|
||||
if (ts.isStringLiteralLike(node)) { if (/^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+$/.test(node.text)) codes.set(node.text, file); }
|
||||
else if (ts.isConditionalExpression(node)) { literals(node.whenTrue, file); literals(node.whenFalse, file); }
|
||||
else if (ts.isParenthesizedExpression(node)) literals(node.expression, file);
|
||||
};
|
||||
const walk = (dir) => {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const file = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) { walk(file); continue; }
|
||||
if (!file.endsWith(".ts") || file.endsWith(".d.ts")) continue;
|
||||
const source = ts.createSourceFile(file, fs.readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true);
|
||||
(function visit(node) {
|
||||
if ((ts.isNewExpression(node) || ts.isCallExpression(node)) && ts.isIdentifier(node.expression) &&
|
||||
["AnonymousError", "billingError", "appError"].includes(node.expression.text) && node.arguments?.length) {
|
||||
literals(node.arguments[0], path.relative(root, file));
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
})(source);
|
||||
}
|
||||
};
|
||||
walk(path.join(root, "src"));
|
||||
return codes;
|
||||
}
|
||||
|
||||
describe("thrown error codes reach the logs", () => {
|
||||
it("keeps the billing expiration and GitHub App state codes", () => {
|
||||
const billing = logRecord("warn", "route", [serializeError(billingError("invalid_billing_expiration"))]);
|
||||
assert.equal(billing.errorCode, "invalid_billing_expiration");
|
||||
let state;
|
||||
try { consumeFlow(undefined, "state"); } catch (error) { state = error; }
|
||||
assert.equal(state.message, "invalid_auth_state");
|
||||
assert.equal(logRecord("warn", "route", [serializeError(state)]).errorCode, "invalid_auth_state");
|
||||
for (const code of ["invalid_billing_expiration", "invalid_auth_state", "streamer_unreachable"]) {
|
||||
assert.ok(collectorCodes.has(code), `${code} is missing from sanitize.vrl`);
|
||||
}
|
||||
});
|
||||
|
||||
it("allowlists every code passed to an error factory", () => {
|
||||
const missing = [...thrownCodes()].filter(([code]) => !LOG_ERROR_CODES.has(code) || !collectorCodes.has(code))
|
||||
.map(([code, file]) => `${code} (${file})`);
|
||||
assert.deepEqual(missing, [], "run node scripts/generate-log-diagnostics.js");
|
||||
});
|
||||
|
||||
it("lets the collector keep every code the logger emits", () => {
|
||||
assert.deepEqual([...LOG_ERROR_CODES].filter((code) => !collectorCodes.has(code)), []);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user