fingerly 0.4.1 → 0.5.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 +200 -19
- data/lib/fingerly/agent_sightings.rb +421 -0
- data/lib/fingerly/agent_sightings_middleware.rb +131 -0
- data/lib/fingerly/agent_sightings_reader.rb +233 -0
- data/lib/fingerly/agent_sightings_store.rb +171 -0
- data/lib/fingerly/client.rb +123 -12
- data/lib/fingerly/config.rb +6 -0
- data/lib/fingerly/enums.rb +68 -7
- data/lib/fingerly/errors.rb +46 -7
- data/lib/fingerly/models.rb +290 -18
- data/lib/fingerly/proxy.rb +15 -2
- data/lib/fingerly/transport.rb +42 -12
- data/lib/fingerly/version.rb +1 -1
- data/lib/fingerly.rb +4 -0
- data/sig/fingerly.rbs +199 -3
- metadata +5 -1
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
require "ipaddr"
|
|
5
|
+
|
|
6
|
+
module Fingerly
|
|
7
|
+
# The key and request reading behind {AgentSightings}; see agent_sightings.rb.
|
|
8
|
+
class AgentSightings
|
|
9
|
+
# The cache key of section 4.1 of the agent sightings contract.
|
|
10
|
+
#
|
|
11
|
+
# @return [String, nil] 32 lowercase hex characters, or nil when
|
|
12
|
+
# +client_ip+ is not one IP literal
|
|
13
|
+
def self.key(user_agent:, client_ip:, signature_agent: "", signed: false)
|
|
14
|
+
ip = Key.canonical_ip(client_ip)
|
|
15
|
+
ip && Key.digest(user_agent.to_s, ip, signature_agent.to_s, signed)
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# An address in its canonical text form: IPv4 dotted, an IPv4-mapped IPv6
|
|
19
|
+
# address as its IPv4 address, and other IPv6 as RFC 5952 has it.
|
|
20
|
+
#
|
|
21
|
+
# @return [String, nil] nil when the value is not one IP literal
|
|
22
|
+
def self.canonical_ip(value)
|
|
23
|
+
Key.canonical_ip(value)
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# @api private
|
|
27
|
+
def self.monotonic
|
|
28
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# Whether the caller runs inside a signal handler, where Ruby refuses to
|
|
32
|
+
# lock a Mutex.
|
|
33
|
+
#
|
|
34
|
+
# @api private
|
|
35
|
+
def self.trap_context?
|
|
36
|
+
Mutex.new.synchronize { false }
|
|
37
|
+
rescue ThreadError
|
|
38
|
+
true
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# Seconds {#close} or {#flush} holds up a signal handler at most: a flush
|
|
42
|
+
# in flight and one more. Past it the handler returns and the work goes
|
|
43
|
+
# on in the background.
|
|
44
|
+
TRAP_WAIT = 2 * IN_FLIGHT_WAIT
|
|
45
|
+
|
|
46
|
+
# Seconds reporting stops after a 429: its Retry-After, or for none a
|
|
47
|
+
# minute, and the next UTC day for the daily allowance. A Retry-After of
|
|
48
|
+
# 0, or a date already past, still stops a second, an unreadable one
|
|
49
|
+
# reads as none, and a huge one stops a day at most.
|
|
50
|
+
#
|
|
51
|
+
# @api private
|
|
52
|
+
def self.rate_limit_pause(error)
|
|
53
|
+
wait = error.retry_after
|
|
54
|
+
if wait.nil?
|
|
55
|
+
wait = RATE_LIMIT_PAUSE
|
|
56
|
+
if error.rate_limit_scope == APIError::RATE_LIMIT_SCOPE_DAILY
|
|
57
|
+
today = Time.now.utc
|
|
58
|
+
wait = (Time.utc(today.year, today.month, today.day) + 86_400 - today).ceil
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
wait.clamp(RETRY_AFTER_MIN, RETRY_AFTER_MAX)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Runs the block on a thread of its own and waits for it, at most
|
|
65
|
+
# {TRAP_WAIT} seconds, for a call made inside a signal handler.
|
|
66
|
+
#
|
|
67
|
+
# The signal may have interrupted this thread while it held one of
|
|
68
|
+
# +locks+, which it releases only once the handler returns: then the
|
|
69
|
+
# block runs as soon as it does, and the handler does not wait for it,
|
|
70
|
+
# which would never end.
|
|
71
|
+
#
|
|
72
|
+
# @api private
|
|
73
|
+
def self.outside_trap(locks, &block)
|
|
74
|
+
thread = Thread.new(&block)
|
|
75
|
+
thread.join(TRAP_WAIT) unless locks.any?(&:owned?)
|
|
76
|
+
nil
|
|
77
|
+
rescue StandardError
|
|
78
|
+
nil
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
private
|
|
82
|
+
|
|
83
|
+
# The locks {#close} and {#flush} take.
|
|
84
|
+
def locks
|
|
85
|
+
[@lock, @log_lock]
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# The cache key of section 4.1 of the agent sightings contract, and the
|
|
89
|
+
# canonical address it hashes.
|
|
90
|
+
#
|
|
91
|
+
# @api private
|
|
92
|
+
module Key
|
|
93
|
+
module_function
|
|
94
|
+
|
|
95
|
+
# @return [String] 32 lowercase hex characters
|
|
96
|
+
def digest(user_agent, ip, signature_agent, signed)
|
|
97
|
+
sha = Digest::SHA256.new
|
|
98
|
+
[user_agent, ip, signature_agent].each { |part| sha << part.b << "\0" }
|
|
99
|
+
sha << (signed ? "1" : "0")
|
|
100
|
+
sha.digest.byteslice(0, 16).unpack1("H*")
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# @return [String, nil] nil when the value is not one IP literal
|
|
104
|
+
def canonical_ip(value)
|
|
105
|
+
return nil unless Config.ip_literal?(value)
|
|
106
|
+
|
|
107
|
+
address = IPAddr.new(value)
|
|
108
|
+
return address.to_s if address.ipv4?
|
|
109
|
+
return address.native.to_s if address.ipv4_mapped?
|
|
110
|
+
|
|
111
|
+
rfc5952(address.hton.unpack("n8"))
|
|
112
|
+
rescue IPAddr::Error
|
|
113
|
+
nil
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
# Eight 16-bit groups in lowercase hex, with the longest run of two or
|
|
117
|
+
# more zero groups shortened to +::+, the first one when two are as long.
|
|
118
|
+
def rfc5952(groups)
|
|
119
|
+
best_at = nil
|
|
120
|
+
best_len = 1
|
|
121
|
+
run_at = nil
|
|
122
|
+
groups.each_with_index do |group, index|
|
|
123
|
+
unless group.zero?
|
|
124
|
+
run_at = nil
|
|
125
|
+
next
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
run_at ||= index
|
|
129
|
+
next unless index - run_at + 1 > best_len
|
|
130
|
+
|
|
131
|
+
best_at = run_at
|
|
132
|
+
best_len = index - run_at + 1
|
|
133
|
+
end
|
|
134
|
+
hex = groups.map { |group| group.to_s(16) }
|
|
135
|
+
return hex.join(":") if best_at.nil?
|
|
136
|
+
|
|
137
|
+
"#{hex[0...best_at].join(":")}::#{hex[(best_at + best_len)..].join(":")}"
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
# Reads what would be reported for one request out of its Rack
|
|
142
|
+
# environment.
|
|
143
|
+
#
|
|
144
|
+
# @api private
|
|
145
|
+
class Reader
|
|
146
|
+
# @param log [#call] takes a line to log at most once a minute
|
|
147
|
+
def initialize(client_ip, log)
|
|
148
|
+
@client_ip = client_ip
|
|
149
|
+
@log = log
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
# @param request [Hash, #env] the Rack environment, or a request object
|
|
153
|
+
# that holds one
|
|
154
|
+
# Every limit is measured on the value as it is sent: UTF-8, with each
|
|
155
|
+
# invalid byte sequence replaced by U+FFFD, which is three bytes. The
|
|
156
|
+
# cache key still hashes the bytes as received.
|
|
157
|
+
#
|
|
158
|
+
# @return [Sighting, nil] nil when the request is not reported at all:
|
|
159
|
+
# a user agent or method over the limit, or no usable client address
|
|
160
|
+
# @raise [ArgumentError] for anything else
|
|
161
|
+
def sighting(request)
|
|
162
|
+
env = Reader.environment(request)
|
|
163
|
+
user_agent = env["HTTP_USER_AGENT"]
|
|
164
|
+
user_agent = "" unless user_agent.is_a?(String)
|
|
165
|
+
sent_user_agent = Agents.utf8(user_agent)
|
|
166
|
+
method = Agents.utf8(env["REQUEST_METHOD"].to_s)
|
|
167
|
+
return nil if [sent_user_agent, method].any? { |value| value.bytesize > MAX_HEADER_BYTES }
|
|
168
|
+
|
|
169
|
+
ip = client_address(env)
|
|
170
|
+
return nil if ip.nil?
|
|
171
|
+
|
|
172
|
+
# A header over the limit is left out, and counts as absent for the
|
|
173
|
+
# key too: the server never sees it.
|
|
174
|
+
signature = header(env, "HTTP_SIGNATURE")
|
|
175
|
+
signature_input = header(env, "HTTP_SIGNATURE_INPUT")
|
|
176
|
+
signature_agent = header(env, "HTTP_SIGNATURE_AGENT")
|
|
177
|
+
signed = !signature.nil? && !signature_input.nil?
|
|
178
|
+
fields = {
|
|
179
|
+
user_agent: sent_user_agent, client_ip: ip, host: bounded(env["HTTP_HOST"]),
|
|
180
|
+
request_method: method, signature: signature && Agents.utf8(signature),
|
|
181
|
+
signature_input: signature_input && Agents.utf8(signature_input),
|
|
182
|
+
signature_agent: signature_agent && Agents.utf8(signature_agent)
|
|
183
|
+
}.compact
|
|
184
|
+
Sighting.new(Key.digest(user_agent, ip, signature_agent.to_s, signed), signed, fields,
|
|
185
|
+
fields.sum { |_name, value| value.bytesize })
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
def self.environment(request)
|
|
189
|
+
return request if request.is_a?(Hash)
|
|
190
|
+
return request.env if request.respond_to?(:env)
|
|
191
|
+
|
|
192
|
+
raise ArgumentError, "a Rack environment or request is required"
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
private
|
|
196
|
+
|
|
197
|
+
# A Web Bot Auth header as received, or nil when absent, empty,
|
|
198
|
+
# whitespace only or over the limit as sent.
|
|
199
|
+
def header(env, name)
|
|
200
|
+
value = env[name]
|
|
201
|
+
return nil unless value.is_a?(String)
|
|
202
|
+
|
|
203
|
+
sent = Agents.utf8(value)
|
|
204
|
+
sent.strip.empty? || sent.bytesize > MAX_HEADER_BYTES ? nil : value
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
# The Host as sent, or nil when absent, empty or over the limit: it is
|
|
208
|
+
# only read to check a signature, so the request is still reported.
|
|
209
|
+
def bounded(host)
|
|
210
|
+
return nil unless host.is_a?(String)
|
|
211
|
+
|
|
212
|
+
sent = Agents.utf8(host)
|
|
213
|
+
sent.empty? || sent.bytesize > MAX_HEADER_BYTES ? nil : sent
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
# The same trusted address the proxy forwards, canonical, or nil.
|
|
217
|
+
def client_address(env)
|
|
218
|
+
returned = begin
|
|
219
|
+
@client_ip.call(ProxyRequest.new(env, env["PATH_INFO"].to_s))
|
|
220
|
+
rescue *Config::CALLBACK_ERRORS => e
|
|
221
|
+
e
|
|
222
|
+
end
|
|
223
|
+
ip = Key.canonical_ip(returned)
|
|
224
|
+
return ip if ip
|
|
225
|
+
|
|
226
|
+
shown = returned.is_a?(Exception) ? "raised" : "returned"
|
|
227
|
+
@log.call("fingerly agent sightings: client_ip #{shown} #{returned.class}, not one IP " \
|
|
228
|
+
"address; such requests are not reported")
|
|
229
|
+
nil
|
|
230
|
+
end
|
|
231
|
+
end
|
|
232
|
+
end
|
|
233
|
+
end
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Fingerly
|
|
4
|
+
class AgentSightings
|
|
5
|
+
# The longest an answer is remembered, in seconds, whatever its ttl.
|
|
6
|
+
MAX_TTL = 86_400
|
|
7
|
+
|
|
8
|
+
# One request worth reporting: its cache key, whether it was signed, and
|
|
9
|
+
# the raw fields an {AgentSightingInput} is built from.
|
|
10
|
+
#
|
|
11
|
+
# @api private
|
|
12
|
+
Sighting = Struct.new(:key, :signed, :fields, :bytes)
|
|
13
|
+
|
|
14
|
+
# One pending report: the first sighting's fields and how many requests
|
|
15
|
+
# it stands for.
|
|
16
|
+
#
|
|
17
|
+
# @api private
|
|
18
|
+
Pending = Struct.new(:id, :key, :signed, :fields, :hits, :added_at, :bytes)
|
|
19
|
+
|
|
20
|
+
# The server's answers, by key, least recently used first.
|
|
21
|
+
#
|
|
22
|
+
# Not thread-safe on its own: {AgentSightings} holds its lock around every
|
|
23
|
+
# call.
|
|
24
|
+
#
|
|
25
|
+
# @api private
|
|
26
|
+
class AnswerCache
|
|
27
|
+
# @return [String, nil] the rules the entries were answered under
|
|
28
|
+
attr_reader :rules_version
|
|
29
|
+
|
|
30
|
+
def initialize(capacity)
|
|
31
|
+
@capacity = capacity
|
|
32
|
+
# A Hash keeps insertion order, so deleting and re-inserting a key on
|
|
33
|
+
# every hit leaves the least recently used one first.
|
|
34
|
+
@entries = {}
|
|
35
|
+
@rules_version = nil
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# @return [AgentSighting, nil] the answer, when present and unexpired
|
|
39
|
+
def get(key, now)
|
|
40
|
+
entry = @entries.delete(key)
|
|
41
|
+
return nil if entry.nil? || entry[1] <= now
|
|
42
|
+
|
|
43
|
+
@entries[key] = entry
|
|
44
|
+
entry[0]
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Stores a response's answers. A new +rules_version+ drops every entry
|
|
48
|
+
# first, an answer with a ttl of 0 is never kept, and none is kept longer
|
|
49
|
+
# than {MAX_TTL}.
|
|
50
|
+
#
|
|
51
|
+
# @param answers [Array(String, AgentSighting)] keys and their answers
|
|
52
|
+
def store(rules_version, answers, now)
|
|
53
|
+
@entries.clear if @rules_version && @rules_version != rules_version
|
|
54
|
+
@rules_version = rules_version
|
|
55
|
+
answers.each do |key, answer|
|
|
56
|
+
next unless answer.ttl.positive?
|
|
57
|
+
|
|
58
|
+
@entries.delete(key)
|
|
59
|
+
@entries[key] = [answer, now + [answer.ttl, MAX_TTL].min]
|
|
60
|
+
@entries.shift while @entries.size > @capacity
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def size = @entries.size
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Reports waiting to be sent, oldest first, bounded by item count.
|
|
68
|
+
#
|
|
69
|
+
# Unsigned sightings of one key fold into one item with a running count;
|
|
70
|
+
# signed ones are never folded, each is its own item. The bound counts
|
|
71
|
+
# the items of the batch in flight too, so a batch put back always fits.
|
|
72
|
+
#
|
|
73
|
+
# @api private
|
|
74
|
+
class PendingBuffer
|
|
75
|
+
# @return [Integer] the byte length of the pending items' fields
|
|
76
|
+
attr_reader :bytes
|
|
77
|
+
|
|
78
|
+
def initialize(max_items, max_count)
|
|
79
|
+
@max_items = max_items
|
|
80
|
+
@max_count = max_count
|
|
81
|
+
@items = {}
|
|
82
|
+
@bytes = 0
|
|
83
|
+
# The ids of the items taken and neither settled nor restored yet.
|
|
84
|
+
@in_flight = {}
|
|
85
|
+
@sequence = 0
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# @return [Symbol] +:folded+, +:added+ or +:dropped+ when full
|
|
89
|
+
def add(sighting, now)
|
|
90
|
+
unless sighting.signed
|
|
91
|
+
existing = @items[sighting.key]
|
|
92
|
+
if existing
|
|
93
|
+
existing.hits = [existing.hits + 1, @max_count].min
|
|
94
|
+
return :folded
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
return :dropped if @items.size + @in_flight.size >= @max_items
|
|
98
|
+
|
|
99
|
+
id = sighting.signed ? "#{sighting.key}/#{@sequence += 1}" : sighting.key
|
|
100
|
+
insert(Pending.new(id, sighting.key, sighting.signed, sighting.fields, 1, now,
|
|
101
|
+
sighting.bytes))
|
|
102
|
+
:added
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# Removes and returns the oldest items, up to +max_items+ and
|
|
106
|
+
# +max_bytes+, and always at least one.
|
|
107
|
+
def take(max_items, max_bytes)
|
|
108
|
+
batch = []
|
|
109
|
+
size = 0
|
|
110
|
+
@items.each_value do |item|
|
|
111
|
+
break if batch.size >= max_items
|
|
112
|
+
break if !batch.empty? && size + item.bytes > max_bytes
|
|
113
|
+
|
|
114
|
+
batch << item
|
|
115
|
+
size += item.bytes
|
|
116
|
+
end
|
|
117
|
+
batch.each do |item|
|
|
118
|
+
@items.delete(item.id)
|
|
119
|
+
@in_flight[item.id] = true
|
|
120
|
+
end
|
|
121
|
+
@bytes -= size
|
|
122
|
+
batch
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# Forgets a batch that was delivered or dropped. Settling a batch twice,
|
|
126
|
+
# or one already restored, changes nothing.
|
|
127
|
+
def settle(batch)
|
|
128
|
+
batch.each { |item| @in_flight.delete(item.id) }
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# Puts a batch that was not delivered back in front of everything
|
|
132
|
+
# newer, each item keeping when it was first seen. A key counted again
|
|
133
|
+
# meanwhile adds its count to the batch's item.
|
|
134
|
+
def restore(batch)
|
|
135
|
+
settle(batch)
|
|
136
|
+
newer = @items
|
|
137
|
+
@items = {}
|
|
138
|
+
@bytes = 0
|
|
139
|
+
batch.each do |item|
|
|
140
|
+
later = item.signed ? nil : newer.delete(item.id)
|
|
141
|
+
item.hits = [item.hits + later.hits, @max_count].min if later
|
|
142
|
+
insert(item)
|
|
143
|
+
end
|
|
144
|
+
newer.each_value { |item| insert(item) }
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def size = @items.size
|
|
148
|
+
|
|
149
|
+
def empty? = @items.empty?
|
|
150
|
+
|
|
151
|
+
# @return [Numeric, nil] when the oldest pending item was added
|
|
152
|
+
def oldest_at
|
|
153
|
+
first = @items.first
|
|
154
|
+
first && first[1].added_at
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def clear
|
|
158
|
+
@items.clear
|
|
159
|
+
@bytes = 0
|
|
160
|
+
@in_flight.clear
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
private
|
|
164
|
+
|
|
165
|
+
def insert(item)
|
|
166
|
+
@items[item.id] = item
|
|
167
|
+
@bytes += item.bytes
|
|
168
|
+
end
|
|
169
|
+
end
|
|
170
|
+
end
|
|
171
|
+
end
|
data/lib/fingerly/client.rb
CHANGED
|
@@ -30,6 +30,10 @@ module Fingerly
|
|
|
30
30
|
# written once per event
|
|
31
31
|
attr_reader :device_check
|
|
32
32
|
|
|
33
|
+
# @return [Agents] reports of the requests your server served, answered
|
|
34
|
+
# with what sent each one. {AgentSightings} uses it for you.
|
|
35
|
+
attr_reader :agents
|
|
36
|
+
|
|
33
37
|
# @param secret_key [String] a server-only key,
|
|
34
38
|
# +fly_sk_{environment}_…+, whose prefix names the environment read
|
|
35
39
|
# @param endpoint [String, nil] overrides the Fingerly API origin: a bare
|
|
@@ -63,6 +67,7 @@ module Fingerly
|
|
|
63
67
|
)
|
|
64
68
|
@events = Events.new(self)
|
|
65
69
|
@device_check = DeviceCheck.new(self)
|
|
70
|
+
@agents = Agents.new(self)
|
|
66
71
|
freeze
|
|
67
72
|
end
|
|
68
73
|
|
|
@@ -150,6 +155,28 @@ module Fingerly
|
|
|
150
155
|
decode(result.body)
|
|
151
156
|
end
|
|
152
157
|
|
|
158
|
+
# Performs one authenticated JSON POST and returns the decoded body.
|
|
159
|
+
#
|
|
160
|
+
# Never retried: the caller decides what a failure means.
|
|
161
|
+
#
|
|
162
|
+
# @raise [APIError] on any non-2xx response
|
|
163
|
+
# @api private
|
|
164
|
+
def post_json(path, body)
|
|
165
|
+
result = @transport.call(
|
|
166
|
+
Net::HTTP::Post, @base_path + path,
|
|
167
|
+
{
|
|
168
|
+
"x-api-key" => @secret_key,
|
|
169
|
+
"accept" => "application/json",
|
|
170
|
+
"content-type" => "application/json",
|
|
171
|
+
"user-agent" => USER_AGENT
|
|
172
|
+
}.freeze,
|
|
173
|
+
body
|
|
174
|
+
)
|
|
175
|
+
raise api_error(result) unless (200..299).cover?(result.status)
|
|
176
|
+
|
|
177
|
+
decode(result.body)
|
|
178
|
+
end
|
|
179
|
+
|
|
153
180
|
# Attempts in all for one DeviceCheck spend, the first included.
|
|
154
181
|
DEVICE_CHECK_ATTEMPTS = 3
|
|
155
182
|
|
|
@@ -247,7 +274,8 @@ module Fingerly
|
|
|
247
274
|
# tree.
|
|
248
275
|
details: error.key?("details") ? redact_tree(error["details"]) : nil,
|
|
249
276
|
request_id: redact(envelope["request_id"] || header(result, "x-request-id")),
|
|
250
|
-
retry_after: retry_after(header(result, "retry-after"))
|
|
277
|
+
retry_after: retry_after(header(result, "retry-after")),
|
|
278
|
+
rate_limit_scope: redact(header(result, "fingerly-ratelimit-scope"))
|
|
251
279
|
)
|
|
252
280
|
end
|
|
253
281
|
|
|
@@ -331,16 +359,28 @@ module Fingerly
|
|
|
331
359
|
# @param limit [Integer, nil] rows per page; the server caps it at 200
|
|
332
360
|
# @param visitor [String, nil] restricts the listing to one exact visitor
|
|
333
361
|
# @param level [String, nil] restricts it to +low+, +medium+ or +high+
|
|
362
|
+
# @param kind [String, nil] restricts it to one visitor kind, such as
|
|
363
|
+
# +ai_bot+; see {VisitorKind}. The server rejects a kind it does not know.
|
|
364
|
+
# @param ai_provider [String, nil] restricts it to AI agents from one
|
|
365
|
+
# operator, exactly as events name it in {AiAgent#provider}, such as
|
|
366
|
+
# +OpenAI+; the match is case-sensitive
|
|
367
|
+
# @param ai_purpose [String, nil] restricts it to AI agents with one
|
|
368
|
+
# purpose, such as +user_fetch+; see {AiPurpose}. The server rejects a
|
|
369
|
+
# purpose it does not know.
|
|
334
370
|
# @return [EventPage]
|
|
335
371
|
# @raise [APIError] on any non-2xx response
|
|
336
|
-
def list(from: nil, to: nil, page: nil, limit: nil, visitor: nil, level: nil
|
|
372
|
+
def list(from: nil, to: nil, page: nil, limit: nil, visitor: nil, level: nil,
|
|
373
|
+
kind: nil, ai_provider: nil, ai_purpose: nil)
|
|
337
374
|
query = {
|
|
338
375
|
"from" => from && Events.instant(from),
|
|
339
376
|
"to" => to && Events.instant(to),
|
|
340
377
|
"page" => page && Config.positive_int(page, "page"),
|
|
341
378
|
"limit" => limit && Config.positive_int(limit, "limit"),
|
|
342
379
|
"visitor" => visitor,
|
|
343
|
-
"level" => level
|
|
380
|
+
"level" => level,
|
|
381
|
+
"kind" => kind,
|
|
382
|
+
"ai_provider" => ai_provider,
|
|
383
|
+
"ai_purpose" => ai_purpose
|
|
344
384
|
}.compact
|
|
345
385
|
|
|
346
386
|
suffix = query.empty? ? "" : "?#{URI.encode_www_form(query)}"
|
|
@@ -502,18 +542,18 @@ module Fingerly
|
|
|
502
542
|
# Reads or writes Apple's two DeviceCheck bits for the device behind an iOS
|
|
503
543
|
# event. Reached as +fingerly.device_check+.
|
|
504
544
|
#
|
|
505
|
-
# Fingerly holds the DeviceCheck
|
|
506
|
-
# one hour, and spends
|
|
507
|
-
# each token as single-use, so a flow that
|
|
508
|
-
# such as a once-per-device free trial, reads
|
|
509
|
-
# writes
|
|
545
|
+
# Fingerly holds the two DeviceCheck tokens that came with an identification
|
|
546
|
+
# for one hour, and spends each once: a read spends the read token, a write
|
|
547
|
+
# the write token. Apple treats each token as single-use, so a flow that
|
|
548
|
+
# reads and then marks a device, such as a once-per-device free trial, reads
|
|
549
|
+
# and writes with the same request ID.
|
|
510
550
|
#
|
|
511
551
|
# A +503+ (+device_check_unavailable+) or a transport failure is retried
|
|
512
552
|
# with the same request; Apple lets a token be retried only that way, and
|
|
513
553
|
# the API answers +409 device_check_spent+ to a retry that differs.
|
|
514
554
|
#
|
|
515
555
|
# bits = fingerly.device_check.query(request_id)
|
|
516
|
-
# fingerly.device_check.write(
|
|
556
|
+
# fingerly.device_check.write(request_id, bit0: true) unless bits.bit0
|
|
517
557
|
class DeviceCheck
|
|
518
558
|
include Redacted
|
|
519
559
|
|
|
@@ -523,7 +563,7 @@ module Fingerly
|
|
|
523
563
|
freeze
|
|
524
564
|
end
|
|
525
565
|
|
|
526
|
-
# Spends the event's held token to read the device's two bits.
|
|
566
|
+
# Spends the event's held read token to read the device's two bits.
|
|
527
567
|
#
|
|
528
568
|
# @param request_id [String] the +request_id+ of an iOS identification
|
|
529
569
|
# made within the last hour
|
|
@@ -538,8 +578,8 @@ module Fingerly
|
|
|
538
578
|
)
|
|
539
579
|
end
|
|
540
580
|
|
|
541
|
-
# Spends the event's held token to set +bit0+, +bit1+ or both. A bit
|
|
542
|
-
# nil keeps its value.
|
|
581
|
+
# Spends the event's held write token to set +bit0+, +bit1+ or both. A bit
|
|
582
|
+
# left nil keeps its value.
|
|
543
583
|
#
|
|
544
584
|
# @param request_id [String] the +request_id+ of an iOS identification
|
|
545
585
|
# made within the last hour
|
|
@@ -573,4 +613,75 @@ module Fingerly
|
|
|
573
613
|
[]
|
|
574
614
|
end
|
|
575
615
|
end
|
|
616
|
+
|
|
617
|
+
# Reports the requests your server served, as raw input, and answers what
|
|
618
|
+
# sent each one. Reached as +fingerly.agents+.
|
|
619
|
+
#
|
|
620
|
+
# AI crawlers and fetchers that never run a page's JavaScript are seen only
|
|
621
|
+
# this way. {AgentSightings} batches, counts and remembers these answers for
|
|
622
|
+
# you; call this directly only to build that yourself.
|
|
623
|
+
class Agents
|
|
624
|
+
include Redacted
|
|
625
|
+
|
|
626
|
+
# The most requests one call may report.
|
|
627
|
+
MAX_SIGHTINGS = 200
|
|
628
|
+
|
|
629
|
+
# @api private
|
|
630
|
+
def initialize(client)
|
|
631
|
+
@client = client
|
|
632
|
+
freeze
|
|
633
|
+
end
|
|
634
|
+
|
|
635
|
+
# Reports up to {MAX_SIGHTINGS} requests in one call.
|
|
636
|
+
#
|
|
637
|
+
# Never retried: a call the server may have counted must not be counted
|
|
638
|
+
# twice. An item the server could not use is answered
|
|
639
|
+
# {VisitorKind::UNKNOWN} with a ttl of 0 in its own position, and is
|
|
640
|
+
# neither classified nor counted; the others are answered as usual.
|
|
641
|
+
#
|
|
642
|
+
# @param items [Array<AgentSightingInput>] the requests, answered in the
|
|
643
|
+
# same order
|
|
644
|
+
# @return [AgentSightingsReport]
|
|
645
|
+
# @raise [ConfigurationError] for no items, more than {MAX_SIGHTINGS}, or
|
|
646
|
+
# an item that is not an {AgentSightingInput}; nothing is sent
|
|
647
|
+
# @raise [APIError] on any non-2xx response: +429+ carries
|
|
648
|
+
# {APIError#retry_after} and {APIError#rate_limit_scope}, +422+ means no
|
|
649
|
+
# item in the batch was usable
|
|
650
|
+
# @raise [TimeoutError, ConnectionError] when no answer arrived
|
|
651
|
+
def report_sightings(items)
|
|
652
|
+
unless items.is_a?(Array) && (1..MAX_SIGHTINGS).cover?(items.size) &&
|
|
653
|
+
items.all?(AgentSightingInput)
|
|
654
|
+
raise ConfigurationError,
|
|
655
|
+
"items must be 1 to #{MAX_SIGHTINGS} Fingerly::AgentSightingInput values"
|
|
656
|
+
end
|
|
657
|
+
|
|
658
|
+
body = JSON.generate({ "items" => items.map { |item| Agents.wire(item) } })
|
|
659
|
+
AgentSightingsReport.new(@client.post_json("/agents/sightings", body))
|
|
660
|
+
end
|
|
661
|
+
|
|
662
|
+
# One item as JSON can carry it: a header that is not valid UTF-8 has its
|
|
663
|
+
# bad bytes replaced, since JSON strings are Unicode.
|
|
664
|
+
#
|
|
665
|
+
# @api private
|
|
666
|
+
def self.wire(item)
|
|
667
|
+
item.to_h.transform_values { |value| value.is_a?(String) ? utf8(value) : value }
|
|
668
|
+
end
|
|
669
|
+
|
|
670
|
+
# A string as JSON carries it: its bytes read as UTF-8, each invalid
|
|
671
|
+
# sequence replaced by U+FFFD, whatever encoding it was tagged with.
|
|
672
|
+
#
|
|
673
|
+
# @api private
|
|
674
|
+
def self.utf8(value)
|
|
675
|
+
return value if value.encoding == Encoding::UTF_8 && value.valid_encoding?
|
|
676
|
+
|
|
677
|
+
text = value.dup.force_encoding(Encoding::UTF_8)
|
|
678
|
+
text.valid_encoding? ? text : text.scrub
|
|
679
|
+
end
|
|
680
|
+
|
|
681
|
+
private
|
|
682
|
+
|
|
683
|
+
def redacted_fields
|
|
684
|
+
[]
|
|
685
|
+
end
|
|
686
|
+
end
|
|
576
687
|
end
|
data/lib/fingerly/config.rb
CHANGED
|
@@ -27,6 +27,12 @@ module Fingerly
|
|
|
27
27
|
# The one Fingerly API origin.
|
|
28
28
|
DEFAULT_ENDPOINT = "https://api.fingerly.io"
|
|
29
29
|
|
|
30
|
+
# What a caller's callback or logger may raise and the SDK still contains.
|
|
31
|
+
# Beyond StandardError: a +NotImplementedError+ left in a callback, or a
|
|
32
|
+
# recursion too deep, would otherwise fail the application's response.
|
|
33
|
+
# Exit, interrupt and out-of-memory are left to propagate.
|
|
34
|
+
CALLBACK_ERRORS = [StandardError, ScriptError, SystemStackError].freeze
|
|
35
|
+
|
|
30
36
|
# The environment a Fingerly key is scoped to.
|
|
31
37
|
Scope = Struct.new(:environment)
|
|
32
38
|
|