fix: 全量代码审计修复—安全/死代码/错误处理/配置净化

P0 安全修复:
  - 支付宝回调验签 (alipay_notify BTreeMap + rsa2_verify)
  - JWT fallback 'default_secret' 改为 .expect() (panic保底)
  - 安全响应头中间件 (CSP/X-Frame-Options/HSTS)

P1 死代码清理:
  - 移除孤儿文件 src/alipay.rs (284行, 无mod注册)
  - 移除Cargo未使用依赖 (actix-files/error/log/hex/digest)
  - log::info! → tracing::info! (auth.rs)
  - 移除 config.rs server_host + 3个TOML定义

P1 质量修复:
  - 修复 weather.rs unwrap() → unwrap_or
  - 修复 auth.rs+payment.rs 错误吞咽 (add tracing::warn)
  - 修复 main.rs 3x parse().unwrap → unwrap_or

P3 运维:
  - 新增 scripts/backup-db.sh (定时备份用)
  - 新增 README.md (快速入门文档)
  - deploy.sh 集成 backup-db.sh 上传
This commit is contained in:
moira
2026-05-13 17:15:36 +08:00
parent cb483298d5
commit 27c8979690
14 changed files with 224 additions and 405 deletions

View File

@@ -509,7 +509,7 @@ pub async fn web_login_confirm(
app_state: web::Data<AppState>,
) -> impl Responder {
let short_code = req.code.trim();
log::info!("[web_login_confirm] received code={}", short_code);
tracing::info!("[web_login_confirm] received code={}", short_code);
// 精确匹配登录码
let record: Option<(String, String, chrono::DateTime<chrono::Utc>, Option<i32>)> =
@@ -519,6 +519,7 @@ pub async fn web_login_confirm(
.bind(short_code)
.fetch_optional(pool.get_ref())
.await
.inspect_err(|e| tracing::warn!("数据库查询登录码失败: {}", e))
.ok()
.flatten();
@@ -537,10 +538,13 @@ pub async fn web_login_confirm(
// 检查是否过期
if Utc::now() > expires_at {
// 清理过期码
let _ = sqlx::query("DELETE FROM web_login_codes WHERE code = $1")
if let Err(e) = sqlx::query("DELETE FROM web_login_codes WHERE code = $1")
.bind(&code)
.execute(pool.get_ref())
.await;
.await
{
tracing::warn!("清理过期登录码失败: {}", e);
}
return HttpResponse::Ok().json(WebLoginConfirmResponse {
success: false,
token: None,
@@ -597,12 +601,14 @@ pub async fn web_login_confirm(
};
// 更新登录码记录,设置 token而非删除让轮询接口能查到
sqlx::query("UPDATE web_login_codes SET token = $1 WHERE code = $2")
if let Err(e) = sqlx::query("UPDATE web_login_codes SET token = $1 WHERE code = $2")
.bind(&token)
.bind(&code)
.execute(pool.get_ref())
.await
.ok();
{
tracing::warn!("更新登录码 token 失败: {}", e);
}
info!("[WEB LOGIN CONFIRM] user_id={} is_paid={}", user_id, is_paid_active);
HttpResponse::Ok().json(WebLoginConfirmResponse {

View File

@@ -159,7 +159,6 @@ function confirmMockPay() {{
}
/// 验证 RSA2 签名
#[allow(dead_code)]
fn rsa2_verify(content: &str, sign: &str, public_key_pem: &str) -> Result<bool, String> {
use rsa::pkcs8::DecodePublicKey;
use rsa::RsaPublicKey;
@@ -266,7 +265,7 @@ fn extract_token(req: &HttpRequest) -> Option<String> {
}
fn get_jwt_secret() -> String {
std::env::var("JWT_SECRET").unwrap_or_else(|_| "default_secret".to_string())
std::env::var("JWT_SECRET").expect("JWT_SECRET must be set")
}
// ===== Handler: GET /payment — 套餐选择页(网页端微信扫码登录) =====
@@ -710,42 +709,56 @@ pub async fn alipay_pay_page(
// ===== Handler: POST /payment/notify — 支付宝异步回调 =====
#[derive(Debug, Deserialize)]
pub struct AlipayNotify {
pub out_trade_no: String,
pub trade_no: String,
pub trade_status: String,
pub total_amount: Option<String>,
pub app_id: Option<String>,
pub sign: Option<String>,
}
#[post("/payment/notify")]
pub async fn alipay_notify(
pool: web::Data<PgPool>,
body: web::Form<AlipayNotify>,
body: web::Form<BTreeMap<String, String>>,
) -> HttpResponse {
let body = body.into_inner();
let out_trade_no = body.get("out_trade_no").cloned().unwrap_or_default();
let trade_status = body.get("trade_status").cloned().unwrap_or_default();
tracing::info!(
"收到支付宝回调: out_trade_no={}, trade_status={}",
body.out_trade_no,
body.trade_status
out_trade_no,
trade_status
);
// 1. 检查交易状态
if body.trade_status != "TRADE_SUCCESS" && body.trade_status != "TRADE_FINISHED" {
if trade_status != "TRADE_SUCCESS" && trade_status != "TRADE_FINISHED" {
return HttpResponse::Ok().body("success");
}
// 2. 确认订单(通过 order_no不校验 user_id
match db::confirm_payment_order_by_orderno(pool.get_ref(), &body.out_trade_no).await {
// 2. 验证 RSA2 签名(防止伪造回调
let Some(config) = AlipayConfig::from_env() else {
tracing::warn!("支付宝配置不存在,无法验证签名");
return HttpResponse::Ok().body("fail");
};
let sign = body.get("sign").cloned().unwrap_or_default();
// BTreeMap 已按 key 排序,直接拼接除 sign 和 sign_type 外的所有参数
let sign_source: String = body
.iter()
.filter(|(k, _)| *k != "sign" && *k != "sign_type")
.map(|(k, v)| format!("{}={}", k, v))
.collect::<Vec<_>>()
.join("&");
if let Err(e) = rsa2_verify(&sign_source, &sign, &config.alipay_public_key) {
tracing::warn!("支付宝签名验证失败: {}", e);
return HttpResponse::Ok().body("fail");
}
// 3. 确认订单(通过 order_no不校验 user_id
match db::confirm_payment_order_by_orderno(pool.get_ref(), &out_trade_no).await {
Ok(_) => {
tracing::info!("订单 {} 支付确认成功", body.out_trade_no);
tracing::info!("订单 {} 支付确认成功", out_trade_no);
HttpResponse::Ok().body("success")
}
Err(e) => {
tracing::error!("订单 {} 确认失败: {}", body.out_trade_no, e);
tracing::error!("订单 {} 确认失败: {}", out_trade_no, e);
HttpResponse::Ok().body("fail")
}
}
@@ -1072,10 +1085,13 @@ pub async fn payment_login_status(
// 检查是否过期
if Utc::now() > expires_at {
let _ = sqlx::query("DELETE FROM web_login_codes WHERE code = $1")
if let Err(e) = sqlx::query("DELETE FROM web_login_codes WHERE code = $1")
.bind(&db_code)
.execute(pool.get_ref())
.await;
.await
{
tracing::warn!("清理过期登录码失败: {}", e);
}
return Ok(HttpResponse::Ok().json(LoginStatusResponse {
success: false,
confirmed: false,

View File

@@ -83,11 +83,11 @@ pub async fn get_weather_details(
(temp_claims.openid, temp_claims.resource_id)
} else if let Some(claims) = claims_from_header() {
let weather_id = match query.get("id") {
Some(v) if v.is_i64() => v.as_i64().unwrap() as i32,
Some(v) if v.is_i64() => v.as_i64().unwrap_or(0) as i32,
Some(v) if v.is_string() => {
v.as_str().and_then(|s| s.parse::<i32>().ok()).unwrap_or(0)
}
Some(v) if v.is_number() => v.as_f64().unwrap() as i32,
Some(v) if v.is_number() => v.as_f64().map(|f| f as i32).unwrap_or(0),
_ => {
return Err(AppError::BadRequest("缺少资源ID参数id".to_string()));
}