graphql-armory 0.1.0.pre8 → 0.1.0.pre10

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.
Files changed (54) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +64 -0
  3. data/README.md +7 -7
  4. data/docs/authorization.md +123 -5
  5. data/docs/encrypted-ids.md +1 -1
  6. data/docs/keyset-connections.md +28 -4
  7. data/docs/persisted-queries.md +111 -19
  8. data/docs/rate-limiting.md +37 -13
  9. data/docs/telemetry.md +31 -8
  10. data/exe/graphql-armory-publish +6 -0
  11. data/lib/graphql/armory/authorization/adapters/cancan.rb +7 -3
  12. data/lib/graphql/armory/authorization/adapters/pundit.rb +8 -1
  13. data/lib/graphql/armory/authorization/audit/baseline.rb +191 -0
  14. data/lib/graphql/armory/authorization/audit/command.rb +57 -8
  15. data/lib/graphql/armory/authorization/audit/findings.rb +3 -2
  16. data/lib/graphql/armory/authorization/audit/interface_rules.rb +4 -1
  17. data/lib/graphql/armory/authorization/audit/observed_rules.rb +58 -0
  18. data/lib/graphql/armory/authorization/audit/payload_reuse.rb +95 -0
  19. data/lib/graphql/armory/authorization/audit/plain_resolvers.rb +85 -0
  20. data/lib/graphql/armory/authorization/audit/reach.rb +75 -0
  21. data/lib/graphql/armory/authorization/audit/report.rb +7 -1
  22. data/lib/graphql/armory/authorization/audit/type_rules.rb +19 -2
  23. data/lib/graphql/armory/authorization/audit.rb +12 -4
  24. data/lib/graphql/armory/authorization/authorize.rb +28 -8
  25. data/lib/graphql/armory/authorization/configuration.rb +4 -3
  26. data/lib/graphql/armory/authorization/definitions.rb +7 -0
  27. data/lib/graphql/armory/authorization/integration/field.rb +26 -4
  28. data/lib/graphql/armory/authorization/integration/object.rb +8 -0
  29. data/lib/graphql/armory/authorization/integration/resolver.rb +2 -0
  30. data/lib/graphql/armory/authorization/integration.rb +14 -3
  31. data/lib/graphql/armory/authorization/rspec.rb +10 -4
  32. data/lib/graphql/armory/authorization/rule.rb +19 -3
  33. data/lib/graphql/armory/authorization/scope.rb +6 -6
  34. data/lib/graphql/armory/authorization.rb +1 -1
  35. data/lib/graphql/armory/ids.rb +11 -11
  36. data/lib/graphql/armory/keyset/encoder_check.rb +113 -0
  37. data/lib/graphql/armory/keyset.rb +23 -3
  38. data/lib/graphql/armory/persisted_queries/manifest.rb +2 -0
  39. data/lib/graphql/armory/persisted_queries/manifests.rb +69 -0
  40. data/lib/graphql/armory/persisted_queries/publisher.rb +127 -0
  41. data/lib/graphql/armory/persisted_queries/redis_store.rb +137 -0
  42. data/lib/graphql/armory/persisted_queries.rb +55 -16
  43. data/lib/graphql/armory/railtie.rb +10 -0
  44. data/lib/graphql/armory/rate_limits/analysis_guard.rb +175 -0
  45. data/lib/graphql/armory/rate_limits/concurrency.rb +93 -14
  46. data/lib/graphql/armory/rate_limits/invalid_queries.rb +75 -0
  47. data/lib/graphql/armory/rate_limits/points.rb +129 -15
  48. data/lib/graphql/armory/rate_limits/time.rb +140 -22
  49. data/lib/graphql/armory/rate_limits.rb +30 -5
  50. data/lib/graphql/armory/telemetry.rb +71 -9
  51. data/lib/graphql/armory/version.rb +1 -1
  52. data/lib/graphql/armory.rb +1 -0
  53. data/lib/tasks/graphql_armory.rake +11 -4
  54. metadata +17 -3
