fingerly 0.1.1 → 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.
@@ -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, nil] the one path answered, without a trailing slash, or
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, which then needs +path+ to know
127
- # which request is its own; without one, a path the proxy does not serve
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, nil] a write-only credential, +fly_px_…+, held
134
- # only on your server
135
- # @param secret_key [String, nil] the deprecated alternative to
136
- # +proxy_key+. Secret read keys will be refused in the next major
137
- # version; do not pass both.
138
- # @param path [String, nil] the path the dashboard issued for this proxy,
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
- # invalid, or if the proxy is middleware without a path. A proxy is wired
152
- # up once at start-up, where an error is natural to handle.
153
- def initialize(app = nil, client_ip:, proxy_key: nil, secret_key: nil,
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
- raise ConfigurationError, "A Fingerly proxy key is required" if !proxy_key && !secret_key
158
- if proxy_key && secret_key
159
- raise ConfigurationError, "Pass proxy_key or deprecated secret_key, not both"
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
- # Middleware sees every request in the stack. Without a path it would
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
- @uses_proxy_key = !proxy_key.nil?
178
- @key = proxy_key || secret_key
179
- @scope = Config.parse_key(@key, @uses_proxy_key ? Config::PROXY : Config::SECRET)
180
- @path = path.nil? ? nil : Config.normalize_path(path)
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.normalize_endpoint(upstream || Config::DEFAULT_ENDPOINT),
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. Without a
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
- @path.nil? || path.to_s == @path
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 @path ? handles?(path) : mounted_exactly?(env)
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
- return refuse(405, "Method Not Allowed", "allow" => "POST") unless
234
- request.request_method.casecmp("POST").zero?
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
- [@uses_proxy_key ? "proxy_key" : "secret_key", Redacted::MARK]]
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
- # Both of the browser SDK's calls go to the one ingest URL, which tells
288
- # them apart by their bodies. The whole answer is read, within its cap,
289
- # before anything is written back, so a response cut short upstream is
290
- # a 502 rather than a truncated success.
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
- relay(result)
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
- def upstream_failed(env, status, message, error)
333
- log(env, "fingerly proxy: #{status} #{error.message}")
334
- refuse(status, message)
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
- # Decides which key to present upstream.
368
+ # Checks the browser's key before anything is forwarded.
346
369
  #
347
- # With a proxy key the browser must supply a public key for the same
348
- # environment, which the proxy forwards alongside its own. The deprecated
349
- # secret-key mode authenticates on its own.
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: only the body's content type, the visitor
364
- # metadata Fingerly needs, and an idempotency key when the SDK sent one.
365
- # The visitor writes the origin, user agent and content type, so each is
366
- # checked before it is repeated into a header of ours.
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
- headers["x-fingerly-proxy-key"] = @key if @uses_proxy_key
380
- idempotency = safe(request.header("idempotency-key"))
381
- headers["idempotency-key"] = idempotency if idempotency && !idempotency.empty?
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
- headers[key] = Array(values).join(", ") if RELAYED_HEADERS.include?(key)
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
- # No chunk at all, not one empty chunk: some servers warn on, or count,
404
- # an empty string in the body of a status that must not have one.
405
- return [result.status, headers, []] if BODILESS.include?(result.status)
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
@@ -2,5 +2,5 @@
2
2
 
3
3
  module Fingerly
4
4
  # The SDK version, reported to the API on every request.
5
- VERSION = "0.1.1"
5
+ VERSION = "0.3.0"
6
6
  end