plugin-elastic-report 0.1.1 → 0.7.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/ai/skills/elastic-report/SKILLS.md +5 -3
- package/dist/client/357.0dd385384cab5dbf.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/851.142c93fc6d666b28.js +10 -0
- package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
- package/dist/client-v2/877.f4095a3dbcadf98f.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +3 -2
- package/dist/locale/en-US.json +100 -1
- package/dist/locale/vi-VN.json +100 -1
- package/dist/locale/zh-CN.json +100 -1
- package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
- package/dist/server/acl-guard.js +97 -25
- package/dist/server/collections/es-report-data-views.js +6 -0
- package/dist/server/collections/es-reports.js +6 -0
- package/dist/server/mcp/ElasticReportToolCatalog.js +232 -10
- package/dist/server/plugin.js +153 -19
- package/dist/server/services/ElasticReportService.js +125 -11
- package/dist/server/services/ElasticsearchConnectionService.js +274 -34
- package/dist/server/services/ReportExportService.js +243 -0
- package/dist/server/services/ReportQueryCompiler.js +532 -91
- package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
- package/dist/shared/constants.js +17 -2
- package/package.json +3 -2
- package/src/client/index.tsx +16 -1
- package/src/client/workflow-instructions.tsx +44 -0
- package/src/client-v2/__tests__/elastic-report.test.tsx +519 -39
- package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
- package/src/client-v2/api.ts +96 -0
- package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
- package/src/client-v2/components/ElasticBasicCharts.tsx +345 -92
- package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
- package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
- package/src/client-v2/components/ElasticReportBlock.tsx +157 -11
- package/src/client-v2/components/ElasticReportRenderer.tsx +621 -71
- package/src/client-v2/components/ReportSelect.tsx +39 -26
- package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
- package/src/client-v2/models/ElasticReportBlockModel.tsx +36 -3
- package/src/client-v2/pages/ElasticReportManager.tsx +432 -26
- package/src/client-v2/plugin.tsx +20 -0
- package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
- package/src/client-v2/workflow/instructions.tsx +149 -0
- package/src/locale/en-US.json +100 -1
- package/src/locale/vi-VN.json +100 -1
- package/src/locale/zh-CN.json +100 -1
- package/src/server/__tests__/query-compiler.test.ts +390 -1
- package/src/server/__tests__/report-mcp-acl.integration.test.ts +271 -3
- package/src/server/acl-guard.ts +119 -28
- package/src/server/collections/es-report-data-views.ts +6 -0
- package/src/server/collections/es-reports.ts +6 -0
- package/src/server/mcp/ElasticReportToolCatalog.ts +255 -9
- package/src/server/plugin.ts +189 -21
- package/src/server/services/ElasticReportService.ts +165 -5
- package/src/server/services/ElasticsearchConnectionService.ts +375 -48
- package/src/server/services/ReportExportService.ts +282 -0
- package/src/server/services/ReportQueryCompiler.ts +629 -94
- package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
- package/src/shared/constants.ts +7 -0
- package/src/shared/types.ts +98 -1
- package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
|
@@ -9,10 +9,12 @@
|
|
|
9
9
|
|
|
10
10
|
import { createServer, type IncomingMessage, type Server } from 'http';
|
|
11
11
|
import type { AddressInfo } from 'net';
|
|
12
|
+
import { JOB_STATUS } from '@nocobase/plugin-workflow';
|
|
12
13
|
import { createMockServer, type MockServer } from '@nocobase/test';
|
|
13
14
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
14
15
|
import PluginDataSourceElasticsearch from '../../../../plugin-data-source-elasticsearch/src/server/plugin';
|
|
15
16
|
import PluginElasticReportServer from '../plugin';
|
|
17
|
+
import { ElasticReportQueryInstruction } from '../workflow/ElasticReportQueryInstruction';
|
|
16
18
|
|
|
17
19
|
function readBody(req: IncomingMessage): Promise<string> {
|
|
18
20
|
return new Promise((resolve) => {
|
|
@@ -27,6 +29,8 @@ describe('plugin-elastic-report REST, DataSource reuse, ACL, and MCP integration
|
|
|
27
29
|
let upstream: Server;
|
|
28
30
|
let esUrl = '';
|
|
29
31
|
let viewerAgent: ReturnType<MockServer['agent']>;
|
|
32
|
+
let financeViewerAgent: ReturnType<MockServer['agent']>;
|
|
33
|
+
let dualRoleViewerAgent: ReturnType<MockServer['agent']>;
|
|
30
34
|
let builderAgent: ReturnType<MockServer['agent']>;
|
|
31
35
|
const capturedSearchBodies: Array<Record<string, unknown>> = [];
|
|
32
36
|
|
|
@@ -96,35 +100,47 @@ describe('plugin-elastic-report REST, DataSource reuse, ACL, and MCP integration
|
|
|
96
100
|
return;
|
|
97
101
|
}
|
|
98
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
|
+
|
|
99
112
|
if (url.includes('_search')) {
|
|
100
113
|
const parsedBody = rawBody ? (JSON.parse(rawBody) as Record<string, unknown>) : {};
|
|
101
114
|
capturedSearchBodies.push(parsedBody);
|
|
102
115
|
res.end(
|
|
103
116
|
JSON.stringify({
|
|
104
117
|
took: 5,
|
|
118
|
+
...(parsedBody.pit ? { pit_id: 'pit-token-1' } : {}),
|
|
105
119
|
hits: {
|
|
106
120
|
total: { value: 2, relation: 'eq' },
|
|
107
121
|
hits: [
|
|
108
122
|
{
|
|
109
123
|
_index: 'logs-2026.11.30',
|
|
110
124
|
_id: 'hit-1',
|
|
111
|
-
sort: [1732920000000],
|
|
125
|
+
sort: [1732920000000, 1],
|
|
112
126
|
_source: {
|
|
113
127
|
'@timestamp': '2026-11-30T01:00:00Z',
|
|
114
128
|
service: 'checkout',
|
|
115
129
|
status: 502,
|
|
116
130
|
latency_ms: 340,
|
|
131
|
+
message: '=2+5',
|
|
117
132
|
},
|
|
118
133
|
},
|
|
119
134
|
{
|
|
120
135
|
_index: 'logs-2026.11.30',
|
|
121
136
|
_id: 'hit-2',
|
|
122
|
-
sort: [1732910000000],
|
|
137
|
+
sort: [1732910000000, 2],
|
|
123
138
|
_source: {
|
|
124
139
|
'@timestamp': '2026-11-30T00:50:00Z',
|
|
125
140
|
service: 'checkout',
|
|
126
141
|
status: 500,
|
|
127
142
|
latency_ms: 210,
|
|
143
|
+
message: 'Upstream gateway timeout',
|
|
128
144
|
},
|
|
129
145
|
},
|
|
130
146
|
],
|
|
@@ -184,7 +200,7 @@ describe('plugin-elastic-report REST, DataSource reuse, ACL, and MCP integration
|
|
|
184
200
|
},
|
|
185
201
|
});
|
|
186
202
|
|
|
187
|
-
for (const roleName of ['report-viewer', 'report-builder']) {
|
|
203
|
+
for (const roleName of ['report-viewer', 'finance-viewer', 'report-builder']) {
|
|
188
204
|
await app.db.getRepository('roles').create({
|
|
189
205
|
values: {
|
|
190
206
|
name: roleName,
|
|
@@ -197,8 +213,16 @@ describe('plugin-elastic-report REST, DataSource reuse, ACL, and MCP integration
|
|
|
197
213
|
});
|
|
198
214
|
const agent = await app.agent().login(user, roleName);
|
|
199
215
|
if (roleName === 'report-viewer') viewerAgent = agent;
|
|
216
|
+
else if (roleName === 'finance-viewer') financeViewerAgent = agent;
|
|
200
217
|
else builderAgent = agent;
|
|
201
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
|
+
|
|
202
226
|
app.acl.getRole('report-builder').snippets.add('pm.elastic-report');
|
|
203
227
|
}, 120000);
|
|
204
228
|
|
|
@@ -374,4 +398,248 @@ describe('plugin-elastic-report REST, DataSource reuse, ACL, and MCP integration
|
|
|
374
398
|
expect(runRes.body.data.result.rows[0].source.service).toBe('checkout');
|
|
375
399
|
expect(capturedSearchBodies.length).toBeGreaterThanOrEqual(2);
|
|
376
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
|
+
});
|
|
377
645
|
});
|
package/src/server/acl-guard.ts
CHANGED
|
@@ -10,15 +10,32 @@
|
|
|
10
10
|
import type { Context } from '@nocobase/actions';
|
|
11
11
|
import type { Application } from '@nocobase/server';
|
|
12
12
|
import { REPORTS_COLLECTION, SERVICE_RESOURCE } from '../shared/constants';
|
|
13
|
+
import type { EsDataViewRecord, EsReportRecord } from '../shared/types';
|
|
13
14
|
import { extractCurrentUserId } from './services/ElasticReportService';
|
|
14
15
|
|
|
15
|
-
function
|
|
16
|
+
export function normalizeRoleList(raw: unknown): string[] {
|
|
17
|
+
if (!Array.isArray(raw)) return [];
|
|
18
|
+
const seen = new Set<string>();
|
|
19
|
+
for (const item of raw) {
|
|
20
|
+
if (typeof item === 'string' && item.trim()) {
|
|
21
|
+
seen.add(item.trim());
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return Array.from(seen);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Return ONLY the authenticated effective role(s) validated by NocoBase's auth/ACL
|
|
29
|
+
* middleware (`ctx.state.currentRole` / `ctx.state.currentRoles`).
|
|
30
|
+
* Never merge `currentUser.roles` or unvalidated `x-role` headers, so role-scoped
|
|
31
|
+
* requests and API keys cannot escalate to dormant roles on the same user account.
|
|
32
|
+
*/
|
|
33
|
+
export function getEffectiveRoles(ctx?: Partial<Context>): string[] {
|
|
16
34
|
const roles = new Set<string>();
|
|
17
35
|
const state = ctx?.state as
|
|
18
36
|
| {
|
|
19
37
|
currentRole?: unknown;
|
|
20
38
|
currentRoles?: unknown;
|
|
21
|
-
currentUser?: { roles?: Array<{ name?: string } | string> };
|
|
22
39
|
}
|
|
23
40
|
| undefined;
|
|
24
41
|
|
|
@@ -27,18 +44,8 @@ function getCurrentRoles(ctx?: Partial<Context>): string[] {
|
|
|
27
44
|
}
|
|
28
45
|
if (Array.isArray(state?.currentRoles)) {
|
|
29
46
|
for (const r of state.currentRoles) {
|
|
30
|
-
if (typeof r === 'string' && r.trim())
|
|
31
|
-
|
|
32
|
-
}
|
|
33
|
-
const headerRole = ctx?.request?.headers?.['x-role'];
|
|
34
|
-
if (typeof headerRole === 'string' && headerRole.trim()) {
|
|
35
|
-
roles.add(headerRole.trim());
|
|
36
|
-
}
|
|
37
|
-
if (Array.isArray(state?.currentUser?.roles)) {
|
|
38
|
-
for (const r of state.currentUser.roles) {
|
|
39
|
-
if (typeof r === 'string' && r.trim()) roles.add(r.trim());
|
|
40
|
-
else if (r && typeof r === 'object' && typeof r.name === 'string' && r.name.trim()) {
|
|
41
|
-
roles.add(r.name.trim());
|
|
47
|
+
if (typeof r === 'string' && r.trim()) {
|
|
48
|
+
roles.add(r.trim());
|
|
42
49
|
}
|
|
43
50
|
}
|
|
44
51
|
}
|
|
@@ -56,27 +63,15 @@ export function assertAuthenticated(ctx?: Partial<Context>): void {
|
|
|
56
63
|
|
|
57
64
|
export function canManageReports(app: Application, ctx?: Partial<Context>): boolean {
|
|
58
65
|
const userId = extractCurrentUserId(ctx);
|
|
59
|
-
if (userId === undefined || userId === null) {
|
|
66
|
+
if (userId === undefined || userId === null || String(userId).trim() === '') {
|
|
60
67
|
return false;
|
|
61
68
|
}
|
|
62
69
|
|
|
63
|
-
const roles =
|
|
70
|
+
const roles = getEffectiveRoles(ctx);
|
|
64
71
|
if (roles.includes('root') || roles.includes('admin')) {
|
|
65
72
|
return true;
|
|
66
73
|
}
|
|
67
74
|
|
|
68
|
-
if (roles.length === 0) {
|
|
69
|
-
// When invoked from an internal authenticated session that has not narrowed `x-role`,
|
|
70
|
-
// defer to whether `acl` explicitly restricts `saveReport`.
|
|
71
|
-
const aclLike = app.acl as unknown as {
|
|
72
|
-
can?: (opts: { role: string; resource: string; action: string }) => unknown;
|
|
73
|
-
};
|
|
74
|
-
if (typeof aclLike?.can !== 'function') {
|
|
75
|
-
return true;
|
|
76
|
-
}
|
|
77
|
-
return Boolean(aclLike.can({ role: 'member', resource: SERVICE_RESOURCE, action: 'saveReport' }));
|
|
78
|
-
}
|
|
79
|
-
|
|
80
75
|
const aclLike = app.acl as unknown as {
|
|
81
76
|
can?: (opts: { role: string; resource: string; action: string }) => unknown;
|
|
82
77
|
};
|
|
@@ -84,6 +79,10 @@ export function canManageReports(app: Application, ctx?: Partial<Context>): bool
|
|
|
84
79
|
return false;
|
|
85
80
|
}
|
|
86
81
|
|
|
82
|
+
if (roles.length === 0) {
|
|
83
|
+
return Boolean(aclLike.can({ role: 'member', resource: SERVICE_RESOURCE, action: 'saveReport' }));
|
|
84
|
+
}
|
|
85
|
+
|
|
87
86
|
return roles.some(
|
|
88
87
|
(role) =>
|
|
89
88
|
Boolean(aclLike.can({ role, resource: SERVICE_RESOURCE, action: 'saveReport' })) ||
|
|
@@ -101,3 +100,95 @@ export function assertCanManageReports(app: Application, ctx?: Partial<Context>)
|
|
|
101
100
|
throw err;
|
|
102
101
|
}
|
|
103
102
|
}
|
|
103
|
+
|
|
104
|
+
function matchesAllowedRoles(effectiveRoles: string[], allowedRoles?: string[] | null): boolean {
|
|
105
|
+
const normalized = normalizeRoleList(allowedRoles);
|
|
106
|
+
if (normalized.length === 0) {
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
if (effectiveRoles.length === 0) {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
return effectiveRoles.some((role) => normalized.includes(role));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function canAccessDataView(
|
|
116
|
+
app: Application,
|
|
117
|
+
ctx: Partial<Context> | undefined,
|
|
118
|
+
dataView: Pick<EsDataViewRecord, 'allowedRoles'>,
|
|
119
|
+
): boolean {
|
|
120
|
+
const userId = extractCurrentUserId(ctx);
|
|
121
|
+
if (userId === undefined || userId === null || String(userId).trim() === '') {
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
if (canManageReports(app, ctx)) {
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
return matchesAllowedRoles(getEffectiveRoles(ctx), dataView.allowedRoles);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function assertCanAccessDataView(
|
|
131
|
+
app: Application,
|
|
132
|
+
ctx: Partial<Context> | undefined,
|
|
133
|
+
dataView: Pick<EsDataViewRecord, 'allowedRoles'>,
|
|
134
|
+
): void {
|
|
135
|
+
assertAuthenticated(ctx);
|
|
136
|
+
if (!canAccessDataView(app, ctx, dataView)) {
|
|
137
|
+
const err = new Error('Permission denied: current role does not have access to this Data View') as Error & {
|
|
138
|
+
status?: number;
|
|
139
|
+
};
|
|
140
|
+
err.status = 403;
|
|
141
|
+
throw err;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function canAccessReport(
|
|
146
|
+
app: Application,
|
|
147
|
+
ctx: Partial<Context> | undefined,
|
|
148
|
+
report: Pick<EsReportRecord, 'published' | 'allowedRoles' | 'dataView'>,
|
|
149
|
+
dataView?: Pick<EsDataViewRecord, 'allowedRoles'> | null,
|
|
150
|
+
): boolean {
|
|
151
|
+
const userId = extractCurrentUserId(ctx);
|
|
152
|
+
if (userId === undefined || userId === null || String(userId).trim() === '') {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
if (canManageReports(app, ctx)) {
|
|
156
|
+
return true;
|
|
157
|
+
}
|
|
158
|
+
if (!report.published) {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
const effectiveRoles = getEffectiveRoles(ctx);
|
|
162
|
+
if (!matchesAllowedRoles(effectiveRoles, report.allowedRoles)) {
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
const targetDv = dataView ?? report.dataView;
|
|
166
|
+
if (targetDv && !matchesAllowedRoles(effectiveRoles, targetDv.allowedRoles)) {
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function assertCanAccessReport(
|
|
173
|
+
app: Application,
|
|
174
|
+
ctx: Partial<Context> | undefined,
|
|
175
|
+
report: Pick<EsReportRecord, 'published' | 'allowedRoles' | 'dataView'>,
|
|
176
|
+
dataView?: Pick<EsDataViewRecord, 'allowedRoles'> | null,
|
|
177
|
+
): void {
|
|
178
|
+
assertAuthenticated(ctx);
|
|
179
|
+
if (canManageReports(app, ctx)) {
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (!report.published) {
|
|
183
|
+
const notFound = new Error('Report not found') as Error & { status?: number };
|
|
184
|
+
notFound.status = 404;
|
|
185
|
+
throw notFound;
|
|
186
|
+
}
|
|
187
|
+
if (!canAccessReport(app, ctx, report, dataView)) {
|
|
188
|
+
const err = new Error('Permission denied: current role does not have access to this report') as Error & {
|
|
189
|
+
status?: number;
|
|
190
|
+
};
|
|
191
|
+
err.status = 403;
|
|
192
|
+
throw err;
|
|
193
|
+
}
|
|
194
|
+
}
|