graphql-armory 0.1.0.pre7 → 0.1.0.pre9

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 (62) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +81 -0
  3. data/README.md +6 -5
  4. data/docs/authorization.md +220 -10
  5. data/docs/encrypted-ids.md +1 -1
  6. data/docs/persisted-queries.md +111 -19
  7. data/docs/rate-limiting.md +32 -11
  8. data/docs/telemetry.md +31 -8
  9. data/exe/graphql-armory-publish +6 -0
  10. data/lib/graphql/armory/authorization/adapters/cancan.rb +17 -4
  11. data/lib/graphql/armory/authorization/adapters/pundit.rb +79 -14
  12. data/lib/graphql/armory/authorization/adapters/substitute.rb +4 -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/denial_hooks.rb +29 -0
  16. data/lib/graphql/armory/authorization/audit/edge_rules.rb +36 -0
  17. data/lib/graphql/armory/authorization/audit/findings.rb +35 -0
  18. data/lib/graphql/armory/authorization/audit/foreign_policies.rb +90 -0
  19. data/lib/graphql/armory/authorization/audit/input_loads.rb +26 -0
  20. data/lib/graphql/armory/authorization/audit/interface_rules.rb +42 -0
  21. data/lib/graphql/armory/authorization/audit/introspection_fields.rb +40 -0
  22. data/lib/graphql/armory/authorization/audit/library_methods.rb +24 -0
  23. data/lib/graphql/armory/authorization/audit/observed_rules.rb +58 -0
  24. data/lib/graphql/armory/authorization/audit/overrides.rb +81 -0
  25. data/lib/graphql/armory/authorization/audit/own_checks.rb +144 -0
  26. data/lib/graphql/armory/authorization/audit/payload_reuse.rb +95 -0
  27. data/lib/graphql/armory/authorization/audit/plain_resolvers.rb +85 -0
  28. data/lib/graphql/armory/authorization/audit/reach.rb +75 -0
  29. data/lib/graphql/armory/authorization/audit/report.rb +7 -1
  30. data/lib/graphql/armory/authorization/audit/type_rules.rb +282 -0
  31. data/lib/graphql/armory/authorization/audit/visibility_models.rb +83 -0
  32. data/lib/graphql/armory/authorization/audit.rb +59 -192
  33. data/lib/graphql/armory/authorization/authorize.rb +35 -9
  34. data/lib/graphql/armory/authorization/configuration.rb +32 -3
  35. data/lib/graphql/armory/authorization/definitions.rb +121 -0
  36. data/lib/graphql/armory/authorization/integration/argument.rb +24 -6
  37. data/lib/graphql/armory/authorization/integration/field.rb +36 -6
  38. data/lib/graphql/armory/authorization/integration/object.rb +9 -1
  39. data/lib/graphql/armory/authorization/integration/resolver.rb +2 -0
  40. data/lib/graphql/armory/authorization/integration/schema.rb +7 -0
  41. data/lib/graphql/armory/authorization/integration.rb +36 -4
  42. data/lib/graphql/armory/authorization/rspec.rb +10 -4
  43. data/lib/graphql/armory/authorization/rule.rb +24 -3
  44. data/lib/graphql/armory/authorization/scope.rb +6 -6
  45. data/lib/graphql/armory/authorization.rb +4 -1
  46. data/lib/graphql/armory/ids.rb +11 -11
  47. data/lib/graphql/armory/persisted_queries/manifest.rb +2 -0
  48. data/lib/graphql/armory/persisted_queries/manifests.rb +69 -0
  49. data/lib/graphql/armory/persisted_queries/publisher.rb +127 -0
  50. data/lib/graphql/armory/persisted_queries/redis_store.rb +137 -0
  51. data/lib/graphql/armory/persisted_queries.rb +55 -16
  52. data/lib/graphql/armory/railtie.rb +10 -0
  53. data/lib/graphql/armory/rate_limits/analysis_guard.rb +79 -0
  54. data/lib/graphql/armory/rate_limits/concurrency.rb +91 -14
  55. data/lib/graphql/armory/rate_limits/points.rb +91 -14
  56. data/lib/graphql/armory/rate_limits/time.rb +107 -19
  57. data/lib/graphql/armory/rate_limits.rb +29 -5
  58. data/lib/graphql/armory/telemetry.rb +71 -9
  59. data/lib/graphql/armory/version.rb +1 -1
  60. data/lib/graphql/armory.rb +1 -0
  61. data/lib/tasks/graphql_armory.rake +11 -4
  62. metadata +28 -3
