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.
@@ -26,10 +26,17 @@ module Fingerly
26
26
  # @return [Events] event reads under this client's secret key
27
27
  attr_reader :events
28
28
 
29
+ # @return [DeviceCheck] the DeviceCheck bits of iOS events, read or
30
+ # written once per event
31
+ attr_reader :device_check
32
+
29
33
  # @param secret_key [String] a server-only key,
30
34
  # +fly_sk_{environment}_…+, whose prefix names the environment read
31
- # @param endpoint [String, nil] overrides the Fingerly API origin, for a
32
- # local or self-hosted API
35
+ # @param endpoint [String, nil] overrides the Fingerly API origin: a bare
36
+ # origin, scheme, host and optional port, and +https+ only
37
+ # @param allow_insecure_loopback [Boolean] lets +endpoint+ be a plain
38
+ # +http+ origin on 127.0.0.1, localhost or [::1], for local development
39
+ # and tests. Off by default.
33
40
  # @param api_version [String] the API route version
34
41
  # @param timeout [Numeric] the deadline for each request in seconds,
35
42
  # covering the response body
@@ -39,11 +46,12 @@ module Fingerly
39
46
  # @raise [ConfigurationError] if a key, endpoint, version or timeout is
40
47
  # invalid. Nothing is sent until then.
41
48
  def initialize(secret_key:, endpoint: nil, api_version: DEFAULT_API_VERSION,
42
- timeout: DEFAULT_TIMEOUT, configure_http: nil)
49
+ timeout: DEFAULT_TIMEOUT, configure_http: nil, allow_insecure_loopback: false)
43
50
  # The key is validated even when an endpoint is given, so a public, proxy
44
51
  # or management key can never reach an API that would accept it.
45
52
  Config.parse_key(secret_key, Config::SECRET)
46
- origin = Config.normalize_endpoint(endpoint || Config::DEFAULT_ENDPOINT)
53
+ origin = Config.normalize_origin(endpoint || Config::DEFAULT_ENDPOINT, "endpoint",
54
+ allow_insecure_loopback: allow_insecure_loopback == true)
47
55
 
48
56
  @secret_key = secret_key
49
57
  @origin = origin
@@ -54,6 +62,7 @@ module Fingerly
54
62
  configure_http: configure_http
55
63
  )
56
64
  @events = Events.new(self)
65
+ @device_check = DeviceCheck.new(self)
57
66
  freeze
58
67
  end
59
68
 
@@ -84,8 +93,129 @@ module Fingerly
84
93
  decode(result.body)
85
94
  end
86
95
 
96
+ # Performs one authenticated DeviceCheck spend and returns the decoded
97
+ # body.
98
+ #
99
+ # A held DeviceCheck token may be retried only with the same request, so a
100
+ # +503+ or a transport failure is retried with exactly these bytes, at
101
+ # most {DEVICE_CHECK_ATTEMPTS} times in all. Nothing else is retried.
102
+ #
103
+ # @param method [Class] +Net::HTTP::Post+ or +Net::HTTP::Put+
104
+ # @param body [String, nil] the JSON body, or nil for none
105
+ # @api private
106
+ def spend_device_check(method, path, body)
107
+ headers = {
108
+ "x-api-key" => @secret_key,
109
+ "accept" => "application/json",
110
+ "user-agent" => USER_AGENT
111
+ }
112
+ if body
113
+ headers["content-type"] = "application/json"
114
+ else
115
+ # No body at all, stated, so nothing in between waits for one.
116
+ headers["content-length"] = "0"
117
+ end
118
+ headers.freeze
119
+
120
+ result = with_device_check_retries do
121
+ @transport.call(method, @base_path + path, headers, body)
122
+ end
123
+ raise device_check_error(result) unless (200..299).cover?(result.status)
124
+
125
+ decode(result.body)
126
+ end
127
+
128
+ # Performs one authenticated consume, a POST with no body, and returns
129
+ # the decoded body.
130
+ #
131
+ # Never retried, like a read.
132
+ #
133
+ # @raise [EventAlreadyConsumedError] on +409 event_already_consumed+
134
+ # @raise [APIError] on any other non-2xx response
135
+ # @api private
136
+ def post_consume(path)
137
+ result = @transport.call(
138
+ Net::HTTP::Post, @base_path + path,
139
+ {
140
+ "x-api-key" => @secret_key,
141
+ "accept" => "application/json",
142
+ "user-agent" => USER_AGENT,
143
+ # No body at all, stated, so nothing in between waits for one.
144
+ "content-length" => "0"
145
+ }.freeze,
146
+ nil
147
+ )
148
+ raise consume_error(result) unless (200..299).cover?(result.status)
149
+
150
+ decode(result.body)
151
+ end
152
+
153
+ # Attempts in all for one DeviceCheck spend, the first included.
154
+ DEVICE_CHECK_ATTEMPTS = 3
155
+
156
+ # Seconds to wait before each retry, when the answer named no
157
+ # +Retry-After+.
158
+ DEVICE_CHECK_BACKOFF = [0.25, 0.5].freeze
159
+
160
+ # The longest +Retry-After+ honoured between attempts.
161
+ DEVICE_CHECK_MAX_WAIT = 2
162
+
87
163
  private
