Skip to content

Commit d60cd85

Browse files
🎨 #4055 修复 DataUtils.handleDataWithSecret 在日志输出前对查询串参数 secret 的脱敏缺陷
1 parent 6ca6c34 commit d60cd85

2 files changed

Lines changed: 30 additions & 2 deletions

File tree

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/DataUtils.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ public class DataUtils {
1717
*/
1818
public static <E> E handleDataWithSecret(E data) {
1919
E dataForLog = data;
20-
if(data instanceof String && StringUtils.contains((String)data, "&secret=")){
21-
dataForLog = (E) RegExUtils.replaceAll((String)data,"&secret=\\w+&","&secret=******&");
20+
if (data instanceof String && StringUtils.contains((String) data, "secret=")) {
21+
dataForLog = (E) RegExUtils.replaceAll((String) data, "(^|[?&])secret=[^&]*", "$1secret=******");
2222
}
2323
return dataForLog;
2424
}

weixin-java-common/src/test/java/me/chanjar/weixin/common/util/DataUtilsTest.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,32 @@ public void testHandleDataWithSecret() {
1919
final String s = DataUtils.handleDataWithSecret(data);
2020
assertTrue(s.contains("&secret=******&"));
2121
}
22+
23+
@Test
24+
public void testHandleDataWithSecretAtEnd() {
25+
// Secret is the last parameter in the query string, so there is no trailing &
26+
String data = "appid=wx123&secret=abc123";
27+
final String s = DataUtils.handleDataWithSecret(data);
28+
assertFalse(s.contains("abc123"), "Secret at the end of the string should be masked");
29+
assertTrue(s.contains("secret=******"), "Secret should be replaced with asterisks");
30+
}
31+
32+
@Test
33+
public void testHandleDataWithSecretAsFirstParam() {
34+
// Secret is the first parameter, so there is no leading &
35+
String data = "secret=abc123&appid=wx123";
36+
final String s = DataUtils.handleDataWithSecret(data);
37+
assertFalse(s.contains("abc123"), "Secret as the first parameter should be masked");
38+
assertTrue(s.contains("secret=******"), "Secret should be replaced with asterisks");
39+
}
40+
41+
@Test
42+
public void testHandleDataWithSecretEncodedValue() {
43+
// The secret value contains URL-encoded and non-word characters; the whole value must be masked
44+
String data = "appid=wx123&secret=abc%2Fdef-.+ghi&grant_type=client_credential";
45+
final String s = DataUtils.handleDataWithSecret(data);
46+
assertFalse(s.contains("def"), "The full secret value must be masked, including after non-word characters");
47+
assertFalse(s.contains("%2F"), "Encoded characters in the secret must be masked too");
48+
assertTrue(s.contains("&secret=******&"), "Secret should be replaced with asterisks");
49+
}
2250
}

0 commit comments

Comments
 (0)