Files
FitOS/ops/deploy/test/test_autodeploy.py

136 lines
5.6 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.
"""
from __future__ import annotations
import subprocess
import sys
import unittest
from pathlib import Path
DEPLOY_DIR = Path(__file__).resolve().parent.parent
AGENT_DIR = DEPLOY_DIR / "agent"
HOSTDEPLOY = DEPLOY_DIR / "hostdeploy.py"
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
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)]), [])
if __name__ == "__main__":
unittest.main()