Class: TruffleHogSecretDetector
- Inherits:
-
Object
- Object
- TruffleHogSecretDetector
- Defined in:
- lib/secret_detector.rb
Defined Under Namespace
Classes: Finding
Instance Method Summary collapse
- #has_secrets?(text) ⇒ Boolean
-
#initialize ⇒ TruffleHogSecretDetector
constructor
A new instance of TruffleHogSecretDetector.
- #redact(text, replacement = '[REDACTED]') ⇒ Object
- #scan(text) ⇒ Object
Constructor Details
#initialize ⇒ TruffleHogSecretDetector
Returns a new instance of TruffleHogSecretDetector.
21 22 23 24 25 26 |
# File 'lib/secret_detector.rb', line 21 def initialize # Check if trufflehog is available unless system('which trufflehog > /dev/null 2>&1') raise "TruffleHog not found. Install it with: brew install trufflehog" end end |
Instance Method Details
#has_secrets?(text) ⇒ Boolean
83 84 85 |
# File 'lib/secret_detector.rb', line 83 def has_secrets?(text) !scan(text).empty? end |
#redact(text, replacement = '[REDACTED]') ⇒ Object
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/secret_detector.rb', line 67 def redact(text, replacement = '[REDACTED]') return text if text.nil? || text.empty? findings = scan(text) return text if findings.empty? redacted_text = text.dup # Sort findings by match length (longest first) to avoid partial replacements findings.sort_by { |f| -f.match.length }.each do |finding| redacted_text = redacted_text.gsub(finding.match, replacement) end redacted_text end |
#scan(text) ⇒ Object
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 |
# File 'lib/secret_detector.rb', line 28 def scan(text) return [] if text.nil? || text.empty? findings = [] # Create a temporary file with the text Tempfile.create(['trufflehog_scan', '.txt']) do |temp_file| temp_file.write(text) temp_file.flush # Run trufflehog on the temporary file output = `trufflehog filesystem --json --no-verification #{temp_file.path} 2>/dev/null` # Parse each line of JSON output output.each_line do |line| line = line.strip next if line.empty? begin result = JSON.parse(line) # Skip non-detection results (like log messages) next unless result['DetectorName'] && result['Raw'] findings << Finding.new( result['DetectorName'], result['Raw'], result['Verified'] || false, result.dig('SourceMetadata', 'Data', 'Filesystem', 'line') ) rescue JSON::ParserError # Skip malformed JSON lines next end end end findings end |