修改
1、微信回调签名验证绕过问题 2、联系请求竞态条件问题 3、contact列表count过滤bug 4、核心业务表索引添加
This commit is contained in:
@@ -2,6 +2,7 @@ from datetime import datetime, timezone, timedelta
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.dependencies import get_db, get_current_user
|
||||
@@ -19,37 +20,48 @@ async def create_contact_request(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
today_end = today_start + timedelta(days=1)
|
||||
today_str = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
count = await db.execute(
|
||||
select(func.count(ContactRequest.id))
|
||||
.where(ContactRequest.user_id == user.id)
|
||||
.where(ContactRequest.created_at >= today_start)
|
||||
.where(ContactRequest.created_at < today_end)
|
||||
)
|
||||
daily_count = count.scalar_one()
|
||||
async with db.begin_nested():
|
||||
user_result = await db.execute(
|
||||
select(User).where(User.id == user.id).with_for_update().limit(1)
|
||||
)
|
||||
locked_user = user_result.scalar_one_or_none()
|
||||
if not locked_user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
|
||||
|
||||
existing = await db.execute(
|
||||
select(ContactRequest.id)
|
||||
.where(ContactRequest.user_id == user.id)
|
||||
.where(ContactRequest.submit_date == today_str)
|
||||
.limit(1)
|
||||
)
|
||||
if existing.scalar_one_or_none():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="每个账号每天只能提交一次联系我们"
|
||||
)
|
||||
|
||||
if daily_count >= 1:
|
||||
try:
|
||||
contact_request = ContactRequest(
|
||||
id=generate_id(),
|
||||
user_id=user.id,
|
||||
phone=request.phone,
|
||||
company_name=request.company_name,
|
||||
industry=request.industry,
|
||||
name=request.name,
|
||||
message=request.message,
|
||||
submit_date=today_str,
|
||||
)
|
||||
db.add(contact_request)
|
||||
await db.commit()
|
||||
except IntegrityError:
|
||||
await db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="每个账号每天只能提交一次联系我们"
|
||||
)
|
||||
|
||||
contact_request = ContactRequest(
|
||||
id=generate_id(),
|
||||
user_id=user.id,
|
||||
phone=request.phone,
|
||||
company_name=request.company_name,
|
||||
industry=request.industry,
|
||||
name=request.name,
|
||||
message=request.message,
|
||||
)
|
||||
|
||||
db.add(contact_request)
|
||||
await db.commit()
|
||||
await db.refresh(contact_request)
|
||||
|
||||
return {"message": "提交成功,我们会尽快与您联系"}
|
||||
|
||||
|
||||
@@ -64,17 +76,20 @@ async def get_contact_requests(
|
||||
if not user.is_admin:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="无权限")
|
||||
|
||||
query = select(ContactRequest).order_by(ContactRequest.created_at.desc())
|
||||
query = select(ContactRequest)
|
||||
count_query = select(func.count(ContactRequest.id))
|
||||
|
||||
if is_handled is not None:
|
||||
query = query.where(ContactRequest.is_handled == is_handled)
|
||||
count_query = count_query.where(ContactRequest.is_handled == is_handled)
|
||||
|
||||
query = query.order_by(ContactRequest.created_at.desc())
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
result = await db.execute(query.offset(offset).limit(page_size))
|
||||
items = result.scalars().all()
|
||||
|
||||
count_result = await db.execute(select(func.count(ContactRequest.id)))
|
||||
total = count_result.scalar_one()
|
||||
total = (await db.execute(count_query)).scalar_one()
|
||||
|
||||
return {"items": items, "total": total}
|
||||
|
||||
|
||||
@@ -127,30 +127,32 @@ async def wechat_callback(request: Request, db: AsyncSession = Depends(get_db)):
|
||||
signature = headers.get("wechatpay-signature", "")
|
||||
serial_no = headers.get("wechatpay-serial", "")
|
||||
|
||||
# 安全要求:非mock模式下必须验证签名,配置缺失直接拒绝
|
||||
if not public_key:
|
||||
logger.error("WeChat platform public key not configured, cannot verify callback signature")
|
||||
return {"code": "FAIL", "message": "Platform public key not configured"}
|
||||
if not serial_no:
|
||||
logger.error("Wechatpay-Serial header missing in callback")
|
||||
return {"code": "FAIL", "message": "Missing Wechatpay-Serial header"}
|
||||
if not timestamp or not nonce or not signature:
|
||||
logger.error("WeChat callback missing required signature headers")
|
||||
return {"code": "FAIL", "message": "Missing signature headers"}
|
||||
|
||||
# 验证签名:使用平台公钥验证
|
||||
if public_key and serial_no:
|
||||
try:
|
||||
# 构造签名串:timestamp + "\n" + nonce + "\n" + body + "\n"
|
||||
# 符合微信支付官方文档规范:https://pay.weixin.qq.com/doc/v3/merchant/4013053249
|
||||
is_verified = rsa_verify(
|
||||
timestamp=timestamp,
|
||||
nonce=nonce,
|
||||
body=body_str,
|
||||
signature=signature,
|
||||
public_key=load_public_key(public_key)
|
||||
)
|
||||
if not is_verified:
|
||||
logger.warning(f"WeChat callback signature verification failed: serial={serial_no}")
|
||||
raise HTTPException(status_code=400, detail="签名验证失败")
|
||||
except Exception as e:
|
||||
logger.warning(f"WeChat signature verification error: {e}, serial={serial_no}")
|
||||
raise HTTPException(status_code=400, detail="签名验证失败")
|
||||
else:
|
||||
if not public_key:
|
||||
logger.warning("WeChat platform public key not configured, skipping signature verification")
|
||||
if not serial_no:
|
||||
logger.warning("Wechatpay-Serial header missing, skipping signature verification")
|
||||
try:
|
||||
is_verified = rsa_verify(
|
||||
timestamp=timestamp,
|
||||
nonce=nonce,
|
||||
body=body_str,
|
||||
signature=signature,
|
||||
public_key=load_public_key(public_key)
|
||||
)
|
||||
if not is_verified:
|
||||
logger.warning(f"WeChat callback signature verification failed: serial={serial_no}")
|
||||
return {"code": "FAIL", "message": "Signature verification failed"}
|
||||
except Exception as e:
|
||||
logger.warning(f"WeChat signature verification error: {e}, serial={serial_no}")
|
||||
return {"code": "FAIL", "message": "Signature verification error"}
|
||||
|
||||
# 解密回调数据:使用 API v3 key
|
||||
# 官方文档:https://pay.weixin.qq.com/doc/v3/merchant/4012071382
|
||||
|
||||
Reference in New Issue
Block a user