@blundergoat/gruff-ts 0.5.0 → 0.6.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/CHANGELOG.md +82 -0
- package/CONTRIBUTING.md +32 -25
- package/README.md +49 -50
- package/SECURITY.md +18 -31
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -10
- package/docs/agent-hook.md +32 -35
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +160 -89
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -172
- package/docs/rules.md +126 -98
- package/package.json +10 -8
- package/src/analyser.ts +817 -323
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +62 -68
- package/src/blocks.ts +512 -336
- package/src/changed-regions.ts +380 -79
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +445 -436
- package/src/cli-program.ts +915 -172
- package/src/cli.ts +9 -3
- package/src/comment-rules.ts +236 -418
- package/src/comment-scanner.ts +339 -47
- package/src/complexity-metrics.ts +111 -35
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +751 -223
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +182 -54
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +493 -140
- package/src/doc-rules.ts +602 -126
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +134 -109
- package/src/findings.ts +47 -27
- package/src/fixture-purpose-rules.ts +194 -50
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +328 -121
- package/src/hook-contract.ts +681 -255
- package/src/init-config.ts +163 -118
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -468
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +32 -127
- package/src/parsed-script.ts +868 -314
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +86 -74
- package/src/project-config-rules.ts +324 -140
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +102 -38
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +821 -203
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +249 -55
- package/src/security-flow-rules.ts +791 -115
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +460 -387
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +378 -104
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +343 -253
- package/src/text-scans.ts +62 -11
- package/src/types.ts +220 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -163
- package/src/test-fixtures.ts +0 -671
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
// Implements `sensitiveExclusions:` config validation, matching, built-in test-path skips, and suppression audit rows.
|
|
2
|
+
//
|
|
3
|
+
// Kept structurally separate from other config surfaces so matching never inspects finding text or secret values (FAMILY-CONTRACT section 13a):
|
|
4
|
+
// - each configured exclusion targets exactly one sensitive-data rule ID, one project-relative path, an optional symbol, and a mandatory reason;
|
|
5
|
+
// - produces deterministic audit rows surfaced across JSON, text, summary, SARIF, and hook envelopes.
|
|
6
|
+
import { arrayValue, isString, objectValue, SUGGEST_EDIT_CONFIG } from "./config-parse.ts";
|
|
7
|
+
import { ConfigLoadError } from "./config-load-error.ts";
|
|
8
|
+
import { isKnownRuleId, isPillarName, rulePillar } from "./profiles.ts";
|
|
9
|
+
import type { Finding, SensitiveExclusion, SuppressionSummary } from "./types.ts";
|
|
10
|
+
|
|
11
|
+
// The only keys an entry may carry. Anything else - `message_contains`, `messageContains`, `value`,
|
|
12
|
+
// `preview` included - fails, so value matching cannot re-enter through an unreviewed key name.
|
|
13
|
+
const SENSITIVE_EXCLUSION_KEYS: readonly string[] = ["rule", "path", "symbol", "reason"];
|
|
14
|
+
|
|
15
|
+
// The one pillar this section governs; a rule from any other pillar is a different review decision.
|
|
16
|
+
const SENSITIVE_EXCLUSION_PILLAR = "sensitive-data";
|
|
17
|
+
|
|
18
|
+
// Characters that turn an exact rule id into a wildcard, glob, or regular expression. Any of them
|
|
19
|
+
// would let one entry claim rules the user never enumerated.
|
|
20
|
+
const RULE_SELECTOR_CHARACTERS = /[*?[\]{}()|+^$\\]/;
|
|
21
|
+
|
|
22
|
+
// Characters that turn an exact file path into a glob. A path glob suppresses findings in files
|
|
23
|
+
// nobody listed, which is the blanket suppression this section exists to prevent.
|
|
24
|
+
const PATH_GLOB_CHARACTERS = /[*?[\]{}]/;
|
|
25
|
+
|
|
26
|
+
const SUGGEST_EXACT_SCOPE = "Each `sensitiveExclusions:` entry needs exactly one `rule:` id, one project-relative `path:`, and a non-empty `reason:`; add a separate entry for every file you mean to exclude.";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Validates the config's sensitiveExclusions section before scanning; an absent section returns no entries.
|
|
30
|
+
* Invalid sections or entries throw ConfigLoadError with the relevant config location; duplicate scopes are rejected.
|
|
31
|
+
* Entries need not match a finding; unmatched entries remain valid and receive zero suppression counts.
|
|
32
|
+
*
|
|
33
|
+
* @param parsedConfig - parsed config document supplying the optional sensitiveExclusions list
|
|
34
|
+
* @returns validated entries in declaration and audit-row order, or an empty list when the section is absent or explicitly empty
|
|
35
|
+
* @throws {ConfigLoadError} - when the section is not a list, an entry is invalid, or two entries claim one scope
|
|
36
|
+
*/
|
|
37
|
+
export function parseSensitiveExclusions(parsedConfig: Record<string, unknown>): SensitiveExclusion[] {
|
|
38
|
+
// A missing section configures no sensitive exclusions.
|
|
39
|
+
if (!("sensitiveExclusions" in parsedConfig)) {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
const section = parsedConfig.sensitiveExclusions;
|
|
43
|
+
// A non-list value cannot carry the per-entry scope and rationale the section requires.
|
|
44
|
+
if (!Array.isArray(section)) {
|
|
45
|
+
throw new ConfigLoadError("Config key `sensitiveExclusions` must be a list of exclusion entries.", SUGGEST_EXACT_SCOPE);
|
|
46
|
+
}
|
|
47
|
+
const exclusions = arrayValue(section).map((entry, index) => parseSensitiveExclusionEntry(entry, index));
|
|
48
|
+
assertUniqueSensitiveScopes(exclusions);
|
|
49
|
+
return exclusions;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Checks entry fields in key, rule, path, optional symbol, and reason order; unknown keys fail first before sibling field errors.
|
|
54
|
+
* An omitted symbol lets the exclusion apply regardless of symbol for the configured rule and path.
|
|
55
|
+
*
|
|
56
|
+
* @param entryValue - raw config entry expected to be a mapping with rule, path, optional symbol, and reason
|
|
57
|
+
* @param index - entry position used to locate the exclusion in config errors
|
|
58
|
+
* @returns normalized fields for the exclusion, omitting symbol when not configured
|
|
59
|
+
* @throws {ConfigLoadError} - when the entry is not a mapping, has an unsupported key, or any field fails validation
|
|
60
|
+
*/
|
|
61
|
+
function parseSensitiveExclusionEntry(entryValue: unknown, index: number): SensitiveExclusion {
|
|
62
|
+
const entry = objectValue(entryValue);
|
|
63
|
+
// Only a mapping can carry the named scope keys; a bare string would hide which field is meant.
|
|
64
|
+
if (!entry) {
|
|
65
|
+
throw new ConfigLoadError(`Config key \`sensitiveExclusions[${index}]\` must be a mapping with \`rule\`, \`path\`, and \`reason\` keys.`, SUGGEST_EXACT_SCOPE);
|
|
66
|
+
}
|
|
67
|
+
assertNoUnsupportedKeys(entry, index);
|
|
68
|
+
return {
|
|
69
|
+
rule: validatedExclusionRule(entry.rule, index),
|
|
70
|
+
path: validatedExclusionPath(entry.path, index),
|
|
71
|
+
...(entry.symbol === undefined ? {} : { symbol: validatedExclusionSymbol(entry.symbol, index) }),
|
|
72
|
+
reason: validatedExclusionReason(entry.reason, index),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Rejects unsupported fields so an exclusion cannot use detected secret text as a match condition.
|
|
78
|
+
*
|
|
79
|
+
* @param entry - exclusion whose keys are checked without changing the entry
|
|
80
|
+
* @param index - exclusion position used in the config diagnostic
|
|
81
|
+
* @returns nothing after checking that the entry uses only supported keys
|
|
82
|
+
* @throws {ConfigLoadError} - when entry contains any key other than rule, path, symbol or reason.
|
|
83
|
+
*/
|
|
84
|
+
function assertNoUnsupportedKeys(entry: Record<string, unknown>, index: number): void {
|
|
85
|
+
// Identify the first unsupported field so the user knows where to amend the config.
|
|
86
|
+
for (const key of Object.keys(entry)) {
|
|
87
|
+
if (!SENSITIVE_EXCLUSION_KEYS.includes(key)) {
|
|
88
|
+
throw new ConfigLoadError(
|
|
89
|
+
`Config key \`sensitiveExclusions[${index}].${key}\` is not supported; a sensitive exclusion accepts only ${SENSITIVE_EXCLUSION_KEYS.join(", ")}.`,
|
|
90
|
+
"Remove the key. Message, value, and preview matching are rejected on purpose so a suppression can never depend on the detected secret.",
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Validates one sensitive-data rule id for an exclusion; selectors and pillar names would widen its scope.
|
|
98
|
+
* Missing, non-string, blank, unknown, and other-pillar values throw ConfigLoadError identifying the entry's rule field.
|
|
99
|
+
*
|
|
100
|
+
* @param configuredRule - raw config rule id to trim and validate against the catalogue
|
|
101
|
+
* @param index - entry position used in config errors
|
|
102
|
+
* @returns the trimmed sensitive-data rule id
|
|
103
|
+
* @throws {ConfigLoadError} - when the rule is missing, non-string, blank, a selector, a pillar, unknown, or outside sensitive-data
|
|
104
|
+
*/
|
|
105
|
+
function validatedExclusionRule(configuredRule: unknown, index: number): string {
|
|
106
|
+
const rule = requiredExclusionString(configuredRule, index, "rule");
|
|
107
|
+
// A selector metacharacter would let one entry claim rules the user never enumerated.
|
|
108
|
+
if (RULE_SELECTOR_CHARACTERS.test(rule)) {
|
|
109
|
+
throw new ConfigLoadError(`Config key \`sensitiveExclusions[${index}].rule\` must be one exact rule id; ${JSON.stringify(rule)} contains a wildcard, glob, or regular-expression character.`, SUGGEST_EXACT_SCOPE);
|
|
110
|
+
}
|
|
111
|
+
// A pillar name would suppress a whole category instead of one reviewed rule.
|
|
112
|
+
if (isPillarName(rule)) {
|
|
113
|
+
throw new ConfigLoadError(`Config key \`sensitiveExclusions[${index}].rule\` must be one exact rule id, not the pillar ${JSON.stringify(rule)}.`, SUGGEST_EXACT_SCOPE);
|
|
114
|
+
}
|
|
115
|
+
// A typo must fail loudly instead of silently suppressing nothing forever.
|
|
116
|
+
if (!isKnownRuleId(rule)) {
|
|
117
|
+
throw new ConfigLoadError(`Config key \`sensitiveExclusions[${index}].rule\` names unknown rule id ${JSON.stringify(rule)}.`, "Use a rule id from `gruff-ts list-rules --format=json`; the id must match the catalogue exactly.");
|
|
118
|
+
}
|
|
119
|
+
// A known rule from another pillar belongs to a different review decision, not this section.
|
|
120
|
+
if (rulePillar(rule) !== SENSITIVE_EXCLUSION_PILLAR) {
|
|
121
|
+
throw new ConfigLoadError(`Config key \`sensitiveExclusions[${index}].rule\` names ${JSON.stringify(rule)}, which is outside the ${SENSITIVE_EXCLUSION_PILLAR} pillar; this section governs sensitive-data rules only.`, "Disable or retune a non-sensitive rule under `rules:` instead.");
|
|
122
|
+
}
|
|
123
|
+
return rule;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Validates one exact project-relative file path, so a reviewer can open the one file the exclusion covers.
|
|
128
|
+
* Rejects the project root, absolute paths, `..` traversal and globs.
|
|
129
|
+
*
|
|
130
|
+
* @param configuredPath - raw config path field to normalise and validate as a project-relative file path
|
|
131
|
+
* @param index - entry position used to name `sensitiveExclusions[<index>].path` in config errors
|
|
132
|
+
* @returns normalised project-relative file path with forward slashes and no leading `./` segments
|
|
133
|
+
* @throws {ConfigLoadError} - when the path is missing, non-string, blank, root-only, absolute, uses `..`, or has a glob character
|
|
134
|
+
*/
|
|
135
|
+
function validatedExclusionPath(configuredPath: unknown, index: number): string {
|
|
136
|
+
const path = normalisedExclusionPath(requiredExclusionString(configuredPath, index, "path"));
|
|
137
|
+
// A bare `.` or `./` resolves to the project root rather than one reviewed file.
|
|
138
|
+
if (path.length === 0 || path === ".") {
|
|
139
|
+
throw new ConfigLoadError(`Config key \`sensitiveExclusions[${index}].path\` must name a specific project-relative file, not the project root.`, SUGGEST_EXACT_SCOPE);
|
|
140
|
+
}
|
|
141
|
+
// An absolute path leaks the author's machine layout and escapes the analysed project.
|
|
142
|
+
if (path.startsWith("/") || /^[A-Za-z]:\//.test(path)) {
|
|
143
|
+
throw new ConfigLoadError(`Config key \`sensitiveExclusions[${index}].path\` must be project-relative; ${JSON.stringify(path)} is absolute.`, SUGGEST_EXACT_SCOPE);
|
|
144
|
+
}
|
|
145
|
+
// A traversal segment points outside the project the user asked gruff to analyse.
|
|
146
|
+
if (path === ".." || path.startsWith("../") || path.includes("/../") || path.endsWith("/..")) {
|
|
147
|
+
throw new ConfigLoadError(`Config key \`sensitiveExclusions[${index}].path\` must stay inside the project; ${JSON.stringify(path)} contains \`..\`.`, SUGGEST_EXACT_SCOPE);
|
|
148
|
+
}
|
|
149
|
+
// A glob suppresses findings across files nobody enumerated.
|
|
150
|
+
if (PATH_GLOB_CHARACTERS.test(path)) {
|
|
151
|
+
throw new ConfigLoadError(`Config key \`sensitiveExclusions[${index}].path\` must be one exact file path; ${JSON.stringify(path)} contains a glob character.`, SUGGEST_EXACT_SCOPE);
|
|
152
|
+
}
|
|
153
|
+
return path;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Validates a configured symbol that limits an exclusion to matching tagged findings; the caller skips this helper when omitted.
|
|
158
|
+
*
|
|
159
|
+
* @param configuredSymbol - raw config symbol field to validate and trim
|
|
160
|
+
* @param index - entry position used to locate the entry in config errors
|
|
161
|
+
* @returns trimmed non-empty symbol name
|
|
162
|
+
* @throws {ConfigLoadError} - when configuredSymbol is undefined, non-string, or blank
|
|
163
|
+
*/
|
|
164
|
+
function validatedExclusionSymbol(configuredSymbol: unknown, index: number): string {
|
|
165
|
+
return requiredExclusionString(configuredSymbol, index, "symbol");
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Validates the mandatory explanation for a suppression audit entry because every exclusion needs a non-empty rationale.
|
|
170
|
+
*
|
|
171
|
+
* @param configuredReason - raw config reason field to validate and trim for the suppression audit
|
|
172
|
+
* @param index - entry position used to identify the entry in config errors
|
|
173
|
+
* @returns trimmed non-empty reason text for the suppression audit
|
|
174
|
+
* @throws {ConfigLoadError} - when configuredReason is missing, non-string, empty, or whitespace-only
|
|
175
|
+
*/
|
|
176
|
+
function validatedExclusionReason(configuredReason: unknown, index: number): string {
|
|
177
|
+
return requiredExclusionString(configuredReason, index, "reason");
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Shared narrowing for the four string-valued keys. Throws ConfigLoadError naming
|
|
182
|
+
* `sensitiveExclusions[<index>].<key>` for a missing, non-string, or whitespace-only value, so the
|
|
183
|
+
* user sees the exact field to fix. Returns the trimmed text.
|
|
184
|
+
*
|
|
185
|
+
* @param configuredValue - raw config field value to validate and trim
|
|
186
|
+
* @param index - entry position used in config errors
|
|
187
|
+
* @param key - field name used in config errors
|
|
188
|
+
* @returns trimmed, non-empty field text
|
|
189
|
+
* @throws {ConfigLoadError} - when the value is missing, is not a string, or is empty or only whitespace
|
|
190
|
+
*/
|
|
191
|
+
function requiredExclusionString(configuredValue: unknown, index: number, key: string): string {
|
|
192
|
+
const location = `sensitiveExclusions[${index}].${key}`;
|
|
193
|
+
// A missing key cannot describe the scope or rationale the section requires.
|
|
194
|
+
if (configuredValue === undefined) {
|
|
195
|
+
throw new ConfigLoadError(`Config key \`${location}\` is required.`, SUGGEST_EXACT_SCOPE);
|
|
196
|
+
}
|
|
197
|
+
// A non-string value has no meaning for a rule id, a path, a symbol, or a rationale.
|
|
198
|
+
if (!isString(configuredValue)) {
|
|
199
|
+
throw new ConfigLoadError(`Config key \`${location}\` must be a string; got ${JSON.stringify(configuredValue)}.`, SUGGEST_EDIT_CONFIG);
|
|
200
|
+
}
|
|
201
|
+
const trimmedText = configuredValue.trim();
|
|
202
|
+
// Blank text leaves reviewers with no scope or rationale for this field.
|
|
203
|
+
if (trimmedText.length === 0) {
|
|
204
|
+
throw new ConfigLoadError(`Config key \`${location}\` must be a non-empty string.`, SUGGEST_EXACT_SCOPE);
|
|
205
|
+
}
|
|
206
|
+
return trimmedText;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Normalises a configured exclusion path for exact matching by converting separators and stripping any repeated leading `./` prefixes.
|
|
211
|
+
*
|
|
212
|
+
* @param path - configured exclusion path before slash and prefix normalisation
|
|
213
|
+
* @returns path with backslashes replaced by forward slashes and all leading `./` prefixes removed
|
|
214
|
+
*/
|
|
215
|
+
function normalisedExclusionPath(path: string): string {
|
|
216
|
+
return path.replaceAll("\\", "/").replace(/^(?:\.\/)+/, "");
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Rejects duplicate rule, path, and symbol scopes because the first matching entry would receive all suppression credit.
|
|
221
|
+
* The error identifies the later entry so the user can merge the two rationales.
|
|
222
|
+
*
|
|
223
|
+
* @param exclusions - entries checked in declaration order. Two entries with the same rule and path and no symbol conflict.
|
|
224
|
+
* @returns nothing after checking that each configured scope is claimed once
|
|
225
|
+
* @throws {ConfigLoadError} - when a later entry repeats an earlier entry's rule, path, and symbol
|
|
226
|
+
*/
|
|
227
|
+
function assertUniqueSensitiveScopes(exclusions: readonly SensitiveExclusion[]): void {
|
|
228
|
+
const claimedScopes = new Map<string, number>();
|
|
229
|
+
// Declaration order lets the error identify the later entry as the duplicate and point to the earlier claim.
|
|
230
|
+
for (const [index, exclusion] of exclusions.entries()) {
|
|
231
|
+
const scope = sensitiveExclusionScopeKey(exclusion);
|
|
232
|
+
const firstIndex = claimedScopes.get(scope);
|
|
233
|
+
if (firstIndex !== undefined) {
|
|
234
|
+
const symbolClause = exclusion.symbol === undefined ? "" : " for symbol " + JSON.stringify(exclusion.symbol);
|
|
235
|
+
throw new ConfigLoadError(
|
|
236
|
+
`Config key \`sensitiveExclusions[${index}]\` is a duplicate of \`sensitiveExclusions[${firstIndex}]\`: both claim rule ${JSON.stringify(exclusion.rule)} in ${JSON.stringify(exclusion.path)}${symbolClause}.`,
|
|
237
|
+
"Merge the two rationales into one entry so its suppression count describes the whole scope.",
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
claimedScopes.set(scope, index);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Builds a stable duplicate-check key by JSON-encoding an exclusion's rule, path, and symbol as separate fields.
|
|
246
|
+
* An omitted symbol is encoded as null and identifies the file-wide scope for that rule.
|
|
247
|
+
*
|
|
248
|
+
* @param exclusion - validated exclusion whose scope fields form the key
|
|
249
|
+
* @returns stable JSON array key encoding rule, path, and symbol (or null when omitted)
|
|
250
|
+
*/
|
|
251
|
+
function sensitiveExclusionScopeKey(exclusion: SensitiveExclusion): string {
|
|
252
|
+
return JSON.stringify([exclusion.rule, exclusion.path, exclusion.symbol ?? null]);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Result of applying the user's sensitive exclusions to one scan.
|
|
257
|
+
*
|
|
258
|
+
* Stable contract: `findings` is what the report, the score, and the exit code see, while `suppressions` always carries one
|
|
259
|
+
* row per configured entry, including entries that matched nothing, so a suppression is counted
|
|
260
|
+
* rather than silently invisible.
|
|
261
|
+
*/
|
|
262
|
+
export interface SensitiveExclusionResult {
|
|
263
|
+
findings: Finding[];
|
|
264
|
+
suppressions: SuppressionSummary[];
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Apply reviewed sensitive-data exclusions before baseline filtering so claimed findings never affect the score or exit code.
|
|
269
|
+
* Stable contract: rule ID, display path, and any supplied symbol must match exactly. Current sensitive-data rules supply no symbol.
|
|
270
|
+
*
|
|
271
|
+
* @param findings - scan findings to check against the exclusions in report order
|
|
272
|
+
* @param exclusions - validated entries checked in declaration order, with the first match claiming each finding
|
|
273
|
+
* @returns Surviving findings in input order and one audit row per entry, including entries that suppressed nothing.
|
|
274
|
+
*/
|
|
275
|
+
export function partitionSensitiveExclusions(findings: readonly Finding[], exclusions: readonly SensitiveExclusion[]): SensitiveExclusionResult {
|
|
276
|
+
const suppressions = exclusions.map((exclusion, index) => initialSuppressionSummary(exclusion, index));
|
|
277
|
+
const kept: Finding[] = [];
|
|
278
|
+
// Each finding is matched against the entries in declaration order so the first claimant counts it.
|
|
279
|
+
for (const finding of findings) {
|
|
280
|
+
const matchedIndex = exclusions.findIndex((exclusion) => sensitiveExclusionMatches(exclusion, finding));
|
|
281
|
+
const summary = suppressions[matchedIndex];
|
|
282
|
+
// A finding no entry claims stays eligible for later reporting, scoring, and exit-code checks.
|
|
283
|
+
if (!summary) {
|
|
284
|
+
kept.push(finding);
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
summary.suppressed += 1;
|
|
288
|
+
}
|
|
289
|
+
return { findings: kept, suppressions };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Reason on each sensitive-data `builtInTestPath[...]` audit row; every port publishes these exact words (FAMILY-CONTRACT.md section 13a).
|
|
293
|
+
export const BUILT_IN_TEST_PATH_REASON = "Test, fixture and example files hold sample credentials, so sensitive-data rules skip them by path.";
|
|
294
|
+
|
|
295
|
+
// Reason on each security `builtInTestPath[...]` audit row, since a test calls insecure APIs on purpose; every port publishes these exact words.
|
|
296
|
+
export const BUILT_IN_SECURITY_TEST_PATH_REASON = "Test, fixture and example files exercise insecure calls on purpose, so security rules skip them by path.";
|
|
297
|
+
|
|
298
|
+
// The family's fixture-PII rule, which keeps reading test paths; gruff-ts has no rule with this id.
|
|
299
|
+
const BUILT_IN_TEST_PATH_EXEMPT_RULE = "sensitive-data.pii-test-fixture";
|
|
300
|
+
|
|
301
|
+
// Directory names, compared case-insensitively, that make a path test code, e.g. `__tests__/` or `Fixtures/`.
|
|
302
|
+
const BUILT_IN_TEST_PATH_DIRECTORIES = new Set(["test", "tests", "__tests__", "spec", "testdata", "fixtures", "examples"]);
|
|
303
|
+
|
|
304
|
+
// Matches a whole base name that marks a test file in any family language, e.g. `login.spec.ts` or `keys_test.go`.
|
|
305
|
+
// `[^\n]` rather than `.`: JavaScript's `.` also refuses \r, U+2028 and U+2029, which the other four ports accept.
|
|
306
|
+
const BUILT_IN_TEST_FILE_NAME = /^(?:[^\n]*_test\.go|test_[^\n]*\.py|[^\n]*_test\.py|[^\n]*Test\.php|[^\n]*\.(?:test|spec)\.(?:js|jsx|ts|tsx|mjs|cjs))$/;
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Checks whether a finding's display path matches a built-in directory or file name convention for tests, fixtures, or examples.
|
|
310
|
+
*
|
|
311
|
+
* @param displayPath - finding display path to check across directory segments and base file name
|
|
312
|
+
* @returns true when any directory segment or the base file name matches the built-in test-path conventions
|
|
313
|
+
*/
|
|
314
|
+
export function isBuiltInTestPath(displayPath: string): boolean {
|
|
315
|
+
const segments = displayPath.replaceAll("\\", "/").split("/");
|
|
316
|
+
const baseName = segments.pop() ?? "";
|
|
317
|
+
// Any directory on the path, compared case-insensitively, or the file name alone can mark test code.
|
|
318
|
+
return segments.some((directory) => BUILT_IN_TEST_PATH_DIRECTORIES.has(directory.toLowerCase())) || BUILT_IN_TEST_FILE_NAME.test(baseName);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Reports whether the test-path skip class covers a rule: every security rule and every sensitive-data rule except the fixture-PII rule.
|
|
323
|
+
*
|
|
324
|
+
* @param ruleId - rule identifier on a finding being evaluated for built-in test-path skipping
|
|
325
|
+
* @returns true for security rules and sensitive-data rules other than the exempt fixture-PII rule
|
|
326
|
+
*/
|
|
327
|
+
function isSkippedOnTestPaths(ruleId: string): boolean {
|
|
328
|
+
// Security rules are skipped whole, because a test exercises insecure calls on purpose.
|
|
329
|
+
if (ruleId.startsWith("security.")) {
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
return ruleId.startsWith("sensitive-data.") && ruleId !== BUILT_IN_TEST_PATH_EXEMPT_RULE;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Filters findings in test paths so projects with sample keys or `eval` in `__tests__/` report `builtInTestPath[...]` rows instead of findings.
|
|
337
|
+
* Every gruff-ts sensitive-data and security rule is covered, including pii-pattern, under FAMILY-CONTRACT.md section 13a.
|
|
338
|
+
*
|
|
339
|
+
* @param findings - findings to partition between surviving report items and built-in test-path skips
|
|
340
|
+
* @param suppressions - existing user-exclusion audit rows copied before appending built-in skip rows
|
|
341
|
+
* @returns surviving findings in input order and a copy of suppressions plus one sorted built-in audit row per skipped file and rule
|
|
342
|
+
*/
|
|
343
|
+
export function applyBuiltInTestPathSkip(findings: readonly Finding[], suppressions: readonly SuppressionSummary[]): SensitiveExclusionResult {
|
|
344
|
+
const skippedCountByFileAndRule = new Map<string, { path: string; rule: string; count: number }>();
|
|
345
|
+
const kept: Finding[] = [];
|
|
346
|
+
// Each finding either stays in the report or is folded into its file's audit row.
|
|
347
|
+
for (const finding of findings) {
|
|
348
|
+
// Only the two pillars' findings in test code are skipped, and never the family's fixture-PII rule.
|
|
349
|
+
if (isSkippedOnTestPaths(finding.ruleId) && isBuiltInTestPath(finding.filePath)) {
|
|
350
|
+
const fileAndRuleKey = `${finding.filePath}\u0000${finding.ruleId}`;
|
|
351
|
+
const skipped = skippedCountByFileAndRule.get(fileAndRuleKey) ?? { path: finding.filePath, rule: finding.ruleId, count: 0 };
|
|
352
|
+
skipped.count += 1;
|
|
353
|
+
skippedCountByFileAndRule.set(fileAndRuleKey, skipped);
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
kept.push(finding);
|
|
357
|
+
}
|
|
358
|
+
const rows = [...suppressions];
|
|
359
|
+
// Built-in rows are numbered among themselves, from 0, so the index means the same thing in every port.
|
|
360
|
+
const skippedFilesAndRules = [...skippedCountByFileAndRule.values()].sort(
|
|
361
|
+
(left, right) => compareUtf8Bytes(left.path, right.path) || compareUtf8Bytes(left.rule, right.rule),
|
|
362
|
+
);
|
|
363
|
+
// One row per file and rule, which text output shows as `builtInTestPath[src/keys.spec.ts] sensitive-data.aws-access-key: 2`.
|
|
364
|
+
for (const [offset, skipped] of skippedFilesAndRules.entries()) {
|
|
365
|
+
rows.push({
|
|
366
|
+
index: offset,
|
|
367
|
+
rule: skipped.rule,
|
|
368
|
+
paths: [skipped.path],
|
|
369
|
+
symbol: null,
|
|
370
|
+
reason: skipped.rule.startsWith("security.") ? BUILT_IN_SECURITY_TEST_PATH_REASON : BUILT_IN_TEST_PATH_REASON,
|
|
371
|
+
suppressed: skipped.count,
|
|
372
|
+
source: "built-in",
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
return { findings: kept, suppressions: rows };
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Compares two strings by UTF-8 bytes for test-path row ordering (FAMILY-CONTRACT.md section 13a),
|
|
380
|
+
* avoiding JavaScript `<` UTF-16 unit ordering on supplementary characters.
|
|
381
|
+
*
|
|
382
|
+
* @param left - first string to encode and compare as UTF-8 bytes
|
|
383
|
+
* @param right - second string to encode and compare as UTF-8 bytes
|
|
384
|
+
* @returns negative, zero, or positive integer when left's UTF-8 bytes sort before, equal, or after right's
|
|
385
|
+
*/
|
|
386
|
+
function compareUtf8Bytes(left: string, right: string): number {
|
|
387
|
+
return Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8"));
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Builds an exclusion's zero-count audit row in the family row shape (`gruff-rs/src/report.rs`, search: `struct SuppressionSummary`),
|
|
392
|
+
* with `paths` as a single-element list and `symbol` set to null when absent.
|
|
393
|
+
*
|
|
394
|
+
* @param exclusion - validated exclusion whose rule, path, optional symbol, and reason populate the row
|
|
395
|
+
* @param index - configured declaration position recorded on the audit row
|
|
396
|
+
* @returns zero-count SuppressionSummary row for the configured exclusion
|
|
397
|
+
*/
|
|
398
|
+
function initialSuppressionSummary(exclusion: SensitiveExclusion, index: number): SuppressionSummary {
|
|
399
|
+
return {
|
|
400
|
+
index,
|
|
401
|
+
rule: exclusion.rule,
|
|
402
|
+
paths: [exclusion.path],
|
|
403
|
+
symbol: exclusion.symbol ?? null,
|
|
404
|
+
reason: exclusion.reason,
|
|
405
|
+
suppressed: 0,
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Matches a finding against an exclusion by exact rule ID, stored display path, and optional symbol; an omitted symbol matches any symbol.
|
|
411
|
+
* Stable contract: matching uses the stored display path so results are independent of working directory, and any specified symbol must match.
|
|
412
|
+
*
|
|
413
|
+
* @param exclusion - validated exclusion specifying the exact rule, path, and optional symbol
|
|
414
|
+
* @param finding - finding checked for exact rule ID, display path, and optional symbol match
|
|
415
|
+
* @returns true when rule ID, display path, and any specified symbol match the exclusion
|
|
416
|
+
*/
|
|
417
|
+
function sensitiveExclusionMatches(exclusion: SensitiveExclusion, finding: Finding): boolean {
|
|
418
|
+
if (finding.ruleId !== exclusion.rule) {
|
|
419
|
+
return false;
|
|
420
|
+
}
|
|
421
|
+
if (finding.filePath !== exclusion.path) {
|
|
422
|
+
return false;
|
|
423
|
+
}
|
|
424
|
+
return exclusion.symbol === undefined || finding.symbol === exclusion.symbol;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Totals suppression counts across audit rows for the human-readable text summary.
|
|
429
|
+
*
|
|
430
|
+
* @param suppressions - audit rows whose suppressed counts contribute to the text summary
|
|
431
|
+
* @returns the number of suppressed findings; zero means the text line is omitted entirely
|
|
432
|
+
*/
|
|
433
|
+
export function totalSuppressedFindings(suppressions: readonly SuppressionSummary[]): number {
|
|
434
|
+
return suppressions.reduce((total, summary) => total + summary.suppressed, 0);
|
|
435
|
+
}
|