File tree 2 files changed +51
-4
lines changed
2 files changed +51
-4
lines changed Original file line number Diff line number Diff line change @@ -30,12 +30,17 @@ def self.unquote(value, normalize_whitespace = true)
30
30
return value
31
31
end
32
32
33
- # Quote a string if required. Doesn't handle newlines correctly currently.
33
+ QUOTES_REQUIRED = /[()<>@,;:\\ "\/ \[ \] ?={} \t ]/
34
+
35
+ # Quote a string for HTTP header values if required.
36
+ #
37
+ # @raises [ArgumentError] if the value contains invalid characters like control characters or newlines.
34
38
def self . quote ( value , force = false )
35
- if value =~ /"/ or force
36
- "\" #{ value . gsub ( /["\\ ]/ , "\\ \\ \\ 0" ) } \" "
39
+ # Check if quoting is required:
40
+ if value =~ QUOTES_REQUIRED or force
41
+ "\" #{ value . gsub ( /["\\ ]/ , '\\\\\0' ) } \" "
37
42
else
38
- return value
43
+ value
39
44
end
40
45
end
41
46
end
Original file line number Diff line number Diff line change
1
+ # frozen_string_literal: true
2
+
3
+ # Released under the MIT License.
4
+ # Copyright, 2016-2024, by Samuel Williams.
5
+
6
+ require 'protocol/http/header/quoted_string'
7
+
8
+ describe Protocol ::HTTP ::Header ::QuotedString do
9
+ with ".unquote" do
10
+ it "ignores linear whitespace" do
11
+ quoted_string = subject . unquote ( %Q{"Hello\r \n World"} )
12
+
13
+ expect ( quoted_string ) . to be == "Hello World"
14
+ end
15
+ end
16
+
17
+ with ".quote" do
18
+ it "doesn't quote a string that has no special characters" do
19
+ quoted_string = subject . quote ( "Hello" )
20
+
21
+ expect ( quoted_string ) . to be == "Hello"
22
+ end
23
+
24
+ it "quotes a string with a space" do
25
+ quoted_string = subject . quote ( "Hello World" )
26
+
27
+ expect ( quoted_string ) . to be == %Q{"Hello World"}
28
+ end
29
+
30
+ it "quotes a string with a double quote" do
31
+ quoted_string = subject . quote ( %Q{Hello "World"} )
32
+
33
+ expect ( quoted_string ) . to be == %Q{"Hello \\ "World\\ ""}
34
+ end
35
+
36
+ it "quotes a string with a backslash" do
37
+ quoted_string = subject . quote ( %Q{Hello \\ World} )
38
+
39
+ expect ( quoted_string ) . to be == %Q{"Hello \\ \\ World"}
40
+ end
41
+ end
42
+ end
You can’t perform that action at this time.
0 commit comments