diff --git a/.env.example b/.env.example index d5959db..0b06ecc 100644 --- a/.env.example +++ b/.env.example @@ -19,7 +19,8 @@ SMTP_PASSWORD= MAIL_FROM=noreply@zhiwu-project.sthkm3.org # ---- 管理員(UID 00000000)---- -# 登入框的信箱欄輸入 ADMIN_LOGIN,驗證碼用 Aegis 等 TOTP App 算(SHA1、6 位、30 秒) +# ADMIN_LOGIN 要是信箱格式(不會寄信,用猜不到的前綴、不要用任何使用者的信箱) +# 登入框的信箱欄輸入它,驗證碼用 Aegis 等 TOTP App 算(SHA1、6 位、30 秒) # ADMIN_TOTP 是 base32 密鑰;兩個都留空 = 停用管理員登入。改完執行 docker compose up -d # 換手機時:docker compose exec zhiwuproject python -m app.admin totp-uri ADMIN_LOGIN= diff --git a/make.md b/make.md index 49379de..c8476cf 100644 --- a/make.md +++ b/make.md @@ -68,7 +68,7 @@ python -m venv .venv | `TUNNEL_NETWORK` | cloudflared 所在的 Docker 網路 | | `SMTP_HOST`、`SMTP_PORT`、`SMTP_USER`、`SMTP_PASSWORD` | 寄驗證碼的信箱服務。465 用 SSL,其他用 STARTTLS | | `MAIL_FROM` | 寄件人,網域要在寄信服務驗證過 | -| `ADMIN_LOGIN`、`ADMIN_TOTP` | 管理員登入用的名稱與 base32 密鑰,兩個都留空就停用。登入時在信箱欄輸入名稱,驗證碼用 Aegis 等 TOTP App 看 | +| `ADMIN_LOGIN`、`ADMIN_TOTP` | 管理員登入用的名稱與 base32 密鑰,兩個都留空就停用。名稱要是信箱格式(不會寄信),前綴用猜不到的字,不要用任何使用者的信箱。登入時在信箱欄輸入它,驗證碼用 Aegis 等 TOTP App 看 | 產生一組 `ADMIN_TOTP`: @@ -84,4 +84,15 @@ python -c "import base64, secrets; print(base64.b32encode(secrets.token_bytes(20 不要直接把容器的 port 開到外網:限流會信任 `CF-Connecting-IP`,繞過 Cloudflare 就能偽造。 -資料在 `/data`(資料庫、大頭貼、投稿、小卡快取),圖庫在 `/memes`,這兩個要掛出來並備份。程式只能跑一個 worker,限流和冷靜時間都記在記憶體。 +資料在 `/data`(資料庫、大頭貼、投稿、小卡快取),圖庫在 `/memes`,這兩個要掛出來並備份。 + +容器用 UID/GID **3007:3004** 執行(不是 root),掛進來的資料夾要給它: + +``` +chown -R 3007:3004 <資料夾> +chmod -R u=rwX,go= <資料夾> +``` + +也可以用 Docker 的 `user` 設定換成別的 UID,資料夾的擁有者一起換就好。從以 root 執行的舊版升級時也要做一次;資料夾不能讀寫時,啟動的 log 會寫要怎麼改。 + +程式只能跑一個 worker,限流和冷靜時間都記在記憶體。 diff --git a/server/Dockerfile b/server/Dockerfile index d80436e..2af905c 100644 --- a/server/Dockerfile +++ b/server/Dockerfile @@ -18,5 +18,10 @@ COPY web ./web ENV DATA_DIR=/data MEME_DIR=/memes WEB_DIR=/app/web EXPOSE 2040 +# 不用 root 執行。掛進來的 /data、/memes 要給這個 UID(或用 docker 的 user 設定換成別的 UID) +RUN groupadd -g 3004 zhiwu && useradd -u 3007 -g 3004 -M -s /usr/sbin/nologin zhiwu \ + && mkdir -p /data /memes && chown 3007:3004 /data /memes +USER 3007:3004 + # SQLite 與記憶體裡的限流都假設只有一個 worker CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "2040", "--workers", "1"] diff --git a/server/app/anticheat.py b/server/app/anticheat.py index 6551920..7d5dd48 100644 --- a/server/app/anticheat.py +++ b/server/app/anticheat.py @@ -5,7 +5,7 @@ """ import asyncio -from . import clock, config, db, notices +from . import clock, config, db, limits, notices from .titles import fmt_uid @@ -42,3 +42,4 @@ async def loop() -> None: while True: await asyncio.sleep(config.CHECK_INTERVAL) await asyncio.to_thread(check_safe) + limits.sweep_all() # 順便清掉過期的限流紀錄 diff --git a/server/app/auth.py b/server/app/auth.py index e5911e0..f637ca2 100644 --- a/server/app/auth.py +++ b/server/app/auth.py @@ -1,18 +1,18 @@ """信箱驗證碼登入(沒有密碼):第一次驗證成功就自動建立帳號。 管理員:信箱欄輸入 ADMIN_LOGIN,驗證碼是 Aegis 算的 TOTP(不寄信)。錯 3 次就全域鎖定,時間逐次加倍。 +對外的回應和一般信箱完全相同(包括鎖定時),別人沒辦法從回應試出哪個是管理員。 """ -import re +import random import secrets import sqlite3 -import threading import time -from collections import defaultdict, deque +from collections import deque from fastapi import APIRouter, Depends, Request, Response from pydantic import BaseModel -from . import clock, config, db, mailer, notices, totp +from . import clock, config, db, limits, mailer, notices, totp from .db import get_db, get_meta, set_meta, transaction from .deps import client_ip, current_user, fail, session_token, sha256 from .i18n import norm_lang @@ -20,36 +20,33 @@ from .users import create_user, profile router = APIRouter() -EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") - -# 同一 IP 的寄信次數(單一 worker,放記憶體就夠) -_ip_hits: dict[str, deque] = defaultdict(deque) -_ip_lock = threading.Lock() +_ip_mail = limits.Window("IP_LIMIT", "IP_WINDOW") # 同一 IP 的寄信次數 +_all_mail = limits.Window("MAIL_LIMIT", "MAIL_WINDOW") # 全站的寄信次數 +_day_mail = limits.Window("MAIL_DAY_LIMIT", "MAIL_DAY_WINDOW") +_send_times: deque = deque(maxlen=20) # 最近實際寄信花的秒數;管理員不寄信,用它等差不多久 -def ip_allowed(ip: str) -> bool: - now = time.monotonic() - with _ip_lock: - q = _ip_hits[ip] - while q and q[0] < now - config.IP_WINDOW: - q.popleft() - if len(q) >= config.IP_LIMIT: - return False - q.append(now) - return True - - -def is_admin_login(raw: str) -> bool: - return db.admin_ok and raw.strip().lower() == config.ADMIN_LOGIN.lower() +def is_admin(conn: sqlite3.Connection, email: str) -> bool: + """管理員的信箱。就算管理員登入停用了也算:不能寄信給它,也不能用一般流程登入。""" + row = conn.execute("SELECT uid FROM users WHERE email = ?", (email,)).fetchone() + return row is not None and row["uid"] == config.ADMIN_UID def norm_email(email: str) -> str: email = email.strip().lower() - if len(email) > 254 or not EMAIL_RE.match(email): + if not limits.valid_email(email): fail(400, "invalid_email") return email +def mail_allowed() -> bool: + for window, name in ((_day_mail, "24 h"), (_all_mail, "10 min")): + if not window.allow("all"): + notices.add("mail_limit", None, name) + return False + return True + + class CodeRequest(BaseModel): email: str lang: str = config.DEFAULT_LANG @@ -64,12 +61,6 @@ class VerifyRequest(BaseModel): @router.post("/api/auth/request-code") def request_code(body: CodeRequest, request: Request, conn: sqlite3.Connection = Depends(get_db)): sent = {"status": "sent", "expires_in": config.CODE_TTL, "resend_in": config.CODE_RESEND} - if is_admin_login(body.email): - # 管理員不寄信,驗證碼看 Aegis。回應和一般信箱完全相同 - if not ip_allowed(client_ip(request)): - fail(429, "too_many_requests") - return sent - email = norm_email(body.email) now = clock.ts() conn.execute("DELETE FROM login_codes WHERE expires_at < ?", (now,)) @@ -77,7 +68,7 @@ def request_code(body: CodeRequest, request: Request, conn: sqlite3.Connection = old = conn.execute("SELECT last_sent_at FROM login_codes WHERE email = ?", (email,)).fetchone() if old and now - old["last_sent_at"] < config.CODE_RESEND: fail(429, "too_many_requests") - if not ip_allowed(client_ip(request)): + if not _ip_mail.allow(limits.ip_key(client_ip(request))) or not mail_allowed(): fail(429, "too_many_requests") # secrets 才是密碼學安全的亂數 @@ -88,8 +79,15 @@ def request_code(body: CodeRequest, request: Request, conn: sqlite3.Connection = "expires_at = excluded.expires_at, last_sent_at = excluded.last_sent_at", (email, sha256(code), now + config.CODE_TTL, now), ) + if is_admin(conn, email): + # 管理員不寄信,驗證碼看 Aegis。等一段和實際寄信差不多的時間,從快慢也看不出來 + if config.SMTP_USER and config.SMTP_PASSWORD: + time.sleep((random.choice(_send_times) if _send_times else 1.5) * random.uniform(0.9, 1.1)) + return sent + started = time.monotonic() try: mailer.send_code(email, code, norm_lang(body.lang)) + _send_times.append(time.monotonic() - started) except Exception as e: print("Error sending email:", e, flush=True) conn.execute("DELETE FROM login_codes WHERE email = ?", (email,)) @@ -151,13 +149,6 @@ def issue_session(conn: sqlite3.Connection, response: Response, user: sqlite3.Ro @router.post("/api/auth/verify") def verify(body: VerifyRequest, request: Request, response: Response, conn: sqlite3.Connection = Depends(get_db)): - if is_admin_login(body.email): - err = admin_check(conn, body.code.strip(), client_ip(request)) - if err: - fail(429 if err == "too_many_requests" else 400, err) - admin = conn.execute("SELECT * FROM users WHERE uid = ?", (config.ADMIN_UID,)).fetchone() - return issue_session(conn, response, admin) - email = norm_email(body.email) code = body.code.strip() now = clock.ts() @@ -169,18 +160,41 @@ def verify(body: VerifyRequest, request: Request, response: Response, conn.execute("DELETE FROM login_codes WHERE email = ?", (email,)) fail(400, "expired") + # 先用掉一次機會再比對(一句 SQL,同時送很多個也不會多猜)。認 code_hash:不會扣到剛重寄的新碼 + this_code = (email, row["code_hash"]) + used = conn.execute("UPDATE login_codes SET attempts = attempts + 1 " + "WHERE email = ? AND code_hash = ? AND attempts < ? RETURNING attempts", + (*this_code, config.CODE_MAX_ATTEMPTS)).fetchall() + if not used: + fail(400, "expired") + + admin = is_admin(conn, email) + if admin: + # 停用時一律不對;鎖定中也只當作碼錯了,不透露這是管理員 + err = admin_check(conn, code, client_ip(request)) if db.admin_ok else "wrong_code" + if err == "code_used": # 碼是對的,只是用過了:不算猜錯 + conn.execute("UPDATE login_codes SET attempts = attempts - 1 WHERE email = ? AND code_hash = ?", this_code) + fail(400, err) + ok = err is None + else: + ok = code.isascii() and secrets.compare_digest(sha256(code), row["code_hash"]) + # 錯太多次直接作廢,防止暴力猜碼 - if not secrets.compare_digest(sha256(code), row["code_hash"]): - attempts = row["attempts"] + 1 - if attempts >= config.CODE_MAX_ATTEMPTS: - conn.execute("DELETE FROM login_codes WHERE email = ?", (email,)) + if not ok: + if used[0]["attempts"] >= config.CODE_MAX_ATTEMPTS: + conn.execute("DELETE FROM login_codes WHERE email = ? AND code_hash = ?", this_code) fail(400, "expired") - conn.execute("UPDATE login_codes SET attempts = ? WHERE email = ?", (attempts, email)) fail(400, "wrong_code") - # 驗證碼只能用一次 - conn.execute("DELETE FROM login_codes WHERE email = ?", (email,)) + # 驗證碼只能用一次(同時送兩個對的,只有一個成功) + if conn.execute("DELETE FROM login_codes WHERE email = ? AND code_hash = ?", this_code).rowcount == 0: + fail(400, "not_requested") user = create_user(conn, email, body.lang) + if admin: + agent = "".join(ch for ch in request.headers.get("user-agent", "") if ch.isprintable())[:160] + country = request.headers.get("cf-ipcountry", "")[:8] + notices.add("admin_login", None, " · ".join(x for x in (client_ip(request)[:64], country, agent) if x), + merge=False) return issue_session(conn, response, user) diff --git a/server/app/card.py b/server/app/card.py index 634fa1b..c810368 100644 --- a/server/app/card.py +++ b/server/app/card.py @@ -10,8 +10,7 @@ import shutil import sqlite3 import tempfile import threading -import time -from collections import OrderedDict, defaultdict, deque +from collections import OrderedDict from functools import lru_cache from pathlib import Path from urllib.parse import urlparse @@ -20,15 +19,14 @@ from fastapi import APIRouter, Depends, Request from fastapi.responses import FileResponse, Response from PIL import Image, ImageDraw, ImageFont, ImageOps -from . import clock, config +from . import clock, config, limits from .checkin import list_memes, stats from .db import get_db from .deps import client_ip, fail from .i18n import norm_lang, t +from .images import FORMATS from .titles import badge_colors, fmt_uid -Image.MAX_IMAGE_PIXELS = 40_000_000 # 擋解壓縮炸彈 - router = APIRouter() W, H = 1080, 1350 @@ -90,7 +88,7 @@ def rounded_mask(size, radius) -> Image.Image: def load_image(path: Path) -> Image.Image | None: try: - with Image.open(path) as im: + with Image.open(path, formats=FORMATS) as im: im.seek(0) # gif 只取第一幀 im = ImageOps.exif_transpose(im) return im.convert("RGB") @@ -238,21 +236,10 @@ def get_card(uid: int, day: str, conn: sqlite3.Connection = Depends(get_db)): GUEST_CODE_RE = re.compile(r"^[A-Z0-9]{4}$") _guest_lock = threading.Lock() -_guest_hits: dict[str, deque] = defaultdict(deque) # IP -> 最近畫圖的時間 +_guest_hits = limits.Window("GUEST_CARD_LIMIT", "GUEST_CARD_WINDOW") _guest_cache: "OrderedDict[tuple, bytes]" = OrderedDict() # 最近畫過的幾張(PNG) -def _guest_allowed(ip: str) -> bool: - now = time.monotonic() - q = _guest_hits[ip] - while q and q[0] < now - config.GUEST_CARD_WINDOW: - q.popleft() - if len(q) >= config.GUEST_CARD_LIMIT: - return False - q.append(now) - return True - - def guest_meme(code: str, day: str) -> str | None: """同一個訪客同一天固定抽到同一張(伺服器沒有地方記,所以用代號 + 日期當亂數種子)。""" memes = list_memes() @@ -269,7 +256,7 @@ def get_guest_card(request: Request, code: str = "", n: str = "0", lang: str = c with _guest_lock: png = _guest_cache.get(key) if png is None: - if not _guest_allowed(client_ip(request)): + if not _guest_hits.allow(limits.ip_key(client_ip(request))): fail(429, "too_many_requests") buf = io.BytesIO() render_guest(lang, code, day, meme, clicks).save(buf, "PNG") diff --git a/server/app/config.py b/server/app/config.py index 90e013b..f00837d 100644 --- a/server/app/config.py +++ b/server/app/config.py @@ -51,7 +51,26 @@ IP_WINDOW = 10 * 60 SESSION_TTL = 90 * 24 * 3600 ADMIN_SESSION_TTL = 7 * 24 * 3600 -# 管理員:信箱欄輸入 ADMIN_LOGIN,驗證碼是 ADMIN_TOTP(base32 密鑰)算出的 TOTP。兩個都設定才啟用 +# 全站寄信上限:擋轟炸別人信箱,也避免把寄信服務的額度用光 +MAIL_LIMIT = 40 +MAIL_WINDOW = 10 * 60 +MAIL_DAY_LIMIT = 400 +MAIL_DAY_WINDOW = 24 * 3600 + +# 請求大小上限 +BODY_MAX = 64 * 1024 +UPLOAD_BODY_MAX = 6 * 1024 * 1024 # 圖片上限 5MB,加上表單的部分 +UPLOAD_PATHS = ("/api/me/avatar", "/api/submissions") + +# 上傳的圖:像素上限(2400 萬像素的手機照片可以過)、等前一張處理完最多幾秒 +IMAGE_MAX_PIXELS = 30_000_000 +IMAGE_WAIT = 10 +# 每個帳號每分鐘最多處理幾次(失敗也算) +AVATAR_LIMIT = 3 +SUBMIT_LIMIT = 10 +UPLOAD_WINDOW = 60 + +# 管理員:ADMIN_LOGIN 要是信箱格式(不會寄信),驗證碼是 ADMIN_TOTP(base32 密鑰)算出的 TOTP。兩個都設定才啟用 ADMIN_LOGIN = os.environ.get("ADMIN_LOGIN", "").strip() ADMIN_TOTP = os.environ.get("ADMIN_TOTP", "").strip() ADMIN_UID = 0 diff --git a/server/app/db.py b/server/app/db.py index 78544a5..b207905 100644 --- a/server/app/db.py +++ b/server/app/db.py @@ -131,12 +131,15 @@ def _migrate(conn: sqlite3.Connection) -> None: def _init_admin(conn: sqlite3.Connection) -> None: """建立或更新管理員帳號(uid 0)。改了 ADMIN_LOGIN 重啟就會生效。""" global admin_ok - from . import totp + from . import limits, totp admin_ok = False login, secret = config.ADMIN_LOGIN, config.ADMIN_TOTP if not login or not secret: return + if not limits.valid_email(login): + print("[ERROR] ADMIN_LOGIN 要是信箱格式(例如 name@example.com,不會真的寄信),管理員登入停用", flush=True) + return try: if len(totp.decode_secret(secret)) < 10: raise ValueError("too short") diff --git a/server/app/images.py b/server/app/images.py new file mode 100644 index 0000000..715fcda --- /dev/null +++ b/server/app/images.py @@ -0,0 +1,45 @@ +"""讀使用者上傳的圖:限制格式、限制像素、同時只處理一張。""" +import io +import threading +import warnings +from contextlib import contextmanager + +from PIL import Image, ImageOps + +from . import config +from .deps import fail + +# 只開這幾種。Pillow 還能讀 PSD、FITS、TIFF 等幾十種,漏洞多半出在那些格式 +FORMATS = ("JPEG", "PNG", "WEBP", "GIF") + +# 第二道保險:Pillow 自己在超過這個值的兩倍時會拒絕(例如檔頭和實際內容不一樣大) +Image.MAX_IMAGE_PIXELS = config.IMAGE_MAX_PIXELS // 2 +warnings.simplefilter("ignore", Image.DecompressionBombWarning) + +_slot = threading.Lock() + + +@contextmanager +def slot(): + """解碼很吃記憶體,全站同時只處理一張;等太久就請使用者稍後再試。""" + if not _slot.acquire(timeout=config.IMAGE_WAIT): + fail(429, "too_frequent") + try: + yield + finally: + _slot.release() + + +def decode(data: bytes) -> tuple[Image.Image, bool]: + """回傳 (RGB 或 RGBA 的圖, 有沒有透明度)。GIF 只取第一格;方向依 EXIF 轉正。""" + try: + with Image.open(io.BytesIO(data), formats=FORMATS) as im: + if im.width * im.height > config.IMAGE_MAX_PIXELS: # 只讀了檔頭,還沒解碼 + raise ValueError("too many pixels") + im.seek(0) + im.load() + ImageOps.exif_transpose(im, in_place=True) + alpha = im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info) + return im.convert("RGBA" if alpha else "RGB"), alpha + except Exception: + fail(400, "invalid_image") diff --git a/server/app/limits.py b/server/app/limits.py new file mode 100644 index 0000000..4357220 --- /dev/null +++ b/server/app/limits.py @@ -0,0 +1,107 @@ +"""限流(放記憶體,只有一個 worker)、IP 分組、信箱格式、請求大小上限。""" +import ipaddress +import re +import threading +import time +from collections import deque + +from fastapi import HTTPException +from starlette.responses import JSONResponse + +from . import config + +# 只收一個單純的 ASCII 地址。、x,a@b.c 這類寫法會寄到同一個人,卻被當成不同信箱 +EMAIL_RE = re.compile( + r"[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}" + r"@(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])") + + +def valid_email(email: str) -> bool: + return len(email) <= 254 and EMAIL_RE.fullmatch(email) is not None + + +def ip_key(ip: str) -> str: + """限流用的 IP。IPv6 的使用者手上通常有一整段 /64 可以換,所以算同一個。""" + try: + addr = ipaddress.ip_address(ip.strip()) + except ValueError: + return ip[:64] + if addr.version == 6: + if addr.ipv4_mapped: + return str(addr.ipv4_mapped) + return str(ipaddress.ip_network((int(addr), 64), strict=False)) + return str(addr) + + +class Window: + """同一個 key 在 window 秒內最多 limit 次。傳 config 的名稱,測試改值才會生效。""" + _all: list["Window"] = [] + + def __init__(self, limit: str, window: str): + self._limit, self._window = limit, window + self._hits: dict = {} + self._lock = threading.Lock() + Window._all.append(self) + + def allow(self, key) -> bool: + now = time.monotonic() + with self._lock: + q = self._hits.setdefault(key, deque()) + while q and q[0] < now - getattr(config, self._window): + q.popleft() + if len(q) >= getattr(config, self._limit): + return False + q.append(now) + return True + + def clear(self) -> None: + with self._lock: + self._hits.clear() + + def sweep(self) -> None: + """丟掉已經過期的 key,不然來過的 IP 會一直佔著記憶體。""" + old = time.monotonic() - getattr(config, self._window) + with self._lock: + for key in [k for k, q in self._hits.items() if not q or q[-1] < old]: + del self._hits[key] + + +def sweep_all() -> None: + for w in Window._all: + w.sweep() + + +class BodyLimit: + """擋太大的請求。沒有這個的話,還沒檢查登入就會先把整個請求收完。""" + + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + if scope["type"] != "http": + return await self.app(scope, receive, send) + limit = config.UPLOAD_BODY_MAX if scope["path"] in config.UPLOAD_PATHS else config.BODY_MAX + too_big = JSONResponse({"detail": "file_too_large"}, status_code=413) + length = dict(scope["headers"]).get(b"content-length", b"") + if length.isdigit() and int(length[:20]) > limit: + return await too_big(scope, receive, send) + got, replaced = 0, False + + async def limited(): # chunked 沒有 Content-Length,邊收邊算 + nonlocal got + message = await receive() + if message["type"] == "http.request": + got += len(message.get("body", b"")) + if got > limit: + raise HTTPException(413, "file_too_large") + return message + + async def answer(message): # 裡面會把上面的例外變成 400,統一換成 413 + nonlocal replaced + if got <= limit: + await send(message) + elif not replaced: + replaced = True + await too_big(scope, receive, send) + + await self.app(scope, limited, answer) diff --git a/server/app/main.py b/server/app/main.py index 0209218..7d52e4c 100644 --- a/server/app/main.py +++ b/server/app/main.py @@ -1,6 +1,7 @@ import asyncio import hashlib import mimetypes +import os from contextlib import asynccontextmanager from functools import lru_cache @@ -8,7 +9,7 @@ from fastapi import FastAPI, Request from fastapi.responses import FileResponse, HTMLResponse, JSONResponse from fastapi.staticfiles import StaticFiles -from . import __version__, anticheat, auth, card, checkin, config, db, notices, share, submissions, users +from . import __version__, anticheat, auth, card, checkin, config, db, limits, notices, share, submissions, users # python:3.12-slim 沒有 /etc/mime.types,這些副檔名會被當成 text/plain;加上 nosniff 後瀏覽器可能拒絕播放 for _type, _ext in (("image/webp", ".webp"), ("video/mp4", ".mp4"), ("audio/mp4", ".m4a"), ("application/manifest+json", ".webmanifest"), @@ -19,8 +20,25 @@ CSP = ("default-src 'self'; img-src 'self' data: blob:; media-src 'self'; style- "script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'") +def check_storage() -> None: + """容器不是用 root 跑:資料夾的擁有者不對時,啟動就講清楚。""" + who = f"{os.geteuid()}:{os.getegid()}" if hasattr(os, "geteuid") else "?" + + def bad(path): + return path.exists() and not os.access(path, os.R_OK | os.W_OK | (os.X_OK if path.is_dir() else 0)) + + data = config.DATA_DIR + paths = (data, *(data / n for n in ("zhiwu.db", "zhiwu.db-wal", "zhiwu.db-shm", "avatars", "cards", "submissions"))) + for p in paths: + if bad(p): + raise RuntimeError(f"{p} 不能讀寫。目前用 UID:GID {who} 執行,請先 chown -R {who} 掛到 /data 的資料夾") + if bad(config.MEME_DIR): + print(f"[WARN] {config.MEME_DIR} 不能讀寫,圖庫或投稿會失敗。請 chown -R {who} 掛到 /memes 的資料夾", flush=True) + + @asynccontextmanager async def lifespan(app: FastAPI): + check_storage() db.init() if not config.SMTP_USER or not config.SMTP_PASSWORD: print("[WARN] SMTP_USER / SMTP_PASSWORD 沒有設定:不會寄信,驗證碼只印在 log([DEV] verify code ...)", @@ -41,7 +59,7 @@ async def guard(request: Request, call_next): # 防 CSRF:會改資料的 /api 請求要帶 X-ZHIWU: 1(跨站表單帶不了自訂 header)。 # 用 Bearer token 的客戶端(Android)沒有 cookie,不受 CSRF 影響,所以不檢查。 if (request.method in ("POST", "PUT", "PATCH", "DELETE") - and request.url.path.startswith("/api/") + and request.scope["path"].startswith("/api/") and request.headers.get("x-zhiwu") != "1" and not request.headers.get("authorization")): return JSONResponse({"detail": "csrf"}, status_code=403) @@ -55,13 +73,15 @@ async def guard(request: Request, call_next): response.headers.setdefault("X-Content-Type-Options", "nosniff") response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin") response.headers.setdefault("Content-Security-Policy", CSP) - if request.url.path.startswith("/assets/"): + if request.scope["path"].startswith("/assets/"): # 沒有這行時 Cloudflare 會自己快取 .js / .css,改版後使用者拿到舊檔。 # no-cache = 每次向伺服器確認,沒變就回 304 response.headers.setdefault("Cache-Control", "no-cache") return response +app.add_middleware(limits.BodyLimit) # 最後加的在最外層 + for module in (auth, users, checkin, card, share, submissions, notices): app.include_router(module.router) diff --git a/server/app/notices.py b/server/app/notices.py index 0bcd3a9..cfdd9ac 100644 --- a/server/app/notices.py +++ b/server/app/notices.py @@ -18,8 +18,8 @@ router = APIRouter() PAGE_SIZE = 50 -def add(kind: str, uid: int | None = None, detail: str = "") -> None: - """自己開一條連線;不要在交易裡呼叫(會等自己的寫入鎖)。""" +def add(kind: str, uid: int | None = None, detail: str = "", merge: bool = True) -> None: + """自己開一條連線;不要在交易裡呼叫(會等自己的寫入鎖)。merge=False = 每次都是新的一則。""" try: conn = db.connect() try: @@ -28,8 +28,8 @@ def add(kind: str, uid: int | None = None, detail: str = "") -> None: cur = conn.execute( "UPDATE notices SET count = count + 1, updated_at = ?, read_at = NULL " "WHERE kind = ? AND uid IS ? AND detail = ? AND updated_at > ?", - (now, kind, uid, detail, now - config.NOTICE_MERGE)) - if cur.rowcount == 0: + (now, kind, uid, detail, now - config.NOTICE_MERGE)) if merge else None + if cur is None or cur.rowcount == 0: conn.execute( "INSERT INTO notices(kind, uid, detail, created_at, updated_at) VALUES (?, ?, ?, ?, ?)", (kind, uid, detail, now, now)) diff --git a/server/app/submissions.py b/server/app/submissions.py index 633a6db..6888995 100644 --- a/server/app/submissions.py +++ b/server/app/submissions.py @@ -15,9 +15,9 @@ from pathlib import Path from fastapi import APIRouter, Depends, File, UploadFile from fastapi.responses import FileResponse -from PIL import Image, ImageOps +from PIL import Image -from . import clock, config +from . import clock, config, images, limits from .db import get_db, transaction from .deps import admin_user, current_user, fail from .titles import badge, fmt_uid @@ -39,15 +39,7 @@ def pending_path(row: sqlite3.Row) -> Path: def process_meme(data: bytes) -> tuple[bytes, str]: """重新編碼成 JPEG(有透明度就用 PNG):去掉 EXIF(含 GPS)和偽裝成圖片的內容,GIF 只取第一格。""" - try: - with Image.open(io.BytesIO(data)) as im: - im.seek(0) - im.load() - im = ImageOps.exif_transpose(im) - has_alpha = im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info) - im = im.convert("RGBA" if has_alpha else "RGB") - except Exception: - fail(400, "invalid_image") + im, has_alpha = images.decode(data) if max(im.size) > config.SUBMIT_MAX_SIDE: im.thumbnail((config.SUBMIT_MAX_SIDE, config.SUBMIT_MAX_SIDE), Image.LANCZOS) out = io.BytesIO() @@ -104,12 +96,18 @@ def pending_count(conn: sqlite3.Connection) -> int: # ---------- 使用者 ---------- +_upload_hits = limits.Window("SUBMIT_LIMIT", "UPLOAD_WINDOW") + + @router.post("/api/submissions") def upload(file: UploadFile = File(...), user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)): + if not _upload_hits.allow(user["uid"]): + fail(429, "too_frequent") data = file.file.read(config.SUBMIT_MAX_BYTES + 1) if len(data) > config.SUBMIT_MAX_BYTES: fail(413, "file_too_large") - body, ext = process_meme(data) # 先處理圖片,不佔用寫入鎖 + with images.slot(): + body, ext = process_meme(data) # 先處理圖片,不佔用寫入鎖 day = clock.today() submission_dir().mkdir(parents=True, exist_ok=True) # BEGIN IMMEDIATE:同時上傳好幾張也不會超過額度;寫檔失敗會連同 INSERT 一起還原 diff --git a/server/app/totp.py b/server/app/totp.py index 8a4197c..47309f9 100644 --- a/server/app/totp.py +++ b/server/app/totp.py @@ -23,7 +23,7 @@ def code_at(key: bytes, step: int) -> str: def verify(secret: str, code: str, unix_time: int, window: int = 1) -> int | None: """比對前後各 window 個時間窗(容忍手機時鐘誤差),成功回傳符合的時間步。""" - if len(code) != DIGITS or not code.isdigit(): + if len(code) != DIGITS or not code.isascii() or not code.isdigit(): return None key = decode_secret(secret) current = unix_time // PERIOD diff --git a/server/app/users.py b/server/app/users.py index a0348a8..b0d6de4 100644 --- a/server/app/users.py +++ b/server/app/users.py @@ -11,7 +11,7 @@ from markdown_it import MarkdownIt from PIL import Image, ImageOps from pydantic import BaseModel -from . import card, clock, config, notices +from . import card, clock, config, images, limits, notices from .checkin import stats from .db import get_db, transaction from .deps import admin_user, current_user, fail, optional_user @@ -139,15 +139,7 @@ def patch_me(body: ProfilePatch, user=Depends(current_user), conn: sqlite3.Conne def process_avatar(data: bytes) -> bytes: """置中裁成正方形、縮成 1024×1024、重新編成 WebP(順便去掉 EXIF 與偽裝成圖片的內容)。""" - try: - with Image.open(io.BytesIO(data)) as im: - im.seek(0) - im.load() - im = ImageOps.exif_transpose(im) - has_alpha = im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info) - im = im.convert("RGBA" if has_alpha else "RGB") - except Exception: - fail(400, "invalid_image") + im, _ = images.decode(data) size = config.AVATAR_SIZE im = ImageOps.fit(im, (size, size), Image.LANCZOS) out = io.BytesIO() @@ -155,13 +147,19 @@ def process_avatar(data: bytes) -> bytes: return out.getvalue() +_avatar_hits = limits.Window("AVATAR_LIMIT", "UPLOAD_WINDOW") + + @router.put("/api/me/avatar") def put_avatar(file: UploadFile = File(...), user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)): + if not _avatar_hits.allow(user["uid"]): + fail(429, "too_frequent") data = file.file.read(config.AVATAR_MAX_BYTES + 1) if len(data) > config.AVATAR_MAX_BYTES: fail(413, "file_too_large") - webp = process_avatar(data) + with images.slot(): + webp = process_avatar(data) folder = config.DATA_DIR / "avatars" folder.mkdir(parents=True, exist_ok=True) fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp") diff --git a/server/requirements-dev.txt b/server/requirements-dev.txt index ea8fe79..19ea7ed 100644 --- a/server/requirements-dev.txt +++ b/server/requirements-dev.txt @@ -1,3 +1,3 @@ -r requirements.txt -pytest==8.* -httpx +pytest==9.2.0 +httpx==0.28.1 diff --git a/server/requirements.txt b/server/requirements.txt index 2a5624a..83c38d5 100644 --- a/server/requirements.txt +++ b/server/requirements.txt @@ -1,6 +1,7 @@ -fastapi==0.115.* -uvicorn[standard]==0.32.* -pillow==11.* -python-multipart==0.0.* -markdown-it-py==3.* -tzdata +fastapi==0.165.0 +starlette==1.10.0 +uvicorn[standard]==0.54.0 +pillow==13.0.0 +python-multipart==0.0.34 +markdown-it-py==4.3.0 +tzdata==2026.6 diff --git a/server/tests/conftest.py b/server/tests/conftest.py index 602317a..c14299c 100644 --- a/server/tests/conftest.py +++ b/server/tests/conftest.py @@ -4,9 +4,9 @@ import pytest from fastapi.testclient import TestClient from PIL import Image -from app import auth, checkin, clock, config, mailer, totp +from app import auth, checkin, clock, config, db, limits, mailer, totp -ADMIN_LOGIN = "sthkm3" +ADMIN_LOGIN = "boss-7f3a@admin.invalid" ADMIN_TOTP = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP" # 測試用密鑰 @@ -45,7 +45,8 @@ def client(tmp_path, monkeypatch, fake_clock, sent): monkeypatch.setattr(config, "MEME_DIR", memes) monkeypatch.setattr(config, "ADMIN_LOGIN", ADMIN_LOGIN) monkeypatch.setattr(config, "ADMIN_TOTP", ADMIN_TOTP) - auth._ip_hits.clear() + for w in limits.Window._all: + w.clear() for d in (checkin._next, checkin._rejects, checkin._cool): d.clear() from app.main import app @@ -61,6 +62,17 @@ def login(client, sent, email="a@example.com", lang="zh-TW"): return r.json() +def admin_verify(client, code, email=ADMIN_LOGIN, headers=None): + """管理員登入:和一般人一樣要先要驗證碼(這裡略過 60 秒限制),再輸入 TOTP。""" + conn = db.connect() + conn.execute("DELETE FROM login_codes WHERE email = ?", (email,)) + conn.close() + auth._ip_mail.clear() + r = client.post("/api/auth/request-code", json={"email": email}) + assert r.status_code == 200, r.text + return client.post("/api/auth/verify", json={"email": email, "code": code}, headers=headers) + + def admin_code(fake_clock, offset_steps=0): """用假時鐘算出管理員的 TOTP。""" step = int(fake_clock.value.timestamp()) // totp.PERIOD + offset_steps diff --git a/server/tests/test_admin.py b/server/tests/test_admin.py index 9b38651..a25ebc7 100644 --- a/server/tests/test_admin.py +++ b/server/tests/test_admin.py @@ -4,11 +4,11 @@ import pytest from app import admin, config, db, totp -from .conftest import ADMIN_LOGIN, admin_code, login +from .conftest import ADMIN_LOGIN, admin_code, admin_verify, login def admin_login(client, code, login_name=ADMIN_LOGIN): - return client.post("/api/auth/verify", json={"email": login_name, "code": code}) + return admin_verify(client, code, login_name) def test_totp_rfc6238_vector(): @@ -23,7 +23,7 @@ def test_totp_rfc6238_vector(): def test_admin_request_code_does_not_send(client, sent): - r = client.post("/api/auth/request-code", json={"email": "STHKM3"}) + r = client.post("/api/auth/request-code", json={"email": ADMIN_LOGIN.upper()}) assert r.status_code == 200 and r.json()["status"] == "sent" assert sent == {} @@ -64,10 +64,10 @@ def test_admin_lockout(client, fake_clock): wrong = "000000" if good != "000000" else "111111" assert admin_login(client, wrong).json()["detail"] == "wrong_code" assert admin_login(client, wrong).json()["detail"] == "wrong_code" - r = admin_login(client, wrong) # 第 3 次就鎖 - assert r.status_code == 429 + assert admin_login(client, wrong).json()["detail"] == "wrong_code" + assert db.get_meta(db.connect(), "admin_lock_level") == 1 # 第 3 次就鎖,但回應看不出來 # 鎖定中,正確的碼也不行 - assert admin_login(client, good).status_code == 429 + assert admin_login(client, good).json()["detail"] == "wrong_code" # 15 分鐘後解鎖 fake_clock.value += timedelta(minutes=15) @@ -79,7 +79,7 @@ def test_admin_lock_doubles(client, fake_clock): for _ in range(3): admin_login(client, "000000" if admin_code(fake_clock) != "000000" else "111111") fake_clock.value += timedelta(minutes=minutes) - timedelta(seconds=1) - assert admin_login(client, admin_code(fake_clock)).status_code == 429 + assert admin_login(client, admin_code(fake_clock)).status_code == 400 fake_clock.value += timedelta(seconds=1) conn = db.connect() assert db.get_meta(conn, "admin_lock_level") == 3 @@ -88,7 +88,7 @@ def test_admin_lock_doubles(client, fake_clock): def test_admin_unlock_command(client, fake_clock): for _ in range(3): admin_login(client, "000000" if admin_code(fake_clock) != "000000" else "111111") - assert admin_login(client, admin_code(fake_clock)).status_code == 429 + assert admin_login(client, admin_code(fake_clock)).status_code == 400 admin.main(["unlock"]) assert admin_login(client, admin_code(fake_clock)).status_code == 200 @@ -96,16 +96,15 @@ def test_admin_unlock_command(client, fake_clock): def test_admin_disabled_without_secret(client, sent, fake_clock, monkeypatch): monkeypatch.setattr(config, "ADMIN_TOTP", "") db.init() - r = client.post("/api/auth/request-code", json={"email": ADMIN_LOGIN}) - assert r.status_code == 400 and r.json()["detail"] == "invalid_email" - assert admin_login(client, admin_code(fake_clock)).json()["detail"] == "invalid_email" + assert admin_login(client, admin_code(fake_clock)).json()["detail"] == "wrong_code" + assert sent == {} def test_admin_login_renamed(client, fake_clock, monkeypatch): - monkeypatch.setattr(config, "ADMIN_LOGIN", "boss") + monkeypatch.setattr(config, "ADMIN_LOGIN", "Boss2@admin.invalid") db.init() - assert admin_login(client, admin_code(fake_clock), "sthkm3").json()["detail"] == "invalid_email" - r = admin_login(client, admin_code(fake_clock), "boss") + assert admin_login(client, admin_code(fake_clock)).json()["detail"] == "wrong_code" # 舊的變成一般信箱 + r = admin_login(client, admin_code(fake_clock), "boss2@admin.invalid") assert r.status_code == 200 and r.json()["user"]["uid"] == 0 @@ -119,7 +118,7 @@ def test_admin_login_clash_disables(client, sent, fake_clock, monkeypatch): def test_totp_uri(capsys, client): admin.main(["totp-uri"]) last = capsys.readouterr().out.strip().splitlines()[-1] - assert last.startswith("otpauth://totp/%E5%90%B1%E9%BC%AF%E8%A8%88%E7%95%AB%3Asthkm3?secret=") + assert last.startswith("otpauth://totp/%E5%90%B1%E9%BC%AF%E8%A8%88%E7%95%AB%3Aboss-7f3a%40admin.invalid?secret=") @pytest.mark.parametrize("uid", ["0", "-1"]) diff --git a/server/tests/test_anticheat.py b/server/tests/test_anticheat.py index f58e47c..7c97742 100644 --- a/server/tests/test_anticheat.py +++ b/server/tests/test_anticheat.py @@ -7,22 +7,26 @@ import pytest from app import __version__, anticheat, card, checkin, config, db, mailer, notices, users -from .conftest import ADMIN_LOGIN, admin_code, login +from .conftest import admin_code, admin_verify, login from .test_zhi import frozen # noqa: F401 (fixture) def as_admin(client, fake_clock): client.cookies.clear() - r = client.post("/api/auth/verify", json={"email": ADMIN_LOGIN, "code": admin_code(fake_clock)}) + r = admin_verify(client, admin_code(fake_clock)) assert r.status_code == 200, r.text + forget_login() def zhi(client): return client.post("/api/zhi", json={"n": 1}) -def kinds(client): - return [n["kind"] for n in client.get("/api/admin/notices").json()["items"]] +def forget_login(): + """管理員登入本身也會發一則通知,測其他通知時先拿掉。""" + conn = db.connect() + conn.execute("DELETE FROM notices WHERE kind = 'admin_login'") + conn.close() # ---------- 冷靜時間 ---------- @@ -151,7 +155,7 @@ def test_error_mail_and_lock_notices(client, sent, fake_clock, monkeypatch): monkeypatch.setattr(mailer, "send_code", boom) assert client.post("/api/auth/request-code", json={"email": "a@example.com"}).status_code == 502 for _ in range(config.ADMIN_MAX_FAILS): - client.post("/api/auth/verify", json={"email": ADMIN_LOGIN, "code": "abc"}) + admin_verify(client, "abc") monkeypatch.setattr(users, "render_md", boom) with pytest.raises(RuntimeError): client.get("/api/users/0") diff --git a/server/tests/test_security.py b/server/tests/test_security.py new file mode 100644 index 0000000..59d90d6 --- /dev/null +++ b/server/tests/test_security.py @@ -0,0 +1,344 @@ +"""1.0.2 發版前的漏洞修補:寄信限制、管理員不可探測、圖片、請求大小、儲存權限。""" +import io +import os +import struct +import zlib +from concurrent.futures import ThreadPoolExecutor +from datetime import timedelta + +import pytest +from PIL import Image + +from app import anticheat, auth, config, db, images, limits, main, users + +from .conftest import ADMIN_LOGIN, admin_code, admin_verify, login + + +def ask(client, email, ip="198.51.100.1"): + return client.post("/api/auth/request-code", json={"email": email}, headers={"CF-Connecting-IP": ip}) + + +def verify(client, email, code): + return client.post("/api/auth/verify", json={"email": email, "code": code}) + + +def bomb(w, h): + """檔頭寫很大、內容很小的 PNG。""" + def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d)) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(b"\0" * 1000)) + chunk(b"IEND", b"")) + + +def img(fmt, size=(40, 30), **kw): + buf = io.BytesIO() + Image.new("RGB", size, (9, 99, 200)).save(buf, fmt, **kw) + return buf.getvalue() + + +def put_avatar(client, data): + return client.put("/api/me/avatar", files={"file": ("a", data, "image/png")}) + + +# ---------- 寄信 ---------- + +@pytest.mark.parametrize("email", [ + "", "a", "z,v@example.com", "(c)v@example.com", '"x"', "v@example", + "v@-a.com", "v@a..com", "v v@example.com", "v@example.com\nBcc: x@y.zz", "v@example.com", "\ud800@a.co", "v@a.1", "", + "a" * 65 + "@example.com", "v@" + "a." * 130 + "com", +]) +def test_odd_emails_rejected(client, sent, email): + import json + r = client.post("/api/auth/request-code", content=json.dumps({"email": email}), + headers={"Content-Type": "application/json"}) + assert r.status_code == 400 and r.json()["detail"] == "invalid_email" and sent == {} + + +@pytest.mark.parametrize("email", ["a.b+c_d-e@sub.example.co.jp", "x@xn--fiqs8s.xn--fiqz9s", "1@a1.tw", "o'neil@example.com"]) +def test_normal_emails_accepted(email): + assert limits.valid_email(email) + + +def test_ip_key(): + assert limits.ip_key("2001:db8:1:1::5") == limits.ip_key("2001:db8:1:1:ffff::9") + assert limits.ip_key("2001:db8:1:1::5") != limits.ip_key("2001:db8:1:2::5") + assert limits.ip_key("::ffff:203.0.113.9") == limits.ip_key("203.0.113.9") == "203.0.113.9" + assert limits.ip_key("203.0.113.9") != limits.ip_key("203.0.113.10") + assert limits.ip_key("testclient") == "testclient" + + +def test_ipv6_64_shares_limit(client, sent): + codes = [ask(client, f"u{i}@example.com", f"2001:db8:1:1::{i:x}").status_code for i in range(12)] + assert codes == [200] * config.IP_LIMIT + [429] * 2 + + +@pytest.mark.parametrize("name", ["MAIL_LIMIT", "MAIL_DAY_LIMIT"]) +def test_site_wide_mail_limit(client, sent, monkeypatch, name): + monkeypatch.setattr(config, name, 3) + codes = [ask(client, f"u{i}@example.com", f"203.0.113.{i}").status_code for i in range(5)] + assert codes == [200, 200, 200, 429, 429] and len(sent) == 3 + conn = db.connect() + assert [(r["kind"], r["count"]) for r in conn.execute("SELECT * FROM notices")] == [("mail_limit", 2)] + conn.close() + + +def test_sweep_drops_expired_only(monkeypatch): + auth._ip_mail.clear() + now = [1000.0] + monkeypatch.setattr(limits.time, "monotonic", lambda: now[0]) + auth._ip_mail.allow("old") + now[0] += config.IP_WINDOW - 1 + auth._ip_mail.allow("new") + now[0] += 2 + limits.sweep_all() + assert list(auth._ip_mail._hits) == ["new"] + + +def test_hourly_loop_sweeps(monkeypatch): + import asyncio + called = [] + + async def fake_sleep(_): + if called: + raise asyncio.CancelledError + monkeypatch.setattr(anticheat.asyncio, "sleep", fake_sleep) + monkeypatch.setattr(anticheat, "check_safe", lambda: None) + monkeypatch.setattr(limits, "sweep_all", lambda: called.append(1)) + with pytest.raises(asyncio.CancelledError): + asyncio.run(anticheat.loop()) + assert called == [1] + + +# ---------- 驗證碼:同時送也不能多猜、不能重複用 ---------- + +def test_parallel_guesses_are_capped(client, sent, monkeypatch): + ask(client, "a@example.com") + compared = [] + real = auth.secrets.compare_digest + monkeypatch.setattr(auth.secrets, "compare_digest", lambda a, b: compared.append(1) or real(a, b)) + with ThreadPoolExecutor(30) as ex: + codes = list(ex.map(lambda i: verify(client, "a@example.com", f"x{i}").json()["detail"], range(150))) + assert len(compared) == config.CODE_MAX_ATTEMPTS + assert codes.count("wrong_code") == config.CODE_MAX_ATTEMPTS - 1 + + +def test_parallel_right_code_works_once(client, sent): + ask(client, "a@example.com") + with ThreadPoolExecutor(10) as ex: + codes = list(ex.map(lambda _: verify(client, "a@example.com", sent["a@example.com"]).status_code, range(30))) + assert codes.count(200) == 1 + + +def test_fifth_try_can_still_succeed(client, sent): + ask(client, "a@example.com") + for _ in range(config.CODE_MAX_ATTEMPTS - 1): + assert verify(client, "a@example.com", "x").json()["detail"] == "wrong_code" + assert verify(client, "a@example.com", sent["a@example.com"]).status_code == 200 + + +def test_used_admin_code_does_not_burn_attempts(client, fake_clock): + assert admin_verify(client, admin_code(fake_clock)).status_code == 200 + ask(client, ADMIN_LOGIN) + for _ in range(config.CODE_MAX_ATTEMPTS + 2): + assert verify(client, ADMIN_LOGIN, admin_code(fake_clock)).json()["detail"] == "code_used" + + +# ---------- 管理員和一般信箱的回應要完全一樣 ---------- + +def walk(client, email, fake_clock): + """把外人能做的事走一遍,記下每一步的回應。""" + out = [] + + def rec(r): + out.append((r.status_code, r.text, sorted(k for k in r.headers if k not in ("date", "content-length")))) + + rec(verify(client, email, "999999")) # 還沒要驗證碼 + rec(ask(client, email)) + rec(ask(client, email)) # 60 秒內重寄 + for code in ("999999", "123456", "", "abc", "é"): + rec(verify(client, email, code)) # 第 5 次作廢(管理員第 3 次已鎖定) + rec(verify(client, email, "999999")) + fake_clock.value += timedelta(seconds=61) + rec(ask(client, email)) + rec(verify(client, email, "999999")) # 管理員鎖定中 + fake_clock.value += timedelta(minutes=6) + rec(verify(client, email, "999999")) # 過期 + return out + + +def test_admin_is_indistinguishable(client, sent, fake_clock, monkeypatch): + monkeypatch.setattr(auth.secrets, "randbelow", lambda n: 123457) + start = fake_clock.value + normal = walk(client, "someone@example.com", fake_clock) + fake_clock.value = start + auth._ip_mail.clear() + assert walk(client, ADMIN_LOGIN, fake_clock) == normal + assert ADMIN_LOGIN not in sent + conn = db.connect() + assert db.get_meta(conn, "admin_lock_level") == 1 # 裡面還是有鎖 + conn.close() + + +def test_surrogate_code_is_same_for_everyone(client, sent): + for email in ("someone@example.com", ADMIN_LOGIN): + ask(client, email) + r = client.post("/api/auth/verify", content='{"email":"%s","code":"\\ud800"}' % email, + headers={"Content-Type": "application/json"}) + assert r.status_code == 400 and r.json()["detail"] == "wrong_code" + + +def test_admin_waits_like_real_mail(client, sent, monkeypatch): + slept = [] + monkeypatch.setattr(auth.time, "sleep", slept.append) + ask(client, ADMIN_LOGIN) + assert slept == [] # 沒設 SMTP:一般信箱也是立刻回 + db.connect().execute("DELETE FROM login_codes") + monkeypatch.setattr(config, "SMTP_USER", "u") + monkeypatch.setattr(config, "SMTP_PASSWORD", "p") + auth._send_times.clear() + auth._send_times.append(2.0) + ask(client, ADMIN_LOGIN) + assert len(slept) == 1 and 1.8 <= slept[0] <= 2.2 + + +@pytest.mark.parametrize("how", ["no_totp", "bad_totp", "not_email", "no_login"]) +def test_disabled_admin_cannot_be_taken_over_by_mail(client, sent, fake_clock, monkeypatch, how): + """管理員停用後,就算那個信箱真的存在,也不能用寄信的驗證碼登入成管理員。""" + key, value = {"no_totp": ("ADMIN_TOTP", ""), "bad_totp": ("ADMIN_TOTP", "!!"), + "not_email": ("ADMIN_LOGIN", "boss"), "no_login": ("ADMIN_LOGIN", "")}[how] + monkeypatch.setattr(config, key, value) + db.init() + assert db.admin_ok is False + monkeypatch.setattr(auth.secrets, "randbelow", lambda n: 123456) + assert ask(client, ADMIN_LOGIN).status_code == 200 and sent == {} + assert verify(client, ADMIN_LOGIN, "123456").json()["detail"] == "wrong_code" + assert verify(client, ADMIN_LOGIN, admin_code(fake_clock)).json()["detail"] == "wrong_code" + + +def test_admin_login_is_recorded(client, fake_clock): + for _ in range(2): + r = admin_verify(client, admin_code(fake_clock), headers={ + "CF-Connecting-IP": "203.0.113.7", "CF-IPCountry": "TW", "User-Agent": "Test/1.0 " + "x" * 300}) + assert r.status_code == 200 + fake_clock.value += timedelta(seconds=30) + r = client.get("/api/admin/notices").json() + assert [(n["kind"], n["count"], n["unread"]) for n in r["items"]] == [("admin_login", 1, True)] * 2 + assert r["items"][0]["detail"].startswith("203.0.113.7 · TW · Test/1.0 xxx") and len(r["items"][0]["detail"]) < 200 + + +def test_normal_login_is_not_recorded(client, sent): + login(client, sent) + assert db.connect().execute("SELECT COUNT(*) FROM notices").fetchone()[0] == 0 + + +# ---------- 圖片 ---------- + +def test_bomb_rejected_before_decode(client, sent, monkeypatch): + login(client, sent) + monkeypatch.setattr(Image.Image, "load", lambda self: pytest.fail("不該解碼")) + r = put_avatar(client, bomb(8900, 8900)) + assert r.status_code == 400 and r.json()["detail"] == "invalid_image" + + +@pytest.mark.parametrize("fmt,ok", [("PNG", 1), ("JPEG", 1), ("WEBP", 1), ("GIF", 1), + ("TIFF", 0), ("BMP", 0), ("ICO", 0), ("TGA", 0), ("PPM", 0), ("PCX", 0)]) +def test_only_four_formats(client, sent, fmt, ok): + login(client, sent) + assert put_avatar(client, img(fmt)).status_code == (200 if ok else 400) + r = client.post("/api/submissions", files={"file": ("a.png", img(fmt), "image/png")}) + assert r.status_code == (200 if ok else 400) + + +def test_psd_rejected(client, sent): + login(client, sent) + psd = b"8BPS" + struct.pack(">H6xHIIHH", 1, 3, 4, 4, 8, 3) + b"\0" * 14 + b"\0" * 48 + with Image.open(io.BytesIO(psd)) as im: + assert im.format == "PSD" # 這個檔本身是讀得到的 + assert put_avatar(client, psd).status_code == 400 + + +def test_exif_rotation_kept(client, sent): + exif = Image.Exif() + exif[0x0112] = 6 + im, alpha = images.decode(img("JPEG", (40, 30), exif=exif)) + assert im.size == (30, 40) and alpha is False + + +def test_avatar_three_per_minute(client, sent): + login(client, sent) + codes = [put_avatar(client, d).status_code for d in (img("PNG"), b"bad", img("PNG"), img("PNG"))] + assert codes == [200, 400, 200, 429] # 失敗也算 + assert put_avatar(client, img("PNG")).json()["detail"] == "too_frequent" + client.cookies.clear() + login(client, sent, "b@example.com") + assert put_avatar(client, img("PNG")).status_code == 200 + + +def test_one_image_at_a_time(client, sent, monkeypatch): + login(client, sent) + monkeypatch.setattr(config, "IMAGE_WAIT", 0.05) + with images.slot(): + r = put_avatar(client, img("PNG")) + assert r.status_code == 429 and r.json()["detail"] == "too_frequent" + assert put_avatar(client, img("PNG")).status_code == 200 # 失敗後鎖有放開 + assert put_avatar(client, b"bad").status_code == 400 + assert images._slot.acquire(timeout=0) and images._slot.release() is None + + +# ---------- 請求大小、路徑 ---------- + +def test_body_limit_by_length(client): + r = client.post("/api/auth/request-code", json={"email": "a" * config.BODY_MAX}) + assert r.status_code == 413 and r.json()["detail"] == "file_too_large" + r = client.post("/api/submissions", files={"file": ("a", b"\0" * config.UPLOAD_BODY_MAX)}) + assert r.status_code == 413 + + +@pytest.mark.parametrize("path,ctype,limit", [ + ("/api/auth/request-code", "application/json", config.BODY_MAX), + ("/api/submissions", "multipart/form-data; boundary=b", config.UPLOAD_BODY_MAX), +]) +def test_body_limit_chunked(client, path, ctype, limit): + got = [0] + + def body(): + yield b'--b\r\nContent-Disposition: form-data; name="file"; filename="a"\r\n\r\n' if "multi" in ctype else b'{"email":"' + for _ in range(limit // 32768 + 40): + got[0] += 1 + yield b"a" * 32768 + r = client.post(path, content=body(), headers={"Content-Type": ctype}) + assert r.status_code == 413 and r.json()["detail"] == "file_too_large" + + +def test_five_mb_file_still_allowed(client, sent): + login(client, sent) + data = img("PNG") + assert put_avatar(client, data + b"\0" * (config.AVATAR_MAX_BYTES - len(data))).status_code == 200 + + +def test_csrf_not_bypassed_by_host(client, sent): + login(client, sent) + r = client.post("/api/checkin", headers={"X-ZHIWU": "", "Host": "x/y?"}) + assert r.status_code in (400, 403) + + +# ---------- 儲存權限 ---------- + +@pytest.mark.skipif(os.name == "nt" or os.geteuid() == 0, reason="要在非 root 的 Linux 上測") +def test_storage_check(tmp_path, monkeypatch, capsys): + data, memes = tmp_path / "d", tmp_path / "m" + data.mkdir(), memes.mkdir() + monkeypatch.setattr(config, "DATA_DIR", data) + monkeypatch.setattr(config, "MEME_DIR", memes) + main.check_storage() + memes.chmod(0o500) + main.check_storage() + assert "[WARN]" in capsys.readouterr().out + (data / "zhiwu.db").touch(0o400) + with pytest.raises(RuntimeError, match="zhiwu.db"): + main.check_storage() + memes.chmod(0o700) + + +def test_users_module_has_no_direct_open(): + assert not hasattr(users, "Image") or "Image.open" not in open(users.__file__, encoding="utf-8").read() diff --git a/server/tests/test_submissions.py b/server/tests/test_submissions.py index f59c9b0..407335b 100644 --- a/server/tests/test_submissions.py +++ b/server/tests/test_submissions.py @@ -4,7 +4,7 @@ from PIL import Image from app import admin, checkin, config, db -from .conftest import ADMIN_LOGIN, admin_code, login +from .conftest import admin_code, admin_verify, login def _img(fmt="PNG", color=(10, 200, 30), size=(300, 200), **kw): @@ -23,7 +23,7 @@ def upload(client, token, data=None, name="a.png"): def admin_token(client, fake_clock): - r = client.post("/api/auth/verify", json={"email": ADMIN_LOGIN, "code": admin_code(fake_clock)}) + r = admin_verify(client, admin_code(fake_clock)) assert r.status_code == 200, r.text return r.json()["token"] diff --git a/server/tests/test_titles.py b/server/tests/test_titles.py index 8b3bf6b..336aa45 100644 --- a/server/tests/test_titles.py +++ b/server/tests/test_titles.py @@ -4,7 +4,7 @@ import sqlite3 from app import admin, config, db from app.titles import text_on -from .conftest import ADMIN_LOGIN, admin_code, login +from .conftest import admin_code, admin_verify, login def bearer(tok): @@ -12,8 +12,7 @@ def bearer(tok): def admin_token(client, fake_clock): - client.post("/api/auth/request-code", json={"email": ADMIN_LOGIN, "lang": "zh-TW"}) - r = client.post("/api/auth/verify", json={"email": ADMIN_LOGIN, "code": admin_code(fake_clock), "lang": "zh-TW"}) + r = admin_verify(client, admin_code(fake_clock)) assert r.status_code == 200, r.text client.cookies.clear() return r.json()["token"] diff --git a/web/app.js b/web/app.js index b122202..f625974 100644 --- a/web/app.js +++ b/web/app.js @@ -844,7 +844,7 @@ function bindUpload() { ok++; } catch (e) { showError($("upload-error"), e); - if (e.code === "quota_exceeded") break; + if (e.code === "quota_exceeded" || e.code === "too_frequent") break; } } if (ok) toast(t("upload.done", { n: ok })); diff --git a/web/i18n/en.json b/web/i18n/en.json index d07e574..a126a8d 100644 --- a/web/i18n/en.json +++ b/web/i18n/en.json @@ -118,5 +118,8 @@ "flag.text": "This account is flagged: its click count is above the theoretical limit.", "flag.clear": "Remove flag", "flag.cleared": "Flag removed", - "err.cooldown": "Too fast. Take a 10 second break" + "err.cooldown": "Too fast. Take a 10 second break", + "err.too_frequent": "Too many attempts. Please try again later", + "notice.admin_login": "Admin signed in", + "notice.mail_limit": "Site-wide email limit reached" } diff --git a/web/i18n/ja.json b/web/i18n/ja.json index f213e56..1b9963c 100644 --- a/web/i18n/ja.json +++ b/web/i18n/ja.json @@ -118,5 +118,8 @@ "flag.text": "このアカウントはマークされています:チューチューの回数が理論上の上限を超えています。", "flag.clear": "マークを解除", "flag.cleared": "マークを解除しました", - "err.cooldown": "速すぎます。10 秒待ってからどうぞ" + "err.cooldown": "速すぎます。10 秒待ってからどうぞ", + "err.too_frequent": "操作が頻繁すぎます。しばらくしてからお試しください", + "notice.admin_login": "管理者がログインしました", + "notice.mail_limit": "メール送信数がサイト全体の上限に達しました" } diff --git a/web/i18n/ko.json b/web/i18n/ko.json index 59848b5..af8734b 100644 --- a/web/i18n/ko.json +++ b/web/i18n/ko.json @@ -118,5 +118,8 @@ "flag.text": "이 계정은 표시되었어요: 찍찍 횟수가 이론상 한도를 넘었어요.", "flag.clear": "표시 해제", "flag.cleared": "표시를 해제했어요", - "err.cooldown": "너무 빨라요. 10초 쉬었다 하세요" + "err.cooldown": "너무 빨라요. 10초 쉬었다 하세요", + "err.too_frequent": "너무 자주 시도했어요. 잠시 후 다시 시도해 주세요", + "notice.admin_login": "관리자 로그인", + "notice.mail_limit": "메일 발송이 전체 한도에 도달했어요" } diff --git a/web/i18n/zh-CN.json b/web/i18n/zh-CN.json index 025ab36..f0da809 100644 --- a/web/i18n/zh-CN.json +++ b/web/i18n/zh-CN.json @@ -118,5 +118,8 @@ "flag.text": "这个账号被标记:吱吱次数超过理论上限。", "flag.clear": "解除标记", "flag.cleared": "已解除标记", - "err.cooldown": "吱太快了,冷静 10 秒再吱" + "err.cooldown": "吱太快了,冷静 10 秒再吱", + "err.too_frequent": "操作太频繁,请稍后再试", + "notice.admin_login": "管理员登录", + "notice.mail_limit": "发信数量到达全站上限" } diff --git a/web/i18n/zh-TW.json b/web/i18n/zh-TW.json index 8f9c3b3..0dad0ea 100644 --- a/web/i18n/zh-TW.json +++ b/web/i18n/zh-TW.json @@ -118,5 +118,8 @@ "flag.text": "這個帳號被標記:吱吱次數超過理論上限。", "flag.clear": "解除標記", "flag.cleared": "已解除標記", - "err.cooldown": "吱太快了,冷靜 10 秒再吱" + "err.cooldown": "吱太快了,冷靜 10 秒再吱", + "err.too_frequent": "操作太頻繁,請稍後再試", + "notice.admin_login": "管理員登入", + "notice.mail_limit": "寄信數量到達全站上限" }