85 lines
2.6 KiB
JavaScript
85 lines
2.6 KiB
JavaScript
'use strict';
|
|
|
|
const { app, assert } = require('egg-mock/bootstrap');
|
|
|
|
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
|
|
describe('test/app/request_log.test.js', () => {
|
|
it('should write request log after request', async () => {
|
|
await app.httpRequest()
|
|
.get('/')
|
|
.expect(200);
|
|
|
|
// 等待后台异步写入
|
|
await wait(600);
|
|
|
|
const log = await app.model.RequestLog.findOne({
|
|
where: { url: '/' },
|
|
order: [[ 'id', 'DESC' ]],
|
|
});
|
|
|
|
assert(log);
|
|
assert(log.method === 'GET');
|
|
assert(log.status === 200);
|
|
assert(typeof log.duration === 'number');
|
|
});
|
|
|
|
it('should mask sensitive headers and body', async () => {
|
|
await app.httpRequest()
|
|
.post('/api/auth/login')
|
|
.set('Authorization', 'Bearer some-token-value')
|
|
.send({ account: 'mask_test_user', password: 'secret-password' });
|
|
|
|
await wait(600);
|
|
|
|
const log = await app.model.RequestLog.findOne({
|
|
where: { url: '/api/auth/login', method: 'POST' },
|
|
order: [[ 'id', 'DESC' ]],
|
|
});
|
|
|
|
assert(log);
|
|
// 请求头中的 token 已脱敏
|
|
assert(log.headers.includes('***'));
|
|
assert(!log.headers.includes('some-token-value'));
|
|
// 请求报文中的密码已脱敏
|
|
assert(log.request_body.includes('***'));
|
|
assert(!log.request_body.includes('secret-password'));
|
|
});
|
|
|
|
it('should mask token in response but keep business code', async () => {
|
|
const res = await app.httpRequest()
|
|
.post('/api/auth/login')
|
|
.send({ account: 'liufumingren', password: 'mingming1234' });
|
|
|
|
await wait(600);
|
|
|
|
const log = await app.model.RequestLog.findOne({
|
|
where: { url: '/api/auth/login', method: 'POST' },
|
|
order: [[ 'id', 'DESC' ]],
|
|
});
|
|
|
|
assert(log);
|
|
// 登录响应中的 token 必须脱敏
|
|
assert(log.response_body.includes('***'));
|
|
if (res.body.data && res.body.data.token) {
|
|
assert(!log.response_body.includes(res.body.data.token));
|
|
}
|
|
// 业务状态码 code 需保留,不被脱敏
|
|
assert(log.response_body.includes('"code":0'));
|
|
});
|
|
|
|
it('should delete logs older than keepDays', async () => {
|
|
const { keepDays } = app.config.requestLog;
|
|
const old = new Date(Date.now() - (keepDays + 1) * 24 * 60 * 60 * 1000);
|
|
|
|
const row = await app.model.RequestLog.create({ method: 'GET', url: '/expired-log' });
|
|
await row.update({ created_at: old });
|
|
|
|
const deleted = await app.runSchedule('clear_request_logs');
|
|
assert(deleted >= 1);
|
|
|
|
const exists = await app.model.RequestLog.findOne({ where: { url: '/expired-log' } });
|
|
assert(!exists);
|
|
});
|
|
});
|