fingerly 0.2.0 → 0.3.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 +461 -240
- data/lib/fingerly/client.rb +332 -12
- data/lib/fingerly/config.rb +31 -13
- data/lib/fingerly/errors.rb +101 -0
- data/lib/fingerly/models.rb +181 -7
- data/lib/fingerly/proxy.rb +177 -98
- data/lib/fingerly/version.rb +1 -1
- data/sig/fingerly.rbs +141 -8
- metadata +1 -1
data/lib/fingerly/models.rb
CHANGED
|
@@ -5,8 +5,38 @@ require "time"
|
|
|
5
5
|
module Fingerly
|
|
6
6
|
# One signal group that contributed to an event's suspect score.
|
|
7
7
|
class EventTrigger
|
|
8
|
-
|
|
8
|
+
SIGNAL_ATTESTATION_FAILED = "attestation_failed"
|
|
9
|
+
SIGNAL_ATTESTATION_MISSING = "attestation_missing"
|
|
10
|
+
SIGNAL_ATTESTATION_DOWNGRADE = "attestation_downgrade"
|
|
11
|
+
SIGNAL_DEVICE_INCONSISTENT = "device_inconsistent"
|
|
12
|
+
SIGNAL_REPORT_INCOMPLETE = "report_incomplete"
|
|
13
|
+
SIGNAL_PROBE_ERRORS = "probe_errors"
|
|
14
|
+
SIGNAL_FETCH_METADATA_MISSING = "fetch_metadata_missing"
|
|
15
|
+
SIGNAL_WEB_TICKET_MISSING = "web_ticket_missing"
|
|
16
|
+
SIGNAL_WEB_TICKET_INVALID = "web_ticket_invalid"
|
|
17
|
+
SIGNAL_TAMPERING = "tampering"
|
|
18
|
+
SIGNAL_BROWSER_TAMPERING = "browser_tampering"
|
|
19
|
+
SIGNAL_CUSTOM_ROOT_CA = "custom_root_ca"
|
|
20
|
+
SIGNAL_SECONDARY_USER_PROFILE = "secondary_user_profile"
|
|
21
|
+
|
|
22
|
+
V3_SIGNALS = [
|
|
23
|
+
SIGNAL_ATTESTATION_FAILED,
|
|
24
|
+
SIGNAL_ATTESTATION_DOWNGRADE,
|
|
25
|
+
SIGNAL_DEVICE_INCONSISTENT,
|
|
26
|
+
SIGNAL_REPORT_INCOMPLETE,
|
|
27
|
+
SIGNAL_PROBE_ERRORS,
|
|
28
|
+
SIGNAL_FETCH_METADATA_MISSING,
|
|
29
|
+
SIGNAL_WEB_TICKET_MISSING,
|
|
30
|
+
SIGNAL_WEB_TICKET_INVALID,
|
|
31
|
+
SIGNAL_TAMPERING,
|
|
32
|
+
SIGNAL_CUSTOM_ROOT_CA,
|
|
33
|
+
SIGNAL_SECONDARY_USER_PROFILE
|
|
34
|
+
].freeze
|
|
35
|
+
|
|
36
|
+
# @return [String, nil] the signal or signal group, such as +vpn+ or +attestation_failed+
|
|
9
37
|
attr_reader :signal
|
|
38
|
+
# @return [String, nil] optional group identifier when returned alongside a raw signal
|
|
39
|
+
attr_reader :group
|
|
10
40
|
# @return [Integer] the group's combined weight in this score
|
|
11
41
|
attr_reader :weight
|
|
12
42
|
# @return [String, nil] +low+, +medium+ or +high+
|
|
@@ -15,6 +45,7 @@ module Fingerly
|
|
|
15
45
|
# @api private
|
|
16
46
|
def initialize(payload)
|
|
17
47
|
@signal = payload["signal"]
|
|
48
|
+
@group = payload["group"]
|
|
18
49
|
@weight = payload["weight"] || 0
|
|
19
50
|
@confidence = payload["confidence"]
|
|
20
51
|
freeze
|
|
@@ -33,11 +64,12 @@ module Fingerly
|
|
|
33
64
|
# the distinction at the call site.
|
|
34
65
|
class Event
|
|
35
66
|
# Fields copied straight from the response, in the order the API documents
|
|
36
|
-
# them. Anything not listed stays reachable through {#raw}. +
|
|
37
|
-
#
|
|
38
|
-
# when
|
|
67
|
+
# them. Anything not listed stays reachable through {#raw}. +visitor_id+ is
|
|
68
|
+
# +""+ when the submission was unidentifiable, +reason+ explains why
|
|
69
|
+
# enrichment did not happen when unavailable, and +project_id+ is the UUID
|
|
70
|
+
# string of the Fingerly project the event belongs to (nil on older servers).
|
|
39
71
|
STRING_FIELDS = %w[
|
|
40
|
-
request_id project_id visitor_id state environment platform sdk_platform
|
|
72
|
+
request_id project_id visitor_id state reason environment platform sdk_platform
|
|
41
73
|
sdk_version origin url_host url_path tag ip_network country_code
|
|
42
74
|
country_name asn asn_name anonymity_network agent agent_version os
|
|
43
75
|
device_kind visitor_kind suspect_level
|
|
@@ -62,10 +94,17 @@ module Fingerly
|
|
|
62
94
|
# API adds after this SDK was released needs no upgrade
|
|
63
95
|
attr_reader :raw
|
|
64
96
|
|
|
97
|
+
# @param lenient_time [Boolean] keeps a missing or malformed
|
|
98
|
+
# +occurred_at+ as nil rather than raising, for +events.verify+, which
|
|
99
|
+
# answers +too_old+ for it
|
|
65
100
|
# @api private
|
|
66
|
-
def initialize(payload)
|
|
101
|
+
def initialize(payload, lenient_time: false)
|
|
67
102
|
STRING_FIELDS.each { |name| instance_variable_set(:"@#{name}", payload[name]) }
|
|
68
|
-
@occurred_at =
|
|
103
|
+
@occurred_at = if lenient_time
|
|
104
|
+
Models.rfc3339(payload["occurred_at"])
|
|
105
|
+
else
|
|
106
|
+
Models.parse_instant(payload["occurred_at"])
|
|
107
|
+
end
|
|
69
108
|
@suspect_score = payload["suspect_score"]
|
|
70
109
|
@has_document = payload["has_document"] ? true : false
|
|
71
110
|
@triggers = Array(payload["triggers"]).map { |item| EventTrigger.new(item) }.freeze
|
|
@@ -125,6 +164,129 @@ module Fingerly
|
|
|
125
164
|
end
|
|
126
165
|
end
|
|
127
166
|
|
|
167
|
+
# The first consumption of an event, from +fingerly.events.consume+.
|
|
168
|
+
class EventConsumption
|
|
169
|
+
# @return [String, nil] the consumed event's request id
|
|
170
|
+
attr_reader :request_id
|
|
171
|
+
# @return [String, nil] when it was consumed, as the API sent it (RFC 3339)
|
|
172
|
+
attr_reader :consumed_at
|
|
173
|
+
# @return [Boolean] true for the call that consumed the event
|
|
174
|
+
attr_reader :first
|
|
175
|
+
# @return [Hash] the response body exactly as it arrived
|
|
176
|
+
attr_reader :raw
|
|
177
|
+
|
|
178
|
+
# @api private
|
|
179
|
+
def initialize(payload)
|
|
180
|
+
@request_id = payload["request_id"].is_a?(String) ? payload["request_id"] : nil
|
|
181
|
+
@consumed_at = payload["consumed_at"].is_a?(String) ? payload["consumed_at"] : nil
|
|
182
|
+
@first = payload["first"] == true
|
|
183
|
+
@raw = payload
|
|
184
|
+
freeze
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
def first? = first
|
|
188
|
+
|
|
189
|
+
def inspect
|
|
190
|
+
"#<Fingerly::EventConsumption request_id=#{request_id.inspect} first=#{first}>"
|
|
191
|
+
end
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
# The answer of +fingerly.events.verify+.
|
|
195
|
+
#
|
|
196
|
+
# {#reason} is +""+ when {#ok?}, and otherwise the first check that failed,
|
|
197
|
+
# as one of the wire strings below. The score is not checked: apply your own
|
|
198
|
+
# policy to {#event} after {#ok?}.
|
|
199
|
+
class EventVerification
|
|
200
|
+
NOT_FOUND = "not_found"
|
|
201
|
+
TOO_OLD = "too_old"
|
|
202
|
+
TAG_MISMATCH = "tag_mismatch"
|
|
203
|
+
UNIDENTIFIABLE = "unidentifiable"
|
|
204
|
+
UNSCORED = "unscored"
|
|
205
|
+
ALREADY_CONSUMED = "already_consumed"
|
|
206
|
+
|
|
207
|
+
# Every reason, in the order the checks run.
|
|
208
|
+
REASONS = [NOT_FOUND, TOO_OLD, TAG_MISMATCH, UNIDENTIFIABLE, UNSCORED, ALREADY_CONSUMED].freeze
|
|
209
|
+
|
|
210
|
+
# @return [Boolean] whether every check passed
|
|
211
|
+
attr_reader :ok
|
|
212
|
+
# @return [String] the failed check, or +""+ when {#ok}
|
|
213
|
+
attr_reader :reason
|
|
214
|
+
# @return [Event, nil] the event read; nil only for +not_found+
|
|
215
|
+
attr_reader :event
|
|
216
|
+
|
|
217
|
+
# @api private
|
|
218
|
+
def initialize(reason:, event:)
|
|
219
|
+
@ok = reason.empty?
|
|
220
|
+
@reason = reason
|
|
221
|
+
@event = event
|
|
222
|
+
freeze
|
|
223
|
+
end
|
|
224
|
+
|
|
225
|
+
def ok? = ok
|
|
226
|
+
|
|
227
|
+
def inspect
|
|
228
|
+
"#<Fingerly::EventVerification ok=#{ok} reason=#{reason.inspect}>"
|
|
229
|
+
end
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
# What Apple holds for the device behind an event, from
|
|
233
|
+
# +fingerly.device_check.query+. The bits mean what you decide; Fingerly
|
|
234
|
+
# never reads them.
|
|
235
|
+
class DeviceCheckBits
|
|
236
|
+
# @return [Boolean] false when Apple holds no bits for the device yet;
|
|
237
|
+
# both bits are then false
|
|
238
|
+
attr_reader :found
|
|
239
|
+
# @return [Boolean] the first bit
|
|
240
|
+
attr_reader :bit0
|
|
241
|
+
# @return [Boolean] the second bit
|
|
242
|
+
attr_reader :bit1
|
|
243
|
+
# @return [String, nil] when the bits last changed, as +YYYY-MM+; nil when
|
|
244
|
+
# Apple holds no bits
|
|
245
|
+
attr_reader :last_update
|
|
246
|
+
# @return [Hash] the response body exactly as it arrived
|
|
247
|
+
attr_reader :raw
|
|
248
|
+
|
|
249
|
+
# @api private
|
|
250
|
+
def initialize(payload)
|
|
251
|
+
@found = payload["found"] == true
|
|
252
|
+
@bit0 = payload["bit0"] == true
|
|
253
|
+
@bit1 = payload["bit1"] == true
|
|
254
|
+
@last_update = payload["last_update"].is_a?(String) ? payload["last_update"] : nil
|
|
255
|
+
@raw = payload
|
|
256
|
+
freeze
|
|
257
|
+
end
|
|
258
|
+
|
|
259
|
+
def found? = found
|
|
260
|
+
|
|
261
|
+
def inspect
|
|
262
|
+
"#<Fingerly::DeviceCheckBits found=#{found} bit0=#{bit0} bit1=#{bit1}>"
|
|
263
|
+
end
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
# The bits Apple accepted, from +fingerly.device_check.write+.
|
|
267
|
+
class DeviceCheckWrite
|
|
268
|
+
# @return [Boolean, nil] the value set for the first bit; nil when the
|
|
269
|
+
# write left it out
|
|
270
|
+
attr_reader :bit0
|
|
271
|
+
# @return [Boolean, nil] the value set for the second bit; nil when the
|
|
272
|
+
# write left it out
|
|
273
|
+
attr_reader :bit1
|
|
274
|
+
# @return [Hash] the response body exactly as it arrived
|
|
275
|
+
attr_reader :raw
|
|
276
|
+
|
|
277
|
+
# @api private
|
|
278
|
+
def initialize(payload)
|
|
279
|
+
@bit0 = [true, false].include?(payload["bit0"]) ? payload["bit0"] : nil
|
|
280
|
+
@bit1 = [true, false].include?(payload["bit1"]) ? payload["bit1"] : nil
|
|
281
|
+
@raw = payload
|
|
282
|
+
freeze
|
|
283
|
+
end
|
|
284
|
+
|
|
285
|
+
def inspect
|
|
286
|
+
"#<Fingerly::DeviceCheckWrite bit0=#{bit0.inspect} bit1=#{bit1.inspect}>"
|
|
287
|
+
end
|
|
288
|
+
end
|
|
289
|
+
|
|
128
290
|
# The envelope every webhook delivery shares.
|
|
129
291
|
#
|
|
130
292
|
# {#data} is left as a plain Hash, so a new event type needs no SDK upgrade.
|
|
@@ -179,5 +341,17 @@ module Fingerly
|
|
|
179
341
|
rescue ArgumentError, TypeError
|
|
180
342
|
raise Error, "Fingerly API returned a timestamp that is not RFC 3339"
|
|
181
343
|
end
|
|
344
|
+
|
|
345
|
+
RFC3339 = /\A\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})\z/
|
|
346
|
+
|
|
347
|
+
# A strict RFC 3339 date-time, or nil for anything else, a date alone
|
|
348
|
+
# included.
|
|
349
|
+
def rfc3339(value)
|
|
350
|
+
return nil unless value.is_a?(String) && value.match?(RFC3339)
|
|
351
|
+
|
|
352
|
+
Time.iso8601(value.upcase)
|
|
353
|
+
rescue ArgumentError
|
|
354
|
+
nil
|
|
355
|
+
end
|
|
182
356
|
end
|
|
183
357
|
end
|
data/lib/fingerly/proxy.rb
CHANGED
|
@@ -52,7 +52,7 @@ module Fingerly
|
|
|
52
52
|
if key.start_with?("HTTP_") then key[5..].downcase.tr("_", "-")
|
|
53
53
|
elsif %w[CONTENT_TYPE CONTENT_LENGTH].include?(key) then key.downcase.tr("_", "-")
|
|
54
54
|
end
|
|
55
|
-
headers[name] = value if name
|
|
55
|
+
headers[name] = headers.key?(name) ? "#{headers[name]}, #{value}" : value if name
|
|
56
56
|
end
|
|
57
57
|
headers.freeze
|
|
58
58
|
end
|
|
@@ -100,6 +100,26 @@ module Fingerly
|
|
|
100
100
|
# The answer when client_ip returns anything but one IP address.
|
|
101
101
|
NO_CLIENT_IP = "The client IP callback returned no valid address"
|
|
102
102
|
|
|
103
|
+
# JSON refusal when both Origin and a validated native SDK platform are absent.
|
|
104
|
+
MISSING_ORIGIN_JSON =
|
|
105
|
+
"{\"error\":{\"code\":\"missing_origin\",\"message\":\"Missing origin\",\"status\":400}}"
|
|
106
|
+
|
|
107
|
+
# Exact lowercase native/bridge identifiers allowed in x-fingerly-sdk-platform.
|
|
108
|
+
ALLOWED_PLATFORMS = Regexp.new(
|
|
109
|
+
"\\A(ios|android|react-native|react-native-ios|react-native-android|" \
|
|
110
|
+
"flutter|flutter-ios|flutter-android|lynx-ios|lynx-android|" \
|
|
111
|
+
"capacitor|kotlin-multiplatform)\\z"
|
|
112
|
+
).freeze
|
|
113
|
+
|
|
114
|
+
# Allowlisted client headers forwarded verbatim when present and header-safe.
|
|
115
|
+
FORWARDED_CLIENT_HEADERS = %w[
|
|
116
|
+
idempotency-key sec-fetch-site sec-fetch-mode sec-fetch-dest
|
|
117
|
+
sec-ch-ua sec-ch-ua-mobile sec-ch-ua-platform
|
|
118
|
+
].freeze
|
|
119
|
+
|
|
120
|
+
# Upstream statuses that can be relayed; 3xx inside this range is not.
|
|
121
|
+
RELAYABLE_STATUS = (200..599)
|
|
122
|
+
|
|
103
123
|
# Statuses that must not carry a body.
|
|
104
124
|
BODILESS = [204, 205, 304].freeze
|
|
105
125
|
|
|
@@ -116,31 +136,30 @@ module Fingerly
|
|
|
116
136
|
|
|
117
137
|
# @return [Integer] the request body limit in bytes
|
|
118
138
|
attr_reader :max_body_bytes
|
|
119
|
-
# @return [String
|
|
120
|
-
# nil to answer whatever the framework routes here
|
|
139
|
+
# @return [String] the one path answered, without a trailing slash
|
|
121
140
|
attr_reader :path
|
|
122
141
|
# @return [String] the API route version forwarded upstream
|
|
123
142
|
attr_reader :api_version
|
|
124
143
|
|
|
125
144
|
# @param app [#call, nil] the rest of the Rack stack. Rack passes this
|
|
126
|
-
# when the proxy is used as middleware
|
|
127
|
-
#
|
|
128
|
-
# gets 404.
|
|
145
|
+
# when the proxy is used as middleware; without one, a path the proxy
|
|
146
|
+
# does not serve gets 404.
|
|
129
147
|
# @param client_ip [#call] resolves the visitor's address from a
|
|
130
148
|
# {ProxyRequest}. Read it from a header your own infrastructure sets,
|
|
131
149
|
# such as your load balancer's or CDN's. Never use the left-most
|
|
132
150
|
# +X-Forwarded-For+ value: the visitor writes it.
|
|
133
|
-
# @param proxy_key [String
|
|
134
|
-
#
|
|
135
|
-
#
|
|
136
|
-
#
|
|
137
|
-
#
|
|
138
|
-
#
|
|
139
|
-
# such as +/k7x2qm4a+, matched exactly. Omit it only where the framework
|
|
140
|
-
# already routes that path here, as a Rails +mount+ or a +Rack::URLMap+
|
|
141
|
-
# entry does; the proxy then answers whatever it is handed.
|
|
151
|
+
# @param proxy_key [String] a write-only credential, +fly_px_…+, held only
|
|
152
|
+
# on your server. Required. Every forwarded request carries it as
|
|
153
|
+
# +X-Fingerly-Proxy-Key+ alongside the browser's public key, which must
|
|
154
|
+
# be scoped to the same environment.
|
|
155
|
+
# @param path [String] the path the dashboard issued for this proxy, such
|
|
156
|
+
# as +/k7x2qm4a+, matched exactly against +PATH_INFO+. Required.
|
|
142
157
|
# @param api_version [String] the version of the upstream ingest URL
|
|
143
|
-
# @param upstream [String, nil] overrides the API origin implied by the key
|
|
158
|
+
# @param upstream [String, nil] overrides the API origin implied by the key:
|
|
159
|
+
# a bare origin, scheme, host and optional port, and +https+ only
|
|
160
|
+
# @param allow_insecure_loopback [Boolean] lets +upstream+ be a plain
|
|
161
|
+
# +http+ origin on 127.0.0.1, localhost or [::1], for local development
|
|
162
|
+
# and tests. Off by default.
|
|
144
163
|
# @param max_body_bytes [Integer] larger request bodies are refused with 413
|
|
145
164
|
# @param timeout [Numeric] how long to wait for Fingerly, in seconds
|
|
146
165
|
# @param configure_http [Proc, nil] receives the +Net::HTTP+ before it connects
|
|
@@ -148,20 +167,20 @@ module Fingerly
|
|
|
148
167
|
# Without one, +rack.logger+ is used when the server provides it, and
|
|
149
168
|
# standard error otherwise.
|
|
150
169
|
# @raise [ConfigurationError] if a credential, path, limit or callback is
|
|
151
|
-
#
|
|
152
|
-
#
|
|
153
|
-
def initialize(app = nil, client_ip:, proxy_key
|
|
154
|
-
path: nil, api_version: "v1", upstream: nil,
|
|
170
|
+
# missing or invalid. A proxy is wired up once at start-up, where an error is
|
|
171
|
+
# natural to handle.
|
|
172
|
+
def initialize(app = nil, client_ip:, proxy_key:,
|
|
173
|
+
path: nil, allowed_origins: nil, api_version: "v1", upstream: nil,
|
|
155
174
|
max_body_bytes: DEFAULT_MAX_BODY_BYTES, timeout: DEFAULT_TIMEOUT,
|
|
156
|
-
configure_http: nil, logger: nil)
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
raise ConfigurationError,
|
|
175
|
+
configure_http: nil, logger: nil, allow_insecure_loopback: false)
|
|
176
|
+
scope = Config.scope_for(proxy_key, Config::PROXY)
|
|
177
|
+
unless scope
|
|
178
|
+
raise ConfigurationError,
|
|
179
|
+
"proxy_key must be a Fingerly proxy key, fly_px_<environment>_..., " \
|
|
180
|
+
"for the production, staging or development environment"
|
|
160
181
|
end
|
|
161
182
|
raise ConfigurationError, "client_ip is required" unless client_ip.respond_to?(:call)
|
|
162
|
-
|
|
163
|
-
# take all of them from the application behind it.
|
|
164
|
-
raise ConfigurationError, "path is required when the proxy is middleware" if app && !path
|
|
183
|
+
raise ConfigurationError, "path is required" if path.nil?
|
|
165
184
|
|
|
166
185
|
if logger && !logger.respond_to?(:warn)
|
|
167
186
|
raise ConfigurationError, "logger must respond to warn"
|
|
@@ -174,15 +193,16 @@ module Fingerly
|
|
|
174
193
|
@misconfigured = []
|
|
175
194
|
@misconfigured_lock = Mutex.new
|
|
176
195
|
@client_ip = client_ip
|
|
177
|
-
@
|
|
178
|
-
@
|
|
179
|
-
@
|
|
180
|
-
@
|
|
196
|
+
@key = proxy_key
|
|
197
|
+
@scope = scope
|
|
198
|
+
@path = Config.normalize_path(path)
|
|
199
|
+
@allowed_origins = normalize_origins(allowed_origins)
|
|
181
200
|
@api_version = Config.normalize_api_version(api_version)
|
|
182
201
|
@ingest = "/api/#{@api_version}/ingest".freeze
|
|
183
202
|
@max_body_bytes = Config.positive_int(max_body_bytes, "max_body_bytes")
|
|
184
203
|
@transport = Transport.new(
|
|
185
|
-
origin: Config.
|
|
204
|
+
origin: Config.normalize_origin(upstream || Config::DEFAULT_ENDPOINT, "upstream",
|
|
205
|
+
allow_insecure_loopback: allow_insecure_loopback == true),
|
|
186
206
|
timeout: Config.positive_seconds(timeout, "timeout"),
|
|
187
207
|
configure_http: configure_http
|
|
188
208
|
)
|
|
@@ -197,14 +217,12 @@ module Fingerly
|
|
|
197
217
|
# application it passed the request along to would receive nothing.
|
|
198
218
|
#
|
|
199
219
|
# The match is exact and case-sensitive: no trailing or doubled slash, no
|
|
200
|
-
# dot segment, no encoded slash, nothing under the path.
|
|
201
|
-
# configured +path+ the framework routed the request here, and {#call}
|
|
202
|
-
# checks that the mount was hit exactly.
|
|
220
|
+
# dot segment, no encoded slash, nothing under the path.
|
|
203
221
|
#
|
|
204
222
|
# @param path [String] the request path
|
|
205
223
|
# @return [Boolean]
|
|
206
224
|
def handles?(path)
|
|
207
|
-
|
|
225
|
+
path.to_s == @path
|
|
208
226
|
end
|
|
209
227
|
|
|
210
228
|
# Serves one Rack request.
|
|
@@ -217,7 +235,7 @@ module Fingerly
|
|
|
217
235
|
# about, so the application-relative path is the one that means the
|
|
218
236
|
# same thing wherever the application is deployed.
|
|
219
237
|
path = env["PATH_INFO"].to_s
|
|
220
|
-
return pass(env) unless
|
|
238
|
+
return pass(env) unless handles?(path)
|
|
221
239
|
|
|
222
240
|
serve(env, ProxyRequest.new(env, path))
|
|
223
241
|
end
|
|
@@ -230,46 +248,41 @@ module Fingerly
|
|
|
230
248
|
# behind the middleware: an +Errno::ENOENT+ or an +IOError+ raised by the
|
|
231
249
|
# host application is that application's error, not a visitor hanging up.
|
|
232
250
|
def serve(env, request)
|
|
233
|
-
|
|
234
|
-
|
|
251
|
+
sdk_platform = validated_platform(request.header("x-fingerly-sdk-platform"))
|
|
252
|
+
origin = non_blank(safe(request.header("origin")))
|
|
253
|
+
cors = cors_headers(origin)
|
|
254
|
+
|
|
255
|
+
# Methods are case-sensitive in HTTP: +post+ is not +POST+.
|
|
256
|
+
if !@allowed_origins.empty? && request.request_method == "OPTIONS"
|
|
257
|
+
return preflight(origin, cors)
|
|
258
|
+
end
|
|
259
|
+
|
|
260
|
+
unless request.request_method == "POST"
|
|
261
|
+
allow = @allowed_origins.empty? ? "POST" : "POST, OPTIONS"
|
|
262
|
+
return refuse(405, "Method Not Allowed", cors.merge("allow" => allow))
|
|
263
|
+
end
|
|
235
264
|
|
|
236
265
|
api_key = upstream_key_for(request.header("x-api-key"))
|
|
237
|
-
return refuse(401, "Unauthorized") if api_key.nil?
|
|
266
|
+
return refuse(401, "Unauthorized", cors) if api_key.nil?
|
|
267
|
+
return json_refuse(400, MISSING_ORIGIN_JSON, cors) if origin.nil? && sdk_platform.nil?
|
|
238
268
|
|
|
239
269
|
# Refuse on the declared size first; the read below enforces the real one.
|
|
240
270
|
declared = request.header("content-length").to_i
|
|
241
|
-
return refuse(413, "Payload Too Large") if declared > @max_body_bytes
|
|
271
|
+
return refuse(413, "Payload Too Large", cors) if declared > @max_body_bytes
|
|
242
272
|
|
|
243
273
|
body = read_bounded(env["rack.input"])
|
|
244
|
-
return refuse(413, "Payload Too Large") if body.nil?
|
|
274
|
+
return refuse(413, "Payload Too Large", cors) if body.nil?
|
|
245
275
|
|
|
246
|
-
forward(env, request, api_key, body)
|
|
276
|
+
forward(env, request, api_key, body, origin: origin, sdk_platform: sdk_platform, cors: cors)
|
|
247
277
|
rescue IOError, SystemCallError
|
|
248
278
|
# The visitor went away while the body was arriving. Nobody is left to
|
|
249
279
|
# read an answer, and there is nothing worth logging.
|
|
250
|
-
refuse(400, "Bad request")
|
|
280
|
+
refuse(400, "Bad request", cors || {})
|
|
251
281
|
end
|
|
252
282
|
|
|
253
283
|
def redacted_fields
|
|
254
284
|
[["path", @path.inspect], ["api_version", @api_version],
|
|
255
|
-
[
|
|
256
|
-
end
|
|
257
|
-
|
|
258
|
-
# Whether a mount routed exactly its own path here.
|
|
259
|
-
#
|
|
260
|
-
# A Rails +mount+ or +Rack::URLMap+ matches a prefix and moves it into
|
|
261
|
-
# SCRIPT_NAME, so +/k7x2qm4a/admin+ arrives with PATH_INFO +/admin+. Rails
|
|
262
|
-
# also hands the mount PATH_INFO +/+ for both +/k7x2qm4a+ and
|
|
263
|
-
# +/k7x2qm4a/+, so where the server reports the raw request line in
|
|
264
|
-
# REQUEST_URI, as Puma and Falcon do, that is compared too.
|
|
265
|
-
def mounted_exactly?(env)
|
|
266
|
-
return false unless ["", "/"].include?(env["PATH_INFO"].to_s)
|
|
267
|
-
|
|
268
|
-
raw = env["REQUEST_URI"]
|
|
269
|
-
return true unless raw.is_a?(String) && !raw.empty?
|
|
270
|
-
|
|
271
|
-
raw = raw.sub(%r{\A[a-z][a-z0-9+.-]*://[^/]*}i, "") # an absolute-form target
|
|
272
|
-
raw.split("?", 2).first == env["SCRIPT_NAME"].to_s
|
|
285
|
+
["proxy_key", Redacted::MARK]]
|
|
273
286
|
end
|
|
274
287
|
|
|
275
288
|
def pass(env)
|
|
@@ -278,23 +291,30 @@ module Fingerly
|
|
|
278
291
|
refuse(404, "Not Found")
|
|
279
292
|
end
|
|
280
293
|
|
|
281
|
-
def forward(env, request, api_key, body)
|
|
294
|
+
def forward(env, request, api_key, body, origin:, sdk_platform:, cors:)
|
|
282
295
|
address = client_address(env, request)
|
|
283
|
-
return refuse(500, NO_CLIENT_IP) if address.nil?
|
|
296
|
+
return refuse(500, NO_CLIENT_IP, cors) if address.nil?
|
|
284
297
|
|
|
285
|
-
headers = upstream_headers(request, api_key, address)
|
|
298
|
+
headers = upstream_headers(request, api_key, address, origin, sdk_platform)
|
|
286
299
|
|
|
287
|
-
#
|
|
288
|
-
#
|
|
289
|
-
#
|
|
290
|
-
#
|
|
300
|
+
# Client SDK envelopes go to the one ingest URL verbatim as raw bytes.
|
|
301
|
+
# The whole answer is read, within its cap, before anything is written
|
|
302
|
+
# back, so a response cut short upstream is a 502 rather than a truncated
|
|
303
|
+
# success.
|
|
291
304
|
result = @transport.call(Net::HTTP::Post, @ingest, headers, body)
|
|
292
|
-
|
|
305
|
+
# The API answers 2xx, 4xx or 5xx. A redirect is never followed, and
|
|
306
|
+
# anything outside 200 to 599 is not a status a browser can be handed.
|
|
307
|
+
unless RELAYABLE_STATUS.cover?(result.status) && !(300..399).cover?(result.status)
|
|
308
|
+
return upstream_failed(env, 502, "Bad gateway", "upstream answered an unusable status",
|
|
309
|
+
cors)
|
|
310
|
+
end
|
|
311
|
+
|
|
312
|
+
relay(result, cors)
|
|
293
313
|
rescue TimeoutError => e
|
|
294
|
-
upstream_failed(env, 504, "Gateway timeout", e)
|
|
314
|
+
upstream_failed(env, 504, "Gateway timeout", e, cors)
|
|
295
315
|
rescue Error => e
|
|
296
316
|
# Refused, reset, unresolvable, malformed, truncated, or over the cap.
|
|
297
|
-
upstream_failed(env, 502, "Bad gateway", e)
|
|
317
|
+
upstream_failed(env, 502, "Bad gateway", e, cors)
|
|
298
318
|
end
|
|
299
319
|
|
|
300
320
|
# What the callback returned, when it is exactly one IP address.
|
|
@@ -329,9 +349,12 @@ module Fingerly
|
|
|
329
349
|
# Answers a failed upstream call and logs one line about it: no stack
|
|
330
350
|
# trace, nothing from the request, and nothing in the response that names
|
|
331
351
|
# Fingerly.
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
352
|
+
# The line names the failure kind only, never the upstream host, port, URL
|
|
353
|
+
# or a key.
|
|
354
|
+
def upstream_failed(env, status, message, error, cors = {})
|
|
355
|
+
reason = error.is_a?(Exception) ? error.message : error.to_s
|
|
356
|
+
log(env, "fingerly proxy: #{status} #{reason}")
|
|
357
|
+
refuse(status, message, cors)
|
|
335
358
|
end
|
|
336
359
|
|
|
337
360
|
def log(env, line)
|
|
@@ -342,16 +365,16 @@ module Fingerly
|
|
|
342
365
|
nil
|
|
343
366
|
end
|
|
344
367
|
|
|
345
|
-
#
|
|
368
|
+
# Checks the browser's key before anything is forwarded.
|
|
346
369
|
#
|
|
347
|
-
#
|
|
348
|
-
# environment
|
|
349
|
-
#
|
|
370
|
+
# The browser must present a public key, +fly_pk_…+, for the proxy key's
|
|
371
|
+
# environment; the proxy forwards it alongside its own. A secret key, a
|
|
372
|
+
# proxy key, a public key of another environment or anything else is
|
|
373
|
+
# refused, so no credential but a public key ever travels upstream as
|
|
374
|
+
# +X-API-Key+.
|
|
350
375
|
#
|
|
351
|
-
# @return [String, nil] the key to forward, or nil when unauthorised
|
|
376
|
+
# @return [String, nil] the public key to forward, or nil when unauthorised
|
|
352
377
|
def upstream_key_for(presented)
|
|
353
|
-
return @key unless @uses_proxy_key
|
|
354
|
-
|
|
355
378
|
browser = Config.scope_for(presented, Config::PUBLIC)
|
|
356
379
|
return nil if browser.nil?
|
|
357
380
|
|
|
@@ -360,25 +383,35 @@ module Fingerly
|
|
|
360
383
|
|
|
361
384
|
# Builds the headers for the forwarded request.
|
|
362
385
|
#
|
|
363
|
-
# Nothing is copied wholesale:
|
|
364
|
-
#
|
|
365
|
-
#
|
|
366
|
-
#
|
|
386
|
+
# Nothing is copied wholesale: all incoming +x-fingerly-*+, +cookie+ and
|
|
387
|
+
# +authorization+ headers are stripped. +x-fingerly-origin+ is sent when
|
|
388
|
+
# incoming +origin+ is non-empty (never synthesized from +host+ or the
|
|
389
|
+
# request URL); otherwise a validated +x-fingerly-sdk-platform+ is restored.
|
|
367
390
|
#
|
|
368
391
|
# @return [Hash]
|
|
369
|
-
def upstream_headers(request, api_key, address)
|
|
392
|
+
def upstream_headers(request, api_key, address, origin, sdk_platform)
|
|
370
393
|
headers = {
|
|
371
|
-
"content-type" => safe(request.header("content-type")) || "application/json",
|
|
394
|
+
"content-type" => non_blank(safe(request.header("content-type"))) || "application/json",
|
|
372
395
|
"x-api-key" => api_key,
|
|
373
396
|
"x-fingerly-client-ip" => address,
|
|
374
|
-
"x-fingerly-origin" => safe(request.header("origin")).to_s,
|
|
375
397
|
"x-fingerly-user-agent" => safe(request.header("user-agent")).to_s,
|
|
376
398
|
"x-fingerly-proxy-version" => PROXY_VERSION,
|
|
377
399
|
"user-agent" => USER_AGENT
|
|
378
400
|
}
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
401
|
+
# One channel only. The API refuses a proxied request that carries both,
|
|
402
|
+
# and a browser Origin wins, as it does for a request sent directly.
|
|
403
|
+
if origin
|
|
404
|
+
headers["x-fingerly-origin"] = origin
|
|
405
|
+
elsif sdk_platform
|
|
406
|
+
headers["x-fingerly-sdk-platform"] = sdk_platform
|
|
407
|
+
end
|
|
408
|
+
host = non_blank(safe(request.header("host")))
|
|
409
|
+
headers["x-fingerly-host"] = host if host
|
|
410
|
+
headers["x-fingerly-proxy-key"] = @key
|
|
411
|
+
FORWARDED_CLIENT_HEADERS.each do |name|
|
|
412
|
+
value = non_blank(safe(request.header(name)))
|
|
413
|
+
headers[name] = value if value
|
|
414
|
+
end
|
|
382
415
|
headers
|
|
383
416
|
end
|
|
384
417
|
|
|
@@ -387,22 +420,62 @@ module Fingerly
|
|
|
387
420
|
Config.header_safe?(value) ? value : nil
|
|
388
421
|
end
|
|
389
422
|
|
|
423
|
+
def non_blank(value)
|
|
424
|
+
value && !value.strip.empty? ? value : nil
|
|
425
|
+
end
|
|
426
|
+
|
|
427
|
+
def validated_platform(value)
|
|
428
|
+
value if Config.header_safe?(value) && ALLOWED_PLATFORMS.match?(value)
|
|
429
|
+
end
|
|
430
|
+
|
|
431
|
+
def normalize_origins(origins)
|
|
432
|
+
Array(origins).filter_map do |origin|
|
|
433
|
+
candidate = origin.to_s.strip
|
|
434
|
+
candidate if !candidate.empty? && Config.header_safe?(candidate)
|
|
435
|
+
end.uniq.freeze
|
|
436
|
+
end
|
|
437
|
+
|
|
438
|
+
def cors_headers(origin)
|
|
439
|
+
return {} unless origin && @allowed_origins.include?(origin)
|
|
440
|
+
|
|
441
|
+
{
|
|
442
|
+
"access-control-allow-origin" => origin,
|
|
443
|
+
"vary" => "Origin",
|
|
444
|
+
"access-control-allow-methods" => "POST, OPTIONS",
|
|
445
|
+
"access-control-allow-headers" =>
|
|
446
|
+
"content-type, x-api-key, idempotency-key, x-fingerly-sdk-platform",
|
|
447
|
+
"access-control-expose-headers" =>
|
|
448
|
+
"x-request-id, ratelimit-limit, ratelimit-remaining, retry-after"
|
|
449
|
+
}
|
|
450
|
+
end
|
|
451
|
+
|
|
452
|
+
def preflight(origin, cors)
|
|
453
|
+
return refuse(403, "Forbidden") if origin && cors.empty?
|
|
454
|
+
|
|
455
|
+
headers = { "cache-control" => "no-store", "allow" => "POST, OPTIONS" }.merge(cors)
|
|
456
|
+
[204, headers, []]
|
|
457
|
+
end
|
|
458
|
+
|
|
390
459
|
# Returns the upstream response, uncacheable and with only the allowlisted
|
|
391
460
|
# headers.
|
|
392
461
|
#
|
|
393
462
|
# Header names are lowercase and repeats joined with ", ", which is the
|
|
394
463
|
# one shape Rack 2 and Rack 3 both accept: Rack 3 refuses an uppercase name
|
|
395
464
|
# outright, and Rack 2 refuses the array Rack 3 would rather have.
|
|
396
|
-
def relay(result)
|
|
397
|
-
headers = { "cache-control" => "no-store" }
|
|
465
|
+
def relay(result, cors = {})
|
|
466
|
+
headers = { "cache-control" => "no-store" }.merge(cors)
|
|
398
467
|
result.headers.each do |name, values|
|
|
399
468
|
key = name.downcase
|
|
400
|
-
|
|
469
|
+
next unless RELAYED_HEADERS.include?(key)
|
|
470
|
+
|
|
471
|
+
filtered = Array(values).select { |v| Config.header_safe?(v) && !v.match?(/fingerly/i) }
|
|
472
|
+
headers[key] = filtered.join(", ") unless filtered.empty?
|
|
401
473
|
end
|
|
402
474
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
475
|
+
if BODILESS.include?(result.status)
|
|
476
|
+
headers.delete("content-type")
|
|
477
|
+
return [result.status, headers, []]
|
|
478
|
+
end
|
|
406
479
|
|
|
407
480
|
[result.status, headers, [result.body]]
|
|
408
481
|
end
|
|
@@ -426,5 +499,11 @@ module Fingerly
|
|
|
426
499
|
headers = { "content-type" => "text/plain; charset=utf-8", "cache-control" => "no-store" }
|
|
427
500
|
[status, headers.merge(extra), [message]]
|
|
428
501
|
end
|
|
502
|
+
|
|
503
|
+
# A JSON refusal that never reached Fingerly.
|
|
504
|
+
def json_refuse(status, body, extra = {})
|
|
505
|
+
headers = { "content-type" => "application/json", "cache-control" => "no-store" }
|
|
506
|
+
[status, headers.merge(extra), [body]]
|
|
507
|
+
end
|
|
429
508
|
end
|
|
430
509
|
end
|
data/lib/fingerly/version.rb
CHANGED