plugin-elastic-report 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client-v2.d.ts +2 -2
- package/client-v2.js +1 -1
- package/client.d.ts +2 -2
- package/client.js +1 -1
- package/{ai → dist/ai}/skills/elastic-report/SKILLS.md +52 -34
- package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
- package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +2 -1
- package/dist/locale/en-US.json +213 -198
- package/dist/locale/vi-VN.json +213 -198
- package/dist/locale/zh-CN.json +213 -198
- package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
- package/dist/server/mcp/ElasticReportToolCatalog.js +6 -4
- package/dist/server/plugin.js +4 -4
- package/dist/server/report-block-tools.js +340 -0
- package/dist/server/services/ElasticReportService.js +12 -6
- package/dist/shared/constants.js +9 -0
- package/package.json +2 -3
- package/server.d.ts +2 -2
- package/server.js +1 -1
- package/src/ai/skills/elastic-report/SKILLS.md +52 -0
- package/src/client/index.tsx +34 -34
- package/src/client/workflow-instructions.tsx +44 -44
- package/src/client-v2/__tests__/elastic-report.test.tsx +879 -791
- package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -178
- package/src/client-v2/api.ts +320 -320
- package/src/client-v2/bus/DashboardFilterBus.ts +212 -212
- package/src/client-v2/components/ElasticBasicCharts.tsx +652 -652
- package/src/client-v2/components/ElasticFilterBar.tsx +372 -372
- package/src/client-v2/components/ElasticKqlInput.tsx +421 -421
- package/src/client-v2/components/ElasticReportBlock.tsx +306 -306
- package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -1257
- package/src/client-v2/components/HighlightText.tsx +50 -50
- package/src/client-v2/components/ReportSelect.tsx +85 -85
- package/src/client-v2/index.tsx +14 -14
- package/src/client-v2/locale.ts +23 -23
- package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -115
- package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -118
- package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1453
- package/src/client-v2/plugin.tsx +107 -72
- package/src/client-v2/report-destination.tsx +126 -0
- package/src/client-v2/utils/kqlAutocomplete.ts +861 -861
- package/src/client-v2/workflow/instructions.tsx +149 -149
- package/src/index.ts +11 -11
- package/src/locale/en-US.json +213 -198
- package/src/locale/vi-VN.json +213 -198
- package/src/locale/zh-CN.json +213 -198
- package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
- package/src/server/__tests__/query-compiler.test.ts +620 -620
- package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -645
- package/src/server/acl-guard.ts +194 -194
- package/src/server/collections/es-report-data-views.ts +64 -64
- package/src/server/collections/es-reports.ts +80 -80
- package/src/server/index.ts +15 -15
- package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
- package/src/server/mcp/ElasticReportToolCatalog.ts +667 -663
- package/src/server/plugin.ts +599 -599
- package/src/server/report-block-tools.ts +400 -0
- package/src/server/services/ElasticReportService.ts +494 -486
- package/src/server/services/ElasticsearchConnectionService.ts +728 -728
- package/src/server/services/ReportExportService.ts +282 -282
- package/src/server/services/ReportQueryCompiler.ts +1552 -1552
- package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -124
- package/src/shared/constants.ts +39 -36
- package/src/shared/types.ts +272 -272
- package/dist/client-v2/851.142c93fc6d666b28.js +0 -10
- package/dist/client-v2/877.f4095a3dbcadf98f.js +0 -10
- package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
- package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
|
@@ -1,645 +1,645 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* This file is part of the NocoBase (R) project.
|
|
3
|
-
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
-
* Authors: NocoBase Team.
|
|
5
|
-
*
|
|
6
|
-
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
-
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import { createServer, type IncomingMessage, type Server } from 'http';
|
|
11
|
-
import type { AddressInfo } from 'net';
|
|
12
|
-
import { JOB_STATUS } from '@nocobase/plugin-workflow';
|
|
13
|
-
import { createMockServer, type MockServer } from '@nocobase/test';
|
|
14
|
-
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
15
|
-
import PluginDataSourceElasticsearch from '../../../../plugin-data-source-elasticsearch/src/server/plugin';
|
|
16
|
-
import PluginElasticReportServer from '../plugin';
|
|
17
|
-
import { ElasticReportQueryInstruction } from '../workflow/ElasticReportQueryInstruction';
|
|
18
|
-
|
|
19
|
-
function readBody(req: IncomingMessage): Promise<string> {
|
|
20
|
-
return new Promise((resolve) => {
|
|
21
|
-
const chunks: Buffer[] = [];
|
|
22
|
-
req.on('data', (chunk: Buffer) => chunks.push(chunk));
|
|
23
|
-
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
describe('plugin-elastic-report REST, DataSource reuse, ACL, and MCP integration', () => {
|
|
28
|
-
let app: MockServer;
|
|
29
|
-
let upstream: Server;
|
|
30
|
-
let esUrl = '';
|
|
31
|
-
let viewerAgent: ReturnType<MockServer['agent']>;
|
|
32
|
-
let financeViewerAgent: ReturnType<MockServer['agent']>;
|
|
33
|
-
let dualRoleViewerAgent: ReturnType<MockServer['agent']>;
|
|
34
|
-
let builderAgent: ReturnType<MockServer['agent']>;
|
|
35
|
-
const capturedSearchBodies: Array<Record<string, unknown>> = [];
|
|
36
|
-
|
|
37
|
-
beforeAll(async () => {
|
|
38
|
-
upstream = createServer(async (req, res) => {
|
|
39
|
-
const url = req.url || '/';
|
|
40
|
-
const rawBody = await readBody(req);
|
|
41
|
-
res.setHeader('x-elastic-product', 'Elasticsearch');
|
|
42
|
-
res.setHeader('content-type', 'application/json');
|
|
43
|
-
|
|
44
|
-
if (req.method === 'HEAD' || url === '/') {
|
|
45
|
-
res.statusCode = 200;
|
|
46
|
-
res.end(JSON.stringify({ name: 'mock-es', version: { number: '8.17.0' } }));
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
if (url.includes('_cluster/health')) {
|
|
51
|
-
res.end(JSON.stringify({ cluster_name: 'test-es', status: 'green' }));
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
if (url.includes('_cat/indices')) {
|
|
56
|
-
res.end(JSON.stringify([{ index: 'logs-2026.11.29' }, { index: 'logs-2026.11.30' }]));
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
if (url.includes('_field_caps')) {
|
|
61
|
-
res.end(
|
|
62
|
-
JSON.stringify({
|
|
63
|
-
indices: ['logs-2026.11.29', 'logs-2026.11.30'],
|
|
64
|
-
fields: {
|
|
65
|
-
'@timestamp': {
|
|
66
|
-
date: { type: 'date', searchable: true, aggregatable: true },
|
|
67
|
-
},
|
|
68
|
-
service: {
|
|
69
|
-
text: { type: 'text', searchable: true, aggregatable: false },
|
|
70
|
-
},
|
|
71
|
-
'service.keyword': {
|
|
72
|
-
keyword: { type: 'keyword', searchable: true, aggregatable: true },
|
|
73
|
-
},
|
|
74
|
-
status: {
|
|
75
|
-
integer: { type: 'integer', searchable: true, aggregatable: true },
|
|
76
|
-
},
|
|
77
|
-
latency_ms: {
|
|
78
|
-
double: { type: 'double', searchable: true, aggregatable: true },
|
|
79
|
-
},
|
|
80
|
-
},
|
|
81
|
-
}),
|
|
82
|
-
);
|
|
83
|
-
return;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
if (url.includes('_mapping')) {
|
|
87
|
-
res.end(
|
|
88
|
-
JSON.stringify({
|
|
89
|
-
'logs-2026.11.30': {
|
|
90
|
-
mappings: {
|
|
91
|
-
properties: {
|
|
92
|
-
'@timestamp': { type: 'date' },
|
|
93
|
-
service: { type: 'text', fields: { keyword: { type: 'keyword' } } },
|
|
94
|
-
status: { type: 'integer' },
|
|
95
|
-
},
|
|
96
|
-
},
|
|
97
|
-
},
|
|
98
|
-
}),
|
|
99
|
-
);
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
if (url.includes('_pit')) {
|
|
104
|
-
if (req.method === 'DELETE') {
|
|
105
|
-
res.end(JSON.stringify({ succeeded: true, num_freed: 1 }));
|
|
106
|
-
} else {
|
|
107
|
-
res.end(JSON.stringify({ id: 'pit-token-1' }));
|
|
108
|
-
}
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
if (url.includes('_search')) {
|
|
113
|
-
const parsedBody = rawBody ? (JSON.parse(rawBody) as Record<string, unknown>) : {};
|
|
114
|
-
capturedSearchBodies.push(parsedBody);
|
|
115
|
-
res.end(
|
|
116
|
-
JSON.stringify({
|
|
117
|
-
took: 5,
|
|
118
|
-
...(parsedBody.pit ? { pit_id: 'pit-token-1' } : {}),
|
|
119
|
-
hits: {
|
|
120
|
-
total: { value: 2, relation: 'eq' },
|
|
121
|
-
hits: [
|
|
122
|
-
{
|
|
123
|
-
_index: 'logs-2026.11.30',
|
|
124
|
-
_id: 'hit-1',
|
|
125
|
-
sort: [1732920000000, 1],
|
|
126
|
-
_source: {
|
|
127
|
-
'@timestamp': '2026-11-30T01:00:00Z',
|
|
128
|
-
service: 'checkout',
|
|
129
|
-
status: 502,
|
|
130
|
-
latency_ms: 340,
|
|
131
|
-
message: '=2+5',
|
|
132
|
-
},
|
|
133
|
-
},
|
|
134
|
-
{
|
|
135
|
-
_index: 'logs-2026.11.30',
|
|
136
|
-
_id: 'hit-2',
|
|
137
|
-
sort: [1732910000000, 2],
|
|
138
|
-
_source: {
|
|
139
|
-
'@timestamp': '2026-11-30T00:50:00Z',
|
|
140
|
-
service: 'checkout',
|
|
141
|
-
status: 500,
|
|
142
|
-
latency_ms: 210,
|
|
143
|
-
message: 'Upstream gateway timeout',
|
|
144
|
-
},
|
|
145
|
-
},
|
|
146
|
-
],
|
|
147
|
-
},
|
|
148
|
-
aggregations: {
|
|
149
|
-
es_time_histogram: {
|
|
150
|
-
buckets: [{ key_as_string: '2026-11-30T00:00:00Z', key: 1732910000000, doc_count: 2 }],
|
|
151
|
-
},
|
|
152
|
-
es_buckets: {
|
|
153
|
-
buckets: [{ key: 'checkout', doc_count: 2, es_metric: { value: 275 } }],
|
|
154
|
-
},
|
|
155
|
-
},
|
|
156
|
-
}),
|
|
157
|
-
);
|
|
158
|
-
return;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
res.end(JSON.stringify({}));
|
|
162
|
-
});
|
|
163
|
-
|
|
164
|
-
await new Promise<void>((resolve) => upstream.listen(0, '127.0.0.1', resolve));
|
|
165
|
-
esUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`;
|
|
166
|
-
|
|
167
|
-
app = await createMockServer({
|
|
168
|
-
acl: true,
|
|
169
|
-
resourcer: {
|
|
170
|
-
prefix: '/api',
|
|
171
|
-
},
|
|
172
|
-
plugins: [
|
|
173
|
-
'field-sort',
|
|
174
|
-
'system-settings',
|
|
175
|
-
'users',
|
|
176
|
-
'auth',
|
|
177
|
-
'acl',
|
|
178
|
-
'data-source-manager',
|
|
179
|
-
'data-source-main',
|
|
180
|
-
'error-handler',
|
|
181
|
-
[PluginDataSourceElasticsearch, { name: 'plugin-data-source-elasticsearch' }],
|
|
182
|
-
[PluginElasticReportServer, { name: 'plugin-elastic-report' }],
|
|
183
|
-
],
|
|
184
|
-
});
|
|
185
|
-
|
|
186
|
-
// Register an Elasticsearch data source record as plugin-data-source-elasticsearch does
|
|
187
|
-
await app.db.getRepository('dataSources').create({
|
|
188
|
-
values: {
|
|
189
|
-
key: 'es_logs_cluster',
|
|
190
|
-
displayName: 'ES Logs Cluster',
|
|
191
|
-
type: 'elasticsearch',
|
|
192
|
-
enabled: true,
|
|
193
|
-
options: {
|
|
194
|
-
nodes: esUrl,
|
|
195
|
-
indexPattern: 'logs-*',
|
|
196
|
-
addAllCollections: false,
|
|
197
|
-
selectedCollections: [],
|
|
198
|
-
password: 'super-secret-password',
|
|
199
|
-
},
|
|
200
|
-
},
|
|
201
|
-
});
|
|
202
|
-
|
|
203
|
-
for (const roleName of ['report-viewer', 'finance-viewer', 'report-builder']) {
|
|
204
|
-
await app.db.getRepository('roles').create({
|
|
205
|
-
values: {
|
|
206
|
-
name: roleName,
|
|
207
|
-
title: roleName,
|
|
208
|
-
snippets: roleName === 'report-builder' ? ['pm.elastic-report'] : [],
|
|
209
|
-
},
|
|
210
|
-
});
|
|
211
|
-
const user = await app.db.getRepository('users').create({
|
|
212
|
-
values: { username: roleName, roles: [roleName] },
|
|
213
|
-
});
|
|
214
|
-
const agent = await app.agent().login(user, roleName);
|
|
215
|
-
if (roleName === 'report-viewer') viewerAgent = agent;
|
|
216
|
-
else if (roleName === 'finance-viewer') financeViewerAgent = agent;
|
|
217
|
-
else builderAgent = agent;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// Create a user whose account possesses 'admin' + 'report-viewer', but whose active request role is narrowed to 'report-viewer'
|
|
221
|
-
const dualUser = await app.db.getRepository('users').create({
|
|
222
|
-
values: { username: 'dual-admin-viewer', roles: ['admin', 'report-viewer'] },
|
|
223
|
-
});
|
|
224
|
-
dualRoleViewerAgent = await app.agent().login(dualUser, 'report-viewer');
|
|
225
|
-
|
|
226
|
-
app.acl.getRole('report-builder').snippets.add('pm.elastic-report');
|
|
227
|
-
}, 120000);
|
|
228
|
-
|
|
229
|
-
afterAll(async () => {
|
|
230
|
-
await app?.destroy();
|
|
231
|
-
if (upstream) {
|
|
232
|
-
await new Promise<void>((resolve) => upstream.close(() => resolve()));
|
|
233
|
-
}
|
|
234
|
-
});
|
|
235
|
-
|
|
236
|
-
it('blocks unprivileged viewers from managing connections or saving reports while never leaking ES secrets', async () => {
|
|
237
|
-
const deniedConn = await viewerAgent.resource('esReportService').listConnections();
|
|
238
|
-
expect(deniedConn.status).toBe(403);
|
|
239
|
-
|
|
240
|
-
const allowedConn = await builderAgent.resource('esReportService').listConnections();
|
|
241
|
-
expect(allowedConn.status).toBe(200);
|
|
242
|
-
expect(allowedConn.body.data).toEqual([
|
|
243
|
-
expect.objectContaining({
|
|
244
|
-
key: 'es_logs_cluster',
|
|
245
|
-
displayName: 'ES Logs Cluster',
|
|
246
|
-
}),
|
|
247
|
-
]);
|
|
248
|
-
expect(JSON.stringify(allowedConn.body)).not.toContain('super-secret-password');
|
|
249
|
-
});
|
|
250
|
-
|
|
251
|
-
it('supports full AI Employee MCP workflow over /api/elastic-report-mcp and enforces viewer/builder ACL', async () => {
|
|
252
|
-
// 1. Unauthenticated request to MCP endpoint is rejected
|
|
253
|
-
const anonRes = await app
|
|
254
|
-
.agent()
|
|
255
|
-
.post('/api/elastic-report-mcp')
|
|
256
|
-
.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} });
|
|
257
|
-
expect([401, 403]).toContain(anonRes.status);
|
|
258
|
-
|
|
259
|
-
// 2. Initialize & list tools as report-builder
|
|
260
|
-
const initRes = await builderAgent
|
|
261
|
-
.post('/api/elastic-report-mcp')
|
|
262
|
-
.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26' } });
|
|
263
|
-
expect(initRes.status).toBe(200);
|
|
264
|
-
expect(initRes.body.result.serverInfo.name).toBe('elastic-report');
|
|
265
|
-
|
|
266
|
-
const listToolsRes = await builderAgent
|
|
267
|
-
.post('/api/elastic-report-mcp')
|
|
268
|
-
.send({ jsonrpc: '2.0', id: 2, method: 'tools/list' });
|
|
269
|
-
expect(listToolsRes.status).toBe(200);
|
|
270
|
-
const toolNames = (listToolsRes.body.result.tools as Array<{ name: string }>).map((t) => t.name);
|
|
271
|
-
expect(toolNames).toEqual(
|
|
272
|
-
expect.arrayContaining([
|
|
273
|
-
'es_list_connections',
|
|
274
|
-
'es_upsert_data_view',
|
|
275
|
-
'es_inspect_fields',
|
|
276
|
-
'es_preview_report',
|
|
277
|
-
'es_save_report',
|
|
278
|
-
'es_list_reports',
|
|
279
|
-
]),
|
|
280
|
-
);
|
|
281
|
-
|
|
282
|
-
// 3. Viewer cannot invoke write MCP tool `es_upsert_data_view`
|
|
283
|
-
const viewerWriteMcp = await viewerAgent.post('/api/elastic-report-mcp').send({
|
|
284
|
-
jsonrpc: '2.0',
|
|
285
|
-
id: 3,
|
|
286
|
-
method: 'tools/call',
|
|
287
|
-
params: {
|
|
288
|
-
name: 'es_upsert_data_view',
|
|
289
|
-
arguments: {
|
|
290
|
-
title: 'Unauthorized DV',
|
|
291
|
-
dataSourceKey: 'es_logs_cluster',
|
|
292
|
-
indexPattern: 'logs-*',
|
|
293
|
-
},
|
|
294
|
-
},
|
|
295
|
-
});
|
|
296
|
-
expect(viewerWriteMcp.status).toBe(200);
|
|
297
|
-
expect(viewerWriteMcp.body.result.isError).toBe(true);
|
|
298
|
-
expect(viewerWriteMcp.body.result.content[0].text).toContain('403');
|
|
299
|
-
|
|
300
|
-
// 4. Builder creates Data View via MCP -> auto-detects @timestamp via _field_caps
|
|
301
|
-
const createDvMcp = await builderAgent.post('/api/elastic-report-mcp').send({
|
|
302
|
-
jsonrpc: '2.0',
|
|
303
|
-
id: 4,
|
|
304
|
-
method: 'tools/call',
|
|
305
|
-
params: {
|
|
306
|
-
name: 'es_upsert_data_view',
|
|
307
|
-
arguments: {
|
|
308
|
-
title: 'Production Logs',
|
|
309
|
-
dataSourceKey: 'es_logs_cluster',
|
|
310
|
-
indexPattern: 'logs-*',
|
|
311
|
-
},
|
|
312
|
-
},
|
|
313
|
-
});
|
|
314
|
-
expect(createDvMcp.body.result.isError).toBe(false);
|
|
315
|
-
const dvPayload = JSON.parse(createDvMcp.body.result.content[0].text) as {
|
|
316
|
-
dataView: { id: number; timeField: string };
|
|
317
|
-
fieldCount: number;
|
|
318
|
-
};
|
|
319
|
-
expect(dvPayload.dataView.timeField).toBe('@timestamp');
|
|
320
|
-
expect(dvPayload.fieldCount).toBe(5);
|
|
321
|
-
|
|
322
|
-
// 5. Builder previews and saves a Kibana Table Report via MCP
|
|
323
|
-
const previewMcp = await builderAgent.post('/api/elastic-report-mcp').send({
|
|
324
|
-
jsonrpc: '2.0',
|
|
325
|
-
id: 5,
|
|
326
|
-
method: 'tools/call',
|
|
327
|
-
params: {
|
|
328
|
-
name: 'es_preview_report',
|
|
329
|
-
arguments: {
|
|
330
|
-
dataViewId: dvPayload.dataView.id,
|
|
331
|
-
spec: {
|
|
332
|
-
visualization: 'table',
|
|
333
|
-
query: 'status >= 500 AND service: "checkout"',
|
|
334
|
-
sort: [{ field: 'service', order: 'asc' }],
|
|
335
|
-
timeRange: { preset: 'last_24h' },
|
|
336
|
-
},
|
|
337
|
-
},
|
|
338
|
-
},
|
|
339
|
-
});
|
|
340
|
-
expect(previewMcp.body.result.isError).toBe(false);
|
|
341
|
-
const previewData = JSON.parse(previewMcp.body.result.content[0].text) as { total: number };
|
|
342
|
-
expect(previewData.total).toBe(2);
|
|
343
|
-
|
|
344
|
-
const saveMcp = await builderAgent.post('/api/elastic-report-mcp').send({
|
|
345
|
-
jsonrpc: '2.0',
|
|
346
|
-
id: 6,
|
|
347
|
-
method: 'tools/call',
|
|
348
|
-
params: {
|
|
349
|
-
name: 'es_save_report',
|
|
350
|
-
arguments: {
|
|
351
|
-
title: 'Checkout 5xx Errors',
|
|
352
|
-
dataViewId: dvPayload.dataView.id,
|
|
353
|
-
published: true,
|
|
354
|
-
spec: {
|
|
355
|
-
visualization: 'table',
|
|
356
|
-
query: 'status >= 500',
|
|
357
|
-
filters: [{ field: 'service', operator: 'eq', value: 'checkout' }],
|
|
358
|
-
sort: [{ field: '@timestamp', order: 'desc' }],
|
|
359
|
-
timeRange: { preset: 'last_24h' },
|
|
360
|
-
columns: ['@timestamp', 'service', 'status', 'latency_ms'],
|
|
361
|
-
},
|
|
362
|
-
},
|
|
363
|
-
},
|
|
364
|
-
});
|
|
365
|
-
expect(saveMcp.body.result.isError).toBe(false);
|
|
366
|
-
const savedReportPayload = JSON.parse(saveMcp.body.result.content[0].text) as {
|
|
367
|
-
report: { id: number; title: string };
|
|
368
|
-
};
|
|
369
|
-
|
|
370
|
-
// 6. Regular page viewer can list published reports (for ReportSelect), fetch GET getReportMeta?reportId=..., and execute the saved report with interactive overrides!
|
|
371
|
-
const publishedList = await viewerAgent.get('/api/esReportService:listPublishedReports?search=Checkout');
|
|
372
|
-
expect(publishedList.status).toBe(200);
|
|
373
|
-
expect(publishedList.body.data).toEqual([
|
|
374
|
-
expect.objectContaining({
|
|
375
|
-
id: savedReportPayload.report.id,
|
|
376
|
-
title: 'Checkout 5xx Errors',
|
|
377
|
-
}),
|
|
378
|
-
]);
|
|
379
|
-
|
|
380
|
-
const metaRes = await viewerAgent.get(
|
|
381
|
-
`/api/esReportService:getReportMeta?reportId=${savedReportPayload.report.id}`,
|
|
382
|
-
);
|
|
383
|
-
expect(metaRes.status).toBe(200);
|
|
384
|
-
expect(metaRes.body.data.report.title).toBe('Checkout 5xx Errors');
|
|
385
|
-
expect(metaRes.body.data.fields.length).toBeGreaterThan(0);
|
|
386
|
-
|
|
387
|
-
const runRes = await viewerAgent.resource('esReportService').runReport({
|
|
388
|
-
values: {
|
|
389
|
-
reportId: savedReportPayload.report.id,
|
|
390
|
-
overrides: {
|
|
391
|
-
query: 'status >= 502',
|
|
392
|
-
page: 1,
|
|
393
|
-
},
|
|
394
|
-
},
|
|
395
|
-
});
|
|
396
|
-
expect(runRes.status).toBe(200);
|
|
397
|
-
expect(runRes.body.data.result.total).toBe(2);
|
|
398
|
-
expect(runRes.body.data.result.rows[0].source.service).toBe('checkout');
|
|
399
|
-
expect(capturedSearchBodies.length).toBeGreaterThanOrEqual(2);
|
|
400
|
-
});
|
|
401
|
-
|
|
402
|
-
it('prevents dormant admin role escalation and enforces per-report allowedRoles + server lockedFilters', async () => {
|
|
403
|
-
// 1. Account with ['admin', 'report-viewer'] logged in under effective role 'report-viewer' MUST NOT escalate to manager
|
|
404
|
-
const dualSaveMcp = await dualRoleViewerAgent.post('/api/elastic-report-mcp').send({
|
|
405
|
-
jsonrpc: '2.0',
|
|
406
|
-
id: 10,
|
|
407
|
-
method: 'tools/call',
|
|
408
|
-
params: {
|
|
409
|
-
name: 'es_save_report',
|
|
410
|
-
arguments: {
|
|
411
|
-
title: 'Escalation Attempt',
|
|
412
|
-
dataViewId: 1,
|
|
413
|
-
spec: { visualization: 'table' },
|
|
414
|
-
},
|
|
415
|
-
},
|
|
416
|
-
});
|
|
417
|
-
expect(dualSaveMcp.status).toBe(200);
|
|
418
|
-
expect(dualSaveMcp.body.result.isError).toBe(true);
|
|
419
|
-
expect(dualSaveMcp.body.result.content[0].text).toContain('Permission denied');
|
|
420
|
-
|
|
421
|
-
// 2. Invalid KQL syntax is rejected with HTTP 400 on saveReport
|
|
422
|
-
const badKqlRes = await builderAgent.resource('esReportService').saveReport({
|
|
423
|
-
values: {
|
|
424
|
-
title: 'Broken KQL',
|
|
425
|
-
dataViewId: 1,
|
|
426
|
-
spec: {
|
|
427
|
-
visualization: 'table',
|
|
428
|
-
query: 'status: (400 OR',
|
|
429
|
-
},
|
|
430
|
-
},
|
|
431
|
-
});
|
|
432
|
-
expect(badKqlRes.status).toBe(400);
|
|
433
|
-
|
|
434
|
-
// 3. Builder creates a role-restricted report with mandatory lockedFilters
|
|
435
|
-
const restrictedSave = await builderAgent.resource('esReportService').saveReport({
|
|
436
|
-
values: {
|
|
437
|
-
title: 'Finance Billing Audit',
|
|
438
|
-
dataViewId: 1,
|
|
439
|
-
published: true,
|
|
440
|
-
allowedRoles: ['finance-viewer'],
|
|
441
|
-
spec: {
|
|
442
|
-
visualization: 'table',
|
|
443
|
-
query: 'status: (500 OR 502)',
|
|
444
|
-
lockedFilters: [{ field: 'service', operator: 'eq', value: 'billing' }],
|
|
445
|
-
filters: [{ field: 'status', operator: 'gte', value: 400 }],
|
|
446
|
-
allowInteractiveControls: true,
|
|
447
|
-
},
|
|
448
|
-
},
|
|
449
|
-
});
|
|
450
|
-
expect(restrictedSave.status).toBe(200);
|
|
451
|
-
const restrictedReportId = restrictedSave.body.data.id as number;
|
|
452
|
-
|
|
453
|
-
// 4. 'report-viewer' (and dual-role user acting as 'report-viewer') cannot list, inspect, or run 'Finance Billing Audit'
|
|
454
|
-
const viewerPublished = await viewerAgent.get('/api/esReportService:listPublishedReports?search=Finance');
|
|
455
|
-
expect(viewerPublished.status).toBe(200);
|
|
456
|
-
expect(viewerPublished.body.data).toEqual([]);
|
|
457
|
-
|
|
458
|
-
const viewerMetaDenied = await viewerAgent.get(`/api/esReportService:getReportMeta?reportId=${restrictedReportId}`);
|
|
459
|
-
expect(viewerMetaDenied.status).toBe(403);
|
|
460
|
-
|
|
461
|
-
const dualRunDenied = await dualRoleViewerAgent.resource('esReportService').runReport({
|
|
462
|
-
values: { reportId: restrictedReportId },
|
|
463
|
-
});
|
|
464
|
-
expect(dualRunDenied.status).toBe(403);
|
|
465
|
-
|
|
466
|
-
// 5. 'finance-viewer' CAN run the report, and attempting to clear filters via runtime overrides STILL preserves lockedFilters!
|
|
467
|
-
const beforeCount = capturedSearchBodies.length;
|
|
468
|
-
const financeRun = await financeViewerAgent.resource('esReportService').runReport({
|
|
469
|
-
values: {
|
|
470
|
-
reportId: restrictedReportId,
|
|
471
|
-
overrides: {
|
|
472
|
-
query: '',
|
|
473
|
-
filters: [],
|
|
474
|
-
},
|
|
475
|
-
},
|
|
476
|
-
});
|
|
477
|
-
expect(financeRun.status).toBe(200);
|
|
478
|
-
expect(capturedSearchBodies.length).toBe(beforeCount + 1);
|
|
479
|
-
const executedEsBody = capturedSearchBodies[capturedSearchBodies.length - 1];
|
|
480
|
-
expect(JSON.stringify(executedEsBody)).toContain('"service.keyword":"billing"');
|
|
481
|
-
});
|
|
482
|
-
|
|
483
|
-
it('supports top-values inspection, streaming CSV/NDJSON export with {{$role}} lockedFilters, workflow instruction, and AI Analyst MCP tools', async () => {
|
|
484
|
-
// 1. MCP tools/list exposes all 9 tools including es_analyze_report & es_create_dashboard_bundle
|
|
485
|
-
const listToolsRes = await builderAgent
|
|
486
|
-
.post('/api/elastic-report-mcp')
|
|
487
|
-
.send({ jsonrpc: '2.0', id: 20, method: 'tools/list' });
|
|
488
|
-
const toolNames = (listToolsRes.body.result.tools as Array<{ name: string }>).map((t) => t.name);
|
|
489
|
-
expect(toolNames).toHaveLength(9);
|
|
490
|
-
expect(toolNames).toEqual(expect.arrayContaining(['es_analyze_report', 'es_create_dashboard_bundle']));
|
|
491
|
-
|
|
492
|
-
// 2. Builder creates a coordinated multi-panel dashboard bundle via MCP with dynamic {{$role}} lockedFilters
|
|
493
|
-
const bundleRes = await builderAgent.post('/api/elastic-report-mcp').send({
|
|
494
|
-
jsonrpc: '2.0',
|
|
495
|
-
id: 21,
|
|
496
|
-
method: 'tools/call',
|
|
497
|
-
params: {
|
|
498
|
-
name: 'es_create_dashboard_bundle',
|
|
499
|
-
arguments: {
|
|
500
|
-
dataViewId: 1,
|
|
501
|
-
allowedRoles: ['finance-viewer'],
|
|
502
|
-
lockedFilters: [{ field: 'service', operator: 'eq', value: '{{$role}}' }],
|
|
503
|
-
panels: [
|
|
504
|
-
{
|
|
505
|
-
title: 'Role Scoped KPI',
|
|
506
|
-
spec: {
|
|
507
|
-
visualization: 'metric',
|
|
508
|
-
timeRange: { preset: 'last_24h' },
|
|
509
|
-
chart: { metricType: 'count', comparePreviousPeriod: true },
|
|
510
|
-
},
|
|
511
|
-
},
|
|
512
|
-
{
|
|
513
|
-
title: 'Role Scoped Export Table',
|
|
514
|
-
spec: {
|
|
515
|
-
visualization: 'table',
|
|
516
|
-
columns: ['@timestamp', 'service', 'status', 'message'],
|
|
517
|
-
allowExport: true,
|
|
518
|
-
},
|
|
519
|
-
},
|
|
520
|
-
{
|
|
521
|
-
title: 'Export Disabled Table',
|
|
522
|
-
spec: {
|
|
523
|
-
visualization: 'table',
|
|
524
|
-
columns: ['@timestamp', 'service'],
|
|
525
|
-
allowExport: false,
|
|
526
|
-
},
|
|
527
|
-
},
|
|
528
|
-
],
|
|
529
|
-
},
|
|
530
|
-
},
|
|
531
|
-
});
|
|
532
|
-
expect(bundleRes.body.result.isError).toBe(false);
|
|
533
|
-
const bundlePayload = JSON.parse(bundleRes.body.result.content[0].text) as {
|
|
534
|
-
createdCount: number;
|
|
535
|
-
reports: Array<{ id: number; title: string }>;
|
|
536
|
-
};
|
|
537
|
-
expect(bundlePayload.createdCount).toBe(3);
|
|
538
|
-
const exportTableId = bundlePayload.reports[1].id;
|
|
539
|
-
const noExportTableId = bundlePayload.reports[2].id;
|
|
540
|
-
|
|
541
|
-
// 3. Viewer-safe es_analyze_report: denied for unauthorized 'report-viewer', allowed for 'finance-viewer' with {{$role}} resolved!
|
|
542
|
-
const deniedAnalyze = await viewerAgent.post('/api/elastic-report-mcp').send({
|
|
543
|
-
jsonrpc: '2.0',
|
|
544
|
-
id: 22,
|
|
545
|
-
method: 'tools/call',
|
|
546
|
-
params: {
|
|
547
|
-
name: 'es_analyze_report',
|
|
548
|
-
arguments: { reportId: exportTableId },
|
|
549
|
-
},
|
|
550
|
-
});
|
|
551
|
-
expect(deniedAnalyze.body.result.isError).toBe(true);
|
|
552
|
-
expect(deniedAnalyze.body.result.content[0].text).toContain('403');
|
|
553
|
-
|
|
554
|
-
const allowedAnalyze = await financeViewerAgent.post('/api/elastic-report-mcp').send({
|
|
555
|
-
jsonrpc: '2.0',
|
|
556
|
-
id: 23,
|
|
557
|
-
method: 'tools/call',
|
|
558
|
-
params: {
|
|
559
|
-
name: 'es_analyze_report',
|
|
560
|
-
arguments: { reportId: exportTableId, query: 'status >= 500' },
|
|
561
|
-
},
|
|
562
|
-
});
|
|
563
|
-
expect(allowedAnalyze.body.result.isError).toBe(false);
|
|
564
|
-
const analyzedData = JSON.parse(allowedAnalyze.body.result.content[0].text) as { total: number };
|
|
565
|
-
expect(analyzedData.total).toBe(2);
|
|
566
|
-
const analyzeDsl = capturedSearchBodies[capturedSearchBodies.length - 1];
|
|
567
|
-
expect(JSON.stringify(analyzeDsl)).toContain('"service.keyword":"finance-viewer"');
|
|
568
|
-
|
|
569
|
-
// 4. esReportService:inspectTopValues returns top buckets for authorized viewer and rejects unauthorized viewer
|
|
570
|
-
const deniedTop = await viewerAgent.get(
|
|
571
|
-
`/api/esReportService:inspectTopValues?reportId=${exportTableId}&field=service`,
|
|
572
|
-
);
|
|
573
|
-
expect(deniedTop.status).toBe(403);
|
|
574
|
-
|
|
575
|
-
const topRes = await financeViewerAgent.get(
|
|
576
|
-
`/api/esReportService:inspectTopValues?reportId=${exportTableId}&field=service&size=5`,
|
|
577
|
-
);
|
|
578
|
-
expect(topRes.status).toBe(200);
|
|
579
|
-
expect(topRes.body.data.buckets).toEqual([
|
|
580
|
-
expect.objectContaining({ value: 'checkout', count: 2, percentage: 100 }),
|
|
581
|
-
]);
|
|
582
|
-
|
|
583
|
-
// 5. Streaming CSV & NDJSON export enforces ACL, allowExport, PIT cursor, UTF-8 BOM, and CSV formula neutralization
|
|
584
|
-
const unauthorizedExport = await viewerAgent.post('/api/esReportService:exportReport').send({
|
|
585
|
-
reportId: exportTableId,
|
|
586
|
-
format: 'csv',
|
|
587
|
-
});
|
|
588
|
-
expect(unauthorizedExport.status).toBe(403);
|
|
589
|
-
|
|
590
|
-
const disabledExport = await financeViewerAgent.post('/api/esReportService:exportReport').send({
|
|
591
|
-
reportId: noExportTableId,
|
|
592
|
-
format: 'csv',
|
|
593
|
-
});
|
|
594
|
-
expect(disabledExport.status).toBe(403);
|
|
595
|
-
|
|
596
|
-
const csvRes = await financeViewerAgent.post('/api/esReportService:exportReport').send({
|
|
597
|
-
reportId: exportTableId,
|
|
598
|
-
format: 'csv',
|
|
599
|
-
});
|
|
600
|
-
expect(csvRes.status).toBe(200);
|
|
601
|
-
expect(csvRes.headers['content-type']).toContain('text/csv');
|
|
602
|
-
expect(csvRes.headers['content-disposition']).toContain('role-scoped-export-table.csv');
|
|
603
|
-
expect(csvRes.text).toContain('@timestamp,service,status,message');
|
|
604
|
-
// Formula payload "=2+5" is prefixed with single quote to prevent spreadsheet execution
|
|
605
|
-
expect(csvRes.text).toContain("'=2+5");
|
|
606
|
-
const exportEsDsl = capturedSearchBodies[capturedSearchBodies.length - 1];
|
|
607
|
-
expect(JSON.stringify(exportEsDsl)).toContain('"service.keyword":"finance-viewer"');
|
|
608
|
-
expect(JSON.stringify(exportEsDsl)).toContain('"_shard_doc"');
|
|
609
|
-
|
|
610
|
-
const ndjsonRes = await financeViewerAgent.post('/api/esReportService:exportReport').send({
|
|
611
|
-
reportId: exportTableId,
|
|
612
|
-
format: 'ndjson',
|
|
613
|
-
});
|
|
614
|
-
expect(ndjsonRes.status).toBe(200);
|
|
615
|
-
expect(ndjsonRes.headers['content-type']).toContain('application/x-ndjson');
|
|
616
|
-
const ndjsonLines = ndjsonRes.text.trim().split('\n');
|
|
617
|
-
expect(ndjsonLines).toHaveLength(2);
|
|
618
|
-
expect(JSON.parse(ndjsonLines[0])).toMatchObject({ _id: 'hit-1', service: 'checkout', status: 502 });
|
|
619
|
-
|
|
620
|
-
// 6. Workflow instruction ElasticReportQueryInstruction executes report and evaluates threshold breach
|
|
621
|
-
const pluginInstance = app.pm.get(PluginElasticReportServer) as PluginElasticReportServer;
|
|
622
|
-
const instruction = new ElasticReportQueryInstruction({} as never, pluginInstance.reportService);
|
|
623
|
-
const wfJob = await instruction.run(
|
|
624
|
-
{
|
|
625
|
-
id: 99,
|
|
626
|
-
config: {
|
|
627
|
-
reportId: 1,
|
|
628
|
-
thresholdField: 'total',
|
|
629
|
-
thresholdOperator: 'gte',
|
|
630
|
-
thresholdValue: 2,
|
|
631
|
-
},
|
|
632
|
-
} as never,
|
|
633
|
-
{},
|
|
634
|
-
{
|
|
635
|
-
getParsedValue: (val: unknown) => val,
|
|
636
|
-
} as never,
|
|
637
|
-
);
|
|
638
|
-
expect(wfJob.status).toBe(JOB_STATUS.RESOLVED);
|
|
639
|
-
expect(wfJob.result).toMatchObject({
|
|
640
|
-
reportId: 1,
|
|
641
|
-
total: 2,
|
|
642
|
-
breached: true,
|
|
643
|
-
});
|
|
644
|
-
});
|
|
645
|
-
});
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { createServer, type IncomingMessage, type Server } from 'http';
|
|
11
|
+
import type { AddressInfo } from 'net';
|
|
12
|
+
import { JOB_STATUS } from '@nocobase/plugin-workflow';
|
|
13
|
+
import { createMockServer, type MockServer } from '@nocobase/test';
|
|
14
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
15
|
+
import PluginDataSourceElasticsearch from '../../../../plugin-data-source-elasticsearch/src/server/plugin';
|
|
16
|
+
import PluginElasticReportServer from '../plugin';
|
|
17
|
+
import { ElasticReportQueryInstruction } from '../workflow/ElasticReportQueryInstruction';
|
|
18
|
+
|
|
19
|
+
function readBody(req: IncomingMessage): Promise<string> {
|
|
20
|
+
return new Promise((resolve) => {
|
|
21
|
+
const chunks: Buffer[] = [];
|
|
22
|
+
req.on('data', (chunk: Buffer) => chunks.push(chunk));
|
|
23
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
describe('plugin-elastic-report REST, DataSource reuse, ACL, and MCP integration', () => {
|
|
28
|
+
let app: MockServer;
|
|
29
|
+
let upstream: Server;
|
|
30
|
+
let esUrl = '';
|
|
31
|
+
let viewerAgent: ReturnType<MockServer['agent']>;
|
|
32
|
+
let financeViewerAgent: ReturnType<MockServer['agent']>;
|
|
33
|
+
let dualRoleViewerAgent: ReturnType<MockServer['agent']>;
|
|
34
|
+
let builderAgent: ReturnType<MockServer['agent']>;
|
|
35
|
+
const capturedSearchBodies: Array<Record<string, unknown>> = [];
|
|
36
|
+
|
|
37
|
+
beforeAll(async () => {
|
|
38
|
+
upstream = createServer(async (req, res) => {
|
|
39
|
+
const url = req.url || '/';
|
|
40
|
+
const rawBody = await readBody(req);
|
|
41
|
+
res.setHeader('x-elastic-product', 'Elasticsearch');
|
|
42
|
+
res.setHeader('content-type', 'application/json');
|
|
43
|
+
|
|
44
|
+
if (req.method === 'HEAD' || url === '/') {
|
|
45
|
+
res.statusCode = 200;
|
|
46
|
+
res.end(JSON.stringify({ name: 'mock-es', version: { number: '8.17.0' } }));
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (url.includes('_cluster/health')) {
|
|
51
|
+
res.end(JSON.stringify({ cluster_name: 'test-es', status: 'green' }));
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (url.includes('_cat/indices')) {
|
|
56
|
+
res.end(JSON.stringify([{ index: 'logs-2026.11.29' }, { index: 'logs-2026.11.30' }]));
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (url.includes('_field_caps')) {
|
|
61
|
+
res.end(
|
|
62
|
+
JSON.stringify({
|
|
63
|
+
indices: ['logs-2026.11.29', 'logs-2026.11.30'],
|
|
64
|
+
fields: {
|
|
65
|
+
'@timestamp': {
|
|
66
|
+
date: { type: 'date', searchable: true, aggregatable: true },
|
|
67
|
+
},
|
|
68
|
+
service: {
|
|
69
|
+
text: { type: 'text', searchable: true, aggregatable: false },
|
|
70
|
+
},
|
|
71
|
+
'service.keyword': {
|
|
72
|
+
keyword: { type: 'keyword', searchable: true, aggregatable: true },
|
|
73
|
+
},
|
|
74
|
+
status: {
|
|
75
|
+
integer: { type: 'integer', searchable: true, aggregatable: true },
|
|
76
|
+
},
|
|
77
|
+
latency_ms: {
|
|
78
|
+
double: { type: 'double', searchable: true, aggregatable: true },
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
}),
|
|
82
|
+
);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (url.includes('_mapping')) {
|
|
87
|
+
res.end(
|
|
88
|
+
JSON.stringify({
|
|
89
|
+
'logs-2026.11.30': {
|
|
90
|
+
mappings: {
|
|
91
|
+
properties: {
|
|
92
|
+
'@timestamp': { type: 'date' },
|
|
93
|
+
service: { type: 'text', fields: { keyword: { type: 'keyword' } } },
|
|
94
|
+
status: { type: 'integer' },
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
}),
|
|
99
|
+
);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (url.includes('_pit')) {
|
|
104
|
+
if (req.method === 'DELETE') {
|
|
105
|
+
res.end(JSON.stringify({ succeeded: true, num_freed: 1 }));
|
|
106
|
+
} else {
|
|
107
|
+
res.end(JSON.stringify({ id: 'pit-token-1' }));
|
|
108
|
+
}
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (url.includes('_search')) {
|
|
113
|
+
const parsedBody = rawBody ? (JSON.parse(rawBody) as Record<string, unknown>) : {};
|
|
114
|
+
capturedSearchBodies.push(parsedBody);
|
|
115
|
+
res.end(
|
|
116
|
+
JSON.stringify({
|
|
117
|
+
took: 5,
|
|
118
|
+
...(parsedBody.pit ? { pit_id: 'pit-token-1' } : {}),
|
|
119
|
+
hits: {
|
|
120
|
+
total: { value: 2, relation: 'eq' },
|
|
121
|
+
hits: [
|
|
122
|
+
{
|
|
123
|
+
_index: 'logs-2026.11.30',
|
|
124
|
+
_id: 'hit-1',
|
|
125
|
+
sort: [1732920000000, 1],
|
|
126
|
+
_source: {
|
|
127
|
+
'@timestamp': '2026-11-30T01:00:00Z',
|
|
128
|
+
service: 'checkout',
|
|
129
|
+
status: 502,
|
|
130
|
+
latency_ms: 340,
|
|
131
|
+
message: '=2+5',
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
_index: 'logs-2026.11.30',
|
|
136
|
+
_id: 'hit-2',
|
|
137
|
+
sort: [1732910000000, 2],
|
|
138
|
+
_source: {
|
|
139
|
+
'@timestamp': '2026-11-30T00:50:00Z',
|
|
140
|
+
service: 'checkout',
|
|
141
|
+
status: 500,
|
|
142
|
+
latency_ms: 210,
|
|
143
|
+
message: 'Upstream gateway timeout',
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
],
|
|
147
|
+
},
|
|
148
|
+
aggregations: {
|
|
149
|
+
es_time_histogram: {
|
|
150
|
+
buckets: [{ key_as_string: '2026-11-30T00:00:00Z', key: 1732910000000, doc_count: 2 }],
|
|
151
|
+
},
|
|
152
|
+
es_buckets: {
|
|
153
|
+
buckets: [{ key: 'checkout', doc_count: 2, es_metric: { value: 275 } }],
|
|
154
|
+
},
|
|
155
|
+
},
|
|
156
|
+
}),
|
|
157
|
+
);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
res.end(JSON.stringify({}));
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
await new Promise<void>((resolve) => upstream.listen(0, '127.0.0.1', resolve));
|
|
165
|
+
esUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`;
|
|
166
|
+
|
|
167
|
+
app = await createMockServer({
|
|
168
|
+
acl: true,
|
|
169
|
+
resourcer: {
|
|
170
|
+
prefix: '/api',
|
|
171
|
+
},
|
|
172
|
+
plugins: [
|
|
173
|
+
'field-sort',
|
|
174
|
+
'system-settings',
|
|
175
|
+
'users',
|
|
176
|
+
'auth',
|
|
177
|
+
'acl',
|
|
178
|
+
'data-source-manager',
|
|
179
|
+
'data-source-main',
|
|
180
|
+
'error-handler',
|
|
181
|
+
[PluginDataSourceElasticsearch, { name: 'plugin-data-source-elasticsearch' }],
|
|
182
|
+
[PluginElasticReportServer, { name: 'plugin-elastic-report' }],
|
|
183
|
+
],
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
// Register an Elasticsearch data source record as plugin-data-source-elasticsearch does
|
|
187
|
+
await app.db.getRepository('dataSources').create({
|
|
188
|
+
values: {
|
|
189
|
+
key: 'es_logs_cluster',
|
|
190
|
+
displayName: 'ES Logs Cluster',
|
|
191
|
+
type: 'elasticsearch',
|
|
192
|
+
enabled: true,
|
|
193
|
+
options: {
|
|
194
|
+
nodes: esUrl,
|
|
195
|
+
indexPattern: 'logs-*',
|
|
196
|
+
addAllCollections: false,
|
|
197
|
+
selectedCollections: [],
|
|
198
|
+
password: 'super-secret-password',
|
|
199
|
+
},
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
for (const roleName of ['report-viewer', 'finance-viewer', 'report-builder']) {
|
|
204
|
+
await app.db.getRepository('roles').create({
|
|
205
|
+
values: {
|
|
206
|
+
name: roleName,
|
|
207
|
+
title: roleName,
|
|
208
|
+
snippets: roleName === 'report-builder' ? ['pm.elastic-report'] : [],
|
|
209
|
+
},
|
|
210
|
+
});
|
|
211
|
+
const user = await app.db.getRepository('users').create({
|
|
212
|
+
values: { username: roleName, roles: [roleName] },
|
|
213
|
+
});
|
|
214
|
+
const agent = await app.agent().login(user, roleName);
|
|
215
|
+
if (roleName === 'report-viewer') viewerAgent = agent;
|
|
216
|
+
else if (roleName === 'finance-viewer') financeViewerAgent = agent;
|
|
217
|
+
else builderAgent = agent;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Create a user whose account possesses 'admin' + 'report-viewer', but whose active request role is narrowed to 'report-viewer'
|
|
221
|
+
const dualUser = await app.db.getRepository('users').create({
|
|
222
|
+
values: { username: 'dual-admin-viewer', roles: ['admin', 'report-viewer'] },
|
|
223
|
+
});
|
|
224
|
+
dualRoleViewerAgent = await app.agent().login(dualUser, 'report-viewer');
|
|
225
|
+
|
|
226
|
+
app.acl.getRole('report-builder').snippets.add('pm.elastic-report');
|
|
227
|
+
}, 120000);
|
|
228
|
+
|
|
229
|
+
afterAll(async () => {
|
|
230
|
+
await app?.destroy();
|
|
231
|
+
if (upstream) {
|
|
232
|
+
await new Promise<void>((resolve) => upstream.close(() => resolve()));
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
it('blocks unprivileged viewers from managing connections or saving reports while never leaking ES secrets', async () => {
|
|
237
|
+
const deniedConn = await viewerAgent.resource('esReportService').listConnections();
|
|
238
|
+
expect(deniedConn.status).toBe(403);
|
|
239
|
+
|
|
240
|
+
const allowedConn = await builderAgent.resource('esReportService').listConnections();
|
|
241
|
+
expect(allowedConn.status).toBe(200);
|
|
242
|
+
expect(allowedConn.body.data).toEqual([
|
|
243
|
+
expect.objectContaining({
|
|
244
|
+
key: 'es_logs_cluster',
|
|
245
|
+
displayName: 'ES Logs Cluster',
|
|
246
|
+
}),
|
|
247
|
+
]);
|
|
248
|
+
expect(JSON.stringify(allowedConn.body)).not.toContain('super-secret-password');
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('supports full AI Employee MCP workflow over /api/elastic-report-mcp and enforces viewer/builder ACL', async () => {
|
|
252
|
+
// 1. Unauthenticated request to MCP endpoint is rejected
|
|
253
|
+
const anonRes = await app
|
|
254
|
+
.agent()
|
|
255
|
+
.post('/api/elastic-report-mcp')
|
|
256
|
+
.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} });
|
|
257
|
+
expect([401, 403]).toContain(anonRes.status);
|
|
258
|
+
|
|
259
|
+
// 2. Initialize & list tools as report-builder
|
|
260
|
+
const initRes = await builderAgent
|
|
261
|
+
.post('/api/elastic-report-mcp')
|
|
262
|
+
.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26' } });
|
|
263
|
+
expect(initRes.status).toBe(200);
|
|
264
|
+
expect(initRes.body.result.serverInfo.name).toBe('elastic-report');
|
|
265
|
+
|
|
266
|
+
const listToolsRes = await builderAgent
|
|
267
|
+
.post('/api/elastic-report-mcp')
|
|
268
|
+
.send({ jsonrpc: '2.0', id: 2, method: 'tools/list' });
|
|
269
|
+
expect(listToolsRes.status).toBe(200);
|
|
270
|
+
const toolNames = (listToolsRes.body.result.tools as Array<{ name: string }>).map((t) => t.name);
|
|
271
|
+
expect(toolNames).toEqual(
|
|
272
|
+
expect.arrayContaining([
|
|
273
|
+
'es_list_connections',
|
|
274
|
+
'es_upsert_data_view',
|
|
275
|
+
'es_inspect_fields',
|
|
276
|
+
'es_preview_report',
|
|
277
|
+
'es_save_report',
|
|
278
|
+
'es_list_reports',
|
|
279
|
+
]),
|
|
280
|
+
);
|
|
281
|
+
|
|
282
|
+
// 3. Viewer cannot invoke write MCP tool `es_upsert_data_view`
|
|
283
|
+
const viewerWriteMcp = await viewerAgent.post('/api/elastic-report-mcp').send({
|
|
284
|
+
jsonrpc: '2.0',
|
|
285
|
+
id: 3,
|
|
286
|
+
method: 'tools/call',
|
|
287
|
+
params: {
|
|
288
|
+
name: 'es_upsert_data_view',
|
|
289
|
+
arguments: {
|
|
290
|
+
title: 'Unauthorized DV',
|
|
291
|
+
dataSourceKey: 'es_logs_cluster',
|
|
292
|
+
indexPattern: 'logs-*',
|
|
293
|
+
},
|
|
294
|
+
},
|
|
295
|
+
});
|
|
296
|
+
expect(viewerWriteMcp.status).toBe(200);
|
|
297
|
+
expect(viewerWriteMcp.body.result.isError).toBe(true);
|
|
298
|
+
expect(viewerWriteMcp.body.result.content[0].text).toContain('403');
|
|
299
|
+
|
|
300
|
+
// 4. Builder creates Data View via MCP -> auto-detects @timestamp via _field_caps
|
|
301
|
+
const createDvMcp = await builderAgent.post('/api/elastic-report-mcp').send({
|
|
302
|
+
jsonrpc: '2.0',
|
|
303
|
+
id: 4,
|
|
304
|
+
method: 'tools/call',
|
|
305
|
+
params: {
|
|
306
|
+
name: 'es_upsert_data_view',
|
|
307
|
+
arguments: {
|
|
308
|
+
title: 'Production Logs',
|
|
309
|
+
dataSourceKey: 'es_logs_cluster',
|
|
310
|
+
indexPattern: 'logs-*',
|
|
311
|
+
},
|
|
312
|
+
},
|
|
313
|
+
});
|
|
314
|
+
expect(createDvMcp.body.result.isError).toBe(false);
|
|
315
|
+
const dvPayload = JSON.parse(createDvMcp.body.result.content[0].text) as {
|
|
316
|
+
dataView: { id: number; timeField: string };
|
|
317
|
+
fieldCount: number;
|
|
318
|
+
};
|
|
319
|
+
expect(dvPayload.dataView.timeField).toBe('@timestamp');
|
|
320
|
+
expect(dvPayload.fieldCount).toBe(5);
|
|
321
|
+
|
|
322
|
+
// 5. Builder previews and saves a Kibana Table Report via MCP
|
|
323
|
+
const previewMcp = await builderAgent.post('/api/elastic-report-mcp').send({
|
|
324
|
+
jsonrpc: '2.0',
|
|
325
|
+
id: 5,
|
|
326
|
+
method: 'tools/call',
|
|
327
|
+
params: {
|
|
328
|
+
name: 'es_preview_report',
|
|
329
|
+
arguments: {
|
|
330
|
+
dataViewId: dvPayload.dataView.id,
|
|
331
|
+
spec: {
|
|
332
|
+
visualization: 'table',
|
|
333
|
+
query: 'status >= 500 AND service: "checkout"',
|
|
334
|
+
sort: [{ field: 'service', order: 'asc' }],
|
|
335
|
+
timeRange: { preset: 'last_24h' },
|
|
336
|
+
},
|
|
337
|
+
},
|
|
338
|
+
},
|
|
339
|
+
});
|
|
340
|
+
expect(previewMcp.body.result.isError).toBe(false);
|
|
341
|
+
const previewData = JSON.parse(previewMcp.body.result.content[0].text) as { total: number };
|
|
342
|
+
expect(previewData.total).toBe(2);
|
|
343
|
+
|
|
344
|
+
const saveMcp = await builderAgent.post('/api/elastic-report-mcp').send({
|
|
345
|
+
jsonrpc: '2.0',
|
|
346
|
+
id: 6,
|
|
347
|
+
method: 'tools/call',
|
|
348
|
+
params: {
|
|
349
|
+
name: 'es_save_report',
|
|
350
|
+
arguments: {
|
|
351
|
+
title: 'Checkout 5xx Errors',
|
|
352
|
+
dataViewId: dvPayload.dataView.id,
|
|
353
|
+
published: true,
|
|
354
|
+
spec: {
|
|
355
|
+
visualization: 'table',
|
|
356
|
+
query: 'status >= 500',
|
|
357
|
+
filters: [{ field: 'service', operator: 'eq', value: 'checkout' }],
|
|
358
|
+
sort: [{ field: '@timestamp', order: 'desc' }],
|
|
359
|
+
timeRange: { preset: 'last_24h' },
|
|
360
|
+
columns: ['@timestamp', 'service', 'status', 'latency_ms'],
|
|
361
|
+
},
|
|
362
|
+
},
|
|
363
|
+
},
|
|
364
|
+
});
|
|
365
|
+
expect(saveMcp.body.result.isError).toBe(false);
|
|
366
|
+
const savedReportPayload = JSON.parse(saveMcp.body.result.content[0].text) as {
|
|
367
|
+
report: { id: number; title: string };
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
// 6. Regular page viewer can list published reports (for ReportSelect), fetch GET getReportMeta?reportId=..., and execute the saved report with interactive overrides!
|
|
371
|
+
const publishedList = await viewerAgent.get('/api/esReportService:listPublishedReports?search=Checkout');
|
|
372
|
+
expect(publishedList.status).toBe(200);
|
|
373
|
+
expect(publishedList.body.data).toEqual([
|
|
374
|
+
expect.objectContaining({
|
|
375
|
+
id: savedReportPayload.report.id,
|
|
376
|
+
title: 'Checkout 5xx Errors',
|
|
377
|
+
}),
|
|
378
|
+
]);
|
|
379
|
+
|
|
380
|
+
const metaRes = await viewerAgent.get(
|
|
381
|
+
`/api/esReportService:getReportMeta?reportId=${savedReportPayload.report.id}`,
|
|
382
|
+
);
|
|
383
|
+
expect(metaRes.status).toBe(200);
|
|
384
|
+
expect(metaRes.body.data.report.title).toBe('Checkout 5xx Errors');
|
|
385
|
+
expect(metaRes.body.data.fields.length).toBeGreaterThan(0);
|
|
386
|
+
|
|
387
|
+
const runRes = await viewerAgent.resource('esReportService').runReport({
|
|
388
|
+
values: {
|
|
389
|
+
reportId: savedReportPayload.report.id,
|
|
390
|
+
overrides: {
|
|
391
|
+
query: 'status >= 502',
|
|
392
|
+
page: 1,
|
|
393
|
+
},
|
|
394
|
+
},
|
|
395
|
+
});
|
|
396
|
+
expect(runRes.status).toBe(200);
|
|
397
|
+
expect(runRes.body.data.result.total).toBe(2);
|
|
398
|
+
expect(runRes.body.data.result.rows[0].source.service).toBe('checkout');
|
|
399
|
+
expect(capturedSearchBodies.length).toBeGreaterThanOrEqual(2);
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
it('prevents dormant admin role escalation and enforces per-report allowedRoles + server lockedFilters', async () => {
|
|
403
|
+
// 1. Account with ['admin', 'report-viewer'] logged in under effective role 'report-viewer' MUST NOT escalate to manager
|
|
404
|
+
const dualSaveMcp = await dualRoleViewerAgent.post('/api/elastic-report-mcp').send({
|
|
405
|
+
jsonrpc: '2.0',
|
|
406
|
+
id: 10,
|
|
407
|
+
method: 'tools/call',
|
|
408
|
+
params: {
|
|
409
|
+
name: 'es_save_report',
|
|
410
|
+
arguments: {
|
|
411
|
+
title: 'Escalation Attempt',
|
|
412
|
+
dataViewId: 1,
|
|
413
|
+
spec: { visualization: 'table' },
|
|
414
|
+
},
|
|
415
|
+
},
|
|
416
|
+
});
|
|
417
|
+
expect(dualSaveMcp.status).toBe(200);
|
|
418
|
+
expect(dualSaveMcp.body.result.isError).toBe(true);
|
|
419
|
+
expect(dualSaveMcp.body.result.content[0].text).toContain('Permission denied');
|
|
420
|
+
|
|
421
|
+
// 2. Invalid KQL syntax is rejected with HTTP 400 on saveReport
|
|
422
|
+
const badKqlRes = await builderAgent.resource('esReportService').saveReport({
|
|
423
|
+
values: {
|
|
424
|
+
title: 'Broken KQL',
|
|
425
|
+
dataViewId: 1,
|
|
426
|
+
spec: {
|
|
427
|
+
visualization: 'table',
|
|
428
|
+
query: 'status: (400 OR',
|
|
429
|
+
},
|
|
430
|
+
},
|
|
431
|
+
});
|
|
432
|
+
expect(badKqlRes.status).toBe(400);
|
|
433
|
+
|
|
434
|
+
// 3. Builder creates a role-restricted report with mandatory lockedFilters
|
|
435
|
+
const restrictedSave = await builderAgent.resource('esReportService').saveReport({
|
|
436
|
+
values: {
|
|
437
|
+
title: 'Finance Billing Audit',
|
|
438
|
+
dataViewId: 1,
|
|
439
|
+
published: true,
|
|
440
|
+
allowedRoles: ['finance-viewer'],
|
|
441
|
+
spec: {
|
|
442
|
+
visualization: 'table',
|
|
443
|
+
query: 'status: (500 OR 502)',
|
|
444
|
+
lockedFilters: [{ field: 'service', operator: 'eq', value: 'billing' }],
|
|
445
|
+
filters: [{ field: 'status', operator: 'gte', value: 400 }],
|
|
446
|
+
allowInteractiveControls: true,
|
|
447
|
+
},
|
|
448
|
+
},
|
|
449
|
+
});
|
|
450
|
+
expect(restrictedSave.status).toBe(200);
|
|
451
|
+
const restrictedReportId = restrictedSave.body.data.id as number;
|
|
452
|
+
|
|
453
|
+
// 4. 'report-viewer' (and dual-role user acting as 'report-viewer') cannot list, inspect, or run 'Finance Billing Audit'
|
|
454
|
+
const viewerPublished = await viewerAgent.get('/api/esReportService:listPublishedReports?search=Finance');
|
|
455
|
+
expect(viewerPublished.status).toBe(200);
|
|
456
|
+
expect(viewerPublished.body.data).toEqual([]);
|
|
457
|
+
|
|
458
|
+
const viewerMetaDenied = await viewerAgent.get(`/api/esReportService:getReportMeta?reportId=${restrictedReportId}`);
|
|
459
|
+
expect(viewerMetaDenied.status).toBe(403);
|
|
460
|
+
|
|
461
|
+
const dualRunDenied = await dualRoleViewerAgent.resource('esReportService').runReport({
|
|
462
|
+
values: { reportId: restrictedReportId },
|
|
463
|
+
});
|
|
464
|
+
expect(dualRunDenied.status).toBe(403);
|
|
465
|
+
|
|
466
|
+
// 5. 'finance-viewer' CAN run the report, and attempting to clear filters via runtime overrides STILL preserves lockedFilters!
|
|
467
|
+
const beforeCount = capturedSearchBodies.length;
|
|
468
|
+
const financeRun = await financeViewerAgent.resource('esReportService').runReport({
|
|
469
|
+
values: {
|
|
470
|
+
reportId: restrictedReportId,
|
|
471
|
+
overrides: {
|
|
472
|
+
query: '',
|
|
473
|
+
filters: [],
|
|
474
|
+
},
|
|
475
|
+
},
|
|
476
|
+
});
|
|
477
|
+
expect(financeRun.status).toBe(200);
|
|
478
|
+
expect(capturedSearchBodies.length).toBe(beforeCount + 1);
|
|
479
|
+
const executedEsBody = capturedSearchBodies[capturedSearchBodies.length - 1];
|
|
480
|
+
expect(JSON.stringify(executedEsBody)).toContain('"service.keyword":"billing"');
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
it('supports top-values inspection, streaming CSV/NDJSON export with {{$role}} lockedFilters, workflow instruction, and AI Analyst MCP tools', async () => {
|
|
484
|
+
// 1. MCP tools/list exposes all 9 tools including es_analyze_report & es_create_dashboard_bundle
|
|
485
|
+
const listToolsRes = await builderAgent
|
|
486
|
+
.post('/api/elastic-report-mcp')
|
|
487
|
+
.send({ jsonrpc: '2.0', id: 20, method: 'tools/list' });
|
|
488
|
+
const toolNames = (listToolsRes.body.result.tools as Array<{ name: string }>).map((t) => t.name);
|
|
489
|
+
expect(toolNames).toHaveLength(9);
|
|
490
|
+
expect(toolNames).toEqual(expect.arrayContaining(['es_analyze_report', 'es_create_dashboard_bundle']));
|
|
491
|
+
|
|
492
|
+
// 2. Builder creates a coordinated multi-panel dashboard bundle via MCP with dynamic {{$role}} lockedFilters
|
|
493
|
+
const bundleRes = await builderAgent.post('/api/elastic-report-mcp').send({
|
|
494
|
+
jsonrpc: '2.0',
|
|
495
|
+
id: 21,
|
|
496
|
+
method: 'tools/call',
|
|
497
|
+
params: {
|
|
498
|
+
name: 'es_create_dashboard_bundle',
|
|
499
|
+
arguments: {
|
|
500
|
+
dataViewId: 1,
|
|
501
|
+
allowedRoles: ['finance-viewer'],
|
|
502
|
+
lockedFilters: [{ field: 'service', operator: 'eq', value: '{{$role}}' }],
|
|
503
|
+
panels: [
|
|
504
|
+
{
|
|
505
|
+
title: 'Role Scoped KPI',
|
|
506
|
+
spec: {
|
|
507
|
+
visualization: 'metric',
|
|
508
|
+
timeRange: { preset: 'last_24h' },
|
|
509
|
+
chart: { metricType: 'count', comparePreviousPeriod: true },
|
|
510
|
+
},
|
|
511
|
+
},
|
|
512
|
+
{
|
|
513
|
+
title: 'Role Scoped Export Table',
|
|
514
|
+
spec: {
|
|
515
|
+
visualization: 'table',
|
|
516
|
+
columns: ['@timestamp', 'service', 'status', 'message'],
|
|
517
|
+
allowExport: true,
|
|
518
|
+
},
|
|
519
|
+
},
|
|
520
|
+
{
|
|
521
|
+
title: 'Export Disabled Table',
|
|
522
|
+
spec: {
|
|
523
|
+
visualization: 'table',
|
|
524
|
+
columns: ['@timestamp', 'service'],
|
|
525
|
+
allowExport: false,
|
|
526
|
+
},
|
|
527
|
+
},
|
|
528
|
+
],
|
|
529
|
+
},
|
|
530
|
+
},
|
|
531
|
+
});
|
|
532
|
+
expect(bundleRes.body.result.isError).toBe(false);
|
|
533
|
+
const bundlePayload = JSON.parse(bundleRes.body.result.content[0].text) as {
|
|
534
|
+
createdCount: number;
|
|
535
|
+
reports: Array<{ id: number; title: string }>;
|
|
536
|
+
};
|
|
537
|
+
expect(bundlePayload.createdCount).toBe(3);
|
|
538
|
+
const exportTableId = bundlePayload.reports[1].id;
|
|
539
|
+
const noExportTableId = bundlePayload.reports[2].id;
|
|
540
|
+
|
|
541
|
+
// 3. Viewer-safe es_analyze_report: denied for unauthorized 'report-viewer', allowed for 'finance-viewer' with {{$role}} resolved!
|
|
542
|
+
const deniedAnalyze = await viewerAgent.post('/api/elastic-report-mcp').send({
|
|
543
|
+
jsonrpc: '2.0',
|
|
544
|
+
id: 22,
|
|
545
|
+
method: 'tools/call',
|
|
546
|
+
params: {
|
|
547
|
+
name: 'es_analyze_report',
|
|
548
|
+
arguments: { reportId: exportTableId },
|
|
549
|
+
},
|
|
550
|
+
});
|
|
551
|
+
expect(deniedAnalyze.body.result.isError).toBe(true);
|
|
552
|
+
expect(deniedAnalyze.body.result.content[0].text).toContain('403');
|
|
553
|
+
|
|
554
|
+
const allowedAnalyze = await financeViewerAgent.post('/api/elastic-report-mcp').send({
|
|
555
|
+
jsonrpc: '2.0',
|
|
556
|
+
id: 23,
|
|
557
|
+
method: 'tools/call',
|
|
558
|
+
params: {
|
|
559
|
+
name: 'es_analyze_report',
|
|
560
|
+
arguments: { reportId: exportTableId, query: 'status >= 500' },
|
|
561
|
+
},
|
|
562
|
+
});
|
|
563
|
+
expect(allowedAnalyze.body.result.isError).toBe(false);
|
|
564
|
+
const analyzedData = JSON.parse(allowedAnalyze.body.result.content[0].text) as { total: number };
|
|
565
|
+
expect(analyzedData.total).toBe(2);
|
|
566
|
+
const analyzeDsl = capturedSearchBodies[capturedSearchBodies.length - 1];
|
|
567
|
+
expect(JSON.stringify(analyzeDsl)).toContain('"service.keyword":"finance-viewer"');
|
|
568
|
+
|
|
569
|
+
// 4. esReportService:inspectTopValues returns top buckets for authorized viewer and rejects unauthorized viewer
|
|
570
|
+
const deniedTop = await viewerAgent.get(
|
|
571
|
+
`/api/esReportService:inspectTopValues?reportId=${exportTableId}&field=service`,
|
|
572
|
+
);
|
|
573
|
+
expect(deniedTop.status).toBe(403);
|
|
574
|
+
|
|
575
|
+
const topRes = await financeViewerAgent.get(
|
|
576
|
+
`/api/esReportService:inspectTopValues?reportId=${exportTableId}&field=service&size=5`,
|
|
577
|
+
);
|
|
578
|
+
expect(topRes.status).toBe(200);
|
|
579
|
+
expect(topRes.body.data.buckets).toEqual([
|
|
580
|
+
expect.objectContaining({ value: 'checkout', count: 2, percentage: 100 }),
|
|
581
|
+
]);
|
|
582
|
+
|
|
583
|
+
// 5. Streaming CSV & NDJSON export enforces ACL, allowExport, PIT cursor, UTF-8 BOM, and CSV formula neutralization
|
|
584
|
+
const unauthorizedExport = await viewerAgent.post('/api/esReportService:exportReport').send({
|
|
585
|
+
reportId: exportTableId,
|
|
586
|
+
format: 'csv',
|
|
587
|
+
});
|
|
588
|
+
expect(unauthorizedExport.status).toBe(403);
|
|
589
|
+
|
|
590
|
+
const disabledExport = await financeViewerAgent.post('/api/esReportService:exportReport').send({
|
|
591
|
+
reportId: noExportTableId,
|
|
592
|
+
format: 'csv',
|
|
593
|
+
});
|
|
594
|
+
expect(disabledExport.status).toBe(403);
|
|
595
|
+
|
|
596
|
+
const csvRes = await financeViewerAgent.post('/api/esReportService:exportReport').send({
|
|
597
|
+
reportId: exportTableId,
|
|
598
|
+
format: 'csv',
|
|
599
|
+
});
|
|
600
|
+
expect(csvRes.status).toBe(200);
|
|
601
|
+
expect(csvRes.headers['content-type']).toContain('text/csv');
|
|
602
|
+
expect(csvRes.headers['content-disposition']).toContain('role-scoped-export-table.csv');
|
|
603
|
+
expect(csvRes.text).toContain('@timestamp,service,status,message');
|
|
604
|
+
// Formula payload "=2+5" is prefixed with single quote to prevent spreadsheet execution
|
|
605
|
+
expect(csvRes.text).toContain("'=2+5");
|
|
606
|
+
const exportEsDsl = capturedSearchBodies[capturedSearchBodies.length - 1];
|
|
607
|
+
expect(JSON.stringify(exportEsDsl)).toContain('"service.keyword":"finance-viewer"');
|
|
608
|
+
expect(JSON.stringify(exportEsDsl)).toContain('"_shard_doc"');
|
|
609
|
+
|
|
610
|
+
const ndjsonRes = await financeViewerAgent.post('/api/esReportService:exportReport').send({
|
|
611
|
+
reportId: exportTableId,
|
|
612
|
+
format: 'ndjson',
|
|
613
|
+
});
|
|
614
|
+
expect(ndjsonRes.status).toBe(200);
|
|
615
|
+
expect(ndjsonRes.headers['content-type']).toContain('application/x-ndjson');
|
|
616
|
+
const ndjsonLines = ndjsonRes.text.trim().split('\n');
|
|
617
|
+
expect(ndjsonLines).toHaveLength(2);
|
|
618
|
+
expect(JSON.parse(ndjsonLines[0])).toMatchObject({ _id: 'hit-1', service: 'checkout', status: 502 });
|
|
619
|
+
|
|
620
|
+
// 6. Workflow instruction ElasticReportQueryInstruction executes report and evaluates threshold breach
|
|
621
|
+
const pluginInstance = app.pm.get(PluginElasticReportServer) as PluginElasticReportServer;
|
|
622
|
+
const instruction = new ElasticReportQueryInstruction({} as never, pluginInstance.reportService);
|
|
623
|
+
const wfJob = await instruction.run(
|
|
624
|
+
{
|
|
625
|
+
id: 99,
|
|
626
|
+
config: {
|
|
627
|
+
reportId: 1,
|
|
628
|
+
thresholdField: 'total',
|
|
629
|
+
thresholdOperator: 'gte',
|
|
630
|
+
thresholdValue: 2,
|
|
631
|
+
},
|
|
632
|
+
} as never,
|
|
633
|
+
{},
|
|
634
|
+
{
|
|
635
|
+
getParsedValue: (val: unknown) => val,
|
|
636
|
+
} as never,
|
|
637
|
+
);
|
|
638
|
+
expect(wfJob.status).toBe(JOB_STATUS.RESOLVED);
|
|
639
|
+
expect(wfJob.result).toMatchObject({
|
|
640
|
+
reportId: 1,
|
|
641
|
+
total: 2,
|
|
642
|
+
breached: true,
|
|
643
|
+
});
|
|
644
|
+
});
|
|
645
|
+
});
|