Class: PromptSanitizer::Integrations::SanitizerMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/prompt_sanitizer/integrations/middleware.rb

Overview

Rack middleware — auto-sanitizes incoming JSON request bodies.

Intercepts POST/PUT/PATCH requests with Content-Type: application/json and sanitizes the following payload keys before they reach the app:

  • messages[*].content (OpenAI / Anthropic / LangChain style)
  • prompt, input, inputs, text, query

The sanitized body is written back into the Rack env so that downstream controllers see clean payloads with no raw PII.

Optionally, if restore_response: true, the middleware deanonymizes JSON response bodies using the same session vault before sending them to the client.

Usage (manually)

use PromptSanitizer::Integrations::SanitizerMiddleware,
  sanitizer: PromptSanitizer.sanitizer,
  routes:    ["/api/llm"],
  restore_response: false

Usage (via Railtie config)

config.prompt_sanitizer.middleware        = true
config.prompt_sanitizer.middleware_routes = ["/api/llm"]

Constant Summary collapse

BODY_KEYS =

Keys in a flat JSON body whose string values are sanitized.

%w[prompt input inputs text query message content].freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, sanitizer: nil, routes: nil, restore_response: false) ⇒ SanitizerMiddleware



39
40
41
42
43
44
# File 'lib/prompt_sanitizer/integrations/middleware.rb', line 39

def initialize(app, sanitizer: nil, routes: nil, restore_response: false)
  @app     = app
  @san     = sanitizer || PromptSanitizer.sanitizer
  @routes  = routes ? Array(routes) : nil
  @restore = restore_response
end

Instance Method Details

#call(env) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/prompt_sanitizer/integrations/middleware.rb', line 46

def call(env)
  req = Rack::Request.new(env)

  session = nil

  if should_process?(req)
    session = _sanitize_request(req)
  end

  status, headers, body = @app.call(env)

  if session && @restore
    status, headers, body = _restore_response(status, headers, body, session)
  end

  [status, headers, body]
end