feat(admin): add managed Open API client keys

This commit is contained in:
jiashumeng
2026-09-15 12:05:26 +09:30
parent 6cf1c0f4a0
commit e064e86def
22 changed files with 783 additions and 27 deletions
@@ -0,0 +1,65 @@
package me.iiv.agent.admin;
import jakarta.servlet.http.HttpSession;
import me.iiv.agent.open.OpenClientService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** 复用现有管理员会话的服务密钥管理接口。 */
@RestController
@RequestMapping("/api/admin/open-clients")
public class AdminOpenClientController {
private final OpenClientService service;
public AdminOpenClientController(OpenClientService service) {
this.service = service;
}
@GetMapping
public List<OpenClientService.ClientView> list() {
return service.list();
}
@PostMapping
public OpenClientService.IssuedClient create(@RequestBody OpenClientService.ClientRequest body,
HttpSession session) {
return service.create(body, adminId(session));
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void update(@PathVariable Long id, @RequestBody OpenClientService.ClientRequest body,
HttpSession session) {
service.update(id, body, adminId(session));
}
@PatchMapping("/{id}/status")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void status(@PathVariable Long id, @RequestBody StatusRequest body, HttpSession session) {
if (body == null) throw new org.springframework.web.server.ResponseStatusException(
HttpStatus.BAD_REQUEST, "请求内容不能为空");
service.status(id, body.status(), adminId(session));
}
@PostMapping("/{id}/rotate")
public OpenClientService.IssuedClient rotate(@PathVariable Long id, HttpSession session) {
return service.rotate(id, adminId(session));
}
private static Long adminId(HttpSession session) {
return (Long) session.getAttribute(AdminSessionFilter.ADMIN_SESSION_ID);
}
public record StatusRequest(byte status) {}
}
@@ -0,0 +1,34 @@
package me.iiv.agent.entity.svc;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
@Getter
@Setter
@ToString
@TableName("app_open_client")
public class AppOpenClient implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String name;
private String keyPrefix;
private String keyHash;
private String memo;
private Byte status;
private Date lastUsedTime;
private Long createId;
private Date createTime;
private Long modifyId;
private Date modifyTime;
private Byte softDelete;
}
@@ -0,0 +1,30 @@
package me.iiv.agent.entity.svc;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
@Getter
@Setter
@ToString
@TableName("app_open_client_scope")
public class AppOpenClientScope implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private Long clientId;
private Long scopeId;
private Long createId;
private Date createTime;
private Long modifyId;
private Date modifyTime;
private Byte softDelete;
}
@@ -0,0 +1,13 @@
package me.iiv.agent.mapper.svc;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import me.iiv.agent.entity.svc.AppOpenClient;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
public interface AppOpenClientMapper extends BaseMapper<AppOpenClient> {
/** 使用时间属于运行态信息,不应改变管理员看到的配置修改时间。 */
@Update("UPDATE app_open_client SET last_used_time = CURRENT_TIMESTAMP, modify_time = modify_time WHERE id = #{id}")
int touchLastUsed(@Param("id") Long id);
}
@@ -0,0 +1,7 @@
package me.iiv.agent.mapper.svc;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import me.iiv.agent.entity.svc.AppOpenClientScope;
public interface AppOpenClientScopeMapper extends BaseMapper<AppOpenClientScope> {
}
@@ -9,8 +9,8 @@ import java.util.List;
/**
* /api/open 服务密钥配置(REQ-20260911-0014)。
* 旧配置 api-key 为单个不绑定数据域的密钥,仅保留给存量用户 Token ensure;
* 新接入方(尤其签发 service 类型 Token)必须配置 clients:密钥 → 名称 + 允许的作用域编码,
* 鉴权时按密钥确定可调用的数据域,越域请求 403。
* 新接入方优先使用管理后台创建并落库的服务密钥;clients 继续作为环境变量兼容通道。
* 两种来源都按密钥确定允许的作用域编码,越域请求 403。
*/
@Component
@ConfigurationProperties(prefix = "app.open")
@@ -0,0 +1,253 @@
package me.iiv.agent.open;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.iiv.agent.entity.svc.AgentScope;
import me.iiv.agent.entity.svc.AppOpenClient;
import me.iiv.agent.entity.svc.AppOpenClientScope;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.mapper.svc.AppOpenClientMapper;
import me.iiv.agent.mapper.svc.AppOpenClientScopeMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ResponseStatusException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Date;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 数据库托管的 Open API 服务密钥。
* 明文只在创建或轮换时存在于本次响应中,持久化层仅保存 SHA-256 哈希。
*/
@Service
public class OpenClientService {
private static final Logger log = LoggerFactory.getLogger(OpenClientService.class);
private static final SecureRandom RANDOM = new SecureRandom();
private static final String KEY_PREFIX = "xqok_";
private final AppOpenClientMapper clientMapper;
private final AppOpenClientScopeMapper clientScopeMapper;
private final AgentScopeMapper scopeMapper;
public OpenClientService(AppOpenClientMapper clientMapper, AppOpenClientScopeMapper clientScopeMapper,
AgentScopeMapper scopeMapper) {
this.clientMapper = clientMapper;
this.clientScopeMapper = clientScopeMapper;
this.scopeMapper = scopeMapper;
}
/** 解析后台创建的密钥;禁用或删除的调用方不会命中。 */
public OpenClientProperties.ResolvedClient resolve(String plaintext) {
if (!StringUtils.hasText(plaintext)) return null;
AppOpenClient client = clientMapper.selectOne(new LambdaQueryWrapper<AppOpenClient>()
.eq(AppOpenClient::getKeyHash, sha256(plaintext))
.eq(AppOpenClient::getStatus, 1).eq(AppOpenClient::getSoftDelete, 0));
if (client == null) return null;
List<String> scopeCodes = boundScopes(client.getId()).stream().map(AgentScope::getCode).toList();
try {
clientMapper.touchLastUsed(client.getId());
} catch (RuntimeException e) {
// 使用时间是非关键遥测,不应使一把本来有效的密钥鉴权失败。
log.warn("服务密钥最后使用时间更新失败 clientId={}: {}", client.getId(), e.getMessage());
}
return new OpenClientProperties.ResolvedClient(client.getName(), scopeCodes, false);
}
/** 数据库中存在任何未删除配置时,Open API 视为已配置(即使当前全部已吊销)。 */
public boolean hasConfiguredClients() {
Long count = clientMapper.selectCount(new LambdaQueryWrapper<AppOpenClient>()
.eq(AppOpenClient::getSoftDelete, 0));
return count != null && count > 0;
}
public List<ClientView> list() {
List<AppOpenClient> clients = clientMapper.selectList(new LambdaQueryWrapper<AppOpenClient>()
.eq(AppOpenClient::getSoftDelete, 0).orderByDesc(AppOpenClient::getId));
if (clients.isEmpty()) return List.of();
Set<Long> clientIds = clients.stream().map(AppOpenClient::getId).collect(Collectors.toSet());
List<AppOpenClientScope> relations = clientScopeMapper.selectList(
new LambdaQueryWrapper<AppOpenClientScope>().in(AppOpenClientScope::getClientId, clientIds)
.eq(AppOpenClientScope::getSoftDelete, 0));
Set<Long> scopeIds = relations.stream().map(AppOpenClientScope::getScopeId).collect(Collectors.toSet());
Map<Long, AgentScope> scopeById = scopeIds.isEmpty() ? Map.of() : scopeMapper.selectList(
new LambdaQueryWrapper<AgentScope>().in(AgentScope::getId, scopeIds)
.eq(AgentScope::getSoftDelete, 0))
.stream().collect(Collectors.toMap(AgentScope::getId, Function.identity()));
Map<Long, List<AgentScope>> scopesByClient = new LinkedHashMap<>();
for (AppOpenClientScope relation : relations) {
AgentScope scope = scopeById.get(relation.getScopeId());
if (scope != null) scopesByClient.computeIfAbsent(relation.getClientId(), ignored -> new ArrayList<>()).add(scope);
}
return clients.stream().map(client -> view(client, scopesByClient.getOrDefault(client.getId(), List.of()))).toList();
}
@Transactional(transactionManager = "svcTransactionManager")
public IssuedClient create(ClientRequest body, Long adminId) {
ValidatedRequest request = validate(body, null);
String plaintext = generateKey();
AppOpenClient client = new AppOpenClient();
client.setName(request.name());
client.setMemo(request.memo());
client.setKeyPrefix(displayPrefix(plaintext));
client.setKeyHash(sha256(plaintext));
client.setStatus((byte) 1);
client.setCreateId(adminId);
client.setModifyId(adminId);
client.setSoftDelete((byte) 0);
clientMapper.insert(client);
replaceScopes(client.getId(), request.scopeIds(), adminId);
return new IssuedClient(plaintext, view(client, request.scopes()));
}
@Transactional(transactionManager = "svcTransactionManager")
public void update(Long id, ClientRequest body, Long adminId) {
AppOpenClient client = activeClient(id);
ValidatedRequest request = validate(body, id);
client.setName(request.name());
client.setMemo(request.memo());
client.setModifyId(adminId);
clientMapper.updateById(client);
replaceScopes(id, request.scopeIds(), adminId);
}
public void status(Long id, byte status, Long adminId) {
if (status != 0 && status != 1) bad("状态无效");
AppOpenClient client = activeClient(id);
client.setStatus(status);
client.setModifyId(adminId);
clientMapper.updateById(client);
}
@Transactional(transactionManager = "svcTransactionManager")
public IssuedClient rotate(Long id, Long adminId) {
AppOpenClient client = activeClient(id);
String plaintext = generateKey();
client.setKeyPrefix(displayPrefix(plaintext));
client.setKeyHash(sha256(plaintext));
client.setModifyId(adminId);
clientMapper.updateById(client);
return new IssuedClient(plaintext, view(client, boundScopes(client.getId())));
}
private ValidatedRequest validate(ClientRequest body, Long currentId) {
if (body == null) bad("请求内容不能为空");
if (!StringUtils.hasText(body.name()) || body.name().trim().length() > 64) {
bad("调用方名称不能为空且最多 64 字");
}
if (body.memo() != null && body.memo().length() > 255) bad("用途备注最多 255 字");
AppOpenClient duplicate = clientMapper.selectOne(new LambdaQueryWrapper<AppOpenClient>()
.eq(AppOpenClient::getName, body.name().trim()).eq(AppOpenClient::getSoftDelete, 0)
.ne(currentId != null, AppOpenClient::getId, currentId));
if (duplicate != null) throw new ResponseStatusException(HttpStatus.CONFLICT, "调用方名称已存在");
List<Long> ids = body.scopeIds() == null ? List.of() : body.scopeIds().stream()
.filter(Objects::nonNull).distinct().toList();
if (ids.isEmpty()) bad("至少选择一个作用域");
if (ids.size() > 100) bad("作用域数量不能超过 100");
List<AgentScope> scopes = scopeMapper.selectList(new LambdaQueryWrapper<AgentScope>()
.in(AgentScope::getId, ids).eq(AgentScope::getStatus, 1).eq(AgentScope::getSoftDelete, 0));
if (scopes.size() != ids.size()) bad("作用域不存在或已停用");
Map<Long, AgentScope> byId = scopes.stream().collect(Collectors.toMap(AgentScope::getId, Function.identity()));
List<AgentScope> ordered = ids.stream().map(byId::get).toList();
return new ValidatedRequest(body.name().trim(), trimToNull(body.memo()), ids, ordered);
}
private void replaceScopes(Long clientId, List<Long> scopeIds, Long adminId) {
List<AppOpenClientScope> old = clientScopeMapper.selectList(new LambdaQueryWrapper<AppOpenClientScope>()
.eq(AppOpenClientScope::getClientId, clientId));
for (AppOpenClientScope relation : old) {
relation.setSoftDelete((byte) 1);
relation.setModifyId(adminId);
clientScopeMapper.updateById(relation);
}
for (Long scopeId : scopeIds) {
AppOpenClientScope relation = old.stream()
.filter(row -> Objects.equals(row.getScopeId(), scopeId)).findFirst().orElse(null);
if (relation == null) {
relation = new AppOpenClientScope();
relation.setClientId(clientId);
relation.setScopeId(scopeId);
relation.setCreateId(adminId);
}
relation.setModifyId(adminId);
relation.setSoftDelete((byte) 0);
if (relation.getId() == null) clientScopeMapper.insert(relation);
else clientScopeMapper.updateById(relation);
}
}
private AppOpenClient activeClient(Long id) {
AppOpenClient client = clientMapper.selectById(id);
if (client == null || !Byte.valueOf((byte) 0).equals(client.getSoftDelete())) bad("服务密钥不存在");
return client;
}
private List<AgentScope> boundScopes(Long clientId) {
List<Long> ids = clientScopeMapper.selectList(new LambdaQueryWrapper<AppOpenClientScope>()
.eq(AppOpenClientScope::getClientId, clientId).eq(AppOpenClientScope::getSoftDelete, 0))
.stream().map(AppOpenClientScope::getScopeId).toList();
if (ids.isEmpty()) return List.of();
return scopeMapper.selectList(new LambdaQueryWrapper<AgentScope>().in(AgentScope::getId, ids)
.eq(AgentScope::getSoftDelete, 0).orderByAsc(AgentScope::getId));
}
private static ClientView view(AppOpenClient client, List<AgentScope> scopes) {
return new ClientView(client.getId(), client.getName(), client.getKeyPrefix(), client.getMemo(),
client.getStatus(), client.getLastUsedTime(), client.getCreateTime(), client.getModifyTime(),
scopes.stream().map(AgentScope::getId).toList(),
scopes.stream().map(AgentScope::getName).toList(),
scopes.stream().map(AgentScope::getCode).toList());
}
static String generateKey() {
byte[] random = new byte[24];
RANDOM.nextBytes(random);
return KEY_PREFIX + HexFormat.of().formatHex(random);
}
static String sha256(String value) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 不可用", e);
}
}
private static String displayPrefix(String plaintext) {
return plaintext.substring(0, Math.min(13, plaintext.length()));
}
private static String trimToNull(String value) {
if (value == null || value.trim().isEmpty()) return null;
return value.trim();
}
private static void bad(String message) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
}
public record ClientRequest(String name, String memo, List<Long> scopeIds) {}
public record ClientView(Long id, String name, String keyPrefix, String memo, Byte status,
Date lastUsedTime, Date createTime, Date modifyTime,
List<Long> scopeIds, List<String> scopeNames, List<String> scopeCodes) {}
public record IssuedClient(String plaintext, ClientView client) {}
private record ValidatedRequest(String name, String memo, List<Long> scopeIds, List<AgentScope> scopes) {}
}
@@ -26,9 +26,11 @@ public class OpenKeyFilter extends OncePerRequestFilter {
static final String CLIENT_ATTRIBUTE = "me.iiv.agent.open.client";
private final OpenClientProperties properties;
private final OpenClientService clientService;
public OpenKeyFilter(OpenClientProperties properties) {
public OpenKeyFilter(OpenClientProperties properties, OpenClientService clientService) {
this.properties = properties;
this.clientService = clientService;
}
@Override
@@ -44,7 +46,8 @@ public class OpenKeyFilter extends OncePerRequestFilter {
OpenClientProperties.ResolvedClient client = provided == null ? null : resolve(provided);
if (client == null) {
boolean configured = properties.getApiKey() != null && !properties.getApiKey().isBlank()
|| properties.getClients() != null && !properties.getClients().isEmpty();
|| properties.getClients() != null && !properties.getClients().isEmpty()
|| clientService.hasConfiguredClients();
error(response, configured ? 401 : 403, configured ? "服务间密钥无效" : "Open API 未启用");
return;
}
@@ -54,6 +57,8 @@ public class OpenKeyFilter extends OncePerRequestFilter {
/** 命中 clients 清单返回绑定的作用域;命中旧 api-key 返回不绑域的 legacy client;均未命中返回 null */
private OpenClientProperties.ResolvedClient resolve(String provided) {
OpenClientProperties.ResolvedClient managed = clientService.resolve(provided);
if (managed != null) return managed;
byte[] providedBytes = provided.getBytes(StandardCharsets.UTF_8);
if (properties.getClients() != null) {
for (OpenClientProperties.Client client : properties.getClients()) {
@@ -23,7 +23,7 @@ import java.util.Date;
* 存在有效 Token 时解密 key_cipher 回传明文(二次获取,2026-09-07 决策);
* 历史数据无密文的 Token 自动轮换(禁用旧把、签发新把);
* 不存在则自动创建永久 Token。两条路径均返回明文。
* service 类型(REQ-20260911-0014):要求服务密钥已在配置中绑定该作用域(app.open.clients),
* service 类型(REQ-20260911-0014):要求服务密钥已在后台或配置中绑定该作用域,
* 旧版不限域密钥(app.open.api-key)不可签发服务 Token。
*/
@Service
@@ -91,7 +91,7 @@ public class OpenTokenService {
}
if (service && client.legacy()) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN,
"签发服务 Token 必须在 app.open.clients 中配置绑定了作用域的服务密钥");
"签发服务 Token 必须使用绑定了作用域的非旧版服务密钥");
}
}