diff --git a/.gitignore b/.gitignore
index d70cda5..4ae261a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -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
diff --git a/README.md b/README.md
index 59a71ad..a0a7920 100644
--- a/README.md
+++ b/README.md
@@ -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.
diff --git a/pom.xml b/pom.xml
index 1755489..1eb0160 100644
--- a/pom.xml
+++ b/pom.xml
@@ -12,9 +12,9 @@
com.finance.system
- finance-system
+ financial_system_backend
1.0.0
- finance-system
+ financial_system_backend
统一费用支付平台 - 员工报销管理系统
@@ -22,7 +22,9 @@
0.11.5
1.5.5.Final
1.6.15
+ 3.18.4
1.18.30
+ 6.6
@@ -47,6 +49,15 @@
org.springframework.boot
spring-boot-starter-actuator
+
+ io.micrometer
+ micrometer-registry-prometheus
+
+
+ net.logstash.logback
+ logstash-logback-encoder
+ ${logstash.logback.encoder.version}
+
@@ -112,6 +123,13 @@
jackson-datatype-jsr310
+
+
+ com.aliyun.oss
+ aliyun-sdk-oss
+ ${aliyun-oss.version}
+
+
org.springframework.boot
spring-boot-starter-test
diff --git a/run.bat b/run.bat
index 3c6ef09..4f69bf2 100644
--- a/run.bat
+++ b/run.bat
@@ -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%"
diff --git a/src/main/java/com/finance/system/FinanceSystemApplication.java b/src/main/java/com/finance/system/FinanceSystemApplication.java
index 116db1f..0f35d9e 100644
--- a/src/main/java/com/finance/system/FinanceSystemApplication.java
+++ b/src/main/java/com/finance/system/FinanceSystemApplication.java
@@ -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();
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFileClient.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFileClient.java
index 780e2d5..9ff71fb 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFileClient.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFileClient.java
@@ -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);
}
}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java
index 0850e1a..ef58a13 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuAuthService.java
@@ -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 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());
+ Map requestBody = new java.util.HashMap<>();
+ requestBody.put("grant_type", "authorization_code");
+ requestBody.put("code", code);
HttpEntity> request = new HttpEntity<>(requestBody, headers);
try {
- ResponseEntity response = restTemplate.postForEntity(
- url, request, FeishuTokenResponse.class);
+ ResponseEntity 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 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,13 +390,95 @@ 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);
+ }
+
/**
* 获取tenant_access_token
*/
@@ -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.
- return loginPersistence.completeOAuth(user.getId(), feishuUserInfo);
+ 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);
}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java b/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java
index e289bc9..ae10625 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuConfig.java
@@ -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
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java
index 897cce7..0ecda9a 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDefinitionSyncService.java
@@ -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("已验证并同步审批定义(发起申请可用);事件订阅暂未成功,请检查飞书事件权限后再次同步");
}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java
index 09eb601..0eba949 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryAccessService.java
@@ -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 args = new ArrayList<>();
args.add(context);
if (!blank(query)) {
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBindingProvisioner.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBindingProvisioner.java
index 030da4c..445e20d 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBindingProvisioner.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBindingProvisioner.java
@@ -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> 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 directory = directoryRows.get(0);
List> 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 openOwner = null;
for (Map row : accountRows) {
@@ -81,7 +86,7 @@ public class FeishuDirectoryBindingProvisioner {
if(!blank(legacyRequest))legacyIds.add(legacyRequest);
for(String legacyId:legacyIds){
List> 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 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);
}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBootstrap.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBootstrap.java
index f6ac463..d85a9cc 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBootstrap.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryBootstrap.java
@@ -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("启动时通讯录同步不可用;为保障安全,继续拒绝员工访问"); }
}
}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java
index 841322f..2f296d8 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryClient.java
@@ -29,10 +29,11 @@ public class FeishuDirectoryClient {
"department_id", "name", "parent_department_id", "order_weight", "department_count"));
static final List 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> fields=fieldErrors.fields();
+ while(fields.hasNext()) {
+ Map.Entry 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) {
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryCurrentStore.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryCurrentStore.java
index 8cb396c..729b999 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryCurrentStore.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryCurrentStore.java
@@ -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> relations=relations(snapshot);Map counts=memberCounts(snapshot,relations);
+ Map> relations=relations(snapshot,false);Map counts=memberCounts(snapshot,relations);
Map oldDepartments=hashes("SELECT open_department_id,content_hash FROM feishu_directory_department");
Map oldUsers=hashes("SELECT open_id,content_hash FROM feishu_directory_user");
+ Map oldObservedUsers=hashes("SELECT open_id,content_hash FROM feishu_directory_employee_observation");
Set wantedDepartments=new LinkedHashSet<>(),wantedUsers=new LinkedHashSet<>();
- List departmentRows=new ArrayList<>(),userRows=new ArrayList<>();
- List retainedDepartmentRows=new ArrayList<>(),retainedUserRows=new ArrayList<>();
+ Set wantedObservedUsers=new LinkedHashSet<>();
+ List departmentRows=new ArrayList<>(),userRows=new ArrayList<>(),observedUserRows=new ArrayList<>();
+ List 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 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 oldMemberships=new LinkedHashSet<>();for(Map 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")));
SetwantedMemberships=new LinkedHashSet<>();ListmembershipRows=new ArrayList<>(),retainedMembershipRows=new ArrayList<>();
for(Map.Entry> 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 oldObservedMemberships=new LinkedHashSet<>();for(Map 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")));
+ SetwantedObservedMemberships=new LinkedHashSet<>();ListobservedMembershipRows=new ArrayList<>(),retainedObservedMembershipRows=new ArrayList<>();
+ for(Map.Entry> 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 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> readDepartments(){
+ List> 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 parents=new LinkedHashMap<>();
+ for(Map row:rows)parents.put(string(row.get("open_department_id")),string(row.get("parent_open_department_id")));
+ Map> observedMembers=new HashMap<>();
+ for(Map 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 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> departments=new ArrayList<>();
- for(Mapr: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(Mapr:rows){
Mapd=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(Mapr: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> userRows=scope==null?jdbc.queryForList(userSql):jdbc.queryForList(userSql,openIds.toArray());
List>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;iold,Setwanted){Listrows=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,Setold,Setwanted){Listrows=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,Setold,Setwanted){Listrows=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,Listrows){for(int i=0;ihashes(String sql){Mapr=new LinkedHashMap<>();for(Maprow:jdbc.queryForList(sql)){Iteratori=row.values().iterator();r.put(string(i.next()),string(i.next()));}return r;}
- private Map>relations(FeishuDirectoryClient.Snapshot s){Map>r=new LinkedHashMap<>();int total=0;for(Map.Entrye:s.userSummaries.entrySet()){LinkedHashSetids=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>relations(FeishuDirectoryClient.Snapshot s,boolean eligibleOnly){Map>r=new LinkedHashMap<>();int total=0;for(Map.Entrye:s.userSummaries.entrySet()){FeishuDirectoryClient.UserSummary user=e.getValue();if(user==null)throw FeishuTenantTokenService.diagnostic("DIRECTORY_IDENTITY_CONFLICT");if(eligibleOnly&&!user.eligible)continue;LinkedHashSetids=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 MapmemberCounts(FeishuDirectoryClient.Snapshot s,Map>relations){Mapparents=new HashMap<>();for(String id:s.departments){FeishuDirectoryClient.Department d=s.departmentDetails.get(id);parents.put(id,d==null?"0":d.parentOpenDepartmentId);}Map>members=new HashMap<>();int expanded=0;for(Map.Entry>e:relations.entrySet()){String employee=e.getKey();for(String id:e.getValue()){Setvisited=new HashSet<>();String current=id;while(current!=null&&parents.containsKey(current)&&visited.add(current)){Setset=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;}}}Mapr=new HashMap<>();for(Map.Entry>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);}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublisher.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublisher.java
index 8f43269..66ab315 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublisher.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryPublisher.java
@@ -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 values,Set result){Listall=new ArrayList<>(values);for(int start=0;startb=all.subList(start,Math.min(all.size(),start+LOOKUP_BATCH));for(Maprow: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(Maprow){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;i0)b.append(',');b.append('?');}return b.toString();}
private static String trim(String value){return value==null?"":value.trim();}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryRunStore.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryRunStore.java
index dd56b45..0075f41 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryRunStore.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryRunStore.java
@@ -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,28 +38,46 @@ 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 -> {
- lockState();
- Integer active = jdbc.queryForObject("SELECT COUNT(*) FROM feishu_directory_sync_run WHERE state IN ('QUEUED','RUNNING')", Integer.class);
- if (active != null && active > 0) throw new BusinessException("Directory sync already running", 409);
- Timestamp now = databaseNow();
- FeishuDirectoryService.Run run = new FeishuDirectoryService.Run();
- run.setRunId(UUID.randomUUID().toString());
- 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));
- return run;
- });
+ 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 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();
+ run.setRunId(UUID.randomUUID().toString());
+ 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,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 state = lockState();
List> rows = jdbc.queryForList(
"SELECT run_id,trigger_type,attempt_count FROM feishu_directory_sync_run " +
- "WHERE (state='QUEUED' OR (state='RUNNING' AND lease_untilCURRENT_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 requireLease(Claim claim) {
Map state = lockState();
- List valid = jdbc.query("SELECT 1 FROM feishu_directory_sync_run WHERE run_id=? AND state='RUNNING' " +
+ List 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 state = lockState();
List> 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 expired=jdbc.query("SELECT run_id FROM feishu_directory_sync_run WHERE state='RUNNING' " +
- "AND lease_until=? FOR UPDATE",(rs,row)->rs.getString(1),MAX_ATTEMPTS);
+ List expired=jdbc.query("SELECT run_id FROM feishu_directory_sync_run WHERE tenant_id=? AND state='RUNNING' " +
+ "AND lease_until=? 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 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) {
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java
index 61ce3ff..57810fa 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectoryService.java
@@ -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 status(){
- Map state=null;try{state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");}catch(RuntimeException ignored){}
+ Map 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 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 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 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 state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
+ Map 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 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 state=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
+ Map 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 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 current=jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
+ Map 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;}}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java
index 8dfec05..2af0c3a 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncDispatcher.java
@@ -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){
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncWorker.java b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncWorker.java
index 6226d0f..03860dd 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncWorker.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuDirectorySyncWorker.java
@@ -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);}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java
index a97bca0..ca0cc8e 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuLoginPersistenceService.java
@@ -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); }
}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuOAuthStateOriginStore.java b/src/main/java/com/finance/system/adapter/feishu/FeishuOAuthStateOriginStore.java
new file mode 100644
index 0000000..0db1342
--- /dev/null
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuOAuthStateOriginStore.java
@@ -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 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> 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;
+ }
+ }
+}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java
index cef5136..8904291 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuTenantTokenService.java
@@ -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 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 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 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 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) {
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuTokenResponse.java b/src/main/java/com/finance/system/adapter/feishu/FeishuTokenResponse.java
index 5a07f8f..04997dd 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuTokenResponse.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuTokenResponse.java
@@ -9,7 +9,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
public class FeishuTokenResponse {
- private int code;
+ private Integer code;
private String msg;
private TokenData data;
@@ -29,4 +29,4 @@ public class FeishuTokenResponse {
@JsonProperty("refresh_token")
private String refreshToken;
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuUserProvisioningService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuUserProvisioningService.java
new file mode 100644
index 0000000..a1e67fc
--- /dev/null
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuUserProvisioningService.java
@@ -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;
+ }
+ }
+}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuUserResponse.java b/src/main/java/com/finance/system/adapter/feishu/FeishuUserResponse.java
index 9e210d9..47d7115 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuUserResponse.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuUserResponse.java
@@ -9,7 +9,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
public class FeishuUserResponse {
- private int code;
+ private Integer code;
private String msg;
private UserData data;
@@ -30,4 +30,4 @@ public class FeishuUserResponse {
@JsonProperty("avatar_url")
private String avatarUrl;
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java b/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java
index e609d29..100c9df 100644
--- a/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java
+++ b/src/main/java/com/finance/system/adapter/feishu/ReimbursementCanonicalizer.java
@@ -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());
diff --git a/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java b/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java
index b3592a4..18e70e7 100644
--- a/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java
+++ b/src/main/java/com/finance/system/adapter/kingdee/KingdeeClient.java
@@ -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);
diff --git a/src/main/java/com/finance/system/audit/AuditDeliveryService.java b/src/main/java/com/finance/system/audit/AuditDeliveryService.java
new file mode 100644
index 0000000..d085351
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditDeliveryService.java
@@ -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 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 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";
+ }
+}
+
diff --git a/src/main/java/com/finance/system/audit/AuditEvent.java b/src/main/java/com/finance/system/audit/AuditEvent.java
new file mode 100644
index 0000000..89af49b
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditEvent.java
@@ -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;
+}
diff --git a/src/main/java/com/finance/system/audit/AuditEventAppender.java b/src/main/java/com/finance/system/audit/AuditEventAppender.java
new file mode 100644
index 0000000..6baeaf0
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditEventAppender.java
@@ -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();
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/AuditEventCommand.java b/src/main/java/com/finance/system/audit/AuditEventCommand.java
new file mode 100644
index 0000000..b083126
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditEventCommand.java
@@ -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 changes;
+ private Map attributes;
+}
+
diff --git a/src/main/java/com/finance/system/audit/AuditEventPolicy.java b/src/main/java/com/finance/system/audit/AuditEventPolicy.java
new file mode 100644
index 0000000..ed09feb
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditEventPolicy.java
@@ -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 CATEGORIES = new HashSet<>(Arrays.asList(
+ "SECURITY", "ADMIN", "BUSINESS", "INTEGRATION"));
+ private static final Set OUTCOMES = new HashSet<>(Arrays.asList(
+ "SUCCESS", "FAILURE", "DENIED", "UNKNOWN"));
+ private static final Set ACTOR_TYPES = new HashSet<>(Arrays.asList(
+ "USER", "SYSTEM", "SERVICE", "ANONYMOUS"));
+ private static final Set 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.emptyList());
+ }
+
+ @Autowired
+ public AuditEventPolicy(ObjectMapper objectMapper, List 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);
+ }
+ }
+}
+
diff --git a/src/main/java/com/finance/system/audit/AuditEventRepository.java b/src/main/java/com/finance/system/audit/AuditEventRepository.java
new file mode 100644
index 0000000..e90092c
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditEventRepository.java
@@ -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 {
+ boolean existsByEventUid(String eventUid);
+
+ List findByIdGreaterThanOrderByIdAsc(Long id, Pageable pageable);
+}
+
diff --git a/src/main/java/com/finance/system/audit/AuditEventSchemaContributor.java b/src/main/java/com/finance/system/audit/AuditEventSchemaContributor.java
new file mode 100644
index 0000000..e8db179
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditEventSchemaContributor.java
@@ -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 schemas();
+}
diff --git a/src/main/java/com/finance/system/audit/AuditEventSchemaRegistry.java b/src/main/java/com/finance/system/audit/AuditEventSchemaRegistry.java
new file mode 100644
index 0000000..c9b76e5
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditEventSchemaRegistry.java
@@ -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 schemas = new LinkedHashMap<>();
+
+ public AuditEventSchemaRegistry(Collection 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 values, Map rules, String location) {
+ Map actual = values == null ? Collections.emptyMap() : values;
+ for (Map.Entry 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 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 changes, Map attributes) {
+ return new Schema(category, action, version, changes, attributes);
+ }
+
+ public static Map none() { return Collections.emptyMap(); }
+
+ public static Map fields(Object... pairs) {
+ if (pairs.length % 2 != 0) throw new IllegalArgumentException("AUDIT_SCHEMA_FIELD_PAIRS");
+ Map 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 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 changes;
+ private final Map attributes;
+
+ private Schema(String category, String action, int version,
+ Map changes, Map 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); }
+}
diff --git a/src/main/java/com/finance/system/audit/AuditEventService.java b/src/main/java/com/finance/system/audit/AuditEventService.java
new file mode 100644
index 0000000..a534b3e
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditEventService.java
@@ -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);
+ }
+ }
+}
+
diff --git a/src/main/java/com/finance/system/audit/AuditInstanceIdentity.java b/src/main/java/com/finance/system/audit/AuditInstanceIdentity.java
new file mode 100644
index 0000000..8db74ca
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditInstanceIdentity.java
@@ -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);
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/AuditIntegrityProperties.java b/src/main/java/com/finance/system/audit/AuditIntegrityProperties.java
new file mode 100644
index 0000000..90de82c
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditIntegrityProperties.java
@@ -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 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 resolvedKeys() {
+ return resolvedKeySet().keys;
+ }
+
+ ResolvedKeySet resolvedKeySet() {
+ CurrentKey resolvedCurrent = resolvedCurrentKey();
+ Map 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 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 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 keys;
+
+ private ResolvedKeySet(String currentKeyId, String currentKey, Map 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 getHistoricalKeys() {
+ return historicalKeys;
+ }
+
+ public void setHistoricalKeys(Map 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;
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/AuditIntegrityScanLeaseService.java b/src/main/java/com/finance/system/audit/AuditIntegrityScanLeaseService.java
new file mode 100644
index 0000000..f72aed9
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditIntegrityScanLeaseService.java
@@ -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;
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/AuditIntegrityScanState.java b/src/main/java/com/finance/system/audit/AuditIntegrityScanState.java
new file mode 100644
index 0000000..1191b27
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditIntegrityScanState.java
@@ -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;
+}
diff --git a/src/main/java/com/finance/system/audit/AuditIntegrityScanStateRepository.java b/src/main/java/com/finance/system/audit/AuditIntegrityScanStateRepository.java
new file mode 100644
index 0000000..ef7a56f
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditIntegrityScanStateRepository.java
@@ -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 {
+ @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 findByScanNameForUpdate(@Param("scanName") String scanName);
+}
diff --git a/src/main/java/com/finance/system/audit/AuditIntegrityService.java b/src/main/java/com/finance/system/audit/AuditIntegrityService.java
new file mode 100644
index 0000000..bfbb803
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditIntegrityService.java
@@ -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 keys;
+
+ private ResolvedIntegrityKeys(String currentKeyId, String currentKey,
+ Map keys) {
+ this.currentKeyId = currentKeyId;
+ this.currentKey = currentKey;
+ this.keys = keys;
+ }
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/AuditIntegrityVerifier.java b/src/main/java/com/finance/system/audit/AuditIntegrityVerifier.java
new file mode 100644
index 0000000..a2b339a
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditIntegrityVerifier.java
@@ -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 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());
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/AuditOutbox.java b/src/main/java/com/finance/system/audit/AuditOutbox.java
new file mode 100644
index 0000000..392a0e4
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditOutbox.java
@@ -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;
+}
+
diff --git a/src/main/java/com/finance/system/audit/AuditOutboxClaimService.java b/src/main/java/com/finance/system/audit/AuditOutboxClaimService.java
new file mode 100644
index 0000000..403829f
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditOutboxClaimService.java
@@ -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 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));
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/AuditOutboxDispatcher.java b/src/main/java/com/finance/system/audit/AuditOutboxDispatcher.java
new file mode 100644
index 0000000..6c47d39
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditOutboxDispatcher.java
@@ -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 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();
+ }
+ }
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/AuditOutboxRepository.java b/src/main/java/com/finance/system/audit/AuditOutboxRepository.java
new file mode 100644
index 0000000..87cc87b
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditOutboxRepository.java
@@ -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 {
+ @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 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 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 findByIdForUpdate(@Param("id") Long id);
+
+ @Lock(LockModeType.PESSIMISTIC_WRITE)
+ @Query("select o from AuditOutbox o where o.id = :id and o.leaseOwner = :owner")
+ Optional findOwnedByIdForUpdate(@Param("id") Long id, @Param("owner") String owner);
+}
+
diff --git a/src/main/java/com/finance/system/audit/AuditPort.java b/src/main/java/com/finance/system/audit/AuditPort.java
new file mode 100644
index 0000000..8382b2c
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditPort.java
@@ -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);
+}
+
diff --git a/src/main/java/com/finance/system/audit/AuditReliabilityHealthIndicator.java b/src/main/java/com/finance/system/audit/AuditReliabilityHealthIndicator.java
new file mode 100644
index 0000000..d552384
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditReliabilityHealthIndicator.java
@@ -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;
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/AuditReliabilityMetrics.java b/src/main/java/com/finance/system/audit/AuditReliabilityMetrics.java
new file mode 100644
index 0000000..d9f9e85
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditReliabilityMetrics.java
@@ -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());
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/AuditReliabilityProperties.java b/src/main/java/com/finance/system/audit/AuditReliabilityProperties.java
new file mode 100644
index 0000000..3cdba7c
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditReliabilityProperties.java
@@ -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));
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/AuditReliabilitySnapshot.java b/src/main/java/com/finance/system/audit/AuditReliabilitySnapshot.java
new file mode 100644
index 0000000..77152f1
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditReliabilitySnapshot.java
@@ -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;
+}
diff --git a/src/main/java/com/finance/system/audit/AuditReliabilitySnapshotProvider.java b/src/main/java/com/finance/system/audit/AuditReliabilitySnapshotProvider.java
new file mode 100644
index 0000000..3892b92
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/AuditReliabilitySnapshotProvider.java
@@ -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_atutc_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 outbox = jdbcTemplate.queryForMap(
+ OUTBOX_SNAPSHOT_SQL, properties.getMaxPendingAgeSeconds());
+ Map 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;
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/query/AuditEventView.java b/src/main/java/com/finance/system/audit/query/AuditEventView.java
new file mode 100644
index 0000000..d00e678
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/query/AuditEventView.java
@@ -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;
+}
diff --git a/src/main/java/com/finance/system/audit/query/AuditQueryAuthorization.java b/src/main/java/com/finance/system/audit/query/AuditQueryAuthorization.java
new file mode 100644
index 0000000..99a4af3
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/query/AuditQueryAuthorization.java
@@ -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("不支持的审计类别");
+ }
+}
diff --git a/src/main/java/com/finance/system/audit/query/AuditQueryRepository.java b/src/main/java/com/finance/system/audit/query/AuditQueryRepository.java
new file mode 100644
index 0000000..1caa215
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/query/AuditQueryRepository.java
@@ -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 {
+ @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 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);
+}
diff --git a/src/main/java/com/finance/system/audit/query/AuditQueryScope.java b/src/main/java/com/finance/system/audit/query/AuditQueryScope.java
new file mode 100644
index 0000000..cacb19f
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/query/AuditQueryScope.java
@@ -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;
+}
diff --git a/src/main/java/com/finance/system/audit/query/AuditQueryService.java b/src/main/java/com/finance/system/audit/query/AuditQueryService.java
new file mode 100644
index 0000000..f460b99
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/query/AuditQueryService.java
@@ -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 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 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 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.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; }
+}
diff --git a/src/main/java/com/finance/system/audit/query/CursorPage.java b/src/main/java/com/finance/system/audit/query/CursorPage.java
new file mode 100644
index 0000000..278c0b5
--- /dev/null
+++ b/src/main/java/com/finance/system/audit/query/CursorPage.java
@@ -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 {
+ List items;
+ LocalDateTime nextEventTime;
+ Long nextId;
+ boolean hasMore;
+}
diff --git a/src/main/java/com/finance/system/authorization/AuthorizationAdminService.java b/src/main/java/com/finance/system/authorization/AuthorizationAdminService.java
new file mode 100644
index 0000000..ca107f0
--- /dev/null
+++ b/src/main/java/com/finance/system/authorization/AuthorizationAdminService.java
@@ -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 listPolicies() {
+ List 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 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 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 ids = positiveIds(policyIds, "policyIds");
+ List 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 rolePolicyIds(Long roleId) {
+ if (!roles.existsById(roleId)) throw new ResourceNotFoundException("角色不存在");
+ List result = new ArrayList<>();
+ for (AuthorizationRolePolicyEntity link : rolePolicies.findByIdRoleId(roleId)) result.add(link.getId().getPolicyId());
+ return result;
+ }
+
+ @Transactional
+ public Map createSubjectBinding(Map 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> listSodRules() {
+ List> result = new ArrayList<>();
+ for (AuthorizationSodRuleEntity rule : sodRules.findAll()) {
+ Map 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 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 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 memberships = groupMembers.findByIdGroupId(binding.getSubjectId());
+ if (memberships == null || memberships.isEmpty()) return null;
+ Set 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 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 bindingMap(AuthorizationSubjectRoleBindingEntity binding) {
+ Map 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 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.emptyMap()).attributes(attributes).build());
+ }
+
+ private String normalizedPart(Map body, String key) {
+ String value = evaluator.normalizePart(text(body, key, 80));
+ if (value == null) throw new BadRequestException(key + "格式不正确");
+ return value;
+ }
+ private String text(Map 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 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 enumValue(Map body, String key, Class type) {
+ E value = optionalEnum(body, key, type);
+ if (value == null) throw new BadRequestException(key + "不能为空或无效");
+ return value;
+ }
+ private > E optionalEnum(Map body, String key, Class 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 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 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 body, String key) {
+ Long value = optionalPositiveLong(body, key);
+ if (value == null) throw new BadRequestException(key + "不能为空");
+ return value;
+ }
+ private Long optionalPositiveLong(Map 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 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 positiveIds(Collection> raw, String field) {
+ if (raw == null) throw new BadRequestException(field + "不能为空");
+ Set 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 attributes(Object... values) {
+ Map result = new LinkedHashMap<>();
+ for (int i=0; i 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()))
+ );
+ }
+}
diff --git a/src/main/java/com/finance/system/authorization/AuthorizationBindingDto.java b/src/main/java/com/finance/system/authorization/AuthorizationBindingDto.java
new file mode 100644
index 0000000..c38022a
--- /dev/null
+++ b/src/main/java/com/finance/system/authorization/AuthorizationBindingDto.java
@@ -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;
+}
diff --git a/src/main/java/com/finance/system/authorization/AuthorizationBindingPageDto.java b/src/main/java/com/finance/system/authorization/AuthorizationBindingPageDto.java
new file mode 100644
index 0000000..2cbd424
--- /dev/null
+++ b/src/main/java/com/finance/system/authorization/AuthorizationBindingPageDto.java
@@ -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 content;
+ int page;
+ int size;
+ long totalElements;
+ int totalPages;
+}
diff --git a/src/main/java/com/finance/system/authorization/AuthorizationBindingQueryRequest.java b/src/main/java/com/finance/system/authorization/AuthorizationBindingQueryRequest.java
new file mode 100644
index 0000000..0839017
--- /dev/null
+++ b/src/main/java/com/finance/system/authorization/AuthorizationBindingQueryRequest.java
@@ -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;
+}
diff --git a/src/main/java/com/finance/system/authorization/AuthorizationCapabilitiesDto.java b/src/main/java/com/finance/system/authorization/AuthorizationCapabilitiesDto.java
new file mode 100644
index 0000000..bbaed01
--- /dev/null
+++ b/src/main/java/com/finance/system/authorization/AuthorizationCapabilitiesDto.java
@@ -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 capabilities;
+ Set auditAccess;
+ Set auditSecurity;
+ Set auditBusiness;
+ Set auditIntegration;
+ Set financeActions;
+
+ public static AuthorizationCapabilitiesDto from(Set raw) {
+ Set 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 prefix(Set values, String prefix) {
+ return prefixes(values, prefix);
+ }
+
+ private static Set prefixes(Set values, String... prefixes) {
+ Set 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 unmodifiable(Set values) {
+ return Collections.unmodifiableSet(new TreeSet<>(values));
+ }
+}
diff --git a/src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionEntity.java b/src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionEntity.java
new file mode 100644
index 0000000..a4feaf5
--- /dev/null
+++ b/src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionEntity.java
@@ -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;
+}
diff --git a/src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionRepository.java b/src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionRepository.java
new file mode 100644
index 0000000..d61ad0a
--- /dev/null
+++ b/src/main/java/com/finance/system/authorization/AuthorizationCatalogVersionRepository.java
@@ -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 {
+ @Lock(LockModeType.PESSIMISTIC_READ)
+ @Query("select v from AuthorizationCatalogVersionEntity v where v.id = :id")
+ Optional findByIdForShare(@Param("id") Integer id);
+}
diff --git a/src/main/java/com/finance/system/authorization/AuthorizationController.java b/src/main/java/com/finance/system/authorization/AuthorizationController.java
new file mode 100644
index 0000000..bc0fb60
--- /dev/null
+++ b/src/main/java/com/finance/system/authorization/AuthorizationController.java
@@ -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> capabilities() {
+ SubjectContext subject = currentSubject();
+ Set 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