Class: Otto::Security::Config

Inherits:
Object
  • Object
show all
Includes:
Core::Freezable
Defined in:
lib/otto/security/config.rb

Overview

Security configuration for Otto applications

This class manages all security-related settings including CSRF protection, input validation, trusted proxies, and security headers. Security features are disabled by default for backward compatibility.

Examples:

Basic usage

config = Otto::Security::Config.new
config.enable_csrf_protection!
config.add_trusted_proxy('10.0.0.0/8')

Custom limits

config = Otto::Security::Config.new
config.max_request_size = 5 * 1024 * 1024  # 5MB
config.max_param_depth = 16

Constant Summary collapse

PROXY_MODE_CONFLICT_MESSAGE =

Error raised when the two mutually-exclusive trusted-proxy resolution modes are configured together: CIDR-walk (enumerated #trusted_proxies) and count-based depth (#trusted_proxy_depth >= 1).

<<~MSG.gsub(/\s+/, ' ').strip.freeze
  Cannot configure both trusted_proxies (CIDR filter mode) and
  trusted_proxy_depth >= 1 (count mode). Enumerate proxy CIDRs OR set a
  hop count, not both.
MSG
CSRF_SECRET_REQUIRED_MESSAGE =

Error raised when CSRF protection is enabled in production without an explicitly configured secret. A randomly-generated per-process secret silently breaks token verification across workers and restarts, so we refuse it in production rather than serve intermittently-failing tokens.

<<~MSG.gsub(/\s+/, ' ').strip.freeze
  CSRF protection is enabled in production without a configured secret.
  Set OTTO_CSRF_SECRET (or config.csrf_secret=) to a stable random value
  (e.g. SecureRandom.hex(32)); a per-process random secret is not valid
  across workers or restarts.
MSG

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeConfig

Initialize security configuration with safe defaults

All security features are disabled by default to maintain backward compatibility with existing Otto applications.



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/otto/security/config.rb', line 65

def initialize
  @csrf_protection        = false
  @csrf_token_key         = '_csrf_token'
  @csrf_header_key        = 'HTTP_X_CSRF_TOKEN'
  @csrf_session_key       = '_csrf_session_id'
  @max_request_size       = 10 * 1024 * 1024 # 10MB
  @max_param_depth        = 32
  @max_param_keys         = 64
  @trusted_proxies        = []
  @trusted_proxy_matchers = []
  @trusted_proxy_depth    = nil
  @require_secure_cookies = false
  @security_headers       = default_security_headers
  @input_validation       = true
  @csp_nonce_enabled      = false
  @debug_csp              = false
  @rate_limiting_config   = { custom_rules: {} }
  @ip_privacy_config      = Otto::Privacy::Config.new

  configured_secret      = ENV.fetch('OTTO_CSRF_SECRET', nil)
  @csrf_secret_generated = configured_secret.nil? || configured_secret.empty?
  @csrf_secret           = @csrf_secret_generated ? SecureRandom.hex(32) : configured_secret
end

Instance Attribute Details

#csp_nonce_enabledObject (readonly)

Returns the value of attribute csp_nonce_enabled.



55
56
57
# File 'lib/otto/security/config.rb', line 55

def csp_nonce_enabled
  @csp_nonce_enabled
end

#csrf_header_keyObject (readonly)

Returns the value of attribute csrf_header_key.



55
56
57
# File 'lib/otto/security/config.rb', line 55

def csrf_header_key
  @csrf_header_key
end

#csrf_protectionObject (readonly)

Returns the value of attribute csrf_protection.



55
56
57
# File 'lib/otto/security/config.rb', line 55

def csrf_protection
  @csrf_protection
end

#csrf_session_keyObject

Returns the value of attribute csrf_session_key.



51
52
53
# File 'lib/otto/security/config.rb', line 51

def csrf_session_key
  @csrf_session_key
end

#csrf_token_keyObject

Returns the value of attribute csrf_token_key.



51
52
53
# File 'lib/otto/security/config.rb', line 51

def csrf_token_key
  @csrf_token_key
end

#debug_cspObject (readonly)

Returns the value of attribute debug_csp.



55
56
57
# File 'lib/otto/security/config.rb', line 55

def debug_csp
  @debug_csp
end

#input_validationObject

Returns the value of attribute input_validation.



51
52
53
# File 'lib/otto/security/config.rb', line 51

def input_validation
  @input_validation
end

#ip_privacy_configObject (readonly)

Returns the value of attribute ip_privacy_config.



55
56
57
# File 'lib/otto/security/config.rb', line 55

def ip_privacy_config
  @ip_privacy_config
end

#max_param_depthObject

Returns the value of attribute max_param_depth.



51
52
53
# File 'lib/otto/security/config.rb', line 51

def max_param_depth
  @max_param_depth
end

#max_param_keysObject

Returns the value of attribute max_param_keys.



51
52
53
# File 'lib/otto/security/config.rb', line 51

def max_param_keys
  @max_param_keys
end

#max_request_sizeObject

Returns the value of attribute max_request_size.



51
52
53
# File 'lib/otto/security/config.rb', line 51

def max_request_size
  @max_request_size
end

#mcp_authObject (readonly)

Returns the value of attribute mcp_auth.



55
56
57
# File 'lib/otto/security/config.rb', line 55

def mcp_auth
  @mcp_auth
end

#rate_limiting_configObject

Returns the value of attribute rate_limiting_config.



51
52
53
# File 'lib/otto/security/config.rb', line 51

def rate_limiting_config
  @rate_limiting_config
end

#require_secure_cookiesObject (readonly)

Returns the value of attribute require_secure_cookies.



55
56
57
# File 'lib/otto/security/config.rb', line 55

def require_secure_cookies
  @require_secure_cookies
end

#security_headersObject (readonly)

Returns the value of attribute security_headers.



55
56
57
# File 'lib/otto/security/config.rb', line 55

def security_headers
  @security_headers
end

#trusted_proxiesObject (readonly)

Returns the value of attribute trusted_proxies.



55
56
57
# File 'lib/otto/security/config.rb', line 55

def trusted_proxies
  @trusted_proxies
end

#trusted_proxy_depthObject

Returns the value of attribute trusted_proxy_depth.



55
56
57
# File 'lib/otto/security/config.rb', line 55

def trusted_proxy_depth
  @trusted_proxy_depth
end

Instance Method Details

#add_trusted_proxy(proxy) ⇒ void

This method returns an undefined value.

Add a trusted proxy server for accurate client IP detection

Only requests from trusted proxies will have their X-Forwarded-For and similar headers honored for IP detection. This prevents IP spoofing from untrusted sources.

Examples:

Add single proxy

config.add_trusted_proxy('10.0.0.1')

Add CIDR range

config.add_trusted_proxy('192.168.0.0/16')

Add multiple proxies

config.add_trusted_proxy(['10.0.0.1', '172.16.0.0/12'])

Parameters:

  • proxy (String, Array)

    IP address, CIDR range, or array of addresses

Raises:

  • (ArgumentError)

    if proxy is not a String or Array

  • (FrozenError)

    if configuration is frozen



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/otto/security/config.rb', line 141

def add_trusted_proxy(proxy)
  ensure_not_frozen!
  # CIDR-walk and count-based depth are mutually exclusive. Catch the
  # conflict eagerly here (and in #trusted_proxy_depth=) so it surfaces at
  # configuration time, not only at freeze (which the test harness skips).
  raise ArgumentError, PROXY_MODE_CONFLICT_MESSAGE if trusted_proxy_depth_mode?

  case proxy
  when String, Regexp
    @trusted_proxies << proxy
    @trusted_proxy_matchers << register_proxy_matcher(proxy)
  when Array
    proxy.each { |entry| @trusted_proxy_matchers << register_proxy_matcher(entry) }
    @trusted_proxies.concat(proxy)
  else
    raise ArgumentError, 'Proxy must be a String, Regexp, or Array'
  end
end

#csp_nonce_enabled?Boolean

Check if CSP nonce support is enabled

Returns:

  • (Boolean)

    true if CSP nonce support is enabled



352
353
354
# File 'lib/otto/security/config.rb', line 352

def csp_nonce_enabled?
  @csp_nonce_enabled
end

#csrf_enabled?Boolean

Check if CSRF protection is currently enabled

Returns:

  • (Boolean)

    true if CSRF protection is enabled



118
119
120
# File 'lib/otto/security/config.rb', line 118

def csrf_enabled?
  @csrf_protection
end

#csrf_secret=(secret) ⇒ Object

Set the server-side secret used to sign (HMAC) CSRF tokens. Set this to a stable value (e.g. ENV) in multi-process or multi-host deployments so tokens stay valid across workers and restarts.

Write-only by design: the signing key has no public reader, so it is not exposed to inspection/logging/serialization via the config object.



250
251
252
253
254
255
# File 'lib/otto/security/config.rb', line 250

def csrf_secret=(secret)
  ensure_not_frozen!

  @csrf_secret           = secret
  @csrf_secret_generated = false
end

#debug_csp?Boolean

Check if CSP debug logging is enabled

Returns:

  • (Boolean)

    true if CSP debug logging is enabled



359
360
361
# File 'lib/otto/security/config.rb', line 359

def debug_csp?
  @debug_csp
end

#deep_freeze!self

Override deep_freeze! to ensure rate_limiting_config has custom_rules initialized

This pre-initializes any lazy values before freezing to prevent FrozenError when accessing configuration after it’s frozen.

Returns:

  • (self)

    The frozen configuration



407
408
409
410
411
412
413
# File 'lib/otto/security/config.rb', line 407

def deep_freeze!
  # Ensure custom_rules is initialized (should already be done in constructor)
  @rate_limiting_config[:custom_rules] ||= {}
  validate_trusted_proxy_config!
  validate_csrf_secret_config!
  super
end

#disable_csp_nonce!void

This method returns an undefined value.

Disable CSP nonce support

Raises:

  • (FrozenError)

    if configuration is frozen



343
344
345
346
347
# File 'lib/otto/security/config.rb', line 343

def disable_csp_nonce!
  ensure_not_frozen!

  @csp_nonce_enabled = false
end

#disable_csrf_protection!void

This method returns an undefined value.

Disable CSRF protection

Raises:

  • (FrozenError)

    if configuration is frozen



109
110
111
112
113
# File 'lib/otto/security/config.rb', line 109

def disable_csrf_protection!
  ensure_not_frozen!

  @csrf_protection = false
end

#enable_csp!(policy = "default-src 'self'") ⇒ void

This method returns an undefined value.

Enable Content Security Policy (CSP) header

CSP helps prevent XSS attacks by controlling which resources can be loaded. The default policy only allows resources from the same origin.

Examples:

Custom policy

config.enable_csp!("default-src 'self'; script-src 'self' 'unsafe-inline'")

Parameters:

  • policy (String) (defaults to: "default-src 'self'")

    CSP policy string (default: “default-src ‘self’”)

Raises:

  • (FrozenError)

    if configuration is frozen



314
315
316
317
318
# File 'lib/otto/security/config.rb', line 314

def enable_csp!(policy = "default-src 'self'")
  ensure_not_frozen!

  @security_headers['content-security-policy'] = policy
end

#enable_csp_with_nonce!(debug: false) ⇒ void

This method returns an undefined value.

Enable Content Security Policy (CSP) with nonce support

This enables dynamic CSP header generation with nonces for enhanced security. Unlike enable_csp!, this doesn’t set a static policy but enables the response helper to generate CSP headers with nonces on a per-request basis.

Examples:

config.enable_csp_with_nonce!(debug: true)

Parameters:

  • debug (Boolean) (defaults to: false)

    Enable debug logging for CSP headers (default: false)

Raises:

  • (FrozenError)

    if configuration is frozen



332
333
334
335
336
337
# File 'lib/otto/security/config.rb', line 332

def enable_csp_with_nonce!(debug: false)
  ensure_not_frozen!

  @csp_nonce_enabled = true
  @debug_csp         = debug
end

#enable_csrf_protection!void

This method returns an undefined value.

Enable CSRF (Cross-Site Request Forgery) protection

When enabled, Otto will:

  • Generate CSRF tokens for safe HTTP methods (GET, HEAD, OPTIONS, TRACE)

  • Validate CSRF tokens for unsafe methods (POST, PUT, DELETE, PATCH)

  • Automatically inject CSRF meta tags into HTML responses

  • Provide helper methods for forms and AJAX requests

Raises:

  • (FrozenError)

    if configuration is frozen



99
100
101
102
103
# File 'lib/otto/security/config.rb', line 99

def enable_csrf_protection!
  ensure_not_frozen!

  @csrf_protection = true
end

#enable_frame_protection!(option = 'SAMEORIGIN') ⇒ void

This method returns an undefined value.

Enable X-Frame-Options header to prevent clickjacking

Parameters:

  • option (String) (defaults to: 'SAMEORIGIN')

    Frame options: ‘DENY’, ‘SAMEORIGIN’, or ‘ALLOW-FROM uri’

Raises:

  • (FrozenError)

    if configuration is frozen



378
379
380
381
382
# File 'lib/otto/security/config.rb', line 378

def enable_frame_protection!(option = 'SAMEORIGIN')
  ensure_not_frozen!

  @security_headers['x-frame-options'] = option
end

#enable_hsts!(max_age: 31_536_000, include_subdomains: true) ⇒ void

This method returns an undefined value.

Enable HTTP Strict Transport Security (HSTS) header

HSTS forces browsers to use HTTPS for all future requests to this domain. WARNING: This can make your domain inaccessible if HTTPS is not properly configured. Only enable this when you’re certain HTTPS is working correctly.

Parameters:

  • max_age (Integer) (defaults to: 31_536_000)

    Maximum age in seconds (default: 1 year)

  • include_subdomains (Boolean) (defaults to: true)

    Apply to all subdomains (default: true)

Raises:

  • (FrozenError)

    if configuration is frozen



295
296
297
298
299
300
301
# File 'lib/otto/security/config.rb', line 295

def enable_hsts!(max_age: 31_536_000, include_subdomains: true)
  ensure_not_frozen!

  hsts_value                                     = "max-age=#{max_age}"
  hsts_value                                    += '; includeSubDomains' if include_subdomains
  @security_headers['strict-transport-security'] = hsts_value
end

#generate_csrf_token(session_id = nil) ⇒ Object

Generate a CSRF token bound to the given session id and signed (HMAC-SHA256) with the server-side secret, so tokens cannot be self-minted and are not valid across sessions. A session binding is REQUIRED.

Raises:

  • (ArgumentError)


260
261
262
263
264
265
266
267
268
# File 'lib/otto/security/config.rb', line 260

def generate_csrf_token(session_id = nil)
  binding_id = session_id.to_s
  raise ArgumentError, 'CSRF token generation requires a session binding' if binding_id.empty?

  reject_generated_secret_in_production!
  warn_generated_csrf_secret
  token = SecureRandom.hex(32)
  "#{token}:#{sign_csrf_token(binding_id, token)}"
end

#generate_nonce_csp(nonce, development_mode: false) ⇒ String

Generate a CSP policy string with the provided nonce

Parameters:

  • nonce (String)

    The nonce value to include in the CSP

  • development_mode (Boolean) (defaults to: false)

    Whether to use development-friendly directives

Returns:

  • (String)

    Complete CSP policy string



368
369
370
371
# File 'lib/otto/security/config.rb', line 368

def generate_nonce_csp(nonce, development_mode: false)
  directives = development_mode ? development_csp_directives(nonce) : production_csp_directives(nonce)
  directives.join(' ')
end

#get_or_create_session_id(request) ⇒ Object



415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/otto/security/config.rb', line 415

def get_or_create_session_id(request)
  # Try existing sources first
  session_id = extract_existing_session_id(request)

  # Create and persist if none found
  if session_id.nil? || session_id.empty?
    session_id = SecureRandom.hex(16)
    store_session_id(request, session_id)
  end

  session_id
end

#set_custom_headers(headers) ⇒ void

This method returns an undefined value.

Set custom security headers

Examples:

config.set_custom_headers({
  'permissions-policy' => 'geolocation=(), microphone=()',
  'cross-origin-opener-policy' => 'same-origin'
})

Parameters:

  • headers (Hash)

    Hash of header name => value pairs

Raises:

  • (FrozenError)

    if configuration is frozen



395
396
397
398
399
# File 'lib/otto/security/config.rb', line 395

def set_custom_headers(headers)
  ensure_not_frozen!

  @security_headers.merge!(headers)
end

#trusted_proxy?(ip) ⇒ Boolean

Check if an IP address is from a trusted proxy

String entries that parse as an IP or CIDR range are matched with proper IPAddr containment (IPv4 and IPv6). Entries that are not valid IPs (e.g. a bare prefix like ‘172.16.’) fall back to the legacy exact/prefix string match for backward compatibility. Regexp entries are matched against the raw IP string.

Proxy entries are parsed once at registration (see #add_trusted_proxy) into @trusted_proxy_matchers, so this never re-parses per request.

Parameters:

  • ip (String)

    IP address to check

Returns:

  • (Boolean)

    true if the IP is from a trusted proxy



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/otto/security/config.rb', line 173

def trusted_proxy?(ip)
  return false if @trusted_proxy_matchers.empty? || ip.nil? || ip.empty?

  # Fold IPv4-mapped IPv6 (::ffff:a.b.c.d) to plain IPv4 so a dual-stack
  # peer presented in mapped form still matches an IPv4 proxy entry.
  client = parse_ipaddr(ip)&.native

  @trusted_proxy_matchers.any? do |entry, range|
    if range
      # Pre-parsed IP/CIDR entry -> proper containment
      client && ip_in_range?(range, client)
    elsif entry.is_a?(Regexp)
      entry.match?(ip)
    elsif entry.is_a?(String)
      # Legacy non-IP entry (e.g. '172.16.') -> exact/prefix match
      ip == entry || ip.start_with?(entry)
    else
      false
    end
  end
end

#trusted_proxy_depth_mode?Boolean

Whether count-based (“trust the last N hops”) proxy resolution is active.

When true, Otto::Utils.resolve_client_ip ignores trusted-proxy CIDRs and instead trusts a fixed number of hops from the right of the forwarded chain (Express ‘trust proxy = N`). This is the only sound model for non-enumerable proxy tiers (Fly, cloud load balancers, dynamic reverse proxies) whose addresses cannot be listed as CIDRs.

Returns:

  • (Boolean)

    true when trusted_proxy_depth is an Integer >= 1



204
205
206
# File 'lib/otto/security/config.rb', line 204

def trusted_proxy_depth_mode?
  @trusted_proxy_depth.is_a?(Integer) && @trusted_proxy_depth >= 1
end

#validate_request_size(content_length) ⇒ Boolean

Validate that a request size is within acceptable limits

Parameters:

  • content_length (String, Integer, nil)

    Content-Length header value

Returns:

  • (Boolean)

    true if request size is acceptable

Raises:



233
234
235
236
237
238
239
240
241
242
# File 'lib/otto/security/config.rb', line 233

def validate_request_size(content_length)
  return true if content_length.nil?

  size = content_length.to_i
  if size > @max_request_size
    raise Otto::Security::RequestTooLargeError,
          "Request size #{size} exceeds maximum #{@max_request_size}"
  end
  true
end

#verify_csrf_token(token, session_id = nil) ⇒ Object

Verify a CSRF token against its session binding using a constant-time comparison. Returns false (never raises) for blank/malformed input.



272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/otto/security/config.rb', line 272

def verify_csrf_token(token, session_id = nil)
  return false if token.nil? || token.empty?

  binding_id = session_id.to_s
  return false if binding_id.empty?

  token_part, signature = token.split(':', 2)
  return false if token_part.nil? || signature.nil?

  expected_signature = sign_csrf_token(binding_id, token_part)
  secure_compare(signature, expected_signature)
end