문제: 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 통과.
99 lines
3.9 KiB
TypeScript
99 lines
3.9 KiB
TypeScript
import { appendFileSync, readFileSync } from "node:fs";
|
|
import path from "node:path";
|
|
|
|
/**
|
|
* Opt-in record of every process the provider launch chain starts.
|
|
*
|
|
* The cgroup system test has to prove which processes ran, with which argv,
|
|
* and in which cgroup. Sampling `/proc` from outside could not: `systemd-run
|
|
* --scope` execs into the scope wrapper on the same PID, a fresh child shows
|
|
* its parent's argv until it execs, and a 5 ms sampler kept recording the
|
|
* wrong phase. Each stage therefore writes its own line here, at the moment it
|
|
* knows the answer: a process records itself from the kernel's view
|
|
* (`/proc/self`), and a spawner records a child with the exact argv vector it
|
|
* handed to `spawn`.
|
|
*
|
|
* Off unless `PROVIDER_PROCESS_TRACE_PATH` is set, and nothing in CI sets it.
|
|
* The trace is a second place argv lands. Persisting it in production would
|
|
* turn a future argv regression — a credential or the provider command put on
|
|
* a command line — into a durable file instead of a transient `/proc` value,
|
|
* and as audit evidence it would need the same publish-path, size and schema
|
|
* controls as the sealed reports. Neither is part of this fix.
|
|
*
|
|
* A line carries only role, PID, parent PID, argv and (for self records) the
|
|
* cgroup. Never the environment: that is where credentials and the provider
|
|
* command travel. Every spawn in the launch chain must call
|
|
* {@link traceSpawnedProviderProcess}; a spawn that does not is invisible to
|
|
* the test.
|
|
*/
|
|
export const PROVIDER_PROCESS_TRACE_VARIABLE = "PROVIDER_PROCESS_TRACE_PATH";
|
|
|
|
export type ProviderProcessRole =
|
|
| "supervisor"
|
|
| "guardian"
|
|
| "systemd-run"
|
|
| "scope-wrapper"
|
|
| "bwrap";
|
|
|
|
export type ProviderProcessTraceEntry = Readonly<{
|
|
role: ProviderProcessRole;
|
|
pid: number;
|
|
ppid: number;
|
|
argv: readonly string[];
|
|
cgroup?: string;
|
|
}>;
|
|
|
|
/** Records the calling process as `role`, as the kernel sees it. */
|
|
export function traceOwnProviderProcess(role: ProviderProcessRole): void {
|
|
if (!process.env[PROVIDER_PROCESS_TRACE_VARIABLE]) return;
|
|
writeTrace(() => ({
|
|
role,
|
|
pid: process.pid,
|
|
ppid: process.ppid,
|
|
argv: readFileSync("/proc/self/cmdline", "utf8").split("\0").slice(0, -1),
|
|
cgroup: readFileSync("/proc/self/cgroup", "utf8").trim(),
|
|
}));
|
|
}
|
|
|
|
/**
|
|
* Records a child this process just spawned with exactly `argv`.
|
|
*
|
|
* The argv is the vector passed to `spawn`, not a later `/proc` read: by the
|
|
* time anyone looks, `systemd-run` may already have exec'd into the wrapper.
|
|
* No cgroup either, for the same reason — the wrapper records its own.
|
|
*/
|
|
export function traceSpawnedProviderProcess(
|
|
role: ProviderProcessRole,
|
|
pid: number | undefined,
|
|
argv: readonly string[],
|
|
): void {
|
|
if (!process.env[PROVIDER_PROCESS_TRACE_VARIABLE] || !pid) return;
|
|
writeTrace(() => ({ role, pid, ppid: process.pid, argv: [...argv] }));
|
|
}
|
|
|
|
/**
|
|
* The trace setting for a child whose environment is otherwise rebuilt from
|
|
* an allow-list (`systemd-run` hands its own environment to the wrapper).
|
|
*/
|
|
export function providerProcessTraceEnvironment(): Readonly<Record<string, string>> {
|
|
const target = process.env[PROVIDER_PROCESS_TRACE_VARIABLE];
|
|
return target ? { [PROVIDER_PROCESS_TRACE_VARIABLE]: target } : {};
|
|
}
|
|
|
|
/**
|
|
* A diagnostic must not decide whether a provider run passes, so a failed
|
|
* write is reported and dropped. Whoever reads the trace sees the line missing.
|
|
*/
|
|
function writeTrace(entry: () => ProviderProcessTraceEntry): void {
|
|
const target = process.env[PROVIDER_PROCESS_TRACE_VARIABLE]!;
|
|
try {
|
|
// Relative would resolve against a different cwd in each process.
|
|
if (!path.isAbsolute(target)) throw new TypeError(`${PROVIDER_PROCESS_TRACE_VARIABLE} must be absolute`);
|
|
appendFileSync(target, `${JSON.stringify(entry())}\n`, { mode: 0o600 });
|
|
} catch (error) {
|
|
process.stderr.write(`provider process trace was not written: ${
|
|
error instanceof Error ? error.message : String(error)
|
|
}\n`);
|
|
}
|
|
}
|