@shieldaai/security-watch 1.0.1 → 1.1.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.
- package/CHANGELOG.md +32 -0
- package/README.md +79 -38
- package/SECURITY.md +3 -2
- package/dist/cli.js +356 -32
- package/dist/config.d.ts +10 -0
- package/dist/config.js +56 -0
- package/dist/index.d.ts +7 -1
- package/dist/index.js +4 -1
- package/dist/intake.d.ts +36 -0
- package/dist/intake.js +341 -0
- package/dist/inventory.d.ts +16 -0
- package/dist/inventory.js +129 -5
- package/dist/manifests.d.ts +67 -0
- package/dist/manifests.js +1193 -0
- package/dist/sbom.d.ts +16 -1
- package/dist/sbom.js +156 -5
- package/dist/sources.js +45 -3
- package/dist/types.d.ts +18 -1
- package/dist/upload.d.ts +21 -0
- package/dist/upload.js +76 -0
- package/docs/compatibility.md +10 -10
- package/docs/configuration.md +27 -3
- package/docs/offline-advisory-preview.md +2 -2
- package/docs/sbom.md +266 -0
- package/package.json +9 -5
package/dist/cli.js
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { parseArgs } from 'node:util';
|
|
3
|
-
import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, } from 'node:fs';
|
|
4
|
-
import { dirname, extname, join, resolve } from 'node:path';
|
|
3
|
+
import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
|
|
4
|
+
import { basename, dirname, extname, join, resolve } from 'node:path';
|
|
5
5
|
import { createInterface } from 'node:readline/promises';
|
|
6
6
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
7
7
|
import { stringify } from 'yaml';
|
|
8
8
|
import { z } from 'zod';
|
|
9
9
|
import { loadConfig, parseConfig, missingCredentials } from './config.js';
|
|
10
10
|
import { loadInventory } from './inventory.js';
|
|
11
|
-
import {
|
|
11
|
+
import { importSbom } from './sbom.js';
|
|
12
|
+
import { DEPENDENCY_FILES, generateSbom } from './manifests.js';
|
|
13
|
+
import { intakeDirectory, startIntake } from './intake.js';
|
|
14
|
+
import { uploadSbom } from './upload.js';
|
|
12
15
|
import { refreshCoverage } from './coverage.js';
|
|
13
16
|
import { Store, readPilotReport } from './store.js';
|
|
14
17
|
import { PilotReportError } from './pilot-report.js';
|
|
@@ -60,7 +63,13 @@ function firstScanNotice(config, store, offline) {
|
|
|
60
63
|
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
61
64
|
const help = `Shielda Security Watch ${VERSION}
|
|
62
65
|
|
|
63
|
-
security-watch
|
|
66
|
+
security-watch sbom [--project PATH] [--output FILE.cdx.json] [--name NAME] [--system-id ID]
|
|
67
|
+
[--owner TEXT] [--environment TEXT] [--note TEXT] [--exposure internet|internal|unknown]
|
|
68
|
+
[--criticality low|medium|high|critical] [--production] [--source-url URL] [--source-revision REV]
|
|
69
|
+
[--upload URL [--token-env NAME] [--allow-http]]
|
|
70
|
+
security-watch upload --input FILE.json --url URL [--system-id ID] [--token-env NAME] [--allow-http]
|
|
71
|
+
security-watch intake [--config PATH] [--credentials-file PATH]
|
|
72
|
+
security-watch init [--directory PATH] [--yes] [--project PATH ...] [--systems nodejs,python]
|
|
64
73
|
[--libraries PATH --ecosystem php] [--vendor-feeds nodejs,python,php] [--heartbeat]
|
|
65
74
|
[--provider NAME --model ID] [--endpoint URL] [--allow-private-endpoint]
|
|
66
75
|
[--poll-minutes 30] [--lookback-minutes 40]
|
|
@@ -69,7 +78,7 @@ const help = `Shielda Security Watch ${VERSION}
|
|
|
69
78
|
security-watch providers
|
|
70
79
|
security-watch templates
|
|
71
80
|
security-watch ecosystems
|
|
72
|
-
security-watch import-sbom --input PATH [--output PATH]
|
|
81
|
+
security-watch import-sbom --input PATH [--output PATH] (CycloneDX or SPDX JSON)
|
|
73
82
|
security-watch coverage | inventory-drift [--config PATH]
|
|
74
83
|
security-watch normalize-libraries --input PATH [--ecosystem php] [--output PATH]
|
|
75
84
|
security-watch scan [--dry-run] [--notify] [--fixture PATH] [--no-ai]
|
|
@@ -95,6 +104,12 @@ const help = `Shielda Security Watch ${VERSION}
|
|
|
95
104
|
security-watch unlock (only removes a stopped worker's lock)
|
|
96
105
|
security-watch test-notification --channel slack|email
|
|
97
106
|
|
|
107
|
+
sbom reads the lockfiles and manifests in a project (npm, Python, Go, Rust, PHP, Ruby, Java,
|
|
108
|
+
.NET, Dart, Elixir, Swift, Haskell) and writes a CycloneDX SBOM. It runs nothing and sends nothing.
|
|
109
|
+
init --project creates a monitor for that project in one step. With an intake section in the
|
|
110
|
+
configuration, start also receives SBOMs from CI (sbom --upload, upload); intake runs only that.
|
|
111
|
+
Upload tokens are read from SECURITY_WATCH_INTAKE_TOKEN unless --token-env names another variable.
|
|
112
|
+
|
|
98
113
|
Default config: ./security-watch.yaml. scan records findings; --dry-run writes no state,
|
|
99
114
|
disables models and sends nothing. --notify sends due jobs. start runs the foreground scheduler and
|
|
100
115
|
configured notification routes. Model/feed requests can leave this machine; fixture
|
|
@@ -149,6 +164,21 @@ function argumentsFromCommandLine() {
|
|
|
149
164
|
help: { type: 'boolean' },
|
|
150
165
|
version: { type: 'boolean' },
|
|
151
166
|
'scan-only': { type: 'boolean' },
|
|
167
|
+
project: { type: 'string', multiple: true },
|
|
168
|
+
name: { type: 'string' },
|
|
169
|
+
'system-id': { type: 'string' },
|
|
170
|
+
owner: { type: 'string' },
|
|
171
|
+
environment: { type: 'string' },
|
|
172
|
+
note: { type: 'string' },
|
|
173
|
+
exposure: { type: 'string' },
|
|
174
|
+
criticality: { type: 'string' },
|
|
175
|
+
production: { type: 'boolean' },
|
|
176
|
+
'source-url': { type: 'string' },
|
|
177
|
+
'source-revision': { type: 'string' },
|
|
178
|
+
upload: { type: 'string' },
|
|
179
|
+
url: { type: 'string' },
|
|
180
|
+
'token-env': { type: 'string' },
|
|
181
|
+
'allow-http': { type: 'boolean' },
|
|
152
182
|
},
|
|
153
183
|
});
|
|
154
184
|
}
|
|
@@ -187,6 +217,198 @@ function libraryInput(path, ecosystem) {
|
|
|
187
217
|
throw new Error('Provide between 1 and 20000 libraries.');
|
|
188
218
|
return components;
|
|
189
219
|
}
|
|
220
|
+
/** The repository a CI job runs for, from the variables GitHub Actions and GitLab CI set. */
|
|
221
|
+
function ciSource(env) {
|
|
222
|
+
let url;
|
|
223
|
+
let revision;
|
|
224
|
+
if (env.GITHUB_ACTIONS === 'true' && env.GITHUB_REPOSITORY) {
|
|
225
|
+
url = `${env.GITHUB_SERVER_URL ?? 'https://github.com'}/${env.GITHUB_REPOSITORY}`;
|
|
226
|
+
revision = env.GITHUB_SHA;
|
|
227
|
+
}
|
|
228
|
+
else if (env.GITLAB_CI === 'true' && env.CI_PROJECT_URL) {
|
|
229
|
+
url = env.CI_PROJECT_URL;
|
|
230
|
+
revision = env.CI_COMMIT_SHA;
|
|
231
|
+
}
|
|
232
|
+
if (!url)
|
|
233
|
+
return {};
|
|
234
|
+
try {
|
|
235
|
+
const parsed = new URL(url);
|
|
236
|
+
if (parsed.protocol !== 'https:' || parsed.username || parsed.password || parsed.search || parsed.hash)
|
|
237
|
+
return {};
|
|
238
|
+
return {
|
|
239
|
+
url: parsed.href.replace(/\/$/, ''),
|
|
240
|
+
repository: parsed.pathname.replace(/^\/|\/$/g, ''),
|
|
241
|
+
...(revision && /^[A-Za-z0-9._-]{1,100}$/.test(revision) ? { revision } : {}),
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
return {};
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
function oneOf(flag, value, allowed) {
|
|
249
|
+
if (value === undefined)
|
|
250
|
+
return undefined;
|
|
251
|
+
if (!allowed.includes(value))
|
|
252
|
+
throw new Error(`--${flag} must be one of: ${allowed.join(', ')}.`);
|
|
253
|
+
return value;
|
|
254
|
+
}
|
|
255
|
+
function sbomOptions(project) {
|
|
256
|
+
const ci = ciSource(process.env);
|
|
257
|
+
const sourceUrl = values['source-url'] ?? ci.url;
|
|
258
|
+
const sourceRevision = values['source-revision'] ?? (values['source-url'] ? undefined : ci.revision);
|
|
259
|
+
const note = values.note ?? (ci.repository && !values['source-url'] ? `repository ${ci.repository}` : undefined);
|
|
260
|
+
return {
|
|
261
|
+
project,
|
|
262
|
+
...(values.name ? { name: values.name } : {}),
|
|
263
|
+
...(values['system-id'] ? { systemId: values['system-id'] } : {}),
|
|
264
|
+
...(values.owner ? { owner: values.owner } : {}),
|
|
265
|
+
...(values.environment ? { environment: values.environment } : {}),
|
|
266
|
+
...(note ? { note } : {}),
|
|
267
|
+
...(values.exposure
|
|
268
|
+
? { exposure: oneOf('exposure', values.exposure, ['internet', 'internal', 'unknown']) }
|
|
269
|
+
: {}),
|
|
270
|
+
...(values.criticality
|
|
271
|
+
? {
|
|
272
|
+
criticality: oneOf('criticality', values.criticality, [
|
|
273
|
+
'unknown',
|
|
274
|
+
'low',
|
|
275
|
+
'medium',
|
|
276
|
+
'high',
|
|
277
|
+
'critical',
|
|
278
|
+
]),
|
|
279
|
+
}
|
|
280
|
+
: {}),
|
|
281
|
+
...(sourceUrl ? { sourceUrl } : {}),
|
|
282
|
+
...(sourceRevision ? { sourceRevision } : {}),
|
|
283
|
+
...(values.production ? { production: true } : {}),
|
|
284
|
+
toolVersion: VERSION,
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
const SUPPORTED_FILES = Object.values(DEPENDENCY_FILES).flat().join(', ');
|
|
288
|
+
/** Builds an SBOM and refuses one with no packages: an empty SBOM would look like a clean result. */
|
|
289
|
+
function buildSbom(project) {
|
|
290
|
+
const result = generateSbom(sbomOptions(project));
|
|
291
|
+
if (!result.packages)
|
|
292
|
+
throw new Error(`No packages found in ${resolve(project)}${result.files.length ? ` (read ${result.files.map((file) => file.path).join(', ')})` : ''}. Supported files: ${SUPPORTED_FILES}. For container images and other inputs, use Trivy or Syft; see docs/sbom.md.`);
|
|
293
|
+
return result;
|
|
294
|
+
}
|
|
295
|
+
function sbomSummary(result, destination, shown = Infinity) {
|
|
296
|
+
const files = result.files.filter((file) => file.packages);
|
|
297
|
+
const lines = [
|
|
298
|
+
`${result.system.name}: ${result.packages} package${result.packages === 1 ? '' : 's'} (${result.ecosystems.join(', ')}) from ${files.length} file${files.length === 1 ? '' : 's'}: ${files
|
|
299
|
+
.slice(0, 8)
|
|
300
|
+
.map((file) => file.path)
|
|
301
|
+
.join(', ')}${files.length > 8 ? `, and ${files.length - 8} more` : ''}.`,
|
|
302
|
+
];
|
|
303
|
+
if (result.unversioned)
|
|
304
|
+
lines.push(`${result.unversioned} package${result.unversioned === 1 ? ' has' : 's have'} no exact version and ${result.unversioned === 1 ? 'is' : 'are'} watched by name only.`);
|
|
305
|
+
for (const warning of result.warnings.slice(0, shown))
|
|
306
|
+
lines.push(`warning: ${warning}`);
|
|
307
|
+
if (result.warnings.length > shown)
|
|
308
|
+
lines.push(`warning: ${result.warnings.length - shown} more; security-watch sbom --project lists them all.`);
|
|
309
|
+
if (destination)
|
|
310
|
+
lines.push(`Wrote ${destination}.`);
|
|
311
|
+
return lines.join('\n');
|
|
312
|
+
}
|
|
313
|
+
/** Replaces the destination in one step, so a reader never sees half a file. */
|
|
314
|
+
function replaceFile(destination, content) {
|
|
315
|
+
mkdirSync(dirname(destination), { recursive: true });
|
|
316
|
+
const directory = mkdtempSync(join(dirname(destination), '.security-watch-'));
|
|
317
|
+
try {
|
|
318
|
+
const staged = join(directory, 'sbom.json');
|
|
319
|
+
writeFileSync(staged, content, { flag: 'wx' });
|
|
320
|
+
renameSync(staged, destination);
|
|
321
|
+
}
|
|
322
|
+
finally {
|
|
323
|
+
rmSync(directory, { recursive: true, force: true });
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
/** The system an SBOM file is for: its `security-watch:system-id` property, else the file name. */
|
|
327
|
+
function systemIdOf(body, path) {
|
|
328
|
+
try {
|
|
329
|
+
const document = JSON.parse(body.toString('utf8'));
|
|
330
|
+
const property = document.metadata?.properties?.find((entry) => entry?.name === 'security-watch:system-id' && typeof entry.value === 'string');
|
|
331
|
+
if (property)
|
|
332
|
+
return property.value;
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
// The intake reports an unreadable SBOM; the file name still names the system.
|
|
336
|
+
}
|
|
337
|
+
return basename(path).replace(/(?:\.(?:cdx|spdx|bom|sbom|cyclonedx))?\.json$/i, '');
|
|
338
|
+
}
|
|
339
|
+
async function sendSbom(body, systemId) {
|
|
340
|
+
const tokenEnv = values['token-env'] ?? 'SECURITY_WATCH_INTAKE_TOKEN';
|
|
341
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(tokenEnv))
|
|
342
|
+
throw new Error('--token-env must name an environment variable.');
|
|
343
|
+
const token = process.env[tokenEnv];
|
|
344
|
+
if (!token)
|
|
345
|
+
throw new Error(`Set ${tokenEnv} to the intake upload token.`);
|
|
346
|
+
const url = values.upload ?? values.url;
|
|
347
|
+
const result = await uploadSbom({
|
|
348
|
+
url,
|
|
349
|
+
systemId,
|
|
350
|
+
body,
|
|
351
|
+
token,
|
|
352
|
+
...(values['allow-http'] ? { allowHttp: true } : {}),
|
|
353
|
+
});
|
|
354
|
+
console.error(`Uploaded ${result.system_id}: ${result.packages} package${result.packages === 1 ? '' : 's'} will be watched from the next scan${result.warnings
|
|
355
|
+
? ` (${result.warnings} warning${result.warnings === 1 ? '' : 's'}, for example: ${result.warning_examples[0]})`
|
|
356
|
+
: ''}.`);
|
|
357
|
+
}
|
|
358
|
+
async function writeSbom() {
|
|
359
|
+
if ((values.project?.length ?? 0) > 1)
|
|
360
|
+
throw new Error('sbom takes one --project; run it once per project.');
|
|
361
|
+
if ((values['token-env'] || values['allow-http']) && !values.upload)
|
|
362
|
+
throw new Error('--token-env and --allow-http apply to --upload.');
|
|
363
|
+
const result = buildSbom(values.project?.[0] ?? '.');
|
|
364
|
+
const content = JSON.stringify(result.bom, null, 2) + '\n';
|
|
365
|
+
if (values.upload) {
|
|
366
|
+
if (values.output) {
|
|
367
|
+
const destination = resolve(values.output);
|
|
368
|
+
if (existsSync(destination) && !statSync(destination).isFile())
|
|
369
|
+
throw new Error('--output must name a file.');
|
|
370
|
+
replaceFile(destination, content);
|
|
371
|
+
console.error(sbomSummary(result, destination));
|
|
372
|
+
}
|
|
373
|
+
else
|
|
374
|
+
console.error(sbomSummary(result));
|
|
375
|
+
await sendSbom(content, result.system.id);
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
if (values.output) {
|
|
379
|
+
const destination = resolve(values.output);
|
|
380
|
+
if (existsSync(destination) && !statSync(destination).isFile())
|
|
381
|
+
throw new Error('--output must name a file.');
|
|
382
|
+
replaceFile(destination, content);
|
|
383
|
+
console.error(sbomSummary(result, destination));
|
|
384
|
+
}
|
|
385
|
+
else {
|
|
386
|
+
process.stdout.write(content);
|
|
387
|
+
console.error(sbomSummary(result));
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function intakeProblems(config) {
|
|
391
|
+
if (!config.intake)
|
|
392
|
+
return [];
|
|
393
|
+
const problems = [];
|
|
394
|
+
for (const { token_env } of config.intake.tokens) {
|
|
395
|
+
const value = process.env[token_env];
|
|
396
|
+
if (!value)
|
|
397
|
+
problems.push(`${token_env}: the intake upload token is not set.`);
|
|
398
|
+
else if (value.length < 32 || /\s/.test(value))
|
|
399
|
+
problems.push(`${token_env}: an upload token needs at least 32 characters without spaces (openssl rand -hex 32).`);
|
|
400
|
+
}
|
|
401
|
+
try {
|
|
402
|
+
intakeDirectory(config.inventory);
|
|
403
|
+
}
|
|
404
|
+
catch (error) {
|
|
405
|
+
problems.push(`intake: ${error instanceof Error ? error.message : 'the SBOM folder cannot be used'}`);
|
|
406
|
+
}
|
|
407
|
+
for (const file of [config.intake.tls_cert_file, config.intake.tls_key_file])
|
|
408
|
+
if (file && !existsSync(file))
|
|
409
|
+
problems.push(`intake: ${file} does not exist.`);
|
|
410
|
+
return problems;
|
|
411
|
+
}
|
|
190
412
|
async function initialize() {
|
|
191
413
|
const directory = resolve(values.directory ?? '.');
|
|
192
414
|
const configPath = resolve(directory, 'security-watch.yaml'), inventoryPath = resolve(directory, 'systems.yaml');
|
|
@@ -199,6 +421,23 @@ async function initialize() {
|
|
|
199
421
|
if (values.ecosystem && !values.libraries)
|
|
200
422
|
throw new Error('--ecosystem requires --libraries.');
|
|
201
423
|
const libraries = values.libraries ? libraryInput(values.libraries, values.ecosystem) : undefined;
|
|
424
|
+
if (values.project && values.libraries)
|
|
425
|
+
throw new Error('--project and --libraries both describe your libraries; choose one.');
|
|
426
|
+
if (values.production && !values.project)
|
|
427
|
+
throw new Error('--production requires --project.');
|
|
428
|
+
// Read the projects first: a project with nothing to watch is reported before any question is asked.
|
|
429
|
+
const projects = (values.project ?? []).map((project) => buildSbom(project));
|
|
430
|
+
const sbomIds = new Set();
|
|
431
|
+
const sbomFiles = projects.map((project, index) => {
|
|
432
|
+
let id = project.system.id;
|
|
433
|
+
for (let suffix = 2; sbomIds.has(id); suffix++)
|
|
434
|
+
id = `${project.system.id}-${suffix}`;
|
|
435
|
+
sbomIds.add(id);
|
|
436
|
+
return { id, project, path: resolve(values.project[index]) };
|
|
437
|
+
});
|
|
438
|
+
const nonNpm = projects.some((project) => project.ecosystems.some((ecosystem) => ecosystem !== 'npm'));
|
|
439
|
+
if (sbomFiles.some(({ id }) => existsSync(resolve(directory, 'sboms', `${id}.cdx.json`))))
|
|
440
|
+
throw new Error('An SBOM with the same name already exists in sboms/; init never overwrites it.');
|
|
202
441
|
if (provider === 'none' && (model || endpoint || allowPrivate))
|
|
203
442
|
throw new Error('--model, --endpoint and --allow-private-endpoint require --provider.');
|
|
204
443
|
if (provider !== 'none' && !PROVIDERS.some((entry) => entry.id === provider))
|
|
@@ -262,7 +501,7 @@ async function initialize() {
|
|
|
262
501
|
poll_interval_minutes: Number(pollMinutes),
|
|
263
502
|
news_lookback_minutes: Number(lookbackMinutes),
|
|
264
503
|
sources: {
|
|
265
|
-
...(libraries ? { osv: true } : {}),
|
|
504
|
+
...(libraries || nonNpm ? { osv: true } : {}),
|
|
266
505
|
vendor_feeds: values['vendor-feeds']?.split(',').map((name) => name.trim()) ?? [],
|
|
267
506
|
},
|
|
268
507
|
...(values.heartbeat ? { monitoring: { heartbeat_url_env: 'HEARTBEAT_URL' } } : {}),
|
|
@@ -299,30 +538,51 @@ async function initialize() {
|
|
|
299
538
|
});
|
|
300
539
|
mkdirSync(directory, { recursive: true });
|
|
301
540
|
writeFileSync(configPath, '# Run doctor after editing this file. Credentials belong in a private env file.\n' + stringify(config), { flag: 'wx', mode: 0o600 });
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
541
|
+
for (const { id, project } of sbomFiles) {
|
|
542
|
+
mkdirSync(resolve(directory, 'sboms'), { recursive: true });
|
|
543
|
+
const bom = project.bom;
|
|
544
|
+
for (const property of bom.metadata.properties)
|
|
545
|
+
if (property.name === 'security-watch:system-id')
|
|
546
|
+
property.value = id;
|
|
547
|
+
writeFileSync(resolve(directory, 'sboms', `${id}.cdx.json`), JSON.stringify(bom, null, 2) + '\n', {
|
|
548
|
+
flag: 'wx',
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
writeFileSync(inventoryPath, stringify(sbomFiles.length
|
|
552
|
+
? { sbom_directory: './sboms', systems: systems ?? [] }
|
|
553
|
+
: {
|
|
554
|
+
systems: systems ?? [
|
|
555
|
+
{
|
|
556
|
+
id: libraries ? 'application' : 'example-api',
|
|
557
|
+
name: libraries ? 'Application' : 'Example API',
|
|
558
|
+
note: 'Replace me: where this system runs and who to ask',
|
|
559
|
+
environment: libraries ? 'unknown' : 'development',
|
|
560
|
+
exposure: 'unknown',
|
|
561
|
+
criticality: 'unknown',
|
|
562
|
+
updated_at: new Date().toISOString(),
|
|
563
|
+
components: libraries ?? [
|
|
564
|
+
{
|
|
565
|
+
id: 'example-parser',
|
|
566
|
+
ecosystem: 'npm',
|
|
567
|
+
name: 'example-parser',
|
|
568
|
+
version: '1.2.0',
|
|
569
|
+
note: 'Replace me: where this library is used',
|
|
570
|
+
},
|
|
571
|
+
],
|
|
572
|
+
products: [],
|
|
573
|
+
keywords: [],
|
|
574
|
+
},
|
|
575
|
+
],
|
|
576
|
+
}), { flag: 'wx', mode: 0o600 });
|
|
577
|
+
if (sbomFiles.length) {
|
|
578
|
+
for (const { id, project, path } of sbomFiles) {
|
|
579
|
+
const destination = resolve(directory, 'sboms', `${id}.cdx.json`);
|
|
580
|
+
console.log(sbomSummary(project, destination, 5));
|
|
581
|
+
console.log(`Refresh it when dependencies change, or from CI (docs/sbom.md):\n security-watch sbom --project ${shellArgument(path)} --system-id ${shellArgument(id)} --output ${shellArgument(destination)}`);
|
|
582
|
+
}
|
|
583
|
+
if (nonNpm)
|
|
584
|
+
console.log('OSV is turned on: it covers the non-npm packages and receives their names and versions (see README, Boundaries and privacy).');
|
|
585
|
+
}
|
|
326
586
|
const envExample = resolve(directory, '.env.example');
|
|
327
587
|
if (!existsSync(envExample))
|
|
328
588
|
writeFileSync(envExample, '# Copy this file to .env, set the values you use, then run chmod 600 .env.\n' +
|
|
@@ -333,7 +593,7 @@ async function initialize() {
|
|
|
333
593
|
(channels.includes('slack') ? 'SLACK_WEBHOOK_URL=\n' : '# SLACK_WEBHOOK_URL=\n') +
|
|
334
594
|
(channels.includes('email') ? 'SMTP_URL=\n' : '# SMTP_URL=\n') +
|
|
335
595
|
(values.heartbeat ? 'HEARTBEAT_URL=\n' : '# HEARTBEAT_URL=\n'), { flag: 'wx', mode: 0o600 });
|
|
336
|
-
console.log(`Created ${configPath} and ${inventoryPath}. Add installed versions and deployment details to systems.yaml. Copy .env.example to .env and fill in any required credentials. Then run:\n security-watch doctor --config ${shellArgument(configPath)} --credentials-file ${shellArgument(resolve(directory, '.env'))}\n security-watch scan --config ${shellArgument(configPath)} --credentials-file ${shellArgument(resolve(directory, '.env'))} --dry-run\nNo messages were sent.`);
|
|
596
|
+
console.log(`Created ${configPath} and ${inventoryPath}. ${sbomFiles.length ? 'Each SBOM in sboms/ is one system; add owners and notes with security-watch sbom --owner/--note, or describe more systems in systems.yaml.' : 'Add installed versions and deployment details to systems.yaml.'} Copy .env.example to .env and fill in any required credentials. Then run:\n security-watch doctor --config ${shellArgument(configPath)} --credentials-file ${shellArgument(resolve(directory, '.env'))}\n security-watch scan --config ${shellArgument(configPath)} --credentials-file ${shellArgument(resolve(directory, '.env'))} --dry-run\nNo messages were sent.`);
|
|
337
597
|
}
|
|
338
598
|
async function main() {
|
|
339
599
|
if (values.version) {
|
|
@@ -345,7 +605,28 @@ async function main() {
|
|
|
345
605
|
return;
|
|
346
606
|
}
|
|
347
607
|
const commandFlags = {
|
|
608
|
+
sbom: [
|
|
609
|
+
'project',
|
|
610
|
+
'output',
|
|
611
|
+
'name',
|
|
612
|
+
'system-id',
|
|
613
|
+
'owner',
|
|
614
|
+
'environment',
|
|
615
|
+
'note',
|
|
616
|
+
'exposure',
|
|
617
|
+
'criticality',
|
|
618
|
+
'production',
|
|
619
|
+
'source-url',
|
|
620
|
+
'source-revision',
|
|
621
|
+
'upload',
|
|
622
|
+
'token-env',
|
|
623
|
+
'allow-http',
|
|
624
|
+
],
|
|
625
|
+
upload: ['input', 'url', 'system-id', 'token-env', 'allow-http'],
|
|
626
|
+
intake: ['config'],
|
|
348
627
|
init: [
|
|
628
|
+
'project',
|
|
629
|
+
'production',
|
|
349
630
|
'directory',
|
|
350
631
|
'yes',
|
|
351
632
|
'systems',
|
|
@@ -424,10 +705,24 @@ async function main() {
|
|
|
424
705
|
output(ECOSYSTEMS);
|
|
425
706
|
return;
|
|
426
707
|
}
|
|
708
|
+
if (command === 'sbom') {
|
|
709
|
+
await writeSbom();
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
if (command === 'upload') {
|
|
713
|
+
if (!values.input || !values.url)
|
|
714
|
+
throw new Error('upload needs --input FILE.json and --url URL.');
|
|
715
|
+
const path = resolve(values.input);
|
|
716
|
+
const body = readFileSync(path);
|
|
717
|
+
if (body.byteLength > 20 * 1024 * 1024)
|
|
718
|
+
throw new Error('An SBOM may be at most 20 MiB.');
|
|
719
|
+
await sendSbom(body, values['system-id'] ?? systemIdOf(body, path));
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
427
722
|
if (command === 'import-sbom') {
|
|
428
723
|
if (!values.input)
|
|
429
724
|
throw new Error('--input PATH required');
|
|
430
|
-
const report =
|
|
725
|
+
const report = importSbom(resolve(values.input));
|
|
431
726
|
if (values.output)
|
|
432
727
|
writeFileSync(resolve(values.output), JSON.stringify(report, null, 2) + '\n', {
|
|
433
728
|
flag: 'wx',
|
|
@@ -533,6 +828,16 @@ async function main() {
|
|
|
533
828
|
throw new Error('Configure maintenance.retention before planning or applying pruning.');
|
|
534
829
|
if (values['no-ai'])
|
|
535
830
|
config.models.enabled = false;
|
|
831
|
+
if (command === 'intake') {
|
|
832
|
+
const running = await startIntake(config, { log: (line) => console.log(line) });
|
|
833
|
+
console.log(`Receiving SBOMs at ${running.url}/v1/sboms/SYSTEM_ID; they are written to ${intakeDirectory(config.inventory)}. Stop with Ctrl-C.`);
|
|
834
|
+
await new Promise((done) => {
|
|
835
|
+
process.once('SIGINT', done);
|
|
836
|
+
process.once('SIGTERM', done);
|
|
837
|
+
});
|
|
838
|
+
await running.close();
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
536
841
|
if (command === 'unlock') {
|
|
537
842
|
unlockStoppedWorker(config.database);
|
|
538
843
|
console.log('Stopped-worker lock removed.');
|
|
@@ -565,6 +870,7 @@ async function main() {
|
|
|
565
870
|
`${config.notifications.email.smtp_url_env}: ${smtpProblem(smtp)}.${/%/.test(smtp) ? ' Write a literal % in a password as %25.' : ''}`,
|
|
566
871
|
]
|
|
567
872
|
: []),
|
|
873
|
+
...intakeProblems(config),
|
|
568
874
|
// The heartbeat refuses such an address on every ping.
|
|
569
875
|
...(heartbeat && heartbeatProblem(heartbeat, config.monitoring.allow_private_endpoint)
|
|
570
876
|
? [`${config.monitoring.heartbeat_url_env}: the external heartbeat address cannot be used.`]
|
|
@@ -608,6 +914,17 @@ async function main() {
|
|
|
608
914
|
}
|
|
609
915
|
: { configured: false },
|
|
610
916
|
maintenance: config.maintenance ?? null,
|
|
917
|
+
intake: config.intake
|
|
918
|
+
? {
|
|
919
|
+
listen: config.intake.listen,
|
|
920
|
+
tls: Boolean(config.intake.tls_cert_file),
|
|
921
|
+
tokens: config.intake.tokens.map((token) => ({
|
|
922
|
+
token_env: token.token_env,
|
|
923
|
+
systems: token.systems,
|
|
924
|
+
present: Boolean(process.env[token.token_env]),
|
|
925
|
+
})),
|
|
926
|
+
}
|
|
927
|
+
: { configured: false },
|
|
611
928
|
notices: [
|
|
612
929
|
'Model compatibility is verified only by a real analysis request; doctor does not spend tokens or send notifications.',
|
|
613
930
|
'Public advisory queries disclose package names/versions. Models receive relevant inventory context.',
|
|
@@ -969,6 +1286,12 @@ async function main() {
|
|
|
969
1286
|
store.saveAssessment(finding, decide(finding, config));
|
|
970
1287
|
}
|
|
971
1288
|
store.recoverSending();
|
|
1289
|
+
// Receiving SBOMs is part of the worker, so one process keeps the inventory current and watches it.
|
|
1290
|
+
const intake = config.intake
|
|
1291
|
+
? await startIntake(config, { log: (line) => console.log(line) })
|
|
1292
|
+
: undefined;
|
|
1293
|
+
if (intake)
|
|
1294
|
+
console.log(`Receiving SBOMs at ${intake.url}/v1/sboms/SYSTEM_ID into ${intakeDirectory(config.inventory)}.`);
|
|
972
1295
|
const controller = new AbortController();
|
|
973
1296
|
const startedAt = new Date().toISOString();
|
|
974
1297
|
const catchingUpSince = catchingUpFrom(store, startedAt);
|
|
@@ -1074,6 +1397,7 @@ async function main() {
|
|
|
1074
1397
|
}
|
|
1075
1398
|
finally {
|
|
1076
1399
|
controller.abort();
|
|
1400
|
+
await intake?.close();
|
|
1077
1401
|
if (scanning)
|
|
1078
1402
|
await scanning;
|
|
1079
1403
|
if (maintaining)
|
package/dist/config.d.ts
CHANGED
|
@@ -279,6 +279,16 @@ export declare const configSchema: z.ZodObject<{
|
|
|
279
279
|
interval_seconds: z.ZodDefault<z.ZodNumber>;
|
|
280
280
|
allow_private_endpoint: z.ZodDefault<z.ZodBoolean>;
|
|
281
281
|
}, z.core.$strict>>;
|
|
282
|
+
intake: z.ZodOptional<z.ZodObject<{
|
|
283
|
+
listen: z.ZodDefault<z.ZodString>;
|
|
284
|
+
tokens: z.ZodDefault<z.ZodArray<z.ZodObject<{
|
|
285
|
+
token_env: z.ZodString;
|
|
286
|
+
systems: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
287
|
+
}, z.core.$strict>>>;
|
|
288
|
+
tls_cert_file: z.ZodOptional<z.ZodString>;
|
|
289
|
+
tls_key_file: z.ZodOptional<z.ZodString>;
|
|
290
|
+
allow_plain_http: z.ZodDefault<z.ZodBoolean>;
|
|
291
|
+
}, z.core.$strict>>;
|
|
282
292
|
maintenance: z.ZodOptional<z.ZodObject<{
|
|
283
293
|
interval_hours: z.ZodDefault<z.ZodNumber>;
|
|
284
294
|
retention: z.ZodOptional<z.ZodObject<{
|
package/dist/config.js
CHANGED
|
@@ -204,6 +204,58 @@ export const configSchema = z
|
|
|
204
204
|
})
|
|
205
205
|
.strict()
|
|
206
206
|
.optional(),
|
|
207
|
+
intake: z
|
|
208
|
+
.object({
|
|
209
|
+
listen: z
|
|
210
|
+
.string()
|
|
211
|
+
.trim()
|
|
212
|
+
.regex(/^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9.-]+):\d{1,5}$/, 'Use HOST:PORT, for example 127.0.0.1:8787 or [::]:8787')
|
|
213
|
+
.refine((value) => Number(value.slice(value.lastIndexOf(':') + 1)) <= 65535, 'Invalid port')
|
|
214
|
+
.default('127.0.0.1:8787'),
|
|
215
|
+
tokens: z
|
|
216
|
+
.array(z
|
|
217
|
+
.object({
|
|
218
|
+
token_env: envName,
|
|
219
|
+
systems: z
|
|
220
|
+
.array(z
|
|
221
|
+
.string()
|
|
222
|
+
.regex(/^(?:\*|[A-Za-z0-9][A-Za-z0-9._-]{0,99}\*?)$/, 'Use a system ID, an ID prefix ending in *, or * for every system'))
|
|
223
|
+
.min(1)
|
|
224
|
+
.max(1000)
|
|
225
|
+
.default(['*']),
|
|
226
|
+
})
|
|
227
|
+
.strict())
|
|
228
|
+
.min(1)
|
|
229
|
+
.max(100)
|
|
230
|
+
.default([{ token_env: 'SECURITY_WATCH_INTAKE_TOKEN', systems: ['*'] }]),
|
|
231
|
+
tls_cert_file: z.string().trim().min(1).max(4096).optional(),
|
|
232
|
+
tls_key_file: z.string().trim().min(1).max(4096).optional(),
|
|
233
|
+
allow_plain_http: z.boolean().default(false),
|
|
234
|
+
})
|
|
235
|
+
.strict()
|
|
236
|
+
.superRefine((intake, ctx) => {
|
|
237
|
+
if (Boolean(intake.tls_cert_file) !== Boolean(intake.tls_key_file))
|
|
238
|
+
ctx.addIssue({
|
|
239
|
+
code: 'custom',
|
|
240
|
+
message: 'Set both tls_cert_file and tls_key_file, or neither',
|
|
241
|
+
path: ['tls_cert_file'],
|
|
242
|
+
});
|
|
243
|
+
const host = intake.listen.slice(0, intake.listen.lastIndexOf(':')).replace(/^\[|\]$/g, '');
|
|
244
|
+
// An address, not a name that starts like one: `127.example.com` can point anywhere.
|
|
245
|
+
const loopback = host.toLowerCase() === 'localhost' ||
|
|
246
|
+
(isIP(host) === 4 && host.startsWith('127.')) ||
|
|
247
|
+
(isIP(host) === 6 && /^(?:0*:)*:?0*1$/.test(host));
|
|
248
|
+
if (!loopback && !intake.tls_cert_file && !intake.allow_plain_http)
|
|
249
|
+
ctx.addIssue({
|
|
250
|
+
code: 'custom',
|
|
251
|
+
message: 'Listening beyond this machine sends upload tokens over the network: set tls_cert_file and tls_key_file, or allow_plain_http: true when a TLS proxy in front of it is the only way in',
|
|
252
|
+
path: ['listen'],
|
|
253
|
+
});
|
|
254
|
+
const envs = intake.tokens.map((token) => token.token_env);
|
|
255
|
+
if (new Set(envs).size !== envs.length)
|
|
256
|
+
ctx.addIssue({ code: 'custom', message: 'Each token needs its own token_env', path: ['tokens'] });
|
|
257
|
+
})
|
|
258
|
+
.optional(),
|
|
207
259
|
maintenance: z
|
|
208
260
|
.object({
|
|
209
261
|
interval_hours: z.number().int().min(1).max(168).default(24),
|
|
@@ -375,6 +427,10 @@ export function loadConfig(path) {
|
|
|
375
427
|
const config = parseConfig(substitute(parse(raw, { maxAliasCount: 0 })));
|
|
376
428
|
config.inventory = resolve(dirname(resolve(path)), config.inventory);
|
|
377
429
|
config.database = resolve(dirname(resolve(path)), config.database);
|
|
430
|
+
if (config.intake?.tls_cert_file)
|
|
431
|
+
config.intake.tls_cert_file = resolve(dirname(resolve(path)), config.intake.tls_cert_file);
|
|
432
|
+
if (config.intake?.tls_key_file)
|
|
433
|
+
config.intake.tls_key_file = resolve(dirname(resolve(path)), config.intake.tls_key_file);
|
|
378
434
|
if (config.maintenance?.backup)
|
|
379
435
|
config.maintenance.backup.directory = resolve(dirname(resolve(path)), config.maintenance.backup.directory);
|
|
380
436
|
return config;
|
package/dist/index.d.ts
CHANGED
|
@@ -30,7 +30,13 @@ export { verifyBackup, readPilotBackupReport } from './maintenance.js';
|
|
|
30
30
|
export { runRehearsal, readRehearsal } from './rehearsal.js';
|
|
31
31
|
export type { RehearsalReport, RehearsalScenario, RehearsalSink } from './rehearsal.js';
|
|
32
32
|
export type { RetentionPolicy, PruneCounts, PruneReport, BackupVerification } from './maintenance.js';
|
|
33
|
-
export { importCycloneDx } from './sbom.js';
|
|
33
|
+
export { importCycloneDx, importSbom } from './sbom.js';
|
|
34
|
+
export { generateSbom, DEPENDENCY_FILES } from './manifests.js';
|
|
35
|
+
export type { SbomOptions, GeneratedSbom, DependencyFile } from './manifests.js';
|
|
36
|
+
export { createIntakeHandler, startIntake } from './intake.js';
|
|
37
|
+
export type { IntakeUpload, IntakeOptions, RunningIntake } from './intake.js';
|
|
38
|
+
export { uploadSbom } from './upload.js';
|
|
39
|
+
export type { UploadOptions } from './upload.js';
|
|
34
40
|
export type { SbomImport } from './sbom.js';
|
|
35
41
|
export { compareInventories, attachLocation, attachRemediation } from './inventory-evidence.js';
|
|
36
42
|
export { refreshCoverage } from './coverage.js';
|
package/dist/index.js
CHANGED
|
@@ -18,6 +18,9 @@ export { HeartbeatMonitor } from './heartbeat.js';
|
|
|
18
18
|
export { MaintenanceScheduler } from './operations.js';
|
|
19
19
|
export { verifyBackup, readPilotBackupReport } from './maintenance.js';
|
|
20
20
|
export { runRehearsal, readRehearsal } from './rehearsal.js';
|
|
21
|
-
export { importCycloneDx } from './sbom.js';
|
|
21
|
+
export { importCycloneDx, importSbom } from './sbom.js';
|
|
22
|
+
export { generateSbom, DEPENDENCY_FILES } from './manifests.js';
|
|
23
|
+
export { createIntakeHandler, startIntake } from './intake.js';
|
|
24
|
+
export { uploadSbom } from './upload.js';
|
|
22
25
|
export { compareInventories, attachLocation, attachRemediation } from './inventory-evidence.js';
|
|
23
26
|
export { refreshCoverage } from './coverage.js';
|
package/dist/intake.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type IncomingMessage, type ServerResponse } from 'node:http';
|
|
2
|
+
import type { Config } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Receives SBOMs from CI pipelines and writes them into the inventory's SBOM folder, where the next
|
|
5
|
+
* scan picks them up. Every upload needs a bearer token; each token may be limited to some system
|
|
6
|
+
* IDs. An upload is checked exactly as the scanner will read it, and is written only if it imports,
|
|
7
|
+
* so a pipeline learns at once that its SBOM is unusable instead of a week later from a stale warning.
|
|
8
|
+
*/
|
|
9
|
+
export declare const INTAKE_MAX_BYTES: number;
|
|
10
|
+
export interface IntakeUpload {
|
|
11
|
+
system_id: string;
|
|
12
|
+
/** File name in the SBOM folder. */
|
|
13
|
+
file: string;
|
|
14
|
+
format: 'CycloneDX' | 'SPDX';
|
|
15
|
+
/** Packages Security Watch will watch. */
|
|
16
|
+
packages: number;
|
|
17
|
+
/** Things a scan will report about this SBOM: packages or relationships it cannot use. */
|
|
18
|
+
warnings: number;
|
|
19
|
+
warning_examples: string[];
|
|
20
|
+
}
|
|
21
|
+
export interface IntakeOptions {
|
|
22
|
+
/** Called with one line of JSON per upload or refusal. Never given a token. */
|
|
23
|
+
log?: (line: string) => void;
|
|
24
|
+
now?: () => number;
|
|
25
|
+
}
|
|
26
|
+
/** The SBOM folder named by the inventory, which is where uploads go. */
|
|
27
|
+
export declare function intakeDirectory(inventoryPath: string): string;
|
|
28
|
+
/** The request handler, separate from the listening socket so that it can be tested and embedded. */
|
|
29
|
+
export declare function createIntakeHandler(config: Config, options?: IntakeOptions): (request: IncomingMessage, response: ServerResponse) => void;
|
|
30
|
+
export interface RunningIntake {
|
|
31
|
+
/** Base address, for example `https://127.0.0.1:8787`. */
|
|
32
|
+
url: string;
|
|
33
|
+
close(): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
/** Starts listening. The returned promise settles once the socket is bound. */
|
|
36
|
+
export declare function startIntake(config: Config, options?: IntakeOptions): Promise<RunningIntake>;
|