@@ -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)
@@ -94,7 +172,7 @@ module GraphQL
94
172
  # Takes the slot during analysis, before anything runs.
95
173
  class Analyzer < GraphQL::Analysis::Analyzer
96
174
  def result
97
- concurrency.(query)
175
+ AnalysisGuard.answer(query, concurrency) { concurrency.(query) }
98
176
  end
99
177
  end
100
178
 
@@ -108,12 +186,11 @@ module GraphQL
108
186
  # error is raised afterwards.
109
187
  failure = nil
110
188
  multiplex.queries.each do |query|
111
- slots = query.context.namespace(NAMESPACE)
112
- concurrency, key, token = slots.delete(:concurrency_slot)
113
- next unless concurrency
189
+ slots = query.context.namespace(NAMESPACE).delete(:concurrency_slots)
190
+ next unless slots
114
191
 
115
192
  begin
116
- concurrency.release(query, key, token)
193
+ Concurrency.release_all(query, slots)
117
194
  rescue StandardError => error
118
195
  failure ||= error
119
196
  end
@@ -16,9 +16,13 @@ module GraphQL
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)
20
+ points = build(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, sinks: sinks, extensions: extensions)
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)
22
26
  end
23
27
 
24
28
  # HTTP headers for the budget a result recorded: `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`
@@ -35,13 +39,13 @@ module GraphQL
35
39
  end
36
40
 
37
41
  # 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)
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)
40
44
  end
41
45
 
42
46
  # `new` is inert: with no store wired it refuses every query. It checks every setting, so no partial
43
47
  # 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)
48
+ def initialize(store: Store::Null.new, limit: 1, window: 60, soft: false, key: nil, on_store_error: nil, sinks: [], extensions: false)
45
49
  unless Settings.store_answers?(store, take: %i[cost limit window force])
46
50
  raise ConfigurationError, "store: must answer take(key, cost:, limit:, window:, force:), like a MemoryStore"
47
51
  end
@@ -52,13 +56,24 @@ module GraphQL
52
56
  @window = Settings.seconds(:window, window)
53
57
  @soft = Settings.wired_soft(soft, store)
54
58
  @key = Settings.key_reader(key)
55
- @on_store_error = Settings.store_error_handler(on_store_error)
59
+ @on_store_error = Settings.store_error_handler(on_store_error, limiter: :points, sinks: sinks)
56
60
  @extensions = extensions
57
61
  end
58
62
 
63
+ def soft?
64
+ @soft
65
+ end
66
+
67
+ # Whether this query's client has no limit to charge.
68
+ def exempt?(query)
69
+ Settings.exempt?(@key, @limit, query)
70
+ end
71
+
59
72
  # The refusal for a query that costs `cost`, or nil to let it run.
60
73
  def call(query, cost)
61
74
  key = Settings.key_for(@key, query)
75
+ return call_several(query, key, cost) if key.is_a?(Array)
76
+
62
77
  limit = Settings.limit_for(@limit, key, query)
63
78
  if limit.nil?
64
79
  record(query, key: key, cost: cost, limit: nil, remaining: nil, limited: false)
@@ -76,19 +91,70 @@ module GraphQL
76
91
  taken, remaining = Settings.checked(answer, :take, "the Integer points left")
77
92
 
78
93
  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
94
+ announce(query, info, cost) if @extensions
83
95
  refusal(cost, limit, remaining) unless taken || @soft
