Class: RuboCop::Cop::Rack::LowercaseHeaderKeys

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rack/lowercase_header_keys.rb

Overview

Detects HTTP response headers with uppercase characters. HTTP response header keys should be lowercase for compatibility with HTTP/2 and modern web standards.

HTTP/2 (RFC 9113) requires all header field names to be lowercase. Using lowercase keys ensures compatibility across HTTP versions and Rack implementations.

Examples:

# bad
headers['Content-Type'] = 'application/json'
response.headers['Location'] = '/redirect'
response.set_header('X-Custom', 'value')
response.headers['Content-Security-Policy'] += policy

# good
headers['content-type'] = 'application/json'
response.headers['location'] = '/redirect'
response.set_header('x-custom', 'value')
response.headers['content-security-policy'] += policy

Constant Summary collapse

MSG =
"HTTP response header keys should be lowercase. Use `%{downcased}` instead of `%{original}`."
RESTRICT_ON_SEND =
%i([]= [] set_header get_header delete_header has_header?).freeze

Instance Method Summary collapse

Instance Method Details

#on_op_asgn(node) ⇒ Object

Handle compound assignment: headers += val Ruby parses this as an op_asgn node, not a []= send



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/rubocop/cop/rack/lowercase_header_keys.rb', line 58

def on_op_asgn(node)
  lhs = node.children[0]
  return unless lhs.send_type? && lhs.method?(:[])

  receiver = lhs.receiver
  return unless receiver.send_type? && response_headers_receiver?(receiver)

  key_node = lhs.first_argument
  return unless key_node.str_type?

  check_key(key_node)
end

#on_send(node) ⇒ Object Also known as: on_csend



47
48
49
50
51
52
53
# File 'lib/rubocop/cop/rack/lowercase_header_keys.rb', line 47

def on_send(node)
  if node.method?(:[]=) || node.method?(:[])
    check_bracket_access(node)
  elsif response_header_method?(node)
    check_header_method(node)
  end
end

#response_header_method?(node) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rubocop/cop/rack/lowercase_header_keys.rb', line 34

def_node_matcher :response_header_method?, <<~PATTERN
  (send
    {
      (send nil? :response)
      (lvar :response)
      (self)
    }
    {:set_header :get_header :delete_header :has_header?}
    (str _)
    ...
  )
PATTERN