Top Level Namespace

Defined Under Namespace

Modules: AiFix, AutoFix, Formatter, Platforms, Rules, Sentinel, TokenResolver Classes: CloneClient, Finding, GitHubClient, LocalClient, MockShaResolver, Policy, RuleEngine, Scanner, ShaResolver, SupplyChain, Workflow

Constant Summary collapse

HOOK_MARKER_BEGIN =
"# --- sentinel pre-commit hook begin ---"
HOOK_MARKER_END =
"# --- sentinel pre-commit hook end ---"
HOOK_SCRIPT =
<<~'BASH'
#!/usr/bin/env bash
# --- sentinel pre-commit hook begin ---
# Sentinel pre-commit hook — scans workflow files for security issues

# Only run if workflow files are staged
STAGED=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.github/workflows/.*\.ya?ml$')
if [ -z "$STAGED" ]; then
  exit 0
fi

# Run sentinel scan
if command -v sentinel &>/dev/null; then
  sentinel scan --local . --severity high
  exit $?
elif command -v ruby &>/dev/null; then
  ruby -e 'require "rubygems"; gem "sentinel-ci"; load Gem.bin_path("sentinel-ci", "sentinel")' scan --local . --severity high 2>/dev/null
  exit $?
else
  echo "Warning: sentinel not found. Install with: gem install sentinel-ci"
  exit 0
fi
# --- sentinel pre-commit hook end ---
BASH

Instance Method Summary collapse

Instance Method Details

#build_fix_pr_body(result) ⇒ Object


Build PR body from fix results




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
# File 'lib/cli/fix.rb', line 353

def build_fix_pr_body(result)
    lines = []
    lines << "## Security fixes applied by sentinel"
    lines << ""
    lines << "This PR was automatically generated by [sentinel](https://github.com/jpr5/sentinel)."
    lines << ""
    lines << "### Changes"
    lines << ""

    result[:mechanical_details].each do |filename, details|
        lines << "**#{filename}** (mechanical):"
        details.each { |d| lines << d }
        lines << ""
    end

    result[:ai_details].each do |filename, details|
        lines << "**#{filename}** (AI-assisted):"
        details.each { |d| lines << d }
        lines << ""
    end

    if result[:ai_count] > 0
        lines << "> **Note:** AI-generated fixes should be reviewed carefully before merging."
        lines << ""
    end

    lines << "---"
    lines << "*[sentinel](https://github.com/jpr5/sentinel) | [Report false positive](https://github.com/jpr5/sentinel/issues)*"

    lines.join("\n")
end

#changed_files_for_pr(result) ⇒ Object


Build files hash for PrWriter (path => content)




336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/cli/fix.rb', line 336

def changed_files_for_pr(result)
    files = {}
    all_changed = (result[:mechanical_details].keys + result[:ai_details].keys).uniq

    all_changed.each do |filename|
        original = result[:original_contents][filename] || ""
        content = result[:file_contents][filename]
        next unless content && content != original
        files[".github/workflows/#{filename}"] = content
    end

    files
end

Display fix summary




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
# File 'lib/cli/fix.rb', line 237

def print_fix_summary(result, options)
    mechanical_details = result[:mechanical_details]
    ai_details = result[:ai_details]
    ai_count = result[:ai_count]
    mechanical_count = result[:mechanical_count]
    skipped = result[:skipped]

    puts ""

    mechanical_details.each do |filename, details|
        action = options[:dry_run] ? "Would fix (mechanical)" : "Fixed (mechanical)"
        puts "#{action}: .github/workflows/#{filename}"
        details.each { |d| puts d }
        puts ""
    end

    ai_details.each do |filename, details|
        action = options[:dry_run] ? "Would fix (AI)" : "Fixed (AI)"
        puts "#{action}: .github/workflows/#{filename}"
        details.each { |d| puts d }
        puts ""
    end

    if skipped.any?
        puts "Skipped (no auto-fix, no --ai):"
        skipped.each do |f|
            puts "  - #{f.rule}: #{f.file}:#{f.line}"
        end
        puts ""
    end

    if ai_count > 0
        puts "⚠ AI-generated fixes should be reviewed before merging."
        puts ""
    end

    total_fixed = mechanical_count + ai_count
    manual_count = skipped.length
    verb = options[:dry_run] ? "would be fixed" : "fixed"
    parts = ["#{total_fixed} findings #{verb}"]
    parts << "#{mechanical_count} mechanical" if mechanical_count > 0 && ai_count > 0
    parts << "#{ai_count} AI" if ai_count > 0
    parts << "#{manual_count} require manual review" if manual_count > 0
    puts parts.join(", ") + "."
end

#scan_and_fix(workflows_dir, scan_target, options, ai_key) ⇒ Object


Shared fix logic — operates on a workflows_dir, returns fix results




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
# File 'lib/cli/fix.rb', line 113

