feat(admin): 增加账号管理与 Token 签发审计

This commit is contained in:
my_local_kimi_dev2
2026-11-18 11:57:33 +08:00
parent ba2ffabf19
commit 2a8c9260a6
14 changed files with 701 additions and 21 deletions
+2 -1
View File
@@ -141,6 +141,7 @@ nohup java -jar target/xiaoqu-agent-service.jar > target/app.log 2>&1 &
- 不提供默认 profile;数据库/Redis 连接信息明文写在 `application-dev.yml`(内网 dev 库,与 xiaoqu-franchisee pom.xml dev profile 同一惯例);生产/测试环境不得在配置文件写明文密码。
- dev 端口 **8088**,管理后台 `http://localhost:8088/`,MCP 端点 `http://localhost:8088/mcp`。
- 「账号管理」仅内置 `admin` 可见并调用,支持账号添加、编辑、禁用与软删除;编辑时密码留空表示不修改。删除或禁用后已有会话立即失效;不能禁用/删除当前登录账号或最后一个正常账号,内置 `admin` 不可改名。
- Flyway 在 Web 服务启动前执行 `validate + migrate`;checksum、版本或 SQL 执行失败时应用不会启动。
- 新增 SQL 必须遵循 [sql/README.md](sql/README.md),禁止修改已合并的历史 migration。
@@ -258,7 +259,7 @@ curl -X POST http://localhost:8088/api/open/token/ensure \
**服务 Token(principalType=service)**:`serviceName` 必填;只能绑定「允许服务主体」的作用域(`agent_scope.service_enabled=1`,REQ-20260921-0004 起由标记驱动,取代原先的 sync 硬编码),旧版不限域密钥不可签发服务 Token。服务 Token 无用户身份:调 SYNC 变化流工具为全量;调在线查询工具按**总部视角全量可见、不做行过滤**(PermissionService 统一分支),走独立限流档 `app.rate-limit.service-query-per-minute`(默认 300/分钟);`warehouse.todo.list.query` 按当前登录人统计,服务身份调用返回 PERMISSION_DENIED。典型用法:运营后台免登录分页拉取全量数据(scope `ops-query`)。
**签发规则(2026-09-04 起)**:一作用域一 Token。后台签发时选 N 个作用域会生成 N 把 token,每把独立绑定单作用域;编辑存量 token 时作用域为单选。
**签发规则(2026-09-04 起)**:后台签发时选 N 个作用域会生成 N 把 Token,每把独立绑定单作用域;编辑存量 Token 时也可多选作用域。Token 列表通过 `agent_api_key.create_id` 展示签发后台账号,Open API 自动签发显示为「系统自动」。
## codegen(run-once)
+90 -9
View File
@@ -5,6 +5,7 @@ import { api, setCsrf } from './api'
const menus = [
{ id: 'tokens', label: '用户与 Token', icon: '👥' },
{ id: 'accounts', label: '账号管理', icon: '▣' },
{ id: 'clients', label: '服务密钥', icon: '🔐' },
{ id: 'tools', label: '工具管理', icon: '🔧' },
{ id: 'scopes', label: '作用域管理', icon: '🧩' },
@@ -31,8 +32,11 @@ const toolFilter = reactive({ category: '', kind: '', keyword: '' })
const toolPage = reactive({ page: 1, pageSize: 20, total: 0 })
const auditFilter = reactive({ person: '', tokenPrefix: '', tool: '', result: '', client: '', from: '', to: '' })
const tokenDialog = ref(false)
const tokenForm = reactive({ id: null, memo: '', scopeIds: [], scopeId: null, expireTime: null })
const tokenForm = reactive({ id: null, memo: '', scopeIds: [], expireTime: null })
const issuedTokens = ref([])
const accounts = ref([])
const accountDialog = ref(false)
const accountForm = reactive({ id: null, account: '', name: '', password: '', status: 1 })
const clientDialog = ref(false)
const clientForm = reactive({ id: null, name: '', memo: '', scopeIds: [] })
const issuedOpenKey = ref(null)
@@ -125,9 +129,11 @@ async function logout() {
}
async function switchMenu(id) {
if (id === 'accounts' && session.account !== 'admin') return
if (!openTabs.value.includes(id)) openTabs.value = [...openTabs.value, id]
current.value = id
if (id === 'tokens') await loadUsers()
if (id === 'accounts') await loadAccounts()
if (id === 'clients') await loadOpenClients()
if (id === 'tools') await Promise.all([loadTools(), loadAllTools()])
if (id === 'scopes') await loadScopes()
@@ -169,14 +175,14 @@ async function selectUser(user) {
function openToken(token = null) {
Object.assign(tokenForm, token ? {
id: token.id, memo: token.memo || '', scopeIds: [], scopeId: token.scopeIds[0] ?? null,
id: token.id, memo: token.memo || '', scopeIds: [...token.scopeIds],
expireTime: token.expireTime || null,
} : { id: null, memo: '', scopeIds: [], scopeId: null, expireTime: null })
} : { id: null, memo: '', scopeIds: [], expireTime: null })
tokenDialog.value = true
}
async function saveToken() {
const scopeIds = tokenForm.id ? (tokenForm.scopeId ? [tokenForm.scopeId] : []) : tokenForm.scopeIds
const scopeIds = tokenForm.scopeIds
if (!scopeIds.length) return ElMessage.warning('至少选择一个作用域')
await run(async () => {
const body = JSON.stringify({ memo: tokenForm.memo, scopeIds, expireTime: tokenForm.expireTime })
@@ -209,6 +215,48 @@ async function deleteToken(token) {
}).catch(() => {})
}
async function loadAccounts() {
accounts.value = await api('/accounts')
}
function openAccount(account = null) {
Object.assign(accountForm, account ? {
id: account.id, account: account.account, name: account.name || '', password: '', status: account.status,
} : { id: null, account: '', name: '', password: '', status: 1 })
accountDialog.value = true
}
async function saveAccount() {
if (!accountForm.account.trim()) return ElMessage.warning('请输入登录账号')
if (!accountForm.id && accountForm.password.length < 12) return ElMessage.warning('密码至少 12 位')
if (accountForm.password && accountForm.password.length < 12) return ElMessage.warning('密码至少 12 位')
await run(async () => {
const body = JSON.stringify({
account: accountForm.account, name: accountForm.name,
password: accountForm.password, status: accountForm.status,
})
if (accountForm.id) {
await api(`/accounts/${accountForm.id}`, { method: 'PUT', body })
} else {
await api('/accounts', { method: 'POST', body })
}
accountDialog.value = false
await loadAccounts()
ElMessage.success(accountForm.id ? '账号已更新' : '账号已添加')
}).catch(() => {})
}
async function deleteAccount(account) {
try {
await ElMessageBox.confirm(`确认删除账号“${account.account}”?删除后该账号将立即无法登录。`, '删除账号', { type: 'warning' })
} catch { return }
await run(async () => {
await api(`/accounts/${account.id}`, { method: 'DELETE' })
await loadAccounts()
ElMessage.success('账号已删除')
}).catch(() => {})
}
async function loadOpenClients() {
;[openClients.value, scopes.value] = await Promise.all([api('/open-clients'), api('/scopes')])
}
@@ -380,6 +428,7 @@ onMounted(async () => {
<div class="logo"><span>趣</span> 智能体服务后台</div>
<nav aria-label="主导航">
<button :class="['menu-item', { active: current === 'tokens' }]" data-testid="admin-menu-tokens" @click="switchMenu('tokens')">👥 用户与 Token</button>
<button v-if="session.account === 'admin'" :class="['menu-item', { active: current === 'accounts' }]" data-testid="admin-menu-accounts" @click="switchMenu('accounts')">▣ 账号管理</button>
<button :class="['menu-item', { active: current === 'clients' }]" data-testid="admin-menu-clients" @click="switchMenu('clients')">🔐 服务密钥</button>
<button :class="['menu-item', { active: current === 'tools' }]" data-testid="admin-menu-tools" @click="switchMenu('tools')">🔧 工具管理</button>
<button :class="['menu-item', { active: current === 'scopes' }]" data-testid="admin-menu-scopes" @click="switchMenu('scopes')">🧩 作用域管理</button>
@@ -448,6 +497,7 @@ onMounted(async () => {
<el-table-column label="前缀" min-width="125"><template #default="{ row }"><code>{{ row.keyPrefix }}…</code></template></el-table-column>
<el-table-column prop="memo" label="备注" min-width="150" />
<el-table-column label="作用域" min-width="180"><template #default="{ row }"><el-tag v-for="name in row.scopeNames" :key="name" size="small" effect="plain">{{ name }}</el-tag></template></el-table-column>
<el-table-column label="签发账号" min-width="145"><template #default="{ row }"><span v-if="row.issuerAccount">{{ row.issuerAccount }}<template v-if="row.issuerName">({{ row.issuerName }})</template></span><span v-else>{{ row.issuerId === 0 ? '系统自动' : '未知' }}</span></template></el-table-column>
<el-table-column label="状态" width="90"><template #default="{ row }"><el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">{{ row.status === 1 ? '正常' : '已禁用' }}</el-tag></template></el-table-column>
<el-table-column label="过期时间" min-width="150"><template #default="{ row }">{{ expiry(row.expireTime) }}</template></el-table-column>
<el-table-column label="最后使用" min-width="150"><template #default="{ row }">{{ date(row.lastUsedTime) }}</template></el-table-column>
@@ -463,6 +513,30 @@ onMounted(async () => {
</div>
</template>
<template v-if="session.account === 'admin' && openTabs.includes('accounts')">
<div v-show="current === 'accounts'">
<article class="card">
<div class="card-title">
<span>管理后台账号</span>
<el-button type="primary" data-testid="admin-btn-new-account" @click="openAccount()">+ 添加账号</el-button>
</div>
<el-alert title="账号仅用于登录本管理后台;删除或禁用后,该账号的现有会话立即失效。" type="info" :closable="false" show-icon />
<el-table :data="accounts" class="client-table" data-testid="admin-table-accounts" empty-text="暂无账号">
<el-table-column prop="account" label="登录账号" min-width="180" />
<el-table-column prop="name" label="姓名" min-width="140"><template #default="{ row }">{{ row.name || '—' }}</template></el-table-column>
<el-table-column label="状态" width="100"><template #default="{ row }"><el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">{{ row.status === 1 ? '正常' : '已禁用' }}</el-tag></template></el-table-column>
<el-table-column label="创建时间" min-width="165"><template #default="{ row }">{{ date(row.createTime) }}</template></el-table-column>
<el-table-column label="修改时间" min-width="165"><template #default="{ row }">{{ date(row.modifyTime) }}</template></el-table-column>
<el-table-column label="操作" width="145" fixed="right"><template #default="{ row }">
<el-button link type="primary" :data-testid="`admin-account-edit-${row.id}`" @click="openAccount(row)">编辑</el-button>
<el-button link type="danger" :disabled="row.id === session.id" :data-testid="`admin-account-delete-${row.id}`" @click="deleteAccount(row)">删除</el-button>
</template></el-table-column>
</el-table>
<p class="hint">编辑时密码留空表示不修改;不能禁用或删除当前登录账号,且系统至少保留一个正常账号。</p>
</article>
</div>
</template>
<template v-if="openTabs.includes('clients')">
<div v-show="current === 'clients'">
<article class="card">
@@ -583,19 +657,26 @@ onMounted(async () => {
<el-form-item label="所属人员"><strong>{{ selectedUser?.name }}</strong></el-form-item>
<el-form-item label="用途备注"><el-input v-model="tokenForm.memo" maxlength="255" placeholder="如:Kimi 桌面用" aria-label="Token 用途备注" data-testid="admin-token-memo" /></el-form-item>
<el-form-item label="作用域">
<el-radio-group v-if="tokenForm.id" v-model="tokenForm.scopeId" data-testid="admin-token-scopes">
<el-radio v-for="scope in scopes.filter(item => item.status === 1)" :key="scope.id" :value="scope.id">{{ scope.name }}</el-radio>
</el-radio-group>
<el-checkbox-group v-else v-model="tokenForm.scopeIds" data-testid="admin-token-scopes">
<el-checkbox-group v-model="tokenForm.scopeIds" data-testid="admin-token-scopes">
<el-checkbox v-for="scope in scopes.filter(item => item.status === 1)" :key="scope.id" :value="scope.id">{{ scope.name }}</el-checkbox>
</el-checkbox-group>
<div class="hint" style="margin:4px 0 0">{{ tokenForm.id ? '一把 Token 只绑一个作用域' : '一作用域一 Token:选几个作用域就签发几把' }}</div>
<div class="hint" style="margin:4px 0 0">{{ tokenForm.id ? '至少选择一个作用域,保存后调整当前 Token 的作用域' : '一作用域一 Token:选几个作用域就签发几把' }}</div>
</el-form-item>
<el-form-item label="过期时间"><el-date-picker v-model="tokenForm.expireTime" type="datetime" value-format="YYYY-MM-DDTHH:mm:ssZ" placeholder="留空为永久" aria-label="Token 过期时间" data-testid="admin-token-expiry" /></el-form-item>
</el-form>
<template #footer><el-button data-testid="admin-token-cancel" @click="tokenDialog = false">取消</el-button><el-button type="primary" data-testid="admin-token-save" @click="saveToken">确认</el-button></template>
</el-dialog>
<el-dialog v-model="accountDialog" :title="accountForm.id ? '编辑后台账号' : '添加后台账号'" width="520px" destroy-on-close>
<el-form label-width="88px">
<el-form-item label="登录账号"><el-input v-model="accountForm.account" maxlength="64" autocomplete="off" :disabled="accountForm.account === 'admin'" aria-label="后台登录账号" data-testid="admin-account-account" /><div v-if="accountForm.account === 'admin'" class="hint">内置 admin 账号不能改名</div></el-form-item>
<el-form-item label="姓名"><el-input v-model="accountForm.name" maxlength="64" autocomplete="off" aria-label="后台账号姓名" data-testid="admin-account-name" /></el-form-item>
<el-form-item label="密码"><el-input v-model="accountForm.password" type="password" show-password maxlength="1024" autocomplete="new-password" :placeholder="accountForm.id ? '留空则不修改密码' : '至少 12 位'" aria-label="后台账号密码" data-testid="admin-account-password" /></el-form-item>
<el-form-item label="状态"><el-switch v-model="accountForm.status" :active-value="1" :inactive-value="0" active-text="正常" inactive-text="禁用" :disabled="accountForm.id === session.id" data-testid="admin-account-status" /></el-form-item>
</el-form>
<template #footer><el-button data-testid="admin-account-cancel" @click="accountDialog = false">取消</el-button><el-button type="primary" data-testid="admin-account-save" @click="saveAccount">保存</el-button></template>
</el-dialog>
<el-dialog v-model="scopeDialog" :title="scopeForm.id ? '编辑作用域' : '新建作用域'" width="520px" destroy-on-close>
<el-form label-width="88px">
<el-form-item label="名称"><el-input v-model="scopeForm.name" maxlength="64" aria-label="作用域名称" data-testid="admin-scope-name" /></el-form-item>
@@ -13,6 +13,14 @@ test('prototype interactions expose stable test ids', async () => {
'admin-menu-tools',
'admin-menu-scopes',
'admin-menu-audit',
'admin-menu-accounts',
'admin-btn-new-account',
'admin-table-accounts',
'admin-account-account',
'admin-account-name',
'admin-account-password',
'admin-account-status',
'admin-account-save',
'admin-input-user-search',
'admin-btn-issue-token',
'admin-btn-new-client',
@@ -41,4 +49,29 @@ test('multi-tab navigation exposes tab bar and close controls', async () => {
assert.match(source, /openTabs\.includes\('scopes'\)/, 'scopes panel gated by openTabs')
assert.match(source, /openTabs\.includes\('audit'\)/, 'audit panel gated by openTabs')
assert.match(source, /function closeTab\(/, 'closeTab handler')
assert.match(source, /openTabs\.includes\('accounts'\)/, 'accounts panel gated by openTabs')
})
test('token edit uses the same multi-scope selection as token issuing', async () => {
const source = await readFile(new URL('../src/App.vue', import.meta.url), 'utf8')
assert.match(source, /scopeIds: \[\.\.\.token\.scopeIds\]/, 'edit copies all current scopes')
assert.match(source, /const scopeIds = tokenForm\.scopeIds/, 'save uses one scope list for add and edit')
assert.doesNotMatch(source, /tokenForm\.scopeId\b/, 'legacy single-scope editor removed')
assert.doesNotMatch(source, /<el-radio-group v-if="tokenForm\.id"/, 'single-scope radio group removed')
})
test('account management uses CRUD endpoints and token rows expose issuer', async () => {
const source = await readFile(new URL('../src/App.vue', import.meta.url), 'utf8')
assert.match(source, /api\('\/accounts'\)/, 'account list')
assert.match(source, /api\('\/accounts', \{ method: 'POST'/, 'account create')
assert.match(source, /api\(`\/accounts\/\$\{accountForm\.id\}`, \{ method: 'PUT'/, 'account update')
assert.match(source, /api\(`\/accounts\/\$\{account\.id\}`, \{ method: 'DELETE'/, 'account delete')
assert.match(source, /row\.issuerAccount/, 'token issuer account column')
})
test('account management is only available to the admin account', async () => {
const source = await readFile(new URL('../src/App.vue', import.meta.url), 'utf8')
assert.match(source, /<button v-if="session\.account === 'admin'"[^>]*data-testid="admin-menu-accounts"/, 'admin-only menu')
assert.match(source, /v-if="session\.account === 'admin' && openTabs\.includes\('accounts'\)"/, 'admin-only panel')
assert.match(source, /if \(id === 'accounts' && session\.account !== 'admin'\) return/, 'admin-only navigation guard')
})
@@ -0,0 +1,54 @@
package me.iiv.agent.admin;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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/accounts")
public class AdminAccountController {
private final AdminAccountService service;
public AdminAccountController(AdminAccountService service) {
this.service = service;
}
@GetMapping
public List<AdminAccountService.AccountView> list() {
return service.list();
}
@PostMapping
public AdminAccountService.AccountView create(@RequestBody AdminAccountService.AccountRequest body,
HttpSession session) {
return service.create(body, adminId(session));
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void update(@PathVariable Long id, @RequestBody AdminAccountService.AccountRequest body,
HttpSession session) {
service.update(id, body, adminId(session));
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id, HttpSession session) {
service.delete(id, adminId(session));
}
private static Long adminId(HttpSession session) {
return (Long) session.getAttribute(AdminSessionFilter.ADMIN_SESSION_ID);
}
}
@@ -0,0 +1,130 @@
package me.iiv.agent.admin;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.util.Date;
import java.util.List;
@Service
public class AdminAccountService {
private final AdminUserMapper mapper;
private final AdminPasswordHasher hasher;
public AdminAccountService(AdminUserMapper mapper, AdminPasswordHasher hasher) {
this.mapper = mapper;
this.hasher = hasher;
}
public List<AccountView> list() {
return mapper.selectList(new LambdaQueryWrapper<AdminUser>()
.eq(AdminUser::getSoftDelete, 0).orderByDesc(AdminUser::getId))
.stream().map(AdminAccountService::view).toList();
}
@Transactional(transactionManager = "svcTransactionManager")
public AccountView create(AccountRequest body, Long operatorId) {
String account = validate(body, null, true);
AdminUser admin = new AdminUser();
admin.setAccount(account);
admin.setPasswordHash(hasher.hash(body.password()));
admin.setName(normalizeName(body.name()));
admin.setStatus(body.status() == null ? (byte) 1 : body.status());
admin.setCreateId(operatorId);
admin.setModifyId(operatorId);
admin.setSoftDelete((byte) 0);
mapper.insert(admin);
return view(admin);
}
@Transactional(transactionManager = "svcTransactionManager")
public void update(Long id, AccountRequest body, Long operatorId) {
AdminUser admin = active(id);
String account = validate(body, id, false);
if ("admin".equals(admin.getAccount()) && !"admin".equals(account)) {
conflict("内置 admin 账号不能改名");
}
byte status = body.status() == null ? admin.getStatus() : body.status();
if (id.equals(operatorId) && status == 0) conflict("不能禁用当前登录账号");
if (Byte.valueOf((byte) 1).equals(admin.getStatus()) && status == 0) ensureAnotherActive(id);
admin.setAccount(account);
admin.setName(normalizeName(body.name()));
admin.setStatus(status);
if (body.password() != null && !body.password().isBlank()) {
admin.setPasswordHash(hasher.hash(body.password()));
}
admin.setModifyId(operatorId);
mapper.updateById(admin);
}
@Transactional(transactionManager = "svcTransactionManager")
public void delete(Long id, Long operatorId) {
AdminUser admin = active(id);
if (id.equals(operatorId)) conflict("不能删除当前登录账号");
if (Byte.valueOf((byte) 1).equals(admin.getStatus())) ensureAnotherActive(id);
admin.setStatus((byte) 0);
admin.setSoftDelete((byte) 1);
admin.setModifyId(operatorId);
mapper.updateById(admin);
}
private String validate(AccountRequest body, Long currentId, boolean creating) {
if (body == null) bad("请求内容不能为空");
if (body.account() == null || body.account().isBlank() || body.account().length() > 64) {
bad("登录账号不能为空且最多 64 字");
}
if (body.name() != null && body.name().length() > 64) bad("姓名最多 64 字");
if (body.status() != null && body.status() != 0 && body.status() != 1) bad("账号状态无效");
if (creating || (body.password() != null && !body.password().isBlank())) {
if (body.password() == null || body.password().length() < 12 || body.password().length() > 1024) {
bad("密码长度须为 12 至 1024 位");
}
}
String account = body.account().trim();
AdminUser duplicate = mapper.selectOne(new LambdaQueryWrapper<AdminUser>()
.eq(AdminUser::getAccount, account)
.ne(currentId != null, AdminUser::getId, currentId));
if (duplicate != null) conflict("登录账号已存在");
return account;
}
private void ensureAnotherActive(Long excludedId) {
Long count = mapper.selectCount(new LambdaQueryWrapper<AdminUser>()
.eq(AdminUser::getStatus, 1).eq(AdminUser::getSoftDelete, 0)
.ne(AdminUser::getId, excludedId));
if (count == null || count == 0) conflict("至少保留一个正常状态的管理后台账号");
}
private AdminUser active(Long id) {
AdminUser admin = mapper.selectById(id);
if (admin == null || !Byte.valueOf((byte) 0).equals(admin.getSoftDelete())) bad("账号不存在");
return admin;
}
private static AccountView view(AdminUser admin) {
return new AccountView(admin.getId(), admin.getAccount(), admin.getName(), admin.getStatus(),
admin.getCreateTime(), admin.getModifyTime());
}
private static String normalizeName(String name) {
return name == null || name.isBlank() ? null : name.trim();
}
private static void bad(String message) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
}
private static void conflict(String message) {
throw new ResponseStatusException(HttpStatus.CONFLICT, message);
}
public record AccountRequest(String account, String password, String name, Byte status) {}
public record AccountView(Long id, String account, String name, Byte status,
Date createTime, Date modifyTime) {}
}
@@ -56,7 +56,7 @@ public class AdminAuthController {
if (admin == null || admin.getStatus() == null || admin.getStatus() != 1
|| admin.getSoftDelete() == null || admin.getSoftDelete() != 0) throw unauthorized();
return new SessionView(id, admin.getAccount(),
(String) session.getAttribute(AdminSessionFilter.ADMIN_SESSION_NAME),
admin.getName() == null ? admin.getAccount() : admin.getName(),
(String) session.getAttribute(AdminSessionFilter.CSRF_SESSION_KEY));
}
@@ -5,6 +5,8 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@@ -18,6 +20,12 @@ public class AdminSessionFilter extends OncePerRequestFilter {
static final String ADMIN_SESSION_NAME = "adminName";
static final String CSRF_SESSION_KEY = "adminCsrf";
private final AdminUserMapper adminUserMapper;
public AdminSessionFilter(AdminUserMapper adminUserMapper) {
this.adminUserMapper = adminUserMapper;
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return !request.getRequestURI().startsWith("/api/admin/");
@@ -37,6 +45,21 @@ public class AdminSessionFilter extends OncePerRequestFilter {
error(response, 401, "请先登录");
return;
}
Long adminId = (Long) session.getAttribute(ADMIN_SESSION_ID);
AdminUser admin = adminUserMapper.selectById(adminId);
if (admin == null || !Byte.valueOf((byte) 1).equals(admin.getStatus())
|| !Byte.valueOf((byte) 0).equals(admin.getSoftDelete())) {
session.invalidate();
error(response, 401, "账号已禁用或删除,请重新登录");
return;
}
if (("/api/admin/accounts".equals(uri) || uri.startsWith("/api/admin/accounts/"))
&& !"admin".equals(admin.getAccount())) {
error(response, 403, "仅 admin 可管理后台账号");
return;
}
session.setAttribute(ADMIN_SESSION_NAME,
admin.getName() == null ? admin.getAccount() : admin.getName());
Object csrf = session.getAttribute(CSRF_SESSION_KEY);
if (isMutation(request.getMethod())
&& (csrf == null || !csrf.equals(request.getHeader("X-CSRF-Token")))) {
@@ -2,10 +2,12 @@ package me.iiv.agent.admin;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.iiv.agent.entity.m0.User;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.entity.svc.AgentScope;
import me.iiv.agent.entity.svc.TokenScope;
import me.iiv.agent.mapper.m0.UserMapper;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import me.iiv.agent.mapper.svc.AgentApiKeyMapper;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.mapper.svc.TokenScopeMapper;
@@ -18,6 +20,9 @@ import org.springframework.web.server.ResponseStatusException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class AdminTokenService {
@@ -27,15 +32,17 @@ public class AdminTokenService {
private final TokenScopeMapper relationMapper;
private final AgentScopeMapper scopeMapper;
private final TokenCipher tokenCipher;
private final AdminUserMapper adminUserMapper;
public AdminTokenService(UserMapper userMapper, AgentApiKeyMapper tokenMapper,
TokenScopeMapper relationMapper, AgentScopeMapper scopeMapper,
TokenCipher tokenCipher) {
TokenCipher tokenCipher, AdminUserMapper adminUserMapper) {
this.userMapper = userMapper;
this.tokenMapper = tokenMapper;
this.relationMapper = relationMapper;
this.scopeMapper = scopeMapper;
this.tokenCipher = tokenCipher;
this.adminUserMapper = adminUserMapper;
}
/**
@@ -184,10 +191,21 @@ public class AdminTokenService {
List<AgentApiKey> tokens = tokenMapper.selectList(new LambdaQueryWrapper<AgentApiKey>()
.eq(AgentApiKey::getUserId, userId).eq(AgentApiKey::getSoftDelete, 0)
.orderByDesc(AgentApiKey::getCreateTime));
return tokens.stream().map(this::view).toList();
Set<Long> issuerIds = tokens.stream().map(AgentApiKey::getCreateId)
.filter(id -> id != null && id > 0).collect(Collectors.toSet());
Map<Long, AdminUser> issuers = issuerIds.isEmpty() ? Map.of()
: adminUserMapper.selectBatchIds(issuerIds).stream()
.collect(Collectors.toMap(AdminUser::getId, admin -> admin));
return tokens.stream().map(token -> view(token, issuers.get(token.getCreateId()))).toList();
}
private TokenView view(AgentApiKey token) {
AdminUser issuer = token.getCreateId() == null || token.getCreateId() <= 0
? null : adminUserMapper.selectById(token.getCreateId());
return view(token, issuer);
}
private TokenView view(AgentApiKey token, AdminUser issuer) {
List<Long> scopeIds = relationMapper.selectList(new LambdaQueryWrapper<TokenScope>()
.eq(TokenScope::getTokenId, token.getId()).eq(TokenScope::getSoftDelete, 0))
.stream().map(TokenScope::getScopeId).toList();
@@ -196,7 +214,9 @@ public class AdminTokenService {
.stream().map(AgentScope::getName).toList();
return new TokenView(token.getId(), token.getKeyPrefix(), token.getMemo(), token.getStatus(),
token.getPrincipalType(), token.getSubjectName(),
token.getExpireTime(), token.getLastUsedTime(), scopeIds, scopeNames);
token.getExpireTime(), token.getLastUsedTime(), scopeIds, scopeNames,
token.getCreateId(), issuer == null ? null : issuer.getAccount(),
issuer == null ? null : issuer.getName());
}
private void replaceScopes(Long tokenId, List<Long> scopeIds, Long adminId) {
@@ -252,6 +272,7 @@ public class AdminTokenService {
public record TokenView(Long id, String keyPrefix, String memo, Byte status,
String principalType, String subjectName, Date expireTime,
Date lastUsedTime, List<Long> scopeIds, List<String> scopeNames) {}
Date lastUsedTime, List<Long> scopeIds, List<String> scopeNames,
Long issuerId, String issuerAccount, String issuerName) {}
public record IssuedToken(String plaintext, TokenView token) {}
}
@@ -0,0 +1,178 @@
package me.iiv.agent.admin;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class AdminAccountServiceTest {
@Mock AdminUserMapper mapper;
@Mock AdminPasswordHasher hasher;
private AdminAccountService service() {
return new AdminAccountService(mapper, hasher);
}
@Test
void createHashesPasswordAndRecordsOperator() {
when(mapper.selectOne(any())).thenReturn(null);
when(hasher.hash("a-strong-password")).thenReturn("pbkdf2-hash");
when(mapper.insert(any(AdminUser.class))).thenAnswer(invocation -> {
invocation.<AdminUser>getArgument(0).setId(8L);
return 1;
});
AdminAccountService.AccountView view = service().create(
new AdminAccountService.AccountRequest("operator", "a-strong-password", "运营管理员", null), 1L);
ArgumentCaptor<AdminUser> captor = ArgumentCaptor.forClass(AdminUser.class);
verify(mapper).insert(captor.capture());
AdminUser stored = captor.getValue();
assertEquals("operator", stored.getAccount());
assertEquals("pbkdf2-hash", stored.getPasswordHash());
assertEquals(1L, stored.getCreateId());
assertEquals(1L, stored.getModifyId());
assertEquals((byte) 1, stored.getStatus());
assertEquals((byte) 0, stored.getSoftDelete());
assertEquals(8L, view.id());
assertEquals("operator", view.account());
}
@Test
void createRejectsDuplicateEvenWhenOldAccountWasDeleted() {
AdminUser deleted = new AdminUser();
deleted.setSoftDelete((byte) 1);
when(mapper.selectOne(any())).thenReturn(deleted);
assertThrows(ResponseStatusException.class, () -> service().create(
new AdminAccountService.AccountRequest("operator", "a-strong-password", "运营", null), 1L));
verify(mapper, never()).insert(any(AdminUser.class));
}
@Test
void updateWithBlankPasswordKeepsExistingHash() {
AdminUser current = activeAdmin(8L, "old-account");
when(mapper.selectById(8L)).thenReturn(current);
when(mapper.selectOne(any())).thenReturn(null);
service().update(8L, new AdminAccountService.AccountRequest(
"new-account", "", "新姓名", (byte) 1), 1L);
assertEquals("new-account", current.getAccount());
assertEquals("new-name-hash", current.getPasswordHash());
assertEquals("新姓名", current.getName());
assertEquals(1L, current.getModifyId());
verify(hasher, never()).hash(any());
verify(mapper).updateById(current);
}
@Test
void updateCanResetPassword() {
AdminUser current = activeAdmin(8L, "operator");
when(mapper.selectById(8L)).thenReturn(current);
when(mapper.selectOne(any())).thenReturn(null);
when(hasher.hash("another-strong-password")).thenReturn("new-hash");
service().update(8L, new AdminAccountService.AccountRequest(
"operator", "another-strong-password", "运营", (byte) 1), 1L);
assertEquals("new-hash", current.getPasswordHash());
}
@Test
void builtInAdminCannotBeRenamed() {
AdminUser current = activeAdmin(1L, "admin");
when(mapper.selectById(1L)).thenReturn(current);
when(mapper.selectOne(any())).thenReturn(null);
assertThrows(ResponseStatusException.class, () -> service().update(1L,
new AdminAccountService.AccountRequest("other-admin", "", "系统管理员", (byte) 1), 1L));
verify(mapper, never()).updateById(any(AdminUser.class));
}
@Test
void updateRejectsDisablingCurrentLoginAccount() {
AdminUser current = activeAdmin(8L, "operator");
when(mapper.selectById(8L)).thenReturn(current);
when(mapper.selectOne(any())).thenReturn(null);
assertThrows(ResponseStatusException.class, () -> service().update(8L,
new AdminAccountService.AccountRequest("operator", "", "运营", (byte) 0), 8L));
verify(mapper, never()).updateById(any(AdminUser.class));
}
@Test
void deleteRejectsCurrentLoginAccount() {
AdminUser current = activeAdmin(8L, "operator");
when(mapper.selectById(8L)).thenReturn(current);
assertThrows(ResponseStatusException.class, () -> service().delete(8L, 8L));
verify(mapper, never()).updateById(any(AdminUser.class));
}
@Test
void deleteRejectsLastActiveAdministrator() {
AdminUser current = activeAdmin(8L, "operator");
when(mapper.selectById(8L)).thenReturn(current);
when(mapper.selectCount(any())).thenReturn(0L);
assertThrows(ResponseStatusException.class, () -> service().delete(8L, 1L));
verify(mapper, never()).updateById(any(AdminUser.class));
}
@Test
void deleteSoftDeletesAndDisablesAccount() {
AdminUser current = activeAdmin(8L, "operator");
when(mapper.selectById(8L)).thenReturn(current);
when(mapper.selectCount(any())).thenReturn(1L);
service().delete(8L, 1L);
assertEquals((byte) 0, current.getStatus());
assertEquals((byte) 1, current.getSoftDelete());
assertEquals(1L, current.getModifyId());
verify(mapper).updateById(current);
}
@Test
void listNeverExposesPasswordHash() {
AdminUser admin = activeAdmin(8L, "operator");
admin.setPasswordHash("must-not-leak");
admin.setName("运营");
when(mapper.selectList(any())).thenReturn(List.of(admin));
List<AdminAccountService.AccountView> result = service().list();
assertEquals(1, result.size());
assertEquals("operator", result.get(0).account());
assertEquals("运营", result.get(0).name());
assertEquals(6, AdminAccountService.AccountView.class.getRecordComponents().length,
"AccountView 只应暴露 id/account/name/status/createTime/modifyTime");
}
private static AdminUser activeAdmin(Long id, String account) {
AdminUser admin = new AdminUser();
admin.setId(id);
admin.setAccount(account);
admin.setPasswordHash("new-name-hash");
admin.setName("管理员");
admin.setStatus((byte) 1);
admin.setSoftDelete((byte) 0);
return admin;
}
}
@@ -0,0 +1,39 @@
package me.iiv.agent.admin;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class AdminSessionAccountTest {
@Test
void deletedAccountSessionIsRejected() throws Exception {
AdminUserMapper mapper = mock(AdminUserMapper.class);
AdminUser deleted = new AdminUser();
deleted.setId(1L);
deleted.setStatus((byte) 0);
deleted.setSoftDelete((byte) 1);
when(mapper.selectById(1L)).thenReturn(deleted);
AdminSessionFilter filter = new AdminSessionFilter(mapper);
MockHttpSession session = new MockHttpSession();
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_ID, 1L);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/admin/tools");
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertEquals(401, response.getStatus());
assertNull(chain.getRequest());
}
}
@@ -1,5 +1,8 @@
package me.iiv.agent.admin;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -9,10 +12,24 @@ import org.springframework.mock.web.MockHttpSession;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class AdminSessionFilterTest {
private final AdminSessionFilter filter = new AdminSessionFilter();
private final AdminUserMapper mapper = mock(AdminUserMapper.class);
private final AdminSessionFilter filter = new AdminSessionFilter(mapper);
@BeforeEach
void setUp() {
AdminUser admin = new AdminUser();
admin.setId(1L);
admin.setAccount("admin");
admin.setStatus((byte) 1);
admin.setSoftDelete((byte) 0);
lenient().when(mapper.selectById(1L)).thenReturn(admin);
}
@Test
void protectedApiRequiresSession() throws Exception {
@@ -50,6 +67,39 @@ class AdminSessionFilterTest {
assertSame(request, chain.getRequest());
}
@Test
void accountManagementRejectsNonAdmin() throws Exception {
AdminUser operator = new AdminUser();
operator.setId(2L);
operator.setAccount("operator");
operator.setStatus((byte) 1);
operator.setSoftDelete((byte) 0);
when(mapper.selectById(2L)).thenReturn(operator);
MockHttpSession session = new MockHttpSession();
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_ID, 2L);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/admin/accounts");
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertEquals(403, response.getStatus());
assertNull(chain.getRequest());
}
@Test
void accountManagementAllowsAdmin() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/admin/accounts");
request.setSession(authenticatedSession());
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertSame(request, chain.getRequest());
}
@Test
void mutationRequiresMatchingCsrfToken() throws Exception {
MockHttpSession session = authenticatedSession();
@@ -0,0 +1,67 @@
package me.iiv.agent.admin;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.entity.svc.AgentScope;
import me.iiv.agent.entity.svc.TokenScope;
import me.iiv.agent.mapper.m0.UserMapper;
import me.iiv.agent.mapper.svc.AdminUserMapper;
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.TokenCipher;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class AdminTokenIssuerTest {
@Mock UserMapper userMapper;
@Mock AgentApiKeyMapper tokenMapper;
@Mock TokenScopeMapper tokenScopeMapper;
@Mock AgentScopeMapper scopeMapper;
@Mock TokenCipher tokenCipher;
@Mock AdminUserMapper adminUserMapper;
@Test
void tokenListIncludesIssuingAdminAccountEvenAfterAccountDeletion() {
AgentApiKey token = new AgentApiKey();
token.setId(11L);
token.setUserId(7L);
token.setCreateId(3L);
token.setSoftDelete((byte) 0);
when(tokenMapper.selectList(any())).thenReturn(List.of(token));
TokenScope relation = new TokenScope();
relation.setTokenId(11L);
relation.setScopeId(5L);
relation.setSoftDelete((byte) 0);
when(tokenScopeMapper.selectList(any())).thenReturn(List.of(relation));
AgentScope scope = new AgentScope();
scope.setId(5L);
scope.setName("研发专用");
when(scopeMapper.selectList(any())).thenReturn(List.of(scope));
AdminUser issuer = new AdminUser();
issuer.setId(3L);
issuer.setAccount("wangheng");
issuer.setName("王恒");
issuer.setSoftDelete((byte) 1);
when(adminUserMapper.selectBatchIds(anyCollection())).thenReturn(List.of(issuer));
AdminTokenService service = new AdminTokenService(userMapper, tokenMapper,
tokenScopeMapper, scopeMapper, tokenCipher, adminUserMapper);
AdminTokenService.TokenView view = service.list(7L).get(0);
assertEquals(3L, view.issuerId());
assertEquals("wangheng", view.issuerAccount());
assertEquals("王恒", view.issuerName());
}
}
@@ -5,6 +5,7 @@ import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.entity.svc.AgentScope;
import me.iiv.agent.entity.svc.TokenScope;
import me.iiv.agent.mapper.m0.UserMapper;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import me.iiv.agent.mapper.svc.AgentApiKeyMapper;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.mapper.svc.TokenScopeMapper;
@@ -36,6 +37,7 @@ class AdminTokenServiceTest {
@Mock TokenScopeMapper tokenScopeMapper;
@Mock AgentScopeMapper scopeMapper;
@Mock TokenCipher tokenCipher;
@Mock AdminUserMapper adminUserMapper;
private User stubUser() {
User user = new User();
@@ -48,7 +50,8 @@ class AdminTokenServiceTest {
private AdminTokenService service() {
org.mockito.Mockito.lenient().when(tokenCipher.encrypt(any()))
.thenAnswer(invocation -> "cipher:" + invocation.getArgument(0));
return new AdminTokenService(userMapper, tokenMapper, tokenScopeMapper, scopeMapper, tokenCipher);
return new AdminTokenService(userMapper, tokenMapper, tokenScopeMapper, scopeMapper,
tokenCipher, adminUserMapper);
}
@Test
@@ -96,7 +96,7 @@ class OpenTokenServiceTest {
private static AdminTokenService.IssuedToken issuedToken(String plaintext) {
AdminTokenService.TokenView view = new AdminTokenService.TokenView(
12L, "xqak_efgh5678", "open-api 自动签发(operation)", (byte) 1,
"user", null, null, null, List.of(3L), List.of("运营"));
"user", null, null, null, List.of(3L), List.of("运营"), 0L, null, null);
return new AdminTokenService.IssuedToken(plaintext, view);
}
@@ -228,7 +228,7 @@ class OpenTokenServiceTest {
when(tokenService.findActiveServiceToken("xiaoqu-ai", 9L)).thenReturn(null);
AdminTokenService.TokenView view = new AdminTokenService.TokenView(
12L, "xqak_efgh5678", "open-api 服务签发(sync)", (byte) 1,
"service", "xiaoqu-ai", null, null, List.of(9L), List.of("数据同步"));
"service", "xiaoqu-ai", null, null, List.of(9L), List.of("数据同步"), 0L, null, null);
when(tokenService.issueServiceToken(eq("xiaoqu-ai"), anyString(), eq(9L), isNull(), eq(0L)))
.thenReturn(new AdminTokenService.IssuedToken("xqak_" + "c".repeat(48), view));
@@ -273,7 +273,7 @@ class OpenTokenServiceTest {
when(tokenService.findActiveServiceToken("xiaoqu-ai", 9L)).thenReturn(existing);
AdminTokenService.TokenView view = new AdminTokenService.TokenView(
12L, "xqak_efgh5678", "open-api 服务签发(sync)", (byte) 1,
"service", "xiaoqu-ai", null, null, List.of(9L), List.of("数据同步"));
"service", "xiaoqu-ai", null, null, List.of(9L), List.of("数据同步"), 0L, null, null);
when(tokenService.issueServiceToken(eq("xiaoqu-ai"), anyString(), eq(9L), isNull(), eq(0L)))
.thenReturn(new AdminTokenService.IssuedToken("xqak_" + "d".repeat(48), view));
@@ -330,7 +330,7 @@ class OpenTokenServiceTest {
when(tokenService.findActiveServiceToken("ops", 10L)).thenReturn(null);
AdminTokenService.TokenView view = new AdminTokenService.TokenView(
13L, "xqak_ops00000", "open-api 服务签发(ops-query)", (byte) 1,
"service", "ops", null, null, List.of(10L), List.of("运营查询"));
"service", "ops", null, null, List.of(10L), List.of("运营查询"), 0L, null, null);
when(tokenService.issueServiceToken(eq("ops"), anyString(), eq(10L), isNull(), eq(0L)))
.thenReturn(new AdminTokenService.IssuedToken("xqak_" + "e".repeat(48), view));