Class: ShieldAst::Main

Inherits:
Object
  • Object
show all
Defined in:
lib/shield_ast.rb

Overview

Main class for the Shield AST command-line tool.

Constant Summary collapse

SCAN_DATA_FILE =
File.join(Dir.pwd, "reports", "scan_data.json")
REPORT_JSON_FILE =
File.join(Dir.pwd, "reports", "scan_report.json")
REPORT_PDF_FILE =
File.join(Dir.pwd, "reports", "scan_report.pdf")
PDF_TEMPLATE =
File.join(Dir.pwd, "reports", "templates", "pdf_report_template.rb")

Class Method Summary collapse

Class Method Details

.apply_default_scanners(options) ⇒ Object



195
196
197
198
199
200
201
202
203
# File 'lib/shield_ast.rb', line 195

def self.apply_default_scanners(options)
  options.tap do |o|
    if !o[:sast] && !o[:sca] && !o[:iac]
      o[:sast] = true
      o[:sca] = true
      o[:iac] = true
    end
  end
end


415
416
417
418
419
420
421
422
423
424
425
426
427
# File 'lib/shield_ast.rb', line 415

def self.banner
  gray = "\e[90m"
  white = "\e[97m"
  bold = "\e[1m"
  reset = "\e[0m"

  title = "Shield AST v#{ShieldAst::VERSION}"
  line_char = "─"
  line_segment = line_char * 10

  puts "#{gray}#{line_segment}┤#{reset} #{bold}#{white}#{title}#{reset} #{gray}├#{line_segment}#{reset}"
  puts ""
end

.calculate_severity_summary(reports) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/shield_ast.rb', line 298

def self.calculate_severity_summary(reports)
  error_count = 0
  warning_count = 0
  info_count = 0

  reports.each_value do |report_data|
    (report_data[:results] || report_data["results"] || []).each do |result|
      severity = result[:severity] || result["severity"] || result.dig(:extra,
                                                                       :severity) || result.dig("extra", "severity")
      case severity&.upcase
      when "ERROR" then error_count += 1
      when "WARNING" then warning_count += 1
      when "INFO" then info_count += 1
      end
    end
  end

  { error_count: error_count, warning_count: warning_count, info_count: info_count }
end

.calculate_total_issues(reports) ⇒ Object



188
189
190
191
192
193
# File 'lib/shield_ast.rb', line 188

def self.calculate_total_issues(reports)
  sast_count = (reports[:sast]&.[](:results) || reports["sast"]&.[]("results") || []).length
  sca_count = (reports[:sca]&.[](:results) || reports["sca"]&.[]("results") || []).length
  iac_count = (reports[:iac]&.[](:results) || reports["iac"]&.[]("results") || []).length
  sast_count + sca_count + iac_count
end

.call(args) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/shield_ast.rb', line 25

def self.call(args)
  banner

  unless scanner_exists?("osv-scanner") && scanner_exists?("opengrep")
    puts "\e[31m[!] ERROR:\e[0m Required tools not found."
    puts "    Install: \e[33mosv-scanner\e[0m, \e[33mopengrep\e[0m"
    exit 1
  end

  options = parse_args(args)
  handle_options(options)
end

.display_reports(reports) ⇒ Object



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
# File 'lib/shield_ast.rb', line 205

def self.display_reports(reports)
  gemini_enabled = !ENV["GEMINI_API_KEY"].to_s.empty?

  total_issues = flatten_findings(reports).length

  if total_issues.zero?
    puts "✅ No security issues found! Your code looks clean."
    return
  end

  puts "\nScan Results:"
  if gemini_enabled
    model = ENV.fetch("GEMINI_MODEL", "gemini-2.5-flash")
    puts "\e[34m🔑 Gemini API key found. False positive analysis enabled (this may slow down the scan).\e[0m"
    puts "🤖 AI Model: #{model}"
  end

  reports.each do |scan_type, report_data|
    next unless report_data.is_a?(Hash)

    results = report_data[:results] || report_data["results"] || []
    next if results.empty?

    sorted_results = sort_by_severity(results)

    top_results = sorted_results.first(5)
    remaining_count = sorted_results.length - top_results.length

    puts "\n#{get_scan_icon(scan_type.to_sym)} #{scan_type.to_s.upcase} (#{results.length} #{results.length == 1 ? "issue" : "issues"}#{remaining_count.positive? ? ", showing top 5" : ""})"
    puts "-" * 60

    top_results.each do |result|
      if scan_type.to_sym == :sca && has_sca_format?(result)
        format_sca_result(result)
      else
        fp_indicator = gemini_enabled ? ShieldAst::AiAnalyzer.new(result).call : ""
        format_default_result(result, fp_indicator)
      end
      puts ""
    end

    if remaining_count.positive?
      puts "... and #{remaining_count} more #{remaining_count == 1 ? "issue" : "issues"}. See the full report for details."
    end
  end

  puts "\n#{"=" * 60}"
  severity_summary = calculate_severity_summary(reports)
  puts "📊 Total: #{total_issues} findings {error_count: #{severity_summary[:error_count]}, warning_count: #{severity_summary[:warning_count]}, info_count: #{severity_summary[:info_count]}}"
