internetdata 2.10.1 → 2.11.1

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: 8d551a2233a205fbf677c4bab66f4e48970795b8948f5253736e13795e1100e1
4
- data.tar.gz: 66390534b688de43157024deb0a86b217f681f2649e32f128df5a78358def68c
3
+ metadata.gz: 4a58e5c8517c31d0efff47e5ee257e6b76975986ff347f81d57da28316eb4220
4
+ data.tar.gz: 736a9a2681f777c062b92e5a327ec3908abf00c4e86e23385e099e88233e1455
5
5
  SHA512:
6
- metadata.gz: 1874592aab4b4c990fbfc5dd7bab23620c9109fa9eed5c2bb51cf954d52160fb73506a2e52186568b9fcd3f656943145a081c09c1459a51d5a95ac105a4d0a03
7
- data.tar.gz: 030c478b5e77d67f10ce5b6c0698841732ba35cfe025a546cf003a081b05af02ba4c39b20a1856a6eaf048facb941cdf5fa730c9f8a3582d28848eb3bfb21696
6
+ metadata.gz: 86fc22e6f67d2706ed9408a7b865aea17ac4892ac3cf23921cd3769f6081932b4f0bc90bfbf88a6aac8d07116eb56a08d2444ba5390d073517b40be58a244e4e
7
+ data.tar.gz: e20048c654b165baf6d77e83c9d8b6da4214271ce26a9217a60da0cd8f4d99ab4cc134fa49e45b8f3094c75e5c3702160a9774a4b195432ea8d17cc41fbb4038
@@ -101,7 +101,7 @@ module InternetData
101
101
  # The API answers an AS or a domain at this path too, as an answer this call
102
102
  # cannot read, so one is refused unsent rather than retried as unreadable.
103
103
  unless Bogon.address?(ip)