84
96
  end
85
97
 
86
98
  private
87
99
 
100
+ # Reads every balance first, so a query one key refuses leaves the others as they were, then charges each key.
101
+ # Two queries can race between the two steps: then the refused one leaves the other keys charged. A key whose store
102
+ # fails is left out, and the others still decide: an attacker who can pick a dead shard must not cancel a refusal.
103
+ def call_several(query, keys, cost)
104
+ limits = Settings.limits_for(@limit, keys, query)
105
+ if limits.empty?
106
+ record(query, key: keys.first, cost: cost, limit: nil, remaining: nil, limited: false, keys: [])
107
+ return nil
108
+ end
109
+
110
+ read = takes(query, limits, 0, false) unless @soft
111
+ budgets = if read&.any? { |budget| budget[:remaining] < cost }
112
+ read
113
+ else
114
+ takes(query, read ? read.to_h { |budget| budget.values_at(:key, :limit) } : limits, cost, @soft, charging: true)
115
+ end
116
+ if budgets.empty?
117
+ query.context[CONTEXT_KEY] = nil
118
+ return nil
119
+ end
120
+
121
+ refused = budgets.select { |budget| budget.fetch(:taken) { budget[:remaining] >= cost } == false }
122
+ binding = binding_budget(refused, cost) || budgets.min_by { |budget| budget[:remaining] }
123
+ limited = !refused.empty?
124
+ info = record(query, key: binding[:key], cost: cost, limit: binding[:limit], remaining: binding[:remaining], limited: limited,
125
+ keys: budgets.map { |budget| budget.slice(:key, :limit, :remaining) })
126
+ announce(query, info, cost) if @extensions
127
+ refusal(cost, binding[:limit], binding[:remaining]) if limited && !@soft
128
+ end
129
+
130
+ # What the store answers for each key, without the keys whose store failed.
131
+ def takes(query, limits, cost, force, charging: false)
132
+ limits.filter_map do |key, limit|
133
+ answer = begin
134
+ @store.take(key, cost: cost, limit: limit, window: @window, force: force)
135
+ rescue StandardError => error
136
+ @on_store_error.call(error, query)
137
+ next
138
+ end
139
+ taken, remaining = Settings.checked(answer, :take, "the Integer points left")
140
+ { key: key, limit: limit, remaining: remaining, **(charging ? { taken: taken } : {}) }
141
+ end
142
+ end
143
+
144
+ # What the client is told: a key that can never pay, otherwise the longest wait.
145
+ def binding_budget(refused, cost)
146
+ refused.find { |budget| cost > budget[:limit] } || refused.max_by { |budget| (cost - budget[:remaining]) / budget[:limit].to_f }
147
+ end
148
+
149
+ def announce(query, info, cost)
150
+ query.context.response_extensions["rateLimit"] =
151
+ { "cost" => cost, "limit" => info[:limit], "remaining" => info[:remaining], "resetIn" => self.class.reset_in(info) }
152
+ end
153
+
88
154
  # In the context hash for instrumentation, and per query for `headers`: queries of a multiplex may share one
89
155
  # context hash, where the last query's record wins.
90
156
  def record(query, **info)
91
- info = { **info.slice(:key, :cost, :limit, :remaining), window: @window, soft: @soft, limited: info[:limited] }
157
+ info = { **info.slice(:key, :cost, :limit, :remaining), window: @window, soft: @soft, limited: info[:limited], **info.slice(:keys) }
92
158
  query.context.namespace(NAMESPACE)[:points] = info
93
159
  query.context[CONTEXT_KEY] = info
94
160
  end
@@ -110,14 +176,25 @@ module GraphQL
110
176
 
111
177
  # graphql-ruby's own complexity analysis, then the charge.
112
178
  class Analyzer < GraphQL::Analysis::QueryComplexity
