"""Publication contract: real candidates, private provenance, CAS and immutable live.""" import json import os import shutil import tempfile import unittest from pathlib import Path from unittest.mock import patch from fastapi.testclient import TestClient from site_engine.build.pipeline import build_site, hash_tree from site_engine.services.auth import hash_password from site_engine.services.documents import EditorContext from site_engine.services.publication import PublicationService from site_engine.web.app import create_app ROOT = Path(__file__).resolve().parents[1] class PublicationTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.password = "publication test password" cls.password_hash = hash_password(cls.password, n=2**10) def setUp(self): tmp = tempfile.TemporaryDirectory(prefix="publication-test-") self.addCleanup(tmp.cleanup) self.work = Path(tmp.name) self.site, self.dist, self.state = (self.work / n for n in ("site", "dist", "state")) shutil.copytree( ROOT / "examples/site-studio", self.site, ignore=shutil.ignore_patterns(".engine") ) env = patch.dict( os.environ, { "SITE_ROOT": str(self.site), "SITE_DIST": str(self.dist), "SITE_STATE_DIR": str(self.state), "SITE_ADMIN_LOGIN": "admin", "SITE_ADMIN_PASSWORD_HASH": self.password_hash, "SITE_SECRET_KEY": "publication-test-secret-" * 4, "SITE_COOKIE_SECURE": "0", "SITE_ADMIN_ORIGIN": "", "SITE_PREVIEW_ORIGIN": "", }, ) env.start() self.addCleanup(env.stop) self.app = create_app() self.client = TestClient(self.app) self.addCleanup(self.client.close) cookie = self.app.state.auth.login("admin", self.password, "testclient") self.client.cookies.set("se_session", cookie) self.app.state.api_credentials["test"] = (cookie, "testclient") self.principal = self.app.state.auth.authenticate(cookie) self.ctx = EditorContext(self.principal, "testclient") self.csrf = self.app.state.auth.csrf_token(self.principal) self.svc = PublicationService(self.site, self.dist, self.state, self.app.state.auth.audit) def api(self, method="GET", path="", payload=None): return self.client.request( method, "/admin/api/v1/publication" + path, json=payload, headers={"Authorization": "Bearer test"}, ) def ui(self, operation, payload=None, csrf=None): return self.client.post( "/admin/publication/" + operation, data={ "csrf": self.csrf if csrf is None else csrf, "payload": json.dumps(payload or {}), }, headers={"Origin": "http://testserver", "Accept": "application/json"}, ) def build(self): r = self.api("POST", "/build") self.assertEqual(r.status_code, 200, r.text) return r.json() def activate(self, candidate, base=None, comment="Проверенный релиз"): return self.api( "POST", "/activate", {"id": candidate["id"], "expected_live": base, "comment": comment} ) def edit(self, rel="pages/index.md", old="Студия автоматизации", new="Новая студия"): path = self.site / rel source = path.read_text() if old not in source: source += "\n" + new else: source = source.replace(old, new) path.write_text(source) def test_original_screen_and_api_only_adapter_static_and_csrf(self): r = self.client.get("/admin/publish") self.assertEqual(r.status_code, 200, r.text) self.assertIn("data-publication-root", r.text) for name in ( "publication.css", "publication-adapter.css", "publication.js", "publication-icons.json", ): self.assertEqual(self.client.get("/admin/static/" + name).status_code, 200, name) before = self.app.state.api_calls self.assertEqual(self.ui("validate").status_code, 200) self.assertEqual(self.app.state.api_calls - before, 1) self.assertEqual(self.ui("build", csrf="bad").status_code, 403) self.assertEqual(self.client.get("/admin/publication/build").status_code, 405) self.assertEqual(self.client.get("/admin/publication/unknown").status_code, 404) def test_build_never_activates_and_private_snapshots_never_in_dist(self): initial = hash_tree(self.site) c = self.build() self.assertIsNone(self.svc.current()) self.assertEqual(hash_tree(self.site), initial) self.assertTrue((self.dist / c["id"] / "index.html").is_file()) self.assertFalse((self.dist / c["id"] / "pages").exists()) self.assertFalse((self.dist / c["id"] / "content").exists()) self.assertNotIn("sources", self.svc.manifest(c["id"])) self.assertIn("content/services/automation.md", self.svc.provenance(c["id"])["sources"]) state = self.api().json() self.assertTrue(state["candidate"]["fresh"]) self.assertTrue(state["history"][0]["candidate"]) self.assertEqual(state["builds"][0]["status"], "ready") def test_activate_exact_existing_output_and_no_rebuild(self): c = self.build() output = hash_tree(self.dist / c["id"]) with patch( "site_engine.services.publication.build_site", side_effect=AssertionError("must not rebuild"), ): r = self.activate(c) self.assertEqual(r.status_code, 200, r.text) self.assertEqual(self.svc.current(), c["id"]) self.assertEqual(hash_tree(self.dist / c["id"]), output) state = self.api().json() self.assertIsNone(state["candidate"]) self.assertFalse(state["changes"]) self.assertEqual(state["history"][0]["comment"], "Проверенный релиз") def test_stale_source_and_replaced_candidate_cannot_activate_or_rollback(self): c = self.build() self.edit() self.assertFalse(self.api().json()["candidate"]["fresh"]) self.assertEqual(self.activate(c).status_code, 409) self.assertEqual( self.api("POST", "/rollback", {"id": c["id"], "expected_live": None}).status_code, 422 ) newer = self.build() self.assertNotEqual(c["id"], newer["id"]) self.assertEqual(self.activate(c).status_code, 409) self.assertIsNone(self.svc.current()) def test_engine_resources_and_output_tampering_invalidate_candidate(self): c = self.build() with patch( "site_engine.services.publication.render_fingerprint", return_value="changed-engine" ): self.assertFalse(self.api().json()["candidate"]["fresh"]) self.assertEqual(self.activate(c).status_code, 409) (self.dist / c["id"] / "index.html").write_text("tampered") self.assertEqual(self.activate(c).status_code, 422) self.assertIsNone(self.svc.current()) def test_live_cas_and_rollback_do_not_touch_workspace(self): a = self.build() self.assertEqual(self.activate(a).status_code, 200) self.edit() b = self.build() self.assertEqual(self.activate(b, base="20000101T000000-12345678").status_code, 409) self.assertEqual(self.activate(b, base=a["id"]).status_code, 200) before = hash_tree(self.site) r = self.api("POST", "/rollback", {"id": a["id"], "expected_live": b["id"]}) self.assertEqual(r.status_code, 200, r.text) self.assertEqual(self.svc.current(), a["id"]) self.assertEqual(hash_tree(self.site), before) self.assertEqual( self.api("POST", "/rollback", {"id": b["id"], "expected_live": b["id"]}).status_code, 409, ) self.assertTrue(self.api().json()["changes"]) def test_comparison_actual_text_added_deleted_assets_and_old_release_unknown(self): a = self.build() self.activate(a) self.edit() (self.site / "assets/new.txt").write_text("new asset") (self.site / "assets/hero.webp").unlink() state = self.api().json() rows = {x["path"]: x for x in state["changes"]} self.assertEqual(rows["pages/index.md"]["kind"], "modified") self.assertEqual(rows["assets/new.txt"]["kind"], "new") self.assertEqual(rows["assets/hero.webp"]["kind"], "deleted") diff = self.api(path="/compare?path=pages/index.md").json() self.assertNotEqual(diff["before"]["source"], diff["after"]["source"]) (self.state / "publication/releases" / f"{a['id']}.json").unlink() state = self.api().json() self.assertFalse(state["comparison_available"]) self.assertTrue(all(x["kind"] == "unknown" for x in state["changes"])) self.assertIsNone(self.api(path="/compare?path=pages/index.md").json()["before"]) def test_candidate_diff_is_immutable_after_workspace_change(self): a = self.build() self.activate(a) self.edit() self.build() before = self.api(path="/candidate-diff").json() (self.site / "assets/not-in-candidate.txt").write_text("later") after = self.api(path="/candidate-diff").json() self.assertEqual(before, after) self.assertNotIn("assets/not-in-candidate.txt", json.dumps(after)) def test_validation_and_failed_strict_render_preserve_live_and_previous_candidate(self): a = self.build() self.activate(a) self.edit() b = self.build() with ( patch( "site_engine.core.render.Renderer.render", side_effect=RuntimeError("real render probe"), ), self.assertLogs("uvicorn.error", level="ERROR") as captured, ): r = self.api("POST", "/build") self.assertEqual(r.status_code, 500) self.assertIn("real render probe", "\n".join(captured.output)) self.assertTrue(r.json()["error"]["request_id"]) state = self.api().json() self.assertEqual(state["current"], a["id"]) self.assertEqual(state["candidate"]["id"], b["id"]) self.assertEqual(state["builds"][0]["status"], "failed") self.edit( "pages/index.md", "status: published", "status: published\nlayout: missing-layout" ) r = self.api("POST", "/validate") self.assertEqual(r.status_code, 200, r.text) self.assertGreater(r.json()["errors"], 0) self.assertEqual(self.api("POST", "/build").status_code, 422) self.assertEqual(self.svc.current(), a["id"]) def test_passive_snapshot_is_real_build_with_assets_and_no_site_scripts(self): c = self.build() self.edit() r = self.api("POST", "/preview", {"id": c["id"], "route": "/"}) self.assertEqual(r.status_code, 200, r.text) preview = r.json() page = self.client.get(preview["url"]) self.assertEqual(page.status_code, 200) self.assertNotIn("