104
- raise Error.new(:bad_request, "#{ip.inspect} is not an IP address: look an AS up with lookup_asn " \
104
+ raise Error.new(:bad_request, "'#{ip}' is not an IP address: look up an AS with lookup_asn, " \
105
105
  'and a domain with lookup_domain')
106
106
  end
107
107
  return Bogon.result(ip) if Bogon.bogon?(ip)
@@ -177,7 +177,7 @@ module InternetData
177
177
  @ignore_operation_servers = false
178
178
  @inject_format = false
179
179
  @force_ending_format = false
180
- @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
180
+ @logger = defined?(::Rails) ? ::Rails.logger : Logger.new(STDOUT)
181
181
 
182
182
  yield(self) if block_given?
183
183
  end
@@ -0,0 +1,148 @@
1
+ # frozen_string_literal: true
2
+
3
+ module InternetData
4
+ module Middleware
5
+ # Deciding whether an answer is worth blocking.
6
+ #
7
+ # A condition is written in the shape of a served answer and keyed by the
8
+ # same names the API uses, so what you write here reads like what you get
9
+ # back. Symbol and string keys both work.
10
+ #
11
+ # { location: { country: %w[CU IR KP] } }
12
+ # { asn: { type: 'hosting' } }
13
+ # { is_resproxy: true, resproxy: { hits: { gte: 5 } } }
14
+ # { is_vpn: true, vpn: { provider: 'nordvpn' } }
15
+ # [{ is_tor: true }, { is_resproxy: true }] # a list is OR
16
+ #
17
+ # A value may be a scalar (equality, strings without regard to case), an
18
+ # Array meaning any-of, a Hash of `gte`/`gt`/`lte`/`lt` bounding a number,
19
+ # or a nested condition. A member set to `false` or `nil` is ignored
20
+ # entirely - a condition states the positive signals you act on, so there is
21
+ # no way to write "block when this is false", which would otherwise read as
22
+ # blocking everybody.
23
+ module Condition
24
+ BOUND_KEYS = %w[gte gt lte lt].freeze
25
+
26
+ module_function
27
+
28
+ # Whether an answer satisfies the condition, and should therefore be
29
+ # blocked.
30
+ def matches?(condition, result)
31
+ Array(wrap(condition)).any? { |one| matches_object?(one, result.raw) }
32
+ end
33
+
34
+ # The members a condition names that this answer did not carry: a
35
+ # top-level member, or a paid one inside an object every plan gets, by its
36
+ # path (`location.city`).
37
+ #
38
+ # A field your plan does not include is absent rather than false, so a
39
+ # condition naming one can never match and the block would silently never
40
+ # fire. An empty object (`{}`) is a real answer meaning the flag above it
41
+ # is false, so nothing inside one is reported: `vpn` empty is not a plan
42
+ # gap. A populated object carries every member the plan includes, so a
43
+ # member missing there is one.
44
+ #
45
+ # A locally answered bogon needs no special case: it is synthesized in the
46
+ # widest shape, so every member is present and nothing reads as missing.
47
+ def missing_members(condition, result)
48
+ missing = []
49
+ wrap(condition).each { |one| collect_missing(one, result.raw, '', missing) }
50
+ missing
51
+ end
52
+
53
+ # Refuse a condition that constrains nothing.
54
+ #
55
+ # Ignoring `false` means `{ is_vpn: false }` and `{}` have no terms left
56
+ # to satisfy, so they would match every answer and block all traffic.
57
+ # Nobody writes that on purpose, and failing when the middleware is built
58
+ # beats discovering it in production.
59
+ def validate!(condition)
60
+ return if condition.nil?
61
+
62
+ wrap(condition).each do |one|
63
+ next unless constraint_count(one).zero?
64
+
65
+ raise ArgumentError,
66
+ "internetdata: block condition #{one.inspect} constrains nothing, which " \
67
+ 'would block every request; a member set to false or nil is ignored, so ' \
68
+ 'state the positive signals you act on'
69
+ end
70
+ end
71
+
72
+ # How many leaf constraints a condition actually carries.
73
+ def constraint_count(condition)
74
+ case condition
75
+ when nil, false then 0
76
+ when Hash
77
+ bound?(condition) ? 1 : condition.values.sum { |v| constraint_count(v) }
78
+ when Array then condition.sum { |v| constraint_count(v) }
79
+ else 1
80
+ end
81
+ end
82
+
83
+ def wrap(condition)
84
+ condition.is_a?(Array) ? condition : [condition]
85
+ end
86
+
87
+ def collect_missing(condition, value, prefix, missing)
88
+ condition.each do |member, want|
89
+ next if constraint_count(want).zero?
90
+
91
+ path = "#{prefix}#{member}"
92
+ unless value.key?(member.to_s)
93
+ missing << path unless missing.include?(path)
94
+ next
95
+ end
96
+ got = value[member.to_s]
97
+ next unless want.is_a?(Hash) && !bound?(want) && got.is_a?(Hash) && !got.empty?
98
+
99
+ collect_missing(want, got, "#{path}.", missing)
100
+ end
101
+ end
102
+
103
+ def matches_object?(condition, value)
104
+ condition.all? do |member, want|
105
+ next true if constraint_count(want).zero?
106
+
107
+ matches_value?(want, value.is_a?(Hash) ? value[member.to_s] : nil)
108
+ end
109
+ end
110
+
111
+ # An ABSENT member arrives here as nil, which is exactly what "not in your
112
+ # plan" looks like. Every branch below must therefore reject it, which is
113
+ # what makes an unserved member fail a match rather than pass it.
114
+ def matches_value?(want, got)
115
+ case want
116
+ when Array then want.any? { |entry| matches_value?(entry, got) }
117
+ when Hash
118
+ bound?(want) ? matches_bound?(want, got) : matches_object?(want, got)
119
+ when String
120
+ # Providers are lowercase slugs and countries uppercase codes on the
121
+ # wire, and a caller should not have to know which, so a string
122
+ # compares without case.
123
+ got.is_a?(String) && want.casecmp?(got)
124
+ when true, false then want == got
125
+ when Numeric then got.is_a?(Numeric) && !got.is_a?(TrueClass) && want == got
126
+ else want == got
127
+ end
128
+ end
129
+
130
+ def matches_bound?(bound, got)
131
+ return false unless got.is_a?(Numeric)
132
+
133
+ normalized = bound.transform_keys(&:to_s)
134
+ return false if normalized['gte'] && got < normalized['gte']
135
+ return false if normalized['gt'] && got <= normalized['gt']
136
+ return false if normalized['lte'] && got > normalized['lte']
137
+
138
+ !(normalized['lt'] && got >= normalized['lt'])
139
+ end
140
+
141
+ def bound?(value)
142
+ return false unless value.is_a?(Hash)
143
+
144
+ !value.empty? && value.keys.all? { |k| BOUND_KEYS.include?(k.to_s) }
145
+ end
146
+ end
147
+ end
148
+ end
@@ -0,0 +1,181 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'condition'
4
+
5
+ module InternetData
6
+ # The framework-agnostic half of a web middleware: resolve a client address,
7
+ # classify it, and decide whether the condition matched.
8
+ #
9
+ # An adapter - the internetdata-rails gem - keeps only the parts that are
10
+ # genuinely framework-shaped and shares everything here, so the shared
11
+ # conformance corpus is asserted once for Ruby rather than once per framework.
12
+ module Middleware
13
+ # What a middleware attached to the request, whether or not it succeeded.
14
+ Lookup = Struct.new(:blocked, :ip, :result, :error, keyword_init: true) do
15
+ # Whether the condition matched. Always false when none was configured.
16
+ def blocked?
17
+ blocked == true
18
+ end
19
+ end
20
+
21
+ # Enough of an incoming request for a selector to work with, whatever
22
+ # framework it came from. An adapter supplies one of these per request.
23
+ RequestView = Struct.new(:header, :framework_ip, keyword_init: true)
24
+
25
+ # Defaults set for a request path rather than for a script: failing open
26
+ # quickly beats holding a visitor while we try again.
27
+ DEFAULT_TIMEOUT = 2.5
28
+ DEFAULT_RETRIES = 0
29
+
30
+ # Resolve, classify, decide.
31
+ class Core
32
+ # @param default_ip_selector [#call] the framework's own accessor, used
33
+ # when the caller named none.
34
+ def initialize(default_ip_selector, **options)
35
+ Condition.validate!(options[:block_condition])
36
+ @condition = options[:block_condition]
37
+ @selector = options[:ip_selector] || default_ip_selector
38
+ @fail_closed = options.fetch(:fail_closed, false)
39
+ @on_missing_field = options.fetch(:on_missing_field, :warn)
40
+ @skip = options[:skip]
41
+ @on_warn = options[:on_warn]
42
+ @retries = options.fetch(:retries, DEFAULT_RETRIES)
43
+ Retries.checked_count(@retries) unless @retries.nil?
44
+ @warned = {}
45
+ @client = options[:client] || Client.new(
46
+ api_key: options[:api_key],
47
+ **{ base_url: options[:base_url] }.compact,
48
+ timeout: options.fetch(:timeout, DEFAULT_TIMEOUT)
49
+ )
50
+ end
51
+
52
+ # Whether a condition was configured at all.
53
+ def blocking?
54
+ !@condition.nil?
55
+ end
56
+
57
+ # Classify one request. Answers nil when `skip` claimed it.
58
+ #
59
+ # A failed LOOKUP is not raised: it lands on `Lookup#error` and the
60
+ # request is let through. What CAN raise is a misconfiguration - a
61
+ # condition naming a member the plan does not serve, with
62
+ # `on_missing_field: :raise`.
63
+ def evaluate(request)
64
+ return nil if @skip&.call(request)
65
+
66
+ ip = @selector.call(request).to_s.strip
67
+ return unresolved if ip.empty?
68
+
69
+ if Bogon.bogon?(ip)
70
+ # Expected in local development. Anywhere else it means a proxy sits
71
+ # in front and its own address is what reached us.
72
+ warn_once(
73
+ "resolved the client address as #{ip}, which is not a public address. If this " \
74
+ 'application runs behind a proxy or load balancer, configure its trusted-proxy ' \
75
+ "setting or pass an ip_selector that reads your edge's header."
76
+ )
77
+ end
78
+
79
+ begin
80
+ result = @client.lookup(ip, retries: @retries)
81
+ rescue InternetData::Error => e
82
+ return Lookup.new(blocked: @fail_closed, ip: ip, error: e)
83
+ end
84
+ decide(ip, result)
85
+ end
86
+
87
+ private
88
+
89
+ def unresolved
90
+ warn_once(
91
+ 'could not resolve a client address from this request; pass an ip_selector that ' \
92
+ 'knows where yours comes from'
93
+ )
94
+ Lookup.new(
95
+ blocked: @fail_closed,
96
+ error: InternetData::Error.new(:bad_request, 'no client address on the request')
97
+ )
98
+ end
99
+
100
+ def decide(ip, result)
101
+ return Lookup.new(blocked: false, ip: ip, result: result) if @condition.nil?
102
+
103
+ report_missing(result)
104
+ Lookup.new(
105
+ blocked: Condition.matches?(@condition, result),
106
+ ip: ip,
107
+ result: result
108
+ )
109
+ end
110
+
111
+ def report_missing(result)
112
+ return if @on_missing_field == :ignore
113
+
114
+ missing = Condition.missing_members(@condition, result)
115
+ return if missing.empty?
116
+
117
+ message = "block_condition names #{missing.join(', ')}, which your plan does not " \
118
+ 'include, so those terms can never match. An absent member means "not in ' \
119
+ 'your plan", not "checked, and no".'
120
+ raise ArgumentError, "internetdata: #{message}" if @on_missing_field == :raise
121
+
122
+ warn_once(message)
123
+ end
124
+
125
+ # A misconfiguration is the same on every request, so saying so once is a
126
+ # warning and saying so a million times is an outage of its own.
127
+ def warn_once(message)
128
+ return if @warned[message]
129
+
130
+ @warned[message] = true
131
+ @on_warn ? @on_warn.call(message) : Kernel.warn("[internetdata] #{message}")
132
+ end
133
+ end
134
+
135
+ # The shared client-address selectors, bound to one framework's request type.
136
+ #
137
+ # There is no portable default: a framework's own accessor may return the
138
+ # socket peer, or may already have walked a proxy chain, depending on the
139
+ # framework and on how the application configured it.
140
+ class Selectors
141
+ def initialize(&view)
142
+ @view = view
143
+ end
144
+
145
+ # The framework's own client-address accessor.
146
+ def default
147
+ ->(request) { @view.call(request).framework_ip.call }
148
+ end
149
+
150
+ # An address from `X-Forwarded-For`.
151
+ #
152
+ # The LEFT-MOST entry (depth 0) is whatever the caller sent, because
153
+ # proxies append to this header, so a visitor who sets it themselves
154
+ # appears first and this returns their forgery. It is only trustworthy
155
+ # when an edge you control overwrites the header. When you know how many
156
+ # proxies sit in front, count from the right: depth 1 is the address your
157
+ # nearest proxy saw.
158
+ def xff(depth = 0)
159
+ lambda do |request|
160
+ seen = @view.call(request)
161
+ chain = (seen.header.call('X-Forwarded-For') || '').split(',').map(&:strip).reject(&:empty?)
162
+ next seen.framework_ip.call if chain.empty?
163
+ next chain.first if depth <= 0 || depth > chain.length
164
+
165
+ chain[-depth]
166
+ end
167
+ end
168
+
169
+ # An address from a single-value header your edge writes -
170
+ # `header('CF-Connecting-IP')` behind Cloudflare. Falls back to the
171
+ # framework's accessor when the header is absent.
172
+ def header(name)
173
+ lambda do |request|
174
+ seen = @view.call(request)
175
+ value = (seen.header.call(name) || '').strip
176
+ value.empty? ? seen.framework_ip.call : value
177
+ end
178
+ end
179
+ end
180
+ end
181
+ end
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'middleware/condition'
4
+ require_relative 'middleware/core'
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module InternetData
4
- VERSION = '2.10.1'
4
+ VERSION = '2.11.1'
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: internetdata
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.10.1
4
+ version: 2.11.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mslm Dev
@@ -62,6 +62,9 @@ files:
62
62
  - lib/internetdata/database_api.rb
63
63
  - lib/internetdata/domain_result.rb
64
64
  - lib/internetdata/errors.rb
65
+ - lib/internetdata/middleware.rb
66
+ - lib/internetdata/middleware/condition.rb
67
+ - lib/internetdata/middleware/core.rb
65
68
  - lib/internetdata/models/abuse_contact.rb
66
69
  - lib/internetdata/models/asn.rb
67
70
  - lib/internetdata/models/asn_lookup_response.rb