回调验证和调试日志
This commit is contained in:
1 parent
f15f4162eb
commit
4818f25d8f
4 files changed
+164
-56
No files matched your search
+75
-56
@@ -1,88 +1,107 @@
|
||||
package com.ruoyi.system.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.system.rental.RentalCallbackDemoController;
|
||||
import com.ruoyi.system.rental.RentalStore;
|
||||
import com.ruoyi.system.rental.RentalValues;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.util.UriUtils;
|
||||
|
||||
/**
|
||||
* 通用 Webhook 免登录调试入口。只用于确认网络连通和观察回调数据,
|
||||
* 不校验业务签名、不修改订单,也不代表业务回调已验签或已处理成功。
|
||||
*/
|
||||
/** 租赁回调验签调试端:按原始正文验证WEBHOOK域HMAC,仅记录事件摘要,不修改订单。 */
|
||||
@RestController
|
||||
public class WebhookDebugController {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WebhookDebugController.class);
|
||||
private static final int MAX_BODY_BYTES = 512 * 1024;
|
||||
private final RentalStore store;
|
||||
private final ObjectMapper json;
|
||||
@Value("${rental.webhook-debug.api-key:}")
|
||||
private String apiKey;
|
||||
@Value("${rental.webhook-debug.api-secret:}")
|
||||
private String apiSecret;
|
||||
/** 显式配置外部原始路径;不信任调用方传入的Forwarded头。空值使用请求URI。 */
|
||||
@Value("${rental.webhook-debug.signature-path:}")
|
||||
private String signaturePath;
|
||||
|
||||
/** 限制单次读取量,避免匿名请求产生无限大的日志或内存占用。 */
|
||||
private static final int MAX_BODY_BYTES = 64 * 1024;
|
||||
public WebhookDebugController(RentalStore store, ObjectMapper json) {
|
||||
this.store = store;
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
/** JSON、表单和查询参数中的常见凭据不得直接写入日志。 */
|
||||
private static final Pattern SENSITIVE_VALUE = Pattern.compile(
|
||||
"(?i)([\"']?(?:token_key|private_key|privateKey|api_secret|apiSecret|password|"
|
||||
+ "mnemonic|authorization|secret|access_token|token|signature)[\"']?\\s*[:=]\\s*)"
|
||||
+ "(\"(?:\\\\.|[^\"\\\\])*\"|'[^']*'|[^&\\s,}]+)");
|
||||
|
||||
/**
|
||||
* 接受任意 HTTP 方法和正文格式,兼容 JSON、表单及纯文本回调。
|
||||
* 正常接收返回 HTTP 200 和纯文本 ok,便于回调发送方确认送达。
|
||||
* 仅记录 Content-Type 等必要元数据,不记录可能携带令牌的请求头。
|
||||
*
|
||||
* @param request 原始回调请求
|
||||
* @return 回调接收确认;正文超过上限时返回 HTTP 413
|
||||
* @throws IOException 请求流读取失败时由框架返回错误,不伪装成成功
|
||||
*/
|
||||
@RequestMapping(value = "/api/webhook/debug", produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
@PostMapping(value = "/api/webhook/debug", consumes = MediaType.APPLICATION_JSON_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
public ResponseEntity<String> receive(HttpServletRequest request) throws IOException {
|
||||
if (apiKey == null || apiKey.isEmpty() || apiSecret == null || apiSecret.isEmpty()) {
|
||||
LOG.warn("租赁调试回调拒绝 reason=CREDENTIAL_NOT_CONFIGURED");
|
||||
return ResponseEntity.status(503).body("callback credentials not configured");
|
||||
}
|
||||
String path = signaturePath == null || signaturePath.isEmpty() ? request.getRequestURI() : signaturePath;
|
||||
LOG.info("租赁调试回调接收 method=POST requestPath={} signaturePath={} contentLength={}",
|
||||
safe(request.getRequestURI()), safe(path), request.getContentLengthLong());
|
||||
byte[] buffer = new byte[MAX_BODY_BYTES + 1];
|
||||
int total = 0;
|
||||
int count;
|
||||
while (total < buffer.length
|
||||
&& (count = request.getInputStream().read(buffer, total, buffer.length - total)) != -1) {
|
||||
// 只获取一次输入流,防止可重复读取包装器在循环中重复返回正文。
|
||||
ServletInputStream stream = request.getInputStream();
|
||||
while (total < buffer.length && (count = stream.read(buffer, total, buffer.length - total)) != -1) {
|
||||
total += count;
|
||||
}
|
||||
if (total > MAX_BODY_BYTES) {
|
||||
LOG.warn("Webhook debug rejected: body exceeds {} bytes", MAX_BODY_BYTES);
|
||||
LOG.warn("租赁调试回调拒绝 reason=BODY_TOO_LARGE");
|
||||
return ResponseEntity.status(413).body("payload too large");
|
||||
}
|
||||
String body = new String(buffer, 0, total, StandardCharsets.UTF_8);
|
||||
String query = request.getQueryString();
|
||||
// 表单先解码再脱敏,防止百分号编码的字段名绕过敏感字段匹配。
|
||||
if (request.getContentType() != null
|
||||
&& request.getContentType().startsWith(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
|
||||
body = decode(body);
|
||||
final JsonNode event;
|
||||
String stage = "SIGNATURE";
|
||||
try {
|
||||
String body = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
|
||||
.decode(ByteBuffer.wrap(buffer, 0, total)).toString();
|
||||
RentalCallbackDemoController.verify(apiKey, apiSecret, request.getHeader("X-Rent-Key"),
|
||||
Long.parseLong(request.getHeader("X-Rent-Timestamp")), request.getHeader("X-Rent-Nonce"),
|
||||
path, body, request.getHeader("X-Rent-Signature"), System.currentTimeMillis());
|
||||
stage = "EVENT_JSON";
|
||||
event = json.readTree(body);
|
||||
RentalValues.require(event != null && event.isObject() && event.path("event_no").isTextual()
|
||||
&& !event.path("event_no").asText().isEmpty()
|
||||
&& event.path("event_no").asText().length() <= 64, "通知事件无效");
|
||||
} catch (Exception ex) {
|
||||
// 不输出异常原文、认证请求头、Secret、签名及正文。
|
||||
LOG.warn("租赁调试回调拒绝 stage={} reason=INVALID_NOTIFICATION exceptionType={}",
|
||||
stage, ex.getClass().getSimpleName());
|
||||
return ResponseEntity.status("SIGNATURE".equals(stage) ? 401 : 400).body("invalid notification");
|
||||
}
|
||||
LOG.info("Webhook debug received: method={}, path={}, remote={}, contentType={}, query={}, body={}",
|
||||
new Object[] {request.getMethod(), request.getRequestURI(), request.getRemoteAddr(),
|
||||
safe(request.getContentType()), safe(decode(query)), safe(body)});
|
||||
try {
|
||||
// 独立scope和数据库唯一键跨实例防重放;合法事件重投使用新nonce。
|
||||
// 此接口不执行记账,重复event_no允许观察;正式业务应另做事件幂等处理。
|
||||
store.insert("nonce", RentalValues.map("api_key", apiKey, "scope", "DEBUG_WEBHOOK",
|
||||
"nonce", request.getHeader("X-Rent-Nonce"), "expires_at", RentalValues.after(180)));
|
||||
} catch (DuplicateKeyException ex) {
|
||||
LOG.warn("租赁调试回调拒绝 reason=NONCE_REPLAY");
|
||||
return ResponseEntity.status(409).body("replayed notification");
|
||||
} catch (Exception ex) {
|
||||
LOG.warn("租赁调试回调拒绝 reason=NONCE_STORAGE_FAILED exceptionType={}", ex.getClass().getSimpleName());
|
||||
return ResponseEntity.status(503).body("retry later");
|
||||
}
|
||||
LOG.info("租赁调试回调验签成功 eventNo={} orderNo={} eventType={} orderType={} status={} bodyBytes={}",
|
||||
safe(event.path("event_no").asText()), safe(event.path("order_no").asText()),
|
||||
safe(event.path("event_type").asText()), safe(event.path("order_type").asText()),
|
||||
safe(event.path("status").asText()), total);
|
||||
return ResponseEntity.ok("ok");
|
||||
}
|
||||
|
||||
/** 非法 URL 编码不回显原文,避免错误日志泄露凭据。 */
|
||||
private static String decode(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return UriUtils.decode(value, StandardCharsets.UTF_8.name());
|
||||
} catch (Exception exception) {
|
||||
return "[invalid URL encoding]";
|
||||
}
|
||||
}
|
||||
|
||||
/** 脱敏后转义换行,确保一条回调对应一条日志,避免伪造日志行。 */
|
||||
private static String safe(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
return SENSITIVE_VALUE.matcher(value).replaceAll("$1\"***\"")
|
||||
.replace("\r", "\\r").replace("\n", "\\n");
|
||||
String clean = value.replaceAll("[\\p{Cntrl}]", "_");
|
||||
return clean.substring(0, Math.min(clean.length(), 256));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user