1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 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 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
|
# frozen_string_literal: true
require 'set'
require 'time'
require 'rack'
module Sprockets
# `Server` is a concern mixed into `Environment` and
# `CachedEnvironment` that provides a Rack compatible `call`
# interface and url generation helpers.
module Server
# Supported HTTP request methods.
ALLOWED_REQUEST_METHODS = ['GET', 'HEAD'].to_set.freeze
# :stopdoc:
if Gem::Version.new(Rack::RELEASE) < Gem::Version.new("3")
X_CASCADE = "X-Cascade"
VARY = "Vary"
else
X_CASCADE = "x-cascade"
VARY = "vary"
end
# :startdoc:
# `call` implements the Rack 1.x specification which accepts an
# `env` Hash and returns a three item tuple with the status code,
# headers, and body.
#
# Mapping your environment at a url prefix will serve all assets
# in the path.
#
# map "/assets" do
# run Sprockets::Environment.new
# end
#
# A request for `"/assets/foo/bar.js"` will search your
# environment for `"foo/bar.js"`.
def call(env)
start_time = Time.now.to_f
time_elapsed = lambda { ((Time.now.to_f - start_time) * 1000).to_i }
unless ALLOWED_REQUEST_METHODS.include? env['REQUEST_METHOD']
return method_not_allowed_response
end
msg = "Served asset #{env['PATH_INFO']} -"
# Extract the path from everything after the leading slash
full_path = Rack::Utils.unescape(env['PATH_INFO'].to_s.sub(/^\//, ''))
path = full_path
unless path.valid_encoding?
return bad_request_response(env)
end
# Strip fingerprint
if fingerprint = path_fingerprint(path)
path = path.sub("-#{fingerprint}", '')
end
# URLs containing a `".."` are rejected for security reasons.
if forbidden_request?(path)
return forbidden_response(env)
end
if fingerprint
if_match = fingerprint
elsif env['HTTP_IF_MATCH']
if_match = env['HTTP_IF_MATCH'][/"(\w+)"$/, 1]
end
if env['HTTP_IF_NONE_MATCH']
if_none_match = env['HTTP_IF_NONE_MATCH'][/"(\w+)"$/, 1]
end
# Look up the asset.
asset = find_asset(path)
# Fallback to looking up the asset with the full path.
# This will make assets that are hashed with webpack or
# other js bundlers work consistently between production
# and development pipelines.
if asset.nil? && (asset = find_asset(full_path))
if_match = asset.etag if fingerprint
fingerprint = asset.etag
end
if asset.nil?
status = :not_found
elsif fingerprint && asset.etag != fingerprint
status = :not_found
elsif if_match && asset.etag != if_match
status = :precondition_failed
elsif if_none_match && asset.etag == if_none_match
status = :not_modified
else
status = :ok
end
case status
when :ok
logger.info "#{msg} 200 OK (#{time_elapsed.call}ms)"
ok_response(asset, env)
when :not_modified
logger.info "#{msg} 304 Not Modified (#{time_elapsed.call}ms)"
not_modified_response(env, if_none_match)
when :not_found
logger.info "#{msg} 404 Not Found (#{time_elapsed.call}ms)"
not_found_response(env)
when :precondition_failed
logger.info "#{msg} 412 Precondition Failed (#{time_elapsed.call}ms)"
precondition_failed_response(env)
end
rescue Exception => e
logger.error "Error compiling asset #{path}:"
logger.error "#{e.class.name}: #{e.message}"
case File.extname(path)
when ".js"
# Re-throw JavaScript asset exceptions to the browser
logger.info "#{msg} 500 Internal Server Error\n\n"
return javascript_exception_response(e)
when ".css"
# Display CSS asset exceptions in the browser
logger.info "#{msg} 500 Internal Server Error\n\n"
return css_exception_response(e)
else
raise
end
end
private
def forbidden_request?(path)
# Prevent access to files elsewhere on the file system
#
# http://example.org/assets/../../../etc/passwd
#
path.include?("..") || absolute_path?(path) || path.include?("://")
end
def head_request?(env)
env['REQUEST_METHOD'] == 'HEAD'
end
# Returns a 200 OK response tuple
def ok_response(asset, env)
if head_request?(env)
[ 200, headers(env, asset, 0), [] ]
else
[ 200, headers(env, asset, asset.length), asset ]
end
end
# Returns a 304 Not Modified response tuple
def not_modified_response(env, etag)
[ 304, cache_headers(env, etag), [] ]
end
# Returns a 400 Forbidden response tuple
def bad_request_response(env)
if head_request?(env)
[ 400, { Rack::CONTENT_TYPE => "text/plain", Rack::CONTENT_LENGTH => "0" }, [] ]
else
[ 400, { Rack::CONTENT_TYPE => "text/plain", Rack::CONTENT_LENGTH => "11" }, [ "Bad Request" ] ]
end
end
# Returns a 403 Forbidden response tuple
def forbidden_response(env)
if head_request?(env)
[ 403, { Rack::CONTENT_TYPE => "text/plain", Rack::CONTENT_LENGTH => "0" }, [] ]
else
[ 403, { Rack::CONTENT_TYPE => "text/plain", Rack::CONTENT_LENGTH => "9" }, [ "Forbidden" ] ]
end
end
# Returns a 404 Not Found response tuple
def not_found_response(env)
if head_request?(env)
[ 404, { Rack::CONTENT_TYPE => "text/plain", Rack::CONTENT_LENGTH => "0", X_CASCADE => "pass" }, [] ]
else
[ 404, { Rack::CONTENT_TYPE => "text/plain", Rack::CONTENT_LENGTH => "9", X_CASCADE => "pass" }, [ "Not found" ] ]
end
end
def method_not_allowed_response
[ 405, { Rack::CONTENT_TYPE => "text/plain", Rack::CONTENT_LENGTH => "18" }, [ "Method Not Allowed" ] ]
end
def precondition_failed_response(env)
if head_request?(env)
[ 412, { Rack::CONTENT_TYPE => "text/plain", Rack::CONTENT_LENGTH => "0", X_CASCADE => "pass" }, [] ]
else
[ 412, { Rack::CONTENT_TYPE => "text/plain", Rack::CONTENT_LENGTH => "19", X_CASCADE => "pass" }, [ "Precondition Failed" ] ]
end
end
# Returns a JavaScript response that re-throws a Ruby exception
# in the browser
def javascript_exception_response(exception)
err = "#{exception.class.name}: #{exception.message}\n (in #{exception.backtrace[0]})"
body = "throw Error(#{err.inspect})"
[ 200, { Rack::CONTENT_TYPE => "application/javascript", Rack::CONTENT_LENGTH => body.bytesize.to_s }, [ body ] ]
end
# Returns a CSS response that hides all elements on the page and
# displays the exception
def css_exception_response(exception)
message = "\n#{exception.class.name}: #{exception.message}"
backtrace = "\n #{exception.backtrace.first}"
body = <<-CSS
html {
padding: 18px 36px;
}
head {
display: block;
}
body {
margin: 0;
padding: 0;
}
body > * {
display: none !important;
}
head:after, body:before, body:after {
display: block !important;
}
head:after {
font-family: sans-serif;
font-size: large;
font-weight: bold;
content: "Error compiling CSS asset";
}
body:before, body:after {
font-family: monospace;
white-space: pre-wrap;
}
body:before {
font-weight: bold;
content: "#{escape_css_content(message)}";
}
body:after {
content: "#{escape_css_content(backtrace)}";
}
CSS
[ 200, { Rack::CONTENT_TYPE => "text/css; charset=utf-8", Rack::CONTENT_LENGTH => body.bytesize.to_s }, [ body ] ]
end
# Escape special characters for use inside a CSS content("...") string
def escape_css_content(content)
content.
gsub('\\', '\\\\005c ').
gsub("\n", '\\\\000a ').
gsub('"', '\\\\0022 ').
gsub('/', '\\\\002f ')
end
def cache_headers(env, etag)
headers = {}
# Set caching headers
headers[Rack::CACHE_CONTROL] = +"public"
headers[Rack::ETAG] = %("#{etag}")
# If the request url contains a fingerprint, set a long
# expires on the response
if path_fingerprint(env["PATH_INFO"])
headers[Rack::CACHE_CONTROL] << ", max-age=31536000, immutable"
# Otherwise set `must-revalidate` since the asset could be modified.
else
headers[Rack::CACHE_CONTROL] << ", must-revalidate"
headers[VARY] = "Accept-Encoding"
end
headers
end
def headers(env, asset, length)
headers = {}
# Set content length header
headers[Rack::CONTENT_LENGTH] = length.to_s
# Set content type header
if type = asset.content_type
# Set charset param for text/* mime types
if type.start_with?("text/") && asset.charset
type += "; charset=#{asset.charset}"
end
headers[Rack::CONTENT_TYPE] = type
end
headers.merge(cache_headers(env, asset.etag))
end
# Gets ETag fingerprint.
#
# "foo-0aa2105d29558f3eb790d411d7d8fb66.js"
# # => "0aa2105d29558f3eb790d411d7d8fb66"
#
def path_fingerprint(path)
path[/-([0-9a-zA-Z]{7,128})\.[^.]+\z/, 1]
end
end
end
|