系统安全加密优化

This commit is contained in:
Weiming committed 2026-12-01 17:57:38 +08:00
1 parent 741bf2ee73
commit c3cdb9e2d6
267 files changed
+15947 -2548

No files matched your search

+23 -9
View File
@@ -1,20 +1,34 @@
# Maven/Java generated output.
target/
.idea/
*.iml
out/
*.class
*.log
*.hprof
# Runtime-only data.
logs/
uploads/
tmp/
*.log
*.pid
# Local configuration; commit application.yml and safe example templates.
.env
.env.*
!.env.example
application-local.yml
application-local.yaml
application-local.properties
logs/
uploads/
tmp/
# IDE, temporary and OS files.
.idea/
.vscode/
*.iml
*.tmp
*.temp
*.swp
*.swo
*.bak
*~
.DS_Store
Thumbs.db
Desktop.ini
+43 -14
View File
@@ -5,28 +5,57 @@ Before saving any `secret=true` value in `sys_integration_config`, configure
longer secret) in the backend runtime environment. Do not commit the key or
place a real value in `src/main/resources/application.yml`.
## Payee bank-account protection
Before creating or changing a payee bank account, provide these runtime secrets:
- `APP_BANK_ACCOUNT_ENCRYPTION_KEYS`: comma-separated `version=Base64Key`
entries; every decoded AES key must be exactly 32 bytes. Keep old versions
present while old ciphertext still exists.
- `APP_BANK_ACCOUNT_ACTIVE_KEY_VERSION`: the version used for new ciphertext.
- `APP_BANK_ACCOUNT_FINGERPRINT_KEY`: a separate Base64-encoded 32-byte HMAC key.
Never reuse the integration key, JWT secret, database password, or an encryption
key as the fingerprint key. Keep all real values outside the repository.
For an existing database, apply
`V20261201_02__protect_payee_bank_accounts.sql` first. After a verified backup,
set `APP_BANK_ACCOUNT_LEGACY_BACKFILL_ENABLED=true` for one observed maintenance
run, then return it to `false`. The backfill is deliberately non-destructive: it
adds ciphertext, mask, fingerprint, and key version but does not clear the legacy
plaintext column. Final plaintext clearing requires a separate reviewed change,
explicit data-cleanup authorization, restore evidence, and post-change checks.
For rollout and operations of asynchronous Feishu directory synchronization,
see [`../docs/feishu-directory-sync.md`](../docs/feishu-directory-sync.md).
see [`../financial_system_docs/feishu-directory-sync.md`](../financial_system_docs/feishu-directory-sync.md).
## Database contract
[`../database/init_schema.sql`](../database/init_schema.sql) is the only schema
and bootstrap source. Run it with a MySQL 5.7 client only when
[`../financial_system_database/init_schema.sql`](../financial_system_database/init_schema.sql) is the clean-install
schema/bootstrap snapshot. Run it with a MySQL 8.4 LTS client only when
`finance_system` does not yet exist. It intentionally fails against an existing
or partial installation. The application keeps Hibernate `ddl-auto: validate`
and never changes the application-owned schema during startup. The optional,
explicitly authorized Kingdee table-preparation feature can create or alter only
its configured target tables; use a narrowly scoped DDL account for that action
or have a DBA pre-create those tables and keep the runtime account DML-only.
Existing installations require a separately reviewed DBA release script and
procedure for every in-place upgrade; never run the clean-install script against
them.
Existing installations use the closed manifest and chain runner documented in
[`../financial_system_docs/mysql-migration-runner.md`](../financial_system_docs/mysql-migration-runner.md), with
DBA review and staging rehearsal; never run the clean-install snapshot against them.
Deployment JDBC `serverTimezone` and `DB_TIME_ZONE` are both `UTC`. MySQL 8.4 LTS
is the runtime target; repository tests are not evidence of execution on a real
production-equivalent instance, so the exact manifest requires production-like rehearsal.
The sole script intentionally seeds exactly one environment-specific Feishu
identity and binds it to the built-in `SUPER_ADMIN_GROUP`. Treat the script as an
access-controlled deployment asset, verify that the identity is the intended
operator, and edit it before installing another tenant. The seed has no local
password, mobile, email, or avatar URL; it receives `SUPER_ADMIN` only through
group membership, while `DEFAULT_EMPLOYEE` has no materialized member. Default
passwords, local-profile bootstrap, and first-user auto-promotion remain
prohibited.
The clean-install snapshot creates built-in roles, groups, and group-role links,
but no person, default administrator, or personal group membership. Bootstrap the
first `SUPER_ADMIN` exactly once: the candidate first completes normal Feishu
login, two independent reviewers verify the immutable user ID and tenant against
the corporate directory, and a DBA runs an external, hashed, parameterized
transaction that adds only that `ACTIVE` user to `SUPER_ADMIN_GROUP`, checks the
affected row and unique membership, and records the evidence in the change ticket.
The candidate verifies `/api/auth/me`, the second reviewer closes the one-time
channel, and all later grants use normal IAM administration. Never store the
identity, script parameters, or secrets in the repository and never auto-promote
the first user. `LocalDataInitializer` is loaded only by the `local` profile, and
`finance.local-bootstrap.super-admin.enabled` defaults to `false`; neither the
profile nor the switch is permitted in production.
+20 -2
View File
@@ -12,9 +12,9 @@
</parent>
<groupId>com.finance.system</groupId>
<artifactId>finance-system</artifactId>
<artifactId>financial_system_backend</artifactId>
<version>1.0.0</version>
<name>finance-system</name>
<name>financial_system_backend</name>
<description>统一费用支付平台 - 员工报销管理系统</description>
<properties>
@@ -22,7 +22,9 @@
<jjwt.version>0.11.5</jjwt.version>
<mapstruct.version>1.5.5.Final</mapstruct.version>
<springdoc.version>1.6.15</springdoc.version>
<aliyun-oss.version>3.18.4</aliyun-oss.version>
<lombok.version>1.18.30</lombok.version>
<logstash.logback.encoder.version>6.6</logstash.logback.encoder.version>
</properties>
<dependencies>
@@ -47,6 +49,15 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>${logstash.logback.encoder.version}</version>
</dependency>
<!-- Database -->
<dependency>
@@ -112,6 +123,13 @@
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<!-- Persistent attachment storage -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun-oss.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
+1 -1
View File
@@ -1,7 +1,7 @@
@echo off
set JAVA_HOME=C:\PROGRA~1\Java\OPENJD~1
set MAVEN_HOME=C:\Users\it\.m2
set PROJECT_DIR=D:\code\Java\financial_system\finance-system\backend
set PROJECT_DIR=D:\code\Java\financial_system\financial_system_backend
cd /d "%PROJECT_DIR%"
@@ -27,7 +27,7 @@ public class FinanceSystemApplication {
@EventListener(ApplicationReadyEvent.class)
public void logApplicationReady() {
String application = environment.getProperty("spring.application.name", "finance-system");
String application = environment.getProperty("spring.application.name", "financial_system_backend");
String port = environment.getProperty("local.server.port",
environment.getProperty("server.port", "8080"));
String[] profiles = environment.getActiveProfiles();
@@ -53,10 +53,10 @@ public class FeishuApprovalFileClient {
return code.asText();
} catch (BusinessException e) { throw e;
} catch (RestClientResponseException e) {
log.warn("Feishu attachment upload rejected: httpStatus={}", e.getRawStatusCode());
log.warn("飞书附件上传被拒绝: httpStatus={}", e.getRawStatusCode());
throw new BusinessException("飞书附件上传失败,结果可能未知,请勿自动重试", 502);
} catch (Exception e) {
log.warn("Feishu attachment upload outcome unknown", e);
log.warn("飞书附件上传结果未知", e);
throw new BusinessException("飞书附件上传结果未知,请勿自动重试", 502);
}
}
@@ -1,5 +1,7 @@
package com.finance.system.adapter.feishu;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.finance.system.entity.SysUser;
import com.finance.system.entity.SysOauthState;
import com.finance.system.exception.BusinessException;
@@ -14,13 +16,21 @@ import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Base64;
import java.util.Locale;
import java.util.Objects;
@Slf4j
@Service
@@ -31,6 +41,7 @@ public class FeishuAuthService {
private final SysUserRepository sysUserRepository;
private final SysOauthStateRepository sysOauthStateRepository;
private final RestTemplate restTemplate;
private final FeishuUserProvisioningService userProvisioning;
private IntegrationConfigReader integrationConfigReader;
@Autowired
private FeishuTenantTokenService tenantTokens;
@@ -44,6 +55,12 @@ public class FeishuAuthService {
private static final String FEISHU_OPEN_API = "https://open.feishu.cn/open-apis";
private static final String FEISHU_AUTH_URL = "https://open.feishu.cn/open-apis/authen/v1/authorize";
private static final int FEISHU_RATE_LIMIT_CODE = 99991400;
private static final int FEISHU_AUTH_LOGIN_INVALID_CODE = 99991501;
private static final int FEISHU_USER_ACCESS_TOKEN_INVALID_CODE = 99991668;
private static final int FEISHU_ACCESS_TOKEN_BAD_FORMAT_CODE = 99991671;
private static final BigInteger MAX_PROVIDER_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L);
private static final ObjectMapper OAUTH_ERROR_MAPPER = new ObjectMapper();
private static final long OAUTH_STATE_TTL_MILLIS = 5 * 60 * 1000L;
private final SecureRandom secureRandom = new SecureRandom();
@@ -52,6 +69,22 @@ public class FeishuAuthService {
*/
@Transactional
public AuthUrl buildAuthUrlWithState() {
return buildAuthUrlWithState(redirectUri());
}
/**
* Builds an OAuth URL for a trusted frontend origin. Local development
* commonly configures the callback with localhost; that host is unusable
* when another workstation starts the login. In that case only, replace
* the loopback host with the already allowlisted frontend host while
* retaining the configured callback scheme, port and path.
*/
@Transactional
public AuthUrl buildAuthUrlForFrontendOrigin(String trustedFrontendOrigin) {
return buildAuthUrlWithState(resolveRedirectUri(trustedFrontendOrigin));
}
private AuthUrl buildAuthUrlWithState(String oauthRedirectUri) {
requireConfigured();
long now = System.currentTimeMillis();
// Cleanup is deliberately limited to expired rows. There is no fixed
@@ -67,12 +100,45 @@ public class FeishuAuthService {
String authUrl = FEISHU_AUTH_URL
+ "?app_id=" + encode(appId())
+ "&redirect_uri=" + encode(redirectUri())
+ "&redirect_uri=" + encode(oauthRedirectUri)
+ "&response_type=code"
+ "&state=" + state;
return new AuthUrl(authUrl, state);
}
private String resolveRedirectUri(String trustedFrontendOrigin) {
String configuredRedirectUri = redirectUri();
try {
URI configuredUri = URI.create(configuredRedirectUri);
URI frontendUri = URI.create(trustedFrontendOrigin);
if (!isLoopbackHost(configuredUri.getHost()) || isLoopbackHost(frontendUri.getHost())) {
return configuredRedirectUri;
}
if (frontendUri.getHost() == null || configuredUri.getScheme() == null
|| configuredUri.getRawPath() == null || configuredUri.getRawPath().isEmpty()) {
throw new IllegalArgumentException("Incomplete OAuth redirect URI");
}
return new URI(
configuredUri.getScheme(),
null,
frontendUri.getHost(),
configuredUri.getPort(),
configuredUri.getPath(),
configuredUri.getQuery(),
null).toASCIIString();
} catch (IllegalArgumentException | URISyntaxException invalid) {
throw new BusinessException("飞书回调地址配置无效", 500);
}
}
private boolean isLoopbackHost(String host) {
if (!StringUtils.hasText(host)) return false;
String normalized = host.toLowerCase(Locale.ROOT);
return "localhost".equals(normalized)
|| "::1".equals(normalized)
|| normalized.startsWith("127.");
}
/** Builds the URL while retaining the original service method contract. */
@Transactional
public String buildAuthUrl() {
@@ -95,9 +161,12 @@ public class FeishuAuthService {
|| !state.matches("[A-Za-z0-9_-]{43}")) {
throw new BusinessException("飞书登录状态缺失,请重新发起授权", 400);
}
if (consume && (!StringUtils.hasText(browserState)
|| !java.security.MessageDigest.isEqual(
state.getBytes(StandardCharsets.UTF_8), browserState.getBytes(StandardCharsets.UTF_8)))) {
if (StringUtils.hasText(browserState)
&& !java.security.MessageDigest.isEqual(
state.getBytes(StandardCharsets.UTF_8), browserState.getBytes(StandardCharsets.UTF_8))) {
throw new BusinessException("飞书登录状态与当前浏览器不匹配,请重新发起授权", 400);
}
if (consume && !StringUtils.hasText(browserState)) {
throw new BusinessException("飞书登录状态与当前浏览器不匹配,请重新发起授权", 400);
}
long now = System.currentTimeMillis();
@@ -112,10 +181,10 @@ public class FeishuAuthService {
private void requireConfigured() {
if (integrationConfigReader != null && !integrationConfigReader.isEnabled("FEISHU")) {
throw new BusinessException("飞书集成未启用,请先完成配置");
throw new BusinessException("飞书集成未启用,请先完成配置", 503);
}
if (!StringUtils.hasText(appId()) || !StringUtils.hasText(appSecret())) {
throw new BusinessException("飞书登录未配置,请在后端运行配置中设置 FEISHU_APP_ID 和 FEISHU_APP_SECRET");
throw new BusinessException("飞书登录未配置,请联系管理员", 503);
}
}
@@ -155,32 +224,108 @@ public class FeishuAuthService {
* 通过授权码获取access_token
*/
public FeishuTokenResponse getAccessToken(String code) {
if (!StringUtils.hasText(code)) throw invalidAuthorizationCode();
requireConfigured();
String url = FEISHU_OPEN_API + "/authen/v1/access_token";
String appAccessToken;
try {
appAccessToken = tenantTokens.getAppAccessToken();
} catch (FeishuTenantTokenService.DiagnosticFailure failure) {
log.warn("飞书应用令牌获取失败 event=feishu.oauth.app_token outcome=failed diagnostic={}",
failure.getDiagnosticCode());
throw new BusinessException("飞书登录服务暂时不可用,请稍后重试", failure.getStatusCode());
} catch (BusinessException failure) {
log.warn("飞书应用令牌获取失败 event=feishu.oauth.app_token outcome=failed diagnostic=BUSINESS_FAILURE");
throw new BusinessException("飞书登录服务暂时不可用,请稍后重试", failure.getStatusCode());
} catch (RuntimeException failure) {
log.warn("飞书应用令牌请求失败 event=feishu.oauth.app_token outcome=failed diagnostic=TOKEN_REQUEST_FAILED");
throw oauthUnavailable();
}
if (!StringUtils.hasText(appAccessToken)) {
log.warn("飞书应用令牌响应无效 event=feishu.oauth.app_token outcome=invalid_response diagnostic=TOKEN_RESPONSE_INVALID");
throw oauthUpstreamInvalid();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setBearerAuth(appAccessToken.trim());
Map<String, String> requestBody = new java.util.HashMap<>();
requestBody.put("grant_type", "authorization_code");
requestBody.put("code", code);
requestBody.put("app_id", appId());
requestBody.put("app_secret", appSecret());
HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
try {
ResponseEntity<FeishuTokenResponse> response = restTemplate.postForEntity(
url, request, FeishuTokenResponse.class);
ResponseEntity<FeishuTokenResponse> response = restTemplate.exchange(
url, HttpMethod.POST, request, FeishuTokenResponse.class);
FeishuTokenResponse tokenResponse = response.getBody();
if (tokenResponse == null) throw new BusinessException("飞书授权未返回令牌");
if (tokenResponse.getCode() != 0) throw new BusinessException("飞书授权失败,请稍后重试");
if (tokenResponse.getData() == null || !StringUtils.hasText(tokenResponse.getData().getAccessToken()))
throw new BusinessException("飞书授权未返回有效令牌");
if (tokenResponse == null) {
log.warn("飞书授权令牌交换响应为空 event=feishu.oauth.token_exchange outcome=invalid_response httpStatus={} diagnostic=EMPTY_BODY",
response.getStatusCodeValue());
throw oauthUpstreamInvalid();
}
Integer responseCode = tokenResponse.getCode();
if (responseCode == null) {
log.warn("飞书授权令牌交换响应缺少服务商状态码 event=feishu.oauth.token_exchange outcome=invalid_response httpStatus={} diagnostic=PROVIDER_CODE_MISSING",
response.getStatusCodeValue());
throw oauthUpstreamInvalid();
}
if (responseCode != 0) {
Integer providerCode = safeProviderCode(responseCode);
if (providerCode == null) {
log.warn("飞书授权令牌交换响应的服务商状态码无效 event=feishu.oauth.token_exchange outcome=invalid_response httpStatus={} diagnostic=INVALID_PROVIDER_CODE",
response.getStatusCodeValue());
throw oauthUpstreamInvalid();
}
if (isRateLimited(providerCode)) {
log.warn("飞书授权令牌交换服务不可用 event=feishu.oauth.token_exchange outcome=unavailable httpStatus={} providerCode={}",
response.getStatusCodeValue(), providerCode);
throw oauthUnavailable();
}
if (isAuthorizationCodeRejected(providerCode)) {
log.warn("飞书授权令牌交换被服务商拒绝 event=feishu.oauth.token_exchange outcome=provider_rejected httpStatus={} providerCode={}",
response.getStatusCodeValue(), providerCode);
throw invalidAuthorizationCode();
}
log.warn("飞书授权令牌交换上游服务失败 event=feishu.oauth.token_exchange outcome=upstream_failure httpStatus={} providerCode={}",
response.getStatusCodeValue(), providerCode);
throw oauthUpstreamInvalid();
}
if (tokenResponse.getData() == null
|| !StringUtils.hasText(tokenResponse.getData().getAccessToken())) {
log.warn("飞书授权令牌交换响应缺少令牌 event=feishu.oauth.token_exchange outcome=invalid_response httpStatus={} diagnostic=TOKEN_MISSING",
response.getStatusCodeValue());
throw oauthUpstreamInvalid();
}
log.info("飞书授权令牌交换成功 event=feishu.oauth.token_exchange outcome=success httpStatus={}",
response.getStatusCodeValue());
return tokenResponse;
} catch (Exception e) {
log.warn("Feishu OAuth token exchange failed");
throw new BusinessException("飞书授权失败,请稍后重试");
} catch (BusinessException failure) {
throw failure;
} catch (HttpStatusCodeException failure) {
int status = failure.getStatusCode().value();
Integer providerCode = safeProviderCode(failure.getResponseBodyAsString());
if (status == 429 || isRateLimited(providerCode)) {
logProviderHttpFailure("feishu.oauth.token_exchange", "unavailable", status, providerCode);
throw oauthUnavailable();
}
if (isAuthorizationCodeRejected(providerCode)) {
logProviderHttpFailure("feishu.oauth.token_exchange", "provider_rejected", status, providerCode);
throw invalidAuthorizationCode();
}
logProviderHttpFailure("feishu.oauth.token_exchange", "upstream_failure", status, providerCode);
throw oauthUpstreamInvalid();
} catch (ResourceAccessException failure) {
log.warn("飞书授权令牌交换网络请求失败 event=feishu.oauth.token_exchange outcome=unavailable diagnostic=NETWORK_FAILURE");
throw oauthUnavailable();
} catch (RestClientException failure) {
log.warn("飞书授权令牌交换客户端请求失败 event=feishu.oauth.token_exchange outcome=invalid_response diagnostic=HTTP_CLIENT_FAILURE");
throw oauthUpstreamInvalid();
} catch (RuntimeException failure) {
log.warn("飞书授权令牌交换发生未预期的错误 event=feishu.oauth.token_exchange outcome=failed diagnostic=UNEXPECTED_FAILURE");
throw oauthUnavailable();
}
}
@@ -188,6 +333,7 @@ public class FeishuAuthService {
* 获取用户信息
*/
public FeishuUserInfo getUserInfo(String accessToken) {
if (!StringUtils.hasText(accessToken)) throw invalidUserCredential();
String url = FEISHU_OPEN_API + "/authen/v1/user_info";
HttpHeaders headers = new HttpHeaders();
@@ -199,8 +345,43 @@ public class FeishuAuthService {
ResponseEntity<FeishuUserResponse> response = restTemplate.exchange(
url, HttpMethod.GET, request, FeishuUserResponse.class);
FeishuUserResponse userResponse = response.getBody();
if (userResponse == null || userResponse.getCode() != 0 || userResponse.getData() == null)
throw new BusinessException("获取用户信息失败");
if (userResponse == null) {
log.warn("飞书用户信息响应为空 event=feishu.oauth.user_info outcome=invalid_response httpStatus={} diagnostic=EMPTY_BODY",
response.getStatusCodeValue());
throw oauthUpstreamInvalid();
}
Integer responseCode = userResponse.getCode();
if (responseCode == null) {
log.warn("飞书用户信息响应缺少服务商状态码 event=feishu.oauth.user_info outcome=invalid_response httpStatus={} diagnostic=PROVIDER_CODE_MISSING",
response.getStatusCodeValue());
throw oauthUpstreamInvalid();
}
if (responseCode != 0) {
Integer providerCode = safeProviderCode(responseCode);
if (providerCode == null) {
log.warn("飞书用户信息响应的服务商状态码无效 event=feishu.oauth.user_info outcome=invalid_response httpStatus={} diagnostic=INVALID_PROVIDER_CODE",
response.getStatusCodeValue());
throw oauthUpstreamInvalid();
}
if (isRateLimited(providerCode)) {
log.warn("飞书用户信息服务不可用 event=feishu.oauth.user_info outcome=unavailable httpStatus={} providerCode={}",
response.getStatusCodeValue(), providerCode);
throw oauthUnavailable();
}
if (isUserCredentialRejected(providerCode)) {
log.warn("飞书用户信息请求被服务商拒绝 event=feishu.oauth.user_info outcome=provider_rejected httpStatus={} providerCode={}",
response.getStatusCodeValue(), providerCode);
throw invalidUserCredential();
}
log.warn("飞书用户信息上游服务失败 event=feishu.oauth.user_info outcome=upstream_failure httpStatus={} providerCode={}",
response.getStatusCodeValue(), providerCode);
throw oauthUpstreamInvalid();
}
if (userResponse.getData() == null) {
log.warn("飞书用户信息响应缺少用户数据 event=feishu.oauth.user_info outcome=invalid_response httpStatus={} diagnostic=USER_DATA_MISSING",
response.getStatusCodeValue());
throw oauthUpstreamInvalid();
}
FeishuUserInfo userInfo = new FeishuUserInfo();
userInfo.setOpenId(userResponse.getData().getOpenId());
@@ -209,11 +390,93 @@ public class FeishuAuthService {
userInfo.setAvatarUrl(userResponse.getData().getAvatarUrl());
userInfo.setEmail(userResponse.getData().getEmail());
userInfo.setMobile(userResponse.getData().getMobile());
log.info("飞书用户信息获取成功 event=feishu.oauth.user_info outcome=success httpStatus={}",
response.getStatusCodeValue());
return userInfo;
} catch (Exception e) {
log.warn("Feishu OAuth user-info request failed");
throw new BusinessException("获取用户信息失败");
} catch (BusinessException failure) {
throw failure;
} catch (HttpStatusCodeException failure) {
int status = failure.getStatusCode().value();
Integer providerCode = safeProviderCode(failure.getResponseBodyAsString());
if (status == 429 || isRateLimited(providerCode)) {
logProviderHttpFailure("feishu.oauth.user_info", "unavailable", status, providerCode);
throw oauthUnavailable();
}
if (isUserCredentialRejected(providerCode)) {
logProviderHttpFailure("feishu.oauth.user_info", "provider_rejected", status, providerCode);
throw invalidUserCredential();
}
logProviderHttpFailure("feishu.oauth.user_info", "upstream_failure", status, providerCode);
throw oauthUpstreamInvalid();
} catch (ResourceAccessException failure) {
log.warn("飞书用户信息网络请求失败 event=feishu.oauth.user_info outcome=unavailable diagnostic=NETWORK_FAILURE");
throw oauthUnavailable();
} catch (RestClientException failure) {
log.warn("飞书用户信息客户端请求失败 event=feishu.oauth.user_info outcome=invalid_response diagnostic=HTTP_CLIENT_FAILURE");
throw oauthUpstreamInvalid();
} catch (RuntimeException failure) {
log.warn("飞书用户信息获取发生未预期的错误 event=feishu.oauth.user_info outcome=failed diagnostic=UNEXPECTED_FAILURE");
throw oauthUnavailable();
}
}
private static void logProviderHttpFailure(String event, String outcome,
int httpStatus, Integer providerCode) {
if (providerCode == null) {
log.warn("飞书服务商 HTTP 请求失败 event={} outcome={} httpStatus={} diagnostic=PROVIDER_HTTP_FAILURE",
event, outcome, httpStatus);
} else {
log.warn("飞书服务商 HTTP 请求失败 event={} outcome={} httpStatus={} providerCode={}",
event, outcome, httpStatus, providerCode);
}
}
private static Integer safeProviderCode(int code) {
return code > 0 && BigInteger.valueOf(code).compareTo(MAX_PROVIDER_DIAGNOSTIC_CODE) <= 0
? code : null;
}
private static Integer safeProviderCode(String responseBody) {
if (responseBody == null || responseBody.length() > 16384) return null;
try {
JsonNode value = OAUTH_ERROR_MAPPER.readTree(responseBody).path("code");
if (!value.isIntegralNumber()) return null;
BigInteger code = value.bigIntegerValue();
if (code.signum() <= 0 || code.compareTo(MAX_PROVIDER_DIAGNOSTIC_CODE) > 0) return null;
return code.intValueExact();
} catch (Exception ignored) {
return null;
}
}
private static boolean isRateLimited(Integer providerCode) {
return providerCode != null && providerCode == FEISHU_RATE_LIMIT_CODE;
}
private static boolean isAuthorizationCodeRejected(Integer providerCode) {
return providerCode != null && providerCode == FEISHU_AUTH_LOGIN_INVALID_CODE;
}
private static boolean isUserCredentialRejected(Integer providerCode) {
return providerCode != null
&& (providerCode == FEISHU_USER_ACCESS_TOKEN_INVALID_CODE
|| providerCode == FEISHU_ACCESS_TOKEN_BAD_FORMAT_CODE);
}
private static BusinessException invalidAuthorizationCode() {
return new BusinessException("飞书授权码无效或已过期,请重新登录", 400);
}
private static BusinessException invalidUserCredential() {
return new BusinessException("飞书登录凭证无效或已过期,请重新登录", 400);
}
private static BusinessException oauthUpstreamInvalid() {
return new BusinessException("飞书登录服务响应异常,请稍后重试", 502);
}
private static BusinessException oauthUnavailable() {
return new BusinessException("飞书登录服务暂时不可用,请稍后重试", 503);
}
/**
@@ -245,59 +508,90 @@ public class FeishuAuthService {
// Check ownership before provisioning. user_id is only a duplicate-
// ownership guard; it is never used to discover or adopt an account.
SysUser otherOwner = userId == null ? null : sysUserRepository.findByFeishuUserId(userId);
if (otherOwner != null && (user == null || !java.util.Objects.equals(user.getId(), otherOwner.getId()))) {
throw new BusinessException("飞书账号绑定不一致,请联系管理员", 403);
}
requireCompatibleBinding(user, otherOwner, userId);
if (user == null) {
try {
user = provisionEmployee(feishuUserInfo);
user = userProvisioning.provisionEmployee(feishuUserInfo);
} catch (DataIntegrityViolationException race) {
// A concurrent first login may have won the unique open_id
// insert. Reuse that committed account instead of exposing
// a database 500 to the OAuth callback.
user = sysUserRepository.findByFeishuOpenId(openId);
if (user == null) throw new BusinessException("飞书账号绑定冲突,请联系管理员", 403);
// The REQUIRES_NEW provisioning transaction has already rolled
// back here. Recovery lookups therefore never run in the failed
// transaction and can observe a committed concurrent winner.
user = recoverProvisioningConflict(openId, userId, race);
}
}
// Reject dual ownership even when both identifiers on the selected record are populated.
if (otherOwner != null && !java.util.Objects.equals(user.getId(), otherOwner.getId()))
throw new BusinessException("飞书账号绑定不一致,请联系管理员", 403);
// Re-read user_id ownership after provisioning so a concurrent binding
// cannot pass the optimistic checks above.
otherOwner = userId == null ? null : sysUserRepository.findByFeishuUserId(userId);
requireCompatibleBinding(user, otherOwner, userId);
// The finalizer rechecks the exact open_id and current ACTIVE status
// under a row lock, then performs only the safe profile/binding update.
try {
return loginPersistence.completeOAuth(user.getId(), feishuUserInfo);
} catch (DataIntegrityViolationException conflict) {
return recoverFinalizationConflict(user, userId, conflict);
}
}
/** Provision an ordinary employee; OAuth can never create a privileged account. */
@Transactional
protected SysUser provisionEmployee(FeishuUserInfo feishuUserInfo) {
String openId = feishuUserInfo.getOpenId().trim();
SysUser existing = sysUserRepository.findByFeishuOpenId(openId);
if (existing != null) return existing;
private SysUser recoverProvisioningConflict(String openId, String userId,
DataIntegrityViolationException conflict) {
SysUser byOpenId = sysUserRepository.findByFeishuOpenId(openId);
SysUser byUserId = userId == null ? null : sysUserRepository.findByFeishuUserId(userId);
if (byUserId != null && (byOpenId == null || !Objects.equals(byOpenId.getId(), byUserId.getId()))) {
log.warn("飞书账号配置被拒绝:用户编号冲突 event=feishu.oauth.provision outcome=denied conflictType=USER_ID_UNIQUE");
throw bindingConflict();
}
if (byOpenId != null) {
requireCompatibleBinding(byOpenId, byUserId, userId);
log.info("飞书账号配置已恢复:已存在相同开放平台用户标识 event=feishu.oauth.provision outcome=recovered conflictType=OPEN_ID_UNIQUE");
return byOpenId;
}
String category = constraintCategory(conflict);
log.warn("飞书账号配置失败 event=feishu.oauth.provision outcome=failed conflictType={}", category);
throw new BusinessException("飞书账号创建冲突,请稍后重试", 409);
}
String userId = feishuUserInfo.getUserId() == null ? null : feishuUserInfo.getUserId().trim();
String number = uniqueEmployeeNo();
private SysUser recoverFinalizationConflict(SysUser selected, String userId,
DataIntegrityViolationException conflict) {
SysUser byUserId = userId == null ? null : sysUserRepository.findByFeishuUserId(userId);
if (byUserId != null && !Objects.equals(selected.getId(), byUserId.getId())) {
log.warn("飞书登录完成操作被拒绝:用户编号冲突 event=feishu.oauth.finalize outcome=denied conflictType=USER_ID_UNIQUE");
throw bindingConflict();
}
log.warn("飞书登录完成操作失败 event=feishu.oauth.finalize outcome=failed conflictType={}", constraintCategory(conflict));
throw new BusinessException("飞书账号绑定冲突,请稍后重试", 409);
}
SysUser user = SysUser.builder()
.feishuOpenId(openId)
.feishuUserId(StringUtils.hasText(userId) ? userId : null)
.employeeNo(number)
.realName(StringUtils.hasText(feishuUserInfo.getName()) ? feishuUserInfo.getName() : "Feishu User")
.avatarUrl(feishuUserInfo.getAvatarUrl())
.email(feishuUserInfo.getEmail())
.mobile(feishuUserInfo.getMobile())
.userType("EMPLOYEE")
.status("ACTIVE")
.directoryStatus("UNKNOWN")
.build();
SysUser saved = sysUserRepository.save(user);
if (saved != null) user = saved;
log.info("Feishu OAuth provisioned an employee account");
// Flush so the subsequent lookup sees the new record
sysUserRepository.flush();
return user;
private void requireCompatibleBinding(SysUser selected, SysUser userIdOwner, String requestedUserId) {
if (userIdOwner != null && (selected == null || !Objects.equals(selected.getId(), userIdOwner.getId()))) {
throw bindingConflict();
}
if (selected == null || requestedUserId == null) return;
String boundUserId = StringUtils.hasText(selected.getFeishuUserId())
? selected.getFeishuUserId().trim() : null;
if (boundUserId != null && !boundUserId.equals(requestedUserId)) throw bindingConflict();
}
static String constraintCategory(DataIntegrityViolationException conflict) {
Throwable current = conflict;
while (current != null) {
String message = current.getMessage();
String normalized = message == null ? "" : message.toLowerCase(Locale.ROOT);
if (normalized.contains("ux_user_feishu_open_id")
|| normalized.contains("feishu_oauth_open_id_unique")) return "OPEN_ID_UNIQUE";
if (normalized.contains("ux_user_feishu_user_id")
|| normalized.contains("feishu_oauth_user_id_unique")) return "USER_ID_UNIQUE";
if (normalized.contains("ux_user_employee_no")
|| normalized.contains("feishu_oauth_employee_no_unique")) return "EMPLOYEE_NO_UNIQUE";
current = current.getCause();
}
return "UNKNOWN_CONSTRAINT";
}
private BusinessException bindingConflict() {
return new BusinessException("飞书账号已绑定其他账户,请联系管理员", 403);
}
private void validateOAuthProfile(String openId, String userId, FeishuUserInfo info) {
@@ -315,14 +609,6 @@ public class FeishuAuthService {
}
}
private String uniqueEmployeeNo() {
for (int attempt = 0; attempt < 5; attempt++) {
String number = "FS-" + java.util.UUID.randomUUID();
if (sysUserRepository.findByEmployeeNo(number) == null) return number;
}
throw new BusinessException("员工编号生成失败,请稍后重试", 503);
}
private BusinessException invalidFeishuIdentity() {
return new BusinessException("飞书身份无效,请重新授权", 403);
}
@@ -9,12 +9,12 @@ import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "feishu")
public class FeishuConfig {
/** Master switch for Feishu OAuth / approval / directory token use. */
private boolean enabled = true;
private boolean enabled = false;
private String appId;
private String appSecret;
private String redirectUri;
/** Independent switch for Feishu directory sync (defaults on when credentials exist). */
private boolean syncOrgEnabled = true;
/** Independent switch for Feishu directory sync; must be explicitly enabled. */
private boolean syncOrgEnabled = false;
/**
* Legacy setting retained for configuration compatibility. OAuth no
* longer has a local bootstrap exception and always provisions an
@@ -51,7 +51,7 @@ public class FeishuDefinitionSyncService {
? "已验证审批定义并完成事件订阅;飞书审批状态变更将实时同步到本系统"
: "已验证审批定义;事件订阅已存在,飞书审批状态变更将实时同步到本系统");
} catch (Exception e) {
log.warn("飞书审批定义已同步,但事件订阅失败: {}", e.toString());
log.warn("飞书审批事件订阅失败 feishu_approval_subscription_failed code=SUBSCRIBE_FAILED");
result.setEventSubscribed(false);
result.setMessage("已验证并同步审批定义(发起申请可用);事件订阅暂未成功,请检查飞书事件权限后再次同步");
}
@@ -161,9 +161,9 @@ public class FeishuDirectoryAccessService {
String generation = publication.getRevision();
String context = publication.getSuccessfulContext();
// Directory-first: every valid row in the immutable published
// generation is a candidate, independent of employment policy
// and independent of whether a local account already exists.
// Directory-first, but business membership is explicitly limited
// to ACTIVE/eligible rows because the current directory also
// retains resigned employees for organizational visibility.
StringBuilder sql = new StringBuilder("SELECT gu.open_id,gu.user_id,gu.name,gu.employee_no,gu.eligible,")
.append("open_owner.id AS open_owner_id,open_owner.status AS local_status,")
.append("open_owner.feishu_user_id AS local_user_id,")
@@ -171,7 +171,7 @@ public class FeishuDirectoryAccessService {
.append("FROM feishu_directory_user gu ")
.append("LEFT JOIN sys_user open_owner ON open_owner.feishu_open_id=gu.open_id ")
.append("LEFT JOIN sys_user_group_member gm ON gm.user_id=open_owner.id ")
.append("WHERE gu.context=? ");
.append("WHERE gu.context=? AND gu.eligible=TRUE AND gu.employment_status='ACTIVE' ");
List<Object> args = new ArrayList<>();
args.add(context);
if (!blank(query)) {
@@ -4,6 +4,7 @@ import com.finance.system.dto.DirectoryIdentityDto;
import com.finance.system.exception.BusinessException;
import com.finance.system.service.FeishuDirectoryLock;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
@@ -25,6 +26,10 @@ import java.util.*;
public class FeishuDirectoryBindingProvisioner {
private final JdbcTemplate jdbc;
private final FeishuDirectoryTime time;
@Value("${observability.tenant-id:default}")
private String deploymentTenant = "default";
@Value("${observability.organization-id:1}")
private Long deploymentOrganizationId = 1L;
public FeishuDirectoryBindingProvisioner(JdbcTemplate jdbc, FeishuDirectoryTime time) {
this.jdbc = jdbc;
this.time = time;
@@ -58,13 +63,13 @@ public class FeishuDirectoryBindingProvisioner {
List<Map<String,Object>> directoryRows = jdbc.queryForList(
"SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url,eligible "
+ "FROM feishu_directory_user WHERE context=? AND snapshot_run_id=? "
+ "AND open_id=? FOR UPDATE",
+ "AND open_id=? AND eligible=TRUE AND employment_status='ACTIVE' FOR UPDATE",
context, generation, identity.getOpenId());
if (directoryRows.size() != 1) throw conflict();
Map<String,Object> directory = directoryRows.get(0);
List<Map<String,Object>> accountRows = jdbc.queryForList(
"SELECT id,feishu_open_id,feishu_user_id,status FROM sys_user "
"SELECT id,feishu_open_id,feishu_user_id,status,tenant_id,organization_id FROM sys_user "
+ "WHERE feishu_open_id=? FOR UPDATE", identity.getOpenId());
Map<String,Object> openOwner = null;
for (Map<String,Object> row : accountRows) {
@@ -81,7 +86,7 @@ public class FeishuDirectoryBindingProvisioner {
if(!blank(legacyRequest))legacyIds.add(legacyRequest);
for(String legacyId:legacyIds){
List<Map<String,Object>> owners=jdbc.queryForList(
"SELECT id,feishu_open_id,feishu_user_id,status FROM sys_user WHERE feishu_user_id=? FOR UPDATE",
"SELECT id,feishu_open_id,feishu_user_id,status,tenant_id,organization_id FROM sys_user WHERE feishu_user_id=? FOR UPDATE",
legacyId);
for(Map<String,Object> owner:owners){
if(openOwner==null||!Objects.equals(number(openOwner.get("id")),number(owner.get("id"))))throw conflict();
@@ -89,6 +94,10 @@ public class FeishuDirectoryBindingProvisioner {
}
if (openOwner != null) {
if (!deploymentTenant().equals(value(openOwner.get("tenant_id")))
|| !Objects.equals(deploymentOrganizationId(), number(openOwner.get("organization_id")))) {
throw conflict();
}
String counterpart = value(openOwner.get("feishu_user_id"));
if (!blank(counterpart)&&!blank(legacyRow)&&!legacyRow.equals(counterpart)) throw conflict();
if (!blank(counterpart)&&!blank(legacyRequest)&&!legacyRequest.equals(counterpart)) throw conflict();
@@ -117,8 +126,8 @@ public class FeishuDirectoryBindingProvisioner {
PreparedStatementCreator insert = connection -> {
PreparedStatement statement = connection.prepareStatement(
"INSERT INTO sys_user(feishu_open_id,feishu_user_id,employee_no,real_name,avatar_url,email,mobile,position,"
+ "user_type,password_hash,status,directory_status,directory_context,directory_verified_at,"
+ "directory_last_seen_run_id,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,'EMPLOYEE',NULL,'ACTIVE',?,?,?,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
+ "tenant_id,organization_id,user_type,password_hash,status,directory_status,directory_context,directory_verified_at,"
+ "directory_last_seen_run_id,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,'EMPLOYEE',NULL,'ACTIVE',?,?,?,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
Statement.RETURN_GENERATED_KEYS);
int index = 1;
statement.setString(index++, openId); statement.setString(index++, null);
@@ -127,6 +136,8 @@ public class FeishuDirectoryBindingProvisioner {
statement.setString(index++, boundedNullable(value(row.get("email")), 200));
statement.setString(index++, boundedNullable(value(row.get("mobile")), 20));
statement.setString(index++, boundedNullable(value(row.get("job_title")), 200));
statement.setString(index++, deploymentTenant());
statement.setLong(index++, deploymentOrganizationId());
statement.setString(index++, directoryStatus); statement.setString(index++, context);
statement.setTimestamp(index++, observed); statement.setString(index, generation);
return statement;
@@ -182,6 +193,14 @@ public class FeishuDirectoryBindingProvisioner {
if (result == null) result = boundedNullable(fallback, max);
return result;
}
private String deploymentTenant() {
if (blank(deploymentTenant)) throw conflict();
return deploymentTenant.trim();
}
private long deploymentOrganizationId() {
if (deploymentOrganizationId == null || deploymentOrganizationId <= 0) throw conflict();
return deploymentOrganizationId;
}
private static BusinessException conflict() {
return new BusinessException("目录身份或成员状态已变更,请刷新后重试", 409);
}
@@ -16,6 +16,6 @@ public class FeishuDirectoryBootstrap {
public void start() {
if (!settings.isBootstrapSyncOnStartup()) return;
try { directory.sync("STARTUP"); }
catch (Exception e) { log.warn("Startup directory sync unavailable; employee access remains fail-closed"); }
catch (Exception e) { log.warn("启动时通讯录同步不可用;为保障安全,继续拒绝员工访问"); }
}
}
@@ -29,10 +29,11 @@ public class FeishuDirectoryClient {
"department_id", "name", "parent_department_id", "order_weight", "department_count"));
static final List<String> EMPLOYEE_FIELDS = Collections.unmodifiableList(Arrays.asList(
"base_info.employee_id", "base_info.name", "base_info.mobile", "base_info.email",
"base_info.departments.department_id", "base_info.avatar",
"base_info.departments.department_id", "base_info.avatar", "base_info.is_resigned",
"work_info.job_number", "work_info.job_title.job_title_name"));
private static final BigInteger RATE_LIMIT_CODE = BigInteger.valueOf(99991400L);
private static final BigInteger MAX_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L);
private static final BigInteger DIRECTORY_FIELD_UNAVAILABLE_CODE = BigInteger.valueOf(1000L);
private static final ObjectMapper JSON = new ObjectMapper();
private enum Kind {
@@ -184,7 +185,35 @@ public class FeishuDirectoryClient {
private static void validateAbnormals(JsonNode data,Kind kind) {
JsonNode abnormal=data.get("abnormals");
if(abnormal==null) return;
if(!abnormal.isArray()||abnormal.size()!=0) fail(kind.diagnostic+"_ABNORMAL");
if(!abnormal.isArray()) fail(kind.diagnostic+"_ABNORMAL");
if(abnormal.size()==0)return;
// Directory-v1 can report a selectively requested unavailable field as
// field error 1000. Classify only the exact, homogeneous
// base_info.is_resigned case; mixed row/field errors must retain the
// generic fail-closed diagnostic so another provider defect is not hidden.
if(kind==Kind.EMPLOYEE&&onlyResignationPermissionErrors(abnormal))
fail("DIRECTORY_USER_RESIGNATION_FIELD_UNAVAILABLE");
fail(kind.diagnostic+"_ABNORMAL");
}
private static boolean onlyResignationPermissionErrors(JsonNode abnormals) {
boolean seen=false;
for(JsonNode abnormal:abnormals) {
if(abnormal==null||!abnormal.isObject())return false;
JsonNode rowError=abnormal.get("row_error");
if(rowError!=null&&!rowError.isNull()
&&(!rowError.isIntegralNumber()||!BigInteger.ZERO.equals(rowError.bigIntegerValue())))return false;
JsonNode fieldErrors=abnormal.get("field_errors");
if(fieldErrors==null||!fieldErrors.isObject()||fieldErrors.size()==0)return false;
Iterator<Map.Entry<String,JsonNode>> fields=fieldErrors.fields();
while(fields.hasNext()) {
Map.Entry<String,JsonNode> field=fields.next();
if(!"base_info.is_resigned".equals(field.getKey())
||!field.getValue().isIntegralNumber()
||!DIRECTORY_FIELD_UNAVAILABLE_CODE.equals(field.getValue().bigIntegerValue()))return false;
seen=true;
}
}
return seen;
}
private String mergeDepartment(Snapshot snapshot,JsonNode node) {
@@ -275,9 +304,17 @@ public class FeishuDirectoryClient {
fail("DIRECTORY_USER_ITEM_INVALID");
u.jobTitle=i18n(title.get("job_title_name"),200,"DIRECTORY_USER_ITEM_INVALID");
}
// Exhaustive traversal defines the current employee population. The status
// partition used by transport is deliberately neither projected nor parsed.
u.eligible=true;
JsonNode resigned=base.get("is_resigned");
// Directory-v1 may omit a selectively projected field because of field
// authorization, response-contract or app/tenant mismatch. Absence must
// remain fail-closed and must never be interpreted as an active employee.
// A present value must still follow the documented boolean contract; no
// string/number coercion is allowed.
if(resigned==null||resigned.isNull())fail("DIRECTORY_USER_RESIGNATION_FIELD_UNAVAILABLE");
if(!resigned.isBoolean())fail("DIRECTORY_USER_RESIGNATION_FIELD_INVALID");
// staff_status only partitions the exhaustive transport. Directory-v1's
// explicitly projected boolean is the sole employment eligibility source.
u.eligible=!resigned.booleanValue();
return u;
}
private static String avatar(JsonNode avatar) {
@@ -12,6 +12,8 @@ import java.util.*;
@Component
public class FeishuDirectoryCurrentStore {
static final int MAX_DIRECT_MEMBERSHIPS=500_000, MAX_EXPANDED_MEMBERSHIPS=1_000_000, WRITE_BATCH_SIZE=1_000;
static final String EMPLOYMENT_STATUS_ACTIVE="ACTIVE",EMPLOYMENT_STATUS_RESIGNED="RESIGNED";
static final String EMPLOYMENT_STATUS_SOURCE="FEISHU_DIRECTORY_V1_IS_RESIGNED";
private final JdbcTemplate jdbc; private final int maxDirect,maxExpanded,batchSize;
@Autowired public FeishuDirectoryCurrentStore(JdbcTemplate jdbc){this(jdbc,MAX_DIRECT_MEMBERSHIPS,MAX_EXPANDED_MEMBERSHIPS,WRITE_BATCH_SIZE);}
FeishuDirectoryCurrentStore(JdbcTemplate jdbc,int maxDirect,int maxExpanded,int batchSize){
@@ -20,12 +22,14 @@ public class FeishuDirectoryCurrentStore {
}
public void publish(String revision,String context,FeishuDirectoryClient.Snapshot snapshot,Timestamp now){
Map<String,List<String>> relations=relations(snapshot);Map<String,Integer> counts=memberCounts(snapshot,relations);
Map<String,List<String>> relations=relations(snapshot,false);Map<String,Integer> counts=memberCounts(snapshot,relations);
Map<String,String> oldDepartments=hashes("SELECT open_department_id,content_hash FROM feishu_directory_department");
Map<String,String> oldUsers=hashes("SELECT open_id,content_hash FROM feishu_directory_user");
Map<String,String> oldObservedUsers=hashes("SELECT open_id,content_hash FROM feishu_directory_employee_observation");
Set<String> wantedDepartments=new LinkedHashSet<>(),wantedUsers=new LinkedHashSet<>();
List<Object[]> departmentRows=new ArrayList<>(),userRows=new ArrayList<>();
List<Object[]> retainedDepartmentRows=new ArrayList<>(),retainedUserRows=new ArrayList<>();
Set<String> wantedObservedUsers=new LinkedHashSet<>();
List<Object[]> departmentRows=new ArrayList<>(),userRows=new ArrayList<>(),observedUserRows=new ArrayList<>();
List<Object[]> retainedDepartmentRows=new ArrayList<>(),retainedUserRows=new ArrayList<>(),retainedObservedUserRows=new ArrayList<>();
for(String id:snapshot.departments){
FeishuDirectoryClient.Department d=snapshot.departmentDetails.get(id);if(d==null)d=fallbackDepartment(id);
String open=bounded(d.openDepartmentId,64,id),name=bounded(d.name,200,""),parent=bounded(d.parentOpenDepartmentId,64,"0"),status=bounded(d.status,30,"ACTIVE");
@@ -34,24 +38,53 @@ public class FeishuDirectoryCurrentStore {
else retainedDepartmentRows.add(new Object[]{revision,context,now,open});
}
for(Map.Entry<String,FeishuDirectoryClient.UserSummary> e:snapshot.userSummaries.entrySet()){
FeishuDirectoryClient.UserSummary u=e.getValue();String open=bounded(u.openId,100,"");
FeishuDirectoryClient.UserSummary u=e.getValue();
if(u==null)throw FeishuTenantTokenService.diagnostic("DIRECTORY_IDENTITY_CONFLICT");
String observedOpen=bounded(u.openId,100,"");
if(!observedOpen.equals(e.getKey()))throw FeishuTenantTokenService.diagnostic("DIRECTORY_IDENTITY_CONFLICT");
String observedUserId=nullableBounded(u.userId,100),observedName=bounded(u.name,100,observedOpen);
String observedEmployee=nullableBounded(u.employeeNo,50),observedEmail=bounded(u.email,320,"");
String observedMobile=bounded(u.mobile,50,""),observedJob=bounded(u.jobTitle,200,""),observedAvatar=bounded(u.avatarUrl,500,"");
String employmentStatus=u.eligible?EMPLOYMENT_STATUS_ACTIVE:EMPLOYMENT_STATUS_RESIGNED;
String observedHash=hash(observedOpen,observedUserId,observedName,observedEmployee,observedEmail,observedMobile,
observedJob,observedAvatar,employmentStatus,String.valueOf(!u.eligible),EMPLOYMENT_STATUS_SOURCE,context);
wantedObservedUsers.add(observedOpen);
if(!observedHash.equals(oldObservedUsers.get(observedOpen)))observedUserRows.add(new Object[]{observedOpen,observedUserId,
observedName,observedEmployee,employmentStatus,!u.eligible,EMPLOYMENT_STATUS_SOURCE,now,revision,context,
observedEmail,observedMobile,observedJob,observedAvatar,observedHash,now});
else retainedObservedUserRows.add(new Object[]{revision,context,now,observedOpen});
String open=bounded(u.openId,100,"");
if(!open.equals(e.getKey()))throw FeishuTenantTokenService.diagnostic("DIRECTORY_IDENTITY_CONFLICT");
String name=bounded(u.name,100,open);String employee=nullableBounded(u.employeeNo,50);
String email=bounded(u.email,320,""),mobile=bounded(u.mobile,50,""),job=bounded(u.jobTitle,200,""),avatar=bounded(u.avatarUrl,500,"");boolean eligible=u.eligible;
String hash=hash(open,"",name,employee,email,mobile,job,avatar,String.valueOf(eligible),context);wantedUsers.add(open);
if(!hash.equals(oldUsers.get(open)))userRows.add(new Object[]{open,null,name,employee,eligible,revision,context,now,email,mobile,job,avatar,hash,now});
String email=bounded(u.email,320,""),mobile=bounded(u.mobile,50,""),job=bounded(u.jobTitle,200,""),avatar=bounded(u.avatarUrl,500,"");
String hash=hash(open,observedUserId,name,employee,email,mobile,job,avatar,
String.valueOf(u.eligible),employmentStatus,context);wantedUsers.add(open);
if(!hash.equals(oldUsers.get(open)))userRows.add(new Object[]{open,observedUserId,name,employee,u.eligible,
employmentStatus,revision,context,now,email,mobile,job,avatar,hash,now});
else retainedUserRows.add(new Object[]{revision,context,now,open});
}
Set<String> oldMemberships=new LinkedHashSet<>();for(Map<String,Object> row:jdbc.queryForList("SELECT open_id,open_department_id FROM feishu_directory_user_department"))oldMemberships.add(key(row.get("open_id"),row.get("open_department_id")));
Set<String>wantedMemberships=new LinkedHashSet<>();List<Object[]>membershipRows=new ArrayList<>(),retainedMembershipRows=new ArrayList<>();
for(Map.Entry<String,List<String>> e:relations.entrySet()){String open=e.getKey();for(String department:e.getValue()){String key=key(open,department);wantedMemberships.add(key);if(!oldMemberships.contains(key))membershipRows.add(new Object[]{open,department,revision,now});else retainedMembershipRows.add(new Object[]{revision,open,department});}}
batchDeleteMemberships(oldMemberships,wantedMemberships);batchDelete("feishu_directory_user","open_id",oldUsers.keySet(),wantedUsers);batchDelete("feishu_directory_department","open_department_id",oldDepartments.keySet(),wantedDepartments);
Set<String> oldObservedMemberships=new LinkedHashSet<>();for(Map<String,Object> row:jdbc.queryForList("SELECT open_id,open_department_id FROM feishu_directory_employee_observation_department"))oldObservedMemberships.add(key(row.get("open_id"),row.get("open_department_id")));
Set<String>wantedObservedMemberships=new LinkedHashSet<>();List<Object[]>observedMembershipRows=new ArrayList<>(),retainedObservedMembershipRows=new ArrayList<>();
for(Map.Entry<String,List<String>> e:relations.entrySet()){String open=e.getKey();for(String department:e.getValue()){String key=key(open,department);wantedObservedMemberships.add(key);if(!oldObservedMemberships.contains(key))observedMembershipRows.add(new Object[]{open,department,revision,now});else retainedObservedMembershipRows.add(new Object[]{revision,open,department});}}
batchDeleteMemberships("feishu_directory_user_department",oldMemberships,wantedMemberships);
batchDeleteMemberships("feishu_directory_employee_observation_department",oldObservedMemberships,wantedObservedMemberships);
batchDelete("feishu_directory_user","open_id",oldUsers.keySet(),wantedUsers);
batchDelete("feishu_directory_employee_observation","open_id",oldObservedUsers.keySet(),wantedObservedUsers);
batchDelete("feishu_directory_department","open_department_id",oldDepartments.keySet(),wantedDepartments);
batch("INSERT INTO feishu_directory_department(open_department_id,name,parent_open_department_id,sort_order,status,member_count,snapshot_run_id,context,observed_at,content_hash,changed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE name=VALUES(name),parent_open_department_id=VALUES(parent_open_department_id),sort_order=VALUES(sort_order),status=VALUES(status),member_count=VALUES(member_count),snapshot_run_id=VALUES(snapshot_run_id),context=VALUES(context),observed_at=VALUES(observed_at),content_hash=VALUES(content_hash),changed_at=VALUES(changed_at)",departmentRows);
batch("INSERT INTO feishu_directory_user(open_id,user_id,name,employee_no,eligible,snapshot_run_id,context,observed_at,email,mobile,job_title,avatar_url,content_hash,changed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE name=VALUES(name),employee_no=VALUES(employee_no),eligible=VALUES(eligible),snapshot_run_id=VALUES(snapshot_run_id),context=VALUES(context),observed_at=VALUES(observed_at),email=VALUES(email),mobile=VALUES(mobile),job_title=VALUES(job_title),avatar_url=VALUES(avatar_url),content_hash=VALUES(content_hash),changed_at=VALUES(changed_at)",userRows);
batch("INSERT INTO feishu_directory_user(open_id,user_id,name,employee_no,eligible,employment_status,snapshot_run_id,context,observed_at,email,mobile,job_title,avatar_url,content_hash,changed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE user_id=VALUES(user_id),name=VALUES(name),employee_no=VALUES(employee_no),eligible=VALUES(eligible),employment_status=VALUES(employment_status),snapshot_run_id=VALUES(snapshot_run_id),context=VALUES(context),observed_at=VALUES(observed_at),email=VALUES(email),mobile=VALUES(mobile),job_title=VALUES(job_title),avatar_url=VALUES(avatar_url),content_hash=VALUES(content_hash),changed_at=VALUES(changed_at)",userRows);
batch("INSERT INTO feishu_directory_user_department(open_id,open_department_id,revision_run_id,changed_at) VALUES (?,?,?,?)",membershipRows);
batch("INSERT INTO feishu_directory_employee_observation(open_id,user_id,name,employee_no,employment_status,is_resigned,status_source,status_observed_at,snapshot_run_id,context,email,mobile,job_title,avatar_url,content_hash,changed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE user_id=VALUES(user_id),name=VALUES(name),employee_no=VALUES(employee_no),employment_status=VALUES(employment_status),is_resigned=VALUES(is_resigned),status_source=VALUES(status_source),status_observed_at=VALUES(status_observed_at),snapshot_run_id=VALUES(snapshot_run_id),context=VALUES(context),email=VALUES(email),mobile=VALUES(mobile),job_title=VALUES(job_title),avatar_url=VALUES(avatar_url),content_hash=VALUES(content_hash),changed_at=VALUES(changed_at)",observedUserRows);
batch("INSERT INTO feishu_directory_employee_observation_department(open_id,open_department_id,revision_run_id,changed_at) VALUES (?,?,?,?)",observedMembershipRows);
batch("UPDATE feishu_directory_department SET snapshot_run_id=?,context=?,observed_at=? WHERE open_department_id=?",retainedDepartmentRows);
batch("UPDATE feishu_directory_user SET snapshot_run_id=?,context=?,observed_at=? WHERE open_id=?",retainedUserRows);
batch("UPDATE feishu_directory_user_department SET revision_run_id=? WHERE open_id=? AND open_department_id=?",retainedMembershipRows);
batch("UPDATE feishu_directory_employee_observation SET snapshot_run_id=?,context=?,status_observed_at=?,changed_at=changed_at WHERE open_id=?",retainedObservedUserRows);
batch("UPDATE feishu_directory_employee_observation_department SET revision_run_id=? WHERE open_id=? AND open_department_id=?",retainedObservedMembershipRows);
assertCurrentAndObservationConsistent();
}
public Map<String,Object> read(){
@@ -63,12 +96,24 @@ public class FeishuDirectoryCurrentStore {
/** Departments only — used by the organization shell so the page can paint before members load. */
public List<Map<String,Object>> readDepartments(){
List<Map<String,Object>> rows=jdbc.queryForList("SELECT open_department_id,name,parent_open_department_id,sort_order,member_count FROM feishu_directory_department ORDER BY sort_order,open_department_id");
Map<String,String> parents=new LinkedHashMap<>();
for(Map<String,Object> row:rows)parents.put(string(row.get("open_department_id")),string(row.get("parent_open_department_id")));
Map<String,Set<String>> observedMembers=new HashMap<>();
for(Map<String,Object> membership:jdbc.queryForList("SELECT open_id,open_department_id FROM feishu_directory_user_department ORDER BY open_id,open_department_id")){
String open=string(membership.get("open_id")),current=string(membership.get("open_department_id"));
Set<String> visited=new HashSet<>();
while(!current.isEmpty()&&parents.containsKey(current)&&visited.add(current)){
observedMembers.computeIfAbsent(current,key->new HashSet<>()).add(open);
String parent=parents.get(current);if(parent==null||parent.equals(current))break;current=parent;
}
}
List<Map<String,Object>> departments=new ArrayList<>();
for(Map<String,Object>r:jdbc.queryForList("SELECT open_department_id,name,parent_open_department_id,sort_order,member_count FROM feishu_directory_department ORDER BY sort_order,open_department_id")){
for(Map<String,Object>r:rows){
Map<String,Object>d=new LinkedHashMap<>();
d.put("id",string(r.get("open_department_id")));d.put("name",string(r.get("name")));
d.put("parentId",string(r.get("parent_open_department_id")));d.put("order",String.valueOf(longValue(r.get("sort_order"))));
d.put("memberCount",intValue(r.get("member_count")));departments.add(d);
d.put("memberCount",observedMembers.getOrDefault(string(r.get("open_department_id")),Collections.emptySet()).size());departments.add(d);
}
return departments;
}
@@ -109,8 +154,8 @@ public class FeishuDirectoryCurrentStore {
for(Map<String,Object>r:allForUsers)memberships.computeIfAbsent(string(r.get("open_id")),k->new ArrayList<>()).add(string(r.get("open_department_id")));
}
String userSql=scope==null
?"SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url FROM feishu_directory_user ORDER BY open_id"
:"SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url FROM feishu_directory_user WHERE open_id IN ("
?"SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url,eligible,employment_status,observed_at FROM feishu_directory_user ORDER BY open_id"
:"SELECT open_id,user_id,name,employee_no,email,mobile,job_title,avatar_url,eligible,employment_status,observed_at FROM feishu_directory_user WHERE open_id IN ("
+placeholders(openIds.size())+") ORDER BY open_id";
List<Map<String,Object>> userRows=scope==null?jdbc.queryForList(userSql):jdbc.queryForList(userSql,openIds.toArray());
List<Map<String,Object>>users=new ArrayList<>();
@@ -120,22 +165,43 @@ public class FeishuDirectoryCurrentStore {
u.put("name",string(r.get("name")));u.put("employeeNo",r.get("employee_no"));
u.put("email",string(r.get("email")));u.put("mobile",string(r.get("mobile")));
u.put("jobTitle",string(r.get("job_title")));u.put("avatarUrl",string(r.get("avatar_url")));
String employmentStatus=string(r.get("employment_status"));
u.put("employmentStatus",employmentStatus);u.put("resigned",EMPLOYMENT_STATUS_RESIGNED.equals(employmentStatus));
u.put("employmentStatusSource",EMPLOYMENT_STATUS_SOURCE);
Object statusObservedAt=r.get("observed_at");u.put("employmentStatusObservedAt",statusObservedAt==null?null:String.valueOf(statusObservedAt));
u.put("departmentIds",memberships.getOrDefault(open,Collections.emptyList()));users.add(u);
}
return users;
}
private void assertCurrentAndObservationConsistent(){
String sql="SELECT COUNT(*) FROM ("
+"SELECT u.open_id FROM feishu_directory_user u LEFT JOIN feishu_directory_employee_observation o ON o.open_id=u.open_id "
+"WHERE o.open_id IS NULL OR NOT(u.user_id<=>o.user_id) OR u.name<>o.name OR NOT(u.employee_no<=>o.employee_no) "
+"OR u.employment_status<>o.employment_status OR u.eligible<>(o.employment_status='ACTIVE') "
+"OR o.is_resigned<>(u.employment_status='RESIGNED') OR u.snapshot_run_id<>o.snapshot_run_id "
+"OR NOT(u.context<=>o.context) OR NOT(u.email<=>o.email) OR NOT(u.mobile<=>o.mobile) "
+"OR NOT(u.job_title<=>o.job_title) OR NOT(u.avatar_url<=>o.avatar_url) "
+"UNION ALL SELECT o.open_id FROM feishu_directory_employee_observation o LEFT JOIN feishu_directory_user u ON u.open_id=o.open_id WHERE u.open_id IS NULL "
+"UNION ALL SELECT ud.open_id FROM feishu_directory_user_department ud LEFT JOIN feishu_directory_employee_observation_department od "
+"ON od.open_id=ud.open_id AND od.open_department_id=ud.open_department_id WHERE od.open_id IS NULL "
+"UNION ALL SELECT od.open_id FROM feishu_directory_employee_observation_department od LEFT JOIN feishu_directory_user_department ud "
+"ON ud.open_id=od.open_id AND ud.open_department_id=od.open_department_id WHERE ud.open_id IS NULL) drift";
Integer drift=jdbc.queryForObject(sql,Integer.class);
if(drift==null||drift.intValue()!=0)throw FeishuTenantTokenService.diagnostic("DIRECTORY_STORAGE_INCONSISTENT");
}
private static String placeholders(int count){
if(count<1)throw new IllegalArgumentException("placeholder count");
StringBuilder b=new StringBuilder("?");
for(int i=1;i<count;i++)b.append(",?");
return b.toString();
}
private void batchDeleteMemberships(Set<String>old,Set<String>wanted){List<Object[]>rows=new ArrayList<>();for(String value:old)if(!wanted.contains(value)){int split=value.indexOf('\u0000');rows.add(new Object[]{value.substring(0,split),value.substring(split+1)});}batch("DELETE FROM feishu_directory_user_department WHERE open_id=? AND open_department_id=?",rows);}
private void batchDeleteMemberships(String table,Set<String>old,Set<String>wanted){List<Object[]>rows=new ArrayList<>();for(String value:old)if(!wanted.contains(value)){int split=value.indexOf('\u0000');rows.add(new Object[]{value.substring(0,split),value.substring(split+1)});}batch("DELETE FROM "+table+" WHERE open_id=? AND open_department_id=?",rows);}
private void batchDelete(String table,String column,Set<String>old,Set<String>wanted){List<Object[]>rows=new ArrayList<>();for(String value:old)if(!wanted.contains(value))rows.add(new Object[]{value});batch("DELETE FROM "+table+" WHERE "+column+"=?",rows);}
private void batch(String sql,List<Object[]>rows){for(int i=0;i<rows.size();i+=batchSize)jdbc.batchUpdate(sql,rows.subList(i,Math.min(rows.size(),i+batchSize)));}
private Map<String,String>hashes(String sql){Map<String,String>r=new LinkedHashMap<>();for(Map<String,Object>row:jdbc.queryForList(sql)){Iterator<Object>i=row.values().iterator();r.put(string(i.next()),string(i.next()));}return r;}
private Map<String,List<String>>relations(FeishuDirectoryClient.Snapshot s){Map<String,List<String>>r=new LinkedHashMap<>();int total=0;for(Map.Entry<String,FeishuDirectoryClient.UserSummary>e:s.userSummaries.entrySet()){LinkedHashSet<String>ids=new LinkedHashSet<>();for(String id:e.getValue().departmentIds)if(id!=null&&s.departments.contains(id.trim()))ids.add(id.trim());if(ids.isEmpty()&&s.departments.contains("0"))ids.add("0");if(ids.size()>maxDirect-total)throw FeishuTenantTokenService.diagnostic("DIRECTORY_LIMIT_EXCEEDED");total+=ids.size();r.put(e.getKey(),new ArrayList<>(ids));}return r;}
private Map<String,List<String>>relations(FeishuDirectoryClient.Snapshot s,boolean eligibleOnly){Map<String,List<String>>r=new LinkedHashMap<>();int total=0;for(Map.Entry<String,FeishuDirectoryClient.UserSummary>e:s.userSummaries.entrySet()){FeishuDirectoryClient.UserSummary user=e.getValue();if(user==null)throw FeishuTenantTokenService.diagnostic("DIRECTORY_IDENTITY_CONFLICT");if(eligibleOnly&&!user.eligible)continue;LinkedHashSet<String>ids=new LinkedHashSet<>();for(String id:user.departmentIds)if(id!=null&&s.departments.contains(id.trim()))ids.add(id.trim());if(ids.isEmpty()&&s.departments.contains("0"))ids.add("0");if(ids.size()>maxDirect-total)throw FeishuTenantTokenService.diagnostic("DIRECTORY_LIMIT_EXCEEDED");total+=ids.size();r.put(e.getKey(),new ArrayList<>(ids));}return r;}
private Map<String,Integer>memberCounts(FeishuDirectoryClient.Snapshot s,Map<String,List<String>>relations){Map<String,String>parents=new HashMap<>();for(String id:s.departments){FeishuDirectoryClient.Department d=s.departmentDetails.get(id);parents.put(id,d==null?"0":d.parentOpenDepartmentId);}Map<String,Set<String>>members=new HashMap<>();int expanded=0;for(Map.Entry<String,List<String>>e:relations.entrySet()){String employee=e.getKey();for(String id:e.getValue()){Set<String>visited=new HashSet<>();String current=id;while(current!=null&&parents.containsKey(current)&&visited.add(current)){Set<String>set=members.computeIfAbsent(current,k->new HashSet<>());if(set.add(employee)&&++expanded>maxExpanded)throw FeishuTenantTokenService.diagnostic("DIRECTORY_LIMIT_EXCEEDED");String parent=parents.get(current);if(parent==null||parent.equals(current))break;current=parent;}}}Map<String,Integer>r=new HashMap<>();for(Map.Entry<String,Set<String>>e:members.entrySet())r.put(e.getKey(),e.getValue().size());return r;}
private static String hash(String...values){StringBuilder b=new StringBuilder();for(String v:values){String x=v==null?"":v;b.append(x.length()).append(':').append(x).append(';');}return Sha256.hex(b.toString());}
private static String key(Object a,Object b){return string(a)+'\u0000'+string(b);}
@@ -30,6 +30,10 @@ public class FeishuDirectoryPublisher {
private final FeishuTenantTokenService tokens;
private final ObjectMapper mapper;
private final FeishuDirectoryTime time;
@org.springframework.beans.factory.annotation.Value("${observability.tenant-id:default}")
private String systemTenant = "default";
@org.springframework.beans.factory.annotation.Value("${observability.organization-id:1}")
private Long systemOrganization = 1L;
public FeishuDirectoryPublisher(JdbcTemplate jdbc, PlatformTransactionManager manager,
FeishuDirectoryRunStore runs, FeishuDirectoryCurrentStore directory,
@@ -55,12 +59,12 @@ public class FeishuDirectoryPublisher {
if (!captured.fingerprint.equals(tokens.capture().fingerprint)) throw FeishuTenantTokenService.contextChanged();
run.setState("SUCCEEDED"); run.setComplete(true); run.setApplied(true); run.setFinishedAt(now.toInstant().toString());
int completed=jdbc.update("UPDATE feishu_directory_sync_run SET state='SUCCEEDED',finished_at=?,complete=TRUE,applied=TRUE,"+
"departments=?,users_seen=?,eligible=?,excluded=?,created=?,updated=?,ineligible=?,out_of_scope=?,context=?,lease_until=NULL,error_code=NULL,error_message=NULL WHERE run_id=? AND execution_token=? AND fence_token=?",
now,counts.getDepartments(),counts.getUsersSeen(),counts.getEligible(),counts.getExcluded(),counts.getCreated(),counts.getUpdated(),counts.getIneligible(),counts.getOutOfScope(),captured.fingerprint,claim.getRunId(),claim.getExecutionToken(),claim.getFenceToken());
"departments=?,users_seen=?,eligible=?,excluded=?,created=?,updated=?,ineligible=?,out_of_scope=?,context=?,lease_until=NULL,error_code=NULL,error_message=NULL WHERE tenant_id=? AND run_id=? AND execution_token=? AND fence_token=?",
now,counts.getDepartments(),counts.getUsersSeen(),counts.getEligible(),counts.getExcluded(),counts.getCreated(),counts.getUpdated(),counts.getIneligible(),counts.getOutOfScope(),captured.fingerprint,systemTenant,claim.getRunId(),claim.getExecutionToken(),claim.getFenceToken());
if(completed!=1)throw FeishuTenantTokenService.ownershipLost();
String runJson=encode(run);
int moved=jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL,last_run=?,last_successful_run_id=?,last_successful_at=?,successful_context=? WHERE id=1 AND owner=? AND fence_token=?",
runJson,claim.getRunId(),now,captured.fingerprint,claim.getRunId(),claim.getFenceToken());
int moved=jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL,last_run=?,last_successful_run_id=?,last_successful_at=?,successful_context=? WHERE tenant_id=? AND id=1 AND owner=? AND fence_token=?",
runJson,claim.getRunId(),now,captured.fingerprint,systemTenant,claim.getRunId(),claim.getFenceToken());
if(moved!=1)throw FeishuTenantTokenService.ownershipLost();
return run;
});
@@ -161,7 +165,9 @@ public class FeishuDirectoryPublisher {
}
private void loadEmployeeNumbers(Set<String> values,Set<String> result){List<String>all=new ArrayList<>(values);for(int start=0;start<all.size();start+=LOOKUP_BATCH){List<String>b=all.subList(start,Math.min(all.size(),start+LOOKUP_BATCH));for(Map<String,Object>row:jdbc.queryForList("SELECT employee_no FROM sys_user WHERE employee_no IN ("+placeholders(b.size())+")",b.toArray()))result.add(String.valueOf(row.get("employee_no")));}}
private boolean employeeExists(String employee){Integer count=jdbc.queryForObject("SELECT COUNT(*) FROM sys_user WHERE employee_no=?",Integer.class,employee);return count!=null&&count>0;}
private long insertAccount(String open,String employee,String name){KeyHolder key=new GeneratedKeyHolder();PreparedStatementCreator creator=connection->{PreparedStatement statement=connection.prepareStatement("INSERT INTO sys_user(feishu_open_id,feishu_user_id,employee_no,real_name,status,user_type,directory_status,created_at,updated_at) VALUES (?,NULL,?,?,'ACTIVE','EMPLOYEE','UNKNOWN',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",Statement.RETURN_GENERATED_KEYS);statement.setString(1,open);statement.setString(2,employee);statement.setString(3,name);return statement;};jdbc.update(creator,key);if(key.getKey()==null)throw new IllegalStateException("Directory account key unavailable");return key.getKey().longValue();}
private long insertAccount(String open,String employee,String name){
String tenant=trim(systemTenant);if(tenant.isEmpty()||systemOrganization==null||systemOrganization<=0)throw FeishuTenantTokenService.diagnostic("DIRECTORY_DEPLOYMENT_BOUNDARY_INVALID");
KeyHolder key=new GeneratedKeyHolder();PreparedStatementCreator creator=connection->{PreparedStatement statement=connection.prepareStatement("INSERT INTO sys_user(feishu_open_id,feishu_user_id,employee_no,real_name,tenant_id,organization_id,status,user_type,directory_status,created_at,updated_at) VALUES (?,NULL,?,?,?,?,'ACTIVE','EMPLOYEE','UNKNOWN',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",Statement.RETURN_GENERATED_KEYS);statement.setString(1,open);statement.setString(2,employee);statement.setString(3,name);statement.setString(4,tenant);statement.setLong(5,systemOrganization);return statement;};jdbc.update(creator,key);if(key.getKey()==null)throw new IllegalStateException("Directory account key unavailable");return key.getKey().longValue();}
Account account(Map<String,Object>row){return new Account(((Number)row.get("id")).longValue(),value(row.get("feishu_open_id")),value(row.get("feishu_user_id")),value(row.get("directory_status")),value(row.get("directory_context")),time.instant(row.get("directory_verified_at")));}
private static String value(Object value){return value==null?null:String.valueOf(value);} private static String placeholders(int n){StringBuilder b=new StringBuilder();for(int i=0;i<n;i++){if(i>0)b.append(',');b.append('?');}return b.toString();}
private static String trim(String value){return value==null?"":value.trim();}
@@ -23,6 +23,8 @@ public class FeishuDirectoryRunStore {
private final TransactionTemplate requiresNew;
private final ObjectMapper mapper;
private final long leaseSeconds;
@org.springframework.beans.factory.annotation.Value("${observability.tenant-id:default}")
private String systemTenant = "default";
public FeishuDirectoryRunStore(JdbcTemplate jdbc, PlatformTransactionManager manager,
ObjectMapper mapper, FeishuDirectorySettings settings) {
@@ -36,16 +38,30 @@ public class FeishuDirectoryRunStore {
}
public FeishuDirectoryService.Run enqueue(String trigger) {
if (!"MANUAL".equals(trigger) && !"STARTUP".equals(trigger) && !"SCHEDULED".equals(trigger))
throw new IllegalArgumentException("Invalid trigger");
validateTrigger(trigger);
// Normal duplicate POSTs avoid waiting behind a long publication. The
// locked recheck below remains the correctness boundary.
Integer observedActive = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')", Integer.class);
Integer observedActive = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE tenant_id=? AND state IN ('QUEUED','RUNNING')", Integer.class, systemTenant);
if (observedActive != null && observedActive > 0)
throw new BusinessException("Directory sync already running", 409);
return requiresNew.execute(status -> {
return requiresNew.execute(status -> enqueueLocked(trigger));
}
/** Participates in the caller's transaction so queue insertion and audit outbox are atomic. */
public FeishuDirectoryService.Run enqueueInCurrentTransaction(String trigger, String trustedTenantId) {
validateTrigger(trigger);
if (trustedTenantId == null || !trustedTenantId.equals(systemTenant)) {
throw new BusinessException("Invalid tenant boundary", 403);
}
Integer observedActive = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE tenant_id=? AND state IN ('QUEUED','RUNNING')", Integer.class, systemTenant);
if (observedActive != null && observedActive > 0)
throw new BusinessException("Directory sync already running", 409);
return enqueueLocked(trigger);
}
private FeishuDirectoryService.Run enqueueLocked(String trigger) {
lockState();
Integer active = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')", Integer.class);
Integer active = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE tenant_id=? AND state IN ('QUEUED','RUNNING')", Integer.class, systemTenant);
if (active != null && active > 0) throw new BusinessException("Directory sync already running", 409);
Timestamp now = databaseNow();
FeishuDirectoryService.Run run = new FeishuDirectoryService.Run();
@@ -53,11 +69,15 @@ public class FeishuDirectoryRunStore {
run.setTrigger(trigger);
run.setState("RUNNING"); // Public vocabulary deliberately has no QUEUED state.
run.setStartedAt(null); // Execution time begins only when a worker claims this row.
jdbc.update("INSERT INTO feishu_directory_sync_run(run_id,trigger_type,state,queued_at,started_at,complete,applied) VALUES (?,?, 'QUEUED',?,NULL,FALSE,FALSE)",
run.getRunId(), trigger, now);
jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE id=1", encode(run));
jdbc.update("INSERT INTO feishu_directory_sync_run(run_id,tenant_id,trigger_type,state,queued_at,started_at,complete,applied) VALUES (?,?,?, 'QUEUED',?,NULL,FALSE,FALSE)",
run.getRunId(), systemTenant, trigger, now);
jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE tenant_id=? AND id=1", encode(run), systemTenant);
return run;
});
}
private void validateTrigger(String trigger) {
if (!"MANUAL".equals(trigger) && !"STARTUP".equals(trigger) && !"SCHEDULED".equals(trigger))
throw new IllegalArgumentException("Invalid trigger");
}
public Claim claimNext() {
@@ -65,8 +85,8 @@ public class FeishuDirectoryRunStore {
Map<String,Object> state = lockState();
List<Map<String,Object>> rows = jdbc.queryForList(
"SELECT run_id,trigger_type,attempt_count FROM feishu_directory_sync_run " +
"WHERE (state='QUEUED' OR (state='RUNNING' AND lease_until<CURRENT_TIMESTAMP)) " +
"AND attempt_count<? ORDER BY queued_at,run_id LIMIT 1 FOR UPDATE", MAX_ATTEMPTS);
"WHERE tenant_id=? AND (state='QUEUED' OR (state='RUNNING' AND lease_until<CURRENT_TIMESTAMP)) " +
"AND attempt_count<? ORDER BY queued_at,run_id LIMIT 1 FOR UPDATE", systemTenant, MAX_ATTEMPTS);
if (rows.isEmpty()) {
failExhaustedExpiredRuns();
return null;
@@ -79,11 +99,11 @@ public class FeishuDirectoryRunStore {
String execution = UUID.randomUUID().toString();
Timestamp now = databaseNow();
Timestamp lease = Timestamp.from(now.toInstant().plusSeconds(leaseSeconds));
jdbc.update("UPDATE feishu_directory_state SET owner=?,lease_until=?,fence_token=?,context=NULL WHERE id=1",
runId, lease, fence);
jdbc.update("UPDATE feishu_directory_sync_run SET state='RUNNING',started_at=COALESCE(started_at,?),attempt_count=?,execution_token=?,fence_token=?,heartbeat_at=?,lease_until=?,error_code=NULL,error_message=NULL WHERE run_id=?",
jdbc.update("UPDATE feishu_directory_state SET owner=?,lease_until=?,fence_token=?,context=NULL WHERE tenant_id=? AND id=1",
runId, lease, fence, systemTenant);
jdbc.update("UPDATE feishu_directory_sync_run SET state='RUNNING',started_at=COALESCE(started_at,?),attempt_count=?,execution_token=?,fence_token=?,heartbeat_at=?,lease_until=?,error_code=NULL,error_message=NULL WHERE tenant_id=? AND run_id=?",
now,
attempt, execution, fence, now, lease, runId);
attempt, execution, fence, now, lease, systemTenant, runId);
return new Claim(runId, trigger, execution, fence, attempt);
});
}
@@ -95,10 +115,10 @@ public class FeishuDirectoryRunStore {
Timestamp now = databaseNow();
Timestamp lease = Timestamp.from(now.toInstant().plusSeconds(leaseSeconds));
int changed = jdbc.update("UPDATE feishu_directory_sync_run SET heartbeat_at=?,lease_until=? " +
"WHERE run_id=? AND state='RUNNING' AND execution_token=? AND fence_token=? AND lease_until>CURRENT_TIMESTAMP",
now, lease, claim.runId, claim.executionToken, claim.fenceToken);
if (changed == 1) jdbc.update("UPDATE feishu_directory_state SET lease_until=? WHERE id=1 AND owner=? AND fence_token=?",
lease, claim.runId, claim.fenceToken);
"WHERE tenant_id=? AND run_id=? AND state='RUNNING' AND execution_token=? AND fence_token=? AND lease_until>CURRENT_TIMESTAMP",
now, lease, systemTenant, claim.runId, claim.executionToken, claim.fenceToken);
if (changed == 1) jdbc.update("UPDATE feishu_directory_state SET lease_until=? WHERE tenant_id=? AND id=1 AND owner=? AND fence_token=?",
lease, systemTenant, claim.runId, claim.fenceToken);
return changed == 1;
});
return Boolean.TRUE.equals(result);
@@ -107,9 +127,9 @@ public class FeishuDirectoryRunStore {
/** Must be called in the publication transaction; takes the singleton lock first. */
public Map<String,Object> requireLease(Claim claim) {
Map<String,Object> state = lockState();
List<Integer> valid = jdbc.query("SELECT 1 FROM feishu_directory_sync_run WHERE run_id=? AND state='RUNNING' " +
List<Integer> valid = jdbc.query("SELECT 1 FROM feishu_directory_sync_run WHERE tenant_id=? AND run_id=? AND state='RUNNING' " +
"AND execution_token=? AND fence_token=? AND lease_until>CURRENT_TIMESTAMP",
(rs, row) -> rs.getInt(1), claim.runId, claim.executionToken, claim.fenceToken);
(rs, row) -> rs.getInt(1), systemTenant, claim.runId, claim.executionToken, claim.fenceToken);
if (valid.isEmpty() || !claim.runId.equals(state.get("owner"))
|| ((Number) state.get("fence_token")).longValue() != claim.fenceToken)
throw FeishuTenantTokenService.ownershipLost();
@@ -120,22 +140,22 @@ public class FeishuDirectoryRunStore {
requiresNew.execute(status -> {
Map<String,Object> state = lockState();
List<Map<String,Object>> rows = jdbc.queryForList("SELECT attempt_count FROM feishu_directory_sync_run " +
"WHERE run_id=? AND state='RUNNING' AND execution_token=? AND fence_token=? FOR UPDATE",
claim.runId, claim.executionToken, claim.fenceToken);
"WHERE tenant_id=? AND run_id=? AND state='RUNNING' AND execution_token=? AND fence_token=? FOR UPDATE",
systemTenant, claim.runId, claim.executionToken, claim.fenceToken);
if (rows.isEmpty()) return null; // A newer owner has fenced this attempt.
int attempts = ((Number) rows.get(0).get("attempt_count")).intValue();
if (attempts < MAX_ATTEMPTS && retryable(code)) {
jdbc.update("UPDATE feishu_directory_sync_run SET state='QUEUED',execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL,error_code=?,error_message=? WHERE run_id=?",
code, message, claim.runId);
jdbc.update("UPDATE feishu_directory_sync_run SET state='QUEUED',execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL,error_code=?,error_message=? WHERE tenant_id=? AND run_id=?",
code, message, systemTenant, claim.runId);
} else {
Timestamp now = databaseNow();
jdbc.update("UPDATE feishu_directory_sync_run SET state='FAILED',finished_at=?,complete=FALSE,applied=FALSE,error_code=?,error_message=?,execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL WHERE run_id=?",
now, code, message, claim.runId);
jdbc.update("UPDATE feishu_directory_sync_run SET state='FAILED',finished_at=?,complete=FALSE,applied=FALSE,error_code=?,error_message=?,execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL WHERE tenant_id=? AND run_id=?",
now, code, message, systemTenant, claim.runId);
FeishuDirectoryService.Run run = loadPublic(claim.runId);
jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE id=1", encode(run));
jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE tenant_id=? AND id=1", encode(run), systemTenant);
}
if (claim.runId.equals(state.get("owner")) && ((Number) state.get("fence_token")).longValue() == claim.fenceToken)
jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL WHERE id=1");
jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL WHERE tenant_id=? AND id=1", systemTenant);
return null;
});
}
@@ -148,7 +168,7 @@ public class FeishuDirectoryRunStore {
}
public FeishuDirectoryService.Run loadPublic(String runId) {
return jdbc.queryForObject("SELECT * FROM feishu_directory_sync_run WHERE run_id=?", (rs, row) -> {
return jdbc.queryForObject("SELECT * FROM feishu_directory_sync_run WHERE tenant_id=? AND run_id=?", (rs, row) -> {
FeishuDirectoryService.Run run = new FeishuDirectoryService.Run();
run.setRunId(rs.getString("run_id")); run.setTrigger(rs.getString("trigger_type"));
String internal = rs.getString("state");
@@ -164,24 +184,24 @@ public class FeishuDirectoryRunStore {
counts.setIneligible(rs.getInt("ineligible")); counts.setOutOfScope(rs.getInt("out_of_scope"));
run.setCounts(counts); run.setErrorCode(rs.getString("error_code")); run.setErrorMessage(rs.getString("error_message"));
return run;
}, runId);
}, systemTenant, runId);
}
private void failExhaustedExpiredRuns() {
List<String> expired=jdbc.query("SELECT run_id FROM feishu_directory_sync_run WHERE state='RUNNING' " +
"AND lease_until<CURRENT_TIMESTAMP AND attempt_count>=? FOR UPDATE",(rs,row)->rs.getString(1),MAX_ATTEMPTS);
List<String> expired=jdbc.query("SELECT run_id FROM feishu_directory_sync_run WHERE tenant_id=? AND state='RUNNING' " +
"AND lease_until<CURRENT_TIMESTAMP AND attempt_count>=? FOR UPDATE",(rs,row)->rs.getString(1),systemTenant,MAX_ATTEMPTS);
for(String runId:expired){
jdbc.update("UPDATE feishu_directory_sync_run SET state='FAILED',finished_at=CURRENT_TIMESTAMP,complete=FALSE,applied=FALSE," +
"error_code='DIRECTORY_WORKER_UNAVAILABLE',error_message='Directory sync failed; current directory retained.'," +
"execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL WHERE run_id=?",runId);
"execution_token=NULL,fence_token=NULL,heartbeat_at=NULL,lease_until=NULL WHERE tenant_id=? AND run_id=?",systemTenant,runId);
FeishuDirectoryService.Run failed=loadPublic(runId);
jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE id=1",encode(failed));
jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL WHERE id=1 AND owner=?",runId);
jdbc.update("UPDATE feishu_directory_state SET last_run=? WHERE tenant_id=? AND id=1",encode(failed),systemTenant);
jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,context=NULL WHERE tenant_id=? AND id=1 AND owner=?",systemTenant,runId);
}
}
private Map<String,Object> lockState() {
return jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1 FOR UPDATE");
return jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE tenant_id=? AND id=1 FOR UPDATE", systemTenant);
}
private Timestamp databaseNow() { return jdbc.queryForObject("SELECT CURRENT_TIMESTAMP", Timestamp.class); }
private String encode(FeishuDirectoryService.Run run) {
@@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
@@ -34,6 +35,8 @@ public class FeishuDirectoryService {
private final ObjectMapper mapper;
private final FeishuDirectoryClient directClient;
private final FeishuDirectoryPublisher directPublisher;
@Value("${observability.tenant-id:default}")
private String systemTenant = "default";
@Autowired
public FeishuDirectoryService(JdbcTemplate jdbc, PlatformTransactionManager manager,
@@ -75,18 +78,18 @@ public class FeishuDirectoryService {
@PostConstruct
public void initializeState(){
try{jdbc.update("INSERT INTO feishu_directory_state(id) SELECT 1 WHERE NOT EXISTS (SELECT 1 FROM feishu_directory_state WHERE id=1)");}
try{jdbc.update("INSERT INTO feishu_directory_state(id,tenant_id) SELECT 1,? WHERE NOT EXISTS (SELECT 1 FROM feishu_directory_state WHERE tenant_id=? AND id=1)",systemTenant,systemTenant);}
catch(DuplicateKeyException ignored){ }
}
public Map<String,Object> status(){
Map<String,Object> state=null;try{state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");}catch(RuntimeException ignored){}
Map<String,Object> state=null;try{state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE tenant_id=? AND id=1",systemTenant);}catch(RuntimeException ignored){}
FeishuDirectoryPublication publication=FeishuDirectoryPublication.classify(state,time);
String context=currentContext();
Instant success=publication.getSuccessfulAt();
Integer active=null;try{active=jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')",Integer.class);}catch(RuntimeException ignored){}
Integer active=null;try{active=jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE tenant_id=? AND state IN ('QUEUED','RUNNING')",Integer.class,systemTenant);}catch(RuntimeException ignored){}
Map<String,Object> result=new LinkedHashMap<>();result.put("configured",context!=null);result.put("running",active!=null&&active>0);result.put("snapshotState",publication.getSnapshotState());result.put("availabilityState",publication.getAvailabilityState());result.put("additionsAllowed",publication.isAdditionsAllowed());result.put("contextState",publication.contextState(context).name());result.put("storageMode","CURRENT_STATE");result.put("currentRevision",publication.getRevision());result.put("maxStatusAgeSeconds",0);result.put("lastSuccessfulRunId",publication.getRevision());result.put("lastSuccessfulAt",success==null?null:success.toString());result.put("snapshotExpiresAt",null);
Run last=null;try{List<String> ids=jdbc.query("SELECT run_id FROM feishu_directory_sync_run ORDER BY queued_at DESC,run_id DESC LIMIT 1",(rs,row)->rs.getString(1));if(!ids.isEmpty())last=runs.loadPublic(ids.get(0));}catch(Exception ignored){last=parse(state==null?null:(String)state.get("last_run"));}
Run last=null;try{List<String> ids=jdbc.query("SELECT run_id FROM feishu_directory_sync_run WHERE tenant_id=? ORDER BY queued_at DESC,run_id DESC LIMIT 1",(rs,row)->rs.getString(1),systemTenant);if(!ids.isEmpty())last=runs.loadPublic(ids.get(0));}catch(Exception ignored){last=parse(state==null?null:(String)state.get("last_run"));}
result.put("lastRun",last);return result;
}
@@ -98,7 +101,7 @@ public class FeishuDirectoryService {
if(!organizationPermits.tryAcquire())return unavailable;
try{
OrganizationSnapshot captured=organizationSnapshot.execute(status->{
Map<String,Object> state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
Map<String,Object> state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE tenant_id=? AND id=1",systemTenant);
FeishuDirectoryPublication publication=FeishuDirectoryPublication.classify(state,time);
Instant success=publication.getSuccessfulAt();
Map<String,Object> result=emptyOrganization(publication,success==null?null:success.toString(),"UNKNOWN");
@@ -111,7 +114,7 @@ public class FeishuDirectoryService {
if(!revalidate(captured.publication))return unavailable;
captured.value.put("contextState",captured.publication.contextState(currentContext()).name());
return captured.value;
}catch(Exception ignored){log.warn("Feishu organization snapshot could not be read");return unavailable;}
}catch(Exception ignored){log.warn("无法读取飞书组织快照");return unavailable;}
finally{organizationPermits.release();}
}
@@ -124,7 +127,7 @@ public class FeishuDirectoryService {
String target=departmentId.trim();
try{
OrganizationSnapshot captured=organizationSnapshot.execute(status->{
Map<String,Object> state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
Map<String,Object> state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE tenant_id=? AND id=1",systemTenant);
FeishuDirectoryPublication publication=FeishuDirectoryPublication.classify(state,time);
Instant success=publication.getSuccessfulAt();
Map<String,Object> result=emptyOrganization(publication,success==null?null:success.toString(),"UNKNOWN");
@@ -142,7 +145,7 @@ public class FeishuDirectoryService {
if(!revalidate(captured.publication))return unavailable;
captured.value.put("contextState",captured.publication.contextState(currentContext()).name());
return captured.value;
}catch(Exception ignored){log.warn("Feishu organization members could not be read");return unavailable;}
}catch(Exception ignored){log.warn("无法读取飞书组织成员");return unavailable;}
finally{organizationPermits.release();}
}
@@ -169,7 +172,7 @@ public class FeishuDirectoryService {
/** A separate READ_COMMITTED transaction observes publications committed during materialization. */
private boolean revalidate(FeishuDirectoryPublication captured){
Boolean stable=observation.execute(status->{
Map<String,Object> current=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
Map<String,Object> current=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE tenant_id=? AND id=1",systemTenant);
FeishuDirectoryPublication now=FeishuDirectoryPublication.classify(current,time);
return now.isAvailable()&&Objects.equals(captured.getRevision(),now.getRevision())
&&Objects.equals(captured.getSuccessfulContext(),now.getSuccessfulContext())
@@ -213,7 +216,13 @@ public class FeishuDirectoryService {
}
return"UNEXPECTED";
}
static String failureMessage(String diagnostic){return"Directory sync failed; current directory retained. Check Feishu contact permissions, app visibility and configuration. 目录同步失败,已保留当前通讯录;请检查飞书通讯录权限、应用可见范围和配置。 Diagnostic category: "+diagnostic+".";}
static String failureMessage(String diagnostic){
if("DIRECTORY_USER_RESIGNATION_FIELD_UNAVAILABLE".equals(diagnostic))
return"Directory sync failed; current directory retained. Feishu did not return base_info.is_resigned. Verify that either directory:employee.base.is_resigned:read or directory:employee.base.status:read is granted and published; if already authorized, verify the Directory-v1 response field contract and that the application and tenant match. 目录同步失败,已保留当前通讯录;飞书未返回离职状态字段。请检查上述两种权限之一是否已授予并发布;若已授权,请继续检查 Directory-v1 返回字段契约,以及应用与租户是否匹配。 Diagnostic category: "+diagnostic+".";
if("DIRECTORY_USER_RESIGNATION_FIELD_INVALID".equals(diagnostic))
return"Directory sync failed; current directory retained. Feishu returned an invalid base_info.is_resigned value; retry after checking the Directory-v1 field contract. 目录同步失败,已保留当前通讯录;飞书返回的离职状态字段不符合布尔契约,请检查 Directory-v1 字段契约后重试。 Diagnostic category: "+diagnostic+".";
return"Directory sync failed; current directory retained. Check Feishu contact permissions, app visibility and configuration. 目录同步失败,已保留当前通讯录;请检查飞书通讯录权限、应用可见范围和配置。 Diagnostic category: "+diagnostic+".";
}
@Data public static class Run {private String runId,trigger,state="RUNNING",startedAt,finishedAt;private boolean complete,applied;private Counts counts=new Counts();private String errorCode,errorMessage;}
@Data public static class Counts {private int departments,usersSeen,excluded,created,updated,outOfScope;@JsonIgnore private int eligible;@JsonIgnore private int ineligible;@JsonIgnore public int getEligible(){return eligible;}@JsonIgnore public int getIneligible(){return ineligible;}}
@@ -35,7 +35,7 @@ public class FeishuDirectorySyncDispatcher implements SmartLifecycle {
catch(Throwable ex){
// Context shutdown closes the shared Hibernate session/pool while a tick may still be in flight.
if(!running.get()||isShutdownNoise(ex))return;
log.warn("Feishu directory dispatcher iteration failed: {}", ex.toString());
log.warn("飞书通讯录同步调度轮询失败: {}", ex.toString());
}
}
private static boolean isShutdownNoise(Throwable ex){
@@ -45,7 +45,7 @@ public class FeishuDirectorySyncWorker {
succeeded=true;
}catch(Throwable failure){
String code=FeishuDirectoryService.safeDiagnostic(failure,phase);
log.warn("Feishu directory attempt failed: runId={}, attempt={}, phase={}, errorCode={}, failureType={}",
log.warn("飞书通讯录同步尝试失败: runId={}, attempt={}, phase={}, errorCode={}, failureType={}",
claim.getRunId(),claim.getAttempt(),phase,code,FeishuDirectoryService.safeFailureType(failure));
runs.recordFailure(claim,code,FeishuDirectoryService.failureMessage(code));
}finally{heartbeat.cancel(false);}
@@ -4,7 +4,9 @@ import com.finance.system.entity.SysUser;
import com.finance.system.exception.BusinessException;
import com.finance.system.repository.SysUserRepository;
import com.finance.system.service.FeishuDirectoryLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
@@ -20,12 +22,17 @@ import java.util.Objects;
* columns can be written. Role/status and directory observations are never written here.
*/
@Service
@Slf4j
public class FeishuLoginPersistenceService {
private final JdbcTemplate jdbc;
private final EntityManager em;
private final SysUserRepository users;
private final FeishuDirectoryAccessService access;
private final TransactionTemplate tx;
@Value("${observability.tenant-id:default}")
private String deploymentTenant = "default";
@Value("${observability.organization-id:1}")
private Long deploymentOrganizationId = 1L;
public FeishuLoginPersistenceService(JdbcTemplate jdbc, EntityManager em, SysUserRepository users,
FeishuDirectoryAccessService access, FeishuTenantTokenService tokens, PlatformTransactionManager manager) {
this.jdbc = jdbc; this.em = em; this.users = users; this.access = access;
@@ -50,14 +57,25 @@ public class FeishuLoginPersistenceService {
SysUser fresh = locked(id);
// open_id is the only Feishu identity used for account matching.
// Never replace it or adopt an account using user_id alone.
if (!Objects.equals(fresh.getFeishuOpenId(), openId)) throw denied();
if (!Objects.equals(fresh.getFeishuOpenId(), openId)) throw bindingDenied();
String tenantId = deploymentTenant();
long organizationId = deploymentOrganizationId();
if (!tenantId.equals(fresh.getTenantId())) throw bindingDenied();
if (fresh.getOrganizationId() == null) {
int repaired = jdbc.update("UPDATE sys_user SET organization_id=?,updated_at=CURRENT_TIMESTAMP(6) "
+ "WHERE id=? AND tenant_id=? AND organization_id IS NULL",
organizationId, id, tenantId);
if (repaired != 1) throw bindingDenied();
em.refresh(fresh);
}
if (!Objects.equals(fresh.getOrganizationId(), organizationId)) throw bindingDenied();
String counterpart = info.getUserId() == null ? null : info.getUserId().trim();
if (counterpart != null && counterpart.isEmpty()) counterpart = null;
String existingUserId = fresh.getFeishuUserId();
if (counterpart != null && existingUserId != null && !existingUserId.trim().isEmpty()
&& !counterpart.equals(existingUserId)) throw denied();
if (counterpart != null && jdbc.queryForObject("SELECT COUNT(*) FROM sys_user WHERE feishu_user_id=? AND id<>?", Integer.class, counterpart, id) != 0) throw denied();
&& !counterpart.equals(existingUserId)) throw bindingDenied();
if (counterpart != null && jdbc.queryForObject("SELECT COUNT(*) FROM sys_user WHERE feishu_user_id=? AND id<>?", Integer.class, counterpart, id) != 0) throw bindingDenied();
String name = info.getName() == null || info.getName().trim().isEmpty() ? fresh.getRealName() : info.getName();
validate(name, 100); validate(info.getAvatarUrl(), 500); validate(info.getEmail(), 200); validate(info.getMobile(), 20); validate(counterpart, 100);
jdbc.update("UPDATE sys_user SET real_name=?,avatar_url=?,email=?,mobile=?,feishu_user_id=CASE WHEN feishu_user_id IS NULL OR TRIM(feishu_user_id)='' THEN ? ELSE feishu_user_id END,last_login_at=? WHERE id=?",
@@ -92,5 +110,20 @@ public class FeishuLoginPersistenceService {
private static String keepExisting(String incoming, String existing) {
return incoming == null || incoming.trim().isEmpty() ? existing : incoming;
}
private String deploymentTenant() {
if (deploymentTenant == null || deploymentTenant.trim().isEmpty()) throw boundaryUnavailable();
return deploymentTenant.trim();
}
private long deploymentOrganizationId() {
if (deploymentOrganizationId == null || deploymentOrganizationId <= 0) throw boundaryUnavailable();
return deploymentOrganizationId;
}
private static BusinessException bindingDenied() {
log.warn("飞书登录身份归属冲突,登录完成操作被拒绝 event=feishu.oauth.finalize outcome=denied conflictType=IDENTITY_OWNERSHIP");
return new BusinessException("飞书账号已绑定其他账户,请联系管理员", 403);
}
private static BusinessException boundaryUnavailable() {
return new BusinessException("飞书账号部署边界未配置", 503);
}
private static BusinessException denied() { return new BusinessException("Active Feishu identity binding required", 403); }
}
@@ -0,0 +1,81 @@
package com.finance.system.adapter.feishu;
import com.finance.system.exception.BusinessException;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.function.LongSupplier;
/** Short-lived, bounded server-side binding between OAuth state and a trusted frontend origin. */
@Component
public class FeishuOAuthStateOriginStore {
static final long DEFAULT_TTL_MILLIS = 5L * 60L * 1000L;
static final int DEFAULT_MAX_ENTRIES = 4096;
private final Map<String, Entry> entries = new HashMap<>();
private final LongSupplier clock;
private final long ttlMillis;
private final int maxEntries;
public FeishuOAuthStateOriginStore() {
this(System::currentTimeMillis, DEFAULT_TTL_MILLIS, DEFAULT_MAX_ENTRIES);
}
FeishuOAuthStateOriginStore(LongSupplier clock, long ttlMillis, int maxEntries) {
this.clock = clock;
this.ttlMillis = ttlMillis;
this.maxEntries = maxEntries;
}
public synchronized void bind(String state, String trustedOrigin) {
if (state == null || !state.matches("[A-Za-z0-9_-]{43}") || trustedOrigin == null) {
throw new BusinessException("飞书登录状态创建失败", 503);
}
long now = clock.getAsLong();
cleanup(now);
if (entries.containsKey(state)) {
throw new BusinessException("飞书登录状态创建失败", 503);
}
if (!entries.containsKey(state) && entries.size() >= maxEntries) {
throw new BusinessException("飞书登录请求过多,请稍后重试", 503);
}
entries.put(state, new Entry(trustedOrigin, now + ttlMillis));
}
/** Atomically returns the trusted origin once; replays and expiry fail closed. */
public synchronized String consume(String state) {
long now = clock.getAsLong();
cleanup(now);
Entry entry = entries.get(state);
if (entry == null || entry.consumed) {
throw new BusinessException("飞书登录状态无效或已过期", 400);
}
entry.consumed = true;
return entry.origin;
}
synchronized int size() {
cleanup(clock.getAsLong());
return entries.size();
}
private void cleanup(long now) {
Iterator<Map.Entry<String, Entry>> iterator = entries.entrySet().iterator();
while (iterator.hasNext()) {
if (iterator.next().getValue().expiresAt <= now) iterator.remove();
}
}
private static final class Entry {
private final String origin;
private final long expiresAt;
private boolean consumed;
private Entry(String origin, long expiresAt) {
this.origin = origin;
this.expiresAt = expiresAt;
}
}
}
@@ -17,6 +17,13 @@ import java.util.concurrent.TimeUnit;
@Service
public class FeishuTenantTokenService {
static final String API = "https://open.feishu.cn/open-apis";
static final String DIRECTORY_CONTEXT_POLICY =
"api=directory-v1-filter;employee_id_type=open_id;department_id_type=open_department_id"
+ ";department_filter=parent_department_id:eq:json-string:bfs-root-0"
+ ";employee_transport_partition=work_info.staff_status:eq:1,2,3,4,5:not-projected:not-persisted"
+ ";required_field=base_info.is_resigned:boolean"
+ ";resignation_policy=is_resigned:false:business-eligible-current-directory-all-statuses"
+ ";policy=directory-v1-6";
private static final BigInteger SUCCESS_CODE = BigInteger.ZERO;
private static final BigInteger RATE_LIMIT_CODE = BigInteger.valueOf(99991400L);
private static final BigInteger MAX_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L);
@@ -81,7 +88,7 @@ public class FeishuTenantTokenService {
throw diagnostic("CONFIGURATION_UNAVAILABLE");
}
if (values == null) throw diagnostic("CONFIGURATION_MISSING");
String app = values.get("appId"), secret = values.get("appSecret");
String app = trim(values.get("appId")), secret = trim(values.get("appSecret"));
// A disabled integration is deliberately reported as configuration missing,
// while the independent directory-sync switch is reported as SYNC_DISABLED.
// Neither path exposes the configured values.
@@ -89,13 +96,14 @@ public class FeishuTenantTokenService {
|| !Boolean.parseBoolean(values.get(IntegrationConfigReader.INTERNAL_ENABLED_KEY)))
throw diagnostic("CONFIGURATION_MISSING");
return new Context(app, secret, fingerprint(app + "\n" + secret
+ "\napi=directory-v1-filter;employee_id_type=open_id;department_id_type=open_department_id"
+ ";department_filter=parent_department_id:eq:json-string:bfs-root-0"
+ ";employee_transport_partition=work_info.staff_status:eq:1,2,3,4,5:not-projected:not-persisted"
+ ";policy=directory-v1-4\n"
+ "\n" + DIRECTORY_CONTEXT_POLICY + "\n"
+ settings.getCredentialRevision()));
}
private static String trim(String value) {
return value == null ? null : value.trim();
}
public boolean syncEnabled() {
try {
Map<String,String> values = config.freshFeishu();
@@ -104,16 +112,27 @@ public class FeishuTenantTokenService {
catch (Exception ex) { throw diagnostic("CONFIGURATION_UNAVAILABLE"); }
}
public String getTenantAccessToken() { return token(capture()); }
public String getAppAccessToken() { return appToken(capture()); }
public String token(Context context) {
return token(context, "/auth/v3/tenant_access_token/internal", "tenant_access_token");
}
String appToken(Context context) {
return token(context, "/auth/v3/app_access_token/internal", "app_access_token");
}
private String token(Context context, String endpoint, String responseField) {
if (context == null) throw diagnostic("TOKEN_CONTEXT_MISSING");
Map<String,String> body = new HashMap<>(); body.put("app_id", context.app); body.put("app_secret", context.secret);
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(settings.elapsed());
int retries=0;
while(true){
try {
ResponseEntity<JsonNode> exchange=http.exchange(API + "/auth/v3/tenant_access_token/internal",
HttpMethod.POST,new HttpEntity<>(body),JsonNode.class);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<JsonNode> exchange=http.exchange(API + endpoint,
HttpMethod.POST,new HttpEntity<>(body, headers),JsonNode.class);
JsonNode response=exchange.getBody();
BigInteger responseCode = responseCode(response);
if (RATE_LIMIT_CODE.equals(responseCode)) {
@@ -127,10 +146,10 @@ public class FeishuTenantTokenService {
Long code = safeCode(response);
throw code == null ? diagnostic("TOKEN_RESPONSE_INVALID") : diagnostic("FEISHU_CODE_" + code);
}
if (!response.path("tenant_access_token").isTextual()
|| response.path("tenant_access_token").asText().trim().isEmpty())
if (!response.path(responseField).isTextual()
|| response.path(responseField).asText().trim().isEmpty())
throw diagnostic("TOKEN_RESPONSE_INVALID");
return response.path("tenant_access_token").asText();
return response.path(responseField).asText();
} catch (DiagnosticFailure ex) {
throw ex;
} catch (org.springframework.web.client.HttpStatusCodeException ex) {
@@ -9,7 +9,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
public class FeishuTokenResponse {
private int code;
private Integer code;
private String msg;
private TokenData data;
@@ -0,0 +1,170 @@
package com.finance.system.adapter.feishu;
import com.finance.system.entity.SysUser;
import com.finance.system.exception.BusinessException;
import com.finance.system.repository.SysUserRepository;
import com.finance.system.service.FeishuDirectoryLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;
import java.sql.Statement;
import java.util.Objects;
/**
* Owns the independent transaction used by first-time Feishu account creation.
* A uniqueness failure is rolled back before it is returned to the OAuth
* orchestrator, so any recovery lookup runs in a clean transaction context.
*/
@Slf4j
@Service
public class FeishuUserProvisioningService {
private final SysUserRepository users;
private final JdbcTemplate jdbc;
private final TransactionTemplate transaction;
@Value("${observability.tenant-id:default}")
private String deploymentTenant = "default";
@Value("${observability.organization-id:1}")
private Long deploymentOrganizationId = 1L;
public FeishuUserProvisioningService(SysUserRepository users,
JdbcTemplate jdbc,
PlatformTransactionManager transactionManager) {
this.users = users;
this.jdbc = jdbc;
this.transaction = new TransactionTemplate(transactionManager);
this.transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
this.transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
this.transaction.setTimeout(30);
}
public SysUser provisionEmployee(FeishuUserInfo info) {
ProvisioningResult result = transaction.execute(status -> createEmployee(info));
if (result == null || result.user == null || result.user.getId() == null) {
throw new BusinessException("飞书账号创建失败,请稍后重试", 503);
}
log.info("飞书员工账号配置完成 event=feishu.oauth.provision outcome={} accountType=EMPLOYEE",
result.created ? "created" : "recovered");
return result.user;
}
private ProvisioningResult createEmployee(FeishuUserInfo info) {
if (info == null || !StringUtils.hasText(info.getOpenId())) {
throw new BusinessException("飞书身份无效,请重新授权", 403);
}
String openId = info.getOpenId().trim();
String userId = StringUtils.hasText(info.getUserId()) ? info.getUserId().trim() : null;
String tenantId = deploymentTenant();
long organizationId = deploymentOrganizationId();
// Use the same short database mutex as directory publication and OAuth
// finalization. Re-read under that lock to avoid the common in-process
// first-login race without ever discovering/adopting an account by
// user_id alone: only the exact open_id may be returned.
FeishuDirectoryLock.acquire(jdbc);
SysUser existing = users.findByFeishuOpenId(openId);
SysUser userIdOwner = userId == null ? null : users.findByFeishuUserId(userId);
if (existing != null) {
requireCompatibleExactOpen(existing, userIdOwner, userId);
return new ProvisioningResult(existing, false);
}
if (userIdOwner != null) throw bindingConflict();
String employeeNo = uniqueEmployeeNo();
KeyHolder key = new GeneratedKeyHolder();
PreparedStatementCreator insert = connection -> {
java.sql.PreparedStatement statement = connection.prepareStatement(
"INSERT INTO sys_user(feishu_open_id,feishu_user_id,employee_no,real_name,avatar_url,email,mobile,"
+ "tenant_id,organization_id,user_type,status,directory_status,created_at,updated_at) "
+ "VALUES (?,?,?,?,?,?,?,?,?,'EMPLOYEE','ACTIVE','UNKNOWN',CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6))",
Statement.RETURN_GENERATED_KEYS);
statement.setString(1, openId);
statement.setString(2, userId);
statement.setString(3, employeeNo);
statement.setString(4, StringUtils.hasText(info.getName()) ? info.getName() : "Feishu User");
statement.setString(5, info.getAvatarUrl());
statement.setString(6, info.getEmail());
statement.setString(7, info.getMobile());
statement.setString(8, tenantId);
statement.setLong(9, organizationId);
return statement;
};
try {
jdbc.update(insert, key);
} catch (DataIntegrityViolationException conflict) {
// Do not let a vendor SQLException (which may contain identifier
// values) reach TransactionTemplate's diagnostic logging. The
// orchestrator still receives a DataIntegrityViolationException,
// but its message contains only a whitelisted constraint category.
throw sanitizedConflict(conflict);
}
Number generated = key.getKey();
if (generated == null) throw new BusinessException("飞书账号创建失败,请稍后重试", 503);
SysUser inserted = users.findById(generated.longValue())
.orElseThrow(() -> new BusinessException("飞书账号创建失败,请稍后重试", 503));
return new ProvisioningResult(inserted, true);
}
private void requireCompatibleExactOpen(SysUser existing, SysUser userIdOwner, String requestedUserId) {
if (!deploymentTenant().equals(existing.getTenantId())) throw bindingConflict();
if (userIdOwner != null && !Objects.equals(existing.getId(), userIdOwner.getId())) {
throw bindingConflict();
}
String boundUserId = StringUtils.hasText(existing.getFeishuUserId())
? existing.getFeishuUserId().trim() : null;
if (boundUserId != null && requestedUserId != null && !boundUserId.equals(requestedUserId)) {
throw bindingConflict();
}
}
private DataIntegrityViolationException sanitizedConflict(DataIntegrityViolationException conflict) {
String category = FeishuAuthService.constraintCategory(conflict);
return new DataIntegrityViolationException("FEISHU_OAUTH_" + category);
}
private BusinessException bindingConflict() {
log.warn("飞书员工账号身份归属冲突,账号配置被拒绝 event=feishu.oauth.provision outcome=denied conflictType=IDENTITY_OWNERSHIP");
return new BusinessException("飞书账号已绑定其他账户,请联系管理员", 403);
}
private String uniqueEmployeeNo() {
for (int attempt = 0; attempt < 5; attempt++) {
String number = "FS-" + java.util.UUID.randomUUID();
if (users.findByEmployeeNo(number) == null) return number;
}
throw new BusinessException("员工编号生成失败,请稍后重试", 503);
}
private String deploymentTenant() {
if (!StringUtils.hasText(deploymentTenant)) {
throw new BusinessException("飞书账号部署边界未配置", 503);
}
return deploymentTenant.trim();
}
private long deploymentOrganizationId() {
if (deploymentOrganizationId == null || deploymentOrganizationId <= 0) {
throw new BusinessException("飞书账号部署边界未配置", 503);
}
return deploymentOrganizationId;
}
private static final class ProvisioningResult {
private final SysUser user;
private final boolean created;
private ProvisioningResult(SysUser user, boolean created) {
this.user = user;
this.created = created;
}
}
}
@@ -9,7 +9,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
public class FeishuUserResponse {
private int code;
private Integer code;
private String msg;
private UserData data;
@@ -36,9 +36,10 @@ public final class ReimbursementCanonicalizer {
field(out, "feishuFormDisplayValues", app.getFeishuFormDisplayValues());
field(out, "bankName", bank == null ? null : bank.getBankName());
field(out, "branchName", bank == null ? null : bank.getBranchName());
field(out, "accountName", bank == null ? null : bank.getAccountName());
field(out, "accountNo", bank == null ? null : bank.getAccountNo());
field(out, "accountNoMask", bank == null ? null : bank.getAccountNoMask());
// Metadata detects an account change without placing plaintext, ciphertext,
// or the equality fingerprint in the Feishu canonical representation.
field(out, "bankAccountUpdatedAt", bank == null ? null : bank.getUpdatedAt());
for (ReimExpenseItem item : orderedItems(sourceItems)) {
field(out, "item.seq", item.getSeqNo());
field(out, "item.date", item.getExpenseDate());
@@ -7,6 +7,7 @@ import com.finance.system.service.IntegrationConfigReader;
import com.finance.system.service.IntegrationConfigService;
import com.finance.system.service.KingdeeAccountBindingService;
import com.finance.system.util.AuditUtil;
import com.finance.system.security.UserPrincipal;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@@ -89,9 +90,12 @@ public class KingdeeClient {
if (kingdeeAccountBindingService == null) {
throw new BusinessException("金蝶员工账号绑定服务未配置");
}
Long userId = AuditUtil.getCurrentUserId();
UserPrincipal principal = AuditUtil.getCurrentUser();
if (principal == null || principal.getId() == null || principal.getTenantId() == null) {
throw new BusinessException("缺少可信的金蝶操作员租户边界", 403);
}
KingdeeAccountBindingService.KingdeeCredentials credentials =
kingdeeAccountBindingService.requireCredentials(userId);
kingdeeAccountBindingService.requireCredentials(principal.getId(), principal.getTenantId());
String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc";
String userSession = authenticate(credentials.getUsername(), credentials.getPassword());
return executeKingdeeApi(url, formId, data, userSession);
@@ -0,0 +1,128 @@
package com.finance.system.audit;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class AuditDeliveryService {
private final AuditOutboxRepository outboxRepository;
private final AuditEventRepository eventRepository;
private final AuditEventAppender eventAppender;
private final AuditEventPolicy policy;
private final ObjectMapper objectMapper;
private final AuditIntegrityService integrityService;
@Value("${observability.audit.max-attempts:10}")
private int maxAttempts;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public boolean deliver(Long outboxId, String owner) {
Optional<AuditOutbox> optional = outboxRepository.findOwnedByIdForUpdate(outboxId, owner);
if (!optional.isPresent()) return false;
AuditOutbox outbox = optional.get();
LocalDateTime now = AuditEventService.utcNow();
if (!"PENDING".equals(outbox.getStatus()) || outbox.getLeaseUntil() == null
|| !outbox.getLeaseUntil().isAfter(now)) return false;
if (outbox.getAvailableAt().isAfter(now)) return false;
AuditEventCommand command;
try {
command = objectMapper.readValue(outbox.getEventPayload(), AuditEventCommand.class);
} catch (JsonProcessingException e) {
throw new IllegalStateException("AUDIT_PAYLOAD_INVALID", e);
}
policy.validate(command);
if (!eventRepository.existsByEventUid(command.getEventId())) {
eventAppender.append(toEntity(command));
}
outbox.setStatus("PUBLISHED");
outbox.setPublishedAt(now);
outbox.setLastErrorCode(null);
clearLease(outbox);
return true;
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public boolean markFailure(Long outboxId, String owner, String errorCode) {
Optional<AuditOutbox> optional = outboxRepository.findOwnedByIdForUpdate(outboxId, owner);
if (!optional.isPresent()) return false;
AuditOutbox outbox = optional.get();
LocalDateTime now = AuditEventService.utcNow();
if (!"PENDING".equals(outbox.getStatus()) || outbox.getLeaseUntil() == null
|| !outbox.getLeaseUntil().isAfter(now)) return false;
int attempts = outbox.getAttemptCount() == null ? 1 : outbox.getAttemptCount() + 1;
outbox.setAttemptCount(attempts);
outbox.setLastErrorCode(safeErrorCode(errorCode));
if (attempts >= Math.max(1, maxAttempts)) {
outbox.setStatus("DEAD");
} else {
outbox.setStatus("PENDING");
long delaySeconds = Math.min(300L, 1L << Math.min(8, attempts));
outbox.setAvailableAt(now.plusSeconds(delaySeconds));
}
clearLease(outbox);
return true;
}
private static void clearLease(AuditOutbox outbox) {
outbox.setLeaseOwner(null);
outbox.setLeaseUntil(null);
}
private AuditEvent toEntity(AuditEventCommand command) {
LocalDateTime occurred = LocalDateTime.ofInstant(
command.getEventTime() == null ? Instant.now() : command.getEventTime(), ZoneOffset.UTC);
AuditEvent event = AuditEvent.builder()
.eventUid(command.getEventId())
.schemaVersion(command.getSchemaVersion() == null ? 1 : command.getSchemaVersion())
.occurredAt(occurred)
.recordedAt(AuditEventService.utcNow())
.tenantId(command.getTenantId())
.organizationId(command.getOrganizationId())
.category(command.getCategory())
.actionCode(command.getAction())
.outcome(command.getOutcome())
.reasonCode(command.getReasonCode())
.actorType(command.getActorType())
.actorId(command.getActorId())
.targetType(command.getTargetType())
.targetId(command.getTargetId())
.resourceType(command.getResourceType())
.resourceId(command.getResourceId())
.requestId(command.getRequestId())
.traceId(command.getTraceId())
.spanId(command.getSpanId())
.sourceChannel(command.getSource())
.clientIpHash(command.getClientIpHash())
.changedFields(writeJson(command.getChanges()))
.attributes(writeJson(command.getAttributes()))
.build();
event.setIntegrityHash(integrityService.sign(event));
return event;
}
private String writeJson(Object value) {
try {
return objectMapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new IllegalStateException("AUDIT_PAYLOAD_INVALID", e);
}
}
private static String safeErrorCode(String value) {
if (value != null && value.matches("[A-Z0-9_]{1,80}")) return value;
return "AUDIT_DELIVERY_FAILED";
}
}
@@ -0,0 +1,83 @@
package com.finance.system.audit;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Immutable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Immutable
@Table(name = "sys_audit_event")
public class AuditEvent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "event_uid", nullable = false, unique = true, length = 32)
private String eventUid;
@Column(name = "schema_version", nullable = false)
private Integer schemaVersion;
@Column(name = "occurred_at", nullable = false)
private LocalDateTime occurredAt;
@Column(name = "recorded_at", nullable = false)
private LocalDateTime recordedAt;
@Column(name = "tenant_id", nullable = false, length = 64)
private String tenantId;
@Column(name = "organization_id", nullable = false)
private Long organizationId;
@Column(nullable = false, length = 24)
private String category;
@Column(name = "action_code", nullable = false, length = 120)
private String actionCode;
@Column(nullable = false, length = 16)
private String outcome;
@Column(name = "reason_code", length = 80)
private String reasonCode;
@Column(name = "actor_type", nullable = false, length = 16)
private String actorType;
@Column(name = "actor_id")
private Long actorId;
@Column(name = "target_type", length = 64)
private String targetType;
@Column(name = "target_id", length = 128)
private String targetId;
@Column(name = "resource_type", nullable = false, length = 64)
private String resourceType;
@Column(name = "resource_id", nullable = false, length = 128)
private String resourceId;
@Column(name = "request_id", length = 64)
private String requestId;
@Column(name = "trace_id", length = 32)
private String traceId;
@Column(name = "span_id", length = 16)
private String spanId;
@Column(name = "source_channel", nullable = false, length = 24)
private String sourceChannel;
@Column(name = "client_ip_hash", length = 64)
private String clientIpHash;
@Lob
@Column(name = "changed_fields", columnDefinition = "MEDIUMTEXT")
private String changedFields;
@Lob
@Column(columnDefinition = "MEDIUMTEXT")
private String attributes;
@Column(name = "integrity_algorithm", nullable = false, length = 32)
private String integrityAlgorithm;
@Column(name = "integrity_key_id", nullable = false, length = 64)
private String integrityKeyId;
@Column(name = "integrity_hash", nullable = false, length = 64)
private String integrityHash;
}
@@ -0,0 +1,19 @@
package com.finance.system.audit;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/** The sole application write path for the immutable audit event table. */
@Component
public class AuditEventAppender {
@PersistenceContext
private EntityManager entityManager;
public void append(AuditEvent event) {
if (event == null || event.getId() != null) throw new IllegalArgumentException("AUDIT_APPEND_INVALID");
entityManager.persist(event);
entityManager.flush();
}
}
@@ -0,0 +1,39 @@
package com.finance.system.audit;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
import java.util.Map;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AuditEventCommand {
private String eventId;
private Integer schemaVersion;
private Instant eventTime;
private String tenantId;
private Long organizationId;
private String category;
private String action;
private String outcome;
private String reasonCode;
private String actorType;
private Long actorId;
private String targetType;
private String targetId;
private String resourceType;
private String resourceId;
private String requestId;
private String traceId;
private String spanId;
private String source;
private String clientIpHash;
private Map<String, Object> changes;
private Map<String, Object> attributes;
}
@@ -0,0 +1,154 @@
package com.finance.system.audit;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
@Component
public class AuditEventPolicy {
// Versioned deny-by-default audit schemas are enforced below.
static final int MAX_DEPTH = 5;
static final int MAX_NODES = 256;
static final int MAX_SERIALIZED_BYTES = 16 * 1024;
static final int MAX_STRING_LENGTH = 512;
private static final Pattern CODE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,119}");
private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}");
private static final Set<String> CATEGORIES = new HashSet<>(Arrays.asList(
"SECURITY", "ADMIN", "BUSINESS", "INTEGRATION"));
private static final Set<String> OUTCOMES = new HashSet<>(Arrays.asList(
"SUCCESS", "FAILURE", "DENIED", "UNKNOWN"));
private static final Set<String> ACTOR_TYPES = new HashSet<>(Arrays.asList(
"USER", "SYSTEM", "SERVICE", "ANONYMOUS"));
private static final Set<String> SOURCES = new HashSet<>(Arrays.asList(
"WEB", "JOB", "WEBHOOK", "OAUTH", "INTERNAL"));
private final ObjectMapper objectMapper;
private final AuditEventSchemaRegistry schemaRegistry;
public AuditEventPolicy() {
this(new ObjectMapper().findAndRegisterModules(),
Collections.<AuditEventSchemaContributor>emptyList());
}
@Autowired
public AuditEventPolicy(ObjectMapper objectMapper, List<AuditEventSchemaContributor> contributors) {
this.objectMapper = objectMapper;
this.schemaRegistry = new AuditEventSchemaRegistry(contributors);
}
public void validate(AuditEventCommand event) {
if (event == null) throw new IllegalArgumentException("audit event is required");
if (!StringUtils.hasText(event.getEventId()) || event.getEventId().length() > 32
|| !SAFE_ID.matcher(event.getEventId()).matches()) {
throw new IllegalArgumentException("invalid audit eventId");
}
if (!StringUtils.hasText(event.getTenantId()) || event.getTenantId().length() > 64
|| !SAFE_ID.matcher(event.getTenantId()).matches()) {
throw new IllegalArgumentException("invalid audit tenantId");
}
if (event.getOrganizationId() == null || event.getOrganizationId() <= 0) {
throw new IllegalArgumentException("invalid audit organizationId");
}
requireCode(event.getCategory(), "category");
requireCode(event.getAction(), "action");
requireCode(event.getOutcome(), "outcome");
requireCode(event.getActorType(), "actorType");
requireCode(event.getResourceType(), "resourceType");
requireId(event.getResourceId(), "resourceId");
requireCode(event.getSource(), "source");
optionalCode(event.getReasonCode(), "reasonCode");
optionalCode(event.getTargetType(), "targetType");
if (StringUtils.hasText(event.getTargetId())) requireId(event.getTargetId(), "targetId");
optionalId(event.getRequestId(), 64, "requestId");
optionalHex(event.getTraceId(), 32, "traceId");
optionalHex(event.getSpanId(), 16, "spanId");
optionalHex(event.getClientIpHash(), 64, "clientIpHash");
if (!CATEGORIES.contains(event.getCategory())) throw new IllegalArgumentException("invalid audit category");
if (!OUTCOMES.contains(event.getOutcome())) throw new IllegalArgumentException("invalid audit outcome");
if (!ACTOR_TYPES.contains(event.getActorType())) throw new IllegalArgumentException("invalid actor type");
if (!SOURCES.contains(event.getSource())) throw new IllegalArgumentException("invalid audit source");
validateComplexityAndSize(event);
schemaRegistry.validate(event);
}
private void validateComplexityAndSize(AuditEventCommand event) {
int[] nodes = {0};
validateValue(event.getChanges(), 0, nodes);
validateValue(event.getAttributes(), 0, nodes);
try {
if (objectMapper.writeValueAsBytes(event).length > MAX_SERIALIZED_BYTES)
throw new IllegalArgumentException("AUDIT_POLICY_PAYLOAD_BYTES");
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
throw new IllegalArgumentException("AUDIT_POLICY_PAYLOAD_SERIALIZATION", e);
}
}
private void validateValue(Object value, int depth, int[] nodes) {
if (depth > MAX_DEPTH) throw new IllegalArgumentException("AUDIT_POLICY_PAYLOAD_DEPTH");
if (++nodes[0] > MAX_NODES) throw new IllegalArgumentException("AUDIT_POLICY_PAYLOAD_NODES");
if (value == null || value instanceof Number || value instanceof Boolean) return;
if (value instanceof String) {
requireText((String) value, MAX_STRING_LENGTH, "attribute value");
return;
}
if (value instanceof Map) {
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
requireCode(String.valueOf(entry.getKey()), "attribute key");
validateValue(entry.getValue(), depth + 1, nodes);
}
return;
}
if (value instanceof Collection) {
Collection<?> collection = (Collection<?>) value;
for (Object element : collection) validateValue(element, depth + 1, nodes);
return;
}
throw new IllegalArgumentException("unsupported audit attribute type");
}
private static void requireCode(String value, String field) {
if (!StringUtils.hasText(value) || !CODE.matcher(value).matches()) {
throw new IllegalArgumentException("invalid audit " + field);
}
}
private static void requireText(String value, int max, String field) {
if (!StringUtils.hasText(value) || value.length() > max || value.chars().anyMatch(Character::isISOControl)) {
throw new IllegalArgumentException("invalid audit " + field);
}
}
private static void requireId(String value, String field) {
if (!StringUtils.hasText(value) || !SAFE_ID.matcher(value).matches()) {
throw new IllegalArgumentException("invalid audit " + field);
}
}
private static void optionalCode(String value, String field) {
if (StringUtils.hasText(value)) requireCode(value, field);
}
private static void optionalId(String value, int max, String field) {
if (StringUtils.hasText(value) && (value.length() > max || !SAFE_ID.matcher(value).matches())) {
throw new IllegalArgumentException("invalid audit " + field);
}
}
private static void optionalHex(String value, int length, String field) {
if (StringUtils.hasText(value) && !value.matches("[0-9a-fA-F]{" + length + "}")) {
throw new IllegalArgumentException("invalid audit " + field);
}
}
}
@@ -0,0 +1,14 @@
package com.finance.system.audit;
import org.springframework.data.repository.Repository;
import org.springframework.data.domain.Pageable;
import java.util.List;
/** Read-only repository surface; append is only available through AuditEventAppender. */
public interface AuditEventRepository extends Repository<AuditEvent, Long> {
boolean existsByEventUid(String eventUid);
List<AuditEvent> findByIdGreaterThanOrderByIdAsc(Long id, Pageable pageable);
}
@@ -0,0 +1,8 @@
package com.finance.system.audit;
import java.util.Collection;
/** Domain extension point. Duplicate schemas fail startup; unknown schemas fail validation. */
public interface AuditEventSchemaContributor {
Collection<AuditEventSchemaRegistry.Schema> schemas();
}
@@ -0,0 +1,158 @@
package com.finance.system.audit;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/** Explicit category/action/version and field schemas. There is no wildcard schema. */
public final class AuditEventSchemaRegistry {
private static final Pattern CODE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,119}");
private final Map<String, Schema> schemas = new LinkedHashMap<>();
public AuditEventSchemaRegistry(Collection<AuditEventSchemaContributor> contributors) {
builtIns();
if (contributors != null) for (AuditEventSchemaContributor contributor : contributors) {
if (contributor != null && contributor.schemas() != null)
for (Schema schema : contributor.schemas()) register(schema);
}
}
public void validate(AuditEventCommand event) {
int version = event.getSchemaVersion() == null ? 1 : event.getSchemaVersion();
Schema schema = schemas.get(key(event.getCategory(), event.getAction(), version));
if (schema == null) throw new IllegalArgumentException("AUDIT_POLICY_SCHEMA_NOT_REGISTERED");
validateFields(event.getChanges(), schema.changes, "CHANGES");
validateFields(event.getAttributes(), schema.attributes, "ATTRIBUTES");
}
private void validateFields(Map<String, Object> values, Map<String, Rule> rules, String location) {
Map<String, Object> actual = values == null ? Collections.<String, Object>emptyMap() : values;
for (Map.Entry<String, Object> entry : actual.entrySet()) {
Rule rule = rules.get(entry.getKey());
if (rule == null) throw new IllegalArgumentException("AUDIT_POLICY_UNKNOWN_" + location + "_FIELD");
rule.validate(entry.getValue());
}
for (Map.Entry<String, Rule> entry : rules.entrySet()) {
if (entry.getValue().required && !actual.containsKey(entry.getKey()))
throw new IllegalArgumentException("AUDIT_POLICY_MISSING_" + location + "_FIELD");
}
}
private void builtIns() {
register(schema("ADMIN", "iam.role.create", 1, none(), fields("roleCode", code(80))));
register(schema("ADMIN", "iam.role.update", 1, none(), fields("roleCode", code(80))));
register(schema("ADMIN", "iam.role.delete", 1, none(), fields("roleCode", code(80))));
register(schema("ADMIN", "iam.role.permission.update", 1, none(),
fields("roleCode", code(80), "policyCount", integer(0, 10000))));
register(schema("ADMIN", "iam.group.create", 1, none(), fields("groupCode", code(80))));
register(schema("ADMIN", "iam.group.update", 1, none(), fields("groupCode", code(80))));
register(schema("ADMIN", "iam.group.delete", 1, none(), fields("groupCode", code(80))));
register(schema("ADMIN", "iam.group.role.update", 1, none(), fields("roleCount", integer(0, 10000))));
register(schema("ADMIN", "iam.group.member.update", 1, none(), fields("memberCount", integer(0, 5000))));
register(schema("ADMIN", "iam.user.status.update", 1, none(),
fields("statusCode", enumeration("ACTIVE", "INACTIVE"))));
register(schema("ADMIN", "rbac.role.permissions.changed", 1,
fields("permissionCodes", codeList(1000, 120)), none()));
}
private void register(Schema schema) {
String key = key(schema.category, schema.action, schema.version);
if (schemas.putIfAbsent(key, schema) != null)
throw new IllegalStateException("AUDIT_SCHEMA_DUPLICATE:" + schema.action);
}
private static String key(String category, String action, int version) {
return category + "\u0000" + action + "\u0000" + version;
}
public static Schema schema(String category, String action, int version,
Map<String, Rule> changes, Map<String, Rule> attributes) {
return new Schema(category, action, version, changes, attributes);
}
public static Map<String, Rule> none() { return Collections.emptyMap(); }
public static Map<String, Rule> fields(Object... pairs) {
if (pairs.length % 2 != 0) throw new IllegalArgumentException("AUDIT_SCHEMA_FIELD_PAIRS");
Map<String, Rule> result = new LinkedHashMap<>();
for (int i = 0; i < pairs.length; i += 2) result.put(String.valueOf(pairs[i]), (Rule) pairs[i + 1]);
return Collections.unmodifiableMap(result);
}
public static Rule code(int maxLength) {
return new Rule(false, value -> {
if (!(value instanceof String) || ((String) value).length() > maxLength
|| !CODE.matcher((String) value).matches()) invalid("FIELD_CODE");
});
}
public static Rule integer(long min, long max) {
return new Rule(false, value -> {
if (!(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long))
invalid("FIELD_INTEGER");
long number = ((Number) value).longValue();
if (number < min || number > max) invalid("FIELD_INTEGER_RANGE");
});
}
public static Rule enumeration(String... allowed) {
List<String> values = Arrays.asList(allowed);
return new Rule(false, value -> {
if (!(value instanceof String) || !values.contains(value)) invalid("FIELD_ENUM");
});
}
public static Rule flag() {
return new Rule(false, value -> {
if (!(value instanceof Boolean)) invalid("FIELD_BOOLEAN");
});
}
public static Rule codeList(int maxItems, int maxLength) {
return new Rule(false, value -> {
if (!(value instanceof Collection)) invalid("FIELD_CODE_LIST");
Collection<?> list = (Collection<?>) value;
if (list.size() > maxItems) invalid("FIELD_CODE_LIST_SIZE");
for (Object item : list) if (!(item instanceof String) || ((String) item).length() > maxLength
|| !CODE.matcher((String) item).matches()) invalid("FIELD_CODE_LIST_ITEM");
});
}
private static void invalid(String code) { throw new IllegalArgumentException("AUDIT_POLICY_" + code); }
public static final class Schema {
private final String category;
private final String action;
private final int version;
private final Map<String, Rule> changes;
private final Map<String, Rule> attributes;
private Schema(String category, String action, int version,
Map<String, Rule> changes, Map<String, Rule> attributes) {
this.category = category;
this.action = action;
this.version = version;
this.changes = changes == null ? none() : changes;
this.attributes = attributes == null ? none() : attributes;
}
}
public static final class Rule {
private final boolean required;
private final Validator validator;
private Rule(boolean required, Validator validator) {
this.required = required;
this.validator = validator;
}
public Rule required() { return new Rule(true, validator); }
private void validate(Object value) { validator.validate(value); }
}
private interface Validator { void validate(Object value); }
}
@@ -0,0 +1,118 @@
package com.finance.system.audit;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.RequiredArgsConstructor;
import com.finance.system.security.UserPrincipal;
import com.finance.system.util.AuditUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Collections;
import java.util.UUID;
@Service
public class AuditEventService implements AuditPort {
private final AuditOutboxRepository outboxRepository;
private final AuditEventPolicy policy;
private final ObjectMapper objectMapper;
private final String systemTenantId;
private final Long systemOrganizationId;
@Autowired
public AuditEventService(AuditOutboxRepository outboxRepository, AuditEventPolicy policy,
ObjectMapper objectMapper,
@Value("${observability.tenant-id:default}") String systemTenantId,
@Value("${observability.organization-id:1}") Long systemOrganizationId) {
this.outboxRepository = outboxRepository;
this.policy = policy;
this.objectMapper = objectMapper;
this.systemTenantId = systemTenantId;
this.systemOrganizationId = systemOrganizationId;
}
public AuditEventService(AuditOutboxRepository outboxRepository, AuditEventPolicy policy,
ObjectMapper objectMapper) {
this(outboxRepository, policy, objectMapper, "default", 1L);
}
@Override
@Transactional
public String emit(AuditEventCommand event) {
normalize(event);
policy.validate(event);
String payload;
try {
payload = objectMapper.writer().with(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)
.writeValueAsString(event);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("audit event cannot be serialized", e);
}
String payloadHash = sha256(payload);
LocalDateTime now = utcNow();
// MySQL's unique event_uid and atomic INSERT .. ON DUPLICATE KEY remove
// the exists+save race. This statement participates in the caller's
// transaction; a business rollback also removes the outbox row.
outboxRepository.insertIfAbsent(event.getEventId(), event.getResourceType(),
event.getResourceId(), event.getAction(), payload, payloadHash, now);
AuditOutbox stored = outboxRepository.findByEventUidForUpdate(event.getEventId())
.orElseThrow(() -> new IllegalStateException("AUDIT_OUTBOX_WRITE_LOST"));
if (!payloadHash.equals(stored.getPayloadHash()) || !payload.equals(stored.getEventPayload())) {
throw new IllegalStateException("AUDIT_EVENT_ID_COLLISION");
}
return event.getEventId();
}
private void normalize(AuditEventCommand event) {
if (event == null) return;
if (!StringUtils.hasText(event.getEventId())) {
event.setEventId(UUID.randomUUID().toString().replace("-", ""));
}
if (event.getSchemaVersion() == null) event.setSchemaVersion(1);
if (event.getEventTime() == null) event.setEventTime(Instant.now());
UserPrincipal principal = AuditUtil.getCurrentUser();
if (principal != null) {
if (!StringUtils.hasText(principal.getTenantId()) || principal.getOrganizationId() == null
|| principal.getOrganizationId() <= 0) {
throw new IllegalArgumentException("AUDIT_TRUSTED_CONTEXT_REQUIRED");
}
event.setTenantId(principal.getTenantId());
event.setOrganizationId(principal.getOrganizationId());
} else {
if (!StringUtils.hasText(systemTenantId) || systemOrganizationId == null
|| systemOrganizationId <= 0) {
throw new IllegalArgumentException("AUDIT_SYSTEM_CONTEXT_REQUIRED");
}
event.setTenantId(systemTenantId);
event.setOrganizationId(systemOrganizationId);
}
if (event.getChanges() == null) event.setChanges(Collections.emptyMap());
if (event.getAttributes() == null) event.setAttributes(Collections.emptyMap());
}
static LocalDateTime utcNow() {
return LocalDateTime.now(ZoneOffset.UTC);
}
static String sha256(String value) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder(64);
for (byte current : digest) result.append(String.format("%02x", current & 0xff));
return result.toString();
} catch (Exception e) {
throw new IllegalStateException("AUDIT_HASH_UNAVAILABLE", e);
}
}
}
@@ -0,0 +1,27 @@
package com.finance.system.audit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.UUID;
@Component
public class AuditInstanceIdentity {
private final String instanceId;
public AuditInstanceIdentity(@Value("${observability.audit.instance-id:}") String configuredId) {
String prefix = StringUtils.hasText(configuredId)
? configuredId.replaceAll("[^A-Za-z0-9._-]", "_") : "audit";
if (prefix.length() > 24) prefix = prefix.substring(0, 24);
this.instanceId = prefix + "-" + UUID.randomUUID().toString().replace("-", "");
}
public String getInstanceId() {
return instanceId;
}
public String newClaimOwner() {
return instanceId + "-" + UUID.randomUUID().toString().replace("-", "").substring(0, 6);
}
}
@@ -0,0 +1,200 @@
package com.finance.system.audit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "observability.audit.integrity")
public class AuditIntegrityProperties {
static final String LOCAL_DEVELOPMENT_KEY_ID = "local-development";
private static final String LOCAL_DEVELOPMENT_KEY =
"finance-system-local-audit-integrity-key-v1";
private String currentKeyId;
private String currentKey;
private Map<String, String> historicalKeys = new LinkedHashMap<>();
private String historicalKeysSpec;
private boolean verificationEnabled = true;
private long verificationDelayMs = 300000L;
private long verificationInitialDelayMs = 60000L;
private int verificationBatchSize = 200;
private Environment environment;
@Autowired
void setEnvironment(Environment environment) {
this.environment = environment;
}
public Map<String, String> resolvedKeys() {
return resolvedKeySet().keys;
}
ResolvedKeySet resolvedKeySet() {
CurrentKey resolvedCurrent = resolvedCurrentKey();
Map<String, String> result = new LinkedHashMap<>();
if (historicalKeys != null) result.putAll(historicalKeys);
if (StringUtils.hasText(historicalKeysSpec)) {
for (String entry : historicalKeysSpec.split(";")) {
if (!StringUtils.hasText(entry)) continue;
int split = entry.indexOf('=');
if (split <= 0 || split == entry.length() - 1) {
throw new IllegalStateException("AUDIT_HISTORICAL_KEY_SPEC_INVALID");
}
putUnique(result, entry.substring(0, split).trim(), entry.substring(split + 1));
}
}
for (Map.Entry<String, String> entry : result.entrySet()) {
validateKeyId(entry.getKey());
validateKey(entry.getValue());
}
putUnique(result, resolvedCurrent.keyId, resolvedCurrent.key);
if (verificationBatchSize < 1 || verificationBatchSize > 10000) {
throw new IllegalStateException("AUDIT_VERIFICATION_BATCH_SIZE_INVALID");
}
return new ResolvedKeySet(resolvedCurrent.keyId, resolvedCurrent.key,
Collections.unmodifiableMap(result));
}
private CurrentKey resolvedCurrentKey() {
boolean hasKeyId = StringUtils.hasText(currentKeyId);
boolean hasKey = StringUtils.hasText(currentKey);
if (!hasKeyId && !hasKey) {
if (hasLocalProfile()) {
return new CurrentKey(LOCAL_DEVELOPMENT_KEY_ID, LOCAL_DEVELOPMENT_KEY);
}
throw new IllegalStateException("AUDIT_INTEGRITY_CURRENT_KEY_PAIR_REQUIRED");
}
if (!hasKeyId) {
throw new IllegalStateException("AUDIT_INTEGRITY_CURRENT_KEY_ID_REQUIRED");
}
if (!hasKey) {
throw new IllegalStateException("AUDIT_INTEGRITY_CURRENT_KEY_REQUIRED");
}
validateKeyId(currentKeyId);
validateKey(currentKey);
return new CurrentKey(currentKeyId, currentKey);
}
private boolean hasLocalProfile() {
if (environment == null) return false;
String[] activeProfiles = environment.getActiveProfiles();
if (activeProfiles.length == 0) return false;
for (String profile : activeProfiles) {
if (!"local".equalsIgnoreCase(profile)) return false;
}
return true;
}
private static void putUnique(Map<String, String> keys, String keyId, String key) {
String existing = keys.putIfAbsent(keyId, key);
if (existing != null && !existing.equals(key)) {
throw new IllegalStateException("AUDIT_KEY_ID_COLLISION:" + keyId);
}
}
private static void validateKeyId(String keyId) {
if (!StringUtils.hasText(keyId) || !keyId.matches("[A-Za-z0-9._-]{1,64}")) {
throw new IllegalStateException("AUDIT_INTEGRITY_CURRENT_KEY_ID_INVALID");
}
}
private static void validateKey(String key) {
if (!StringUtils.hasText(key) || key.getBytes(StandardCharsets.UTF_8).length < 32) {
throw new IllegalStateException("AUDIT_INTEGRITY_KEY_MUST_HAVE_32_BYTES");
}
}
private static final class CurrentKey {
private final String keyId;
private final String key;
private CurrentKey(String keyId, String key) {
this.keyId = keyId;
this.key = key;
}
}
static final class ResolvedKeySet {
final String currentKeyId;
final String currentKey;
final Map<String, String> keys;
private ResolvedKeySet(String currentKeyId, String currentKey, Map<String, String> keys) {
this.currentKeyId = currentKeyId;
this.currentKey = currentKey;
this.keys = keys;
}
}
public String getCurrentKeyId() {
return currentKeyId;
}
public void setCurrentKeyId(String currentKeyId) {
this.currentKeyId = currentKeyId;
}
public String getCurrentKey() {
return currentKey;
}
public void setCurrentKey(String currentKey) {
this.currentKey = currentKey;
}
public Map<String, String> getHistoricalKeys() {
return historicalKeys;
}
public void setHistoricalKeys(Map<String, String> historicalKeys) {
this.historicalKeys = historicalKeys;
}
public String getHistoricalKeysSpec() {
return historicalKeysSpec;
}
public void setHistoricalKeysSpec(String historicalKeysSpec) {
this.historicalKeysSpec = historicalKeysSpec;
}
public boolean isVerificationEnabled() {
return verificationEnabled;
}
public void setVerificationEnabled(boolean verificationEnabled) {
this.verificationEnabled = verificationEnabled;
}
public long getVerificationDelayMs() {
return verificationDelayMs;
}
public void setVerificationDelayMs(long verificationDelayMs) {
this.verificationDelayMs = verificationDelayMs;
}
public long getVerificationInitialDelayMs() {
return verificationInitialDelayMs;
}
public void setVerificationInitialDelayMs(long verificationInitialDelayMs) {
this.verificationInitialDelayMs = verificationInitialDelayMs;
}
public int getVerificationBatchSize() {
return verificationBatchSize;
}
public void setVerificationBatchSize(int verificationBatchSize) {
this.verificationBatchSize = verificationBatchSize;
}
}
@@ -0,0 +1,19 @@
package com.finance.system.audit;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
@Service
@RequiredArgsConstructor
public class AuditIntegrityScanLeaseService {
private final AuditIntegrityScanStateRepository repository;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public boolean claim(String owner, LocalDateTime now, LocalDateTime leaseUntil) {
return repository.claimLease(AuditIntegrityVerifier.SCAN_NAME, owner, now, leaseUntil) == 1;
}
}
@@ -0,0 +1,38 @@
package com.finance.system.audit;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "sys_audit_integrity_scan_state")
public class AuditIntegrityScanState {
@Id
@Column(name = "scan_name", length = 64)
private String scanName;
@Column(name = "cursor_id", nullable = false)
private Long cursorId;
@Column(name = "lease_owner", length = 64)
private String leaseOwner;
@Column(name = "lease_until")
private LocalDateTime leaseUntil;
@Column(name = "current_cycle_failures", nullable = false)
private Long currentCycleFailures;
@Column(name = "last_cycle_failures", nullable = false)
private Long lastCycleFailures;
@Column(name = "last_scan_at")
private LocalDateTime lastScanAt;
@Column(name = "last_completed_at")
private LocalDateTime lastCompletedAt;
@Column(name = "last_failure_at")
private LocalDateTime lastFailureAt;
@Column(name = "last_failure_event_id")
private Long lastFailureEventId;
@Column(name = "updated_at", nullable = false)
private LocalDateTime updatedAt;
}
@@ -0,0 +1,23 @@
package com.finance.system.audit;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import javax.persistence.LockModeType;
import java.time.LocalDateTime;
import java.util.Optional;
public interface AuditIntegrityScanStateRepository extends JpaRepository<AuditIntegrityScanState, String> {
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query(value = "update sys_audit_integrity_scan_state set lease_owner=:owner,lease_until=:leaseUntil,updated_at=:now "
+ "where scan_name=:scanName and (lease_until is null or lease_until<:now or lease_owner=:owner)", nativeQuery = true)
int claimLease(@Param("scanName") String scanName, @Param("owner") String owner,
@Param("now") LocalDateTime now, @Param("leaseUntil") LocalDateTime leaseUntil);
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select s from AuditIntegrityScanState s where s.scanName=:scanName")
Optional<AuditIntegrityScanState> findByScanNameForUpdate(@Param("scanName") String scanName);
}
@@ -0,0 +1,147 @@
package com.finance.system.audit;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
/** Keyed integrity tag over every immutable event column except the tag itself. */
@Component
public class AuditIntegrityService {
public static final String PERSISTED_ALGORITHM = "HMAC-SHA256";
public static final String LEGACY_UNVERIFIABLE_ALGORITHM = "LEGACY-HMAC-SHA256";
public static final String LEGACY_UNVERIFIABLE_KEY_ID = "legacy-unverifiable";
private static final String JCA_ALGORITHM = "HmacSHA256";
private static final DateTimeFormatter MICROSECOND_TIME =
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS");
private final AuditIntegrityProperties properties;
private volatile ResolvedIntegrityKeys resolved;
public AuditIntegrityService(AuditIntegrityProperties properties) {
this.properties = properties;
}
@PostConstruct
synchronized void validateKey() {
if (resolved != null) return;
AuditIntegrityProperties.ResolvedKeySet resolvedProperties = properties.resolvedKeySet();
resolved = new ResolvedIntegrityKeys(resolvedProperties.currentKeyId,
resolvedProperties.currentKey, resolvedProperties.keys);
}
public String sign(AuditEvent event) {
ResolvedIntegrityKeys activeKeys = activeKeys();
event.setOccurredAt(normalizeToMicros(event.getOccurredAt()));
event.setRecordedAt(normalizeToMicros(event.getRecordedAt()));
event.setIntegrityAlgorithm(PERSISTED_ALGORITHM);
event.setIntegrityKeyId(activeKeys.currentKeyId);
return calculate(event, activeKeys.currentKey);
}
/** Constant-time tag verification; unknown key ids and algorithms fail closed. */
public boolean verify(AuditEvent event) {
if (event == null || !PERSISTED_ALGORITHM.equals(event.getIntegrityAlgorithm())) return false;
String key = activeKeys().keys.get(event.getIntegrityKeyId());
if (key == null) return false;
try {
byte[] actual = decodeHex(event.getIntegrityHash());
byte[] expected = decodeHex(calculate(event, key));
return actual != null && MessageDigest.isEqual(expected, actual);
} catch (RuntimeException e) {
return false;
}
}
public static LocalDateTime normalizeToMicros(LocalDateTime value) {
if (value == null) return null;
return value.withNano((value.getNano() / 1000) * 1000);
}
private String calculate(AuditEvent event, String key) {
try {
Mac mac = Mac.getInstance(JCA_ALGORITHM);
mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), JCA_ALGORITHM));
append(mac, event.getIntegrityAlgorithm());
append(mac, event.getIntegrityKeyId());
append(mac, event.getEventUid());
append(mac, event.getSchemaVersion());
append(mac, event.getOccurredAt());
append(mac, event.getRecordedAt());
append(mac, event.getTenantId());
// Pre-organization legacy rows remain verifiable with their original
// tag. New rows always have an organization and bind it into the HMAC.
if (event.getOrganizationId() != null) append(mac, event.getOrganizationId());
append(mac, event.getCategory());
append(mac, event.getActionCode());
append(mac, event.getOutcome());
append(mac, event.getReasonCode());
append(mac, event.getActorType());
append(mac, event.getActorId());
append(mac, event.getTargetType());
append(mac, event.getTargetId());
append(mac, event.getResourceType());
append(mac, event.getResourceId());
append(mac, event.getRequestId());
append(mac, event.getTraceId());
append(mac, event.getSpanId());
append(mac, event.getSourceChannel());
append(mac, event.getClientIpHash());
append(mac, event.getChangedFields());
append(mac, event.getAttributes());
byte[] digest = mac.doFinal();
StringBuilder result = new StringBuilder(64);
for (byte current : digest) result.append(String.format("%02x", current & 0xff));
return result.toString();
} catch (Exception e) {
throw new IllegalStateException("AUDIT_HMAC_UNAVAILABLE", e);
}
}
private static void append(Mac mac, Object value) {
String text = value == null ? "" : value instanceof LocalDateTime
? MICROSECOND_TIME.format(normalizeToMicros((LocalDateTime) value)) : String.valueOf(value);
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
mac.update((byte) ((bytes.length >>> 24) & 0xff));
mac.update((byte) ((bytes.length >>> 16) & 0xff));
mac.update((byte) ((bytes.length >>> 8) & 0xff));
mac.update((byte) (bytes.length & 0xff));
mac.update(bytes);
}
private static byte[] decodeHex(String value) {
if (value == null || value.length() != 64) return null;
byte[] result = new byte[32];
for (int i = 0; i < result.length; i++) {
int high = Character.digit(value.charAt(i * 2), 16);
int low = Character.digit(value.charAt(i * 2 + 1), 16);
if (high < 0 || low < 0) return null;
result[i] = (byte) ((high << 4) | low);
}
return result;
}
private ResolvedIntegrityKeys activeKeys() {
ResolvedIntegrityKeys activeKeys = resolved;
if (activeKeys == null) throw new IllegalStateException("AUDIT_INTEGRITY_NOT_INITIALIZED");
return activeKeys;
}
private static final class ResolvedIntegrityKeys {
private final String currentKeyId;
private final String currentKey;
private final Map<String, String> keys;
private ResolvedIntegrityKeys(String currentKeyId, String currentKey,
Map<String, String> keys) {
this.currentKeyId = currentKeyId;
this.currentKey = currentKey;
this.keys = keys;
}
}
}
@@ -0,0 +1,131 @@
package com.finance.system.audit;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
/** Incremental scheduled integrity verification with bounded batches. */
@Component
@Slf4j
public class AuditIntegrityVerifier {
static final String SCAN_NAME = "PRIMARY";
private final AuditEventRepository repository;
private final AuditIntegrityScanStateRepository scanStates;
private final AuditIntegrityScanLeaseService scanLease;
private final AuditIntegrityService integrityService;
private final AuditIntegrityProperties properties;
private final AuditReliabilityProperties reliabilityProperties;
private final AuditInstanceIdentity identity;
private final Counter verifiedCounter;
private final Counter failureCounter;
private final Counter legacyCounter;
private final Counter cycleCounter;
private final Counter contentionCounter;
public AuditIntegrityVerifier(AuditEventRepository repository,
AuditIntegrityScanStateRepository scanStates,
AuditIntegrityScanLeaseService scanLease,
AuditIntegrityService integrityService,
AuditIntegrityProperties properties,
AuditReliabilityProperties reliabilityProperties,
AuditInstanceIdentity identity,
MeterRegistry meterRegistry) {
this.repository = repository;
this.scanStates = scanStates;
this.scanLease = scanLease;
this.integrityService = integrityService;
this.properties = properties;
this.reliabilityProperties = reliabilityProperties;
this.identity = identity;
this.verifiedCounter = Counter.builder("audit.integrity.verified")
.description("Audit events with a valid HMAC tag").register(meterRegistry);
this.failureCounter = Counter.builder("audit.integrity.failures")
.description("Audit events failing integrity verification").register(meterRegistry);
this.legacyCounter = Counter.builder("audit.integrity.legacy_unverifiable")
.description("Pre-remediation audit events that cannot be cryptographically reverified")
.register(meterRegistry);
this.cycleCounter = Counter.builder("audit.integrity.scan.cycles")
.description("Completed full audit-integrity scan cycles").register(meterRegistry);
this.contentionCounter = Counter.builder("audit.integrity.scan.lease.contention")
.description("Integrity scan attempts blocked by another instance lease").register(meterRegistry);
}
@Scheduled(fixedDelayString = "${observability.audit.integrity.verification-delay-ms:300000}",
initialDelayString = "${observability.audit.integrity.verification-initial-delay-ms:60000}")
@Transactional
public void verifyBatch() {
if (!properties.isVerificationEnabled()) return;
LocalDateTime now = AuditEventService.utcNow();
String owner = identity.getInstanceId();
if (!scanLease.claim(owner, now, now.plusSeconds(reliabilityProperties.boundedIntegrityScanLeaseSeconds()))) {
contentionCounter.increment();
return;
}
AuditIntegrityScanState state = scanStates.findByScanNameForUpdate(SCAN_NAME)
.orElseThrow(() -> new IllegalStateException("AUDIT_INTEGRITY_SCAN_STATE_MISSING"));
if (!owner.equals(state.getLeaseOwner()) || state.getLeaseUntil() == null || !state.getLeaseUntil().isAfter(now)) {
contentionCounter.increment();
return;
}
long cursor = state.getCursorId() == null ? 0L : state.getCursorId();
List<AuditEvent> events = repository.findByIdGreaterThanOrderByIdAsc(cursor,
PageRequest.of(0, properties.getVerificationBatchSize()));
state.setLastScanAt(now);
if (events.isEmpty()) {
completeCycle(state, now);
return;
}
for (AuditEvent event : events) {
state.setCursorId(event.getId());
if (isLegacyUnverifiable(event)) {
legacyCounter.increment();
log.warn("历史审计记录无法验证完整性 AUDIT_INTEGRITY_LEGACY_UNVERIFIABLE eventId={}", event.getId());
} else if (integrityService.verify(event)) {
verifiedCounter.increment();
} else {
failureCounter.increment();
state.setCurrentCycleFailures(value(state.getCurrentCycleFailures()) + 1L);
state.setLastFailureAt(now);
state.setLastFailureEventId(event.getId());
log.error("审计完整性验证失败 AUDIT_INTEGRITY_VERIFICATION_FAILED eventId={} algorithm={} keyId={}",
event.getId(), event.getIntegrityAlgorithm(), event.getIntegrityKeyId());
}
}
if (events.size() < properties.getVerificationBatchSize()) {
completeCycle(state, now);
} else {
release(state, now);
}
}
private void completeCycle(AuditIntegrityScanState state, LocalDateTime now) {
state.setCursorId(0L);
state.setLastCycleFailures(value(state.getCurrentCycleFailures()));
state.setCurrentCycleFailures(0L);
state.setLastCompletedAt(now);
release(state, now);
cycleCounter.increment();
}
private void release(AuditIntegrityScanState state, LocalDateTime now) {
state.setLeaseOwner(null);
state.setLeaseUntil(null);
state.setUpdatedAt(now);
}
private static long value(Long value) {
return value == null ? 0L : value;
}
private boolean isLegacyUnverifiable(AuditEvent event) {
return AuditIntegrityService.LEGACY_UNVERIFIABLE_ALGORITHM.equals(event.getIntegrityAlgorithm())
&& AuditIntegrityService.LEGACY_UNVERIFIABLE_KEY_ID.equals(event.getIntegrityKeyId());
}
}
@@ -0,0 +1,71 @@
package com.finance.system.audit;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "sys_audit_outbox")
public class AuditOutbox {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "event_uid", nullable = false, unique = true, length = 32)
private String eventUid;
@Column(name = "aggregate_type", nullable = false, length = 64)
private String aggregateType;
@Column(name = "aggregate_id", nullable = false, length = 128)
private String aggregateId;
@Column(name = "action_code", nullable = false, length = 120)
private String actionCode;
@Lob
@Column(name = "event_payload", nullable = false, columnDefinition = "MEDIUMTEXT")
private String eventPayload;
@Column(name = "payload_hash", nullable = false, length = 64)
private String payloadHash;
@Column(nullable = false, length = 16)
private String status;
@Column(name = "available_at", nullable = false)
private LocalDateTime availableAt;
@Column(name = "attempt_count", nullable = false)
private Integer attemptCount;
@Column(name = "lease_owner", length = 64)
private String leaseOwner;
@Column(name = "lease_until")
private LocalDateTime leaseUntil;
@Column(name = "last_error_code", length = 80)
private String lastErrorCode;
@Column(name = "created_at", nullable = false)
private LocalDateTime createdAt;
@Column(name = "published_at")
private LocalDateTime publishedAt;
}
@@ -0,0 +1,23 @@
package com.finance.system.audit;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
@Service
@RequiredArgsConstructor
public class AuditOutboxClaimService {
private final AuditOutboxRepository repository;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public List<Long> claim(String owner, LocalDateTime now, LocalDateTime leaseUntil, int limit) {
int boundedLimit = Math.max(1, Math.min(limit, 200));
repository.claimReady(owner, now, leaseUntil, boundedLimit);
return repository.findClaimedIds(owner, now, PageRequest.of(0, boundedLimit));
}
}
@@ -0,0 +1,47 @@
package com.finance.system.audit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "observability.audit", name = "dispatch-enabled", havingValue = "true", matchIfMissing = true)
public class AuditOutboxDispatcher {
private final AuditOutboxRepository outboxRepository;
private final AuditOutboxClaimService claimService;
private final AuditDeliveryService deliveryService;
private final AuditInstanceIdentity instanceIdentity;
private final AuditReliabilityProperties reliabilityProperties;
private final AuditReliabilityMetrics metrics;
@org.springframework.beans.factory.annotation.Value("${observability.audit.dispatch-batch-size:50}")
private int batchSize;
@Scheduled(fixedDelayString = "${observability.audit.dispatch-delay-ms:1000}")
public void dispatch() {
LocalDateTime now = AuditEventService.utcNow();
String owner = instanceIdentity.newClaimOwner();
List<Long> ids = claimService.claim(owner, now,
now.plusSeconds(reliabilityProperties.boundedOutboxLeaseSeconds()), batchSize);
if (ids.isEmpty() && outboxRepository.countReady(now) > 0) metrics.recordClaimContention();
for (Long id : ids) {
long started = System.nanoTime();
try {
if (deliveryService.deliver(id, owner)) metrics.recordDeliverySuccess(Duration.ofNanos(System.nanoTime() - started));
else metrics.recordClaimContention();
} catch (Exception failure) {
log.warn("审计事件投递失败 event=audit.delivery.failed outboxId={} errorCode=AUDIT_DELIVERY_FAILED", id);
metrics.recordDeliveryFailure(Duration.ofNanos(System.nanoTime() - started));
if (!deliveryService.markFailure(id, owner, "AUDIT_DELIVERY_FAILED")) metrics.recordClaimContention();
}
}
}
}
@@ -0,0 +1,56 @@
package com.finance.system.audit;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import javax.persistence.LockModeType;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
public interface AuditOutboxRepository extends JpaRepository<AuditOutbox, Long> {
@Modifying
@Query(value = "insert into sys_audit_outbox "
+ "(event_uid,aggregate_type,aggregate_id,action_code,event_payload,payload_hash,status,"
+ "available_at,attempt_count,created_at) values "
+ "(:eventUid,:aggregateType,:aggregateId,:actionCode,:payload,:payloadHash,'PENDING',:now,0,:now) "
+ "on duplicate key update id=id", nativeQuery = true)
int insertIfAbsent(@Param("eventUid") String eventUid,
@Param("aggregateType") String aggregateType,
@Param("aggregateId") String aggregateId,
@Param("actionCode") String actionCode,
@Param("payload") String payload,
@Param("payloadHash") String payloadHash,
@Param("now") LocalDateTime now);
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select o from AuditOutbox o where o.eventUid = :eventUid")
Optional<AuditOutbox> findByEventUidForUpdate(@Param("eventUid") String eventUid);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query(value = "update sys_audit_outbox set lease_owner=:owner, lease_until=:leaseUntil "
+ "where status='PENDING' and available_at<=:now "
+ "and (lease_until is null or lease_until<:now) order by available_at,id limit :limit", nativeQuery = true)
int claimReady(@Param("owner") String owner, @Param("now") LocalDateTime now,
@Param("leaseUntil") LocalDateTime leaseUntil, @Param("limit") int limit);
@Query("select o.id from AuditOutbox o where o.status = 'PENDING' and o.leaseOwner = :owner "
+ "and o.leaseUntil > :now order by o.availableAt, o.id")
List<Long> findClaimedIds(@Param("owner") String owner, @Param("now") LocalDateTime now, Pageable pageable);
@Query("select count(o) from AuditOutbox o where o.status = 'PENDING' and o.availableAt <= :now")
long countReady(@Param("now") LocalDateTime now);
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select o from AuditOutbox o where o.id = :id")
Optional<AuditOutbox> findByIdForUpdate(@Param("id") Long id);
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select o from AuditOutbox o where o.id = :id and o.leaseOwner = :owner")
Optional<AuditOutbox> findOwnedByIdForUpdate(@Param("id") Long id, @Param("owner") String owner);
}
@@ -0,0 +1,10 @@
package com.finance.system.audit;
public interface AuditPort {
/**
* Adds an immutable audit event to the transactional outbox. Supplying the
* same eventId more than once is idempotent.
*/
String emit(AuditEventCommand event);
}
@@ -0,0 +1,60 @@
package com.finance.system.audit;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component("auditReliabilityHealthIndicator")
@RequiredArgsConstructor
public class AuditReliabilityHealthIndicator implements HealthIndicator {
private final AuditReliabilitySnapshotProvider snapshots;
private final AuditReliabilityProperties properties;
@Override
public Health health() {
try {
AuditReliabilitySnapshot snapshot = snapshots.snapshot();
String reason = reason(snapshot);
Health.Builder builder = reason == null ? Health.up() : Health.outOfService();
return builder.withDetail("reasonCode", reason == null ? "AUDIT_RELIABILITY_OK" : reason)
.withDetail("pendingCount", snapshot.getPendingCount())
.withDetail("deadCount", snapshot.getDeadCount())
.withDetail("oldestPendingAgeSeconds", snapshot.getOldestPendingAgeSeconds())
.withDetail("pendingTimestampInvalid", snapshot.isPendingTimestampInvalid())
.withDetail("integrityScanAgeSeconds", snapshot.getIntegrityScanAgeSeconds())
.withDetail("integrityScanMissing", snapshot.isIntegrityScanMissing())
.withDetail("integrityScanTimestampInvalid", snapshot.isIntegrityScanTimestampInvalid())
.withDetail("integrityFailureCount", snapshot.getIntegrityFailureCount()).build();
} catch (RuntimeException ex) {
return Health.down().withDetail("reasonCode", "AUDIT_RELIABILITY_PROBE_FAILED").build();
}
}
private String reason(AuditReliabilitySnapshot snapshot) {
if (snapshot.getDeadCount() > properties.getMaxDeadCount()) return "AUDIT_OUTBOX_DEAD_THRESHOLD";
if (snapshot.getPendingCount() > 0
&& (snapshot.isPendingTimestampInvalid() || snapshot.getOldestPendingAgeSeconds() < 0L)) {
return "AUDIT_OUTBOX_PENDING_TIME_INVALID";
}
if (snapshot.getPendingCount() > 0
&& (snapshot.isPendingAgeThresholdExceeded()
|| snapshot.getOldestPendingAgeSeconds() > properties.getMaxPendingAgeSeconds())) {
return "AUDIT_OUTBOX_PENDING_AGE_THRESHOLD";
}
if (properties.isFailOnIntegrityFailure() && snapshot.getIntegrityFailureCount() > 0) {
return "AUDIT_INTEGRITY_FAILURE";
}
if (snapshot.isIntegrityScanMissing() || snapshot.getIntegrityScanAgeSeconds() == Long.MAX_VALUE) {
return "AUDIT_INTEGRITY_SCAN_NOT_RECORDED";
}
if (snapshot.isIntegrityScanTimestampInvalid() || snapshot.getIntegrityScanAgeSeconds() < 0L) {
return "AUDIT_INTEGRITY_SCAN_TIME_INVALID";
}
if (snapshot.isIntegrityScanStale()
|| snapshot.getIntegrityScanAgeSeconds() > properties.getMaxIntegrityScanAgeSeconds()) {
return "AUDIT_INTEGRITY_SCAN_STALE";
}
return null;
}
}
@@ -0,0 +1,59 @@
package com.finance.system.audit;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicLong;
@Component
public class AuditReliabilityMetrics {
private final Counter deliverySuccess;
private final Counter deliveryFailure;
private final Counter claimContention;
private final Timer deliveryLatency;
private final AuditReliabilitySnapshotProvider snapshots;
private final AtomicLong pending = new AtomicLong();
private final AtomicLong dead = new AtomicLong();
private final AtomicLong oldestPendingAge = new AtomicLong();
private final AtomicLong scanAge = new AtomicLong();
public AuditReliabilityMetrics(MeterRegistry registry, AuditReliabilitySnapshotProvider snapshots) {
this.snapshots = snapshots;
deliverySuccess = Counter.builder("audit.outbox.delivery.success").register(registry);
deliveryFailure = Counter.builder("audit.outbox.delivery.failure").register(registry);
claimContention = Counter.builder("audit.outbox.claim.contention").register(registry);
deliveryLatency = Timer.builder("audit.outbox.delivery.latency").publishPercentileHistogram().register(registry);
Gauge.builder("audit.outbox.pending", pending, AtomicLong::get).register(registry);
Gauge.builder("audit.outbox.dead", dead, AtomicLong::get).register(registry);
Gauge.builder("audit.outbox.oldest.pending.age.seconds", oldestPendingAge, AtomicLong::get).register(registry);
Gauge.builder("audit.integrity.scan.age.seconds", scanAge, AtomicLong::get).register(registry);
}
public void recordDeliverySuccess(Duration duration) {
deliverySuccess.increment();
deliveryLatency.record(duration);
}
public void recordDeliveryFailure(Duration duration) {
deliveryFailure.increment();
deliveryLatency.record(duration);
}
public void recordClaimContention() {
claimContention.increment();
}
@Scheduled(fixedDelayString = "${observability.audit.reliability.metrics-refresh-ms:30000}")
public void refresh() {
AuditReliabilitySnapshot value = snapshots.snapshot();
pending.set(value.getPendingCount());
dead.set(value.getDeadCount());
oldestPendingAge.set(value.getOldestPendingAgeSeconds());
scanAge.set(value.getIntegrityScanAgeSeconds());
}
}
@@ -0,0 +1,26 @@
package com.finance.system.audit;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "observability.audit.reliability")
public class AuditReliabilityProperties {
private int outboxLeaseSeconds = 30;
private int integrityScanLeaseSeconds = 120;
private long maxPendingAgeSeconds = 300L;
private long maxDeadCount = 0L;
private long maxIntegrityScanAgeSeconds = 900L;
private boolean failOnIntegrityFailure = true;
private long metricsRefreshMs = 30000L;
public int boundedOutboxLeaseSeconds() {
return Math.max(5, Math.min(outboxLeaseSeconds, 3600));
}
public int boundedIntegrityScanLeaseSeconds() {
return Math.max(30, Math.min(integrityScanLeaseSeconds, 3600));
}
}
@@ -0,0 +1,19 @@
package com.finance.system.audit;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class AuditReliabilitySnapshot {
long pendingCount;
long deadCount;
long oldestPendingAgeSeconds;
boolean pendingTimestampInvalid;
boolean pendingAgeThresholdExceeded;
long integrityScanAgeSeconds;
boolean integrityScanMissing;
boolean integrityScanTimestampInvalid;
boolean integrityScanStale;
long integrityFailureCount;
}
@@ -0,0 +1,78 @@
package com.finance.system.audit;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
@RequiredArgsConstructor
public class AuditReliabilitySnapshotProvider {
static final String OUTBOX_SNAPSHOT_SQL =
"select pending_count,dead_count,"
+ "case when oldest_pending_at is null then 0 "
+ "else timestampdiff(second,oldest_pending_at,utc_timestamp(6)) end "
+ "oldest_pending_age_seconds,"
+ "case when invalid_pending_time_count>0 "
+ "then 1 else 0 end pending_time_invalid,"
+ "case when oldest_pending_at is not null "
+ "and oldest_pending_at<timestampadd(second,0-?,utc_timestamp(6)) "
+ "then 1 else 0 end pending_age_exceeded "
+ "from (select "
+ "coalesce(sum(case when status='PENDING' then 1 else 0 end),0) pending_count,"
+ "coalesce(sum(case when status='DEAD' then 1 else 0 end),0) dead_count,"
+ "coalesce(sum(case when status='PENDING' and "
+ "(created_at is null or created_at>utc_timestamp(6)) then 1 else 0 end),0) "
+ "invalid_pending_time_count,"
+ "min(case when status='PENDING' then created_at end) oldest_pending_at "
+ "from sys_audit_outbox) outbox_state";
static final String INTEGRITY_SCAN_SNAPSHOT_SQL =
"select case when last_scan_at is null then null "
+ "else timestampdiff(second,last_scan_at,utc_timestamp(6)) end "
+ "integrity_scan_age_seconds,"
+ "case when last_scan_at is null then 1 else 0 end scan_missing,"
+ "case when last_scan_at is not null and last_scan_at>utc_timestamp(6) "
+ "then 1 else 0 end scan_time_invalid,"
+ "case when last_scan_at is not null "
+ "and last_scan_at<timestampadd(second,0-?,utc_timestamp(6)) "
+ "then 1 else 0 end scan_stale,"
+ "current_cycle_failures,last_cycle_failures "
+ "from sys_audit_integrity_scan_state where scan_name='PRIMARY'";
private final JdbcTemplate jdbcTemplate;
private final AuditReliabilityProperties properties;
public AuditReliabilitySnapshot snapshot() {
Map<String, Object> outbox = jdbcTemplate.queryForMap(
OUTBOX_SNAPSHOT_SQL, properties.getMaxPendingAgeSeconds());
Map<String, Object> scan = jdbcTemplate.queryForMap(
INTEGRITY_SCAN_SNAPSHOT_SQL, properties.getMaxIntegrityScanAgeSeconds());
long failures = number(scan.get("current_cycle_failures")) + number(scan.get("last_cycle_failures"));
return AuditReliabilitySnapshot.builder()
.pendingCount(number(outbox.get("pending_count")))
.deadCount(number(outbox.get("dead_count")))
.oldestPendingAgeSeconds(number(outbox.get("oldest_pending_age_seconds")))
.pendingTimestampInvalid(flag(outbox.get("pending_time_invalid")))
.pendingAgeThresholdExceeded(flag(outbox.get("pending_age_exceeded")))
.integrityScanAgeSeconds(number(scan.get("integrity_scan_age_seconds"), Long.MAX_VALUE))
.integrityScanMissing(flag(scan.get("scan_missing")))
.integrityScanTimestampInvalid(flag(scan.get("scan_time_invalid")))
.integrityScanStale(flag(scan.get("scan_stale")))
.integrityFailureCount(failures)
.build();
}
private static long number(Object value) {
return number(value, 0L);
}
private static long number(Object value, long missingValue) {
return value instanceof Number ? ((Number) value).longValue() : missingValue;
}
private static boolean flag(Object value) {
return number(value) != 0L;
}
}
@@ -0,0 +1,33 @@
package com.finance.system.audit.query;
import lombok.Builder;
import lombok.Value;
import java.time.LocalDateTime;
/** Explicit audit-query allowlist. Payload, attributes and integrity metadata are never exposed. */
@Value
@Builder
public class AuditEventView {
Long id;
LocalDateTime eventTime;
String category;
String categoryLabel;
String action;
String actionLabel;
String outcome;
String outcomeLabel;
String reasonCode;
String reasonLabel;
String actorType;
String actorLabel;
Long actorId;
String targetType;
String targetId;
String resourceType;
String resourceLabel;
String resourceId;
String requestId;
String traceId;
String source;
}
@@ -0,0 +1,58 @@
package com.finance.system.audit.query;
import com.finance.system.authorization.AuthorizationRequest;
import com.finance.system.authorization.AuthorizationService;
import com.finance.system.authorization.ResourceContext;
import com.finance.system.authorization.SubjectContext;
import com.finance.system.exception.UnauthorizedException;
import com.finance.system.security.UserPrincipal;
import com.finance.system.util.AuditUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Locale;
@Component
@RequiredArgsConstructor
public class AuditQueryAuthorization {
private final AuthorizationService authorizationService;
public AuditQueryScope authorize(String area) {
UserPrincipal principal = AuditUtil.getCurrentUser();
if (principal == null || principal.getId() == null) throw new UnauthorizedException("未登录");
SubjectContext subject = authorizationService.subject(principal);
if (subject == null || !StringUtils.hasText(subject.getTenantId())
|| subject.getOrganizationId() == null) {
throw new AccessDeniedException("缺少审计查询隔离边界");
}
String resource = resource(area);
ResourceContext context = ResourceContext.builder().resourceType(resource)
.tenantId(subject.getTenantId()).organizationId(subject.getOrganizationId())
.ownerId(subject.getUserId()).build();
if (authorizationService.can(request(subject, resource, "read-all", context))) {
return new AuditQueryScope(subject.getTenantId(), subject.getOrganizationId(), subject.getUserId(), true);
}
if (authorizationService.can(request(subject, resource, "read-own", context))) {
return new AuditQueryScope(subject.getTenantId(), subject.getOrganizationId(), subject.getUserId(), false);
}
throw new AccessDeniedException("无权查看该类审计事件");
}
private AuthorizationRequest request(SubjectContext subject, String resource, String action,
ResourceContext context) {
return AuthorizationRequest.builder().subject(subject).resource(resource).action(action)
.resourceContext(context).build();
}
private String resource(String area) {
String normalized = area == null ? "" : area.trim().toUpperCase(Locale.ROOT);
if ("ACCESS".equals(normalized)) return "audit.access";
if ("SECURITY".equals(normalized)) return "audit.security";
if ("BUSINESS".equals(normalized)) return "audit.business";
if ("ADMIN".equals(normalized)) return "audit.admin";
if ("INTEGRATION".equals(normalized)) return "audit.integration";
throw new IllegalArgumentException("不支持的审计类别");
}
}
@@ -0,0 +1,31 @@
package com.finance.system.audit.query;
import com.finance.system.audit.AuditEvent;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import java.time.LocalDateTime;
import java.util.List;
public interface AuditQueryRepository extends Repository<AuditEvent, Long> {
@Query("select e from AuditEvent e where e.tenantId = :tenantId and e.organizationId = :organizationId "
+ "and (:allActors = true or e.actorId = :actorId) and e.category = :category "
+ "and (:action is null or e.actionCode = :action) "
+ "and (:outcome is null or e.outcome = :outcome) "
+ "and (:filterActorId is null or e.actorId = :filterActorId) "
+ "and (:resourceType is null or e.resourceType = :resourceType) "
+ "and (:resourceId is null or e.resourceId = :resourceId) "
+ "and (:cursorTime is null or e.occurredAt < :cursorTime "
+ "or (e.occurredAt = :cursorTime and e.id < :cursorId)) "
+ "order by e.occurredAt desc, e.id desc")
List<AuditEvent> search(@Param("tenantId") String tenantId,
@Param("organizationId") Long organizationId,
@Param("allActors") boolean allActors, @Param("actorId") Long actorId,
@Param("category") String category, @Param("action") String action,
@Param("outcome") String outcome, @Param("filterActorId") Long filterActorId,
@Param("resourceType") String resourceType, @Param("resourceId") String resourceId,
@Param("cursorTime") LocalDateTime cursorTime, @Param("cursorId") Long cursorId,
Pageable pageable);
}
@@ -0,0 +1,11 @@
package com.finance.system.audit.query;
import lombok.Value;
@Value
public class AuditQueryScope {
String tenantId;
Long organizationId;
Long actorId;
boolean allActors;
}
@@ -0,0 +1,78 @@
package com.finance.system.audit.query;
import com.finance.system.audit.AuditEvent;
import com.finance.system.observability.LogText;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@Service
@RequiredArgsConstructor
public class AuditQueryService {
private static final int DEFAULT_LIMIT = 50;
private static final int MAX_LIMIT = 100;
private final AuditQueryRepository repository;
@Transactional(readOnly = true)
public CursorPage<AuditEventView> search(AuditQueryScope scope, String category, String action,
String outcome, Long actorId, String resourceType, String resourceId,
LocalDateTime cursorTime, Long cursorId, Integer requestedLimit) {
if ((cursorTime == null) != (cursorId == null))
throw new IllegalArgumentException("cursorTime 与 cursorId 必须同时提供");
if (!scope.isAllActors() && actorId != null && !actorId.equals(scope.getActorId())) {
throw new org.springframework.security.access.AccessDeniedException("仅可查询本人审计事件");
}
int limit = requestedLimit == null ? DEFAULT_LIMIT : Math.max(1, Math.min(requestedLimit, MAX_LIMIT));
Long filterActor = scope.isAllActors() ? actorId : scope.getActorId();
if (scope.getOrganizationId() == null || scope.getOrganizationId() <= 0)
throw new org.springframework.security.access.AccessDeniedException("缺少组织隔离边界");
List<AuditEvent> rows = repository.search(scope.getTenantId(), scope.getOrganizationId(),
scope.isAllActors(), scope.getActorId(),
normalizeCategory(category), clean(action), clean(outcome), filterActor,
clean(resourceType), clean(resourceId), cursorTime, cursorId, PageRequest.of(0, limit + 1));
boolean more = rows.size() > limit;
List<AuditEventView> items = new ArrayList<>();
for (int i = 0; i < Math.min(limit, rows.size()); i++) {
AuditEvent row = rows.get(i);
if (!scope.getTenantId().equals(row.getTenantId())
|| !scope.getOrganizationId().equals(row.getOrganizationId())) {
throw new org.springframework.security.access.AccessDeniedException("审计事件组织边界不匹配");
}
items.add(toView(row));
}
AuditEvent last = more && !items.isEmpty() ? rows.get(limit - 1) : null;
return CursorPage.<AuditEventView>builder().items(items).hasMore(more)
.nextEventTime(last == null ? null : last.getOccurredAt())
.nextId(last == null ? null : last.getId()).build();
}
private AuditEventView toView(AuditEvent e) {
return AuditEventView.builder().id(e.getId()).eventTime(e.getOccurredAt())
.category(e.getCategory()).categoryLabel(LogText.auditCategory(e.getCategory()))
.action(e.getActionCode()).actionLabel(LogText.auditAction(e.getActionCode()))
.outcome(e.getOutcome()).outcomeLabel(LogText.outcome(e.getOutcome()))
.reasonCode(e.getReasonCode()).reasonLabel(LogText.reason(e.getReasonCode()))
.actorType(e.getActorType())
.actorLabel(LogText.actorType(e.getActorType())).actorId(e.getActorId())
.targetType(e.getTargetType()).targetId(e.getTargetId())
.resourceType(e.getResourceType()).resourceLabel(LogText.resourceType(e.getResourceType()))
.resourceId(e.getResourceId())
.requestId(e.getRequestId()).traceId(e.getTraceId()).source(e.getSourceChannel()).build();
}
private String normalizeCategory(String value) {
String result = value == null ? "" : value.trim().toUpperCase(Locale.ROOT);
if (!java.util.Arrays.asList("SECURITY", "BUSINESS", "ADMIN", "INTEGRATION").contains(result))
throw new IllegalArgumentException("不支持的审计类别");
return result;
}
private String clean(String value) { return StringUtils.hasText(value) ? value.trim() : null; }
}
@@ -0,0 +1,16 @@
package com.finance.system.audit.query;
import lombok.Builder;
import lombok.Value;
import java.time.LocalDateTime;
import java.util.List;
@Value
@Builder
public class CursorPage<T> {
List<T> items;
LocalDateTime nextEventTime;
Long nextId;
boolean hasMore;
}
@@ -0,0 +1,470 @@
package com.finance.system.authorization;
import com.finance.system.audit.AuditEventCommand;
import com.finance.system.audit.AuditPort;
import com.finance.system.entity.SysRole;
import com.finance.system.exception.BadRequestException;
import com.finance.system.exception.BusinessException;
import com.finance.system.exception.ResourceNotFoundException;
import com.finance.system.repository.SysRoleRepository;
import com.finance.system.repository.SysUserGroupRepository;
import com.finance.system.repository.SysUserGroupMemberRepository;
import com.finance.system.repository.SysUserRepository;
import com.finance.system.entity.SysUser;
import com.finance.system.entity.SysUserGroupMember;
import com.finance.system.service.RoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*;
/** Super-admin mutation boundary for canonical policies and subject bindings. */
@Service
@RequiredArgsConstructor
public class AuthorizationAdminService {
private final AuthorizationPolicyEvaluator evaluator;
private final AuthorizationPolicyRepository policies;
private final AuthorizationRolePolicyRepository rolePolicies;
private final AuthorizationSubjectRoleBindingRepository subjectBindings;
private final AuthorizationFieldRuleRepository fieldRules;
private final AuthorizationPolicyVersionRepository versions;
private final AuthorizationSodRuleRepository sodRules;
private final SysRoleRepository roles;
private final SysUserRepository users;
private final SysUserGroupRepository groups;
private final SysUserGroupMemberRepository groupMembers;
private final RoleService roleService;
private final AuditPort auditPort;
@Autowired
private AuthorizationRoleProfileVersionRepository roleProfileVersions;
@Transactional(readOnly = true)
public List<AuthorizationPolicyDto> listPolicies() {
List<AuthorizationPolicyDto> result = new ArrayList<>();
for (AuthorizationPolicyEntity policy : policies.findAll()) result.add(policyDto(policy));
return result;
}
/** Internal-only gate for raw policy diagnostics and maintenance endpoints. */
@Transactional(readOnly = true)
public void assertInternalPolicyAdmin(Long actorId) {
requireSuperAdmin(actorId);
}
@Transactional
public AuthorizationPolicyDto savePolicy(Long id, AuthorizationPolicyRequest request, Long actorId) {
if (request == null) throw new BadRequestException("策略请求不能为空");
return savePolicy(id, request.toMap(), actorId);
}
@Transactional
public AuthorizationPolicyDto savePolicy(Long id, Map<String, Object> body, Long actorId) {
requireSuperAdmin(actorId);
String resource = normalizedPart(body, "resource");
String action = normalizedPart(body, "action");
String policyCode = text(body, "policyCode", 120);
PolicyEffect effect = enumValue(body, "effect", PolicyEffect.class);
DataScope dataScope = enumValue(body, "dataScope", DataScope.class);
String scopeParameter = optionalText(body, "scopeParameter", 120);
int priority = integer(body, "priority", 0, -10000, 10000);
boolean enabled = bool(body, "enabled", true);
AuthorizationPolicyEntity policy = id == null ? new AuthorizationPolicyEntity()
: policies.findById(id).orElseThrow(() -> new ResourceNotFoundException("授权策略不存在"));
AuthorizationPolicyEntity duplicate = policies.findByPolicyCode(policyCode).orElse(null);
if (duplicate != null && !Objects.equals(duplicate.getId(), id)) throw new BusinessException("策略编码已存在", 409);
boolean delegable = bool(body, "delegable", policy.getDelegable() == null || policy.getDelegable());
PolicyRiskLevel riskLevel = optionalEnum(body, "riskLevel", PolicyRiskLevel.class);
if (riskLevel == null) riskLevel = policy.getRiskLevel() == null ? PolicyRiskLevel.NORMAL : policy.getRiskLevel();
boolean protectedPolicy = bool(body, "protected", Boolean.TRUE.equals(policy.getProtectedPolicy()));
validateProtectedPolicyMutation(id, body, policy, policyCode, resource, action, effect, dataScope,
scopeParameter, priority, enabled, delegable, riskLevel, protectedPolicy);
if ((protectedPolicy || riskLevel == PolicyRiskLevel.CRITICAL) && delegable) {
throw new BusinessException("受保护或CRITICAL策略必须显式设为不可委派", 403);
}
if (riskLevel == PolicyRiskLevel.CRITICAL && !protectedPolicy) {
throw new BusinessException("CRITICAL策略必须显式设为受保护", 403);
}
policy.setPolicyCode(policyCode);
policy.setResourceCode(resource);
policy.setActionCode(action);
policy.setEffect(effect);
policy.setDataScope(dataScope);
policy.setScopeParameter(scopeParameter);
policy.setPriority(priority);
policy.setEnabled(enabled);
policy.setDelegable(delegable);
policy.setRiskLevel(riskLevel);
policy.setProtectedPolicy(protectedPolicy);
LocalDateTime now = LocalDateTime.now();
if (policy.getCreatedAt() == null) policy.setCreatedAt(now);
policy.setUpdatedAt(now);
AuthorizationPolicyEntity saved = policies.save(policy);
replaceFieldRules(saved.getId(), body == null ? null : body.get("fieldAccess"));
bumpVersion();
audit("iam.policy." + (id == null ? "create" : "update"), actorId,
"IAM_POLICY", saved.getId(), attributes("policyCode", saved.getPolicyCode(), "effectCode", saved.getEffect().name()));
return policyDto(saved);
}
@Transactional(readOnly = true)
public AuthorizationBindingPageDto listBindings(AuthorizationBindingQueryRequest query, Long actorId,
String actorTenant) {
if (query == null) query = new AuthorizationBindingQueryRequest();
if (!StringUtils.hasText(actorTenant)) throw new BusinessException("当前主体缺少租户边界", 403);
boolean superAdmin = actorId != null && roleService.isSuperAdmin(actorId);
String requestedTenant = StringUtils.hasText(query.getTenant()) ? query.getTenant().trim() : actorTenant;
boolean global = "*".equals(requestedTenant);
if (global && !superAdmin) throw new BusinessException("只有超级管理员可以查询GLOBAL授权绑定", 403);
if (!global && !actorTenant.equals(requestedTenant) && !superAdmin) {
throw new BusinessException("禁止跨租户查询授权绑定", 403);
}
int page = query.getPage() == null ? 0 : query.getPage();
int size = query.getSize() == null ? 20 : query.getSize();
if (page < 0 || size < 1 || size > 100) throw new BadRequestException("分页参数无效");
List<AuthorizationBindingDto> filtered = new ArrayList<>();
for (AuthorizationSubjectRoleBindingEntity binding : subjectBindings.findAll()) {
if (binding == null || binding.getId() == null) continue;
AuthorizationSubjectType subjectType;
try { subjectType = AuthorizationSubjectType.valueOf(binding.getSubjectType()); }
catch (RuntimeException ex) { continue; }
String bindingTenant = resolveBindingTenant(binding, subjectType);
if (!global && !requestedTenant.equals(bindingTenant)) continue;
if (query.getSubjectType() != null && query.getSubjectType() != subjectType) continue;
if (query.getSubjectId() != null && !query.getSubjectId().equals(binding.getSubjectId())) continue;
if (query.getRoleId() != null && !query.getRoleId().equals(binding.getRoleId())) continue;
if (query.getEnabled() != null && !query.getEnabled().equals(binding.getEnabled())) continue;
filtered.add(bindingDto(binding, subjectType, bindingTenant));
}
filtered.sort(Comparator.comparing(AuthorizationBindingDto::getId));
long total = filtered.size();
long offset = (long) page * size;
int from = offset >= total ? filtered.size() : (int) offset;
int to = Math.min(filtered.size(), from + size);
return AuthorizationBindingPageDto.builder().content(new ArrayList<>(filtered.subList(from, to)))
.page(page).size(size).totalElements(total)
.totalPages(total == 0 ? 0 : (int) ((total + size - 1) / size)).build();
}
@Transactional
public void replaceRolePolicies(Long roleId, Collection<?> policyIds, Long actorId) {
replaceRolePoliciesInternal(roleId, policyIds, actorId, true);
}
@Transactional
public void replaceRolePoliciesFromProfile(Long roleId, Collection<?> policyIds, Long actorId) {
replaceRolePoliciesInternal(roleId, policyIds, actorId, false);
}
private void replaceRolePoliciesInternal(Long roleId, Collection<?> policyIds, Long actorId,
boolean bumpRoleProfileVersion) {
requireSuperAdmin(actorId);
// Every authorization writer must acquire the role row first. The
// atomic profile writer already does this before locking its version
// row; keeping the legacy policy endpoint on the same leading lock
// serializes same-role writes and prevents downstream lock inversion.
SysRole role = roles.findByIdForUpdate(roleId)
.orElseThrow(() -> new ResourceNotFoundException("角色不存在"));
Set<Long> ids = positiveIds(policyIds, "policyIds");
List<AuthorizationPolicyEntity> selected = policies.findAllById(ids);
if (selected.size() != ids.size()) throw new BadRequestException("policyIds包含不存在的策略");
boolean protectedTarget = "SUPER_ADMIN".equals(role.getRoleCode()) && Boolean.TRUE.equals(role.getBuiltIn());
for (AuthorizationPolicyEntity policy : selected) {
if ((!Boolean.TRUE.equals(policy.getDelegable()) || Boolean.TRUE.equals(policy.getProtectedPolicy())
|| policy.getRiskLevel() == PolicyRiskLevel.CRITICAL)
&& !protectedTarget) {
throw new BusinessException("不可委派、受保护或CRITICAL策略只能绑定内置超级管理员角色", 403);
}
}
for (AuthorizationRolePolicyEntity existing : rolePolicies.findByIdRoleId(roleId)) {
if (existing == null || existing.getId() == null || ids.contains(existing.getId().getPolicyId())) continue;
AuthorizationPolicyEntity policy = policies.findById(existing.getId().getPolicyId()).orElse(null);
if (policy != null && Boolean.TRUE.equals(policy.getProtectedPolicy())) {
throw new BusinessException("受保护策略不能通过角色策略替换移除", 403);
}
}
rolePolicies.deleteByIdRoleId(roleId);
for (Long policyId : ids) rolePolicies.save(new AuthorizationRolePolicyEntity(roleId, policyId));
bumpVersion();
if (bumpRoleProfileVersion && roleProfileVersions != null) roleProfileVersions.bumpRoleVersion(roleId);
audit("iam.role.policy.update", actorId, "IAM_ROLE", roleId,
attributes("roleCode", role.getRoleCode(), "policyCount", ids.size()));
}
@Transactional(readOnly = true)
public List<Long> rolePolicyIds(Long roleId) {
if (!roles.existsById(roleId)) throw new ResourceNotFoundException("角色不存在");
List<Long> result = new ArrayList<>();
for (AuthorizationRolePolicyEntity link : rolePolicies.findByIdRoleId(roleId)) result.add(link.getId().getPolicyId());
return result;
}
@Transactional
public Map<String, Object> createSubjectBinding(Map<String, Object> body, Long actorId) {
requireSuperAdmin(actorId);
String subjectType = text(body, "subjectType", 16).toUpperCase(Locale.ROOT);
if (!("USER".equals(subjectType) || "GROUP".equals(subjectType))) throw new BadRequestException("subjectType必须是USER或GROUP");
Long subjectId = positiveLong(body, "subjectId");
Long roleId = positiveLong(body, "roleId");
if ("USER".equals(subjectType) && subjectId.equals(actorId)) throw new BusinessException("禁止给当前操作者自授权", 403);
if ("USER".equals(subjectType) && !users.existsById(subjectId)) throw new ResourceNotFoundException("用户不存在");
if ("GROUP".equals(subjectType) && !groups.existsById(subjectId)) throw new ResourceNotFoundException("用户组不存在");
SysRole role = roles.findById(roleId).orElseThrow(() -> new ResourceNotFoundException("角色不存在"));
DataScope scopeOverride = optionalEnum(body, "scopeOverride", DataScope.class);
Long scopeReferenceId = optionalPositiveLong(body, "scopeReferenceId");
if (scopeReferenceId != null && scopeOverride != DataScope.DEPARTMENT
&& scopeOverride != DataScope.DEPARTMENT_TREE) {
throw new BadRequestException("scopeReferenceId仅适用于部门范围");
}
if (subjectBindings.existsNormalized(subjectType, subjectId, roleId, scopeOverride, scopeReferenceId)) {
throw new BusinessException("授权绑定已存在", 409);
}
AuthorizationSubjectRoleBindingEntity binding = new AuthorizationSubjectRoleBindingEntity();
binding.setSubjectType(subjectType); binding.setSubjectId(subjectId); binding.setRoleId(roleId);
binding.setScopeOverride(scopeOverride);
binding.setScopeReferenceId(scopeReferenceId);
binding.setValidFrom(optionalDateTime(body, "validFrom"));
binding.setValidUntil(optionalDateTime(body, "validUntil"));
if (binding.getValidFrom() != null && binding.getValidUntil() != null
&& !binding.getValidUntil().isAfter(binding.getValidFrom())) {
throw new BadRequestException("validUntil必须晚于validFrom");
}
binding.setEnabled(bool(body, "enabled", true)); binding.setCreatedBy(actorId); binding.setRecordVersion(0L);
AuthorizationSubjectRoleBindingEntity saved;
try {
saved = subjectBindings.saveAndFlush(binding);
} catch (DataIntegrityViolationException ex) {
throw new BusinessException("授权绑定已存在", 409);
}
bumpVersion();
audit("iam.binding.create", actorId, "IAM_BINDING", saved.getId(),
attributes("subjectType", subjectType, "subjectId", subjectId, "roleCode", role.getRoleCode()));
return bindingMap(saved);
}
@Transactional
public void deleteSubjectBinding(Long bindingId, Long actorId) {
requireSuperAdmin(actorId);
AuthorizationSubjectRoleBindingEntity binding = subjectBindings.findById(bindingId)
.orElseThrow(() -> new ResourceNotFoundException("授权绑定不存在"));
if ("USER".equals(binding.getSubjectType()) && Objects.equals(binding.getSubjectId(), actorId)) {
throw new BusinessException("禁止移除当前操作者自身的授权绑定", 403);
}
subjectBindings.delete(binding);
bumpVersion();
audit("iam.binding.delete", actorId, "IAM_BINDING", bindingId,
attributes("subjectType", binding.getSubjectType(), "subjectId", binding.getSubjectId(), "roleId", binding.getRoleId()));
}
@Transactional(readOnly = true)
public List<Map<String, Object>> listSodRules() {
List<Map<String, Object>> result = new ArrayList<>();
for (AuthorizationSodRuleEntity rule : sodRules.findAll()) {
Map<String,Object> item = new LinkedHashMap<>();
item.put("id", rule.getId()); item.put("ruleCode", rule.getRuleCode());
item.put("leftDuty", rule.getLeftDuty()); item.put("rightDuty", rule.getRightDuty());
item.put("relationType", rule.getRelationType()); item.put("enabled", rule.getEnabled());
result.add(item);
}
return result;
}
private void replaceFieldRules(Long policyId, Object raw) {
if (raw == null) return;
if (!(raw instanceof Map)) throw new BadRequestException("fieldAccess必须是对象");
Map<?,?> values = (Map<?,?>) raw;
if (values.size() > 200) throw new BadRequestException("字段规则不能超过200项");
fieldRules.deleteByPolicyId(policyId);
for (Map.Entry<?,?> entry : values.entrySet()) {
String field = String.valueOf(entry.getKey());
if (!field.matches("[A-Za-z][A-Za-z0-9_.-]{0,119}")) throw new BadRequestException("字段编码格式不正确");
FieldAccess access;
try { access = FieldAccess.valueOf(String.valueOf(entry.getValue()).toUpperCase(Locale.ROOT)); }
catch (Exception ex) { throw new BadRequestException("字段访问级别无效"); }
AuthorizationFieldRuleEntity rule = new AuthorizationFieldRuleEntity();
rule.setPolicyId(policyId); rule.setFieldCode(field); rule.setFieldAccess(access); fieldRules.save(rule);
}
}
private void validateProtectedPolicyMutation(Long id, Map<String,Object> body,
AuthorizationPolicyEntity existing,
String policyCode, String resource, String action,
PolicyEffect effect, DataScope dataScope,
String scopeParameter, int priority, boolean enabled,
boolean delegable, PolicyRiskLevel riskLevel,
boolean protectedPolicy) {
if (id == null || existing == null) return;
boolean locked = Boolean.TRUE.equals(existing.getProtectedPolicy())
|| existing.getRiskLevel() == PolicyRiskLevel.CRITICAL;
if (!locked) return;
boolean changed = !Objects.equals(existing.getPolicyCode(), policyCode)
|| !Objects.equals(existing.getResourceCode(), resource)
|| !Objects.equals(existing.getActionCode(), action)
|| existing.getEffect() != effect
|| existing.getDataScope() != dataScope
|| !Objects.equals(existing.getScopeParameter(), scopeParameter)
|| !Objects.equals(existing.getPriority(), priority)
|| !Objects.equals(existing.getEnabled(), enabled)
|| !Objects.equals(existing.getDelegable(), delegable)
|| existing.getRiskLevel() != riskLevel
|| !Objects.equals(existing.getProtectedPolicy(), protectedPolicy)
|| (body != null && body.containsKey("fieldAccess"));
if (changed) {
throw new BusinessException("受保护或CRITICAL策略不支持普通更新;系统未提供break-glass降级通道", 403);
}
}
private AuthorizationPolicyDto policyDto(AuthorizationPolicyEntity policy) {
Map<String,FieldAccess> fields = new LinkedHashMap<>();
if (policy.getId() != null) for (AuthorizationFieldRuleEntity rule : fieldRules.findByPolicyId(policy.getId())) fields.put(rule.getFieldCode(), rule.getFieldAccess());
return AuthorizationPolicyDto.builder().id(policy.getId()).policyCode(policy.getPolicyCode())
.resource(policy.getResourceCode()).action(policy.getActionCode()).effect(policy.getEffect())
.dataScope(policy.getDataScope()).scopeParameter(policy.getScopeParameter())
.priority(policy.getPriority()).enabled(policy.getEnabled()).delegable(policy.getDelegable())
.riskLevel(policy.getRiskLevel()).protectedPolicy(policy.getProtectedPolicy())
.validFrom(policy.getValidFrom()).validUntil(policy.getValidUntil())
.version(policy.getRecordVersion()).fieldAccess(Collections.unmodifiableMap(fields)).build();
}
private AuthorizationBindingDto bindingDto(AuthorizationSubjectRoleBindingEntity binding,
AuthorizationSubjectType subjectType, String tenantId) {
return AuthorizationBindingDto.builder().id(binding.getId()).tenantId(tenantId)
.subjectType(subjectType).subjectId(binding.getSubjectId()).roleId(binding.getRoleId())
.scopeOverride(binding.getScopeOverride()).scopeReferenceId(binding.getScopeReferenceId())
.enabled(binding.getEnabled()).validFrom(binding.getValidFrom()).validUntil(binding.getValidUntil())
.version(binding.getRecordVersion()).build();
}
private String resolveBindingTenant(AuthorizationSubjectRoleBindingEntity binding,
AuthorizationSubjectType subjectType) {
if (subjectType == AuthorizationSubjectType.USER) {
return users.findById(binding.getSubjectId()).map(SysUser::getTenantId).filter(StringUtils::hasText)
.orElse(null);
}
List<SysUserGroupMember> memberships = groupMembers.findByIdGroupId(binding.getSubjectId());
if (memberships == null || memberships.isEmpty()) return null;
Set<Long> userIds = new LinkedHashSet<>();
for (SysUserGroupMember membership : memberships) {
if (membership != null && membership.getId() != null && membership.getId().getUserId() != null)
userIds.add(membership.getId().getUserId());
}
if (userIds.isEmpty()) return null;
Set<String> tenants = new LinkedHashSet<>();
int resolvedUsers = 0;
for (SysUser user : users.findAllById(userIds)) {
if (user == null || !StringUtils.hasText(user.getTenantId())) return null;
resolvedUsers++; tenants.add(user.getTenantId());
}
return resolvedUsers == userIds.size() && tenants.size() == 1 ? tenants.iterator().next() : null;
}
private Map<String,Object> bindingMap(AuthorizationSubjectRoleBindingEntity binding) {
Map<String,Object> result = new LinkedHashMap<>();
result.put("id", binding.getId()); result.put("subjectType", binding.getSubjectType());
result.put("subjectId", binding.getSubjectId()); result.put("roleId", binding.getRoleId());
result.put("scopeOverride", binding.getScopeOverride()); result.put("scopeReferenceId", binding.getScopeReferenceId());
result.put("enabled", binding.getEnabled()); result.put("validFrom", binding.getValidFrom());
result.put("validUntil", binding.getValidUntil()); result.put("version", binding.getRecordVersion());
return result;
}
private void requireSuperAdmin(Long actorId) {
if (actorId == null || !roleService.isSuperAdmin(actorId)) throw new BusinessException("只有超级管理员可以变更规范授权策略", 403);
}
private void bumpVersion() {
if (versions.incrementPolicyVersion() == 0) {
AuthorizationPolicyVersionEntity version = new AuthorizationPolicyVersionEntity();
version.setId(1); version.setPolicyVersion(1L); version.setUpdatedAt(LocalDateTime.now()); versions.save(version);
}
}
private void audit(String action, Long actorId, String resourceType, Long resourceId, Map<String,Object> attributes) {
auditPort.emit(AuditEventCommand.builder().eventTime(Instant.now()).tenantId("default")
.category("ADMIN").action(action).outcome("SUCCESS").actorType("USER").actorId(actorId)
.targetType(resourceType).targetId(String.valueOf(resourceId))
.resourceType(resourceType).resourceId(String.valueOf(resourceId)).source("WEB")
.changes(Collections.<String,Object>emptyMap()).attributes(attributes).build());
}
private String normalizedPart(Map<String,Object> body, String key) {
String value = evaluator.normalizePart(text(body, key, 80));
if (value == null) throw new BadRequestException(key + "格式不正确");
return value;
}
private String text(Map<String,Object> body, String key, int max) {
String value = optionalText(body, key, max);
if (!StringUtils.hasText(value)) throw new BadRequestException(key + "不能为空");
return value;
}
private String optionalText(Map<String,Object> body, String key, int max) {
Object raw = body == null ? null : body.get(key);
if (raw == null) return null;
if (!(raw instanceof String)) throw new BadRequestException(key + "必须是字符串");
String value = ((String)raw).trim();
if (value.isEmpty()) return null;
if (value.length() > max || value.chars().anyMatch(Character::isISOControl)) throw new BadRequestException(key + "格式不正确");
return value;
}
private <E extends Enum<E>> E enumValue(Map<String,Object> body, String key, Class<E> type) {
E value = optionalEnum(body, key, type);
if (value == null) throw new BadRequestException(key + "不能为空或无效");
return value;
}
private <E extends Enum<E>> E optionalEnum(Map<String,Object> body, String key, Class<E> type) {
String value = optionalText(body, key, 40);
if (value == null) return null;
try { return Enum.valueOf(type, value.toUpperCase(Locale.ROOT)); }
catch (IllegalArgumentException ex) { throw new BadRequestException(key + "无效"); }
}
private int integer(Map<String,Object> body, String key, int fallback, int min, int max) {
Object raw = body == null ? null : body.get(key);
if (raw == null) return fallback;
if (!(raw instanceof Number)) throw new BadRequestException(key + "必须是整数");
int value = ((Number)raw).intValue();
if (value < min || value > max) throw new BadRequestException(key + "超出范围");
return value;
}
private boolean bool(Map<String,Object> body, String key, boolean fallback) {
Object raw = body == null ? null : body.get(key);
if (raw == null) return fallback;
if (!(raw instanceof Boolean)) throw new BadRequestException(key + "必须是布尔值");
return (Boolean)raw;
}
private Long positiveLong(Map<String,Object> body, String key) {
Long value = optionalPositiveLong(body, key);
if (value == null) throw new BadRequestException(key + "不能为空");
return value;
}
private Long optionalPositiveLong(Map<String,Object> body, String key) {
Object raw = body == null ? null : body.get(key);
if (raw == null) return null;
if (!(raw instanceof Number) || ((Number)raw).longValue() <= 0) throw new BadRequestException(key + "必须是正整数");
return ((Number)raw).longValue();
}
private LocalDateTime optionalDateTime(Map<String,Object> body, String key) {
String value = optionalText(body, key, 40);
if (value == null) return null;
try { return LocalDateTime.parse(value); }
catch (java.time.format.DateTimeParseException ex) { throw new BadRequestException(key + "格式无效"); }
}
private Set<Long> positiveIds(Collection<?> raw, String field) {
if (raw == null) throw new BadRequestException(field + "不能为空");
Set<Long> result = new LinkedHashSet<>();
for (Object value : raw) {
if (!(value instanceof Number) || ((Number)value).longValue() <= 0 || !result.add(((Number)value).longValue()))
throw new BadRequestException(field + "包含无效或重复ID");
}
return result;
}
private Map<String,Object> attributes(Object... values) {
Map<String,Object> result = new LinkedHashMap<>();
for (int i=0; i<values.length; i+=2) result.put(String.valueOf(values[i]), values[i+1]);
return result;
}
}
@@ -0,0 +1,9 @@
package com.finance.system.authorization;
/** Ownership of a role-policy binding. SYSTEM rows are immutable; safe
* BUSINESS-mapped DERIVED and historical LEGACY rows follow the role tree. */
public enum AuthorizationAssignmentSource {
DERIVED,
SYSTEM,
LEGACY
}
@@ -0,0 +1,40 @@
package com.finance.system.authorization;
import com.finance.system.audit.AuditEventSchemaContributor;
import com.finance.system.audit.AuditEventSchemaRegistry;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Collection;
import static com.finance.system.audit.AuditEventSchemaRegistry.*;
/** Registers strict allowlists for canonical IAM events without widening the audit core. */
@Component
public class AuthorizationAuditSchemaContributor implements AuditEventSchemaContributor {
static final int MAX_MATCHED_POLICY_IDS = 200;
@Override
public Collection<AuditEventSchemaRegistry.Schema> schemas() {
return Arrays.asList(
schema("ADMIN", "iam.policy.create", 1, none(),
fields("policyCode", code(120), "effectCode", enumeration("ALLOW", "DENY"))),
schema("ADMIN", "iam.policy.update", 1, none(),
fields("policyCode", code(120), "effectCode", enumeration("ALLOW", "DENY"))),
schema("ADMIN", "iam.role.policy.update", 1, none(),
fields("roleCode", code(80), "policyCount", integer(0, 10000))),
schema("ADMIN", "iam.binding.create", 1, none(),
fields("subjectType", enumeration("USER", "GROUP"),
"subjectId", integer(1, Long.MAX_VALUE), "roleCode", code(80))),
schema("ADMIN", "iam.binding.delete", 1, none(),
fields("subjectType", enumeration("USER", "GROUP"),
"subjectId", integer(1, Long.MAX_VALUE), "roleId", integer(1, Long.MAX_VALUE))),
schema("SECURITY", "security.authorization.denied", 1, none(),
fields("resource", code(80), "action", code(80),
"reason", code(80), "policyVersion", integer(0, Long.MAX_VALUE),
"matchedPolicyIds", codeList(MAX_MATCHED_POLICY_IDS, 32),
"matchedPolicyCount", integer(0, Integer.MAX_VALUE),
"truncated", flag()))
);
}
}
@@ -0,0 +1,22 @@
package com.finance.system.authorization;
import lombok.Builder;
import lombok.Value;
import java.time.LocalDateTime;
@Value
@Builder
public class AuthorizationBindingDto {
Long id;
String tenantId;
AuthorizationSubjectType subjectType;
Long subjectId;
Long roleId;
DataScope scopeOverride;
Long scopeReferenceId;
Boolean enabled;
LocalDateTime validFrom;
LocalDateTime validUntil;
Long version;
}
@@ -0,0 +1,16 @@
package com.finance.system.authorization;
import lombok.Builder;
import lombok.Value;
import java.util.List;
@Value
@Builder
public class AuthorizationBindingPageDto {
List<AuthorizationBindingDto> content;
int page;
int size;
long totalElements;
int totalPages;
}
@@ -0,0 +1,23 @@
package com.finance.system.authorization;
import lombok.Data;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
@Data
public class AuthorizationBindingQueryRequest {
@Pattern(regexp = "\\*|[A-Za-z0-9][A-Za-z0-9._:-]{0,63}")
private String tenant;
private AuthorizationSubjectType subjectType;
@Min(1)
private Long subjectId;
@Min(1)
private Long roleId;
private Boolean enabled;
@Min(0)
private Integer page = 0;
@Min(1) @Max(100)
private Integer size = 20;
}
@@ -0,0 +1,52 @@
package com.finance.system.authorization;
import lombok.Builder;
import lombok.Value;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
@Value
@Builder
public class AuthorizationCapabilitiesDto {
String source;
Set<String> capabilities;
Set<String> auditAccess;
Set<String> auditSecurity;
Set<String> auditBusiness;
Set<String> auditIntegration;
Set<String> financeActions;
public static AuthorizationCapabilitiesDto from(Set<String> raw) {
Set<String> canonical = new TreeSet<>();
if (raw != null) for (String value : raw) {
if (value != null && value.contains(":")
&& !value.startsWith("page.") && !value.startsWith("ui.page")) canonical.add(value);
}
return AuthorizationCapabilitiesDto.builder().source("CANONICAL_POLICY")
.capabilities(unmodifiable(canonical))
.auditAccess(prefix(canonical, "audit.access:"))
.auditSecurity(prefix(canonical, "audit.security:"))
.auditBusiness(prefix(canonical, "audit.business:"))
.auditIntegration(prefix(canonical, "audit.integration:"))
.financeActions(prefixes(canonical, "finance.", "reimbursement."))
.build();
}
private static Set<String> prefix(Set<String> values, String prefix) {
return prefixes(values, prefix);
}
private static Set<String> prefixes(Set<String> values, String... prefixes) {
Set<String> result = new TreeSet<>();
for (String value : values) for (String prefix : prefixes) {
if (value.startsWith(prefix)) { result.add(value); break; }
}
return unmodifiable(result);
}
private static Set<String> unmodifiable(Set<String> values) {
return Collections.unmodifiableSet(new TreeSet<>(values));
}
}
@@ -0,0 +1,23 @@
package com.finance.system.authorization;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@Entity
@Table(name = "authz_permission_catalog_version")
public class AuthorizationCatalogVersionEntity {
@Id
private Integer id;
@Column(nullable = false)
private Long version;
@Column(name = "updated_at", nullable = false)
private LocalDateTime updatedAt;
}
@@ -0,0 +1,15 @@
package com.finance.system.authorization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import javax.persistence.LockModeType;
import java.util.Optional;
public interface AuthorizationCatalogVersionRepository extends JpaRepository<AuthorizationCatalogVersionEntity, Integer> {
@Lock(LockModeType.PESSIMISTIC_READ)
@Query("select v from AuthorizationCatalogVersionEntity v where v.id = :id")
Optional<AuthorizationCatalogVersionEntity> findByIdForShare(@Param("id") Integer id);
}
@@ -0,0 +1,159 @@
package com.finance.system.authorization;
import com.finance.system.dto.ApiResponse;
import com.finance.system.security.UserPrincipal;
import com.finance.system.util.AuditUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
@RestController
@RequestMapping("/api/authorization")
@RequiredArgsConstructor
@PreAuthorize("isAuthenticated()")
public class AuthorizationController {
private final AuthorizationService authorizationService;
private final AuthorizationAdminService adminService;
@GetMapping("/capabilities")
public ResponseEntity<ApiResponse<AuthorizationCapabilitiesDto>> capabilities() {
SubjectContext subject = currentSubject();
Set<String> capabilities = authorizationService.capabilities(subject);
return ResponseEntity.ok(ApiResponse.success(AuthorizationCapabilitiesDto.from(capabilities)));
}
/** Self-service explanation endpoint. The result is advisory and never reused as an enforcement token. */
@PostMapping("/decision")
public ResponseEntity<ApiResponse<Map<String, Object>>> decision(@RequestBody Map<String, Object> body) {
SubjectContext subject = currentSubject();
String resource = text(body, "resource");
String action = text(body, "action");
ResourceContext context = resource.startsWith("iam.") ? ResourceContext.global(resource)
: ResourceContext.builder().resourceType(resource)
.resourceId(optionalText(body, "resourceId"))
.tenantId(subject.getTenantId())
.ownerId(optionalLong(body, "ownerId"))
.currentApproverId(optionalLong(body, "currentApproverId"))
.departmentId(optionalLong(body, "departmentId"))
.organizationId(optionalLong(body, "organizationId")).build();
AuthorizationDecision decision = authorizationService.evaluate(AuthorizationRequest.builder()
.subject(subject).resource(resource).action(action).resourceContext(context).build());
Map<String, Object> result = new LinkedHashMap<>();
result.put("allowed", decision.isAllowed());
result.put("reasonCode", decision.getReasonCode());
result.put("matchedPolicyIds", decision.getMatchedPolicyIds());
result.put("resolvedScope", decision.getResolvedScope());
result.put("fieldAccess", decision.getFieldAccess());
result.put("policyVersion", decision.getPolicyVersion());
return ResponseEntity.ok(ApiResponse.success(result));
}
@GetMapping("/policies")
@PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'read')")
public ResponseEntity<ApiResponse<java.util.List<AuthorizationPolicyDto>>> policies() {
adminService.assertInternalPolicyAdmin(AuditUtil.getCurrentUserId());
return ResponseEntity.ok(ApiResponse.success(adminService.listPolicies()));
}
@PostMapping("/policies")
@PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'manage')")
public ResponseEntity<ApiResponse<AuthorizationPolicyDto>> createPolicy(
@Valid @RequestBody AuthorizationPolicyRequest body) {
throw rawPolicyWritesRetired();
}
@PutMapping("/policies/{id}")
@PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'manage')")
public ResponseEntity<ApiResponse<AuthorizationPolicyDto>> updatePolicy(@PathVariable Long id,
@Valid @RequestBody AuthorizationPolicyRequest body) {
throw rawPolicyWritesRetired();
}
@GetMapping("/roles/{roleId}/policies")
@PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'read')")
public ResponseEntity<ApiResponse<Map<String, Object>>> rolePolicies(@PathVariable Long roleId) {
adminService.assertInternalPolicyAdmin(AuditUtil.getCurrentUserId());
Map<String,Object> result = new LinkedHashMap<>();
result.put("policyIds", adminService.rolePolicyIds(roleId));
return ResponseEntity.ok(ApiResponse.success(result));
}
@PutMapping("/roles/{roleId}/policies")
@PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'manage')")
public ResponseEntity<ApiResponse<Void>> replaceRolePolicies(@PathVariable Long roleId,
@RequestBody Map<String, Object> body) {
throw rawPolicyWritesRetired();
}
@PostMapping("/bindings")
@PreAuthorize("@permissionChecker.check(authentication, 'iam.binding', 'manage')")
public ResponseEntity<ApiResponse<Map<String, Object>>> createBinding(@RequestBody Map<String, Object> body) {
throw rawPolicyWritesRetired();
}
@GetMapping("/bindings")
@PreAuthorize("@permissionChecker.check(authentication, 'iam.binding', 'manage')")
public ResponseEntity<ApiResponse<AuthorizationBindingPageDto>> bindings(
@Valid @ModelAttribute AuthorizationBindingQueryRequest query) {
UserPrincipal principal = currentPrincipal();
return ResponseEntity.ok(ApiResponse.success(
adminService.listBindings(query, principal.getId(), principal.getTenantId())));
}
@DeleteMapping("/bindings/{id}")
@PreAuthorize("@permissionChecker.check(authentication, 'iam.binding', 'manage')")
public ResponseEntity<ApiResponse<Void>> deleteBinding(@PathVariable Long id) {
adminService.deleteSubjectBinding(id, AuditUtil.getCurrentUserId());
return ResponseEntity.ok(ApiResponse.success());
}
@GetMapping("/sod-rules")
@PreAuthorize("@permissionChecker.check(authentication, 'iam.policy', 'read')")
public ResponseEntity<ApiResponse<java.util.List<Map<String, Object>>>> sodRules() {
adminService.assertInternalPolicyAdmin(AuditUtil.getCurrentUserId());
return ResponseEntity.ok(ApiResponse.success(adminService.listSodRules()));
}
private SubjectContext currentSubject() {
return authorizationService.subject(currentPrincipal());
}
private UserPrincipal currentPrincipal() {
UserPrincipal principal = AuditUtil.getCurrentUser();
if (principal == null) throw new org.springframework.security.access.AccessDeniedException("Authentication required");
return principal;
}
private String text(Map<String, Object> body, String key) {
String value = optionalText(body, key);
if (value == null) throw new com.finance.system.exception.BadRequestException(key + "不能为空");
return value;
}
private String optionalText(Map<String, Object> body, String key) {
Object value = body == null ? null : body.get(key);
if (!(value instanceof String)) return null;
String text = ((String) value).trim();
if (text.isEmpty() || text.length() > 120) return null;
return text;
}
private Long optionalLong(Map<String, Object> body, String key) {
Object value = body == null ? null : body.get(key);
if (value == null) return null;
if (!(value instanceof Number)) throw new com.finance.system.exception.BadRequestException(key + "必须是整数");
long parsed = ((Number) value).longValue();
if (parsed <= 0) throw new com.finance.system.exception.BadRequestException(key + "必须是正整数");
return parsed;
}
private com.finance.system.exception.BusinessException rawPolicyWritesRetired() {
return new com.finance.system.exception.BusinessException("原始授权策略写入接口已停用,请使用角色授权档案", 410);
}
}
@@ -0,0 +1,26 @@
package com.finance.system.authorization;
import lombok.Builder;
import lombok.Singular;
import lombok.Value;
import java.util.List;
import java.util.Map;
@Value
@Builder
public class AuthorizationDecision {
boolean allowed;
String reasonCode;
DataScope resolvedScope;
@Singular List<Long> matchedPolicyIds;
@Singular("fieldAccess") Map<String, FieldAccess> fieldAccess;
long policyVersion;
boolean shadow;
Boolean legacyAllowed;
public FieldAccess accessFor(String fieldCode) {
FieldAccess value = fieldAccess == null ? null : fieldAccess.get(fieldCode);
return value == null ? FieldAccess.HIDDEN : value;
}
}
@@ -0,0 +1,73 @@
package com.finance.system.authorization;
import com.finance.system.audit.AuditEventCommand;
import com.finance.system.audit.AuditPort;
import lombok.RequiredArgsConstructor;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.Collections;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
/** Persists authorization denials independently from the rejected business transaction. */
@Service
@RequiredArgsConstructor
public class AuthorizationDenialAuditService {
private final AuditPort auditPort;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void record(AuthorizationRequest request, AuthorizationDecision decision) {
SubjectContext subject = request == null ? null : request.getSubject();
String resource = safeCode(request == null ? null : request.getResource(), "unknown");
String action = safeCode(request == null ? null : request.getAction(), "unknown");
String reason = safeCode(decision == null ? null : decision.getReasonCode(), "UNKNOWN_DENY");
String resourceId = resource + ":" + action;
if (resourceId.length() > 128) resourceId = resourceId.substring(0, 128);
LinkedHashSet<String> uniquePolicyIds = new LinkedHashSet<>();
if (decision != null && decision.getMatchedPolicyIds() != null) {
for (Long id : decision.getMatchedPolicyIds()) {
if (id != null && id > 0) uniquePolicyIds.add(String.valueOf(id));
}
}
int matchedPolicyCount = uniquePolicyIds.size();
List<String> policyIds = new ArrayList<>(Math.min(matchedPolicyCount,
AuthorizationAuditSchemaContributor.MAX_MATCHED_POLICY_IDS));
for (String policyId : uniquePolicyIds) {
if (policyIds.size() >= AuthorizationAuditSchemaContributor.MAX_MATCHED_POLICY_IDS) break;
policyIds.add(policyId);
}
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("resource", resource);
attributes.put("action", action);
attributes.put("reason", reason);
attributes.put("policyVersion", decision == null ? 0L : decision.getPolicyVersion());
attributes.put("matchedPolicyIds", policyIds);
attributes.put("matchedPolicyCount", matchedPolicyCount);
attributes.put("truncated", matchedPolicyCount > policyIds.size());
auditPort.emit(AuditEventCommand.builder().eventTime(Instant.now())
.tenantId(safeTenant(subject == null ? null : subject.getTenantId()))
.category("SECURITY").action("security.authorization.denied").outcome("DENIED")
.reasonCode(reason).actorType(subject == null ? "ANONYMOUS" : "USER")
.actorId(subject == null ? null : subject.getUserId())
.resourceType("AUTHORIZATION").resourceId(resourceId)
.requestId(MDC.get("request_id")).source("INTERNAL")
.changes(Collections.<String, Object>emptyMap()).attributes(attributes).build());
}
private String safeCode(String value, String fallback) {
if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,119}")) return fallback;
return value;
}
private String safeTenant(String value) {
if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,63}")) return "default";
return value;
}
}
@@ -0,0 +1,21 @@
package com.finance.system.authorization;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@NoArgsConstructor
@Entity
@Table(name = "authz_field_rule")
public class AuthorizationFieldRuleEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "policy_id", nullable = false)
private Long policyId;
@Column(name = "field_code", nullable = false, length = 120)
private String fieldCode;
@Enumerated(EnumType.STRING) @Column(name = "field_access", nullable = false, length = 16)
private FieldAccess fieldAccess;
}
@@ -0,0 +1,12 @@
package com.finance.system.authorization;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Collection;
import java.util.List;
public interface AuthorizationFieldRuleRepository extends JpaRepository<AuthorizationFieldRuleEntity, Long> {
List<AuthorizationFieldRuleEntity> findByPolicyIdIn(Collection<Long> policyIds);
List<AuthorizationFieldRuleEntity> findByPolicyId(Long policyId);
void deleteByPolicyId(Long policyId);
}
@@ -0,0 +1,6 @@
package com.finance.system.authorization;
public enum AuthorizationMode {
SHADOW,
ENFORCE
}
@@ -0,0 +1,42 @@
package com.finance.system.authorization;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
import java.io.Serializable;
@Data
@NoArgsConstructor
@Entity
@Table(name = "authz_permission_policy_map")
public class AuthorizationPermissionPolicyMapEntity {
@EmbeddedId
private Id id;
@Enumerated(EnumType.STRING)
@Column(name = "min_access_level", nullable = false, length = 8)
private RolePermissionAccess minAccessLevel;
@Enumerated(EnumType.STRING)
@Column(name = "mapping_type", nullable = false, length = 16)
private PermissionPolicyMappingType mappingType;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Embeddable
public static class Id implements Serializable {
@Column(name = "permission_id")
private Long permissionId;
@Column(name = "policy_id")
private Long policyId;
}
}
@@ -0,0 +1,10 @@
package com.finance.system.authorization;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Collection;
import java.util.List;
public interface AuthorizationPermissionPolicyMapRepository extends JpaRepository<AuthorizationPermissionPolicyMapEntity, AuthorizationPermissionPolicyMapEntity.Id> {
List<AuthorizationPermissionPolicyMapEntity> findByIdPermissionIdIn(Collection<Long> permissionIds);
}
@@ -0,0 +1,29 @@
package com.finance.system.authorization;
import lombok.Builder;
import lombok.Value;
import java.time.LocalDateTime;
import java.util.Map;
/** Public canonical policy representation; never exposes the JPA entity. */
@Value
@Builder
public class AuthorizationPolicyDto {
Long id;
String policyCode;
String resource;
String action;
PolicyEffect effect;
DataScope dataScope;
String scopeParameter;
Integer priority;
Boolean enabled;
Boolean delegable;
PolicyRiskLevel riskLevel;
Boolean protectedPolicy;
LocalDateTime validFrom;
LocalDateTime validUntil;
Long version;
Map<String, FieldAccess> fieldAccess;
}
@@ -0,0 +1,54 @@
package com.finance.system.authorization;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@Entity
@Table(name = "authz_policy")
public class AuthorizationPolicyEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "policy_code", nullable = false, length = 120, unique = true)
private String policyCode;
@Column(name = "resource_code", nullable = false, length = 80)
private String resourceCode;
@Column(name = "action_code", nullable = false, length = 80)
private String actionCode;
@Enumerated(EnumType.STRING) @Column(nullable = false, length = 10)
private PolicyEffect effect;
@Enumerated(EnumType.STRING) @Column(name = "data_scope", nullable = false, length = 24)
private DataScope dataScope;
@Column(name = "scope_parameter", length = 120)
private String scopeParameter;
@Column(nullable = false)
private Integer priority;
@Column(nullable = false)
private Boolean enabled;
@Column(nullable = false)
private Boolean delegable;
@Enumerated(EnumType.STRING)
@Column(name = "risk_level", nullable = false, length = 16)
private PolicyRiskLevel riskLevel;
@Column(name = "protected_policy", nullable = false)
private Boolean protectedPolicy;
@Column(name = "valid_from")
private LocalDateTime validFrom;
@Column(name = "valid_until")
private LocalDateTime validUntil;
@Version @Column(name = "record_version", nullable = false)
private Long recordVersion;
@Column(name = "created_at", nullable = false)
private LocalDateTime createdAt;
@Column(name = "updated_at", nullable = false)
private LocalDateTime updatedAt;
public boolean activeAt(LocalDateTime now) {
return Boolean.TRUE.equals(enabled) && (validFrom == null || !validFrom.isAfter(now))
&& (validUntil == null || validUntil.isAfter(now));
}
}
@@ -0,0 +1,157 @@
package com.finance.system.authorization;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.*;
import java.util.regex.Pattern;
/** Pure, default-deny policy evaluator. DENY always wins over ALLOW. */
@Component
public class AuthorizationPolicyEvaluator {
private static final Pattern PART = Pattern.compile("[a-z][a-z0-9_.-]{0,79}");
public AuthorizationDecision evaluate(AuthorizationRequest request,
Collection<EffectivePolicy> candidates,
long policyVersion) {
if (!isValid(request)) return denied("INVALID_REQUEST", policyVersion, Collections.<Long>emptyList());
String resource = normalizePart(request.getResource());
String action = normalizePart(request.getAction());
List<EffectivePolicy> matched = new ArrayList<>();
if (candidates != null) {
for (EffectivePolicy policy : candidates) {
if (policy == null || policy.getEffect() == null || policy.getDataScope() == null) continue;
if (!matchesPart(policy.getResource(), resource) || !matchesPart(policy.getAction(), action)) continue;
if (matchesScope(request.getSubject(), request.getResourceContext(), policy)) matched.add(policy);
}
}
matched.sort(Comparator.comparingInt(EffectivePolicy::getPriority).reversed()
.thenComparing(p -> p.getPolicyId() == null ? Long.MAX_VALUE : p.getPolicyId()));
List<Long> ids = policyIds(matched);
for (EffectivePolicy policy : matched) {
if (policy.getEffect() == PolicyEffect.DENY) return denied("EXPLICIT_DENY", policyVersion, ids);
}
List<EffectivePolicy> allows = new ArrayList<>();
for (EffectivePolicy policy : matched) if (policy.getEffect() == PolicyEffect.ALLOW) allows.add(policy);
if (allows.isEmpty()) return denied("DEFAULT_DENY", policyVersion, ids);
Map<String, FieldAccess> fields = new TreeMap<>();
DataScope scope = null;
for (EffectivePolicy policy : allows) {
scope = broader(scope, policy.getDataScope());
if (policy.getFieldAccess() == null) continue;
for (Map.Entry<String, FieldAccess> entry : policy.getFieldAccess().entrySet()) {
String field = normalizeField(entry.getKey());
if (field != null) fields.put(field, FieldAccess.stronger(fields.get(field), entry.getValue()));
}
}
return AuthorizationDecision.builder().allowed(true).reasonCode("ALLOW_POLICY")
.resolvedScope(scope).matchedPolicyIds(ids).fieldAccess(fields)
.policyVersion(policyVersion).shadow(false).build();
}
public String normalizePart(String value) {
if (!StringUtils.hasText(value)) return null;
String normalized = value.trim().toLowerCase(Locale.ROOT);
if (!PART.matcher(normalized).matches()) return null;
return normalized;
}
public String permissionCode(String resource, String action) {
String normalizedResource = normalizePart(resource);
String normalizedAction = normalizePart(action);
if (normalizedResource == null || normalizedAction == null) return null;
return normalizedResource + ":" + normalizedAction;
}
private boolean isValid(AuthorizationRequest request) {
return request != null && request.getSubject() != null
&& request.getSubject().getUserId() != null
&& normalizePart(request.getResource()) != null
&& normalizePart(request.getAction()) != null;
}
private boolean matchesPart(String configured, String actual) {
if ("*".equals(configured)) return true;
String normalized = normalizePart(configured);
return normalized != null && normalized.equals(actual);
}
private boolean matchesScope(SubjectContext subject, ResourceContext resource, EffectivePolicy policy) {
switch (policy.getDataScope()) {
case GLOBAL:
return resource != null && resource.isExplicitGlobal();
case ALL:
return sameIsolationBoundary(subject, resource);
case SELF:
return resource != null && Objects.equals(subject.getUserId(), resource.getOwnerId())
&& sameIsolationBoundary(subject, resource);
case CURRENT_APPROVER:
return resource != null && Objects.equals(subject.getUserId(), resource.getCurrentApproverId())
&& sameIsolationBoundary(subject, resource);
case DEPARTMENT:
return resource != null && subject.getDepartmentId() != null
&& Objects.equals(subject.getDepartmentId(), resource.getDepartmentId())
&& matchesScopeParameter(resource.getDepartmentId(), policy.getScopeParameter())
&& sameIsolationBoundary(subject, resource);
case DEPARTMENT_TREE:
return resource != null && resource.getDepartmentId() != null
&& (Objects.equals(subject.getDepartmentId(), resource.getDepartmentId())
|| subject.safeDepartmentTreeIds().contains(resource.getDepartmentId()))
&& matchesScopeParameter(resource.getDepartmentId(), policy.getScopeParameter())
&& sameIsolationBoundary(subject, resource);
default:
return false;
}
}
private boolean sameIsolationBoundary(SubjectContext subject, ResourceContext resource) {
return resource != null && StringUtils.hasText(subject.getTenantId())
&& StringUtils.hasText(resource.getTenantId())
&& subject.getOrganizationId() != null && resource.getOrganizationId() != null
&& subject.getTenantId().equals(resource.getTenantId())
&& Objects.equals(subject.getOrganizationId(), resource.getOrganizationId());
}
private boolean matchesScopeParameter(Long resourceDepartmentId, String configured) {
if (!StringUtils.hasText(configured)) return true;
try {
return Objects.equals(resourceDepartmentId, Long.valueOf(configured.trim()));
} catch (NumberFormatException ex) {
return false;
}
}
private String normalizeField(String value) {
if (!StringUtils.hasText(value)) return null;
String field = value.trim();
return field.matches("[A-Za-z][A-Za-z0-9_.-]{0,119}") ? field : null;
}
private List<Long> policyIds(List<EffectivePolicy> policies) {
List<Long> result = new ArrayList<>();
for (EffectivePolicy policy : policies) if (policy.getPolicyId() != null) result.add(policy.getPolicyId());
return result;
}
private AuthorizationDecision denied(String reason, long version, List<Long> ids) {
return AuthorizationDecision.builder().allowed(false).reasonCode(reason)
.matchedPolicyIds(ids).fieldAccess(Collections.<String, FieldAccess>emptyMap())
.policyVersion(version).shadow(false).build();
}
private DataScope broader(DataScope left, DataScope right) {
if (left == null) return right;
if (right == null) return left;
return scopeRank(left) >= scopeRank(right) ? left : right;
}
private int scopeRank(DataScope scope) {
if (scope == DataScope.GLOBAL) return 6;
if (scope == DataScope.ALL) return 5;
if (scope == DataScope.DEPARTMENT_TREE) return 4;
if (scope == DataScope.DEPARTMENT) return 3;
if (scope == DataScope.CURRENT_APPROVER) return 2;
return 1;
}
}
@@ -0,0 +1,9 @@
package com.finance.system.authorization;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface AuthorizationPolicyRepository extends JpaRepository<AuthorizationPolicyEntity, Long> {
Optional<AuthorizationPolicyEntity> findByPolicyCode(String policyCode);
}
@@ -0,0 +1,55 @@
package com.finance.system.authorization;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.LinkedHashMap;
import java.util.Map;
/** Controlled create/update payload for canonical policies. */
@Data
public class AuthorizationPolicyRequest {
@NotBlank @Size(max = 120)
private String policyCode;
@NotBlank @Pattern(regexp = "[a-z][a-z0-9_.-]{0,79}")
private String resource;
@NotBlank @Pattern(regexp = "[a-z][a-z0-9_.-]{0,79}")
private String action;
@NotNull
private PolicyEffect effect;
@NotNull
private DataScope dataScope;
@Size(max = 120)
private String scopeParameter;
@Min(-10000) @Max(10000)
private Integer priority;
private Boolean enabled;
private Boolean delegable;
private PolicyRiskLevel riskLevel;
@JsonProperty("protected")
private Boolean protectedPolicy;
@Size(max = 200)
private Map<String, FieldAccess> fieldAccess;
Map<String,Object> toMap() {
Map<String,Object> values = new LinkedHashMap<>();
values.put("policyCode", policyCode); values.put("resource", resource); values.put("action", action);
values.put("effect", effect == null ? null : effect.name());
values.put("dataScope", dataScope == null ? null : dataScope.name());
put(values, "scopeParameter", scopeParameter); put(values, "priority", priority);
put(values, "enabled", enabled); put(values, "delegable", delegable);
put(values, "riskLevel", riskLevel == null ? null : riskLevel.name());
put(values, "protected", protectedPolicy); put(values, "fieldAccess", fieldAccess);
return values;
}
private void put(Map<String,Object> values, String key, Object value) {
if (value != null) values.put(key, value);
}
}
@@ -0,0 +1,19 @@
package com.finance.system.authorization;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@Entity
@Table(name = "authz_policy_version")
public class AuthorizationPolicyVersionEntity {
@Id private Integer id;
@Column(name = "policy_version", nullable = false)
private Long policyVersion;
@Column(name = "updated_at", nullable = false)
private LocalDateTime updatedAt;
}
@@ -0,0 +1,11 @@
package com.finance.system.authorization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
public interface AuthorizationPolicyVersionRepository extends JpaRepository<AuthorizationPolicyVersionEntity, Integer> {
@Modifying
@Query("update AuthorizationPolicyVersionEntity v set v.policyVersion = v.policyVersion + 1, v.updatedAt = CURRENT_TIMESTAMP where v.id = 1")
int incrementPolicyVersion();
}
@@ -0,0 +1,17 @@
package com.finance.system.authorization;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "authorization")
public class AuthorizationProperties {
/** Safe rollout default: observe new decisions while legacy callers remain compatible. */
private AuthorizationMode mode = AuthorizationMode.SHADOW;
private boolean legacyAdapterEnabled = true;
public AuthorizationMode getMode() { return mode; }
public void setMode(AuthorizationMode mode) { this.mode = mode == null ? AuthorizationMode.SHADOW : mode; }
public boolean isLegacyAdapterEnabled() { return legacyAdapterEnabled; }
public void setLegacyAdapterEnabled(boolean legacyAdapterEnabled) { this.legacyAdapterEnabled = legacyAdapterEnabled; }
}
@@ -0,0 +1,13 @@
package com.finance.system.authorization;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class AuthorizationRequest {
SubjectContext subject;
String resource;
String action;
ResourceContext resourceContext;
}
@@ -0,0 +1,41 @@
package com.finance.system.authorization;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "authz_role_policy")
public class AuthorizationRolePolicyEntity {
@EmbeddedId
private Id id;
@Enumerated(EnumType.STRING)
@Column(name = "assignment_source", nullable = false, length = 16)
private AuthorizationAssignmentSource assignmentSource;
public AuthorizationRolePolicyEntity(Long roleId, Long policyId) {
this.id = new Id(roleId, policyId);
this.assignmentSource = AuthorizationAssignmentSource.LEGACY;
}
public AuthorizationRolePolicyEntity(Long roleId, Long policyId, AuthorizationAssignmentSource assignmentSource) {
this.id = new Id(roleId, policyId);
this.assignmentSource = assignmentSource;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Embeddable
public static class Id implements Serializable {
@Column(name = "role_id") private Long roleId;
@Column(name = "policy_id") private Long policyId;
}
}
@@ -0,0 +1,30 @@
package com.finance.system.authorization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.Collection;
import java.util.List;
public interface AuthorizationRolePolicyRepository extends JpaRepository<AuthorizationRolePolicyEntity, AuthorizationRolePolicyEntity.Id> {
List<AuthorizationRolePolicyEntity> findByIdRoleIdIn(Collection<Long> roleIds);
List<AuthorizationRolePolicyEntity> findByIdRoleId(Long roleId);
List<AuthorizationRolePolicyEntity> findByIdRoleIdAndAssignmentSource(Long roleId, AuthorizationAssignmentSource assignmentSource);
List<AuthorizationRolePolicyEntity> findByIdPolicyId(Long policyId);
void deleteByIdRoleId(Long roleId);
@Modifying(flushAutomatically = true, clearAutomatically = true)
@Query(value = "UPDATE authz_role_policy rp JOIN authz_policy p ON p.id = rp.policy_id "
+ "SET rp.assignment_source = 'SYSTEM' "
+ "WHERE rp.role_id = :roleId AND p.effect = 'DENY' AND rp.assignment_source <> 'SYSTEM'", nativeQuery = true)
int protectDenyByRoleId(@Param("roleId") Long roleId);
@Modifying(flushAutomatically = true, clearAutomatically = true)
@Query(value = "DELETE rp FROM authz_role_policy rp JOIN authz_policy p ON p.id = rp.policy_id "
+ "WHERE rp.role_id = :roleId AND rp.assignment_source <> 'SYSTEM' "
+ "AND p.effect = 'ALLOW' AND p.delegable = TRUE AND p.protected_policy = FALSE "
+ "AND p.risk_level IS NOT NULL AND p.risk_level <> 'CRITICAL' "
+ "AND EXISTS (SELECT 1 FROM authz_permission_policy_map ppm "
+ "WHERE ppm.policy_id = rp.policy_id AND ppm.mapping_type = 'BUSINESS')", nativeQuery = true)
int deleteReplaceableBusinessMappedByRoleId(@Param("roleId") Long roleId);
}
@@ -0,0 +1,21 @@
package com.finance.system.authorization;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@Entity
@Table(name = "authz_role_profile_version")
public class AuthorizationRoleProfileVersionEntity {
@Id
@Column(name = "role_id")
private Long roleId;
@Column(nullable = false)
private Long version;
@Column(name = "updated_at", nullable = false)
private LocalDateTime updatedAt;
}
@@ -0,0 +1,21 @@
package com.finance.system.authorization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.repository.query.Param;
import javax.persistence.LockModeType;
import java.util.Optional;
public interface AuthorizationRoleProfileVersionRepository extends JpaRepository<AuthorizationRoleProfileVersionEntity, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select v from AuthorizationRoleProfileVersionEntity v where v.roleId = :roleId")
Optional<AuthorizationRoleProfileVersionEntity> findByRoleIdForUpdate(@Param("roleId") Long roleId);
@Modifying
@Query(value = "INSERT INTO authz_role_profile_version(role_id,version,updated_at) VALUES (:roleId,1,CURRENT_TIMESTAMP(6)) " +
"ON DUPLICATE KEY UPDATE version=version+1,updated_at=CURRENT_TIMESTAMP(6)", nativeQuery = true)
int bumpRoleVersion(@Param("roleId") Long roleId);
}
@@ -0,0 +1,339 @@
package com.finance.system.authorization;
import com.finance.system.adapter.feishu.FeishuDirectoryAccessService;
import com.finance.system.entity.SysUserGroupMember;
import com.finance.system.entity.SysUserGroupRole;
import com.finance.system.entity.SysRole;
import com.finance.system.entity.SysUser;
import com.finance.system.entity.SysUserGroup;
import com.finance.system.entity.SysUserRole;
import com.finance.system.repository.SysUserGroupMemberRepository;
import com.finance.system.repository.SysUserGroupRoleRepository;
import com.finance.system.repository.SysUserGroupRepository;
import com.finance.system.repository.SysUserRepository;
import com.finance.system.repository.SysRoleRepository;
import com.finance.system.repository.SysUserRoleRepository;
import com.finance.system.repository.SysDepartmentRepository;
import com.finance.system.entity.SysDepartment;
import com.finance.system.security.UserPrincipal;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthorizationService {
private static final String DEFAULT_EMPLOYEE_GROUP = "DEFAULT_EMPLOYEE";
private static final String EMPLOYEE_ROLE = "EMPLOYEE";
private final AuthorizationPolicyEvaluator evaluator;
private final AuthorizationPolicyRepository policies;
private final AuthorizationRolePolicyRepository rolePolicies;
private final AuthorizationSubjectRoleBindingRepository subjectBindings;
private final AuthorizationFieldRuleRepository fieldRules;
private final AuthorizationPolicyVersionRepository versions;
private final SysUserGroupMemberRepository groupMembers;
private final SysUserGroupRoleRepository legacyGroupRoles;
private final SysUserRoleRepository legacyUserRoles;
private final SysUserRepository users;
private final SysUserGroupRepository groups;
private final SysRoleRepository roles;
private final SysDepartmentRepository departments;
private final LegacyPermissionAdapter legacyAdapter;
private final AuthorizationProperties properties;
private final AuthorizationDenialAuditService denialAudit;
private AuthorizationShadowMetrics shadowMetrics;
private FeishuDirectoryAccessService directoryAccess;
@Autowired
void setShadowMetrics(AuthorizationShadowMetrics shadowMetrics) {
this.shadowMetrics = shadowMetrics;
}
@Autowired(required = false)
void setDirectoryAccess(FeishuDirectoryAccessService directoryAccess) {
this.directoryAccess = directoryAccess;
}
@Transactional(readOnly = true)
public AuthorizationDecision evaluate(AuthorizationRequest request) {
if (request == null || request.getSubject() == null) {
return evaluator.evaluate(request, Collections.<EffectivePolicy>emptyList(), policyVersion());
}
return evaluator.evaluate(request, loadEffectivePolicies(request.getSubject()), policyVersion());
}
/** Always enforces the canonical decision; rollout mode does not weaken this API. */
@Transactional(readOnly = true)
public AuthorizationDecision check(AuthorizationRequest request) {
AuthorizationDecision decision = evaluate(request);
if (!decision.isAllowed()) {
try {
denialAudit.record(request, decision);
} catch (RuntimeException ex) {
log.error("授权拒绝审计记录失败 authorization_denial_audit_failed reason={}", safeCode(decision.getReasonCode()));
}
throw new AccessDeniedException("Authorization denied: " + decision.getReasonCode());
}
return decision;
}
@Transactional(readOnly = true)
public boolean can(AuthorizationRequest request) {
return evaluate(request).isAllowed();
}
/** Legacy method-security bridge. SHADOW preserves the legacy result; ENFORCE uses only the canonical result. */
@Transactional(readOnly = true)
public boolean evaluateLegacy(SubjectContext subject, String legacyPermissionCode,
boolean edit, boolean legacyAllowed) {
if (!properties.isLegacyAdapterEnabled()) return false;
LegacyPermissionAdapter.CanonicalPermission canonical = legacyAdapter.adapt(legacyPermissionCode, edit);
AuthorizationDecision canonicalDecision;
if (canonical == null || canonical.getResource().startsWith("ui.page")) {
canonicalDecision = AuthorizationDecision.builder().allowed(false)
.reasonCode(canonical == null ? "LEGACY_UNMAPPED" : "UI_PERMISSION_NOT_BUSINESS_AUTHORITY")
.policyVersion(policyVersion()).shadow(true).legacyAllowed(legacyAllowed).build();
} else {
ResourceContext context = canonical.getResource().startsWith("iam.")
? ResourceContext.global(canonical.getResource())
: ResourceContext.unscoped(canonical.getResource());
canonicalDecision = evaluate(AuthorizationRequest.builder().subject(subject)
.resource(canonical.getResource()).action(canonical.getAction())
.resourceContext(context).build());
}
if (canonicalDecision.isAllowed() != legacyAllowed) {
log.warn("授权影子校验结果不一致 authorization_shadow_mismatch code={} canonical={} legacy={} reason={}",
safeCode(legacyPermissionCode), canonicalDecision.isAllowed(), legacyAllowed,
canonicalDecision.getReasonCode());
}
if (shadowMetrics != null) shadowMetrics.record(canonicalDecision.isAllowed(), legacyAllowed);
return properties.getMode() == AuthorizationMode.SHADOW ? legacyAllowed : canonicalDecision.isAllowed();
}
@Transactional(readOnly = true)
public <T> List<T> filter(SubjectContext subject, String resource, String action,
Collection<T> values, Function<T, ResourceContext> contextFactory) {
List<T> result = new ArrayList<>();
if (values == null || contextFactory == null) return result;
for (T value : values) {
AuthorizationRequest request = AuthorizationRequest.builder().subject(subject)
.resource(resource).action(action).resourceContext(contextFactory.apply(value)).build();
if (evaluate(request).isAllowed()) result.add(value);
}
return result;
}
/** Applies server-side read obligations to a flat DTO/map. Unknown fields default to HIDDEN. */
public Map<String, Object> project(Map<String, Object> source, AuthorizationDecision decision) {
Map<String, Object> result = new LinkedHashMap<>();
if (source == null || decision == null || !decision.isAllowed()) return result;
for (Map.Entry<String, Object> entry : source.entrySet()) {
FieldAccess access = decision.accessFor(entry.getKey());
if (access == FieldAccess.READ || access == FieldAccess.EDIT) result.put(entry.getKey(), entry.getValue());
else if (access == FieldAccess.MASKED) result.put(entry.getKey(), mask(entry.getValue()));
}
return result;
}
@Transactional(readOnly = true)
public Set<String> capabilities(SubjectContext subject) {
Set<String> result = new TreeSet<>();
if (subject == null || subject.getUserId() == null) return result;
LocalDateTime now = LocalDateTime.now();
List<EffectivePolicy> effectivePolicies = loadEffectivePolicies(subject, now);
long version = policyVersion();
for (AuthorizationPolicyEntity policy : safe(policies.findAll())) {
if (policy == null || !policy.activeAt(now)) continue;
String permissionCode = evaluator.permissionCode(policy.getResourceCode(), policy.getActionCode());
if (permissionCode == null || permissionCode.trim().isEmpty()) continue;
ResourceContext context = policy.getDataScope() == DataScope.GLOBAL
? ResourceContext.global(policy.getResourceCode())
: ResourceContext.builder().resourceType(policy.getResourceCode())
.ownerId(subject.getUserId()).currentApproverId(subject.getUserId())
.tenantId(subject.getTenantId()).departmentId(subject.getDepartmentId())
.organizationId(subject.getOrganizationId()).build();
AuthorizationDecision decision = evaluator.evaluate(AuthorizationRequest.builder().subject(subject)
.resource(policy.getResourceCode()).action(policy.getActionCode())
.resourceContext(context).build(), effectivePolicies, version);
if (decision.isAllowed()) result.add(permissionCode);
}
return result;
}
public SubjectContext subject(UserPrincipal principal) {
if (principal == null) return null;
SubjectContext.SubjectContextBuilder builder = SubjectContext.builder().userId(principal.getId())
.tenantId(principal.getTenantId()).organizationId(principal.getOrganizationId())
.departmentId(principal.getDepartmentId());
for (Long departmentId : departmentTree(principal.getDepartmentId())) builder.departmentTreeId(departmentId);
return builder.build();
}
private Set<Long> departmentTree(Long rootId) {
if (rootId == null) return Collections.emptySet();
Map<Long,List<Long>> children = new HashMap<>();
List<SysDepartment> activeDepartments = departments.findByStatus("ACTIVE");
if (activeDepartments == null) activeDepartments = Collections.emptyList();
for (SysDepartment department : activeDepartments) {
if (department.getId() == null || department.getParentId() == null) continue;
children.computeIfAbsent(department.getParentId(), key -> new ArrayList<>()).add(department.getId());
}
Set<Long> result = new LinkedHashSet<>();
Deque<Long> queue = new ArrayDeque<>();
queue.add(rootId);
while (!queue.isEmpty() && result.size() < 10000) {
Long current = queue.removeFirst();
if (!result.add(current)) continue;
for (Long child : children.getOrDefault(current, Collections.<Long>emptyList())) queue.addLast(child);
}
return result;
}
private List<EffectivePolicy> loadEffectivePolicies(SubjectContext subject) {
return loadEffectivePolicies(subject, LocalDateTime.now());
}
private List<EffectivePolicy> loadEffectivePolicies(SubjectContext subject, LocalDateTime now) {
Map<Long, List<RoleGrant>> grants = roleGrants(subject, now);
if (grants.isEmpty()) return Collections.emptyList();
List<AuthorizationRolePolicyEntity> links = rolePolicies.findByIdRoleIdIn(grants.keySet());
Set<Long> policyIds = new LinkedHashSet<>();
for (AuthorizationRolePolicyEntity link : links) {
if (link != null && link.getId() != null && link.getId().getPolicyId() != null) policyIds.add(link.getId().getPolicyId());
}
if (policyIds.isEmpty()) return Collections.emptyList();
Map<Long, AuthorizationPolicyEntity> policyById = new HashMap<>();
for (AuthorizationPolicyEntity policy : policies.findAllById(policyIds)) {
if (policy.activeAt(now)) policyById.put(policy.getId(), policy);
}
Map<Long, Map<String, FieldAccess>> fieldsByPolicy = new HashMap<>();
for (AuthorizationFieldRuleEntity rule : fieldRules.findByPolicyIdIn(policyIds)) {
if (rule.getPolicyId() == null || rule.getFieldAccess() == null) continue;
fieldsByPolicy.computeIfAbsent(rule.getPolicyId(), k -> new LinkedHashMap<>())
.merge(rule.getFieldCode(), rule.getFieldAccess(), FieldAccess::stronger);
}
List<EffectivePolicy> result = new ArrayList<>();
for (AuthorizationRolePolicyEntity link : links) {
if (link == null || link.getId() == null) continue;
AuthorizationPolicyEntity policy = policyById.get(link.getId().getPolicyId());
if (policy == null) continue;
for (RoleGrant grant : grants.getOrDefault(link.getId().getRoleId(), Collections.<RoleGrant>emptyList())) {
DataScope scope = grant.scopeOverride == null ? policy.getDataScope() : grant.scopeOverride;
String scopeParameter = grant.scopeReferenceId == null ? policy.getScopeParameter()
: String.valueOf(grant.scopeReferenceId);
result.add(EffectivePolicy.builder().policyId(policy.getId()).resource(policy.getResourceCode())
.action(policy.getActionCode()).effect(policy.getEffect()).dataScope(scope)
.scopeParameter(scopeParameter).priority(policy.getPriority() == null ? 0 : policy.getPriority())
.fieldAccess(fieldsByPolicy.getOrDefault(policy.getId(), Collections.<String, FieldAccess>emptyMap()))
.build());
}
}
return result;
}
private Map<Long, List<RoleGrant>> roleGrants(SubjectContext subject, LocalDateTime now) {
Map<Long, List<RoleGrant>> result = new LinkedHashMap<>();
SysUser user = users.findById(subject.getUserId()).orElse(null);
if (user == null || !isActive(user.getStatus())) return result;
if (!Objects.equals(user.getTenantId(), subject.getTenantId())
|| !Objects.equals(user.getOrganizationId(), subject.getOrganizationId())
|| !Objects.equals(user.getDepartmentId(), subject.getDepartmentId())) return result;
for (SysUserRole link : safe(legacyUserRoles.findByIdUserId(subject.getUserId()))) {
if (link != null && link.getId() != null) addGrant(result, link.getId().getRoleId(), null, null);
}
Set<Long> candidateGroupIds = new LinkedHashSet<>();
for (SysUserGroupMember membership : safe(groupMembers.findByIdUserId(subject.getUserId()))) {
if (membership != null && membership.getId() != null) candidateGroupIds.add(membership.getId().getGroupId());
}
if (isDynamicDefaultEmployee(user)) {
roles.findByRoleCode(EMPLOYEE_ROLE)
.filter(role -> role.getId() != null && isActive(role.getStatus()))
.map(SysRole::getId)
.ifPresent(roleId -> addGrant(result, roleId, null, null));
}
Set<Long> groupIds = new LinkedHashSet<>();
if (!candidateGroupIds.isEmpty()) {
for (SysUserGroup group : safe(groups.findAllById(candidateGroupIds))) {
if (group != null && group.getId() != null && isActive(group.getStatus())) groupIds.add(group.getId());
}
}
for (Long groupId : groupIds) {
for (SysUserGroupRole link : safe(legacyGroupRoles.findByIdGroupId(groupId))) {
if (link != null && link.getId() != null) addGrant(result, link.getId().getRoleId(), null, null);
}
}
for (AuthorizationSubjectRoleBindingEntity binding : safe(subjectBindings.findBySubjectTypeAndSubjectId("USER", subject.getUserId()))) {
if (binding != null && binding.activeAt(now)) addGrant(result, binding.getRoleId(), binding.getScopeOverride(), binding.getScopeReferenceId());
}
if (!groupIds.isEmpty()) {
for (AuthorizationSubjectRoleBindingEntity binding : safe(subjectBindings.findBySubjectTypeAndSubjectIdIn("GROUP", groupIds))) {
if (binding != null && binding.activeAt(now)) addGrant(result, binding.getRoleId(), binding.getScopeOverride(), binding.getScopeReferenceId());
}
}
if (!result.isEmpty()) {
Set<Long> activeRoleIds = new LinkedHashSet<>();
for (SysRole role : safe(roles.findAllById(result.keySet()))) {
if (role != null && role.getId() != null && isActive(role.getStatus())) activeRoleIds.add(role.getId());
}
result.keySet().retainAll(activeRoleIds);
}
return result;
}
private boolean isDynamicDefaultEmployee(SysUser user) {
SysUserGroup defaultGroup = groups.findByGroupCode(DEFAULT_EMPLOYEE_GROUP).orElse(null);
return defaultGroup != null
&& DEFAULT_EMPLOYEE_GROUP.equalsIgnoreCase(defaultGroup.getGroupCode())
&& isActive(defaultGroup.getStatus())
&& directoryAccess != null
&& directoryAccess.directoryAllowed(user)
&& user.getDirectoryLastSeenRunId() != null
&& StringUtils.hasText(user.getFeishuOpenId());
}
private boolean isActive(String status) {
return "ACTIVE".equalsIgnoreCase(status);
}
private <T> Iterable<T> safe(Iterable<T> values) {
return values == null ? Collections.<T>emptyList() : values;
}
private void addGrant(Map<Long, List<RoleGrant>> target, Long roleId, DataScope scope, Long ref) {
if (roleId != null) target.computeIfAbsent(roleId, k -> new ArrayList<>()).add(new RoleGrant(scope, ref));
}
private long policyVersion() {
return versions.findById(1).map(AuthorizationPolicyVersionEntity::getPolicyVersion).orElse(0L);
}
private String safeCode(String code) {
if (code == null) return "null";
return code.length() > 120 ? code.substring(0, 120) : code.replaceAll("[^A-Za-z0-9._:-]", "_");
}
private String mask(Object value) {
if (value == null) return null;
String text = String.valueOf(value);
if (text.length() <= 4) return "****";
return text.substring(0, 2) + "****" + text.substring(text.length() - 2);
}
private static final class RoleGrant {
private final DataScope scopeOverride;
private final Long scopeReferenceId;
private RoleGrant(DataScope scopeOverride, Long scopeReferenceId) {
this.scopeOverride = scopeOverride;
this.scopeReferenceId = scopeReferenceId;
}
}
}
@@ -0,0 +1,38 @@
package com.finance.system.authorization;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicLong;
@Component
public class AuthorizationShadowMetrics {
private final Counter allowMismatch;
private final Counter denyMismatch;
private final AtomicLong evaluations = new AtomicLong();
private final AtomicLong mismatches = new AtomicLong();
public AuthorizationShadowMetrics(MeterRegistry registry) {
allowMismatch = Counter.builder("authorization.shadow.allow.mismatch")
.description("Canonical allow while legacy denied").register(registry);
denyMismatch = Counter.builder("authorization.shadow.deny.mismatch")
.description("Canonical deny while legacy allowed").register(registry);
Gauge.builder("authorization.shadow.mismatch.ratio", this, AuthorizationShadowMetrics::ratio)
.description("Canonical/legacy mismatch ratio").register(registry);
}
public void record(boolean canonicalAllowed, boolean legacyAllowed) {
evaluations.incrementAndGet();
if (canonicalAllowed == legacyAllowed) return;
mismatches.incrementAndGet();
if (canonicalAllowed) allowMismatch.increment();
else denyMismatch.increment();
}
double ratio() {
long total = evaluations.get();
return total == 0L ? 0.0d : ((double) mismatches.get()) / total;
}
}
@@ -0,0 +1,29 @@
package com.finance.system.authorization;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@Entity
@Table(name = "authz_sod_rule")
public class AuthorizationSodRuleEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "rule_code", nullable = false, unique = true, length = 120)
private String ruleCode;
@Column(name = "left_duty", nullable = false, length = 80)
private String leftDuty;
@Column(name = "right_duty", nullable = false, length = 80)
private String rightDuty;
@Column(name = "relation_type", nullable = false, length = 32)
private String relationType;
@Column(nullable = false)
private Boolean enabled;
@Column(name = "valid_from") private LocalDateTime validFrom;
@Column(name = "valid_until") private LocalDateTime validUntil;
@Version @Column(name = "record_version", nullable = false) private Long recordVersion;
}
@@ -0,0 +1,9 @@
package com.finance.system.authorization;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface AuthorizationSodRuleRepository extends JpaRepository<AuthorizationSodRuleEntity, Long> {
List<AuthorizationSodRuleEntity> findByEnabledTrue();
}
@@ -0,0 +1,41 @@
package com.finance.system.authorization;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@Entity
@Table(name = "authz_subject_role_binding")
public class AuthorizationSubjectRoleBindingEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "subject_type", nullable = false, length = 16)
private String subjectType;
@Column(name = "subject_id", nullable = false)
private Long subjectId;
@Column(name = "role_id", nullable = false)
private Long roleId;
@Enumerated(EnumType.STRING) @Column(name = "scope_override", length = 24)
private DataScope scopeOverride;
@Column(name = "scope_reference_id")
private Long scopeReferenceId;
@Column(nullable = false)
private Boolean enabled;
@Column(name = "valid_from")
private LocalDateTime validFrom;
@Column(name = "valid_until")
private LocalDateTime validUntil;
@Column(name = "created_by")
private Long createdBy;
@Version @Column(name = "record_version", nullable = false)
private Long recordVersion;
public boolean activeAt(LocalDateTime now) {
return Boolean.TRUE.equals(enabled) && (validFrom == null || !validFrom.isAfter(now))
&& (validUntil == null || validUntil.isAfter(now));
}
}
@@ -0,0 +1,23 @@
package com.finance.system.authorization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.Collection;
import java.util.List;
public interface AuthorizationSubjectRoleBindingRepository extends JpaRepository<AuthorizationSubjectRoleBindingEntity, Long> {
List<AuthorizationSubjectRoleBindingEntity> findBySubjectTypeAndSubjectId(String subjectType, Long subjectId);
List<AuthorizationSubjectRoleBindingEntity> findBySubjectTypeAndSubjectIdIn(String subjectType, Collection<Long> subjectIds);
@Query("select case when count(b)>0 then true else false end from AuthorizationSubjectRoleBindingEntity b " +
"where b.subjectType=:subjectType and b.subjectId=:subjectId and b.roleId=:roleId " +
"and ((:scopeOverride is null and b.scopeOverride is null) or b.scopeOverride=:scopeOverride) " +
"and ((:scopeReferenceId is null and b.scopeReferenceId is null) or b.scopeReferenceId=:scopeReferenceId)")
boolean existsNormalized(@Param("subjectType") String subjectType,
@Param("subjectId") Long subjectId,
@Param("roleId") Long roleId,
@Param("scopeOverride") DataScope scopeOverride,
@Param("scopeReferenceId") Long scopeReferenceId);
}
@@ -0,0 +1,6 @@
package com.finance.system.authorization;
public enum AuthorizationSubjectType {
USER,
GROUP
}
@@ -0,0 +1,11 @@
package com.finance.system.authorization;
public enum DataScope {
/** Explicit cross-organization system-administration scope. */
GLOBAL,
SELF,
CURRENT_APPROVER,
DEPARTMENT,
DEPARTMENT_TREE,
ALL
}
@@ -0,0 +1,20 @@
package com.finance.system.authorization;
import lombok.Builder;
import lombok.Singular;
import lombok.Value;
import java.util.Map;
@Value
@Builder
public class EffectivePolicy {
Long policyId;
String resource;
String action;
PolicyEffect effect;
DataScope dataScope;
String scopeParameter;
int priority;
@Singular("fieldAccess") Map<String, FieldAccess> fieldAccess;
}
@@ -0,0 +1,24 @@
package com.finance.system.authorization;
public enum FieldAccess {
HIDDEN(0),
MASKED(1),
READ(2),
EDIT(3);
private final int rank;
FieldAccess(int rank) {
this.rank = rank;
}
public int rank() {
return rank;
}
public static FieldAccess stronger(FieldAccess left, FieldAccess right) {
if (left == null) return right == null ? HIDDEN : right;
if (right == null) return left;
return left.rank >= right.rank ? left : right;
}
}
@@ -0,0 +1,61 @@
package com.finance.system.authorization;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* Temporary compatibility mapping. Page/menu permissions intentionally map
* only to ui.page and can never authorize a business resource.
*/
@Component
public class LegacyPermissionAdapter {
private final Map<String, CanonicalPermission> mappings;
public LegacyPermissionAdapter() {
Map<String, CanonicalPermission> values = new HashMap<>();
map(values, "system.role.create", "iam.role", "create");
map(values, "system.role.edit", "iam.role", "update");
map(values, "system.role.delete", "iam.role", "delete");
map(values, "system.role.permission.configure", "iam.policy", "manage");
map(values, "system.group.create", "iam.group", "create");
map(values, "system.group.edit", "iam.group", "update");
map(values, "system.group.delete", "iam.group", "delete");
map(values, "system.group.member.bind", "iam.group.member", "manage");
map(values, "system.group.role.bind", "iam.group.role", "manage");
map(values, "system.user.status.change", "iam.user.status", "manage");
map(values, "system.role.view", "iam.role", "read");
map(values, "system.group.view", "iam.group", "read");
map(values, "system.user.view", "iam.user", "read");
mappings = Collections.unmodifiableMap(values);
}
public CanonicalPermission adapt(String legacyCode, boolean edit) {
if (legacyCode == null) return null;
String normalized = legacyCode.trim().toLowerCase(Locale.ROOT);
if (normalized.startsWith("page.")) {
return new CanonicalPermission("ui.page", normalized.substring("page.".length()) + ".view");
}
return mappings.get(normalized);
}
private void map(Map<String, CanonicalPermission> values, String legacy, String resource, String action) {
values.put(legacy.toLowerCase(Locale.ROOT), new CanonicalPermission(resource, action));
}
public static final class CanonicalPermission {
private final String resource;
private final String action;
CanonicalPermission(String resource, String action) {
this.resource = resource;
this.action = action;
}
public String getResource() { return resource; }
public String getAction() { return action; }
}
}
Loaded 100 of 267 files, more files were not shown because too many files have changed in this diff.
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.