mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 17:13:33 +01:00
357 lines
20 KiB
JavaScript
357 lines
20 KiB
JavaScript
const { expect } = require("chai");
|
|
const { createHmac, generateKeyPairSync } = require("crypto");
|
|
const process = require("process");
|
|
const { URL, URLSearchParams } = require("node:url");
|
|
const express = require("express");
|
|
const mongoose = require("mongoose");
|
|
require("ts-node/register/transpile-only");
|
|
const config = require("../src/config").default;
|
|
const github = require("../src/core/GitHubUtils");
|
|
const app = require("../src/core/github-app");
|
|
const { setCredential } = require("../src/core/credentials");
|
|
const list = require("../src/core/user-repository-list");
|
|
const { UserRepositoryModel: Rows, UserRepositorySyncModel: Syncs } = require("../src/core/model/user-repositories");
|
|
const Users = require("../src/core/model/users/users.model").default;
|
|
const Credentials = require("../src/core/model/credentials/credentials.model").default;
|
|
const Installations = require("../src/core/model/github-installation").default;
|
|
const { githubAppWebhook, revokeGrant } = require("../src/server/routes/github-app");
|
|
|
|
const keys = JSON.stringify({ test: Buffer.alloc(32, 9).toString("base64") });
|
|
const pem = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs8", format: "pem" });
|
|
const repo = (id, name, extra = {}) => ({ id, full_name: name, private: id % 2 === 0, default_branch: "main",
|
|
updated_at: "2026-01-01T00:00:00Z", pushed_at: "2026-01-02T00:00:00Z", ...extra });
|
|
|
|
const describeMongo = process.env.TEST_MONGODB_URI ? describe : describe.skip;
|
|
describeMongo("stored repository picker list", function () {
|
|
this.timeout(20000);
|
|
let owner, other, previousConfig, previousOctokit, previousFetch, server, base, upstream, calls;
|
|
before(async () => {
|
|
previousConfig = { ...config };
|
|
Object.assign(config, { GITHUB_APP_ENABLED: true, GITHUB_APP_ID: "123", GITHUB_APP_CLIENT_ID: "Iv.test",
|
|
GITHUB_APP_PRIVATE_KEY: pem, CREDENTIAL_KEYS: keys, CREDENTIAL_ACTIVE_KEY_ID: "test",
|
|
GITHUB_APP_WEBHOOK_SECRET: "webhook-secret" });
|
|
await mongoose.connect(process.env.TEST_MONGODB_URI, { dbName: "repo_list_test_" + Date.now() });
|
|
await Promise.all([Rows, Syncs, Credentials, Installations].map(m => m.createIndexes()));
|
|
const api = express();
|
|
api.use("/github/app/webhook", githubAppWebhook);
|
|
api.use((req, _res, next) => {
|
|
req.user = { user: owner };
|
|
req.isAuthenticated = () => true;
|
|
req.logout = done => done();
|
|
next();
|
|
});
|
|
api.use("/api/user", require("../src/server/routes/user").default);
|
|
server = await new Promise(resolve => { const s = api.listen(0, "127.0.0.1", () => resolve(s)); });
|
|
base = `http://127.0.0.1:${server.address().port}`;
|
|
previousOctokit = github.octokit;
|
|
previousFetch = globalThis.fetch;
|
|
});
|
|
after(async () => {
|
|
github.octokit = previousOctokit;
|
|
globalThis.fetch = previousFetch;
|
|
await new Promise(resolve => server.close(resolve));
|
|
await mongoose.connection.dropDatabase();
|
|
await mongoose.disconnect();
|
|
Object.assign(config, previousConfig);
|
|
});
|
|
beforeEach(async () => {
|
|
await list.settleRepositorySyncs();
|
|
await Promise.all([Rows, Syncs, Users, Credentials, Installations].map(m => m.deleteMany({})));
|
|
owner = await Users.create({ username: "owner", externalIDs: { github: "10" } });
|
|
other = await Users.create({ username: "other", externalIDs: { github: "11" } });
|
|
calls = [];
|
|
// OAuth: GitHub /user/repos pages of 100, sorted by name.
|
|
upstream = Array.from({ length: 250 }, (_, i) => repo(1000 + i, `org/repo-${String(i).padStart(3, "0")}`));
|
|
github.octokit = () => ({ request: async (route, params) => {
|
|
calls.push(params.page);
|
|
const data = upstream.slice((params.page - 1) * 100, params.page * 100);
|
|
const more = params.page * 100 < upstream.length;
|
|
return { data, headers: more ? { link: '<https://api.github.com/user/repos?page=2>; rel="next"' } : {} };
|
|
} });
|
|
globalThis.fetch = previousFetch;
|
|
});
|
|
afterEach(async () => { await list.settleRepositorySyncs(); });
|
|
|
|
const picker = async (params = {}) => {
|
|
const response = await previousFetch(`${base}/api/user/repository_picker?${new URLSearchParams(params)}`);
|
|
return { status: response.status, body: await response.json() };
|
|
};
|
|
function webhook(event, payload, secret = "webhook-secret") {
|
|
const body = JSON.stringify(payload);
|
|
return previousFetch(base + "/github/app/webhook", { method: "POST", body, headers: {
|
|
"Content-Type": "application/json", "X-GitHub-Event": event,
|
|
"X-Hub-Signature-256": "sha256=" + createHmac("sha256", secret).update(body).digest("hex") } });
|
|
}
|
|
// GitHub App upstream: installations and their repositories, plus the installation check.
|
|
function mockApp(installations) {
|
|
globalThis.fetch = async (url, options) => {
|
|
if (String(url).startsWith(base)) return previousFetch(url, options);
|
|
const path = new URL(String(url)).pathname;
|
|
calls.push(path);
|
|
let body;
|
|
const listed = /^\/user\/installations\/(\d+)\/repositories$/.exec(path);
|
|
if (path === "/user/installations") body = { installations: Object.keys(installations).map(id => ({ id: Number(id), app_id: 123, suspended_at: null, account: { id: 10, login: "owner", type: "User" }, permissions: {} })) };
|
|
else if (listed) body = { repositories: installations[listed[1]] || [] };
|
|
else if (/^\/app\/installations\/\d+$/.test(path)) body = { id: Number(path.split("/").pop()), app_id: 123, suspended_at: null, account: { id: 10, login: "owner", type: "User" } };
|
|
else return new globalThis.Response("{}", { status: 404 });
|
|
return new globalThis.Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
|
|
};
|
|
}
|
|
const grantApp = ownerId => app.saveAppGrant(ownerId, { access_token: "ghu_" + ownerId, refresh_token: "ghr", expires_in: 3600, refresh_token_expires_in: 100000 });
|
|
const names = async ownerId => (await Rows.find({ ownerId: String(ownerId) }).sort({ nameKey: 1 }).lean()).map(r => r.fullName);
|
|
|
|
it("fetches an empty list once, then pages and searches from MongoDB", async () => {
|
|
await setCredential(owner.id, "oauth-token");
|
|
const first = await picker();
|
|
expect(first.status).to.equal(200);
|
|
expect(first.body.items).to.have.length(20);
|
|
expect(first.body.items[0]).to.deep.equal({ id: 1000, fullName: "org/repo-000", private: true });
|
|
expect(first.body.nextCursor).to.equal(20);
|
|
expect(first.body.webhooks).to.equal(false);
|
|
await list.settleRepositorySyncs();
|
|
expect(calls).to.deep.equal([1, 2, 3]);
|
|
expect(await Rows.countDocuments({ ownerId: owner.id, connection: "oauth" })).to.equal(250);
|
|
const stored = await Rows.findOne({ repositoryId: 1001 }).lean();
|
|
expect(stored).to.include({ fullName: "org/repo-001", private: false, defaultBranch: "main", connection: "oauth" });
|
|
expect(stored.pushedAt.toISOString()).to.equal("2026-01-02T00:00:00.000Z");
|
|
|
|
calls = [];
|
|
const page = await picker({ cursor: 240 });
|
|
expect(page.body.items.map(r => r.fullName)).to.deep.equal(Array.from({ length: 10 }, (_, i) => `org/repo-${240 + i}`));
|
|
expect(page.body.nextCursor).to.equal(null);
|
|
expect(page.body.syncedAt).to.be.a("string");
|
|
const search = await picker({ q: "REPO-12" });
|
|
expect(search.body.items.map(r => r.fullName)).to.deep.equal([...Array.from({ length: 10 }, (_, i) => `org/repo-12${i}`)]);
|
|
// Regex characters are literal.
|
|
expect((await picker({ q: "repo.01" })).body.items).to.deep.equal([]);
|
|
expect(calls).to.deep.equal([]);
|
|
});
|
|
|
|
it("returns the first page of a large account before pagination finishes", async () => {
|
|
await setCredential(owner.id, "oauth-token");
|
|
let release;
|
|
const gate = new Promise(resolve => { release = resolve; });
|
|
const original = github.octokit;
|
|
github.octokit = token => ({ request: async (route, params) => {
|
|
if (params.page > 1) await gate;
|
|
return original(token).request(route, params);
|
|
} });
|
|
const first = await picker();
|
|
expect(first.body.items).to.have.length(20);
|
|
expect(first.body.nextCursor).to.equal(20);
|
|
expect(first.body.syncing).to.equal(true);
|
|
expect(first.body.syncedAt).to.equal(null);
|
|
// A second request while the sync runs does not start another one.
|
|
expect((await picker()).body.syncing).to.equal(true);
|
|
release();
|
|
await list.settleRepositorySyncs();
|
|
expect(calls).to.deep.equal([1, 2, 3]);
|
|
const done = await picker();
|
|
expect(done.body.syncing).to.equal(false);
|
|
expect(await Rows.countDocuments()).to.equal(250);
|
|
});
|
|
|
|
it("runs one sync per list even when requests arrive together", async () => {
|
|
await setCredential(owner.id, "oauth-token");
|
|
const results = await Promise.all([picker(), picker(), picker()]);
|
|
await list.settleRepositorySyncs();
|
|
expect(calls.filter(page => page === 1)).to.have.length(1);
|
|
expect(results.every(r => r.status === 200)).to.equal(true);
|
|
// A lock held by another process blocks this one until it expires.
|
|
await Syncs.updateOne({ ownerId: owner.id }, { $set: { lockId: "elsewhere", lockUntil: new Date(Date.now() + 60000) } });
|
|
expect(await list.startRepositorySync(owner.id, "oauth")).to.equal(null);
|
|
await Syncs.updateOne({ ownerId: owner.id }, { $set: { lockUntil: new Date(Date.now() - 1) } });
|
|
expect(await list.startRepositorySync(owner.id, "oauth")).to.have.property("first");
|
|
});
|
|
|
|
it("refreshes only when forced, and drops repositories that disappeared", async () => {
|
|
await setCredential(owner.id, "oauth-token");
|
|
await picker();
|
|
await list.settleRepositorySyncs();
|
|
upstream = [repo(1, "new/one"), ...upstream.slice(1)];
|
|
calls = [];
|
|
await picker();
|
|
expect(calls).to.deep.equal([]);
|
|
// A forced refresh right after a sync is ignored.
|
|
await picker({ force: "1" });
|
|
expect(calls).to.deep.equal([]);
|
|
await Syncs.updateOne({ ownerId: owner.id }, { $set: { syncedAt: new Date(Date.now() - 60000) } });
|
|
const forced = await picker({ force: "1" });
|
|
expect(forced.status).to.equal(200);
|
|
await list.settleRepositorySyncs();
|
|
expect(calls).to.deep.equal([1, 2, 3]);
|
|
const stored = await names(owner.id);
|
|
expect(stored).to.include("new/one");
|
|
expect(stored).not.to.include("org/repo-000");
|
|
expect(stored).to.have.length(250);
|
|
});
|
|
|
|
it("resyncs a list older than 12 hours in the background", async () => {
|
|
await setCredential(owner.id, "oauth-token");
|
|
await picker();
|
|
await list.settleRepositorySyncs();
|
|
calls = [];
|
|
await Syncs.updateOne({ ownerId: owner.id }, { $set: { syncedAt: new Date(Date.now() - 11 * 3600_000) } });
|
|
await picker();
|
|
await list.settleRepositorySyncs();
|
|
expect(calls).to.deep.equal([]);
|
|
await Syncs.updateOne({ ownerId: owner.id }, { $set: { syncedAt: new Date(Date.now() - 13 * 3600_000) } });
|
|
expect((await picker()).status).to.equal(200);
|
|
await list.settleRepositorySyncs();
|
|
expect(calls).to.deep.equal([1, 2, 3]);
|
|
});
|
|
|
|
it("pauses after a rate limit instead of retrying on every load", async () => {
|
|
await setCredential(owner.id, "oauth-token");
|
|
github.octokit = () => ({ request: async () => {
|
|
calls.push("limited");
|
|
const error = new Error("API rate limit exceeded");
|
|
error.status = 403;
|
|
error.response = { headers: { "x-ratelimit-remaining": "0", "retry-after": "120" } };
|
|
throw error;
|
|
} });
|
|
expect((await picker()).status).to.equal(429);
|
|
await list.settleRepositorySyncs();
|
|
const state = await Syncs.findOne({ ownerId: owner.id }).lean();
|
|
expect(state.error).to.equal("github_rate_limit_exceeded");
|
|
expect(state.retryAfter.getTime()).to.be.greaterThan(Date.now() + 100000);
|
|
expect((await picker({ force: "1" })).status).to.equal(429);
|
|
expect(calls).to.deep.equal(["limited"]);
|
|
});
|
|
|
|
it("lists App installations and keeps OAuth and App lists apart", async () => {
|
|
await setCredential(owner.id, "oauth-token");
|
|
await grantApp(owner.id);
|
|
mockApp({ 4: [repo(7, "owner/app-repo")], 5: [repo(8, "acme/lab")] });
|
|
// The first installation's page answers at once; the next one follows.
|
|
expect((await picker({ connection: "github-app" })).body.items.map(r => r.fullName)).to.deep.equal(["owner/app-repo"]);
|
|
await list.settleRepositorySyncs();
|
|
const result = await picker({ connection: "github-app" });
|
|
expect(result.body.items.map(r => r.fullName)).to.deep.equal(["acme/lab", "owner/app-repo"]);
|
|
expect(result.body.webhooks).to.equal(true);
|
|
expect((await Rows.findOne({ repositoryId: 8 }).lean()).installationId).to.equal(5);
|
|
expect(await Rows.countDocuments({ connection: "oauth" })).to.equal(0);
|
|
expect((await picker()).body.items[0].fullName).to.equal("org/repo-000");
|
|
await list.settleRepositorySyncs();
|
|
await revokeGrant(owner.id, "github-app-user");
|
|
expect(await Rows.countDocuments({ connection: "github-app" })).to.equal(0);
|
|
expect(await Rows.countDocuments({ connection: "oauth" })).to.equal(250);
|
|
expect((await picker({ connection: "github-app" })).status).to.equal(401);
|
|
});
|
|
|
|
describe("GitHub App webhooks", () => {
|
|
beforeEach(async () => {
|
|
await grantApp(owner.id);
|
|
await grantApp(other.id);
|
|
mockApp({ 4: [repo(7, "owner/seven"), repo(9, "owner/nine")], 6: [repo(70, "acme/shared")] });
|
|
await picker({ connection: "github-app" });
|
|
await list.settleRepositorySyncs();
|
|
await Rows.insertMany([
|
|
{ ownerId: other.id, connection: "github-app", repositoryId: 7, fullName: "owner/seven", nameKey: "owner/seven", installationId: 4, syncedAt: new Date() },
|
|
]);
|
|
await Syncs.create({ ownerId: other.id, connection: "github-app", syncedAt: new Date() });
|
|
calls = [];
|
|
});
|
|
|
|
it("rejects unsigned or forged deliveries without changing lists", async () => {
|
|
const payload = { action: "deleted", installation: { id: 4, app_id: 123 } };
|
|
expect((await webhook("installation", payload, "wrong-secret")).status).to.equal(401);
|
|
expect(await Rows.countDocuments({ installationId: 4 })).to.equal(3);
|
|
});
|
|
|
|
it("adds and removes selected repositories idempotently", async () => {
|
|
const added = { action: "added", installation: { id: 4, app_id: 123, account: { id: 10, type: "User" } },
|
|
sender: { id: 10 }, repository_selection: "selected", repositories_added: [{ id: 12, full_name: "owner/twelve", private: true }] };
|
|
expect((await webhook("installation_repositories", added)).status).to.equal(204);
|
|
expect((await webhook("installation_repositories", added)).status).to.equal(204);
|
|
expect(await Rows.countDocuments({ repositoryId: 12, ownerId: owner.id })).to.equal(1);
|
|
// Another installation user is not told about a private repository; they resync instead.
|
|
expect(await Rows.countDocuments({ repositoryId: 12, ownerId: other.id })).to.equal(0);
|
|
expect((await Syncs.findOne({ ownerId: other.id }).lean()).needsSyncAt).to.be.instanceOf(Date);
|
|
expect((await Syncs.findOne({ ownerId: owner.id }).lean()).needsSyncAt).to.equal(undefined);
|
|
const search = await picker({ connection: "github-app", q: "twelve" });
|
|
expect(search.body.items).to.deep.equal([{ id: 12, fullName: "owner/twelve", private: true }]);
|
|
|
|
const removed = { action: "removed", installation: { id: 4, app_id: 123 }, sender: { id: 10 },
|
|
repositories_removed: [{ id: 7, full_name: "owner/seven" }, { id: 12, full_name: "owner/twelve" }] };
|
|
expect((await webhook("installation_repositories", removed)).status).to.equal(204);
|
|
expect((await webhook("installation_repositories", removed)).status).to.equal(204);
|
|
expect(await names(owner.id)).to.deep.equal(["acme/shared", "owner/nine"]);
|
|
expect(await names(other.id)).to.deep.equal([]);
|
|
});
|
|
|
|
it("removes an uninstalled installation's repositories and hides suspended ones", async () => {
|
|
const suspend = { action: "suspend", installation: { id: 6, app_id: 123 } };
|
|
expect((await webhook("installation", suspend)).status).to.equal(204);
|
|
expect((await picker({ connection: "github-app" })).body.items.map(r => r.fullName)).to.deep.equal(["owner/nine", "owner/seven"]);
|
|
expect((await webhook("installation", { action: "unsuspend", installation: { id: 6, app_id: 123 } })).status).to.equal(204);
|
|
expect((await Syncs.findOne({ ownerId: owner.id }).lean()).needsSyncAt).to.be.instanceOf(Date);
|
|
await list.settleRepositorySyncs();
|
|
expect((await picker({ connection: "github-app" })).body.items.map(r => r.fullName)).to.include("acme/shared");
|
|
await list.settleRepositorySyncs();
|
|
|
|
const deleted = { action: "deleted", installation: { id: 4, app_id: 123 } };
|
|
expect((await webhook("installation", deleted)).status).to.equal(204);
|
|
expect((await webhook("installation", deleted)).status).to.equal(204);
|
|
expect(await names(owner.id)).to.deep.equal(["acme/shared"]);
|
|
expect(await names(other.id)).to.deep.equal([]);
|
|
});
|
|
|
|
it("stores a new installation's repositories for the user who installed it", async () => {
|
|
const created = { action: "created", installation: { id: 8, app_id: 123, account: { id: 99, type: "Organization" } },
|
|
sender: { id: 11 }, repositories: [{ id: 80, full_name: "neworg/tool", private: false }] };
|
|
expect((await webhook("installation", created)).status).to.equal(204);
|
|
expect(await names(other.id)).to.deep.equal(["neworg/tool", "owner/seven"]);
|
|
expect((await Rows.findOne({ repositoryId: 80 }).lean()).installationId).to.equal(8);
|
|
expect(await Rows.countDocuments({ repositoryId: 80, ownerId: owner.id })).to.equal(0);
|
|
expect((await Syncs.findOne({ ownerId: other.id }).lean()).needsSyncAt).to.be.instanceOf(Date);
|
|
});
|
|
|
|
it("follows repository renames, visibility changes and deletions", async () => {
|
|
const renamed = { action: "renamed", installation: { id: 4 }, sender: { id: 10 },
|
|
repository: repo(7, "owner/seven-renamed", { private: false, updated_at: "2026-02-01T00:00:00Z" }) };
|
|
expect((await webhook("repository", renamed)).status).to.equal(204);
|
|
expect(await names(owner.id)).to.include("owner/seven-renamed");
|
|
expect(await names(other.id)).to.deep.equal(["owner/seven-renamed"]);
|
|
// A delayed older delivery does not undo the rename.
|
|
const stale = { ...renamed, repository: repo(7, "owner/seven-old", { updated_at: "2026-01-15T00:00:00Z" }) };
|
|
expect((await webhook("repository", stale)).status).to.equal(204);
|
|
expect(await names(other.id)).to.deep.equal(["owner/seven-renamed"]);
|
|
|
|
const privatized = { action: "privatized", installation: { id: 4 }, sender: { id: 10 },
|
|
repository: repo(7, "owner/seven-renamed", { private: true, updated_at: "2026-02-02T00:00:00Z" }) };
|
|
expect((await webhook("repository", privatized)).status).to.equal(204);
|
|
expect((await Rows.findOne({ ownerId: other.id, repositoryId: 7 }).lean()).private).to.equal(true);
|
|
expect((await Syncs.findOne({ ownerId: other.id }).lean()).needsSyncAt).to.be.instanceOf(Date);
|
|
|
|
const created = { action: "created", installation: { id: 4 }, sender: { id: 10 }, repository: repo(15, "owner/fresh") };
|
|
expect((await webhook("repository", created)).status).to.equal(204);
|
|
expect(await names(owner.id)).to.include("owner/fresh");
|
|
expect(await Rows.countDocuments({ repositoryId: 15, ownerId: other.id })).to.equal(0);
|
|
|
|
const deleted = { action: "deleted", installation: { id: 4 }, sender: { id: 10 }, repository: repo(7, "owner/seven-renamed") };
|
|
expect((await webhook("repository", deleted)).status).to.equal(204);
|
|
expect((await webhook("repository", deleted)).status).to.equal(204);
|
|
expect(await Rows.countDocuments({ repositoryId: 7 })).to.equal(0);
|
|
expect(calls.filter(c => c.startsWith("/user/"))).to.deep.equal([]);
|
|
});
|
|
|
|
it("lets a sync keep rows a webhook wrote while it ran", async () => {
|
|
let release;
|
|
const gate = new Promise(resolve => { release = resolve; });
|
|
const fetchApp = globalThis.fetch;
|
|
globalThis.fetch = async (url, options) => {
|
|
if (String(url).includes("/user/installations/6/repositories")) await gate;
|
|
return fetchApp(url, options);
|
|
};
|
|
await Syncs.updateOne({ ownerId: owner.id }, { $set: { syncedAt: new Date(Date.now() - 60000) } });
|
|
await picker({ connection: "github-app", force: "1" });
|
|
await webhook("installation_repositories", { action: "added", installation: { id: 4, app_id: 123, account: { id: 10, type: "User" } },
|
|
sender: { id: 10 }, repositories_added: [{ id: 13, full_name: "owner/during", private: false }] });
|
|
release();
|
|
await list.settleRepositorySyncs();
|
|
expect(await names(owner.id)).to.include("owner/during");
|
|
});
|
|
});
|
|
});
|