문제: tests/system의 cgroup 테스트는 provider 실행 중 /proc을 5 ms마다 표본으로 읽어 어떤 프로세스가 어떤 argv로 돌았는지 판정한다. systemd-run --scope는 scope로 옮긴 뒤 같은 PID에서 sh 게이트와 scope wrapper로 exec하고, 갓 fork된 자식은 exec 전까지 부모 argv를 보인다. 표본은 PID마다 처음 본 argv만 남겨 이 짧은 단계를 자주 놓친다. 운영 코드에는 테스트가 결정적으로 읽을 실행 증거가 없다. 고른 방법: scripts/lib/provider-process-trace.ts를 추가한다. PROVIDER_PROCESS_TRACE_PATH가 있을 때만 각 단계가 JSON 한 줄을 덧붙인다. - 자기 기록: supervisor와 scope wrapper가 /proc/self/cmdline과 /proc/self/cgroup을 남긴다(커널이 본 값). - 자식 기록: supervisor가 systemd-run, guardian client가 guardian, wrapper가 bwrap을 spawn에 넘긴 argv 배열 그대로 남긴다. spawn과 기록이 같은 배열을 쓴다. - 필드는 role, pid, ppid, argv, (자기 기록만) cgroup. 환경변수는 담지 않는다. credential과 provider 명령이 지나가는 곳이기 때문이다. - systemd-run 환경은 허용 목록으로 다시 만들어지므로 providerProcessTraceEnvironment()로 기록 경로만 넘긴다. bwrap은 --clearenv라 sandbox 안의 provider는 경로를 받지 않는다. guardian은 빈 환경을 그대로 두고 client가 spawn 지점에서 기록한다. 테스트용 opt-in으로 두고 운영 감사 증거로 쓰지 않는다. 운영에서 켜면 argv가 두 번째로 남는 곳이 생긴다. 나중에 credential이나 provider 명령이 argv에 들어가는 회귀가 생기면, 지금은 /proc에 잠깐 보이는 값이 파일로 남아 CI 산출물이 될 수 있다. 감사 증거로 쓰려면 봉인 보고서와 같은 경로 안전·크기 상한·스키마·보존 정책이 필요하고 이번 범위가 아니다. CI 워크플로는 이 변수를 설정하지 않는다. 버린 대안: - /proc 표본 보강(부모와 같은 argv 무시, PID별 argv 이력 보존): 리뷰 README 13.1에서 시도하고 되돌렸다. 이력 보존은 prlimit -> sh로 바뀌는 PID 이력에 provider 명령이 섞여 "인프라 argv에 명령 없음" 단언의 뜻이 바뀐다. - spawn 직후 /proc/<pid>/cmdline 읽기: libuv는 exec 뒤에 반환하지만 systemd-run은 곧 wrapper로 다시 exec하므로 경쟁이 남는다. - guardian 자기 기록: guardian이 빈 환경으로 뜨는 것이 보장이라 기록 경로를 넘기지 않는다. 위험·한계: - 기록은 각 단계가 스스로 남긴다. 새 spawn 지점이 기록을 빠뜨리면 테스트에서 보이지 않는다. 모듈 주석에 적었다. - 기록 실패는 run 결과를 바꾸지 않고 stderr에 한 줄 남긴다. wrapper의 stderr는 provider 출력으로 버려지므로 빠진 줄은 기록을 읽는 쪽에서 드러난다. - 변수가 없으면 spawn 인자와 환경은 이전과 같다. 검증: - node scripts/run-vitest.ts run tests/unit/provider-process-trace.test.ts 2건 통과. 자식 기록에 env 필드를 넣는 변이를 넣으면 실패한다. - 관련 테스트 6파일 44건 통과(provider-process-trace, task3-selective- integration, provider-output-limiter, security-provider-evidence, provider-guardian-transaction, provider-process-group). - pnpm 없는 하네스(운영 encoder로 systemd-run -> sh -> wrapper -> bwrap -> prlimit -> provider 실행)에서 실행 기록 20회 중 20회 완전. - tsc(tsconfig.node.json, tsconfig.test.json), eslint 통과.
218 lines
7.8 KiB
TypeScript
218 lines
7.8 KiB
TypeScript
import { spawn } from "node:child_process";
|
|
import { closeSync, writeSync } from "node:fs";
|
|
import { Socket } from "node:net";
|
|
|
|
import { traceOwnProviderProcess, traceSpawnedProviderProcess } from "./provider-process-trace.ts";
|
|
import { cleanupOwnedProviderReport } from "./provider-raw-cleanup.ts";
|
|
|
|
const MAX_FRAME_BYTES = 16_777_216;
|
|
const reportIdentity = parseReportIdentity(process.argv.slice(2));
|
|
traceOwnProviderProcess("scope-wrapper");
|
|
let pending = Buffer.alloc(0);
|
|
let expectedBytes: number | undefined;
|
|
let provider: ReturnType<typeof spawn> | undefined;
|
|
let providerClosed = false;
|
|
let livenessLost = false;
|
|
/**
|
|
* The supervisor keeps this pipe open for the scope's whole life — that is how
|
|
* parent loss is observed — and only ever writes one frame into it.
|
|
*
|
|
* It must be read through libuv's event loop, not through `fs`. An `fs` read
|
|
* runs a blocking `read(2)` on a threadpool thread, and on a pipe with a live
|
|
* writer that call never returns. Closing the descriptor does not interrupt it,
|
|
* so once bubblewrap exits the wrapper deadlocks in `process.exit` waiting to
|
|
* join that thread: the scope outlives the provider, the supervisor's wall
|
|
* clock expires, and a completed provider is reported as a timeout kill.
|
|
*/
|
|
const liveness = openLivenessChannel();
|
|
|
|
liveness.on("data", (chunk: Buffer | string) => {
|
|
if (provider) {
|
|
terminateForProtocolFailure("provider scope received trailing protocol bytes");
|
|
return;
|
|
}
|
|
pending = Buffer.concat([pending, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
|
|
if (expectedBytes === undefined && pending.byteLength >= 4) {
|
|
expectedBytes = pending.readUInt32BE(0);
|
|
if (expectedBytes <= 0 || expectedBytes > MAX_FRAME_BYTES) {
|
|
terminateForProtocolFailure("provider scope frame length is invalid");
|
|
return;
|
|
}
|
|
}
|
|
if (expectedBytes !== undefined && pending.byteLength === expectedBytes + 4) {
|
|
launchProvider(pending.subarray(4));
|
|
pending = Buffer.alloc(0);
|
|
} else if (expectedBytes !== undefined && pending.byteLength > expectedBytes + 4) {
|
|
terminateForProtocolFailure("provider scope frame has trailing bytes");
|
|
}
|
|
});
|
|
|
|
liveness.once("end", () => terminateForParentLoss());
|
|
liveness.once("error", () => terminateForParentLoss());
|
|
|
|
function launchProvider(payload: Buffer): void {
|
|
const frame = parseFrame(payload);
|
|
if (
|
|
frame.reportPath !== reportIdentity.reportPath ||
|
|
frame.reportDev !== reportIdentity.reportDev ||
|
|
frame.reportIno !== reportIdentity.reportIno
|
|
) {
|
|
throw new TypeError("provider scope frame identity does not match its launch identity");
|
|
}
|
|
const bwrapInput = Buffer.from(frame.bwrapInputBase64, "base64");
|
|
// The options are read from fd 0; the command must stay on real argv because
|
|
// bubblewrap discards whatever follows the option stream inside an args file.
|
|
const bwrapArguments = ["--args", "0", "--", ...frame.bwrapCommand];
|
|
provider = spawn("/usr/bin/bwrap", bwrapArguments, {
|
|
detached: true,
|
|
stdio: ["pipe", "inherit", "inherit"],
|
|
});
|
|
traceSpawnedProviderProcess("bwrap", provider.pid, ["/usr/bin/bwrap", ...bwrapArguments]);
|
|
// bubblewrap can exit before the options are fully written — a usage error
|
|
// closes fd 0 immediately. Without this the EPIPE would surface as an
|
|
// unhandled stream error and the scope would be torn down as a crash rather
|
|
// than reported as the provider exit it is.
|
|
provider.stdin?.once("error", () => {});
|
|
provider.stdin?.end(bwrapInput);
|
|
provider.once("error", (error) => finishProvider(frame, null, null, error));
|
|
provider.once("close", (code, signal) => finishProvider(frame, code, signal));
|
|
}
|
|
|
|
async function finishProvider(
|
|
frame: ReturnType<typeof parseFrame>,
|
|
code: number | null,
|
|
signal: NodeJS.Signals | null,
|
|
error?: Error,
|
|
): Promise<void> {
|
|
if (providerClosed) return;
|
|
providerClosed = true;
|
|
if (livenessLost) await cleanupOwnedProviderReport(frame);
|
|
closeLivenessInput();
|
|
if (error) {
|
|
writeSync(2, `${error.message}\n`);
|
|
process.exit(1);
|
|
}
|
|
if (signal) process.exit(128 + signalNumber(signal));
|
|
process.exit(code ?? 1);
|
|
}
|
|
|
|
function terminateForParentLoss(): void {
|
|
if (livenessLost) return;
|
|
livenessLost = true;
|
|
if (!provider || providerClosed) {
|
|
void cleanupAfterParentLossAndExit();
|
|
return;
|
|
}
|
|
try {
|
|
process.kill(-provider.pid!, "SIGKILL");
|
|
} catch (error) {
|
|
if (!hasErrorCode(error, "ESRCH")) throw error;
|
|
}
|
|
}
|
|
|
|
async function cleanupAfterParentLossAndExit(): Promise<void> {
|
|
try {
|
|
await cleanupOwnedProviderReport(reportIdentity);
|
|
} catch (error) {
|
|
writeSync(2, `${error instanceof Error ? error.message : String(error)}\n`);
|
|
}
|
|
closeLivenessInput();
|
|
process.exit(125);
|
|
}
|
|
|
|
function terminateForProtocolFailure(message: string): void {
|
|
writeSync(2, `${message}\n`);
|
|
terminateForParentLoss();
|
|
}
|
|
|
|
function openLivenessChannel(): Socket {
|
|
try {
|
|
return new Socket({ fd: 0, readable: true, writable: false });
|
|
} catch (error) {
|
|
// Without an observable parent this process cannot be trusted to notice
|
|
// supervisor loss, and an unsupervised sandbox is worse than no run.
|
|
writeSync(2, `provider scope liveness channel is unavailable: ${
|
|
error instanceof Error ? error.message : String(error)
|
|
}\n`);
|
|
process.exit(125);
|
|
}
|
|
}
|
|
|
|
function closeLivenessInput(): void {
|
|
liveness.removeAllListeners();
|
|
liveness.destroy();
|
|
try {
|
|
closeSync(0);
|
|
} catch (error) {
|
|
// `Socket.destroy()` owns the descriptor and closes it itself, so a second
|
|
// close is expected rather than exceptional.
|
|
if (!hasErrorCode(error, "EBADF")) throw error;
|
|
}
|
|
}
|
|
|
|
function parseFrame(payload: Buffer): Readonly<{
|
|
bwrapInputBase64: string;
|
|
bwrapCommand: readonly string[];
|
|
reportPath: string;
|
|
reportDev: number;
|
|
reportIno: number;
|
|
}> {
|
|
const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(payload)) as Record<string, unknown>;
|
|
if (
|
|
typeof value.bwrapInputBase64 !== "string" ||
|
|
typeof value.reportPath !== "string" || !value.reportPath.startsWith("/") ||
|
|
!Number.isSafeInteger(value.reportDev) || Number(value.reportDev) <= 0 ||
|
|
!Number.isSafeInteger(value.reportIno) || Number(value.reportIno) <= 0
|
|
) {
|
|
throw new TypeError("provider scope frame payload is invalid");
|
|
}
|
|
assertBwrapCommand(value.bwrapCommand);
|
|
return {
|
|
bwrapInputBase64: value.bwrapInputBase64,
|
|
bwrapCommand: Object.freeze([...value.bwrapCommand]),
|
|
reportPath: value.reportPath,
|
|
reportDev: Number(value.reportDev),
|
|
reportIno: Number(value.reportIno),
|
|
};
|
|
}
|
|
|
|
function assertBwrapCommand(value: unknown): asserts value is readonly string[] {
|
|
if (
|
|
!Array.isArray(value) || value.length === 0 ||
|
|
typeof value[0] !== "string" || !value[0].startsWith("/") ||
|
|
value.some((argument) => typeof argument !== "string" || argument.includes("\0"))
|
|
) {
|
|
throw new TypeError("provider scope frame command is invalid");
|
|
}
|
|
}
|
|
|
|
function parseReportIdentity(arguments_: readonly string[]): Readonly<{
|
|
cpuSeconds: number;
|
|
reportPath: string;
|
|
reportDev: number;
|
|
reportIno: number;
|
|
}> {
|
|
const [cpuValue, reportPath, devValue, inoValue, ...trailing] = arguments_;
|
|
const cpuSeconds = Number(cpuValue);
|
|
const reportDev = Number(devValue);
|
|
const reportIno = Number(inoValue);
|
|
if (
|
|
trailing.length > 0 ||
|
|
!Number.isSafeInteger(cpuSeconds) || cpuSeconds <= 0 ||
|
|
typeof reportPath !== "string" || !reportPath.startsWith("/") || reportPath.includes("\0") ||
|
|
!Number.isSafeInteger(reportDev) || reportDev <= 0 ||
|
|
!Number.isSafeInteger(reportIno) || reportIno <= 0
|
|
) {
|
|
throw new TypeError("provider scope launch identity is invalid");
|
|
}
|
|
return { cpuSeconds, reportPath, reportDev, reportIno };
|
|
}
|
|
|
|
function signalNumber(signal: NodeJS.Signals): number {
|
|
return signal === "SIGKILL" ? 9 : signal === "SIGXCPU" ? 24 : 1;
|
|
}
|
|
|
|
function hasErrorCode(error: unknown, code: string): boolean {
|
|
return Boolean(error && typeof error === "object" && "code" in error && error.code === code);
|
|
}
|