fix: 拒绝过短密钥,并把对外端口只留在本机
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user