179
+ # graphql-ruby's words when a connection has no `first:`, `last:` or page size. A client can send that, so it answers
180
+ # an error for the client and not a server error. Nothing is charged, and any other error while scoring still raises.
181
+ UNSIZED_CONNECTION = "Can't calculate complexity for "
182
+
113
183
  def result
114
- cost = super
184
+ cost = begin
185
+ super
186
+ rescue GraphQL::Error => error
187
+ raise unless error.instance_of?(GraphQL::Error) && error.message.start_with?(UNSIZED_CONNECTION)
188
+
189
+ query.context[CONTEXT_KEY] = nil
190
+ return AnalysisGuard.answer(query, points) { GraphQL::AnalysisError.new("This connection needs first: or last:", extensions: { "code" => "PAGE_SIZE_REQUIRED" }) }
191
+ end
115
192
  unless cost.is_a?(Numeric) && cost.finite? && !cost.negative?
116
193
  raise ConfigurationError, "the query complexity is #{cost.inspect}: field complexities must be numbers of zero or more"
117
194
  end
118
195
 
119
196
  # Fractional complexities (`complexity: 0.5`) are charged whole points, rounded up.
120
- points.(query, cost.ceil)
197
+ AnalysisGuard.answer(query, points) { points.(query, cost.ceil) }
121
198
  end
122
199
  end
123
200
  end
@@ -17,9 +17,17 @@ module GraphQL
17
17
  class Time
18
18
  CONTEXT_KEY = :rate_limit_time
19
19
  NAMESPACE = :graphql_armory
20
+ BUCKET_PREFIX = "time:"
20
21
 
21
- def self.use(schema, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, clock: Clock.monotonic, extensions: false)
22
- build(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, clock: clock, extensions: extensions).install(schema)
22
+ def self.use(schema, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, sinks: [], clock: Clock.monotonic, extensions: false)
23
+ build(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, sinks: sinks, clock: clock, extensions: extensions).install(schema)
24
+ end
25
+
26
+ # Where a client's milliseconds live in the store: apart from its points, so Points and Time can share a store
27
+ # and a key. Read a balance with this, not with the client's key. In the key's encoding: interpolating a UTF-16
28
+ # key would raise inside the limiter's rescue, which fails open.
29
+ def self.bucket_key(key)
30
+ BUCKET_PREFIX.encode(key.encoding) + key
23
31
  end
24
32
 
25
33
  # HTTP headers for the budget a result recorded: `RateLimit-Time-Limit` and `RateLimit-Time-Remaining` in
@@ -37,13 +45,13 @@ module GraphQL
37
45
  end
38
46
 
39
47
  # Wires the app's store with `use`'s defaults (soft mode); `use` goes through here.
40
- def self.build(store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, clock: Clock.monotonic, extensions: false)
41
- new(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, clock: clock, extensions: extensions)
48
+ def self.build(store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, sinks: [], clock: Clock.monotonic, extensions: false)
49
+ new(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, sinks: sinks, clock: clock, extensions: extensions)
42
50
  end
43
51
 
44
52
  # `new` is inert: with no store wired it refuses every query. It checks every setting, so no partial
45
53
  # configuration lets a query through either.
46
- def initialize(store: Store::Null.new, limit: 1, window: 60, soft: false, key: nil, on_store_error: nil, clock: Clock.monotonic, extensions: false)
54
+ def initialize(store: Store::Null.new, limit: 1, window: 60, soft: false, key: nil, on_store_error: nil, sinks: [], clock: Clock.monotonic, extensions: false)
47
55
  unless Settings.store_answers?(store, take: %i[cost limit window force])
48
56
  raise ConfigurationError, "store: must answer take(key, cost:, limit:, window:, force:), like a MemoryStore"
49
57
  end
@@ -53,7 +61,7 @@ module GraphQL
53
61
  @window = Settings.seconds(:window, window)
54
62
  @soft = Settings.wired_soft(soft, store)
55
63
  @key = Settings.key_reader(key)
