http_resource 0.3.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 316f4111914f2024aa5e42083d0305a68f344a3bb5c0beb18b84d5e61228186a
4
- data.tar.gz: 8851400609748c96c0380c5b0c9da199e41b988837bf79971dd5eba9196c52af
3
+ metadata.gz: 54121171e391d5c93c206858ee6f2f6e6436ed46bcec2f3c53c68f5afc42cd8a
4
+ data.tar.gz: b172e10720457ff5f4e9d0ad61c63f473dc23c548e28364a95ca4c9a0628d7a6
5
5
  SHA512:
6
- metadata.gz: 36d4d4964057b673e712eebecd63594fbc222c3a6fe604f853f00c2e3af595ae55417a7701df6b6b6214e3b9ab389e083c2641a38b10aadd0b8f3e6fbaed9ea2
7
- data.tar.gz: 9905e5472ea9ec3002ad82f4893e28b6a63f9672389f5a1c767da1e25f57b54cece01d797043488628c3bbeed173f8f40d982774818ceb2101bd917dfbfed27a
6
+ metadata.gz: cfce40b735fd7044d8e82a891f5c0de4e805270a98dc3b411a4ed7e25c66ffbb9705eb5142b69f2a39cb08dbb1a4ec7b74a0eb09029f1a240a967fa49a7792f0
7
+ data.tar.gz: 57f180da78e05ed7c28a1337b3d77e9c1f68a00d1a57d93612435ee06c6de146aead46b0a88d76ded3932af4edc3cd6aa378354d70dde665eb3cc60eabdbe3b7
data/README.md CHANGED
@@ -8,8 +8,8 @@ with a **typed error hierarchy**, Rails-style **bang/non-bang resources**,
8
8
  **pluggable auth**, **per-call timeouts**, and **escape-safe URL building** so
9
9
  untrusted path segments can never escape the protocol.
10
10
 
11
- It is the generic core extracted from Skiftet's `mejla_api_client`: a small set
12
- of proven patterns you would otherwise hand-roll (and get subtly wrong) in every
11
+ It is the generic core extracted from an in-house API client: a small set of
12
+ proven patterns you would otherwise hand-roll (and get subtly wrong) in every
13
13
  service-to-service client.
14
14
 
15
15
  ## Why
@@ -184,9 +184,9 @@ MyGem::Simulation::Backend.register("api/contacts", ContactsHandler)
184
184
 
185
185
  # 2. Build a simulated client — or inject a prepared backend instance.
186
186
  client = HttpResource::Client.new(base_url: "https://irrelevant.test", simulation: true)
187
- client.simulation.seed(contacts: [{ id: 1, email: "a@b.se" }])
187
+ client.simulation.seed(contacts: [{ id: 1, email: "anna@example.com" }])
188
188
 
189
- client.get(["api", "contacts", 1]) # => { "id" => 1, "email" => "a@b.se" } — no network
189
+ client.get(["api", "contacts", 1]) # => { "id" => 1, "email" => "anna@example.com" } — no network
190
190
  client.get(["api", "contacts", 9]) # => raises NotFoundError (from your handler)
191
191
 
192
192
  # 3. Inject failures to exercise error paths.
@@ -221,6 +221,196 @@ The pieces:
221
221
  `simulation: backend_instance` injects a prepared one. `client.simulation`
222
222
  returns the backend (`nil` in real mode).
223
223
 
