@docupace/pipeline 1.0.123-xray.2 → 1.0.123

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.
@@ -1,107 +0,0 @@
1
- import fs from 'fs';
2
- import {
3
- extractFindings,
4
- countBySeverity,
5
- buildBuildLink,
6
- buildParentPayload,
7
- buildThreadPayload,
8
- parseReportArgs,
9
- rankOf,
10
- sortBySeverity,
11
- } from './report.js';
12
- import { postMessage } from './slack.js';
13
-
14
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
15
-
16
- // Orchestrates the full bin/xray.sh flow: read the report-args file, collect
17
- // findings from each simple-json scan file, post a Slack summary, then thread
18
- // one message per finding at or above minSeverity. Dependencies are
19
- // injectable so this can be unit tested without touching fs or the network.
20
- export async function notify({
21
- reportArgsFile = process.env.XRAY_REPORT_ARGS_FILE || '/tmp/xray-report-args',
22
- minSeverity = process.env.XRAY_SLACK_MIN_SEVERITY || 'High',
23
- notifyClean = process.env.XRAY_SLACK_NOTIFY_CLEAN === 'true',
24
- channel = process.env.XRAY_SLACK_CHANNEL,
25
- token = process.env.XRAY_SLACK_TOKEN,
26
- project = process.env.BITBUCKET_REPO_SLUG || 'unknown',
27
- branch = process.env.BITBUCKET_BRANCH || '',
28
- buildLink = buildBuildLink({
29
- workspace: process.env.BITBUCKET_WORKSPACE,
30
- repoSlug: process.env.BITBUCKET_REPO_SLUG,
31
- buildNumber: process.env.BITBUCKET_BUILD_NUMBER,
32
- }),
33
- readFile = (path) => fs.readFileSync(path, 'utf8'),
34
- post = postMessage,
35
- log = console.log,
36
- delay = sleep,
37
- } = {}) {
38
- const minRank = rankOf(minSeverity);
39
-
40
- let reportArgsContent;
41
- try {
42
- reportArgsContent = readFile(reportArgsFile);
43
- } catch {
44
- log(
45
- `No scan results file at ${reportArgsFile} — skipping Slack notification.`,
46
- );
47
- return { posted: 0, skipped: true };
48
- }
49
-
50
- const findings = [];
51
- for (const { label, file } of parseReportArgs(reportArgsContent)) {
52
- let raw;
53
- try {
54
- raw = readFile(file);
55
- } catch {
56
- log(`Skipping ${label} (${file}): not produced or empty.`);
57
- continue;
58
- }
59
- let data;
60
- try {
61
- data = JSON.parse(raw);
62
- } catch {
63
- log(`Skipping ${label} (${file}): not produced or empty.`);
64
- continue;
65
- }
66
- findings.push(...extractFindings(data, label));
67
- }
68
-
69
- const counts = countBySeverity(findings);
70
- log(
71
- `📊 Counts: Critical=${counts.Critical}, High=${counts.High}, Medium=${counts.Medium}, Low=${counts.Low}, Total=${counts.total}`,
72
- );
73
-
74
- if (counts.total === 0 && !notifyClean) {
75
- log('✅ No vulnerabilities found, skipping Slack notification.');
76
- return { posted: 0, skipped: true };
77
- }
78
-
79
- const parentPayload = buildParentPayload({
80
- channel,
81
- project,
82
- branch,
83
- buildLink,
84
- counts,
85
- });
86
- const parentResponse = await post(parentPayload, token);
87
- const threadTs = parentResponse?.ts;
88
-
89
- if (!threadTs) {
90
- log('❌ Failed to create parent Slack message:');
91
- log(JSON.stringify(parentResponse));
92
- throw new Error('Failed to create parent Slack message');
93
- }
94
-
95
- log(`✅ Parent message created. thread_ts=${threadTs}`);
96
-
97
- let posted = 0;
98
- for (const finding of sortBySeverity(findings)) {
99
- if (finding.rank > minRank) continue;
100
- await post(buildThreadPayload({ channel, threadTs, finding }), token);
101
- posted += 1;
102
- await delay(100);
103
- }
104
-
105
- log(`✅ Posted ${posted} finding(s) to thread.`);
106
- return { posted, skipped: false, threadTs };
107
- }
@@ -1,161 +0,0 @@
1
- import { describe, expect, jest, test } from '@jest/globals';
2
- import { notify } from './notify.js';
3
-
4
- function makeReadFile(files) {
5
- return (path) => {
6
- if (!(path in files)) {
7
- const err = new Error(`ENOENT: ${path}`);
8
- err.code = 'ENOENT';
9
- throw err;
10
- }
11
- return files[path];
12
- };
13
- }
14
-
15
- describe('notify', () => {
16
- test('skips Slack entirely when the report-args file is missing', async () => {
17
- const log = jest.fn();
18
- const post = jest.fn();
19
- const result = await notify({
20
- reportArgsFile: '/tmp/does-not-exist',
21
- readFile: makeReadFile({}),
22
- post,
23
- log,
24
- delay: jest.fn(),
25
- });
26
-
27
- expect(result).toEqual({ posted: 0, skipped: true });
28
- expect(post).not.toHaveBeenCalled();
29
- expect(log).toHaveBeenCalledWith(
30
- expect.stringContaining('No scan results file'),
31
- );
32
- });
33
-
34
- test('skips a scan file that is missing or invalid JSON, continues with the rest', async () => {
35
- const files = {
36
- '/tmp/report-args':
37
- 'bad:xray-report/bad.json\ngood:xray-report/good.json\n',
38
- 'xray-report/bad.json': 'not json',
39
- 'xray-report/good.json': JSON.stringify({
40
- vulnerabilities: [{ severity: 'Critical', issueId: 'X-1' }],
41
- }),
42
- };
43
- const post = jest.fn().mockResolvedValue({ ts: '111.222' });
44
- const log = jest.fn();
45
-
46
- const result = await notify({
47
- reportArgsFile: '/tmp/report-args',
48
- readFile: makeReadFile(files),
49
- post,
50
- log,
51
- delay: jest.fn(),
52
- channel: '#c',
53
- token: 'xoxb-x',
54
- });
55
-
56
- expect(log).toHaveBeenCalledWith(expect.stringContaining('Skipping bad'));
57
- expect(result.posted).toBe(1);
58
- });
59
-
60
- test('does not notify Slack when there are zero findings and notifyClean is false', async () => {
61
- const files = {
62
- '/tmp/report-args': 'clean:xray-report/clean.json\n',
63
- 'xray-report/clean.json': JSON.stringify({}),
64
- };
65
- const post = jest.fn();
66
-
67
- const result = await notify({
68
- reportArgsFile: '/tmp/report-args',
69
- readFile: makeReadFile(files),
70
- post,
71
- log: jest.fn(),
72
- delay: jest.fn(),
73
- notifyClean: false,
74
- });
75
-
76
- expect(result).toEqual({ posted: 0, skipped: true });
77
- expect(post).not.toHaveBeenCalled();
78
- });
79
-
80
- test('posts a clean parent message when notifyClean is true even with zero findings', async () => {
81
- const files = {
82
- '/tmp/report-args': 'clean:xray-report/clean.json\n',
83
- 'xray-report/clean.json': JSON.stringify({}),
84
- };
85
- const post = jest.fn().mockResolvedValue({ ts: '111.222' });
86
-
87
- const result = await notify({
88
- reportArgsFile: '/tmp/report-args',
89
- readFile: makeReadFile(files),
90
- post,
91
- log: jest.fn(),
92
- delay: jest.fn(),
93
- notifyClean: true,
94
- channel: '#c',
95
- token: 'xoxb-x',
96
- });
97
-
98
- expect(post).toHaveBeenCalledTimes(1);
99
- expect(result).toEqual({ posted: 0, skipped: false, threadTs: '111.222' });
100
- });
101
-
102
- test('throws when Slack fails to create the parent message', async () => {
103
- const files = {
104
- '/tmp/report-args': 'scan:xray-report/x.json\n',
105
- 'xray-report/x.json': JSON.stringify({
106
- vulnerabilities: [{ severity: 'Critical' }],
107
- }),
108
- };
109
- const post = jest
110
- .fn()
111
- .mockResolvedValue({ ok: false, error: 'invalid_auth' });
112
-
113
- await expect(
114
- notify({
115
- reportArgsFile: '/tmp/report-args',
116
- readFile: makeReadFile(files),
117
- post,
118
- log: jest.fn(),
119
- delay: jest.fn(),
120
- }),
121
- ).rejects.toThrow('Failed to create parent Slack message');
122
- });
123
-
124
- test('only threads findings at or above minSeverity, sorted Critical -> Low', async () => {
125
- const files = {
126
- '/tmp/report-args': 'scan:xray-report/x.json\n',
127
- 'xray-report/x.json': JSON.stringify({
128
- vulnerabilities: [
129
- { severity: 'Low', issueId: 'L-1' },
130
- { severity: 'Critical', issueId: 'C-1' },
131
- { severity: 'Medium', issueId: 'M-1' },
132
- ],
133
- }),
134
- };
135
- const post = jest
136
- .fn()
137
- .mockResolvedValueOnce({ ts: '111.222' }) // parent
138
- .mockResolvedValue({ ts: '111.222' }); // thread replies
139
- const delay = jest.fn().mockResolvedValue();
140
-
141
- const result = await notify({
142
- reportArgsFile: '/tmp/report-args',
143
- readFile: makeReadFile(files),
144
- post,
145
- log: jest.fn(),
146
- delay,
147
- minSeverity: 'Medium',
148
- channel: '#c',
149
- token: 'xoxb-x',
150
- });
151
-
152
- // parent + Critical + Medium, Low excluded
153
- expect(post).toHaveBeenCalledTimes(3);
154
- expect(result.posted).toBe(2);
155
- const threadedIds = post.mock.calls
156
- .slice(1)
157
- .map(([payload]) => payload.blocks[0].text.text);
158
- expect(threadedIds[0]).toContain('*Critical*');
159
- expect(threadedIds[1]).toContain('*Medium*');
160
- });
161
- });
@@ -1,194 +0,0 @@
1
- // Pure parsing/formatting logic for Xray findings, ported from bin/xray.sh's
2
- // jq pipeline. Kept dependency-free (no fs/network) so it's unit-testable.
3
-
4
- const SEVERITY_RANK = { Critical: 0, High: 1, Medium: 2, Low: 3 };
5
-
6
- export function rankOf(severity) {
7
- return SEVERITY_RANK[severity] ?? 9;
8
- }
9
-
10
- const SCA_SECTIONS = [
11
- ['vulnerabilities', 'Vulnerability'],
12
- ['securityViolations', 'Security violation'],
13
- ['licensesViolations', 'License violation'],
14
- ['operationalRiskViolations', 'Operational risk'],
15
- ];
16
-
17
- const CODE_SECTIONS = [
18
- ['secrets', 'Secret'],
19
- ['secretsViolations', 'Secret violation'],
20
- ['sast', 'SAST'],
21
- ['sastViolations', 'SAST violation'],
22
- ['iac', 'IaC'],
23
- ['iacViolations', 'IaC violation'],
24
- ['maliciousCode', 'Malicious code'],
25
- ];
26
-
27
- function scaRow(row, scan, kind) {
28
- const severity = row.severity ?? 'Unknown';
29
- const cvesAll = (row.cves ?? []).map((c) => c.cve).filter(Boolean);
30
- return {
31
- scan,
32
- kind,
33
- severity,
34
- rank: rankOf(severity),
35
- cve: cvesAll[0] ?? row.issueId ?? 'N/A',
36
- cvesAll,
37
- pkg: `${row.impactedPackageName ?? 'N/A'} ${row.impactedPackageVersion ?? ''}`,
38
- fixed: (row.fixedVersions ?? []).join(', '),
39
- directs: [
40
- ...new Set((row.components ?? []).map((c) => c.name).filter(Boolean)),
41
- ].join(', '),
42
- path: '',
43
- line: 0,
44
- };
45
- }
46
-
47
- function codeRow(row, scan, kind) {
48
- const severity = row.severity ?? 'Unknown';
49
- return {
50
- scan,
51
- kind,
52
- severity,
53
- rank: rankOf(severity),
54
- cve: row.ruleId ?? 'N/A',
55
- cvesAll: [],
56
- pkg: row.finding ?? row.scannerShortDescription ?? 'N/A',
57
- fixed: '',
58
- directs: '',
59
- path: row.file ?? '',
60
- line: row.startLine ?? 0,
61
- };
62
- }
63
-
64
- // Flattens one simple-json scan report into the same per-finding record shape
65
- // bin/xray.sh's jq filter produced (one row per vulnerability/secret/etc).
66
- export function extractFindings(data, scanLabel) {
67
- const findings = [];
68
- for (const [key, kind] of SCA_SECTIONS) {
69
- for (const row of data[key] ?? []) {
70
- findings.push(scaRow(row, scanLabel, kind));
71
- }
72
- }
73
- for (const [key, kind] of CODE_SECTIONS) {
74
- for (const row of data[key] ?? []) {
75
- findings.push(codeRow(row, scanLabel, kind));
76
- }
77
- }
78
- return findings;
79
- }
80
-
81
- // Only Critical/High/Medium/Low are counted, matching the bash script's
82
- // count_sev — an "Unknown" severity finding is neither counted nor totaled.
83
- export function countBySeverity(findings) {
84
- const counts = { Critical: 0, High: 0, Medium: 0, Low: 0 };
85
- for (const f of findings) {
86
- if (f.severity in counts) counts[f.severity] += 1;
87
- }
88
- const total = counts.Critical + counts.High + counts.Medium + counts.Low;
89
- return { ...counts, total };
90
- }
91
-
92
- export function buildBuildLink({ workspace, repoSlug, buildNumber }) {
93
- if (!workspace || !repoSlug || !buildNumber) return '';
94
- return `https://bitbucket.org/${workspace}/${repoSlug}/pipelines/results/${buildNumber}`;
95
- }
96
-
97
- export function buildParentPayload({
98
- channel,
99
- project,
100
- branch,
101
- buildLink,
102
- counts,
103
- }) {
104
- const contextText = buildLink
105
- ? `Detailed findings are in the thread below 👇 • <${buildLink}|Pipeline run>`
106
- : 'Detailed findings are in the thread below 👇';
107
-
108
- return {
109
- channel,
110
- blocks: [
111
- {
112
- type: 'header',
113
- text: { type: 'plain_text', text: '🚨 Xray Security Report' },
114
- },
115
- {
116
- type: 'section',
117
- text: {
118
- type: 'mrkdwn',
119
- text: `*Project:* ${project}${branch ? ` | *Branch:* ${branch}` : ''}`,
120
- },
121
- },
122
- {
123
- type: 'section',
124
- text: {
125
- type: 'mrkdwn',
126
- text: `🔴 *Critical:* ${counts.Critical} 🔥 *High:* ${counts.High} 🎃 *Medium:* ${counts.Medium} 👻 *Low:* ${counts.Low}`,
127
- },
128
- },
129
- { type: 'context', elements: [{ type: 'mrkdwn', text: contextText }] },
130
- { type: 'divider' },
131
- ],
132
- };
133
- }
134
-
135
- const SEVERITY_EMOJI = { Critical: '🔴', High: '🔥', Medium: '🎃' };
136
- const DEFAULT_EMOJI = '👻';
137
- const CVE_PATTERN = /^CVE-/;
138
-
139
- function nvdLink(id) {
140
- return `<https://nvd.nist.gov/vuln/detail/${id}|${id}>`;
141
- }
142
-
143
- function idText(finding) {
144
- if (finding.cvesAll.length > 0) {
145
- return finding.cvesAll.map(nvdLink).join(', ');
146
- }
147
- return CVE_PATTERN.test(finding.cve) ? nvdLink(finding.cve) : finding.cve;
148
- }
149
-
150
- export function buildFindingText(finding) {
151
- const emoji = SEVERITY_EMOJI[finding.severity] ?? DEFAULT_EMOJI;
152
- let text =
153
- `${emoji} *${finding.severity}* — ${finding.scan} (${finding.kind})` +
154
- `\n*ID:* ${idText(finding)}` +
155
- `\n*Component:* \`${finding.pkg}\``;
156
- if (finding.fixed) text += `\n*Fixed in:* ${finding.fixed}`;
157
- if (finding.directs) text += `\n*Via:* ${finding.directs}`;
158
- if (finding.path) {
159
- text += `\n*File:* \`${finding.path}${finding.line > 0 ? `:${finding.line}` : ''}\``;
160
- }
161
- return text;
162
- }
163
-
164
- export function buildThreadPayload({ channel, threadTs, finding }) {
165
- return {
166
- channel,
167
- thread_ts: threadTs,
168
- blocks: [
169
- {
170
- type: 'section',
171
- text: { type: 'mrkdwn', text: buildFindingText(finding) },
172
- },
173
- ],
174
- };
175
- }
176
-
177
- // Parses the "label:file" lines written by the scan step (one per completed
178
- // scan) into { label, file } pairs. Blank lines are skipped.
179
- export function parseReportArgs(content) {
180
- return content
181
- .split('\n')
182
- .map((line) => line.trim())
183
- .filter(Boolean)
184
- .map((line) => {
185
- const idx = line.indexOf(':');
186
- return idx === -1
187
- ? { label: line, file: '' }
188
- : { label: line.slice(0, idx), file: line.slice(idx + 1) };
189
- });
190
- }
191
-
192
- export function sortBySeverity(findings) {
193
- return [...findings].sort((a, b) => a.rank - b.rank);
194
- }