fix(install): двухфазная установка, clean-host контракт и проверка поколения

Установщик мог повредить работающий сервер до того, как откажется его
трогать: install.sh переписывал /usr/local/lib/hy2xs, раскладывал
runtime-пакет и перезаписывал install-state.json, и только потом
запускал clean-host preflight. При ошибочном запуске поверх старой
установки rollback дополнительно делал stop и disable для работающих
hysteria-server и hy2xs-admin.

Установка разделена на две фазы с жёсткой границей:

  PHASE 0 - read only: права, checksums пакета, clean-host preflight
            из распакованного архива (новая команда preflight-install)
  PHASE 1 - mutation: раскладка оркестратора и сама установка

Граница держится не соглашением, а read-only guard: под ним writeText,
writeTextAtomic и мутирующие раннеры lib/process кидают ошибку.
Внутри install() preflight выполняется раньше первой записи состояния.

Остальное в этом же инварианте:

- clean-host контракт расширен с двух маркеров до четырнадцати, пути
  установки и данных берутся из конфигурации, а не захардкожены;
- отсутствие HY2XS_CONFIG_SCHEMA_VERSION трактуется как legacy, а не
  как текущая схема: до v1 этого поля не существовало. Тест,
  закреплявший прежнее поведение, инвертирован;
- install-state несёт идентификацию поколения (product, release_line,
  config_schema_version); reconfigure и repair проверяют её до всего
  остального, потому что installed: true мог остаться и от 0.x;
- repair требует явного --allow-partial-state;
- классификация отказа опирается на ownership-флаги, а не на текст
  ошибки: раньше сообщение со словом nftables приводило к откату
  чужого firewall. stop/disable выполняется только для юнитов,
  развёрнутых текущей операцией, а fatal_pre_apply не делает
  системного отката и не собирает diagnostics-бандл.
