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;
}
}