rack 3.0.18 → 3.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/rack/utils.rb CHANGED
@@ -6,6 +6,7 @@ require 'fileutils'
6
6
  require 'set'
7
7
  require 'tempfile'
8
8
  require 'time'
9
+ require 'erb'
9
10
 
10
11
  require_relative 'query_parser'
11
12
  require_relative 'mime'
@@ -23,6 +24,7 @@ module Rack
23
24
  DEFAULT_SEP = QueryParser::DEFAULT_SEP
24
25
  COMMON_SEP = QueryParser::COMMON_SEP
25
26
  KeySpaceConstrainedParams = QueryParser::Params
27
+ URI_PARSER = defined?(::URI::RFC2396_PARSER) ? ::URI::RFC2396_PARSER : ::URI::DEFAULT_PARSER
26
28
 
27
29
  class << self
28
30
  attr_accessor :default_query_parser
@@ -42,13 +44,13 @@ module Rack
42
44
  # Like URI escaping, but with %20 instead of +. Strictly speaking this is
43
45
  # true URI escaping.
44
46
  def escape_path(s)
45
- ::URI::DEFAULT_PARSER.escape s
47
+ URI_PARSER.escape s
46
48
  end
47
49
 
48
50
  # Unescapes the **path** component of a URI. See Rack::Utils.unescape for
49
51
  # unescaping query parameters or form components.
50
52
  def unescape_path(s)
51
- ::URI::DEFAULT_PARSER.unescape s
53
+ URI_PARSER.unescape s
52
54
  end
53
55
 
54
56
  # Unescapes a URI escaped string with +encoding+. +encoding+ will be the
@@ -85,15 +87,6 @@ module Rack
85
87
  self.default_query_parser = self.default_query_parser.new_depth_limit(v)
86
88
  end
87
89
 
88
- def self.key_space_limit
89
- warn("`Rack::Utils.key_space_limit` is deprecated as this value no longer has an effect. It will be removed in Rack 3.1", uplevel: 1)
90
- 65536
91
- end
92
-
93
- def self.key_space_limit=(v)
94
- warn("`Rack::Utils.key_space_limit=` is deprecated and no longer has an effect. It will be removed in Rack 3.1", uplevel: 1)
95
- end
96
-
97
90
  if defined?(Process::CLOCK_MONOTONIC)
98
91
  def clock_time
99
92
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
@@ -184,20 +177,16 @@ module Rack
184
177
  matches&.first
185
178
  end
186
179
 
187
- ESCAPE_HTML = {
188
- "&" => "&amp;",
189
- "<" => "&lt;",
190
- ">" => "&gt;",
191
- "'" => "&#x27;",
192
- '"' => "&quot;",
193
- "/" => "&#x2F;"
194
- }
195
-
196
- ESCAPE_HTML_PATTERN = Regexp.union(*ESCAPE_HTML.keys)
197
-
198
- # Escape ampersands, brackets and quotes to their HTML/XML entities.
199
- def escape_html(string)
200
- string.to_s.gsub(ESCAPE_HTML_PATTERN){|c| ESCAPE_HTML[c] }
180
+ # Introduced in ERB 4.0. ERB::Escape is an alias for ERB::Utils which
181
+ # doesn't get monkey-patched by rails
182
+ if defined?(ERB::Escape) && ERB::Escape.instance_method(:html_escape)
183
+ define_method(:escape_html, ERB::Escape.instance_method(:html_escape))
184
+ else
185
+ require 'cgi/escape'
186
+ # Escape ampersands, brackets and quotes to their HTML/XML entities.
187
+ def escape_html(string)
188
+ CGI.escapeHTML(string.to_s)
189
+ end
201
190
  end
202
191
 
203
192
  def select_best_encoding(available_encodings, accept_encoding)
@@ -252,21 +241,6 @@ module Rack
252
241
  end
253
242
  end
254
243
 
