Files
dbx-main/tests/test_notice.py
T
king 2aa6b6efae feat(notice): urgent notices centered on every ERP screen until acknowledged
- Super admin only: /notice/ page (title, body with images, show time KST, all or picked people,
  preview, edit with optional re-show, cancel/undo, per-person acknowledgement status)
- Shown on every ERP page (erp_base, main, admin) dead center; [확인] only (no Esc/backdrop close),
  queue in order, ack failure keeps the dialog, closes when acked/cancelled elsewhere
- project_db migration 024 (urgent_notices, targets, acks, images as bytea); shares ProjectStore.pool
- Body sanitized like task descriptions, images restricted to /notice/images/{id}, type sniffed
- Entry points: ERP sidebar foot and Project options dialog (super admin)
- Docs (NOTICE_MODULE, DEPLOYMENT 024, overview, CLAUDE.md); tests (DB-less, real PostgreSQL, jsdom)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:07:10 +09:00

165 lines
7.9 KiB
Python

"""긴급 공지 — 검증(본문 정리·이미지 형식·시각·받는 사람)과 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 = ('<p>점검 <b>안내</b></p><img src="/notice/images/7" alt="a"><img src="https://evil.example/x.png">'
'<img src="data:image/png;base64,AAAA"><script>alert(1)</script><a href="javascript:alert(1)">x</a>')
out = store.sanitize_body(html)
self.assertIn('/notice/images/7', out)
self.assertNotIn("evil.example", out)
self.assertNotIn("data:image", out)
self.assertNotIn("<script", out)
self.assertNotIn("javascript:", out)
self.assertIn("<b>안내</b>", 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"<svg onload=alert(1)>", b"<html>", 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": "<p>x</p>", "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):
self.acked.append((notice_id, email))
return True
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"<svg/>", "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 테스트)
self.assertEqual(set(out[0]), {"id", "title", "body_html", "show_at", "created_by"}) # 받는 사람 목록·확인 현황 없음
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/99/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()