diff --git a/.gitea/workflows/quality-gates.yml b/.gitea/workflows/quality-gates.yml index 582f543e..cadcc500 100644 --- a/.gitea/workflows/quality-gates.yml +++ b/.gitea/workflows/quality-gates.yml @@ -160,7 +160,7 @@ jobs: run: corepack pnpm ci:gate -- FE-GATE-007 - name: "FE-GATE-013 / security" if: ${{ !cancelled() }} - run: scripts/run-in-system-container.sh corepack pnpm ci:gate -- FE-GATE-013 + run: corepack pnpm ci:gate -- FE-GATE-013 --enter-host-environment - name: "FE-GATE-020 / removability" if: ${{ !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-020 diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a135067..6a50ebc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,7 +27,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지 | 표시 | 변경 | 영향 경로 | 커밋 | | --- | --- | --- | --- | -| [계약] | 게이트 필드 `hostEnvironment`(`"system-container"`)를 더한다. 생성기와 `scripts/verify.sh`가 그 게이트를 `scripts/run-in-system-container.sh`로 감싸고, 실행 검사는 계약이 정한 접두어로 돈 줄만 센다. FE-GATE-013에 준다 | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `scripts/generate-ci-workflow.ts`, `scripts/verify.sh`, `scripts/run-in-system-container.sh`, `config/ci/system-container.Dockerfile` | `1d3eb901` | +| [계약] | 게이트 필드 `hostEnvironment`(`"system-container"`)를 더한다. `scripts/verify.sh`는 그 게이트를 `scripts/run-in-system-container.sh`로 감싼다. 생성기는 그 step을 `ci:gate -- --enter-host-environment`로 그리고, `ci:gate`가 job에서 PR 선택을 본 뒤 돌 때만 그 래퍼로 들어간다. 실행 검사는 계약이 정한 명령으로 돈 줄만 센다. FE-GATE-013에 준다 | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `scripts/generate-ci-workflow.ts`, `scripts/run-ci-gate.ts`, `scripts/verify.sh`, `scripts/run-in-system-container.sh`, `config/ci/system-container.Dockerfile`, `.gitea/workflows/quality-gates.yml` | `1d3eb901`, `8fe5c4c5` | | [계약] | 게이트 FE-GATE-030 `optional-removability`(main 단계)를 더하고 FE-GATE-020에서 선택 runtime 제거 드릴 셋을 옮긴다. 정규 게이트 ID는 001..030, MAIN_READY는 029·030, 계약 보고서 `gateCount`는 29다(권하는 안으로 정함 2026-11-12, 총괄) | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `scripts/lib/promotion-readiness.ts`, `scripts/lib/ci-contract-report.ts`, `scripts/lib/feature-scaffold-drill.ts` | `8de1403b` | | [계약] | `browser-install` 단계에 `image`(Playwright 레지스트리 noble 태그 + digest)를 더한다. 생성기는 그 job의 container와 job env `CI_RUNNER_IMAGE`로 그리고, 단계는 글꼴만 설치한다. gate-sequence job에만 둔다 | 같은 파일, `tests/unit/ci-browser-image.test.ts` | `92abfd20` | | [계약] | job 단계 `dependency-cache`와 CI action `cache`(actions/cache v4.3.0, 짝 백엔드와 같은 pin)를 더한다. merge job 셋에만 두고(계약이 다른 job을 거절), 생성기가 main 복원·저장과 그 밖 복원만 두 단계, job env `COREPACK_HOME`·`PNPM_CONFIG_STORE_DIR`·`PNPM_CONFIG_CACHE_DIR`로 그린다. `scripts/run-in-system-container.sh`가 그 store와 메타데이터 캐시를 컨테이너에 넘긴다(권하는 안으로 정함 2026-11-13, 총괄) | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `scripts/generate-ci-workflow.ts`, `scripts/run-in-system-container.sh`, `.gitea/workflows/quality-gates.yml` | `7ed0af3d` | diff --git a/docs/operations/ci-quality-gates.md b/docs/operations/ci-quality-gates.md index 5fabe8af..092ff137 100644 --- a/docs/operations/ci-quality-gates.md +++ b/docs/operations/ci-quality-gates.md @@ -245,8 +245,12 @@ namespace 점검을 돌아, 이 조건이 없는 runner에서 이름과 host 설 **이 템플릿이 FE-GATE-013을 돌리는 곳.** 호스트 설정을 바꾸지 않고, 게이트를 일회용 privileged systemd 컨테이너 안에서 돌린다. 계약의 FE-GATE-013 -`hostEnvironment: "system-container"`를 보고 생성 workflow와 -`scripts/verify.sh`가 `scripts/run-in-system-container.sh`로 게이트를 감싼다. +`hostEnvironment: "system-container"`를 보고 `scripts/verify.sh`는 +`scripts/run-in-system-container.sh`로 게이트를 감싼다. 생성 workflow는 그 step을 +`corepack pnpm ci:gate -- FE-GATE-013 --enter-host-environment`로 그린다. +`ci:gate`가 job 안에서 PR 선택을 먼저 보고, 게이트가 돌 때만 같은 래퍼로 +들어간다. 그래서 이 게이트에 안 닿는 PR은 컨테이너를 띄우지 않는다. 컨테이너에는 +PR의 base 브랜치를 넘기지 않아서 안에서 다시 고르거나 `git fetch`를 하지 않는다. 래퍼는 `config/ci/system-container.Dockerfile`(Ubuntu 24.04, systemd PID 1, root linger, bubblewrap)로 이미지를 만들고, 작업 트리·git 이력·호출한 쪽의 node와 corepack을 복사해 root로 돌린 뒤 `artifacts/`를 되가져온다. CI에서는 diff --git a/docs/work/reference/gates.md b/docs/work/reference/gates.md index 12816965..9bb98c81 100644 --- a/docs/work/reference/gates.md +++ b/docs/work/reference/gates.md @@ -71,7 +71,7 @@ release 단계 게이트는 merge 단계에 없다. 그래서 lab 게이트 회 **흔들림 기록과 시간 단언.** 흔들린 시험은 처음 본 날 `docs/ledger/flaky-tests.jsonl`에 한 줄 남긴다([testing.md](testing.md) 5절 6번). 새 시험이 벽시계 상한이나 시작 순서를 단언하면 리뷰가 막는다([리뷰 기준](review-criteria.md) 2절, design-docs `ci/manual.md` 8.4절). -**FE-GATE-013은 시스템 컨테이너 안에서 돈다.** provider sandbox는 systemd user manager와 bubblewrap을 쓴다. CI의 job 컨테이너에는 둘 다 없고, desktop ssh 셸은 비특권 user namespace가 막혀 있다. 그래서 계약(`config/ci/gates.json`의 `hostEnvironment`)이 이 게이트를 `scripts/run-in-system-container.sh` 안에서 돌게 하고, workflow와 `scripts/verify.sh`가 같은 길을 쓴다. 래퍼는 일회용 privileged systemd 컨테이너(`config/ci/system-container.Dockerfile`)를 띄워 작업 트리를 복사하고 root로 돌린 뒤 `artifacts/`를 되가져온다. Docker가 필요하다(CI는 runner의 dind, desktop은 호스트 Docker). 컨테이너 안에서 통과하면 다른 게이트처럼 통과로 센다(소유자 결정 2026-11-11: 조건이 되는 실행 환경을 찾아 초록으로). 컨테이너 안은 root라 「비특권 runner에서 bwrap user namespace」 조건 자체는 증명하지 않는다. 실패하면 `scripts/verify.sh parts FE-GATE-013`으로 명령마다 보고, `SYSTEM_CONTAINER_KEEP=1`이면 컨테이너를 남긴다. 호스트 시스템 설정은 바꾸지 않는다. +**FE-GATE-013은 시스템 컨테이너 안에서 돈다.** provider sandbox는 systemd user manager와 bubblewrap을 쓴다. CI의 job 컨테이너에는 둘 다 없고, desktop ssh 셸은 비특권 user namespace가 막혀 있다. 그래서 계약(`config/ci/gates.json`의 `hostEnvironment`)이 이 게이트를 `scripts/run-in-system-container.sh` 안에서 돌게 한다. `scripts/verify.sh`는 이 래퍼로 게이트를 바로 감싼다. workflow는 job 안에서 `corepack pnpm ci:gate -- FE-GATE-013 --enter-host-environment`를 돌린다. `ci:gate`가 PR 선택을 먼저 보고, 게이트가 돌 때만 같은 래퍼로 들어간다. 그래서 이 게이트에 안 닿는 PR은 컨테이너를 띄우지 않는다. 래퍼는 일회용 privileged systemd 컨테이너(`config/ci/system-container.Dockerfile`)를 띄워 작업 트리를 복사하고 root로 돌린 뒤 `artifacts/`를 되가져온다. Docker가 필요하다(CI는 runner의 dind, desktop은 호스트 Docker). 컨테이너 안에서 통과하면 다른 게이트처럼 통과로 센다(소유자 결정 2026-11-11: 조건이 되는 실행 환경을 찾아 초록으로). 컨테이너 안은 root라 「비특권 runner에서 bwrap user namespace」 조건 자체는 증명하지 않는다. 실패하면 `scripts/verify.sh parts FE-GATE-013`으로 명령마다 보고, `SYSTEM_CONTAINER_KEEP=1`이면 컨테이너를 남긴다. 호스트 시스템 설정은 바꾸지 않는다. **컨테이너를 띄울 수 없는 호스트의 FE-GATE-013.** Docker가 없거나 privileged 컨테이너를 막는 호스트에서는 래퍼가 종료 코드 3으로 끝난다. 그런 호스트는 `VERIFY_HOST_ENVIRONMENT=off`를 주어 게이트를 호스트에서 돌리고 아래로 판정한다. desktop ssh 셸에서는 비특권 user namespace가 막혀 `bwrap --unshare-net`이 실패하고, `test:system`의 provider 테스트가 호스트 원인으로 떨어진다. 사전 점검(`scripts/check-system-test-prerequisites.ts`)은 이 제한을 이름으로 대며 실패한다. merge 판정에서는 이 실패를 호스트 원인으로 보고 뺀다(소유자 결정 2026-11-11에 따라 2026-11-12에 정함, [decisions.md](decisions.md) 2.2절). 뺄 수 있는 조건은 둘이고, 하나라도 어기면 merge 가능이 아니다. diff --git a/scripts/contracts/ci-gates.ts b/scripts/contracts/ci-gates.ts index ecb748fe..bcc1b5a5 100644 --- a/scripts/contracts/ci-gates.ts +++ b/scripts/contracts/ci-gates.ts @@ -362,12 +362,28 @@ const gateSchema = z * requirements. "system-container": scripts/run-in-system-container.sh * runs the gate in a disposable privileged systemd container * (config/ci/system-container.Dockerfile), in CI through the runner's - * Docker daemon and on desktop through scripts/verify.sh. + * Docker daemon and on desktop through scripts/verify.sh. The workflow + * enters it through `ci:gate` (HOST_ENVIRONMENT_ENTRY). */ hostEnvironment: z.enum(["system-container"]).optional(), }) .strict(); +/** + * The command that enters each gate host environment (`hostEnvironment`), + * and the `ci:gate` flag that asks for it. The workflow runs such a gate as + * `ci:gate -- --enter-host-environment` in the job: the runner + * decides the PR selection there, where the job has the PR's base branch, + * and runs the gate through this command only when it runs. The container + * gets no base branch (scripts/run-in-system-container.sh), so it does not + * fetch or select again (fe-ci-next (2)). scripts/verify.sh runs the gate + * through the same command itself; it has no PR base branch. + */ +export const HOST_ENVIRONMENT_ENTRY = Object.freeze({ + "system-container": "scripts/run-in-system-container.sh", +} as const); +export const ENTER_HOST_ENVIRONMENT_FLAG = "--enter-host-environment"; + const stageSchema = z .object({ id, diff --git a/scripts/generate-ci-workflow.ts b/scripts/generate-ci-workflow.ts index 85860be5..13bf254a 100644 --- a/scripts/generate-ci-workflow.ts +++ b/scripts/generate-ci-workflow.ts @@ -12,6 +12,7 @@ import path from "node:path"; import { DEPENDENCY_CACHE, + ENTER_HOST_ENVIRONMENT_FLAG, indexCiGateContract, loadCiGateContract, resolveCiStepActionUses, @@ -289,12 +290,18 @@ function renderHostRequirements( } /** - * A gate whose host requirements the job container cannot meet runs in the - * environment its contract names (`hostEnvironment`). FE-GATE-013's provider - * sandbox needs systemd and bubblewrap, which the runner's job image lacks. + * The run command of a gate step. A gate whose host requirements the job + * container cannot meet runs in the environment its contract names + * (`hostEnvironment`): FE-GATE-013's provider sandbox needs systemd and + * bubblewrap, which the runner's job image lacks. `ci:gate` enters it from + * the job, after it has decided the PR selection there, so a gate the PR + * skips starts no container (HOST_ENVIRONMENT_ENTRY). */ -function gateHostPrefix(gate: Readonly<{ hostEnvironment?: "system-container" | undefined }> | undefined): string { - return gate?.hostEnvironment === "system-container" ? "scripts/run-in-system-container.sh " : ""; +function gateRunCommand( + gateId: string, + gate: Readonly<{ hostEnvironment?: "system-container" | undefined }> | undefined, +): string { + return `corepack pnpm ci:gate -- ${gateId}${gate?.hostEnvironment ? ` ${ENTER_HOST_ENVIRONMENT_FLAG}` : ""}`; } /** @@ -401,7 +408,7 @@ function renderStep( return job.gateIds.flatMap((gateId) => [ ` - name: ${yamlScalar(`${gateId} / ${index.gates.get(gateId)?.name ?? ""}`)}`, " if: ${{ !cancelled() }}", - ` run: ${gateHostPrefix(index.gates.get(gateId))}corepack pnpm ci:gate -- ${gateId}`, + ` run: ${gateRunCommand(gateId, index.gates.get(gateId))}`, ]); } // 12-02: every gate the job owns runs, in order. Rendering only the first @@ -631,11 +638,12 @@ export function workflowGateExecutionFailures( ) { productFailures.push(`product gates do not hold the release stage: ${PRODUCT_GATES_HOLD} does not need ${PRODUCT_GATE_JOB}`); } - const hostPrefixes = new Map(contract.gates.map((gate) => [gate.id, gateHostPrefix(gate)])); + const runCommands = new Map(contract.gates.map((gate) => [gate.id, gateRunCommand(gate.id, gate)])); for (const job of jobs) { - for (const match of job.matchAll(/^ +run: (\S+ )?corepack pnpm ci:gate -- (FE-GATE-\d{3})$/gmu)) { - // A gate runs through the prefix its contract names, and only that one. - if ((match[1] ?? "") === hostPrefixes.get(match[2]!)) executed.add(match[2]!); + for (const match of job.matchAll(/^ +run: (.*\bci:gate -- (FE-GATE-\d{3})\b.*)$/gmu)) { + // A gate runs by the command its contract names, and only that one: + // a host environment gate with the flag, every other gate without. + if (match[1] === runCommands.get(match[2]!)) executed.add(match[2]!); } if (/^ +run: corepack pnpm ci:gate -- \$\{\{ matrix\.gate \}\}$/mu.test(job)) { for (const match of job.matchAll(/^ +- \{ gate: (FE-GATE-\d{3}),/gmu)) { diff --git a/scripts/run-ci-gate.ts b/scripts/run-ci-gate.ts index 998039f0..e9783ea9 100644 --- a/scripts/run-ci-gate.ts +++ b/scripts/run-ci-gate.ts @@ -1,5 +1,6 @@ import { spawnSync } from "node:child_process"; import { lstat } from "node:fs/promises"; +import { constants as osConstants } from "node:os"; import path from "node:path"; import { @@ -9,7 +10,11 @@ import { isValidSourceDateEpoch, } from "./lib/build-environment.ts"; import { classifyGateStepResult } from "./lib/ci-step-result.ts"; -import { withCiGatePreflight } from "./contracts/ci-gates.ts"; +import { + ENTER_HOST_ENVIRONMENT_FLAG, + HOST_ENVIRONMENT_ENTRY, + withCiGatePreflight, +} from "./contracts/ci-gates.ts"; import { validateCiArtifact } from "./lib/ci-artifact-validator.ts"; import { formatGateFailure } from "./lib/ci-gate-failure.ts"; import { writeCiGateLogAtomic } from "./lib/ci-gate-log.ts"; @@ -43,6 +48,29 @@ if (skipReason !== undefined) { process.stdout.write(`${line}\n`); return; } +// A gate with a host environment runs there (config/ci/gates.json +// hostEnvironment). The workflow asks for that with the flag, so the PR +// selection above is decided in the job, which has the PR's base branch, and +// a gate the PR skips starts no container. Inside, the gate runs as a plain +// `ci:gate`; the container has no base branch, so it does not select again. +if (process.argv.includes(ENTER_HOST_ENVIRONMENT_FLAG)) { + const entry = gate.hostEnvironment ? HOST_ENVIRONMENT_ENTRY[gate.hostEnvironment] : undefined; + if (!entry) { + throw new TypeError(`${gateId} has no host environment to enter (config/ci/gates.json hostEnvironment)`); + } + const entered = spawnSync(entry, ["corepack", "pnpm", "ci:gate", "--", gateId], { + stdio: "inherit", + env: process.env, + }); + if (entered.error) throw entered.error; + if (entered.signal) { + // An OOM kill or a cancelled run: name the signal and end as the step's + // shell did when it ran the wrapper itself (128 + the signal number). + process.stderr.write(`${gateId}: ${entry} ended on ${entered.signal}\n`); + process.exit(128 + osConstants.signals[entered.signal]); + } + process.exit(entered.status ?? 1); +} const output: string[] = []; let outputBytes = 0; let passed = true; diff --git a/scripts/tests/test_verify.py b/scripts/tests/test_verify.py index d22d4924..b0be140a 100644 --- a/scripts/tests/test_verify.py +++ b/scripts/tests/test_verify.py @@ -52,8 +52,9 @@ class StagePlanTest(unittest.TestCase): [f"corepack pnpm -s {scripts[c]}" for c in gate["commandIds"]]) def test_a_gate_with_a_host_environment_runs_in_it_as_in_the_workflow(self) -> None: - # FE-GATE-013 needs systemd and bubblewrap; the workflow and verify.sh both run it through - # scripts/run-in-system-container.sh (config/ci/gates.json hostEnvironment). + # FE-GATE-013 needs systemd and bubblewrap; verify.sh runs it through + # scripts/run-in-system-container.sh (config/ci/gates.json hostEnvironment), and the workflow's + # ci:gate enters the same wrapper from the job once it has decided the PR selection. contract = gates() hosted = [g for g in contract["gates"] if g.get("hostEnvironment") == "system-container"] self.assertEqual([g["id"] for g in hosted], ["FE-GATE-013"]) @@ -66,7 +67,8 @@ class StagePlanTest(unittest.TestCase): self.assertEqual([line.split(": ", 1)[1] for line in result.stdout.splitlines()], [f"{wrapper} corepack pnpm -s {scripts[c]}" for c in hosted[0]["commandIds"]]) workflow = (REPO / ".gitea/workflows/quality-gates.yml").read_text(encoding="utf-8") - self.assertIn(f"run: {wrapper} corepack pnpm ci:gate -- FE-GATE-013", workflow) + self.assertIn("run: corepack pnpm ci:gate -- FE-GATE-013 --enter-host-environment", workflow) + self.assertNotIn(f"run: {wrapper} corepack pnpm ci:gate -- FE-GATE-013", workflow) # A host that cannot start the container runs the gate here (gates.md 3절). result = sh([str(VERIFY), "gate", "FE-GATE-013", "--dry-run"], cwd=REPO, env={"VERIFY_HOST_ENVIRONMENT": "off"}) self.assertEqual(result.stdout.splitlines(), ["FE-GATE-013: corepack pnpm -s ci:gate FE-GATE-013"]) diff --git a/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap b/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap index b12b2db4..a44af252 100644 --- a/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap +++ b/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap @@ -163,7 +163,7 @@ jobs: run: corepack pnpm ci:gate -- FE-GATE-007 - name: "FE-GATE-013 / security" if: \${{ !cancelled() }} - run: scripts/run-in-system-container.sh corepack pnpm ci:gate -- FE-GATE-013 + run: corepack pnpm ci:gate -- FE-GATE-013 --enter-host-environment - name: "FE-GATE-020 / removability" if: \${{ !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-020 diff --git a/tests/unit/ci-gate-host-environment.test.ts b/tests/unit/ci-gate-host-environment.test.ts new file mode 100644 index 00000000..e343fd9a --- /dev/null +++ b/tests/unit/ci-gate-host-environment.test.ts @@ -0,0 +1,264 @@ +import { spawnSync } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts"; +import { renderCiWorkflow } from "../../scripts/generate-ci-workflow.ts"; +import { FIXTURE_PNPM_ENVIRONMENT } from "../../scripts/lib/fixture-node-modules.ts"; +import { + PR_BASE_REF_VARIABLE, + PR_GATE_SELECTION_PATH, + SKIPPED_GATE_LINE, +} from "../../scripts/lib/pr-gate-selection.ts"; +import { childProcessTimeout } from "../helpers/child-process-timeout.ts"; + +/** + * Longest desktop run of a test below: in FE-GATE-005's test:unit at load 14 + * (2026-11-20). Alone or in test:coverage they took 1.0 to 1.5 s. + */ +const GATE_STEP_MS = 3688; + +const repository = process.cwd(); +const GATE = "FE-GATE-013"; +const STARTED = "container-started"; +/** + * Stands in for scripts/run-in-system-container.sh: it adds a line for each + * container that would start, with its command, and exits with the code the + * test asks for (the real one exits with the command's code), or dies on the + * signal it asks for (the job's OOM kill, a cancelled run). + */ +const STAND_IN_WRAPPER = `#!/bin/sh +printf '%s\\n' "$*" >> ${STARTED} +[ -z "\${STAND_IN_SIGNAL:-}" ] || kill -s "$STAND_IN_SIGNAL" $$ +exit "\${STAND_IN_EXIT:-0}" +`; +const CONTAINER_WRAPPER = "scripts/run-in-system-container.sh"; +const STAND_IN_CONTAINER = "stand-in-container"; +const CALL_END = ""; +/** + * Stands in for docker under the real wrapper (SYSTEM_CONTAINER_DOCKER): it + * writes each call's arguments one per line, then CALL_END, starts a + * container that is at once running, takes what is piped in, and hands back + * an empty artifacts archive. + */ +const STAND_IN_DOCKER = `#!/bin/sh +for argument in "$@"; do printf '%s\\n' "$argument"; done >> "$DOCKER_CALLS" +echo '${CALL_END}' >> "$DOCKER_CALLS" +case "$1 $2" in + "run -d") echo ${STAND_IN_CONTAINER} ;; + "exec -i") cat > /dev/null ;; +esac +case "$*" in + *is-system-running*) echo running ;; + *"-cf - artifacts"*) tar -cf - -T /dev/null ;; +esac +exit 0 +`; + +function executable(file: string, content: string): void { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, content); + chmodSync(file, 0o755); +} + +/** + * A checkout with the real container wrapper and its Dockerfile, the docker + * stand-in, and a node whose install is one small file: the wrapper copies the + * caller's node into the container. + */ +function wrapperCheckout(root: string): string { + const checkout = path.join(root, "checkout"); + for (const file of [CONTAINER_WRAPPER, "config/ci/system-container.Dockerfile"]) { + mkdirSync(path.dirname(path.join(checkout, file)), { recursive: true }); + writeFileSync(path.join(checkout, file), readFileSync(path.join(repository, file))); + } + chmodSync(path.join(checkout, CONTAINER_WRAPPER), 0o755); + git(checkout, "init", "--quiet"); + git(checkout, "add", "."); + git(checkout, "commit", "--quiet", "-m", "wrapper"); + executable(path.join(root, "docker"), STAND_IN_DOCKER); + executable(path.join(root, "node/bin/node"), "#!/bin/sh\nexit 0\n"); + return checkout; +} + +/** The merge job's run line for FE-GATE-013, as the generated workflow has it. */ +async function gateRunLine(): Promise { + const workflow = renderCiWorkflow(await loadCiGateContract(repository)); + const lines = workflow.split("\n").filter((line) => line.includes(`ci:gate -- ${GATE}`)); + expect(lines).toHaveLength(1); + return lines[0]!.replace(/^ +run: /u, ""); +} + +function git(cwd: string, ...args: string[]): void { + const result = spawnSync( + "git", + ["-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "init.defaultBranch=main", ...args], + { cwd, encoding: "utf8" }, + ); + if (result.status !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr}`); +} + +/** + * A shallow PR checkout like a merge job's: this repository's gate contract + * and path table on main, the PR's one file on top, `ci:gate` running this + * repository's runner, and the stand-in container wrapper. + */ +function prCheckout(root: string, prFile: string): string { + const origin = path.join(root, "origin"); + for (const file of ["config/ci/gates.json", PR_GATE_SELECTION_PATH]) { + mkdirSync(path.dirname(path.join(origin, file)), { recursive: true }); + writeFileSync(path.join(origin, file), readFileSync(path.join(repository, file))); + } + const packageDocument = JSON.parse(readFileSync(path.join(repository, "package.json"), "utf8")) as { + scripts: Record; + }; + // The contract loader refuses a package without the gates' scripts, so the + // checkout keeps them all; only `ci:gate` points at this repository's runner. + packageDocument.scripts["ci:gate"] = `node ${path.join(repository, "scripts/run-ci-gate.ts")}`; + writeFileSync(path.join(origin, "package.json"), `${JSON.stringify(packageDocument)}\n`); + executable(path.join(origin, CONTAINER_WRAPPER), STAND_IN_WRAPPER); + git(origin, "init", "--quiet"); + git(origin, "add", "."); + git(origin, "commit", "--quiet", "-m", "base"); + git(origin, "switch", "--quiet", "-c", "pr"); + mkdirSync(path.dirname(path.join(origin, prFile)), { recursive: true }); + writeFileSync(path.join(origin, prFile), "x\n"); + git(origin, "add", "."); + git(origin, "commit", "--quiet", "-m", "pr"); + git(root, "clone", "--quiet", "--depth", "1", "--branch", "pr", `file://${origin}`, "checkout"); + return path.join(root, "checkout"); +} + +function run(command: string, cwd: string, environment: Readonly>) { + return spawnSync("sh", ["-c", command], { + cwd, + encoding: "utf8", + env: { ...process.env, ...FIXTURE_PNPM_ENVIRONMENT, CI: "false", ...environment }, + }); +} + +// fe-ci-next (2). The container wrapper got only the gate's own environment, +// not the PR's base branch, so the PR selection inside it always ran +// FE-GATE-013: a PR the path table keeps away from the gate still started the +// system container and ran it (3 to 5 runner minutes). Handing the base +// branch in would let a `git fetch` without a timeout hang the job from +// inside the container. The job decides first, where the base branch is. +describe("FE-GATE-013 in a merge job", { timeout: childProcessTimeout(GATE_STEP_MS) }, () => { + it("skips the gate in the job for a PR the path table keeps away, and starts no container", async () => { + const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-")); + try { + const checkout = prCheckout(root, "docs/only.md"); + const result = run(await gateRunLine(), checkout, { [PR_BASE_REF_VARIABLE]: "main" }); + + expect(existsSync(path.join(checkout, STARTED))).toBe(false); + expect(result.status).toBe(0); + const skipped = result.stdout.split("\n").filter((line) => SKIPPED_GATE_LINE.test(line)); + expect(skipped).toEqual([expect.stringMatching(new RegExp(`^건너뜀: ${GATE} — `, "u"))]); + expect(readFileSync(path.join(checkout, "artifacts/quality/gates/FE-GATE-013.txt"), "utf8")).toBe( + `${skipped[0]}\n`, + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("runs the gate in the container for a PR that reaches it, with the container's exit code", async () => { + const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-")); + try { + const checkout = prCheckout(root, "src/reaches-the-gate.ts"); + const result = run(await gateRunLine(), checkout, { + [PR_BASE_REF_VARIABLE]: "main", + STAND_IN_EXIT: "7", + }); + + expect(readFileSync(path.join(checkout, STARTED), "utf8")).toBe(`corepack pnpm ci:gate -- ${GATE}\n`); + expect(result.status).toBe(7); + expect(result.stdout).not.toMatch(/^건너뜀: /mu); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("enters the container once from ci:gate in the job and hands back its exit code", () => { + const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-")); + try { + // A main run: no PR base branch, so the gate runs. + const checkout = prCheckout(root, "docs/only.md"); + const result = run( + `corepack pnpm ci:gate -- ${GATE} --enter-host-environment`, + checkout, + { [PR_BASE_REF_VARIABLE]: "", STAND_IN_EXIT: "3" }, + ); + + expect(readFileSync(path.join(checkout, STARTED), "utf8")).toBe(`corepack pnpm ci:gate -- ${GATE}\n`); + expect(result.status).toBe(3); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("names the signal a container entry died on and ends as a shell would", () => { + const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-")); + try { + const checkout = prCheckout(root, "docs/only.md"); + const result = run( + `corepack pnpm ci:gate -- ${GATE} --enter-host-environment`, + checkout, + { [PR_BASE_REF_VARIABLE]: "", STAND_IN_SIGNAL: "TERM" }, + ); + + expect(readFileSync(path.join(checkout, STARTED), "utf8")).toBe(`corepack pnpm ci:gate -- ${GATE}\n`); + expect(result.stderr).toContain(`${GATE}: ${CONTAINER_WRAPPER} ended on SIGTERM`); + expect(result.status).toBe(128 + 15); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + // The container must not select again: with the base branch it would fetch + // from inside, where a `git fetch` without a timeout can hang the job. + // ci:gate hands the wrapper the job's whole environment, so what the + // container gets is what the wrapper's `docker exec` passes. + it("hands the container the job's gate environment and no PR base branch", () => { + const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-")); + try { + const checkout = wrapperCheckout(root); + const calls = path.join(root, "docker-calls"); + const result = spawnSync(CONTAINER_WRAPPER, ["corepack", "pnpm", "ci:gate", "--", GATE], { + cwd: checkout, + encoding: "utf8", + env: { + ...process.env, + PATH: `${path.join(root, "node/bin")}${path.delimiter}${process.env["PATH"] ?? ""}`, + SYSTEM_CONTAINER_DOCKER: path.join(root, "docker"), + DOCKER_CALLS: calls, + COREPACK_HOME: path.join(root, "no-corepack"), + PNPM_CONFIG_STORE_DIR: "", + PNPM_CONFIG_CACHE_DIR: "", + CI: "true", + [PR_BASE_REF_VARIABLE]: "main", + }, + }); + expect(result.status, result.stderr).toBe(0); + + const gateCalls = readFileSync(calls, "utf8") + .split(`${CALL_END}\n`) + .map((call) => call.split("\n").filter((argument) => argument !== "")) + .filter((call) => call.join(" ").endsWith(`${STAND_IN_CONTAINER} corepack pnpm ci:gate -- ${GATE}`)); + expect(gateCalls).toHaveLength(1); + const [call] = gateCalls as [string[]]; + expect(call.slice(0, 3)).toEqual(["exec", "-w", "/work"]); + const options = call.slice(3, call.indexOf(STAND_IN_CONTAINER)); + // Every option is `-e NAME=value`, so the names below are all it passes. + expect(options.filter((_, index) => index % 2 === 0).every((option) => option === "-e")).toBe(true); + const names = options.filter((_, index) => index % 2 === 1).map((pair) => pair.split("=", 1)[0]); + expect(names).toContain("CI"); + expect(names).not.toContain(PR_BASE_REF_VARIABLE); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/tests/unit/ci-workflow-generation.test.ts b/tests/unit/ci-workflow-generation.test.ts index 295fd96f..b1524792 100644 --- a/tests/unit/ci-workflow-generation.test.ts +++ b/tests/unit/ci-workflow-generation.test.ts @@ -1925,25 +1925,35 @@ describe("CI workflow generation", () => { }); // The job container has neither systemd nor bubblewrap, so FE-GATE-013 runs - // in the system container its contract names (hostEnvironment). + // in the system container its contract names (hostEnvironment). ci:gate + // enters it from the job, after the PR selection (fe-ci-next (2); the run + // itself is tests/unit/ci-gate-host-environment.test.ts). it("runs a gate with a host environment through it, and counts only that run", async () => { const contract = await loadCiGateContract(process.cwd()); expect(contract.gates.filter((gate) => gate.hostEnvironment).map(({ id }) => id)).toEqual(["FE-GATE-013"]); const workflow = renderCiWorkflow(contract); - const wrapped = " run: scripts/run-in-system-container.sh corepack pnpm ci:gate -- FE-GATE-013"; - expect(workflow.split("\n").filter((line) => line.includes("ci:gate -- FE-GATE-013"))).toEqual([wrapped]); + const entering = " run: corepack pnpm ci:gate -- FE-GATE-013 --enter-host-environment"; + expect(workflow.split("\n").filter((line) => line.includes("ci:gate -- FE-GATE-013"))).toEqual([entering]); expect(workflowGateExecutionFailures(contract, workflow)).toEqual([]); - expect(workflowGateExecutionFailures( - contract, - workflow.replace(wrapped, " run: corepack pnpm ci:gate -- FE-GATE-013"), - )).toEqual(["gate is not executed by any workflow run step: FE-GATE-013"]); - expect(workflowGateExecutionFailures( - contract, - workflow.replace( - " run: corepack pnpm ci:gate -- FE-GATE-005", - " run: scripts/run-in-system-container.sh corepack pnpm ci:gate -- FE-GATE-005", - ), - )).toEqual(["gate is not executed by any workflow run step: FE-GATE-005"]); + for (const other of [ + // On the job's host, where the provider sandbox cannot run. + " run: corepack pnpm ci:gate -- FE-GATE-013", + // Straight into the container, where the PR selection cannot be read. + " run: scripts/run-in-system-container.sh corepack pnpm ci:gate -- FE-GATE-013", + ]) { + expect(workflowGateExecutionFailures(contract, workflow.replace(entering, other))).toEqual([ + "gate is not executed by any workflow run step: FE-GATE-013", + ]); + } + for (const other of [ + " run: corepack pnpm ci:gate -- FE-GATE-005 --enter-host-environment", + " run: scripts/run-in-system-container.sh corepack pnpm ci:gate -- FE-GATE-005", + ]) { + expect(workflowGateExecutionFailures( + contract, + workflow.replace(" run: corepack pnpm ci:gate -- FE-GATE-005", other), + )).toEqual(["gate is not executed by any workflow run step: FE-GATE-005"]); + } }); it("rejects a runner requirement that would leave its workflow comment (1105/12-01)", async () => {