259 lines
12 KiB
Python
259 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Testy auto-deployu stagingu (stdlib unittest):
|
|
|
|
python -m unittest discover -s ops/deploy/test -v
|
|
|
|
1. Strażnik bazy: w hostdeploy.py i agencie NIE MA zadnej sciezki kasowania
|
|
wolumenow (żadne podejrzone wyrazenie nie wystepuje w kodzie) — pilnuje,
|
|
zeby auto-deploy nigdy nie mogl skasowac `fitos-alt_fitos_alt_*`.
|
|
2. Suchy run CLI hostdeploy.py --help (exit 0 + oczekiwane flagi).
|
|
3. Logika webhooka: HMAC, filtr repo (wylacznosc FitOS), filtr refa, marker
|
|
[skip deploy], bramka destrukcyjnych migracji.
|
|
4. Maszyna stanow kolejki catch-up (deploy_queue.next_action): in_sync /
|
|
deploy / parking po RETRY_FAILED_SHA nieudanych probach.
|
|
5. Bramka migracji na prawdziwym repositium (fixture `git`): dodanie (A),
|
|
zmiana istniejacej (M) i RENAME destrukcyjnej migracji musza byc skanowane
|
|
(`--no-renames`), usuniecie (D) tylko ostrzezenie.
|
|
6. Skan realnych migracji w repo: swiezo dodana migracja musi byc czysta.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
DEPLOY_DIR = Path(__file__).resolve().parent.parent
|
|
AGENT_DIR = DEPLOY_DIR / "agent"
|
|
HOSTDEPLOY = DEPLOY_DIR / "hostdeploy.py"
|
|
REPO_ROOT = DEPLOY_DIR.parent.parent
|
|
MIGRATIONS_DIR = REPO_ROOT / "api" / "prisma" / "migrations"
|
|
|
|
sys.path.insert(0, str(AGENT_DIR))
|
|
sys.path.insert(0, str(DEPLOY_DIR))
|
|
|
|
from hooks import classify_push, parse_json, verify_signature # noqa: E402
|
|
from deploy_queue import ACTION_DEPLOY, ACTION_IN_SYNC, ACTION_PARKED, next_action # noqa: E402
|
|
import hostdeploy # noqa: E402
|
|
|
|
# tokeny zlozone z kawalkow — test nie zawiera ich jako calych literali
|
|
FORBIDDEN_TOKENS = ("volume" + " rm", "down" + " -v", "--reset" + "-db")
|
|
|
|
|
|
def read_sources() -> dict[str, str]:
|
|
files = [HOSTDEPLOY, AGENT_DIR / "listener.py", AGENT_DIR / "hooks.py"]
|
|
return {f.name: f.read_text(encoding="utf-8") for f in files}
|
|
|
|
|
|
class TestVolumeWipeGuard(unittest.TestCase):
|
|
def test_no_volume_destruction_paths(self) -> None:
|
|
for name, src in read_sources().items():
|
|
for token in FORBIDDEN_TOKENS:
|
|
self.assertNotIn(token, src, f"{name}: znaleziono zabronione wyrazenie {token!r}")
|
|
|
|
def test_cli_help_runs(self) -> None:
|
|
proc = subprocess.run([sys.executable, str(HOSTDEPLOY), "--help"],
|
|
capture_output=True, text=True)
|
|
self.assertEqual(proc.returncode, 0, proc.stderr)
|
|
for flag in ("--ref", "--agent", "--force", "--no-smoke", "--allow-destructive"):
|
|
self.assertIn(flag, proc.stdout)
|
|
|
|
|
|
def push_payload(full_name: str, ref: str = "refs/heads/main", after: str = "a" * 40,
|
|
message: str = "Obszar: test (efekt)") -> dict:
|
|
return {
|
|
"ref": ref,
|
|
"after": after,
|
|
"repository": {"full_name": full_name},
|
|
"commits": [{"id": after, "message": message}],
|
|
}
|
|
|
|
|
|
class TestWebhookPolicy(unittest.TestCase):
|
|
SECRET = "test-secret"
|
|
|
|
def test_signature_ok(self) -> None:
|
|
import hashlib
|
|
import hmac
|
|
body = b'{"ref":"refs/heads/main"}'
|
|
sig = hmac.new(self.SECRET.encode(), body, hashlib.sha256).hexdigest()
|
|
self.assertTrue(verify_signature(self.SECRET, sig, body))
|
|
|
|
def test_signature_rejects_bad_or_missing(self) -> None:
|
|
body = b"{}"
|
|
self.assertFalse(verify_signature(self.SECRET, "deadbeef", body))
|
|
self.assertFalse(verify_signature(self.SECRET, "", body))
|
|
self.assertFalse(verify_signature("", "abcd", body))
|
|
|
|
def test_only_fitos_repo_accepted(self) -> None:
|
|
verdict = classify_push(push_payload("Tisachi/FitOS"), repo="Tisachi/FitOS",
|
|
branch_ref="refs/heads/main")
|
|
self.assertEqual(verdict["status"], "accepted")
|
|
self.assertEqual(verdict["sha"], "a" * 40)
|
|
|
|
def test_other_repo_rejected_even_signed(self) -> None:
|
|
verdict = classify_push(push_payload("Tisachi/InnyProjekt"), repo="Tisachi/FitOS",
|
|
branch_ref="refs/heads/main")
|
|
self.assertEqual(verdict["status"], "rejected")
|
|
|
|
def test_non_main_ref_ignored(self) -> None:
|
|
verdict = classify_push(push_payload("Tisachi/FitOS", ref="refs/heads/dev"),
|
|
repo="Tisachi/FitOS", branch_ref="refs/heads/main")
|
|
self.assertEqual(verdict["status"], "ignored")
|
|
|
|
def test_branch_deletion_ignored(self) -> None:
|
|
verdict = classify_push(push_payload("Tisachi/FitOS", after="0" * 40),
|
|
repo="Tisachi/FitOS", branch_ref="refs/heads/main")
|
|
self.assertEqual(verdict["status"], "ignored")
|
|
|
|
def test_malformed_payload_rejected(self) -> None:
|
|
self.assertIsNone(parse_json(b"nie json"))
|
|
verdict = classify_push(parse_json(b"nie json"), repo="Tisachi/FitOS",
|
|
branch_ref="refs/heads/main")
|
|
self.assertEqual(verdict["status"], "rejected")
|
|
|
|
def test_skip_marker_on_head_commit(self) -> None:
|
|
verdict = classify_push(push_payload("Tisachi/FitOS", message="docs: update [skip deploy]"),
|
|
repo="Tisachi/FitOS", branch_ref="refs/heads/main")
|
|
self.assertTrue(verdict["skip_marker"])
|
|
|
|
|
|
class TestMigrationGate(unittest.TestCase):
|
|
def test_detects_destructive_ddl(self) -> None:
|
|
cases = {
|
|
"DROP TABLE exercises;": "DROP TABLE",
|
|
"ALTER TABLE plan DROP COLUMN difficulty;": "DROP",
|
|
"TRUNCATE TABLE users;": "TRUNCATE",
|
|
"DELETE FROM sessions WHERE 1=1;": "DELETE FROM",
|
|
"ALTER TABLE puzzle RENAME TO exercise;": "RENAME",
|
|
"ALTER TABLE gym RENAME COLUMN name_en TO name_en_new;": "RENAME",
|
|
}
|
|
for sql, _ in cases.items():
|
|
hits = hostdeploy.scan_destructive([("api/prisma/migrations/x/migration.sql", sql)])
|
|
self.assertTrue(hits, f"bramka nie wykryla: {sql}")
|
|
|
|
def test_safe_migrations_pass(self) -> None:
|
|
sql = ("CREATE TABLE gym_photo (id TEXT PRIMARY KEY);\n"
|
|
"CREATE INDEX idx_day ON plan_day (plan_id);\n"
|
|
"ALTER TABLE gym ADD COLUMN city TEXT;\n")
|
|
self.assertEqual(hostdeploy.scan_destructive([("api/prisma/migrations/x/migration.sql", sql)]), [])
|
|
|
|
|
|
class TestQueueStateMachine(unittest.TestCase):
|
|
"""catch-up: ten sam SHA co RELEASE = nic; nowy = deploy; powtarzane
|
|
awarie tego SHA po limicie prob trafiaja na parking."""
|
|
|
|
def test_in_sync_when_release_matches_head(self) -> None:
|
|
self.assertEqual(next_action("a" * 40, "a" * 40, "", 0, 2), ACTION_IN_SYNC)
|
|
|
|
def test_new_sha_triggers_deploy(self) -> None:
|
|
self.assertEqual(next_action("b" * 40, "a" * 40, "a" * 40, 2, 2), ACTION_DEPLOY)
|
|
|
|
def test_failed_sha_retries_until_limit(self) -> None:
|
|
self.assertEqual(next_action("b" * 40, "a" * 40, "b" * 40, 0, 2), ACTION_DEPLOY)
|
|
self.assertEqual(next_action("b" * 40, "a" * 40, "b" * 40, 1, 2), ACTION_DEPLOY)
|
|
self.assertEqual(next_action("b" * 40, "a" * 40, "b" * 40, 2, 2), ACTION_PARKED)
|
|
|
|
def test_parked_stays_parked_until_new_sha(self) -> None:
|
|
for fails in (2, 3, 9):
|
|
self.assertEqual(next_action("b" * 40, "a" * 40, "b" * 40, fails, 2), ACTION_PARKED)
|
|
self.assertEqual(next_action("c" * 40, "a" * 40, "b" * 40, 2, 2), ACTION_DEPLOY)
|
|
|
|
def test_empty_head_sha_rejected(self) -> None:
|
|
with self.assertRaises(ValueError):
|
|
next_action("", "a" * 40, "", 0, 2)
|
|
|
|
|
|
def git_run(repo: Path, *args: str) -> str:
|
|
proc = subprocess.run(["git", "-c", "user.name=gate-test", "-c", "user.email=gate@test.local",
|
|
*args], cwd=str(repo), capture_output=True, text=True)
|
|
if proc.returncode != 0:
|
|
raise RuntimeError(f"git {' '.join(args)}: {proc.stderr.strip()}")
|
|
return proc.stdout.strip()
|
|
|
|
|
|
def write_migration(repo: Path, name: str, sql: str) -> None:
|
|
d = repo / hostdeploy.MIG_DIR / name
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
(d / "migration.sql").write_text(sql, encoding="utf-8")
|
|
|
|
|
|
class TestMigrationGateGit(unittest.TestCase):
|
|
"""Bramka na prawdziwym repositium: A/M/rename/D w diffie migracji."""
|
|
|
|
SAFE = "CREATE TABLE gate_a (id TEXT PRIMARY KEY);\n"
|
|
DESTRUCTIVE = "DROP TABLE gate_a;\n"
|
|
|
|
def setUp(self) -> None:
|
|
self._tmp = tempfile.TemporaryDirectory(prefix="fitos-gate-")
|
|
self.repo = Path(self._tmp.name)
|
|
git_run(self.repo, "init", "-q")
|
|
write_migration(self.repo, "20260101000000_pierwsza", self.SAFE)
|
|
git_run(self.repo, "add", "-A")
|
|
git_run(self.repo, "commit", "-q", "-m", "init")
|
|
self.base = git_run(self.repo, "rev-parse", "HEAD")
|
|
|
|
def tearDown(self) -> None:
|
|
self._tmp.cleanup()
|
|
|
|
def commit_all(self) -> str:
|
|
git_run(self.repo, "add", "-A")
|
|
git_run(self.repo, "commit", "-q", "-m", "zmiana migracji")
|
|
return git_run(self.repo, "rev-parse", "HEAD")
|
|
|
|
def test_added_destructive_detected(self) -> None:
|
|
write_migration(self.repo, "20260102000000_druga", self.DESTRUCTIVE)
|
|
new = self.commit_all()
|
|
found = hostdeploy.find_new_migrations(self.repo, self.base, new)
|
|
self.assertEqual([p for p, _ in found], [f"{hostdeploy.MIG_DIR}/20260102000000_druga/migration.sql"])
|
|
self.assertTrue(hostdeploy.scan_destructive(found))
|
|
|
|
def test_added_safe_passes_gate(self) -> None:
|
|
write_migration(self.repo, "20260102000000_druga", "ALTER TABLE gate_a ADD COLUMN city TEXT;\n")
|
|
new = self.commit_all()
|
|
found = hostdeploy.find_new_migrations(self.repo, self.base, new)
|
|
self.assertEqual(len(found), 1)
|
|
self.assertEqual(hostdeploy.scan_destructive(found), [])
|
|
|
|
def test_modified_migration_scanned(self) -> None:
|
|
# przestepca edytuje JOZ WDROZONA migracje — status M, tez musi byc skanowany
|
|
write_migration(self.repo, "20260101000000_pierwsza", self.DESTRUCTIVE)
|
|
new = self.commit_all()
|
|
found = hostdeploy.find_new_migrations(self.repo, self.base, new)
|
|
self.assertEqual([p for p, _ in found], [f"{hostdeploy.MIG_DIR}/20260101000000_pierwsza/migration.sql"])
|
|
self.assertTrue(hostdeploy.scan_destructive(found))
|
|
|
|
def test_renamed_migration_not_hidden(self) -> None:
|
|
write_migration(self.repo, "20260102000000_stara", self.DESTRUCTIVE)
|
|
self.commit_all()
|
|
git_run(self.repo, "mv", f"{hostdeploy.MIG_DIR}/20260102000000_stara",
|
|
f"{hostdeploy.MIG_DIR}/20260103000000_nowaNazwa")
|
|
new = self.commit_all()
|
|
found = hostdeploy.find_new_migrations(self.repo, self.base, new)
|
|
paths = [p for p, _ in found]
|
|
self.assertIn(f"{hostdeploy.MIG_DIR}/20260103000000_nowaNazwa/migration.sql", paths)
|
|
self.assertTrue(hostdeploy.scan_destructive(found))
|
|
|
|
def test_deleted_migration_not_treated_as_new(self) -> None:
|
|
write_migration(self.repo, "20260102000000_stara", self.DESTRUCTIVE)
|
|
mid = self.commit_all()
|
|
git_run(self.repo, "rm", "-q", f"{hostdeploy.MIG_DIR}/20260102000000_stara/migration.sql")
|
|
new = self.commit_all()
|
|
self.assertEqual(hostdeploy.find_new_migrations(self.repo, mid, new), [])
|
|
|
|
|
|
class TestRealRepoMigrations(unittest.TestCase):
|
|
def test_latest_pending_migration_is_safe(self) -> None:
|
|
if not MIGRATIONS_DIR.is_dir():
|
|
self.skipTest("brak api/prisma/migrations w tym drzewie")
|
|
latest = sorted(p.parent.name for p in MIGRATIONS_DIR.glob("*/migration.sql"))[-1]
|
|
sql = (MIGRATIONS_DIR / latest / "migration.sql").read_text(encoding="utf-8")
|
|
self.assertEqual(hostdeploy.scan_destructive([(latest, sql)]), [],
|
|
f"najnowsza migracja {latest} zawiera destrukcyjne DDL")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|