def scan_and_fix(workflows_dir, scan_target, options, ai_key)
    $stderr.puts "Scanning..."

    client = LocalClient.new(File.dirname(File.dirname(workflows_dir)))
    formatter = Formatter::Terminal.new
    scanner = Scanner.new(client: client, formatter: formatter, min_severity: options[:severity])
    result = scanner.scan(scan_target)
    findings = result[:findings]

    mechanical = findings.select { |f| AutoFix.can_fix?(f) }
    ai_eligible = findings.select { |f| AiFix.can_fix?(f) }

    $stderr.puts "Found #{findings.length} findings (#{mechanical.length} mechanical, #{ai_eligible.length} AI-eligible)"
    $stderr.puts ""

    if mechanical.empty? && (!options[:ai] || ai_eligible.empty?)
        $stderr.puts "No fixable findings."
        return nil
    end

    # --- Read raw file contents ---
    all_fixable_files = (mechanical + (options[:ai] ? ai_eligible : [])).map(&:file).uniq
    file_contents = {}
    original_contents = {}
    all_fixable_files.each do |filename|
        path = File.join(workflows_dir, filename)
        if File.exist?(path)
            file_contents[filename] = File.read(path)
            original_contents[filename] = file_contents[filename].dup
        end
    end

    # --- Pass 1: Mechanical fixes ---
    mechanical_details = Hash.new { |h, k| h[k] = [] }
    mechanical_count = 0

    by_file_mechanical = mechanical.group_by(&:file)
    by_file_mechanical.each do |filename, file_findings|
        content = file_contents[filename]
        next unless content

        sorted = file_findings.sort_by { |f| -(f.line || 0) }

        sorted.each do |finding|
            content = AutoFix.apply(finding, content)

            detail = case finding.rule
            when "unpinned-actions"
                action_match = finding.code&.match(/uses:\s*(\S+)/)
                action_ref = action_match ? action_match[1] : finding.code
                "unpinned-actions: #{action_ref} pinned to SHA"
            when "shell-injection-expr"
                "shell-injection-expr: moved expression to env block"
            when "missing-persist-credentials"
                "missing-persist-credentials: added persist-credentials: false"
            when "workflow-dispatch-injection"
                "workflow-dispatch-injection: moved dispatch input to env block"
            when "missing-permissions"
                "missing-permissions: added permissions: contents: read"
            when "missing-timeouts"
                job_match = finding.message&.match(/job '([^']+)'/) || finding.message&.match(/job "([^"]+)"/)
                job_name = job_match ? job_match[1] : "job"
                "missing-timeouts: added timeout-minutes: 30 to #{job_name}"
            else
                "#{finding.rule}: applied fix"
            end

            mechanical_details[filename] << "  - #{detail}"
            mechanical_count += 1
        end

        file_contents[filename] = content
    end

    # --- Pass 2: AI fixes (if --ai is set) ---
    ai_details = Hash.new { |h, k| h[k] = [] }
    ai_count = 0
    ai_model = options[:model] || AiFix::DEFAULT_MODEL

    if options[:ai] && ai_key
        by_file_ai = ai_eligible.group_by(&:file)
        by_file_ai.each do |filename, file_findings|
            content = file_contents[filename]
            next unless content

            file_findings.each do |finding|
                $stderr.puts "  AI fixing #{finding.rule} in #{filename}:#{finding.line}..."
                fixed = AiFix.apply(finding, content, model: ai_model, api_key: ai_key)

                if fixed
                    content = fixed
                    ai_details[filename] << "  - #{finding.rule}: AI-generated fix applied"
                    ai_count += 1
                else
                    $stderr.puts "  AI fix failed for #{finding.rule} in #{filename}:#{finding.line}"
                end
            end

            file_contents[filename] = content
        end
    end

    # Skipped findings
    skipped = if options[:ai]
        []
    else
        ai_eligible
    end

    {
        file_contents: file_contents,
        original_contents: original_contents,
        mechanical_details: mechanical_details,
        mechanical_count: mechanical_count,
        ai_details: ai_details,
        ai_count: ai_count,
        skipped: skipped,
        findings: findings,
    }
end

#show_diffs(result, workflows_dir) ⇒ Object


Show unified diffs for changed files




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
# File 'lib/cli/fix.rb', line 286

def show_diffs(result, workflows_dir)
    require "tempfile"

    all_changed_files = (result[:mechanical_details].keys + result[:ai_details].keys).uniq

    all_changed_files.each do |filename|
        original = result[:original_contents][filename] || ""
        content = result[:file_contents][filename]

        next unless content && content != original

        orig_file = Tempfile.new(["orig", ".yml"])
        fixed_file = Tempfile.new(["fixed", ".yml"])
        begin
            orig_file.write(original)
            orig_file.flush
            fixed_file.write(content)
            fixed_file.flush

            diff_output = `diff -u #{orig_file.path} #{fixed_file.path} 2>&1`
            diff_output.sub!(/^--- .*$/, "--- .github/workflows/#{filename}")
            diff_output.sub!(/^\+\+\+ .*$/, "+++ .github/workflows/#{filename} (fixed)")
            puts diff_output
            puts ""
        ensure
            orig_file.close!
            fixed_file.close!
        end
    end
end

#write_fixes(result, workflows_dir) ⇒ Object


Write fixed files to disk




320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/cli/fix.rb', line 320

def write_fixes(result, workflows_dir)
    all_changed_files = (result[:mechanical_details].keys + result[:ai_details].keys).uniq

    all_changed_files.each do |filename|
        path = File.join(workflows_dir, filename)
        original = File.exist?(path) ? File.read(path) : ""
        content = result[:file_contents][filename]

        next unless content && content != original
        File.write(path, content)
    end
end