@@ -0,0 +1,175 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module RateLimits
6
+ # graphql-ruby discards an ExecutionError raised during analysis, drops what every analyzer answered, and runs the query.
7
+ # A client can choose that by field order when a `complexity:` lambda raises. So on such a raise each limiter still
8
+ # decides: a refusal already given stands, a limiter not asked yet is asked on its own, and a limiter that cannot answer
9
+ # refuses the query in hard mode and records `charged: false` in soft mode. Every other analyzer is then asked on its
10
+ # own: a refusal it returns or raises stands, and one that raises anything else cannot answer, so unless another refusal
11
+ # stands the query is refused with QUERY_LIMIT_UNKNOWN. A multiplex analyzer cannot be asked again, so when the raise
12
+ # stopped the visit before its end, a query of a multiplex with multiplex analyzers is refused the same way.
13
+ # Only the analysis of an execution counts: an analysis the app runs itself takes no slot and charges nothing here. It
14
+ # does not cover a trace that takes no modules from the schema (`context[:trace]`, or a class given to `trace_mode`).
15
+ module AnalysisGuard
16
+ ANSWERS = :limiter_answers
17
+ ASKED = :limiter_asked
18
+ ARMED = :limiter_guard_armed
19
+ MULTIPLEXED = :limiter_guard_multiplexed
20
+ # Set just before the guard asks one analyzer again, and taken by that analysis only, so a nested one never sees it.
21
+ REASK = :limiter_guard_reask
22
+ RAISED = :limiter_guard_raised
23
+ VISITED = :limiter_guard_visited
24
+ NOT_CHARGED = "This query could not be charged to its rate limit."
25
+ LIMIT_UNKNOWN = "The limits of this query could not be computed."
26
+
27
+ # Prepended to the limiters' analyzers: records that a visit of the query reached its end. graphql-ruby calls `result`
28
+ # only after the whole visit, every hook of every analyzer (the multiplex ones too) included; a leave hook is not
29
+ # enough, since the query analyzers leave before the multiplex ones. Marked before computing anything, because a
30
+ # `complexity:` lambda raises inside Points' `result`.
31
+ module Visited
32
+ def result
33
+ query.context.namespace(Points::NAMESPACE)[VISITED] = true
34
+ super
35
+ end
36
+ end
37
+
38
+ # Runs a limiter, keeping per query and per limiter that it was asked and what it answered. A limiter that raised partway
39
+ # may have charged some of its keys, so it is never asked again.
40
+ def self.answer(query, limiter)
41
+ state = query.context.namespace(Points::NAMESPACE)
42
+ (state[ASKED] ||= {})[limiter] = true
43
+ (state[ANSWERS] ||= {})[limiter] = yield
44
+ end
45
+
46
+ def self.decide(query, error)
47
+ state = query.context.namespace(Points::NAMESPACE)
48
+ # Read before the guard's own visits below. A limiter answers from `result`, after the whole visit.
49
+ visited = state[VISITED] || !(state[ASKED] || {}).empty?
50
+ refusals, late = limiter_refusals(query, error)
51
+ # Each new visit gets a whole timeout of its own, and the timeout already refuses the query.
52
+ return [late] if late
53
+ return refusals if timeout?(error)
54
+
55
+ kept, unknown = other_answers(query)
56
+ unknown ||= !visited && state[MULTIPLEXED]
57
+ # A lambda's AnalysisError can come back from a limiter and from a maximum alike: show it once.
58
+ refusals = (refusals + kept).uniq { |refusal| [refusal.message, refusal.extensions] }
59
+ refusals.empty? && unknown ? [GraphQL::AnalysisError.new(LIMIT_UNKNOWN, extensions: { "code" => "QUERY_LIMIT_UNKNOWN" })] : refusals
60
+ end
61
+
62
+ # Asks one analyzer on its own and answers `[results, the error it raised or nil]`.
63
+ def self.ask(query, analyzer)
64
+ state = query.context.namespace(Points::NAMESPACE)
65
+ state[REASK] = true
66
+ [GraphQL::Analysis.analyze_query(query, [analyzer]), state.delete(RAISED)]
67
+ ensure
68
+ state.delete(REASK)
69
+ end
70
+ private_class_method :ask
71
+
72
+ def self.limiter_refusals(query, error)
73
+ analyzers = query.analyzers.select { |analyzer| analyzer.respond_to?(:armory_limiter) }
74
+ state = query.context.namespace(Points::NAMESPACE)
75
+ answers = (state[ANSWERS] ||= {})
76
+ asked = (state[ASKED] ||= {})
77
+ analyzers.reject { |analyzer| asked.key?(analyzer.armory_limiter) }.each do |analyzer|
78
+ results, raised = ask(query, analyzer)
79
+ late = timeout?(raised) ? raised : results.flatten.find { |answer| timeout?(answer) }
80
+ return [[], late] if late
81
+ end
82
+
83
+ silent = analyzers.map(&:armory_limiter).reject { |limiter| answers.key?(limiter) || exempt?(limiter, query) }
84
+ silent.each { |limiter| query.context[limiter.class::CONTEXT_KEY] = { limit: nil, soft: limiter.soft?, limited: !limiter.soft?, charged: false } }
85
+
86
+ refusals = answers.values.compact
87
+ return [refusals, nil] unless refusals.empty?
88
+ return [[], nil] if silent.all?(&:soft?)
89
+
90
+ [[error.is_a?(GraphQL::AnalysisError) ? error : GraphQL::AnalysisError.new(NOT_CHARGED, extensions: { "code" => "RATE_LIMIT_NOT_CHARGED" })], nil]
91
+ end
92
+
93
+ private_class_method :limiter_refusals
94
+
95
+ # What the analyzers that are not limiters return or raise, one at a time, and whether one could not answer. Each is
96
+ # asked once more at most, so a raise the client chose costs one more visit per analyzer of the schema.
97
+ def self.other_answers(query)
98
+ kept = []
99
+ unknown = false
100
+ query.analyzers.reject { |analyzer| analyzer.respond_to?(:armory_limiter) }.each do |analyzer|
101
+ results, raised = ask(query, analyzer)
102
+ answers = results.flatten.grep(GraphQL::AnalysisError)
103
+ late = timeout?(raised) ? raised : answers.find { |answer| timeout?(answer) }
104
+ return [[late], false] if late
105
+
106
+ if raised.is_a?(GraphQL::AnalysisError)
107
+ # Raised from `result`: a refusal, with the app's own message.
108
+ kept << raised
109
+ elsif raised
110
+ unknown = true
111
+ else
112
+ kept.concat(answers)
113
+ end
114
+ end
115
+ [kept, unknown]
116
+ end
117
+ private_class_method :other_answers
118
+
119
+ def self.timeout?(error)
120
+ defined?(GraphQL::Analysis::TimeoutError) && error.is_a?(GraphQL::Analysis::TimeoutError)
121
+ end
122
+ private_class_method :timeout?
123
+
124
+ # A limit that cannot be asked for does not exempt anyone.
125
+ def self.exempt?(limiter, query)
126
+ limiter.exempt?(query)
127
+ rescue GraphQL::ExecutionError, GraphQL::UnauthorizedError
128
+ false
129
+ end
130
+ private_class_method :exempt?
131
+
132
+ # Mirrors how graphql-ruby builds the multiplex analyzers on both engines.
133
+ def analyze_multiplex(multiplex:)
134
+ multiplexed = !multiplex.max_complexity.nil? || multiplex.schema.multiplex_analyzers.any?
135
+ multiplex.queries.each do |query|
136
+ state = query.context.namespace(Points::NAMESPACE)
137
+ state[ARMED] = true
138
+ state[MULTIPLEXED] = multiplexed
139
+ end
140
+ super
141
+ end
142
+
143
+ # The first analysis of each query in an execution, and each analyzer the guard asks again. Any other, nested in them or
144
+ # run by the app, passes through. graphql-ruby swallows a raise outside this hook, so the guard records it here.
145
+ def analyze_query(query:)
146
+ state = query.context.namespace(Points::NAMESPACE)
147
+ return reasked(state) { super } if state.delete(REASK)
148
+ return super unless state.delete(ARMED)
149
+
150
+ begin
151
+ super
152
+ rescue GraphQL::ExecutionError, GraphQL::UnauthorizedError => error
153
+ decided(query, error)
154
+ end
155
+ end
156
+
157
+ private
158
+
159
+ def reasked(state)
160
+ yield
161
+ rescue GraphQL::ExecutionError, GraphQL::UnauthorizedError => error
162
+ state[RAISED] = error
163
+ raise
164
+ end
165
+
166
+ def decided(query, error)
167
+ refusals = AnalysisGuard.decide(query, error)
168
+ raise error if refusals.empty?
169
+
170
+ refusals
171
+ end
172
+ end
173
+ end
174
+ end
175
+ end
@@ -18,20 +18,24 @@ module GraphQL
18
18
  CONTEXT_KEY = :rate_limit_concurrency
