From 1151dc253518324282bec89e0cfbafb469cd1398 Mon Sep 17 00:00:00 2001 From: luqingjie <544309509@qq.com> Date: Mon, 2 Nov 2026 22:34:18 -0500 Subject: [PATCH] =?UTF-8?q?=E5=9B=9E=E8=B0=83=E9=97=AE=E9=A2=98=E5=A4=84?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/rental-address-onchain.md | 7 +- docs/rental-webhook-405.md | 2 +- .../src/main/resources/application-rental.yml | 3 +- .../system/WebhookDebugControllerTest.java | 28 +++++++- .../controller/WebhookDebugController.java | 64 ++++++++++++++++--- .../rental/RentalCallbackDemoController.java | 10 ++- .../ruoyi/system/rental/RentalWorkers.java | 1 + 7 files changed, 99 insertions(+), 16 deletions(-) diff --git a/docs/rental-address-onchain.md b/docs/rental-address-onchain.md index 1ef536b..600e23f 100644 --- a/docs/rental-address-onchain.md +++ b/docs/rental-address-onchain.md @@ -142,17 +142,20 @@ WAITING且没有任务表示尚未派单;已有PENDING任务则继续检查Soc ### 调试接收端验签 -`WebhookDebugController`的`POST /api/webhook/debug`仅接收application/json。使用原始UTF-8正文和X-Rent-Key/Timestamp/Nonce/Signature请求头,复用租赁WEBHOOK域HMAC-SHA256协议,允许时间偏差小于60秒;正文上限512KiB。GET返回405,未配置凭证返回503,认证失败401,事件JSON无效400,nonce重放409;仅验签及持久化nonce成功返回纯文本ok。不更新业务订单,不用于正式记账,合法事件重投携带新nonce时可再次观察。 +`WebhookDebugController`的`POST /api/webhook/debug`仅接收application/json。使用原始UTF-8正文和X-Rent-Key/Timestamp/Nonce/Signature请求头,复用租赁WEBHOOK域HMAC-SHA256协议,允许时间偏差小于60秒;正文上限512KiB。GET返回405,CONFIGURED模式缺凭证或存储故障503,认证失败401,事件JSON无效400,nonce重放409;仅验签及持久化nonce成功返回纯文本ok。不更新业务订单,不用于正式记账,合法事件重投携带新nonce时可再次观察。 ```yaml rental: webhook-debug: + credential-source: ${RENT_WEBHOOK_DEBUG_CREDENTIAL_SOURCE:APP} api-key: ${RENT_WEBHOOK_DEBUG_API_KEY:} api-secret: ${RENT_WEBHOOK_DEBUG_API_SECRET:} signature-path: ${RENT_WEBHOOK_DEBUG_SIGNATURE_PATH:} ``` -凭证必须与发送器当前选择的APP有效凭证一致;轮换后同步更新接收端。路径必须与外部notify_url路径逐字一致:例如回调地址为`http://192.168.3.103/api/api/webhook/debug`,Nginx移除一层/api后,设置`RENT_WEBHOOK_DEBUG_SIGNATURE_PATH=/api/api/webhook/debug`。留空使用后端实际请求URI,不能从不可信转发头推断路径。不将Secret、签名、完整正文或异常原文写日志;成功记录事件号、订单号、事件类型及状态摘要。修改配置后重启服务。此接口映射不能修复Nginx静态服务产生的405,仍需确保POST转发到后端2020端口。 +默认APP模式按请求X-Rent-Key查询本系统ACTIVE且未过期的APP凭证并解密Secret验签,不需要填写固定api-key/api-secret;未知、NODE、停用或过期凭证拒绝。适用于同系统调试,能够验证各应用轮换后的真实签名,不能作为外部商户生产回调的身份授权模型。CONFIGURED模式使用上面的固定凭证,必须与发送器当前选择的APP有效凭证一致;轮换后同步更新接收端。路径必须与外部notify_url路径逐字一致:例如回调地址为`http://192.168.3.103/api/api/webhook/debug`,Nginx移除一层/api后,设置`RENT_WEBHOOK_DEBUG_SIGNATURE_PATH=/api/api/webhook/debug`。留空使用后端实际请求URI,不能从不可信转发头推断路径。不将Secret、签名、完整正文或异常原文写日志;成功记录事件号、订单号、事件类型及状态摘要。修改配置后重启服务。此接口映射不能修复Nginx静态服务产生的405,仍需确保POST转发到后端2020端口。 + +认证诊断不再合并为“通知认证参数无效”:分别记录KEY_MISSING、KEY_MISMATCH、ACTIVE_APP_CREDENTIAL_NOT_FOUND、NONCE_INVALID、TIMESTAMP_NOT_UNIX_MILLIS、TIMESTAMP_OUT_OF_WINDOW及SIGNATURE_MISMATCH_CHECK_SECRET_PATH_AND_BODY。日志提供Key不可逆摘要、时间差毫秒数、nonce长度,不记录认证原文。HTTP时间戳是Unix毫秒,与DATETIME存储时区无关,不允许手工加8小时或取消时间窗验证。独立demo接收端仍使用其固定配置,并返回具体参数校验说明。 在服务端日志中按 `webhookId` 或 `orderId` 查询“租赁回调”。日志依次包含领取次数/正文字节数、目标主机/路径、有效凭证记录ID、POST请求开始、HTTP响应状态/长度和最终状态;异常包含失败阶段及安全的异常类型/代码位置,不输出Secret、签名、请求正文或响应正文。`rent_webhook.last_error`同步保存固定阶段和原因码。 diff --git a/docs/rental-webhook-405.md b/docs/rental-webhook-405.md index e6ad58c..9b0ecd5 100644 --- a/docs/rental-webhook-405.md +++ b/docs/rental-webhook-405.md @@ -26,7 +26,7 @@ curl -i --connect-timeout 3 --max-time 10 \ sudo nginx -T ``` -新版后端在缺凭证时应返回503,配置凭证但无签名返回401,并带后端标记;不应返回405。不要为测试返回ok而关闭验签。 +新版后端默认APP模式,无认证请求头应返回401;CONFIGURED模式缺凭证时返回503,有凭证但无签名返回401,并带后端标记;不应返回405。不要为测试返回ok而关闭验签。 如果Nginx和后端同机、后端端口为2020,在实际监听80、匹配192.168.3.103的server块添加以下精确location(不是放在只监听443的server块): diff --git a/ruoyi-admin/src/main/resources/application-rental.yml b/ruoyi-admin/src/main/resources/application-rental.yml index f566df2..0b26cf5 100644 --- a/ruoyi-admin/src/main/resources/application-rental.yml +++ b/ruoyi-admin/src/main/resources/application-rental.yml @@ -9,7 +9,8 @@ rental: # 允许192.168/10/172.16~31及IPv6 ULA内网HTTP/HTTPS回调;HTTP允许自定义端口,HTTPS仍验证证书。 allow-private-network: ${RENT_WEBHOOK_ALLOW_PRIVATE_NETWORK:true} webhook-debug: - # 填写发送回调使用的有效APP凭证;缺失返回503,不跳过验签。 + # APP按请求Key读取当前有效应用凭证验签,避免轮换后固定Key不匹配;CONFIGURED使用下面的独立凭证。 + credential-source: ${RENT_WEBHOOK_DEBUG_CREDENTIAL_SOURCE:APP} api-key: ${RENT_WEBHOOK_DEBUG_API_KEY:} api-secret: ${RENT_WEBHOOK_DEBUG_API_SECRET:} # 签名使用外部URL路径;代理移除前缀时可填写/api/api/webhook/debug。 diff --git a/ruoyi-admin/src/test/java/com/ruoyi/web/controller/system/WebhookDebugControllerTest.java b/ruoyi-admin/src/test/java/com/ruoyi/web/controller/system/WebhookDebugControllerTest.java index d595c65..466ab9c 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/web/controller/system/WebhookDebugControllerTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/web/controller/system/WebhookDebugControllerTest.java @@ -5,6 +5,7 @@ import com.ruoyi.system.controller.WebhookDebugController; import com.ruoyi.system.controller.WebhookDebugTraceFilter; import com.ruoyi.system.rental.RentalCrypto; import com.ruoyi.system.rental.RentalStore; +import com.ruoyi.system.rental.RentalIdentity; import org.junit.Test; import org.springframework.dao.DuplicateKeyException; import org.springframework.mock.web.MockHttpServletRequest; @@ -19,11 +20,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. /** 验证原文签名、代理路径、重放和HTTP方法,不连接真实数据库或回调目标。 */ public class WebhookDebugControllerTest { private final RentalStore store = mock(RentalStore.class); - private final WebhookDebugController controller = new WebhookDebugController(store, new ObjectMapper()); + private final RentalIdentity identity = mock(RentalIdentity.class); + private final WebhookDebugController controller = new WebhookDebugController(store, new ObjectMapper(), identity); private final String body = "{\"event_no\":\"WH-test\",\"event_type\":\"SUCCESS\"}"; private final String externalPath = "/api/api/webhook/debug"; private void configure() { + ReflectionTestUtils.setField(controller, "credentialSource", "CONFIGURED"); ReflectionTestUtils.setField(controller, "apiKey", "test-key"); ReflectionTestUtils.setField(controller, "apiSecret", "test-secret"); ReflectionTestUtils.setField(controller, "signaturePath", externalPath); @@ -59,6 +62,7 @@ public class WebhookDebugControllerTest { } @Test public void postMappingAndMissingConfigurationAreExplicit() throws Exception { + ReflectionTestUtils.setField(controller, "credentialSource", "CONFIGURED"); MockMvc mvc = MockMvcBuilders.standaloneSetup(controller).addFilters(new WebhookDebugTraceFilter()).build(); mvc.perform(get("/api/webhook/debug").header("X-Rent-Callback-Id", "test-callback")) .andExpect(status().isMethodNotAllowed()) @@ -70,4 +74,26 @@ public class WebhookDebugControllerTest { mvc.perform(post("/api/webhook/debug").contentType("application/json").content(body)) .andExpect(status().isUnauthorized()); } + + @Test public void appModeUsesActualSigningCredentialInsteadOfStaleConfiguredKey() throws Exception { + configure(); + ReflectionTestUtils.setField(controller, "credentialSource", "APP"); + ReflectionTestUtils.setField(controller, "apiKey", "stale-key"); + ReflectionTestUtils.setField(controller, "apiSecret", "stale-secret"); + java.util.Map credential = new java.util.HashMap<>(); + credential.put("api_key", "test-key"); + when(store.one(anyString(), eq("test-key"), any())).thenReturn(credential); + when(identity.secret(credential)).thenReturn("test-secret"); + assertEquals("ok", controller.receive(signed(body, System.currentTimeMillis(), externalPath)).getBody()); + verify(identity).secret(credential); + verify(store).insert(eq("nonce"), argThat(values -> "test-key".equals(values.get("api_key")))); + } + + @Test public void unknownOrInactiveAppKeyIsNotAccepted() throws Exception { + ReflectionTestUtils.setField(controller, "signaturePath", externalPath); + when(store.one(anyString(), eq("test-key"), any())).thenReturn(null); + assertEquals(401, controller.receive(signed(body, System.currentTimeMillis(), externalPath)).getStatusCodeValue()); + verifyNoInteractions(identity); + verify(store, never()).insert(anyString(), anyMap()); + } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/WebhookDebugController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/WebhookDebugController.java index 6b11f40..5160e92 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/controller/WebhookDebugController.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/WebhookDebugController.java @@ -4,6 +4,8 @@ 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.RentalIdentity; +import com.ruoyi.system.rental.RentalCrypto; import com.ruoyi.system.rental.RentalValues; import java.io.IOException; import java.nio.ByteBuffer; @@ -27,6 +29,9 @@ public class WebhookDebugController { private static final int MAX_BODY_BYTES = 512 * 1024; private final RentalStore store; private final ObjectMapper json; + private final RentalIdentity identity; + @Value("${rental.webhook-debug.credential-source:APP}") + private String credentialSource = "APP"; @Value("${rental.webhook-debug.api-key:}") private String apiKey; @Value("${rental.webhook-debug.api-secret:}") @@ -35,15 +40,21 @@ public class WebhookDebugController { @Value("${rental.webhook-debug.signature-path:}") private String signaturePath; - public WebhookDebugController(RentalStore store, ObjectMapper json) { + public WebhookDebugController(RentalStore store, ObjectMapper json, RentalIdentity identity) { this.store = store; this.json = json; + this.identity = identity; } @PostMapping(value = "/api/webhook/debug", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.TEXT_PLAIN_VALUE) public ResponseEntity receive(HttpServletRequest request) throws IOException { - if (apiKey == null || apiKey.isEmpty() || apiSecret == null || apiSecret.isEmpty()) { + boolean appCredentials = "APP".equalsIgnoreCase(credentialSource); + if (!appCredentials && !"CONFIGURED".equalsIgnoreCase(credentialSource)) { + LOG.warn("租赁调试回调拒绝 reason=INVALID_CREDENTIAL_SOURCE"); + return ResponseEntity.status(503).body("invalid credential source"); + } + if (!appCredentials && (apiKey == null || apiKey.isEmpty() || apiSecret == null || apiSecret.isEmpty())) { LOG.warn("租赁调试回调拒绝 reason=CREDENTIAL_NOT_CONFIGURED"); return ResponseEntity.status(503).body("callback credentials not configured"); } @@ -63,28 +74,65 @@ public class WebhookDebugController { return ResponseEntity.status(413).body("payload too large"); } final JsonNode event; + String verifiedKey = apiKey; String stage = "SIGNATURE"; + String authenticationReason = "BODY_ENCODING_INVALID"; 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"), + String key = request.getHeader("X-Rent-Key"); + String secret = apiSecret; + authenticationReason = "KEY_MISSING"; + RentalValues.require(key != null && !key.isEmpty() && key.length() <= 128, "通知Key缺失或过长"); + if (appCredentials) { + stage = "CREDENTIAL_LOOKUP"; + authenticationReason = "ACTIVE_APP_CREDENTIAL_NOT_FOUND"; + java.util.Map credential = store.one( + "SELECT * FROM rent_credential WHERE api_key=? AND owner_type='APP' AND status='ACTIVE'" + + " AND (expires_at IS NULL OR expires_at>?)", key, RentalValues.now()); + RentalValues.require(credential != null, "未找到有效应用凭证"); + authenticationReason = "CREDENTIAL_DECRYPT_FAILED"; + secret = identity.secret(credential); + verifiedKey = key; + } + stage = "SIGNATURE"; + authenticationReason = "KEY_MISMATCH"; + RentalValues.require(key.equals(verifiedKey), "通知Key不匹配"); + String nonce = request.getHeader("X-Rent-Nonce"); + authenticationReason = "NONCE_INVALID"; + RentalValues.require(nonce != null && nonce.matches("[A-Za-z0-9_-]{16,64}"), "通知nonce格式无效"); + authenticationReason = "TIMESTAMP_NOT_UNIX_MILLIS"; + String rawTimestamp = request.getHeader("X-Rent-Timestamp"); + RentalValues.require(rawTimestamp != null && rawTimestamp.matches("[0-9]{13}"), "通知时间戳格式无效"); + long timestamp = Long.parseLong(rawTimestamp); + long now = System.currentTimeMillis(); + LOG.info("租赁调试回调认证参数检查 source={} keyFingerprint={} timestampSkewMs={} nonceLength={} signaturePresent={}", + credentialSource, RentalCrypto.sha256(key).substring(0, 12), now - timestamp, nonce.length(), + request.getHeader("X-Rent-Signature") != null); + authenticationReason = "TIMESTAMP_OUT_OF_WINDOW"; + RentalValues.require(timestamp > now - 60000 && timestamp < now + 60000, "通知时间戳超窗"); + authenticationReason = "SIGNATURE_MISMATCH_CHECK_SECRET_PATH_AND_BODY"; + RentalCallbackDemoController.verify(verifiedKey, secret, key, + timestamp, nonce, path, body, request.getHeader("X-Rent-Signature"), System.currentTimeMillis()); stage = "EVENT_JSON"; + authenticationReason = "EVENT_JSON_INVALID"; 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.warn("租赁调试回调拒绝 stage={} reason={} exceptionType={}", + stage, authenticationReason, ex.getClass().getSimpleName()); + return ResponseEntity.status("CREDENTIAL_LOOKUP".equals(stage) + && !"ACTIVE_APP_CREDENTIAL_NOT_FOUND".equals(authenticationReason) ? 503 + : "EVENT_JSON".equals(stage) ? 400 : 401).body("invalid notification"); } try { // 独立scope和数据库唯一键跨实例防重放;合法事件重投使用新nonce。 // 此接口不执行记账,重复event_no允许观察;正式业务应另做事件幂等处理。 - store.insert("nonce", RentalValues.map("api_key", apiKey, "scope", "DEBUG_WEBHOOK", + store.insert("nonce", RentalValues.map("api_key", verifiedKey, "scope", "DEBUG_WEBHOOK", "nonce", request.getHeader("X-Rent-Nonce"), "expires_at", RentalValues.after(180))); } catch (DuplicateKeyException ex) { LOG.warn("租赁调试回调拒绝 reason=NONCE_REPLAY"); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalCallbackDemoController.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalCallbackDemoController.java index 420b00a..3441b28 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalCallbackDemoController.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalCallbackDemoController.java @@ -112,9 +112,13 @@ public class RentalCallbackDemoController { /** 验证实际原文及WEBHOOK域;代理必须保留回调路径,不可二次序列化JSON。 */ public static void verify(String expectedKey, String secret, String key, long timestamp, String nonce, String path, String body, String signature, long now) { - require(expectedKey != null && !expectedKey.isEmpty() && secret != null && !secret.isEmpty() - && expectedKey.equals(key) && nonce != null && nonce.matches("[A-Za-z0-9_-]{16,64}") - && timestamp > now - 60000 && timestamp < now + 60000, "通知认证参数无效"); + require(expectedKey != null && !expectedKey.isEmpty() && secret != null && !secret.isEmpty(), + "通知接收端凭证未配置"); + require(key != null && !key.isEmpty(), "通知缺少X-Rent-Key"); + require(expectedKey.equals(key), "通知API Key与接收端凭证不匹配"); + require(nonce != null && nonce.matches("[A-Za-z0-9_-]{16,64}"), "通知nonce格式无效"); + require(timestamp > now - 60000 && timestamp < now + 60000, + "通知时间戳超出60秒窗口,请使用Unix毫秒并同步服务器时钟"); require(RentalCrypto.equal(RentalCrypto.sign(secret, "WEBHOOK", key, timestamp, nonce, "POST", path, body), signature), "通知签名无效"); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalWorkers.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalWorkers.java index b5c176b..16099cc 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalWorkers.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalWorkers.java @@ -368,6 +368,7 @@ public class RentalWorkers { String responseBody = RentalHttp.body(response); acked = "ok".equals(responseBody); if (!acked) { + LOG.error("responseBody {}",responseBody); failure = "ACK_BODY_NOT_EXACT_OK"; } }