255
- def add_cookie_to_header(header, key, value)
256
- warn("add_cookie_to_header is deprecated and will be removed in Rack 3.1", uplevel: 1)
257
-
258
- case header
259
- when nil, ''
260
- return set_cookie_header(key, value)
261
- when String
262
- [header, set_cookie_header(key, value)]
263
- when Array
264
- header + [set_cookie_header(key, value)]
265
- else
266
- raise ArgumentError, "Unrecognized cookie header value. Expected String, Array, or nil, got #{header.inspect}"
267
- end
268
- end
269
-
270
244
  # :call-seq:
271
245
  # parse_cookies(env) -> hash
272
246
  #
@@ -280,6 +254,20 @@ module Rack
280
254
  parse_cookies_header env[HTTP_COOKIE]
281
255
  end
282
256
 
257
+ # A valid cookie key according to RFC2616.
258
+ # A <cookie-name> can be any US-ASCII characters, except control characters, spaces, or tabs. It also must not contain a separator character like the following: ( ) < > @ , ; : \ " / [ ] ? = { }.
259
+ VALID_COOKIE_KEY = /\A[!#$%&'*+\-\.\^_`|~0-9a-zA-Z]+\z/.freeze
260
+ private_constant :VALID_COOKIE_KEY
261
+
262
+ private def escape_cookie_key(key)
263
+ if key =~ VALID_COOKIE_KEY
264
+ key
265
+ else
266
+ warn "Cookie key #{key.inspect} is not valid according to RFC2616; it will be escaped. This behaviour is deprecated and will be removed in a future version of Rack.", uplevel: 2
267
+ escape(key)
268
+ end
269
+ end
270
+
283
271
  # :call-seq:
284
272
  # set_cookie_header(key, value) -> encoded string
285
273
  #
@@ -306,7 +294,7 @@ module Rack
306
294
  def set_cookie_header(key, value)
307
295
  case value
308
296
  when Hash
309
- key = escape(key) unless value[:escape_key] == false
297
+ key = escape_cookie_key(key) unless value[:escape_key] == false
310
298
  domain = "; domain=#{value[:domain]}" if value[:domain]
311
299
  path = "; path=#{value[:path]}" if value[:path]
312
300
  max_age = "; max-age=#{value[:max_age]}" if value[:max_age]
@@ -318,23 +306,24 @@ module Rack
318
306
  when false, nil
319
307
  nil
320
308
  when :none, 'None', :None
321
- '; SameSite=None'
309
+ '; samesite=none'
322
310
  when :lax, 'Lax', :Lax
323
- '; SameSite=Lax'
311
+ '; samesite=lax'
324
312
  when true, :strict, 'Strict', :Strict
325
- '; SameSite=Strict'
313
+ '; samesite=strict'
326
314
  else
327
- raise ArgumentError, "Invalid SameSite value: #{value[:same_site].inspect}"
315
+ raise ArgumentError, "Invalid :same_site value: #{value[:same_site].inspect}"
328
316
  end
317
+ partitioned = "; partitioned" if value[:partitioned]
329
318
  value = value[:value]
330
319
  else
331
- key = escape(key)
320
+ key = escape_cookie_key(key)
332
321
  end
333
322
 
334
323
  value = [value] unless Array === value
335
324
 
336
325
  return "#{key}=#{value.map { |v| escape v }.join('&')}#{domain}" \
337
- "#{path}#{max_age}#{expires}#{secure}#{httponly}#{same_site}"
326
+ "#{path}#{max_age}#{expires}#{secure}#{httponly}#{same_site}#{partitioned}"
338
327
  end
339
328
 
340
329
  # :call-seq:
@@ -375,24 +364,12 @@ module Rack
375
364
  set_cookie_header(key, value.merge(max_age: '0', expires: Time.at(0), value: ''))
376
365
  end
377
366
 
378
- def make_delete_cookie_header(header, key, value)
379
- warn("make_delete_cookie_header is deprecated and will be removed in Rack 3.1, use delete_set_cookie_header! instead", uplevel: 1)
380
-
381
- delete_set_cookie_header!(header, key, value)
382
- end
383
-
384
367
  def delete_cookie_header!(headers, key, value = {})
385
368
  headers[SET_COOKIE] = delete_set_cookie_header!(headers[SET_COOKIE], key, value)
386
369
 
387
370
  return nil
388
371
  end
389
372
 
390
- def add_remove_cookie_to_header(header, key, value = {})
391
- warn("add_remove_cookie_to_header is deprecated and will be removed in Rack 3.1, use delete_set_cookie_header! instead", uplevel: 1)
392
-
393
- delete_set_cookie_header!(header, key, value)
394
- end
395
-
396
373
  # :call-seq:
397
374
  # delete_set_cookie_header!(header, key, value = {}) -> header value
398
375
  #
@@ -435,6 +412,8 @@ module Rack
435
412
 
436
413
  def get_byte_ranges(http_range, size)
437
414
  # See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35>
415
+ # Ignore Range when file size is 0 to avoid a 416 error.
416
+ return nil if size.zero?
438
417
  return nil unless http_range && http_range =~ /bytes=([^;]+)/
439
418
  ranges = []
440
419
  $1.split(/,\s*/).each do |range_spec|
@@ -517,39 +496,12 @@ module Rack
517
496
  end
518
497
  end
519
498
 
520
- # A wrapper around Headers
521
- # header when set.
522
- #
523
- # @api private
524
- class HeaderHash < Hash # :nodoc:
525
- def self.[](headers)
526
- warn "Rack::Utils::HeaderHash is deprecated and will be removed in Rack 3.1, switch to Rack::Headers", uplevel: 1
527
- if headers.is_a?(Headers) && !headers.frozen?
528
- return headers
529
- end
530
-
531
- new_headers = Headers.new
532
- headers.each{|k,v| new_headers[k] = v}
533
- new_headers
534
- end
535
-
536
- def self.new(hash = {})
537
- warn "Rack::Utils::HeaderHash is deprecated and will be removed in Rack 3.1, switch to Rack::Headers", uplevel: 1
538
- headers = Headers.new
539
- hash.each{|k,v| headers[k] = v}
540
- headers
541
- end
542
-
543
- def self.allocate
544
- raise TypeError, "cannot allocate HeaderHash"
545
- end
546
- end
547
-
548
499
  # Every standard HTTP code mapped to the appropriate message.
549
500
  # Generated with:
550
- # curl -s https://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv | \
551
- # ruby -ne 'm = /^(\d{3}),(?!Unassigned|\(Unused\))([^,]+)/.match($_) and \
552
- # puts "#{m[1]} => \x27#{m[2].strip}\x27,"'
501
+ # curl -s https://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv \
502
+ # | ruby -rcsv -e "puts CSV.parse(STDIN, headers: true) \
503
+ # .reject {|v| v['Description'] == 'Unassigned' or v['Description'].include? '(' } \
504
+ # .map {|v| %Q/#{v['Value']} => '#{v['Description']}'/ }.join(','+?\n)"
553
505
  HTTP_STATUS_CODES = {
554
506
  100 => 'Continue',
555
507
  101 => 'Switching Protocols',
@@ -571,7 +523,6 @@ module Rack
571
523
  303 => 'See Other',
572
524
  304 => 'Not Modified',
573
525
  305 => 'Use Proxy',
574
- 306 => '(Unused)',
575
526
  307 => 'Temporary Redirect',
576
527
  308 => 'Permanent Redirect',
577
528
  400 => 'Bad Request',
@@ -587,13 +538,13 @@ module Rack
587
538
  410 => 'Gone',
588
539
  411 => 'Length Required',
589
540
  412 => 'Precondition Failed',
590
- 413 => 'Payload Too Large',
541
+ 413 => 'Content Too Large',
591
542
  414 => 'URI Too Long',
592
543
  415 => 'Unsupported Media Type',
593
544
  416 => 'Range Not Satisfiable',
594
545
  417 => 'Expectation Failed',
595
546
  421 => 'Misdirected Request',
596
- 422 => 'Unprocessable Entity',
547
+ 422 => 'Unprocessable Content',
597
548
  423 => 'Locked',
598
549
  424 => 'Failed Dependency',
599
550
  425 => 'Too Early',
@@ -601,7 +552,7 @@ module Rack
601
552
  428 => 'Precondition Required',
602
553
  429 => 'Too Many Requests',
603
554
  431 => 'Request Header Fields Too Large',
604
- 451 => 'Unavailable for Legal Reasons',
555
+ 451 => 'Unavailable For Legal Reasons',
605
556
  500 => 'Internal Server Error',
606
557
  501 => 'Not Implemented',
607
558
  502 => 'Bad Gateway',
@@ -611,8 +562,6 @@ module Rack
611
562
  506 => 'Variant Also Negotiates',
612
563
  507 => 'Insufficient Storage',
613
564
  508 => 'Loop Detected',
614
- 509 => 'Bandwidth Limit Exceeded',
615
- 510 => 'Not Extended',
616
565
  511 => 'Network Authentication Required'
617
566
  }
618
567
 
@@ -620,12 +569,36 @@ module Rack
620
569
  STATUS_WITH_NO_ENTITY_BODY = Hash[((100..199).to_a << 204 << 304).product([true])]
621
570
 
622
571
  SYMBOL_TO_STATUS_CODE = Hash[*HTTP_STATUS_CODES.map { |code, message|
623
- [message.downcase.gsub(/\s|-|'/, '_').to_sym, code]
572
+ [message.downcase.gsub(/\s|-/, '_').to_sym, code]
624
573
  }.flatten]
625
574
 
575
+ OBSOLETE_SYMBOLS_TO_STATUS_CODES = {
576
+ payload_too_large: 413,
577
+ unprocessable_entity: 422,
578
+ bandwidth_limit_exceeded: 509,
579
+ not_extended: 510
580
+ }.freeze
581
+ private_constant :OBSOLETE_SYMBOLS_TO_STATUS_CODES
582
+
583
+ OBSOLETE_SYMBOL_MAPPINGS = {
584
+ payload_too_large: :content_too_large,
585
+ unprocessable_entity: :unprocessable_content
586
+ }.freeze
587
+ private_constant :OBSOLETE_SYMBOL_MAPPINGS
588
+
626
589
  def status_code(status)
627
590
  if status.is_a?(Symbol)
628
- SYMBOL_TO_STATUS_CODE.fetch(status) { raise ArgumentError, "Unrecognized status code #{status.inspect}" }
591
+ SYMBOL_TO_STATUS_CODE.fetch(status) do
592
+ fallback_code = OBSOLETE_SYMBOLS_TO_STATUS_CODES.fetch(status) { raise ArgumentError, "Unrecognized status code #{status.inspect}" }
593
+ message = "Status code #{status.inspect} is deprecated and will be removed in a future version of Rack."
594
+ if canonical_symbol = OBSOLETE_SYMBOL_MAPPINGS[status]
595
+ # message = "#{message} Please use #{canonical_symbol.inspect} instead."
596
+ # For now, let's not emit any warning when there is a mapping.
597
+ else
598
+ warn message, uplevel: 3
599
+ end
600
+ fallback_code
601
+ end
629
602
  else
630
603
  status.to_i
631
604
  end
data/lib/rack/version.rb CHANGED
@@ -12,20 +12,7 @@
12
12
  # so it should be enough just to <tt>require 'rack'</tt> in your code.
13
13
 
14
14
  module Rack
15
- # The Rack protocol version number implemented.
16
- VERSION = [1, 3].freeze
17
- deprecate_constant :VERSION
18
-
19
- VERSION_STRING = "1.3".freeze
20
- deprecate_constant :VERSION_STRING
21
-
22
- # The Rack protocol version number implemented.
23
- def self.version
24
- warn "Rack.version is deprecated and will be removed in Rack 3.1!", uplevel: 1
25
- VERSION
26
- end
27
-
28
- RELEASE = "3.0.18"
15
+ RELEASE = "3.1.18"
29
16
 
30
17
  # Return the Rack release as a dotted string.
31
18
  def self.release
data/lib/rack.rb CHANGED
@@ -15,10 +15,10 @@ require_relative 'rack/version'
15
15
  require_relative 'rack/constants'
16
16
 
17
17
  module Rack
18
+ autoload :BadRequest, "rack/bad_request"
18
19
  autoload :BodyProxy, "rack/body_proxy"
19
20
  autoload :Builder, "rack/builder"
20
21
  autoload :Cascade, "rack/cascade"
21
- autoload :Chunked, "rack/chunked"
22
22
  autoload :CommonLogger, "rack/common_logger"
23
23
  autoload :ConditionalGet, "rack/conditional_get"
24
24
  autoload :Config, "rack/config"
@@ -28,7 +28,6 @@ module Rack
28
28
  autoload :Directory, "rack/directory"
29
29
  autoload :ETag, "rack/etag"
30
30
  autoload :Events, "rack/events"
31
- autoload :File, "rack/file"
32
31
  autoload :Files, "rack/files"
33
32
  autoload :ForwardRequest, "rack/recursive"
34
33
  autoload :Head, "rack/head"
@@ -60,7 +59,6 @@ module Rack
60
59
 
61
60
  module Auth
62
61
  autoload :Basic, "rack/auth/basic"
63
- autoload :Digest, "rack/auth/digest"
64
62
  autoload :AbstractHandler, "rack/auth/abstract/handler"
65
63
  autoload :AbstractRequest, "rack/auth/abstract/request"
66
64
  end
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rack
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.0.18
4
+ version: 3.1.18
5
5
  platform: ruby
6
6
  authors:
7
7
  - Leah Neukirchen
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2025-05-22 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: minitest
@@ -75,9 +75,9 @@ email: leah@vuxu.org
75
75
  executables: []
76
76
  extensions: []
77
77
  extra_rdoc_files:
78
- - README.md
79
78
  - CHANGELOG.md
80
79
  - CONTRIBUTING.md
80
+ - README.md
81
81
  files:
82
82
  - CHANGELOG.md
83
83
  - CONTRIBUTING.md
@@ -88,15 +88,10 @@ files:
88
88
  - lib/rack/auth/abstract/handler.rb
89
89
  - lib/rack/auth/abstract/request.rb
90
90
  - lib/rack/auth/basic.rb
91
- - lib/rack/auth/digest.rb
92
- - lib/rack/auth/digest/md5.rb
93
- - lib/rack/auth/digest/nonce.rb
94
- - lib/rack/auth/digest/params.rb
95
- - lib/rack/auth/digest/request.rb
91
+ - lib/rack/bad_request.rb
96
92
  - lib/rack/body_proxy.rb
97
93
  - lib/rack/builder.rb
98
94
  - lib/rack/cascade.rb
99
- - lib/rack/chunked.rb
100
95
  - lib/rack/common_logger.rb
101
96
  - lib/rack/conditional_get.rb
102
97
  - lib/rack/config.rb
@@ -107,7 +102,6 @@ files:
107
102
  - lib/rack/directory.rb
108
103
  - lib/rack/etag.rb
109
104
  - lib/rack/events.rb
110
- - lib/rack/file.rb
111
105
  - lib/rack/files.rb
112
106
  - lib/rack/head.rb
113
107
  - lib/rack/headers.rb
@@ -162,7 +156,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
162
156
  - !ruby/object:Gem::Version
163
157
  version: '0'
164
158
  requirements: []
165
- rubygems_version: 3.6.2
159
+ rubygems_version: 3.6.9
166
160
  specification_version: 4
167
161
  summary: A modular Ruby webserver interface.
168
162
  test_files: []
@@ -1 +0,0 @@
1
- require_relative '../digest'
@@ -1 +0,0 @@
1
- require_relative '../digest'
@@ -1 +0,0 @@
1
- require_relative '../digest'
@@ -1 +0,0 @@
1
- require_relative '../digest'
@@ -1,256 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative 'abstract/handler'
4
- require_relative 'abstract/request'
5
- require 'digest/md5'
6
- require 'base64'
7
-
8
- module Rack
9
- warn "Rack::Auth::Digest is deprecated and will be removed in Rack 3.1", uplevel: 1
10
-
11
- module Auth
12
- module Digest
13
- # Rack::Auth::Digest::Nonce is the default nonce generator for the
14
- # Rack::Auth::Digest::MD5 authentication handler.
15
- #
16
- # +private_key+ needs to set to a constant string.
17
- #
18
- # +time_limit+ can be optionally set to an integer (number of seconds),
19
- # to limit the validity of the generated nonces.
20
-
21
- class Nonce
22
-
23
- class << self
24
- attr_accessor :private_key, :time_limit
25
- end
26
-
27
- def self.parse(string)
28
- new(*Base64.decode64(string).split(' ', 2))
29
- end
30
-
31
- def initialize(timestamp = Time.now, given_digest = nil)
32
- @timestamp, @given_digest = timestamp.to_i, given_digest
33
- end
34
-
35
- def to_s
36
- Base64.encode64("#{@timestamp} #{digest}").strip
37
- end
38
-
39
- def digest
40
- ::Digest::MD5.hexdigest("#{@timestamp}:#{self.class.private_key}")
41
- end
42
-
43
- def valid?
44
- digest == @given_digest
45
- end
46
-
47
- def stale?
48
- !self.class.time_limit.nil? && (Time.now.to_i - @timestamp) > self.class.time_limit
49
- end
50
-
51
- def fresh?
52
- !stale?
53
- end
54
-
55
- end
56
-
57
- class Params < Hash
58
-
59
- def self.parse(str)
60
- Params[*split_header_value(str).map do |param|
61
- k, v = param.split('=', 2)
62
- [k, dequote(v)]
63
- end.flatten]
64
- end
65
-
66
- def self.dequote(str) # From WEBrick::HTTPUtils
67
- ret = (/\A"(.*)"\Z/ =~ str) ? $1 : str.dup
68
- ret.gsub!(/\\(.)/, "\\1")
69
- ret
70
- end
71
-
72
- def self.split_header_value(str)
73
- str.scan(/\w+\=(?:"[^\"]+"|[^,]+)/n)
74
- end
75
-
76
- def initialize
77
- super()
78
-
79
- yield self if block_given?
80
- end
81
-
82
- def [](k)
83
- super k.to_s
84
- end
85
-
86
- def []=(k, v)
87
- super k.to_s, v.to_s
88
- end
89
-
90
- UNQUOTED = ['nc', 'stale']
91
-
92
- def to_s
93
- map do |k, v|
94
- "#{k}=#{(UNQUOTED.include?(k) ? v.to_s : quote(v))}"
95
- end.join(', ')
96
- end
97
-
98
- def quote(str) # From WEBrick::HTTPUtils
99
- '"' + str.gsub(/[\\\"]/o, "\\\1") + '"'
100
- end
101
-
102
- end
103
-
104
- class Request < Auth::AbstractRequest
105
- def method
106
- @env[RACK_METHODOVERRIDE_ORIGINAL_METHOD] || @env[REQUEST_METHOD]
107
- end
108
-
109
- def digest?
110
- "digest" == scheme
111
- end
112
-
113
- def correct_uri?
114
- request.fullpath == uri
115
- end
116
-
117
- def nonce
118
- @nonce ||= Nonce.parse(params['nonce'])
119
- end
120
-
121
- def params
122
- @params ||= Params.parse(parts.last)
123
- end
124
-
125
- def respond_to?(sym, *)
126
- super or params.has_key? sym.to_s
127
- end
128
-
129
- def method_missing(sym, *args)
130
- return super unless params.has_key?(key = sym.to_s)
131
- return params[key] if args.size == 0
132
- raise ArgumentError, "wrong number of arguments (#{args.size} for 0)"
133
- end
134
- end
135
-
136
- # Rack::Auth::Digest::MD5 implements the MD5 algorithm version of
137
- # HTTP Digest Authentication, as per RFC 2617.
138
- #
139
- # Initialize with the [Rack] application that you want protecting,
140
- # and a block that looks up a plaintext password for a given username.
141
- #
142
- # +opaque+ needs to be set to a constant base64/hexadecimal string.
143
- #
144
- class MD5 < AbstractHandler
145
-
146
- attr_accessor :opaque
147
-
148
- attr_writer :passwords_hashed
149
-
150
- def initialize(app, realm = nil, opaque = nil, &authenticator)
151
- @passwords_hashed = nil
152
- if opaque.nil? and realm.respond_to? :values_at
153
- realm, opaque, @passwords_hashed = realm.values_at :realm, :opaque, :passwords_hashed
154
- end
155
- super(app, realm, &authenticator)
156
- @opaque = opaque
157
- end
158
-
159
- def passwords_hashed?
160
- !!@passwords_hashed
161
- end
162
-
163
- def call(env)
164
- auth = Request.new(env)
165
-
166
- unless auth.provided?
167
- return unauthorized
168
- end
169
-
170
- if !auth.digest? || !auth.correct_uri? || !valid_qop?(auth)
171
- return bad_request
172
- end
173
-
174
- if valid?(auth)
175
- if auth.nonce.stale?
176
- return unauthorized(challenge(stale: true))
177
- else
178
- env['REMOTE_USER'] = auth.username
179
-
180
- return @app.call(env)
181
- end
182
- end
183
-
184
- unauthorized
185
- end
186
-
187
-
188
- private
189
-
190
- QOP = 'auth'
191
-
192
- def params(hash = {})
193
- Params.new do |params|
194
- params['realm'] = realm
195
- params['nonce'] = Nonce.new.to_s
196
- params['opaque'] = H(opaque)
197
- params['qop'] = QOP
198
-
199
- hash.each { |k, v| params[k] = v }
200
- end
201
- end
202
-
203
- def challenge(hash = {})
204
- "Digest #{params(hash)}"
205
- end
206
-
207
- def valid?(auth)
208
- valid_opaque?(auth) && valid_nonce?(auth) && valid_digest?(auth)
209
- end
210
-
211
- def valid_qop?(auth)
212
- QOP == auth.qop
213
- end
214
-
215
- def valid_opaque?(auth)
216
- H(opaque) == auth.opaque
217
- end
218
-
219
- def valid_nonce?(auth)
220
- auth.nonce.valid?
221
- end
222
-
223
- def valid_digest?(auth)
224
- pw = @authenticator.call(auth.username)
225
- pw && Rack::Utils.secure_compare(digest(auth, pw), auth.response)
226
- end
227
-
228
- def md5(data)
229
- ::Digest::MD5.hexdigest(data)
230
- end
231
-
232
- alias :H :md5
233
-
234
- def KD(secret, data)
235
- H "#{secret}:#{data}"
236
- end
237
-
238
- def A1(auth, password)
239
- "#{auth.username}:#{auth.realm}:#{password}"
240
- end
241
-
242
- def A2(auth)
243
- "#{auth.method}:#{auth.uri}"
244
- end
245
-
246
- def digest(auth, password)
247
- password_hash = passwords_hashed? ? password : H(A1(auth, password))
248
-
249
- KD password_hash, "#{auth.nonce}:#{auth.nc}:#{auth.cnonce}:#{QOP}:#{H A2(auth)}"
250
- end
251
-
252
- end
253
- end
254
- end
255
- end
256
-