Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
313 lines
12 KiB
Python
313 lines
12 KiB
Python
"""Anonymous reel preview: service (injected fetchers, no live network) +
|
|
endpoint (DB-backed, Turnstile soft/hard modes, rate limit, claim auth).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json as json_mod
|
|
from contextlib import contextmanager
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
from fastapi import FastAPI
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
from sqlalchemy.pool import StaticPool
|
|
from starlette.responses import JSONResponse
|
|
from starlette.testclient import TestClient
|
|
|
|
from app.domains.reel_preview import router as reel_preview_mod
|
|
from app.domains.reel_preview.service import (
|
|
ReelPreviewError,
|
|
build_preview,
|
|
claim_preview,
|
|
url_hash_of,
|
|
)
|
|
from app.models.db.base import Base
|
|
from app.models.db.anon_preview import AnonPreview
|
|
from app.models.db.models import User
|
|
from app.models.exception import HttpException
|
|
from app.services import ratelimit as ratelimit_mod
|
|
from app.services import turnstile as turnstile_mod
|
|
from app.utils import utils
|
|
|
|
ITUNES_PAYLOAD = {
|
|
"results": [{
|
|
"kind": "software",
|
|
"trackName": "CalDesk AI: Calorie Counter",
|
|
"sellerName": "Umut Arhan Suba",
|
|
"description": "Track calories and macros fast with AI photo scanning.",
|
|
"artworkUrl512": "https://is1.mzstatic.com/icon512.png",
|
|
"screenshotUrls": [f"https://is1.mzstatic.com/s{i}.png" for i in range(3)],
|
|
"primaryGenreName": "Health & Fitness",
|
|
"trackViewUrl": "https://apps.apple.com/us/app/caldesk/id6780166477",
|
|
}],
|
|
}
|
|
|
|
_WEBSITE_HTML = """
|
|
<html><head>
|
|
<title>Acme Focus — the calm to-do app</title>
|
|
<meta name="description" content="Acme Focus helps you finish deep work without burnout.">
|
|
<meta property="og:image" content="/social-card.png">
|
|
</head><body>
|
|
<h1>Acme Focus</h1>
|
|
<ul><li>One task at a time</li></ul>
|
|
</body></html>
|
|
"""
|
|
|
|
|
|
def _fake_generate(_prompt: str) -> str:
|
|
return json_mod.dumps({"pov": "POV: you finally finish deep work without burning out."})
|
|
|
|
|
|
@contextmanager
|
|
def _sqlite_session():
|
|
engine = create_engine(
|
|
"sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool, future=True
|
|
)
|
|
Base.metadata.create_all(engine)
|
|
Factory = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False, future=True)
|
|
with Factory() as s:
|
|
yield s
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Pure service (injected fetchers, no live network)
|
|
# --------------------------------------------------------------------------- #
|
|
def test_build_preview_app_store_uses_real_screenshots():
|
|
def getter(url: str, **kwargs):
|
|
assert "lookup" in url
|
|
return SimpleNamespace(text=lambda: json_mod.dumps(ITUNES_PAYLOAD))
|
|
|
|
with _sqlite_session() as session:
|
|
data = build_preview(
|
|
"https://apps.apple.com/us/app/caldesk/id6780166477",
|
|
session=session,
|
|
remote_ip="1.2.3.4",
|
|
getter=getter,
|
|
generate=_fake_generate,
|
|
)
|
|
assert data["source_kind"] == "app_store"
|
|
assert data["title"] == "CalDesk AI: Calorie Counter"
|
|
assert data["frames"] == [f"https://is1.mzstatic.com/s{i}.png" for i in range(3)]
|
|
assert data["hook"]["line"].startswith("POV:")
|
|
assert data["hook"]["source"] == "model"
|
|
assert data["preset_id"] == "gameplay_split"
|
|
assert data["cached"] is False
|
|
|
|
|
|
def test_build_preview_website_uses_og_image_and_resolves_relative_url():
|
|
with _sqlite_session() as session:
|
|
data = build_preview(
|
|
"https://acme.example/product",
|
|
session=session,
|
|
fetcher=lambda _u: _WEBSITE_HTML,
|
|
generate=_fake_generate,
|
|
)
|
|
assert data["source_kind"] == "website"
|
|
assert data["title"] == "Acme Focus — the calm to-do app"
|
|
assert data["frames"] == ["https://acme.example/social-card.png"]
|
|
|
|
|
|
def test_build_preview_caches_by_url_no_second_fetch():
|
|
calls = {"n": 0}
|
|
|
|
def fetcher(_u: str) -> str:
|
|
calls["n"] += 1
|
|
return _WEBSITE_HTML
|
|
|
|
with _sqlite_session() as session:
|
|
first = build_preview(
|
|
"https://acme.example/same-page", session=session, fetcher=fetcher, generate=_fake_generate
|
|
)
|
|
second = build_preview(
|
|
"https://acme.example/same-page", session=session, fetcher=fetcher, generate=_fake_generate
|
|
)
|
|
assert calls["n"] == 1 # the second call was served from the cache
|
|
assert first["preview_id"] == second["preview_id"]
|
|
assert first["cached"] is False
|
|
assert second["cached"] is True
|
|
|
|
|
|
def test_build_preview_rejects_empty_url():
|
|
with _sqlite_session() as session:
|
|
with pytest.raises(ReelPreviewError) as exc_info:
|
|
build_preview("", session=session)
|
|
assert exc_info.value.status_code == 400
|
|
|
|
|
|
def test_build_preview_website_without_usable_content_422():
|
|
with _sqlite_session() as session:
|
|
with pytest.raises(ReelPreviewError) as exc_info:
|
|
build_preview(
|
|
"https://acme.example/empty", session=session, fetcher=lambda _u: "<html></html>"
|
|
)
|
|
assert exc_info.value.status_code == 422
|
|
|
|
|
|
def test_claim_preview_first_claim_wins_and_is_idempotent():
|
|
with _sqlite_session() as session:
|
|
built = build_preview(
|
|
"https://acme.example/claim-me", session=session, fetcher=lambda _u: _WEBSITE_HTML, generate=_fake_generate
|
|
)
|
|
first = claim_preview(built["preview_id"], "user-a", session=session)
|
|
second = claim_preview(built["preview_id"], "user-b", session=session)
|
|
row = session.query(AnonPreview).filter(AnonPreview.id == built["preview_id"]).first()
|
|
assert first is not None and second is not None
|
|
assert row.claimed_user_id == "user-a" # first claim wins; the second call did not overwrite it
|
|
|
|
|
|
def test_claim_preview_not_found_returns_none():
|
|
with _sqlite_session() as session:
|
|
assert claim_preview("does-not-exist", "user-a", session=session) is None
|
|
|
|
|
|
def test_url_hash_is_case_and_whitespace_insensitive():
|
|
assert url_hash_of("https://Acme.example/x ") == url_hash_of(" https://acme.example/x")
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Turnstile (soft no-op when unconfigured; fail-closed once configured)
|
|
# --------------------------------------------------------------------------- #
|
|
def test_turnstile_soft_mode_when_unconfigured(monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.delenv("TURNSTILE_SECRET_KEY", raising=False)
|
|
assert turnstile_mod.turnstile_configured() is False
|
|
assert turnstile_mod.verify_turnstile("", "1.2.3.4") is True # no token needed yet
|
|
|
|
|
|
def test_turnstile_fails_closed_on_missing_token_once_configured(monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setenv("TURNSTILE_SECRET_KEY", "fake-secret")
|
|
assert turnstile_mod.turnstile_configured() is True
|
|
assert turnstile_mod.verify_turnstile("", "1.2.3.4") is False
|
|
|
|
|
|
def test_turnstile_passes_on_real_success(monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setenv("TURNSTILE_SECRET_KEY", "fake-secret")
|
|
|
|
class _Resp:
|
|
def json(self):
|
|
return {"success": True}
|
|
|
|
monkeypatch.setattr(turnstile_mod.requests, "post", lambda *a, **k: _Resp())
|
|
assert turnstile_mod.verify_turnstile("real-token", "1.2.3.4") is True
|
|
|
|
|
|
def test_turnstile_fails_closed_on_network_error(monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setenv("TURNSTILE_SECRET_KEY", "fake-secret")
|
|
|
|
def _boom(*a, **k):
|
|
raise OSError("network down")
|
|
|
|
monkeypatch.setattr(turnstile_mod.requests, "post", _boom)
|
|
assert turnstile_mod.verify_turnstile("real-token", "1.2.3.4") is False
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Endpoint
|
|
# --------------------------------------------------------------------------- #
|
|
@pytest.fixture()
|
|
def client(monkeypatch):
|
|
engine = create_engine(
|
|
"sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool, future=True
|
|
)
|
|
Base.metadata.create_all(engine)
|
|
Factory = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False, future=True)
|
|
with Factory() as s:
|
|
s.add(User(email="a@example.com", api_key_hash=hashlib.sha256(b"k").hexdigest()))
|
|
s.commit()
|
|
|
|
@contextmanager
|
|
def _gs():
|
|
s = Factory()
|
|
try:
|
|
yield s
|
|
s.commit()
|
|
finally:
|
|
s.close()
|
|
|
|
import app.core.api_dependencies as deps
|
|
|
|
monkeypatch.setattr(deps, "get_session", _gs)
|
|
monkeypatch.setattr(reel_preview_mod, "get_session", _gs)
|
|
monkeypatch.setenv("APP_API_KEY", "")
|
|
# Force the in-process fallback bucket (this box may have a real local
|
|
# Redis reachable, whose counters would otherwise leak across tests).
|
|
ratelimit_mod.reset_local_buckets()
|
|
monkeypatch.setattr(ratelimit_mod, "_get_client", lambda: None)
|
|
|
|
import app.domains.reel_preview.service as service_mod
|
|
|
|
monkeypatch.setattr(service_mod, "write_hooks", lambda **kw: [{"hook_style": "pov", "hook": "POV: it just works.", "source": "model"}])
|
|
|
|
app = FastAPI()
|
|
app.include_router(reel_preview_mod.router)
|
|
|
|
def _http_handler(_request, exc: HttpException):
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content=utils.get_response(exc.status_code, exc.data, exc.message),
|
|
)
|
|
|
|
app.add_exception_handler(HttpException, _http_handler)
|
|
return TestClient(app)
|
|
|
|
|
|
def test_preview_endpoint_public_no_auth_needed(client, monkeypatch):
|
|
monkeypatch.delenv("TURNSTILE_SECRET_KEY", raising=False)
|
|
monkeypatch.setattr(
|
|
"app.domains.reel_preview.service.fetch_website", lambda _u: _WEBSITE_HTML
|
|
)
|
|
resp = client.post("/api/v1/public/reel-preview", json={"url": "https://acme.example/pub"})
|
|
assert resp.status_code == 200, resp.text
|
|
body = resp.json()["data"]
|
|
assert body["frames"] == ["https://acme.example/social-card.png"]
|
|
|
|
|
|
def test_preview_endpoint_rate_limited_after_threshold(client, monkeypatch):
|
|
monkeypatch.delenv("TURNSTILE_SECRET_KEY", raising=False)
|
|
monkeypatch.setattr(
|
|
"app.domains.reel_preview.service.fetch_website", lambda _u: _WEBSITE_HTML
|
|
)
|
|
last = None
|
|
for i in range(reel_preview_mod._RATE_LIMIT + 1):
|
|
last = client.post(
|
|
"/api/v1/public/reel-preview", json={"url": f"https://acme.example/rl-{i}"}
|
|
)
|
|
assert last.status_code == 429
|
|
|
|
|
|
def test_preview_endpoint_requires_turnstile_once_configured(client, monkeypatch):
|
|
monkeypatch.setenv("TURNSTILE_SECRET_KEY", "fake-secret")
|
|
resp = client.post("/api/v1/public/reel-preview", json={"url": "https://acme.example/needs-token"})
|
|
assert resp.status_code == 403
|
|
|
|
|
|
def test_claim_endpoint_requires_auth(client):
|
|
resp = client.post("/api/v1/reel-preview/claim", json={"preview_id": "whatever"})
|
|
assert resp.status_code == 401
|
|
|
|
|
|
def test_claim_endpoint_claims_with_valid_api_key(client, monkeypatch):
|
|
monkeypatch.delenv("TURNSTILE_SECRET_KEY", raising=False)
|
|
monkeypatch.setattr(
|
|
"app.domains.reel_preview.service.fetch_website", lambda _u: _WEBSITE_HTML
|
|
)
|
|
created = client.post(
|
|
"/api/v1/public/reel-preview", json={"url": "https://acme.example/claim-flow"}
|
|
).json()["data"]
|
|
resp = client.post(
|
|
"/api/v1/reel-preview/claim",
|
|
json={"preview_id": created["preview_id"]},
|
|
headers={"x-api-key": "k"},
|
|
)
|
|
assert resp.status_code == 200, resp.text
|
|
assert resp.json()["data"]["preview_id"] == created["preview_id"]
|
|
|
|
|
|
def test_claim_endpoint_404_for_unknown_id(client):
|
|
resp = client.post(
|
|
"/api/v1/reel-preview/claim", json={"preview_id": "nope"}, headers={"x-api-key": "k"}
|
|
)
|
|
assert resp.status_code == 404
|