19
19
  NAMESPACE = :graphql_armory
20
20
 
21
- def self.use(schema, store:, limit:, stale_after: 60, soft: true, key: nil, on_store_error: nil)
22
- concurrency = build(store: store, limit: limit, stale_after: stale_after, soft: soft, key: key, on_store_error: on_store_error)
23
- schema.query_analyzer(Class.new(Analyzer) { define_method(:concurrency) { concurrency } })
21
+ def self.use(schema, store:, limit:, stale_after: 60, soft: true, key: nil, on_store_error: nil, sinks: [])
22
+ concurrency = build(store: store, limit: limit, stale_after: stale_after, soft: soft, key: key, on_store_error: on_store_error, sinks: sinks)
23
+ schema.query_analyzer(Class.new(Analyzer) do
24
+ define_method(:concurrency) { concurrency }
25
+ define_singleton_method(:armory_limiter) { concurrency }
26
+ end)
24
27
  schema.trace_with(Release)
28
+ schema.trace_with(AnalysisGuard)
25
29
  end
26
30
 
27
31
  # Wires the app's store with `use`'s defaults (soft mode); `use` goes through here.
28
- def self.build(store:, limit:, stale_after: 60, soft: true, key: nil, on_store_error: nil)
29
- new(store: store, limit: limit, stale_after: stale_after, soft: soft, key: key, on_store_error: on_store_error)
32
+ def self.build(store:, limit:, stale_after: 60, soft: true, key: nil, on_store_error: nil, sinks: [])
33
+ new(store: store, limit: limit, stale_after: stale_after, soft: soft, key: key, on_store_error: on_store_error, sinks: sinks)
30
34
  end
