优化第一次

This commit is contained in:
Weiming committed 2026-10-09 16:35:47 +08:00
1 parent 52fb651e3e
commit 741bf2ee73
16 files changed
+454 -235

No files matched your search

@@ -1,16 +1,48 @@
package com.finance.system; package com.finance.system;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties; 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 org.springframework.scheduling.annotation.EnableScheduling;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
@SpringBootApplication @SpringBootApplication
@EnableConfigurationProperties @EnableConfigurationProperties
@EnableScheduling @EnableScheduling
@Slf4j
@RequiredArgsConstructor
public class FinanceSystemApplication { public class FinanceSystemApplication {
private final Environment environment;
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(FinanceSystemApplication.class, 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;
}
} }
@@ -91,7 +91,8 @@ public class FeishuAuthService {
*/ */
@Transactional @Transactional
public void validateCallbackState(String state, String browserState, boolean consume) { 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); throw new BusinessException("飞书登录状态缺失,请重新发起授权", 400);
} }
if (consume && (!StringUtils.hasText(browserState) if (consume && (!StringUtils.hasText(browserState)
@@ -5,6 +5,8 @@ import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys; import io.jsonwebtoken.security.Keys;
import lombok.Getter; import lombok.Getter;
import org.springframework.beans.factory.annotation.Value; 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.stereotype.Component;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@@ -38,13 +40,26 @@ public class JwtConfig {
@Value("${auth.time-zone:Asia/Shanghai}") @Value("${auth.time-zone:Asia/Shanghai}")
private String timeZone = "Asia/Shanghai"; private String timeZone = "Asia/Shanghai";
@Autowired
private Environment environment;
@PostConstruct @PostConstruct
void validateConfiguration() { void validateConfiguration() {
validateSecretValue(secret); 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); validateExpirationValue(expiration);
getAuthZoneId(); getAuthZoneId();
} }
private boolean isLocalProfile() {
return environment != null && java.util.Arrays.stream(environment.getActiveProfiles())
.anyMatch(profile -> "local".equalsIgnoreCase(profile));
}
static void validateSecretValue(String secret) { static void validateSecretValue(String secret) {
if (!StringUtils.hasText(secret) if (!StringUtils.hasText(secret)
|| secret.getBytes(StandardCharsets.UTF_8).length < MIN_SECRET_BYTES) { || secret.getBytes(StandardCharsets.UTF_8).length < MIN_SECRET_BYTES) {
@@ -38,14 +38,15 @@ public class SecurityConfig {
.authorizeHttpRequests(auth -> { .authorizeHttpRequests(auth -> {
if (isDevelopmentProfile()) { if (isDevelopmentProfile()) {
auth.antMatchers("/api/auth/login").permitAll(); auth.antMatchers("/api/auth/login").permitAll();
auth.antMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll();
} }
auth auth
.antMatchers("/api/auth/feishu-login").permitAll() .antMatchers("/api/auth/feishu-login").permitAll()
.antMatchers("/api/feishu/auth-url", "/api/feishu/callback", "/api/feishu/webhook", "/api/feishu/login").permitAll() // OAuth initiation/callback and the signed Feishu event receiver are the
.antMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll() // 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("/actuator/health").permitAll()
.antMatchers("/api/**").authenticated() .anyRequest().authenticated();
.anyRequest().permitAll();
}) })
.exceptionHandling(exceptions -> exceptions.authenticationEntryPoint( .exceptionHandling(exceptions -> exceptions.authenticationEntryPoint(
(request, response, exception) -> { (request, response, exception) -> {
@@ -58,7 +59,11 @@ public class SecurityConfig {
)) ))
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterAfter(apiAccessLogFilter, 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(); return http.build();
} }
@@ -16,7 +16,7 @@ import java.util.Collections;
@Configuration @Configuration
public class WebConfig implements WebMvcConfigurer { public class WebConfig implements WebMvcConfigurer {
@Value("${app.frontend-url:http://localhost:5173}") @Value("${app.frontend-url:}")
private String frontendUrl; private String frontendUrl;
@Bean @Bean
@@ -30,7 +30,8 @@ public class WebConfig implements WebMvcConfigurer {
config.setAllowedOrigins(Collections.<String>emptyList()); config.setAllowedOrigins(Collections.<String>emptyList());
} }
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")); 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.setAllowCredentials(true);
config.setMaxAge(3600L); config.setMaxAge(3600L);
@@ -101,9 +101,10 @@ public class AuthController {
@CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) { @CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) {
String code = request.get("code"); String code = request.get("code");
String state = request.get("state"); 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() return ResponseEntity.badRequest()
.body(ApiResponse.error(400, "授权码不能为空")); .body(ApiResponse.error(400, "飞书授权参数无效,请重新发起登录"));
} }
feishuAuthService.validateCallbackState(state, browserState, true); feishuAuthService.validateCallbackState(state, browserState, true);
@@ -25,6 +25,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.CookieValue;
import java.net.URI; import java.net.URI;
import java.net.URLEncoder; import java.net.URLEncoder;
@@ -53,7 +54,7 @@ public class FeishuAuthController {
this.webhookInboxService = webhookInboxService; this.webhookInboxService = webhookInboxService;
} }
@Value("${app.frontend-url:http://localhost:5173}") @Value("${app.frontend-url:}")
private String frontendUrl; private String frontendUrl;
@GetMapping("/auth-url") @GetMapping("/auth-url")
@@ -76,15 +77,24 @@ public class FeishuAuthController {
*/ */
@GetMapping("/callback") @GetMapping("/callback")
public ResponseEntity<Void> callback( public ResponseEntity<Void> callback(
@RequestParam("code") String code, @RequestParam(value = "code", required = false) String code,
@RequestParam(value = "state", required = false) String state) { @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"); log.info("Feishu OAuth callback received");
try { 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) String redirectUrl = frontendUrl + "/login?code=" + encodeUrl(code)
+ "&state=" + encodeUrl(state); + "&state=" + encodeUrl(state);
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
applySensitiveRedirectHeaders(headers);
headers.setLocation(URI.create(redirectUrl)); headers.setLocation(URI.create(redirectUrl));
return new ResponseEntity<>(headers, HttpStatus.FOUND); return new ResponseEntity<>(headers, HttpStatus.FOUND);
@@ -92,12 +102,14 @@ public class FeishuAuthController {
log.warn("Feishu OAuth callback rejected; category=business status={}", e.getStatusCode()); log.warn("Feishu OAuth callback rejected; category=business status={}", e.getStatusCode());
String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败,请重新发起授权"); String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败,请重新发起授权");
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
applySensitiveRedirectHeaders(headers);
headers.setLocation(URI.create(errorUrl)); headers.setLocation(URI.create(errorUrl));
return new ResponseEntity<>(headers, HttpStatus.FOUND); return new ResponseEntity<>(headers, HttpStatus.FOUND);
} catch (Exception e) { } catch (Exception e) {
log.error("Feishu OAuth callback failed; category=internal"); log.error("Feishu OAuth callback failed; category=internal");
String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败,请稍后重试"); String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败,请稍后重试");
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
applySensitiveRedirectHeaders(headers);
headers.setLocation(URI.create(errorUrl)); headers.setLocation(URI.create(errorUrl));
return new ResponseEntity<>(headers, HttpStatus.FOUND); 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 * 飞书审批回调Webhook
* 处理审批实例状态变更、审批任务变更等事件 * 处理审批实例状态变更、审批任务变更等事件
@@ -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<ApiResponse<LoginResponse>> feishuLogin(
@RequestBody Map<String, String> 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<ApiResponse<LoginResponse>> 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());
}
}
@@ -6,6 +6,7 @@ import com.finance.system.util.AuditUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.context.annotation.Profile;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@@ -16,6 +17,7 @@ import java.util.*;
@RestController @RestController
@RequestMapping("/api/payments") @RequestMapping("/api/payments")
@RequiredArgsConstructor @RequiredArgsConstructor
@Profile({"local", "test"})
public class PaymentController { public class PaymentController {
/** /**
@@ -13,6 +13,9 @@ import java.util.Optional;
public interface SysRoleRepository extends JpaRepository<SysRole, Long> { public interface SysRoleRepository extends JpaRepository<SysRole, Long> {
Optional<SysRole> findByRoleCode(String roleCode); Optional<SysRole> findByRoleCode(String roleCode);
@Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE) @Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE)
@Query("select r from SysRole r where r.id = :id")
Optional<SysRole> findByIdForUpdate(@Param("id") Long id);
@Lock(javax.persistence.LockModeType.PESSIMISTIC_WRITE)
@Query("select r from SysRole r where r.roleCode = :roleCode") @Query("select r from SysRole r where r.roleCode = :roleCode")
Optional<SysRole> findByRoleCodeForUpdate(@Param("roleCode") String roleCode); Optional<SysRole> findByRoleCodeForUpdate(@Param("roleCode") String roleCode);
boolean existsByRoleCode(String roleCode); boolean existsByRoleCode(String roleCode);
@@ -4,6 +4,7 @@ import com.finance.system.entity.SysApiAccessLog;
import com.finance.system.service.ApiAccessLogService; import com.finance.system.service.ApiAccessLogService;
import com.finance.system.util.AuditUtil; import com.finance.system.util.AuditUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
@@ -25,27 +26,24 @@ import java.util.UUID;
* Authorization headers and known secret query keys are never stored. * Authorization headers and known secret query keys are never stored.
*/ */
@Component @Component
@Slf4j
@RequiredArgsConstructor @RequiredArgsConstructor
public class ApiAccessLogFilter extends OncePerRequestFilter { public class ApiAccessLogFilter extends OncePerRequestFilter {
private static final Set<String> REDACT_QUERY_KEYS = new HashSet<>(Arrays.asList( private static final Set<String> REDACT_QUERY_KEYS = new HashSet<>(Arrays.asList(
"password", "passwd", "secret", "token", "access_token", "refresh_token", "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; private final ApiAccessLogService apiAccessLogService;
@Override @Override
protected boolean shouldNotFilter(HttpServletRequest request) { protected boolean shouldNotFilter(HttpServletRequest request) {
String path = path(request); String path = path(request);
if (!path.startsWith("/api/")) { // Capture every API method (including read and preflight requests), as
return true; // well as operational actuator endpoints. Static resources are excluded.
} return !(path.startsWith("/api/") || path.startsWith("/actuator/"));
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;
} }
@Override @Override
@@ -57,13 +55,31 @@ public class ApiAccessLogFilter extends OncePerRequestFilter {
try { try {
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
} finally { } finally {
SysApiAccessLog entry = null;
try { 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) {
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) { } catch (Exception ignored) {
// Logging must never break the original request/response path. // Logging must never break the original request/response path.
} }
} }
} }
}
private SysApiAccessLog buildEntry(HttpServletRequest request, HttpServletResponse response, private SysApiAccessLog buildEntry(HttpServletRequest request, HttpServletResponse response,
String requestId, long started) { String requestId, long started) {
@@ -84,15 +100,16 @@ public class ApiAccessLogFilter extends OncePerRequestFilter {
.statusCode(status) .statusCode(status)
.durationMs((int) Math.min(Integer.MAX_VALUE, Math.max(0, System.currentTimeMillis() - started))) .durationMs((int) Math.min(Integer.MAX_VALUE, Math.max(0, System.currentTimeMillis() - started)))
.clientIp(truncate(clientIp(request), 64)) .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) .errorMessage(status >= 400 ? truncate("HTTP " + status, 1000) : null)
.build(); .build();
} }
private String resolveRequestId(HttpServletRequest request) { private String resolveRequestId(HttpServletRequest request) {
String incoming = request.getHeader("X-Request-Id"); String incoming = request.getHeader("X-Request-Id");
if (StringUtils.hasText(incoming)) { if (StringUtils.hasText(incoming) && incoming.length() <= 64
return truncate(incoming.trim(), 64); && incoming.matches("[A-Za-z0-9._-]+")) {
return incoming;
} }
return UUID.randomUUID().toString().replace("-", ""); return UUID.randomUUID().toString().replace("-", "");
} }
@@ -107,16 +124,9 @@ public class ApiAccessLogFilter extends OncePerRequestFilter {
} }
private String clientIp(HttpServletRequest request) { private String clientIp(HttpServletRequest request) {
String forwarded = request.getHeader("X-Forwarded-For"); // Forwarded headers are client-controlled unless a trusted proxy chain
if (StringUtils.hasText(forwarded)) { // has been configured. Log the transport peer instead of spoofable data.
int comma = forwarded.indexOf(','); return safe(request.getRemoteAddr(), 64);
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();
} }
private String sanitizeQuery(String query) { private String sanitizeQuery(String query) {
@@ -135,22 +145,59 @@ public class ApiAccessLogFilter extends OncePerRequestFilter {
String key = eq >= 0 ? part.substring(0, eq) : part; String key = eq >= 0 ? part.substring(0, eq) : part;
String value = eq >= 0 ? part.substring(eq + 1) : ""; String value = eq >= 0 ? part.substring(eq + 1) : "";
if (REDACT_QUERY_KEYS.contains(key.toLowerCase(Locale.ROOT))) { if (REDACT_QUERY_KEYS.contains(key.toLowerCase(Locale.ROOT))) {
sanitized.append(key).append('=').append("***"); sanitized.append(safe(key, 100)).append('=').append("[REDACTED]");
} else { } else {
sanitized.append(key); sanitized.append(safe(key, 100));
if (eq >= 0) { 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) { private String truncate(String value, int max) {
if (!StringUtils.hasText(value)) { return safe(value, max);
return value; }
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);
} }
} }
@@ -26,7 +26,7 @@ public class RoleService {
public static final String SUPER_ADMIN = "SUPER_ADMIN"; public static final String SUPER_ADMIN = "SUPER_ADMIN";
public static final String DEFAULT_EMPLOYEE_GROUP = "DEFAULT_EMPLOYEE"; public static final String DEFAULT_EMPLOYEE_GROUP = "DEFAULT_EMPLOYEE";
private static final Set<String> ACCESS_LEVELS = new HashSet<>(Arrays.asList("HIDDEN", "READ", "EDIT")); private static final Set<String> ACCESS_LEVELS = new HashSet<>(Arrays.asList("HIDDEN", "READ", "EDIT"));
private static final Set<String> PERMISSION_TYPES = new HashSet<>(Arrays.asList("MENU", "BUTTON", "FIELD")); private static final Set<String> PERMISSION_TYPES = new HashSet<>(Arrays.asList("MENU", "ACTION", "BUTTON", "FIELD"));
private static final Set<String> SAFE_EMPLOYEE_PERMISSIONS = new LinkedHashSet<>(Arrays.asList( private static final Set<String> SAFE_EMPLOYEE_PERMISSIONS = new LinkedHashSet<>(Arrays.asList(
"dashboard", "applications", "application:create", "application:view-own", "dashboard", "applications", "application:create", "application:view-own",
"application:amount", "application:payeeName", "application:bankAccount", "application:amount", "application:payeeName", "application:bankAccount",
@@ -212,7 +212,8 @@ public class RoleService {
@Transactional @Transactional
public void replaceRolePermissions(Long roleId, Map<String, Object> body, Long actorId) { public void replaceRolePermissions(Long roleId, Map<String, Object> body, Long actorId) {
SysRole targetRole = requireRole(roleId); SysRole targetRole = roles.findByIdForUpdate(roleId)
.orElseThrow(() -> new ResourceNotFoundException("角色不存在"));
boolean superAdmin = isSuperAdmin(actorId); boolean superAdmin = isSuperAdmin(actorId);
if (!superAdmin && !hasEditPermission(actorId, "system.role.permission.configure")) { if (!superAdmin && !hasEditPermission(actorId, "system.role.permission.configure")) {
throw new BusinessException("无权管理角色权限", 403); throw new BusinessException("无权管理角色权限", 403);
@@ -221,8 +222,10 @@ public class RoleService {
throw new BusinessException("普通管理员不能修改内置角色权限", 403); throw new BusinessException("普通管理员不能修改内置角色权限", 403);
} }
if (body == null) throw new BusinessException("权限请求不能为空", 400); if (body == null) throw new BusinessException("权限请求不能为空", 400);
validatePermissionPayload(body);
Map<String, SysPermission> catalog = permissions.findAll().stream() Map<String, SysPermission> catalog = permissions.findAll().stream()
.collect(Collectors.toMap(SysPermission::getPermissionCode, p -> p)); .collect(Collectors.toMap(SysPermission::getPermissionCode, p -> p));
validatePermissionSnapshot(roleId, body, catalog);
Map<String, String> requested = requestedAccess(body, catalog); Map<String, String> requested = requestedAccess(body, catalog);
addReadableAncestors(requested, catalog); addReadableAncestors(requested, catalog);
for (Map.Entry<String, String> entry : requested.entrySet()) { for (Map.Entry<String, String> entry : requested.entrySet()) {
@@ -1200,6 +1203,53 @@ public class RoleService {
return result; return result;
} }
private void validatePermissionPayload(Map<String, Object> 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<String, Object> body,
Map<String, SysPermission> catalog) {
Map<String, String> expected = stringMap(body.get("expectedPermissionAccess"));
if (expected.isEmpty()) {
throw new BusinessException("权限编辑基线为空,请重新加载角色权限后重试", 400);
}
for (Map.Entry<String, String> entry : expected.entrySet()) {
if (!catalog.containsKey(entry.getKey()) || !ACCESS_LEVELS.contains(entry.getValue())) {
throw new BusinessException("权限编辑基线格式无效,请重新加载后重试", 400);
}
}
Map<String, Object> currentPayload = rolePermissions(roleId);
Map<String, String> current = stringMap(currentPayload.get("permissionAccess"));
if (!expected.equals(current)) {
throw new BusinessException("角色权限已被其他管理员修改,请重新加载后再保存", 409);
}
}
private void addReadableAncestors(Map<String, String> requested, Map<String, SysPermission> catalog) { private void addReadableAncestors(Map<String, String> requested, Map<String, SysPermission> catalog) {
for (String code : new ArrayList<>(requested.keySet())) { for (String code : new ArrayList<>(requested.keySet())) {
if ("HIDDEN".equals(requested.get(code))) continue; if ("HIDDEN".equals(requested.get(code))) continue;
@@ -542,11 +542,13 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
return !oldAmounts.equals(newAmounts); return !oldAmounts.equals(newAmounts);
} }
private static final BigDecimal MAX_MONEY_AMOUNT = new BigDecimal("99999999.99");
private void validateRequest(CreateApplicationRequest request, Long userId) { private void validateRequest(CreateApplicationRequest request, Long userId) {
if (request == null || request.getTotalAmount() == null if (request == null || request.getTotalAmount() == null) {
|| request.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0) { throw new BusinessException("请填写申请金额", 400);
throw new BusinessException("总金额必须大于0", 400);
} }
assertMoneyAmount(request.getTotalAmount(), "申请金额");
if (userId == null || !sysUserRepository.findById(userId).map(u -> u.getDepartmentId() != null).orElse(false)) { if (userId == null || !sysUserRepository.findById(userId).map(u -> u.getDepartmentId() != null).orElse(false)) {
throw new BusinessException("申请人未配置部门"); throw new BusinessException("申请人未配置部门");
} }
@@ -565,15 +567,20 @@ public class ReimApplicationServiceImpl implements ReimApplicationService {
throw new BusinessException("费用类型不存在或已停用"); throw new BusinessException("费用类型不存在或已停用");
} }
BigDecimal sum = BigDecimal.ZERO; BigDecimal sum = BigDecimal.ZERO;
int index = 0;
for (ExpenseItemDto item : request.getItems()) { for (ExpenseItemDto item : request.getItems()) {
if (item == null || item.getAmount() == null || item.getAmount().compareTo(BigDecimal.ZERO) <= 0 index++;
|| item.getCategory() == null || item.getCategory().trim().isEmpty()) { if (item == null || item.getCategory() == null || item.getCategory().trim().isEmpty()) {
throw new BusinessException("费用明细金额必须大于0"); throw new BusinessException("第 " + index + " 条费用明细类别不能为空", 400);
} }
if (item.getAmount() == null) {
throw new BusinessException("第 " + index + " 条费用明细:请填写金额", 400);
}
assertMoneyAmount(item.getAmount(), "第 " + index + " 条费用明细金额");
sum = sum.add(item.getAmount()); sum = sum.add(item.getAmount());
} }
if (sum.compareTo(request.getTotalAmount()) != 0) { if (sum.compareTo(request.getTotalAmount()) != 0) {
throw new BusinessException("费用明细合计必须等于总金额"); throw new BusinessException("明细合计须与申请金额一致,请核对各行金额", 400);
} }
if (request.getPayeeBankId() == null if (request.getPayeeBankId() == null
|| !sysBankAccountRepository.findById(request.getPayeeBankId()).map(b -> userId.equals(b.getUserId())).orElse(false)) { || !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) { private void validatePersistedApplication(ReimApplication app) {
List<ReimExpenseItem> items = reimExpenseItemRepository.findByApplicationId(app.getId()); List<ReimExpenseItem> items = reimExpenseItemRepository.findByApplicationId(app.getId());
if (app.getTotalAmount() == null || app.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0 || items.isEmpty()) { if (app.getTotalAmount() == null || app.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0 || items.isEmpty()) {
+1 -1
View File
@@ -30,7 +30,7 @@ database:
# Must match Connector/J's DB_URL serverTimezone because MySQL DATETIME has no zone. # Must match Connector/J's DB_URL serverTimezone because MySQL DATETIME has no zone.
time-zone: "${DB_TIME_ZONE:Asia/Shanghai}" time-zone: "${DB_TIME_ZONE:Asia/Shanghai}"
jwt: jwt:
secret: "${JWT_SECRET:Uqen22fWWeubQ6f2dFIWteMDIhd4PU4u}" secret: "${JWT_SECRET:local-only-insecure-secret-change-before-deploy}"
expiration: ${JWT_EXPIRATION:86400000} expiration: ${JWT_EXPIRATION:86400000}
auth: auth:
time-zone: "${AUTH_TIME_ZONE:Asia/Shanghai}" time-zone: "${AUTH_TIME_ZONE:Asia/Shanghai}"
@@ -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<SysApiAccessLog> 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<SysApiAccessLog> 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);
}
}
}
@@ -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.<String, Object>singletonMap("permissionAccess", Collections.emptyMap()), 1L))
.isInstanceOf(BusinessException.class);
verify(rolePermissions, never()).deleteByIdRoleId(7L);
}
@Test
void rejectsEmptyLegacyPayloadWithoutDeleting() {
Map<String, Object> 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<String, Object> 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<String, Object> allHidden = new LinkedHashMap<>();
allHidden.put("report.export", "HIDDEN");
allHidden.put("dashboard", "HIDDEN");
Map<String, Object> 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<String, Object> 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<String, Object> 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;
}
}
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.