From 5a82d93ccb886e7ca3f7518e044f16ee6dee74cd Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:10:33 +0100 Subject: [PATCH] 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 --- modules/gitea/catalog.ts | 15 +--- modules/gitea/findings.ts | 19 +++++ modules/gitea/packages-account.ts | 3 +- modules/gitea/test/token.test.ts | 105 ++++++++++++++++++++++++-- modules/gitea/token.ts | 86 +++++++++++++++++++-- modules/gitea/tokenfiles.ts | 121 ++++++++++++++++++++++++++++++ 6 files changed, 324 insertions(+), 25 deletions(-) create mode 100644 modules/gitea/findings.ts create mode 100644 modules/gitea/tokenfiles.ts diff --git a/modules/gitea/catalog.ts b/modules/gitea/catalog.ts index b02664536..eee2af55e 100644 --- a/modules/gitea/catalog.ts +++ b/modules/gitea/catalog.ts @@ -127,20 +127,7 @@ export class CatalogView { /** The kind of a finding of a first view unanswered past its bound (ADR 0615 §6), as mesh-sdk's Go views writes it. */ export const UNANSWERED_KIND = "first-view-unanswered"; -/** The key of a finding about a module: scope, the id's dotted parts, and the kind, each part made safe (mesh-sdk health.Key). */ -export function findingKey(scope: string, id: string, kind: string): string { - return [scope, ...id.split("."), kind].map((p) => p.trim().replace(/[^A-Za-z0-9_=/-]/g, "_") || "_").join("."); -} - -/** A finding as the condition keeper reads it from the module's state `findings`: its key and its value. */ -export function findingValue(f: Finding): { key: string; value: Record } { - const key = findingKey("module", f.id, f.kind); - return { key, value: { - v: 1, key, kind: f.kind, subject: { scope: "module", id: f.id }, severity: "warning", summary: f.summary, headline: f.headline, - explanation: f.explanation, resolved: "", evidence: [{ at: f.at, said: f.summary }], source: `${f.observer}.${f.kind}`, - observer: f.observer, at: f.at, - } }; -} +export { findingKey, findingValue } from "./findings.js"; /** A part's finding of a first view unanswered past its bound, from the follower's status. */ export function unansweredFinding(part: string, s: Status, at: Date): Finding { diff --git a/modules/gitea/findings.ts b/modules/gitea/findings.ts new file mode 100644 index 000000000..b9fd41b06 --- /dev/null +++ b/modules/gitea/findings.ts @@ -0,0 +1,19 @@ +// The key and the value of a finding a part writes into its own state `findings`, as the condition keeper reads it +// (kept apart from catalog.ts, which loads the catalog seat's contract, so a part that only writes a finding loads nothing else). + +import type { Finding } from "@novox/mesh-sdk/views"; + +/** The key of a finding about a module: scope, the id's dotted parts, and the kind, each part made safe (mesh-sdk health.Key). */ +export function findingKey(scope: string, id: string, kind: string): string { + return [scope, ...id.split("."), kind].map((p) => p.trim().replace(/[^A-Za-z0-9_=/-]/g, "_") || "_").join("."); +} + +/** A finding as the condition keeper reads it from the module's state `findings`: its key and its value. */ +export function findingValue(f: Finding): { key: string; value: Record } { + const key = findingKey("module", f.id, f.kind); + return { key, value: { + v: 1, key, kind: f.kind, subject: { scope: "module", id: f.id }, severity: "warning", summary: f.summary, headline: f.headline, + explanation: f.explanation, resolved: "", evidence: [{ at: f.at, said: f.summary }], source: `${f.observer}.${f.kind}`, + observer: f.observer, at: f.at, + } }; +} diff --git a/modules/gitea/packages-account.ts b/modules/gitea/packages-account.ts index bc264d44d..e0adb5c83 100644 --- a/modules/gitea/packages-account.ts +++ b/modules/gitea/packages-account.ts @@ -19,7 +19,7 @@ import { randomBytes } from "node:crypto"; import { adminFromEnv, MintedToken } from "./token.js"; -import { TOOLS_ORG, type ToolsForge } from "./tools-account.js"; +import { TOOLS_ACCOUNT, TOOLS_ORG, type ToolsForge } from "./tools-account.js"; /** The account the package seats write as (internal/forgehttp PackagesAccount). */ export const PACKAGES_ACCOUNT = "mesh-packages"; @@ -52,6 +52,7 @@ export function packagesToken(url: string, env: NodeJS.ProcessEnv = process.env, const base = over.vault && over.lease ? {} : MintedToken.settingsFromEnv(env); return new MintedToken({ ...base, ...over, url, admin, passwordFile, account, oldName: PACKAGES_TOKEN_NAME, scopes: PACKAGES_TOKEN_SCOPES, log, + tokenFile: "packages-token", listAccounts: async () => [account, env.MESH_GITEA_TOOLS_USER || TOOLS_ACCOUNT], setUp: async (password) => { const { GiteaAdmin } = await import("./client.js"); await setUpPackagesAccount(new GiteaAdmin(url, admin, password), account, () => randomBytes(24).toString("base64url")); diff --git a/modules/gitea/test/token.test.ts b/modules/gitea/test/token.test.ts index 0bd3e0008..bfe5da014 100644 --- a/modules/gitea/test/token.test.ts +++ b/modules/gitea/test/token.test.ts @@ -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; admins: Map; pullState: string; @@ -119,7 +120,7 @@ function fakeForge(): Promise { 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 { 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): Promise { + 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(); 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) => + 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")); +}); diff --git a/modules/gitea/token.ts b/modules/gitea/token.ts index c02c3fa01..52eb09991 100644 --- a/modules/gitea/token.ts +++ b/modules/gitea/token.ts @@ -47,6 +47,7 @@ import { state, type State } from "@novox/mesh-sdk/state"; import { setUpToolsAccount, TOOLS_ACCOUNT, type AdminCall } from "./tools-account.js"; import { keepMainRules } from "./mainrules.js"; import { durationMs } from "./taken.js"; +import { passOver, readLists, remaining, type FindingSink, type ForgeTokens, type Lists } from "./tokenfiles.js"; /** The tools' token's old fixed name in the forge's list, the one the admin's own token carried too (ADR 0365 §2). */ export const TOKEN_NAME = "mesh-tools"; @@ -283,8 +284,16 @@ export interface MintedTokenOptions { readonly leaseMs?: number; /** Who holds the lease when this process does: the node and the process. */ readonly holder?: string; - /** The module's runtime state directory, where a retirement of the admin's old token that failed is remembered. */ + /** The module's runtime state directory, where a retirement of the admin's old token that failed is remembered, and + * where an earlier build kept the token files (tokenfiles.ts). */ readonly stateDir?: string; + /** The name of the token file an earlier build kept for this account (`token`, `packages-token`): at each start while + * it remains, it is ended once this start's token is held (H-A-575, H-A-699). */ + readonly tokenFile?: string; + /** The accounts whose tokens at the forge are listed to find the files' tokens, besides the admin's (H-A-699 (2)). */ + readonly listAccounts?: () => Promise; + /** The module's state `findings`, where a token file that stays is written (token-file-unrevoked). */ + readonly findings?: FindingSink; readonly now?: () => Date; readonly log?: (line: string) => void; readonly fetch?: typeof fetch; @@ -293,6 +302,9 @@ export interface MintedTokenOptions { /** The token the module mints for itself, kept in the vault and renewed when the forge rejects it. */ export class MintedToken implements TokenSource { private held: VaultToken | null = null; + /** The forge's token lists, read once at this start before it deletes any token there: null when they could not be read. */ + private fileLists: Lists | null | undefined; + private filesPassed = false; private inflight: Promise | null = null; private readonly scopes: readonly string[]; private readonly ttlMs: number; @@ -330,7 +342,11 @@ export class MintedToken implements TokenSource { if (shared) return shared; if (account === admin) throw new Error(`MESH_GITEA_TOOLS_USER names the admin account "${admin}"; the tools act as an account of their own (novox/hq ADR 0365)`); const source = new MintedToken({ - ...MintedToken.settingsFromEnv(env), url, admin, passwordFile, account, oldName: TOKEN_NAME, + ...MintedToken.settingsFromEnv(env), url, admin, passwordFile, account, oldName: TOKEN_NAME, tokenFile: "token", + listAccounts: async () => { + const { PACKAGES_ACCOUNT } = await import("./packages-account.js"); + return [account, env.MESH_GITEA_PACKAGES_USER || PACKAGES_ACCOUNT]; + }, // GiteaAdmin is loaded when first used: client.ts imports this file. setUp: async (password) => { const { GiteaAdmin } = await import("./client.js"); @@ -344,12 +360,12 @@ export class MintedToken implements TokenSource { private static readonly shared = new Map(); /** What every account's source takes from the environment: the vault and lease over the bus, the two settings. */ - static settingsFromEnv(env: NodeJS.ProcessEnv): Pick { + static settingsFromEnv(env: NodeJS.ProcessEnv): Pick { const log = (line: string) => console.log(`[gitea] ${line}`); return { vault: sharedVault(), lease: sharedLease(), ttlMs: settingMs(env, "token-ttl", TOKEN_TTL_DEFAULT, log), leaseMs: settingMs(env, "mint-lease", MINT_LEASE_DEFAULT, log), - stateDir: env.MESH_GITEA_STATE_DIR || undefined, + stateDir: env.MESH_GITEA_STATE_DIR || undefined, findings: state("findings"), }; } @@ -368,6 +384,7 @@ export class MintedToken implements TokenSource { if (this.retireFile && existsSync(this.retireFile)) await this.retireAdmin().catch((err) => this.log(`${err}`)); } this.held = kept; + await this.endTokenFiles(); return kept.token; } @@ -403,7 +420,10 @@ export class MintedToken implements TokenSource { private mint(why: string, stale: string | null): Promise { if (this.inflight === null) { this.log(why); - this.inflight = this.leased(stale).finally(() => { + this.inflight = this.leased(stale).then(async (token) => { + await this.endTokenFiles(); + return token; + }).finally(() => { this.inflight = null; }); } @@ -438,6 +458,59 @@ export class MintedToken implements TokenSource { } } + /** The forge's token lists, once a start, when a token file of this account remains; a read that fails is said and + * leaves every file standing. */ + private async readFileLists(admin: AdminCall = this.adminCall()): Promise { + if (this.fileLists !== undefined || !this.opts.stateDir || !this.opts.tokenFile) return; + if (remaining(this.opts.stateDir, this.opts.tokenFile).length === 0) return; + try { + const accounts = [...(await this.opts.listAccounts?.() ?? [this.opts.account]), this.opts.admin]; + this.fileLists = await readLists(this.forgeTokens(admin), accounts); + } catch (err) { + this.fileLists = null; + this.log(`the forge's token lists could not be read, so the token files an earlier build kept stay: ${err instanceof Error ? err.message : err}`); + } + } + + private forgeTokens(admin: AdminCall): ForgeTokens { + return { + list: async (account) => { + const out: { id: number; token_last_eight: string; scopes: string[] }[] = []; + for (let page = 1; page <= 100; page++) { + const listed = await admin("GET", `/users/${encodeURIComponent(account)}/tokens?page=${page}&limit=50`); + if (listed.status !== 200 || !Array.isArray(listed.body)) throw new Error(`Gitea GET /users/${account}/tokens: ${listed.status} ${detail(listed.body)}`); + if (listed.body.length === 0) break; + for (const t of listed.body) { + if (typeof t?.id === "number" && typeof t?.token_last_eight === "string") { + out.push({ id: t.id, token_last_eight: t.token_last_eight, scopes: Array.isArray(t.scopes) ? t.scopes.map(String) : [] }); + } + } + } + return out; + }, + revoke: async (account, id) => { + const res = await admin("DELETE", `/users/${encodeURIComponent(account)}/tokens/${id}`); + return res.status === 204 || res.status === 404 ? null : `${res.status} ${detail(res.body)}`; + }, + }; + } + + /** The earlier build's token files end once this start's token is held, at the first time in this process (H-A-575, + * H-A-602, H-A-699): never a failure of the token. */ + private async endTokenFiles(): Promise { + if (this.filesPassed || !this.opts.stateDir || !this.opts.tokenFile) return; + this.filesPassed = true; + if (remaining(this.opts.stateDir, this.opts.tokenFile).length === 0) return; + try { + await this.readFileLists(); + if (!this.fileLists) return; + await passOver({ dir: this.opts.stateDir, base: this.opts.tokenFile, lists: this.fileLists, forge: this.forgeTokens(this.adminCall()), + findings: this.opts.findings, log: (l) => this.log(l), now: this.now }); + } catch (err) { + this.log(`the token files an earlier build kept could not be ended: ${err instanceof Error ? err.message : err}`); + } + } + /** The admin password, read now. */ private password(): string { try { @@ -528,6 +601,9 @@ export class MintedToken implements TokenSource { if (kept !== generation) this.log(`the vault kept ${vaultName(account)} at generation ${kept}, the forge names it ${name}`); this.held = { token, scopes: this.scopes, generation: kept, changedAt: this.now().toISOString() }; this.log(`minted ${name} for "${account}" (${this.scopes.join(", ")}), kept in the vault as ${vaultName(account)}`); + // The lists are read now, after the own-put and before the drop of the old fixed name below: the earlier build's + // token files hold tokens of that name (H-A-699 (2)). + await this.readFileLists(admin); // Only now, with the new token kept, does the one it replaces go. const gone = replaced ? mintName(account, replaced.generation) : this.opts.oldName; diff --git a/modules/gitea/tokenfiles.ts b/modules/gitea/tokenfiles.ts new file mode 100644 index 000000000..1a09cb9ed --- /dev/null +++ b/modules/gitea/tokenfiles.ts @@ -0,0 +1,121 @@ +// The token files an earlier build kept under the module's state directory, and their end (design 47 H2 H-A-575, +// H-A-602, H-A-642, H-A-699). An earlier build wrote each account's token to `token` (the tools') or `packages-token` +// (the packages account's), the scopes it was minted with beside it in `.scopes` ("", +// then " for " for an account that is not the admin), each written through a `.tmp` and renamed. The vault +// keeps the tokens now, so no build writes these files and this pass ends them: +// +// - it runs at each start of the process while any of the files remains, once this start's token is held; +// - a file's token is found at the forge by the last eight characters of the token and the scopes its `.scopes` names, +// in the lists read before this start deleted any token there; a matched pair is revoked at the forge by its id, +// then both files are deleted; a `.tmp` goes with its pair, and one holding no whole token (forty hexadecimal +// characters) is deleted with no revocation, since it names no token at the forge; +// - a pair with no match, and a pair whose revocation the forge refused, stay, said in the journal and written as the +// finding `token-file-unrevoked` (id the file) in the module's `findings`, cleared when the pair is deleted. + +import { existsSync, readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { findingKey, findingValue } from "./findings.js"; + +export const TOKEN_FILE_UNREVOKED = "token-file-unrevoked"; + +/** A token as the forge lists it: never its value, its id, its last eight characters and its scopes. */ +export interface ListedToken { readonly id: number; readonly token_last_eight: string; readonly scopes: readonly string[] } + +/** What the pass asks of the forge, as the administrator. */ +export interface ForgeTokens { + /** Every token an account holds. */ + list(account: string): Promise; + /** Delete one by its id; null when it is deleted or was gone, else the forge's answer. */ + revoke(account: string, id: number): Promise; +} + +/** The module's state `findings`. */ +export interface FindingSink { + put(key: string, value: unknown): Promise; + delete(key: string): Promise; +} + +/** The tokens each account held when the lists were read. */ +export type Lists = ReadonlyMap; + +/** The files one token file's name stands for: the token, its scopes, and a `.tmp` of each. */ +export const filesOf = (base: string): string[] => [base, `${base}.tmp`, `${base}.scopes`, `${base}.scopes.tmp`]; + +/** The files of `base` that remain under `dir`. */ +export const remaining = (dir: string, base: string): string[] => filesOf(base).filter((f) => existsSync(join(dir, f))); + +/** The lists of each account, read once. */ +export async function readLists(forge: ForgeTokens, accounts: readonly string[]): Promise { + const lists = new Map(); + for (const account of accounts) if (!lists.has(account)) lists.set(account, await forge.list(account)); + return lists; +} + +const WHOLE = /^[0-9a-f]{40}$/; +const sorted = (scopes: readonly string[]): string => [...scopes].sort().join(","); + +export interface PassOptions { + readonly dir: string; + /** `token` or `packages-token`. */ + readonly base: string; + readonly lists: Lists; + readonly forge: ForgeTokens; + readonly findings?: FindingSink; + readonly log: (line: string) => void; + readonly now?: () => Date; +} + +/** The pass over one token file's pair and their `.tmp` files. Never throws for a file it cannot end: it stays, said. */ +export async function passOver(o: PassOptions): Promise { + const at = (o.now ?? (() => new Date()))().toISOString(); + const path = (f: string) => join(o.dir, f); + const scopesFile = [`${o.base}.scopes`, `${o.base}.scopes.tmp`].find((f) => existsSync(path(f))); + // The scopes its `.scopes` names, without the account they are "for". + const named = scopesFile === undefined ? null : sorted(readFileSync(path(scopesFile), "utf8").trim().split(" for ")[0].split(",").filter(Boolean)); + const clear = async (file: string) => { await o.findings?.delete(findingKey("module", file, TOKEN_FILE_UNREVOKED)); }; + const keep = async (file: string, why: string) => { + o.log(`the token file ${file} stays: ${why}`); + const f = findingValue({ observer: "gitea", kind: TOKEN_FILE_UNREVOKED, id: file, at, + summary: `the token file ${file} under gitea's state directory stays: ${why}`, + headline: `gitea could not end the token file ${file}`, + explanation: `An earlier build of gitea kept its token in ${file}. The vault keeps the tokens now, so the file is revoked at the forge and ` + + `deleted at each start of the module; this one stays because ${why}. It is tried again at the next start; delete the token at the forge by hand and the file with it to end it.` }); + await o.findings?.put(f.key, f.value); + }; + for (const file of [o.base, `${o.base}.tmp`]) { + if (!existsSync(path(file))) continue; + const token = readFileSync(path(file), "utf8").trim().split("\n")[0].trim(); + if (!WHOLE.test(token)) { + rmSync(path(file), { force: true }); + o.log(`deleted the token file ${file}: it holds no whole token, so nothing is revoked at the forge`); + await clear(file); + continue; + } + const last = token.slice(-8); + let found: { account: string; id: number } | null = null; + if (named !== null) { + for (const [account, tokens] of o.lists) { + const t = tokens.find((x) => x.token_last_eight === last && sorted(x.scopes) === named); + if (t) { found = { account, id: t.id }; break; } + } + } + if (found === null) { + await keep(file, named === null ? "its scopes file is gone, so no token at the forge can be matched to it" : "no token at the forge matches its last eight characters and its scopes"); + continue; + } + const refused = await o.forge.revoke(found.account, found.id).catch((err) => err instanceof Error ? err.message : String(err)); + if (refused !== null) { + await keep(file, `the forge refused to revoke its token (${refused})`); + continue; + } + rmSync(path(file), { force: true }); + o.log(`revoked the token ${file} held, at the forge, and deleted ${file}`); + await clear(file); + } + // The scopes hold no token: they go when no token file of the pair remains. + if (![o.base, `${o.base}.tmp`].some((f) => existsSync(path(f)))) { + for (const f of [`${o.base}.scopes`, `${o.base}.scopes.tmp`]) { + if (existsSync(path(f))) { rmSync(path(f), { force: true }); o.log(`deleted ${f}`); } + } + } +}