88
164
 
165
+ def with_device_check_retries
166
+ attempt = 0
167
+ loop do
168
+ attempt += 1
169
+ last = attempt >= DEVICE_CHECK_ATTEMPTS
170
+ begin
171
+ result = yield
172
+ rescue TimeoutError, ConnectionError
173
+ raise if last
174
+
175
+ sleep DEVICE_CHECK_BACKOFF[attempt - 1]
176
+ next
177
+ end
178
+ return result unless result.status == 503 && !last
179
+
180
+ wait = retry_after(header(result, "retry-after"))
181
+ sleep(wait ? [wait, DEVICE_CHECK_MAX_WAIT].min : DEVICE_CHECK_BACKOFF[attempt - 1])
182
+ end
183
+ end
184
+
185
+ def device_check_error(result)
186
+ error = api_error(result)
187
+ DeviceCheckError.new(
188
+ status: error.status, code: error.code, details: error.details,
189
+ request_id: error.request_id, retry_after: error.retry_after
190
+ )
191
+ end
192
+
193
+ # The already-consumed answer's shape is read tolerantly: its code from
194
+ # the error envelope or the top level, and its +consumed_at+ from the top
195
+ # level, the envelope, or a +details+ entry.
196
+ def consume_error(result)
197
+ error = api_error(result)
198
+ envelope = error_envelope(result.body)
199
+ code = error.code || (envelope["code"].is_a?(String) ? redact(envelope["code"]) : nil)
200
+ return error unless result.status == 409 && code == EventAlreadyConsumedError::CODE
201
+
202
+ EventAlreadyConsumedError.new(
203
+ status: error.status, code: code, details: error.details,
204
+ request_id: error.request_id, retry_after: error.retry_after,
205
+ consumed_at: consumed_at(envelope, error.details)
206
+ )
207
+ end
208
+
209
+ def consumed_at(envelope, details)
210
+ nested = envelope["error"].is_a?(Hash) ? envelope["error"]["consumed_at"] : nil
211
+ entry = details.is_a?(Array) &&
212
+ details.find { |item| item.is_a?(Hash) && item["field"] == "consumed_at" }
213
+ found = [envelope["consumed_at"], nested, entry && entry["issue"]].find do |value|
214
+ value.is_a?(String) && !value.empty?
215
+ end
216
+ redact(found)
217
+ end
218
+
89
219
  def redacted_fields
90
220
  [["endpoint", @origin + @base_path], ["secret_key", Redacted::MARK]]
91
221
  end
@@ -187,14 +317,7 @@ module Fingerly
187
317
  # past retention.
188
318
  # @raise [TimeoutError] if the request exceeds the client timeout
189
319
  def get(request_id)
190
- # URL parsers resolve a dot segment even when it is percent-encoded, so
191
- # escaping cannot keep these in the path: "." and the empty id would name
192
- # the list route, and ".." a route above it, secret key attached.
193
- if ["", ".", ".."].include?(request_id.to_s)
194
- raise ConfigurationError, "request_id is not a Fingerly request id"
195
- end
196
-
197
- Event.new(@client.get("/events/#{Events.escape(request_id)}"))
320
+ Event.new(@client.get("/events/#{Events.segment(request_id)}"))
198
321
  end
199
322
 
200
323
  # Lists events within the retention window, newest first.
@@ -224,6 +347,124 @@ module Fingerly
224
347
  EventPage.new(@client.get("/events#{suffix}"))
225
348
  end
226
349
 
