vouchington-tooling 0.68.0 → 0.69.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 (37) hide show
  1. package/README.md +32 -0
  2. package/dist/cli/commands/docker-image-mirror.d.mts +13 -0
  3. package/dist/cli/commands/docker-image-mirror.mjs +39 -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 +25 -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 +108 -0
  16. package/dist/docker-image-mirror/index.d.mts +16 -0
  17. package/dist/docker-image-mirror/index.mjs +39 -0
  18. package/dist/index.d.mts +4 -0
  19. package/dist/index.mjs +2 -0
  20. package/dist/trivy-policy/background.d.mts +1 -0
  21. package/dist/trivy-policy/background.mjs +24 -0
  22. package/dist/trivy-policy/gate.d.mts +5 -0
  23. package/dist/trivy-policy/gate.mjs +92 -0
  24. package/dist/trivy-policy/index.d.mts +15 -0
  25. package/dist/trivy-policy/index.mjs +48 -0
  26. package/dist/trivy-policy/invocations.d.mts +4 -0
  27. package/dist/trivy-policy/invocations.mjs +76 -0
  28. package/dist/trivy-policy/options.d.mts +26 -0
  29. package/dist/trivy-policy/options.mjs +17 -0
  30. package/dist/trivy-policy/registry.d.mts +7 -0
  31. package/dist/trivy-policy/registry.mjs +48 -0
  32. package/dist/trivy-policy/scan.d.mts +5 -0
  33. package/dist/trivy-policy/scan.mjs +59 -0
  34. package/dist/trivy-policy/shell.d.mts +2 -0
  35. package/dist/trivy-policy/shell.mjs +62 -0
  36. package/package.json +11 -1
  37. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
