protocol-http 0.53.0 → 0.55.0

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.
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Released under the MIT License.
4
+ # Copyright, 2025, by Samuel Williams.
5
+
6
+ require_relative "split"
7
+ require_relative "../quoted_string"
8
+ require_relative "../error"
9
+
10
+ module Protocol
11
+ module HTTP
12
+ module Header
13
+ # The `te` header indicates the transfer encodings the client is willing to accept. AKA `accept-transfer-encoding`. How we ended up with `te` instead of `accept-transfer-encoding` is a mystery lost to time.
14
+ #
15
+ # The `te` header allows a client to indicate which transfer encodings it can handle, and in what order of preference using quality factors.
16
+ class TE < Split
17
+ ParseError = Class.new(Error)
18
+
19
+ # Transfer encoding token pattern
20
+ TOKEN = /[!#$%&'*+\-.0-9A-Z^_`a-z|~]+/
21
+
22
+ # Quality value pattern (0.0 to 1.0)
23
+ QVALUE = /0(\.[0-9]{0,3})?|1(\.[0]{0,3})?/
24
+
25
+ # Pattern for parsing transfer encoding with optional quality factor
26
+ TRANSFER_CODING = /\A(?<name>#{TOKEN})(\s*;\s*q=(?<q>#{QVALUE}))?\z/
27
+
28
+ # The `chunked` transfer encoding
29
+ CHUNKED = "chunked"
30
+
31
+ # The `gzip` transfer encoding
32
+ GZIP = "gzip"
33
+
34
+ # The `deflate` transfer encoding
35
+ DEFLATE = "deflate"
36
+
37
+ # The `compress` transfer encoding
38
+ COMPRESS = "compress"
39
+
40
+ # The `identity` transfer encoding
41
+ IDENTITY = "identity"
42
+
43
+ # The `trailers` pseudo-encoding indicates willingness to accept trailer fields
44
+ TRAILERS = "trailers"
45
+
46
+ # A single transfer coding entry with optional quality factor
47
+ TransferCoding = Struct.new(:name, :q) do
48
+ def quality_factor
49
+ (q || 1.0).to_f
50
+ end
51
+
52
+ def <=> other
53
+ other.quality_factor <=> self.quality_factor
54
+ end
55
+
56
+ def to_s
57
+ if q && q != 1.0
58
+ "#{name};q=#{q}"
59
+ else
60
+ name.to_s
61
+ end
62
+ end
63
+ end
64
+
65
+ # Initializes the TE header with the given value. The value is split into distinct entries and converted to lowercase for normalization.
66
+ #
67
+ # @parameter value [String | Nil] the raw header value containing transfer encodings separated by commas.
68
+ def initialize(value = nil)
69
+ super(value&.downcase)
70
+ end
71
+
72
+ # Adds one or more comma-separated values to the TE header. The values are converted to lowercase for normalization.
73
+ #
74
+ # @parameter value [String] the value or values to add, separated by commas.
75
+ def << value
76
+ super(value.downcase)
77
+ end
78
+
79
+ # Parse the `te` header value into a list of transfer codings with quality factors.
80
+ #
81
+ # @returns [Array(TransferCoding)] the list of transfer codings and their associated quality factors.
82
+ def transfer_codings
83
+ self.map do |value|
84
+ if match = value.match(TRANSFER_CODING)
85
+ TransferCoding.new(match[:name], match[:q])
86
+ else
87
+ raise ParseError.new("Could not parse transfer coding: #{value.inspect}")
88
+ end
89
+ end
90
+ end
91
+
92
+ # @returns [Boolean] whether the `chunked` encoding is accepted.
93
+ def chunked?
94
+ self.any? {|value| value.start_with?(CHUNKED)}
95
+ end
96
+
97
+ # @returns [Boolean] whether the `gzip` encoding is accepted.
98
+ def gzip?
99
+ self.any? {|value| value.start_with?(GZIP)}
100
+ end
101
+
102
+ # @returns [Boolean] whether the `deflate` encoding is accepted.
103
+ def deflate?
104
+ self.any? {|value| value.start_with?(DEFLATE)}
105
+ end
106
+
107
+ # @returns [Boolean] whether the `compress` encoding is accepted.
108
+ def compress?
109
+ self.any? {|value| value.start_with?(COMPRESS)}
110
+ end
111
+
112
+ # @returns [Boolean] whether the `identity` encoding is accepted.
113
+ def identity?
114
+ self.any? {|value| value.start_with?(IDENTITY)}
115
+ end
116
+
117
+ # @returns [Boolean] whether trailers are accepted.
118
+ def trailers?
119
+ self.any? {|value| value.start_with?(TRAILERS)}
120
+ end
121
+
122
+ # Whether this header is acceptable in HTTP trailers.
123
+ # TE headers negotiate transfer encodings and must not appear in trailers.
124
+ # @returns [Boolean] `false`, as TE headers are hop-by-hop and control message framing.
125
+ def self.trailer?
126
+ false
127
+ end
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Released under the MIT License.
4
+ # Copyright, 2025, by Samuel Williams.
5
+
6
+ require_relative "split"
7
+
8
+ module Protocol
9
+ module HTTP
10
+ module Header
11
+ # Represents headers that can contain multiple distinct values separated by commas.
12
+ #
13
+ # This isn't a specific header class is a utility for handling headers with comma-separated values, such as `accept`, `cache-control`, and other similar headers. The values are split and stored as an array internally, and serialized back to a comma-separated string when needed.
14
+ class Trailer < Split
15
+ # Whether this header is acceptable in HTTP trailers.
16
+ # @returns [Boolean] `false`, as Trailer headers control trailer processing and must appear before the message body.
17
+ def self.trailer?
18
+ false
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Released under the MIT License.
4
+ # Copyright, 2025, by Samuel Williams.
5
+
6
+ require_relative "split"
7
+
8
+ module Protocol
9
+ module HTTP
10
+ module Header
11
+ # The `transfer-encoding` header indicates the encoding transformations that have been applied to the message body.
12
+ #
13
+ # The `transfer-encoding` header is used to specify the form of encoding used to safely transfer the message body between the sender and receiver.
14
+ class TransferEncoding < Split
15
+ # The `chunked` transfer encoding allows a server to send data of unknown length by breaking it into chunks.
16
+ CHUNKED = "chunked"
17
+
18
+ # The `gzip` transfer encoding compresses the message body using the gzip algorithm.
19
+ GZIP = "gzip"
20
+
21
+ # The `deflate` transfer encoding compresses the message body using the deflate algorithm.
22
+ DEFLATE = "deflate"
23
+
24
+ # The `compress` transfer encoding compresses the message body using the compress algorithm.
25
+ COMPRESS = "compress"
26
+
27
+ # The `identity` transfer encoding indicates no transformation has been applied.
28
+ IDENTITY = "identity"
29
+
30
+ # Initializes the transfer encoding header with the given value. The value is split into distinct entries and converted to lowercase for normalization.
31
+ #
32
+ # @parameter value [String | Nil] the raw header value containing transfer encodings separated by commas.
33
+ def initialize(value = nil)
34
+ super(value&.downcase)
35
+ end
36
+
37
+ # Adds one or more comma-separated values to the transfer encoding header. The values are converted to lowercase for normalization.
38
+ #
39
+ # @parameter value [String] the value or values to add, separated by commas.
40
+ def << value
41
+ super(value.downcase)
42
+ end
43
+
44
+ # @returns [Boolean] whether the `chunked` encoding is present.
45
+ def chunked?
46
+ self.include?(CHUNKED)
47
+ end
48
+
49
+ # @returns [Boolean] whether the `gzip` encoding is present.
50
+ def gzip?
51
+ self.include?(GZIP)
52
+ end
53
+
54
+ # @returns [Boolean] whether the `deflate` encoding is present.
55
+ def deflate?
56
+ self.include?(DEFLATE)
57
+ end
58
+
59
+ # @returns [Boolean] whether the `compress` encoding is present.
60
+ def compress?
61
+ self.include?(COMPRESS)
62
+ end
63
+
64
+ # @returns [Boolean] whether the `identity` encoding is present.
65
+ def identity?
66
+ self.include?(IDENTITY)
67
+ end
68
+
69
+ # Whether this header is acceptable in HTTP trailers.
70
+ # Transfer-Encoding headers control message framing and must not appear in trailers.
71
+ # @returns [Boolean] `false`, as Transfer-Encoding headers are hop-by-hop and must precede the message body.
72
+ def self.trailer?
73
+ false
74
+ end
75
+ end
76
+ end
77
+ end
78
+ end
@@ -17,11 +17,16 @@ require_relative "header/vary"
17
17
  require_relative "header/authorization"
18
18
  require_relative "header/date"
19
19
  require_relative "header/priority"
20
+ require_relative "header/trailer"
21
+ require_relative "header/server_timing"
22
+ require_relative "header/digest"
20
23
 
21
24
  require_relative "header/accept"
22
25
  require_relative "header/accept_charset"
23
26
  require_relative "header/accept_encoding"
24
27
  require_relative "header/accept_language"
28
+ require_relative "header/transfer_encoding"
29
+ require_relative "header/te"
25
30
 
26
31
  module Protocol
27
32
  module HTTP
@@ -65,7 +70,7 @@ module Protocol
65
70
  #
66
71
  # @parameter fields [Array] An array of `[key, value]` pairs.
67
72
  # @parameter tail [Integer | Nil] The index of the trailer start in the @fields array.
68
- def initialize(fields = [], tail = nil, indexed: nil)
73
+ def initialize(fields = [], tail = nil, indexed: nil, policy: POLICY)
69
74
  @fields = fields
70
75
 
71
76
  # Marks where trailer start in the @fields array:
@@ -73,6 +78,21 @@ module Protocol
73
78
 
74
79
  # The cached index of headers:
75
80
  @indexed = nil
81
+
82
+ @policy = policy
83
+ end
84
+
85
+ # @attribute [Hash] The policy for the headers.
86
+ attr :policy
87
+
88
+ # Set the policy for the headers.
89
+ #
90
+ # The policy is used to determine how headers are merged and normalized. For example, if a header is specified multiple times, the policy will determine how the values are merged.
91
+ #
92
+ # @parameter policy [Hash] The policy for the headers.
93
+ def policy=(policy)
94
+ @policy = policy
95
+ @indexed = nil
76
96
  end
77
97
 
78
98
  # Initialize a copy of the headers.
@@ -250,17 +270,23 @@ module Protocol
250
270
  "content-disposition" => false,
251
271
  "content-length" => false,
252
272
  "content-type" => false,
273
+ "expect" => false,
253
274
  "from" => false,
254
275
  "host" => false,
255
276
  "location" => false,
256
277
  "max-forwards" => false,
278
+ "range" => false,
257
279
  "referer" => false,
258
280
  "retry-after" => false,
281
+ "server" => false,
282
+ "transfer-encoding" => Header::TransferEncoding,
259
283
  "user-agent" => false,
284
+ "trailer" => Header::Trailer,
260
285
 
261
286
  # Custom headers:
262
287
  "connection" => Header::Connection,
263
288
  "cache-control" => Header::CacheControl,
289
+ "te" => Header::TE,
264
290
  "vary" => Header::Vary,
265
291
  "priority" => Header::Priority,
266
292
 
@@ -299,6 +325,12 @@ module Protocol
299
325
  "accept-charset" => Header::AcceptCharset,
300
326
  "accept-encoding" => Header::AcceptEncoding,
301
327
  "accept-language" => Header::AcceptLanguage,
328
+
329
+ # Performance headers:
330
+ "server-timing" => Header::ServerTiming,
331
+
332
+ # Content integrity headers:
333
+ "digest" => Header::Digest,
302
334
  }.tap{|hash| hash.default = Split}
303
335
 
304
336
  # Delete all header values for the given key, and return the merged value.
@@ -316,7 +348,7 @@ module Protocol
316
348
 
317
349
  if @indexed
318
350
  return @indexed.delete(key)
319
- elsif policy = POLICY[key]
351
+ elsif policy = @policy[key]
320
352
  (key, value), *tail = deleted
321
353
  merged = policy.new(value)
322
354
 
@@ -334,14 +366,24 @@ module Protocol
334
366
  # @parameter hash [Hash] The hash to merge into.
335
367
  # @parameter key [String] The header key.
336
368
  # @parameter value [String] The raw header value.
337
- protected def merge_into(hash, key, value)
338
- if policy = POLICY[key]
369
+ protected def merge_into(hash, key, value, trailer = @tail)
370
+ if policy = @policy[key]
371
+ # Check if we're adding to trailers and this header is allowed:
372
+ if trailer && !policy.trailer?
373
+ return false
374
+ end
375
+
339
376
  if current_value = hash[key]
340
377
  current_value << value
341
378
  else
342
379
  hash[key] = policy.new(value)
343
380
  end
344
381
  else
382
+ # By default, headers are not allowed in trailers:
383
+ if trailer
384
+ return false
385
+ end
386
+
345
387
  if hash.key?(key)
346
388
  raise DuplicateHeaderError, key
347
389
  end
@@ -362,11 +404,17 @@ module Protocol
362
404
  #
363
405
  # @returns [Hash] A hash table of `{key, value}` pairs.
364
406
  def to_h
365
- @indexed ||= @fields.inject({}) do |hash, (key, value)|
366
- merge_into(hash, key.downcase, value)
407
+ unless @indexed
408
+ @indexed = {}
367
409
 
368
- hash
410
+ @fields.each_with_index do |(key, value), index|
411
+ trailer = (@tail && index >= @tail)
412
+
413
+ merge_into(@indexed, key.downcase, value, trailer)
414
+ end
369
415
  end
416
+
417
+ return @indexed
370
418
  end
371
419
 
372
420
  alias as_json to_h
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Released under the MIT License.
4
+ # Copyright, 2025, by Samuel Williams.
5
+
6
+ module Protocol
7
+ module HTTP
8
+ # According to https://tools.ietf.org/html/rfc7231#appendix-C
9
+ TOKEN = /[!#$%&'*+\-.^_`|~0-9A-Z]+/i
10
+
11
+ QUOTED_STRING = /"(?:.(?!(?<!\\)"))*.?"/
12
+
13
+ # https://tools.ietf.org/html/rfc7231#section-5.3.1
14
+ QVALUE = /0(\.[0-9]{0,3})?|1(\.[0]{0,3})?/
15
+
16
+ # Handling of HTTP quoted strings.
17
+ module QuotedString
18
+ # Unquote a "quoted-string" value according to <https://tools.ietf.org/html/rfc7230#section-3.2.6>. It should already match the QUOTED_STRING pattern above by the parser.
19
+ def self.unquote(value, normalize_whitespace = true)
20
+ value = value[1...-1]
21
+
22
+ value.gsub!(/\\(.)/, '\1')
23
+
24
+ if normalize_whitespace
25
+ # LWS = [CRLF] 1*( SP | HT )
26
+ value.gsub!(/[\r\n]+\s+/, " ")
27
+ end
28
+
29
+ return value
30
+ end
31
+
32
+ QUOTES_REQUIRED = /[()<>@,;:\\"\/\[\]?={} \t]/
33
+
34
+ # Quote a string for HTTP header values if required.
35
+ #
36
+ # @raises [ArgumentError] if the value contains invalid characters like control characters or newlines.
37
+ def self.quote(value, force = false)
38
+ # Check if quoting is required:
39
+ if value =~ QUOTES_REQUIRED or force
40
+ "\"#{value.gsub(/["\\]/, '\\\\\0')}\""
41
+ else
42
+ value
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
@@ -5,6 +5,6 @@
5
5
 