350
+ # The age past which {#verify} answers +too_old+, in seconds.
351
+ DEFAULT_MAX_AGE_SECONDS = 300
352
+
353
+ # Marks an event consumed, once. Every later call for the same event
354
+ # raises {EventAlreadyConsumedError}, so one event backs one decision.
355
+ #
356
+ # Never retried.
357
+ #
358
+ # @param request_id [String] the +request_id+ returned by identification
359
+ # @return [EventConsumption]
360
+ # @raise [EventAlreadyConsumedError] when the event was already consumed;
361
+ # see {EventAlreadyConsumedError#consumed_at}
362
+ # @raise [APIError] on any other non-2xx response, such as
363
+ # +404 event_not_found+
364
+ # @raise [TimeoutError] if the request exceeds the client timeout
365
+ def consume(request_id)
366
+ EventConsumption.new(@client.post_consume(consume_path(Events.segment(request_id))))
367
+ end
368
+
369
+ # Reads an event and checks it can back a backend action, then consumes
370
+ # it.
371
+ #
372
+ # The checks run in this order and stop at the first failure, which
373
+ # becomes {EventVerification#reason}: +not_found+, +too_old+ (older than
374
+ # +max_age_seconds+, or with no readable +occurred_at+), +tag_mismatch+
375
+ # (only when +tag+ is given), +unidentifiable+ (empty +visitor_id+),
376
+ # +unscored+ (no +suspect_score+), then +already_consumed+ from the
377
+ # consume, which runs last and only when everything else passed. The score
378
+ # itself is never judged: that policy is the caller's.
379
+ #
380
+ # @param request_id [String] the +request_id+ returned by identification
381
+ # @param max_age_seconds [Integer] the oldest event accepted, in seconds
382
+ # @param tag [String, nil] the tag the event must carry exactly; nil
383
+ # skips the check
384
+ # @param consume [Boolean] false skips the consume
385
+ # @return [EventVerification]
386
+ # @raise [ConfigurationError] for an invalid option or request id; nothing
387
+ # is sent
388
+ # @raise [APIError] for any failure other than +404 event_not_found+ and
389
+ # +409 event_already_consumed+, +404 event_pending+ included: a pending
390
+ # event is not a verdict
391
+ # @raise [TimeoutError, ConnectionError] as for {#get}
392
+ def verify(request_id, max_age_seconds: DEFAULT_MAX_AGE_SECONDS, tag: nil, consume: true)
393
+ Events.verify_options(max_age_seconds, tag, consume)
394
+ segment = Events.segment(request_id)
395
+
396
+ begin
397
+ payload = @client.get("/events/#{segment}")
398
+ rescue APIError => e
399
+ raise unless e.event_not_found?
400
+
401
+ return EventVerification.new(reason: EventVerification::NOT_FOUND, event: nil)
402
+ end
403
+
404
+ event = Event.new(payload, lenient_time: true)
405
+ reason = Events.failed_check(event, max_age_seconds, tag)
406
+ return EventVerification.new(reason: reason || "", event: event) if reason || !consume
407
+
408
+ begin
409
+ @client.post_consume(consume_path(segment))
410
+ rescue EventAlreadyConsumedError
411
+ return EventVerification.new(reason: EventVerification::ALREADY_CONSUMED, event: event)
412
+ rescue APIError => e
413
+ raise unless e.event_not_found?
414
+
415
+ return EventVerification.new(reason: EventVerification::NOT_FOUND, event: nil)
416
+ end
417
+ EventVerification.new(reason: "", event: event)
418
+ end
419
+
420
+ # @raise [ConfigurationError] for an option {#verify} cannot apply
421
+ # @api private
422
+ def self.verify_options(max_age_seconds, tag, consume)
423
+ unless max_age_seconds.is_a?(Integer) && max_age_seconds.positive?
424
+ raise ConfigurationError, "max_age_seconds must be a positive Integer"
425
+ end
426
+ # An empty tag would match every untagged event, so it is refused rather
427
+ # than read as no check.
428
+ unless tag.nil? || (tag.is_a?(String) && !tag.empty?)
429
+ raise ConfigurationError, "tag must be a non-empty String or nil"
430
+ end
431
+ return if [true, false].include?(consume)
432
+
433
+ raise ConfigurationError, "consume must be true or false"
434
+ end
435
+
436
+ # The first check {#verify} fails before the consume, or nil.
437
+ #
438
+ # @api private
439
+ def self.failed_check(event, max_age_seconds, tag)
440
+ occurred_at = event.occurred_at
441
+ # A future time passes; a missing or unreadable one fails closed.
442
+ if occurred_at.nil? || Time.now - occurred_at > max_age_seconds
443
+ return EventVerification::TOO_OLD
444
+ end
445
+
446
+ return EventVerification::TAG_MISMATCH if tag && (event.tag || "") != tag
447
+ return EventVerification::UNIDENTIFIABLE if event.visitor_id.nil? || event.visitor_id.empty?
448
+ return EventVerification::UNSCORED unless event.scored?
449
+
450
+ nil
451
+ end
452
+
453
+ # A request id as one escaped path segment.
454
+ #
455
+ # @raise [ConfigurationError] for an id no escaping can keep in its segment
456
+ # @api private
457
+ def self.segment(request_id)
458
+ # URL parsers resolve a dot segment even when it is percent-encoded, so
459
+ # escaping cannot keep these in the path: "." and the empty id would name
460
+ # the list route, and ".." a route above it, secret key attached.
461
+ if ["", ".", ".."].include?(request_id.to_s)
462
+ raise ConfigurationError, "request_id is not a Fingerly request id"
463
+ end
464
+
465
+ escape(request_id)
466
+ end
467
+
227
468
  # Percent-encodes a request id into exactly one path segment.