31
35
 
32
36
  # `new` is inert: with no store wired it refuses every query. It checks every setting, so no partial
33
37
  # configuration lets a query through either.
34
- def initialize(store: Store::Null.new, limit: 1, stale_after: 60, soft: false, key: nil, on_store_error: nil)
38
+ def initialize(store: Store::Null.new, limit: 1, stale_after: 60, soft: false, key: nil, on_store_error: nil, sinks: [])
35
39
  unless Settings.store_answers?(store, acquire: %i[token limit ttl force], release: %i[token])
36
40
  raise ConfigurationError, "store: must answer acquire(key, token:, limit:, ttl:, force:) and release(key, token:), like a MemoryStore"
37
41
  end
@@ -41,7 +45,16 @@ module GraphQL
41
45
  @stale_after = Settings.seconds(:stale_after, stale_after)
42
46
  @soft = Settings.wired_soft(soft, store)
43
47
  @key = Settings.key_reader(key)
44
- @on_store_error = Settings.store_error_handler(on_store_error)
48
+ @on_store_error = Settings.store_error_handler(on_store_error, limiter: :concurrency, sinks: sinks)
49
+ end
50
+
51
+ def soft?
52
+ @soft
53
+ end
54
+
55
+ # Whether this query's client has no limit to charge.
56
+ def exempt?(query)
57
+ Settings.exempt?(@key, @limit, query)
45
58
  end
46
59
 
47
60
  # Takes a slot for the query: the refusal when none is free, or nil to let it run.
@@ -51,6 +64,8 @@ module GraphQL
51
64
  end
52
65
 
53
66
  key = Settings.key_for(@key, query)
67
+ return call_several(query, key) if key.is_a?(Array)
68
+
54
69
  limit = Settings.limit_for(@limit, key, query)
55
70
  if limit.nil?
56
71
  record(query, key: key, limit: nil, active: nil, limited: false)
@@ -67,7 +82,7 @@ module GraphQL
67
82
  acquired, active = Settings.checked(answer, :acquire, "the Integer slots held")
68
83
 
69
84
  # Per query, not in the context hash: queries of a multiplex may share one hash.
70
- query.context.namespace(NAMESPACE)[:concurrency_slot] = [self, key, token] if acquired || @soft
85
+ slots_of(query) << [self, key, token] if acquired || @soft
71
86
  record(query, key: key, limit: limit, active: active, limited: !acquired)
72
87
  refusal(limit, active) unless acquired || @soft
73
88
  end
@@ -78,10 +93,73 @@ module GraphQL
78
93
  @on_store_error.call(error, query)
79
94
  end
80
95
 
96
+ # Gives every slot back, even if one release raises (an on_store_error that raises); the first such error is
97
+ # raised afterwards.
98
+ def self.release_all(query, slots)
99
+ failure = nil
100
+ slots.each do |concurrency, key, token|
101
+ concurrency.release(query, key, token)
102
+ rescue StandardError => error
103
+ failure ||= error
104
+ end
105
+ raise failure if failure
106
+ end
107
+
81
108
  private
82
109
 