@@ -0,0 +1,108 @@
1
+ import { withoutShellComment } from "../trivy-policy/shell.mjs";
2
+ // Unauthenticated Docker Hub pulls from hosted runners hit its rate limit. A pull-through mirror
3
+ // serves the same pinned digest without credentials, so every image must name a non-Hub registry.
4
+ // Shell scripts are not workflow bodies and are outside this scan.
5
+ export const DEFAULT_MIRROR = 'mirror.gcr.io';
6
+ const HUB_HOSTS = ['docker.io', 'index.docker.io', 'registry-1.docker.io'];
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
+ function isHubImage(reference) {
9
+ const image = reference.replace(/^["']|["'),;]+$/gu, '');
10
+ if (image === '' || image === 'scratch')
11
+ return false;
12
+ // Only the part before a variable is knowable; a wholly dynamic reference or registry is not.
13
+ const dynamicAt = image.search(/\$|\{\{/u);
14
+ const known = dynamicAt === -1 ? image : image.slice(0, dynamicAt);
15
+ if (known === '')
16
+ return false;
17
+ if (dynamicAt !== -1 && !known.includes('/') && image.slice(dynamicAt).includes('/'))
18
+ return false;
19
+ const [first = ''] = known.split('/');
20
+ if (!known.includes('/'))
21
+ return true;
22
+ if (HUB_HOSTS.includes(first))
23
+ return true;
24
+ return !(first.includes('.') || first.includes(':') || first === 'localhost');
25
+ }
26
+ const GLOBAL_VALUE_OPTIONS = new Set('--config --context -c --host -H --log-level -l --tlscacert --tlscert --tlskey'.split(' '));
27
+ function dockerCommandImages(script) {
28
+ const logical = withoutShellComment(script).replace(/\\\r?\n/gu, ' ');
29
+ return [...logical.matchAll(/\bdocker\s+([^\n;&|]*)/gu)].flatMap(([, command]) => {
30
+ const tokens = command.match(/(?:[^\s"']|"[^"]*"|'[^']*')+/gu) ?? [];
31
+ let i = 0;
32
+ while (tokens[i]?.startsWith('-'))
33
+ i += GLOBAL_VALUE_OPTIONS.has(tokens[i]) ? 2 : 1;
34
+ if (tokens[i] === 'container' || tokens[i] === 'image')
35
+ i++;
36
+ if (!['run', 'pull', 'create'].includes(tokens[i] ?? ''))
37
+ return [];
38
+ for (i++; i < tokens.length; i++) {
39
+ const token = tokens[i];
40
+ if (!token.startsWith('-'))
41
+ return [token];
42
+ if (VALUE_FLAGS.has(token))
43
+ i++;
44
+ }
45
+ return [];
46
+ });
47
+ }
48
+ function stepImages(step) {
49
+ const driverOptions = step.with?.['driver-opts'];
50
+ const driverImage = /(?:^|[\s,])image=(\S+)/u.exec(typeof driverOptions === 'string' ? driverOptions : '');
51
+ // setup-buildx-action's docker-container driver defaults to moby/buildkit from Docker Hub.
52
+ const driver = step.with?.driver;
53
+ const defaultsToHub = step.uses?.startsWith('docker/setup-buildx-action') === true &&
54
+ !driverImage &&
55
+ (driver === undefined || driver === 'docker-container');
56
+ return [
57
+ ...dockerCommandImages(step.run ?? ''),
58
+ ...(driverImage ? [driverImage[1]] : []),
59
+ ...(defaultsToHub ? ['moby/buildkit'] : []),
60
+ ...(step.uses?.startsWith('docker://') ? [step.uses.slice('docker://'.length)] : []),
61
+ ];
62
+ }
63
+ export function workflowImageViolations(path, document, mirror = DEFAULT_MIRROR) {
64
+ const found = [];
65
+ for (const [jobId, job] of Object.entries(document.jobs ?? {})) {
66
+ const container = typeof job.container === 'string' ? job.container : job.container?.image;
67
+ if (container)
68
+ found.push([`${jobId} container`, container]);
69
+ for (const [name, service] of Object.entries(job.services ?? {})) {
70
+ if (service.image)
71
+ found.push([`${jobId} service ${name}`, service.image]);
72
+ }
73
+ for (const step of job.steps ?? []) {
74
+ found.push(...stepImages(step).map((image) => [jobId, image]));
75
+ }
76
+ }
77
+ const actionImage = document.runs?.image;
78
+ if (actionImage?.startsWith('docker://')) {
79
+ found.push(['action image', actionImage.slice('docker://'.length)]);
80
+ }
81
+ for (const step of document.runs?.steps ?? []) {
82
+ found.push(...stepImages(step).map((image) => ['composite', image]));
83
+ }
84
+ return found.flatMap(([where, image]) => isHubImage(image) ? [`${path}#${where}: ${image} must come from ${mirror}/`] : []);
85
+ }
86
+ export function dockerfileViolations(path, source) {
87
+ const stages = new Set();
88
+ const violations = [];
89
+ const syntax = /^#\s*syntax\s*=\s*(\S+)/imu.exec(source)?.[1];
90
+ if (syntax && isHubImage(syntax))
91
+ violations.push(`${path}: # syntax=${syntax}`);
92
+ for (const line of source.replace(/\\\r?\n/gu, ' ').split('\n')) {
93
+ const copyFrom = /^\s*COPY\s+(?:--\S+\s+)*--from=(\S+)/iu.exec(line)?.[1];
94
+ if (copyFrom && !/^\d+$/u.test(copyFrom) && !stages.has(copyFrom.toLowerCase())) {
95
+ if (isHubImage(copyFrom))
96
+ violations.push(`${path}: COPY --from=${copyFrom}`);
97
+ }
98
+ const from = /^\s*FROM\s+(?:--\S+\s+)*(\S+)(?:\s+AS\s+(\S+))?/iu.exec(line);
99
+ if (!from)
100
+ continue;
101
+ if (!stages.has(from[1].toLowerCase()) && isHubImage(from[1])) {
102
+ violations.push(`${path}: FROM ${from[1]}`);
103
+ }
104
+ if (from[2])
105
+ stages.add(from[2].toLowerCase());
106
+ }
107
+ return violations;
108
+ }
@@ -0,0 +1,16 @@
1
+ export { DEFAULT_MIRROR, dockerfileViolations, workflowImageViolations } from './images.mts';
2
+ export type { Document } from './images.mts';
3
+ export interface DockerImageMirrorOptions {
4
+ /**
5
+ * Registry host named in violation messages as the place to pull from. Any registry other than
6
+ * Docker Hub passes; this value does not restrict them. Default `mirror.gcr.io`.
7
+ */
8
+ readonly mirror?: string;
9
+ }
10
+ export declare function isDockerfilePath(path: string): boolean;
11
+ /**
12
+ * Violations for tracked workflows, composite actions and Dockerfiles that pull from Docker Hub
13
+ * instead of the mirror. A tracked workflow deleted from disk is skipped; an unreadable tracked
14
+ * Dockerfile is an error.
15
+ */
16
+ export declare function checkDockerImageMirrors(root: string, trackedFiles: readonly string[], options?: DockerImageMirrorOptions): string[];
@@ -0,0 +1,39 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parse } from 'yaml';
4
+ import { DEFAULT_MIRROR, dockerfileViolations, workflowImageViolations, } from "./images.mjs";
5
+ export { DEFAULT_MIRROR, dockerfileViolations, workflowImageViolations } from "./images.mjs";
6
+ function parseDocument(path, source) {
7
+ try {
8
+ return parse(source) ?? {};
9
+ }
10
+ catch (error) {
11
+ throw new Error(`${path}: ${error.message}`, { cause: error });
12
+ }
13
+ }
14
+ export function isDockerfilePath(path) {
15
+ return /(?:^|\/)(?:Dockerfile(?:\.[^/]+)?|[^/]+\.Dockerfile)$/u.test(path);
16
+ }
17
+ /**
18
+ * Violations for tracked workflows, composite actions and Dockerfiles that pull from Docker Hub
19
+ * instead of the mirror. A tracked workflow deleted from disk is skipped; an unreadable tracked
20
+ * Dockerfile is an error.
21
+ */
22
+ export function checkDockerImageMirrors(root, trackedFiles, options = {}) {
23
+ const mirror = options.mirror ?? DEFAULT_MIRROR;
24
+ const errors = [];
25
+ for (const path of trackedFiles) {
26
+ const yaml = /^\.github\/workflows\/[^/]+\.ya?ml$/u.test(path) ||
27
+ /^\.github\/actions\/(?:.+\/)?action\.ya?ml$/u.test(path);
28
+ const dockerfile = isDockerfilePath(path);
29
+ if (!yaml && !dockerfile)
30
+ continue;
31
+ if (yaml && !existsSync(join(root, path)))
32
+ continue;
33
+ const source = readFileSync(join(root, path), 'utf8');
34
+ errors.push(...(yaml
35
+ ? workflowImageViolations(path, parseDocument(path, source), mirror)
36
+ : dockerfileViolations(path, source)));
37
+ }
38
+ return errors;
39
+ }
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";
@@ -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;
@@ -0,0 +1,48 @@
1
+ import { parse } from 'yaml';
2
+ import { resolveOptions } from "./options.mjs";
3
+ const PART = String.raw `(?:[A-Za-z0-9._~+-]|%[0-9A-Fa-f]{2})+`;
4
+ const VALUE = String.raw `(?:[A-Za-z0-9._~+:-]|%[0-9A-Fa-f]{2})+`;
5
+ const QUALIFIER = String.raw `${PART}=${VALUE}`;
6
+ const OS_PURL = new RegExp(String.raw `^pkg:(deb|apk|rpm)\/${PART}\/${PART}@${VALUE}(?:\?${QUALIFIER}(?:&${QUALIFIER})*)?$`);
7
+ // The registry's fields are all re-validated below with an explicit `typeof` check plus a regex,
8
+ // so the default YAML core schema is safe: a value it coerces to a non-string still fails.
9
+ export function parseIgnoreRegistry(source) {
10
+ return parse(source);
11
+ }
12
+ function isCalendarDate(value) {
13
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value))
14
+ return false;
15
+ const date = new Date(`${value}T00:00:00Z`);
16
+ return !Number.isNaN(date.valueOf()) && date.toISOString().slice(0, 10) === value;
17
+ }
18
+ function validateExpiry(expiredAt, prefix, options) {
19
+ const { now, maxExpiryDays } = resolveOptions(options);
20
+ if (typeof expiredAt !== 'string' || !isCalendarDate(expiredAt))
21
+ throw new Error(`${prefix}.expired_at must be a UTC calendar date`);
22
+ const today = now.toISOString().slice(0, 10);
23
+ if (expiredAt <= today)
24
+ throw new Error(`${prefix}.expired_at must be after today`);
25
+ const latest = new Date(`${today}T00:00:00Z`);
26
+ latest.setUTCDate(latest.getUTCDate() + maxExpiryDays);
27
+ if (expiredAt > latest.toISOString().slice(0, 10))
28
+ throw new Error(`${prefix}.expired_at must be no more than ${maxExpiryDays} days away`);
29
+ }
30
+ export function validateIgnoreRegistry(registry, options = {}) {
31
+ const vulnerabilities = registry?.vulnerabilities;
32
+ if (!Array.isArray(vulnerabilities))
33
+ throw new Error('vulnerabilities must be an array');
34
+ const { cleanupUrlPattern } = resolveOptions(options);
35
+ const statement = new RegExp(String.raw `^Not exploitable:\s*(?=\S).+?\.\s*Cleanup:\s*${cleanupUrlPattern}[1-9]\d*$`, 'i');
36
+ for (const [index, ignore] of vulnerabilities.entries()) {
37
+ const prefix = `vulnerabilities[${index}]`;
38
+ if (typeof ignore.id !== 'string' || ignore.id.trim() === '')
39
+ throw new Error(`${prefix}.id must be a vulnerability identifier`);
40
+ if (!Array.isArray(ignore.purls) ||
41
+ ignore.purls.length === 0 ||
42
+ ignore.purls.some((purl) => typeof purl !== 'string' || !OS_PURL.test(purl)))
43
+ throw new Error(`${prefix}.purls must contain exact versioned package purls`);
44
+ if (typeof ignore.statement !== 'string' || !statement.test(ignore.statement))
45
+ throw new Error(`${prefix}.statement must give exploitability rationale and cleanup issue URL`);
46
+ validateExpiry(ignore.expired_at, prefix, options);
47
+ }
48
+ }
@@ -0,0 +1,5 @@
1
+ export declare function isShellPolicySource(path: string): boolean;
2
+ export declare function assertNoUnsupportedTrivyAction(uses: unknown, path?: string): void;
3
+ export declare function assertNoUnsupportedTrivyShellSource(source: string, path?: string): void;
4
+ /** Every Trivy package-scan command in tracked workflows and composite actions. */
5
+ export declare function trivyPackageScanCommands(repositoryFiles: readonly string[], root: string): string[];
@@ -0,0 +1,59 @@
1
+ import { existsSync, readFileSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parse } from 'yaml';
4
+ import { isDownloadDatabaseOnly } from "./gate.mjs";
5
+ import { trivyPackageScanCommandSegments } from "./invocations.mjs";
6
+ export function isShellPolicySource(path) {
7
+ if (/\.(bash|sh|zsh)$/.test(path))
8
+ return true;
9
+ try {
10
+ if ((statSync(path).mode & 0o111) === 0)
11
+ return false;
12
+ const firstLine = readFileSync(path, 'utf8').split('\n', 1)[0];
13
+ return /^#!\s*(?:\/usr\/bin\/env(?:\s+-S)?\s+|\/(?:usr\/)?bin\/)(?:ba|z)?sh(?:\s|$)/.test(firstLine);
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ function workflowSteps(path) {
20
+ const document = parse(readFileSync(path, 'utf8'));
21
+ return [
22
+ ...Object.values(document?.jobs ?? {}).flatMap((job) => job.steps ?? []),
23
+ ...(document?.runs?.steps ?? []),
24
+ ];
25
+ }
26
+ export function assertNoUnsupportedTrivyAction(uses, path = 'fixture') {
27
+ if (typeof uses === 'string' && /trivy/i.test(uses)) {
28
+ throw new Error(`${path}: unsupported Trivy action ${uses}; use an auditable CLI run block`);
29
+ }
30
+ }
31
+ function assertSupportedWorkflowSteps(paths) {
32
+ const commands = [];
33
+ for (const path of paths) {
34
+ for (const step of workflowSteps(path)) {
35
+ assertNoUnsupportedTrivyAction(step.uses, path);
36
+ if (typeof step.run !== 'string')
37
+ continue;
38
+ commands.push(...trivyPackageScanCommandSegments(step.run));
39
+ }
40
+ }
41
+ return commands;
42
+ }
43
+ export function assertNoUnsupportedTrivyShellSource(source, path = 'fixture') {
44
+ if (trivyPackageScanCommandSegments(source).some((command) => !isDownloadDatabaseOnly(command))) {
45
+ throw new Error(`${path}: unsupported Trivy shell-script scan; use an auditable workflow run block`);
46
+ }
47
+ }
48
+ /** Every Trivy package-scan command in tracked workflows and composite actions. */
49
+ export function trivyPackageScanCommands(repositoryFiles, root) {
50
+ const present = repositoryFiles.filter((path) => existsSync(join(root, path)));
51
+ for (const path of present.filter((path) => isShellPolicySource(join(root, path)))) {
52
+ assertNoUnsupportedTrivyShellSource(readFileSync(join(root, path), 'utf8'), path);
53
+ }
54
+ const yamlPaths = [
55
+ ...present.filter((path) => /^\.github\/workflows\/[^/]+\.ya?ml$/.test(path)),
56
+ ...present.filter((path) => /^\.github\/actions\/.+\.ya?ml$/.test(path)),
57
+ ];
58
+ return assertSupportedWorkflowSteps(yamlPaths.map((path) => join(root, path)));
59
+ }
@@ -0,0 +1,2 @@
1
+ export declare function withoutShellComment(command: string): string;
2
+ export declare function shellSegments(command: string): string[];