문제
tests/unit/task3-selective-integration.test.ts의 EOF 테스트는
provider-scope-wrapper.ts를 새 Node로 띄우고, 준비 신호 없이 75 ms를 잔
뒤 stdin을 닫고 1초 안에 끝나기를 기다린다. 75 ms 안에 자식이 기동을
끝내지 못하면 Node 기동과 TS 모듈 import가 그 1초에 들어간다. 그래서
부하가 걸린 호스트에서 "provider scope EOF close timed out"으로 merge
게이트가 코드와 무관하게 떨어진다.
고른 방법
- guardian 테스트(c862004)와 같은 방식: 자식을 loader로 띄우고, loader가
바뀌지 않은 wrapper를 import한 뒤 여분 pipe(fd 3)에 1바이트를 쓴다.
테스트는 그 신호를 받은 뒤에 stdin을 닫는다. import가 끝나면 wrapper는
liveness 채널을 열고 EOF 처리기를 붙인 상태다.
- 한도는 1초 대신 같은 계열의 watchdog 5초로 둔다. 이 한도는 멈춤만
판정한다. wrapper에 EOF 마감 같은 프로토콜 요구는 없다.
- 버린 대안: 한도만 5초로 올리기. 기동 시간이 계속 한도 안에 든다.
PROVIDER_PROCESS_TRACE_PATH 기록을 준비 신호로 쓰기. 파일 poll에 다시
마감이 필요하다.
위험·한계
- wrapper는 main 모듈이 아니라 loader가 import한 모듈로 돈다. wrapper는
argv[2..]만 읽고 import.meta를 쓰지 않는다. 여분 fd 3은 신호 뒤 닫힌다.
- 파일 위치(tests/unit vs taxonomy의 tests/integration)는 1101/10-05와
같이 정할 일이라 옮기지 않았다.
검증
- RED: 자식만 기동에 1.5초를 쓰게 하는 --import 훅(scratchpad
slow-start.mjs)으로 수정 전 테스트가 "provider scope EOF close timed
out"으로 실패했다. 수정 뒤 같은 조건에서 통과(1.6초).
- 한 코어에 바쁜 이웃 14개(taskset) 5회 모두 통과.
- 변이: wrapper의 liveness.once("end", …)를 지우면 테스트가 실패한다
(code 0 ≠ 125). 되돌렸다.
- 파일 전체 7건 통과, eslint 통과.
Refs: docs/reviews/2026-11-03-maturity-review/10-tests-fast-layers.md 10-01
297 lines
12 KiB
TypeScript
297 lines
12 KiB
TypeScript
import { spawn } from "node:child_process";
|
|
import { writeFileSync } from "node:fs";
|
|
import { lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import { pathToFileURL } from "node:url";
|
|
|
|
import { afterEach, describe, expect, it } from "vitest";
|
|
|
|
import {
|
|
CI_CONTRACT_BASELINE_PATH,
|
|
loadCiGateContract,
|
|
measureCiContractBaseline,
|
|
parseCiGateContract,
|
|
} from "../../scripts/contracts/ci-gates.ts";
|
|
import { generateCiWorkflow } from "../../scripts/generate-ci-workflow.ts";
|
|
import { validatePackageScriptGraph } from "../../scripts/lib/package-script-graph.ts";
|
|
|
|
const roots: string[] = [];
|
|
/**
|
|
* Test watchdog only, as in tests/integration/provider-guardian-transaction.test.ts.
|
|
* It bounds a hang. The wrapper has no protocol deadline for EOF, and a loaded
|
|
* host can take longer than a second just to start a child.
|
|
*/
|
|
const PROCESS_WATCHDOG_MS = 5_000;
|
|
/** The extra pipe on which spawnLoadedScopeWrapper reports the wrapper loaded. */
|
|
const SCOPE_WRAPPER_LOADED_FD = 3;
|
|
|
|
afterEach(async () => {
|
|
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
|
});
|
|
|
|
describe("selective Task 3 contract closure", () => {
|
|
it("builds a private offline aggregate-cgroup provider launch without argv secrets", async () => {
|
|
const {
|
|
encodeProviderBwrapInput,
|
|
encodeProviderScopeFrame,
|
|
formatProviderCgroupUnitName,
|
|
systemctlKillProviderArguments,
|
|
systemdRunProviderArguments,
|
|
} = await import("../../scripts/lib/provider-cgroup.ts");
|
|
const unit = formatProviderCgroupUnitName(
|
|
"vulnerability",
|
|
42,
|
|
"0123456789abcdef01234567",
|
|
);
|
|
const command = "node provider.mjs --token command-secret";
|
|
const credential = "credential-secret";
|
|
const launch = systemdRunProviderArguments(
|
|
unit,
|
|
1_800_000,
|
|
1_200,
|
|
"/trusted/node",
|
|
"/workspace/scripts/lib/provider-scope-wrapper.ts",
|
|
"/exact/report.json",
|
|
12,
|
|
34,
|
|
);
|
|
|
|
expect(launch).toEqual(expect.arrayContaining([
|
|
"--scope",
|
|
"--property=MemoryMax=1073741824",
|
|
"--property=MemorySwapMax=0",
|
|
"--property=TasksMax=64",
|
|
"--property=CPUQuota=100%",
|
|
"--property=KillMode=control-group",
|
|
"/trusted/node",
|
|
"/workspace/scripts/lib/provider-scope-wrapper.ts",
|
|
]));
|
|
expect(launch.join("\0")).not.toContain(command);
|
|
expect(launch.join("\0")).not.toContain(credential);
|
|
expect(
|
|
encodeProviderBwrapInput(
|
|
["--unshare-net", "--bind", "/exact/report.json", "/exact/report.json"],
|
|
{ PROVIDER_COMMAND: command, PROVIDER_CREDENTIAL: credential },
|
|
),
|
|
).toEqual(expect.any(Buffer));
|
|
expect(systemctlKillProviderArguments(unit)).toEqual([
|
|
"--user",
|
|
"kill",
|
|
"--kill-whom=all",
|
|
"--signal=SIGKILL",
|
|
unit,
|
|
]);
|
|
// `bwrap --args FD` stops parsing at the first non-option and never hands
|
|
// the remainder back, so a command placed in the args file is dropped and
|
|
// bubblewrap exits with its usage text. Refusing `--` in the option stream
|
|
// is what keeps that silent no-sandbox launch from returning.
|
|
expect(() =>
|
|
encodeProviderBwrapInput(
|
|
["--unshare-net", "--", "/usr/bin/prlimit"],
|
|
{ PROVIDER_COMMAND: command },
|
|
),
|
|
).toThrow(/terminate the option stream/u);
|
|
const frame = encodeProviderScopeFrame({
|
|
bwrapInput: Buffer.from("private-bwrap-vector\0"),
|
|
bwrapCommand: ["/usr/bin/prlimit", "--nofile=64:64", "--", "/bin/sh", "-eu", "-c", 'exec /bin/sh -eu -c "$PROVIDER_COMMAND"'],
|
|
reportPath: "/exact/report.json",
|
|
reportDev: 12,
|
|
reportIno: 34,
|
|
});
|
|
expect(frame.readUInt32BE(0)).toBe(frame.byteLength - 4);
|
|
expect(frame.subarray(4).toString("utf8")).toContain(
|
|
Buffer.from("private-bwrap-vector\0").toString("base64"),
|
|
);
|
|
expect(launch.join("\0")).not.toContain("private-bwrap-vector");
|
|
// The command vector rides on real argv, so it must never be able to carry
|
|
// the secret that the args file exists to hide.
|
|
expect(frame.subarray(4).toString("utf8")).not.toContain(credential);
|
|
expect(() =>
|
|
encodeProviderScopeFrame({
|
|
bwrapInput: Buffer.from("x\0"),
|
|
bwrapCommand: [],
|
|
reportPath: "/exact/report.json",
|
|
reportDev: 12,
|
|
reportIno: 34,
|
|
}),
|
|
).toThrow(/bwrap command is invalid/u);
|
|
expect(() =>
|
|
encodeProviderScopeFrame({
|
|
bwrapInput: Buffer.from("x\0"),
|
|
bwrapCommand: ["prlimit"],
|
|
reportPath: "/exact/report.json",
|
|
reportDev: 12,
|
|
reportIno: 34,
|
|
}),
|
|
).toThrow(/bwrap command is invalid/u);
|
|
});
|
|
|
|
it("removes only the pinned raw inode during parent-loss cleanup", async () => {
|
|
const { cleanupOwnedProviderReport } = await import(
|
|
"../../scripts/lib/provider-raw-cleanup.ts"
|
|
);
|
|
const root = await mkdtemp(path.join(tmpdir(), "provider-raw-cleanup-"));
|
|
roots.push(root);
|
|
const reportPath = path.join(root, "raw.json");
|
|
const originalPath = path.join(root, "original.json");
|
|
await writeFile(reportPath, "owned\n");
|
|
const identity = await lstat(reportPath);
|
|
await rename(reportPath, originalPath);
|
|
await writeFile(reportPath, "unrelated\n");
|
|
|
|
await expect(cleanupOwnedProviderReport({
|
|
reportPath,
|
|
reportDev: identity.dev,
|
|
reportIno: identity.ino,
|
|
})).resolves.toBe(false);
|
|
await expect(readFile(reportPath, "utf8")).resolves.toBe("unrelated\n");
|
|
|
|
await rm(reportPath);
|
|
await rename(originalPath, reportPath);
|
|
await expect(cleanupOwnedProviderReport({
|
|
reportPath,
|
|
reportDev: identity.dev,
|
|
reportIno: identity.ino,
|
|
})).resolves.toBe(true);
|
|
await expect(lstat(reportPath)).rejects.toMatchObject({ code: "ENOENT" });
|
|
await expect(readdir(root)).resolves.toEqual([]);
|
|
});
|
|
|
|
it("uses early liveness EOF to clean the pinned raw file without waiting for a command frame", async () => {
|
|
const root = await mkdtemp(path.join(tmpdir(), "provider-scope-eof-"));
|
|
roots.push(root);
|
|
const reportPath = path.join(root, "raw.json");
|
|
await writeFile(reportPath, "partial\n");
|
|
const identity = await lstat(reportPath);
|
|
const child = spawnLoadedScopeWrapper(await mkdtemp(path.join(tmpdir(), "provider-scope-loader-")), [
|
|
"1",
|
|
reportPath,
|
|
String(identity.dev),
|
|
String(identity.ino),
|
|
]);
|
|
const completion = waitForChildResult(child);
|
|
await waitForScopeWrapperLoaded(child);
|
|
// Time to exit on its own, which it must not do before EOF.
|
|
await new Promise<void>((resolve) => setTimeout(resolve, 75));
|
|
expect(child.exitCode).toBeNull();
|
|
await expect(readFile(reportPath, "utf8")).resolves.toBe("partial\n");
|
|
child.stdin!.end();
|
|
const result = await within(completion, PROCESS_WATCHDOG_MS, "provider scope EOF close");
|
|
expect(result).toEqual({ code: 125, signal: null });
|
|
await expect(lstat(reportPath)).rejects.toMatchObject({ code: "ENOENT" });
|
|
await expect(readdir(root)).resolves.toEqual([]);
|
|
}, PROCESS_WATCHDOG_MS * 3);
|
|
|
|
it("tracks npm run-script dependencies instead of bypassing the graph", () => {
|
|
expect(validatePackageScriptGraph({ root: "npm run-script missing" }, "root"))
|
|
.toContain("package script missing: root -> missing");
|
|
});
|
|
|
|
// D-13: the counts and gate shape come from the reviewed baseline file, so a
|
|
// removal fixture that re-baselines its reduced contract passes here too.
|
|
it("matches the owned contract baseline and rejects orphan retention", async () => {
|
|
const canonical = await loadCiGateContract(process.cwd());
|
|
const baseline = JSON.parse(await readFile(CI_CONTRACT_BASELINE_PATH, "utf8")) as Record<string, unknown>;
|
|
expect(baseline).toMatchObject(measureCiContractBaseline(canonical));
|
|
expect(baseline["owner"]).toEqual(expect.any(String));
|
|
expect(baseline["reason"]).toEqual(expect.any(String));
|
|
expect(canonical.retention.classes).toHaveLength(5);
|
|
|
|
const orphan = JSON.parse(JSON.stringify(canonical)) as Record<string, any>;
|
|
orphan.retention.classes.push({ id: "unused", policy: "never referenced" });
|
|
expect(() => parseCiGateContract(orphan)).toThrow(/five canonical retention|orphan retention/u);
|
|
});
|
|
|
|
it("rejects the retired validate-candidate-archive grammar", async () => {
|
|
const canonical = JSON.parse(
|
|
JSON.stringify(await loadCiGateContract(process.cwd())),
|
|
) as Record<string, any>;
|
|
canonical.jobs.find((job: Record<string, any>) => job.id === "vulnerability_provider")
|
|
.steps.splice(4, 0, {
|
|
kind: "validate-candidate-archive",
|
|
archivePath: ".release/candidate/release-candidate.tar.gz",
|
|
});
|
|
expect(() => parseCiGateContract(canonical)).toThrow(
|
|
/invalid discriminator|forbidden|canonical job step sequence/iu,
|
|
);
|
|
});
|
|
|
|
it("publishes a generated workflow as exactly 0644 under a restrictive umask", async () => {
|
|
const root = await mkdtemp(path.join(tmpdir(), "ci-workflow-mode-"));
|
|
roots.push(root);
|
|
await mkdir(path.join(root, ".gitea/workflows"), { recursive: true });
|
|
const previous = process.umask(0o777);
|
|
try {
|
|
const contract = await loadCiGateContract(process.cwd());
|
|
await generateCiWorkflow({ root, contract, check: false });
|
|
} finally {
|
|
process.umask(previous);
|
|
}
|
|
const target = path.join(root, ".gitea/workflows/quality-gates.yml");
|
|
const metadata = await lstat(target);
|
|
expect(metadata.mode & 0o777).toBe(0o644);
|
|
expect((await readFile(target, "utf8")).startsWith("# GENERATED FILE")).toBe(true);
|
|
});
|
|
});
|
|
|
|
/**
|
|
* 1103/10-01. Starts the unchanged scope wrapper through a loader that writes
|
|
* one byte to an extra pipe once the import has finished: by then the wrapper
|
|
* has opened its liveness channel and attached the EOF handler. Closing stdin
|
|
* at a fixed 75 ms put the child's whole start-up inside the EOF limit, and a
|
|
* loaded host failed the test with "EOF close timed out". The wrapper reads its
|
|
* launch identity from argv after the main module, so the loader takes the
|
|
* wrapper's place there.
|
|
*/
|
|
function spawnLoadedScopeWrapper(
|
|
loaderDirectory: string,
|
|
launchArguments: readonly string[],
|
|
): ReturnType<typeof spawn> {
|
|
roots.push(loaderDirectory);
|
|
const loader = path.join(loaderDirectory, "provider-scope-loaded.mjs");
|
|
writeFileSync(loader, [
|
|
'import { closeSync, writeSync } from "node:fs";',
|
|
`await import(${JSON.stringify(
|
|
pathToFileURL(path.resolve("scripts/lib/provider-scope-wrapper.ts")).href,
|
|
)});`,
|
|
`writeSync(${SCOPE_WRAPPER_LOADED_FD}, "1");`,
|
|
`closeSync(${SCOPE_WRAPPER_LOADED_FD});`,
|
|
"",
|
|
].join("\n"));
|
|
return spawn(process.execPath, [loader, ...launchArguments], {
|
|
stdio: ["pipe", "pipe", "pipe", "pipe"],
|
|
});
|
|
}
|
|
|
|
async function waitForScopeWrapperLoaded(child: ReturnType<typeof spawn>): Promise<void> {
|
|
const loaded = (child.stdio as readonly unknown[])[SCOPE_WRAPPER_LOADED_FD] as NodeJS.ReadableStream;
|
|
await within(new Promise<void>((resolve, reject) => {
|
|
loaded.once("data", () => resolve());
|
|
loaded.once("end", () => reject(new Error("provider scope wrapper exited before it loaded")));
|
|
}), PROCESS_WATCHDOG_MS, "provider scope wrapper start-up");
|
|
}
|
|
|
|
async function waitForChildResult(
|
|
child: ReturnType<typeof spawn>,
|
|
): Promise<Readonly<{ code: number | null; signal: NodeJS.Signals | null }>> {
|
|
return await new Promise((resolve, reject) => {
|
|
child.once("error", reject);
|
|
child.once("close", (code, signal) => resolve({ code, signal }));
|
|
});
|
|
}
|
|
|
|
async function within<T>(operation: Promise<T>, timeoutMs: number, label: string): Promise<T> {
|
|
let timer: NodeJS.Timeout | undefined;
|
|
try {
|
|
return await Promise.race([
|
|
operation,
|
|
new Promise<never>((_resolve, reject) => {
|
|
timer = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);
|
|
}),
|
|
]);
|
|
} finally {
|
|
if (timer) clearTimeout(timer);
|
|
}
|
|
}
|