feat: 공유를 비율 고르기 + 공유하기 하나로 줄이고 이미지에 행사 사진·우리 주소 넣기
- 공유 이미지 9:16·4:5·1:1, 위 로고·지역 날짜 / 카드 / 아래 주소 알약 (시안 A) - 2장 카드는 한 이미지에 묶음, 버튼만 빼고 링크(장소)는 남김 - 웹폰트는 카드 글자에 필요한 조각만 data URL 로 넣어 글꼴이 안 깨지게 - 문구 고르기·링크 복사 제거, 공유하기 한 번에 이미지 + 제목·주소 글 - 행사 사진은 백엔드 /v1/image 가 대신 받음 (IMAGE_PROXY_HOSTS 만 허용) - 공유 주소는 VITE_SITE_URL 하나로
This commit is contained in:
1 parent
2fde88df27
commit
5e2846ff72
17 files changed
+432
-135
No files matched your search
@@ -28,6 +28,8 @@ class Settings(BaseSettings):
|
||||
|
||||
data_go_kr_service_key: str = ""
|
||||
teams_webhook_url: str = ""
|
||||
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
|
||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr"
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
@@ -40,6 +42,10 @@ class Settings(BaseSettings):
|
||||
"""인코딩 키를 넣어도 디코딩해 둔다. httpx 가 다시 인코딩하므로 이중 인코딩을 막는다."""
|
||||
return unquote(v) if "%" in v else v
|
||||
|
||||
@property
|
||||
def image_proxy_host_set(self) -> frozenset[str]:
|
||||
return frozenset(h.strip().lower() for h in self.image_proxy_hosts.split(",") if h.strip())
|
||||
|
||||
@property
|
||||
def db_url(self) -> str:
|
||||
return f"postgresql+asyncpg://{self.db_user}:{self.db_password}@{self.db_host}:{self.db_port}/{self.db_name}"
|
||||
|
||||
@@ -9,6 +9,7 @@ from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from router.v1.auth.account import router as auth_router
|
||||
from router.v1.feed.feed import router as feed_router
|
||||
from router.v1.image.image import router as image_router
|
||||
from router.v1.index.index import router as index_router
|
||||
from router.v1.reaction.reaction import router as reaction_router
|
||||
from router.v1.region.region import router as region_router
|
||||
@@ -41,6 +42,7 @@ app.include_router(feed_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(reaction_router)
|
||||
app.include_router(watch_router)
|
||||
app.include_router(image_router)
|
||||
|
||||
|
||||
class Res_Health(Res_WebPacketProtocol):
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,22 @@
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi.responses import Response
|
||||
|
||||
from common.logger import LOG
|
||||
from services.external.image_proxy import TIMEOUT_SEC, ImageFetchFailed, allowed, fetch_image
|
||||
|
||||
router = APIRouter(prefix="/v1/image", tags=["image"])
|
||||
|
||||
|
||||
# 이미지 자체를 돌려주므로 다른 API 와 달리 실패는 HTTP 상태 코드로 알린다
|
||||
@router.get("", summary="행사 사진 대신 받기 (공유 이미지용, 허용한 호스트만)", responses={200: {"content": {"image/*": {}}}, 400: {}, 502: {}})
|
||||
async def get_image(url: str = Query(..., max_length=2048, description="원본 이미지 주소")) -> Response:
|
||||
if not allowed(url):
|
||||
raise HTTPException(status_code=400, detail="url not allowed")
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=TIMEOUT_SEC, headers={"User-Agent": "nalssigak-bot"}) as client:
|
||||
data, ctype = await fetch_image(client, url)
|
||||
except (ImageFetchFailed, httpx.HTTPError) as e:
|
||||
LOG.warning(f"[image] fetch failed {url}: {e!r}")
|
||||
raise HTTPException(status_code=502, detail="image fetch failed") from e
|
||||
return Response(content=data, media_type=ctype, headers={"Cache-Control": "public, max-age=86400", "X-Content-Type-Options": "nosniff"})
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import httpx
|
||||
|
||||
from config.settings import settings
|
||||
|
||||
# 공유 이미지에 행사 사진을 그리려고 대신 받아 준다. 사진 서버가 브라우저가 픽셀을 읽는 것(CORS)을 막기 때문. 허용 호스트는 IMAGE_PROXY_HOSTS.
|
||||
MAX_BYTES = 5 * 1024 * 1024
|
||||
TIMEOUT_SEC = 10.0
|
||||
|
||||
|
||||
class ImageFetchFailed(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def allowed(url: str) -> bool:
|
||||
"""https, 허용한 호스트, 기본 포트, 계정 정보 없음일 때만."""
|
||||
try:
|
||||
u = urlsplit(url)
|
||||
port = u.port
|
||||
except ValueError:
|
||||
return False
|
||||
return u.scheme == "https" and u.hostname in settings.image_proxy_host_set and port in (None, 443) and not u.username and not u.password
|
||||
|
||||
|
||||
async def fetch_image(client: httpx.AsyncClient, url: str) -> tuple[bytes, str]:
|
||||
"""이미지 바이트와 content-type. 리다이렉트는 따라가지 않는다."""
|
||||
async with client.stream("GET", url, follow_redirects=False) as res:
|
||||
if res.status_code != 200:
|
||||
raise ImageFetchFailed(f"status {res.status_code}")
|
||||
ctype = res.headers.get("content-type", "").split(";")[0].strip().lower()
|
||||
if not ctype.startswith("image/") or ctype == "image/svg+xml":
|
||||
raise ImageFetchFailed(f"content-type {ctype or '-'}")
|
||||
buf = bytearray()
|
||||
async for chunk in res.aiter_bytes():
|
||||
buf += chunk
|
||||
if len(buf) > MAX_BYTES:
|
||||
raise ImageFetchFailed("too large")
|
||||
return bytes(buf), ctype
|
||||
@@ -0,0 +1,93 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
from services.external import image_proxy
|
||||
from services.external.image_proxy import ImageFetchFailed, allowed, fetch_image
|
||||
|
||||
OK_URL = "https://tong.visitkorea.or.kr/cms/resource/01/test_image.jpg"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url,ok", [
|
||||
(OK_URL, True),
|
||||
("https://www.culture.go.kr/upload/test.jpg", True),
|
||||
("http://tong.visitkorea.or.kr/cms/a.jpg", False),
|
||||
("https://evil.example.com/a.jpg", False),
|
||||
("https://tong.visitkorea.or.kr.evil.example.com/a.jpg", False),
|
||||
("https://tong.visitkorea.or.kr:8443/a.jpg", False),
|
||||
("https://user:pw@tong.visitkorea.or.kr/a.jpg", False),
|
||||
("https://169.254.169.254/latest/meta-data", False),
|
||||
("not a url", False),
|
||||
])
|
||||
def test_allowed(url, ok):
|
||||
assert allowed(url) is ok
|
||||
|
||||
|
||||
def _client(handler) -> httpx.AsyncClient:
|
||||
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_image_returns_bytes_and_type():
|
||||
async with _client(lambda r: httpx.Response(200, content=b"\xff\xd8jpeg", headers={"content-type": "image/jpeg; charset=binary"})) as c:
|
||||
assert await fetch_image(c, OK_URL) == (b"\xff\xd8jpeg", "image/jpeg")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("res", [
|
||||
httpx.Response(302, headers={"location": "https://evil.example.com/a.jpg"}),
|
||||
httpx.Response(404),
|
||||
httpx.Response(200, content=b"<html>", headers={"content-type": "text/html"}),
|
||||
httpx.Response(200, content=b"<svg/>", headers={"content-type": "image/svg+xml"}),
|
||||
])
|
||||
async def test_fetch_image_rejects_redirect_error_and_non_image(res):
|
||||
async with _client(lambda r: res) as c:
|
||||
with pytest.raises(ImageFetchFailed):
|
||||
await fetch_image(c, OK_URL)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_image_rejects_too_large(monkeypatch):
|
||||
monkeypatch.setattr(image_proxy, "MAX_BYTES", 10)
|
||||
async with _client(lambda r: httpx.Response(200, content=b"x" * 11, headers={"content-type": "image/png"})) as c:
|
||||
with pytest.raises(ImageFetchFailed):
|
||||
await fetch_image(c, OK_URL)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_image_api_blocks_other_hosts():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
|
||||
res = await c.get("/v1/image", params={"url": "https://evil.example.com/a.jpg"})
|
||||
assert res.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_image_api_serves_image_with_cache(monkeypatch):
|
||||
async def fake(_client, url):
|
||||
assert url == OK_URL
|
||||
return b"png-bytes", "image/png"
|
||||
monkeypatch.setattr("router.v1.image.image.fetch_image", fake)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
|
||||
res = await c.get("/v1/image", params={"url": OK_URL})
|
||||
assert res.status_code == 200
|
||||
assert res.content == b"png-bytes"
|
||||
assert res.headers["content-type"] == "image/png"
|
||||
assert "max-age=86400" in res.headers["cache-control"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_image_api_reports_upstream_failure(monkeypatch):
|
||||
async def fail(_client, _url):
|
||||
raise ImageFetchFailed("status 404")
|
||||
monkeypatch.setattr("router.v1.image.image.fetch_image", fail)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
|
||||
res = await c.get("/v1/image", params={"url": OK_URL})
|
||||
assert res.status_code == 502
|
||||
|
||||
|
||||
def test_allowed_follows_settings(monkeypatch):
|
||||
from config.settings import settings
|
||||
monkeypatch.setattr(settings, "image_proxy_hosts", " cdn.example.org , ")
|
||||
assert allowed("https://cdn.example.org/a.jpg") is True
|
||||
assert allowed(OK_URL) is False
|
||||
Reference in new issue
Block a user