Class: Olyx::Guardrails::InjectionDetector

Inherits:
Object
  • Object
show all
Defined in:
lib/olyx/guardrails/injection_detector.rb

Overview

Detects known prompt-injection structures, phrases, and adjacent-turn combinations.

Detection checks bounded normalized and decoded variants. A false result does not prove that arbitrary text is safe.

Class Method Summary collapse

Class Method Details

.check(messages) ⇒ Object

:call-seq:

InjectionDetector.check(messages) -> Hash

Delegates to scan. messages follows the same contract.



33
34
35
# File 'lib/olyx/guardrails/injection_detector.rb', line 33

def self.check(messages)
  scan(messages)
end

.injection?(text) ⇒ Boolean

:call-seq:

InjectionDetector.injection?(text) -> true or false

Converts text with to_s, scans it as one user message, and returns whether a known injection pattern was detected.

Returns:

  • (Boolean)


42
43
44
# File 'lib/olyx/guardrails/injection_detector.rb', line 42

def self.injection?(text)
  scan([{ 'role' => 'user', 'content' => text.to_s }])[:injection_attempt]
end

.scan(messages) ⇒ Object

:call-seq:

InjectionDetector.scan(messages) -> Hash

Scans messages, which must be an Array of Hashes, and returns an :injection_attempt Boolean with the matched pattern fragments. Individual messages and adjacent user-to-assistant turns are checked. Invalid structure raises ArgumentError.



22
23
24
25
26
27
# File 'lib/olyx/guardrails/injection_detector.rb', line 22

def self.scan(messages)
  Validation.array_of!(messages, Hash, name: 'messages')
  findings = messages.flat_map { |message| SingleMessageInjectionDetector.call(message) }
  findings.concat(MultiTurnInjectionDetector.call(messages))
  { injection_attempt: findings.any?, patterns: findings.uniq { |finding| finding[:match] } }
end