安全审计:登记登录、登出、登录失败、修改本人密码、初始化、导出与备份下载
- 新增 server/security-audit.js:统一写入 {ip, userAgent(≤200字)} 及少量说明,写入失败只打印错误、不改变响应
- 登录失败用合成身份“未登录”(role=system),记录登录名(≤50字)与原因 unknown_user / password_not_set / wrong_password;判断顺序与原条件一致,未知账号照常计算哈希
- 修改本人密码失败会整体回滚:分发器新增 ctx.afterRollback,回滚后另行写入失败记录
- 导出库存流水Excel记录实际使用的筛选条件;下载备份记录文件名
- 员工业务数据判定忽略 auth:*、export、backup 审计,登录不影响员工删除资格
- 两处“只读不改库”测试改为忽略安全审计行
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2305900178
commit
a965becde3
9 files changed
+360
-39
No files matched your search
@@ -258,12 +258,18 @@ async function fixture(t) {
|
||||
return { l, actors, call, pending, pendingDelete, order };
|
||||
}
|
||||
|
||||
// 登录与导出的安全审计(及其自增序号)不属于业务数据。
|
||||
function businessRows(l, name) {
|
||||
if (name === 'audit')
|
||||
return l.rows("SELECT * FROM audit WHERE entity NOT LIKE 'auth:%' AND entity<>'export' ORDER BY rowid");
|
||||
if (name === 'sqlite_sequence') return l.rows("SELECT * FROM sqlite_sequence WHERE name<>'audit' ORDER BY rowid");
|
||||
return l.rows('SELECT * FROM "' + name + '" ORDER BY rowid');
|
||||
}
|
||||
test('三账号HTTP下载所有筛后记录超过100条,与分页排序一致且不导出成本/订单详情/审批ID,不改数据库', async t => {
|
||||
const f = await fixture(t),
|
||||
path = '/api/inventory/movements/export.xlsx',
|
||||
tables = f.l.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(row => row.name),
|
||||
snapshot = () =>
|
||||
JSON.stringify(tables.map(name => [name, f.l.rows('SELECT * FROM "' + name + '" ORDER BY rowid')])),
|
||||
snapshot = () => JSON.stringify(tables.map(name => [name, businessRows(f.l, name)])),
|
||||
before = snapshot();
|
||||
assert.equal((await f.call(path, 'none')).status, 401);
|
||||
let previous;
|
||||
@@ -338,8 +344,7 @@ test('货盘和5种类型沿用分页筛选,导出不受page限制;空筛选
|
||||
test('三账号HTTP隐藏删除与分页、Excel共用完整筛选,保留待删除审批及有效更正,不写数据库', async t => {
|
||||
const f = await fixture(t),
|
||||
tables = f.l.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(row => row.name),
|
||||
snapshot = () =>
|
||||
JSON.stringify(tables.map(name => [name, f.l.rows('SELECT * FROM "' + name + '" ORDER BY rowid')])),
|
||||
snapshot = () => JSON.stringify(tables.map(name => [name, businessRows(f.l, name)])),
|
||||
before = snapshot();
|
||||
const all = f.l.inventoryMovementsExport({}, f.actors.owner).movements;
|
||||
assert.equal(all.filter(row => row.status === 'deleted').length, 2);
|
||||
|
||||
@@ -966,7 +966,6 @@ test('员工旧人数幂等回执也拒绝读取,缓存与原写入不改', as
|
||||
const tables = [
|
||||
'daily_people_counts',
|
||||
'operations',
|
||||
'audit',
|
||||
'orders',
|
||||
'payments',
|
||||
'expenses',
|
||||
@@ -974,7 +973,10 @@ test('员工旧人数幂等回执也拒绝读取,缓存与原写入不改', as
|
||||
'movements',
|
||||
'team_fund_cash',
|
||||
],
|
||||
before = contents(l, tables);
|
||||
// 登录的安全审计不属于业务数据。
|
||||
snapshot = () =>
|
||||
contents(l, tables) + JSON.stringify(l.rows("SELECT * FROM audit WHERE entity NOT LIKE 'auth:%' ORDER BY id")),
|
||||
before = snapshot();
|
||||
for (const sample of samples) {
|
||||
const cookie = await login(sample.member);
|
||||
assert.equal((await call('/api/people-count', cookie, sample.body, sample.key)).status, 403);
|
||||
@@ -982,7 +984,7 @@ test('员工旧人数幂等回执也拒绝读取,缓存与原写入不改', as
|
||||
}
|
||||
const cookie = await login('assistant');
|
||||
assert.equal((await call('/api/people-count', cookie, errorBody, errorKey)).status, 403);
|
||||
assert.equal(contents(l, tables), before, '拒绝访问不改原operations、人数或账务');
|
||||
assert.equal(snapshot(), before, '拒绝访问不改原operations、人数或账务');
|
||||
});
|
||||
|
||||
test('员工不能通过旧人数、订单簿或日报取得总数和基准日期', async t => {
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
'use strict';
|
||||
const test = require('node:test'),
|
||||
assert = require('node:assert/strict'),
|
||||
crypto = require('node:crypto'),
|
||||
fs = require('node:fs'),
|
||||
os = require('node:os'),
|
||||
path = require('node:path');
|
||||
const { Ledger } = require('../ledger');
|
||||
const { createApp, createUser } = require('../server');
|
||||
const Employees = require('../employee-management');
|
||||
|
||||
const OWNER_PW = 'owner-secret-password-1',
|
||||
ASSISTANT_PW = 'assistant-secret-password-2',
|
||||
NEW_PW = 'owner-new-secret-password-3',
|
||||
WRONG_PW = 'wrong-secret-password-4',
|
||||
LONG_UA = 'SecurityAuditTest/1.0 ' + 'x'.repeat(300);
|
||||
|
||||
async function start(t, options) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-security-audit-'));
|
||||
const app = createApp({ port: 0, dataDir: dir, feishuConfig: { enabled: false }, ...options });
|
||||
await new Promise(r => app.server.listen(0, '127.0.0.1', r));
|
||||
t.after(async () => {
|
||||
await new Promise(r => {
|
||||
app.server.closeAllConnections();
|
||||
app.server.close(r);
|
||||
});
|
||||
app.ledger.close();
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
const base = 'http://127.0.0.1:' + app.server.address().port;
|
||||
const client = { cookie: '', tokens: [] };
|
||||
client.call = async (route, data, { write = false } = {}) => {
|
||||
const r = await fetch(base + route, {
|
||||
method: data ? 'POST' : 'GET',
|
||||
headers: {
|
||||
'User-Agent': LONG_UA,
|
||||
...(client.cookie ? { Cookie: client.cookie } : {}),
|
||||
...(data ? { 'Content-Type': 'application/json', Origin: base, 'X-Requested-With': 'maimai-ledger' } : {}),
|
||||
...(write ? { 'Idempotency-Key': crypto.randomUUID() } : {}),
|
||||
},
|
||||
body: data ? JSON.stringify(data) : undefined,
|
||||
});
|
||||
const cookie = r.headers.get('set-cookie');
|
||||
if (cookie?.startsWith('mm_session=') && !cookie.startsWith('mm_session=;')) {
|
||||
client.cookie = cookie.split(';')[0];
|
||||
client.tokens.push(client.cookie.slice(11));
|
||||
}
|
||||
const type = r.headers.get('content-type') || '';
|
||||
return { status: r.status, body: type.includes('json') ? await r.json() : Buffer.from(await r.arrayBuffer()) };
|
||||
};
|
||||
return { app, client, base };
|
||||
}
|
||||
const auditRows = ledger =>
|
||||
ledger.rows('SELECT * FROM audit ORDER BY id').map(row => ({ ...row, detail: JSON.parse(row.detail) }));
|
||||
const securityRows = ledger =>
|
||||
auditRows(ledger).filter(row => /^auth:/.test(row.entity) || ['export', 'backup'].includes(row.entity));
|
||||
const last = (ledger, action) => securityRows(ledger).findLast(row => row.action === action);
|
||||
function assertRequestInfo(row) {
|
||||
assert.match(row.detail.ip, /127\.0\.0\.1/);
|
||||
assert.equal(row.detail.userAgent, LONG_UA.slice(0, 200));
|
||||
}
|
||||
function assertNoSecrets(ledger, client) {
|
||||
const secrets = [OWNER_PW, ASSISTANT_PW, NEW_PW, WRONG_PW, ...client.tokens];
|
||||
for (const token of client.tokens) secrets.push(crypto.createHash('sha256').update(token).digest('hex'));
|
||||
for (const u of ledger.rows('SELECT salt,hash FROM users')) secrets.push(u.salt, u.hash);
|
||||
for (const s of ledger.rows('SELECT hash FROM sessions')) secrets.push(s.hash);
|
||||
const rows = securityRows(ledger);
|
||||
assert.ok(rows.length > 0);
|
||||
for (const row of rows) {
|
||||
const text = JSON.stringify(row);
|
||||
for (const secret of secrets) assert.ok(!text.includes(secret), row.action + ' 的审计内容含有敏感信息');
|
||||
for (const key of Object.keys(row.detail))
|
||||
assert.ok(!/password|hash|salt|token|cookie/i.test(key), row.action + ' 的审计字段 ' + key + ' 不应出现');
|
||||
}
|
||||
}
|
||||
|
||||
test('初始化、登录成功/失败、修改本人密码、导出、备份下载与登出均登记安全审计,响应不变', async t => {
|
||||
const { app, client } = await start(t, { mode: 'trial' });
|
||||
const ledger = app.ledger;
|
||||
|
||||
const setup = await client.call('/api/setup', { ownerPassword: OWNER_PW, assistantPassword: ASSISTANT_PW });
|
||||
assert.equal(setup.status, 200);
|
||||
assert.deepEqual(Object.keys(setup.body), ['user']);
|
||||
const ownerId = setup.body.user.id;
|
||||
let row = last(ledger, '初始化账号');
|
||||
assert.equal(row.entity, 'auth:' + ownerId);
|
||||
assert.equal(row.actor, '麦麦');
|
||||
assertRequestInfo(row);
|
||||
assert.deepEqual(row.detail.actorIdentity, { id: ownerId, role: 'owner', member: 'owner' });
|
||||
|
||||
// 登录失败:未知账号、未设置密码、密码错误;响应保持 401 与原文,不下发 cookie。
|
||||
const unset = createUser(ledger, '未设密码员工', 'assistant', crypto.randomUUID(), null, { passwordSet: false });
|
||||
const failures = [
|
||||
[{ name: '不存在的员工' + 'z'.repeat(80), password: WRONG_PW }, 'auth:unknown', 'unknown_user'],
|
||||
[{ name: '未设密码员工', password: WRONG_PW }, 'auth:' + unset, 'password_not_set'],
|
||||
[{ name: '麦麦', password: WRONG_PW }, 'auth:' + ownerId, 'wrong_password'],
|
||||
[{ member: 'owner', password: WRONG_PW }, 'auth:' + ownerId, 'wrong_password'],
|
||||
[{ name: { toString: 1 }, password: WRONG_PW }, 'auth:unknown', 'unknown_user'],
|
||||
];
|
||||
for (const [input, entity, reason] of failures) {
|
||||
client.cookie = '';
|
||||
const r = await client.call('/api/login', input);
|
||||
assert.equal(r.status, 401);
|
||||
assert.deepEqual(r.body, { error: '账号或密码不正确' });
|
||||
assert.equal(client.cookie, '');
|
||||
row = last(ledger, '登录失败');
|
||||
assert.equal(row.entity, entity);
|
||||
assert.equal(row.actor, '未登录');
|
||||
assert.equal(row.detail.reason, reason);
|
||||
const attempted = input.member ?? input.name;
|
||||
assert.equal(row.detail.loginName, typeof attempted === 'string' ? attempted.slice(0, 50) : null);
|
||||
assert.deepEqual(row.detail.actorIdentity, { id: null, role: 'system', member: null });
|
||||
assertRequestInfo(row);
|
||||
}
|
||||
assert.equal(last(ledger, '登录失败').detail.loginName, null);
|
||||
assert.equal(securityRows(ledger).filter(r => r.action === '登录失败')[0].detail.loginName.length, 50);
|
||||
|
||||
const login = await client.call('/api/login', { name: '麦麦', password: OWNER_PW });
|
||||
assert.equal(login.status, 200);
|
||||
assert.equal(login.body.user.id, ownerId);
|
||||
row = last(ledger, '登录成功');
|
||||
assert.equal(row.entity, 'auth:' + ownerId);
|
||||
assert.equal(row.actor, '麦麦');
|
||||
assertRequestInfo(row);
|
||||
|
||||
// 原密码错误:仍为 400 原文,密码不变;失败记录在回滚后另行写入,不随事务撤销。
|
||||
const wrong = await client.call('/api/password', { current: WRONG_PW, password: NEW_PW }, { write: true });
|
||||
assert.equal(wrong.status, 400);
|
||||
assert.deepEqual(wrong.body, { error: '原密码不正确' });
|
||||
row = last(ledger, '修改本人密码失败');
|
||||
assert.equal(row.entity, 'auth:' + ownerId);
|
||||
assert.equal(row.detail.reason, 'wrong_password');
|
||||
assertRequestInfo(row);
|
||||
assert.equal(last(ledger, '修改本人密码'), undefined);
|
||||
// 新密码过短仍按原样拒绝,不登记成功。
|
||||
const short = await client.call('/api/password', { current: OWNER_PW, password: 'short' }, { write: true });
|
||||
assert.deepEqual([short.status, short.body], [400, { error: '新密码至少12个字符' }]);
|
||||
assert.equal(last(ledger, '修改本人密码'), undefined);
|
||||
|
||||
// 导出与备份下载。
|
||||
const csv = await client.call('/api/export/inventory');
|
||||
assert.equal(csv.status, 200);
|
||||
assert.ok(csv.body.toString('utf8').startsWith('货盘,'));
|
||||
row = last(ledger, '导出库存CSV');
|
||||
assert.equal(row.entity, 'export');
|
||||
assert.equal(row.actor, '麦麦');
|
||||
assertRequestInfo(row);
|
||||
|
||||
const xlsx = await client.call('/api/inventory/movements/export.xlsx?kind=manual&from=2020-01-01&to=2099-12-31');
|
||||
assert.equal(xlsx.status, 200);
|
||||
assert.equal(xlsx.body.subarray(0, 2).toString(), 'PK');
|
||||
row = last(ledger, '导出库存流水Excel');
|
||||
assert.equal(row.entity, 'export');
|
||||
assert.equal(row.detail.filters.kind, 'manual');
|
||||
assert.equal(row.detail.filters.from, '2020-01-01');
|
||||
assert.equal(row.detail.filters.to, '2099-12-31');
|
||||
assert.ok('pocket' in row.detail.filters && 'hideDeleted' in row.detail.filters);
|
||||
assertRequestInfo(row);
|
||||
// 导出失败不登记。
|
||||
const badExport = await client.call('/api/inventory/movements/export.xlsx?kind=bogus');
|
||||
assert.equal(badExport.status, 400);
|
||||
assert.equal(securityRows(ledger).filter(r => r.action === '导出库存流水Excel').length, 1);
|
||||
|
||||
const backup = await client.call('/api/backup', {});
|
||||
assert.equal(backup.status, 200);
|
||||
const download = await client.call('/api/backup/' + backup.body.name);
|
||||
assert.equal(download.status, 200);
|
||||
assert.equal(download.body.subarray(0, 15).toString(), 'SQLite format 3');
|
||||
row = last(ledger, '下载备份');
|
||||
assert.equal(row.entity, 'backup');
|
||||
assert.equal(row.detail.file, backup.body.name);
|
||||
assertRequestInfo(row);
|
||||
assert.deepEqual((await client.call('/api/backup/ledger-2000-01-01T00-00-00-000Z.sqlite')).status, 404);
|
||||
assert.equal(securityRows(ledger).filter(r => r.action === '下载备份').length, 1);
|
||||
|
||||
const changed = await client.call('/api/password', { current: OWNER_PW, password: NEW_PW }, { write: true });
|
||||
assert.deepEqual([changed.status, changed.body], [200, { ok: true }]);
|
||||
row = last(ledger, '修改本人密码');
|
||||
assert.equal(row.entity, 'auth:' + ownerId);
|
||||
assertRequestInfo(row);
|
||||
assert.equal((await client.call('/api/state')).status, 401, '改密后旧会话仍应失效');
|
||||
|
||||
await client.call('/api/login', { name: '麦麦', password: NEW_PW });
|
||||
const logout = await client.call('/api/logout', {});
|
||||
assert.deepEqual([logout.status, logout.body], [200, { ok: true }]);
|
||||
row = last(ledger, '登出');
|
||||
assert.equal(row.entity, 'auth:' + ownerId);
|
||||
assert.equal(row.actor, '麦麦');
|
||||
assertRequestInfo(row);
|
||||
|
||||
assertNoSecrets(ledger, client);
|
||||
|
||||
// 员工登录与失败尝试不算业务数据,删除资格不变。
|
||||
client.cookie = '';
|
||||
await client.call('/api/login', { name: '助理', password: ASSISTANT_PW });
|
||||
await client.call('/api/inventory/movements/export.xlsx');
|
||||
await client.call('/api/logout', {});
|
||||
await client.call('/api/login', { name: '助理', password: WRONG_PW });
|
||||
const assistant = Employees.list(ledger, {}, { id: ownerId, name: '麦麦', role: 'owner' }).employees.find(
|
||||
e => e.member === 'assistant',
|
||||
);
|
||||
assert.equal(assistant.hasBusinessData, false);
|
||||
assert.equal(assistant.canDelete, true);
|
||||
});
|
||||
|
||||
test('演示登录登记安全审计,无效成员不登记', async t => {
|
||||
const { app, client } = await start(t, { mode: 'demo' });
|
||||
const r = await client.call('/api/demo-login', { member: 'assistant' });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.user.member, 'assistant');
|
||||
const row = last(app.ledger, '演示登录');
|
||||
assert.equal(row.entity, 'auth:' + r.body.user.id);
|
||||
assert.equal(row.actor, r.body.user.name);
|
||||
assertRequestInfo(row);
|
||||
const invalid = await client.call('/api/demo-login', { member: 'nobody' });
|
||||
assert.deepEqual([invalid.status, invalid.body], [400, { error: '演示成员无效' }]);
|
||||
assert.equal(securityRows(app.ledger).filter(row => row.action === '演示登录').length, 1);
|
||||
assertNoSecrets(app.ledger, client);
|
||||
});
|
||||
|
||||
test('审计写入失败不改变登录、登出与改密的响应', async t => {
|
||||
const ledger = new Ledger(':memory:');
|
||||
createUser(ledger, '合成店主', 'owner', OWNER_PW);
|
||||
const { client } = await start(t, { mode: 'trial', ledger });
|
||||
ledger.audit = () => {
|
||||
throw new Error('合成审计故障');
|
||||
};
|
||||
const errors = [];
|
||||
const original = console.error;
|
||||
console.error = message => errors.push(String(message));
|
||||
t.after(() => (console.error = original));
|
||||
const failed = await client.call('/api/login', { name: '不存在', password: WRONG_PW });
|
||||
assert.deepEqual([failed.status, failed.body], [401, { error: '账号或密码不正确' }]);
|
||||
const ok = await client.call('/api/login', { name: '合成店主', password: OWNER_PW });
|
||||
assert.equal(ok.status, 200);
|
||||
assert.equal(ok.body.user.name, '合成店主');
|
||||
const wrong = await client.call('/api/password', { current: WRONG_PW, password: NEW_PW }, { write: true });
|
||||
assert.deepEqual([wrong.status, wrong.body], [400, { error: '原密码不正确' }]);
|
||||
const changed = await client.call('/api/password', { current: OWNER_PW, password: NEW_PW }, { write: true });
|
||||
assert.deepEqual([changed.status, changed.body], [200, { ok: true }]);
|
||||
await client.call('/api/login', { name: '合成店主', password: NEW_PW });
|
||||
const logout = await client.call('/api/logout', {});
|
||||
assert.deepEqual([logout.status, logout.body], [200, { ok: true }]);
|
||||
assert.ok(errors.length >= 5 && errors.every(e => e.includes('安全审计写入失败')));
|
||||
});
|
||||
Reference in new issue
Block a user