224
+ ## ETag conditional caching (opt-in)
225
+
226
+ Transparent revalidation: inject a cache store and `get` stays `get` — no new
227
+ method, no ETag in any signature. With a store attached, a GET sends
228
+ `If-None-Match` from the stored ETag; a **304 returns the cached value** (the
229
+ caller never sees the 304 or the ETag), a 200 stores the new `{etag, value}`.
230
+ This is pure *revalidation*, not a freshness cache: every call still hits the
231
+ network; the win is that a 304 carries no body. Without `cache:`, behavior is
232
+ byte-for-byte unchanged.
233
+
234
+ ```ruby
235
+ class MyEtagStore
236
+ Entry = Struct.new(:etag, :value)
237
+ def initialize = (@h = {}; @m = Mutex.new)
238
+ def read(key) = @m.synchronize { @h[key] }
239
+ def write(key, etag, value) = @m.synchronize { @h[key] = Entry.new(etag, value) }
240
+ end
241
+
242
+ client = HttpResource::Client.new(
243
+ base_url: "https://api.example.org",
244
+ auth: HttpResource::Auth.bearer(token),
245
+ cache: MyEtagStore.new,
246
+ logger: Rails.logger # optional: receives cache-write warnings
247
+ )
248
+
249
+ client.get(["api", "permissions"]) # 200 -> stored; later calls: 304 -> cached value
250
+ ```
251
+
252
+ The store is duck-typed (like auth strategies): `read(key)` returns `nil` or an
253
+ entry responding to `.etag`/`.value`; `write(key, etag, value)` is called only
254
+ on a 2xx GET carrying an ETag. Notes:
255
+
256
+ - **Frozen results** — a cached value is deep-frozen once at store time; the
257
+ caller gets the same frozen object (mutation raises `FrozenError` instead of
258
+ silently poisoning the cache — `dup` to mutate).
259
+ - **Identity-safe keys** — keys are namespaced by a SHA-256 fingerprint of the
260
+ headers the auth strategy sets, so one store shared across clients with
261
+ different credentials can never leak a response across identities. The raw
262
+ credential never enters a key.
263
+ - **Write failures warn, never fail** — a store-write error on a successful
264
+ response logs a warning (`logger:`, falling back to `Kernel#warn`) and
265
+ returns the value uncached. Store *reads* stay unguarded on purpose.
266
+ - **GET-only**; errors are untouched (a failure never clobbers a cached
267
+ value); weak ETags (`W/"…"`) round-trip verbatim; an *unsolicited* 304
268
+ still raises `RedirectError` exactly as before.
269
+ - **Inert in simulation** — with `simulation:`, the backend replaces the
270
+ transport before any conditional logic runs; the store is never touched.
271
+ - Also wireable via `HttpResource.configure` (`c.cache = …`, `c.logger = …`).
272
+
273
+ ## Safe fetch of untrusted URLs (opt-in)
274
+
275
+ For a URL someone else gave you (a pasted link, an address found on another page,
276
+ a user's webhook target), `HttpResource::SafeFetch` GETs it under one strict
277
+ rule, and `HttpResource::PublicAddress` is that address rule alone (for a link
278
+ checker or a sender that makes its own request). Both are opt-in beside the
279
+ unchanged `Client`, stdlib only, and load only when named (0.4.0 and later).
280
+
281
+ ```ruby
282
+ fetch = HttpResource::SafeFetch.new(user_agent: "fetch/1.0")
283
+ response = fetch.get("https://www.example.com/page", max_bytes: 3_000_000, deadline: 12)
284
+ response.body # => a binary String; response is the Net::HTTPSuccess
285
+ fetch.redirect_target("https://www.example.org/s/1") # => the URI its one 3xx names, not asked itself
286
+
287
+ HttpResource::PublicAddress.public?("93.184.216.34") # => true
288
+ HttpResource::PublicAddress.connectable?("172.20.1.2", inside: true) # => true
289
+ HttpResource::PublicAddress.address("127.0.0.1/0") # => nil, a range is no address
290
+ ```
291
+
292
+ **The address rule, on every hop.** Before each request, the first and every
293
+ redirect, the host is resolved (an IP literal is its own address; a decimal or
294
+ hex spelling is looked up) and the request is refused, unsent, unless EVERY
295
+ address is public: an allow rule, so anything not shown public is refused.
296
+ `PublicAddress.address(value)` is the reading `public?` and `connectable?` judge
297
+ by: an `IPAddr` when `value` (an `IPAddr` or a String) is one address, nil when
298
+ it is none. A range (`127.0.0.1/0`; a full prefix is one address), a String
299
+ that is not ASCII only, a host name and a decimal or hex spelling are none, and
300
+ for them `public?` and `connectable?` answer false.
301
+
302
+ | Not public | RFC |
303
+ |---|---|
304
+ | 0.0.0.0/8; 127.0.0.0/8 | 1122 |
305
+ | 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 (see inside hosts) | 1918 |
306
+ | 100.64.0.0/10 | 6598 |
307
+ | 169.254.0.0/16, the cloud metadata address 169.254.169.254 among it | 3927 |
308
+ | 192.0.0.0/24 | 6890 |
309
+ | 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24 | 5737 |
310
+ | 192.88.99.0/24 | 3068, 7526 |
311
+ | 198.18.0.0/15 | 2544 |
312
+ | 224.0.0.0/4; 240.0.0.0/4 with 255.255.255.255 | 5771; 1112, 919 |
313
+ | all IPv6 outside 2000::/3 | 4291 §2.4 |
314
+ | 2001::/23 (Teredo, benchmarking, ORCHIDv2) | 2928, 4380, 5180, 7343 |
315
+ | 2001:db8::/32; 3fff::/20 | 3849; 9637 |
316
+ | 2002::/16, 6to4 whole | 3056 |
317
+ | ::ffff:0:0/96 and 64:ff9b::/96: judged by the IPv4 address they carry | 4291 §2.5.5.2, 6052 |
318
+
319
+ **Inside hosts.** `inside_hosts: ["intranet.example.org"]` names the hosts on
320
+ your private network, each a name in exactly this form: lower-case labels of
321
+ a-z, 0-9 and hyphen joined by dots, at most 253 characters, no label empty, over
322
+ 63 or with a hyphen at an end, the last beginning with a letter (`intranet` is
323
+ one). Anything else (capitals, a trailing dot, an address in any spelling such
324
+ as `10.0.5` or `::1`) is an `ArgumentError` when the fetch is built. A request
325
+ whose host, lower-cased with one trailing dot dropped, is such a name equal to an
326
+ entry may also connect to an RFC 1918 IPv4 address; to no other address that is
327
+ not public, nor for a subdomain. Anyone who can hand your app a URL can reach a
328
+ listed host, directly or by a redirect: list only hosts that may be read so.
329
+
330
+ **The connection** goes to the address that was checked (the first IPv4 one,
331
+ else the first; one lookup per hop), never through an environment proxy
332
+ (`https_proxy` is ignored); TLS verifies the URL's host by Net::HTTP's defaults,
333
+ which the gem never changes. Each hop is its own connection, no retry; no cookie
334
+ or other answer header reaches the next hop. Every hop, one to another host too,
335
+ is sent the call's `headers:` and `user_agent` (it replaces theirs), so a secret
336
+ header belongs only in a call with `follow_redirects: false` or an `allow` that
337
+ keeps every hop on that host. The gem adds no header to Net::HTTP's defaults.
338
+
339
+ **Scheme and redirects.** https only: `plain_http: :refuse` (the default) refuses
340
+ `http:`, `:upgrade` asks the same URL over https (its port kept), `:allow` asks
341
+ it as written; the same holds for every redirect target. The port is the URL's
342
+ own (a Location's, an inside host's too): check it first, and in `allow`, if only
343
+ 443 will do. A URL with userinfo (`https://user:pw@www.example.com/`) is refused unsent, first or hop,
344
+ so `allow` never sees one. The first URL must be ASCII: it is read as written,
345
+ and one with a byte outside ASCII is refused unsent. `SafeFetch.wire_url(url)`
346
+ makes a pasted link so: it percent-encodes each byte outside ASCII
347
+ (`https://www.example.com/café` becomes `https://www.example.com/caf%C3%A9`) and
348
+ repairs nothing else (a raw space is still refused), and the fetch puts every
349
+ Location through it. A host outside ASCII must arrive in its xn-- form
350
+ (`xn--bcher-kva.example.com`, not `bücher.example.com`); `wire_url` makes none.
351
+ At most `max_redirects` hops (default 3, 1-10). `allow:` is asked of
352
+ every hop's target (a String), never of the first URL; false refuses it unrequested, and
353
+ what it raises reaches you as it is. `follow_redirects: false` makes a 3xx an error.
354
+
355
+ **Bounds, always on.** `max_bytes:` (default 10 MiB) counts body bytes as read,
356
+ after inflation: a Content-Length over it is refused before a body byte is read
357
+ and a longer body is cut as it arrives. `deadline:` (default 60 s) is wall-clock
358
+ over all hops: every lookup (at most `RESOLVE_TIMEOUT`, 4 s), connect, handshake,
359
+ head and body runs under `Timeout` for what is left. `open_timeout:` (the
360
+ connect) and `read_timeout:` (each read) default to 10 s, cut to what is left.
361
+ The head holds `HEAD_BYTES` (64 KiB) in all, 1xx heads included, and no line (a
362
+ chunk size, a trailer) may reach it before its end. The three times are finite
363
+ positive numbers and `max_bytes:` a positive Integer, with no upper limit; `nil`
364
+ or anything else is an `ArgumentError`, as is any keyword off its form.
365
+
366
+ **Type.** `accept_type: ->(type) { type.start_with?("image/") }` is asked of a
367
+ 2xx with the lower-cased type/subtype (or nil), after its declared length and
368
+ before its body; falsy refuses it with the body unread. What it raises reaches
369
+ you as it is, unless its class is in one of the two lists below.
370
+
371
+ **Errors.** Every refusal is a `HttpResource::SafeFetch::Error` (an
372
+ `HttpResource::Error`) with `#reason`, and `#status` for the answer that ended it:
373
+
374
+ | `reason` | When |
375
+ |---|---|
376
+ | `:address` | not an http(s) URL with a host; a URL that is not ASCII (a pasted link goes through `wire_url` first; a host outside ASCII arrives in its xn-- form); a URL with userinfo; an address not allowed |
377
+ | `:scheme` | plain http under `:refuse` |
378
+ | `:redirect_off_allow` | a hop's Location unreadable, not http(s), with userinfo, plain http under `:refuse`, or not allowed |
379
+ | `:status` | an answer neither 2xx nor 3xx, or a 3xx with `follow_redirects: false` (`status` its code); a 3xx without Location, too many redirects, `redirect_target` answered 2xx (`status` nil) |
380
+ | `:type` | `accept_type` said no |
381
+ | `:too_large` | over `max_bytes`; `SafeFetch::HeadTooLarge` for the head |
382
+ | `:truncated` | the stream ended before the body did: short of its Content-Length, a chunked body before its last chunk, or over TLS a connection cut without its closing message (close_notify) while the body is read, a body the close would end among them; whatever the transport raised for it (`EOFError`, or OpenSSL's "unexpected eof while reading"); no part of it is returned, by `get` or `read_body` |
383
+ | `:timeout` | the deadline, or one of `TIMEOUT_ERRORS` |
384
+ | `:network` | no address, or any other of `NETWORK_ERRORS` (a reset, bad TLS, a broken answer or compressed stream, a connection that ended before an answer) |
385
+
386
+ A message carries the URL as it was asked, query string included (a URL that
387
+ could not be read is not repeated, and a failure while the body is read names
388
+ what failed, not the URL); each piece the far end wrote is cut to 200
389
+ bytes, so a message is valid UTF-8. A wire failure's `cause` is its own, uncut.
390
+
391
+ **Testing your code.** Hand in `resolver: ->(host) { ["93.184.216.34"] }` (the
392
+ default, `SYSTEM_RESOLVER`, asks `Addrinfo.getaddrinfo`), and stub
393
+ `PublicAddress.connectable?` or `SafeFetch.monotonic_now`: the fetch asks both
394
+ through those singleton methods. These steer the address check (and
395
+ `monotonic_now` the clock), never the wire: the request still goes to the address
396
+ the resolver answered, so a suite stubs the wire too, one of two ways. A stub of
397
+ Net::HTTP such as WebMock's (`stub_request(:get, "https://www.example.com/page")`)
398
+ matches the URL's host whatever the resolver answers, and opens no connection. Or
399
+ the suite runs its own server on 127.0.0.1, the resolver answers `["127.0.0.1"]`,
400
+ `connectable?` is stubbed to allow it, and the URL names the server's port (plain
401
+ http with `plain_http: :allow`, or TLS the suite trusts). The gem's own suite does
402
+ both and reaches no other machine.
403
+
404
+ **Your own API client's requests.** The wire pieces are public:
405
+ `SafeFetch.connection(host, port)` (a `Net::HTTP` with no proxy and the head
406
+ bound; you set TLS, `ipaddr`, timeouts, retries), `SafeFetch.read_body(response,
407
+ max_bytes:, ends_at:)` (inside `request`'s block; what the wire raises while it
408
+ reads is a `SafeFetch::Error` by the table above), `wire_url`, `media_type`,
409
+ `monotonic_now`, and the lists `TIMEOUT_ERRORS` and `NETWORK_ERRORS`.
410
+
411
+ **It does not** send anything but GET, keep cookies, retry, follow more than 10
412
+ redirects, take a proxy, or offer a switch to allow every address.
413
+
224
414
  ## Error hierarchy
225
415
 
226
416
  Every failure is an `HttpResource::ApiError` carrying `#status` (an `Integer`, or
@@ -309,6 +499,22 @@ adversarial spec (`spec/escape_safety_spec.rb`).
309
499
 
310
500
  ## Changelog
311
501
 
502
+ ### 0.4.0
503
+
504
+ - Add opt-in **ETag conditional caching**: a duck-typed `cache:` store on
505
+ `Client` (+ `logger:` for cache-write warnings, both also on
506
+ `HttpResource.configure`). GETs transparently revalidate with
507
+ `If-None-Match`; a 304 returns the cached value invisibly. Cached values are
508
+ deep-frozen; keys are namespaced per auth identity. No `cache:` → behavior
509
+ unchanged.
510
+ - Add opt-in **safe fetch of untrusted URLs**: `HttpResource::SafeFetch` GETs a
511
+ URL someone else gave you under one address rule, checked before every hop
512
+ (https only by default, bounded size and time, every refusal a
513
+ `SafeFetch::Error` with `#reason`), and `HttpResource::PublicAddress` is that
514
+ address rule alone. The wire pieces (`SafeFetch.connection`,
515
+ `SafeFetch.read_body`, the error lists) are public for your own API client's
516
+ requests. Stdlib only, loaded only when named; `Client` is unchanged.
517
+
312
518
  ### 0.3.0
313
519
 
314
520
  - Add opt-in **simulation mode**: `HttpResource::Simulation::Backend`/`Store` +
@@ -43,9 +43,13 @@ module HttpResource
43
43
  Simulation::Backend
44
44
  end
45
45
 
46
+ # cache: opts into transparent ETag revalidation on GET (see
47
+ # ConditionalCache for the store contract); logger: receives cache-write
48
+ # warnings (falls back to Kernel#warn). Inert in simulation mode — the
49
+ # backend replaces the transport before any conditional logic runs.
46
50
  def initialize(base_url:, auth: nil, username: nil, password: nil,
47
51
  open_timeout: DEFAULT_OPEN_TIMEOUT, read_timeout: DEFAULT_READ_TIMEOUT,
48
- simulation: nil)
52
+ simulation: nil, cache: nil, logger: nil)
49
53
  raise ConfigurationError, "base_url is required" if blank?(base_url)
50
54
 
51
55
  @base_url = base_url.to_s.sub(%r{/+\z}, "")
@@ -53,6 +57,8 @@ module HttpResource
53
57
  @open_timeout = open_timeout
54
58
  @read_timeout = read_timeout
55
59
  @simulation = setup_simulation(simulation)
60
+ @conditional_cache = cache && ConditionalCache.new(store: cache, auth: @auth, base_url: @base_url,
61
+ logger:)
56
62
  end
57
63
 
58
64
  # Low-level REST verbs. `path` may be a String ("/api/foo") sent verbatim, or
@@ -102,10 +108,15 @@ module HttpResource
102
108
  # deterministic caller bug, and must NOT be masked as a retryable
103
109
  # TransportError — that would have a worker retry it forever.
104
110
  uri = build_uri(path, params)
105
- req = build_request(method, uri, body, form)
111
+ # GET-only: with a cache attached, read the store ONCE into a carrier
112
+ # (deterministic side, like uri/req — a broken store read surfaces
113
+ # honestly). handle() never re-reads, so an eviction between request
114
+ # and response can't turn a solicited 304 into a RedirectError.
115
+ cond = @conditional_cache && method == :get ? @conditional_cache.conditional_for(uri) : nil
116
+ req = build_request(method, uri, body, form, cond)
106
117
  connection = http(uri, open_timeout:, read_timeout:)
107
118
  begin
108
- handle(connection.request(req))
119
+ handle(connection.request(req), cond)
109
120
  rescue ApiError
110
121
  raise
111
122
  rescue Timeout::Error, Errno::ETIMEDOUT => e # Net::Open/ReadTimeout subclass Timeout::Error
@@ -149,7 +160,7 @@ module HttpResource
149
160
  ERB::Util.url_encode(str)
150
161
  end
151
162
 
152
- def build_request(method, uri, body, form = nil)
163
+ def build_request(method, uri, body, form = nil, cond = nil)
153
164
  klass = {
154
165
  get: Net::HTTP::Get, post: Net::HTTP::Post, put: Net::HTTP::Put,
155
166
  patch: Net::HTTP::Patch, delete: Net::HTTP::Delete
@@ -157,6 +168,9 @@ module HttpResource
157
168
  request = klass.new(uri)
158
169
  @auth&.apply(request)
159
170
  request["Accept"] = "application/json"
171
+ # The stored validator is replayed VERBATIM (quotes, any W/ prefix):
172
+ # RFC 7232 gives If-None-Match weak comparison; the server owns the match.
173
+ request["If-None-Match"] = cond.etag if cond&.etag
160
174
  apply_body(request, body, form)
161
175
  request
162
176
  end
@@ -185,12 +199,23 @@ module HttpResource
185
199
  http
186
200
  end
187
201
 
188
- def handle(response)
202
+ def handle(response, cond = nil)
189
203
  status = response.code.to_i
204
+ # Solicited 304: return the value carried from request time — the caller
205
+ # never sees the 304 or the ETag. MUST sit above the body read (a 304
206
+ # has no body; reading it can raise) and above for_status (which maps
207
+ # 3xx to RedirectError). An UNSOLICITED 304 (no If-None-Match sent)
208
+ # still falls through and raises, exactly as without a cache.
209
+ return @conditional_cache.freeze_value(cond.value) if cond&.etag && status == 304
210
+
190
211
  body = response.body.to_s
191
212
  parsed = body.empty? ? nil : parse_json(body)
192
- return parsed if status.between?(200, 299)
213
+ if status.between?(200, 299)
214
+ parsed = @conditional_cache.store_response(cond, response, parsed) if cond
215
+ return parsed
216
+ end
193
217
 
218
+ # A failure never touches the store: a cached value survives an outage.
194
219
  raise ApiError.for_status("HTTP request returned #{status}", status:, body:)
195
220
  end
196
221
 
@@ -0,0 +1,135 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "openssl"
6
+
7
+ module HttpResource
8
+ # Transparent ETag revalidation for a Client (opt-in via the cache: kwarg).
9
+ # Pure REVALIDATION, not a freshness cache: every GET still hits the network;
10
+ # the win is that a 304 carries no body — the caller gets the cached value
11
+ # back and never sees the 304, the ETag, or any new method.
12
+ #
13
+ # The injected store is duck-typed (like Auth strategies):
14
+ #
15
+ # read(key) -> entry | nil # entry responds to .etag/.value
16
+ # write(key, etag, value) -> (ignored) # called only on a 2xx GET with an ETag
17
+ #
18
+ # The Client reads `.etag`/`.value` — never hash keys — so a store may hand
19
+ # back a Struct, an OpenStruct, or a deserialized object. The OUTER nil from
20
+ # read is the only "missing" signal; a stored value may itself be nil (a
21
+ # cached 204). Store thread-safety is the store's responsibility.
22
+ class ConditionalCache
23
+ # Read ONCE per GET, at request time, and threaded through the request:
24
+ # the 304 path returns the carried value and never re-reads the store, so
25
+ # an eviction between request and response can't break revalidation.
26
+ Conditional = Struct.new(:key, :etag, :value)
27
+
28
+ def initialize(store:, auth:, base_url:, logger: nil)
29
+ @store = store
30
+ @auth = auth
31
+ @base_url = base_url
32
+ @logger = logger
33
+ end
34
+
35
+ # A carrier for EVERY GET — etag/value are nil on a miss (or an entry with
36
+ # a blank etag), which means: send a plain GET, but still store the 200.
37
+ def conditional_for(uri)
38
+ key = cache_key(uri)
39
+ entry = @store.read(key)
40
+ Conditional.new(key, presence(entry&.etag), entry&.value)
41
+ end
42
+
43
+ # Store a fresh 2xx GET body when the response carries a validator. The
44
+ # value is deep-frozen FIRST (parsed JSON is only Hash/Array/String/
45
+ # Numeric/bool/nil, so the freeze is total) — both the store and the
46
+ # caller get the same frozen object, so a caller mutation can't poison
47
+ # the cache: it raises FrozenError instead. Returns the value to hand the
48
+ # caller (frozen when cached, untouched when there was no ETag).
49
+ def store_response(conditional, response, parsed)
50
+ etag = presence(response["ETag"]&.strip)
51
+ return parsed unless etag
52
+
53
+ frozen = deep_freeze(parsed)
54
+ begin
55
+ @store.write(conditional.key, etag, frozen)
56
+ rescue StandardError => e
57
+ # A cache-write failure must not fail a SUCCESSFUL response — warn and
58
+ # return the value uncached. Reads stay unguarded: a broken read is a
59
+ # deterministic bug that should surface, not hide.
60
+ warn_failure(e)
61
+ end
62
+ frozen
63
+ end
64
+
65
+ # Public for the Client's 304 path: an in-memory store hands back the
66
+ # already-frozen object (no-op), but a SERIALIZING store (Rails.cache,
67
+ # Redis…) returns fresh unfrozen copies — freeze them too, so the
68
+ # "results are read-only" guarantee is uniform across 200 and 304.
69
+ def freeze_value(value)
70
+ deep_freeze(value)
71
+ end
72
+
73
+ private
74
+
75
+ # NUL separator: cannot appear in a URI or a percent-encoded segment, so
76
+ # distinct tuples can never alias. request_uri = path + "?" + query, so
77
+ # different params are different entries (different representations).
78
+ def cache_key(uri)
79
+ [identity, uri.scheme, uri.host, uri.port, uri.request_uri].join("\0")
80
+ end
81
+
82
+ # Namespace the key by WHO is asking, so one store shared across clients
83
+ # with different credentials can never leak a representation across
84
+ # identities. Fingerprint = SHA-256 of ONLY the headers the auth strategy
85
+ # sets/changes (the delta against an un-applied probe — Net::HTTP's
86
+ # defaults like User-Agent are excluded, so a persistent store survives a
87
+ # Ruby upgrade). Uses the existing #apply duck — no new Auth API; the raw
88
+ # credential never enters a key. Lazy + memoized: a throwing custom auth
89
+ # surfaces on first request, not at construction.
90
+ def identity
91
+ @identity ||=
92
+ if @auth.nil?
93
+ "anon"
94
+ else
95
+ baseline = Net::HTTP::Get.new(URI(@base_url)).to_hash
96
+ probe = Net::HTTP::Get.new(URI(@base_url))
97
+ @auth.apply(probe)
98
+ delta = probe.to_hash.reject { |name, value| baseline[name] == value }
99
+ "h:#{OpenSSL::Digest::SHA256.hexdigest(delta.sort.to_s)}"
100
+ end
101
+ end
102
+
103
+ def presence(string)
104
+ string unless string.nil? || string.empty?
105
+ end
106
+
107
+ def deep_freeze(value)
108
+ case value
109
+ when Hash
110
+ value.each do |key, val|
111
+ deep_freeze(key)
112
+ deep_freeze(val)
113
+ end
114
+ when Array
115
+ value.each { deep_freeze(_1) }
116
+ end
117
+ value.freeze
118
+ end
119
+
120
+ # Best-effort by design: warning about a cache hiccup must never be the
121
+ # thing that fails a SUCCESSFUL response — a raising logger degrades to
122
+ # Kernel#warn, and even a closed stderr is swallowed.
123
+ def warn_failure(error)
124
+ message = "http_resource: cache write failed (#{error.class}: #{error.message}); " \
125
+ "response served uncached"
126
+ @logger ? @logger.warn(message) : Kernel.warn(message)
127
+ rescue StandardError
128
+ begin
129
+ Kernel.warn(message)
130
+ rescue StandardError
131
+ nil
132
+ end
133
+ end
134
+ end
135
+ end
@@ -10,13 +10,17 @@ module HttpResource
10
10
  # c.auth = HttpResource::Auth.bearer(ENV.fetch("API_TOKEN"))
11
11
  # end
12
12
  class Configuration
13
- attr_accessor :base_url, :auth, :open_timeout, :read_timeout
13
+ # cache: an ETag store opting the default client into conditional caching
14
+ # (see ConditionalCache); logger: receives cache-write warnings.
15
+ attr_accessor :base_url, :auth, :open_timeout, :read_timeout, :cache, :logger
14
16
 
15
17
  def initialize
16
18
  @base_url = nil
17
19
  @auth = nil
18
20
  @open_timeout = Client::DEFAULT_OPEN_TIMEOUT
19
21
  @read_timeout = Client::DEFAULT_READ_TIMEOUT
22
+ @cache = nil
23
+ @logger = nil
20
24
  end
21
25
  end
22
26
  end
@@ -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"
@@ -12,8 +12,9 @@ module HttpResource
12
12
  # Contact = Data.define(:email, :name) do
13
13
  # extend HttpResource::ValueObject
14
14
  # end
15
- # Contact.from("data" => { "email" => "a@b.se" }) # => #<data Contact email="a@b.se", name=nil>
16
- # Contact.from(nil) # => nil
15
+ # Contact.from("data" => { "email" => "anna@example.com" })
16
+ # # => #<data Contact email="anna@example.com", name=nil>
17
+ # Contact.from(nil) # => nil
17
18
  #
18
19
  # Resource methods should still guard `data && Contact.from(data)` so the
19
20
  # caller never receives a ghost object from an empty body.
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module HttpResource
4
- VERSION = "0.3.0"
4
+ VERSION = "0.4.0"
5
5
  end
data/lib/http_resource.rb CHANGED
@@ -3,6 +3,7 @@
3
3
  require "http_resource/version"
4
4
  require "http_resource/errors"
5
5
  require "http_resource/auth"
6
+ require "http_resource/conditional_cache"
6
7
  require "http_resource/client"
7
8
  require "http_resource/configuration"
8
9
  require "http_resource/resource"
@@ -25,7 +26,13 @@ require "http_resource/value_object"
25
26
  # c.auth = HttpResource::Auth.basic(ENV.fetch("API_USER"), ENV.fetch("API_PASS"))
26
27
  # end
27
28
  # HttpResource.client.get(["api", "ping"])
29
+ #
30
+ # For a URL someone else gave, HttpResource::SafeFetch (opt-in) fetches it under a strict address rule;
31
+ # HttpResource::PublicAddress is that rule on its own. Neither is loaded until it is named.
28
32
  module HttpResource
33
+ autoload :PublicAddress, "http_resource/public_address"
34
+ autoload :SafeFetch, "http_resource/safe_fetch"
35
+
29
36
  class << self
30
37
  # Configure the process-wide default client, then (re)build it.
31
38
  def configure
@@ -47,8 +54,9 @@ module HttpResource
47
54
  # but every option can be overridden per call — handy for talking to more
48
55
  # than one host without a global default.
49
56
  def build_client(base_url: configuration.base_url, auth: configuration.auth,
50
- open_timeout: configuration.open_timeout, read_timeout: configuration.read_timeout)
51
- Client.new(base_url:, auth:, open_timeout:, read_timeout:)
57
+ open_timeout: configuration.open_timeout, read_timeout: configuration.read_timeout,
58
+ cache: configuration.cache, logger: configuration.logger)
59
+ Client.new(base_url:, auth:, open_timeout:, read_timeout:, cache:, logger:)
52
60
  end
53
61
 
54
62
  # Drop the memoized config + client (mainly for tests / reconfiguration).
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: http_resource
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Skiftet
@@ -15,8 +15,6 @@ description: HttpResource gives you a Net::HTTP transport with a typed error hie
15
15
  timeouts, and escape-safe URL building so untrusted path segments can never escape
16
16
  the protocol. Bring a base_url and an auth strategy; build clients and resources
17
17
  on top. Zero runtime dependencies (stdlib only).
18
- email:
19
- - joel.e.svensson@skiftet.org
20
18
  executables: []
21
19
  extensions: []
22
20
  extra_rdoc_files: []
@@ -29,9 +27,14 @@ files:
29
27
  - lib/http_resource/auth/bearer.rb
30
28
  - lib/http_resource/auth/header.rb
31
29
  - lib/http_resource/client.rb
30
+ - lib/http_resource/conditional_cache.rb
32
31
  - lib/http_resource/configuration.rb
33
32
  - lib/http_resource/errors.rb
33
+ - lib/http_resource/public_address.rb
34
34
  - lib/http_resource/resource.rb
35
+ - lib/http_resource/safe_fetch.rb
36
+ - lib/http_resource/safe_fetch/call.rb
37
+ - lib/http_resource/safe_fetch/wire.rb
35
38
  - lib/http_resource/simulation.rb
36
39
  - lib/http_resource/simulation/backend.rb
37
40
  - lib/http_resource/simulation/store.rb