Merge remote-tracking branch 'origin/V1.00' into V1.00

This commit is contained in:
cheney 2026-05-21 14:05:22 +08:00
commit 597fa4fe67
13 changed files with 170 additions and 36 deletions

View File

@ -8,6 +8,8 @@ public interface RoleUkeyBindingRepository {
Optional<RoleUkeyBindingEntity> findById(Long id);
Optional<RoleUkeyBindingEntity> findByRoleCodeAndUidAndUkeySerial(String roleCode, Integer uid, String ukeySerial);
List<RoleUkeyBindingEntity> findActiveByRoleCodeAndUid(String roleCode, Integer uid);
List<RoleUkeyBindingEntity> findActiveByRoleCode(String roleCode);

View File

@ -1,5 +1,6 @@
package com.cisd.tms.modules.auth.repository.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cisd.tms.modules.auth.entity.RoleUkeyBindingEntity;
import com.cisd.tms.modules.auth.mapper.RoleUkeyBindingMapper;
import com.cisd.tms.modules.auth.repository.RoleUkeyBindingRepository;
@ -21,6 +22,14 @@ public class RoleUkeyBindingRepositoryImpl implements RoleUkeyBindingRepository
return Optional.ofNullable(roleUkeyBindingMapper.selectById(id));
}
@Override
public Optional<RoleUkeyBindingEntity> findByRoleCodeAndUidAndUkeySerial(String roleCode, Integer uid, String ukeySerial) {
return Optional.ofNullable(roleUkeyBindingMapper.selectOne(new LambdaQueryWrapper<RoleUkeyBindingEntity>()
.eq(RoleUkeyBindingEntity::getRoleCode, roleCode)
.eq(RoleUkeyBindingEntity::getUid, uid)
.eq(RoleUkeyBindingEntity::getUkeySerial, ukeySerial)));
}
@Override
public List<RoleUkeyBindingEntity> findActiveByRoleCodeAndUid(String roleCode, Integer uid) {
return roleUkeyBindingMapper.selectActiveByRoleCodeAndUid(roleCode, uid);

View File

@ -312,10 +312,10 @@ public class AuthAdminServiceImpl implements AuthAdminService {
authFullAccountRepository.findByRoleCodeAndUid(targetRoleCode, uid)
.orElseThrow(() -> new BizException(ErrorCode.VALIDATE_FAILED.getCode(), "目标角色完整账号不存在"));
RoleUkeyBindingEntity binding = findReusableBinding(targetRoleCode, uid, ukeySerial, ukeyPubkey);
if (RoleCode.SUPER_ADMIN != targetRole) {
unbindActiveSeatBindings(targetRoleCode, uid);
}
RoleUkeyBindingEntity binding = findExistingActiveBinding(targetRoleCode, uid, ukeySerial, ukeyPubkey);
if (binding.getId() == null) {
binding.setId((long) Math.abs(Objects.hash(targetRoleCode, uid, ukeySerial, TraceIdUtil.newTraceId())));
binding.setRoleCode(targetRoleCode);
@ -340,15 +340,23 @@ public class AuthAdminServiceImpl implements AuthAdminService {
roleUkeyBindingRepository.update(binding);
}
private RoleUkeyBindingEntity findExistingActiveBinding(
private RoleUkeyBindingEntity findReusableBinding(
String roleCode,
Integer uid,
String ukeySerial,
String ukeyPubkey
) {
return roleUkeyBindingRepository.findByRoleCodeAndUidAndUkeySerial(roleCode, uid, ukeySerial)
.orElseGet(() -> findExistingActiveBinding(roleCode, uid, ukeyPubkey));
}
private RoleUkeyBindingEntity findExistingActiveBinding(
String roleCode,
Integer uid,
String ukeyPubkey
) {
return roleUkeyBindingRepository.findActiveByRoleCodeAndUid(roleCode, uid).stream()
.filter(binding -> Objects.equals(binding.getUkeySerial(), ukeySerial)
|| Objects.equals(binding.getUkeyPubkey(), ukeyPubkey))
.filter(binding -> Objects.equals(binding.getUkeyPubkey(), ukeyPubkey))
.findFirst()
.orElseGet(RoleUkeyBindingEntity::new);
}

View File

@ -817,11 +817,9 @@ public class ConfigurableInitStepExecutor implements InitStepExecutor {
int changed = 0;
for (Path configFile : configFiles) {
changed += replaceProperty(configFile, "spring.rabbitmq.username", configuredUsername);
changed += replaceProperty(configFile, "spring.rabbitmq.password", configuredPassword);
appendLog(logFile, "updated app rabbitmq credentials: " + configFile);
appendLog(logFile, "skipped app rabbitmq credential rewrite: " + configFile);
}
return InitStepExecutionResult.success("应用MQ凭据已应用,变更数量=" + changed, 0, logFile.toString());
return InitStepExecutionResult.success("应用MQ凭据回写已跳过变更数量=" + changed, 0, logFile.toString());
}
private InitStepExecutionResult executeDirectDbInit(InitTaskEntity task, InitTaskStepEntity step) throws IOException {

View File

@ -267,19 +267,11 @@ public class LmkServiceImpl implements LmkService {
if (deviceStatus != null) {
log.info("device status:{}/lmk seed mac:{}", deviceStatus.getFsmState(), recoveryResult.getLmkSeedMac());
}
clearKeyEntityRegistry();
runMasterKeySecurityMaintenance(masterKeyActivateEntity, "主密钥恢复后");
MasterKeyStateResult result = new MasterKeyStateResult();
result.setStatus(true);
result.setSeedMac(Hex.toHexString(recoveryResult.getLmkSeedMac()));
try {
masterKeyActivateEntity.setActivationStatus(false);
masterKeyActivateEntity.setEverInitialized(false);
masterKeyActivateRepository.update(masterKeyActivateEntity);
} catch (RuntimeException ex) {
log.error("主密钥恢复后更新激活记录失败", ex);
}
return result;
}
@ -642,29 +634,29 @@ public class LmkServiceImpl implements LmkService {
private void schedulePostMasterKeyInitMaintenance(MasterKeyActivateEntity masterKeyActivateEntity) {
try {
masterKeyPostInitExecutor.execute(() -> runPostMasterKeyInitMaintenance(masterKeyActivateEntity));
masterKeyPostInitExecutor.execute(() -> runMasterKeySecurityMaintenance(masterKeyActivateEntity, "主密钥初始化后"));
} catch (RuntimeException ex) {
log.error("提交主密钥初始化后置维护任务失败", ex);
}
}
private void runPostMasterKeyInitMaintenance(MasterKeyActivateEntity masterKeyActivateEntity) {
private void runMasterKeySecurityMaintenance(MasterKeyActivateEntity masterKeyActivateEntity, String operationName) {
try {
clearKeyEntityRegistry();
} catch (RuntimeException ex) {
log.error("主密钥初始化后清理实体密钥登记表失败", ex);
log.error("{}清理实体密钥登记表失败", operationName, ex);
}
try {
authSecurityResetService.resetAfterMasterKeyInitialized();
} catch (RuntimeException ex) {
log.error("主密钥初始化后重置认证状态失败", ex);
log.error("{}重置认证状态失败", operationName, ex);
}
try {
masterKeyActivateEntity.setActivationStatus(false);
masterKeyActivateEntity.setEverInitialized(false);
masterKeyActivateRepository.update(masterKeyActivateEntity);
} catch (RuntimeException ex) {
log.error("主密钥初始化后更新激活记录失败", ex);
log.error("{}更新激活记录失败", operationName, ex);
}
}

View File

@ -111,10 +111,22 @@ public class MasterKeyActivateServiceImpl implements MasterKeyActivateService {
MasterKeyActivateEntity masterKeyActivateEntity = masterKeyActivateRepository.find().orElseThrow(() -> new BizException(ErrorCode.VALIDATE_FAILED.getCode(), "激活记录不存在"));
Boolean everInitialized = masterKeyActivateEntity.getEverInitialized();
Boolean activationStatus = masterKeyActivateEntity.getActivationStatus();
if (everInitialized) {
throw new BizException(ErrorCode.BIZ_ERROR.getCode(), "从未进行初始化密钥, 无需激活");
throw new BizException(ErrorCode.BIZ_ERROR.getCode(), "从未进行初始化密钥, 无需激活");
}
DeviceInfoResponse deviceInfoResponse = deviceService.info();
if (deviceInfoResponse.getMasterKeyStatus()){
throw new BizException(ErrorCode.BIZ_ERROR.getCode(), "设备存在主密钥, 无需激活");
}
if (activationStatus) {
throw new BizException(ErrorCode.BIZ_ERROR.getCode(), "设备已激活, 无需激活");
}
if (masterKeyActivateRequest.getUserId() == null){
throw new IllegalArgumentException("使用者ID不能为空");
}

View File

@ -22,6 +22,8 @@ import org.springframework.stereotype.Component;
@Component
public class UpgradeTaskRunner {
private static final int DETACHED_RESTART_DELAY_SECONDS = 5;
private final UpgradeTaskRepository upgradeTaskRepository;
private final FileRecordRepository fileRecordRepository;
private final DeviceSoftwareVersionRepository deviceSoftwareVersionRepository;
@ -250,6 +252,7 @@ public class UpgradeTaskRunner {
+ "APP_HOME=\"${APP_HOME:-/home/tms}\"; "
+ "RUN_DIR=\"${RUN_DIR:-${APP_HOME}/run}\"; "
+ "PENDING_META=\"${RUN_DIR}/tms-upgrade.pending-jar\"; "
+ "sleep " + DETACHED_RESTART_DELAY_SECONDS + "; "
+ "\"${APP_HOME}/scripts/tms.sh\" stop; "
+ "if [ -s \"${PENDING_META}\" ]; then "
+ "PENDING_JAR=\"$(cat \"${PENDING_META}\")\"; "

View File

@ -147,7 +147,7 @@ tms:
standard-rabbit-queue-script-path-02: ${TMS_INIT_EXECUTOR_STANDARD_RABBIT_QUEUE_SCRIPT_PATH_02:${tms.init.executor.standard-home-dir}/cpackage/rabq/addrabq_R_02.sh}
# 通道用户授权 vhost默认 /RQ
rabbit-vhost: ${TMS_INIT_EXECUTOR_RABBIT_VHOST:/RQ}
# 标准版应用配置文件匹配规则;用于回写 RabbitMQ 通道账号密码。
# 标准版应用配置文件匹配规则;保留历史配置项,当前不再回写 RabbitMQ 通道账号密码。
standard-rabbit-app-config-patterns:
- ${TMS_INIT_EXECUTOR_STANDARD_RABBIT_APP_CONFIG_PATTERN_1:${tms.init.executor.standard-home-dir}/cmsp/application-prd*.properties}
- ${TMS_INIT_EXECUTOR_STANDARD_RABBIT_APP_CONFIG_PATTERN_2:${tms.init.executor.standard-home-dir}/cmtp/application-prd*.properties}
@ -166,7 +166,7 @@ tms:
cisd:
preset:
# 设备预制版本ENTERPRISE / INDIRECT / DIRECT。
product-type: ${TMS_CISD_PRESET_PRODUCT_TYPE:ENTERPRISE}
product-type: ${TMS_CISD_PRESET_PRODUCT_TYPE:INDIRECT}
# 预制版本号(用于前端展示与任务记录)。
version: ${TMS_CISD_PRESET_VERSION:V1.0.0}
# 预制信息来源标识CONFIG/DB 等自定义值)。
@ -188,7 +188,7 @@ tms:
disk-usage-path: ${TMS_DEVICE_RUNTIME_STATUS_DISK_USAGE_PATH:/home/tms}
upgrade:
# 升级包解压和脚本执行暂存目录。
staging-root-dir: ${TMS_UPGRADE_STAGING_ROOT_DIR:/home/tmp/tms-upgrade-staging}
staging-root-dir: ${TMS_UPGRADE_STAGING_ROOT_DIR:/home/tms/tmp/tms-upgrade-staging}
# 升级任务统一日志目录。
log-dir: ${TMS_UPGRADE_LOG_DIR:/home/tms/tmp/tms-upgrade-logs}
# 升级包验签使用的公钥 PEM 文件路径;为空时升级预检会拒绝通过。

View File

@ -190,6 +190,34 @@ class AuthAdminServiceTest {
&& item.getUnboundAt() != null));
}
@Test
void shouldRebindSingleSeatAdminSameSerialByReusingExistingBindingRow() {
InMemoryRoleAccountRepository roles = new InMemoryRoleAccountRepository();
InMemoryAuthFullAccountRepository accounts = new InMemoryAuthFullAccountRepository();
InMemoryRoleUkeyBindingRepository bindings = new InMemoryRoleUkeyBindingRepository();
roles.save(role(RoleCode.KEY_ADMIN, RoleAccountStatus.ACTIVE));
accounts.save(account(RoleCode.KEY_ADMIN, 1, "key-admin-01", "HASH-OLD", "SALT-OLD"));
RoleUkeyBindingEntity existing = binding(RoleCode.KEY_ADMIN, 1, "UK-SAME", "PUB-OLD", "SIG-OLD");
bindings.save(existing);
LmkService lmkService = Mockito.mock(LmkService.class);
Mockito.when(lmkService.exportIkPublicKeyHex()).thenReturn("IK-PUB-001");
Mockito.when(lmkService.signIk(Mockito.anyString())).thenReturn("ISSUE-SIGN-SAME");
UKeySignDTO dto = new UKeySignDTO();
dto.setPubKey("PUB-NEW");
dto.setUkeySerial("UK-SAME");
dto.setUid(1);
service(roles, accounts, bindings, lmkService)
.issueUkeyBindingSign(RoleCode.SUPER_ADMIN.getCode(), AuthLevel.FULL.name(), RoleCode.KEY_ADMIN.getCode(), dto);
Assertions.assertEquals(1, bindings.all().size());
RoleUkeyBindingEntity rebound = bindings.findActiveByRoleCodeAndUid(RoleCode.KEY_ADMIN.getCode(), 1).get(0);
Assertions.assertEquals(existing.getId(), rebound.getId());
Assertions.assertEquals("UK-SAME", rebound.getUkeySerial());
Assertions.assertEquals("PUB-NEW", rebound.getUkeyPubkey());
Assertions.assertEquals("ISSUE-SIGN-SAME", rebound.getIssuerSign());
}
@Test
void shouldBootstrapSuperAdminUkeyWithoutLoginContext() {
InMemoryRoleAccountRepository roles = new InMemoryRoleAccountRepository();
@ -506,6 +534,15 @@ class AuthAdminServiceTest {
.findFirst();
}
@Override
public Optional<RoleUkeyBindingEntity> findByRoleCodeAndUidAndUkeySerial(String roleCode, Integer uid, String ukeySerial) {
return store.stream()
.filter(entity -> roleCode.equals(entity.getRoleCode()))
.filter(entity -> uid.equals(entity.getUid()))
.filter(entity -> ukeySerial.equals(entity.getUkeySerial()))
.findFirst();
}
@Override
public List<RoleUkeyBindingEntity> findActiveByRoleCode(String roleCode) {
return store.stream()

View File

@ -510,6 +510,15 @@ class AuthServiceTest {
.findFirst();
}
@Override
public Optional<RoleUkeyBindingEntity> findByRoleCodeAndUidAndUkeySerial(String roleCode, Integer uid, String ukeySerial) {
return store.stream()
.filter(entity -> roleCode.equals(entity.getRoleCode()))
.filter(entity -> uid.equals(entity.getUid()))
.filter(entity -> ukeySerial.equals(entity.getUkeySerial()))
.findFirst();
}
@Override
public List<RoleUkeyBindingEntity> findActiveByRoleCode(String roleCode) {
return store.stream()

View File

@ -380,7 +380,7 @@ class ConfigurableInitStepExecutorTest {
}
@Test
void shouldApplyStandardAppMqCredentials() throws Exception {
void shouldNotRewriteStandardAppMqCredentials() throws Exception {
Path tempRoot = Files.createTempDirectory("init-executor-standard-rabbit-cred-test");
Path cmspDir = tempRoot.resolve("cmsp");
Path cmtpDir = tempRoot.resolve("cmtp");
@ -424,12 +424,58 @@ class ConfigurableInitStepExecutorTest {
InitStepExecutionResult result = executor.execute(task, step);
Assertions.assertTrue(result.isSuccess());
String encryptedUser = encryptWith3DesHex("new_user", "ABCDEFGHIJKLMN1234567890");
String encryptedPass = encryptWith3DesHex("new_pass", "ABCDEFGHIJKLMN1234567890");
Assertions.assertTrue(Files.readString(cmspCfg).contains("spring.rabbitmq.username=" + encryptedUser));
Assertions.assertTrue(Files.readString(cmspCfg).contains("spring.rabbitmq.password=" + encryptedPass));
Assertions.assertTrue(Files.readString(cmtpCfg).contains("spring.rabbitmq.username=" + encryptedUser));
Assertions.assertTrue(Files.readString(cmtpCfg).contains("spring.rabbitmq.password=" + encryptedPass));
Assertions.assertEquals("spring.rabbitmq.username=OLD\nspring.rabbitmq.password=OLD\n", Files.readString(cmspCfg));
Assertions.assertEquals("spring.rabbitmq.username=OLD\nspring.rabbitmq.password=OLD\n", Files.readString(cmtpCfg));
}
@Test
void shouldNotRewriteStandardMediaTemplateWhenApplyingAppMqCredentials() throws Exception {
Path tempRoot = Files.createTempDirectory("init-executor-standard-rabbit-template-test");
Path templateDir = tempRoot.resolve("cpackage/cmsp/01");
Path runtimeDir = tempRoot.resolve("cmsp");
Files.createDirectories(templateDir);
Files.createDirectories(runtimeDir);
Path templateCfg = templateDir.resolve("application-prd-ci01.properties");
Path runtimeCfg = runtimeDir.resolve("application-prd-ci01.properties");
String original = "spring.rabbitmq.username=FIXED\nspring.rabbitmq.password=FIXED\n";
Files.writeString(templateCfg, original);
Files.writeString(runtimeCfg, "spring.rabbitmq.username=OLD\nspring.rabbitmq.password=OLD\n");
InitExecutorProperties properties = new InitExecutorProperties();
properties.setMode(InitExecutorProperties.Mode.LOCAL);
properties.setLogDir(tempRoot.resolve("logs").toString());
properties.setStandardRabbitAppConfigPatterns(List.of(
templateCfg.toString(),
runtimeCfg.toString()
));
ConfigurableInitStepExecutor executor = new ConfigurableInitStepExecutor(properties, new ObjectMapper());
InitTaskEntity task = new InitTaskEntity();
task.setTaskId("TASK-APP-CRED-TEMPLATE-1");
task.setProductType("ENTERPRISE");
task.setInitPlanJson(buildInitPlanJson(
"ENTERPRISE",
Map.of(
"orgCodeType", "BIC",
"orgCode", "AAAABBBBXXX",
"orgNameCn", "测试机构",
"orgNameEn", "TEST BANK",
"deployMode", "SINGLE",
"nodes", Map.of("node01Ip", "10.0.1.1"),
"mq", Map.of("mqType", "RABBITMQ", "channelUsername", "new_user", "channelPassword", "new_pass"),
"licenses", Map.of("receiverLicenseFileId", "file-receiver-001")
)
));
InitTaskStepEntity step = new InitTaskStepEntity();
step.setStepNo(1);
step.setStepCode("APP_MQ_CREDENTIALS_APPLY");
step.setCommandLine("internal::app_mq_credentials_apply");
InitStepExecutionResult result = executor.execute(task, step);
Assertions.assertTrue(result.isSuccess());
Assertions.assertEquals(original, Files.readString(templateCfg));
Assertions.assertEquals("spring.rabbitmq.username=OLD\nspring.rabbitmq.password=OLD\n", Files.readString(runtimeCfg));
}
@Test

View File

@ -379,6 +379,7 @@ class LmkServiceTest {
PcieCryptoService pcieCryptoService = Mockito.mock(PcieCryptoService.class);
MasterKeyActivateRepository masterKeyActivateRepository = Mockito.mock(MasterKeyActivateRepository.class);
MasterKeyInitProperties properties = configuredPins("MTIzNDU2Nzg=", "ODc2NTQzMjE=");
allowMasterKeyInit(masterKeyActivateRepository);
MasterKeyRecoveryResult recoveryResult = new MasterKeyRecoveryResult();
recoveryResult.setLmkSeedMac(hex("1112131415161718"));
recoveryResult.setDeviceStatus(new DeviceStatusResult());
@ -414,21 +415,36 @@ class LmkServiceTest {
}
@Test
void shouldClearKeyEntityRegistryAfterMasterKeyRecoverySucceeds() {
void shouldRunSecurityCleanupAfterMasterKeyRecoverySucceeds() {
PcieCryptoService pcieCryptoService = Mockito.mock(PcieCryptoService.class);
MasterKeyActivateRepository masterKeyActivateRepository = Mockito.mock(MasterKeyActivateRepository.class);
AuthSecurityResetService authSecurityResetService = Mockito.mock(AuthSecurityResetService.class);
KeyEntityRepository keyEntityRepository = Mockito.mock(KeyEntityRepository.class);
MasterKeyInitProperties properties = configuredPins("MTIzNDU2Nzg=", "ODc2NTQzMjE=");
allowMasterKeyInit(masterKeyActivateRepository);
MasterKeyRecoveryResult recoveryResult = new MasterKeyRecoveryResult();
recoveryResult.setLmkSeedMac(hex("1112131415161718"));
Mockito.when(pcieCryptoService.recoverMasterKeyMaterial(Mockito.any())).thenReturn(recoveryResult);
LmkService service = new LmkServiceImpl(pcieCryptoService, properties, () -> { }, masterKeyActivateRepository, keyEntityRepository);
LmkService service = new LmkServiceImpl(
pcieCryptoService,
properties,
authSecurityResetService,
masterKeyActivateRepository,
keyEntityRepository
);
service.recoverKeyPackets(List.of(recoverPacketFixture(1), recoverPacketFixture(2)));
InOrder inOrder = Mockito.inOrder(pcieCryptoService, keyEntityRepository);
InOrder inOrder = Mockito.inOrder(
pcieCryptoService,
keyEntityRepository,
authSecurityResetService,
masterKeyActivateRepository
);
inOrder.verify(pcieCryptoService).recoverMasterKeyMaterial(Mockito.any());
inOrder.verify(keyEntityRepository).deleteAll();
inOrder.verify(authSecurityResetService).resetAfterMasterKeyInitialized();
inOrder.verify(masterKeyActivateRepository).update(Mockito.any());
}
@Test

View File

@ -188,7 +188,9 @@ class UpgradeTaskRunnerTest {
Assertions.assertTrue(command.contains("PENDING_META"));
Assertions.assertTrue(command.contains("tms-upgrade.pending-jar"));
Assertions.assertTrue(command.contains("sleep 5"));
Assertions.assertTrue(command.contains("cp \"${PENDING_JAR}\" \"${APP_HOME}/tms-framework.jar\""));
Assertions.assertTrue(command.indexOf("sleep 5") < command.indexOf("\"${APP_HOME}/scripts/tms.sh\" stop"));
Assertions.assertTrue(command.indexOf("\"${APP_HOME}/scripts/tms.sh\" stop") < command.indexOf("cp \"${PENDING_JAR}\""));
Assertions.assertTrue(command.indexOf("cp \"${PENDING_JAR}\"") < command.indexOf("\"${APP_HOME}/scripts/tms.sh\" start"));
}