110
+ def slots_of(query)
111
+ query.context.namespace(NAMESPACE)[:concurrency_slots] ||= []
112
+ end
113
+
114
+ # Takes a slot per key, in order, and stops at the first full key, so a refused client holds a shared key as little
115
+ # as it can. A refusal gives back what this query took here, at once: a multiplex can run on for long. Each slot is
116
+ # listed as it is taken, so a raise later on still lets `Release` give it back. A key whose store fails is left out,
117
+ # and the others still decide.
118
+ def call_several(query, keys)
119
+ limits = Settings.limits_for(@limit, keys, query)
120
+ if limits.empty?
121
+ record(query, key: keys.first, limit: nil, active: nil, limited: false, keys: [])
122
+ return nil
123
+ end
124
+
125
+ taken = []
126
+ held = []
127
+ limits.each do |key, limit|
128
+ token = SecureRandom.hex(16)
129
+ answer = begin
130
+ @store.acquire(key, token: token, limit: limit, ttl: @stale_after, force: @soft)
131
+ rescue StandardError => error
132
+ @on_store_error.call(error, query)
133
+ next
134
+ end
135
+ acquired, active = Settings.checked(answer, :acquire, "the Integer slots held")
136
+ if acquired || @soft
137
+ slot = [self, key, token]
138
+ taken << slot
139
+ slots_of(query) << slot
140
+ end
141
+ held << { key: key, limit: limit, active: active, acquired: acquired }
142
+ break unless acquired || @soft
143
+ end
144
+ return nil if held.empty?
145
+
146
+ settle_several(query, held, taken)
147
+ end
148
+
149
+ def settle_several(query, held, taken)
150
+ full = held.find { |slot| !slot[:acquired] }
151
+ binding = full || held.max_by { |slot| slot[:active] / slot[:limit].to_f }
152
+ record(query, key: binding[:key], limit: binding[:limit], active: binding[:active], limited: !full.nil?,
153
+ keys: held.map { |slot| slot.slice(:key, :limit, :active) })
154
+ return unless full && !@soft
155
+
156
+ slots_of(query).reject! { |slot| taken.include?(slot) }
157
+ self.class.release_all(query, taken)
158
+ refusal(full[:limit], full[:active])
159
+ end
160
+
83
161
  def record(query, **info)
84
- query.context[CONTEXT_KEY] = { **info.slice(:key, :limit, :active), soft: @soft, limited: info[:limited] }
162
+ query.context[CONTEXT_KEY] = { **info.slice(:key, :limit, :active), soft: @soft, limited: info[:limited], **info.slice(:keys) }
85
163
  end
86
164
 
87
165
  def refusal(limit, active)
@@ -93,8 +171,10 @@ module GraphQL
93
171
 
94
172
  # Takes the slot during analysis, before anything runs.
95
173
  class Analyzer < GraphQL::Analysis::Analyzer
174
+ prepend AnalysisGuard::Visited
175
+
96
176
  def result
97
- concurrency.(query)
177
+ AnalysisGuard.answer(query, concurrency) { concurrency.(query) }
98
178
  end
99
179
  end
100
180
 
@@ -108,12 +188,11 @@ module GraphQL
108
188
  # error is raised afterwards.
109
189
  failure = nil
110
190
  multiplex.queries.each do |query|
111
- slots = query.context.namespace(NAMESPACE)
112
- concurrency, key, token = slots.delete(:concurrency_slot)
113
- next unless concurrency
191
+ slots = query.context.namespace(NAMESPACE).delete(:concurrency_slots)
192
+ next unless slots
114
193
 
115
194
  begin
116
- concurrency.release(query, key, token)
195
+ Concurrency.release_all(query, slots)
117
196
  rescue StandardError => error
118
197
  failure ||= error
119
198
  end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module RateLimits
