Class: Otto::Security::Config
- Inherits:
-
Object
- Object
- Otto::Security::Config
- 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.
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
- GEO_HEADER_DEPTH_CONFLICT_MESSAGE =
Error raised when an app-configured trusted geo header (ip_privacy geo_header) is combined with count-based depth mode. Geo headers are honored only for peers matching enumerated trusted_proxies CIDRs (geo_headers_trusted? gates on trusted_proxies_configured?) — a hop trusted by count cannot be verified as the geo-setting CDN — so a geo_header configured alongside a depth could never be consulted. Failing loud at config time replaces a silent database/’**’ fallback at request time.
<<~MSG.gsub(/\s+/, ' ').strip.freeze Cannot configure a trusted geo header (ip_privacy geo_header) together with trusted_proxy_depth (count mode): geo headers are only honored for peers matching enumerated trusted_proxies CIDRs, so the header would be silently ignored. Use filter mode (add_trusted_proxy) for header-based geo, or drop geo_header and use database-backed geo (geo_db_path or geo_db_reader). MSG
- TRUSTED_PROXY_HEADERS =
Forwarded-header sources depth mode (#trusted_proxy_depth) can count hops from: X-Forwarded-For (default), the RFC 7239 Forwarded header, or Both (Forwarded when present, else X-Forwarded-For). Mirrors OneTimeSecret’s site.network.trusted_proxy.header. Only consulted in depth mode; CIDR-walk is unaffected.
%w[X-Forwarded-For Forwarded Both].freeze
- CSP_REPORTING_GROUP =
Endpoint group name shared by the CSP
report-todirective and theReporting-Endpointsresponse header (modern Reporting API). Browsers match the directive’s group to the header’s key, so both must agree. Aliases Otto::Security::CSP::Policy::REPORTING_GROUP — the one source the policy builder uses — so the header and the directive cannot drift. Otto::Security::CSP::Policy::REPORTING_GROUP
- 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
-
#csp_directive_overrides ⇒ Object
Returns the value of attribute csp_directive_overrides.
-
#csp_nonce_enabled ⇒ Object
readonly
Returns the value of attribute csp_nonce_enabled.
-
#csp_nonce_key ⇒ Object
Returns the value of attribute csp_nonce_key.
-
#csp_report_to_url ⇒ Object
Returns the value of attribute csp_report_to_url.
-
#csp_report_uri ⇒ Object
Returns the value of attribute csp_report_uri.
-
#csp_request_extras_enabled ⇒ Object
readonly
Returns the value of attribute csp_request_extras_enabled.
-
#csp_violation_callback ⇒ Object
readonly
Returns the value of attribute csp_violation_callback.
-
#csrf_header_key ⇒ Object
readonly
Returns the value of attribute csrf_header_key.
-
#csrf_protection ⇒ Object
readonly
Returns the value of attribute csrf_protection.
-
#csrf_session_key ⇒ Object
Returns the value of attribute csrf_session_key.
-
#csrf_token_key ⇒ Object
Returns the value of attribute csrf_token_key.
-
#debug_csp ⇒ Object
readonly
Returns the value of attribute debug_csp.
-
#input_validation ⇒ Object
Returns the value of attribute input_validation.
-
#ip_privacy_config ⇒ Object
readonly
Returns the value of attribute ip_privacy_config.
-
#max_param_depth ⇒ Object
Returns the value of attribute max_param_depth.
-
#max_param_keys ⇒ Object
Returns the value of attribute max_param_keys.
-
#max_request_size ⇒ Object
Returns the value of attribute max_request_size.
-
#mcp_auth ⇒ Object
readonly
Returns the value of attribute mcp_auth.
-
#rate_limiting_config ⇒ Object
Returns the value of attribute rate_limiting_config.
-
#require_secure_cookies ⇒ Object
readonly
Returns the value of attribute require_secure_cookies.
-
#security_headers ⇒ Object
readonly
Returns the value of attribute security_headers.
-
#trusted_proxies ⇒ Object
readonly
Returns the value of attribute trusted_proxies.
-
#trusted_proxy_depth ⇒ Object
Returns the value of attribute trusted_proxy_depth.
-
#trusted_proxy_header ⇒ Object
Returns the value of attribute trusted_proxy_header.
Instance Method Summary collapse
-
#add_trusted_proxy(proxy) ⇒ void
Add a trusted proxy server for accurate client IP detection.
-
#csp_nonce_enabled? ⇒ Boolean
Check if CSP nonce support is enabled.
-
#csp_request_extras_enabled? ⇒ Boolean
Check if the request-scoped CSP directive extras channel is enabled.
-
#csrf_enabled? ⇒ Boolean
Check if CSRF protection is currently enabled.
-
#csrf_secret=(secret) ⇒ Object
Set the server-side secret used to sign (HMAC) CSRF tokens.
-
#debug_csp? ⇒ Boolean
Check if CSP debug logging is enabled.
-
#deep_freeze! ⇒ self
Override deep_freeze! to ensure rate_limiting_config has custom_rules initialized.
-
#disable_csp_nonce! ⇒ void
Disable CSP nonce support.
-
#disable_csrf_protection! ⇒ void
Disable CSRF protection.
-
#dispatch_csp_violation(report) ⇒ void
Invoke the registered violation callback for a report, isolating any error it raises.
-
#enable_csp!(policy = "default-src 'self'") ⇒ void
Enable Content Security Policy (CSP) header.
-
#enable_csp_request_extras! ⇒ void
Enable the request-scoped CSP directive extras channel (delano/otto#243).
-
#enable_csp_with_nonce!(debug: false, directives: {}) ⇒ void
Enable Content Security Policy (CSP) with nonce support.
-
#enable_csrf_protection! ⇒ void
Enable CSRF (Cross-Site Request Forgery) protection.
-
#enable_frame_protection!(option = 'SAMEORIGIN') ⇒ void
Enable X-Frame-Options header to prevent clickjacking.
-
#enable_hsts!(max_age: 31_536_000, include_subdomains: true) ⇒ void
Enable HTTP Strict Transport Security (HSTS) header.
-
#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.
-
#generate_nonce_csp(nonce, development_mode: false, extra_directives: nil) {|applied, dropped| ... } ⇒ String
Generate a CSP policy string with the provided nonce.
-
#get_or_create_session_id(request) ⇒ Object
-
#initialize ⇒ Config
constructor
Initialize security configuration with safe defaults.
-
#merge_csp_directives(overrides) ⇒ void
Merge additional per-directive overrides into the existing set, leaving untouched any directive not named in +overrides+ (last write wins for a repeated directive).
-
#on_csp_violation {|report| ... } ⇒ void
Register the callback invoked once per parsed CSP violation report.
-
#proxy_trust_configured? ⇒ Boolean
Whether ANY proxy-trust mode is configured — CIDR matchers (filter mode) or count-based depth.
-
#set_custom_headers(headers) ⇒ void
Set custom security headers.
-
#trusted_proxies_configured? ⇒ Boolean
Whether any trusted-proxy IP/CIDR/Regexp matchers are configured.
-
#trusted_proxy?(ip) ⇒ Boolean
Check if an IP address is from a trusted proxy.
-
#trusted_proxy_depth_mode? ⇒ Boolean
Whether count-based (“trust the last N hops”) proxy resolution is active.
-
#validate_request_size(content_length) ⇒ Boolean
Validate that a request size is within acceptable limits.
-
#verify_csrf_token(token, session_id = nil) ⇒ Object
Verify a CSRF token against its session binding using a constant-time comparison.
Constructor Details
#initialize ⇒ Config
Initialize security configuration with safe defaults
All security features are disabled by default to maintain backward compatibility with existing Otto applications.
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
# File 'lib/otto/security/config.rb', line 99 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 @trusted_proxy_header = 'X-Forwarded-For' @require_secure_cookies = false @security_headers = default_security_headers @input_validation = true @csp_nonce_enabled = false @debug_csp = false @csp_nonce_key = 'otto.nonce' @csp_policy = nil @csp_report_uri = nil @csp_report_to_url = nil @csp_violation_callback = nil @csp_directive_overrides = {} @csp_request_extras_enabled = false @csp_script_src_override_warned = 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_directive_overrides ⇒ Object
Returns the value of attribute csp_directive_overrides.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def csp_directive_overrides @csp_directive_overrides end |
#csp_nonce_enabled ⇒ Object (readonly)
Returns the value of attribute csp_nonce_enabled.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def csp_nonce_enabled @csp_nonce_enabled end |
#csp_nonce_key ⇒ Object
Returns the value of attribute csp_nonce_key.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def csp_nonce_key @csp_nonce_key end |
#csp_report_to_url ⇒ Object
Returns the value of attribute csp_report_to_url.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def csp_report_to_url @csp_report_to_url end |
#csp_report_uri ⇒ Object
Returns the value of attribute csp_report_uri.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def csp_report_uri @csp_report_uri end |
#csp_request_extras_enabled ⇒ Object (readonly)
Returns the value of attribute csp_request_extras_enabled.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def csp_request_extras_enabled @csp_request_extras_enabled end |
#csp_violation_callback ⇒ Object (readonly)
Returns the value of attribute csp_violation_callback.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def csp_violation_callback @csp_violation_callback end |
#csrf_header_key ⇒ Object (readonly)
Returns the value of attribute csrf_header_key.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def csrf_header_key @csrf_header_key end |
#csrf_protection ⇒ Object (readonly)
Returns the value of attribute csrf_protection.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def csrf_protection @csrf_protection end |
#csrf_session_key ⇒ Object
Returns the value of attribute csrf_session_key.
83 84 85 |
# File 'lib/otto/security/config.rb', line 83 def csrf_session_key @csrf_session_key end |
#csrf_token_key ⇒ Object
Returns the value of attribute csrf_token_key.
83 84 85 |
# File 'lib/otto/security/config.rb', line 83 def csrf_token_key @csrf_token_key end |
#debug_csp ⇒ Object (readonly)
Returns the value of attribute debug_csp.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def debug_csp @debug_csp end |
#input_validation ⇒ Object
Returns the value of attribute input_validation.
83 84 85 |
# File 'lib/otto/security/config.rb', line 83 def input_validation @input_validation end |
#ip_privacy_config ⇒ Object (readonly)
Returns the value of attribute ip_privacy_config.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def ip_privacy_config @ip_privacy_config end |
#max_param_depth ⇒ Object
Returns the value of attribute max_param_depth.
83 84 85 |
# File 'lib/otto/security/config.rb', line 83 def max_param_depth @max_param_depth end |
#max_param_keys ⇒ Object
Returns the value of attribute max_param_keys.
83 84 85 |
# File 'lib/otto/security/config.rb', line 83 def max_param_keys @max_param_keys end |
#max_request_size ⇒ Object
Returns the value of attribute max_request_size.
83 84 85 |
# File 'lib/otto/security/config.rb', line 83 def max_request_size @max_request_size end |
#mcp_auth ⇒ Object (readonly)
Returns the value of attribute mcp_auth.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def mcp_auth @mcp_auth end |
#rate_limiting_config ⇒ Object
Returns the value of attribute rate_limiting_config.
83 84 85 |
# File 'lib/otto/security/config.rb', line 83 def rate_limiting_config @rate_limiting_config end |
#require_secure_cookies ⇒ Object (readonly)
Returns the value of attribute require_secure_cookies.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def @require_secure_cookies end |
#security_headers ⇒ Object (readonly)
Returns the value of attribute security_headers.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def security_headers @security_headers end |
#trusted_proxies ⇒ Object (readonly)
Returns the value of attribute trusted_proxies.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def trusted_proxies @trusted_proxies end |
#trusted_proxy_depth ⇒ Object
Returns the value of attribute trusted_proxy_depth.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def trusted_proxy_depth @trusted_proxy_depth end |
#trusted_proxy_header ⇒ Object
Returns the value of attribute trusted_proxy_header.
87 88 89 |
# File 'lib/otto/security/config.rb', line 87 def trusted_proxy_header @trusted_proxy_header 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.
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
# File 'lib/otto/security/config.rb', line 184 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
512 513 514 |
# File 'lib/otto/security/config.rb', line 512 def csp_nonce_enabled? @csp_nonce_enabled end |
#csp_request_extras_enabled? ⇒ Boolean
Check if the request-scoped CSP directive extras channel is enabled
545 546 547 |
# File 'lib/otto/security/config.rb', line 545 def csp_request_extras_enabled? @csp_request_extras_enabled end |
#csrf_enabled? ⇒ Boolean
Check if CSRF protection is currently enabled
161 162 163 |
# File 'lib/otto/security/config.rb', line 161 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[‘OTTO_CSRF_SECRET’]) 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.
343 344 345 346 347 348 |
# File 'lib/otto/security/config.rb', line 343 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
568 569 570 |
# File 'lib/otto/security/config.rb', line 568 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.
742 743 744 745 746 747 748 |
# File 'lib/otto/security/config.rb', line 742 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
503 504 505 506 507 |
# File 'lib/otto/security/config.rb', line 503 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
152 153 154 155 156 |
# File 'lib/otto/security/config.rb', line 152 def disable_csrf_protection! ensure_not_frozen! @csrf_protection = false end |
#dispatch_csp_violation(report) ⇒ void
This method returns an undefined value.
Invoke the registered violation callback for a report, isolating any error it raises. A misbehaving application callback must never break the report receiver (which always answers 204).
667 668 669 670 671 672 673 674 |
# File 'lib/otto/security/config.rb', line 667 def dispatch_csp_violation(report) callback = @csp_violation_callback return if callback.nil? callback.call(report) rescue StandardError => e Otto.logger.error("[Otto::CSP] violation callback raised #{e.class}: #{e.}") 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.
407 408 409 410 411 412 |
# File 'lib/otto/security/config.rb', line 407 def enable_csp!(policy = "default-src 'self'") ensure_not_frozen! @csp_policy = policy @security_headers['content-security-policy'] = build_static_csp(policy) end |
#enable_csp_request_extras! ⇒ void
This method returns an undefined value.
Enable the request-scoped CSP directive extras channel (delano/otto#243)
Off by default: env['otto.csp.extra_directives'] is a write surface
that ANY middleware in the Rack stack can reach — a lower-trust
position than boot code — so the channel does not exist until the app
explicitly opts in here. Until then the Writer ignores the env key
entirely (no sanitize work, no logs).
With the channel enabled, a handler (or middleware) can widen directives with values only known at request time by writing a hash of directive name => additional origin tokens to the env before the response is finalized. Extras are additive-only and sanitized defensively; see Otto::Security::CSP::RequestExtras.
536 537 538 539 540 |
# File 'lib/otto/security/config.rb', line 536 def enable_csp_request_extras! ensure_not_frozen! @csp_request_extras_enabled = true end |
#enable_csp_with_nonce!(debug: false, directives: {}) ⇒ 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.
Per-directive overrides may be supplied to customize the emitted nonce policy without vendoring the gem. They merge into Otto’s base directive sets (Otto::Security::CSP::Policy.development_directives / Otto::Security::CSP::Policy.production_directives): a matching directive is replaced in place, a new directive is appended, and a nil/false value removes a directive. See #csp_directive_overrides= for the accepted shape.
438 439 440 441 442 443 444 445 446 447 |
# File 'lib/otto/security/config.rb', line 438 def enable_csp_with_nonce!(debug: false, directives: {}) ensure_not_frozen! # Apply overrides before toggling state so a bad +directives+ argument # raises without leaving the config half-updated (nonce enabled but # overrides not merged). merge_csp_directives(directives) unless directives.nil? || directives.empty? @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
142 143 144 145 146 |
# File 'lib/otto/security/config.rb', line 142 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
713 714 715 716 717 |
# File 'lib/otto/security/config.rb', line 713 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.
388 389 390 391 392 393 394 |
# File 'lib/otto/security/config.rb', line 388 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.
353 354 355 356 357 358 359 360 361 |
# File 'lib/otto/security/config.rb', line 353 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, extra_directives: nil) {|applied, dropped| ... } ⇒ String
Generate a CSP policy string with the provided nonce
Thin facade over Otto::Security::CSP::Policy.nonce_policy; the directive sets and report-uri/report-to assembly live there now. Any configured #csp_directive_overrides are merged into the base directive set. Output is byte-identical to Otto’s historical policy when no overrides or reporting are configured.
696 697 698 699 700 701 702 703 704 705 706 |
# File 'lib/otto/security/config.rb', line 696 def generate_nonce_csp(nonce, development_mode: false, extra_directives: nil, &extras_outcome) Otto::Security::CSP::Policy.nonce_policy( nonce, development_mode: development_mode, report_uri: @csp_report_uri, report_to_url: @csp_report_to_url, directive_overrides: @csp_directive_overrides, extra_directives: extra_directives, &extras_outcome ) end |
#get_or_create_session_id(request) ⇒ Object
750 751 752 753 754 755 756 757 758 759 760 761 |
# File 'lib/otto/security/config.rb', line 750 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 |
#merge_csp_directives(overrides) ⇒ void
This method returns an undefined value.
Merge additional per-directive overrides into the existing set, leaving untouched any directive not named in +overrides+ (last write wins for a repeated directive). Use this to accumulate overrides incrementally; use #csp_directive_overrides= to replace them wholesale.
491 492 493 494 495 496 497 |
# File 'lib/otto/security/config.rb', line 491 def merge_csp_directives(overrides) ensure_not_frozen! normalized = Otto::Security::CSP::Policy.normalize_overrides(overrides || {}) warn_if_script_src_overridden(normalized) @csp_directive_overrides = @csp_directive_overrides.merge(normalized) end |
#on_csp_violation {|report| ... } ⇒ void
This method returns an undefined value.
Register the callback invoked once per parsed CSP violation report.
The block receives an Otto::Security::CSP::Report. Your application decides what to do — log, emit a metric, store, forward, or ignore. Otto adds no storage or database coupling.
Registering a second callback REPLACES the first (last registration
wins), matching the singular on_csp_violation semantics. Calling this
with NO block clears (unregisters) any previously-set callback.
SECURITY NOTE: report URL fields may carry sensitive path/query data in some applications. Redact them in your callback before logging if needed; Otto passes them through un-redacted (see Otto::Security::CSP::Report).
655 656 657 658 659 |
# File 'lib/otto/security/config.rb', line 655 def on_csp_violation(&block) ensure_not_frozen! @csp_violation_callback = block end |
#proxy_trust_configured? ⇒ Boolean
Whether ANY proxy-trust mode is configured — CIDR matchers (filter mode) or count-based depth. This is the gate for writing env[‘otto.via_trusted_proxy’] at all: when neither mode is configured the key is left ABSENT (tri-state contract), so downstream consumers can distinguish “operator configured trust and this peer failed it” (false) from “no proxy trust configured” (absent) and apply their own legacy heuristics only in the latter case.
260 261 262 |
# File 'lib/otto/security/config.rb', line 260 def proxy_trust_configured? trusted_proxies_configured? || trusted_proxy_depth_mode? end |
#set_custom_headers(headers) ⇒ void
This method returns an undefined value.
Set custom security headers
730 731 732 733 734 |
# File 'lib/otto/security/config.rb', line 730 def set_custom_headers(headers) ensure_not_frozen! @security_headers.merge!(headers) end |
#trusted_proxies_configured? ⇒ Boolean
Whether any trusted-proxy IP/CIDR/Regexp matchers are configured.
This mirrors #trusted_proxy?, which consults the same matcher list. It deliberately EXCLUDES count-based depth mode: depth grants the peer blanket trust for otto.via_trusted_proxy (#226), but it cannot verify that the hop is a geo-setting CDN, so header-based geo stays gated on enumerated matchers only. Used to gate geo-header trust.
247 248 249 |
# File 'lib/otto/security/config.rb', line 247 def trusted_proxies_configured? @trusted_proxy_matchers.any? 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.
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 |
# File 'lib/otto/security/config.rb', line 216 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.
273 274 275 |
# File 'lib/otto/security/config.rb', line 273 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
326 327 328 329 330 331 332 333 334 335 |
# File 'lib/otto/security/config.rb', line 326 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.
365 366 367 368 369 370 371 372 373 374 375 376 |
# File 'lib/otto/security/config.rb', line 365 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 |