228
469
  #
229
470
  # Only RFC 3986 unreserved characters survive, so a slash cannot escape the
@@ -249,6 +490,85 @@ module Fingerly
249
490
 
250
491
  private
251
492
 
493
+ def consume_path(segment)
494
+ "/events/#{segment}/consume"
495
+ end
496
+
497
+ def redacted_fields
498
+ []
499
+ end
500
+ end
501
+
502
+ # Reads or writes Apple's two DeviceCheck bits for the device behind an iOS
503
+ # event. Reached as +fingerly.device_check+.
504
+ #
505
+ # Fingerly holds the DeviceCheck token that came with an identification for
506
+ # one hour, and spends it once: a read or a write, never both. Apple treats
507
+ # each token as single-use, so a flow that reads and then marks a device,
508
+ # such as a once-per-device free trial, reads on one identification and
509
+ # writes on the next.
510
+ #
511
+ # A +503+ (+device_check_unavailable+) or a transport failure is retried
512
+ # with the same request; Apple lets a token be retried only that way, and
513
+ # the API answers +409 device_check_spent+ to a retry that differs.
514
+ #
515
+ # bits = fingerly.device_check.query(request_id)
516
+ # fingerly.device_check.write(next_request_id, bit0: true) unless bits.bit0
517
+ class DeviceCheck
518
+ include Redacted
519
+
520
+ # @api private
521
+ def initialize(client)
522
+ @client = client
523
+ freeze
524
+ end
525
+
526
+ # Spends the event's held token to read the device's two bits.
527
+ #
528
+ # @param request_id [String] the +request_id+ of an iOS identification
529
+ # made within the last hour
530
+ # @return [DeviceCheckBits]
531
+ # @raise [DeviceCheckError] on any non-2xx response; its predicates name
532
+ # the documented codes
533
+ # @raise [TimeoutError, ConnectionError] when every attempt failed to get
534
+ # an answer
535
+ def query(request_id)
536
+ DeviceCheckBits.new(
537
+ @client.spend_device_check(Net::HTTP::Post, "#{path(request_id)}/query", nil)
538
+ )
539
+ end
540
+
541
+ # Spends the event's held token to set +bit0+, +bit1+ or both. A bit left
542
+ # nil keeps its value.
543
+ #
544
+ # @param request_id [String] the +request_id+ of an iOS identification
545
+ # made within the last hour
546
+ # @param bit0 [Boolean, nil] the value for the first bit
547
+ # @param bit1 [Boolean, nil] the value for the second bit
548
+ # @return [DeviceCheckWrite] the bits Apple accepted
549
+ # @raise [ConfigurationError] when neither bit is given, or a bit is not
550
+ # true, false or nil; nothing is sent
551
+ # @raise [DeviceCheckError] on any non-2xx response
552
+ # @raise [TimeoutError, ConnectionError] when every attempt failed to get
553
+ # an answer
554
+ def write(request_id, bit0: nil, bit1: nil)
555
+ bits = { "bit0" => bit0, "bit1" => bit1 }.compact
556
+ raise ConfigurationError, "name bit0, bit1 or both" if bits.empty?
557
+ unless bits.values.all? { |value| [true, false].include?(value) }
558
+ raise ConfigurationError, "bit0 and bit1 must be true, false or nil"
559
+ end
560
+
561
+ DeviceCheckWrite.new(
562
+ @client.spend_device_check(Net::HTTP::Put, path(request_id), JSON.generate(bits))
563
+ )
564
+ end
565
+
566
+ private
567
+
568
+ def path(request_id)
569
+ "/events/#{Events.segment(request_id)}/device-check"
570
+ end
571
+
252
572
  def redacted_fields