6
+ # Finds what a limiter owes for a multiplex's invalid queries, which no analyzer ever sees. It runs after the answers are
7
+ # made, so a failure here is reported and never replaces them.
8
+ module InvalidQueries
9
+ # The invalid queries this limiter did not handle, grouped by what they draw from: `{ { key => limit } => [query] }`.
10
+ def self.grouped(multiplex, limiter, reader, limit, handler)
11
+ groups = {}
12
+ multiplex.queries.each do |query|
13
+ next unless invalid?(query, limiter)
14
+
15
+ key = Settings.key_for(reader, query)
16
+ limits = Settings.limits_for(limit, Array(key), query)
17
+ (groups[limits] ||= []) << query unless limits.empty?
18
+ rescue StandardError => error
19
+ report(handler, error, query)
20
+ end
21
+ groups
22
+ end
23
+
24
+ # Takes `cost` from each key in order, as if the queries had come one at a time. A key that cannot pay all of it pays
25
+ # what it holds, and the keys after it pay only that much: sending invalid queries together never costs a client less
26
+ # than sending them apart, and a client with nothing left cannot keep draining a bucket it shares. Never with `force`,
27
+ # never below zero. A key whose store fails is left out. Answers `[budgets, every key paid in full]`.
28
+ def self.charge(store, limits, cost, window, handler, query, bucket: ->(key) { key })
29
+ budgets = []
30
+ paid = true
31
+ limits.each do |key, limit|
32
+ break if cost.zero?
33
+
34
+ stored = bucket.call(key)
35
+ taken, remaining = take(store, stored, cost, limit, window)
36
+ unless taken
37
+ paid = false
38
+ # A refused take changes nothing and answers what the key holds. Taking that can still fail when another request
39
+ # got there first; then the keys after it pay nothing.
40
+ held = remaining
41
+ cost = 0
42
+ if held.positive?
43
+ again, remaining = take(store, stored, held, limit, window)
44
+ cost = held if again
45
+ end
46
+ end
47
+ budgets << { key: key, limit: limit, remaining: remaining }
48
+ rescue StandardError => error
49
+ report(handler, error, query)
50
+ end
51
+ [budgets, paid]
52
+ end
53
+
54
+ def self.take(store, key, cost, limit, window)
55
+ Settings.checked(store.take(key, cost: cost, limit: limit, window: window, force: false), :take, "the Integer left")
56
+ end
57
+ private_class_method :take
58
+
59
+ def self.report(handler, error, query)
60
+ handler.call(error, query)
61
+ rescue StandardError => raised
62
+ warn("graphql-armory: on_store_error raised while charging an invalid query: #{raised.class}: #{raised.message}")
63
+ end
64
+
65
+ # Only validation decides: `valid?` is also false for a query an analyzer refused, and graphql-ruby copies a multiplex
66
+ # analyzer's errors into every query, invalid ones included. A query that was analyzed is not invalid: what the
67
+ # limiter decided on it stands.
68
+ def self.invalid?(query, limiter)
69
+ !query.validation_pipeline.valid? && !query.context.namespace(Points::NAMESPACE)[AnalysisGuard::ASKED]&.key?(limiter)
70
+ end
71
+ private_class_method :invalid?
72
+ end
73
+ end
74
+ end
75
+ end
@@ -11,14 +11,19 @@ module GraphQL
11
11
  #
12
12
  # A query that costs more than the client has left is refused before any field resolves, and charged
13
13
  # nothing. Soft mode (the default) charges and records but refuses nothing. What happened is in
14
- # `context[:rate_limit_points]`.
14
+ # `context[:rate_limit_points]`. An invalid query, which no analyzer sees, costs `invalid_cost:`, charged by a trace.
15
15
  class Points
16
16
  CONTEXT_KEY = :rate_limit_points
17
17
  NAMESPACE = :graphql_armory
18
18
 
19
- def self.use(schema, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, extensions: false)
20
- points = build(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, extensions: extensions)
21
- schema.query_analyzer(Class.new(Analyzer) { define_method(:points) { points } })
19
+ def self.use(schema, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, sinks: [], extensions: false, invalid_cost: 1)
20
+ points = build(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, sinks: sinks, extensions: extensions, invalid_cost: invalid_cost)
21
+ schema.query_analyzer(Class.new(Analyzer) do
22
+ define_method(:points) { points }
23
+ define_singleton_method(:armory_limiter) { points }
24
+ end)
25
+ schema.trace_with(AnalysisGuard)
26
+ schema.trace_with(points.invalid_trace)
22
27
  end
23
28
 
24
29
  # HTTP headers for the budget a result recorded: `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`
@@ -35,13 +40,13 @@ module GraphQL
35
40
  end
36
41
 
37
42
  # Wires the app's store with `use`'s defaults (soft mode); `use` goes through here.
38
- def self.build(store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, extensions: false)
39
- new(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, extensions: extensions)
43
+ def self.build(store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, sinks: [], extensions: false, invalid_cost: 1)
44
+ new(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, sinks: sinks, extensions: extensions, invalid_cost: invalid_cost)
40
45
  end
41
46
 
42
47
  # `new` is inert: with no store wired it refuses every query. It checks every setting, so no partial
43
48
  # configuration lets a query through either.