56
- @on_store_error = Settings.store_error_handler(on_store_error)
64
+ @on_store_error = Settings.store_error_handler(on_store_error, limiter: :time, sinks: sinks)
57
65
  @clock = Settings.clock(clock)
58
66
  now # a clock that answers anything but a finite number fails here, not by charging nothing
59
67
  @extensions = Settings.extensions(extensions)
@@ -63,8 +71,21 @@ module GraphQL
63
71
  # Adds the analyzer and the trace to the schema.
64
72
  def install(schema)
65
73
  time = self
66
- schema.query_analyzer(Class.new(Analyzer) { define_method(:time) { time } })
74
+ schema.query_analyzer(Class.new(Analyzer) do
75
+ define_method(:time) { time }
76
+ define_singleton_method(:armory_limiter) { time }
77
+ end)
67
78
  schema.trace_with(@trace)
79
+ schema.trace_with(AnalysisGuard)
80
+ end
81
+
82
+ def soft?
83
+ @soft
84
+ end
85
+
86
+ # Whether this query's client has no limit to charge.
87
+ def exempt?(query)
88
+ Settings.exempt?(@key, @limit, query)
68
89
  end
69
90
 
70
91
  # The refusal for a client with no milliseconds left, or nil to let the operation run (and be charged).
@@ -74,6 +95,8 @@ module GraphQL
74
95
  end
75
96
 
76
97
  key = Settings.key_for(@key, query)
98
+ return call_several(query, key) if key.is_a?(Array)
99
+
77
100
  limit = Settings.limit_for(@limit, key, query)
78
101
  if limit.nil?
79
102
  record(query, key: key, limit: nil, remaining: nil, limited: false)
@@ -81,7 +104,7 @@ module GraphQL
81
104
  end
82
105
 
83
106
  answer = begin
84
- @store.take(key, cost: 0, limit: limit, window: @window, force: false)
107
+ @store.take(self.class.bucket_key(key), cost: 0, limit: limit, window: @window, force: false)
85
108
  rescue StandardError => error
86
109
  # Fail open, and still measure: the charge may find the store back.
87
110
  query.context[CONTEXT_KEY] = nil
@@ -135,27 +158,92 @@ module GraphQL
135
158
 
136
159
  private
137
160
 
161
+ # 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
+ # first error a hook raises is raised afterwards.
138
163
  def charge_one(query, debt, cost)
139
- answer = @store.take(debt[:key], cost: cost, limit: debt[:limit], window: @window, force: true)
140
- _taken, remaining = Settings.checked(answer, :take, "the Integer milliseconds left")
141
- settle(query, debt, cost, remaining)
142
- rescue StandardError => error
164
+ failure = nil
165
+ charged = (debt[:others] || {}).to_h do |key, limit|
166
+ [key, charge_key(key, limit, cost)]
167
+ rescue StandardError => error
168
+ failure ||= heard(query, error)
169
+ [key, nil]
170
+ end
171
+ begin
172
+ settle(query, debt, cost, charge_key(debt[:key], debt[:limit], cost), charged)
173
+ rescue StandardError => error
174
+ failure ||= heard(query, error)
175
+ end
176
+ raise failure if failure
177
+ end
178
+
179
+ def charge_key(key, limit, cost)
180
+ answer = @store.take(self.class.bucket_key(key), cost: cost, limit: limit, window: @window, force: true)
181
+ Settings.checked(answer, :take, "the Integer milliseconds left").last
182
+ end
183
+
184
+ # What the hook raised for this error, if it did.
185
+ def heard(query, error)
143
186
  @on_store_error.call(error, query)
