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
+121
View File
@@ -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 `<file>.scopes` ("<sorted scopes, comma-joined>",
// then " for <account>" 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<readonly ListedToken[]>;
/** Delete one by its id; null when it is deleted or was gone, else the forge's answer. */
revoke(account: string, id: number): Promise<string | null>;
}
/** The module's state `findings`. */
export interface FindingSink {
put(key: string, value: unknown): Promise<unknown>;
delete(key: string): Promise<void>;
}
/** The tokens each account held when the lists were read. */
export type Lists = ReadonlyMap<string, readonly ListedToken[]>;
/** 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<Lists> {
const lists = new Map<string, readonly ListedToken[]>();
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<void> {
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}`); }
}
}
}