feat: add rolling logs and separate local and production profiles
This commit is contained in:
1 parent
e22e5c4024
commit
30c5f9f114
17 files changed
+621
-20
No files matched your search
@@ -1,6 +1,9 @@
|
||||
package com.hongzhen.hera.common;
|
||||
|
||||
import com.hongzhen.hera.security.AuthenticationException;
|
||||
import com.hongzhen.hera.logging.SafeThrowableConverter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.validation.BindException;
|
||||
@@ -8,32 +11,101 @@ import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.HttpMediaTypeNotAcceptableException;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
import org.springframework.web.multipart.support.MissingServletRequestPartException;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
/** 登录过期与普通业务校验区分,供客户端清理会话并重新登录。 */
|
||||
@ExceptionHandler(AuthenticationException.class)
|
||||
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
||||
public ApiResponse<Void> handleAuthentication(AuthenticationException exception) {
|
||||
LOGGER.warn("authentication_rejected");
|
||||
return new ApiResponse<Void>(401, exception.getMessage(), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务拒绝只记录事件,不记录可能包含外部接口信息的异常消息。
|
||||
*/
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<Void> handleBusiness(BusinessException exception) {
|
||||
LOGGER.warn("business_rejected exceptionType={}", exception.getClass().getSimpleName());
|
||||
return ApiResponse.fail(exception.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
|
||||
/**
|
||||
* 参数错误不输出请求参数、正文与校验失败值。
|
||||
*/
|
||||
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class,
|
||||
HttpMessageNotReadableException.class, MethodArgumentTypeMismatchException.class,
|
||||
MissingServletRequestParameterException.class, MissingServletRequestPartException.class})
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<Void> handleValidation(Exception exception) {
|
||||
LOGGER.warn("validation_rejected exceptionType={}", exception.getClass().getSimpleName());
|
||||
return ApiResponse.fail("参数不正确");
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据约束错误不打印 SQL、参数或底层异常消息。
|
||||
*/
|
||||
@ExceptionHandler(DataIntegrityViolationException.class)
|
||||
@ResponseStatus(HttpStatus.CONFLICT)
|
||||
public ApiResponse<Void> handleDataIntegrity(DataIntegrityViolationException exception) {
|
||||
LOGGER.warn("data_integrity_rejected");
|
||||
return ApiResponse.fail("数据重复或关联关系不正确");
|
||||
}
|
||||
|
||||
/**
|
||||
* 保留框架的标准 HTTP 状态,防止兜底处理把 404、405 等误报为服务故障。
|
||||
*/
|
||||
@ExceptionHandler({HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class,
|
||||
HttpMediaTypeNotAcceptableException.class, NoHandlerFoundException.class, ResponseStatusException.class})
|
||||
public org.springframework.http.ResponseEntity<ApiResponse<Void>> handleHttpException(Exception exception) {
|
||||
HttpStatus status;
|
||||
if (exception instanceof ResponseStatusException) {
|
||||
status = ((ResponseStatusException) exception).getStatus();
|
||||
} else if (exception instanceof HttpRequestMethodNotSupportedException) {
|
||||
status = HttpStatus.METHOD_NOT_ALLOWED;
|
||||
} else if (exception instanceof HttpMediaTypeNotSupportedException) {
|
||||
status = HttpStatus.UNSUPPORTED_MEDIA_TYPE;
|
||||
} else if (exception instanceof HttpMediaTypeNotAcceptableException) {
|
||||
status = HttpStatus.NOT_ACCEPTABLE;
|
||||
} else {
|
||||
status = HttpStatus.NOT_FOUND;
|
||||
}
|
||||
LOGGER.warn("http_rejected status={} exceptionType={}", status.value(), exception.getClass().getSimpleName());
|
||||
return org.springframework.http.ResponseEntity.status(status)
|
||||
.body(new ApiResponse<Void>(status.value(), status.getReasonPhrase(), null));
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传超限不记录文件内容或文件名。
|
||||
*/
|
||||
@ExceptionHandler(MaxUploadSizeExceededException.class)
|
||||
@ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE)
|
||||
public ApiResponse<Void> handleUploadLimit(MaxUploadSizeExceededException exception) {
|
||||
LOGGER.warn("upload_size_rejected");
|
||||
return new ApiResponse<Void>(HttpStatus.PAYLOAD_TOO_LARGE.value(), "上传文件超过大小限制", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 未知异常记录类型与安全定位堆栈,客户端只收到通用错误。
|
||||
*/
|
||||
@ExceptionHandler(Exception.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public ApiResponse<Void> handleUnexpected(Exception exception) {
|
||||
LOGGER.error("request_failed\n{}", SafeThrowableConverter.stackTrace(exception));
|
||||
return new ApiResponse<Void>(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务暂时不可用,请稍后重试", null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.hongzhen.hera.config;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.core.env.Profiles;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 防止混用本地与线上配置,线上不允许使用缺失、过短或默认开发 JWT 密钥。
|
||||
*/
|
||||
@Component
|
||||
public class EnvironmentConfigurationValidator implements InitializingBean {
|
||||
private static final int MIN_JWT_SECRET_BYTES = 32;
|
||||
private final Environment environment;
|
||||
private final HeraProperties properties;
|
||||
|
||||
public EnvironmentConfigurationValidator(Environment environment, HeraProperties properties) {
|
||||
this.environment = environment;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动阶段只报告配置项名称,不将配置值写入异常或日志。
|
||||
*/
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
List<String> profiles = Arrays.asList(environment.getActiveProfiles());
|
||||
if (profiles.contains("local") && profiles.contains("prod")) {
|
||||
throw new IllegalStateException("local 与 prod 环境不能同时启用");
|
||||
}
|
||||
if (environment.acceptsProfiles(Profiles.of("prod"))) {
|
||||
String secret = properties.getJwtSecret();
|
||||
if (secret == null || secret.trim().isEmpty()
|
||||
|| secret.getBytes(StandardCharsets.UTF_8).length < MIN_JWT_SECRET_BYTES
|
||||
|| secret.startsWith("replace-this-development-secret")) {
|
||||
throw new IllegalStateException("线上必须配置独立的 hera.jwt-secret,UTF-8 长度至少 32 字节");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.hongzhen.hera.logging;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
|
||||
/**
|
||||
* 记录请求方法、路由模板、状态码与耗时,不记录查询串、正文、Cookie 和认证头。
|
||||
*/
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class RequestLoggingFilter extends OncePerRequestFilter {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RequestLoggingFilter.class);
|
||||
private static final String REQUEST_ID_KEY = "requestId";
|
||||
private static final String REQUEST_ID_HEADER = "X-Request-Id";
|
||||
|
||||
/**
|
||||
* 为每个请求生成服务端追踪号,并在请求结束时恢复线程原有 MDC。
|
||||
*/
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain chain) throws ServletException, IOException {
|
||||
Map<String, String> previous = MDC.getCopyOfContextMap();
|
||||
String requestId = UUID.randomUUID().toString().replace("-", "");
|
||||
MDC.put(REQUEST_ID_KEY, requestId);
|
||||
response.setHeader(REQUEST_ID_HEADER, requestId);
|
||||
long start = System.nanoTime();
|
||||
boolean failed = false;
|
||||
try {
|
||||
chain.doFilter(request, response);
|
||||
} catch (ServletException | IOException | RuntimeException exception) {
|
||||
failed = true;
|
||||
LOGGER.error("request_failed\n{}", SafeThrowableConverter.stackTrace(exception));
|
||||
throw exception;
|
||||
} finally {
|
||||
try {
|
||||
Object matched = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||
String route = matched == null ? "<unmapped>" : matched.toString();
|
||||
int status = failed ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : response.getStatus();
|
||||
long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
|
||||
if (status >= HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
|
||||
LOGGER.error("http_request method={} route={} status={} durationMs={}", request.getMethod(), route, status, duration);
|
||||
} else if (status >= HttpServletResponse.SC_BAD_REQUEST) {
|
||||
LOGGER.warn("http_request method={} route={} status={} durationMs={}", request.getMethod(), route, status, duration);
|
||||
} else {
|
||||
LOGGER.info("http_request method={} route={} status={} durationMs={}", request.getMethod(), route, status, duration);
|
||||
}
|
||||
} finally {
|
||||
if (previous == null) { MDC.clear(); } else { MDC.setContextMap(previous); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.hongzhen.hera.logging;
|
||||
|
||||
import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.classic.spi.IThrowableProxy;
|
||||
import ch.qos.logback.classic.spi.StackTraceElementProxy;
|
||||
import ch.qos.logback.classic.spi.ThrowableProxy;
|
||||
|
||||
/**
|
||||
* 保留异常类型和定位堆栈,不输出可能包含 SQL 参数、微信密钥或签名 URL 的异常消息。
|
||||
*/
|
||||
public class SafeThrowableConverter extends ThrowableProxyConverter {
|
||||
private static final int MAX_CAUSES = 6;
|
||||
private static final int MAX_FRAMES = 30;
|
||||
|
||||
/**
|
||||
* 输出有界的安全异常堆栈,不调用异常消息格式化逻辑。
|
||||
*/
|
||||
@Override
|
||||
public String convert(ILoggingEvent event) {
|
||||
return render(event.getThrowableProxy());
|
||||
}
|
||||
|
||||
/**
|
||||
* 供业务日志显式输出安全堆栈,不将原始异常传给其他日志配置。
|
||||
*/
|
||||
public static String stackTrace(Throwable exception) {
|
||||
return render(new ThrowableProxy(exception));
|
||||
}
|
||||
|
||||
private static String render(IThrowableProxy cause) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int depth = 0; cause != null && depth < MAX_CAUSES; depth++) {
|
||||
result.append(depth == 0 ? "exception=" : "causedBy=").append(cause.getClassName()).append('\n');
|
||||
StackTraceElementProxy[] frames = cause.getStackTraceElementProxyArray();
|
||||
if (frames != null) {
|
||||
for (int index = 0; index < Math.min(frames.length, MAX_FRAMES); index++) {
|
||||
result.append(" ").append(frames[index].getSTEAsString()).append('\n');
|
||||
}
|
||||
if (frames.length > MAX_FRAMES) { result.append(" ... remaining frames omitted\n"); }
|
||||
}
|
||||
cause = cause.getCause();
|
||||
}
|
||||
if (cause != null) { result.append("... remaining causes omitted\n"); }
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
spring:
|
||||
config:
|
||||
import: "${HERA_LOCAL_CONFIG:optional:file:./.hera-local.yml}"
|
||||
datasource:
|
||||
url: "${DB_URL:jdbc:mysql://101.43.139.56:3306/hera?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true}"
|
||||
redis:
|
||||
host: "${REDIS_HOST:101.43.139.56}"
|
||||
sql:
|
||||
init:
|
||||
mode: always
|
||||
logging:
|
||||
level:
|
||||
root: INFO
|
||||
hera:
|
||||
jwt-secret: "${HERA_JWT_SECRET:replace-this-development-secret-replace-this-development-secret}"
|
||||
@@ -0,0 +1,13 @@
|
||||
spring:
|
||||
config:
|
||||
import: "${HERA_PROD_CONFIG:optional:file:./.hera-prod.yml}"
|
||||
datasource:
|
||||
url: "${DB_URL:jdbc:mysql://10.0.8.9:3306/hera?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true}"
|
||||
redis:
|
||||
host: "${REDIS_HOST:10.0.8.9}"
|
||||
sql:
|
||||
init:
|
||||
mode: never
|
||||
logging:
|
||||
level:
|
||||
root: INFO
|
||||
@@ -1,11 +1,12 @@
|
||||
---
|
||||
server:
|
||||
port: 8080
|
||||
port: "${SERVER_PORT:8080}"
|
||||
spring:
|
||||
application:
|
||||
name: hera
|
||||
profiles:
|
||||
default: local
|
||||
redis:
|
||||
host: "${REDIS_HOST:101.43.139.56}"
|
||||
port: "${REDIS_PORT:6379}"
|
||||
username: "${REDIS_USERNAME:}"
|
||||
password: "${REDIS_PASSWORD:}"
|
||||
@@ -21,19 +22,23 @@ spring:
|
||||
enabled: false
|
||||
datasource:
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
url: "${DB_URL:jdbc:mysql://101.43.139.56:3306/hera?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true}"
|
||||
username: "${DB_USERNAME:hera_user}"
|
||||
password: "${DB_PASSWORD:}"
|
||||
sql:
|
||||
init:
|
||||
mode: always
|
||||
encoding: UTF-8
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 5MB
|
||||
max-request-size: 5MB
|
||||
config:
|
||||
import: optional:file:./.hera-local.yml
|
||||
logging:
|
||||
file:
|
||||
path: "${LOG_PATH:./logs}"
|
||||
logback:
|
||||
rollingpolicy:
|
||||
max-file-size: "${LOG_MAX_FILE_SIZE:20MB}"
|
||||
max-history: "${LOG_MAX_HISTORY:30}"
|
||||
total-size-cap: "${LOG_TOTAL_SIZE_CAP:2GB}"
|
||||
mybatis:
|
||||
mapper-locations: classpath*:/mapper/**/*.xml
|
||||
configuration:
|
||||
@@ -46,7 +51,7 @@ hera:
|
||||
region: "${TENCENT_COS_REGION:ap-beijing}"
|
||||
signed-url-seconds: 900
|
||||
public-base-url: "${TENCENT_COS_PUBLIC_BASE_URL:http://101.43.139.56/file/}"
|
||||
jwt-secret: "${HERA_JWT_SECRET:replace-this-development-secret-replace-this-development-secret}"
|
||||
jwt-secret: "${HERA_JWT_SECRET:}"
|
||||
upload-dir: "${HERA_UPLOAD_DIR:./uploads}"
|
||||
wx:
|
||||
app-id: "${WECHAT_APP_ID:wxa76a2ef9e8ba612e}"
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<springProperty scope="context" name="LOG_PATH" source="logging.file.path" defaultValue="./logs"/>
|
||||
<springProperty scope="context" name="MAX_FILE_SIZE" source="logging.logback.rollingpolicy.max-file-size" defaultValue="20MB"/>
|
||||
<springProperty scope="context" name="MAX_HISTORY" source="logging.logback.rollingpolicy.max-history" defaultValue="30"/>
|
||||
<springProperty scope="context" name="TOTAL_SIZE_CAP" source="logging.logback.rollingpolicy.total-size-cap" defaultValue="2GB"/>
|
||||
<conversionRule conversionWord="safeEx" converterClass="com.hongzhen.hera.logging.SafeThrowableConverter"/>
|
||||
<property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS,Asia/Shanghai} %-5level [%thread] [requestId=%X{requestId:-none}] %logger{60} - %msg%n%safeEx"/>
|
||||
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder><charset>UTF-8</charset><pattern>${LOG_PATTERN}</pattern></encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="APPLICATION" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_PATH}/hera.log</file>
|
||||
<encoder><charset>UTF-8</charset><pattern>${LOG_PATTERN}</pattern></encoder>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/archive/hera.%d{yyyy-MM-dd,Asia/Shanghai}.%i.log.gz</fileNamePattern>
|
||||
<maxFileSize>${MAX_FILE_SIZE}</maxFileSize>
|
||||
<maxHistory>${MAX_HISTORY}</maxHistory>
|
||||
<totalSizeCap>${TOTAL_SIZE_CAP}</totalSizeCap>
|
||||
<cleanHistoryOnStart>true</cleanHistoryOnStart>
|
||||
</rollingPolicy>
|
||||
</appender>
|
||||
|
||||
<appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_PATH}/hera-error.log</file>
|
||||
<filter class="ch.qos.logback.classic.filter.ThresholdFilter"><level>ERROR</level></filter>
|
||||
<encoder><charset>UTF-8</charset><pattern>${LOG_PATTERN}</pattern></encoder>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/archive/hera-error.%d{yyyy-MM-dd,Asia/Shanghai}.%i.log.gz</fileNamePattern>
|
||||
<maxFileSize>${MAX_FILE_SIZE}</maxFileSize>
|
||||
<maxHistory>${MAX_HISTORY}</maxHistory>
|
||||
<totalSizeCap>${TOTAL_SIZE_CAP}</totalSizeCap>
|
||||
<cleanHistoryOnStart>true</cleanHistoryOnStart>
|
||||
</rollingPolicy>
|
||||
</appender>
|
||||
|
||||
<!-- SQL parameters and HTTP wire traces can contain credentials or personal data. -->
|
||||
<logger name="com.hongzhen.hera.data" level="INFO"/>
|
||||
<logger name="com.hongzhen.hera.user.UserMapper" level="INFO"/>
|
||||
<logger name="com.hongzhen.hera.auth" level="INFO"/>
|
||||
<logger name="org.mybatis" level="WARN"/>
|
||||
<logger name="org.apache.ibatis" level="WARN"/>
|
||||
<logger name="org.springframework.jdbc" level="WARN"/>
|
||||
<logger name="org.springframework.web" level="WARN"/>
|
||||
<logger name="org.apache.http" level="WARN"/>
|
||||
<logger name="io.lettuce.core" level="WARN"/>
|
||||
<logger name="com.qcloud.cos" level="WARN"/>
|
||||
<root level="${LOG_LEVEL_ROOT:-INFO}">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
<appender-ref ref="APPLICATION"/>
|
||||
<appender-ref ref="ERROR"/>
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.hongzhen.hera.config;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
|
||||
import org.springframework.context.support.GenericApplicationContext;
|
||||
import org.springframework.core.env.ConfigurableEnvironment;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
import org.springframework.mock.env.MockEnvironment;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* 验证两套环境配置、线上内网地址、建表策略与生产 JWT 启动校验。
|
||||
*/
|
||||
class EnvironmentProfilesTest {
|
||||
@Test
|
||||
void defaultEnvironmentIsLocalAndUsesPublicHost() {
|
||||
try (GenericApplicationContext context = environment(null)) {
|
||||
ConfigurableEnvironment env = context.getEnvironment();
|
||||
assertArrayEquals(new String[]{"local"}, env.getDefaultProfiles());
|
||||
assertTrue(env.getProperty("spring.datasource.url").contains("101.43.139.56"));
|
||||
assertEquals("101.43.139.56", env.getProperty("spring.redis.host"));
|
||||
assertEquals("always", env.getProperty("spring.sql.init.mode"));
|
||||
assertTrue(env.getProperty("hera.jwt-secret").startsWith("replace-this-development-secret"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void productionUsesInternalHostAndNeverInitializesSchema() {
|
||||
try (GenericApplicationContext context = environment("prod")) {
|
||||
ConfigurableEnvironment env = context.getEnvironment();
|
||||
assertTrue(env.getProperty("spring.datasource.url").contains("10.0.8.9"));
|
||||
assertEquals("10.0.8.9", env.getProperty("spring.redis.host"));
|
||||
assertEquals("never", env.getProperty("spring.sql.init.mode"));
|
||||
assertEquals("", env.getProperty("hera.jwt-secret"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void productionRejectsWeakSecretsWithoutPrintingTheirValues() {
|
||||
MockEnvironment env = new MockEnvironment();
|
||||
env.setActiveProfiles("prod");
|
||||
HeraProperties properties = new HeraProperties();
|
||||
for (String value : new String[]{"", "short-secret", "replace-this-development-secret-replace-this-development-secret"}) {
|
||||
properties.setJwtSecret(value);
|
||||
IllegalStateException error = assertThrows(IllegalStateException.class,
|
||||
() -> new EnvironmentConfigurationValidator(env, properties).afterPropertiesSet());
|
||||
if (!value.isEmpty()) { assertFalse(error.getMessage().contains(value)); }
|
||||
}
|
||||
properties.setJwtSecret("production-test-key-production-test-key");
|
||||
assertDoesNotThrow(() -> new EnvironmentConfigurationValidator(env, properties).afterPropertiesSet());
|
||||
}
|
||||
|
||||
@Test
|
||||
void localAndProductionCannotBeCombined() {
|
||||
MockEnvironment env = new MockEnvironment();
|
||||
env.setActiveProfiles("local", "prod");
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> new EnvironmentConfigurationValidator(env, new HeraProperties()).afterPropertiesSet());
|
||||
}
|
||||
|
||||
private GenericApplicationContext environment(String profile) {
|
||||
GenericApplicationContext context = new GenericApplicationContext();
|
||||
Map<String, Object> values = new HashMap<>();
|
||||
values.put("HERA_LOCAL_CONFIG", "optional:file:./target/nonexistent-profile-test.yml");
|
||||
values.put("HERA_PROD_CONFIG", "optional:file:./target/nonexistent-profile-test.yml");
|
||||
if (profile != null) {
|
||||
values.put("spring.profiles.active", profile);
|
||||
values.put("HERA_JWT_SECRET", "");
|
||||
}
|
||||
context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test-profile-overrides", values));
|
||||
new ConfigDataApplicationContextInitializer().initialize(context);
|
||||
return context;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.hongzhen.hera.logging;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import com.hongzhen.hera.common.ApiResponse;
|
||||
import com.hongzhen.hera.common.BusinessException;
|
||||
import com.hongzhen.hera.common.GlobalExceptionHandler;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
|
||||
/**
|
||||
* 验证请求追踪、错误定位与敏感信息不落日志。
|
||||
*/
|
||||
class RequestLoggingTest {
|
||||
private final Logger requestLogger = (Logger) LoggerFactory.getLogger(RequestLoggingFilter.class);
|
||||
private final Logger errorLogger = (Logger) LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
private final ListAppender<ILoggingEvent> logs = new ListAppender<ILoggingEvent>() {
|
||||
@Override
|
||||
protected void append(ILoggingEvent event) {
|
||||
event.prepareForDeferredProcessing();
|
||||
super.append(event);
|
||||
}
|
||||
};
|
||||
private Level oldLevel;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
logs.start();
|
||||
oldLevel = requestLogger.getLevel();
|
||||
requestLogger.setLevel(Level.INFO);
|
||||
requestLogger.addAppender(logs);
|
||||
errorLogger.addAppender(logs);
|
||||
mvc = MockMvcBuilders.standaloneSetup(new TestController())
|
||||
.setControllerAdvice(new GlobalExceptionHandler()).addFilters(new RequestLoggingFilter()).build();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() {
|
||||
requestLogger.detachAppender(logs);
|
||||
errorLogger.detachAppender(logs);
|
||||
requestLogger.setLevel(oldLevel);
|
||||
logs.stop();
|
||||
MDC.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsRouteTemplateAndTraceWithoutHeadersQueryOrPathValues() throws Exception {
|
||||
MDC.put("requestId", "previous-thread-context");
|
||||
MvcResult result = mvc.perform(get("/test/records/13812345678?token=query-secret")
|
||||
.header("Authorization", "Bearer header-secret").header("X-Request-Id", "untrusted-client-id"))
|
||||
.andReturn();
|
||||
assertEquals(200, result.getResponse().getStatus());
|
||||
String trace = result.getResponse().getHeader("X-Request-Id");
|
||||
assertNotNull(trace);
|
||||
assertTrue(trace.matches("[a-f0-9]{32}"));
|
||||
assertEquals("previous-thread-context", MDC.get("requestId"));
|
||||
ILoggingEvent access = logs.list.stream().filter(event -> event.getFormattedMessage().startsWith("http_request"))
|
||||
.findFirst().get();
|
||||
assertEquals(trace, access.getMDCPropertyMap().get("requestId"));
|
||||
assertTrue(access.getFormattedMessage().contains("route=/test/records/{id}"));
|
||||
assertTrue(access.getFormattedMessage().contains("status=200"));
|
||||
assertNoSensitiveValues("13812345678", "query-secret", "header-secret", "untrusted-client-id");
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorsRetainStackLocationButNeverExposeExceptionMessageOrRequestBody() throws Exception {
|
||||
MvcResult result = mvc.perform(post("/test/fail").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"password\":\"body-secret\"}")).andReturn();
|
||||
assertEquals(500, result.getResponse().getStatus());
|
||||
assertTrue(result.getResponse().getContentAsString().contains("500"));
|
||||
assertFalse(result.getResponse().getContentAsString().contains("exception-secret"));
|
||||
assertTrue(logs.list.stream().anyMatch(event -> event.getLevel() == Level.ERROR
|
||||
&& event.getFormattedMessage().contains("java.lang.IllegalStateException")
|
||||
&& event.getFormattedMessage().contains("TestController.fail")));
|
||||
assertNoSensitiveValues("body-secret", "exception-secret", "cause-secret");
|
||||
assertNull(MDC.get("requestId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validationAndBusinessRejectionsDoNotPrintValuesAndPreserveHttpStatus() throws Exception {
|
||||
assertEquals(400, mvc.perform(post("/test/fail").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"password\":\"malformed-secret\"")).andReturn().getResponse().getStatus());
|
||||
assertEquals(400, mvc.perform(get("/test/rejected")).andReturn().getResponse().getStatus());
|
||||
assertEquals(405, mvc.perform(get("/test/fail")).andReturn().getResponse().getStatus());
|
||||
assertNoSensitiveValues("malformed-secret", "business-secret");
|
||||
assertNull(MDC.get("requestId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void safeStackConverterOmitsNestedMessagesAndLimitsOutput() {
|
||||
Throwable nested = new IllegalArgumentException("cause-secret");
|
||||
for (int depth = 0; depth < 12; depth++) { nested = new IllegalStateException("exception-secret", nested); }
|
||||
String result = SafeThrowableConverter.stackTrace(nested);
|
||||
assertTrue(result.contains("java.lang.IllegalStateException"));
|
||||
assertTrue(result.contains("remaining causes omitted"));
|
||||
assertFalse(result.contains("exception-secret"));
|
||||
assertFalse(result.contains("cause-secret"));
|
||||
}
|
||||
|
||||
private void assertNoSensitiveValues(String... values) {
|
||||
for (ILoggingEvent event : logs.list) {
|
||||
for (String value : values) { assertFalse(event.getFormattedMessage().contains(value)); }
|
||||
assertNull(event.getThrowableProxy(), "业务日志不得传递未经处理的原始异常");
|
||||
}
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class TestController {
|
||||
@GetMapping("/test/records/{id}")
|
||||
public ApiResponse<String> get(@PathVariable String id) { return ApiResponse.ok(id); }
|
||||
|
||||
@PostMapping("/test/fail")
|
||||
public ApiResponse<Void> fail(@RequestBody Map<String, String> body) {
|
||||
throw new IllegalStateException("exception-secret", new IllegalArgumentException("cause-secret"));
|
||||
}
|
||||
|
||||
@GetMapping("/test/rejected")
|
||||
public ApiResponse<Void> rejected() { throw new BusinessException("business-secret"); }
|
||||
}
|
||||
}
|
||||
@@ -64,8 +64,8 @@ class NfcMySqlIntegrationTest {
|
||||
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
|
||||
FileSystemResource local = new FileSystemResource(".hera-local.yml");
|
||||
yaml.setResources(local.exists()
|
||||
? new org.springframework.core.io.Resource[]{new ClassPathResource("application.yml"), local}
|
||||
: new org.springframework.core.io.Resource[]{new ClassPathResource("application.yml")});
|
||||
? new org.springframework.core.io.Resource[]{new ClassPathResource("application.yml"), new ClassPathResource("application-local.yml"), local}
|
||||
: new org.springframework.core.io.Resource[]{new ClassPathResource("application.yml"), new ClassPathResource("application-local.yml")});
|
||||
Properties values = yaml.getObject();
|
||||
assertNotNull(values);
|
||||
StandardEnvironment env = new StandardEnvironment();
|
||||
|
||||
@@ -40,9 +40,9 @@ class CosIntegrationTest {
|
||||
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
|
||||
FileSystemResource local = new FileSystemResource(".hera-local.yml");
|
||||
if (local.exists()) {
|
||||
yaml.setResources(new ClassPathResource("application.yml"), local);
|
||||
yaml.setResources(new ClassPathResource("application.yml"), new ClassPathResource("application-local.yml"), local);
|
||||
} else {
|
||||
yaml.setResources(new ClassPathResource("application.yml"));
|
||||
yaml.setResources(new ClassPathResource("application.yml"), new ClassPathResource("application-local.yml"));
|
||||
}
|
||||
Properties values = yaml.getObject();
|
||||
assertNotNull(values);
|
||||
|
||||
@@ -26,7 +26,7 @@ class FileGatewayReadIntegrationTest {
|
||||
assertTrue(reference.startsWith("cos://hera/avatar/"));
|
||||
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
|
||||
FileSystemResource local = new FileSystemResource(".hera-local.yml");
|
||||
yaml.setResources(new ClassPathResource("application.yml"), local);
|
||||
yaml.setResources(new ClassPathResource("application.yml"), new ClassPathResource("application-local.yml"), local);
|
||||
Properties values = yaml.getObject();
|
||||
assertNotNull(values);
|
||||
StandardEnvironment environment = new StandardEnvironment();
|
||||
|
||||
@@ -28,9 +28,9 @@ class UserAccountSchemaIntegrationTest {
|
||||
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
|
||||
FileSystemResource local = new FileSystemResource(".hera-local.yml");
|
||||
if (local.exists()) {
|
||||
yaml.setResources(new ClassPathResource("application.yml"), local);
|
||||
yaml.setResources(new ClassPathResource("application.yml"), new ClassPathResource("application-local.yml"), local);
|
||||
} else {
|
||||
yaml.setResources(new ClassPathResource("application.yml"));
|
||||
yaml.setResources(new ClassPathResource("application.yml"), new ClassPathResource("application-local.yml"));
|
||||
}
|
||||
Properties values = yaml.getObject();
|
||||
assertNotNull(values);
|
||||
|
||||
Reference in new issue
Block a user