// PEP-314, spec peppa-ci «Go и временная база для проверок без нового образа»: the template's // .gitea/peppa-tools.sh runs for real — Go comes from a file:// "go.dev/dl" with a mock archive, // PostgreSQL from mock initdb/pg_ctl/createdb (mock-pg-*), no docker anywhere. import assert from "node:assert/strict"; import { execFileSync, spawnSync } from "node:child_process"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import { createServer } from "node:net"; import type { AddressInfo } from "node:net"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { describe, test } from "node:test"; const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const TOOLS = join(ROOT, "template/.gitea/peppa-tools.sh"); const TMP = mkdtempSync(join(tmpdir(), "peppa-stack-tools-")); const ARCH = ({ x64: "amd64", arm64: "arm64" } as Record)[process.arch] ?? process.arch; // The user has a passwd entry (mock getent finds it) — the sandbox running these tests may have none; // the case without one has its own describe below. const HAS_USER = mkdtempSync(join(TMP, "mock-getent-ok-")); writeFileSync(join(HAS_USER, "getent"), "#!/bin/sh\necho \"peppa:x:$2:0::/tmp:/bin/sh\"\n"); chmodSync(join(HAS_USER, "getent"), 0o755); const SYS_PATH = `${HAS_USER}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`; const BARE_PATH = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"; // Checks run as root: the mock cluster runs as the current user (the real one — as postgres). const ME = process.getuid?.() === 0 ? "root" : "postgres"; function exe(path: string, body: string) { writeFileSync(path, `#!/usr/bin/env bash\n${body}\n`); chmodSync(path, 0o755); } /** A mock go.dev/dl: go.linux-.tar.gz with go/bin/go answering `go version`. */ function mockGoDl(version: string): string { const dl = mkdtempSync(join(TMP, "mock-go-dl-")); const src = join(dl, "src"); mkdirSync(join(src, "go/bin"), { recursive: true }); exe(join(src, "go/bin/go"), `echo "go version go${version} linux/${ARCH}"`); execFileSync("tar", ["-czf", join(dl, `go${version}.linux-${ARCH}.tar.gz`), "-C", src, "go"]); return dl; } /** Mock PostgreSQL binaries: initdb makes data/, pg_ctl start/status/stop, createdb; all log to calls.log. */ function mockPgBin(): string { const bin = mkdtempSync(join(TMP, "mock-pg-")); // MOCK_PG_NO_USER=1 — the uid has no passwd entry: like the real initdb, refuse unless nss_wrapper gives one. const noUser = `if [ -n "$MOCK_PG_NO_USER" ] && ! { [ -n "$LD_PRELOAD" ] && grep -q ":$(id -u):" "\${NSS_WRAPPER_PASSWD:-/nonexistent}" 2>/dev/null; }; then echo "$(basename "$0"): could not look up effective user ID $(id -u): user does not exist" >&2; exit 1; fi`; exe(join(bin, "initdb"), `${noUser}\necho "initdb $*" >> "${bin}/calls.log"; while [ $# -gt 0 ]; do [ "$1" = -D ] && mkdir -p "$2" && echo 18 > "$2/PG_VERSION"; shift; done`); exe( join(bin, "pg_ctl"), `${noUser}\necho "pg_ctl $*" >> "${bin}/calls.log"; d=""; cmd=""; for a in "$@"; do [ "$prev" = -D ] && d="$a"; prev="$a"; cmd="$a"; done case "$cmd" in start) touch "$d/running" ;; status) [ -f "$d/running" ] ;; stop) rm -f "$d/running" ;; esac`, ); exe(join(bin, "createdb"), `echo "createdb $*" >> "${bin}/calls.log"`); return bin; } /** `source peppa-tools.sh ` in a fresh bash; prints PATH, DATABASE_URL and `command -v go`. */ function source(args: string[], env: Record, cwd = TMP) { const script = `source "${TOOLS}" ${args.join(" ")}; code=$?; echo "CODE=$code"; echo "URL=\${DATABASE_URL:-}"; echo "GO=$(command -v go)"; exit 0`; const r = spawnSync("bash", ["-c", script], { cwd, encoding: "utf8", env: { HOME: TMP, TMPDIR: TMP, PATH: SYS_PATH, PEPPA_PG_USER: ME, ...env } }); const line = (k: string) => (r.stdout.match(new RegExp(`^${k}=(.*)$`, "m")) ?? [])[1] ?? ""; return { code: Number(line("CODE")), url: line("URL"), go: line("GO"), err: r.stderr }; } describe("Go для проверок", () => { test("Scenario: Задание проверок без Go (список выпусков недоступен — go1.27.0)", () => { const dl = mockGoDl("1.27.0"); const work = mkdtempSync(join(TMP, "work-")); writeFileSync(join(work, "go.mod"), "module example.com/shop\n\ngo 1.27\n"); const ghPath = join(work, "github_path"); const cache = join(work, "cache"); const r = source(["go"], { PEPPA_GO_DL_BASE: `file://${dl}`, PEPPA_TOOLS_CACHE: cache, GITHUB_PATH: ghPath }, work); assert.equal(r.code, 0, r.err); assert.match(r.err, new RegExp(`скачиваю go1\\.27\\.0\\.linux-${ARCH}\\.tar\\.gz`)); assert.equal(r.go, join(cache, "go/1.27.0/go/bin/go")); assert.equal(readFileSync(ghPath, "utf8").trim(), join(cache, "go/1.27.0/go/bin")); // the second call takes the cache, nothing is downloaded const again = source(["go"], { PEPPA_GO_DL_BASE: "file:///nonexistent", PEPPA_TOOLS_CACHE: cache }, work); assert.equal(again.code, 0, again.err); assert.doesNotMatch(again.err, /скачиваю/); }); test("Scenario: Go уже есть (песочница агента)", () => { const bin = mkdtempSync(join(TMP, "image-bin-")); exe(join(bin, "go"), 'echo "go version go1.27.3 linux/amd64"'); const r = source(["go"], { PATH: `${bin}:${SYS_PATH}`, PEPPA_GO_DL_BASE: "file:///nonexistent" }); assert.equal(r.code, 0, r.err); assert.equal(r.go, join(bin, "go")); assert.doesNotMatch(r.err, /скачиваю/); }); test("«go 1.27» без третьего числа — последний выпуск ветки из списка go.dev", () => { const dl = mockGoDl("1.27.4"); const json = join(dl, "mock-releases.json"); writeFileSync(json, JSON.stringify([{ version: "go1.28rc1", stable: false }, { version: "go1.27.4", stable: true }, { version: "go1.26.9", stable: true }, { version: "go1.27.3", stable: true }], null, 1)); const work = mkdtempSync(join(TMP, "work-")); writeFileSync(join(work, "go.mod"), "module m\n\ngo 1.27\n"); const r = source(["go"], { PEPPA_GO_DL_BASE: `file://${dl}`, PEPPA_GO_DL_JSON: `file://${json}`, PEPPA_TOOLS_CACHE: join(work, "c") }, work); assert.equal(r.code, 0, r.err); assert.match(r.err, /скачиваю go1\.27\.4\./); assert.match(r.go, /go\/1\.27\.4\/go\/bin\/go$/); }); test("go.mod с полной версией и строкой toolchain — качается версия строки go", () => { const dl = mockGoDl("1.27.2"); const work = mkdtempSync(join(TMP, "work-")); writeFileSync(join(work, "go.mod"), "module m\n\ngo 1.27.2\n\ntoolchain go1.27.4\n"); const r = source(["go"], { PEPPA_GO_DL_BASE: `file://${dl}`, PEPPA_TOOLS_CACHE: join(work, "c") }, work); assert.equal(r.code, 0, r.err); assert.match(r.go, /go\/1\.27\.2\/go\/bin\/go$/); }); test("Go не скачался — ошибка, а не тишина", () => { const r = source(["go"], { PEPPA_GO_DL_BASE: `file://${TMP}/no-such-dl`, PEPPA_TOOLS_CACHE: join(TMP, "c-fail") }); assert.equal(r.code, 1); assert.match(r.err, /не удалось скачать Go 1\.27\.0/); assert.equal(r.go, ""); }); }); describe("Временная база для тестов", () => { test("Scenario: Временная база для тестов", () => { const bin = mockPgBin(); const dir = join(TMP, "pg-1"); const ghEnv = join(TMP, "github_env-1"); const env = { PEPPA_PG_BINDIR: bin, PEPPA_PG_DIR: dir, GITHUB_ENV: ghEnv }; const first = source(["postgres"], env); assert.equal(first.code, 0, first.err); const m = first.url.match(/^postgres:\/\/app@127\.0\.0\.1:(\d+)\/app\?sslmode=disable$/); assert.ok(m, first.url); assert.ok(Number(m[1]) >= 18432); assert.equal(readFileSync(ghEnv, "utf8").trim(), `DATABASE_URL=${first.url}`); const calls = readFileSync(join(bin, "calls.log"), "utf8"); assert.match(calls, /initdb -D .* -U app --auth=trust/); assert.match(calls, new RegExp(`listen_addresses=127\\.0\\.0\\.1 -p ${m[1]}`)); assert.match(calls, new RegExp(`createdb -h 127\\.0\\.0\\.1 -p ${m[1]} -U app app`)); const second = source(["postgres"], env); assert.equal(second.url, first.url); assert.equal(readFileSync(join(bin, "calls.log"), "utf8").match(/^initdb /gm)?.length, 1, "no second cluster"); // stop removes the cluster; the next call makes a new one spawnSync("bash", [TOOLS, "stop"], { env: { PATH: SYS_PATH, TMPDIR: TMP, PEPPA_PG_USER: ME, ...env } }); assert.ok(!existsSync(dir)); }); test("занятый порт пропускается", async () => { const busy = createServer(); await new Promise((r) => busy.listen(0, "127.0.0.1", r)); const port = (busy.address() as AddressInfo).port; try { const r = source(["postgres"], { PEPPA_PG_BINDIR: mockPgBin(), PEPPA_PG_DIR: join(TMP, "pg-2"), PEPPA_PG_PORT_FROM: String(port) }); assert.equal(r.code, 0, r.err); assert.notEqual(r.url, `postgres://app@127.0.0.1:${port}/app?sslmode=disable`); } finally { busy.close(); } }); test("Scenario: Нет PostgreSQL и нельзя поставить", { skip: process.getuid?.() === 0 }, () => { const r = source(["postgres"], { PEPPA_PG_DIR: join(TMP, "pg-3") }); assert.notEqual(r.code, 0); assert.match(r.err, /PostgreSQL не найден/); assert.equal(r.url, ""); }); test("запуск без source печатает export для eval", () => { const env = { PEPPA_PG_BINDIR: mockPgBin(), PEPPA_PG_DIR: join(TMP, "pg-4") }; const out = execFileSync("bash", [TOOLS, "postgres"], { encoding: "utf8", env: { PATH: SYS_PATH, TMPDIR: TMP, PEPPA_PG_USER: ME, ...env } }); assert.match(out, /^export DATABASE_URL=postgres:\/\/app@127\.0\.0\.1:\d+\/app\\\?sslmode=disable$/m); }); test("stop не печатает адрес остановленной базы", () => { const env = { PEPPA_PG_BINDIR: mockPgBin(), PEPPA_PG_DIR: join(TMP, "pg-5") }; const opts = { encoding: "utf8" as const, env: { PATH: SYS_PATH, TMPDIR: TMP, PEPPA_PG_USER: ME, ...env } }; const started = execFileSync("bash", [TOOLS, "postgres"], opts); const url = started.match(/^export DATABASE_URL=(.*)$/m)![1]!; const out = execFileSync("bash", [TOOLS, "stop"], { ...opts, env: { ...opts.env, DATABASE_URL: url } }); assert.doesNotMatch(out, /DATABASE_URL/); }); }); // Coordinator's run 27.11: the agent's container runs as --user 1004:1004 with no /etc/passwd entry, // and initdb refused it. Only for a non-root user (the agent); getent is mocked to find nothing. describe("Пользователь без записи в passwd (агент в контейнере)", { skip: process.getuid?.() === 0 }, () => { const noPasswd = () => { const bin = mkdtempSync(join(TMP, "mock-getent-")); exe(join(bin, "getent"), "exit 2"); return bin; }; test("Scenario: Временная база под uid без записи в passwd", () => { const pg = mockPgBin(); const lib = join(TMP, "mock-libnss_wrapper.so"); writeFileSync(lib, ""); const dir = join(TMP, "pg-nss"); const env = { PATH: `${noPasswd()}:${BARE_PATH}`, PEPPA_PG_BINDIR: pg, PEPPA_PG_DIR: dir, PEPPA_NSS_WRAPPER_LIB: lib, MOCK_PG_NO_USER: "1" }; const first = source(["postgres"], env); assert.equal(first.code, 0, first.err); assert.match(first.url, /^postgres:\/\/app@127\.0\.0\.1:\d+\/app\?sslmode=disable$/); assert.match(readFileSync(join(dir + "-nss", "passwd"), "utf8"), new RegExp(`^peppa:x:${process.getuid!()}:${process.getgid!()}:`, "m")); // a second shell reuses the database (pg_ctl status goes through the wrapper too) const second = source(["postgres"], env); assert.equal(second.url, first.url); assert.equal(readFileSync(join(pg, "calls.log"), "utf8").match(/^initdb /gm)?.length, 1); }); test("без nss_wrapper — понятное сообщение", () => { const env = { PATH: `${noPasswd()}:${BARE_PATH}`, PEPPA_PG_BINDIR: mockPgBin(), PEPPA_PG_DIR: join(TMP, "pg-nss-2"), PEPPA_NSS_WRAPPER_LIB: "", MOCK_PG_NO_USER: "1" }; const r = source(["postgres"], env); if (existsSync("/usr/lib/x86_64-linux-gnu/libnss_wrapper.so") || existsSync("/usr/lib/aarch64-linux-gnu/libnss_wrapper.so")) return; // the host has the real one assert.equal(r.code, 1); assert.match(r.err, /нет записи в \/etc\/passwd.*libnss-wrapper/); }); }); // Coordinator 27.11: deploy/Dockerfile.go was taken for Go source — `go vet ./...`, `go build ./...` // and `gofmt -l .` failed in a project made from the template («illegal character U+0023 '#'»). describe("Шаблон не ломает инструменты Go", () => { test("в template/ нет файлов *.go, которые не являются кодом Go", () => { const bad: string[] = []; const walk = (dir: string) => { for (const e of readdirSync(dir, { withFileTypes: true })) { const p = join(dir, e.name); if (e.isDirectory()) walk(p); else if (e.name.endsWith(".go") && !/^package \w+/m.test(readFileSync(p, "utf8"))) bad.push(p.slice(ROOT.length + 1)); } }; walk(join(ROOT, "template")); assert.deepEqual(bad, []); assert.ok(existsSync(join(ROOT, "template/deploy/Dockerfile.golang"))); }); });