6
6
  module Protocol
7
7
  module HTTP
8
- VERSION = "0.53.0"
8
+ VERSION = "0.55.0"
9
9
  end
10
10
  end
data/readme.md CHANGED
@@ -18,11 +18,9 @@ Please see the [project documentation](https://socketry.github.io/protocol-http/
18
18
 
19
19
  - [Message Body](https://socketry.github.io/protocol-http/guides/message-body/index) - This guide explains how to work with HTTP request and response message bodies using `Protocol::HTTP::Body` classes.
20
20
 
21
- - [Middleware](https://socketry.github.io/protocol-http/guides/middleware/index) - This guide explains how to build and use HTTP middleware with `Protocol::HTTP::Middleware`.
22
-
23
- - [Hypertext References](https://socketry.github.io/protocol-http/guides/hypertext-references/index) - This guide explains how to use `Protocol::HTTP::Reference` for constructing and manipulating hypertext references (URLs with parameters).
21
+ - [Headers](https://socketry.github.io/protocol-http/guides/headers/index) - This guide explains how to work with HTTP headers using `protocol-http`.
24
22
 
25
- - [URL Parsing](https://socketry.github.io/protocol-http/guides/url-parsing/index) - This guide explains how to use `Protocol::HTTP::URL` for parsing and manipulating URL components, particularly query strings and parameters.
23
+ - [Middleware](https://socketry.github.io/protocol-http/guides/middleware/index) - This guide explains how to build and use HTTP middleware with `Protocol::HTTP::Middleware`.
26
24
 
27
25
  - [Streaming](https://socketry.github.io/protocol-http/guides/streaming/index) - This guide gives an overview of how to implement streaming requests and responses.
28
26
 
@@ -32,6 +30,20 @@ Please see the [project documentation](https://socketry.github.io/protocol-http/
32
30
 
33
31
  Please see the [project releases](https://socketry.github.io/protocol-http/releases/index) for all releases.
34
32
 
33
+ ### v0.55.0
34
+
35
+ - **Breaking**: Move `Protocol::HTTP::Header::QuotedString` to `Protocol::HTTP::QuotedString` for better reusability.
36
+ - **Breaking**: Handle cookie key/value pairs using `QuotedString` as per RFC 6265.
37
+ - Don't use URL encoding for cookie key/value.
38
+ - **Breaking**: Remove `Protocol::HTTP::URL` and `Protocol::HTTP::Reference` – replaced by `Protocol::URL` gem.
39
+ - `Protocol::HTTP::URL` -\> `Protocol::URL::Encoding`.
40
+ - `Protocol::HTTP::Reference` -\> `Protocol::URL::Reference`.
41
+
42
+ ### v0.54.0
43
+
44
+ - Introduce rich support for `Header::Digest`, `Header::ServerTiming`, `Header::TE`, `Header::Trailer` and `Header::TransferEncoding`.
45
+ - [Improved HTTP Trailer Security](https://socketry.github.io/protocol-http/releases/index#improved-http-trailer-security)
46
+
35
47
  ### v0.53.0
36
48
 
37
49
  - Improve consistency of Body `#inspect`.
@@ -70,17 +82,13 @@ Please see the [project releases](https://socketry.github.io/protocol-http/relea
70
82
 
71
83
  - Ensure chunks are flushed if required, when streaming.
72
84
 
73
- ### v0.30.0
74
-
75
- - [`Request[]` and `Response[]` Keyword Arguments](https://socketry.github.io/protocol-http/releases/index#request[]-and-response[]-keyword-arguments)
76
- - [Interim Response Handling](https://socketry.github.io/protocol-http/releases/index#interim-response-handling)
77
-
78
85
  ## See Also
79
86
 
80
87
  - [protocol-http1](https://github.com/socketry/protocol-http1) — HTTP/1 client/server implementation using this
81
88
  interface.
82
89
  - [protocol-http2](https://github.com/socketry/protocol-http2) — HTTP/2 client/server implementation using this
83
90
  interface.
91
+ - [protocol-url](https://github.com/socketry/protocol-url) — URL parsing and manipulation library.
84
92
  - [async-http](https://github.com/socketry/async-http) — Asynchronous HTTP client and server, supporting multiple HTTP
85
93
  protocols & TLS.
86
94
  - [async-websocket](https://github.com/socketry/async-websocket) — Asynchronous client and server WebSockets.