The file beside the token that kept its scopes went with C4, and with it the re-mint of a token carrying a scope beyond the tools' (write:admin). The value written through own-put now holds the token and its scopes; a token minted with other scopes, or a value naming none, is minted again unasked and the one it replaces deleted at the forge. The Go bundles read the token out of that value. The lost test is back as a row of the scope test in test/token.test.ts. Builds: design 47 H2 §808; H-A-439
668 lines
34 KiB
TypeScript
668 lines
34 KiB
TypeScript
// What holds the module to its own token (token.ts; hq issue 100, the forge's tools): minted with
|
|
// the delivered admin account on the first call and kept at 0600, reused on the next start, minted
|
|
// afresh when the forge rejects it or the kept file is gone, and a refused admin account reported in
|
|
// plain words rather than crash-looped. A configured token still wins. And the tools register once
|
|
// there is a way to a token at all — before one exists.
|
|
//
|
|
// The forge is a fake: the four routes the module touches, with the same status codes gitea gives.
|
|
// Run against the compiled module (npm test builds first), the way the runtime loads it.
|
|
|
|
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 { 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 { tokenLeaseTool } from "../dist/tools/tokenlease.js";
|
|
import { fakeBus } from "./fakebus.ts";
|
|
import { GiteaClient } from "../dist/client.js";
|
|
import { getGiteaTools } from "../dist/tools/index.js";
|
|
|
|
/** What the vault and the forge were asked, in order: each own-put and each token deleted (design 47 H2 §808). */
|
|
const ORDER: string[] = [];
|
|
const ADMIN = "mesh-admin";
|
|
const PASSWORD = "the-vault-minted-this";
|
|
|
|
// ---- A fake forge: what the module sends, and what gitea would answer. ----
|
|
|
|
interface Forge {
|
|
url: string;
|
|
mints: number;
|
|
lastScopes: string[] | null;
|
|
tokens: Map<string, string>;
|
|
/** Tokens beside `tokens` that carry a name already held there: what two mints at once leave behind. */
|
|
twins: { id: number; name: string; sha1: string }[];
|
|
/** 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;
|
|
scopesOf: Map<string, string[]>;
|
|
admins: Map<string, string>;
|
|
pullState: string;
|
|
pullTitle: string;
|
|
branchDeleted: boolean;
|
|
close(): Promise<void>;
|
|
}
|
|
|
|
function fakeForge(): Promise<Forge> {
|
|
const forge = {
|
|
mintedFor: "",
|
|
mints: 0,
|
|
lastScopes: null as string[] | null,
|
|
tokens: new Map<string, string>(), // name -> value
|
|
twins: [] as { id: number; name: string; sha1: string }[],
|
|
deletedBy: [] as string[],
|
|
ids: new Map<string, number>(), // value -> id, as gitea numbers its tokens
|
|
nextId: 0,
|
|
scopesOf: new Map<string, string[]>(), // value -> scopes, so a route can enforce them like gitea does
|
|
admins: new Map([[ADMIN, PASSWORD]]),
|
|
pullState: "open",
|
|
pullTitle: "The console shipped",
|
|
branchDeleted: false,
|
|
};
|
|
// write:X implies read:X — gitea's own rule (models/auth/access_token_scope.go).
|
|
const covers = (scopes: string[], required: string): boolean =>
|
|
scopes.includes(required) || scopes.includes(`write:${required.split(":")[1]}`);
|
|
const json = (res: ServerResponse, status: number, body: unknown): void => {
|
|
res.writeHead(status, { "Content-Type": "application/json" });
|
|
res.end(body === null ? "" : JSON.stringify(body));
|
|
};
|
|
const body = (req: IncomingMessage): Promise<any> =>
|
|
new Promise((resolve) => {
|
|
let text = "";
|
|
req.on("data", (c) => (text += c));
|
|
req.on("end", () => resolve(text ? JSON.parse(text) : null));
|
|
});
|
|
const basic = (req: IncomingMessage): string | null => {
|
|
const h = req.headers.authorization ?? "";
|
|
if (!h.startsWith("Basic ")) return null;
|
|
const [user, pass] = Buffer.from(h.slice(6), "base64").toString().split(":");
|
|
return forge.admins.get(user) === pass ? user : null;
|
|
};
|
|
|
|
const server = createServer(async (req, res) => {
|
|
const url = new URL(req.url ?? "/", "http://fake");
|
|
const tokens = url.pathname.match(/^\/api\/v1\/users\/([^/]+)\/tokens(?:\/([^/]+))?$/);
|
|
if (tokens) {
|
|
const user = basic(req);
|
|
// gitea's reqSelfOrAdmin: the account itself, or the administrator for another (the tools' account, ADR 0365).
|
|
if (user === null || (user !== decodeURIComponent(tokens[1]) && user !== ADMIN)) return json(res, 401, { message: "auth required" });
|
|
// This fake keeps one account's tokens: the tools' account's when the module mints for it (ADR 0365), and the
|
|
// admin's own list is then empty — nothing of it is retired.
|
|
if (decodeURIComponent(tokens[1]) === ADMIN && forge.mintedFor === "mesh-tools") {
|
|
return req.method === "GET" ? json(res, 200, []) : json(res, 404, { message: "token not found" });
|
|
}
|
|
if (req.method === "POST") forge.mintedFor = decodeURIComponent(tokens[1]);
|
|
if (req.method === "POST") {
|
|
const { name, scopes } = await body(req);
|
|
if (forge.tokens.has(name)) return json(res, 400, { message: "token name has already been used" });
|
|
forge.mints++;
|
|
forge.lastScopes = scopes;
|
|
const sha1 = `minted-${forge.mints}-${Math.random().toString(36).slice(2)}`;
|
|
forge.tokens.set(name, sha1);
|
|
forge.scopesOf.set(sha1, scopes);
|
|
forge.ids.set(sha1, ++forge.nextId);
|
|
return json(res, 201, { id: forge.ids.get(sha1), name, sha1, scopes, token_last_eight: sha1.slice(-8) });
|
|
}
|
|
// gitea's list: every token of the account, a page at a time (at most three to a page here, so a
|
|
// client that reads only the first page misses some), the values never shown.
|
|
const listed = (): { id: number; name: string; sha1: string }[] => [
|
|
...[...forge.tokens].map(([name, sha1]) => ({ id: forge.ids.get(sha1) ?? 0, name, sha1 })),
|
|
...forge.twins,
|
|
];
|
|
if (req.method === "GET" && !tokens[2]) {
|
|
const page = Math.max(1, Number(url.searchParams.get("page") ?? "1"));
|
|
const limit = Math.min(3, Math.max(1, Number(url.searchParams.get("limit") ?? "3")));
|
|
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: [] })));
|
|
}
|
|
if (req.method === "DELETE" && tokens[2]) {
|
|
// gitea: "identified by ID and if not available by name" — and a name held twice is refused.
|
|
const key = decodeURIComponent(tokens[2]);
|
|
const byId = /^\d+$/.test(key);
|
|
const matches = listed().filter((t) => (byId ? String(t.id) === key : t.name === key));
|
|
if (matches.length === 0) return json(res, 404, { message: "token not found" });
|
|
if (matches.length > 1) return json(res, 422, { message: `multiple matches for token name '${key}'` });
|
|
const t = matches[0];
|
|
forge.deletedBy.push(byId ? "id" : "name");
|
|
ORDER.push(`delete ${t.name}`);
|
|
const twin = forge.twins.findIndex((w) => w.id === t.id);
|
|
if (twin >= 0) forge.twins.splice(twin, 1);
|
|
else forge.tokens.delete(t.name);
|
|
return json(res, 204, null);
|
|
}
|
|
return json(res, 405, { message: "method not allowed" });
|
|
}
|
|
const tokenOf = (): string => {
|
|
const h = req.headers.authorization ?? "";
|
|
return h.startsWith("token ") ? h.slice(6) : "";
|
|
};
|
|
const pull = url.pathname.match(/^\/api\/v1\/repos\/novox\/hq\/pulls\/(\d+)(\.diff)?$/);
|
|
if (pull) {
|
|
if (![...forge.tokens.values()].includes(tokenOf())) return json(res, 401, { message: "token is required" });
|
|
if (pull[2]) {
|
|
res.writeHead(200, { "Content-Type": "text/plain" });
|
|
return res.end("diff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-old\n+new\n");
|
|
}
|
|
if (req.method === "PATCH") {
|
|
const patch = await body(req);
|
|
forge.pullState = patch?.state ?? forge.pullState;
|
|
forge.pullTitle = patch?.title ?? forge.pullTitle;
|
|
}
|
|
return json(res, 200, { number: Number(pull[1]), title: forge.pullTitle, state: forge.pullState, merged: false,
|
|
user: { login: "mesh-admin" }, head: { ref: "feat/x" }, base: { ref: "main" }, html_url: "http://fake/novox/hq/pulls/" + pull[1] });
|
|
}
|
|
if (url.pathname === "/api/v1/repos/novox/hq/issues/223/comments") {
|
|
return json(res, 200, [{ id: 1, user: { login: "jochen" }, body: "landed elsewhere", created_at: "2026-10-01T00:00:00Z", html_url: "http://fake/c/1" }]);
|
|
}
|
|
if (url.pathname === "/api/v1/repos/novox/hq/contents/README.md") {
|
|
return json(res, 200, { type: "file", encoding: "base64", sha: "abc", size: 5, content: Buffer.from("hello").toString("base64") });
|
|
}
|
|
if (url.pathname === "/api/v1/repos/novox/hq/branches") {
|
|
return json(res, 200, [{ name: "main", protected: true, commit: { id: "aaaa" } }, { name: "feat/x", protected: false, commit: { id: "bbbb" } }]);
|
|
}
|
|
if (url.pathname === "/api/v1/repos/novox/hq/branches/feat%2Fx" || url.pathname === "/api/v1/repos/novox/hq/branches/feat/x") {
|
|
if (req.method === "DELETE") { forge.branchDeleted = true; return json(res, 204, null); }
|
|
}
|
|
if (url.pathname === "/api/v1/repos/search") {
|
|
// The client lists through the search endpoint since 2026-09-28 (the forge's whole view);
|
|
// it sits under `repository`, which write:repository covers.
|
|
const h = req.headers.authorization ?? "";
|
|
const value = h.startsWith("token ") ? h.slice(6) : "";
|
|
if (![...forge.tokens.values()].includes(value)) return json(res, 401, { message: "token is required" });
|
|
if (!covers(forge.scopesOf.get(value) ?? [], "read:repository")) {
|
|
return json(res, 403, { message: `token does not have at least one of required scope(s), required=[read:repository]` });
|
|
}
|
|
return json(res, 200, {
|
|
ok: true,
|
|
data: [{ full_name: "novox/hq", name: "hq", owner: { login: "novox" }, private: true, html_url: "http://fake/novox/hq" }],
|
|
});
|
|
}
|
|
if (url.pathname === "/api/v1/user/repos") {
|
|
const h = req.headers.authorization ?? "";
|
|
const value = h.startsWith("token ") ? h.slice(6) : "";
|
|
if (![...forge.tokens.values()].includes(value)) return json(res, 401, { message: "token is required" });
|
|
// gitea 1.27.3: GET /user/repos sits under the `user` scope category, not `repository` —
|
|
// confirmed against the live forge. A token without read:user (or write:user) is refused here.
|
|
const scopes = forge.scopesOf.get(value) ?? [];
|
|
if (!covers(scopes, "read:user")) {
|
|
return json(res, 403, {
|
|
message: `token does not have at least one of required scope(s), required=[read:user]`,
|
|
});
|
|
}
|
|
return json(res, 200, [
|
|
{ full_name: "novox/hq", name: "hq", owner: { login: "novox" }, private: true, html_url: "http://fake/novox/hq" },
|
|
]);
|
|
}
|
|
// What setting up the tools' account asks with the admin login (tools-account.ts, ADR 0365): answered plainly.
|
|
if (basic(req) === ADMIN) {
|
|
const p = url.pathname;
|
|
if (req.method === "GET" && p === "/api/v1/user") return json(res, 200, { login: ADMIN, is_admin: true });
|
|
if (req.method === "GET" && p === "/api/v1/users/mesh-tools") return json(res, 200, { login: "mesh-tools", is_admin: false });
|
|
if (req.method === "POST" && p === "/api/v1/admin/users") return json(res, 422, { message: "user already exists" });
|
|
if (req.method === "PATCH" && p === "/api/v1/admin/users/mesh-tools") return json(res, 200, { login: "mesh-tools" });
|
|
if (req.method === "GET" && p === "/api/v1/orgs/novox/teams") return json(res, 200, [{ id: 7, name: "mesh-tools" }]);
|
|
if (req.method === "PATCH" && p === "/api/v1/teams/7") return json(res, 200, { id: 7 });
|
|
if (req.method === "PUT" && p === "/api/v1/teams/7/members/mesh-tools") return json(res, 204, null);
|
|
// Main's rule put right in every repository (issue 948): this forge has none.
|
|
if (req.method === "GET" && p === "/api/v1/orgs/novox/repos") return json(res, 200, []);
|
|
}
|
|
const adminUser = url.pathname.match(/^\/api\/v1\/admin\/users\/([^/]+)$/);
|
|
if (adminUser && req.method === "PATCH") {
|
|
const h = req.headers.authorization ?? "";
|
|
const value = h.startsWith("token ") ? h.slice(6) : "";
|
|
if (![...forge.tokens.values()].includes(value)) return json(res, 401, { message: "token is required" });
|
|
if (!covers(forge.scopesOf.get(value) ?? [], "write:admin")) {
|
|
return json(res, 403, {
|
|
message: `token does not have at least one of required scope(s), required=[write:admin]`,
|
|
});
|
|
}
|
|
const login = decodeURIComponent(adminUser[1]);
|
|
if (login === "untouchable") return json(res, 403, { message: "user untouchable may not be edited" });
|
|
const patch = await body(req);
|
|
return json(res, 200, { login, is_admin: patch?.admin === true });
|
|
}
|
|
return json(res, 404, { message: "no such route in the fake" });
|
|
});
|
|
return new Promise((resolve) => {
|
|
server.listen(0, "127.0.0.1", () => {
|
|
const { port } = server.address() as { port: number };
|
|
resolve({
|
|
url: `http://127.0.0.1:${port}`,
|
|
get mints() { return forge.mints; },
|
|
get lastScopes() { return forge.lastScopes; },
|
|
get pullState() { return forge.pullState; },
|
|
get pullTitle() { return forge.pullTitle; },
|
|
get branchDeleted() { return forge.branchDeleted; },
|
|
tokens: forge.tokens,
|
|
twins: forge.twins,
|
|
deletedBy: forge.deletedBy,
|
|
plant: (name: string) => {
|
|
const sha1 = `planted-${++forge.nextId}`;
|
|
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);
|
|
},
|
|
scopesOf: forge.scopesOf,
|
|
admins: forge.admins,
|
|
close: () => new Promise((r) => server.close(() => r())),
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
// ---- What the runtime's environment gives the module. ----
|
|
|
|
async function delivered(forge: Forge, now: () => Date = () => new Date()) {
|
|
const dir = await mkdtemp(join(tmpdir(), "gitea-"));
|
|
const passwordFile = join(dir, "admin.secret");
|
|
await writeFile(passwordFile, PASSWORD + "\n", { mode: 0o600 });
|
|
ORDER.length = 0;
|
|
return {
|
|
env: {
|
|
MESH_GITEA_URL: forge.url,
|
|
MESH_GITEA_ADMIN_USER: ADMIN,
|
|
MESH_GITEA_ADMIN_PASSWORD_FILE: passwordFile,
|
|
MESH_GITEA_STATE_DIR: join(dir, "state"),
|
|
} as NodeJS.ProcessEnv,
|
|
bus: fakeBus(now, ORDER),
|
|
logs: [] as string[],
|
|
};
|
|
}
|
|
|
|
/** A client as a fresh process would build it: a new source over the vault and the lease on the bus, its log captured. */
|
|
function minted(env: NodeJS.ProcessEnv, logs: string[], extra: Partial<MintedTokenOptions> = {}): GiteaClient {
|
|
return new GiteaClient(env.MESH_GITEA_URL!, source(env, logs, extra));
|
|
}
|
|
|
|
function source(env: NodeJS.ProcessEnv, logs: string[], extra: Partial<MintedTokenOptions> = {}): MintedToken {
|
|
return new MintedToken({
|
|
url: env.MESH_GITEA_URL!, admin: env.MESH_GITEA_ADMIN_USER!, passwordFile: env.MESH_GITEA_ADMIN_PASSWORD_FILE!,
|
|
account: "mesh-tools", oldName: TOKEN_NAME, vault: vaultOverBus(), lease: leaseOverState(), log: (l) => logs.push(l), ...extra,
|
|
});
|
|
}
|
|
|
|
const VAULT = "module/gitea/mesh-tools";
|
|
/** The token the vault keeps for the tools' account, out of the value that holds it with its scopes (H-A-439). */
|
|
const vaulted = (bus: ReturnType<typeof fakeBus>) => openValue(bus.vault.get(VAULT)?.value ?? "").token;
|
|
const forge = await fakeForge();
|
|
after(() => forge.close());
|
|
|
|
test("first start: mints mesh-tools-1 with the admin account, writes it through own-put, asks for the tools' scopes only", async () => {
|
|
const { env, bus, logs } = await delivered(forge);
|
|
forge.tokens.clear();
|
|
|
|
const repos = await minted(env, logs).listRepos();
|
|
|
|
assert.equal(repos[0]?.full_name, "novox/hq");
|
|
// Never write:admin (novox/hq ADR 0266): the forge's administration is the operator's, not a tool's.
|
|
assert.deepEqual(forge.lastScopes, ["write:repository", "write:issue", "read:user", "read:package"]);
|
|
assert.deepEqual(forge.lastScopes, [...TOKEN_SCOPES]);
|
|
// Design 47 H2 §808, H-A-422 (2), H-A-426: named per mint, kept as the module's own secret, never a file.
|
|
const token = forge.tokens.get("mesh-tools-1")!;
|
|
assert.ok(token);
|
|
assert.deepEqual([vaulted(bus), bus.vault.get(VAULT)?.generation], [token, 1]);
|
|
assert.deepEqual(openValue(bus.vault.get(VAULT)!.value).scopes, [...TOKEN_SCOPES], "kept with the scopes it was minted with (H-A-439)");
|
|
await assert.rejects(stat(join(env.MESH_GITEA_STATE_DIR!, "token")), /ENOENT/);
|
|
assert.ok(logs.some((l) => l.startsWith("minted mesh-tools-1")), logs.join("\n"));
|
|
assert.ok(logs.every((l) => !l.includes(token) && !l.includes(PASSWORD)), logs.join("\n"));
|
|
});
|
|
|
|
test("second start: reuses the vault's token, mints nothing", async () => {
|
|
const { env, logs } = await delivered(forge);
|
|
await minted(env, logs).listRepos();
|
|
const before = forge.mints;
|
|
|
|
const again: string[] = [];
|
|
await minted(env, again).listRepos();
|
|
|
|
assert.equal(forge.mints, before);
|
|
assert.ok(again.some((l) => l.startsWith(`reusing the token the vault keeps as ${VAULT}`)), again.join("\n"));
|
|
});
|
|
|
|
test("the forge rejects the vault's token: mesh-tools-2 is minted once, written through own-put, and only then is mesh-tools-1 deleted by its id", async () => {
|
|
const { env, bus, logs } = await delivered(forge);
|
|
forge.tokens.clear();
|
|
const client = minted(env, logs);
|
|
await client.listRepos();
|
|
const before = forge.mints;
|
|
ORDER.length = 0;
|
|
forge.deletedBy.length = 0;
|
|
|
|
forge.tokens.set("mesh-tools-1", "revoked-meanwhile"); // the forge no longer takes the vault's token
|
|
const repos = await client.listRepos();
|
|
|
|
assert.equal(repos.length, 1);
|
|
assert.equal(forge.mints, before + 1);
|
|
assert.equal(vaulted(bus), forge.tokens.get("mesh-tools-2"));
|
|
// H-A-422 (2): the own-put first, the replaced token's delete after, by id; the forge holds one tools' token after.
|
|
assert.deepEqual(ORDER, [`own-put ${VAULT} 2`, "delete mesh-tools-1"]);
|
|
assert.deepEqual(forge.deletedBy, ["id"]);
|
|
assert.deepEqual([...forge.tokens.keys()].filter((n) => n.startsWith("mesh-tools")), ["mesh-tools-2"]);
|
|
assert.ok(logs.some((l) => l.startsWith("the forge rejected the vault's token")), logs.join("\n"));
|
|
});
|
|
|
|
test("an own-put that fails leaves the old token standing, and the next mint replaces the unused one it left", async () => {
|
|
const { env, bus, logs } = await delivered(forge);
|
|
forge.tokens.clear();
|
|
const client = minted(env, logs);
|
|
await client.listRepos();
|
|
const old = forge.tokens.get("mesh-tools-1")!;
|
|
forge.tokens.set("mesh-tools-1", "revoked-meanwhile");
|
|
ORDER.length = 0;
|
|
let failPut = true;
|
|
const failing = minted(env, logs, { vault: { get: vaultOverBus().get, put: async (a, t, scopes) => {
|
|
if (failPut) { failPut = false; throw new Error("the vault is away"); }
|
|
return vaultOverBus().put(a, t, scopes);
|
|
} } });
|
|
|
|
await assert.rejects(failing.listRepos(), /the vault is away/);
|
|
assert.deepEqual(ORDER, [], "nothing deleted while the vault holds the old token");
|
|
assert.equal(bus.vault.get(VAULT)?.generation, 1);
|
|
assert.ok(forge.tokens.has("mesh-tools-2"), "the unused token of the failed mint stands");
|
|
|
|
assert.equal((await failing.listRepos()).length, 1);
|
|
assert.deepEqual(ORDER, ["delete mesh-tools-2", `own-put ${VAULT} 2`, "delete mesh-tools-1"]);
|
|
assert.notEqual(vaulted(bus), old);
|
|
});
|
|
|
|
test("a token older than token-ttl is minted again, and the one it replaces deleted", async () => {
|
|
let clock = Date.parse("2026-11-22T00:00:00Z");
|
|
const now = () => new Date(clock);
|
|
const { env, bus, logs } = await delivered(forge, now);
|
|
forge.tokens.clear();
|
|
const client = minted(env, logs, { now, ttlMs: 24 * 3600_000 });
|
|
await client.listRepos();
|
|
const before = forge.mints;
|
|
|
|
clock += 23 * 3600_000;
|
|
await client.listRepos();
|
|
assert.equal(forge.mints, before, "a token within token-ttl is used");
|
|
clock += 2 * 3600_000;
|
|
await client.listRepos();
|
|
|
|
assert.equal(forge.mints, before + 1);
|
|
assert.equal(bus.vault.get(VAULT)?.generation, 2);
|
|
assert.deepEqual([...forge.tokens.keys()].filter((n) => n.startsWith("mesh-tools")), ["mesh-tools-2"]);
|
|
assert.ok(logs.some((l) => l.includes("older than token-ttl")), logs.join("\n"));
|
|
});
|
|
|
|
test("a token lacking a scope the tools need: the forge refuses the call for the scope, the token is re-minted with the whole list, and the call goes through", async (t) => {
|
|
const { env, bus, logs } = await delivered(forge);
|
|
forge.tokens.clear();
|
|
const client = minted(env, logs);
|
|
await client.listRepos();
|
|
const before = forge.mints;
|
|
const old = forge.tokens.get("mesh-tools-1")!;
|
|
forge.scopesOf.set(old, ["write:repository", "write:issue"]); // minted before read:user was added
|
|
|
|
const repos = await client.api<unknown[]>("/user/repos");
|
|
|
|
assert.equal(repos.length, 1);
|
|
assert.equal(forge.mints, before + 1);
|
|
assert.deepEqual(forge.lastScopes, [...TOKEN_SCOPES]);
|
|
assert.equal(vaulted(bus), forge.tokens.get("mesh-tools-2"));
|
|
|
|
// Design 47 H2 §808, H-A-439: the vault keeps the scopes beside the token, so one carrying a scope beyond the tools'
|
|
// is minted again unasked, as when they were kept in a file beside it.
|
|
await t.test("a token kept with write:admin is minted again without it at the next start, and the forge drops the old one", async () => {
|
|
const { env, bus, logs } = await delivered(forge);
|
|
forge.tokens.clear();
|
|
await minted(env, logs).listRepos();
|
|
const old = forge.tokens.get("mesh-tools-1")!;
|
|
// An earlier mint asked write:admin too, and the vault keeps what it asked.
|
|
bus.vault.get(VAULT)!.value = vaultValue(old, [...TOKEN_SCOPES, "write:admin"]);
|
|
forge.scopesOf.set(old, [...TOKEN_SCOPES, "write:admin"]);
|
|
const before = forge.mints;
|
|
|
|
const again: string[] = [];
|
|
await minted(env, again).listRepos();
|
|
|
|
assert.equal(forge.mints, before + 1);
|
|
assert.deepEqual(forge.lastScopes, [...TOKEN_SCOPES]);
|
|
assert.ok(![...forge.tokens.values()].includes(old), "the old token still stands on the forge");
|
|
assert.deepEqual(openValue(bus.vault.get(VAULT)!.value), { token: forge.tokens.get("mesh-tools-2"), scopes: [...TOKEN_SCOPES] });
|
|
assert.ok(again.some((l) => l.includes("minted with other scopes")), again.join("\n"));
|
|
// An admin route through the escape hatch is refused before it is sent.
|
|
const tool = getGiteaTools(minted(env, again)).find((x) => x.name === "gitea_api")!;
|
|
await assert.rejects(tool.run({ path: "/admin/users/mesh_novox_builder", method: "PATCH", body: { admin: true } }, undefined as never),
|
|
/not a write gitea_api makes/);
|
|
});
|
|
});
|
|
|
|
test("the first mint deletes by id every token under the old fixed name, two raced ones too, and keeps the account's others", async () => {
|
|
const { env, logs } = await delivered(forge);
|
|
forge.tokens.clear();
|
|
forge.twins.length = 0;
|
|
for (const other of ["laptop", "backup", "ci"]) forge.plant(other); // the account's other tokens: kept
|
|
forge.plant("mesh-tools");
|
|
forge.plant("mesh-tools"); // gitea refuses to delete either by name from here on
|
|
forge.deletedBy.length = 0;
|
|
const before = forge.mints;
|
|
|
|
const repos = await minted(env, logs).listRepos();
|
|
|
|
assert.equal(repos.length, 1);
|
|
assert.equal(forge.mints, before + 1);
|
|
// H-A-430 (1): the tokens the module kept before under the old fixed name are the ones the first mint replaces.
|
|
assert.deepEqual(forge.deletedBy, ["id", "id"]);
|
|
assert.deepEqual(ORDER, [`own-put ${VAULT} 1`, "delete mesh-tools", "delete mesh-tools"]);
|
|
assert.equal(forge.twins.length, 0);
|
|
assert.deepEqual([...forge.tokens.keys()].sort(), ["backup", "ci", "laptop", "mesh-tools-1"]);
|
|
});
|
|
|
|
test("concurrent first calls share one mint", async () => {
|
|
const { env, logs } = await delivered(forge);
|
|
forge.tokens.clear();
|
|
const client = minted(env, logs);
|
|
const before = forge.mints;
|
|
|
|
await Promise.all([client.listRepos(), client.listRepos(), client.listRepos()]);
|
|
|
|
assert.equal(forge.mints, before + 1);
|
|
});
|
|
|
|
test("two processes, one holding the old token, both refused, mint one token in all: the second waits for the lease and uses the vault's newer token", async () => {
|
|
const { env, bus, logs } = await delivered(forge);
|
|
forge.tokens.clear();
|
|
forge.twins.length = 0;
|
|
const first = minted(env, logs);
|
|
await first.listRepos();
|
|
const second = minted(env, logs);
|
|
await second.listRepos(); // both hold mesh-tools-1
|
|
const before = forge.mints;
|
|
|
|
forge.tokens.set("mesh-tools-1", "revoked-meanwhile");
|
|
await Promise.all([first.listRepos(), second.listRepos()]);
|
|
|
|
// Design 47 H2 §808: one mint in all, and the forge holds one token for the account after.
|
|
assert.equal(forge.mints, before + 1);
|
|
assert.deepEqual([...forge.tokens.keys()].filter((n) => n.startsWith("mesh-tools")), ["mesh-tools-2"]);
|
|
assert.equal(bus.vault.get(VAULT)?.generation, 2);
|
|
assert.ok(logs.some((l) => l.includes("another process holds the mint lease")), logs.join("\n"));
|
|
assert.equal(bus.kv.size, 0, "the lease is deleted after the mint");
|
|
});
|
|
|
|
test("a minter killed while holding the lease is replaced after mint-lease: the waiter creates the lease itself and mints", async () => {
|
|
let clock = Date.parse("2026-11-22T00:00:00Z");
|
|
const now = () => new Date(clock);
|
|
const { env, bus, logs } = await delivered(forge, now);
|
|
forge.tokens.clear();
|
|
// A process that took the lease and died: its key lives mint-lease (60 s) and nobody deletes it.
|
|
await bus.ask("mesh/state.create", { state: "token-lease", key: "mint", value: { holder: "ace/4242", since: now().toISOString() }, ttl_seconds: 60 });
|
|
const waited: number[] = [];
|
|
const lease = leaseOverState();
|
|
// Waiting for the key to change: nothing changes, so the wait lasts its bound, the clock moving on by it.
|
|
const before = forge.mints;
|
|
|
|
const repos = await minted(env, logs, { lease: { ...lease, changed: async (ms) => { waited.push(ms); clock += ms; } } }).listRepos();
|
|
|
|
assert.equal(repos.length, 1);
|
|
assert.deepEqual(waited, [60_000], "the waiter waited mint-lease once");
|
|
assert.equal(forge.mints, before + 1);
|
|
assert.ok(logs.some((l) => l.includes("another process holds the mint lease (ace/4242 since")), logs.join("\n"));
|
|
});
|
|
|
|
test("the admin account is refused: said plainly, nothing kept, and the next call fails the same way rather than crashing", async () => {
|
|
const { env, bus, logs } = await delivered(forge);
|
|
forge.tokens.clear();
|
|
forge.admins.delete(ADMIN); // the forge's data came from a predecessor; mesh-admin was never created there
|
|
try {
|
|
const client = minted(env, logs);
|
|
const before = forge.mints;
|
|
|
|
await assert.rejects(client.listRepos(), (err: unknown) => {
|
|
assert.ok(err instanceof AdminRefused, String(err));
|
|
// 47 H2 §776: the forge's refusal, never worded as an account to create.
|
|
assert.match(err.message, /the forge refuses the mesh's admin account "mesh-admin" \(401\)/);
|
|
assert.doesNotMatch(err.message, /[Cc]reate/);
|
|
assert.ok(!err.message.includes(PASSWORD));
|
|
return true;
|
|
});
|
|
await assert.rejects(client.listRepos(), AdminRefused);
|
|
assert.equal(forge.mints, before);
|
|
assert.equal(bus.vault.size, 0);
|
|
|
|
// The account appears (the operator created it): the very next call mints and works.
|
|
forge.admins.set(ADMIN, PASSWORD);
|
|
assert.equal((await client.listRepos()).length, 1);
|
|
assert.equal(forge.mints, before + 1);
|
|
} finally {
|
|
forge.admins.set(ADMIN, PASSWORD);
|
|
}
|
|
});
|
|
|
|
test("one process shares one source per account — the watcher and the tools never renew against each other", async () => {
|
|
const { env } = await delivered(forge);
|
|
assert.equal(MintedToken.fromEnv(env.MESH_GITEA_URL!, env), MintedToken.fromEnv(env.MESH_GITEA_URL!, env));
|
|
});
|
|
|
|
test("a second process finds the token the first renewed in the vault, and reuses it instead of minting over it", async () => {
|
|
const { env, logs } = await delivered(forge);
|
|
forge.tokens.clear();
|
|
const first = minted(env, logs);
|
|
const second = minted(env, logs);
|
|
await first.listRepos();
|
|
await second.listRepos(); // both hold the same token
|
|
const before = forge.mints;
|
|
|
|
forge.tokens.set("mesh-tools-1", "revoked-meanwhile");
|
|
await first.listRepos(); // renews: one mint
|
|
await second.listRepos(); // rejected too — but the vault already holds the renewed one
|
|
|
|
assert.equal(forge.mints, before + 1);
|
|
assert.ok(logs.some((l) => l.includes("is newer (generation 2) — reusing it")), logs.join("\n"));
|
|
});
|
|
|
|
test("forge_token_lease says the lease's holder and since when, and each token's age from the vault, never the token", async () => {
|
|
let clock = Date.parse("2026-11-22T00:00:00Z");
|
|
const now = () => new Date(clock);
|
|
const { env, bus, logs } = await delivered(forge, now);
|
|
forge.tokens.clear();
|
|
await minted(env, logs, { now }).listRepos();
|
|
await bus.ask("mesh/state.create", { state: "token-lease", key: "mint", value: { holder: "ace/4242", since: "2026-11-22T00:00:30Z" }, ttl_seconds: 60 });
|
|
clock += 90_000;
|
|
const tool = tokenLeaseTool(vaultOverBus(), leaseOverState(), ["mesh-tools", "mesh-packages"], now);
|
|
|
|
const said = await tool.run({}, undefined as never) as any;
|
|
|
|
assert.equal(tool.name, "forge_token_lease");
|
|
assert.deepEqual(said.tokens.map((t: any) => [t.account, t.held, t.generation, t["age-seconds"]]),
|
|
[["mesh-tools", true, 1, 90], ["mesh-packages", false, undefined, undefined]]);
|
|
assert.ok(!JSON.stringify(said).includes(vaulted(bus)), "the token is never said");
|
|
// The lease lives mint-lease: past it, nobody holds it.
|
|
clock += 30_000;
|
|
assert.deepEqual((await tool.run({}, undefined as never) as any).lease, { held: false });
|
|
});
|
|
|
|
test("a configured token wins, and is reported rather than minted over when the forge rejects it", async () => {
|
|
const { env } = await delivered(forge);
|
|
const before = forge.mints;
|
|
|
|
const client = GiteaClient.fromEnv({ ...env, GITEA_TOKEN: "one-somebody-pasted-in" });
|
|
|
|
await assert.rejects(client.listRepos(), /rejected the configured Gitea token \(401\)/);
|
|
assert.equal(forge.mints, before);
|
|
// MESH_GITEA_TOKEN is no word of the mesh's (nothing sets it, checks/environment): it is not read, the module mints.
|
|
await assert.doesNotReject(GiteaClient.fromEnv({ ...env, MESH_GITEA_TOKEN: "one-somebody-pasted-in" }).listRepos());
|
|
});
|
|
|
|
test("nothing to mint with and no token: the client says what is missing", async () => {
|
|
assert.throws(
|
|
() => GiteaClient.fromEnv({ MESH_GITEA_URL: forge.url, MESH_GITEA_ADMIN_USER: ADMIN, MESH_GITEA_TOOLS_USER: "mesh-tools-nothing" }),
|
|
/set GITEA_TOKEN, or MESH_GITEA_ADMIN_PASSWORD_FILE/,
|
|
);
|
|
});
|
|
|
|
test("the tools register once there is a way to a token, and the first call mints it", async () => {
|
|
const { env } = await delivered(forge);
|
|
const before = forge.mints;
|
|
|
|
const withAdmin = collectTools(env).find((c) => c.module === "gitea")!;
|
|
const withNothing = collectTools({}).find((c) => c.module === "gitea")!;
|
|
|
|
assert.equal(withNothing.tools.length, 0);
|
|
assert.deepEqual(
|
|
withAdmin.tools.map((t) => t.name),
|
|
[
|
|
"gitea_list_repos", "gitea_create_repo", "gitea_delete_repo",
|
|
"gitea_list_issues", "gitea_get_issue", "gitea_create_issue", "gitea_close_issue",
|
|
"gitea_list_pull_requests", "gitea_get_pull_request", "gitea_create_pull_request",
|
|
"gitea_close_pull_request",
|
|
"gitea_reopen_pull_request",
|
|
"gitea_update_pull_request",
|
|
"gitea_pull_request_files",
|
|
"gitea_pull_request_diff",
|
|
"gitea_list_comments",
|
|
"gitea_reopen_issue",
|
|
"gitea_get_file",
|
|
"gitea_list_branches",
|
|
"gitea_delete_branch",
|
|
"gitea_branch_protection_get", "gitea_team_rights", "gitea_branch_protection_set", "gitea_branch_protection_set_full", "gitea_branch_protection_loosen", "gitea_repo_settings_set_full",
|
|
"gitea_default_branch_set", "gitea_pull_base_set",
|
|
"gitea_commit_statuses", "gitea_open_pulls", "gitea_commit_trees", "gitea_contains",
|
|
"gitea_list_labels", "gitea_create_label",
|
|
"gitea_api",
|
|
],
|
|
);
|
|
assert.equal(forge.mints, before, "registering must not mint — the forge may not be up yet");
|
|
|
|
const result = (await withAdmin.tools.find((t) => t.name === "gitea_list_repos")!.run({})) as { repos: unknown[] };
|
|
assert.equal(result.repos.length, 1);
|
|
assert.equal(forge.mints, before + 1);
|
|
});
|
|
|
|
// The forge's tools reach every action a review needs without a checkout and without the API
|
|
// escape hatch: close a pull request whose work landed elsewhere, read its diff, its comments, a
|
|
// file, the branches, and delete the branch left behind. Against the fake forge, through the
|
|
// compiled tools, the way the console calls them.
|
|
test("a pull request can be closed, read and cleaned up through the tools", async () => {
|
|
const { env } = await delivered(forge);
|
|
const tools = collectTools(env).find((c) => c.module === "gitea")!.tools;
|
|
const tool = (name: string) => tools.find((t) => t.name === name)!;
|
|
for (const name of ["gitea_close_pull_request", "gitea_reopen_pull_request", "gitea_update_pull_request", "gitea_pull_request_files",
|
|
"gitea_pull_request_diff", "gitea_list_comments", "gitea_reopen_issue", "gitea_get_file", "gitea_list_branches", "gitea_delete_branch"]) {
|
|
assert.ok(tool(name), `${name} is not a tool`);
|
|
}
|
|
const closed = (await tool("gitea_close_pull_request").run({ owner: "novox", repo: "hq", number: 223 })) as { pull: { state: string } };
|
|
assert.equal(closed.pull.state, "closed");
|
|
assert.equal(forge.pullState, "closed");
|
|
const renamed = (await tool("gitea_update_pull_request").run({ owner: "novox", repo: "hq", number: 223, title: "Superseded" })) as { pull: { title: string } };
|
|
assert.equal(renamed.pull.title, "Superseded");
|
|
const diff = (await tool("gitea_pull_request_diff").run({ owner: "novox", repo: "hq", number: 223 })) as { diff: string };
|
|
assert.match(diff.diff, /^diff --git/);
|
|
const comments = (await tool("gitea_list_comments").run({ owner: "novox", repo: "hq", number: 223 })) as { comments: { body: string }[] };
|
|
assert.equal(comments.comments[0].body, "landed elsewhere");
|
|
const file = (await tool("gitea_get_file").run({ owner: "novox", repo: "hq", path: "README.md" })) as { file: { content: string } };
|
|
assert.equal(file.file.content, "hello");
|
|
const branches = (await tool("gitea_list_branches").run({ owner: "novox", repo: "hq" })) as { branches: { name: string }[] };
|
|
assert.deepEqual(branches.branches.map((b) => b.name), ["main", "feat/x"]);
|
|
await tool("gitea_delete_branch").run({ owner: "novox", repo: "hq", branch: "feat/x" });
|
|
assert.equal(forge.branchDeleted, true);
|
|
});
|