187
+ nil
188
+ rescue StandardError => raised
189
+ raised
190
+ end
191
+
192
+ # Reads every balance. A refusal charges none, as with one key; otherwise every key owes the whole time. A key whose
193
+ # store fails at the read still owes it, and the others still decide.
194
+ def call_several(query, keys)
195
+ limits = Settings.limits_for(@limit, keys, query)
196
+ if limits.empty?
197
+ record(query, key: keys.first, limit: nil, remaining: nil, limited: false, keys: [])
198
+ return nil
199
+ end
200
+
201
+ budgets = limits.filter_map do |key, limit|
202
+ answer = begin
203
+ @store.take(self.class.bucket_key(key), cost: 0, limit: limit, window: @window, force: false)
204
+ rescue StandardError => error
205
+ @on_store_error.call(error, query)
206
+ next
207
+ end
208
+ { key: key, limit: limit, remaining: Settings.checked(answer, :take, "the Integer milliseconds left").last }
209
+ end
210
+ if budgets.empty?
211
+ query.context[CONTEXT_KEY] = nil
212
+ first, *rest = limits.to_a
213
+ owe(query, first[0], first[1], others: rest.to_h)
214
+ return nil
215
+ end
216
+
217
+ limited = budgets.any? { |budget| budget[:remaining].zero? }
218
+ binding = budgets.select { |budget| budget[:remaining].zero? }.min_by { |budget| budget[:limit] } || budgets.min_by { |budget| budget[:remaining] }
219
+ info = record(query, key: binding[:key], limit: binding[:limit], remaining: binding[:remaining], limited: limited, keys: budgets)
220
+ extension = announce(query, info) if @extensions
221
+ return refusal(binding[:limit]) if limited && !@soft
222
+
223
+ owe(query, binding[:key], binding[:limit], info, extension, others: limits.reject { |key, _limit| key == binding[:key] })
224
+ nil
144
225
  end
145
226
 
146
227
  # What the client has left once the charge is in, in the record and in the extensions announced earlier.
147
- def settle(query, debt, cost, remaining)
228
+ def settle(query, debt, cost, remaining, others = {})
148
229
  info = (debt[:info] || base_record(key: debt[:key], limit: debt[:limit], limited: false)).merge(remaining: remaining, elapsed: cost)
230
+ if info[:keys]
231
+ current = others.compact.merge(debt[:key] => remaining)
232
+ info[:keys] = info[:keys].map { |budget| budget.merge(remaining: current.fetch(budget[:key], budget[:remaining])) }
233
+ # Keys with different limits refill at different rates during the run, so the binding one may have changed.
234
+ info = info.merge(info[:keys].min_by { |budget| budget[:remaining] })
235
+ remaining = info[:remaining]
236
+ end
149
237
  query.context.namespace(NAMESPACE)[:time] = info
150
238
  query.context[CONTEXT_KEY] = info
151
- debt[:extension]&.merge!("remaining" => remaining, "elapsed" => cost, "resetIn" => Points.reset_in(info))
239
+ debt[:extension]&.merge!("limit" => info[:limit], "remaining" => remaining, "elapsed" => cost, "resetIn" => Points.reset_in(info))
152
240
  end
153
241
 
154
242
  # Per query and per limiter, not in the context hash: queries of a multiplex may share one hash, and a
155
243
  # schema may use several limiters.
156
- def owe(query, key, limit, info = nil, extension = nil)
244
+ def owe(query, key, limit, info = nil, extension = nil, others: {})
157
245
  charges = (query.context.namespace(NAMESPACE)[:time_charges] ||= {})
158
- charges[self] = { key: key, limit: limit, info: info, extension: extension }
246
+ charges[self] = { key: key, limit: limit, info: info, extension: extension, others: others }
159
247
  end
160
248
 
161
249
  def record(query, **info)
@@ -165,8 +253,8 @@ module GraphQL
165
253
  end
166
254
 
167
255
  # `elapsed` is nil until the operation ends and is charged; it stays nil for a refused one.
168
- def base_record(key:, limit:, limited:, remaining: nil)
169
- { key: key, limit: limit, remaining: remaining, elapsed: nil, window: @window, soft: @soft, limited: limited }
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 } : {}) }
170
258
  end
171
259
 
172
260
  # The budget before the run; the charge completes the same hash, which the response already holds.