44
- def initialize(store: Store::Null.new, limit: 1, window: 60, soft: false, key: nil, on_store_error: nil, extensions: false)
49
+ def initialize(store: Store::Null.new, limit: 1, window: 60, soft: false, key: nil, on_store_error: nil, sinks: [], extensions: false, invalid_cost: 1)
45
50
  unless Settings.store_answers?(store, take: %i[cost limit window force])
46
51
  raise ConfigurationError, "store: must answer take(key, cost:, limit:, window:, force:), like a MemoryStore"
47
52
  end
@@ -52,13 +57,58 @@ module GraphQL
52
57
  @window = Settings.seconds(:window, window)
53
58
  @soft = Settings.wired_soft(soft, store)
54
59
  @key = Settings.key_reader(key)
55
- @on_store_error = Settings.store_error_handler(on_store_error)
60
+ @on_store_error = Settings.store_error_handler(on_store_error, limiter: :points, sinks: sinks)
56
61
  @extensions = extensions
62
+ unless invalid_cost.nil? || (invalid_cost.is_a?(Integer) && invalid_cost.positive?)
63
+ raise ConfigurationError, "invalid_cost: must be a positive Integer or nil, got #{invalid_cost.inspect}"
64
+ end
65
+
66
+ @invalid_cost = invalid_cost
67
+ end
68
+
69
+ # One module per limiter, so a schema with several charges each. Inside `ensure`: the answers are already made.
70
+ def invalid_trace
71
+ points = self
72
+ Module.new do
73
+ define_method(:execute_multiplex) do |multiplex:, &block|
74
+ super(multiplex: multiplex, &block)
75
+ ensure
76
+ points.charge_invalid(multiplex)
77
+ end
78
+ end
79
+ end
80
+
81
+ # Charges the multiplex's invalid queries, together per client. It never raises over the answers.
82
+ def charge_invalid(multiplex)
83
+ return if @invalid_cost.nil?
84
+
85
+ InvalidQueries.grouped(multiplex, self, @key, @limit, @on_store_error).each do |limits, queries|
86
+ budgets, paid = InvalidQueries.charge(@store, limits, @invalid_cost * queries.size, @window, @on_store_error, queries.first)
87
+ next if budgets.empty?
88
+
89
+ binding = budgets.min_by { |budget| budget[:remaining] }
90
+ queries.each do |query|
91
+ record(query, key: binding[:key], cost: @invalid_cost, limit: binding[:limit], remaining: binding[:remaining], limited: !paid, invalid: true)
92
+ end
93
+ end
94
+ rescue StandardError => error
95
+ InvalidQueries.report(@on_store_error, error, multiplex.queries.first)
96
+ end
97
+
98
+ def soft?
99
+ @soft
100
+ end
101
+
102
+ # Whether this query's client has no limit to charge.
103
+ def exempt?(query)
104
+ Settings.exempt?(@key, @limit, query)
57
105
  end
58
106
 
59
107
  # The refusal for a query that costs `cost`, or nil to let it run.
60
108
  def call(query, cost)
61
109
  key = Settings.key_for(@key, query)
110
+ return call_several(query, key, cost) if key.is_a?(Array)
111
+
62
112
  limit = Settings.limit_for(@limit, key, query)
63
113
  if limit.nil?
64
114
  record(query, key: key, cost: cost, limit: nil, remaining: nil, limited: false)
@@ -76,19 +126,70 @@ module GraphQL
76
126
  taken, remaining = Settings.checked(answer, :take, "the Integer points left")
77
127
 
78
128
  info = record(query, key: key, cost: cost, limit: limit, remaining: remaining, limited: !taken)
79
- if @extensions
80
- query.context.response_extensions["rateLimit"] =
81
- { "cost" => cost, "limit" => limit, "remaining" => remaining, "resetIn" => self.class.reset_in(info) }
82
- end
129
+ announce(query, info, cost) if @extensions
83
130
  refusal(cost, limit, remaining) unless taken || @soft
84
131
  end
85
132
 
86
133
  private
87
134
 