253
573
  []
254
574
  end
@@ -61,28 +61,46 @@ module Fingerly
61
61
  Scope.new(match[2])
62
62
  end
63
63
 
64
- # Validates a caller-supplied API origin.
64
+ # Hosts a plain HTTP origin may name, and only with
65
+ # +allow_insecure_loopback: true+.
66
+ LOOPBACK_HOSTS = %w[127.0.0.1 localhost [::1]].freeze
67
+
68
+ # Validates a caller-supplied API origin: the client's +endpoint+ or the
69
+ # proxy's +upstream+, both of which carry a key.
65
70
  #
66
- # Credentials, queries and fragments are refused: they would be attached to
67
- # every authenticated request, and embedded credentials would leak on a
68
- # redirect.
71
+ # Only a bare origin is accepted: scheme, host and an optional port. The
72
+ # scheme is +https+; plain +http+ is accepted only for 127.0.0.1,
73
+ # localhost or [::1], and only when the caller opts in for development.
74
+ # The origin returned is rebuilt from the parsed parts, never the input,
75
+ # and no error repeats the value, which may have been pasted from
76
+ # somewhere it should not be.
69
77
  #
70
- # @return [String] the origin without trailing slashes
71
- # @raise [ConfigurationError] if the URL is malformed or carries any of those
72
- def normalize_endpoint(value)
78
+ # @param option [String] the option's name, for the error message
79
+ # @return [String] the origin, such as +https://api.fingerly.io+
80
+ # @raise [ConfigurationError] if the value is anything else
81
+ def normalize_origin(value, option, allow_insecure_loopback: false)
82
+ shape = "#{option} must be https://host or https://host:port, with no path, " \
83
+ "query, fragment, credentials, whitespace or control characters"
84
+ printable = value.is_a?(String) && value.b.match?(/\A[\x21-\x7e]+\z/)
85
+ raise ConfigurationError, shape unless printable
86
+
73
87
  uri = begin
74
- URI.parse(value.to_s)
88
+ URI.parse(value)
75
89
  rescue URI::InvalidURIError
76
90
  nil
77
91
  end
78
- usable = uri.is_a?(URI::HTTP) && !uri.host.to_s.empty? &&
79
- uri.userinfo.nil? && uri.query.nil? && uri.fragment.nil?
80
- unless usable
92
+ bare = uri.is_a?(URI::HTTP) && !uri.host.to_s.empty? && uri.userinfo.nil? &&
93
+ uri.query.nil? && uri.fragment.nil? && ["", "/"].include?(uri.path.to_s)
94
+ raise ConfigurationError, shape unless bare
95
+
96
+ if uri.scheme == "http" && !(allow_insecure_loopback && LOOPBACK_HOSTS.include?(uri.host))
81
97
  raise ConfigurationError,
82
- "endpoint must be an HTTP(S) URL without credentials, query, or fragment"
98
+ "#{option} must use https; plain http is allowed only for 127.0.0.1, " \
99
+ "localhost or [::1] with allow_insecure_loopback: true"
83
100
  end
84
101
 
85
- value.to_s.sub(%r{/+\z}, "")
102
+ port = uri.port == uri.default_port ? "" : ":#{uri.port}"
103
+ "#{uri.scheme}://#{uri.host}#{port}"
86
104
  end
87
105
 
88
106
  # Validates an API route version before it is spliced into a URL.
@@ -81,6 +81,107 @@ module Fingerly
81
81
  def pending?
82
82
  status == 404 && code == "event_pending"
83
83
  end
