diff --git a/src/main/java/com/finance/system/FinanceSystemApplication.java b/src/main/java/com/finance/system/FinanceSystemApplication.java index 9110f53..116db1f 100644 --- a/src/main/java/com/finance/system/FinanceSystemApplication.java +++ b/src/main/java/com/finance/system/FinanceSystemApplication.java @@ -1,16 +1,48 @@ package com.finance.system; import org.springframework.boot.SpringApplication; +import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.event.EventListener; +import org.springframework.core.env.Environment; import org.springframework.scheduling.annotation.EnableScheduling; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +import java.util.Arrays; @SpringBootApplication @EnableConfigurationProperties @EnableScheduling +@Slf4j +@RequiredArgsConstructor public class FinanceSystemApplication { + private final Environment environment; + public static void main(String[] args) { SpringApplication.run(FinanceSystemApplication.class, args); } + + @EventListener(ApplicationReadyEvent.class) + public void logApplicationReady() { + String application = environment.getProperty("spring.application.name", "finance-system"); + String port = environment.getProperty("local.server.port", + environment.getProperty("server.port", "8080")); + String[] profiles = environment.getActiveProfiles(); + String profileText = profiles.length == 0 ? "默认环境" : Arrays.stream(profiles) + .map(this::profileLabel) + .reduce((left, right) -> left + "、" + right) + .orElse("默认环境"); + log.info("系统启动完成 | 状态=就绪 | 应用={} | 端口={} | 运行环境={}", + application, port, profileText); + } + + private String profileLabel(String profile) { + if ("local".equalsIgnoreCase(profile)) return "本地开发(local)"; + if ("test".equalsIgnoreCase(profile)) return "测试(test)"; + if ("prod".equalsIgnoreCase(profile)) return "生产(prod)"; + return profile; + } } diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java index bb4639e..0850e1a 100644 --- a/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java +++ b/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java @@ -91,7 +91,8 @@ public class FeishuAuthService { */ @Transactional public void validateCallbackState(String state, String browserState, boolean consume) { - if (!StringUtils.hasText(state)) { + if (!StringUtils.hasText(state) || state.length() != 43 + || !state.matches("[A-Za-z0-9_-]{43}")) { throw new BusinessException("飞书登录状态缺失,请重新发起授权", 400); } if (consume && (!StringUtils.hasText(browserState) diff --git a/src/main/java/com/finance/system/config/JwtConfig.java b/src/main/java/com/finance/system/config/JwtConfig.java index 9570594..ac2c555 100644 --- a/src/main/java/com/finance/system/config/JwtConfig.java +++ b/src/main/java/com/finance/system/config/JwtConfig.java @@ -5,6 +5,8 @@ import io.jsonwebtoken.Jwts; import io.jsonwebtoken.security.Keys; import lombok.Getter; import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; @@ -38,13 +40,26 @@ public class JwtConfig { @Value("${auth.time-zone:Asia/Shanghai}") private String timeZone = "Asia/Shanghai"; + @Autowired + private Environment environment; + @PostConstruct void validateConfiguration() { validateSecretValue(secret); + if (!isLocalProfile() && ("Uqen22fWWeubQ6f2dFIWteMDIhd4PU4u".equals(secret) + || "change-me".equalsIgnoreCase(secret) + || "local-only-insecure-secret-change-before-deploy".equals(secret))) { + throw new IllegalStateException("JWT_SECRET must be explicitly configured outside local profile"); + } validateExpirationValue(expiration); getAuthZoneId(); } + private boolean isLocalProfile() { + return environment != null && java.util.Arrays.stream(environment.getActiveProfiles()) + .anyMatch(profile -> "local".equalsIgnoreCase(profile)); + } + static void validateSecretValue(String secret) { if (!StringUtils.hasText(secret) || secret.getBytes(StandardCharsets.UTF_8).length < MIN_SECRET_BYTES) { diff --git a/src/main/java/com/finance/system/config/SecurityConfig.java b/src/main/java/com/finance/system/config/SecurityConfig.java index 88191c2..124fbe1 100644 --- a/src/main/java/com/finance/system/config/SecurityConfig.java +++ b/src/main/java/com/finance/system/config/SecurityConfig.java @@ -38,14 +38,15 @@ public class SecurityConfig { .authorizeHttpRequests(auth -> { if (isDevelopmentProfile()) { auth.antMatchers("/api/auth/login").permitAll(); + auth.antMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll(); } auth .antMatchers("/api/auth/feishu-login").permitAll() - .antMatchers("/api/feishu/auth-url", "/api/feishu/callback", "/api/feishu/webhook", "/api/feishu/login").permitAll() - .antMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll() + // OAuth initiation/callback and the signed Feishu event receiver are the + // only Feishu endpoints intentionally reachable without a local session. + .antMatchers("/api/feishu/auth-url", "/api/feishu/callback", "/api/feishu/webhook").permitAll() .antMatchers("/actuator/health").permitAll() - .antMatchers("/api/**").authenticated() - .anyRequest().permitAll(); + .anyRequest().authenticated(); }) .exceptionHandling(exceptions -> exceptions.authenticationEntryPoint( (request, response, exception) -> { @@ -58,7 +59,11 @@ public class SecurityConfig { )) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) .addFilterAfter(apiAccessLogFilter, UsernamePasswordAuthenticationFilter.class) - .headers(headers -> headers.frameOptions(frame -> frame.sameOrigin())); + .headers(headers -> headers + .frameOptions(frame -> frame.sameOrigin()) + .contentTypeOptions().and() + .httpStrictTransportSecurity(hsts -> hsts.includeSubDomains(true).maxAgeInSeconds(31536000)) + .referrerPolicy(referrer -> referrer.policy(org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))); return http.build(); } diff --git a/src/main/java/com/finance/system/config/WebConfig.java b/src/main/java/com/finance/system/config/WebConfig.java index 18beb36..d18eb4d 100644 --- a/src/main/java/com/finance/system/config/WebConfig.java +++ b/src/main/java/com/finance/system/config/WebConfig.java @@ -16,7 +16,7 @@ import java.util.Collections; @Configuration public class WebConfig implements WebMvcConfigurer { - @Value("${app.frontend-url:http://localhost:5173}") + @Value("${app.frontend-url:}") private String frontendUrl; @Bean @@ -30,7 +30,8 @@ public class WebConfig implements WebMvcConfigurer { config.setAllowedOrigins(Collections.emptyList()); } config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")); - config.setAllowedHeaders(Arrays.asList("*")); + config.setAllowedHeaders(Arrays.asList( + "Authorization", "Content-Type", "Idempotency-Key", "X-Request-Id")); config.setAllowCredentials(true); config.setMaxAge(3600L); diff --git a/src/main/java/com/finance/system/controller/AuthController.java b/src/main/java/com/finance/system/controller/AuthController.java index 58cc041..b4b5ba2 100644 --- a/src/main/java/com/finance/system/controller/AuthController.java +++ b/src/main/java/com/finance/system/controller/AuthController.java @@ -101,9 +101,10 @@ public class AuthController { @CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) { String code = request.get("code"); String state = request.get("state"); - if (code == null || code.isEmpty()) { + if (code == null || code.trim().isEmpty() || code.length() > 4096 + || state == null || state.length() > 128) { return ResponseEntity.badRequest() - .body(ApiResponse.error(400, "授权码不能为空")); + .body(ApiResponse.error(400, "飞书授权参数无效,请重新发起登录")); } feishuAuthService.validateCallbackState(state, browserState, true); diff --git a/src/main/java/com/finance/system/controller/FeishuAuthController.java b/src/main/java/com/finance/system/controller/FeishuAuthController.java index 0e37614..3aeddef 100644 --- a/src/main/java/com/finance/system/controller/FeishuAuthController.java +++ b/src/main/java/com/finance/system/controller/FeishuAuthController.java @@ -25,6 +25,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.security.access.prepost.PreAuthorize; import javax.servlet.http.HttpServletRequest; +import org.springframework.web.bind.annotation.CookieValue; import java.net.URI; import java.net.URLEncoder; @@ -53,7 +54,7 @@ public class FeishuAuthController { this.webhookInboxService = webhookInboxService; } - @Value("${app.frontend-url:http://localhost:5173}") + @Value("${app.frontend-url:}") private String frontendUrl; @GetMapping("/auth-url") @@ -76,15 +77,24 @@ public class FeishuAuthController { */ @GetMapping("/callback") public ResponseEntity callback( - @RequestParam("code") String code, - @RequestParam(value = "state", required = false) String state) { + @RequestParam(value = "code", required = false) String code, + @RequestParam(value = "state", required = false) String state, + @RequestParam(value = "error", required = false) String error, + @CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) { log.info("Feishu OAuth callback received"); try { - feishuAuthService.validateCallbackState(state); + if (code == null || code.trim().isEmpty() || code.length() > 4096 || error != null) { + throw new BusinessException("飞书回调参数无效,请重新发起授权", 400); + } + // The frontend exchanges the authorization code at /api/auth/feishu-login. + // Validate the callback here, but leave the one-time state for that + // exchange endpoint to consume after it verifies the browser cookie. + feishuAuthService.validateCallbackState(state, browserState, false); String redirectUrl = frontendUrl + "/login?code=" + encodeUrl(code) + "&state=" + encodeUrl(state); HttpHeaders headers = new HttpHeaders(); + applySensitiveRedirectHeaders(headers); headers.setLocation(URI.create(redirectUrl)); return new ResponseEntity<>(headers, HttpStatus.FOUND); @@ -92,12 +102,14 @@ public class FeishuAuthController { log.warn("Feishu OAuth callback rejected; category=business status={}", e.getStatusCode()); String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败,请重新发起授权"); HttpHeaders headers = new HttpHeaders(); + applySensitiveRedirectHeaders(headers); headers.setLocation(URI.create(errorUrl)); return new ResponseEntity<>(headers, HttpStatus.FOUND); } catch (Exception e) { log.error("Feishu OAuth callback failed; category=internal"); String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败,请稍后重试"); HttpHeaders headers = new HttpHeaders(); + applySensitiveRedirectHeaders(headers); headers.setLocation(URI.create(errorUrl)); return new ResponseEntity<>(headers, HttpStatus.FOUND); } @@ -111,6 +123,12 @@ public class FeishuAuthController { } } + private void applySensitiveRedirectHeaders(HttpHeaders headers) { + headers.setCacheControl("no-store, no-cache, must-revalidate"); + headers.setPragma("no-cache"); + headers.set("Referrer-Policy", "no-referrer"); + } + /** * 飞书审批回调Webhook * 处理审批实例状态变更、审批任务变更等事件 diff --git a/src/main/java/com/finance/system/controller/FeishuCallbackController.java b/src/main/java/com/finance/system/controller/FeishuCallbackController.java deleted file mode 100644 index 803c448..0000000 --- a/src/main/java/com/finance/system/controller/FeishuCallbackController.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.finance.system.controller; - -import com.finance.system.adapter.feishu.FeishuAuthService; -import com.finance.system.adapter.feishu.FeishuTokenResponse; -import com.finance.system.adapter.feishu.FeishuUserInfo; -import com.finance.system.config.JwtConfig; -import com.finance.system.dto.ApiResponse; -import com.finance.system.dto.LoginResponse; -import com.finance.system.dto.UserProfile; -import com.finance.system.entity.SysDepartment; -import com.finance.system.entity.SysUser; -import com.finance.system.exception.BusinessException; -import com.finance.system.repository.SysDepartmentRepository; -import com.finance.system.repository.SysUserRepository; -import com.finance.system.service.RoleService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.Map; - -@Slf4j -@RestController -@RequestMapping("/api/feishu") -@RequiredArgsConstructor -public class FeishuCallbackController { - - private final FeishuAuthService feishuAuthService; - private final JwtConfig jwtConfig; - private final SysUserRepository sysUserRepository; - private final SysDepartmentRepository sysDepartmentRepository; - private final RoleService roleService; - - /** - * 飞书登录接口 - 返回JSON而非重定向 - * 前端先获取authUrl,用户授权后回调到前端,前端再调用此接口交换token - */ - @PostMapping("/login") - public ResponseEntity> feishuLogin( - @RequestBody Map request, - @CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) { - String code = request.get("code"); - String state = request.get("state"); - if (code == null || code.trim().isEmpty()) { - return ResponseEntity.badRequest() - .body(ApiResponse.error(400, "授权码不能为空")); - } - - try { - feishuAuthService.validateCallbackState(state, browserState, true); - // 1. 交换access_token - FeishuTokenResponse tokenResponse = feishuAuthService.getAccessToken(code); - String accessToken = tokenResponse.getData().getAccessToken(); - log.info("Feishu OAuth token exchange succeeded"); - - // 2. 获取用户信息 - FeishuUserInfo feishuUserInfo = feishuAuthService.getUserInfo(accessToken); - log.info("Feishu OAuth user-info request succeeded"); - - // 3. 查找已绑定的本地用户 - SysUser user = feishuAuthService.findOrCreateUser(feishuUserInfo); - log.info("Feishu OAuth local account finalization succeeded"); - if (!isActive(user)) { - return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用")); - } - - // 4. 生成JWT token - JwtConfig.GeneratedToken generatedToken = jwtConfig.generateTokenWithTtl( - user.getId(), - user.getEmployeeNo(), - user.getRealName(), - RoleService.normalize(user.getUserType())); - - // Profile/binding/lastLogin were committed by the shared locked login finalizer. - - // 6. 构建用户档案 - UserProfile profile = buildUserProfile(user); - - LoginResponse loginResponse = LoginResponse.builder() - .token(generatedToken.getToken()) - .tokenType("Bearer") - .expiresIn(generatedToken.getExpiresIn()) - .user(profile) - .build(); - - return ResponseEntity.ok(ApiResponse.success(loginResponse)); - - } catch (BusinessException e) { - log.warn("Feishu OAuth login rejected; category=business status={}", e.getStatusCode()); - return ResponseEntity.status(e.getStatusCode()) - .body(ApiResponse.error(e.getStatusCode(), e.getMessage())); - } catch (Exception e) { - log.error("Feishu OAuth login failed; category=internal"); - return ResponseEntity.status(500).body(ApiResponse.error(500, "飞书登录失败,请稍后重试")); - } - } - - /** - * GET方式也支持(通过查询参数传递code) - */ - @GetMapping("/login") - public ResponseEntity> feishuLoginGet( - @RequestParam("code") String code, - @RequestParam("state") String state, - @CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) { - if (code == null || code.trim().isEmpty()) { - return ResponseEntity.badRequest() - .body(ApiResponse.error(400, "授权码不能为空")); - } - - try { - feishuAuthService.validateCallbackState(state, browserState, true); - FeishuTokenResponse tokenResponse = feishuAuthService.getAccessToken(code); - String accessToken = tokenResponse.getData().getAccessToken(); - FeishuUserInfo feishuUserInfo = feishuAuthService.getUserInfo(accessToken); - SysUser user = feishuAuthService.findOrCreateUser(feishuUserInfo); - if (!isActive(user)) { - return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用")); - } - - JwtConfig.GeneratedToken generatedToken = jwtConfig.generateTokenWithTtl( - user.getId(), - user.getEmployeeNo(), - user.getRealName(), - RoleService.normalize(user.getUserType())); - - UserProfile profile = buildUserProfile(user); - - LoginResponse loginResponse = LoginResponse.builder() - .token(generatedToken.getToken()) - .tokenType("Bearer") - .expiresIn(generatedToken.getExpiresIn()) - .user(profile) - .build(); - - return ResponseEntity.ok(ApiResponse.success(loginResponse)); - - } catch (BusinessException e) { - log.warn("Feishu OAuth login rejected; category=business status={}", e.getStatusCode()); - return ResponseEntity.status(e.getStatusCode()) - .body(ApiResponse.error(e.getStatusCode(), e.getMessage())); - } catch (Exception e) { - log.error("Feishu OAuth login failed; category=internal"); - return ResponseEntity.status(500).body(ApiResponse.error(500, "飞书登录失败,请稍后重试")); - } - } - - private UserProfile buildUserProfile(SysUser user) { - String deptName = null; - if (user.getDepartmentId() != null) { - SysDepartment dept = sysDepartmentRepository.findById(user.getDepartmentId()).orElse(null); - if (dept != null) { - deptName = dept.getDeptName(); - } - } - - return UserProfile.builder() - .id(user.getId()) - .employeeNo(user.getEmployeeNo()) - .realName(user.getRealName()) - .avatarUrl(user.getAvatarUrl()) - .email(user.getEmail()) - .departmentName(deptName) - .position(user.getPosition()) - .userType(RoleService.normalize(user.getUserType())) - .status(user.getStatus()) - .feishuStatus(user.getFeishuOpenId() != null ? "已授权" : "未绑定") - .lastLoginAt(user.getLastLoginAt() != null ? user.getLastLoginAt().toString().replace("T", " ") : null) - .roleCodes(roleService.userRoleCodes(user.getId())) - .groupNames(roleService.userGroupNames(user.getId())) - .isSuperAdmin(roleService.isSuperAdmin(user.getId())) - .build(); - } - - private boolean isActive(SysUser user) { - return user != null && "ACTIVE".equalsIgnoreCase(user.getStatus()); - } -} diff --git a/src/main/java/com/finance/system/controller/PaymentController.java b/src/main/java/com/finance/system/controller/PaymentController.java index 49fcf72..170cfa1 100644 --- a/src/main/java/com/finance/system/controller/PaymentController.java +++ b/src/main/java/com/finance/system/controller/PaymentController.java @@ -6,6 +6,7 @@ import com.finance.system.util.AuditUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; +import org.springframework.context.annotation.Profile; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; @@ -16,6 +17,7 @@ import java.util.*; @RestController @RequestMapping("/api/payments") @RequiredArgsConstructor +@Profile({"local", "test"}) public class PaymentController { /** diff --git a/src/main/java/com/finance/system/repository/SysRoleRepository.java b/src/main/java/com/finance/system/repository/SysRoleRepository.java index d54dbb2..1dc9b3d 100644 --- a/src/main/java/com/finance/system/repository/SysRoleRepository.java +++ b/src/main/java/com/finance/system/repository/SysRoleRepository.java @@ -13,6 +13,9 @@ import java.util.Optional; public interface SysRoleRepository extends JpaRepository { Optional findByRoleCode(String roleCode); @Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE) + @Query("select r from SysRole r where r.id = :id") + Optional findByIdForUpdate(@Param("id") Long id); + @Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE) @Query("select r from SysRole r where r.roleCode = :roleCode") Optional findByRoleCodeForUpdate(@Param("roleCode") String roleCode); boolean existsByRoleCode(String roleCode); diff --git a/src/main/java/com/finance/system/security/ApiAccessLogFilter.java b/src/main/java/com/finance/system/security/ApiAccessLogFilter.java index 939f6d0..22ab951 100644 --- a/src/main/java/com/finance/system/security/ApiAccessLogFilter.java +++ b/src/main/java/com/finance/system/security/ApiAccessLogFilter.java @@ -4,6 +4,7 @@ import com.finance.system.entity.SysApiAccessLog; import com.finance.system.service.ApiAccessLogService; import com.finance.system.util.AuditUtil; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; @@ -25,27 +26,24 @@ import java.util.UUID; * Authorization headers and known secret query keys are never stored. */ @Component +@Slf4j @RequiredArgsConstructor public class ApiAccessLogFilter extends OncePerRequestFilter { private static final Set REDACT_QUERY_KEYS = new HashSet<>(Arrays.asList( "password", "passwd", "secret", "token", "access_token", "refresh_token", - "authorization", "code", "client_secret", "app_secret", "jwt")); + "authorization", "code", "state", "ticket", "signature", "nonce", + "client_secret", "app_secret", "jwt", "email", "mobile", "phone", + "open_id", "user_id")); private final ApiAccessLogService apiAccessLogService; @Override protected boolean shouldNotFilter(HttpServletRequest request) { String path = path(request); - if (!path.startsWith("/api/")) { - return true; - } - String method = request.getMethod(); - // View/read traffic is intentionally not persisted — only mutating calls are logged. - if ("GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method) || "OPTIONS".equalsIgnoreCase(method)) { - return true; - } - return false; + // Capture every API method (including read and preflight requests), as + // well as operational actuator endpoints. Static resources are excluded. + return !(path.startsWith("/api/") || path.startsWith("/actuator/")); } @Override @@ -57,10 +55,28 @@ public class ApiAccessLogFilter extends OncePerRequestFilter { try { filterChain.doFilter(request, response); } finally { + SysApiAccessLog entry = null; try { - apiAccessLogService.recordAsync(buildEntry(request, response, requestId, started)); + entry = buildEntry(request, response, requestId, started); + UserPrincipal user = AuditUtil.getCurrentUser(); + String operatorName = user == null ? entry.getOperatorName() : safe(user.getRealName(), 100); + String operatorId = user == null || user.getId() == null ? "未登录" : String.valueOf(user.getId()); + log.info("接口访问 | 请求ID={} | 操作人={}(用户ID={}) | 方法={} | 路径={} | 参数={} | 状态={} | 耗时={}毫秒 | 分类={} | 来源IP={}", + entry.getRequestId(), operatorName, operatorId, methodLabel(entry.getHttpMethod()), + entry.getRequestPath(), entry.getQueryString() == null ? "无" : entry.getQueryString(), + statusLabel(entry.getStatusCode()), entry.getDurationMs(), entry.getCategory(), + entry.getClientIp()); } catch (Exception ignored) { - // Logging must never break the original request/response path. + log.warn("接口日志记录失败 | 请求ID={} | 方法={} | 路径={} | 状态码={}", + requestId, methodLabel(safe(request.getMethod(), 16)), + safe(path(request), 500), response.getStatus()); + } + if (entry != null) { + try { + apiAccessLogService.recordAsync(entry); + } catch (Exception ignored) { + // Logging must never break the original request/response path. + } } } } @@ -84,15 +100,16 @@ public class ApiAccessLogFilter extends OncePerRequestFilter { .statusCode(status) .durationMs((int) Math.min(Integer.MAX_VALUE, Math.max(0, System.currentTimeMillis() - started))) .clientIp(truncate(clientIp(request), 64)) - .userAgent(truncate(request.getHeader("User-Agent"), 500)) + .userAgent(safe(request.getHeader("User-Agent"), 500)) .errorMessage(status >= 400 ? truncate("HTTP " + status, 1000) : null) .build(); } private String resolveRequestId(HttpServletRequest request) { String incoming = request.getHeader("X-Request-Id"); - if (StringUtils.hasText(incoming)) { - return truncate(incoming.trim(), 64); + if (StringUtils.hasText(incoming) && incoming.length() <= 64 + && incoming.matches("[A-Za-z0-9._-]+")) { + return incoming; } return UUID.randomUUID().toString().replace("-", ""); } @@ -107,16 +124,9 @@ public class ApiAccessLogFilter extends OncePerRequestFilter { } private String clientIp(HttpServletRequest request) { - String forwarded = request.getHeader("X-Forwarded-For"); - if (StringUtils.hasText(forwarded)) { - int comma = forwarded.indexOf(','); - return (comma >= 0 ? forwarded.substring(0, comma) : forwarded).trim(); - } - String realIp = request.getHeader("X-Real-IP"); - if (StringUtils.hasText(realIp)) { - return realIp.trim(); - } - return request.getRemoteAddr(); + // Forwarded headers are client-controlled unless a trusted proxy chain + // has been configured. Log the transport peer instead of spoofable data. + return safe(request.getRemoteAddr(), 64); } private String sanitizeQuery(String query) { @@ -135,22 +145,59 @@ public class ApiAccessLogFilter extends OncePerRequestFilter { String key = eq >= 0 ? part.substring(0, eq) : part; String value = eq >= 0 ? part.substring(eq + 1) : ""; if (REDACT_QUERY_KEYS.contains(key.toLowerCase(Locale.ROOT))) { - sanitized.append(key).append('=').append("***"); + sanitized.append(safe(key, 100)).append('=').append("[REDACTED]"); } else { - sanitized.append(key); + sanitized.append(safe(key, 100)); if (eq >= 0) { - sanitized.append('=').append(value); + sanitized.append('=').append(safe(value, 200)); } } } - return truncate(sanitized.toString(), 1000); + return safe(sanitized.toString(), 1000); } private String truncate(String value, int max) { - if (!StringUtils.hasText(value)) { - return value; + return safe(value, max); + } + + private String safe(String value, int max) { + if (value == null) return null; + StringBuilder cleaned = new StringBuilder(Math.min(value.length(), max)); + for (int i = 0; i < value.length() && cleaned.length() < max; i++) { + char ch = value.charAt(i); + cleaned.append(Character.isISOControl(ch) ? ' ' : ch); + } + String result = cleaned.toString().trim(); + return result.isEmpty() ? null : result; + } + + private String methodLabel(String method) { + if (method == null) return "未知"; + switch (method.toUpperCase(Locale.ROOT)) { + case "GET": return "GET-查询"; + case "POST": return "POST-提交"; + case "PUT": return "PUT-更新"; + case "PATCH": return "PATCH-部分更新"; + case "DELETE": return "DELETE-删除"; + case "HEAD": return "HEAD-读取元信息"; + case "OPTIONS": return "OPTIONS-跨域预检"; + default: return safe(method, 16); + } + } + + private String statusLabel(int status) { + if (status >= 500) return status + "-服务异常"; + switch (status) { + case 200: return "200-成功"; + case 201: return "201-创建成功"; + case 204: return "204-成功无内容"; + case 400: return "400-请求参数错误"; + case 401: return "401-未认证"; + case 403: return "403-无权限"; + case 404: return "404-资源不存在"; + case 409: return "409-业务冲突"; + case 422: return "422-业务校验未通过"; + default: return status + (status >= 400 ? "-请求失败" : "-已处理"); } - String trimmed = value.trim(); - return trimmed.length() <= max ? trimmed : trimmed.substring(0, max); } } diff --git a/src/main/java/com/finance/system/service/RoleService.java b/src/main/java/com/finance/system/service/RoleService.java index 6a4e262..eaacb9c 100644 --- a/src/main/java/com/finance/system/service/RoleService.java +++ b/src/main/java/com/finance/system/service/RoleService.java @@ -26,7 +26,7 @@ public class RoleService { public static final String SUPER_ADMIN = "SUPER_ADMIN"; public static final String DEFAULT_EMPLOYEE_GROUP = "DEFAULT_EMPLOYEE"; private static final Set ACCESS_LEVELS = new HashSet<>(Arrays.asList("HIDDEN", "READ", "EDIT")); - private static final Set PERMISSION_TYPES = new HashSet<>(Arrays.asList("MENU", "BUTTON", "FIELD")); + private static final Set PERMISSION_TYPES = new HashSet<>(Arrays.asList("MENU", "ACTION", "BUTTON", "FIELD")); private static final Set SAFE_EMPLOYEE_PERMISSIONS = new LinkedHashSet<>(Arrays.asList( "dashboard", "applications", "application:create", "application:view-own", "application:amount", "application:payeeName", "application:bankAccount", @@ -212,7 +212,8 @@ public class RoleService { @Transactional public void replaceRolePermissions(Long roleId, Map body, Long actorId) { - SysRole targetRole = requireRole(roleId); + SysRole targetRole = roles.findByIdForUpdate(roleId) + .orElseThrow(() -> new ResourceNotFoundException("角色不存在")); boolean superAdmin = isSuperAdmin(actorId); if (!superAdmin && !hasEditPermission(actorId, "system.role.permission.configure")) { throw new BusinessException("无权管理角色权限", 403); @@ -221,8 +222,10 @@ public class RoleService { throw new BusinessException("普通管理员不能修改内置角色权限", 403); } if (body == null) throw new BusinessException("权限请求不能为空", 400); + validatePermissionPayload(body); Map catalog = permissions.findAll().stream() .collect(Collectors.toMap(SysPermission::getPermissionCode, p -> p)); + validatePermissionSnapshot(roleId, body, catalog); Map requested = requestedAccess(body, catalog); addReadableAncestors(requested, catalog); for (Map.Entry entry : requested.entrySet()) { @@ -1200,6 +1203,53 @@ public class RoleService { return result; } + private void validatePermissionPayload(Map body) { + if (body.containsKey("permissionAccess")) { + if (!(body.get("permissionAccess") instanceof Map) + || ((Map) body.get("permissionAccess")).isEmpty()) { + throw new BusinessException("permissionAccess 不能为空", 400); + } + } else { + if (!body.containsKey("permissionCodes") && !body.containsKey("fieldPermissions")) { + throw new BusinessException("缺少权限载荷", 400); + } + Object codes = body.get("permissionCodes"); + Object fields = body.get("fieldPermissions"); + if (codes != null && !(codes instanceof Collection)) + throw new BusinessException("permissionCodes 必须是数组", 400); + if (fields != null && !(fields instanceof Map)) + throw new BusinessException("fieldPermissions 必须是对象", 400); + if (!(codes instanceof Collection) && !(fields instanceof Map)) + throw new BusinessException("缺少权限载荷", 400); + if ((codes == null || ((Collection) codes).isEmpty()) + && (fields == null || ((Map) fields).isEmpty())) { + throw new BusinessException("权限载荷不能为空", 400); + } + } + if (!(body.get("expectedPermissionAccess") instanceof Map) + || ((Map) body.get("expectedPermissionAccess")).isEmpty()) { + throw new BusinessException("缺少权限编辑基线,请重新加载角色权限后重试", 400); + } + } + + private void validatePermissionSnapshot(Long roleId, Map body, + Map catalog) { + Map expected = stringMap(body.get("expectedPermissionAccess")); + if (expected.isEmpty()) { + throw new BusinessException("权限编辑基线为空,请重新加载角色权限后重试", 400); + } + for (Map.Entry entry : expected.entrySet()) { + if (!catalog.containsKey(entry.getKey()) || !ACCESS_LEVELS.contains(entry.getValue())) { + throw new BusinessException("权限编辑基线格式无效,请重新加载后重试", 400); + } + } + Map currentPayload = rolePermissions(roleId); + Map current = stringMap(currentPayload.get("permissionAccess")); + if (!expected.equals(current)) { + throw new BusinessException("角色权限已被其他管理员修改,请重新加载后再保存", 409); + } + } + private void addReadableAncestors(Map requested, Map catalog) { for (String code : new ArrayList<>(requested.keySet())) { if ("HIDDEN".equals(requested.get(code))) continue; diff --git a/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java b/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java index 214bc44..e9e0d57 100644 --- a/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java +++ b/src/main/java/com/finance/system/service/impl/ReimApplicationServiceImpl.java @@ -542,11 +542,13 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { return !oldAmounts.equals(newAmounts); } + private static final BigDecimal MAX_MONEY_AMOUNT = new BigDecimal("99999999.99"); + private void validateRequest(CreateApplicationRequest request, Long userId) { - if (request == null || request.getTotalAmount() == null - || request.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0) { - throw new BusinessException("总金额必须大于0", 400); + if (request == null || request.getTotalAmount() == null) { + throw new BusinessException("请填写申请金额", 400); } + assertMoneyAmount(request.getTotalAmount(), "申请金额"); if (userId == null || !sysUserRepository.findById(userId).map(u -> u.getDepartmentId() != null).orElse(false)) { throw new BusinessException("申请人未配置部门"); } @@ -565,15 +567,20 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { throw new BusinessException("费用类型不存在或已停用"); } BigDecimal sum = BigDecimal.ZERO; + int index = 0; for (ExpenseItemDto item : request.getItems()) { - if (item == null || item.getAmount() == null || item.getAmount().compareTo(BigDecimal.ZERO) <= 0 - || item.getCategory() == null || item.getCategory().trim().isEmpty()) { - throw new BusinessException("费用明细金额必须大于0"); + index++; + if (item == null || item.getCategory() == null || item.getCategory().trim().isEmpty()) { + throw new BusinessException("第 " + index + " 条费用明细类别不能为空", 400); } + if (item.getAmount() == null) { + throw new BusinessException("第 " + index + " 条费用明细:请填写金额", 400); + } + assertMoneyAmount(item.getAmount(), "第 " + index + " 条费用明细金额"); sum = sum.add(item.getAmount()); } if (sum.compareTo(request.getTotalAmount()) != 0) { - throw new BusinessException("费用明细合计必须等于总金额"); + throw new BusinessException("明细合计须与申请金额一致,请核对各行金额", 400); } if (request.getPayeeBankId() == null || !sysBankAccountRepository.findById(request.getPayeeBankId()).map(b -> userId.equals(b.getUserId())).orElse(false)) { @@ -581,6 +588,18 @@ public class ReimApplicationServiceImpl implements ReimApplicationService { } } + private void assertMoneyAmount(BigDecimal amount, String label) { + if (amount.compareTo(BigDecimal.ZERO) <= 0) { + throw new BusinessException(label + "须大于 0", 400); + } + if (amount.remainder(new BigDecimal("0.01")).compareTo(BigDecimal.ZERO) != 0) { + throw new BusinessException(label + "最多保留两位小数", 400); + } + if (amount.compareTo(MAX_MONEY_AMOUNT) > 0) { + throw new BusinessException(label + "不能超过 99,999,999.99 元", 400); + } + } + private void validatePersistedApplication(ReimApplication app) { List items = reimExpenseItemRepository.findByApplicationId(app.getId()); if (app.getTotalAmount() == null || app.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0 || items.isEmpty()) { diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 4eb9803..ac79b98 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -30,7 +30,7 @@ database: # Must match Connector/J's DB_URL serverTimezone because MySQL DATETIME has no zone. time-zone: "${DB_TIME_ZONE:Asia/Shanghai}" jwt: - secret: "${JWT_SECRET:Uqen22fWWeubQ6f2dFIWteMDIhd4PU4u}" + secret: "${JWT_SECRET:local-only-insecure-secret-change-before-deploy}" expiration: ${JWT_EXPIRATION:86400000} auth: time-zone: "${AUTH_TIME_ZONE:Asia/Shanghai}" diff --git a/src/test/java/com/finance/system/security/ApiAccessLogFilterTest.java b/src/test/java/com/finance/system/security/ApiAccessLogFilterTest.java new file mode 100644 index 0000000..d039d71 --- /dev/null +++ b/src/test/java/com/finance/system/security/ApiAccessLogFilterTest.java @@ -0,0 +1,88 @@ +package com.finance.system.security; + +import com.finance.system.entity.SysApiAccessLog; +import com.finance.system.service.ApiAccessLogService; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import javax.servlet.FilterChain; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import org.mockito.ArgumentCaptor; + +class ApiAccessLogFilterTest { + + @Test + void logsAndPersistsReadAndWriteApiRequestsWithoutTrustingForwardedIp() throws Exception { + ApiAccessLogService service = mock(ApiAccessLogService.class); + ExposedFilter filter = new ExposedFilter(service); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/auth/me"); + request.setQueryString("code=oauth-code&state=oauth-state&token=bearer-secret&email=person%40example.com&view=summary"); + request.setRemoteAddr("10.0.0.8"); + request.addHeader("X-Forwarded-For", "203.0.113.99"); + request.addHeader("X-Request-Id", "test.request-1"); + MockHttpServletResponse response = new MockHttpServletResponse(); + AtomicInteger invoked = new AtomicInteger(); + FilterChain chain = (req, res) -> { + invoked.incrementAndGet(); + ((MockHttpServletResponse) res).setStatus(200); + }; + + filter.run(request, response, chain); + + assertThat(invoked).hasValue(1); + assertThat(response.getHeader("X-Request-Id")).isEqualTo("test.request-1"); + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(SysApiAccessLog.class); + verify(service).recordAsync(entryCaptor.capture()); + SysApiAccessLog entry = entryCaptor.getValue(); + assertThat(entry.getHttpMethod()).isEqualTo("GET"); + assertThat(entry.getRequestPath()).isEqualTo("/api/auth/me"); + assertThat(entry.getStatusCode()).isEqualTo(200); + assertThat(entry.getClientIp()).isEqualTo("10.0.0.8"); + assertThat(entry.getQueryString()) + .contains("view=summary") + .doesNotContain("oauth-code", "oauth-state", "bearer-secret", "person%40example.com"); + } + + @Test + void capturesOptionsAndErrorResponsesAndSkipsNonApiResources() throws Exception { + ExposedFilter filter = new ExposedFilter(mock(ApiAccessLogService.class)); + assertThat(filter.skips(new MockHttpServletRequest("OPTIONS", "/api/payments"))).isFalse(); + assertThat(filter.skips(new MockHttpServletRequest("HEAD", "/api/users"))).isFalse(); + assertThat(filter.skips(new MockHttpServletRequest("GET", "/assets/app.js"))).isTrue(); + + MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/payments/register"); + MockHttpServletResponse response = new MockHttpServletResponse(); + FilterChain chain = (req, res) -> ((MockHttpServletResponse) res).setStatus(422); + filter.run(request, response, chain); + + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(SysApiAccessLog.class); + verify(filter.service).recordAsync(entryCaptor.capture()); + assertThat(entryCaptor.getValue().getStatusCode()).isEqualTo(422); + assertThat(entryCaptor.getValue().getErrorMessage()).contains("422"); + } + + private static final class ExposedFilter extends ApiAccessLogFilter { + private final ApiAccessLogService service; + + private ExposedFilter(ApiAccessLogService service) { + super(service); + this.service = service; + } + + private boolean skips(MockHttpServletRequest request) { + return shouldNotFilter(request); + } + + private void run(MockHttpServletRequest request, MockHttpServletResponse response, + FilterChain chain) throws Exception { + doFilterInternal(request, response, chain); + } + } +} diff --git a/src/test/java/com/finance/system/service/RoleServicePermissionSecurityTest.java b/src/test/java/com/finance/system/service/RoleServicePermissionSecurityTest.java new file mode 100644 index 0000000..499b88b --- /dev/null +++ b/src/test/java/com/finance/system/service/RoleServicePermissionSecurityTest.java @@ -0,0 +1,116 @@ +package com.finance.system.service; + +import com.finance.system.entity.SysPermission; +import com.finance.system.entity.SysRole; +import com.finance.system.exception.BusinessException; +import com.finance.system.repository.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class RoleServicePermissionSecurityTest { + private SysRoleRepository roles; + private SysPermissionRepository permissions; + private SysRolePermissionRepository rolePermissions; + private RoleService service; + + @BeforeEach + void setUp() { + roles = mock(SysRoleRepository.class); + permissions = mock(SysPermissionRepository.class); + rolePermissions = mock(SysRolePermissionRepository.class); + service = spy(new RoleService(roles, permissions, rolePermissions, mock(SysUserRepository.class), + mock(SysUserGroupRepository.class), mock(SysUserGroupMemberRepository.class), + mock(SysUserGroupRoleRepository.class))); + doReturn(true).when(service).isSuperAdmin(1L); + SysRole target = new SysRole(); + target.setId(7L); + target.setBuiltIn(false); + when(roles.findById(7L)).thenReturn(Optional.of(target)); + when(roles.findByIdForUpdate(7L)).thenReturn(Optional.of(target)); + } + + @Test + void rejectsAbsentOrEmptyPermissionAccessWithoutDeleting() { + assertThatThrownBy(() -> service.replaceRolePermissions(7L, Collections.emptyMap(), 1L)) + .isInstanceOf(BusinessException.class); + assertThatThrownBy(() -> service.replaceRolePermissions(7L, + Collections.singletonMap("permissionAccess", Collections.emptyMap()), 1L)) + .isInstanceOf(BusinessException.class); + verify(rolePermissions, never()).deleteByIdRoleId(7L); + } + + @Test + void rejectsEmptyLegacyPayloadWithoutDeleting() { + Map payload = new HashMap<>(); + payload.put("permissionCodes", Collections.emptyList()); + payload.put("fieldPermissions", Collections.emptyMap()); + assertThatThrownBy(() -> service.replaceRolePermissions(7L, payload, 1L)) + .isInstanceOf(BusinessException.class); + verify(rolePermissions, never()).deleteByIdRoleId(7L); + } + + @Test + void rejectsMalformedLegacyCollectionsWithClientErrorWithoutDeleting() { + Map payload = new HashMap<>(); + payload.put("permissionCodes", "not-an-array"); + payload.put("fieldPermissions", Collections.emptyMap()); + assertThatThrownBy(() -> service.replaceRolePermissions(7L, payload, 1L)) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("permissionCodes 必须是数组"); + verify(rolePermissions, never()).deleteByIdRoleId(7L); + } + + @Test + void acceptsCompleteHiddenPayloadAndActionPermission() { + SysPermission action = permission(21L, "report.export", "ACTION"); + SysPermission menu = permission(22L, "dashboard", "MENU"); + when(permissions.findAll()).thenReturn(Arrays.asList(action, menu)); + + Map allHidden = new LinkedHashMap<>(); + allHidden.put("report.export", "HIDDEN"); + allHidden.put("dashboard", "HIDDEN"); + Map update = new LinkedHashMap<>(); + update.put("permissionAccess", allHidden); + update.put("expectedPermissionAccess", allHidden); + service.replaceRolePermissions(7L, update, 1L); + verify(rolePermissions).deleteByIdRoleId(7L); + verify(rolePermissions).saveAll(any()); + + reset(rolePermissions); + Map grantAction = new LinkedHashMap<>(); + grantAction.put("permissionAccess", Collections.singletonMap("report.export", "EDIT")); + grantAction.put("expectedPermissionAccess", allHidden); + service.replaceRolePermissions(7L, grantAction, 1L); + verify(rolePermissions).deleteByIdRoleId(7L); + verify(rolePermissions).saveAll(any()); + } + + @Test + void rejectsStalePermissionSnapshotWithoutOverwritingNewChanges() { + SysPermission menu = permission(22L, "dashboard", "MENU"); + when(permissions.findAll()).thenReturn(Collections.singletonList(menu)); + Map request = new LinkedHashMap<>(); + request.put("permissionAccess", Collections.singletonMap("dashboard", "EDIT")); + request.put("expectedPermissionAccess", Collections.singletonMap("dashboard", "READ")); + + assertThatThrownBy(() -> service.replaceRolePermissions(7L, request, 1L)) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("已被其他管理员修改"); + verify(rolePermissions, never()).deleteByIdRoleId(7L); + } + + private SysPermission permission(Long id, String code, String type) { + SysPermission permission = new SysPermission(); + permission.setId(id); + permission.setPermissionCode(code); + permission.setPermissionType(type); + permission.setDefaultAccess("READ"); + return permission; + } +}