fix(ci): test:system 사전 점검이 bwrap namespace를 실제로 만들어 본다
문제: FE-GATE-013의 provider sandbox는 bwrap을 --unshare-pid --unshare-ipc --unshare-uts --unshare-net으로 띄운다. bwrap이 setuid가 아니므로 비특권 user namespace가 있어야 한다. 사전 점검 (scripts/check-system-test-prerequisites.ts)은 실행 파일·cgroup·systemd bus만 보고 bwrap을 한 번도 실행하지 않는다. 그래서 이 제한이 있는 호스트 (Ubuntu 24.04, kernel.apparmor_restrict_unprivileged_userns=1)에서 PASS를 낸 뒤 provider 테스트 114건 중 18건이 "bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted" 또는 그 provider를 기다린 시간 초과로 실패한다. 이 조건은 runner 요구 목록, gate 정의, workflow 어디에도 없고 운영 원장의 일회성 메모에만 있다. 고른 방법: - 사전 점검이 provider와 같은 namespace 옵션으로 bwrap에서 /bin/true를 한 번 띄운다. 실패하면 "this host does not allow unprivileged user and network namespaces", bwrap stderr(최대 4줄), user namespace sysctl 값, 고치는 방법 셋(AppArmor profile, sysctl, 다른 runner)을 적고 exit 1. 기존 검사(실행 파일 3개, cgroup v2, systemd bus)는 그대로 둔다. - 옵션 목록을 scripts/lib/provider-sandbox-namespaces.ts로 옮기고 run-and-validate-provider.ts와 사전 점검이 같은 상수를 쓴다. 둘이 갈라지면 점검이 다른 것을 시험하게 된다. - 점검을 findSystemTestPrerequisiteFailures(host)로 내보내고 access· readFile·spawn을 주입받는다. CLI 동작(출력·exit 코드)은 같다. - config/ci/gates.json의 FE-GATE-013에 hostRequirements 두 줄을 둔다. gate schema에 선택 필드를 더하고, generator가 그 gate를 도는 job의 runs-on 바로 위에 "# FE-GATE-013 runner requirement: ..." 주석으로 그린다. runner를 고르는 사람이 보는 자리다. 줄바꿈은 기존 nonEmpty 규칙이 막으므로 주석 밖으로 나갈 수 없다. 이 필드는 gate의 명령·증거가 아니라 runner 설명이라 기준선 gate shape 해시에는 넣지 않았다(기준선 재기록 불필요). - 요구 목록 세 곳(docs/operations/ci-quality-gates.md, docs/security/supply-chain.md, docs/testing/taxonomy.md)과 README merge 게이트 절에 조건을 적었다. ci-quality-gates.md에 AppArmor profile 예시를 두었다. 버린 대안: - namespace가 없으면 provider 테스트를 skip: 거짓 초록이다. - FE-GATE-013을 release 단계로 옮김: PR마다 sandbox 검사를 잃는다. - probe를 systemd-run --user --scope 안에서 돌림: 리뷰 11-R10에서 scope 안과 밖의 결과가 같았다. 직접 실행이 더 단순하다. - workflow에 요구 사항을 runs-on label로 표현: runner label 체계가 아직 없다. 주석이 지금 가능한 가장 작은 표시다. 위험·한계: - probe는 bwrap에 --ro-bind / /만 준다. --size 같은 provider의 다른 옵션 지원은 여기서 보지 않는다(기존과 같다). probe가 다른 이유로 실패해도 namespace 문구가 나오지만 bwrap stderr를 같이 적는다. - 호스트를 고칠지는 호스트 소유자가 정한다. 이 커밋은 조건을 적고 알리기만 한다. 이 desktop에서 FE-GATE-013은 여전히 실패하고, 이제 첫 단계에서 이유와 함께 실패한다. - gate schema에 선택 필드 hostRequirements가 생겼다. 기존 gates.json과 제품 overlay는 그대로 통과한다. 검증: desktop batch에서 확인 - node scripts/run-vitest.ts run tests/unit/system-test-prerequisites.test.ts tests/unit/ci-workflow-generation.test.ts - corepack pnpm check:ci, check:types, lint, verify:documentation - desktop에서 node scripts/check-system-test-prerequisites.ts가 exit 1과 namespace 문구를 내는지, FE-GATE-013이 그 단계에서 멈추는지 Refs: 1105/12-01, 1105/11-02
This commit is contained in:
@@ -1,55 +1,154 @@
|
||||
import { constants } from "node:fs";
|
||||
import { access, readFile } from "node:fs/promises";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const failures: string[] = [];
|
||||
import { PROVIDER_SANDBOX_NAMESPACE_ARGUMENTS } from "./lib/provider-sandbox-namespaces.ts";
|
||||
|
||||
async function requireExecutable(path: string, label: string): Promise<void> {
|
||||
try {
|
||||
await access(path, constants.X_OK);
|
||||
} catch {
|
||||
failures.push(`${label} is required at ${path}`);
|
||||
}
|
||||
}
|
||||
/** What the check reads from the host; a test passes a fake. */
|
||||
export type SystemTestHost = Readonly<{
|
||||
/** Resolves when `target` is executable, rejects otherwise. */
|
||||
access(target: string): Promise<void>;
|
||||
readFile(target: string): Promise<string>;
|
||||
spawn(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
timeoutMs: number,
|
||||
): Readonly<{ status: number | null; stderr: string; error?: Error | undefined }>;
|
||||
}>;
|
||||
|
||||
await Promise.all([
|
||||
requireExecutable("/usr/bin/bwrap", "bubblewrap"),
|
||||
requireExecutable("/usr/bin/systemctl", "systemctl"),
|
||||
requireExecutable("/usr/bin/tar", "tar"),
|
||||
export const nodeSystemTestHost: SystemTestHost = Object.freeze({
|
||||
access: async (target: string) => access(target, constants.X_OK),
|
||||
readFile: async (target: string) => readFile(target, "utf8"),
|
||||
spawn: (command: string, args: readonly string[], timeoutMs: number) => {
|
||||
const result = spawnSync(command, [...args], { encoding: "utf8", timeout: timeoutMs });
|
||||
return { status: result.status, stderr: result.stderr ?? "", error: result.error };
|
||||
},
|
||||
});
|
||||
|
||||
const BWRAP = "/usr/bin/bwrap";
|
||||
const SYSTEMCTL = "/usr/bin/systemctl";
|
||||
|
||||
/**
|
||||
* 1105/12-01. The provider sandbox's own namespace options on /bin/true. The
|
||||
* check used to see only that /usr/bin/bwrap was executable, so a host that
|
||||
* refuses unprivileged user namespaces passed it and then failed 18 provider
|
||||
* tests with `bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted`.
|
||||
*/
|
||||
export const NAMESPACE_PROBE_ARGUMENTS: readonly string[] = Object.freeze([
|
||||
...PROVIDER_SANDBOX_NAMESPACE_ARGUMENTS,
|
||||
"--ro-bind", "/", "/",
|
||||
"--", "/bin/true",
|
||||
]);
|
||||
|
||||
try {
|
||||
const controllers = await readFile("/sys/fs/cgroup/cgroup.controllers", "utf8");
|
||||
if (controllers.trim().length === 0) {
|
||||
failures.push("cgroup v2 controllers are unavailable");
|
||||
/** Host settings that decide whether an unprivileged process may create user namespaces. */
|
||||
const USER_NAMESPACE_SETTINGS = Object.freeze([
|
||||
["kernel.apparmor_restrict_unprivileged_userns", "/proc/sys/kernel/apparmor_restrict_unprivileged_userns"],
|
||||
["kernel.unprivileged_userns_clone", "/proc/sys/kernel/unprivileged_userns_clone"],
|
||||
["user.max_user_namespaces", "/proc/sys/user/max_user_namespaces"],
|
||||
] as const);
|
||||
|
||||
const PROBE_TIMEOUT_MS = 5_000;
|
||||
const MAX_REPORTED_STDERR_LINES = 4;
|
||||
|
||||
export async function findSystemTestPrerequisiteFailures(
|
||||
host: SystemTestHost = nodeSystemTestHost,
|
||||
): Promise<string[]> {
|
||||
const failures: string[] = [];
|
||||
const executable = new Map<string, boolean>();
|
||||
for (const [target, label] of [
|
||||
[BWRAP, "bubblewrap"],
|
||||
[SYSTEMCTL, "systemctl"],
|
||||
["/usr/bin/tar", "tar"],
|
||||
] as const) {
|
||||
try {
|
||||
await host.access(target);
|
||||
executable.set(target, true);
|
||||
} catch {
|
||||
executable.set(target, false);
|
||||
failures.push(`${label} is required at ${target}`);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
failures.push("cgroup v2 is required at /sys/fs/cgroup/cgroup.controllers");
|
||||
}
|
||||
|
||||
if (!failures.some((failure) => failure.includes("systemctl"))) {
|
||||
const probe = spawnSync("/usr/bin/systemctl", ["show-environment"], {
|
||||
encoding: "utf8",
|
||||
timeout: 3_000,
|
||||
});
|
||||
if (probe.error || probe.status !== 0) {
|
||||
failures.push("a reachable systemd manager bus is required");
|
||||
try {
|
||||
const controllers = await host.readFile("/sys/fs/cgroup/cgroup.controllers");
|
||||
if (controllers.trim().length === 0) {
|
||||
failures.push("cgroup v2 controllers are unavailable");
|
||||
}
|
||||
} catch {
|
||||
failures.push("cgroup v2 is required at /sys/fs/cgroup/cgroup.controllers");
|
||||
}
|
||||
|
||||
if (executable.get(SYSTEMCTL)) {
|
||||
const probe = host.spawn(SYSTEMCTL, ["show-environment"], 3_000);
|
||||
if (probe.error || probe.status !== 0) {
|
||||
failures.push("a reachable systemd manager bus is required");
|
||||
}
|
||||
}
|
||||
|
||||
if (executable.get(BWRAP)) {
|
||||
const probe = host.spawn(BWRAP, NAMESPACE_PROBE_ARGUMENTS, PROBE_TIMEOUT_MS);
|
||||
if (probe.error || probe.status !== 0) {
|
||||
failures.push(await namespaceFailure(host, probe));
|
||||
}
|
||||
}
|
||||
return failures;
|
||||
}
|
||||
|
||||
if (failures.length > 0) {
|
||||
process.stderr.write(
|
||||
[
|
||||
"System/CI-runner test prerequisites are unavailable:",
|
||||
...failures.map((failure) => ` - ${failure}`),
|
||||
"",
|
||||
"Run test:unit/test:contract/test:component/test:integration for the",
|
||||
"developer loop. test:system is intentionally reserved for a compatible",
|
||||
"Linux CI-runner host.",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
process.exit(1);
|
||||
async function namespaceFailure(
|
||||
host: SystemTestHost,
|
||||
probe: ReturnType<SystemTestHost["spawn"]>,
|
||||
): Promise<string> {
|
||||
const settings: string[] = [];
|
||||
for (const [name, file] of USER_NAMESPACE_SETTINGS) {
|
||||
try {
|
||||
settings.push(`${name} = ${(await host.readFile(file)).trim()}`);
|
||||
} catch {
|
||||
// Absent on this kernel; the others still say what the host allows.
|
||||
}
|
||||
}
|
||||
const stderr = probe.stderr
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.slice(0, MAX_REPORTED_STDERR_LINES);
|
||||
const outcome = probe.error
|
||||
? `did not finish: ${probe.error.message}`
|
||||
: `exited ${String(probe.status)}`;
|
||||
return [
|
||||
"this host does not allow unprivileged user and network namespaces, which the provider " +
|
||||
`sandbox needs (bwrap ${PROVIDER_SANDBOX_NAMESPACE_ARGUMENTS.join(" ")}).`,
|
||||
` probe: ${BWRAP} ${NAMESPACE_PROBE_ARGUMENTS.join(" ")} ${outcome}`,
|
||||
...(stderr.length > 0 ? stderr.map((line) => ` bwrap stderr: ${line}`) : [" bwrap stderr: (empty)"]),
|
||||
...(settings.length > 0 ? [` host settings: ${settings.join(", ")}`] : []),
|
||||
" To fix, do one of these:",
|
||||
" - give /usr/bin/bwrap an AppArmor profile that allows `userns` (Ubuntu 23.10 and later),",
|
||||
" - on a host you own, set sysctl kernel.apparmor_restrict_unprivileged_userns=0",
|
||||
" (or kernel.unprivileged_userns_clone=1 where that setting exists),",
|
||||
" - run FE-GATE-013 on another runner that allows them.",
|
||||
" Runner requirements: docs/operations/ci-quality-gates.md.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
process.stdout.write("System test prerequisites: PASS\n");
|
||||
export function formatSystemTestPrerequisiteReport(failures: readonly string[]): string {
|
||||
return [
|
||||
"System/CI-runner test prerequisites are unavailable:",
|
||||
...failures.map((failure) => ` - ${failure}`),
|
||||
"",
|
||||
"Run test:unit/test:contract/test:component/test:integration for the",
|
||||
"developer loop. test:system is intentionally reserved for a compatible",
|
||||
"Linux CI-runner host.",
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
const isCli = process.argv[1] !== undefined && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
|
||||
if (isCli) {
|
||||
const failures = await findSystemTestPrerequisiteFailures();
|
||||
if (failures.length > 0) {
|
||||
process.stderr.write(formatSystemTestPrerequisiteReport(failures));
|
||||
process.exit(1);
|
||||
}
|
||||
process.stdout.write("System test prerequisites: PASS\n");
|
||||
}
|
||||
|
||||
@@ -290,6 +290,14 @@ const gateSchema = z
|
||||
evidenceArtifactIds: z.array(id).min(1).max(128),
|
||||
retentionClassId: id,
|
||||
requiresEnvironment: z.array(z.string().max(128).regex(/^[A-Z][A-Z0-9_]*$/u)).max(32).optional(),
|
||||
/**
|
||||
* 1105/12-01. What the runner host must provide for the gate to pass, one
|
||||
* line each. The workflow shows them as comments beside the job's
|
||||
* `runs-on`; a line cannot hold a line break, so it cannot leave the
|
||||
* comment. They describe the runner, not the gate's commands or evidence,
|
||||
* so the reviewed gate shape (canonicalGateShapeSha256) leaves them out.
|
||||
*/
|
||||
hostRequirements: z.array(nonEmpty.max(512)).min(1).max(8).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
|
||||
@@ -167,7 +167,11 @@ function renderJob(
|
||||
if (job.needs.length > 1) lines.push(` needs: [${job.needs.map(yamlKey).join(", ")}]`);
|
||||
const condition = renderCondition(job.condition);
|
||||
if (condition) lines.push(` if: ${condition}`);
|
||||
lines.push(" runs-on: ubuntu-latest", ` timeout-minutes: ${job.timeoutMinutes}`);
|
||||
lines.push(
|
||||
...renderHostRequirements(job, index),
|
||||
" runs-on: ubuntu-latest",
|
||||
` timeout-minutes: ${job.timeoutMinutes}`,
|
||||
);
|
||||
if (job.kind === "immutable") {
|
||||
const archive = job.steps.find((step) => step.kind === "archive-candidate");
|
||||
if (!archive || archive.kind !== "archive-candidate") throw new TypeError("immutable job lacks archive step");
|
||||
@@ -214,6 +218,24 @@ function renderJob(
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1105/12-01. A gate's host requirements (`hostRequirements` in
|
||||
* config/ci/gates.json) sit as comments beside the runner label of the job
|
||||
* that runs the gate, where whoever picks the runner reads them. FE-GATE-013
|
||||
* needs unprivileged user namespaces, and that was written nowhere a runner
|
||||
* is chosen. The contract keeps line breaks out of each requirement.
|
||||
*/
|
||||
function renderHostRequirements(
|
||||
job: CiWorkflowJob,
|
||||
index: ReturnType<typeof indexCiGateContract>,
|
||||
): string[] {
|
||||
return job.gateIds.flatMap((gateId) =>
|
||||
(index.gates.get(gateId)?.hostRequirements ?? []).map(
|
||||
(requirement) => ` # ${gateId} runner requirement: ${requirement}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function renderStep(
|
||||
job: CiWorkflowJob,
|
||||
step: CiWorkflowStep,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 1105/12-01. The namespaces the provider sandbox asks bubblewrap for
|
||||
* (scripts/run-and-validate-provider.ts). bubblewrap is not setuid, so each of
|
||||
* them is an unprivileged user namespace plus the namespace named, and
|
||||
* `--unshare-net` also brings up loopback inside it.
|
||||
*
|
||||
* scripts/check-system-test-prerequisites.ts probes the host with this same
|
||||
* list. A host that refuses them (Ubuntu 24.04 with
|
||||
* kernel.apparmor_restrict_unprivileged_userns=1 and no AppArmor profile for
|
||||
* bwrap) then fails the prerequisite check by name, instead of passing it and
|
||||
* failing the provider tests with a raw netlink error.
|
||||
*/
|
||||
export const PROVIDER_SANDBOX_NAMESPACE_ARGUMENTS: readonly string[] = Object.freeze([
|
||||
"--unshare-pid",
|
||||
"--unshare-ipc",
|
||||
"--unshare-uts",
|
||||
"--unshare-net",
|
||||
]);
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
type ProviderGuardianLease,
|
||||
} from "./lib/provider-guardian-client.ts";
|
||||
import { createProviderOutputLimiter } from "./lib/provider-output-limiter.ts";
|
||||
import { PROVIDER_SANDBOX_NAMESPACE_ARGUMENTS } from "./lib/provider-sandbox-namespaces.ts";
|
||||
import {
|
||||
providerProcessTraceEnvironment,
|
||||
traceOwnProviderProcess,
|
||||
@@ -253,7 +254,7 @@ async function runProviderInSandbox(
|
||||
const cpuSeconds = providerCpuSeconds();
|
||||
const bwrapArguments = [
|
||||
"--die-with-parent", "--new-session", "--as-pid-1",
|
||||
"--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-net",
|
||||
...PROVIDER_SANDBOX_NAMESPACE_ARGUMENTS,
|
||||
"--dev", "/dev", "--remount-ro", "/dev",
|
||||
"--proc", "/proc", "--remount-ro", "/proc",
|
||||
"--size", String(PROVIDER_TMP_BYTES), "--tmpfs", "/tmp",
|
||||
|
||||
Reference in New Issue
Block a user