"""긴급 공지 — 검증(본문 정리·이미지 형식·시각·받는 사람)과 API 권한(수퍼관리자만 만들기, 받는 사람만 확인·이미지). DB 없이.""" import importlib import sys import types import unittest from datetime import datetime, timedelta from unittest.mock import patch from fastapi import FastAPI from fastapi.testclient import TestClient from app.modules.notice import store from app.store import SUPER_ADMIN_EMAIL from app.timezone import KST api = importlib.import_module("app.modules.notice.router") SUPER = {"email": SUPER_ADMIN_EMAIL, "name": "King", "is_super_admin": True} ADMIN = {"email": "admin@test.local", "role": "admin"} BOB = {"email": "bob@test.local"} PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 20 class ValidationTests(unittest.TestCase): def test_body_keeps_only_notice_images(self): html = ('

점검 안내

a' 'x') out = store.sanitize_body(html) self.assertIn('/notice/images/7', out) self.assertNotIn("evil.example", out) self.assertNotIn("data:image", out) self.assertNotIn("안내", out) self.assertEqual(store.image_ids_in(out), [7]) def test_title_targets_time(self): with self.assertRaises(ValueError): store.validate_title(" ") with self.assertRaises(ValueError): store.validate_title("x" * 201) self.assertEqual(store.validate_targets(True, ["a@b"]), (True, [])) self.assertEqual(store.validate_targets(False, ["A@Test.local", "a@test.local", "nope"]), (False, ["a@test.local"])) with self.assertRaises(ValueError): store.validate_targets(False, []) d = store.parse_show_at("2026-10-12T18:30") self.assertEqual((d.hour, d.minute, d.utcoffset()), (18, 30, timedelta(hours=9))) # 화면 입력 = 한국시간 self.assertEqual(store.parse_show_at("2026-10-12T09:30:00Z").astimezone(KST).hour, 18) self.assertLess(abs((store.parse_show_at("") - datetime.now(KST)).total_seconds()), 5) with self.assertRaises(ValueError): store.parse_show_at("내일") def test_image_sniffing(self): self.assertEqual(store.sniff_image(PNG), "image/png") self.assertEqual(store.sniff_image(b"\xff\xd8\xff\xe0abc"), "image/jpeg") self.assertEqual(store.sniff_image(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp") for bad in (b"", b"", b"", b"\x89PNG" + b"0" * (store.IMAGE_MAX_BYTES)): with self.assertRaises(ValueError): store.sniff_image(bad) class FakeStore: def __init__(self): now = datetime.now(KST) self.notices = { 1: {"id": 1, "title": "전체 공지", "body_html": "

x

", "show_at": now.isoformat(), "to_all": True, "created_by": SUPER_ADMIN_EMAIL, "cancelled_at": "", "targets": []}, 2: {"id": 2, "title": "일부", "body_html": "", "show_at": now.isoformat(), "to_all": False, "created_by": SUPER_ADMIN_EMAIL, "cancelled_at": "", "targets": ["carol@test.local"]}, 3: {"id": 3, "title": "예약", "body_html": "", "show_at": (now + timedelta(hours=1)).isoformat(), "to_all": True, "created_by": SUPER_ADMIN_EMAIL, "cancelled_at": "", "targets": []}, } self.images = {5: {"id": 5, "notice_id": 2, "content_type": "image/png", "data": PNG, "uploaded_by": SUPER_ADMIN_EMAIL}, 6: {"id": 6, "notice_id": 3, "content_type": "image/png", "data": PNG, "uploaded_by": SUPER_ADMIN_EMAIL}} self.acked, self.created = [], [] def enabled(self): return True def pending_for(self, email): return [n for n in self.notices.values() if self.is_recipient(notice=n, email=email)] def get_notice(self, notice_id): return self.notices.get(notice_id) def is_recipient(self, notice, email): return notice["to_all"] or email in notice["targets"] def ack(self, notice_id, email, version=None): """저장소 계약(검토 F07·F08) — 받는 사람·표시 시각·취소·내용 버전은 저장소가 판단(실제 판단은 test_notice_db).""" n = self.notices.get(notice_id) if n is None or n["cancelled_at"] or not self.is_recipient(notice=n, email=email) \ or datetime.fromisoformat(n["show_at"]) > datetime.now(KST): return "denied" if version and version != n.get("version", ""): return "stale" self.acked.append((notice_id, email)) return "acked" def list_notices(self): return [{**n, "acks": {}} for n in self.notices.values()] def create_notice(self, **kw): self.created.append(kw) store.validate_title(kw["title"]) return {"id": 9, **kw} def get_image(self, image_id): return self.images.get(image_id) def add_image(self, data, filename, by): return {"id": 10, "url": "/notice/images/10", "content_type": store.sniff_image(data)} class NoticeApiTests(unittest.TestCase): def setUp(self): app = FastAPI() app.include_router(api.router) self.st = FakeStore() app.state.notice_store = self.st self.client = TestClient(app) def as_(self, who): fake = types.ModuleType("app.main") fake.get_current_user_record = lambda request: who return patch.dict(sys.modules, {"app.main": fake}) def test_only_super_admin_manages(self): body = {"title": "t", "body_html": "", "to_all": True} for who in (ADMIN, BOB): with self.as_(who): self.assertEqual(self.client.post("/notice/api/notices", json=body).status_code, 403) self.assertEqual(self.client.get("/notice/api/notices").status_code, 403) self.assertEqual(self.client.post("/notice/api/images", files={"file": ("a.png", PNG, "image/png")}).status_code, 403) with self.as_(SUPER): self.assertEqual(self.client.post("/notice/api/notices", json=body).status_code, 201) self.assertEqual(self.client.post("/notice/api/notices", json={"title": ""}).status_code, 400) r = self.client.post("/notice/api/images", files={"file": ("a.png", PNG, "image/png")}) self.assertEqual((r.status_code, r.json()["image"]["url"]), (201, "/notice/images/10")) self.assertEqual(self.client.post("/notice/api/images", files={"file": ("x.svg", b"", "image/svg+xml")}).status_code, 400) with self.as_(None): self.assertEqual(self.client.get("/notice/api/pending").status_code, 401) def test_pending_hides_admin_fields_and_ack_only_for_recipients(self): with self.as_(BOB): out = self.client.get("/notice/api/pending").json()["notices"] self.assertEqual(sorted(n["id"] for n in out), [1, 3]) # 시각 판단은 저장소(실제 DB 테스트) # 받는 사람 목록·확인 현황 없음, 내용 버전(version)은 보낸다(고친 공지를 다시 그리게, 검토 F07) self.assertEqual(set(out[0]), {"id", "title", "body_html", "show_at", "created_by", "version"}) self.assertEqual(self.client.post("/notice/api/1/ack").status_code, 200) self.assertEqual(self.client.post("/notice/api/2/ack").status_code, 404) # 받는 사람 아님 self.assertEqual(self.client.post("/notice/api/3/ack").status_code, 404) # 띄울 시각 전(예약) — 검토 F08 self.assertEqual(self.client.post("/notice/api/99/ack").status_code, 404) self.st.notices[1]["version"] = "v2" r = self.client.post("/notice/api/1/ack", json={"version": "v1"}) # 고치기 전 내용을 읽고 누름 self.assertEqual(r.status_code, 409) self.assertIn("수정", r.json()["detail"]) self.st.notices[1]["cancelled_at"] = "2026-10-15T10:00+09:00" self.assertEqual(self.client.post("/notice/api/1/ack").status_code, 404) # 취소된 공지 self.assertEqual(self.st.acked, [(1, "bob@test.local")]) def test_image_access(self): with self.as_(BOB): self.assertEqual(self.client.get("/notice/images/5").status_code, 404) # 받는 사람이 아닌 공지 self.assertEqual(self.client.get("/notice/images/6").status_code, 404) # 아직 띄울 시각 전 with self.as_({"email": "carol@test.local"}): r = self.client.get("/notice/images/5") self.assertEqual((r.status_code, r.headers["content-type"], r.headers["x-content-type-options"]), (200, "image/png", "nosniff")) with self.as_(SUPER): self.assertEqual(self.client.get("/notice/images/6").status_code, 200) def test_not_configured_is_503(self): self.client.app.state.notice_store = None with self.as_(BOB): self.assertEqual(self.client.get("/notice/api/pending").status_code, 503) if __name__ == "__main__": unittest.main()