vouchington-tooling 0.68.0 → 0.70.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.
Files changed (41) hide show
  1. package/README.md +50 -0
  2. package/dist/cli/commands/docker-image-mirror.d.mts +13 -0
  3. package/dist/cli/commands/docker-image-mirror.mjs +53 -0
  4. package/dist/cli/commands/trivy-policy.d.mts +12 -0
  5. package/dist/cli/commands/trivy-policy.mjs +76 -0
  6. package/dist/cli/index.mjs +4 -0
  7. package/dist/cli/parse-forwarded-commands.d.mts +7 -72
  8. package/dist/cli/parse-forwarded-commands.mjs +30 -49
  9. package/dist/cli/parse.d.mts +6 -0
  10. package/dist/cli/usage-text-policy.d.mts +2 -0
  11. package/dist/cli/usage-text-policy.mjs +28 -0
  12. package/dist/cli/usage-text.d.mts +1 -1
  13. package/dist/cli/usage-text.mjs +3 -6
  14. package/dist/docker-image-mirror/images.d.mts +25 -0
  15. package/dist/docker-image-mirror/images.mjs +97 -0
  16. package/dist/docker-image-mirror/index.d.mts +19 -0
  17. package/dist/docker-image-mirror/index.mjs +44 -0
  18. package/dist/docker-image-mirror/policy.d.mts +10 -0
  19. package/dist/docker-image-mirror/policy.mjs +53 -0
  20. package/dist/index.d.mts +4 -0
  21. package/dist/index.mjs +2 -0
  22. package/dist/postgres-test-faults/index.d.mts +9 -0
  23. package/dist/postgres-test-faults/index.mjs +9 -0
  24. package/dist/trivy-policy/background.d.mts +1 -0
  25. package/dist/trivy-policy/background.mjs +24 -0
  26. package/dist/trivy-policy/gate.d.mts +5 -0
  27. package/dist/trivy-policy/gate.mjs +92 -0
  28. package/dist/trivy-policy/index.d.mts +15 -0
  29. package/dist/trivy-policy/index.mjs +48 -0
  30. package/dist/trivy-policy/invocations.d.mts +4 -0
  31. package/dist/trivy-policy/invocations.mjs +76 -0
  32. package/dist/trivy-policy/options.d.mts +26 -0
  33. package/dist/trivy-policy/options.mjs +17 -0
  34. package/dist/trivy-policy/registry.d.mts +7 -0
  35. package/dist/trivy-policy/registry.mjs +48 -0
  36. package/dist/trivy-policy/scan.d.mts +5 -0
  37. package/dist/trivy-policy/scan.mjs +59 -0
  38. package/dist/trivy-policy/shell.d.mts +2 -0
  39. package/dist/trivy-policy/shell.mjs +62 -0
  40. package/package.json +11 -1
  41. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
