"""Postiz client + publishing route hardening (Oracle backend review). Covers the credential-exfil default removal (H1), the ``scheduled_date`` normalisation for the drip queue (H3), the disabled-channel refusal (M7) and the error paths that used to 500 (M9). No network: the Postiz client functions are stubbed with monkeypatch. """ import asyncio import inspect from datetime import datetime, timedelta import httpx import pytest import postiz POSTIZ_HEADERS = {"X-Postiz-Url": "https://postiz.example", "X-Postiz-Key": "k"} def _app(): return pytest.importorskip("app") # --- postiz.py ------------------------------------------------------------- class TestResolveBase: def test_bare_host_gets_the_api_prefix(self): assert postiz._resolve_base("https://p.example") == \ "https://p.example/api/public/v1" def test_trailing_slash_is_trimmed(self): assert postiz._resolve_base("https://p.example/") == \ "https://p.example/api/public/v1" def test_existing_prefix_is_not_doubled(self): assert postiz._resolve_base("https://p.example/api/public/v1") == \ "https://p.example/api/public/v1" assert postiz._resolve_base("https://p.example/api/public/v1/") == \ "https://p.example/api/public/v1" def test_env_fallback_used_when_no_argument(self, monkeypatch): monkeypatch.setenv("POSTIZ_URL", "https://env.example/") assert postiz._resolve_base(None) == "https://env.example/api/public/v1" def test_missing_url_is_refused(self, monkeypatch): monkeypatch.delenv("POSTIZ_URL", raising=False) with pytest.raises(postiz.PostizError) as exc: postiz._resolve_base(None) assert exc.value.status_code == 400 assert "Missing Postiz URL" in exc.value.detail def test_no_builtin_host_is_shipped(self): # H1: the old silent default would ship a caller's key to a host we # picked. It must not exist anywhere in the module. assert "postiz.pbento.pt" not in inspect.getsource(postiz) class TestHandle: def test_success_returns_json(self): assert postiz._handle(httpx.Response(200, json={"ok": True})) == {"ok": True} def test_empty_body_is_none(self): assert postiz._handle(httpx.Response(200, content=b"")) is None def test_error_body_is_truncated(self): with pytest.raises(postiz.PostizError) as exc: postiz._handle(httpx.Response(500, text="x" * 5000)) assert exc.value.status_code == 500 assert "x" * 500 in exc.value.detail assert "x" * 501 not in exc.value.detail # --- app.py per-provider settings ----------------------------------------- class TestPostizSettings: def test_tiktok_requires_a_posting_method(self): s = _app()._postiz_settings("tiktok", "Title", "caption", []) assert s["__type"] == "tiktok" assert s["content_posting_method"] == "DIRECT_POST" assert s["privacy_level"] == "PUBLIC_TO_EVERYONE" def test_instagram_sets_post_type(self): assert _app()._postiz_settings("instagram", "Title", "caption", []) == \ {"__type": "instagram", "post_type": "post"} def test_youtube_sets_title_and_type(self): s = _app()._postiz_settings("youtube", "My Short", "caption", ["tag"]) assert s["__type"] == "youtube" assert s["type"] == "public" assert s["title"] == "My Short" assert s["tags"] == [{"value": "tag", "label": "tag"}] def test_youtube_title_is_padded_to_the_minimum(self): assert len(_app()._postiz_settings("youtube", "A", "caption", [])["title"]) >= 2 class TestIsoDate: def test_naive_date_gets_the_timezone(self): assert _app()._postiz_iso_date("2026-12-31T12:00:00", "UTC") == \ "2026-12-31T12:00:00.000Z" def test_unscheduled_defaults_to_now(self): out = _app()._postiz_iso_date(None, "UTC") assert out.endswith("Z") and "T" in out def test_unparseable_date_is_a_400(self): from fastapi import HTTPException with pytest.raises(HTTPException) as exc: _app()._postiz_iso_date("not-a-date", "UTC") assert exc.value.status_code == 400 class TestScheduledNormalisation: def test_scheduled_date_is_backfilled_without_dropping_raw_fields(self): app = _app() post = {"id": "p1", "date": "2026-12-31T12:00:00.000Z"} out = app._normalise_postiz_post(post) assert out["scheduled_date"] == "2026-12-31T12:00:00.000Z" assert out["date"] == "2026-12-31T12:00:00.000Z" assert out is not post assert app._normalise_postiz_post( {"id": "p2", "scheduledDate": "2026-01-02T00:00:00.000Z"} )["scheduled_date"] == "2026-01-02T00:00:00.000Z" assert app._normalise_postiz_post( {"id": "p3", "scheduled_date": "kept"})["scheduled_date"] == "kept" # --- /api/postiz/post request builder ------------------------------------- @pytest.fixture() def publish_env(tmp_path, monkeypatch): app = _app() out = tmp_path / "output" job_dir = out / "job1" job_dir.mkdir(parents=True) (job_dir / "clip_1.mp4").write_bytes(b"video") monkeypatch.setattr(app, "OUTPUT_DIR", str(out)) monkeypatch.setattr(app, "jobs", { "job1": {"result": {"clips": [{ "video_url": "/videos/job1/clip_1.mp4", "title": "Clip title", "video_description_for_instagram": "caption #one", }]}} }) return app @pytest.fixture() def stubbed(monkeypatch): calls = {"order": [], "integrations": []} def list_integrations(base, key, *a, **k): calls["order"].append("list") calls["base"] = base return calls["integrations"] def upload_media(base, key, path, *a, **k): calls["order"].append("upload") calls["uploaded"] = path return {"id": "media-1", "path": "media/path"} def create_post(base, key, payload, *a, **k): calls["order"].append("create") calls["payload"] = payload return [{"postId": "p1", "integration": "x"}] monkeypatch.setattr(postiz, "list_integrations", list_integrations) monkeypatch.setattr(postiz, "upload_media", upload_media) monkeypatch.setattr(postiz, "create_post", create_post) return calls def _call(app, method, path, **kw): async def _do(): transport = httpx.ASGITransport(app=app.app) async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as c: return await getattr(c, method)(path, **kw) return asyncio.run(_do()) def _post(app, payload, headers=POSTIZ_HEADERS): return _call(app, "post", "/api/postiz/post", json=payload, headers=headers) def test_builder_targets_each_integration_and_uploads_first(publish_env, stubbed): stubbed["integrations"] = [ {"id": "i-tt", "identifier": "tiktok", "disabled": False}, {"id": "i-yt", "identifier": "youtube"}, ] r = _post(publish_env, {"job_id": "job1", "clip_index": 0, "platforms": ["tiktok", "youtube"], "title": "My Title"}) assert r.status_code == 200, r.text assert stubbed["order"] == ["list", "upload", "create"] payload = stubbed["payload"] assert [p["integration"]["id"] for p in payload["posts"]] == ["i-tt", "i-yt"] assert [p["settings"]["__type"] for p in payload["posts"]] == ["tiktok", "youtube"] assert payload["posts"][0]["value"][0]["image"][0]["id"] == "media-1" assert payload["shortLink"] is False and payload["type"] == "now" assert stubbed["uploaded"].endswith("clip_1.mp4") def test_disabled_integration_is_refused(publish_env, stubbed): stubbed["integrations"] = [{"id": "i-yt", "identifier": "youtube", "disabled": True}] r = _post(publish_env, {"job_id": "job1", "clip_index": 0, "platforms": ["youtube"]}) assert r.status_code == 400 assert "Disabled" in r.json()["detail"] assert "upload" not in stubbed["order"] and "create" not in stubbed["order"] def test_missing_integration_is_refused(publish_env, stubbed): stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}] r = _post(publish_env, {"job_id": "job1", "clip_index": 0, "platforms": ["instagram"]}) assert r.status_code == 400 assert "Not connected" in r.json()["detail"] assert "upload" not in stubbed["order"] def test_clip_without_video_url_is_400_not_500(publish_env, stubbed): publish_env.jobs["job1"]["result"]["clips"] = [{"title": "no url"}] r = _post(publish_env, {"job_id": "job1", "clip_index": 0, "platforms": ["tiktok"]}) assert r.status_code == 400 assert "video_url" in r.json()["detail"] def test_missing_url_or_key_is_a_400(publish_env, stubbed, monkeypatch): monkeypatch.delenv("POSTIZ_URL", raising=False) monkeypatch.delenv("POSTIZ_API_KEY", raising=False) body = {"job_id": "job1", "clip_index": 0, "platforms": ["tiktok"]} r = _post(publish_env, body, headers={"X-Postiz-Key": "k"}) assert r.status_code == 400 and "URL" in r.json()["detail"] r = _post(publish_env, body, headers={"X-Postiz-Url": "https://p.example"}) assert r.status_code == 400 and "key" in r.json()["detail"].lower() def test_bad_scheduled_date_is_a_400(publish_env, stubbed): stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}] r = _post(publish_env, {"job_id": "job1", "clip_index": 0, "platforms": ["tiktok"], "scheduled_date": "tomorrow"}) assert r.status_code == 400 def test_scheduled_window_is_widened_and_posts_are_normalised(publish_env, monkeypatch): captured = {} def list_posts(base, key, start, end, *a, **k): captured["start"], captured["end"] = start, end return [{"id": "p1", "date": "2026-01-05T00:00:00.000Z"}] monkeypatch.setattr(postiz, "list_posts", list_posts) r = _call(publish_env, "get", "/api/postiz/scheduled", headers=POSTIZ_HEADERS) assert r.status_code == 200, r.text assert r.json()["scheduled_posts"][0]["scheduled_date"] == \ "2026-01-05T00:00:00.000Z" start = datetime.fromisoformat(captured["start"].replace("Z", "+00:00")) end = datetime.fromisoformat(captured["end"].replace("Z", "+00:00")) assert (end - start) >= timedelta(days=89)