Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions app/middleware/suppress_api_compression.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# frozen_string_literal: true

# BREACH mitigation (CVE-2013-3587).
#
# HTTP compression over HTTPS creates a side-channel: an attacker who can observe
# compressed response sizes can infer secrets in the response body (BREACH attack).
#
# This middleware disables gzip compression for all /api/* responses by:
# 1. Removing gzip from Accept-Encoding before the request reaches Rack::Deflater,
# preventing Rails-level compression.
# 2. Setting Content-Encoding: identity on the response, signalling nginx not to
# apply gzip compression at the infrastructure layer.
class SuppressApiCompression
API_PATH_PREFIX = '/api/'

def initialize(app)
@app = app
end

def call(env)
Comment thread
Niharika1117 marked this conversation as resolved.
if env['PATH_INFO'].start_with?(API_PATH_PREFIX)
env['HTTP_ACCEPT_ENCODING'] = strip_gzip(env['HTTP_ACCEPT_ENCODING'])
end

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

headers['Content-Encoding'] = 'identity' if env['PATH_INFO'].start_with?(API_PATH_PREFIX)

[status, headers, body]
end

private

def strip_gzip(accept_encoding)
return accept_encoding if accept_encoding.blank?

result = accept_encoding
.gsub(/gzip\s*(;\s*q\s*=\s*[\d.]+)?\s*,?\s*/i, '')
.gsub(/,\s*$/, '')
.strip
result.presence
end
end
Comment thread
Niharika1117 marked this conversation as resolved.
4 changes: 4 additions & 0 deletions config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ class Application < Rails::Application
require_relative '../app/middleware/mime_type_sanitizer'
config.middleware.insert_before ActionDispatch::Static, MimeTypeSanitizer

# BREACH mitigation: disable gzip for API responses (CVE-2013-3587)
require_relative '../app/middleware/suppress_api_compression'
config.middleware.insert_before Rack::Deflater, SuppressApiCompression

config.load_defaults 6.1

config.generators.stylesheets = false
Expand Down
Loading