Files
reverse-engineering-anything/src/desktop/GpgvKeyCheck.test.ts
T
morluto ab84ba6839 fix(process)!: retain inspection cancellation and cleanup ownership (#10113)
* fix(process): preserve producer-owned inspection cancellation

Prototype the explicit inspection origin and retained file/batch owner protocol. Downstream adapter migration and lease binding remain required before integration.

* fix(process): type inspection ownership handoffs precisely

* fix(process): retain plain inspection preparation cancellation

* fix(process): retain explicit inspection cleanup and cancellation facts

* fix(process): require explicit inspection facts and cleanup scope

* refactor(process): remove redundant cleanup forwarding wrapper

* fix(firmware): retain inspection cancellation and cleanup ownership

* fix(wakaru): retain typed inspection outcomes and caller scope

* fix(ghidra): preserve inspection facts and launch cleanup scope

* fix(providers): preserve typed process inspection outcomes

* refactor(process): remove obsolete inspection cancellation re-export

* fix(native): preserve inspection preparation cleanup and cancellation

* fix(registration): retain typed inspection cleanup during Git discovery

* fix(process): preserve inspection deadline origin in adapter handoff

* fix(process): consume the canonical inspection selector in binding

* fix(native): preserve inspection deadlines and cleanup retry completion

* test(process): narrow the retained Darwin preparation owner

* fix(providers): preserve preparation ownership and timeout policy

Narrow preparation facts through their canonical owner, preserve actual cleanup capabilities and recorded cancellation, and keep enclosing command deadlines authoritative. Retain raw inspection records through Java refusal and configuration projections without changing availability fallback policy.

* refactor(process): use one inspection failure type owner

* fix(providers): retain recorded secondary failures when rebinding

* fix(ghidra): preserve normalized inspection facts through public projection

* fix(process): normalize native process listing cancellation

* docs(development): clarify failure provenance and cleanup verification

* fix(process): preserve direct inspection cancellation facts

* fix(process): retain inspection owners through termination

* fix(process): preserve command inspection cleanup provenance

* fix(desktop): preserve inspection facts after cleanup retry

* refactor(process)!: migrate desktop capture with inspection producers

* fix(desktop)!: preserve capture failure origins and cleanup owners (#10115)

* fix(desktop): preserve capture failure origins and cleanup

* fix(desktop): type keyring cleanup cancellation

* fix(kuna)!: retain copy cleanup before retiring workspaces (#10114)

* fix(kuna): own copy cancellation and descriptor cleanup

* fix(kuna): close copy descriptors before workspace removal

* test(kuna): type copy lifecycle gates for project library

* docs(kuna): explain retained copy-file cleanup and staging ownership

* docs(kuna): separate cache publication, integrity and cleanup guidance

* fix(desktop): retain sampling inspection owners before release

* fix(process): preserve capture file read cancellation origin

* fix(process): retain capture inspection cancellation and cleanup owners

* fix(process): retain sampling inspection failures in capture scope

* fix(process): retain inspection failures through mandatory cleanup

* fix(process): distinguish sampler shutdown from capture cancellation

* fix(browser): retain startup EOF before later cancellation

* fix(process): bind capture inspection cleanup to the owning run

* test(process): migrate cancellation fixtures to typed owners

Record explicit preparation and command cancellation facts, retain exact opaque reasons and physical causes, and guard the mocked version probe from native preparation. Keep the live Wakaru command control while adding a recording equivalent for bounded source verification.

* fix(process): own sampling reads and settle inspection peers

* fix(errors): retain authored recovery through cleanup composition

* fix(process): retain all sampling inspection leaves for final cleanup

* test(browser): report recording cleanup signal outcome

* fix(process): keep inspection error context out of implicit JSON

* fix(desktop): retain normalized sampling cleanup ownership

* test(process): assert tagged startup cancellation
2026-11-11 16:37:48 -05:00

192 lines
7.1 KiB
TypeScript

import { access, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import {
A_ARMORED,
SIGNED_BY_BOTH,
VENDOR_A,
VENDOR_B,
} from "../domain/desktop/aptKeys.fixture.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import { withGpgvKeyCheck } from "./GpgvKeyCheck.js";
import { runHostQuery, type QueryRunner } from "./HostQuery.js";
const hasGpgv =
typeof (await runHostQuery("gpgv", ["--version"], undefined)) === "object";
/** The release both vendor keys signed, and keyring files holding the given keys. */
const files = async (keyrings: Readonly<Record<string, Buffer>>) => {
const folder = await createTestTempDirectory("desktop-gpgv-");
const release = join(folder, "InRelease");
await writeFile(release, SIGNED_BY_BOTH);
const paths: Record<string, string> = {};
for (const [name, bytes] of Object.entries(keyrings)) {
paths[name] = join(folder, name);
await writeFile(paths[name], bytes);
}
return { release, paths };
};
afterEach(() => {
vi.restoreAllMocks();
});
describe.skipIf(!hasGpgv)("withGpgvKeyCheck with gpgv", () => {
it("accepts a key whose signature is good although the release's other signature has no key here", async () => {
const { release, paths } = await files({ "a.gpg": VENDOR_A.key });
const verified = await withGpgvKeyCheck(runHostQuery, undefined, (check) =>
check.firstVerifying([paths["a.gpg"] ?? ""], [release]),
);
expect(verified).toMatchObject({
path: paths["a.gpg"],
format: "binary",
fingerprint: VENDOR_A.fingerprint,
});
});
it("retains only the verifying key of a keyring holding several", async () => {
const { release, paths } = await files({
"trusted.gpg": Buffer.concat([VENDOR_B.key, VENDOR_A.key]),
});
const verified = await withGpgvKeyCheck(runHostQuery, undefined, (check) =>
check.firstVerifying([paths["trusted.gpg"] ?? ""], [release]),
);
if ("reason" in verified) throw new Error(verified.reason);
expect(verified.fingerprint).toBe(VENDOR_A.fingerprint);
expect(verified.bytes.equals(VENDOR_A.key)).toBe(true);
});
it("verifies the armored key a sources entry holds and retains it as it is, named by the entry's file", async () => {
const { release } = await files({});
const sources = "/etc/apt/sources.list.d/a-ubuntu-b-noble.sources";
const verified = await withGpgvKeyCheck(runHostQuery, undefined, (check) =>
check.heldVerifying({ path: sources, bytes: Buffer.from(A_ARMORED) }, [
release,
]),
);
if ("reason" in verified) throw new Error(verified.reason);
expect(verified).toMatchObject({
path: sources,
format: "armored",
fingerprint: VENDOR_A.fingerprint,
});
expect(verified.bytes.toString()).toBe(A_ARMORED);
});
});
describe("withGpgvKeyCheck cleanup", () => {
it.each(["completed", "failed"])(
"observes cancellation during final keyring cleanup after %s work",
async (completion) => {
const cancel = new AbortController();
const reason = new Error("cancelled during keyring cleanup");
const primary = new Error("verification failed");
const create = PrivateRuntimeRoot.create.bind(PrivateRuntimeRoot);
let path: string | undefined;
vi.spyOn(PrivateRuntimeRoot, "create").mockImplementationOnce(
async (options) => {
const root = await create(options);
path = root.path;
const close = root.close.bind(root);
vi.spyOn(root, "close").mockImplementationOnce(async () => {
cancel.abort(reason);
await close();
});
return root;
},
);
const { release, paths } = await files({ "a.gpg": VENDOR_A.key });
const result = withGpgvKeyCheck(
async () => ({ stdout: "", exitCode: 2 }),
cancel.signal,
async (check) => {
const verified = await check.firstVerifying(
[paths["a.gpg"] ?? ""],
[release],
);
if (completion === "failed") throw primary;
return verified;
},
);
if (completion === "failed") await expect(result).rejects.toBe(primary);
else {
const failure = await result.catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
if (!(failure instanceof ArtifactReaderFailure))
throw new Error("Expected typed keyring cleanup cancellation");
expect(failure.reason).toBe("cancelled");
expect(failure.cause).toBe(reason);
}
expect(path).toBeDefined();
await expect(access(path ?? "")).rejects.toMatchObject({
code: "ENOENT",
});
},
);
it("keeps the private keyring folder's owner when its removal fails", async () => {
const create = PrivateRuntimeRoot.create.bind(PrivateRuntimeRoot);
let owned: PrivateRuntimeRoot | undefined;
vi.spyOn(PrivateRuntimeRoot, "create").mockImplementationOnce(
async (options) => {
owned = await create(options);
vi.spyOn(owned, "close").mockRejectedValueOnce(new Error("busy"));
return owned;
},
);
const { release, paths } = await files({ "a.gpg": VENDOR_A.key });
const runQuery: QueryRunner = async () => ({ stdout: "", exitCode: 2 });
const failure = await withGpgvKeyCheck(runQuery, undefined, (check) =>
check.firstVerifying([paths["a.gpg"] ?? ""], [release]),
).then(
() => undefined,
(cause: unknown) => cause,
);
if (!(failure instanceof ArtifactReaderFailure) || owned === undefined)
throw new Error("expected a cleanup failure");
expect(failure.cleanup?.resources).toEqual([owned.path]);
await access(owned.path);
await Promise.all(
failure.cleanupLeases?.map((lease) => lease.release()) ?? [],
);
await expect(access(owned.path)).rejects.toMatchObject({ code: "ENOENT" });
});
it("writes a held key's keyring into the private folder and removes it, saying why the key does not verify", async () => {
const { release } = await files({});
const keyrings: string[] = [];
const runQuery: QueryRunner = async (_command, argv) => {
keyrings.push(argv[argv.indexOf("--keyring") + 1] ?? "");
return { stdout: "[GNUPG:] NEWSIG\n", exitCode: 2 };
};
const sources = "/etc/apt/sources.list.d/a-ubuntu-b-noble.sources";
const verified = await withGpgvKeyCheck(runQuery, undefined, (check) =>
check.heldVerifying({ path: sources, bytes: Buffer.from(A_ARMORED) }, [
release,
]),
);
if (!("reason" in verified)) throw new Error("expected a refusal");
expect(verified.reason).toContain(sources);
expect(verified.reason).toContain(release);
expect(verified.reason).not.toMatch(/[a-z][a-z0-9+.-]*:\/\//iu);
expect(keyrings).toHaveLength(1);
await expect(access(keyrings[0] ?? "")).rejects.toMatchObject({
code: "ENOENT",
});
});
});