graphql-armory 0.1.0.pre9 → 0.1.0.pre11

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 (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +35 -0
  3. data/README.md +5 -5
  4. data/docs/authorization.md +45 -3
  5. data/docs/keyset-connections.md +28 -4
  6. data/docs/rate-limiting.md +7 -4
  7. data/lib/graphql/armory/authorization/audit/baseline.rb +3 -3
  8. data/lib/graphql/armory/authorization/audit/denial_hooks.rb +3 -3
  9. data/lib/graphql/armory/authorization/audit/edge_rules.rb +1 -1
  10. data/lib/graphql/armory/authorization/audit/findings.rb +5 -4
  11. data/lib/graphql/armory/authorization/audit/foreign_policies.rb +2 -2
  12. data/lib/graphql/armory/authorization/audit/input_loads.rb +1 -1
  13. data/lib/graphql/armory/authorization/audit/interface_rules.rb +3 -3
  14. data/lib/graphql/armory/authorization/audit/introspection_fields.rb +1 -1
  15. data/lib/graphql/armory/authorization/audit/observed_rules.rb +7 -17
  16. data/lib/graphql/armory/authorization/audit/overrides.rb +3 -3
  17. data/lib/graphql/armory/authorization/audit/own_checks.rb +6 -6
  18. data/lib/graphql/armory/authorization/audit/payload_reuse.rb +1 -1
  19. data/lib/graphql/armory/authorization/audit/plain_resolvers.rb +1 -1
  20. data/lib/graphql/armory/authorization/audit/report.rb +11 -4
  21. data/lib/graphql/armory/authorization/audit/type_rules.rb +32 -31
  22. data/lib/graphql/armory/authorization/audit/visibility_models.rb +5 -5
  23. data/lib/graphql/armory/authorization/audit.rb +2 -2
  24. data/lib/graphql/armory/authorization/integration/argument.rb +3 -0
  25. data/lib/graphql/armory/authorization/integration/field.rb +4 -0
  26. data/lib/graphql/armory/authorization/integration/object.rb +5 -1
  27. data/lib/graphql/armory/authorization/integration/resolver.rb +4 -0
  28. data/lib/graphql/armory/authorization/integration/root_check.rb +35 -0
  29. data/lib/graphql/armory/authorization/integration.rb +52 -5
  30. data/lib/graphql/armory/authorization/location.rb +79 -0
  31. data/lib/graphql/armory/authorization.rb +2 -0
  32. data/lib/graphql/armory/keyset/encoder_check.rb +113 -0
  33. data/lib/graphql/armory/keyset.rb +23 -3
  34. data/lib/graphql/armory/rate_limits/analysis_guard.rb +107 -11
  35. data/lib/graphql/armory/rate_limits/concurrency.rb +2 -0
  36. data/lib/graphql/armory/rate_limits/invalid_queries.rb +75 -0
  37. data/lib/graphql/armory/rate_limits/points.rb +44 -7
  38. data/lib/graphql/armory/rate_limits/time.rb +36 -6
  39. data/lib/graphql/armory/rate_limits.rb +1 -0
  40. data/lib/graphql/armory/version.rb +1 -1
  41. metadata +5 -1
@@ -84,9 +84,26 @@ module GraphQL
84
84
 
85
85
  attr_reader :columns
86
86
 
87
- # Checks the relation and its ordering; resolvers go through here.
88
- def self.build(relation, plain_cursors: false)
87
+ # Checks the encoder when the schema loads, and keeps checking any encoder set later on it or on a subclass. Put it
88
+ # below `cursor_encoder`: graphql-ruby runs `use` at once, with no hook for the end of the class body.
89
+ def self.use(schema, plain_cursors: false)
89
90
  raise ConfigurationError, "plain_cursors: must be true or false, got #{plain_cursors.inspect}" unless [true, false].include?(plain_cursors)
91
+
92
+ unless plain_cursors
93
+ if schema.cursor_encoder == GraphQL::Schema::Base64Encoder
94
+ raise ConfigurationError, "no cursor_encoder is set on this schema: put cursor_encoder above `use GraphQL::Armory::Keyset`, or pass plain_cursors: true"
95
+ end
96
+
97
+ EncoderCheck.(schema.cursor_encoder)
98
+ end
99
+ schema.extend(SchemaChecks)
100
+ schema.armory_keyset_plain_cursors = plain_cursors
101
+ end
102
+
103
+ # Checks the relation and its ordering; resolvers go through here. With no `plain_cursors:`, the schema's setting
104
+ # decides when the page loads.
105
+ def self.build(relation, plain_cursors: nil)
106
+ raise ConfigurationError, "plain_cursors: must be true, false or nil, got #{plain_cursors.inspect}" unless [true, false, nil].include?(plain_cursors)
90
107
  raise ConfigurationError, "a keyset connection needs an ActiveRecord relation, got #{relation.class}" unless relation.respond_to?(:order_values)
91
108
 
92
109
  new(relation, columns: Ordering.(relation), plain_cursors: plain_cursors)
@@ -181,9 +198,11 @@ module GraphQL
181
198
  end
182
199
 
183
200
  def refuse_plain_cursors
201
+ schema = context&.schema
202
+ return if @plain_cursors.nil? && schema.respond_to?(:armory_keyset_plain_cursors) && schema.armory_keyset_plain_cursors
184
203
  return if @plain_cursors
185
204
 
186
- encoder = context&.schema&.cursor_encoder
205
+ encoder = schema&.cursor_encoder
187
206
  return unless encoder.nil? || encoder == GraphQL::Schema::Base64Encoder
188
207
 
189
208
  raise ConfigurationError,
@@ -277,3 +296,4 @@ module GraphQL
277
296
  end
278
297
 
279
298
  require "graphql/armory/keyset/controls"
299
+ require "graphql/armory/keyset/encoder_check"
@@ -6,14 +6,34 @@ module GraphQL
6
6
  # graphql-ruby discards an ExecutionError raised during analysis, drops what every analyzer answered, and runs the query.
7
7
  # A client can choose that by field order when a `complexity:` lambda raises. So on such a raise each limiter still
8
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. Only the analysis of an execution counts: an
10
- # analysis the app runs itself takes no slot and charges nothing here. It does not cover a trace that takes no modules
11
- # from the schema (`context[:trace]`, or a class given to `trace_mode`).
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`).
12
15
  module AnalysisGuard
13
16
  ANSWERS = :limiter_answers
14
17
  ASKED = :limiter_asked
15
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
16
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
17
37
 
18
38
  # Runs a limiter, keeping per query and per limiter that it was asked and what it answered. A limiter that raised partway
19
39
  # may have charged some of its keys, so it is never asked again.
@@ -24,22 +44,83 @@ module GraphQL
24
44
  end
25
45
 
26
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)
27
73
  analyzers = query.analyzers.select { |analyzer| analyzer.respond_to?(:armory_limiter) }
28
74
  state = query.context.namespace(Points::NAMESPACE)
29
75
  answers = (state[ANSWERS] ||= {})
30
76
  asked = (state[ASKED] ||= {})
31
- analyzers.reject { |analyzer| asked.key?(analyzer.armory_limiter) }.each { |analyzer| GraphQL::Analysis.analyze_query(query, [analyzer]) }
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
32
82
 
33
83
  silent = analyzers.map(&:armory_limiter).reject { |limiter| answers.key?(limiter) || exempt?(limiter, query) }
34
84
  silent.each { |limiter| query.context[limiter.class::CONTEXT_KEY] = { limit: nil, soft: limiter.soft?, limited: !limiter.soft?, charged: false } }
35
85
 
36
86
  refusals = answers.values.compact
37
- return refusals unless refusals.empty?
38
- return [] if silent.all?(&:soft?)
87
+ return [refusals, nil] unless refusals.empty?
88
+ return [[], nil] if silent.all?(&:soft?)
39
89
 
40
- [error.is_a?(GraphQL::AnalysisError) ? error : GraphQL::AnalysisError.new(NOT_CHARGED, extensions: { "code" => "RATE_LIMIT_NOT_CHARGED" })]
90
+ [[error.is_a?(GraphQL::AnalysisError) ? error : GraphQL::AnalysisError.new(NOT_CHARGED, extensions: { "code" => "RATE_LIMIT_NOT_CHARGED" })], nil]
41
91
  end
42
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
+
43
124
  # A limit that cannot be asked for does not exempt anyone.
44
125
  def self.exempt?(limiter, query)
45
126
  limiter.exempt?(query)
@@ -48,15 +129,23 @@ module GraphQL
48
129
  end
49
130
  private_class_method :exempt?
50
131
 
132
+ # Mirrors how graphql-ruby builds the multiplex analyzers on both engines.
51
133
  def analyze_multiplex(multiplex:)
52
- multiplex.queries.each { |query| query.context.namespace(Points::NAMESPACE)[ARMED] = true }
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
53
140
  super
54
141
  end
55
142
 
56
- # The first analysis of each query in an execution. Any other, nested in it or run by the app, passes through, and
57
- # each analyzer is asked apart, so one that raises leaves the others asked.
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.
58
145
  def analyze_query(query:)
59
- return super unless query.context.namespace(Points::NAMESPACE).delete(ARMED)
146
+ state = query.context.namespace(Points::NAMESPACE)
147
+ return reasked(state) { super } if state.delete(REASK)
148
+ return super unless state.delete(ARMED)
60
149
 
61
150
  begin
62
151
  super
@@ -67,6 +156,13 @@ module GraphQL
67
156
 
68
157
  private
69
158
 
159
+ def reasked(state)
160
+ yield
161
+ rescue GraphQL::ExecutionError, GraphQL::UnauthorizedError => error
162
+ state[RAISED] = error
163
+ raise
164
+ end
165
+
70
166
  def decided(query, error)
71
167
  refusals = AnalysisGuard.decide(query, error)
72
168
  raise error if refusals.empty?
@@ -171,6 +171,8 @@ module GraphQL
171
171
 
172
172
  # Takes the slot during analysis, before anything runs.
173
173
  class Analyzer < GraphQL::Analysis::Analyzer
174
+ prepend AnalysisGuard::Visited
175
+
174
176
  def result
175
177
  AnalysisGuard.answer(query, concurrency) { concurrency.(query) }
176
178
  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,18 +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, sinks: [], extensions: false)
20
- points = build(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, sinks: sinks, extensions: extensions)
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
21
  schema.query_analyzer(Class.new(Analyzer) do
22
22
  define_method(:points) { points }
23
23
  define_singleton_method(:armory_limiter) { points }
24
24
  end)
25
25
  schema.trace_with(AnalysisGuard)
26
+ schema.trace_with(points.invalid_trace)
26
27
  end
27
28
 
28
29
  # HTTP headers for the budget a result recorded: `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`
@@ -39,13 +40,13 @@ module GraphQL
39
40
  end
40
41
 
41
42
  # Wires the app's store with `use`'s defaults (soft mode); `use` goes through here.
42
- def self.build(store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, sinks: [], extensions: false)
43
- new(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, sinks: sinks, 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)
44
45
  end
45
46
 
46
47
  # `new` is inert: with no store wired it refuses every query. It checks every setting, so no partial
47
48
  # configuration lets a query through either.
48
- def initialize(store: Store::Null.new, limit: 1, window: 60, soft: false, key: nil, on_store_error: nil, sinks: [], 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)
49
50
  unless Settings.store_answers?(store, take: %i[cost limit window force])
50
51
  raise ConfigurationError, "store: must answer take(key, cost:, limit:, window:, force:), like a MemoryStore"
51
52
  end
@@ -58,6 +59,40 @@ module GraphQL
58
59
  @key = Settings.key_reader(key)
59
60
  @on_store_error = Settings.store_error_handler(on_store_error, limiter: :points, sinks: sinks)
60
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)
61
96
  end
62
97
 
63
98
  def soft?
@@ -154,7 +189,7 @@ module GraphQL
154
189
  # In the context hash for instrumentation, and per query for `headers`: queries of a multiplex may share one
155
190
  # context hash, where the last query's record wins.
156
191
  def record(query, **info)
157
- info = { **info.slice(:key, :cost, :limit, :remaining), window: @window, soft: @soft, limited: info[:limited], **info.slice(:keys) }
192
+ info = { **info.slice(:key, :cost, :limit, :remaining), window: @window, soft: @soft, limited: info[:limited], **info.slice(:keys, :invalid) }
158
193
  query.context.namespace(NAMESPACE)[:points] = info
159
194
  query.context[CONTEXT_KEY] = info
160
195
  end
@@ -176,6 +211,8 @@ module GraphQL
176
211
 
177
212
  # graphql-ruby's own complexity analysis, then the charge.
178
213
  class Analyzer < GraphQL::Analysis::QueryComplexity
214
+ prepend AnalysisGuard::Visited
215
+
179
216
  # graphql-ruby's words when a connection has no `first:`, `last:` or page size. A client can send that, so it answers
180
217
  # an error for the client and not a server error. Nothing is charged, and any other error while scoring still raises.
181
218
  UNSIZED_CONNECTION = "Can't calculate complexity for "
@@ -13,7 +13,8 @@ module GraphQL
13
13
  # field resolves, when none is left. A trace measures the multiplex with a monotonic clock and charges the
14
14
  # elapsed milliseconds when it ends, even when it raises. A running operation is never interrupted: the one
15
15
  # that spends the last milliseconds finishes, and the next is refused. Soft mode (the default) charges and
16
- # records but refuses nothing. What happened is in `context[:rate_limit_time]`.
16
+ # records but refuses nothing. What happened is in `context[:rate_limit_time]`. An invalid query, which no analyzer
17
+ # sees, takes its share of the time too.
17
18
  class Time
18
19
  CONTEXT_KEY = :rate_limit_time
19
20
  NAMESPACE = :graphql_armory
@@ -143,9 +144,14 @@ module GraphQL
143
144
  debt = query.context.namespace(NAMESPACE)[:time_charges]&.delete(self)
144
145
  [query, debt] if debt
145
146
  end
146
- return if owed.empty?
147
-
148
- share = (seconds * 1000 / owed.size.to_f).ceil
147
+ # Invalid queries pay only a multiplex that has nothing else to charge: next to a query that ran, they would lower
148
+ # its share, and that query pays with `force` while they cannot.
149
+ invalid = owed.empty? ? invalid_queries(multiplex) : {}
150
+ payers = owed.size + invalid.values.sum(&:size)
151
+ return if payers.zero?
152
+
153
+ share = (seconds * 1000 / payers.to_f).ceil
154
+ invalid.each { |limits, queries| charge_invalid(limits, queries, share) }
149
155
  # Every query is charged even if one hook raises; the first such error is raised afterwards.
150
156
  failure = nil
151
157
  owed.each do |query, debt|
@@ -158,6 +164,28 @@ module GraphQL
158
164
 
159
165
  private
160
166
 
167
+ def invalid_queries(multiplex)
168
+ InvalidQueries.grouped(multiplex, self, @key, @limit, @on_store_error)
169
+ rescue StandardError => error
170
+ InvalidQueries.report(@on_store_error, error, multiplex.queries.first)
171
+ {}
172
+ end
173
+
174
+ # Never raises over the answers, and never with `force`: a key that cannot pay all of it pays what it holds, and the
175
+ # keys after it pay only that much.
176
+ def charge_invalid(limits, queries, share)
177
+ bucket = self.class.method(:bucket_key)
178
+ budgets, paid = InvalidQueries.charge(@store, limits, share * queries.size, @window, @on_store_error, queries.first, bucket: bucket)
179
+ return if budgets.empty?
180
+
181
+ binding = budgets.min_by { |budget| budget[:remaining] }
182
+ queries.each do |query|
183
+ record(query, key: binding[:key], limit: binding[:limit], remaining: binding[:remaining], limited: !paid, invalid: true, elapsed: share)
184
+ end
185
+ rescue StandardError => error
186
+ InvalidQueries.report(@on_store_error, error, queries.first)
187
+ end
188
+
161
189
  # Each key is charged on its own: a store failure on one, or a hook that raises for it, leaves the others charged. The
162
190
  # first error a hook raises is raised afterwards.
163
191
  def charge_one(query, debt, cost)
@@ -253,8 +281,8 @@ module GraphQL
253
281
  end
254
282
 
255
283
  # `elapsed` is nil until the operation ends and is charged; it stays nil for a refused one.
256
- def base_record(key:, limit:, limited:, remaining: nil, keys: nil)
257
- { key: key, limit: limit, remaining: remaining, elapsed: nil, window: @window, soft: @soft, limited: limited, **(keys ? { keys: keys } : {}) }
284
+ def base_record(key:, limit:, limited:, remaining: nil, keys: nil, invalid: false, elapsed: nil)
285
+ { key: key, limit: limit, remaining: remaining, elapsed: elapsed, window: @window, soft: @soft, limited: limited, **(keys ? { keys: keys } : {}), **(invalid ? { invalid: true } : {}) }
258
286
  end
259
287
 
260
288
  # The budget before the run; the charge completes the same hash, which the response already holds.
@@ -287,6 +315,8 @@ module GraphQL
287
315
 
288
316
  # Asks for the balance during analysis, before anything runs.
289
317
  class Analyzer < GraphQL::Analysis::Analyzer
318
+ prepend AnalysisGuard::Visited
319
+
290
320
  def result
291
321
  AnalysisGuard.answer(query, time) { time.(query) }
292
322
  end
@@ -149,6 +149,7 @@ require "graphql/armory/rate_limits/store"
149
149
  require "graphql/armory/rate_limits/clock"
150
150
  require "graphql/armory/rate_limits/redis_store"
151
151
  require "graphql/armory/rate_limits/analysis_guard"
152
+ require "graphql/armory/rate_limits/invalid_queries"
152
153
  require "graphql/armory/rate_limits/points"
153
154
  require "graphql/armory/rate_limits/concurrency"
154
155
  require "graphql/armory/rate_limits/time"
@@ -2,6 +2,6 @@
2
2
 
3
3
  module GraphQL
4
4
  module Armory
5
- VERSION = "0.1.0.pre9"
5
+ VERSION = "0.1.0.pre11"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: graphql-armory
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0.pre9
4
+ version: 0.1.0.pre11
5
5
  platform: ruby
6
6
  authors:
7
7
  - Israel
@@ -92,7 +92,9 @@ files:
92
92
  - lib/graphql/armory/authorization/integration/input_object.rb
93
93
  - lib/graphql/armory/authorization/integration/object.rb
94
94
  - lib/graphql/armory/authorization/integration/resolver.rb
95
+ - lib/graphql/armory/authorization/integration/root_check.rb
95
96
  - lib/graphql/armory/authorization/integration/schema.rb
97
+ - lib/graphql/armory/authorization/location.rb
96
98
  - lib/graphql/armory/authorization/memo.rb
97
99
  - lib/graphql/armory/authorization/rspec.rb
98
100
  - lib/graphql/armory/authorization/rule.rb
@@ -107,6 +109,7 @@ files:
107
109
  - lib/graphql/armory/ids/controls.rb
108
110
  - lib/graphql/armory/keyset.rb
109
111
  - lib/graphql/armory/keyset/controls.rb
112
+ - lib/graphql/armory/keyset/encoder_check.rb
110
113
  - lib/graphql/armory/persisted_queries.rb
111
114
  - lib/graphql/armory/persisted_queries/controls.rb
112
115
  - lib/graphql/armory/persisted_queries/manifest.rb
@@ -120,6 +123,7 @@ files:
120
123
  - lib/graphql/armory/rate_limits/clock.rb
121
124
  - lib/graphql/armory/rate_limits/concurrency.rb
122
125
  - lib/graphql/armory/rate_limits/controls.rb
126
+ - lib/graphql/armory/rate_limits/invalid_queries.rb
123
127
  - lib/graphql/armory/rate_limits/memory_store.rb
124
128
  - lib/graphql/armory/rate_limits/points.rb
125
129
  - lib/graphql/armory/rate_limits/redis_store.rb