This commit is contained in:
2026-08-27 12:14:47 +05:00
parent ddf0ddf71e
commit 2b4a2cb2d5
18 changed files with 1188 additions and 179 deletions
+108
View File
@@ -0,0 +1,108 @@
import { describe, expect, test } from "bun:test";
import {
assertCleanHost,
detectLegacyMarkers,
legacyMarkersFor,
renderLegacyFailure,
type HostProbe
} from "../src/steps/cleanHost";
import { baselineConfig } from "./fixtures";
/**
* Проба, которая считает «существующими» ровно переданный набор целей.
* Это позволяет проверить контракт чистого хоста без файловой системы.
*/
function probeWith(present: readonly string[]): HostProbe {
const set = new Set(present);
return {
async fileExists(path) {
return set.has(path);
},
async dirExists(path) {
return set.has(path);
},
async unitExists(unit) {
return set.has(unit);
}
};
}
const config = baselineConfig();
describe("clean-host контракт", () => {
test("чистый хост проходит", async () => {
await expect(assertCleanHost(config, "bootstrap", probeWith([]))).resolves.toBeUndefined();
});
test("каждый маркер по отдельности останавливает установку", async () => {
const markers = legacyMarkersFor(config, "bootstrap");
expect(markers.length).toBeGreaterThan(10);
for (const marker of markers) {
const probe = probeWith([marker.target]);
await expect(assertCleanHost(config, "bootstrap", probe)).rejects.toThrow(
/предыдущая или посторонняя установка/
);
}
});
test("список покрывает состояние, юниты, бинарник и наследие 0.x", () => {
const targets = legacyMarkersFor(config, "bootstrap").map((marker) => marker.target);
for (const expected of [
"/etc/hysteria/post-install.env",
"/etc/hy2xs/hy2xs.env",
"/var/lib/hy2xs/install-state.json",
"/etc/hy2xs/bootstrap-admin.secret",
"/usr/local/lib/hy2xs/package",
"/etc/hysteria/config.yaml",
"/usr/local/bin/hysteria",
"/etc/nftables.d/hy2xs.nft",
"hy2xs-admin.service",
"hysteria-server.service",
"h-ui.service",
"/usr/local/h-ui",
config.installDir,
config.dataDir
]) {
expect(targets).toContain(expected);
}
});
test("пути из конфигурации попадают в список, а не только дефолтные", () => {
const custom = baselineConfig({
HY2XS_INSTALL_DIR: "/srv/hy2xs-app",
HY2XS_DATA_DIR: "/srv/hy2xs-data"
});
const targets = legacyMarkersFor(custom, "bootstrap").map((marker) => marker.target);
expect(targets).toContain("/srv/hy2xs-app");
expect(targets).toContain("/srv/hy2xs-data");
});
// install.sh раскладывает runtime-пакет между фазами, поэтому в PHASE 1
// этот путь уже наш и маркером быть не может.
test("runtime-пакет — маркер в PHASE 0, но не в PHASE 1", async () => {
const probe = probeWith(["/usr/local/lib/hy2xs/package"]);
await expect(assertCleanHost(config, "bootstrap", probe)).rejects.toThrow(/usr\/local\/lib\/hy2xs\/package/);
await expect(assertCleanHost(config, "install", probe)).resolves.toBeUndefined();
});
test("остальные маркеры продолжают работать и в PHASE 1", async () => {
const probe = probeWith(["hysteria-server.service"]);
await expect(assertCleanHost(config, "install", probe)).rejects.toThrow(/hysteria-server\.service/);
});
test("сообщение перечисляет все найденные маркеры и говорит, что хост не изменён", async () => {
const found = await detectLegacyMarkers(
legacyMarkersFor(config, "bootstrap"),
probeWith(["/etc/hy2xs/hy2xs.env", "hy2xs-admin.service"])
);
expect(found).toHaveLength(2);
const message = renderLegacyFailure(found);
expect(message).toContain("/etc/hy2xs/hy2xs.env");
expect(message).toContain("hy2xs-admin.service");
expect(message).toContain("Ни один файл на сервере не изменён");
expect(message).toContain("docs/14-legacy-cleanup.md");
});
});
+22 -3
View File
@@ -93,9 +93,28 @@ describe("gecko packet sizes", () => {
});
describe("config schema version", () => {
test("отсутствие значения даёт текущую схему", () => {
const config = parseRuntimeEnv(envText({ HY2XS_CONFIG_SCHEMA_VERSION: null }));
expect(config.configSchemaVersion).toBe(HY2XS_CONFIG_SCHEMA_VERSION);
// Отсутствующий маркер — самый вероятный признак конфигурации 0.x: до v1
// этого поля не существовало. Любой fallback здесь молча принял бы legacy.
test("отсутствие значения трактуется как legacy и отклоняется", () => {
expect(() => parseRuntimeEnv(envText({ HY2XS_CONFIG_SCHEMA_VERSION: null }))).toThrow(
/HY2XS_CONFIG_SCHEMA_VERSION отсутствует/
);
});
test("отказ по отсутствующей схеме указывает на чистую установку", () => {
expect(() => parseRuntimeEnv(envText({ HY2XS_CONFIG_SCHEMA_VERSION: null }))).toThrow(
/legacy-cleanup/
);
});
test("пустое значение отклоняется так же, как отсутствующее", () => {
expect(() => parseRuntimeEnv(envText({ HY2XS_CONFIG_SCHEMA_VERSION: "" }))).toThrow(
/HY2XS_CONFIG_SCHEMA_VERSION отсутствует/
);
});
test("текущая схема принимается", () => {
expect(baselineConfig().configSchemaVersion).toBe(HY2XS_CONFIG_SCHEMA_VERSION);
});
test("схема v0/v1 отклоняется с указанием на чистую установку", () => {
+112
View File
@@ -0,0 +1,112 @@
import { afterEach, describe, expect, test } from "bun:test";
import { classifyFailure } from "../src/commands/install";
import { disableReadOnlyGuard, enableReadOnlyGuard, isReadOnlyGuardActive } from "../src/lib/guard";
import { writeText, writeTextAtomic } from "../src/lib/fs";
import { runHidden, runRawVisible, runVisible } from "../src/lib/process";
type Ownership = Parameters<typeof classifyFailure>[0];
function ownership(overrides: Partial<Ownership> = {}): Ownership {
return {
stateWritten: false,
depsInstalled: false,
filesystemPrepared: false,
unitsDeployed: false,
firewallTouched: false,
postInstallWritten: false,
servicesStarted: false,
...overrides
};
}
afterEach(() => {
disableReadOnlyGuard();
});
describe("read-only guard (PHASE 0)", () => {
test("по умолчанию выключен", () => {
expect(isReadOnlyGuardActive()).toBe(false);
});
test("под guard'ом запись в файл невозможна", async () => {
enableReadOnlyGuard("test phase");
await expect(writeText("/tmp/hy2xs-guard-probe", "x")).rejects.toThrow(/read-only guard violation/);
await expect(
writeTextAtomic("/tmp/hy2xs-guard-probe", "x", { mode: 0o600, owner: "root", group: "root" })
).rejects.toThrow(/read-only guard violation/);
});
test("под guard'ом мутирующие раннеры недоступны", async () => {
enableReadOnlyGuard("test phase");
await expect(runVisible`true`).rejects.toThrow(/read-only guard violation/);
await expect(runHidden`true`).rejects.toThrow(/read-only guard violation/);
await expect(runRawVisible("true")).rejects.toThrow(/read-only guard violation/);
});
test("сообщение называет операцию и фазу", async () => {
enableReadOnlyGuard("the read-only install preflight (PHASE 0)");
await expect(writeText("/tmp/hy2xs-guard-probe", "x")).rejects.toThrow(
/writeText\(\/tmp\/hy2xs-guard-probe\).*PHASE 0/s
);
});
test("guard снимается явно", () => {
enableReadOnlyGuard("test phase");
expect(isReadOnlyGuardActive()).toBe(true);
disableReadOnlyGuard();
expect(isReadOnlyGuardActive()).toBe(false);
});
});
describe("классификация отказа установки", () => {
// Ключевой инвариант: пока операция ничего не применила, отказ обязан быть
// pre-apply, что бы ни было написано в тексте ошибки.
test("до любой мутации отказ — fatal_pre_apply", () => {
expect(classifyFailure(ownership(), "installing")).toBe("fatal_pre_apply");
expect(classifyFailure(ownership(), "preflight_ok")).toBe("fatal_pre_apply");
});
test("установленные пакеты уже делают отказ post-apply", () => {
expect(classifyFailure(ownership({ depsInstalled: true }), "preflight_ok")).toBe("fatal_post_apply");
});
test("развёрнутые юниты без firewall — post-apply", () => {
expect(classifyFailure(ownership({ filesystemPrepared: true, unitsDeployed: true }), "units_deployed")).toBe(
"fatal_post_apply"
);
});
test("тронутый firewall классифицируется как firewall failure", () => {
expect(
classifyFailure(ownership({ unitsDeployed: true, firewallTouched: true }), "firewall_applied")
).toBe("firewall_connectivity_failure");
});
test("после записи post-install env отказ — postinstall validation", () => {
expect(
classifyFailure(
ownership({ unitsDeployed: true, firewallTouched: true, postInstallWritten: true }),
"postinstall_env_written"
)
).toBe("postinstall_validation_failure");
});
test("после старта сервисов различаются smoke и service failure", () => {
const started = ownership({
unitsDeployed: true,
firewallTouched: true,
postInstallWritten: true,
servicesStarted: true
});
expect(classifyFailure(started, "smoke_running")).toBe("smoke_readiness_timeout");
expect(classifyFailure(started, "smoke_failed")).toBe("smoke_readiness_timeout");
expect(classifyFailure(started, "services_started")).toBe("service_start_failure");
});
// Регрессия: раньше классификация шла по подстрокам сообщения, поэтому
// preflight-ошибка со словом "nftables" приводила к откату чужого firewall.
test("текст ошибки не влияет на классификацию", () => {
expect(classifyFailure(ownership(), "installing")).toBe("fatal_pre_apply");
expect(classifyFailure(ownership({ depsInstalled: true }), "deps_ok")).toBe("fatal_post_apply");
});
});
+124
View File
@@ -0,0 +1,124 @@
import { describe, expect, test } from "bun:test";
import {
HY2XS_PRODUCT_ID,
assertCurrentGeneration,
buildInstallStateRecord,
detectGenerationProblems,
renderGenerationFailure
} from "../src/lib/installState";
import { HY2XS_CONFIG_SCHEMA_VERSION, HY2XS_RELEASE_LINE } from "../src/config/profile";
function currentState(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
product: HY2XS_PRODUCT_ID,
release_line: HY2XS_RELEASE_LINE,
config_schema_version: HY2XS_CONFIG_SCHEMA_VERSION,
product_version: "1.0.0",
installed: true,
phase: "installed",
...overrides
};
}
describe("идентификация поколения установки", () => {
test("маркер текущего поколения принимается", () => {
expect(detectGenerationProblems(currentState())).toEqual([]);
expect(() => assertCurrentGeneration(currentState())).not.toThrow();
});
// Именно этот случай и есть «старый state marker от 0.x»: installed: true
// сам по себе ничего не доказывает.
test("маркер без полей поколения отклоняется, несмотря на installed: true", () => {
const legacy = { installed: true, phase: "installed", version: "0.0.22" };
expect(detectGenerationProblems(legacy)).toEqual([
"missing_product",
"missing_release_line",
"missing_config_schema"
]);
expect(() => assertCurrentGeneration(legacy)).toThrow(/не относится к текущему поколению/);
});
test("чужой продукт отклоняется", () => {
expect(detectGenerationProblems(currentState({ product: "h-ui" }))).toContain("foreign_product");
});
test("другая линия релиза отклоняется", () => {
expect(detectGenerationProblems(currentState({ release_line: 0 }))).toContain("foreign_release_line");
expect(detectGenerationProblems(currentState({ release_line: 2 }))).toContain("foreign_release_line");
});
test("другая схема конфигурации отклоняется", () => {
expect(detectGenerationProblems(currentState({ config_schema_version: 1 }))).toContain(
"foreign_config_schema"
);
});
test("нечисловые поля поколения считаются отсутствующими", () => {
const problems = detectGenerationProblems(
currentState({ release_line: "1", config_schema_version: "2" })
);
expect(problems).toContain("missing_release_line");
expect(problems).toContain("missing_config_schema");
});
test("не-объект отклоняется целиком", () => {
expect(detectGenerationProblems(null)).toHaveLength(3);
expect(detectGenerationProblems("installed")).toHaveLength(3);
expect(detectGenerationProblems([1, 2])).toHaveLength(3);
});
test("сообщение объясняет расхождение и направляет на чистую переустановку", () => {
const state = currentState({ release_line: 0 });
const message = renderGenerationFailure(detectGenerationProblems(state), state);
expect(message).toContain("release_line");
expect(message).toContain("docs/14-legacy-cleanup.md");
});
});
describe("запись маркера установки", () => {
test("маркер всегда несёт идентификацию поколения", () => {
const record = buildInstallStateRecord({
productVersion: "1.0.0",
buildId: "test-build",
opId: "op",
startedAt: "2026-08-27T00:00:00.000Z",
phase: "installed",
installed: true,
ownedPaths: ["/etc/hysteria/config.yaml"]
});
expect(record.product).toBe(HY2XS_PRODUCT_ID);
expect(record.release_line).toBe(HY2XS_RELEASE_LINE);
expect(record.config_schema_version).toBe(HY2XS_CONFIG_SCHEMA_VERSION);
expect(detectGenerationProblems(record)).toEqual([]);
});
test("успешная установка не несёт repair_hint", () => {
const record = buildInstallStateRecord({
productVersion: "1.0.0",
buildId: "b",
opId: "op",
startedAt: "2026-08-27T00:00:00.000Z",
phase: "installed",
installed: true,
ownedPaths: []
});
expect(record.repair_hint).toBeUndefined();
});
test("незавершённая установка подсказывает repair с явным флагом", () => {
const record = buildInstallStateRecord({
productVersion: "1.0.0",
buildId: "b",
opId: "op",
startedAt: "2026-08-27T00:00:00.000Z",
phase: "failed",
installed: false,
ownedPaths: [],
lastError: "boom",
repairHint: "run: hy2xs-orchestrator repair --allow-partial-state"
});
expect(record.installed).toBe(false);
expect(record.repair_hint).toContain("--allow-partial-state");
});
});