fix: 拒绝过短密钥,并把对外端口只留在本机
This commit is contained in:
@@ -28,3 +28,4 @@ class SystemConfig(Base):
|
||||
admin_sessions_valid_after: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=text("CURRENT_TIMESTAMP")
|
||||
)
|
||||
key_check: Mapped[str] = mapped_column(Text, nullable=False, default="", server_default="")
|
||||
|
||||
@@ -95,6 +95,26 @@ def ensure_admin_seed() -> None:
|
||||
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:
|
||||
"""从设置表重新加载管理员用户名和密码密文。"""
|
||||
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")
|
||||
@@ -71,6 +71,9 @@ class StudyControlBody(_BaseModel):
|
||||
async def lifespan(_app: FastAPI):
|
||||
init_db()
|
||||
ensure_admin_seed()
|
||||
from admin.settings import ensure_key_check
|
||||
|
||||
ensure_key_check()
|
||||
load_admin_identity()
|
||||
from euniv.study_push import attach_loop
|
||||
|
||||
|
||||
+12
-8
@@ -9,11 +9,18 @@ import os
|
||||
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:
|
||||
secret = os.environ.get("EUNIV_SECRET_KEY", "")
|
||||
if not secret:
|
||||
raise RuntimeError("请设置环境变量 EUNIV_SECRET_KEY")
|
||||
digest = hashlib.sha256(secret.encode("utf-8")).digest()
|
||||
digest = hashlib.sha256(require_secret().encode("utf-8")).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.kdf.hkdf import HKDF
|
||||
|
||||
secret = os.environ.get("EUNIV_SECRET_KEY", "")
|
||||
if not secret:
|
||||
raise RuntimeError("请设置环境变量 EUNIV_SECRET_KEY")
|
||||
raw = HKDF(
|
||||
algorithm=hashes.SHA256(),
|
||||
length=32,
|
||||
salt=b"euniv-cookie-v1",
|
||||
info=b"session",
|
||||
).derive(secret.encode("utf-8"))
|
||||
).derive(require_secret().encode("utf-8"))
|
||||
return Fernet(base64.urlsafe_b64encode(raw))
|
||||
|
||||
|
||||
|
||||
@@ -463,7 +463,14 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
|
||||
client = None
|
||||
continue
|
||||
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()
|
||||
valid = False
|
||||
account = db.get(Account, employee_id)
|
||||
|
||||
@@ -8,10 +8,11 @@ _backend = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(_backend))
|
||||
_root = _backend.parent / "Temp" / "pytest"
|
||||
_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_DISABLE_REFRESH"] = "1"
|
||||
os.environ["EUNIV_ADMIN_PASSWORD"] = "test-admin-pass"
|
||||
os.environ["EUNIV_COOKIE_SECURE"] = "0"
|
||||
os.environ.pop("EUNIV_ADMIN_RESET", None)
|
||||
|
||||
|
||||
@@ -19,7 +20,7 @@ os.environ.pop("EUNIV_ADMIN_RESET", None)
|
||||
def fresh_database():
|
||||
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
|
||||
|
||||
with engine.begin() as connection:
|
||||
@@ -33,6 +34,7 @@ def fresh_database():
|
||||
connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
||||
init_db()
|
||||
ensure_admin_seed()
|
||||
ensure_key_check()
|
||||
load_admin_identity()
|
||||
from admin.login_limit import reset
|
||||
|
||||
|
||||
@@ -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:
|
||||
body = '{"knowledgeId":"abc","end":false}'
|
||||
assert encrypt_payload(body) == b'{"body":"{\\"knowledgeId\\":\\"abc\\",\\"end\\":false}"}'
|
||||
|
||||
Reference in New Issue
Block a user