签名问题处理

This commit is contained in:
lu7213 committed 2026-10-30 07:34:07 -04:00
1 parent e5820e36e7
commit 8605c946c9
4 files changed
+128 -34

No files matched your search

@@ -11,6 +11,7 @@ import java.util.*;
/** 外部APP和本地NODE共用凭证认证,登录用户归属仍由sys_user及RBAC决定。 */
@Service
@lombok.extern.slf4j.Slf4j
public class RentalIdentity {
private final RentalStore store;
private final RentalCrypto crypto;
@@ -49,33 +50,68 @@ public class RentalIdentity {
String path,
String body,
String signature) {
require(
key != null
&& key.length() <= 64
&& nonce != null
&& nonce.matches("[A-Za-z0-9_-]{16,64}")
&& timestamp > System.currentTimeMillis() - 60000
&& timestamp < System.currentTimeMillis() + 60000,
"认证时间或随机数无效");
Map<String, Object> row = credential(key);
require(
ownerType.equals(text(row, "owner_type"))
&& RentalCrypto.equal(
RentalCrypto.sign(
secret(row),
scope,
key,
timestamp,
nonce,
method,
path,
body),
signature),
"租赁签名无效");
store.insert(
"nonce",
map("api_key", key, "scope", scope, "nonce", nonce, "expires_at", after(180)));
return row;
String diagnosticId = UUID.randomUUID().toString().replace("-", "");
long serverTime = System.currentTimeMillis();
boolean keyValid = key != null && !key.isEmpty() && key.length() <= 64;
boolean nonceValid = nonce != null && nonce.matches("[A-Za-z0-9_-]{16,64}");
boolean timeValid = timestamp > serverTime - 60000 && timestamp < serverTime + 60000;
boolean signatureFormatValid = signature != null && signature.matches("[0-9a-fA-F]{64}");
String keyFingerprint = key == null ? "missing" : RentalCrypto.sha256(key).substring(0, 16);
// 只记录请求体摘要和长度,不记录正文、Secret、完整认证头或服务端计算的签名。
// bodySha256、method和path可直接与调试台“请求与签名”页逐项核对。
log.info("租赁认证开始 diagnosticId={} keyFingerprint={} expectedOwnerType={} scope={} method={} path={}"
+ " serverTime={} timestamp={} clockSkewMs={} keyValid={} nonceValid={} nonceLength={}"
+ " signatureLength={} signatureFormatValid={} signatureLowercase={} signatureWhitespace={}"
+ " bodyBytes={} bodySha256={} bodyLfCount={} bodyCrCount={}",
diagnosticId, keyFingerprint, safeLog(ownerType), safeLog(scope), safeLog(method), safeLog(path),
serverTime, timestamp, timestamp > 0 ? Long.toString(timestamp - serverTime) : "invalid", keyValid,
nonceValid, nonce == null ? 0 : nonce.length(), signature == null ? 0 : signature.length(),
signatureFormatValid, signature != null && signature.equals(signature.toLowerCase(Locale.ROOT)),
signature != null && !signature.equals(signature.trim()),
body == null ? 0 : body.getBytes(java.nio.charset.StandardCharsets.UTF_8).length,
body == null ? "missing" : RentalCrypto.sha256(body), count(body, '\n'), count(body, '\r'));
String stage = "AUTH_FIELDS";
try {
require(keyValid && nonceValid && timeValid, "认证时间或随机数无效");
stage = "CREDENTIAL_LOAD";
Map<String, Object> row = credential(key);
log.info("租赁认证凭证已定位 diagnosticId={} credentialId={} ownerId={} ownerType={} status={}"
+ " storedMasterVersion={} configuredMasterVersion={}", diagnosticId,
row.get("id"), row.get("owner_id"), safeLog(text(row, "owner_type")), safeLog(text(row, "status")),
safeLog(text(row, "master_key_version")), safeLog(masterVersion));
stage = "OWNER_TYPE";
require(ownerType != null && ownerType.equals(text(row, "owner_type")), "租赁签名无效");
stage = "SIGNATURE_FORMAT";
require(signatureFormatValid, "租赁签名无效");
stage = "SECRET_DECRYPT";
String credentialSecret = secret(row);
stage = "SIGNATURE_COMPARE";
String expected = RentalCrypto.sign(credentialSecret, scope, key, timestamp, nonce, method, path, body);
require(RentalCrypto.equal(expected, signature), "租赁签名无效");
stage = "NONCE_SAVE";
store.insert("nonce", map("api_key", key, "scope", scope, "nonce", nonce, "expires_at", after(180)));
log.info("租赁认证成功 diagnosticId={} credentialId={} scope={}", diagnosticId, row.get("id"), safeLog(scope));
return row;
} catch (RuntimeException ex) {
log.warn("租赁认证失败 diagnosticId={} stage={} keyFingerprint={} diagnostic={}",
diagnosticId, stage, keyFingerprint, RentalDiagnostics.describe(ex));
throw ex;
}
}
/** 日志字段限制长度并移除控制字符,防止外部认证参数注入伪造日志。 */
private static String safeLog(String value) {
return value == null ? "missing" : value.replaceAll("[\\p{Cntrl}]", "_").substring(0, Math.min(value.length(), 256));
}
private static int count(String value, char character) {
int total = 0;
if (value != null) {
for (int index = 0; index < value.length(); index++) {
if (value.charAt(index) == character) { total++; }
}
}
return total;
}
/** 轮换保留历史Secret,仅明确在途任务可以使用VERIFY_ONLY,不能签发新任务。 */
@@ -675,6 +675,38 @@ public class RentalBusinessTest {
} catch (IllegalArgumentException expected) { /* 类型不允许覆盖 */ }
}
/** 经过生产可重复读过滤器再验签,防止格式化JSON的LF/CRLF被全局过滤器删除。 */
@Test
public void formattedPackagesRequestSurvivesRepeatableFilterAndAuthenticates() throws Exception {
Map<String, Object> credential = tx.execute(status -> identity.issue("APP", app, 10));
RentalApiController api = new RentalApiController(identity, store, orders, json);
for (String body : new String[] {"{\n \"network\": \"NILE\"\n}",
" \r\n{\r\n \"network\": \"NILE\",\r\n \"note\": \"中文调试\"\r\n}\r\n "}) {
javax.servlet.http.HttpServletRequest signed = signedRequest("/api/rental/v1/packages", body,
text(credential, "api_key"), text(credential, "api_secret"), "API");
javax.servlet.http.HttpServletRequest input = new javax.servlet.http.HttpServletRequestWrapper(signed) {
@Override public String getContentType() { return "application/json;charset=UTF-8"; }
};
javax.servlet.ServletResponse response = (javax.servlet.ServletResponse) java.lang.reflect.Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] {javax.servlet.ServletResponse.class}, (proxy, method, args) -> null);
new com.ruoyi.common.filter.RepeatableFilter().doFilter(input, response, (filtered, ignored) -> {
try {
javax.servlet.http.HttpServletRequest actual = (javax.servlet.http.HttpServletRequest) filtered;
assertTrue(actual instanceof com.ruoyi.common.filter.RepeatedlyRequestWrapper);
javax.servlet.ServletInputStream stream = actual.getInputStream();
assertFalse(stream.isFinished());
assertArrayEquals(body.getBytes(StandardCharsets.UTF_8), org.apache.commons.io.IOUtils.toByteArray(stream));
assertTrue(stream.isFinished());
assertEquals(0, stream.available());
assertEquals(body, org.apache.commons.io.IOUtils.toString(actual.getReader()));
assertEquals(200, api.execute("packages", actual).get("code"));
} catch (Exception ex) {
throw new javax.servlet.ServletException(ex);
}
});
}
}
/** Servlet代理保留原始字节,无需启动真实HTTP端口。 */
private javax.servlet.http.HttpServletRequest demoRequest(String operation, String body, String secret) {
return signedRequest("/api/rental/v1/demo/callback/" + operation, body, "RKdemo", secret, "WEBHOOK");