@@ -200,7 +288,7 @@ module GraphQL
200
288
  # Asks for the balance during analysis, before anything runs.
201
289
  class Analyzer < GraphQL::Analysis::Analyzer
202
290
  def result
203
- time.(query)
291
+ AnalysisGuard.answer(query, time) { time.(query) }
204
292
  end
205
293
  end
206
294
  end
@@ -9,6 +9,8 @@ module GraphQL
9
9
  class ConfigurationError < Armory::Error; end
10
10
 
11
11
  KEY = :rate_limit_key
12
+ # Each key costs store round trips on every query, so a list cannot grow with what a client sends.
13
+ MAX_KEYS = 5
12
14
 
13
15
  # The settings every limiter shares, checked at boot.
14
16
  module Settings
@@ -21,11 +23,28 @@ module GraphQL
21
23
  key
22
24
  end
23
25
 
26
+ # A String, or a list of them for a query that draws from several buckets.
24
27
  def key_for(reader, query)
25
28
  key = reader.call(query)
26
29
  return key if key.is_a?(String) && !key.empty?
30
+ return key if several_keys?(key)
27
31
 
28
- raise ConfigurationError, "no client key for this query: put a non-empty String in context[:#{KEY}], or give the limiter a key: callable"
32
+ raise ConfigurationError, "no client key for this query: put a non-empty String, or a list of up to #{MAX_KEYS} different ones, in context[:#{KEY}], or give the limiter a key: callable"
33
+ end
34
+
35
+ def exempt?(reader, limit, query)
36
+ key = key_for(reader, query)
37
+ key.is_a?(Array) ? limits_for(limit, key, query).empty? : limit_for(limit, key, query).nil?
38
+ end
39
+
40
+ def several_keys?(keys)
41
+ keys.is_a?(Array) && keys.size.between?(1, MAX_KEYS) && keys.all? { |key| key.is_a?(String) && !key.empty? } && keys.map(&:b).uniq.size == keys.size
42
+ end
43
+
44
+ # The limit of each key, with the keys that have none left out. All of them are asked before any store call, so
45
+ # a limit that raises leaves nothing charged or held.
46
+ def limits_for(limit, keys, query)
47
+ keys.to_h { |key| [key, limit_for(limit, key, query)] }.compact
29
48
  end
30
49
 
31
50
  def soft(value)
@@ -110,11 +129,15 @@ module GraphQL
110
129
  value
111
130
  end
112
131
 
113
- def store_error_handler(handler)
114
- return ->(error, _query) { warn("graphql-armory rate limit store failed, query let through: #{error.class}: #{error.message}") } if handler.nil?
115
- raise ConfigurationError, "on_store_error: must be a callable that takes the error and the query" unless handler.respond_to?(:call)
132
+ def store_error_handler(handler, limiter: nil, sinks: [])
133
+ raise ConfigurationError, "on_store_error: must be a callable that takes the error and the query" unless handler.nil? || handler.respond_to?(:call)
116
134
 
117
- handler
135
+ telemetry = Telemetry.build(sinks: sinks)
136
+ handler ||= ->(error, _query) { warn("graphql-armory rate limit store failed, query let through: #{error.class}") }
137
+ lambda do |error, query|
138
+ telemetry.record(:rate_limit_store_failed, context: query.context, limiter: limiter, error: error.class.to_s)
139
+ handler.call(error, query)
140
+ end
118
141
  end
119
142
  end
120
143
  end
@@ -125,6 +148,7 @@ require "graphql/armory/rate_limits/memory_store"
125
148
  require "graphql/armory/rate_limits/store"
126
149
  require "graphql/armory/rate_limits/clock"
127
150
  require "graphql/armory/rate_limits/redis_store"
151
+ require "graphql/armory/rate_limits/analysis_guard"
128
152
  require "graphql/armory/rate_limits/points"
129
153
  require "graphql/armory/rate_limits/concurrency"
130
154
  require "graphql/armory/rate_limits/time"