Class: Otto::Response

Inherits:
Rack::Response
  • Object
show all
Defined in:
lib/otto/response.rb

Overview

Otto’s enhanced Rack::Response class with built-in helpers

This class extends Rack::Response with Otto’s framework helpers for HTTP response handling, cookie management, CSP headers, and security. Projects can register additional helpers via Otto#register_response_helpers.

Examples:

Using Otto’s response in route handlers

def show(req, res)
  res.send_secure_cookie('session_id', token, 3600)
  res.apply_csp(req.csp_nonce)
  res.no_cache!
end

See Also:

  • #register_response_helpers

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Class Attribute Details

.send_csp_headers_deprecation_warnedObject

rubocop:disable ThreadSafety/ClassAndModuleAttributes



26
27
28
# File 'lib/otto/response.rb', line 26

def send_csp_headers_deprecation_warned
  @send_csp_headers_deprecation_warned
end

Instance Attribute Details

#requestOtto::Request

Reference to the request object (needed by some response helpers)

Returns:



31
32
33
# File 'lib/otto/response.rb', line 31

def request
  @request
end

Instance Method Details

#app_path(*paths) ⇒ String

Build application path by joining path segments

This method safely joins multiple path segments, handling duplicate slashes and ensuring proper path formatting. Includes the script name (mount point) as the first segment.

Examples:

app_path('api', 'v1', 'users')
# => "/myapp/api/v1/users"
app_path(['admin', 'settings'])
# => "/myapp/admin/settings"

Parameters:

  • paths (Array<String>)

    Path segments to join

Returns:

  • (String)

    Properly formatted path



200
201
202
203
204
# File 'lib/otto/response.rb', line 200

def app_path(*paths)
  paths = paths.flatten.compact
  paths.unshift(request.env['SCRIPT_NAME']) if request&.env&.[]('SCRIPT_NAME')
  paths.join('/').gsub('//', '/')
end

#apply_csp(nonce, mode: :override, development_mode: false, security_config: nil) ⇒ Otto::Security::CSP::Writer::Result

Apply a nonce-based Content-Security-Policy to this response.

This is THE emission helper: it routes through the single apply core (Security::CSP::Writer), so all the invariants — enabled-only, nonce-present, HTML-only, lowercase key, no duplicate — hold here exactly as they do in the middleware, with no guard logic duplicated. The response’s Content-Type must already be set (it decides HTML-only); this helper does NOT set it.

mode: :override (the default) is the deliberate per-request call: it REPLACES any existing CSP. Pass mode: :backstop to defer to an existing policy instead.

Examples:

res['content-type'] = 'text/html; charset=utf-8'
res.apply_csp(req.csp_nonce)

Parameters:

  • nonce (String)

    the per-request nonce (typically Otto::Request#csp_nonce)

  • mode (Symbol) (defaults to: :override)

    :override or :backstop (see Security::CSP::Writer::MODES)

  • development_mode (Boolean) (defaults to: false)

    use development-friendly CSP directives

  • security_config (Otto::Security::Config, nil) (defaults to: nil)

    config to use; resolved from the request env when omitted

Returns:



130
131
132
133
134
135
136
# File 'lib/otto/response.rb', line 130

def apply_csp(nonce, mode: :override, development_mode: false, security_config: nil)
  config = security_config || (request&.env && request.env['otto.security_config'])
  Otto::Security::CSP::Writer.apply(
    headers, nonce,
    config: config, mode: mode, development_mode: development_mode
  )
end


87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/otto/response.rb', line 87

def cookie_security_headers
  # Add security headers that complement cookie security
  headers = {}

  # Prevent MIME type sniffing
  headers['x-content-type-options'] = 'nosniff'

  # Add referrer policy
  headers['referrer-policy'] = 'strict-origin-when-cross-origin'

  # Add frame options
  headers['x-frame-options'] = 'DENY'

  # Add XSS protection
  headers['x-xss-protection'] = '1; mode=block'

  headers
end

#no_cache!void

This method returns an undefined value.

Set cache control headers to prevent caching

This method sets comprehensive cache control headers to ensure that the response is not cached by browsers, proxies, or CDNs. This is particularly useful for sensitive pages or dynamic content that should always be fresh.

Examples:

res.no_cache!


178
179
180
181
182
# File 'lib/otto/response.rb', line 178

def no_cache!
  headers['cache-control'] = 'no-store, no-cache, must-revalidate, max-age=0'
  headers['expires']       = 'Mon, 7 Nov 2011 00:00:00 UTC'
  headers['pragma']        = 'no-cache'
end

#send_csp_headers(content_type, nonce, opts = {}) ⇒ Otto::Security::CSP::Writer::Result

Deprecated.

Use #apply_csp instead. Retained as a thin shim over the apply core so existing callers keep working while its historical quirks are fixed: a nil/empty nonce no longer emits a broken script-src 'nonce-' (it skips), a CSP is no longer emitted for non-HTML responses, and the override notice goes through Otto.logger instead of a bare warn to stderr. Unlike #apply_csp, it still sets the Content-Type for you and emits in :override mode.

Parameters:

  • content_type (String)

    Content-Type to set if not already set

  • nonce (String)

    Nonce value to include in CSP directives

  • opts (Hash) (defaults to: {})

    Options

Options Hash (opts):

  • :security_config (Otto::Security::Config)

    Security config to use

  • :development_mode (Boolean)

    Use development-friendly CSP directives

Returns:



152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/otto/response.rb', line 152

def send_csp_headers(content_type, nonce, opts = {})
  warn_send_csp_headers_deprecated

  # Historical behavior the shim keeps (apply_csp does not): default the
  # Content-Type so an HTML response is recognized as HTML.
  headers['content-type'] ||= content_type

  apply_csp(
    nonce,
    mode: :override,
    development_mode: opts[:development_mode] || false,
    security_config: opts[:security_config]
  )
end


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/otto/response.rb', line 33

def send_secure_cookie(name, value, ttl, opts = {})
  # Default security options
  defaults = {
       secure: true,
     httponly: true,
    same_site: :strict,
         path: '/',
  }

  # Merge with provided options
  cookie_opts = defaults.merge(opts)

  # Set expiration using max-age (preferred) and expires (fallback)
  if ttl&.positive?
    cookie_opts[:max_age] = ttl
    cookie_opts[:expires] = (Time.now.utc + ttl + 10)
  elsif ttl&.negative?
    # For deletion, set both to past date
    cookie_opts[:max_age] = 0
    cookie_opts[:expires] = Time.now.utc - 86_400
  end

  # Set the cookie value
  cookie_opts[:value] = value

  # Validate SameSite attribute
  valid_same_site         = [:strict, :lax, :none, 'Strict', 'Lax', 'None']
  cookie_opts[:same_site] = :strict unless valid_same_site.include?(cookie_opts[:same_site])

  # If SameSite=None, Secure must be true
  cookie_opts[:secure] = true if cookie_opts[:same_site].to_s.downcase == 'none'

  set_cookie name, cookie_opts
end


68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/otto/response.rb', line 68

def send_session_cookie(name, value, opts = {})
  # Session cookies don't have expiration
  session_opts = opts.merge(
    secure: true,
    httponly: true,
    samesite: :strict
  )

  # Remove expiration-related options for session cookies
  session_opts.delete(:max_age)
  session_opts.delete(:expires)

  # Adjust secure flag for local development
  session_opts[:secure] = false if request.local?

  session_opts[:value] = value
  set_cookie name, session_opts
end