feat(open): ensure支持二次获取明文(ak存AES-GCM密文key_cipher, app.token-cipher-key派生密钥); 历史无密文Token自动轮换; V3迁移+回滚方案; 同步文档

This commit is contained in:
xiaoqu
2026-09-07 12:41:03 +08:00
parent 1721bc15cb
commit 8c872ac15d
17 changed files with 249 additions and 34 deletions
@@ -10,6 +10,7 @@ import me.iiv.agent.mapper.svc.AgentApiKeyMapper;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.mapper.svc.TokenScopeMapper;
import me.iiv.agent.security.AuthService;
import me.iiv.agent.security.TokenCipher;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -25,18 +26,21 @@ public class AdminTokenService {
private final AgentApiKeyMapper tokenMapper;
private final TokenScopeMapper relationMapper;
private final AgentScopeMapper scopeMapper;
private final TokenCipher tokenCipher;
public AdminTokenService(UserMapper userMapper, AgentApiKeyMapper tokenMapper,
TokenScopeMapper relationMapper, AgentScopeMapper scopeMapper) {
TokenScopeMapper relationMapper, AgentScopeMapper scopeMapper,
TokenCipher tokenCipher) {
this.userMapper = userMapper;
this.tokenMapper = tokenMapper;
this.relationMapper = relationMapper;
this.scopeMapper = scopeMapper;
this.tokenCipher = tokenCipher;
}
/**
* 签发 Token:一作用域一 Token。选 N 个作用域生成 N 把,每把独立绑定单个作用域,
* 便于独立吊销、独立审计,明文逐把返回(仅本次可见)。
* 便于独立吊销、独立审计,明文逐把返回;服务端同时保存 SHA-256 哈希和 AES-GCM 密文(供二次获取)。
*/
@Transactional(transactionManager = "svcTransactionManager")
public List<IssuedToken> issue(Long userId, String memo, List<Long> scopeIds, Date expireTime, Long adminId) {
@@ -56,6 +60,7 @@ public class AdminTokenService {
token.setUserId(userId);
token.setKeyPrefix(plaintext.substring(0, 13));
token.setKeyHash(AuthService.sha256Hex(plaintext));
token.setKeyCipher(tokenCipher.encrypt(plaintext));
token.setMemo(trim(memo, 255));
token.setStatus((byte) 1);
token.setExpireTime(expireTime);
@@ -47,6 +47,11 @@ public class AgentApiKey implements Serializable {
*/
private String keyHash;
/**
* ak 明文 AES-GCM 加密密文(二次获取用),空=历史数据未存
*/
private String keyCipher;
/**
* 用途备注(如 Kimi 用 / Claude 用)
*/
@@ -21,8 +21,8 @@ public class OpenTokenController {
}
/**
* 确保某人员在某作用域下有有效 Token:存在则返回元信息(created=false,无明文),
* 不存在则自动创建永久 Token 并返回明文(created=true,仅此一次可见)。
* 确保某人员在某作用域下有有效 Token:存在则解密回传明文(created=false,二次获取),
* 不存在则自动创建永久 Token 并返回明文(created=true);历史无密文 Token 自动轮换后按创建返回。
*/
@PostMapping("/token/ensure")
public EnsureResult ensure(@RequestBody EnsureRequest body) {
@@ -9,6 +9,7 @@ import me.iiv.agent.entity.svc.AgentScope;
import me.iiv.agent.mapper.m0.UserMapper;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.security.AuthContext;
import me.iiv.agent.security.TokenCipher;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -19,8 +20,9 @@ import java.util.Date;
/**
* Open API:按 手机号/邮箱 + 作用域编码 确保 Token 存在(get-or-create)。
* 存在有效 Token 只回元信息(服务端只存哈希,明文不可回吐);
* 不存在则自动创建永久 Token,明文仅本次返回。
* 存在有效 Token 时解密 key_cipher 回传明文(二次获取,2026-09-07 决策);
* 历史数据无密文的 Token 自动轮换(禁用旧把、签发新把);
* 不存在则自动创建永久 Token。两条路径均返回明文。
*/
@Service
public class OpenTokenService {
@@ -33,13 +35,16 @@ public class OpenTokenService {
private final AgentScopeMapper scopeMapper;
private final AdminTokenService tokenService;
private final AuditService auditService;
private final TokenCipher tokenCipher;
public OpenTokenService(UserMapper userMapper, AgentScopeMapper scopeMapper,
AdminTokenService tokenService, AuditService auditService) {
AdminTokenService tokenService, AuditService auditService,
TokenCipher tokenCipher) {
this.userMapper = userMapper;
this.scopeMapper = scopeMapper;
this.tokenService = tokenService;
this.auditService = auditService;
this.tokenCipher = tokenCipher;
}
@Transactional(transactionManager = "svcTransactionManager")
@@ -65,9 +70,21 @@ public class OpenTokenService {
AgentApiKey existing = tokenService.findActiveToken(user.getId(), scope.getId());
if (existing != null) {
audit(user, existing, body, "success", "已存在有效 Token,返回元信息", start);
return new OpenTokenController.EnsureResult(false, null, existing.getKeyPrefix(),
existing.getExpireTime(), user.getId(), user.getName(), scope.getCode());
if (StringUtils.hasText(existing.getKeyCipher())) {
String plaintext;
try {
plaintext = tokenCipher.decrypt(existing.getKeyCipher());
} catch (IllegalStateException e) {
audit(user, existing, body, "error", "Token 密文解密失败", start);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Token 密文解密失败");
}
audit(user, existing, body, "success", "已存在有效 Token,解密返回明文", start);
return new OpenTokenController.EnsureResult(false, plaintext, existing.getKeyPrefix(),
existing.getExpireTime(), user.getId(), user.getName(), scope.getCode());
}
// 历史数据无密文:禁用旧把并签发新把(轮换),保证总能拿到明文
tokenService.status(existing.getId(), (byte) 0, SYSTEM_CREATOR_ID);
audit(user, existing, body, "success", "旧 Token 无密文,自动轮换", start);
}
AdminTokenService.IssuedToken issued = tokenService.issueSingle(user.getId(),
@@ -0,0 +1,78 @@
package me.iiv.agent.security;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
/**
* ak 明文加密器:AES-GCM,密钥由配置 app.token-cipher-key 经 SHA-256 派生(配置任意长度字符串即可)。
* 密文格式:Base64( iv(12B) ‖ cipher+tag ),供 Open API 二次获取明文时解密。
* 配置为空时加解密直接报错(视为功能未开启,不回退到任何弱行为)。
*/
@Component
public class TokenCipher {
private static final int IV_LEN = 12;
private static final int TAG_BITS = 128;
private final byte[] key;
private final SecureRandom random = new SecureRandom();
public TokenCipher(@Value("${app.token-cipher-key:}") String cipherKey) {
if (cipherKey == null || cipherKey.isBlank()) {
this.key = null;
} else {
try {
this.key = MessageDigest.getInstance("SHA-256")
.digest(cipherKey.trim().getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw new IllegalStateException("SHA-256 不可用", e);
}
}
}
public String encrypt(String plaintext) {
byte[] iv = new byte[IV_LEN];
random.nextBytes(iv);
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(requireKey(), "AES"),
new GCMParameterSpec(TAG_BITS, iv));
byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
byte[] packed = new byte[IV_LEN + encrypted.length];
System.arraycopy(iv, 0, packed, 0, IV_LEN);
System.arraycopy(encrypted, 0, packed, IV_LEN, encrypted.length);
return Base64.getEncoder().encodeToString(packed);
} catch (Exception e) {
throw new IllegalStateException("ak 加密失败", e);
}
}
public String decrypt(String packedBase64) {
try {
byte[] packed = Base64.getDecoder().decode(packedBase64);
byte[] iv = new byte[IV_LEN];
System.arraycopy(packed, 0, iv, 0, IV_LEN);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(requireKey(), "AES"),
new GCMParameterSpec(TAG_BITS, iv));
return new String(cipher.doFinal(packed, IV_LEN, packed.length - IV_LEN), StandardCharsets.UTF_8);
} catch (IllegalStateException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("ak 密文解密失败", e);
}
}
private byte[] requireKey() {
if (key == null) throw new IllegalStateException("未配置 app.token-cipher-key,ak 加解密不可用");
return key;
}
}
@@ -5,6 +5,9 @@ app:
open:
# Open API(/api/open/**)服务间静态密钥,dev 明文;调用方放 header X-Open-Key
api-key: xqok_4b44012f12b9fa54d6ec11690e6da57563a75c891df60961
# ak 明文 AES-GCM 加密密钥(任意长度字符串,SHA-256 派生为密钥),供 ensure 二次获取明文;
# dev 明文(同库密码惯例),生产必须改用环境变量且与 dev 不同值
token-cipher-key: d70da46f5f0db2016d88d5ee4b1d6af35867b7700b97105fec9b3ad567d474a5
datasource:
m0: # 权限库 xiaoqu_comples_d(user/agent/authority/propery/agent_manage_district_auth)
driver-class-name: com.mysql.cj.jdbc.Driver
@@ -0,0 +1,3 @@
-- ak 二次获取(2026-09-07):签发时保存 AES-GCM 加密密文,ensure 已存在 Token 时解密回传明文
ALTER TABLE agent_api_key
ADD COLUMN key_cipher VARCHAR(512) NULL COMMENT 'ak 明文 AES-GCM 加密密文(Base64: iv‖cipher‖tag),空=历史数据未存' AFTER key_hash;
@@ -1,2 +1,3 @@
f8ec43a4fda81382d5675bc59fe7f4339f2e38a5b4241c260c3569e33b43a26d V1__init.sql
0ad892601e891a18712b1b6a613c392c94e63492dc14f4f779375c092a3acab6 V2__p4_admin.sql
0b6e407106156911f5fe83a13b342eeec5986e2e1e5b37b6797431a8720e1332 V3__token_cipher.sql
@@ -9,6 +9,7 @@ import me.iiv.agent.mapper.svc.AgentApiKeyMapper;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.mapper.svc.TokenScopeMapper;
import me.iiv.agent.security.AuthService;
import me.iiv.agent.security.TokenCipher;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
@@ -33,6 +34,7 @@ class AdminTokenServiceTest {
@Mock AgentApiKeyMapper tokenMapper;
@Mock TokenScopeMapper tokenScopeMapper;
@Mock AgentScopeMapper scopeMapper;
@Mock TokenCipher tokenCipher;
private User stubUser() {
User user = new User();
@@ -43,11 +45,13 @@ class AdminTokenServiceTest {
}
private AdminTokenService service() {
return new AdminTokenService(userMapper, tokenMapper, tokenScopeMapper, scopeMapper);
org.mockito.Mockito.lenient().when(tokenCipher.encrypt(any()))
.thenAnswer(invocation -> "cipher:" + invocation.getArgument(0));
return new AdminTokenService(userMapper, tokenMapper, tokenScopeMapper, scopeMapper, tokenCipher);
}
@Test
void issueReturnsPlaintextOnceAndStoresOnlyHash() {
void issueReturnsPlaintextAndStoresHashAndCipher() {
stubUser();
AgentScope scope = new AgentScope();
scope.setId(3L);
@@ -68,6 +72,7 @@ class AdminTokenServiceTest {
assertTrue(issued.get(0).plaintext().matches("xqak_[0-9a-f]{48}"));
assertEquals(AuthService.sha256Hex(issued.get(0).plaintext()), stored.getKeyHash());
assertNotEquals(issued.get(0).plaintext(), stored.getKeyHash());
assertEquals("cipher:" + issued.get(0).plaintext(), stored.getKeyCipher());
assertEquals(11L, issued.get(0).token().id());
}
@@ -19,7 +19,7 @@ class FlywayMigrationTest {
flyway.migrate();
assertEquals("2", flyway.info().current().getVersion().getVersion());
assertEquals("3", flyway.info().current().getVersion().getVersion());
assertEquals(255, passwordHashLength(dataSource));
}
@@ -28,12 +28,13 @@ class FlywayMigrationTest {
JdbcDataSource dataSource = dataSource("legacy");
try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE admin_user (id BIGINT AUTO_INCREMENT PRIMARY KEY, password_hash CHAR(64) NOT NULL)");
statement.execute("CREATE TABLE agent_api_key (id BIGINT AUTO_INCREMENT PRIMARY KEY, key_hash CHAR(64) NOT NULL)");
}
Flyway flyway = flyway(dataSource, true);
flyway.migrate();
assertEquals("2", flyway.info().current().getVersion().getVersion());
assertEquals("3", flyway.info().current().getVersion().getVersion());
assertEquals(255, passwordHashLength(dataSource));
}
@@ -7,6 +7,7 @@ import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.entity.svc.AgentScope;
import me.iiv.agent.mapper.m0.UserMapper;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.security.TokenCipher;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -37,6 +38,7 @@ class OpenTokenServiceTest {
@Mock AgentScopeMapper scopeMapper;
@Mock AdminTokenService tokenService;
@Mock AuditService auditService;
@Mock TokenCipher tokenCipher;
OpenTokenService service;
AgentScope scope;
@@ -44,7 +46,7 @@ class OpenTokenServiceTest {
@BeforeEach
void setUp() {
service = new OpenTokenService(userMapper, scopeMapper, tokenService, auditService);
service = new OpenTokenService(userMapper, scopeMapper, tokenService, auditService, tokenCipher);
scope = new AgentScope();
scope.setId(3L);
scope.setCode("operation");
@@ -62,24 +64,62 @@ class OpenTokenServiceTest {
}
@Test
void existingActiveTokenReturnsMetadataWithoutPlaintext() {
void existingTokenWithCipherReturnsDecryptedPlaintext() {
stubScopeAndUser();
AgentApiKey existing = new AgentApiKey();
existing.setId(11L);
existing.setKeyPrefix("xqak_abcd1234");
existing.setKeyCipher("packed-cipher");
when(tokenService.findActiveToken(7L, 3L)).thenReturn(existing);
when(tokenCipher.decrypt("packed-cipher")).thenReturn("xqak_abcd1234ffff");
OpenTokenController.EnsureResult result = service.ensure(
new OpenTokenController.EnsureRequest("13800001111", null, "operation"));
assertFalse(result.created());
assertNull(result.token());
assertEquals("xqak_abcd1234ffff", result.token());
assertEquals("xqak_abcd1234", result.keyPrefix());
assertEquals(7L, result.userId());
org.mockito.Mockito.verify(tokenService, never())
.issueSingle(anyLong(), anyString(), anyLong(), isNull(), anyLong());
}
@Test
void existingTokenWithoutCipherRotatesAndReturnsNewPlaintext() {
stubScopeAndUser();
AgentApiKey existing = new AgentApiKey();
existing.setId(11L);
existing.setKeyPrefix("xqak_abcd1234");
when(tokenService.findActiveToken(7L, 3L)).thenReturn(existing);
AdminTokenService.TokenView view = new AdminTokenService.TokenView(
12L, "xqak_efgh5678", "open-api 自动签发(operation)", (byte) 1,
null, null, List.of(3L), List.of("运营"));
when(tokenService.issueSingle(eq(7L), anyString(), eq(3L), isNull(), eq(0L)))
.thenReturn(new AdminTokenService.IssuedToken("xqak_" + "b".repeat(48), view));
OpenTokenController.EnsureResult result = service.ensure(
new OpenTokenController.EnsureRequest("13800001111", null, "operation"));
org.mockito.Mockito.verify(tokenService).status(11L, (byte) 0, 0L);
assertTrue(result.created());
assertTrue(result.token().matches("xqak_[0-9a-f]{48}"));
}
@Test
void decryptFailureReturns500() {
stubScopeAndUser();
AgentApiKey existing = new AgentApiKey();
existing.setId(11L);
existing.setKeyPrefix("xqak_abcd1234");
existing.setKeyCipher("bad-cipher");
when(tokenService.findActiveToken(7L, 3L)).thenReturn(existing);
when(tokenCipher.decrypt("bad-cipher")).thenThrow(new IllegalStateException("ak 密文解密失败"));
ResponseStatusException error = assertThrows(ResponseStatusException.class, () -> service.ensure(
new OpenTokenController.EnsureRequest("13800001111", null, "operation")));
assertEquals(500, error.getStatusCode().value());
}
@Test
void missingTokenCreatesPermanentOneAndReturnsPlaintext() {
stubScopeAndUser();
@@ -0,0 +1,50 @@
package me.iiv.agent.security;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class TokenCipherTest {
private final TokenCipher cipher = new TokenCipher("test-cipher-key");
@Test
void encryptDecryptRoundTrip() {
String plaintext = "xqak_25939fab31f812eb4e566197f53f16482d3e1f588b8bcaca";
String packed = cipher.encrypt(plaintext);
assertNotEquals(plaintext, packed);
assertEquals(plaintext, cipher.decrypt(packed));
}
@Test
void samePlaintextEncryptsDifferentlyEachTime() {
String plaintext = "xqak_" + "a".repeat(48);
assertNotEquals(cipher.encrypt(plaintext), cipher.encrypt(plaintext));
}
@Test
void wrongKeyCannotDecrypt() {
String packed = cipher.encrypt("xqak_secret");
TokenCipher other = new TokenCipher("another-key");
assertThrows(IllegalStateException.class, () -> other.decrypt(packed));
}
@Test
void tamperedCipherRejected() {
String packed = cipher.encrypt("xqak_secret");
byte[] raw = java.util.Base64.getDecoder().decode(packed);
raw[raw.length - 1] ^= 0x01;
String tampered = java.util.Base64.getEncoder().encodeToString(raw);
assertThrows(IllegalStateException.class, () -> cipher.decrypt(tampered));
}
@Test
void blankKeyDisablesCipher() {
TokenCipher disabled = new TokenCipher(" ");
assertThrows(IllegalStateException.class, () -> disabled.encrypt("xqak_x"));
assertThrows(IllegalStateException.class, () -> disabled.decrypt("AAAA"));
}
}