fix: 拒绝过短密钥,并把对外端口只留在本机

This commit is contained in:
2026-11-16 02:41:13 +08:00
parent 42f2b457a0
commit ec41af9489
11 changed files with 85 additions and 12 deletions
+2
View File
@@ -5,3 +5,5 @@ EUNIV_DB_PATH=data/euniv.db
EUNIV_ADMIN_PASSWORD= EUNIV_ADMIN_PASSWORD=
# 设为 1 时,启动按上面的口令重置管理员密码 # 设为 1 时,启动按上面的口令重置管理员密码
EUNIV_ADMIN_RESET= EUNIV_ADMIN_RESET=
# 本地 http 开发设为 0;对外只走 https 时设为 1
EUNIV_COOKIE_SECURE=0
+1
View File
@@ -15,5 +15,6 @@ COPY backend/alembic alembic
COPY backend/alembic.ini . COPY backend/alembic.ini .
COPY --from=web /src/web/dist /web/dist COPY --from=web /src/web/dist /web/dist
ENV EUNIV_DB_PATH=/data/euniv.db ENV EUNIV_DB_PATH=/data/euniv.db
ENV EUNIV_COOKIE_SECURE=1
EXPOSE 8000 EXPOSE 8000
CMD ["uvicorn", "euniv.api:app", "--host", "0.0.0.0", "--port", "8000"] CMD ["uvicorn", "euniv.api:app", "--host", "0.0.0.0", "--port", "8000"]
+1
View File
@@ -28,3 +28,4 @@ class SystemConfig(Base):
admin_sessions_valid_after: Mapped[datetime] = mapped_column( admin_sessions_valid_after: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("CURRENT_TIMESTAMP") DateTime(timezone=True), nullable=False, server_default=text("CURRENT_TIMESTAMP")
) )
key_check: Mapped[str] = mapped_column(Text, nullable=False, default="", server_default="")
+20
View File
@@ -95,6 +95,26 @@ def ensure_admin_seed() -> None:
db.commit() db.commit()
def ensure_key_check() -> None:
"""密钥太短、是占位文字,或解不开已有数据时,拒绝启动。"""
from euniv.crypto import decrypt_secret, encrypt_secret, require_secret
from euniv.db import SessionLocal
require_secret()
with SessionLocal() as db:
row = load_config(db)
if not row.key_check:
row.key_check = encrypt_secret("euniv-key-check")
db.commit()
return
try:
matched = decrypt_secret(row.key_check) == "euniv-key-check"
except Exception as exc:
raise RuntimeError("EUNIV_SECRET_KEY 与已有数据不匹配,已停止启动") from exc
if not matched:
raise RuntimeError("EUNIV_SECRET_KEY 与已有数据不匹配,已停止启动")
def load_admin_identity() -> None: def load_admin_identity() -> None:
"""从设置表重新加载管理员用户名和密码密文。""" """从设置表重新加载管理员用户名和密码密文。"""
from euniv.db import SessionLocal from euniv.db import SessionLocal
@@ -0,0 +1,20 @@
"""启动时用一列密文确认密钥没有换错。"""
from alembic import op
import sqlalchemy as sa
revision = "0003_key_check"
down_revision = "0002_sessions"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column(
"system_config",
sa.Column("key_check", sa.Text(), server_default="", nullable=False),
)
def downgrade() -> None:
op.drop_column("system_config", "key_check")
+3
View File
@@ -71,6 +71,9 @@ class StudyControlBody(_BaseModel):
async def lifespan(_app: FastAPI): async def lifespan(_app: FastAPI):
init_db() init_db()
ensure_admin_seed() ensure_admin_seed()
from admin.settings import ensure_key_check
ensure_key_check()
load_admin_identity() load_admin_identity()
from euniv.study_push import attach_loop from euniv.study_push import attach_loop
+12 -8
View File
@@ -9,11 +9,18 @@ import os
from cryptography.fernet import Fernet from cryptography.fernet import Fernet
_PLACEHOLDER_SECRETS = {"请换成一串只放在服务器上的密钥"}
def require_secret() -> str:
secret = os.environ.get("EUNIV_SECRET_KEY", "").strip()
if len(secret) < 32 or secret in _PLACEHOLDER_SECRETS:
raise RuntimeError("EUNIV_SECRET_KEY 至少需要 32 个字符,且不能使用示例里的占位文字")
return secret
def _fernet() -> Fernet: def _fernet() -> Fernet:
secret = os.environ.get("EUNIV_SECRET_KEY", "") digest = hashlib.sha256(require_secret().encode("utf-8")).digest()
if not secret:
raise RuntimeError("请设置环境变量 EUNIV_SECRET_KEY")
digest = hashlib.sha256(secret.encode("utf-8")).digest()
return Fernet(base64.urlsafe_b64encode(digest)) return Fernet(base64.urlsafe_b64encode(digest))
@@ -30,15 +37,12 @@ def _cookie_fernet() -> Fernet:
from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives.kdf.hkdf import HKDF
secret = os.environ.get("EUNIV_SECRET_KEY", "")
if not secret:
raise RuntimeError("请设置环境变量 EUNIV_SECRET_KEY")
raw = HKDF( raw = HKDF(
algorithm=hashes.SHA256(), algorithm=hashes.SHA256(),
length=32, length=32,
salt=b"euniv-cookie-v1", salt=b"euniv-cookie-v1",
info=b"session", info=b"session",
).derive(secret.encode("utf-8")) ).derive(require_secret().encode("utf-8"))
return Fernet(base64.urlsafe_b64encode(raw)) return Fernet(base64.urlsafe_b64encode(raw))
+8 -1
View File
@@ -463,7 +463,14 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
client = None client = None
continue continue
raise raise
except Exception: except Exception as exc:
from cryptography.fernet import InvalidToken
if isinstance(exc, InvalidToken):
import logging
logging.getLogger("euniv.service").exception("账号 %s 的密文无法用当前密钥解开", employee_id)
return
db.rollback() db.rollback()
valid = False valid = False
account = db.get(Account, employee_id) account = db.get(Account, employee_id)
+4 -2
View File
@@ -8,10 +8,11 @@ _backend = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(_backend)) sys.path.insert(0, str(_backend))
_root = _backend.parent / "Temp" / "pytest" _root = _backend.parent / "Temp" / "pytest"
_root.mkdir(parents=True, exist_ok=True) _root.mkdir(parents=True, exist_ok=True)
os.environ["EUNIV_SECRET_KEY"] = "test-secret-key" os.environ["EUNIV_SECRET_KEY"] = "test-secret-key-0123456789abcdef"
os.environ["EUNIV_DB_PATH"] = str(_root / "euniv.db") os.environ["EUNIV_DB_PATH"] = str(_root / "euniv.db")
os.environ["EUNIV_DISABLE_REFRESH"] = "1" os.environ["EUNIV_DISABLE_REFRESH"] = "1"
os.environ["EUNIV_ADMIN_PASSWORD"] = "test-admin-pass" os.environ["EUNIV_ADMIN_PASSWORD"] = "test-admin-pass"
os.environ["EUNIV_COOKIE_SECURE"] = "0"
os.environ.pop("EUNIV_ADMIN_RESET", None) os.environ.pop("EUNIV_ADMIN_RESET", None)
@@ -19,7 +20,7 @@ os.environ.pop("EUNIV_ADMIN_RESET", None)
def fresh_database(): def fresh_database():
from sqlalchemy import text from sqlalchemy import text
from admin.settings import ensure_admin_seed, load_admin_identity from admin.settings import ensure_admin_seed, ensure_key_check, load_admin_identity
from euniv.db import engine, init_db from euniv.db import engine, init_db
with engine.begin() as connection: with engine.begin() as connection:
@@ -33,6 +34,7 @@ def fresh_database():
connection.execute(text("DROP TABLE IF EXISTS alembic_version")) connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
init_db() init_db()
ensure_admin_seed() ensure_admin_seed()
ensure_key_check()
load_admin_identity() load_admin_identity()
from admin.login_limit import reset from admin.login_limit import reset
+12
View File
@@ -14,6 +14,18 @@ from euniv.encrypt import (
) )
def test_short_secret_is_rejected(monkeypatch) -> None:
from euniv.crypto import require_secret
monkeypatch.setenv("EUNIV_SECRET_KEY", "too-short")
try:
require_secret()
except RuntimeError as exc:
assert "32" in str(exc)
else:
raise AssertionError("过短的密钥应当被拒绝")
def test_encrypt_payload_wraps_progress_json_as_string() -> None: def test_encrypt_payload_wraps_progress_json_as_string() -> None:
body = '{"knowledgeId":"abc","end":false}' body = '{"knowledgeId":"abc","end":false}'
assert encrypt_payload(body) == b'{"body":"{\\"knowledgeId\\":\\"abc\\",\\"end\\":false}"}' assert encrypt_payload(body) == b'{"body":"{\\"knowledgeId\\":\\"abc\\",\\"end\\":false}"}'
+2 -1
View File
@@ -3,12 +3,13 @@ services:
web: web:
build: . build: .
ports: ports:
- "8000:8000" - "127.0.0.1:8000:8000"
environment: environment:
EUNIV_SECRET_KEY: ${EUNIV_SECRET_KEY:?请在环境变量或 .env 中设置 EUNIV_SECRET_KEY} EUNIV_SECRET_KEY: ${EUNIV_SECRET_KEY:?请在环境变量或 .env 中设置 EUNIV_SECRET_KEY}
EUNIV_DB_PATH: /data/euniv.db EUNIV_DB_PATH: /data/euniv.db
EUNIV_ADMIN_PASSWORD: ${EUNIV_ADMIN_PASSWORD:-} EUNIV_ADMIN_PASSWORD: ${EUNIV_ADMIN_PASSWORD:-}
EUNIV_ADMIN_RESET: ${EUNIV_ADMIN_RESET:-} EUNIV_ADMIN_RESET: ${EUNIV_ADMIN_RESET:-}
EUNIV_COOKIE_SECURE: ${EUNIV_COOKIE_SECURE:-1}
volumes: volumes:
- euniv-data:/data - euniv-data:/data