mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 10:56:27 +00:00
339 lines
15 KiB
JavaScript
339 lines
15 KiB
JavaScript
const express = require('express');
|
|
const request = require('supertest');
|
|
const responseTime = require('response-time');
|
|
const knex = require('../../infrastructure/database/knex');
|
|
const responseAudit = require('../helpers/response-audit');
|
|
const { correlation, transactionRequest, response: responseTelemetry } = require('../middlewares/response-telemetry.middleware');
|
|
const histograms = Object.values(require('../helpers/prometheusmetrics'));
|
|
const { writeStdoutLine } = require('../helpers/stdout-log');
|
|
|
|
jest.mock('../../infrastructure/database/knex', () => jest.fn());
|
|
jest.mock('../helpers/response-audit', () => ({ record: jest.fn() }));
|
|
jest.mock('../helpers/stdout-log', () => ({
|
|
...jest.requireActual('../helpers/stdout-log'),
|
|
writeStdoutLine: jest.fn(),
|
|
}));
|
|
|
|
const app = express();
|
|
app.use(correlation, responseTelemetry, express.json(), transactionRequest, responseTime());
|
|
const reservationCases = [
|
|
['/api/reservation/validate', { amount: '20000', mid: '*****', card_number: '*****' }],
|
|
['/api/reservation/validate/v2', { amount: '20000', mid: '*****', card_number: '*****' }],
|
|
['/api/reservation', { amount: '20000', mid: '*****', card_number: '*****', customer_name: '*****', phone_number: '*****', ref_no: '*****' }],
|
|
['/api/reservation/v2', { amount: '20000', card_number: '*****', reservation_data: '*****', customer_name: '*****', phone_number: '*****', ref_no: '*****' }],
|
|
['/api/reservation/cancel/validate', { reservation_number: 'RBLTEST01', mid: '*****' }],
|
|
['/api/reservation/cancel/validate/v2', { reservation_number: 'RBLTEST01', mid: '*****', ref_no: '*****' }],
|
|
['/api/reservation/cancel', { reservation_number: 'RBLTEST01', mid: '*****' }],
|
|
['/api/reservation/cancel/v2', { cancel_reservation_data: '*****' }],
|
|
];
|
|
for (const [route] of reservationCases) {
|
|
app.post(route, (req, res) => res.json({ code: '00', data: {} }));
|
|
}
|
|
app.post('/api/topup1', (req, res) => {
|
|
req._startTime = Date.now() - req.body.duration;
|
|
res.locals.hsmUniqueCode = '1234567890121';
|
|
if (req.body.timeout) return res.json({ code: '5001', message: 'Timeout', data: {} });
|
|
res.json({ code: '00', data: { trxID: req.body.trxID } });
|
|
});
|
|
app.post('/api/topup2', (req, res) => {
|
|
req.partner_id_token = 'fixture';
|
|
res.json({ code: '5001', data: {} });
|
|
});
|
|
app.post('/api/topup3', (req, res) => {
|
|
if (!req.body?.unique_code) req.partner_id_token = '9917';
|
|
res.json({ code: '00', data: {} });
|
|
});
|
|
for (const route of ['/api/topup4', '/api/topup5', '/api/topup6', '/api/topup7', '/api/topup8', '/api/loadbalance/request']) {
|
|
app.post(route, (req, res) => res.json({ code: '00', data: {} }));
|
|
}
|
|
app.post('/api/login', (req, res) => {
|
|
res.send({ code: req.body.code, message: req.body.message, data: { access_token: 'fixture-secret' } });
|
|
});
|
|
app.get('/api/getservice', (req, res) => res.json({ code: '00', message: 'Success', data: {} }));
|
|
app.post('/api/payment-recon', (req, res) => res.json({ code: '00', message: 'Success', data: {} }));
|
|
app.post('/api/clear8', (req, res) => res.json({ code: '00', message: 'Success', data: {} }));
|
|
app.post('/api/online/generate-invoice', (req, res) => {
|
|
res.json({
|
|
code: req.body.code,
|
|
message: 'Success',
|
|
data: { invoices: ['fixture-invoice'] },
|
|
});
|
|
});
|
|
app.get('/api/online/cash-in', (req, res) => {
|
|
res.json({ code: '200', message: 'Success', data: { details: ['fixture-cash-in'] } });
|
|
});
|
|
|
|
beforeEach(() => {
|
|
jest.clearAllMocks();
|
|
for (const histogram of histograms) histogram.reset();
|
|
});
|
|
|
|
test('sukses rutin tidak dicatat, tetapi klien tetap menerima request ID', async () => {
|
|
const login = await request(app).post('/api/login')
|
|
.send({ code: '00', message: 'Login Success.' }).expect(200);
|
|
await request(app).get('/api/getservice').expect(200);
|
|
|
|
expect(login.headers['x-request-id']).toBeTruthy();
|
|
expect(writeStdoutLine).not.toHaveBeenCalled();
|
|
expect(responseAudit.record).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test.each(['/api/payment-recon', '/api/clear8'])('hasil sukses transaksi %s masuk stdout', async (route) => {
|
|
const response = await request(app).post(route).expect(200);
|
|
expect(JSON.parse(writeStdoutLine.mock.lastCall[0])).toMatchObject({
|
|
event: 'http_response', route, status_code: '00', request_id: response.headers['x-request-id'],
|
|
});
|
|
expect(responseAudit.record).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test.each([
|
|
['post', '/api/online/generate-invoice', '200', 'success', 'info', { invoices: ['fixture-invoice'] }],
|
|
['post', '/api/online/generate-invoice', '500', 'failed', 'error', { invoices: ['fixture-invoice'] }],
|
|
['get', '/api/online/cash-in', '200', 'success', 'info', { details: ['fixture-cash-in'] }],
|
|
])('keuangan %s %s dengan kode %s hanya mencatat status dan metadata', async (method, route, code, outcome, level, data) => {
|
|
const call = request(app)[method](route);
|
|
if (method === 'post') call.send({ code });
|
|
const response = await call.expect(200);
|
|
expect(response.body).toEqual({ code, message: 'Success', data });
|
|
expect(writeStdoutLine).toHaveBeenCalledTimes(1);
|
|
const [line] = writeStdoutLine.mock.lastCall;
|
|
expect(JSON.parse(line)).toEqual({
|
|
timestamp: expect.any(String), app: 'topuponline', pid: process.pid,
|
|
event: 'http_response', route, method: method.toUpperCase(), request_id: response.headers['x-request-id'],
|
|
http_status: 200, status_code: code, outcome, level, response_time_ms: expect.any(Number),
|
|
});
|
|
expect(responseAudit.record).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('login mencatat satu hasil dengan pesan yang dapat dicari dan ID dari header', async () => {
|
|
const response = await request(app).post('/api/login')
|
|
.send({ code: '403', message: 'Password is wrong.' })
|
|
.expect(200);
|
|
expect(response.body.message).toBe('Password is wrong.');
|
|
expect(writeStdoutLine).toHaveBeenCalledTimes(1);
|
|
const log = JSON.parse(writeStdoutLine.mock.calls[0][0]);
|
|
expect(log).toMatchObject({
|
|
request_id: response.headers['x-request-id'],
|
|
route: '/api/login',
|
|
message: 'Password is wrong.',
|
|
level: 'warn',
|
|
http_status: 200,
|
|
status_code: '403',
|
|
});
|
|
expect(JSON.stringify(log)).not.toContain('fixture-secret');
|
|
expect(responseAudit.record).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('pesan respons dinamis tidak disalin ke stdout', async () => {
|
|
await request(app).post('/api/login')
|
|
.send({ code: '500', message: 'database exception with private input' })
|
|
.expect(200);
|
|
expect(JSON.parse(writeStdoutLine.mock.calls[0][0])).toMatchObject({
|
|
message: 'API request failed',
|
|
level: 'error',
|
|
});
|
|
});
|
|
|
|
test.each(reservationCases)('ringkasan request %s hanya memuat field yang disetujui', async (route, expectedBody) => {
|
|
const response = await request(app).post(route + '?secret=private-query')
|
|
.set('Authorization', 'Bearer private-header')
|
|
.send({
|
|
amount: '20000',
|
|
reservation_number: 'RBLTEST01',
|
|
mid: 'private-mid',
|
|
card_number: 'private-card',
|
|
customer_name: 'private-name',
|
|
phone_number: 'private-phone',
|
|
ref_no: 'private-reference',
|
|
reservation_data: 'private-reservation',
|
|
cancel_reservation_data: 'private-cancellation',
|
|
extra: 'private-extra',
|
|
})
|
|
.expect(200);
|
|
const requestLines = writeStdoutLine.mock.calls.map(([line]) => line)
|
|
.filter(line => JSON.parse(line).event === 'http_request');
|
|
expect(requestLines).toHaveLength(1);
|
|
expect(requestLines[0]).not.toContain('private-');
|
|
expect(JSON.parse(requestLines[0])).toMatchObject({
|
|
route,
|
|
request_id: response.headers['x-request-id'],
|
|
});
|
|
expect(JSON.parse(requestLines[0]).request_body).toEqual(expectedBody);
|
|
});
|
|
|
|
test('nilai yang tidak sesuai format dicatat sebagai tanda bintang dengan nama field asli', async () => {
|
|
await request(app).post('/api/reservation')
|
|
.send({ amount: 'private-value' }).expect(200);
|
|
const entry = JSON.parse(writeStdoutLine.mock.calls[0][0]);
|
|
expect(entry.request_body).toEqual({ amount: '*****' });
|
|
});
|
|
|
|
test('log reservasi mempertahankan nomor kartu, MID, dan TID sambil menyamarkan referensi', async () => {
|
|
const ref_no = 'fixture-private-reference@example.test';
|
|
const card_number = '0000000000001234';
|
|
await request(app).post('/api/reservation')
|
|
.send({ mid: 'A001', tid: 'B002', ref_no, card_number }).expect(200);
|
|
const [line] = writeStdoutLine.mock.lastCall;
|
|
expect(line).not.toContain(ref_no);
|
|
expect(JSON.parse(line).request_body).toEqual({
|
|
mid: 'A001', tid: 'B002', card_number, ref_no: '*****',
|
|
});
|
|
});
|
|
|
|
test('transaksi mencatat awal dan hasil dengan ID yang sama tanpa payload klien', async () => {
|
|
const response = await request(app).post('/api/topup1?debug=fixture-query')
|
|
.set('Authorization', 'Bearer fixture-token')
|
|
.send({ trxID: '0001', duration: 200, card_number: 'fixture-card' })
|
|
.expect(200);
|
|
|
|
expect(writeStdoutLine).toHaveBeenCalledTimes(1);
|
|
const [line] = writeStdoutLine.mock.calls[0];
|
|
const [result] = responseAudit.record.mock.calls[0];
|
|
expect(JSON.parse(line)).toMatchObject({
|
|
event: 'http_request',
|
|
request_id: response.headers['x-request-id'],
|
|
method: 'POST',
|
|
route: '/api/topup1',
|
|
});
|
|
expect(line).not.toMatch(/fixture-query|fixture-token|fixture-card/);
|
|
expect(result).toMatchObject({
|
|
event: 'http_response',
|
|
request_id: response.headers['x-request-id'],
|
|
route: '/api/topup1',
|
|
});
|
|
});
|
|
|
|
test('unique_code menghubungkan seluruh tahap HSM dan load balance tanpa menyamakan ID request', async () => {
|
|
const uniqueCode = '1234567890121';
|
|
const first = await request(app).post('/api/topup1')
|
|
.send({ duration: 100, timeout: true, unique_code: '999' })
|
|
.expect(200);
|
|
expect(first.body.data).toEqual({});
|
|
expect(responseAudit.record.mock.calls[0][0]).toMatchObject({
|
|
unique_code: uniqueCode, status_code: '5001', request_id: first.headers['x-request-id'],
|
|
});
|
|
const requestIds = [first.headers['x-request-id']];
|
|
const routes = Array.from({ length: 7 }, (_, index) => '/api/topup' + (index + 2));
|
|
for (const route of [...routes, '/api/loadbalance/request']) {
|
|
const response = await request(app).post(route).send({ unique_code: uniqueCode }).expect(200);
|
|
expect(JSON.parse(writeStdoutLine.mock.lastCall[0])).toMatchObject({
|
|
event: 'http_request', unique_code: uniqueCode, route, request_id: response.headers['x-request-id'],
|
|
});
|
|
expect(responseAudit.record.mock.lastCall[0]).toMatchObject({
|
|
event: 'http_response', unique_code: uniqueCode, route, request_id: response.headers['x-request-id'],
|
|
});
|
|
requestIds.push(response.headers['x-request-id']);
|
|
}
|
|
expect(new Set(requestIds).size).toBe(9);
|
|
});
|
|
|
|
test('kode sesi yang tidak sesuai format tidak masuk log terstruktur', async () => {
|
|
await request(app).post('/api/topup2').send({ unique_code: 'private-input' }).expect(200);
|
|
expect(JSON.parse(writeStdoutLine.mock.lastCall[0])).not.toHaveProperty('unique_code');
|
|
expect(JSON.stringify(responseAudit.record.mock.lastCall[0])).not.toContain('private-input');
|
|
});
|
|
|
|
test('koneksi yang ditutup sebelum respons selesai mencatat satu event abort', async () => {
|
|
const abortApp = express();
|
|
let closed;
|
|
const responseClosed = new Promise(resolve => { closed = resolve; });
|
|
abortApp.use(correlation);
|
|
abortApp.use('/api', responseTelemetry);
|
|
abortApp.use(express.json(), transactionRequest);
|
|
abortApp.post('/api/topup4', (req, res) => {
|
|
res.once('close', closed);
|
|
res.destroy();
|
|
});
|
|
|
|
await expect(request(abortApp).post('/api/topup4').send({ unique_code: '1234567890121' })).rejects.toThrow();
|
|
await responseClosed;
|
|
|
|
const events = writeStdoutLine.mock.calls.map(([line]) => JSON.parse(line));
|
|
expect(events.map(entry => entry.event)).toEqual(['http_request', 'http_request_aborted']);
|
|
expect(events[1]).toMatchObject({
|
|
request_id: events[0].request_id,
|
|
method: 'POST',
|
|
route: '/api/topup4',
|
|
elapsed_ms: expect.any(Number),
|
|
unique_code: '1234567890121',
|
|
level: 'warn',
|
|
});
|
|
expect(events[1]).not.toHaveProperty('http_status');
|
|
expect(responseAudit.record).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('distinct transaction IDs and latencies share one histogram series per bucket', async () => {
|
|
const transactionIds = ['0001', '0002', '0100', '01a0'];
|
|
const responses = await Promise.all(transactionIds.map((trxID, index) =>
|
|
request(app).post('/api/topup1?fixture=1').send({ trxID, duration: 200 + index * 100 })
|
|
));
|
|
|
|
for (const histogram of histograms) {
|
|
const metric = await histogram.get();
|
|
const counts = metric.values.filter((value) => value.metricName.endsWith('_count'));
|
|
expect(counts).toEqual([{
|
|
metricName: `${metric.name}_count`,
|
|
labels: { route: '/api/topup1', status_code: '00', issuer_name: 'UNDEFINED' },
|
|
value: transactionIds.length,
|
|
}]);
|
|
expect(metric.values.some((entry) => entry.labels.le === 1000)).toBe(true);
|
|
}
|
|
|
|
const logs = responseAudit.record.mock.calls.map(([info]) => info);
|
|
const requestIds = responses.map(({ headers }) => headers['x-request-id']);
|
|
expect(new Set(requestIds).size).toBe(transactionIds.length);
|
|
responses.forEach(({ headers, body }, index) => {
|
|
const record = logs.find((entry) => entry.request_id === headers['x-request-id']);
|
|
expect(headers['x-response-time']).toMatch(/ms$/);
|
|
expect(body.data.trxID).toBe(transactionIds[index]);
|
|
expect(record).toMatchObject({
|
|
event: 'http_response',
|
|
http_status: 200,
|
|
trx_id: transactionIds[index],
|
|
});
|
|
expect(record.response_time_ms).toBeGreaterThanOrEqual(200 + index * 100);
|
|
expect(record).not.toHaveProperty('labels');
|
|
});
|
|
});
|
|
|
|
test('logs the valid request transaction ID on HSM failure even if issuer lookup fails', async () => {
|
|
knex.mockReturnValue({
|
|
where: jest.fn().mockReturnValue({
|
|
first: jest.fn().mockReturnValue({ timeout: jest.fn().mockRejectedValue(new Error('DB unavailable')) }),
|
|
}),
|
|
});
|
|
const response = await request(app).post('/api/topup2').send({ trxID: 'ABCD', card_number: 'fixture-card' });
|
|
|
|
expect(response.status).toBe(200);
|
|
const [info] = responseAudit.record.mock.calls[0];
|
|
expect(info).toMatchObject({
|
|
level: 'error',
|
|
status_code: '5001',
|
|
request_id: response.headers['x-request-id'],
|
|
trx_id: 'abcd',
|
|
issuer_name: 'UNDEFINED',
|
|
});
|
|
expect(info).not.toHaveProperty('card_number');
|
|
});
|
|
|
|
test('a slow issuer lookup is shared and audit records are emitted while it is pending', async () => {
|
|
let finishLookup;
|
|
const pending = new Promise((resolve) => { finishLookup = resolve; });
|
|
const timeout = jest.fn().mockReturnValue(pending);
|
|
knex.mockReturnValue({
|
|
where: jest.fn().mockReturnValue({ first: jest.fn().mockReturnValue({ timeout }) }),
|
|
});
|
|
|
|
try {
|
|
await Promise.all(Array.from({ length: 12 }, () => request(app).post('/api/topup3')));
|
|
expect(timeout).toHaveBeenCalledTimes(1);
|
|
expect(responseAudit.record).toHaveBeenCalledTimes(12);
|
|
expect(responseAudit.record).toHaveBeenCalledWith(expect.objectContaining({
|
|
issuer_name: 'UNDEFINED',
|
|
partner_id: '9917',
|
|
}));
|
|
} finally {
|
|
finishLookup({ c_name: 'Fixture' });
|
|
}
|
|
});
|