@docupace/pipeline 1.0.122 → 1.0.123-xray.1

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.
@@ -0,0 +1,246 @@
1
+ import { describe, expect, jest, test } from '@jest/globals';
2
+ import { scanOne, runVeracodeScan, DEFAULT_WRAPPER_JAR } from './scan.js';
3
+
4
+ function makeFakeVeracode(overrides = {}) {
5
+ return {
6
+ download: jest.fn().mockResolvedValue({ ok: true }),
7
+ runBuildCmd: jest.fn().mockResolvedValue({ ok: true }),
8
+ zip: jest.fn().mockResolvedValue({ ok: true }),
9
+ uploadAndScan: jest.fn().mockResolvedValue({ ok: true }),
10
+ ...overrides,
11
+ };
12
+ }
13
+
14
+ function makeFakeFsops(overrides = {}) {
15
+ return {
16
+ exists: jest.fn().mockReturnValue(true),
17
+ mkdirp: jest.fn(),
18
+ removeSync: jest.fn(),
19
+ ...overrides,
20
+ };
21
+ }
22
+
23
+ const baseCtx = (overrides = {}) => ({
24
+ vid: 'vid-1',
25
+ vkey: 'vkey-1',
26
+ shortSha: 'abc1234',
27
+ wrapperJar: DEFAULT_WRAPPER_JAR,
28
+ veracode: makeFakeVeracode(),
29
+ fsops: makeFakeFsops(),
30
+ log: jest.fn(),
31
+ ...overrides,
32
+ });
33
+
34
+ describe('scanOne', () => {
35
+ test('zips, uploads and cleans up a normal target', async () => {
36
+ const veracode = makeFakeVeracode();
37
+ const fsops = makeFakeFsops();
38
+ const ctx = baseCtx({ veracode, fsops });
39
+
40
+ const result = await scanOne(
41
+ {
42
+ label: 'web',
43
+ slug: 'web',
44
+ appname: 'my-app',
45
+ paths: ['services/web'],
46
+ skipped: false,
47
+ },
48
+ ctx,
49
+ );
50
+
51
+ expect(result).toEqual({ label: 'web', slug: 'web', exitCode: 0 });
52
+ expect(veracode.zip).toHaveBeenCalledWith('veracode-web.zip', [
53
+ 'services/web',
54
+ ]);
55
+ expect(veracode.uploadAndScan).toHaveBeenCalledWith(
56
+ DEFAULT_WRAPPER_JAR,
57
+ expect.arrayContaining([
58
+ '-appname',
59
+ 'my-app',
60
+ '-version',
61
+ 'sha-abc1234-web',
62
+ ]),
63
+ );
64
+ expect(fsops.removeSync).toHaveBeenCalledWith('veracode-web.zip');
65
+ });
66
+
67
+ test('skips a target missing an appname or paths', async () => {
68
+ const veracode = makeFakeVeracode();
69
+ const ctx = baseCtx({ veracode });
70
+
71
+ const result = await scanOne(
72
+ { label: 'web', slug: 'web', appname: '', paths: [], skipped: true },
73
+ ctx,
74
+ );
75
+
76
+ expect(result).toEqual({ label: 'web', slug: 'web', exitCode: 1 });
77
+ expect(veracode.zip).not.toHaveBeenCalled();
78
+ });
79
+
80
+ test('returns exitCode 1 and skips upload when zipping fails', async () => {
81
+ const veracode = makeFakeVeracode({
82
+ zip: jest.fn().mockResolvedValue({ ok: false }),
83
+ });
84
+ const fsops = makeFakeFsops();
85
+ const ctx = baseCtx({ veracode, fsops });
86
+
87
+ const result = await scanOne(
88
+ {
89
+ label: 'web',
90
+ slug: 'web',
91
+ appname: 'my-app',
92
+ paths: ['services/web'],
93
+ skipped: false,
94
+ },
95
+ ctx,
96
+ );
97
+
98
+ expect(result).toEqual({ label: 'web', slug: 'web', exitCode: 1 });
99
+ expect(veracode.uploadAndScan).not.toHaveBeenCalled();
100
+ expect(fsops.removeSync).toHaveBeenCalledWith('veracode-web.zip');
101
+ });
102
+
103
+ test('returns exitCode 1 when the upload fails, but still cleans up the zip', async () => {
104
+ const veracode = makeFakeVeracode({
105
+ uploadAndScan: jest.fn().mockResolvedValue({ ok: false }),
106
+ });
107
+ const fsops = makeFakeFsops();
108
+ const ctx = baseCtx({ veracode, fsops });
109
+
110
+ const result = await scanOne(
111
+ {
112
+ label: 'web',
113
+ slug: 'web',
114
+ appname: 'my-app',
115
+ paths: ['services/web'],
116
+ skipped: false,
117
+ },
118
+ ctx,
119
+ );
120
+
121
+ expect(result).toEqual({ label: 'web', slug: 'web', exitCode: 1 });
122
+ expect(fsops.removeSync).toHaveBeenCalledWith('veracode-web.zip');
123
+ });
124
+ });
125
+
126
+ describe('runVeracodeScan', () => {
127
+ test('fails fast when credentials are missing', async () => {
128
+ const log = jest.fn();
129
+ const result = await runVeracodeScan({
130
+ vid: '',
131
+ vkey: '',
132
+ targetsEnv: 'web:my-app:src',
133
+ log,
134
+ });
135
+
136
+ expect(result).toEqual({ exitCode: 1, results: [] });
137
+ expect(log).toHaveBeenCalledWith(
138
+ expect.stringContaining('VERACODE_API_ID / VERACODE_API_KEY not set'),
139
+ );
140
+ });
141
+
142
+ test('fails fast when VERACODE_TARGETS is missing', async () => {
143
+ const log = jest.fn();
144
+ const result = await runVeracodeScan({
145
+ vid: 'vid-1',
146
+ vkey: 'vkey-1',
147
+ targetsEnv: '',
148
+ log,
149
+ });
150
+
151
+ expect(result).toEqual({ exitCode: 1, results: [] });
152
+ expect(log).toHaveBeenCalledWith(
153
+ expect.stringContaining('VERACODE_TARGETS not set'),
154
+ );
155
+ });
156
+
157
+ test('runs VERACODE_BUILD_CMD before packaging when set', async () => {
158
+ const veracode = makeFakeVeracode();
159
+ const fsops = makeFakeFsops();
160
+
161
+ await runVeracodeScan({
162
+ vid: 'vid-1',
163
+ vkey: 'vkey-1',
164
+ targetsEnv: 'web:my-app:src',
165
+ buildCmd: 'npm run build',
166
+ veracode,
167
+ fsops,
168
+ log: jest.fn(),
169
+ });
170
+
171
+ expect(veracode.runBuildCmd).toHaveBeenCalledWith('npm run build');
172
+ });
173
+
174
+ test('downloads the wrapper jar only when not already cached', async () => {
175
+ const veracode = makeFakeVeracode();
176
+ const fsops = makeFakeFsops({ exists: jest.fn().mockReturnValue(false) });
177
+
178
+ await runVeracodeScan({
179
+ vid: 'vid-1',
180
+ vkey: 'vkey-1',
181
+ targetsEnv: 'web:my-app:src',
182
+ veracode,
183
+ fsops,
184
+ log: jest.fn(),
185
+ });
186
+
187
+ expect(veracode.download).toHaveBeenCalledWith(
188
+ expect.stringContaining('vosp-api-wrappers-java'),
189
+ DEFAULT_WRAPPER_JAR,
190
+ );
191
+ });
192
+
193
+ test('skips the download when the wrapper jar already exists', async () => {
194
+ const veracode = makeFakeVeracode();
195
+ const fsops = makeFakeFsops({ exists: jest.fn().mockReturnValue(true) });
196
+
197
+ await runVeracodeScan({
198
+ vid: 'vid-1',
199
+ vkey: 'vkey-1',
200
+ targetsEnv: 'web:my-app:src',
201
+ veracode,
202
+ fsops,
203
+ log: jest.fn(),
204
+ });
205
+
206
+ expect(veracode.download).not.toHaveBeenCalled();
207
+ });
208
+
209
+ test('scans every target and reports the worst outcome', async () => {
210
+ const veracode = makeFakeVeracode({
211
+ uploadAndScan: jest
212
+ .fn()
213
+ .mockResolvedValueOnce({ ok: true })
214
+ .mockResolvedValueOnce({ ok: false }),
215
+ });
216
+ const fsops = makeFakeFsops();
217
+
218
+ const result = await runVeracodeScan({
219
+ vid: 'vid-1',
220
+ vkey: 'vkey-1',
221
+ targetsEnv: 'web:my-app:apps/web;worker:my-worker:apps/worker',
222
+ veracode,
223
+ fsops,
224
+ log: jest.fn(),
225
+ });
226
+
227
+ expect(result.results.map((r) => r.label)).toEqual(['web', 'worker']);
228
+ expect(result.exitCode).toBe(1);
229
+ });
230
+
231
+ test('exits 0 when every target scans successfully', async () => {
232
+ const veracode = makeFakeVeracode();
233
+ const fsops = makeFakeFsops();
234
+
235
+ const result = await runVeracodeScan({
236
+ vid: 'vid-1',
237
+ vkey: 'vkey-1',
238
+ targetsEnv: 'web:my-app:apps/web',
239
+ veracode,
240
+ fsops,
241
+ log: jest.fn(),
242
+ });
243
+
244
+ expect(result.exitCode).toBe(0);
245
+ });
246
+ });
@@ -0,0 +1,33 @@
1
+ import { $ } from 'zx';
2
+
3
+ // Thin wrappers around the external commands the Veracode step shells out to,
4
+ // so scan.js can inject a fake in tests. Every call uses nothrow: a non-zero
5
+ // exit is meaningful data here (a failed build/zip/upload), not an
6
+ // exceptional case.
7
+ export const veracode = {
8
+ async download(url, dest) {
9
+ const result = await $({
10
+ nothrow: true,
11
+ quiet: true,
12
+ })`curl -sSL ${url} -o ${dest}`;
13
+ return { ok: result.exitCode === 0 };
14
+ },
15
+
16
+ // Runs the consumer-supplied VERACODE_BUILD_CMD via `sh -c` so its own
17
+ // shell operators (&&, |, ...) are honored, mirroring the pipeline's
18
+ // `eval "${VERACODE_BUILD_CMD}"`.
19
+ async runBuildCmd(cmd) {
20
+ const result = await $({ nothrow: true })`sh -c ${cmd}`;
21
+ return { ok: result.exitCode === 0 };
22
+ },
23
+
24
+ async zip(zipFile, paths) {
25
+ const result = await $({ nothrow: true })`zip -r ${zipFile} ${paths}`;
26
+ return { ok: result.exitCode === 0 };
27
+ },
28
+
29
+ async uploadAndScan(jarPath, args) {
30
+ const result = await $({ nothrow: true })`java -jar ${jarPath} ${args}`;
31
+ return { ok: result.exitCode === 0 };
32
+ },
33
+ };
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from 'commander';
4
+ import { notify } from './notify.js';
5
+
6
+ const program = new Command();
7
+
8
+ program
9
+ .command('notify')
10
+ .description(
11
+ 'Post Xray findings to Slack (parent summary + one thread reply per finding)',
12
+ )
13
+ .option(
14
+ '-f, --report-args-file <path>',
15
+ 'Path to the "label:file" report-args file',
16
+ )
17
+ .option(
18
+ '-m, --min-severity <severity>',
19
+ 'Lowest severity to thread (Critical|High|Medium|Low)',
20
+ )
21
+ .option('-c, --notify-clean', 'Post even when there are zero findings')
22
+ .action(async (options) => {
23
+ try {
24
+ await notify({
25
+ ...(options.reportArgsFile && {
26
+ reportArgsFile: options.reportArgsFile,
27
+ }),
28
+ ...(options.minSeverity && { minSeverity: options.minSeverity }),
29
+ ...(options.notifyClean && { notifyClean: true }),
30
+ });
31
+ } catch (error) {
32
+ console.error(error.message);
33
+ process.exit(1);
34
+ }
35
+ });
36
+
37
+ program.parse(process.argv);
@@ -0,0 +1,107 @@
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
+ }
@@ -0,0 +1,161 @@
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
+ });