gitea: a start ends the token files an earlier build kept, revoked at the forge, never read

G2 token-stand-in-goes (TypeScript half): at each start while a token file remains and once
this start's token is held, the forge's token lists are read before any token is deleted, a pair
is matched by the token's last eight characters and its scopes, revoked by its id and deleted;
a .tmp goes with its pair, a cut one unrevoked; a pair that stays is the finding
token-file-unrevoked. findingKey and findingValue move to findings.ts.

Builds: design 47 H2 H-A-575, H-A-602, H-A-642, H-A-699
This commit is contained in:
2026-11-25 17:10:33 +01:00
parent c1abd7e210
commit 5a82d93ccb
6 changed files with 324 additions and 25 deletions
+100 -5
View File
@@ -10,12 +10,13 @@
import { test, after } from "node:test";
import assert from "node:assert/strict";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { mkdtemp, stat, writeFile } from "node:fs/promises";
import { mkdir, mkdtemp, readdir, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { collectTools } from "@novox/mesh-sdk/tools";
import { AdminRefused, MintedToken, TOKEN_NAME, TOKEN_SCOPES, leaseOverState, openValue, vaultOverBus, vaultValue, type MintedTokenOptions } from "../dist/token.js";
import { TOKEN_FILE_UNREVOKED, passOver, type ForgeTokens, type ListedToken } from "../dist/tokenfiles.js";
import { tokenLeaseTool } from "../dist/tools/tokenlease.js";
import { fakeBus } from "./fakebus.ts";
import { GiteaClient } from "../dist/client.js";
@@ -38,7 +39,7 @@ interface Forge {
/** How each DELETE named its token: "id" or "name". */
deletedBy: string[];
/** Plant a token by name, beside any other of the same name, as a raced mint would. */
plant(name: string): void;
plant(name: string, sha1?: string, scopes?: string[]): void;
scopesOf: Map<string, string[]>;
admins: Map<string, string>;
pullState: string;
@@ -119,7 +120,7 @@ function fakeForge(): Promise<Forge> {
const all = listed();
res.setHeader("X-Total-Count", String(all.length));
return json(res, 200, all.slice((page - 1) * limit, page * limit)
.map((t) => ({ id: t.id, name: t.name, sha1: "", token_last_eight: t.sha1.slice(-8), scopes: [] })));
.map((t) => ({ id: t.id, name: t.name, sha1: "", token_last_eight: t.sha1.slice(-8), scopes: forge.scopesOf.get(t.sha1) ?? [] })));
}
if (req.method === "DELETE" && tokens[2]) {
// gitea: "identified by ID and if not available by name" — and a name held twice is refused.
@@ -242,8 +243,10 @@ function fakeForge(): Promise<Forge> {
tokens: forge.tokens,
twins: forge.twins,
deletedBy: forge.deletedBy,
plant: (name: string) => {
const sha1 = `planted-${++forge.nextId}`;
plant: (name: string, value?: string, scopes?: string[]) => {
const sha1 = value ?? `planted-${++forge.nextId}`;
if (value) ++forge.nextId;
if (scopes) forge.scopesOf.set(sha1, scopes);
forge.ids.set(sha1, forge.nextId);
if (forge.tokens.has(name)) forge.twins.push({ id: forge.nextId, name, sha1 });
else forge.tokens.set(name, sha1);
@@ -665,3 +668,95 @@ test("a pull request can be closed, read and cleaned up through the tools", asyn
await tool("gitea_delete_branch").run({ owner: "novox", repo: "hq", branch: "feat/x" });
assert.equal(forge.branchDeleted, true);
});
// ---- The token files an earlier build kept (H-A-575, H-A-602, H-A-642, H-A-699): ended at a start, never read. ----
const HEX = "0123456789abcdef0123456789abcdef01234567";
const SCOPES = ["write:repository", "read:user"];
const SCOPES_LINE = "read:user,write:repository for mesh-tools";
/** The state directory of a start, with the files an earlier build left: the token, its scopes, and what `extra` adds. */
async function leftFiles(env: NodeJS.ProcessEnv, files: Record<string, string>): Promise<void> {
const dir = env.MESH_GITEA_STATE_DIR!;
await mkdir(dir, { recursive: true });
for (const [name, text] of Object.entries(files)) await writeFile(join(dir, name), text);
}
const left = async (env: NodeJS.ProcessEnv) => (await readdir(env.MESH_GITEA_STATE_DIR!).catch(() => [] as string[])).filter((f) => f.includes("token")).sort();
/** The findings a start wrote, by key. */
const sink = () => { const held = new Map<string, any>(); return { held, put: async (k: string, v: unknown) => { held.set(k, v); }, delete: async (k: string) => { held.delete(k); } }; };
test("a start ends the token files: the lists are read before the first mint drops the old name, the pair is revoked by its id and deleted, and a cut .tmp goes unrevoked (H-A-575, H-A-699)", async () => {
const { env, bus, logs } = await delivered(forge);
forge.tokens.clear();
forge.plant(TOKEN_NAME, HEX, SCOPES);
await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n", "token.tmp": "cut-off", "token.scopes.tmp": SCOPES_LINE + "\n" });
const findings = sink();
ORDER.length = 0;
forge.deletedBy.length = 0;
await new GiteaClient(env.MESH_GITEA_URL!, source(env, logs, { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token", findings,
listAccounts: async () => ["mesh-tools", "mesh-packages"] })).listRepos();
// The planted token was listed before the first mint's drop deleted it, so the file's token matched and its revocation found it gone.
assert.deepEqual(await left(env), [], logs.join("\n"));
assert.equal(findings.held.size, 0);
assert.deepEqual(ORDER, [`own-put ${VAULT} 1`, `delete ${TOKEN_NAME}`], "the own-put, then the drop of the old name");
assert.ok(logs.some((l) => l.includes("token.tmp") && l.includes("no whole token")), logs.join("\n"));
assert.ok(logs.every((l) => !l.includes(HEX) && !l.includes(vaulted(bus))), "no line names a token");
});
test("a token file stays when the vault refuses the own-put, and when the forge refuses the revocation or matches nothing: said, written as a finding, cleared once the pair goes", async () => {
const { env, logs } = await delivered(forge);
forge.tokens.clear();
forge.plant(TOKEN_NAME, HEX, SCOPES);
await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n" });
const refusing = source(env, logs, { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token",
vault: { get: vaultOverBus().get, put: async () => { throw new Error("the vault is away"); } } });
await assert.rejects(new GiteaClient(env.MESH_GITEA_URL!, refusing).listRepos(), /the vault is away/);
assert.deepEqual(await left(env), ["token", "token.scopes"], "an own-put refused leaves the files and their token");
// The forge refuses the revocation: the pair stays and the finding names the answer; the next start's success clears it.
const findings = sink();
const listed: ListedToken[] = [{ id: 7, token_last_eight: HEX.slice(-8), scopes: SCOPES }];
let answer: string | null = "403 forbidden";
const forgeTokens: ForgeTokens = { list: async () => listed, revoke: async () => answer };
const run = (lists: Map<string, readonly ListedToken[]>) =>
passOver({ dir: env.MESH_GITEA_STATE_DIR!, base: "token", lists, forge: forgeTokens, findings, log: (l) => logs.push(l) });
await run(new Map([["mesh-tools", listed]]));
const key = [...findings.held.keys()];
assert.equal(key.length, 1);
assert.match(key[0], new RegExp(`token\\.${TOKEN_FILE_UNREVOKED}$`));
assert.match(findings.held.get(key[0]).summary, /403 forbidden/);
assert.deepEqual(await left(env), ["token", "token.scopes"]);
answer = null;
await run(new Map([["mesh-tools", listed]]));
assert.deepEqual([await left(env), findings.held.size], [[], 0]);
// No token at the forge matches the last eight characters and the scopes: the pair stays and says so.
await leftFiles(env, { "packages-token": HEX + "\n", "packages-token.scopes": "write:package for mesh-packages\n" });
await passOver({ dir: env.MESH_GITEA_STATE_DIR!, base: "packages-token", lists: new Map([["mesh-packages", listed]]), forge: forgeTokens,
findings, log: (l) => logs.push(l) });
assert.deepEqual(await left(env), ["packages-token", "packages-token.scopes"]);
assert.equal(findings.held.size, 1);
});
test("a start with the vault holding a token and a file left runs the pass; with no file it lists nothing at the forge", async () => {
const { env, logs } = await delivered(forge);
forge.tokens.clear();
await minted(env, logs).listRepos();
forge.plant("kept-by-the-earlier-build", HEX, SCOPES);
await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n" });
const again: string[] = [];
const options = { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token", listAccounts: async () => ["mesh-tools"] };
await new GiteaClient(env.MESH_GITEA_URL!, source(env, again, options)).listRepos();
assert.ok(again.some((l) => l.startsWith("reusing the token the vault keeps")), again.join("\n"));
assert.deepEqual(await left(env), []);
assert.equal(forge.tokens.has("kept-by-the-earlier-build"), false, "its token is revoked at the forge");
const quiet: string[] = [];
const failing = { ...options, listAccounts: async () => { throw new Error("no lists without files"); } };
await new GiteaClient(env.MESH_GITEA_URL!, source(env, quiet, failing)).listRepos();
assert.ok(quiet.every((l) => !l.includes("no lists")), quiet.join("\n"));
});