end

.flatten_findings(reports) ⇒ Object



376
377
378
379
380
381
382
383
384
385
386
# File 'lib/shield_ast.rb', line 376

def self.flatten_findings(reports)
  findings = []
  reports.each do |scan_type, report_data|
    results = report_data[:results] || report_data["results"] || []

    results.each do |result|
      findings << result.merge(scan_type: scan_type.to_sym)
    end
  end
  sort_by_severity(findings)
end

.format_default_result(result, fp_indicator = "") ⇒ Object



343
344
345
346
347
348
349
350
351
352
# File 'lib/shield_ast.rb', line 343

def self.format_default_result(result, fp_indicator = "")
  severity_icon = get_severity_icon(result.dig("extra", "severity") || result["severity"])
  message = result.dig("extra", "message") || result["check_id"] || "Unknown issue"
  title = message.split(".").first&.strip || message
  file_info = "#{result["path"] || "N/A"}:#{result.dig("start", "line") || "N/A"}"

  puts "  #{severity_icon} #{title}#{fp_indicator}"
  puts "     📁 #{file_info}"
  puts "        #{message}"
end

.format_duration(seconds) ⇒ Object



318
319
320
321
322
323
324
325
326
327
328
# File 'lib/shield_ast.rb', line 318

def self.format_duration(seconds)
  if seconds < 1
    "#{(seconds * 1000).round}ms"
  elsif seconds < 60
    "#{seconds.round(1)}s"
  else
    minutes = (seconds / 60).floor
    remaining_seconds = (seconds % 60).round
    "#{minutes}m #{remaining_seconds}s"
  end
end

.format_report(results, scan_type) ⇒ Object



269
270
271
272
273
274
275
276
277
278
# File 'lib/shield_ast.rb', line 269

def self.format_report(results, scan_type)
  results.each_with_index do |result, index|
    if scan_type == :sca && has_sca_format?(result)
      format_sca_result(result)
    else
      format_default_result(result)
    end
    puts "" if index < results.length - 1
  end
end

.format_sca_result(result) ⇒ Object



337
338
339
340
341
# File 'lib/shield_ast.rb', line 337

def self.format_sca_result(result)
  severity_icon = get_severity_icon(result[:severity] || result["severity"])
  puts "  #{severity_icon} #{result[:title] || result["title"]} (#{result[:vulnerable_version] || result["vulnerable_version"]} → #{result[:fixed_version] || result["fixed_version"]})"
  puts "     📁 #{result[:file] || result["file"]} | #{(result[:description] || result["description"] || "")[0..80]}#{(result[:description] || result["description"] || "").length > 80 ? "..." : ""}"
end

.generate_json_report(scan_data) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/shield_ast.rb', line 127

def self.generate_json_report(scan_data)
  FileUtils.mkdir_p(File.dirname(REPORT_JSON_FILE))
  report = {
    generated_at: scan_data[:generated_at],
    scan_duration: format_duration(scan_data[:execution_time]),
    total_issues: calculate_total_issues(scan_data[:reports]),
    severity_summary: calculate_severity_summary(scan_data[:reports]),
    reports: scan_data[:reports]
  }
  File.write(REPORT_JSON_FILE, JSON.pretty_generate(report))
  puts "JSON report generated at: #{REPORT_JSON_FILE}"
end

.generate_pdf_report(scan_data) ⇒ Object



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
# File 'lib/shield_ast.rb', line 140

