vouchington-tooling 0.67.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.
- package/README.md +55 -0
- package/dist/cli/commands/coverage-scope-check.d.mts +7 -0
- package/dist/cli/commands/coverage-scope-check.mjs +69 -0
- package/dist/cli/commands/docker-image-mirror.d.mts +13 -0
- package/dist/cli/commands/docker-image-mirror.mjs +39 -0
- package/dist/cli/commands/trivy-policy.d.mts +12 -0
- package/dist/cli/commands/trivy-policy.mjs +76 -0
- package/dist/cli/index.mjs +6 -0
- package/dist/cli/parse-forwarded-commands.d.mts +7 -69
- package/dist/cli/parse-forwarded-commands.mjs +30 -47
- package/dist/cli/parse.d.mts +9 -0
- package/dist/cli/usage-text-coverage-scope.d.mts +1 -0
- package/dist/cli/usage-text-coverage-scope.mjs +7 -0
- package/dist/cli/usage-text-policy.d.mts +2 -0
- package/dist/cli/usage-text-policy.mjs +25 -0
- package/dist/cli/usage-text.d.mts +1 -1
- package/dist/cli/usage-text.mjs +3 -3
- package/dist/coverage-scope/check.d.mts +16 -0
- package/dist/coverage-scope/check.mjs +26 -0
- package/dist/coverage-scope/coverage-scope.test-helpers.d.mts +4 -0
- package/dist/coverage-scope/coverage-scope.test-helpers.mjs +38 -0
- package/dist/coverage-scope/index.d.mts +3 -0
- package/dist/coverage-scope/index.mjs +2 -0
- package/dist/coverage-scope/mismatches.d.mts +3 -0
- package/dist/coverage-scope/mismatches.mjs +17 -0
- package/dist/docker-image-mirror/images.d.mts +25 -0
- package/dist/docker-image-mirror/images.mjs +108 -0
- package/dist/docker-image-mirror/index.d.mts +16 -0
- package/dist/docker-image-mirror/index.mjs +39 -0
- package/dist/index.d.mts +4 -0
- package/dist/index.mjs +2 -0
- package/dist/trivy-policy/background.d.mts +1 -0
- package/dist/trivy-policy/background.mjs +24 -0
- package/dist/trivy-policy/gate.d.mts +5 -0
- package/dist/trivy-policy/gate.mjs +92 -0
- package/dist/trivy-policy/index.d.mts +15 -0
- package/dist/trivy-policy/index.mjs +48 -0
- package/dist/trivy-policy/invocations.d.mts +4 -0
- package/dist/trivy-policy/invocations.mjs +76 -0
- package/dist/trivy-policy/options.d.mts +26 -0
- package/dist/trivy-policy/options.mjs +17 -0
- package/dist/trivy-policy/registry.d.mts +7 -0
- package/dist/trivy-policy/registry.mjs +48 -0
- package/dist/trivy-policy/scan.d.mts +5 -0
- package/dist/trivy-policy/scan.mjs +59 -0
- package/dist/trivy-policy/shell.d.mts +2 -0
- package/dist/trivy-policy/shell.mjs +62 -0
- package/package.json +17 -1
- package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
- package/skills/agent-workflow/references/implementation.md +5 -0
- package/skills/manifest.json +20 -20
- package/skills/pr-description/SKILL.md +26 -11
- package/skills/pr-description/references/examples.md +53 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { loadCoverageConfig } from 'coverage-check';
|
|
4
|
+
import { findCoverageScopeMismatches } from "./mismatches.mjs";
|
|
5
|
+
export function listTrackedFiles(cwd) {
|
|
6
|
+
return execFileSync('git', ['ls-files', '-z'], {
|
|
7
|
+
cwd,
|
|
8
|
+
encoding: 'utf8',
|
|
9
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
10
|
+
})
|
|
11
|
+
.split('\0')
|
|
12
|
+
.filter(Boolean);
|
|
13
|
+
}
|
|
14
|
+
/** Returns tracked paths a positive-threshold rule requires but the collector would not instrument. */
|
|
15
|
+
export function checkCoverageScope(options) {
|
|
16
|
+
const { cwd, rulesFile = '.coverage-rules.yml', instrumentedScope } = options;
|
|
17
|
+
const instrumented = {
|
|
18
|
+
version: 1,
|
|
19
|
+
analyzer: 'javascript',
|
|
20
|
+
include: [...instrumentedScope.include],
|
|
21
|
+
ignored: [...instrumentedScope.exclude],
|
|
22
|
+
};
|
|
23
|
+
const config = loadCoverageConfig(resolve(cwd, rulesFile));
|
|
24
|
+
const files = (options.listFiles ?? listTrackedFiles)(cwd);
|
|
25
|
+
return findCoverageScopeMismatches(files, config, instrumented);
|
|
26
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { afterEach } from 'vitest';
|
|
6
|
+
const RULES = [
|
|
7
|
+
'scope:',
|
|
8
|
+
' version: 1',
|
|
9
|
+
' analyzer: javascript',
|
|
10
|
+
' include: ["**/*.mts"]',
|
|
11
|
+
' ignored: ["**/*.test.mts"]',
|
|
12
|
+
'rules:',
|
|
13
|
+
' - paths: "app/**"',
|
|
14
|
+
' patch_coverage_min: 1',
|
|
15
|
+
' - paths: "scripts/**"',
|
|
16
|
+
' patch_coverage_min: 0',
|
|
17
|
+
'',
|
|
18
|
+
].join('\n');
|
|
19
|
+
const dirs = [];
|
|
20
|
+
afterEach(() => {
|
|
21
|
+
for (const dir of dirs.splice(0))
|
|
22
|
+
rmSync(dir, { recursive: true, force: true });
|
|
23
|
+
});
|
|
24
|
+
/** A temp directory holding `.coverage-rules.yml` and the given files, optionally a git repo. */
|
|
25
|
+
export function fixtureRepo(files, options) {
|
|
26
|
+
const cwd = mkdtempSync(join(tmpdir(), 'coverage-scope-'));
|
|
27
|
+
dirs.push(cwd);
|
|
28
|
+
writeFileSync(join(cwd, '.coverage-rules.yml'), RULES);
|
|
29
|
+
for (const file of files) {
|
|
30
|
+
mkdirSync(dirname(join(cwd, file)), { recursive: true });
|
|
31
|
+
writeFileSync(join(cwd, file), 'export const fixture = true\n');
|
|
32
|
+
}
|
|
33
|
+
if (options.git) {
|
|
34
|
+
execFileSync('git', ['init', '--quiet'], { cwd });
|
|
35
|
+
execFileSync('git', ['add', '--', '.coverage-rules.yml', ...files], { cwd });
|
|
36
|
+
}
|
|
37
|
+
return cwd;
|
|
38
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type CoverageConfig, type CoverageScope } from 'coverage-check';
|
|
2
|
+
/** Positive-threshold paths that the coverage gate expects but Vitest will not instrument. */
|
|
3
|
+
export declare function findCoverageScopeMismatches(files: readonly string[], config: CoverageConfig, instrumentedScope: CoverageScope): string[];
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { coverageDisposition } from 'coverage-check';
|
|
2
|
+
// `coverage-check` exports matchRule only through its documented `./src/*.mts` subpath.
|
|
3
|
+
import { matchRule } from 'coverage-check/src/rules.mts';
|
|
4
|
+
/** Positive-threshold paths that the coverage gate expects but Vitest will not instrument. */
|
|
5
|
+
export function findCoverageScopeMismatches(files, config, instrumentedScope) {
|
|
6
|
+
const scope = config.scope;
|
|
7
|
+
if (scope === undefined)
|
|
8
|
+
throw new Error('coverage rules file is missing its scope block');
|
|
9
|
+
return files.filter((file) => {
|
|
10
|
+
if (coverageDisposition(file, scope) === 'ignored')
|
|
11
|
+
return false;
|
|
12
|
+
const rule = matchRule(file, config.rules);
|
|
13
|
+
return (rule !== null &&
|
|
14
|
+
rule.patch_coverage_min > 0 &&
|
|
15
|
+
coverageDisposition(file, instrumentedScope) === 'ignored');
|
|
16
|
+
});
|
|
17
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export declare const DEFAULT_MIRROR = "mirror.gcr.io";
|
|
2
|
+
type Step = {
|
|
3
|
+
name?: string;
|
|
4
|
+
run?: string;
|
|
5
|
+
uses?: string;
|
|
6
|
+
with?: Record<string, unknown>;
|
|
7
|
+
};
|
|
8
|
+
export type Document = {
|
|
9
|
+
jobs?: Record<string, {
|
|
10
|
+
container?: string | {
|
|
11
|
+
image?: string;
|
|
12
|
+
};
|
|
13
|
+
services?: Record<string, {
|
|
14
|
+
image?: string;
|
|
15
|
+
}>;
|
|
16
|
+
steps?: Step[];
|
|
17
|
+
}>;
|
|
18
|
+
runs?: {
|
|
19
|
+
steps?: Step[];
|
|
20
|
+
image?: string;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
export declare function workflowImageViolations(path: string, document: Document, mirror?: string): string[];
|
|
24
|
+
export declare function dockerfileViolations(path: string, source: string): string[];
|
|
25
|
+
export {};
|
|
@@ -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
|
+
}
|