http_resource 0.2.0 → 0.4.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.
- checksums.yaml +4 -4
- data/README.md +278 -2
- data/lib/http_resource/client.rb +70 -6
- data/lib/http_resource/conditional_cache.rb +135 -0
- data/lib/http_resource/configuration.rb +5 -1
- data/lib/http_resource/public_address.rb +93 -0
- data/lib/http_resource/safe_fetch/call.rb +71 -0
- data/lib/http_resource/safe_fetch/wire.rb +163 -0
- data/lib/http_resource/safe_fetch.rb +248 -0
- data/lib/http_resource/simulation/backend.rb +225 -0
- data/lib/http_resource/simulation/store.rb +89 -0
- data/lib/http_resource/simulation.rb +7 -0
- data/lib/http_resource/value_object.rb +3 -2
- data/lib/http_resource/version.rb +1 -1
- data/lib/http_resource.rb +10 -2
- metadata +9 -3
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "ipaddr"
|
|
4
|
+
require "socket"
|
|
5
|
+
|
|
6
|
+
module HttpResource
|
|
7
|
+
# Whether a resolved address is one a fetch of a URL someone else gave may connect to. Public means
|
|
8
|
+
# globally reachable unicast, as an ALLOW rule: anything not shown public is refused, an unparsable value
|
|
9
|
+
# included.
|
|
10
|
+
#
|
|
11
|
+
# IPv4: everything but loopback, the private ranges, link-local (the cloud metadata address
|
|
12
|
+
# 169.254.169.254 among it), shared address space, "this network", the IETF protocol block, the
|
|
13
|
+
# documentation and benchmarking ranges, the 6to4 relay, multicast and 240/4 with the broadcast address.
|
|
14
|
+
# IPv6: only global unicast 2000::/3, less the IETF protocol block (Teredo, benchmarking and ORCHIDv2
|
|
15
|
+
# inside it), the documentation ranges and 6to4 whole. An IPv6 address that carries an IPv4 address
|
|
16
|
+
# (IPv4-mapped, NAT64) is judged by the IPv4 address it carries. A value with a prefix length shorter
|
|
17
|
+
# than its family's full length is a range, not an address, and is never public; nor is a String that
|
|
18
|
+
# is not ASCII only.
|
|
19
|
+
#
|
|
20
|
+
# HttpResource::PublicAddress.public?("93.184.216.34") # => true
|
|
21
|
+
# HttpResource::PublicAddress.public?("::ffff:10.0.0.5") # => false
|
|
22
|
+
# HttpResource::PublicAddress.connectable?("172.20.1.2", inside: true) # => true
|
|
23
|
+
module PublicAddress
|
|
24
|
+
NOT_PUBLIC_V4 = %w[
|
|
25
|
+
0.0.0.0/8 10.0.0.0/8 100.64.0.0/10 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.0.0.0/24 192.0.2.0/24
|
|
26
|
+
192.88.99.0/24 192.168.0.0/16 198.18.0.0/15 198.51.100.0/24 203.0.113.0/24 224.0.0.0/4 240.0.0.0/4
|
|
27
|
+
].map { IPAddr.new(_1) }.freeze
|
|
28
|
+
GLOBAL_UNICAST_V6 = IPAddr.new("2000::/3")
|
|
29
|
+
NOT_PUBLIC_V6 = %w[2001::/23 2001:db8::/32 2002::/16 3fff::/20].map { IPAddr.new(_1) }.freeze
|
|
30
|
+
# IPv6 forms that carry an IPv4 address in their last 32 bits.
|
|
31
|
+
CARRIES_V4 = %w[::ffff:0:0/96 64:ff9b::/96].map { IPAddr.new(_1) }.freeze
|
|
32
|
+
# RFC 1918: the only addresses not public that connectable? may allow, and only with inside: true.
|
|
33
|
+
PRIVATE_V4 = %w[10.0.0.0/8 172.16.0.0/12 192.168.0.0/16].map { IPAddr.new(_1) }.freeze
|
|
34
|
+
private_constant :NOT_PUBLIC_V4, :GLOBAL_UNICAST_V6, :NOT_PUBLIC_V6, :CARRIES_V4, :PRIVATE_V4
|
|
35
|
+
|
|
36
|
+
# True when +address+ (an IPAddr, or an address String) is public; false for everything else, never nil.
|
|
37
|
+
def self.public?(address)
|
|
38
|
+
ip = ip_of(address)
|
|
39
|
+
ip.ipv4? ? public_v4?(ip) : public_v6?(ip)
|
|
40
|
+
rescue IPAddr::Error
|
|
41
|
+
false
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# public?, or, with inside: true (a host the app names as on its own private network), a plain IPv4
|
|
45
|
+
# address in RFC 1918's ranges. Every other address that is not public stays false, an RFC 1918
|
|
46
|
+
# address carried in IPv6 included.
|
|
47
|
+
def self.connectable?(address, inside: false)
|
|
48
|
+
return true if public?(address)
|
|
49
|
+
|
|
50
|
+
ip = ip_of(address)
|
|
51
|
+
inside == true && ip.ipv4? && PRIVATE_V4.any? { _1.include?(ip) }
|
|
52
|
+
rescue IPAddr::Error
|
|
53
|
+
false
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# The one address +address+ is, as an IPAddr, or nil when it is none: the reading public? and
|
|
57
|
+
# connectable? judge by.
|
|
58
|
+
def self.address(address)
|
|
59
|
+
ip_of(address)
|
|
60
|
+
rescue IPAddr::Error
|
|
61
|
+
nil
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# One address, never a range: IPAddr reads "127.0.0.1/0" as 0.0.0.0/0, which no blocked range wholly
|
|
65
|
+
# holds, so a range is refused here as an unparsable value is. So is a String that is not ASCII only
|
|
66
|
+
# (a byte outside ASCII, invalid bytes, an encoding that is not ASCII's), which no address is and on
|
|
67
|
+
# which IPAddr raises an encoding error of its own.
|
|
68
|
+
def self.ip_of(address)
|
|
69
|
+
unless address.is_a?(IPAddr) || address.to_s.ascii_only?
|
|
70
|
+
raise IPAddr::InvalidAddressError, "an address is written in ASCII only"
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
ip = address.is_a?(IPAddr) ? address : IPAddr.new(address.to_s)
|
|
74
|
+
return ip if ip.prefix == (ip.ipv4? ? 32 : 128)
|
|
75
|
+
|
|
76
|
+
raise IPAddr::InvalidAddressError, "a range is no address"
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def self.public_v4?(ip)
|
|
80
|
+
NOT_PUBLIC_V4.none? { _1.include?(ip) }
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def self.public_v6?(ip)
|
|
84
|
+
if CARRIES_V4.any? { _1.include?(ip) }
|
|
85
|
+
return public_v4?(IPAddr.new(ip.to_i & 0xffff_ffff, Socket::AF_INET))
|
|
86
|
+
end
|
|
87
|
+
return false unless GLOBAL_UNICAST_V6.include?(ip)
|
|
88
|
+
|
|
89
|
+
NOT_PUBLIC_V6.none? { _1.include?(ip) }
|
|
90
|
+
end
|
|
91
|
+
private_class_method :ip_of, :public_v4?, :public_v6?
|
|
92
|
+
end
|
|
93
|
+
end
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module HttpResource
|
|
4
|
+
class SafeFetch
|
|
5
|
+
# How a host is read: what a host name is, written once for an inside list entry and a request's host
|
|
6
|
+
# alike, and the form a request's host is compared in.
|
|
7
|
+
module Host
|
|
8
|
+
# Lower-case labels of a to z, 0 to 9 and hyphen joined by dots, none empty, longer than 63 or with a
|
|
9
|
+
# hyphen at either end, and a last label that begins with a letter. No top-level name is a number, so
|
|
10
|
+
# no spelling of an IPv4 address is a name (10.0.5, 0xa.0.0.5, 167772165), and an IPv6 literal, with
|
|
11
|
+
# its colons, never is. One label alone is a name.
|
|
12
|
+
NAME = /\A(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?\z/
|
|
13
|
+
|
|
14
|
+
# Whether +text+ is a host name in exactly that form, at most 253 characters.
|
|
15
|
+
def self.name?(text)
|
|
16
|
+
text.is_a?(String) && text.ascii_only? && text.size <= 253 && NAME.match?(text)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# A request's host as it is compared with the list: lower case, one trailing dot dropped.
|
|
20
|
+
def self.form(host) = host.downcase.delete_suffix(".")
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# The form each keyword takes. A keyword off its form is an ArgumentError naming the keyword, never its
|
|
24
|
+
# value, raised when the policy is built or the call is made, before any lookup.
|
|
25
|
+
module Forms
|
|
26
|
+
SECONDS = ->(value) { value.is_a?(Numeric) && value.real? && value.finite? && value.positive? }
|
|
27
|
+
CALLABLE_OR_NIL = ->(value) { value.nil? || value.respond_to?(:call) }
|
|
28
|
+
BYTES = ->(value) { value.is_a?(Integer) && value.positive? }
|
|
29
|
+
RULES = {
|
|
30
|
+
inside_hosts: ["an Array of host names, each lower-case labels of letters, digits and hyphens " \
|
|
31
|
+
"joined by dots, the last label beginning with a letter",
|
|
32
|
+
->(list) { list.is_a?(Array) && list.all? { Host.name?(_1) } }],
|
|
33
|
+
user_agent: ["nil or a String", ->(value) { value.nil? || value.is_a?(String) }],
|
|
34
|
+
max_redirects: ["an Integer from 1 to 10", ->(cap) { cap.is_a?(Integer) && cap.between?(1, 10) }],
|
|
35
|
+
resolver: ["callable", ->(value) { value.respond_to?(:call) }],
|
|
36
|
+
allow: ["nil or callable", CALLABLE_OR_NIL],
|
|
37
|
+
accept_type: ["nil or callable", CALLABLE_OR_NIL],
|
|
38
|
+
headers: ["a Hash", ->(value) { value.is_a?(Hash) }],
|
|
39
|
+
plain_http: ["one of #{PLAIN_HTTP.inspect}", ->(value) { PLAIN_HTTP.include?(value) }],
|
|
40
|
+
follow_redirects: ["true or false", ->(value) { [true, false].include?(value) }],
|
|
41
|
+
max_bytes: ["a positive Integer number of bytes", BYTES],
|
|
42
|
+
deadline: ["a finite positive number of seconds", SECONDS],
|
|
43
|
+
open_timeout: ["a finite positive number of seconds", SECONDS],
|
|
44
|
+
read_timeout: ["a finite positive number of seconds", SECONDS]
|
|
45
|
+
}.freeze
|
|
46
|
+
|
|
47
|
+
def self.check!(**keywords)
|
|
48
|
+
keywords.each do |name, value|
|
|
49
|
+
form, held = RULES.fetch(name)
|
|
50
|
+
raise ArgumentError, "#{name} must be #{form}" unless held.call(value)
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# One call's options, the monotonic instant its deadline passes, and the URI it asked first (set once
|
|
56
|
+
# the URL is read), which a message names whole where it names a hop's cut.
|
|
57
|
+
Call = Data.define(:allow, :headers, :plain_http, :follow_redirects, :accept_type, :max_bytes,
|
|
58
|
+
:open_timeout, :read_timeout, :ends_at, :target, :asked) do
|
|
59
|
+
def self.for(deadline:, target: false, **keywords)
|
|
60
|
+
Forms.check!(deadline:, **keywords)
|
|
61
|
+
new(ends_at: SafeFetch.monotonic_now + deadline, target:, asked: nil, **keywords)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# The seconds left before the deadline; a SafeFetch::Error :timeout once none are.
|
|
65
|
+
def left!
|
|
66
|
+
Bounds.left!(ends_at)
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
private_constant :Host, :Forms, :Call
|
|
70
|
+
end
|
|
71
|
+
end
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module HttpResource
|
|
4
|
+
class SafeFetch
|
|
5
|
+
# The bounds a body read is held to (the declared length, the bytes read and the deadline), and the one
|
|
6
|
+
# bound on what a message repeats of the far end's words.
|
|
7
|
+
module Bounds
|
|
8
|
+
# The first 200 bytes of +text+, tagged UTF-8 with each invalid byte sequence made a "?": every piece
|
|
9
|
+
# of the far end's words a message repeats goes through here, so a message is a String an app can log
|
|
10
|
+
# or put in JSON whatever bytes arrived.
|
|
11
|
+
def self.cut(text)
|
|
12
|
+
text.to_s.byteslice(0, 200).force_encoding(Encoding::UTF_8).scrub("?")
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# Refuses a declared Content-Length over +cap+ before a body byte is read (nil: no cap).
|
|
16
|
+
def self.declared!(response, cap)
|
|
17
|
+
declared = response["Content-Length"].to_s[/\A\s*(\d+)\s*\z/, 1]
|
|
18
|
+
return unless cap && declared && declared.to_i > cap
|
|
19
|
+
|
|
20
|
+
raise Error.new("the declared Content-Length #{cut(declared)} is over #{cap} bytes",
|
|
21
|
+
reason: :too_large)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def self.over(cap)
|
|
25
|
+
Error.new("the body is over #{cap} bytes", reason: :too_large)
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def self.left!(ends_at)
|
|
29
|
+
left = ends_at - SafeFetch.monotonic_now
|
|
30
|
+
raise Error.new("the deadline passed", reason: :timeout) unless left.positive?
|
|
31
|
+
|
|
32
|
+
left
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# What an error the wire raises counts as, one list for a request and a body read alike: one of
|
|
37
|
+
# TIMEOUT_ERRORS is :timeout; while a body is read, an end of the stream before the body's end is
|
|
38
|
+
# :truncated whatever the transport calls it (EOFError; over TLS, OpenSSL's "unexpected eof while
|
|
39
|
+
# reading", which a connection cut without its closing message raises); every other error of
|
|
40
|
+
# NETWORK_ERRORS is :network, an early end before a body among them (no answer came).
|
|
41
|
+
module WireReason
|
|
42
|
+
EARLY_END = /unexpected eof/i
|
|
43
|
+
|
|
44
|
+
def self.of(error, body:)
|
|
45
|
+
case error
|
|
46
|
+
when *TIMEOUT_ERRORS then :timeout
|
|
47
|
+
when EOFError then body ? :truncated : :network
|
|
48
|
+
when OpenSSL::SSL::SSLError then body && EARLY_END.match?(error.message) ? :truncated : :network
|
|
49
|
+
else :network
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Laid on a connection's socket (Net::BufferedIO) once it connects. Net::HTTP reads every line with
|
|
55
|
+
# #readuntil and a body with #read or #read_all, so the lines read before the first body read are the
|
|
56
|
+
# head, of every 1xx answer too: they hold HEAD_BYTES in all. No line, before a body or inside it (a
|
|
57
|
+
# chunk size, a trailer), may reach HEAD_BYTES before its end, whether that end arrives in the read that
|
|
58
|
+
# crosses the bound or never.
|
|
59
|
+
module BoundedHead
|
|
60
|
+
def bound_head!
|
|
61
|
+
@head_left = HEAD_BYTES
|
|
62
|
+
self
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def readuntil(terminator, *)
|
|
66
|
+
line = super
|
|
67
|
+
unended = line.bytesize - (line.end_with?(terminator) ? terminator.bytesize : 0)
|
|
68
|
+
raise HeadTooLarge, "a response line is over #{HEAD_BYTES} bytes" if unended >= HEAD_BYTES
|
|
69
|
+
return line unless @head_left
|
|
70
|
+
|
|
71
|
+
@head_left -= line.bytesize
|
|
72
|
+
raise HeadTooLarge, "the response head is over #{HEAD_BYTES} bytes" if @head_left.negative?
|
|
73
|
+
|
|
74
|
+
line
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def read(*)
|
|
78
|
+
@head_left = nil
|
|
79
|
+
super
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def read_all(*)
|
|
83
|
+
@head_left = nil
|
|
84
|
+
super
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
private
|
|
88
|
+
|
|
89
|
+
# Called only while a line is unended (a body read empties the buffer first): the buffer is that line.
|
|
90
|
+
def rbuf_fill
|
|
91
|
+
raise HeadTooLarge, "a response line is over #{HEAD_BYTES} bytes" if rbuf_size >= HEAD_BYTES
|
|
92
|
+
|
|
93
|
+
super
|
|
94
|
+
end
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# Laid on each Net::HTTP .connection makes: Net::HTTP's own hook once the socket, and TLS, is up.
|
|
98
|
+
module BoundsHead
|
|
99
|
+
private
|
|
100
|
+
|
|
101
|
+
def on_connect
|
|
102
|
+
super
|
|
103
|
+
@socket.extend(BoundedHead).bound_head!
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
private_constant :Bounds, :WireReason, :BoundedHead, :BoundsHead
|
|
107
|
+
|
|
108
|
+
class << self
|
|
109
|
+
# A Net::HTTP to +host+ on +port+ for one request that never takes an environment proxy and bounds
|
|
110
|
+
# the head from its connect. The caller sets TLS, the address to connect to, timeouts and retries.
|
|
111
|
+
def connection(host, port)
|
|
112
|
+
Net::HTTP.new(host, port, nil).extend(BoundsHead)
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
# +response+'s body as a binary String, read in chunks under +max_bytes+ (nil: no cap) and wholly
|
|
116
|
+
# under Timeout for what is left before +ends_at+, a monotonic_now instant (nil: no deadline). Every
|
|
117
|
+
# error the wire raises while it reads is a SafeFetch::Error by WireReason, never raised as it is. A
|
|
118
|
+
# body whose stream ends before the body does (short of its Content-Length, a chunked body before its
|
|
119
|
+
# last chunk, or over TLS a connection cut without its closing message) is refused, never handed over
|
|
120
|
+
# in part: Net::HTTP raises EOFError for it once the response no longer ignores an early end, OpenSSL
|
|
121
|
+
# its own error, and a body the close ends by its framing raises neither.
|
|
122
|
+
def read_body(response, max_bytes:, ends_at: nil)
|
|
123
|
+
Bounds.declared!(response, max_bytes)
|
|
124
|
+
response.ignore_eof = false
|
|
125
|
+
return stream(response, max_bytes) if ends_at.nil?
|
|
126
|
+
|
|
127
|
+
Timeout.timeout(Bounds.left!(ends_at)) { stream(response, max_bytes) }
|
|
128
|
+
rescue *TIMEOUT_ERRORS, *NETWORK_ERRORS => e
|
|
129
|
+
reason = WireReason.of(e, body: true)
|
|
130
|
+
raise Error.new("the connection closed before the end of the body", reason:) if reason == :truncated
|
|
131
|
+
|
|
132
|
+
raise Error.new("#{e.class} reading the body: #{Bounds.cut(e.message)}", reason:)
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
# +text+ with every byte outside ASCII percent-encoded, as a browser writes a raw letter on the
|
|
136
|
+
# wire; escapes already there and everything else are left as they are.
|
|
137
|
+
def wire_url(text)
|
|
138
|
+
text.to_s.b.gsub(/[\x80-\xFF]/n) { format("%%%02X", _1.ord) }.force_encoding(Encoding::UTF_8)
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
# The lower-cased type/subtype of the answer's Content-Type, or nil.
|
|
142
|
+
def media_type(response)
|
|
143
|
+
type = response["content-type"].to_s.split(";").first.to_s.strip.downcase
|
|
144
|
+
type unless type.empty?
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def monotonic_now
|
|
148
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
private
|
|
152
|
+
|
|
153
|
+
def stream(response, cap)
|
|
154
|
+
body = String.new(encoding: Encoding::BINARY)
|
|
155
|
+
response.read_body do |chunk|
|
|
156
|
+
body << chunk.b
|
|
157
|
+
raise Bounds.over(cap) if cap && body.bytesize > cap
|
|
158
|
+
end
|
|
159
|
+
body
|
|
160
|
+
end
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
end
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "ipaddr"
|
|
4
|
+
require "net/http"
|
|
5
|
+
require "openssl"
|
|
6
|
+
require "socket"
|
|
7
|
+
require "timeout"
|
|
8
|
+
require "uri"
|
|
9
|
+
require "zlib"
|
|
10
|
+
require "http_resource/errors"
|
|
11
|
+
require "http_resource/public_address"
|
|
12
|
+
|
|
13
|
+
module HttpResource
|
|
14
|
+
# A GET of a URL someone else gave, under one strict rule; opt-in, beside the unchanged Client.
|
|
15
|
+
#
|
|
16
|
+
# Before every request, the first and each redirect hop: the URL must be https (plain http only as the
|
|
17
|
+
# call's plain_http says) with no userinfo, and its host is resolved and refused, unsent, unless EVERY
|
|
18
|
+
# address is public (PublicAddress.connectable?), or RFC 1918 IPv4 for a host the app names in
|
|
19
|
+
# inside_hosts. The connection goes to the checked address (the first IPv4 one, else the first) and never
|
|
20
|
+
# through an environment proxy; TLS verifies the URL's host by Net::HTTP's defaults. At most
|
|
21
|
+
# max_redirects hops, each target put to the call's allow. Every call is bounded: a cap on the body's
|
|
22
|
+
# bytes as read (after inflation), a wall-clock deadline over all hops, a bounded head, no retry; a body
|
|
23
|
+
# its connection cut short is refused, never returned in part. Nothing an answer sends (a cookie) reaches
|
|
24
|
+
# the next hop. A message is always valid UTF-8: each piece of what the far end wrote that it repeats (a
|
|
25
|
+
# hop's URL, a declared length, a content type, a broken line) is cut to its first 200 bytes, and a URL
|
|
26
|
+
# that could not be read is not repeated at all.
|
|
27
|
+
#
|
|
28
|
+
# fetch = HttpResource::SafeFetch.new(user_agent: "fetch/1.0")
|
|
29
|
+
# fetch.get("https://www.example.com/page", max_bytes: 3_000_000, deadline: 12).body # => binary String
|
|
30
|
+
class SafeFetch
|
|
31
|
+
DEFAULT_MAX_BYTES = 10_485_760
|
|
32
|
+
DEFAULT_DEADLINE = 60
|
|
33
|
+
RESOLVE_TIMEOUT = 4
|
|
34
|
+
HEAD_BYTES = 65_536
|
|
35
|
+
PLAIN_HTTP = %i[refuse upgrade allow].freeze
|
|
36
|
+
|
|
37
|
+
# No answer in time (reason :timeout). Read before NETWORK_ERRORS, which hold their parents.
|
|
38
|
+
TIMEOUT_ERRORS = [Timeout::Error, IO::TimeoutError, Errno::ETIMEDOUT].freeze
|
|
39
|
+
# Every other failure on the wire (reason :network; an early end of a body is :truncated, WireReason).
|
|
40
|
+
NETWORK_ERRORS = [SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError,
|
|
41
|
+
Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Zlib::Error].freeze
|
|
42
|
+
|
|
43
|
+
# host -> every address String it resolves to, as a connection would ask.
|
|
44
|
+
SYSTEM_RESOLVER = lambda do |host|
|
|
45
|
+
Addrinfo.getaddrinfo(host, nil, nil, :STREAM, nil, 0, timeout: RESOLVE_TIMEOUT).map(&:ip_address).uniq
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# The fetch's own refusal: #reason is one of REASONS; #status the HTTP code of the one answer that
|
|
49
|
+
# ended the fetch, else nil.
|
|
50
|
+
class Error < HttpResource::Error
|
|
51
|
+
REASONS = %i[address scheme redirect_off_allow status type too_large truncated timeout network].freeze
|
|
52
|
+
|
|
53
|
+
attr_reader :reason, :status
|
|
54
|
+
|
|
55
|
+
def initialize(message = nil, reason:, status: nil)
|
|
56
|
+
@reason = reason
|
|
57
|
+
@status = status
|
|
58
|
+
super(message)
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# A line before or inside a body that reaches HEAD_BYTES before its end, or the lines before a body
|
|
63
|
+
# past HEAD_BYTES in all.
|
|
64
|
+
class HeadTooLarge < Error
|
|
65
|
+
def initialize(message)
|
|
66
|
+
super(message, reason: :too_large)
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# inside_hosts: host names on the app's private network, each a name by Host.name? (lower case, no
|
|
71
|
+
# trailing dot, never an address in any spelling), the only hosts whose RFC 1918 addresses may be
|
|
72
|
+
# connected to; resolver: a callable host -> Array of address Strings.
|
|
73
|
+
def initialize(inside_hosts: [], user_agent: nil, max_redirects: 3, resolver: SYSTEM_RESOLVER)
|
|
74
|
+
Forms.check!(inside_hosts:, user_agent:, max_redirects:, resolver:)
|
|
75
|
+
@inside_hosts = inside_hosts.dup.freeze
|
|
76
|
+
@user_agent = user_agent
|
|
77
|
+
@max_redirects = max_redirects
|
|
78
|
+
@resolver = resolver
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# The Net::HTTPSuccess for +url+, its body a binary String, or a SafeFetch::Error.
|
|
82
|
+
def get(url, allow: nil, headers: {}, plain_http: :refuse, follow_redirects: true, accept_type: nil,
|
|
83
|
+
max_bytes: DEFAULT_MAX_BYTES, deadline: DEFAULT_DEADLINE, open_timeout: 10, read_timeout: 10)
|
|
84
|
+
call = Call.for(allow:, headers:, plain_http:, follow_redirects:, accept_type:, max_bytes:, deadline:,
|
|
85
|
+
open_timeout:, read_timeout:)
|
|
86
|
+
uri = first_uri(url, plain_http)
|
|
87
|
+
call = call.with(asked: uri)
|
|
88
|
+
0.step do |hops|
|
|
89
|
+
response = exchange(uri, call)
|
|
90
|
+
return response if response.is_a?(Net::HTTPSuccess)
|
|
91
|
+
if hops == @max_redirects
|
|
92
|
+
raise Error.new("too many redirects (more than #{@max_redirects}) for #{call.asked}",
|
|
93
|
+
reason: :status)
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
uri = next_uri(uri, response, call)
|
|
97
|
+
end
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# One request to +url+: the URI its 3xx names, after the scheme rule and allow, asked nothing itself.
|
|
101
|
+
def redirect_target(url, allow: nil, headers: {}, plain_http: :refuse, max_bytes: DEFAULT_MAX_BYTES,
|
|
102
|
+
deadline: DEFAULT_DEADLINE, open_timeout: 10, read_timeout: 10)
|
|
103
|
+
call = Call.for(allow:, headers:, plain_http:, follow_redirects: true, accept_type: nil, max_bytes:,
|
|
104
|
+
deadline:, open_timeout:, read_timeout:, target: true)
|
|
105
|
+
uri = first_uri(url, plain_http)
|
|
106
|
+
call = call.with(asked: uri)
|
|
107
|
+
next_uri(uri, exchange(uri, call), call)
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
private
|
|
111
|
+
|
|
112
|
+
def first_uri(url, plain_http)
|
|
113
|
+
scheme(parse(url, hop: false), plain_http, hop: false)
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def next_uri(uri, response, call)
|
|
117
|
+
location = response["Location"].to_s
|
|
118
|
+
if location.strip.empty?
|
|
119
|
+
raise Error.new("redirect without Location from #{named(uri, call)}", reason: :status)
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
target = scheme(parse(join(uri, location, call), hop: true), call.plain_http, hop: true)
|
|
123
|
+
return target if call.allow.nil? || call.allow.call(target.to_s)
|
|
124
|
+
|
|
125
|
+
raise Error.new("redirect target not allowed: #{Bounds.cut(target)}", reason: :redirect_off_allow)
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# A Location that could not be read is not repeated, nor is the parser's message, which repeats it,
|
|
129
|
+
# not even as the error's cause: either can hold credentials. The message names the URL that answered.
|
|
130
|
+
def join(uri, location, call)
|
|
131
|
+
URI.join(uri.to_s, self.class.wire_url(location)).to_s
|
|
132
|
+
rescue URI::Error
|
|
133
|
+
raise Error.new("invalid redirect Location from #{named(uri, call)}", reason: :redirect_off_allow),
|
|
134
|
+
cause: nil
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
# The URL as a URI to ask: http(s) with a host and no userinfo, refused unsent otherwise (reason :address
|
|
138
|
+
# for the first URL, :redirect_off_allow for a hop). It is read as bytes, so text outside ASCII in any
|
|
139
|
+
# encoding is a URL that could not be read, never an encoding error. Userinfo is refused first, and a
|
|
140
|
+
# URL that could not be read is not repeated, nor the parser's message (not even as the error's cause),
|
|
141
|
+
# so no refusal, and never allow, is handed credentials.
|
|
142
|
+
def parse(url, hop:)
|
|
143
|
+
reason = hop ? :redirect_off_allow : :address
|
|
144
|
+
uri = URI.parse(url.to_s.b.strip)
|
|
145
|
+
raise Error.new("refused: the URL has userinfo", reason:) if uri.userinfo
|
|
146
|
+
return uri if uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
|
|
147
|
+
|
|
148
|
+
raise Error.new("not an http(s) URL: #{hop ? Bounds.cut(url) : uri}", reason:)
|
|
149
|
+
rescue URI::Error
|
|
150
|
+
raise Error.new("invalid URL", reason:), cause: nil
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
def scheme(uri, plain_http, hop:)
|
|
154
|
+
return uri if uri.scheme == "https" || plain_http == :allow
|
|
155
|
+
return URI.parse(uri.to_s.sub(/\Ahttp:/, "https:")) if plain_http == :upgrade
|
|
156
|
+
raise Error.new("plain http is not allowed: #{uri}", reason: :scheme) unless hop
|
|
157
|
+
|
|
158
|
+
raise Error.new("redirect to plain http is not allowed: #{Bounds.cut(uri)}",
|
|
159
|
+
reason: :redirect_off_allow)
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
# How a message names +uri+: the URI the call asked first whole, as it was asked; a hop's, which the
|
|
163
|
+
# far end wrote, cut.
|
|
164
|
+
def named(uri, call)
|
|
165
|
+
uri.equal?(call.asked) ? uri.to_s : Bounds.cut(uri)
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
# One request, its own connection, to the checked address of +uri+'s host, wholly under what is left
|
|
169
|
+
# of the deadline; returns the answer, a 2xx or a 3xx, its body read.
|
|
170
|
+
def exchange(uri, call)
|
|
171
|
+
request = Net::HTTP::Get.new(uri.request_uri, call.headers)
|
|
172
|
+
request["User-Agent"] = @user_agent if @user_agent
|
|
173
|
+
http = connection_to(uri, checked_address(uri, call), call)
|
|
174
|
+
Timeout.timeout(call.left!) { http.request(request) { |response| take(response, uri, call) } }
|
|
175
|
+
rescue *TIMEOUT_ERRORS, *NETWORK_ERRORS => e
|
|
176
|
+
raise Error.new("#{e.class} fetching #{named(uri, call)}: #{Bounds.cut(e.message)}",
|
|
177
|
+
reason: WireReason.of(e, body: false))
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
def connection_to(uri, address, call)
|
|
181
|
+
left = call.left!
|
|
182
|
+
http = self.class.connection(uri.hostname, uri.port)
|
|
183
|
+
http.use_ssl = uri.scheme == "https"
|
|
184
|
+
http.ipaddr = address
|
|
185
|
+
http.open_timeout = [call.open_timeout, left].min
|
|
186
|
+
http.read_timeout = [call.read_timeout, left].min
|
|
187
|
+
http.max_retries = 0
|
|
188
|
+
http
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
# An IP literal is its own address; any other host is looked up once. Refused unless every address is
|
|
192
|
+
# connectable for this hop's own host, which is inside only when its compared form, taken from the
|
|
193
|
+
# host as the URL writes it (brackets kept, so a bracketed host is never a name), is a host name
|
|
194
|
+
# (Host.name?, the test every list entry passed) equal to an entry. An address is read one way, a
|
|
195
|
+
# literal's and a resolver's answer alike (PublicAddress.address). The connection is handed the
|
|
196
|
+
# checked address in its own text, never the resolver's string (a prefix or brackets dropped).
|
|
197
|
+
def checked_address(uri, call)
|
|
198
|
+
form = Host.form(uri.host)
|
|
199
|
+
literal = PublicAddress.address(form)
|
|
200
|
+
ips = literal ? [literal] : lookup(uri.hostname, call.left!).map { PublicAddress.address(_1) }
|
|
201
|
+
raise Error.new("no address for the host", reason: :network) if ips.empty?
|
|
202
|
+
|
|
203
|
+
inside = Host.name?(form) && @inside_hosts.include?(form)
|
|
204
|
+
unless ips.all? { _1 && PublicAddress.connectable?(_1, inside:) }
|
|
205
|
+
raise Error.new("refused: the host has an address that is not public", reason: :address)
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
ips[ips.index(&:ipv4?) || 0].to_s
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
def lookup(host, left)
|
|
212
|
+
Timeout.timeout([RESOLVE_TIMEOUT, left].min) { Array(@resolver.call(host)).map(&:to_s).uniq }
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
# Inside the request: a status this call will not use is refused before its body is read; a 2xx's
|
|
216
|
+
# declared length, then its type; then the body, a redirect's too, under the cap.
|
|
217
|
+
def take(response, uri, call)
|
|
218
|
+
case response
|
|
219
|
+
when Net::HTTPSuccess then success!(response, uri, call)
|
|
220
|
+
when Net::HTTPRedirection then raise status_error(response, uri, call) unless call.follow_redirects
|
|
221
|
+
else raise status_error(response, uri, call)
|
|
222
|
+
end
|
|
223
|
+
response.body = self.class.read_body(response, max_bytes: call.max_bytes)
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
def success!(response, uri, call)
|
|
227
|
+
if call.target
|
|
228
|
+
raise Error.new("no redirect (HTTP #{response.code}) for #{named(uri, call)}", reason: :status)
|
|
229
|
+
end
|
|
230
|
+
|
|
231
|
+
Bounds.declared!(response, call.max_bytes)
|
|
232
|
+
return unless call.accept_type
|
|
233
|
+
|
|
234
|
+
type = self.class.media_type(response)
|
|
235
|
+
return if call.accept_type.call(type)
|
|
236
|
+
|
|
237
|
+
raise Error.new("content-type #{Bounds.cut(type || '(none)')} was not accepted", reason: :type)
|
|
238
|
+
end
|
|
239
|
+
|
|
240
|
+
def status_error(response, uri, call)
|
|
241
|
+
code = Integer(response.code.to_s, 10, exception: false)
|
|
242
|
+
Error.new("HTTP #{response.code} for #{named(uri, call)}", reason: :status, status: code)
|
|
243
|
+
end
|
|
244
|
+
end
|
|
245
|
+
end
|
|
246
|
+
|
|
247
|
+
require "http_resource/safe_fetch/call"
|
|
248
|
+
require "http_resource/safe_fetch/wire"
|