CI / build (push) Successful in 3m19s
CI / gates (push) Successful in 1m5s
CI / record (push) Skipped
Reusable / Qodana / Qodana (push) Successful in 3m7s
Qodana / qodana (push) Successful in 3m7s
Reusable / Security / Secrets (gitleaks) (push) Successful in 10s
Reusable / Security / Rust (cargo-deny) (push) Skipped
Reusable / Security / .NET (NuGetAudit) (push) Skipped
Reusable / Security / SAST (Opengrep) (push) Successful in 24s
Reusable / Security / Dependencies (osv-scanner) (push) Successful in 17s
Security / security (push) Successful in 52s
CI / deploy (push) Successful in 1m9s
- ci: move the workflows to Gitea Actions (D38) - feat(site): source on Gitea, issues and bug reports on the GitLab mirror - docs: where the project lives now — Gitea, the GitLab mirror, e-mail - docs: the suite on Gitea — D38, CI/CD rewritten, every GitHub-era claim synced - fix(ci): what the first Gitea runs found — Qodana and gitleaks - fix(ci): .gitleaksignore describes the Sonar key instead of quoting it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
384 lines
14 KiB
TypeScript
384 lines
14 KiB
TypeScript
// SPDX-License-Identifier: GPL-3.0-only
|
|
// Copyright (C) 2026 poli0981 (SkullMute)
|
|
//
|
|
// gitea.mjs — the bots' pull requests, issues, dispatches and commit statuses
|
|
// (D38). The script runs for real, as the workflows run it, against a small
|
|
// in-process stand-in for Gitea's REST API that records every request.
|
|
|
|
import { createServer, type IncomingMessage, type Server } from 'node:http';
|
|
import type { AddressInfo } from 'node:net';
|
|
import { readFileSync } from 'node:fs';
|
|
import { join } from 'node:path';
|
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|
import { project, runAsync } from './fixture';
|
|
|
|
interface Row {
|
|
number: number;
|
|
title: string;
|
|
body: string;
|
|
state: string;
|
|
labels: number[];
|
|
head?: { ref: string };
|
|
base?: { ref: string };
|
|
}
|
|
|
|
interface Fake {
|
|
labels: { id: number; name: string }[];
|
|
pulls: Row[];
|
|
issues: Row[];
|
|
comments: { issue: number; body: string }[];
|
|
dispatches: { file: string; ref: string }[];
|
|
statuses: { sha: string; state: string; context: string; target_url?: string }[];
|
|
requests: string[];
|
|
failOn?: string;
|
|
}
|
|
|
|
let fake: Fake;
|
|
let server: Server;
|
|
let api = '';
|
|
|
|
const PREFIX = '/api/v1/repos/poli0981/softharbor';
|
|
|
|
async function bodyOf(req: IncomingMessage): Promise<Record<string, unknown>> {
|
|
let text = '';
|
|
for await (const chunk of req) text += chunk;
|
|
return text ? (JSON.parse(text) as Record<string, unknown>) : {};
|
|
}
|
|
|
|
function page<T>(rows: T[], url: URL): T[] {
|
|
const limit = Number(url.searchParams.get('limit'));
|
|
const n = Number(url.searchParams.get('page'));
|
|
return rows.slice((n - 1) * limit, n * limit);
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
fake = {
|
|
labels: [
|
|
{ id: 39, name: 'dependencies' },
|
|
{ id: 40, name: 'security' },
|
|
],
|
|
pulls: [],
|
|
issues: [],
|
|
comments: [],
|
|
dispatches: [],
|
|
statuses: [],
|
|
requests: [],
|
|
};
|
|
server = createServer((req, res) => {
|
|
void (async () => {
|
|
const url = new URL(req.url ?? '/', 'http://x');
|
|
const path = url.pathname.slice(PREFIX.length);
|
|
const body = await bodyOf(req);
|
|
fake.requests.push(`${req.method} ${path}`);
|
|
const send = (status: number, data?: unknown) => {
|
|
res.writeHead(status, { 'content-type': 'application/json' });
|
|
res.end(data === undefined ? '' : JSON.stringify(data));
|
|
};
|
|
if (req.headers.authorization !== 'token job-token') return send(401, { message: 'no' });
|
|
if (!url.pathname.startsWith(PREFIX)) return send(404, { message: 'repo' });
|
|
if (fake.failOn && path.startsWith(fake.failOn)) return send(500, { message: 'boom' });
|
|
|
|
let m: RegExpMatchArray | null;
|
|
if (req.method === 'GET' && path === '/labels') return send(200, page(fake.labels, url));
|
|
if (req.method === 'GET' && path === '/pulls')
|
|
return send(
|
|
200,
|
|
page(
|
|
fake.pulls.filter((p) => p.state === 'open'),
|
|
url,
|
|
),
|
|
);
|
|
if (req.method === 'GET' && path === '/issues')
|
|
return send(
|
|
200,
|
|
page(
|
|
fake.issues.filter((i) => i.state === 'open'),
|
|
url,
|
|
),
|
|
);
|
|
if (req.method === 'POST' && path === '/pulls') {
|
|
const pull: Row = {
|
|
number: 100 + fake.pulls.length,
|
|
title: String(body['title']),
|
|
body: String(body['body']),
|
|
state: 'open',
|
|
labels: body['labels'] as number[],
|
|
head: { ref: String(body['head']) },
|
|
base: { ref: String(body['base']) },
|
|
};
|
|
fake.pulls.push(pull);
|
|
return send(201, pull);
|
|
}
|
|
if (req.method === 'POST' && path === '/issues') {
|
|
const issue: Row = {
|
|
number: 200 + fake.issues.length,
|
|
title: String(body['title']),
|
|
body: String(body['body']),
|
|
state: 'open',
|
|
labels: body['labels'] as number[],
|
|
};
|
|
fake.issues.push(issue);
|
|
return send(201, issue);
|
|
}
|
|
if ((m = /^\/(pulls|issues)\/(\d+)$/.exec(path)) && req.method === 'PATCH') {
|
|
const rows = m[1] === 'pulls' ? fake.pulls : fake.issues;
|
|
const row = rows.find((r) => r.number === Number(m?.[2]));
|
|
if (!row) return send(404, { message: 'no such row' });
|
|
Object.assign(row, body);
|
|
return send(200, row);
|
|
}
|
|
if ((m = /^\/issues\/(\d+)\/comments$/.exec(path)) && req.method === 'POST') {
|
|
fake.comments.push({ issue: Number(m[1]), body: String(body['body']) });
|
|
return send(201, { id: 1 });
|
|
}
|
|
if ((m = /^\/actions\/workflows\/([^/]+)\/dispatches$/.exec(path)) && req.method === 'POST') {
|
|
fake.dispatches.push({ file: decodeURIComponent(m[1] ?? ''), ref: String(body['ref']) });
|
|
return send(204);
|
|
}
|
|
if ((m = /^\/statuses\/([0-9a-f]+)$/.exec(path)) && req.method === 'POST') {
|
|
fake.statuses.push({ sha: m[1] ?? '', ...(body as Omit<Fake['statuses'][0], 'sha'>) });
|
|
return send(201, { id: 1 });
|
|
}
|
|
return send(404, { message: `unrouted ${req.method} ${path}` });
|
|
})();
|
|
});
|
|
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
api = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/v1`;
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await new Promise((resolve) => server.close(resolve));
|
|
});
|
|
|
|
function gitea(
|
|
args: string[],
|
|
files: Record<string, string> = {},
|
|
env: Record<string, string> = {},
|
|
) {
|
|
const root = project({ 'keep.txt': '', ...files });
|
|
const output = join(root, 'out.txt');
|
|
const done = runAsync('gitea.mjs', root, {
|
|
args,
|
|
env: {
|
|
GITEA_API: api,
|
|
GITEA_REPO: 'poli0981/softharbor',
|
|
GITEA_TOKEN: 'job-token',
|
|
GITHUB_OUTPUT: output,
|
|
...env,
|
|
},
|
|
});
|
|
return done.then((r) => ({ ...r, output: () => readFileSync(output, 'utf8'), root }));
|
|
}
|
|
|
|
const issue = (number: number, title: string): Row => ({
|
|
number,
|
|
title,
|
|
body: '',
|
|
state: 'open',
|
|
labels: [],
|
|
});
|
|
|
|
describe('pr', () => {
|
|
it('opens the pull request with the labels that exist, and says which one is missing', async () => {
|
|
const r = await gitea(
|
|
['pr', 'vt/recheck', 'data: VirusTotal re-check', 'body.md', 'security, quarantine'],
|
|
{
|
|
'body.md': 'the summary',
|
|
},
|
|
);
|
|
expect(r.code).toBe(0);
|
|
expect(fake.pulls).toHaveLength(1);
|
|
expect(fake.pulls[0]).toMatchObject({
|
|
title: 'data: VirusTotal re-check',
|
|
body: 'the summary',
|
|
labels: [40],
|
|
head: { ref: 'vt/recheck' },
|
|
base: { ref: 'main' },
|
|
});
|
|
expect(r.out).toContain('label "quarantine" does not exist');
|
|
expect(r.output()).toBe('number=100\noperation=created\n');
|
|
});
|
|
|
|
it('updates the open pull request from the same branch instead of opening another', async () => {
|
|
fake.pulls.push({ ...issue(7, 'old'), head: { ref: 'vt/recheck' }, base: { ref: 'main' } });
|
|
fake.pulls.push({
|
|
...issue(8, 'other'),
|
|
head: { ref: 'quarantine/auto' },
|
|
base: { ref: 'main' },
|
|
});
|
|
const r = await gitea(['pr', 'vt/recheck', 'new title', 'body.md'], { 'body.md': 'new body' });
|
|
expect(r.code).toBe(0);
|
|
expect(fake.pulls).toHaveLength(2);
|
|
expect(fake.pulls[0]).toMatchObject({ title: 'new title', body: 'new body' });
|
|
expect(fake.requests).not.toContain('POST /pulls');
|
|
expect(fake.requests).not.toContain('GET /labels');
|
|
expect(r.output()).toBe('number=7\noperation=updated\n');
|
|
});
|
|
|
|
it('tells the workflow whether a pull request from a branch is open', async () => {
|
|
fake.pulls.push({ ...issue(9, 'x'), head: { ref: 'vt/recheck' }, base: { ref: 'main' } });
|
|
const open = await gitea(['pr-open', 'vt/recheck']);
|
|
expect(open.output()).toBe('open=true\n');
|
|
expect(open.out).toContain('#9 is open');
|
|
const none = await gitea(['pr-open', 'quarantine/auto']);
|
|
expect(none.output()).toBe('open=false\n');
|
|
});
|
|
});
|
|
|
|
describe('dispatch and status', () => {
|
|
it('dispatches each workflow on the ref', async () => {
|
|
const r = await gitea(['dispatch', 'vt/recheck', 'ci.yml', 'security.yml']);
|
|
expect(r.code).toBe(0);
|
|
expect(fake.dispatches).toEqual([
|
|
{ file: 'ci.yml', ref: 'vt/recheck' },
|
|
{ file: 'security.yml', ref: 'vt/recheck' },
|
|
]);
|
|
});
|
|
|
|
it('records a passed or failed job under the check name protection matches', async () => {
|
|
await gitea(['status', 'abc123', 'CI / build (workflow_dispatch)', 'success', 'https://run/1']);
|
|
await gitea(['status', 'abc123', 'CI / gates (workflow_dispatch)', 'failure']);
|
|
expect(fake.statuses).toEqual([
|
|
expect.objectContaining({
|
|
sha: 'abc123',
|
|
state: 'success',
|
|
context: 'CI / build (workflow_dispatch)',
|
|
target_url: 'https://run/1',
|
|
}),
|
|
expect.objectContaining({ state: 'failure', context: 'CI / gates (workflow_dispatch)' }),
|
|
]);
|
|
expect(fake.statuses[1]).not.toHaveProperty('target_url');
|
|
});
|
|
|
|
it('records nothing for a cancelled or skipped job', async () => {
|
|
const r = await gitea(['status', 'abc123', 'CI / build (workflow_dispatch)', 'cancelled']);
|
|
expect(r.code).toBe(0);
|
|
expect(r.out).toContain('cancelled — nothing to record');
|
|
const empty = await gitea(['status', 'abc123', 'CI / build (workflow_dispatch)', '']);
|
|
expect(empty.out).toContain('no result — nothing to record');
|
|
expect(fake.statuses).toEqual([]);
|
|
});
|
|
});
|
|
|
|
describe('tracking issues', () => {
|
|
it('opens one quarantine issue per new slug, never a second, never for a malformed one', async () => {
|
|
fake.labels.push({ id: 41, name: 'quarantine' });
|
|
fake.issues.push(issue(5, '[quarantine] old-app'));
|
|
const r = await gitea(['quarantine-issues', 'bad-app', 'old-app', 'Not;a slug']);
|
|
expect(r.code).toBe(0);
|
|
expect(fake.issues.map((i) => i.title)).toEqual([
|
|
'[quarantine] old-app',
|
|
'[quarantine] bad-app',
|
|
]);
|
|
expect(fake.issues[1]?.labels).toEqual([40, 41]);
|
|
expect(fake.issues[1]?.body).toContain('`bad-app` was flagged and moved to `data/quarantine/`');
|
|
expect(r.out).toContain('[quarantine] old-app is already tracked in #5');
|
|
expect(r.out).toContain("skipping unexpected slug 'Not;a slug'");
|
|
});
|
|
|
|
it('opens one issue per VirusTotal detection from the review file', async () => {
|
|
fake.issues.push(issue(6, '[vt] tracked'));
|
|
const review = [
|
|
{
|
|
slug: 'some-app',
|
|
evidence: 'https://www.virustotal.com/gui/url/x',
|
|
malicious: 1,
|
|
suspicious: 0,
|
|
was: 'clean',
|
|
status: 'unverified',
|
|
},
|
|
{
|
|
slug: 'tracked',
|
|
evidence: 'e',
|
|
malicious: 2,
|
|
suspicious: 1,
|
|
was: 'clean',
|
|
status: 'unverified',
|
|
},
|
|
];
|
|
const r = await gitea(['vt-issues', 'review.json'], { 'review.json': JSON.stringify(review) });
|
|
expect(r.code).toBe(0);
|
|
expect(fake.issues).toHaveLength(2);
|
|
expect(fake.issues[1]).toMatchObject({ title: '[vt] some-app', labels: [40] });
|
|
expect(fake.issues[1]?.body).toContain('**1 malicious, 0 suspicious**');
|
|
expect(fake.issues[1]?.body).toContain('`clean` → `unverified`');
|
|
});
|
|
|
|
it('finds an open issue past the first page', async () => {
|
|
for (let n = 1; n <= 55; n++) fake.issues.push(issue(n, `filler ${n}`));
|
|
fake.issues.push(issue(56, '[quarantine] deep'));
|
|
const r = await gitea(['quarantine-issues', 'deep']);
|
|
expect(r.out).toContain('already tracked in #56');
|
|
expect(fake.requests.filter((q) => q === 'GET /issues')).toHaveLength(2);
|
|
});
|
|
});
|
|
|
|
describe('link-rot', () => {
|
|
const linkRot = (code: string) =>
|
|
gitea(['link-rot', code, 'out.md', 'https://run/9'], { 'out.md': '# report' });
|
|
|
|
it('opens the tracking issue on the first failure', async () => {
|
|
fake.labels.push({ id: 42, name: 'link-rot' });
|
|
await linkRot('2');
|
|
expect(fake.issues).toEqual([
|
|
expect.objectContaining({
|
|
title: 'link-check: broken official links',
|
|
body: '# report',
|
|
labels: [42],
|
|
}),
|
|
]);
|
|
});
|
|
|
|
it('refreshes the open issue while the sweep keeps failing', async () => {
|
|
fake.issues.push(issue(12, 'link-check: broken official links'));
|
|
const r = await linkRot('2');
|
|
expect(fake.issues[0]?.body).toBe('# report');
|
|
expect(fake.comments).toEqual([
|
|
{ issue: 12, body: 'Still failing in https://run/9 — the report above was refreshed.' },
|
|
]);
|
|
expect(r.out).toContain('Refreshed #12');
|
|
});
|
|
|
|
it('closes it the first week every link resolves', async () => {
|
|
fake.issues.push(issue(12, 'link-check: broken official links'));
|
|
await linkRot('0');
|
|
expect(fake.issues[0]?.state).toBe('closed');
|
|
expect(fake.comments[0]?.body).toContain('Every official link resolved in https://run/9');
|
|
});
|
|
|
|
it('does nothing when the sweep is clean and nothing is open', async () => {
|
|
const r = await linkRot('0');
|
|
expect(r.out).toContain('All links healthy');
|
|
expect(fake.requests).toEqual(['GET /issues']);
|
|
});
|
|
});
|
|
|
|
describe('failures', () => {
|
|
it('fails loudly on an API error', async () => {
|
|
fake.failOn = '/actions';
|
|
const r = await gitea(['dispatch', 'main', 'ci.yml']);
|
|
expect(r.code).toBe(1);
|
|
expect(r.out).toContain('::error::gitea.mjs: POST /actions/workflows/ci.yml/dispatches → 500');
|
|
});
|
|
|
|
it('refuses to run without the API, the repository and the token', async () => {
|
|
const r = await gitea(['pr-open', 'x'], {}, { GITEA_TOKEN: '' });
|
|
expect(r.code).toBe(1);
|
|
expect(r.out).toContain('GITEA_API, GITEA_REPO and GITEA_TOKEN are required');
|
|
});
|
|
|
|
it('rejects an unknown command and a missing argument', async () => {
|
|
const unknown = await gitea(['merge']);
|
|
expect(unknown.code).toBe(1);
|
|
expect(unknown.out).toContain('usage: gitea.mjs');
|
|
const short = await gitea(['status', 'abc123']);
|
|
expect(short.code).toBe(1);
|
|
expect(short.out).toContain('status needs 3 argument(s)');
|
|
});
|
|
|
|
it('writes no output file when the workflow gives none', async () => {
|
|
const r = await gitea(['pr-open', 'x'], {}, { GITHUB_OUTPUT: '' });
|
|
expect(r.code).toBe(0);
|
|
});
|
|
});
|