135
+ # Reads every balance first, so a query one key refuses leaves the others as they were, then charges each key.
136
+ # Two queries can race between the two steps: then the refused one leaves the other keys charged. A key whose store
137
+ # fails is left out, and the others still decide: an attacker who can pick a dead shard must not cancel a refusal.
138
+ def call_several(query, keys, cost)
139
+ limits = Settings.limits_for(@limit, keys, query)
140
+ if limits.empty?
141
+ record(query, key: keys.first, cost: cost, limit: nil, remaining: nil, limited: false, keys: [])
142
+ return nil
143
+ end
144
+
145
+ read = takes(query, limits, 0, false) unless @soft
146
+ budgets = if read&.any? { |budget| budget[:remaining] < cost }
147
+ read
148
+ else
149
+ takes(query, read ? read.to_h { |budget| budget.values_at(:key, :limit) } : limits, cost, @soft, charging: true)
150
+ end
151
+ if budgets.empty?
152
+ query.context[CONTEXT_KEY] = nil
153
+ return nil
154
+ end
155
+
156
+ refused = budgets.select { |budget| budget.fetch(:taken) { budget[:remaining] >= cost } == false }
157
+ binding = binding_budget(refused, cost) || budgets.min_by { |budget| budget[:remaining] }
158
+ limited = !refused.empty?
159
+ info = record(query, key: binding[:key], cost: cost, limit: binding[:limit], remaining: binding[:remaining], limited: limited,
160
+ keys: budgets.map { |budget| budget.slice(:key, :limit, :remaining) })
161
+ announce(query, info, cost) if @extensions
162
+ refusal(cost, binding[:limit], binding[:remaining]) if limited && !@soft
163
+ end
164
+
165
+ # What the store answers for each key, without the keys whose store failed.
166
+ def takes(query, limits, cost, force, charging: false)
167
+ limits.filter_map do |key, limit|
168
+ answer = begin
169
+ @store.take(key, cost: cost, limit: limit, window: @window, force: force)
170
+ rescue StandardError => error
171
+ @on_store_error.call(error, query)
172
+ next
173
+ end
174
+ taken, remaining = Settings.checked(answer, :take, "the Integer points left")
175
+ { key: key, limit: limit, remaining: remaining, **(charging ? { taken: taken } : {}) }
176
+ end
177
+ end
178
+
179
+ # What the client is told: a key that can never pay, otherwise the longest wait.
180
+ def binding_budget(refused, cost)
181
+ refused.find { |budget| cost > budget[:limit] } || refused.max_by { |budget| (cost - budget[:remaining]) / budget[:limit].to_f }
182
+ end
183
+
184
+ def announce(query, info, cost)
185
+ query.context.response_extensions["rateLimit"] =
186
+ { "cost" => cost, "limit" => info[:limit], "remaining" => info[:remaining], "resetIn" => self.class.reset_in(info) }
187
+ end
188
+
88
189
  # In the context hash for instrumentation, and per query for `headers`: queries of a multiplex may share one
89
190
  # context hash, where the last query's record wins.
90
191
  def record(query, **info)
91
- info = { **info.slice(:key, :cost, :limit, :remaining), window: @window, soft: @soft, limited: info[:limited] }
192
+ info = { **info.slice(:key, :cost, :limit, :remaining), window: @window, soft: @soft, limited: info[:limited], **info.slice(:keys, :invalid) }
92
193
  query.context.namespace(NAMESPACE)[:points] = info
93
194
  query.context[CONTEXT_KEY] = info
94
195
  end
@@ -110,14 +211,27 @@ module GraphQL
110
211
 
111
212
  # graphql-ruby's own complexity analysis, then the charge.
112
213
  class Analyzer < GraphQL::Analysis::QueryComplexity
214
+ prepend AnalysisGuard::Visited
215
+
216
+ # graphql-ruby's words when a connection has no `first:`, `last:` or page size. A client can send that, so it answers
217
+ # an error for the client and not a server error. Nothing is charged, and any other error while scoring still raises.
218
+ UNSIZED_CONNECTION = "Can't calculate complexity for "
219
+
113
220
  def result
114
- cost = super
221
+ cost = begin
222
+ super
223
+ rescue GraphQL::Error => error
224
+ raise unless error.instance_of?(GraphQL::Error) && error.message.start_with?(UNSIZED_CONNECTION)
225
+
226
+ query.context[CONTEXT_KEY] = nil
227
+ return AnalysisGuard.answer(query, points) { GraphQL::AnalysisError.new("This connection needs first: or last:", extensions: { "code" => "PAGE_SIZE_REQUIRED" }) }
228
+ end
115
229
  unless cost.is_a?(Numeric) && cost.finite? && !cost.negative?
116
230
  raise ConfigurationError, "the query complexity is #{cost.inspect}: field complexities must be numbers of zero or more"
117
231
  end
118
232
 
119
233
  # Fractional complexities (`complexity: 0.5`) are charged whole points, rounded up.
120
- points.(query, cost.ceil)
234
+ AnalysisGuard.answer(query, points) { points.(query, cost.ceil) }
121
235
  end
122
236
  end
123
237
  end