@@ -0,0 +1,97 @@
1
+ import { withoutShellComment } from "../trivy-policy/shell.mjs";
2
+ import { DEFAULT_MIRROR, imageReasons, policyActive } from "./policy.mjs";
3
+ export { DEFAULT_MIRROR } from "./policy.mjs";
4
+ // Unauthenticated Docker Hub pulls from hosted runners hit its rate limit. A pull-through mirror
5
+ // serves the same pinned digest without credentials, so every image must name a non-Hub registry.
6
+ // Shell scripts are not workflow bodies and are outside this scan.
7
+ const VALUE_FLAGS = new Set('-e --env -p --publish -v --volume --name --network --net --add-host --entrypoint -u --user -w --workdir --tmpfs --platform --mount --label -l --env-file --health-cmd --health-interval --health-retries --health-timeout --health-start-period -m --memory --cpus --restart --cap-add --cap-drop --shm-size --log-driver --ulimit -h --hostname --pull --pids-limit --group-add --device --dns --ipc --pid --cgroupns --stop-signal --stop-timeout --gpus --cidfile --link --volumes-from --cpuset-cpus --cpu-shares --cgroup-parent --dns-search --dns-option --ip --ip6 --mac-address --blkio-weight --memory-swap --memory-reservation --kernel-memory --oom-score-adj --runtime --security-opt --sysctl --userns --uts --annotation --network-alias --expose --label-file --isolation --log-opt --storage-opt --cpu-quota --cpu-period --domainname --detach-keys -a --attach --cpuset-mems --device-cgroup-rule'.split(' '));
8
+ const GLOBAL_VALUE_OPTIONS = new Set('--config --context -c --host -H --log-level -l --tlscacert --tlscert --tlskey'.split(' '));
9
+ function dockerCommandImages(script) {
10
+ const logical = withoutShellComment(script).replace(/\\\r?\n/gu, ' ');
11
+ return [...logical.matchAll(/\bdocker\s+([^\n;&|]*)/gu)].flatMap(([, command]) => {
12
+ const tokens = command.match(/(?:[^\s"']|"[^"]*"|'[^']*')+/gu) ?? [];
13
+ let i = 0;
14
+ while (tokens[i]?.startsWith('-'))
15
+ i += GLOBAL_VALUE_OPTIONS.has(tokens[i]) ? 2 : 1;
16
+ if (tokens[i] === 'container' || tokens[i] === 'image')
17
+ i++;
18
+ if (!['run', 'pull', 'create'].includes(tokens[i] ?? ''))
19
+ return [];
20
+ for (i++; i < tokens.length; i++) {
21
+ const token = tokens[i];
22
+ if (!token.startsWith('-'))
23
+ return [token];
24
+ if (VALUE_FLAGS.has(token))
25
+ i++;
26
+ }
27
+ return [];
28
+ });
29
+ }
30
+ function stepImages(step) {
31
+ const driverOptions = step.with?.['driver-opts'];
32
+ const driverImage = /(?:^|[\s,])image=(\S+)/u.exec(typeof driverOptions === 'string' ? driverOptions : '');
33
+ // setup-buildx-action's docker-container driver defaults to moby/buildkit from Docker Hub.
34
+ const driver = step.with?.driver;
35
+ const defaultsToHub = step.uses?.startsWith('docker/setup-buildx-action') === true &&
36
+ !driverImage &&
37
+ (driver === undefined || driver === 'docker-container');
38
+ return [
39
+ ...dockerCommandImages(step.run ?? ''),
40
+ ...(driverImage ? [driverImage[1]] : []),
41
+ ...(defaultsToHub ? ['moby/buildkit'] : []),
42
+ ...(step.uses?.startsWith('docker://') ? [step.uses.slice('docker://'.length)] : []),
43
+ ];
44
+ }
45
+ export function workflowImageViolations(path, document, mirror = DEFAULT_MIRROR, policy = {}) {
46
+ const found = [];
47
+ for (const [jobId, job] of Object.entries(document.jobs ?? {})) {
48
+ const container = typeof job.container === 'string' ? job.container : job.container?.image;
49
+ if (container)
50
+ found.push([`${jobId} container`, container]);
51
+ for (const [name, service] of Object.entries(job.services ?? {})) {
52
+ if (service.image)
53
+ found.push([`${jobId} service ${name}`, service.image]);
54
+ }
55
+ for (const step of job.steps ?? []) {
56
+ found.push(...stepImages(step).map((image) => [jobId, image]));
57
+ }
58
+ }
59
+ const actionImage = document.runs?.image;
60
+ if (actionImage?.startsWith('docker://')) {
61
+ found.push(['action image', actionImage.slice('docker://'.length)]);
62
+ }
63
+ for (const step of document.runs?.steps ?? []) {
64
+ found.push(...stepImages(step).map((image) => ['composite', image]));
65
+ }
66
+ return found.flatMap(([where, image]) => {
67
+ const reasons = imageReasons(image, mirror, policy);
68
+ return reasons.length > 0 ? [`${path}#${where}: ${image} ${reasons.join('; ')}`] : [];
69
+ });
70
+ }
71
+ export function dockerfileViolations(path, source, policy = {}, mirror = DEFAULT_MIRROR) {
72
+ const stages = new Set();
73
+ const violations = [];
74
+ const check = (label, image) => {
75
+ const reasons = imageReasons(image, mirror, policy);
76
+ if (reasons.length === 0)
77
+ return;
78
+ violations.push(`${path}: ${label}${policyActive(policy) ? ` ${reasons.join('; ')}` : ''}`);
79
+ };
80
+ const syntax = /^#\s*syntax\s*=\s*(\S+)/imu.exec(source)?.[1];
81
+ if (syntax)
82
+ check(`# syntax=${syntax}`, syntax);
83
+ for (const line of source.replace(/\\\r?\n/gu, ' ').split('\n')) {
84
+ const copyFrom = /^\s*COPY\s+(?:--\S+\s+)*--from=(\S+)/iu.exec(line)?.[1];
85
+ if (copyFrom && !/^\d+$/u.test(copyFrom) && !stages.has(copyFrom.toLowerCase())) {
86
+ check(`COPY --from=${copyFrom}`, copyFrom);
87
+ }
88
+ const from = /^\s*FROM\s+(?:--\S+\s+)*(\S+)(?:\s+AS\s+(\S+))?/iu.exec(line);
89
+ if (!from)
90
+ continue;
91
+ if (!stages.has(from[1].toLowerCase()))
92
+ check(`FROM ${from[1]}`, from[1]);
93
+ if (from[2])
94
+ stages.add(from[2].toLowerCase());
95
+ }
96
+ return violations;
97
+ }
@@ -0,0 +1,19 @@
1
+ import { type ImagePolicy } from './policy.mts';
2
+ export { DEFAULT_MIRROR, dockerfileViolations, workflowImageViolations } from './images.mts';
3
+ export type { Document } from './images.mts';
4
+ export type { ImagePolicy } from './policy.mts';
5
+ export interface DockerImageMirrorOptions extends ImagePolicy {
6
+ /**
7
+ * Registry host named in violation messages as the place to pull from. Without
8
+ * `allowRegistries`, any registry other than Docker Hub passes; this value does not restrict
9
+ * them. Default `mirror.gcr.io`.
10
+ */
11
+ readonly mirror?: string | undefined;
12
+ }
13
+ export declare function isDockerfilePath(path: string): boolean;
14
+ /**
15
+ * Violations for tracked workflows, composite actions and Dockerfiles that pull from Docker Hub
16
+ * instead of the mirror. A tracked workflow deleted from disk is skipped; an unreadable tracked
17
+ * Dockerfile is an error.
18
+ */
19
+ export declare function checkDockerImageMirrors(root: string, trackedFiles: readonly string[], options?: DockerImageMirrorOptions): string[];
@@ -0,0 +1,44 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parse } from 'yaml';
4
+ import { dockerfileViolations, workflowImageViolations } from "./images.mjs";
5
+ import { DEFAULT_MIRROR } from "./policy.mjs";
6
+ export { DEFAULT_MIRROR, dockerfileViolations, workflowImageViolations } from "./images.mjs";
7
+ function parseDocument(path, source) {
8
+ try {
9
+ return parse(source) ?? {};
10
+ }
11
+ catch (error) {
12
+ throw new Error(`${path}: ${error.message}`, { cause: error });
13
+ }
14
+ }
15
+ export function isDockerfilePath(path) {
16
+ return /(?:^|\/)(?:Dockerfile(?:\.[^/]+)?|[^/]+\.Dockerfile)$/u.test(path);
17
+ }
18
+ /**
19
+ * Violations for tracked workflows, composite actions and Dockerfiles that pull from Docker Hub
20
+ * instead of the mirror. A tracked workflow deleted from disk is skipped; an unreadable tracked
21
+ * Dockerfile is an error.
22
+ */
23
+ export function checkDockerImageMirrors(root, trackedFiles, options = {}) {
24
+ const mirror = options.mirror ?? DEFAULT_MIRROR;
25
+ const policy = {
26
+ allowRegistries: options.allowRegistries,
27
+ requireDigest: options.requireDigest,
28
+ };
29
+ const errors = [];
30
+ for (const path of trackedFiles) {
31
+ const yaml = /^\.github\/workflows\/[^/]+\.ya?ml$/u.test(path) ||
32
+ /^\.github\/actions\/(?:.+\/)?action\.ya?ml$/u.test(path);
33
+ const dockerfile = isDockerfilePath(path);
34
+ if (!yaml && !dockerfile)
35
+ continue;
36
+ if (yaml && !existsSync(join(root, path)))
37
+ continue;
38
+ const source = readFileSync(join(root, path), 'utf8');
39
+ errors.push(...(yaml
40
+ ? workflowImageViolations(path, parseDocument(path, source), mirror, policy)
41
+ : dockerfileViolations(path, source, policy, mirror)));
42
+ }
43
+ return errors;
44
+ }
@@ -0,0 +1,10 @@
1
+ export declare const DEFAULT_MIRROR = "mirror.gcr.io";
2
+ export interface ImagePolicy {
3
+ /** Prefixes every image reference must start with. Empty or omitted keeps the Docker Hub check. */
4
+ readonly allowRegistries?: readonly string[] | undefined;
5
+ /** Require `@sha256:` followed by 64 lowercase hex characters. */
6
+ readonly requireDigest?: boolean | undefined;
7
+ }
8
+ export declare function policyActive(policy: ImagePolicy): boolean;
9
+ /** Reasons (empty when acceptable) that an image reference breaks the policy. */
10
+ export declare function imageReasons(reference: string, mirror: string, policy?: ImagePolicy): string[];
@@ -0,0 +1,53 @@
1
+ // Image policy shared by workflow and Dockerfile scans. Without `allowRegistries`, only Docker Hub
2
+ // is rejected. With it, every reference must start with one of the prefixes. A reference that
3
+ // expands a variable (`${{ }}`, `$VAR`) is judged by the text before the first variable, so it
4
+ // passes only when that literal text already starts with an allowed prefix; a wholly dynamic
5
+ // reference is rejected. `requireDigest` needs a literal `@sha256:<64 lowercase hex>` suffix, so a
6
+ // variable-expanded digest is rejected too.
7
+ export const DEFAULT_MIRROR = 'mirror.gcr.io';
8
+ const HUB_HOSTS = ['docker.io', 'index.docker.io', 'registry-1.docker.io'];
9
+ const DIGEST = /@sha256:[0-9a-f]{64}$/u;
10
+ export function policyActive(policy) {
11
+ return (policy.allowRegistries?.length ?? 0) > 0 || policy.requireDigest === true;
12
+ }
13
+ function cleanImage(reference) {
14
+ return reference.replace(/^["']|["'),;]+$/gu, '');
15
+ }
16
+ function knownPrefix(image) {
17
+ const dynamicAt = image.search(/\$|\{\{/u);
18
+ return dynamicAt === -1 ? image : image.slice(0, dynamicAt);
19
+ }
20
+ function isHubImage(image) {
21
+ // Only the part before a variable is knowable; a wholly dynamic reference or registry is not.
22
+ const known = knownPrefix(image);
23
+ if (known === '')
24
+ return false;
25
+ if (known !== image && !known.includes('/') && image.slice(known.length).includes('/')) {
26
+ return false;
27
+ }
28
+ const [first = ''] = known.split('/');
29
+ if (!known.includes('/'))
30
+ return true;
31
+ if (HUB_HOSTS.includes(first))
32
+ return true;
33
+ return !(first.includes('.') || first.includes(':') || first === 'localhost');
34
+ }
35
+ /** Reasons (empty when acceptable) that an image reference breaks the policy. */
36
+ export function imageReasons(reference, mirror, policy = {}) {
37
+ const image = cleanImage(reference);
38
+ if (image === '' || image === 'scratch')
39
+ return [];
40
+ const allowed = policy.allowRegistries ?? [];
41
+ const reasons = [];
42
+ if (allowed.length === 0) {
43
+ if (isHubImage(image))
44
+ reasons.push(`must come from ${mirror}/`);
45
+ }
46
+ else if (!allowed.some((prefix) => knownPrefix(image).startsWith(prefix))) {
47
+ reasons.push(`must start with ${allowed.map((prefix) => `"${prefix}"`).join(' or ')}`);
48
+ }
49
+ if (policy.requireDigest === true && !DIGEST.test(image)) {
50
+ reasons.push('must be pinned with @sha256:<64 lowercase hex characters>');
51
+ }
52
+ return reasons;
53
+ }
package/dist/index.d.mts CHANGED
@@ -17,6 +17,10 @@ export type { SqlCreateTableColumn, SqlCreateTableMetadata } from './sql-ast/ind
17
17
  export { dollarQuoteEnd, lineOf, maskSqlQuotedText, readDollarQuoteDelimiter, readStringLiteral, splitSqlStatements, sqlFragments, stripSqlComments, } from './sql-scanner/index.mts';
18
18
  export { auditCiJobRuntime, parseWorkflowNameMatch } from './gha-runtime-audit/index.mts';
19
19
  export type { GhApiExecutor, RuntimeAuditOptions, RuntimeAuditResult, RuntimeAuditWorkflowFilter, RuntimeJobResult, RuntimeSample, } from './gha-runtime-audit/index.mts';
20
+ export { checkTrivyPolicy } from './trivy-policy/index.mts';
21
+ export type { TrivyPolicyOptions } from './trivy-policy/index.mts';
22
+ export { checkDockerImageMirrors } from './docker-image-mirror/index.mts';
23
+ export type { DockerImageMirrorOptions } from './docker-image-mirror/index.mts';
20
24
  export { checkGhaWorkspacePolicy } from './gha-workspace-policy/index.mts';
21
25
  export type { GhaWorkspacePolicyOptions } from './gha-workspace-policy/index.mts';
22
26
  export { checkFreshBase, classifyFreshBase, relationOf } from './fresh-base/index.mts';
package/dist/index.mjs CHANGED
@@ -9,6 +9,8 @@ export { EphemeralListenerAttemptsExhaustedError, isRunnerReservedPort, listenOn
9
9
  export { extractCreateTableMetadata, extractDefaultFunction, extractFuncCallArgColumnNames, initSqlAst, lineOfUtf8ByteOffset, MissingSqlAstParserError, parseSql, } from "./sql-ast/index.mjs";
10
10
  export { dollarQuoteEnd, lineOf, maskSqlQuotedText, readDollarQuoteDelimiter, readStringLiteral, splitSqlStatements, sqlFragments, stripSqlComments, } from "./sql-scanner/index.mjs";
11
11
  export { auditCiJobRuntime, parseWorkflowNameMatch } from "./gha-runtime-audit/index.mjs";
12
+ export { checkTrivyPolicy } from "./trivy-policy/index.mjs";
13
+ export { checkDockerImageMirrors } from "./docker-image-mirror/index.mjs";
12
14
  export { checkGhaWorkspacePolicy } from "./gha-workspace-policy/index.mjs";
13
15
  export { checkFreshBase, classifyFreshBase, relationOf } from "./fresh-base/index.mjs";
14
16
  export { requireUpToDate } from "./require-up-to-date/index.mjs";
@@ -1,5 +1,14 @@
1
1
  export { withPostgresPoolQueryFailureForTest } from './pool-query-failure.mts';
2
2
  export { withPostgresQueryFailureForTest } from './query-failure.mts';
3
+ /**
4
+ * Runs `operation` while holding the package-wide queue that serializes `pg.Pool` instrumentation.
5
+ * `withPostgresQueryFailureForTest` and `withPostgresPoolQueryFailureForTest` already use it, so
6
+ * their scopes never wrap the same pool at once. Wrap your own fault injection or lock observation
7
+ * in it when it patches or watches a pool and may overlap those helpers. Callers wait their turn in
8
+ * arrival order; the next one starts when `operation` settles, even if it rejects. Calling it from
9
+ * inside `operation` (nesting) rejects instead of deadlocking.
10
+ */
11
+ export { runPoolObservationExclusively } from './observation-queue.mts';
3
12
  export { createPostgresLockObservers, type PostgresLockObservers } from './lock-observers.mts';
4
13
  export { getTestPostgresBackendProcessId } from './lock-wait.mts';
5
14
  export type { FaultCommand, LockObserverConfig, LockWaiterDiagnostic, ObserverPool, PollOptions, PostgresFaultOptions, PostgresFaultResult, QueryExecutor, } from './fault-types.mts';
@@ -1,4 +1,13 @@
1
1
  export { withPostgresPoolQueryFailureForTest } from "./pool-query-failure.mjs";
2
2
  export { withPostgresQueryFailureForTest } from "./query-failure.mjs";
3
+ /**
4
+ * Runs `operation` while holding the package-wide queue that serializes `pg.Pool` instrumentation.
5
+ * `withPostgresQueryFailureForTest` and `withPostgresPoolQueryFailureForTest` already use it, so
6
+ * their scopes never wrap the same pool at once. Wrap your own fault injection or lock observation
7
+ * in it when it patches or watches a pool and may overlap those helpers. Callers wait their turn in
8
+ * arrival order; the next one starts when `operation` settles, even if it rejects. Calling it from
9
+ * inside `operation` (nesting) rejects instead of deadlocking.
10
+ */
11
+ export { runPoolObservationExclusively } from "./observation-queue.mjs";
3
12
  export { createPostgresLockObservers } from "./lock-observers.mjs";
4
13
  export { getTestPostgresBackendProcessId } from "./lock-wait.mjs";
@@ -0,0 +1 @@
1
+ export declare function hasBackgroundOperator(command: string): boolean;
@@ -0,0 +1,24 @@
1
+ export function hasBackgroundOperator(command) {
2
+ let quote = '';
3
+ for (let index = 0; index < command.length; index++) {
4
+ const character = command[index];
5
+ if (character === '\\' && quote !== "'") {
6
+ index++;
7
+ continue;
8
+ }
9
+ if (quote !== '') {
10
+ if (character === quote)
11
+ quote = '';
12
+ continue;
13
+ }
14
+ if (character === '"' || character === "'")
15
+ quote = character;
16
+ else if (character === '&' &&
17
+ command[index + 1] !== '&' &&
18
+ command[index - 1] !== '&' &&
19
+ !['<', '>'].includes(command[index - 1] ?? '') &&
20
+ !['<', '>'].includes(command[index + 1] ?? ''))
21
+ return true;
22
+ }
23
+ return false;
24
+ }
@@ -0,0 +1,5 @@
1
+ import { type TrivyPolicyOptions } from './options.mts';
2
+ export declare function isDownloadDatabaseOnly(command: string): boolean;
3
+ export declare function assertVulnerabilityGate(command: string, input?: TrivyPolicyOptions): void;
4
+ export declare function isComponentSbomGeneration(command: string): boolean;
5
+ export declare function assertUnfilteredComponentSbom(command: string): void;
@@ -0,0 +1,92 @@
1
+ import { tokens, trivyPackageScanSubcommand } from "./invocations.mjs";
2
+ import { resolveOptions } from "./options.mjs";
3
+ const GATE_OPTIONS = new Set('--scanners|--quiet|--skip-db-update|--pkg-types|--exit-code|--severity|--ignore-unfixed|--ignorefile|--format|--table-mode|--output'.split('|'));
4
+ const SBOM_OPTIONS = new Set('--quiet|--skip-db-update|--exit-code|--format|--output'.split('|'));
5
+ function policyTokens(command) {
6
+ const commandTokens = tokens(command);
7
+ const terminator = commandTokens.indexOf('--');
8
+ return terminator === -1 ? commandTokens : commandTokens.slice(0, terminator);
9
+ }
10
+ function flagValues(command, flag) {
11
+ const values = [];
12
+ const commandTokens = policyTokens(command);
13
+ for (const [index, token] of commandTokens.entries()) {
14
+ if (token === flag && commandTokens[index + 1] && !commandTokens[index + 1].startsWith('--')) {
15
+ values.push(commandTokens[index + 1]);
16
+ }
17
+ else if (token.startsWith(`${flag}=`))
18
+ values.push(token.slice(flag.length + 1));
19
+ }
20
+ return values;
21
+ }
22
+ function hasBareBoolean(command, flag) {
23
+ const commandTokens = policyTokens(command);
24
+ const flagIndexes = commandTokens.flatMap((token, index) => (token === flag ? [index] : []));
25
+ return (flagIndexes.length === 1 &&
26
+ !commandTokens.some((token) => token.startsWith(`${flag}=`)) &&
27
+ !/^(?:false|true|0|1)$/i.test(commandTokens[flagIndexes[0] + 1] ?? ''));
28
+ }
29
+ export function isDownloadDatabaseOnly(command) {
30
+ return hasBareBoolean(command, '--download-db-only');
31
+ }
32
+ function longOptions(command) {
33
+ const options = [];
34
+ for (const token of tokens(command)) {
35
+ if (token === '--')
36
+ break;
37
+ if (token.startsWith('-'))
38
+ options.push(token.split('=')[0]);
39
+ }
40
+ return options;
41
+ }
42
+ function requireOnlyOptions(command, allowed, label) {
43
+ const option = longOptions(command).find((token) => !allowed.has(token));
44
+ if (option)
45
+ throw new Error(`${label} must not include ${option}`);
46
+ }
47
+ function hasExactSet(command, flag, required) {
48
+ const actual = flagValues(command, flag).flatMap((value) => value.split(','));
49
+ return (actual.length === required.length &&
50
+ actual.every((value) => required.includes(value)) &&
51
+ required.every((value) => actual.includes(value)));
52
+ }
53
+ function hasSingleValue(command, flag, expected) {
54
+ const values = flagValues(command, flag);
55
+ return values.length === 1 && (expected === undefined ? values[0] !== '' : values[0] === expected);
56
+ }
57
+ function requireFlag(condition, argument) {
58
+ if (!condition)
59
+ throw new Error(`Trivy vulnerability scan must include ${argument}`);
60
+ }
61
+ export function assertVulnerabilityGate(command, input = {}) {
62
+ const { ignoreFile, findingsExitCodeEnv } = resolveOptions(input);
63
+ requireOnlyOptions(command, GATE_OPTIONS, 'Trivy vulnerability scan');
64
+ requireFlag(hasExactSet(command, '--scanners', ['vuln']), '--scanners vuln');
65
+ requireFlag(hasBareBoolean(command, '--quiet'), '--quiet');
66
+ requireFlag(hasBareBoolean(command, '--skip-db-update'), '--skip-db-update');
67
+ requireFlag(hasExactSet(command, '--pkg-types', ['os']), '--pkg-types os');
68
+ requireFlag(hasSingleValue(command, '--exit-code', `$${findingsExitCodeEnv}`), `--exit-code "$${findingsExitCodeEnv}"`);
69
+ requireFlag(hasExactSet(command, '--severity', ['CRITICAL', 'HIGH']), '--severity CRITICAL,HIGH');
70
+ requireFlag(hasBareBoolean(command, '--ignore-unfixed'), '--ignore-unfixed');
71
+ requireFlag(hasExactSet(command, '--ignorefile', [ignoreFile]), `--ignorefile ${ignoreFile}`);
72
+ requireFlag(hasExactSet(command, '--format', ['table']), '--format table');
73
+ requireFlag(hasExactSet(command, '--table-mode', ['detailed']), '--table-mode detailed');
74
+ requireFlag(hasSingleValue(command, '--output'), '--output <file>');
75
+ }
76
+ export function isComponentSbomGeneration(command) {
77
+ return (hasExactSet(command, '--format', ['cyclonedx']) &&
78
+ trivyPackageScanSubcommand(command) !== 'sbom');
79
+ }
80
+ export function assertUnfilteredComponentSbom(command) {
81
+ requireOnlyOptions(command, SBOM_OPTIONS, 'Trivy CycloneDX SBOM');
82
+ if (!hasBareBoolean(command, '--quiet'))
83
+ throw new Error('Trivy CycloneDX SBOM must include --quiet');
84
+ if (!hasBareBoolean(command, '--skip-db-update'))
85
+ throw new Error('Trivy CycloneDX SBOM must include --skip-db-update');
86
+ if (!hasExactSet(command, '--exit-code', ['0']))
87
+ throw new Error('Trivy CycloneDX SBOM must include --exit-code 0');
88
+ if (!hasExactSet(command, '--format', ['cyclonedx']))
89
+ throw new Error('Trivy CycloneDX SBOM must include --format cyclonedx');
90
+ if (!hasSingleValue(command, '--output'))
91
+ throw new Error('Trivy CycloneDX SBOM must include --output <file>');
92
+ }
@@ -0,0 +1,15 @@
1
+ import { assertUnfilteredComponentSbom, assertVulnerabilityGate, isComponentSbomGeneration, isDownloadDatabaseOnly } from './gate.mts';
2
+ import { type TrivyPolicyOptions } from './options.mts';
3
+ export { assertUnfilteredComponentSbom, assertVulnerabilityGate, isComponentSbomGeneration };
4
+ export { isDownloadDatabaseOnly };
5
+ export { isTrivyPackageScanCommand, trivyPackageScanCommandSegments, trivyPackageScanSubcommand, } from './invocations.mts';
6
+ export type { ResolvedTrivyPolicyOptions, TrivyPolicyOptions } from './options.mts';
7
+ export { resolveOptions } from './options.mts';
8
+ export { parseIgnoreRegistry, validateIgnoreRegistry } from './registry.mts';
9
+ export type { Ignore, IgnoreRegistry } from './registry.mts';
10
+ export { assertNoUnsupportedTrivyAction, assertNoUnsupportedTrivyShellSource, isShellPolicySource, trivyPackageScanCommands, } from './scan.mts';
11
+ /**
12
+ * Validates the Trivy workflow steps and commands, the ignore registry and its shape for the
13
+ * tracked files under `root`. Returns one message per violation; an empty list means compliant.
14
+ */
15
+ export declare function checkTrivyPolicy(root: string, trackedFiles: readonly string[], input?: TrivyPolicyOptions): string[];
@@ -0,0 +1,48 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { assertUnfilteredComponentSbom, assertVulnerabilityGate, isComponentSbomGeneration, isDownloadDatabaseOnly, } from "./gate.mjs";
4
+ import { resolveOptions } from "./options.mjs";
5
+ import { parseIgnoreRegistry, validateIgnoreRegistry } from "./registry.mjs";
6
+ import { trivyPackageScanCommands } from "./scan.mjs";
7
+ export { assertUnfilteredComponentSbom, assertVulnerabilityGate, isComponentSbomGeneration };
8
+ export { isDownloadDatabaseOnly };
9
+ export { isTrivyPackageScanCommand, trivyPackageScanCommandSegments, trivyPackageScanSubcommand, } from "./invocations.mjs";
10
+ export { resolveOptions } from "./options.mjs";
11
+ export { parseIgnoreRegistry, validateIgnoreRegistry } from "./registry.mjs";
12
+ export { assertNoUnsupportedTrivyAction, assertNoUnsupportedTrivyShellSource, isShellPolicySource, trivyPackageScanCommands, } from "./scan.mjs";
13
+ function attempt(violations, check) {
14
+ try {
15
+ check();
16
+ }
17
+ catch (error) {
18
+ violations.push(error.message);
19
+ }
20
+ }
21
+ /**
22
+ * Validates the Trivy workflow steps and commands, the ignore registry and its shape for the
23
+ * tracked files under `root`. Returns one message per violation; an empty list means compliant.
24
+ */
25
+ export function checkTrivyPolicy(root, trackedFiles, input = {}) {
26
+ const options = resolveOptions(input);
27
+ const violations = [];
28
+ let commands = [];
29
+ attempt(violations, () => {
30
+ commands = trivyPackageScanCommands(trackedFiles, root);
31
+ });
32
+ if (violations.length > 0)
33
+ return violations;
34
+ const scans = commands.filter((command) => !isDownloadDatabaseOnly(command));
35
+ const sboms = scans.filter(isComponentSbomGeneration);
36
+ const gates = scans.filter((command) => !isComponentSbomGeneration(command));
37
+ if (gates.length < options.minGates || sboms.length < options.minSboms)
38
+ violations.push('Trivy policy requires OS gates and unfiltered component SBOMs');
39
+ for (const command of gates)
40
+ attempt(violations, () => assertVulnerabilityGate(command, input));
41
+ for (const command of sboms)
42
+ attempt(violations, () => assertUnfilteredComponentSbom(command));
43
+ if (!trackedFiles.includes(options.ignoreFile))
44
+ violations.push('Trivy exception registry must be tracked');
45
+ else
46
+ attempt(violations, () => validateIgnoreRegistry(parseIgnoreRegistry(readFileSync(join(root, options.ignoreFile), 'utf8')), input));
47
+ return violations;
48
+ }
@@ -0,0 +1,4 @@
1
+ export declare function tokens(command: string): string[];
2
+ export declare function trivyPackageScanSubcommand(command: string): string | undefined;
3
+ export declare function isTrivyPackageScanCommand(command: string): boolean;
4
+ export declare function trivyPackageScanCommandSegments(command: string): string[];
@@ -0,0 +1,76 @@
1
+ import { hasBackgroundOperator } from "./background.mjs";
2
+ import { shellSegments, withoutShellComment } from "./shell.mjs";
3
+ const SUBCOMMANDS = new Set('image|fs|filesystem|rootfs|repo|repository|sbom|vm|k8s|kubernetes'.split('|'));
4
+ // Trivy reads every CLI option from a TRIVY_* variable, so an inline assignment could filter a scan
5
+ // that its flags leave compliant. Only variables that cannot change what is scanned are allowed.
6
+ const SAFE_ENVIRONMENT = /^TRIVY_(?:CACHE_DIR|DB_REPOSITORY|JAVA_DB_REPOSITORY|TIMEOUT|DEBUG|NO_PROGRESS)=/;
7
+ export function tokens(command) {
8
+ const uncommented = withoutShellComment(command);
9
+ return (uncommented.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) ?? []).map((token) => token.replace(/"([^"]*)"|'([^']*)'/g, '$1$2').replace(/\\(.)/g, '$1'));
10
+ }
11
+ function isPackageScan(args) {
12
+ return args.some((token) => SUBCOMMANDS.has(token));
13
+ }
14
+ function isTrivyExecutable(token) {
15
+ return token === 'trivy' || /(?:^|\/)trivy$/.test(token);
16
+ }
17
+ function hasTrivyPackageScan(command) {
18
+ const commandTokens = tokens(command);
19
+ const executable = commandTokens.findIndex(isTrivyExecutable);
20
+ return executable !== -1 && isPackageScan(commandTokens.slice(executable + 1));
21
+ }
22
+ function assertDirectExecution(command, uncommented) {
23
+ if (/(?:\$\([^)]*|`[^`]*)\b(?:[^\s()`]+\/)?trivy(?:\s|\))/.test(uncommented))
24
+ throw new Error(`${command.trim()}: unsupported Trivy command substitution`);
25
+ if (/[<>]\(\s*(?:[^\s()]+\/)?trivy(?:\s|\))/.test(uncommented))
26
+ throw new Error(`${command.trim()}: unsupported Trivy process substitution`);
27
+ if (/\b(?:bash|sh|zsh)\s+-[A-Za-z]*c[A-Za-z]*\s+['"][^'"]*(?:[^\s()]+\/)?trivy(?:\s|$)/.test(uncommented))
28
+ throw new Error(`${command.trim()}: unsupported indirect Trivy execution`);
29
+ if (hasBackgroundOperator(uncommented) && hasTrivyPackageScan(uncommented))
30
+ throw new Error(`${command.trim()}: unsupported background Trivy package scan`);
31
+ }
32
+ function trivyExecutableInvocations(command) {
33
+ const uncommented = withoutShellComment(command);
34
+ assertDirectExecution(command, uncommented);
35
+ return shellSegments(uncommented).flatMap((source) => {
36
+ if (/^\(\s*(?:[^\s()]+\/)?trivy(?:\s|\))/.test(source.trimStart()))
37
+ throw new Error(`${source.trim()}: unsupported grouped Trivy package scan`);
38
+ const segmentTokens = tokens(source);
39
+ const evalIndex = segmentTokens.indexOf('eval');
40
+ if (evalIndex !== -1 &&
41
+ segmentTokens.slice(evalIndex + 1).some((token) => /(?:^|\s|\/)trivy(?:\s|$)/.test(token)))
42
+ throw new Error(`${source.trim()}: unsupported indirect Trivy execution`);
43
+ const executable = segmentTokens.findIndex(isTrivyExecutable);
44
+ if (executable === -1)
45
+ return [];
46
+ const args = segmentTokens.slice(executable + 1);
47
+ const leading = segmentTokens.slice(0, executable);
48
+ if (leading.includes('echo'))
49
+ return [];
50
+ const unsafe = leading.find((token) => token.startsWith('TRIVY_') && !SAFE_ENVIRONMENT.test(token));
51
+ if (unsafe !== undefined && isPackageScan(args))
52
+ throw new Error(`${source.trim()}: unsupported Trivy environment option ${unsafe.split('=')[0]}`);
53
+ if (leading.some((token) => token !== 'env' && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(token))) {
54
+ if (isPackageScan(args))
55
+ throw new Error(`${source.trim()}: unsupported wrapper before Trivy package scan`);
56
+ return [];
57
+ }
58
+ return [{ args, source }];
59
+ });
60
+ }
61
+ export function trivyPackageScanSubcommand(command) {
62
+ return trivyExecutableInvocations(command)
63
+ .flatMap(({ args }) => args)
64
+ .find((token) => SUBCOMMANDS.has(token));
65
+ }
66
+ export function isTrivyPackageScanCommand(command) {
67
+ return trivyPackageScanSubcommand(command) !== undefined;
68
+ }
69
+ export function trivyPackageScanCommandSegments(command) {
70
+ const segments = [];
71
+ for (const { args, source } of trivyExecutableInvocations(command)) {
72
+ if (isPackageScan(args))
73
+ segments.push(source);
74
+ }
75
+ return segments;
76
+ }
@@ -0,0 +1,26 @@
1
+ export interface TrivyPolicyOptions {
2
+ /** Trivy ignore registry that every vulnerability gate must name. Default `.trivyignore.yaml`. */
3
+ readonly ignoreFile?: string;
4
+ /** Environment variable every gate passes to `--exit-code`. Default `TRIVY_FINDINGS_EXIT_CODE`. */
5
+ readonly findingsExitCodeEnv?: string;
6
+ /** Required prefix of the cleanup issue URL in an exception statement. Default: any GitHub issue. */
7
+ readonly cleanupUrlPrefix?: string;
8
+ /** Minimum number of vulnerability gates the repository must define. Default 2. */
9
+ readonly minGates?: number;
10
+ /** Minimum number of CycloneDX component SBOM scans the repository must define. Default 2. */
11
+ readonly minSboms?: number;
12
+ /** Longest allowed exception lifetime in days. Default 30. */
13
+ readonly maxExpiryDays?: number;
14
+ /** Clock used to judge exception expiry. */
15
+ readonly now?: Date;
16
+ }
17
+ export interface ResolvedTrivyPolicyOptions {
18
+ readonly ignoreFile: string;
19
+ readonly findingsExitCodeEnv: string;
20
+ readonly cleanupUrlPattern: string;
21
+ readonly minGates: number;
22
+ readonly minSboms: number;
23
+ readonly maxExpiryDays: number;
24
+ readonly now: Date;
25
+ }
26
+ export declare function resolveOptions(options?: TrivyPolicyOptions): ResolvedTrivyPolicyOptions;
@@ -0,0 +1,17 @@
1
+ const ANY_GITHUB_ISSUE = String.raw `https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/issues\/`;
2
+ function escapeRegExp(value) {
3
+ return value.replace(/[.*+?^${}()|[\]\\/]/g, String.raw `\$&`);
4
+ }
5
+ export function resolveOptions(options = {}) {
6
+ return {
7
+ ignoreFile: options.ignoreFile ?? '.trivyignore.yaml',
8
+ findingsExitCodeEnv: options.findingsExitCodeEnv ?? 'TRIVY_FINDINGS_EXIT_CODE',
9
+ cleanupUrlPattern: options.cleanupUrlPrefix === undefined
10
+ ? ANY_GITHUB_ISSUE
11
+ : escapeRegExp(options.cleanupUrlPrefix),
12
+ minGates: options.minGates ?? 2,
13
+ minSboms: options.minSboms ?? 2,
14
+ maxExpiryDays: options.maxExpiryDays ?? 30,
15
+ now: options.now ?? new Date(),
16
+ };
17
+ }
@@ -0,0 +1,7 @@
1
+ import { type TrivyPolicyOptions } from './options.mts';
2
+ export type Ignore = Partial<Record<'expired_at' | 'id' | 'purls' | 'statement', unknown>>;
3
+ export type IgnoreRegistry = {
4
+ vulnerabilities?: Ignore[];
5
+ };
6
+ export declare function parseIgnoreRegistry(source: string): IgnoreRegistry;
7
+ export declare function validateIgnoreRegistry(registry: IgnoreRegistry, options?: TrivyPolicyOptions): void;