def self.generate_pdf_report(scan_data)
  unless File.exist?(PDF_TEMPLATE)
    puts "Error: PDF template file #{PDF_TEMPLATE} not found."
    return
  end

  FileUtils.mkdir_p(File.dirname(REPORT_PDF_FILE))

  version = ShieldAst::VERSION
  generated_at = scan_data[:generated_at]
  scan_duration = format_duration(scan_data[:execution_time])
  sast_results = normalize_results(sort_by_severity(scan_data[:reports][:sast]&.[](:results) || []))
  sca_results = normalize_results(sort_by_severity(scan_data[:reports][:sca]&.[](:results) || []))
  iac_results = normalize_results(sort_by_severity(scan_data[:reports][:iac]&.[](:results) || []))
  total_issues = calculate_total_issues(scan_data[:reports])
  severity_summary = calculate_severity_summary(scan_data[:reports])
  output_file = REPORT_PDF_FILE

  begin
    template_context = Object.new
    template_context.instance_variable_set(:@version, version)
    template_context.instance_variable_set(:@generated_at, generated_at)
    template_context.instance_variable_set(:@scan_duration, scan_duration)
    template_context.instance_variable_set(:@sast_results, sast_results)
    template_context.instance_variable_set(:@sca_results, sca_results)
    template_context.instance_variable_set(:@iac_results, iac_results)
    template_context.instance_variable_set(:@total_issues, total_issues)
    template_context.instance_variable_set(:@severity_summary, severity_summary)
    template_context.instance_variable_set(:@output_file, output_file)
    template = File.read(PDF_TEMPLATE)
    template_context.instance_eval template, PDF_TEMPLATE
    puts "PDF report generated at: #{REPORT_PDF_FILE}"
  rescue StandardError => e
    puts "Error: Failed to generate PDF: #{e.message}"
    puts "Error: Backtrace: #{e.backtrace&.join("\n")}"
  end
end

.generate_report(options) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/shield_ast.rb', line 105

def self.generate_report(options)
  scan_data = load_scan_data
  unless scan_data
    puts "No scan data available. Please run 'ast scan' first."
    return
  end

  output_format = options[:output] || "json"
  unless %w[json pdf].include?(output_format)
    puts "Error: Invalid output format '#{output_format}'. Use 'json' or 'pdf'."
    return
  end

  puts "Generating #{output_format.upcase} report..."

  if output_format == "json"
    generate_json_report(scan_data)
  elsif output_format == "pdf"
    generate_pdf_report(scan_data)
  end
end

.get_scan_icon(scan_type) ⇒ Object



289
290
291
292
293
294
295
296
# File 'lib/shield_ast.rb', line 289

def self.get_scan_icon(scan_type)
  case scan_type
  when :sast then "🔍"
  when :sca then "📦"
  when :iac then "☁️"
  else "🛡️"
  end
end

.get_severity_icon(severity) ⇒ Object



280
281
282
283
284
285
286
287
# File 'lib/shield_ast.rb', line 280

def self.get_severity_icon(severity)
  case severity&.upcase
  when "ERROR" then "🔴"
  when "WARNING" then "🟡"
  when "INFO" then "🔵"
  else "⚪"
  end
end

.handle_options(options) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/shield_ast.rb', line 42

def self.handle_options(options)
  if options[:help]
    show_help
  elsif options[:version]
    puts "Shield AST version #{ShieldAst::VERSION}"
  elsif options[:command] == "scan"
    run_scan(options)
  elsif options[:command] == "report"
    generate_report(options)
  else
    puts "Invalid command. Use 'ast help' for more information."
    show_help
  end
end

.has_sca_format?(result) ⇒ Boolean

Returns:

  • (Boolean)


330
331
332
333
334
335
# File 'lib/shield_ast.rb', line 330

def self.has_sca_format?(result)
  (result.key?(:title) || result.key?("title")) &&
    (result.key?(:description) || result.key?("description")) &&
    (result.key?(:vulnerable_version) || result.key?("vulnerable_version")) &&
    (result.key?(:fixed_version) || result.key?("fixed_version"))
end

.load_scan_data ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/shield_ast.rb', line 91

def self.load_scan_data
  unless File.exist?(SCAN_DATA_FILE)
    puts "Error: Scan data file #{SCAN_DATA_FILE} does not exist."
    return nil
  end

  begin
    JSON.parse(File.read(SCAN_DATA_FILE), symbolize_names: true)
  rescue JSON::ParserError => e
    puts "Error: Invalid scan data in #{SCAN_DATA_FILE}: #{e.message}"
    nil
  end
end

.normalize_results(results) ⇒ Object