84
+
85
+ # Whether this is a consume for an event that was already consumed
86
+ # (+409 event_already_consumed+). Such an answer raises
87
+ # {EventAlreadyConsumedError}.
88
+ #
89
+ # @return [Boolean]
90
+ def event_already_consumed?
91
+ status == 409 && code == EventAlreadyConsumedError::CODE
92
+ end
93
+ end
94
+
95
+ # Raised when +fingerly.events.consume+ finds the event already consumed
96
+ # (+409 event_already_consumed+).
97
+ #
98
+ # It is an {APIError}, so +rescue Fingerly::APIError+ still catches it.
99
+ #
100
+ # begin
101
+ # fingerly.events.consume(request_id)
102
+ # rescue Fingerly::EventAlreadyConsumedError => e
103
+ # return "refuse" # another decision already used it, at e.consumed_at
104
+ # end
105
+ class EventAlreadyConsumedError < APIError
106
+ CODE = "event_already_consumed"
107
+
108
+ # @return [String, nil] when the event was first consumed, as the API
109
+ # sent it (RFC 3339), or nil when the answer did not say
110
+ attr_reader :consumed_at
111
+
112
+ # @api private
113
+ def initialize(consumed_at: nil, **)
114
+ super(**)
115
+ @consumed_at = consumed_at
116
+ end
117
+ end
118
+
119
+ # Raised for any non-2xx answer to a DeviceCheck read or write.
120
+ #
121
+ # It is an {APIError}, so +rescue Fingerly::APIError+ still catches it; each
122
+ # documented code has its own predicate.
123
+ #
124
+ # begin
125
+ # bits = fingerly.device_check.query(request_id)
126
+ # rescue Fingerly::DeviceCheckError => e
127
+ # raise unless e.not_held? || e.spent? || e.apple_rejected?
128
+ #
129
+ # bits = nil # no answer, not a verdict: decide without the bits
130
+ # end
131
+ class DeviceCheckError < APIError
132
+ NOT_HELD = "device_check_not_held"
133
+ SPENT = "device_check_spent"
134
+ BUSY = "device_check_busy"
135
+ CREDENTIAL_UNAVAILABLE = "credential_unavailable"
136
+ BITS_REQUIRED = "bits_required"
137
+ APPLE_REJECTED = "apple_rejected"
138
+ UNAVAILABLE = "device_check_unavailable"
139
+
140
+ # @return [Integer, nil] Apple's HTTP status for +apple_rejected+, from
141
+ # the +apple_status+ entry of {#details}; nil for any other code
142
+ attr_reader :apple_status
143
+
144
+ # @api private
145
+ def initialize(**)
146
+ super
147
+ @apple_status = parse_apple_status
148
+ end
149
+
150
+ # +404+: no token is held for that event. Decide without the bits.
151
+ def not_held? = status == 404 && code == NOT_HELD
152
+
153
+ # +409+: the token was already used, or this was a retry that is not the
154
+ # request the token was first used for.
155
+ def spent? = status == 409 && code == SPENT
156
+
157
+ # +409+: another call is using the token right now.
158
+ def busy? = status == 409 && code == BUSY
159
+
160
+ # +409+: the project's Apple key is missing, refused, or has DeviceCheck
161
+ # off. The token is kept: fix the key, then retry the same request.
162
+ def credential_unavailable? = status == 409 && code == CREDENTIAL_UNAVAILABLE
163
+
164
+ # +422+: a write named neither bit.
165
+ def bits_required? = status == 422 && code == BITS_REQUIRED
166
+
167
+ # +422+: Apple rejected the token, which is now used up. See
168
+ # {#apple_status}.
169
+ def apple_rejected? = status == 422 && code == APPLE_REJECTED
170
+
171
+ # +503+: Apple or Fingerly's storage could not answer, after the retries
172
+ # the client already made. The token is kept: retry the same request
173
+ # within the hour.
174
+ def unavailable? = status == 503 && code == UNAVAILABLE
175
+
176
+ private
177
+
178
+ def parse_apple_status
179
+ return nil unless code == APPLE_REJECTED && details.is_a?(Array)
180
+
181
+ entry = details.find { |item| item.is_a?(Hash) && item["field"] == "apple_status" }
182
+ issue = entry && entry["issue"]
183
+ issue.is_a?(String) && issue.match?(/\A\d{3}\z/) ? Integer(issue, 10) : nil
184
+ end
84
185
  end
85
186
 
86
187
  # Raised when a request does not finish within its time limit.