plumber-linter 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +79 -3
  2. package/bin/plumber.js +539 -6
  3. package/package.json +10 -3
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Plumber
2
2
 
3
- CI/CD pipeline linter that flags hardcoded secrets, leaked credentials, and dead code — with fixes in plain English.
3
+ CI/CD pipeline linter that flags hardcoded secrets, leaked credentials, and dead code — with fixes in plain English, plus SARIF output for GitHub code scanning and workflow YAML scanning for GitHub Actions.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/plumber-linter.svg)](https://www.npmjs.com/package/plumber-linter)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/parasraju/plumber/blob/main/LICENSE)
@@ -32,11 +32,12 @@ npx plumber-linter scan .
32
32
  # Enforce quality gate in CI (exit 1 on HIGH or CRITICAL issues)
33
33
  npx plumber-linter scan . --fail-on high
34
34
 
35
- # Export report as Markdown or JSON
35
+ # Export report as Markdown, JSON, or SARIF 2.1.0
36
36
  npx plumber-linter scan . --format md
37
37
  npx plumber-linter scan . --format json
38
+ npx plumber-linter scan . --format sarif
38
39
 
39
- # View all 26 inspection rules
40
+ # View all 31 inspection rules
40
41
  npx plumber-linter rules
41
42
  ```
42
43
 
@@ -68,6 +69,75 @@ npx plumber-linter install-hook --fail-on high
68
69
  npx plumber-linter uninstall-hook
69
70
  ```
70
71
 
72
+ ### SARIF output for GitHub code scanning
73
+
74
+ `plumber scan . --format sarif` writes SARIF 2.1.0 JSON to stdout. The file contains one run for `plumber-linter` 1.4.0, every inspection rule (id, name, description, and the plain-English fix in `help.text`), and one result per finding. Each result's `message.text` repeats that finding's explanation and fix. Paths are relative to the scanned directory, and the line is included when the engine recorded one.
75
+
76
+ ```bash
77
+ npx plumber-linter scan . --format sarif > results.sarif
78
+ ```
79
+
80
+ Upload `results.sarif` with GitHub's `upload-sarif` action. The action name, the `sarif_file` input, and the `security-events: write` permission below are taken from GitHub's [Uploading a SARIF file to GitHub](https://docs.github.com/en/code-security/how-tos/find-and-fix-code-vulnerabilities/integrate-with-existing-tools/upload-sarif-file) guide. `partialFingerprints` is left unset; that same action calculates it when the repository contains both the SARIF file and the scanned source.
81
+
82
+ ```yaml
83
+ name: Plumber code scanning
84
+ on:
85
+ push:
86
+ jobs:
87
+ plumber:
88
+ runs-on: ubuntu-latest
89
+ permissions:
90
+ security-events: write
91
+ actions: read
92
+ contents: read
93
+ steps:
94
+ - name: Checkout repository
95
+ uses: actions/checkout@v6
96
+ - name: Run Plumber
97
+ run: npx plumber-linter scan . --format sarif > results.sarif
98
+ - name: Upload SARIF file
99
+ uses: github/codeql-action/upload-sarif@v4
100
+ with:
101
+ sarif_file: results.sarif
102
+ ```
103
+
104
+ ### Workflow YAML scanning — scan .github/workflows/*.yml
105
+
106
+ Workflow YAML scanning checks GitHub Actions files under `.github/workflows` with the same `scan` command. Use it to scan GitHub Actions workflows for structural risks. A repository with no workflow files is unchanged: no new findings and no YAML errors.
107
+
108
+ ```bash
109
+ npx plumber-linter scan .
110
+ npx plumber-linter scan .github/workflows/review.yml
111
+ ```
112
+
113
+ - `sec/pull-request-target` — flags a `pull_request_target` workflow that checks out untrusted PR code or grants write permissions (`CRITICAL`).
114
+ - `sec/expression-injection` — flags `${{ github.event.* }}`, `${{ github.head_ref }}`, or another attacker-controlled context interpolated into a `run:` command (`CRITICAL`).
115
+ - `pipe/action-unpinned` — flags a `uses:` step that references a third-party action by branch or version tag instead of a full commit SHA (`MEDIUM`).
116
+ - `sec/job-permissions` — flags a job that pushes, releases, or deploys with no `permissions:` block, or with `contents: write` where a narrower scope would do (`HIGH`).
117
+ - `sec/secret-to-untrusted` — flags a secret in `env:` or an argument of a step that runs a third-party action (`HIGH`).
118
+
119
+ `.github/workflows/review.yml`:
120
+
121
+ ```yaml
122
+ name: review
123
+ on:
124
+ pull_request_target:
125
+ jobs:
126
+ build:
127
+ runs-on: ubuntu-latest
128
+ steps:
129
+ - uses: actions/checkout@v4
130
+ with:
131
+ ref: ${{ github.event.pull_request.head.sha }}
132
+ ```
133
+
134
+ ```text
135
+ [FILE] .github/workflows/review.yml
136
+ L10 [CRITICAL] Untrusted pull_request_target Checkout or Write Permission
137
+ Found: ref: ${{ github.event.pull_request.head.sha }}
138
+ Fix: Use pull_request, or check out the base ref read-only with no secrets.
139
+ ```
140
+
71
141
  ---
72
142
 
73
143
  ## What It Checks
@@ -152,9 +222,15 @@ Spots hallucinated library imports invented by LLMs or packages missing from pro
152
222
 
153
223
  ## Changelog
154
224
 
225
+ ## 1.3.0
226
+ SARIF output (`--format sarif`) for GitHub code scanning.
227
+
155
228
  ## 1.2.0
156
229
  - `pipe/docker-unpinned`: Flag unpinned Docker images (no tag or `:latest`) in CI jobs and Dockerfiles (`MEDIUM`).
157
230
  - `sec/curl-pipe-shell`: Flag `curl | bash` and `wget | sh` remote script execution in CI run steps (`CRITICAL`).
158
231
  - `sec/permissions-write-all`: Flag overly broad workflow write permissions (`permissions: write-all`, `contents: write`) (`HIGH`).
159
232
  - `leak/slack-webhook`: Flag hardcoded Slack and tokenized webhook URLs in workflows and code (`CRITICAL`).
160
233
  - `pipe/npm-unpinned`: Flag `npm install` in CI steps without `--save-exact` or `npm ci` lockfile enforcement (`MEDIUM`).
234
+
235
+ ## 1.4.0
236
+ Workflow YAML scanning (plumber scan on .github/workflows/*.yml) — 5 workflow rules (audit-gated, see Step 1).
package/bin/plumber.js CHANGED
@@ -3,7 +3,7 @@
3
3
  /**
4
4
  * Plumber CLI & MCP Server (Node.js Thin Client)
5
5
  * Inspects repositories for leaked credentials, AI slop tells, broken pipes, and fragile joints.
6
- * Zero external dependencies.
6
+ * GitHub Actions workflow YAML is parsed with js-yaml.
7
7
  */
8
8
 
9
9
  const fs = require('fs');
@@ -11,6 +11,7 @@ const path = require('path');
11
11
  const https = require('https');
12
12
  const readline = require('readline');
13
13
  const { execFileSync } = require('child_process');
14
+ const yaml = require('js-yaml');
14
15
 
15
16
  const API_BASE = process.env.PLUMBER_API_URL || 'http://localhost:3100';
16
17
  const HOOK_MARKER = '# plumber-managed-hook';
@@ -70,10 +71,30 @@ const RULES = [
70
71
  { id: 'sec/curl-pipe-shell', cat: 'Leaks & Secrets', sev: 'CRITICAL', title: 'Remote Script Piped Directly to Shell (curl | bash)', fix: 'Download script first, verify its SHA256 checksum or signature, then execute it.' },
71
72
  { id: 'sec/permissions-write-all', cat: 'Leaks & Secrets', sev: 'HIGH', title: 'Overly Broad Workflow Write Permissions', fix: 'Use least-privilege permissions (e.g., permissions: { contents: read }).' },
72
73
  { id: 'leak/slack-webhook', cat: 'Leaks & Secrets', sev: 'CRITICAL', title: 'Hardcoded Slack or Tokenized Webhook URL', fix: 'Move webhook URL to CI/CD encrypted secrets (e.g., ${{ secrets.SLACK_WEBHOOK_URL }}).' },
73
- { id: 'pipe/npm-unpinned', cat: 'Pipes & Dependencies', sev: 'MEDIUM', title: 'Unpinned npm Install in CI Without Lockfile Enforcement', fix: 'Use npm ci to enforce lockfile versions or pass --save-exact when adding packages.' }
74
+ { id: 'pipe/npm-unpinned', cat: 'Pipes & Dependencies', sev: 'MEDIUM', title: 'Unpinned npm Install in CI Without Lockfile Enforcement', fix: 'Use npm ci to enforce lockfile versions or pass --save-exact when adding packages.' },
75
+ // v1.4.0 structural GitHub Actions checks. Same ids, severities, and fixes as the MCP engine.
76
+ { id: 'sec/pull-request-target', cat: 'Leaks & Secrets', sev: 'CRITICAL', title: 'Untrusted pull_request_target Checkout or Write Permission', fix: 'Use pull_request, or check out the base ref read-only with no secrets.' },
77
+ { id: 'sec/expression-injection', cat: 'Leaks & Secrets', sev: 'CRITICAL', title: 'Expression Injection in Workflow run Step', fix: 'Pass the value through an env: variable and reference that variable in the script.' },
78
+ { id: 'pipe/action-unpinned', cat: 'Pipes & Dependencies', sev: 'MEDIUM', title: 'Unpinned Third-Party Action', fix: 'Pin the action to a full commit SHA.' },
79
+ { id: 'sec/job-permissions', cat: 'Leaks & Secrets', sev: 'HIGH', title: 'Job Writes Without Least-Privilege Permissions', fix: 'Set least-privilege permissions on the job.' },
80
+ { id: 'sec/secret-to-untrusted', cat: 'Leaks & Secrets', sev: 'HIGH', title: 'Secret Passed to Untrusted Step', fix: 'Scope the secret to the trusted step that needs it.' }
74
81
  ];
75
82
 
76
83
  const SEV_WEIGHT = { CRITICAL: 4, HIGH: 3, MEDIUM: 2, LOW: 1, INFO: 0 };
84
+ const SARIF_SCHEMA = 'https://json.schemastore.org/sarif-2.1.0.json';
85
+ const INFORMATION_URI = 'https://github.com/parasraju/plumber';
86
+ const FULL_SHA = /^[0-9a-f]{40}$/i;
87
+ const FIRST_PARTY_OWNERS = new Set(['actions', 'github']);
88
+ const INJECTED_EXPR = /\$\{\{\s*(?:github\.event\.|github\.head_ref\b|inputs\.)/;
89
+ const SECRET_REF = /\$\{\{\s*secrets\.[A-Za-z0-9_]+\s*\}\}/;
90
+ const UNTRUSTED_CHECKOUT = /github\.event\.pull_request|github\.head_ref|refs\/pull\//;
91
+ const CONTENTS_WRITE_RUN = /\bgit\s+push\b|\bgh\s+release\b|\bgh\s+pr\s+merge\b/;
92
+ const DEPLOY_RUN = /\bnpm\s+publish\b|\bpnpm\s+publish\b|\byarn\s+npm\s+publish\b|\bdocker\s+push\b|\btwine\s+upload\b/;
93
+ const CONTENTS_ACTIONS = new Set([
94
+ 'softprops/action-gh-release',
95
+ 'peaceiris/actions-gh-pages',
96
+ 'ncipollo/release-action'
97
+ ]);
77
98
 
78
99
  // Main entry
79
100
  const args = process.argv.slice(2);
@@ -104,7 +125,7 @@ if (cmd === 'mcp') {
104
125
 
105
126
  function printHelp() {
106
127
  console.log(`
107
- Plumber — Code Leak, Clog, and AI Slop Inspector (v1.0.0)
128
+ Plumber — Code Leak, Clog, and AI Slop Inspector (v${readPackageVersion()})
108
129
 
109
130
  USAGE:
110
131
  npx plumber-linter scan [target] [options]
@@ -119,11 +140,11 @@ COMMANDS:
119
140
  install-hook Block git commits that contain secrets, .env files, or dead code
120
141
  uninstall-hook Remove the Plumber pre-commit hook
121
142
  clean [path] Remove unreachable dead code (dry run unless --write)
122
- rules Display catalogue of 26 inspection rules
143
+ rules Display catalogue of ${RULES.length} inspection rules
123
144
  mcp Run stdio Model Context Protocol (MCP) server for Claude / Cursor
124
145
 
125
146
  OPTIONS:
126
- --format [pretty|json|md] Output format (default: pretty)
147
+ --format [pretty|json|md|sarif] Output format (default: pretty)
127
148
  --fail-on [critical|high|medium|low] Exit code 1 if issues >= severity exist
128
149
  `);
129
150
  }
@@ -186,6 +207,8 @@ function scanLocalDirectory(dirPath) {
186
207
  totalLines += lines.length;
187
208
  const rel = (current === dirPath ? base : path.relative(dirPath, current)).replace(/\\/g, '/');
188
209
  const fileIssues = inspectFile(rel, content, lines, ext);
210
+ const workflowIssues = collectWorkflowIssues(current, rel, content, lines);
211
+ if (workflowIssues.length > 0) fileIssues.push(...workflowIssues);
189
212
  if (fileIssues.length > 0) {
190
213
  issues.push(...fileIssues);
191
214
  fileReports.push({ path: rel, issues: fileIssues });
@@ -248,7 +271,7 @@ function inspectFile(relPath, content, lines, ext) {
248
271
  lines.forEach((l, idx) => {
249
272
  const trim = l.trim();
250
273
  if (trim.startsWith('#') || trim.startsWith('//') || trim.startsWith('/*')) return;
251
- if (ext === '.py' && /^\s*except(?:\s+\w+)?:\s*(?:pass|\.\.\.)/.test(l)) {
274
+ if (ext === '.py' && /^\s*except(?:\s+(?:\(\s*)?(?:Exception|BaseException)(?:\s*\))?)?\s*:\s*(?:pass|\.\.\.)/.test(l)) {
252
275
  issues.push({ rule_id: 'clog/swallowed-error', title: 'Swallowed Exception (Silent Failure)', severity: 'HIGH', line: idx + 1, evidence: trim, fix: 'Log the error or properly re-raise/handle it.' });
253
276
  } else if (ext !== '.py' && /catch\s*\([^)]*\)\s*\{\s*\}/.test(l)) {
254
277
  issues.push({ rule_id: 'clog/swallowed-error', title: 'Swallowed Exception (Silent Failure)', severity: 'HIGH', line: idx + 1, evidence: trim, fix: 'Log the error or properly re-raise/handle it.' });
@@ -261,6 +284,7 @@ function inspectFile(relPath, content, lines, ext) {
261
284
  lines.forEach((l, idx) => {
262
285
  const trim = l.trim();
263
286
  if (trim.startsWith('#') || trim.startsWith('//')) return;
287
+ if (trim.includes('@openssh') || trim.includes('sk-ssh-') || trim.includes('sk-ecdsa-')) return;
264
288
  if (/\b(sk-(?:live|test|proj)?[a-zA-Z0-9_-]{24,})\b/.test(l)) {
265
289
  issues.push({ rule_id: 'leak/api-key', title: 'Leaked OpenAI / Model API Key', severity: 'CRITICAL', line: idx + 1, evidence: trim.slice(0, 70), fix: 'Extract secret to .env file immediately.' });
266
290
  }
@@ -415,6 +439,426 @@ function inspectFile(relPath, content, lines, ext) {
415
439
  return issues;
416
440
  }
417
441
 
442
+ function isGitHubWorkflowPath(filePath) {
443
+ return /(?:^|\/)\.github\/workflows\/[^/]+\.ya?ml$/i.test(String(filePath || '').replace(/\\/g, '/'));
444
+ }
445
+
446
+ function canonicalWorkflowPath(absPath, relPath) {
447
+ const rel = String(relPath || '').replace(/\\/g, '/');
448
+ if (isGitHubWorkflowPath(rel)) return rel;
449
+ const abs = String(absPath || '').replace(/\\/g, '/');
450
+ const marker = '.github/workflows/';
451
+ const idx = abs.toLowerCase().lastIndexOf(marker);
452
+ if (idx === -1) return rel;
453
+ const suffix = abs.slice(idx);
454
+ return isGitHubWorkflowPath(suffix) ? suffix : rel;
455
+ }
456
+
457
+ function collectWorkflowIssues(absPath, relPath, content, lines) {
458
+ const ext = path.extname(absPath).toLowerCase();
459
+ if (ext !== '.yml' && ext !== '.yaml') return [];
460
+ const workflowPath = canonicalWorkflowPath(absPath, relPath);
461
+ if (!isGitHubWorkflowPath(workflowPath)) return [];
462
+ try {
463
+ const doc = loadWorkflow(content, workflowPath);
464
+ if (!doc) return [];
465
+ return inspectWorkflow(doc, lines);
466
+ } catch (err) {
467
+ const detail = err && err.message ? err.message : String(err);
468
+ console.error(`[Error] Workflow scan failed for ${workflowPath}: ${detail}`);
469
+ return [];
470
+ }
471
+ }
472
+
473
+ function ruleById(id) {
474
+ for (let i = 0; i < RULES.length; i++) {
475
+ if (RULES[i].id === id) return RULES[i];
476
+ }
477
+ throw new Error('Unknown Plumber rule: ' + id);
478
+ }
479
+
480
+ function makeIssue(ruleId, line, evidence) {
481
+ const rule = ruleById(ruleId);
482
+ const text = evidence === undefined || evidence === null ? '' : String(evidence).trim();
483
+ return {
484
+ rule_id: rule.id,
485
+ title: rule.title,
486
+ severity: rule.sev,
487
+ line: line > 0 ? line : 1,
488
+ evidence: text.slice(0, 90),
489
+ fix: rule.fix
490
+ };
491
+ }
492
+
493
+ function loadWorkflow(content, workflowPath) {
494
+ let doc;
495
+ try {
496
+ // js-yaml 4 uses YAML 1.2, so the workflow key "on" stays a string.
497
+ doc = yaml.load(content, { schema: yaml.DEFAULT_SCHEMA });
498
+ } catch (err) {
499
+ const detail = err && err.message ? err.message : String(err);
500
+ console.error(`[Error] Failed to parse workflow YAML ${workflowPath}: ${detail}`);
501
+ return null;
502
+ }
503
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return null;
504
+ if (doc.on === undefined || doc.on === null) return null;
505
+ if (!doc.jobs || typeof doc.jobs !== 'object' || Array.isArray(doc.jobs)) return null;
506
+ return doc;
507
+ }
508
+
509
+ function inspectWorkflow(doc, lines) {
510
+ const found = [];
511
+ const seen = new Set();
512
+ function add(ruleId, line, evidence) {
513
+ const issue = makeIssue(ruleId, line, evidence);
514
+ const key = issue.rule_id + '\n' + issue.line + '\n' + issue.evidence;
515
+ if (seen.has(key)) return;
516
+ seen.add(key);
517
+ found.push(issue);
518
+ }
519
+ collectPullRequestTarget(doc, lines, add);
520
+ collectExpressionInjection(doc, lines, add);
521
+ collectUnpinnedActions(doc, lines, add);
522
+ collectJobPermissions(doc, lines, add);
523
+ collectSecrets(doc, lines, add);
524
+ return found;
525
+ }
526
+
527
+ function triggerNames(onValue) {
528
+ if (typeof onValue === 'string' || typeof onValue === 'number' || typeof onValue === 'boolean') {
529
+ return [String(onValue)];
530
+ }
531
+ if (Array.isArray(onValue)) {
532
+ const names = [];
533
+ for (let i = 0; i < onValue.length; i++) {
534
+ if (typeof onValue[i] === 'string') names.push(onValue[i]);
535
+ }
536
+ return names;
537
+ }
538
+ if (onValue && typeof onValue === 'object') return Object.keys(onValue);
539
+ return [];
540
+ }
541
+
542
+ function eachJob(doc, visit) {
543
+ const names = Object.keys(doc.jobs);
544
+ for (let i = 0; i < names.length; i++) {
545
+ const job = doc.jobs[names[i]];
546
+ if (!job || typeof job !== 'object' || Array.isArray(job)) continue;
547
+ visit(names[i], job);
548
+ }
549
+ }
550
+
551
+ function eachStep(job, visit) {
552
+ if (!Array.isArray(job.steps)) return;
553
+ for (let i = 0; i < job.steps.length; i++) {
554
+ const step = job.steps[i];
555
+ if (!step || typeof step !== 'object' || Array.isArray(step)) continue;
556
+ visit(step, i);
557
+ }
558
+ }
559
+
560
+ function scalarText(value) {
561
+ if (typeof value === 'string') return value;
562
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
563
+ return '';
564
+ }
565
+
566
+ function parseActionRef(uses) {
567
+ if (typeof uses !== 'string') return null;
568
+ const spec = uses.trim();
569
+ if (!spec || spec.startsWith('./') || spec.startsWith('docker://')) return null;
570
+ const at = spec.lastIndexOf('@');
571
+ const name = (at === -1 ? spec : spec.slice(0, at)).trim();
572
+ const ref = at === -1 ? '' : spec.slice(at + 1).trim();
573
+ if (!name.includes('/')) return null;
574
+ const owner = name.split('/')[0];
575
+ if (!owner) return null;
576
+ return {
577
+ spec: spec,
578
+ name: name,
579
+ owner: owner,
580
+ ref: ref,
581
+ thirdParty: !FIRST_PARTY_OWNERS.has(owner),
582
+ pinned: FULL_SHA.test(ref)
583
+ };
584
+ }
585
+
586
+ function permissionsGrantWrite(perms) {
587
+ if (typeof perms === 'string') return perms.trim().toLowerCase() === 'write-all';
588
+ if (!perms || typeof perms !== 'object' || Array.isArray(perms)) return false;
589
+ const keys = Object.keys(perms);
590
+ for (let i = 0; i < keys.length; i++) {
591
+ if (String(perms[keys[i]]).trim().toLowerCase() === 'write') return true;
592
+ }
593
+ return false;
594
+ }
595
+
596
+ function jobEffectivePerms(doc, job) {
597
+ if (job && job.permissions !== undefined && job.permissions !== null) return job.permissions;
598
+ if (doc.permissions !== undefined && doc.permissions !== null) return doc.permissions;
599
+ return undefined;
600
+ }
601
+
602
+ function valueHasSecret(value, depth) {
603
+ if (depth > 8 || value === null || value === undefined) return false;
604
+ if (typeof value === 'string') return SECRET_REF.test(value);
605
+ if (typeof value !== 'object') return false;
606
+ if (Array.isArray(value)) {
607
+ for (let i = 0; i < value.length; i++) {
608
+ if (valueHasSecret(value[i], depth + 1)) return true;
609
+ }
610
+ return false;
611
+ }
612
+ const keys = Object.keys(value);
613
+ for (let i = 0; i < keys.length; i++) {
614
+ if (valueHasSecret(value[keys[i]], depth + 1)) return true;
615
+ }
616
+ return false;
617
+ }
618
+
619
+ function collectPullRequestTarget(doc, lines, add) {
620
+ if (triggerNames(doc.on).indexOf('pull_request_target') === -1) return;
621
+ let cursor = 0;
622
+ eachJob(doc, function (name, job) {
623
+ eachStep(job, function (step) {
624
+ if (!checkoutRefIsUntrusted(step)) return;
625
+ const ref = scalarText(step.with && step.with.ref);
626
+ const snippet = ref || scalarText(step.uses);
627
+ const line = lineContainingFrom(lines, snippet.slice(0, 80), cursor);
628
+ cursor = line;
629
+ add('sec/pull-request-target', line, lines[line - 1] || snippet);
630
+ });
631
+ if (permissionsGrantWrite(jobEffectivePerms(doc, job))) {
632
+ const line = lineOfAppliedPermissions(lines, name, jobEffectivePerms(doc, job));
633
+ add('sec/pull-request-target', line, lines[line - 1] || 'permissions');
634
+ }
635
+ });
636
+ }
637
+
638
+ function checkoutRefIsUntrusted(step) {
639
+ if (typeof step.uses !== 'string' || !/^actions\/checkout(?:@|\/|\s|$)/.test(step.uses.trim())) return false;
640
+ const withBlock = step.with;
641
+ if (!withBlock || typeof withBlock !== 'object' || Array.isArray(withBlock)) return false;
642
+ const ref = scalarText(withBlock.ref);
643
+ const repository = scalarText(withBlock.repository);
644
+ if (ref && UNTRUSTED_CHECKOUT.test(ref)) return true;
645
+ if (repository && /github\.event\.pull_request\.head/.test(repository)) return true;
646
+ return false;
647
+ }
648
+
649
+ function collectExpressionInjection(doc, lines, add) {
650
+ let cursor = 0;
651
+ eachJob(doc, function (name, job) {
652
+ eachStep(job, function (step) {
653
+ const run = scalarText(step.run);
654
+ if (!run) return;
655
+ const match = INJECTED_EXPR.exec(run);
656
+ if (!match) return;
657
+ const located = lineOfInjectedRun(lines, match[0], cursor);
658
+ cursor = located.next;
659
+ add('sec/expression-injection', located.line, lines[located.line - 1] || run);
660
+ });
661
+ });
662
+ }
663
+
664
+ function collectUnpinnedActions(doc, lines, add) {
665
+ let cursor = 0;
666
+ eachJob(doc, function (name, job) {
667
+ cursor = flagUnpinned(lines, job.uses, cursor, add);
668
+ eachStep(job, function (step) {
669
+ cursor = flagUnpinned(lines, step.uses, cursor, add);
670
+ });
671
+ });
672
+ }
673
+
674
+ function flagUnpinned(lines, uses, cursor, add) {
675
+ const action = parseActionRef(uses);
676
+ if (!action || !action.thirdParty || action.pinned) return cursor;
677
+ const line = lineOfUses(lines, action.spec, cursor);
678
+ add('pipe/action-unpinned', line, lines[line - 1] || action.spec);
679
+ return line;
680
+ }
681
+
682
+ function collectJobPermissions(doc, lines, add) {
683
+ eachJob(doc, function (name, job) {
684
+ const kinds = jobWriteKinds(job);
685
+ if (!kinds.contents && !kinds.deploy) return;
686
+ const hasJobPerms = job.permissions !== undefined && job.permissions !== null;
687
+ const hasWorkflowPerms = doc.permissions !== undefined && doc.permissions !== null;
688
+ const perms = hasJobPerms ? job.permissions : (hasWorkflowPerms ? doc.permissions : undefined);
689
+ const info = describePermissions(perms);
690
+ let reason = '';
691
+ if (!info) reason = 'missing';
692
+ else if (info.writeAll) reason = 'write-all';
693
+ else if (info.contentsWrite && kinds.deploy && !kinds.contents) reason = 'contents-write';
694
+ else return;
695
+ const line = lineForJobPermission(lines, name, reason);
696
+ add('sec/job-permissions', line, lines[line - 1] || name);
697
+ });
698
+ }
699
+
700
+ function jobWriteKinds(job) {
701
+ const kinds = { contents: false, deploy: false };
702
+ eachStep(job, function (step) {
703
+ const run = scalarText(step.run);
704
+ if (CONTENTS_WRITE_RUN.test(run)) kinds.contents = true;
705
+ if (DEPLOY_RUN.test(run)) kinds.deploy = true;
706
+ const action = parseActionRef(step.uses);
707
+ if (!action) return;
708
+ if (CONTENTS_ACTIONS.has(action.name)) kinds.contents = true;
709
+ if (action.name === 'actions/deploy-pages') kinds.deploy = true;
710
+ if (action.name === 'docker/build-push-action') {
711
+ const push = step.with && step.with.push;
712
+ if (push === true || String(push).toLowerCase() === 'true') kinds.deploy = true;
713
+ }
714
+ });
715
+ return kinds;
716
+ }
717
+
718
+ function describePermissions(perms) {
719
+ if (perms === undefined || perms === null) return null;
720
+ if (typeof perms === 'string') {
721
+ const value = perms.trim().toLowerCase();
722
+ return { writeAll: value === 'write-all', contentsWrite: value === 'write-all' };
723
+ }
724
+ if (typeof perms !== 'object' || Array.isArray(perms)) return null;
725
+ const contents = perms.contents === undefined || perms.contents === null ? '' : String(perms.contents).trim().toLowerCase();
726
+ return { writeAll: false, contentsWrite: contents === 'write' };
727
+ }
728
+
729
+ function collectSecrets(doc, lines, add) {
730
+ let cursor = 0;
731
+ eachJob(doc, function (name, job) {
732
+ const inherited = valueHasSecret(doc.env, 0) || valueHasSecret(job.env, 0);
733
+ const jobAction = parseActionRef(job.uses);
734
+ if (jobAction && jobAction.thirdParty && (job.secrets === 'inherit' || valueHasSecret(job.secrets, 0) || inherited)) {
735
+ const line = lineOfUses(lines, jobAction.spec, cursor);
736
+ cursor = line;
737
+ add('sec/secret-to-untrusted', line, lines[line - 1] || jobAction.spec);
738
+ }
739
+ eachStep(job, function (step) {
740
+ const action = parseActionRef(step.uses);
741
+ if (!action || !action.thirdParty) return;
742
+ const onStep = valueHasSecret(step.env, 0) || valueHasSecret(step.with, 0);
743
+ if (!onStep && !inherited) return;
744
+ const line = onStep
745
+ ? lineContainingFrom(lines, 'secrets.', cursor)
746
+ : lineOfUses(lines, action.spec, cursor);
747
+ cursor = line;
748
+ add('sec/secret-to-untrusted', line, lines[line - 1] || action.spec);
749
+ });
750
+ });
751
+ }
752
+
753
+ function lineContainingFrom(lines, snippet, start) {
754
+ const needle = String(snippet);
755
+ const from = start > 0 ? start : 0;
756
+ for (let i = from; i < lines.length; i++) {
757
+ if (lines[i].includes(needle)) return i + 1;
758
+ }
759
+ for (let i = 0; i < from; i++) {
760
+ if (lines[i].includes(needle)) return i + 1;
761
+ }
762
+ return 1;
763
+ }
764
+
765
+ function lineOfUses(lines, spec, cursor) {
766
+ const from = cursor > 0 ? cursor : 0;
767
+ for (let i = from; i < lines.length; i++) {
768
+ if (lines[i].includes(spec) && /uses\s*:/.test(lines[i])) return i + 1;
769
+ }
770
+ return lineContainingFrom(lines, spec, 0);
771
+ }
772
+
773
+ function lineOfInjectedRun(lines, snippet, cursor) {
774
+ const runKey = /^\s*(?:-\s+)?run\s*:/;
775
+ const start = cursor > 0 ? cursor : 0;
776
+ for (let i = start; i < lines.length; i++) {
777
+ if (!runKey.test(lines[i])) continue;
778
+ const indent = lines[i].search(/\S/);
779
+ if (lines[i].includes(snippet)) return { line: i + 1, next: i + 1 };
780
+ let found = 0;
781
+ let end = i + 1;
782
+ for (let j = i + 1; j < lines.length; j++) {
783
+ if (!lines[j].trim()) continue;
784
+ if (lines[j].search(/\S/) <= indent) break;
785
+ end = j + 1;
786
+ if (!found && lines[j].includes(snippet)) found = j + 1;
787
+ }
788
+ if (found) return { line: found, next: end };
789
+ if (/\*[A-Za-z0-9_-]+/.test(lines[i])) {
790
+ return { line: lineContainingFrom(lines, snippet, 0), next: i + 1 };
791
+ }
792
+ }
793
+ return { line: lineContainingFrom(lines, snippet, 0), next: lines.length };
794
+ }
795
+
796
+ function findJobLine(lines, jobName) {
797
+ const pattern = new RegExp('^ ' + escapeRegExp(jobName) + '\\s*:');
798
+ let seenJobs = false;
799
+ for (let i = 0; i < lines.length; i++) {
800
+ if (/^jobs\s*:/.test(lines[i])) {
801
+ seenJobs = true;
802
+ continue;
803
+ }
804
+ if (seenJobs && pattern.test(lines[i])) return i + 1;
805
+ }
806
+ return 1;
807
+ }
808
+
809
+ function nextJobBoundary(lines, jobLine) {
810
+ for (let i = jobLine; i < lines.length; i++) {
811
+ if (/^ [A-Za-z0-9_-]+\s*:/.test(lines[i])) return i;
812
+ }
813
+ return lines.length;
814
+ }
815
+
816
+ function findLineMatching(lines, pattern, start, end) {
817
+ const from = Math.max(0, start);
818
+ const to = Math.min(lines.length, end);
819
+ for (let i = from; i < to; i++) {
820
+ if (pattern.test(lines[i])) return i + 1;
821
+ }
822
+ return 0;
823
+ }
824
+
825
+ function lineOfAppliedPermissions(lines, jobName, perms) {
826
+ const jobAt = findJobLine(lines, jobName);
827
+ const regionEnd = nextJobBoundary(lines, jobAt);
828
+ if (typeof perms === 'string' && perms.trim().toLowerCase() === 'write-all') {
829
+ return findLineMatching(lines, /permissions\s*:\s*['"]?write-all['"]?/, jobAt - 1, regionEnd)
830
+ || findLineMatching(lines, /permissions\s*:\s*['"]?write-all['"]?/, 0, lines.length)
831
+ || jobAt;
832
+ }
833
+ return findLineMatching(lines, /^\s*.+:\s*['"]?write['"]?\s*(?:#.*)?$/, jobAt - 1, regionEnd)
834
+ || findLineMatching(lines, /^\s*permissions\s*:/, jobAt - 1, regionEnd)
835
+ || findLineMatching(lines, /^permissions\s*:/, 0, lines.length)
836
+ || jobAt;
837
+ }
838
+
839
+ function lineForJobPermission(lines, jobName, reason) {
840
+ const jobAt = findJobLine(lines, jobName);
841
+ const regionEnd = nextJobBoundary(lines, jobAt);
842
+ if (reason === 'write-all') {
843
+ return findLineMatching(lines, /permissions\s*:\s*['"]?write-all['"]?/, 0, lines.length) || jobAt;
844
+ }
845
+ if (reason === 'contents-write') {
846
+ return findLineMatching(lines, /contents\s*:\s*['"]?write['"]?/, jobAt - 1, regionEnd)
847
+ || findLineMatching(lines, /contents\s*:\s*['"]?write['"]?/, 0, lines.length)
848
+ || jobAt;
849
+ }
850
+ return findLineMatching(
851
+ lines,
852
+ /git\s+push|gh\s+release|gh\s+pr\s+merge|npm\s+publish|pnpm\s+publish|docker\s+push|twine\s+upload|action-gh-release|actions-gh-pages|release-action|deploy-pages|build-push-action/,
853
+ jobAt - 1,
854
+ regionEnd
855
+ ) || jobAt;
856
+ }
857
+
858
+ function escapeRegExp(value) {
859
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
860
+ }
861
+
418
862
  function findDeadCode(content, ext) {
419
863
  if (!['.py', '.js', '.jsx', '.ts', '.tsx'].includes(ext)) return [];
420
864
  const lines = content.split('\n');
@@ -479,6 +923,93 @@ function findUnreachable(lines, start, indent, skip, isPy) {
479
923
  return null;
480
924
  }
481
925
 
926
+ function sarifLevel(severity) {
927
+ const level = String(severity || '').toUpperCase();
928
+ if (level === 'CRITICAL' || level === 'HIGH') return 'error';
929
+ if (level === 'MEDIUM') return 'warning';
930
+ return 'note';
931
+ }
932
+
933
+ function readPackageVersion() {
934
+ const pkgPath = path.join(__dirname, '..', 'package.json');
935
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
936
+ if (typeof pkg.version !== 'string' || pkg.version.length === 0) {
937
+ throw new Error(`Missing version in ${pkgPath}`);
938
+ }
939
+ return pkg.version;
940
+ }
941
+
942
+ function sarifArtifactUri(filePath) {
943
+ return String(filePath).replace(/\\/g, '/').split('/').map((segment) => encodeURIComponent(segment)).join('/');
944
+ }
945
+
946
+ function sarifMessage(issue) {
947
+ const explanation = String(issue.title || issue.rule_id || 'Plumber finding').trim();
948
+ const sentence = /[.!?]$/.test(explanation) ? explanation : `${explanation}.`;
949
+ const fix = String(issue.fix || '').trim();
950
+ if (!fix) return sentence;
951
+ return `${sentence} Fix: ${fix}`;
952
+ }
953
+
954
+ function sarifResult(issue, filePath, ruleIndexById) {
955
+ const result = { ruleId: issue.rule_id };
956
+ const ruleIndex = ruleIndexById.get(issue.rule_id);
957
+ if (ruleIndex !== undefined) result.ruleIndex = ruleIndex;
958
+ result.level = sarifLevel(issue.severity);
959
+ result.message = { text: sarifMessage(issue) };
960
+ if (filePath) {
961
+ const physicalLocation = {
962
+ artifactLocation: { uri: sarifArtifactUri(filePath) }
963
+ };
964
+ // Region is omitted when the engine has no line. Line 1 is not invented.
965
+ if (Number.isInteger(issue.line) && issue.line >= 1) {
966
+ physicalLocation.region = { startLine: issue.line };
967
+ }
968
+ result.locations = [{ physicalLocation }];
969
+ }
970
+ return result;
971
+ }
972
+
973
+ function buildSarif(report) {
974
+ const ruleIndexById = new Map(RULES.map((rule, index) => [rule.id, index]));
975
+ const covered = new Set();
976
+ const results = [];
977
+ for (const file of report.file_reports || []) {
978
+ for (const issue of file.issues) {
979
+ covered.add(issue);
980
+ results.push(sarifResult(issue, file.path, ruleIndexById));
981
+ }
982
+ }
983
+ for (const issue of report.issues || []) {
984
+ if (!covered.has(issue)) results.push(sarifResult(issue, null, ruleIndexById));
985
+ }
986
+
987
+ return {
988
+ $schema: SARIF_SCHEMA,
989
+ version: '2.1.0',
990
+ runs: [
991
+ {
992
+ tool: {
993
+ driver: {
994
+ name: 'plumber-linter',
995
+ version: readPackageVersion(),
996
+ informationUri: INFORMATION_URI,
997
+ rules: RULES.map((rule) => ({
998
+ id: rule.id,
999
+ name: rule.title,
1000
+ shortDescription: { text: rule.title },
1001
+ fullDescription: { text: rule.title },
1002
+ help: { text: rule.fix },
1003
+ defaultConfiguration: { level: sarifLevel(rule.sev) }
1004
+ }))
1005
+ }
1006
+ },
1007
+ results
1008
+ }
1009
+ ]
1010
+ };
1011
+ }
1012
+
482
1013
  function renderReport(report, fmt, failOn) {
483
1014
  if (fmt === 'json') {
484
1015
  console.log(JSON.stringify(report, null, 2));
@@ -491,6 +1022,8 @@ function renderReport(report, fmt, failOn) {
491
1022
  console.log(`- **L${i.line} [${i.severity}] ${i.title}**: ${i.fix}`);
492
1023
  }
493
1024
  }
1025
+ } else if (fmt === 'sarif') {
1026
+ console.log(JSON.stringify(buildSarif(report), null, 2));
494
1027
  } else {
495
1028
  console.log('\n' + '='.repeat(64));
496
1029
  console.log(` PLUMBER INSPECTION REPORT: ${report.repo_name}`);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "plumber-linter",
3
- "version": "1.2.0",
4
- "description": "CI/CD pipeline linter that flags hardcoded secrets, leaked credentials, and dead code — with fixes in plain English.",
3
+ "version": "1.4.0",
4
+ "description": "CI/CD pipeline linter that flags hardcoded secrets, leaked credentials, and dead code — with fixes in plain English, plus SARIF output for GitHub code scanning and workflow YAML scanning for GitHub Actions.",
5
5
  "main": "bin/plumber.js",
6
6
  "bin": {
7
7
  "plumber": "bin/plumber.js",
@@ -22,7 +22,11 @@
22
22
  "cli",
23
23
  "docker",
24
24
  "supply-chain",
25
- "slack"
25
+ "slack",
26
+ "sarif",
27
+ "github-code-scanning",
28
+ "yaml",
29
+ "workflow-scanning"
26
30
  ],
27
31
  "author": "Paras Raju",
28
32
  "license": "MIT",
@@ -37,6 +41,9 @@
37
41
  "engines": {
38
42
  "node": ">=18.0.0"
39
43
  },
44
+ "dependencies": {
45
+ "js-yaml": "^4.3.2"
46
+ },
40
47
  "files": [
41
48
  "bin",
42
49
  "README.md"