178
179
180
181
182
183
184
185
186
# File 'lib/shield_ast.rb', line 178

def self.normalize_results(results)
  results.map do |result|
    normalized = result.transform_keys(&:to_sym)
    normalized[:severity] ||= normalized[:extra]&.[](:severity) || normalized[:extra]&.[]("severity") || "INFO"
    normalized[:vulnerable_version] = normalized[:vulnerable_version].to_s if normalized[:vulnerable_version]
    normalized[:fixed_version] = normalized[:fixed_version].to_s if normalized[:fixed_version]
    normalized
  end
end

.parse_args(args) ⇒ Object



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/shield_ast.rb', line 354

def self.parse_args(args)
  options = {
    command: nil, path: nil, sast: false, sca: false, iac: false, help: false, version: false, output: nil
  }

  args.each_with_index do |arg, index|
    case arg
    when "scan" then options[:command] = "scan"
    when "report" then options[:command] = "report"
    when "-s", "--sast" then options[:sast] = true
    when "-c", "--sca" then options[:sca] = true
    when "-i", "--iac" then options[:iac] = true
    when "-h", "--help" then options[:help] = true
    when "--version" then options[:version] = true
    when "-o", "--output"
      options[:output] = args[index + 1] if index + 1 < args.length
    when /^[^-]/ then options[:path] = arg if options[:command] == "scan" && options[:path].nil?
    end
  end
  options
end

.run_scan(options) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/shield_ast.rb', line 57

def self.run_scan(options)
  path = options[:path] || Dir.pwd
  options = apply_default_scanners(options)

  puts "🚀 Starting scan ..."
  start_time = Time.now

  reports = Runner.run(options, path) || {}

  display_reports(reports)

  end_time = Time.now
  execution_time = end_time - start_time
  save_scan_data(reports, execution_time)
end

.save_scan_data(reports, execution_time) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/shield_ast.rb', line 73

def self.save_scan_data(reports, execution_time)
  normalized_reports = {}
  reports.each do |key, value|
    normalized_reports[key.to_sym] = value.transform_keys(&:to_sym)
  end
  data = {
    reports: normalized_reports,
    execution_time: execution_time,
    generated_at: Time.now.strftime("%Y-%m-%d %H:%M:%S %z")
  }
  FileUtils.mkdir_p(File.dirname(SCAN_DATA_FILE))
  File.write(SCAN_DATA_FILE, JSON.pretty_generate(data))
  puts "Scan data saved to: #{SCAN_DATA_FILE}"

  puts "\n🕒 Duration:: #{format_duration(execution_time)}"
  puts "✅ DONE."
end

.scanner_exists?(scanner) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/shield_ast.rb', line 38

def self.scanner_exists?(scanner)
  system("which #{scanner} > /dev/null 2>&1")
end

.show_help ⇒ Object



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
# File 'lib/shield_ast.rb', line 388

def self.show_help
  puts "    ast - A powerful command-line tool for Application Security Testing\n    Usage:\n      ast [command] [options]\n    Commands:\n      scan [path]    Scans a directory for vulnerabilities. Defaults to the current directory.\n      report         Generates a report from the last scan in JSON or PDF format.\n      help           Shows this help message.\n    Options:\n      -s, --sast       Run Static Application Security Testing (SAST) with Opengrep.\n      -c, --sca        Run Software Composition Analysis (SCA) with OSV Scanner.\n      -i, --iac        Run Infrastructure as Code (IaC) analysis with Opengrep.\n      -o, --output     Specify the output format for report (json or pdf, default: json).\n      -h, --help       Show this help message.\n      --version        Show the ast version.\n    Examples:\n      ast scan\n      ast scan /path/to/project --sast --sca\n      ast report --output pdf\n    Description:\n      ast is an all-in-one command-line tool that automates security testing by\n      integrating popular open-source scanners for SAST, SCA, and IaC, helping you\n      find and fix vulnerabilities early in the development lifecycle.\n  HELP\nend\n"

.sort_by_severity(results) ⇒ Object



256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/shield_ast.rb', line 256

def self.sort_by_severity(results)
  severity_order = { "ERROR" => 0, "WARNING" => 1, "INFO" => 2 }

  results.sort_by do |result|
    severity = result[:severity] || result["severity"] || result.dig(:extra,
                                                                     :severity) || result.dig("extra",
                                                                                              "severity") || "INFO"
    severity_order[severity.upcase] || 3
  rescue TypeError
    3
  end
end