CenaForge: primeira versão pública
Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
"""OAuth: state de uso único com validade, PKCE (base64url no Google, HEX no TikTok), troca do code e refresh."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import time
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.platforms.base import challenge_s256_base64url, challenge_s256_hex, make_verifier
|
||||
|
||||
YT = "canal--youtube"
|
||||
TT = "canal--tiktok"
|
||||
|
||||
|
||||
def _configure(env, platform):
|
||||
env.client.put(f"/v1/apps/{platform}", json={"clientId": f"{platform}-id", "clientSecret": f"{platform}-secret"})
|
||||
|
||||
|
||||
def _connect(env, pid, platform):
|
||||
body = env.client.post(f"/v1/profiles/{pid}/connect", json={"platform": platform, "mode": "official"}).json()
|
||||
assert body["next"]["kind"] == "open_url"
|
||||
return parse_qs(urlparse(body["next"]["url"]).query), body
|
||||
|
||||
|
||||
def test_pkce_helpers():
|
||||
verifier = make_verifier()
|
||||
assert 43 <= len(verifier) <= 128
|
||||
digest = hashlib.sha256(verifier.encode()).digest()
|
||||
assert challenge_s256_hex(verifier) == digest.hex()
|
||||
assert len(challenge_s256_hex(verifier)) == 64 and all(c in "0123456789abcdef" for c in challenge_s256_hex(verifier))
|
||||
assert challenge_s256_base64url(verifier) == base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
|
||||
|
||||
|
||||
def test_youtube_full_flow(env):
|
||||
_configure(env, "youtube")
|
||||
query, body = _connect(env, YT, "youtube")
|
||||
assert body["profile"]["status"] == "connecting"
|
||||
assert query["redirect_uri"] == ["http://127.0.0.1:4530/oauth/callback/youtube"]
|
||||
assert query["code_challenge_method"] == ["S256"] and query["access_type"] == ["offline"]
|
||||
assert "youtube.upload" in query["scope"][0]
|
||||
state = query["state"][0]
|
||||
assert env.db.get("SELECT verifier FROM oauth_states WHERE state = ?", state)["verifier"] == "" # nunca no disco
|
||||
verifier = env.publisher._verifiers[state]
|
||||
assert query["code_challenge"] == [challenge_s256_base64url(verifier)]
|
||||
|
||||
env.router.add("POST", "https://oauth2.googleapis.com/token",
|
||||
{"access_token": "ya29.a", "expires_in": 3599, "refresh_token": "1//r"})
|
||||
env.router.add("GET", "https://www.googleapis.com/youtube/v3/channels",
|
||||
{"items": [{"id": "UC1", "snippet": {"title": "Histórias do Litoral", "customUrl": "@litoral"}}]})
|
||||
browser = TestClient(env.app) # o navegador do usuário não manda a chave do serviço
|
||||
page = browser.get(f"/oauth/callback/youtube?state={state}&code=4/abc")
|
||||
assert page.status_code == 200 and 'lang="pt-BR"' in page.text
|
||||
assert "Pode fechar esta aba e voltar ao painel." in page.text and "@litoral" in page.text
|
||||
|
||||
sent = parse_qs(env.router.find("POST", "https://oauth2.googleapis.com/token")[0].content.decode())
|
||||
assert sent["code_verifier"] == [verifier] and sent["grant_type"] == ["authorization_code"]
|
||||
assert sent["client_secret"] == ["youtube-secret"]
|
||||
profile = env.client.get(f"/v1/profiles/{YT}").json()
|
||||
assert profile["status"] == "connected" and profile["handle"] == "@litoral"
|
||||
assert profile["displayName"] == "Histórias do Litoral" and profile["expiresAt"] is None
|
||||
assert env.vault.get(f"token:{YT}")["refreshToken"] == "1//r"
|
||||
|
||||
# uso único
|
||||
again = browser.get(f"/oauth/callback/youtube?state={state}&code=4/abc")
|
||||
assert again.status_code == 400 and "já foi usado" in again.text
|
||||
|
||||
|
||||
def test_state_expired_wrong_platform_and_denied(env):
|
||||
_configure(env, "youtube")
|
||||
query, _ = _connect(env, YT, "youtube")
|
||||
state = query["state"][0]
|
||||
browser = TestClient(env.app)
|
||||
assert "não é válido" in browser.get(f"/oauth/callback/tiktok?state={state}&code=x").text
|
||||
assert "não é válido" in browser.get("/oauth/callback/youtube?state=inventado&code=x").text
|
||||
env.db.run("UPDATE oauth_states SET expires_at = ? WHERE state = ?", time.time() - 1, state)
|
||||
expired = browser.get(f"/oauth/callback/youtube?state={state}&code=x")
|
||||
assert expired.status_code == 400 and "expirou" in expired.text
|
||||
|
||||
query, _ = _connect(env, YT, "youtube")
|
||||
denied = browser.get(f"/oauth/callback/youtube?state={query['state'][0]}&error=access_denied")
|
||||
assert denied.status_code == 400 and "não autorizou" in denied.text
|
||||
assert env.client.get(f"/v1/profiles/{YT}").json()["status"] == "error"
|
||||
|
||||
|
||||
def test_google_invalid_grant_marks_error(env):
|
||||
_configure(env, "youtube")
|
||||
query, _ = _connect(env, YT, "youtube")
|
||||
env.router.add("POST", "https://oauth2.googleapis.com/token",
|
||||
lambda r: httpx.Response(400, json={"error": "invalid_grant"}))
|
||||
page = TestClient(env.app).get(f"/oauth/callback/youtube?state={query['state'][0]}&code=x")
|
||||
assert page.status_code == 400 and "In production" in page.text
|
||||
|
||||
|
||||
def test_tiktok_hex_challenge_and_callback(env):
|
||||
_configure(env, "tiktok")
|
||||
query, _ = _connect(env, TT, "tiktok")
|
||||
assert query["client_key"] == ["tiktok-id"]
|
||||
assert query["scope"] == ["user.info.basic,video.upload,video.publish"]
|
||||
assert query["redirect_uri"] == ["http://127.0.0.1:4530/oauth/callback/tiktok"]
|
||||
state = query["state"][0]
|
||||
assert env.db.get("SELECT verifier FROM oauth_states WHERE state = ?", state)["verifier"] == "" # nunca no disco
|
||||
verifier = env.publisher._verifiers[state]
|
||||
assert query["code_challenge"] == [hashlib.sha256(verifier.encode()).hexdigest()]
|
||||
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/oauth/token/", {
|
||||
"access_token": "act.1", "expires_in": 7200, "open_id": "o1", "refresh_token": "rft.1",
|
||||
"refresh_expires_in": 15552000, "scope": "user.info.basic,video.upload,video.publish", "token_type": "Bearer"})
|
||||
env.router.add("GET", "https://open.tiktokapis.com/v2/user/info/", {"data": {"user": {"display_name": "Litoral"}}})
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/creator_info/query/",
|
||||
{"data": {"creator_username": "litoral", "creator_nickname": "Litoral"}, "error": {"code": "ok"}})
|
||||
page = TestClient(env.app).get(f"/oauth/callback/tiktok?state={state}&code=c*1!")
|
||||
assert page.status_code == 200, page.text
|
||||
sent = parse_qs(env.router.find("POST", "https://open.tiktokapis.com/v2/oauth/token/")[0].content.decode())
|
||||
assert sent["code_verifier"] == [verifier] and sent["client_key"] == ["tiktok-id"] and sent["code"] == ["c*1!"]
|
||||
profile = env.client.get(f"/v1/profiles/{TT}").json()
|
||||
assert profile["status"] == "connected" and profile["handle"] == "@litoral" and profile["expiresAt"]
|
||||
|
||||
|
||||
def test_tiktok_refresh_is_rotated_and_saved(env):
|
||||
_configure(env, "tiktok")
|
||||
env.connect_profile(TT, secret={"accessToken": "old", "accessExpiresAt": time.time() - 10,
|
||||
"refreshToken": "rft.old", "refreshExpiresAt": time.time() + 1000})
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/oauth/token/", {
|
||||
"access_token": "act.new", "expires_in": 7200, "open_id": "o1", "refresh_token": "rft.new",
|
||||
"refresh_expires_in": 15552000})
|
||||
token = env.publisher._token_provider(TT, "tiktok")(False)
|
||||
assert token == "act.new"
|
||||
sent = parse_qs(env.router.requests[-1].content.decode())
|
||||
assert sent["grant_type"] == ["refresh_token"] and sent["refresh_token"] == ["rft.old"]
|
||||
saved = env.vault.get(f"token:{TT}")
|
||||
assert saved["refreshToken"] == "rft.new" and saved["accessToken"] == "act.new"
|
||||
# access ainda válido: não renova de novo
|
||||
assert env.publisher._token_provider(TT, "tiktok")(False) == "act.new"
|
||||
assert len(env.router.requests) == 1
|
||||
|
||||
|
||||
def test_expired_refresh_marks_profile_expired(env):
|
||||
_configure(env, "tiktok")
|
||||
env.connect_profile(TT, secret={"accessToken": "old", "accessExpiresAt": 0, "refreshToken": "r",
|
||||
"refreshExpiresAt": time.time() - 1}, expires_at="2020-01-01T00:00:00Z")
|
||||
assert env.client.get(f"/v1/profiles/{TT}").json()["status"] == "expired"
|
||||
|
||||
|
||||
def test_youtube_refresh_invalid_grant_is_expired(env):
|
||||
_configure(env, "youtube")
|
||||
env.connect_profile(YT, secret={"accessToken": "a", "accessExpiresAt": 0, "refreshToken": "r"})
|
||||
env.router.add("POST", "https://oauth2.googleapis.com/token", lambda r: httpx.Response(400, json={"error": "invalid_grant"}))
|
||||
video = env.video()
|
||||
env.client.post("/v1/jobs", json=env.job_body(YT, video))
|
||||
env.worker.run_once()
|
||||
job = env.db.get("SELECT * FROM jobs")
|
||||
assert job["status"] == "needs_login" and "Conecte o YouTube de novo" in job["error"]
|
||||
assert env.client.get(f"/v1/profiles/{YT}").json()["status"] == "expired"
|
||||
Reference in New Issue
Block a user