graphql-armory 0.1.0.pre5 → 0.1.0.pre7

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.
data/docs/telemetry.md ADDED
@@ -0,0 +1,227 @@
1
+ # Telemetry
2
+
3
+ Know what the gem allowed, refused and ran, without writing anything a client chose into your logs.
4
+
5
+ ## The problem
6
+
7
+ A guard that works in silence is hard to operate:
8
+
9
+ - After a new policy ships, did it start denying real users?
10
+ - Is someone sending forged IDs, or did a key rotation leave clients with IDs that no longer decode?
11
+ - Is a client build missing from the persisted query manifest, and how much raw traffic is left before you can turn on `strict: true`?
12
+
13
+ The gem answers all of these with the same response, "not found" or a validation error, on purpose: a client must not learn why it was refused. That is right for the client and blind for you.
14
+
15
+ Logging the request is not the fix. An ID, an operation id or a query is text an attacker chooses, and writing it to a log ([log injection](https://owasp.org/www-community/attacks/Log_Injection)) or a metrics label (unbounded cardinality) turns one probe into a problem for your operations.
16
+
17
+ ## The solution
18
+
19
+ Each module records **signals**: a short name and a small hash with a *reason*, never a value the client sent. You choose where they go by passing **sinks**, any callable that takes `(signal, data)`:
20
+
21
+ ```ruby
22
+ use GraphQL::Armory::IDs, sinks: [->(signal, data) { Rails.logger.info("armory #{signal} #{data}") }]
23
+ ```
24
+
25
+ It is the same mechanism in authorization, encrypted IDs and persisted queries, so one sink can serve all three. A built-in sink, `Telemetry::Notifications`, reports to `ActiveSupport::Notifications`, which is where Rails apps already send logs and metrics from.
26
+
27
+ ## How to use it
28
+
29
+ ### A sink for every module
30
+
31
+ ```ruby
32
+ class AppSchema < GraphQL::Schema
33
+ armory_log = ->(signal, data) { Rails.logger.info("armory #{signal} #{data}") }
34
+
35
+ use GraphQL::Armory::Authorization, adapter: :pundit, sinks: [armory_log]
36
+ use GraphQL::Armory::IDs, sinks: [armory_log]
37
+ use GraphQL::Armory::PersistedQueries, store: PERSISTED_QUERIES, sinks: [armory_log]
38
+ end
39
+ ```
40
+
41
+ ```
42
+ armory id_refused {reason: :invalid}
43
+ armory operation_refused {reason: :unknown_operation}
44
+ armory denied {type: "Invoice", action: :read}
45
+ ```
46
+
47
+ (Ruby before 3.4 prints a hash as `{:reason=>:invalid}`.)
48
+
49
+ ### With ActiveSupport::Notifications
50
+
51
+ ```ruby
52
+ use GraphQL::Armory::IDs, sinks: [GraphQL::Armory::Telemetry::Notifications]
53
+ ```
54
+
55
+ Every signal becomes an event named `<signal>.graphql_armory`, with the signal's data as payload. Subscribe to the ones you care about, or to all of them:
56
+
57
+ ```ruby
58
+ # config/initializers/armory.rb
59
+ ActiveSupport::Notifications.subscribe("id_refused.graphql_armory") do |_name, _start, _finish, _id, payload|
60
+ Metrics.increment("graphql.id_refused", tags: ["reason:#{payload[:reason]}"])
61
+ end
62
+
63
+ ActiveSupport::Notifications.subscribe(/\.graphql_armory\z/) do |name, _start, _finish, _id, payload|
64
+ Rails.logger.info("#{name} #{payload}")
65
+ end
66
+ ```
67
+
68
+ A `reason` has a handful of values, so it is safe as a metrics tag. `Notifications` needs ActiveSupport loaded: passing it without ActiveSupport raises `Telemetry::ConfigurationError` at boot, instead of silently reporting nothing. A Rails app has ActiveSupport fully loaded; outside Rails, `require "active_support"` before `require "active_support/notifications"`, as the latter alone is not enough in recent versions.
69
+
70
+ ### With Datadog
71
+
72
+ A sink is any callable, so a metrics client plugs in directly. With [DogStatsD](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?tab=ruby), every signal becomes a counter and the signal's data becomes its tags:
73
+
74
+ ```ruby
75
+ # Gemfile: gem "dogstatsd-ruby"
76
+ require "datadog/statsd"
77
+
78
+ STATSD = Datadog::Statsd.new("localhost", 8125)
79
+
80
+ datadog = lambda do |signal, data|
81
+ STATSD.increment("graphql_armory.#{signal}", tags: data.map { |key, value| "#{key}:#{value}" })
82
+ end
83
+
84
+ class AppSchema < GraphQL::Schema
85
+ use GraphQL::Armory::Authorization, adapter: :pundit, sinks: [datadog]
86
+ use GraphQL::Armory::IDs, sinks: [datadog]
87
+ use GraphQL::Armory::PersistedQueries, store: PERSISTED_QUERIES, sinks: [datadog]
88
+ end
89
+ ```
90
+
91
+ In Datadog you get metrics such as `graphql_armory.id_refused` with the tag `reason:invalid`, or `graphql_armory.denied` with `type:Invoice` and `action:read`. Graph them, and build a monitor on the ones that should stay near zero (`id_refused` with `reason:invalid`, `operation_refused` with `reason:unknown_operation`). The tags are safe because they hold reasons, type names and actions: few values, none chosen by a client, so they do not inflate your metrics' cardinality.
92
+
93
+ If you already use `ActiveSupport::Notifications`, subscribe once and send from there instead, so the sink stays out of the schema:
94
+
95
+ ```ruby
96
+ ActiveSupport::Notifications.subscribe(/\.graphql_armory\z/) do |name, _start, _finish, _id, payload|
97
+ STATSD.increment("graphql_armory.#{name.delete_suffix(".graphql_armory")}", tags: payload.map { |key, value| "#{key}:#{value}" })
98
+ end
99
+ ```
100
+
101
+ The gem does not depend on Datadog or on any other backend. The same shape works for StatsD, Prometheus, OpenTelemetry or whatever your team uses: write the callable that turns `(signal, data)` into one call of that client. The example above follows Datadog's documented `increment(name, tags:)`; it has not been run against a live agent.
102
+
103
+ ### What to watch for
104
+
105
+ | You see | It usually means | What to do |
106
+ |---|---|---|
107
+ | `id_refused` with `reason: :invalid` rising | Someone is sending forged or tampered IDs, or a key rotation left clients with IDs made with a key you dropped | If it follows a deploy, check [Rotating keys](encrypted-ids.md#rotating-keys-and-migrating-from-base64). Otherwise it is probing: nothing leaked, but you can rate limit that client |
108
+ | `id_refused` with `reason: :not_found` | A record that does not exist, or that is outside the client's scope. The signal is the same for both, as the client's answer is | A few are normal. A burst from one client walking IDs is an enumeration attempt |
109
+ | `operation_refused` with `reason: :unknown_operation` after a deploy | A client build whose operations are not in the manifest you ship | Deploy the manifest before, or with, the client |
110
+ | `operation_refused` with `reason: :raw_query` from one client | A client sending raw queries to a strict endpoint: a probe, or a client not migrated yet. Strict mode refuses before validating, so a detector that counts validation errors does not see it | Count it as a strike. See [Counting probes in strict mode](persisted-queries.md#counting-probes-in-strict-mode) |
111
+ | `raw_query_run` while you are in `strict: false` | Traffic that does not use persisted queries yet | When it reaches zero, turn on `strict: true` |
112
+ | `denied` rising for one `type` | A new or changed policy for that type | Compare with the release; the [audit](authorization.md#the-audit) lists the types and actions the rules cover |
113
+
114
+ ## Signals
115
+
116
+ ### Authorization
117
+
118
+ | Signal | When | Data |
119
+ |---|---|---|
120
+ | `:allowed` | The policy or ability said yes | `type`, `action` |
121
+ | `:denied` | It said no, nil or anything that is not a clear yes | `type`, `action` |
122
+ | `:bypassed` | The rule is `authorize :none, reason: "..."` | `type` (not on lists), `reason` |
123
+ | `:scoped` | A list or lookup went through the user's scope | `action` |
124
+
125
+ `type` is the Ruby class name of the object, `action` the rule's action. Record attributes are never included.
126
+
127
+ ### Encrypted IDs
128
+
129
+ | Signal | When | Data |
130
+ |---|---|---|
131
+ | `:id_resolved` | An ID was honoured and its record found | `type` (GraphQL type name) |
132
+ | `:id_refused` | An ID was not honoured. The client gets `nil` in every case | `reason`, and `type` for `:not_found` |
133
+
134
+ The reasons of `:id_refused`:
135
+
136
+ | Reason | The ID |
137
+ |---|---|
138
+ | `:invalid` | Did not decrypt: forged, tampered, made with another key or tag, or garbage |
139
+ | `:malformed` | Decrypted, but is not `Type/key` |
140
+ | `:unknown_type` | Names a type the schema does not have, that is not visible to this client, or that does not implement `Node` |
141
+ | `:not_found` | Names a real type, but the record is missing or outside the client's scope. One reason for both, as the client cannot tell them apart either |
142
+
143
+ ### Persisted queries
144
+
145
+ | Signal | When | Data |
146
+ |---|---|---|
147
+ | `:operation_persisted` | A request ran the stored operation its id names | none |
148
+ | `:operation_refused` | A request was refused | `reason`: `:unknown_operation`, `:mismatch` (the id and the query sent with it differ) or `:raw_query` (strict mode, no allow flag) |
149
+ | `:raw_query_run` | A raw query ran because the plugin is not strict | none |
150
+ | `:raw_query_allowed` | A raw query ran in strict mode because the context holds `armory_allow_raw_query: true` | none |
151
+
152
+ `:raw_query_allowed` is your audit trail of who uses the escape hatch (staff, development).
153
+
154
+ ### Rate limiting
155
+
156
+ Rate limiting has no sinks. It records on every query, in the query's context, what it charged and what remains: `context[:rate_limit_points]`, `context[:rate_limit_concurrency]` and `context[:rate_limit_time]`, which carry `limited: true` for the queries it refused or, in soft mode, would have refused. See [Rolling it out](rate-limiting.md#rolling-it-out) and [Showing clients their budget](rate-limiting.md#showing-clients-their-budget). Send those to the same place as the signals above.
157
+
158
+ ## What telemetry does not cover
159
+
160
+ Signals are counters of the gem's decisions. They are not a replacement for these:
161
+
162
+ - **Traces.** A signal is a point event, not a span. In Datadog APM (or any tracer) a refused ID does not appear as a span of its own; it shows in the trace of the request that carried it, as the normal "not found" answer. If you want it on the trace, have your sink add a tag to the active span with your tracer's API.
163
+ - **Who asked.** A signal says `id_refused`, not which user or IP. Correlate with your request logs through the request id, or add the user in your own sink from your request context: that is yours to hold, and stays out of the gem.
164
+ - **Rate limiting.** It has no sinks: it records in the query's context. Send `context[:rate_limit_points]`, `context[:rate_limit_concurrency]` and `context[:rate_limit_time]` from your controller, to the same client. They hold the rate limit `key:` (a user id or an IP): send them somewhere that may hold personal data, or leave the key out.
165
+ - **Slow or failing requests.** The gem records its decisions. Latency, errors and throughput of your GraphQL endpoint come from your APM or from graphql-ruby's own tracing.
166
+ - **Anything that did not reach the gem.** A request rejected before GraphQL runs (a web application firewall, a body size limit, a parse error) never produces a signal.
167
+ - **A guarantee of delivery.** Sinks run in the request and report nothing if the process dies first. Counters sent to StatsD are best effort by design.
168
+ - **History.** The gem keeps nothing: the signals are as durable as the place you send them.
169
+
170
+ ## What a signal never holds
171
+
172
+ A signal has a reason and, where it helps, the name of a type or an action. It **never** holds:
173
+
174
+ - an ID, an operation id or a query, which the client chose;
175
+ - a rate limit key, a user id or a record attribute;
176
+ - the exception message of a decryption failure.
177
+
178
+ For IDs and persisted queries a test pins it (`spec/security/telemetry_signals_spec.rb`): a forged ID and an attacker-chosen operation id are sent, and neither appears in anything recorded. Keep it that way in your own sinks: add the request id or the user from *your* request context if you need them, as your logger already does.
179
+
180
+ ## Testing
181
+
182
+ `Telemetry::Substitute` keeps what was recorded, so a test reads it instead of mocking:
183
+
184
+ ```ruby
185
+ telemetry = GraphQL::Armory::Telemetry::Substitute.new
186
+ lookup = GraphQL::Armory::IDs::Lookup.new(
187
+ encoder: GraphQL::Armory::IDs::Controls::Encoder.example,
188
+ telemetry: telemetry
189
+ )
190
+
191
+ lookup.object_for("forged", context)
192
+
193
+ telemetry.recorded # => [[:id_refused, { reason: :invalid }]]
194
+ telemetry.recorded?(:id_refused) # => true
195
+ ```
196
+
197
+ Through `use`, a sink that collects is enough:
198
+
199
+ ```ruby
200
+ seen = []
201
+ use GraphQL::Armory::PersistedQueries, store: store, sinks: [->(signal, data) { seen << [signal, data] }]
202
+ ```
203
+
204
+ ## Reference
205
+
206
+ - `sinks:` is an option of `use GraphQL::Armory::Authorization`, `use GraphQL::Armory::IDs` and `use GraphQL::Armory::PersistedQueries`. An Array of callables taking `(signal, data)`, called in order; default `[]`.
207
+ - `Telemetry.new(sinks: [])`, `Telemetry.build(sinks: [])`, `telemetry.record(signal, **data)` (answers nil; `data` reaches the sinks frozen).
208
+ - `Telemetry::Notifications`: a sink that calls `ActiveSupport::Notifications.instrument("<signal>.graphql_armory", data)`. `Notifications.available?` tells whether ActiveSupport::Notifications is loaded.
209
+ - `Telemetry::Substitute`: `record`, `recorded` (an Array of `[signal, data]`), `recorded?(signal)`, and `fail_with(error)` / `recover` to make `record` raise, as a broken sink would.
210
+ - `Telemetry::ConfigurationError`, raised at boot when `sinks:` is not an Array of callables, or a sink reports `available?` as false. Its message names the class of the offending value and never prints the value: a metrics client holds its API key.
211
+ - `Authorization::Telemetry` is the same class as `Telemetry`.
212
+
213
+ ## Guarantees and limits
214
+
215
+ - **Sinks run inline**, in the request's thread, in the order given. A slow sink slows every request: increment a counter or enqueue, do not call a remote service.
216
+ - **A sink that raises fails the request closed.** The error normally reaches the request, and nothing is let through because of it. One exception: the gem reads an `Encoder::InvalidError` raised while it looks an ID up (and, for an ID given to a `loads:` argument, also an `ArgumentError` or an `ActiveRecord::RecordNotFound`) as an invalid ID and answers `nil`, so a sink raising one of those does not surface (it is still closed: the record is not loaded). If you would rather a broken metrics client never fail a request, rescue inside your sink.
217
+ - **Every sink gets the same frozen data.** The Hash and its String values are frozen, so a sink cannot change what the next one sees: trying raises `FrozenError`. The signals carry only Symbols and Strings today. `Notifications` makes one unfrozen copy per signal, which ActiveSupport passes to every subscriber: a subscriber that changes its payload changes it for the next subscriber.
218
+ - **One request can record many signals**, one per decision (a list of invoices is several), and each query of a batch records its own.
219
+ - **Signals are not a security log by themselves.** They tell you what the gem decided; who asked comes from your request context.
220
+ - Names and reasons are part of the public API, but the gem is in prerelease: they may change before 1.0, and the CHANGELOG says so when they do.
221
+ - Rate limiting reports through the query context, not through sinks.
222
+
223
+ ## References
224
+
225
+ - Rails guides: [Active Support Instrumentation](https://guides.rubyonrails.org/active_support_instrumentation.html), and the API of [`ActiveSupport::Notifications`](https://api.rubyonrails.org/classes/ActiveSupport/Notifications.html).
226
+ - OWASP: [Logging Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html) (what to log and what to leave out) and [Log Injection](https://owasp.org/www-community/attacks/Log_Injection).
227
+ - Eventide: [The Doctrine of Useful Objects](https://eventide-project.org/user-guide/useful-objects.html#the-doctrine-of-useful-objects), the pattern this gem follows: tests read what an object recorded instead of mocking it.
@@ -16,6 +16,7 @@ module GraphQL
16
16
 
17
17
  @adapter = resolve(adapter)
18
18
  @on_unauthorized = on_unauthorized
19
+ Telemetry.build(sinks: sinks) # raises at boot when the sinks are not callables
19
20
  @sinks = sinks
20
21
  end
21
22
 
@@ -41,6 +41,8 @@ module GraphQL
41
41
 
42
42
  # Runs before pagination, so connections page and count the scoped list.
43
43
  def scope_items(items, context)
44
+ return items.rescoped { |relation| scope_items(relation, context) } if items.is_a?(Keyset)
45
+
44
46
  super(Integration.scoped(items, armory_rule, context), context)
45
47
  end
46
48
 
@@ -4,7 +4,6 @@ require "graphql/armory/authorization/errors"
4
4
  require "graphql/armory/authorization/configuration"
5
5
  require "graphql/armory/authorization/rule"
6
6
  require "graphql/armory/authorization/memo"
7
- require "graphql/armory/authorization/telemetry"
8
7
  require "graphql/armory/authorization/adapters/null"
9
8
  require "graphql/armory/authorization/adapters/substitute"
10
9
  require "graphql/armory/authorization/authorize"
@@ -26,6 +25,11 @@ module GraphQL
26
25
  end
27
26
  end
28
27
 
28
+ module Authorization
29
+ # Authorization's telemetry is the gem's: one Telemetry for every module.
30
+ Telemetry = Armory::Telemetry
31
+ end
32
+
29
33
  # Deny-by-default authorization. The core (Authorize, Scope) knows nothing about
30
34
  # Pundit or CanCanCan: it asks an adapter four questions and trusts only a clear answer.
31
35
  module Authorization
@@ -16,23 +16,23 @@ module GraphQL
16
16
  module IDs
17
17
  SEPARATOR = "/"
18
18
 
19
- def self.use(schema, encoder: nil, find: nil)
20
- lookup = Lookup.build(encoder: encoder, find: find)
19
+ def self.use(schema, encoder: nil, find: nil, sinks: [])
20
+ lookup = Lookup.build(encoder: encoder, find: find, sinks: sinks)
21
21
  schema.define_singleton_method(:id_from_object) { |object, type, _context| lookup.id_for(object, type) }
22
22
  schema.define_singleton_method(:object_from_id) { |id, context| lookup.object_for(id, context) }
23
23
  end
24
24
 
25
25
  # Turns records into IDs and IDs back into records.
26
26
  class Lookup
27
- attr_reader :encoder, :find
27
+ attr_reader :encoder, :find, :telemetry
28
28
 
29
29
  # Wires the default encoder unless one is given; `use` goes through here.
30
- def self.build(encoder: nil, find: nil)
31
- new(encoder: encoder || Encoder.default, find: find)
30
+ def self.build(encoder: nil, find: nil, sinks: [])
31
+ new(encoder: encoder || Encoder.default, find: find, telemetry: Telemetry.build(sinks: sinks))
32
32
  end
33
33
 
34
34
  # `new` is inert: with no encoder wired it hands out no ID and honours none. It checks what it is given.
35
- def initialize(encoder: Encoder::Null, find: nil)
35
+ def initialize(encoder: Encoder::Null, find: nil, telemetry: Telemetry.new)
36
36
  unless %i[encode decode].all? { |name| encoder.respond_to?(name) }
37
37
  raise Encoder::ConfigurationError, "encoder: must answer encode and decode, like an Encoder subclass"
38
38
  end
@@ -40,6 +40,7 @@ module GraphQL
40
40
 
41
41
  @encoder = encoder
42
42
  @find = find
43
+ @telemetry = telemetry
43
44
  end
44
45
 
45
46
  def id_for(object, type)
@@ -51,18 +52,28 @@ module GraphQL
51
52
 
52
53
  def object_for(id, context)
53
54
  type_name, key = encoder.decode(id).split(SEPARATOR, 2)
54
- return nil if key.nil? || key.empty?
55
+ return refuse(:malformed) if key.nil? || key.empty?
55
56
 
56
57
  type = visible_type(type_name, context)
57
- return nil unless node_type?(type)
58
+ return refuse(:unknown_type) unless node_type?(type)
58
59
 
59
- load(type, key, context)
60
+ object = load(type, key, context)
61
+ return refuse(:not_found, type: type.graphql_name) if object.nil?
62
+
63
+ telemetry.record(:id_resolved, type: type.graphql_name)
64
+ object
60
65
  rescue Encoder::InvalidError
61
- nil
66
+ refuse(:invalid)
62
67
  end
63
68
 
64
69
  private
65
70
 
71
+ # Every refusal answers nil, like a missing record; the signal says why, never which ID.
72
+ def refuse(reason, **data)
73
+ telemetry.record(:id_refused, reason: reason, **data)
74
+ nil
75
+ end
76
+
66
77
  # Through the query's own view of the schema: `Schema.get_type(name, context)` does not apply `visible?`
67
78
  # when graphql-ruby runs without `Schema::Visibility`, `context.types` does in both modes.
68
79
  def visible_type(type_name, context)
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ class Keyset
6
+ # Test data for keyset connections, reusable by apps and other gems.
7
+ module Controls
8
+ # A schema with one connection field, `items`, that answers what the root value holds.
9
+ module Schema
10
+ def self.example(base: GraphQL::Schema, cursor_encoder: nil, max_page_size: nil)
11
+ item = Class.new(GraphQL::Schema::Object) do
12
+ graphql_name "Item"
13
+ field :id, String, null: false
14
+ end
15
+ root = Class.new(GraphQL::Schema::Object) do
16
+ graphql_name "Query"
17
+ field :items, item.connection_type, null: false
18
+ end
19
+ Class.new(base) do
20
+ query(root)
21
+ cursor_encoder(cursor_encoder) if cursor_encoder
22
+ default_max_page_size(max_page_size) if max_page_size
23
+ end
24
+ end
25
+ end
26
+
27
+ # The root value `Schema.example` reads its connection from.
28
+ module Root
29
+ def self.example(connection)
30
+ Struct.new(:items).new(connection)
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,279 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module GraphQL
6
+ module Armory
7
+ # A connection that pages an ActiveRecord relation by the values of its ordering columns instead of OFFSET,
8
+ # so rows inserted or deleted between pages neither skip nor repeat items. Return it from a resolver:
9
+ #
10
+ # def invoices
11
+ # GraphQL::Armory::Keyset.build(Invoice.order(created_at: :desc))
12
+ # end
13
+ #
14
+ # A cursor holds the row's ordering values. Base64 cursors would let a client read them and forge them to
15
+ # search a column it cannot see, so the schema's default encoder is refused unless `plain_cursors: true`.
16
+ class Keyset < GraphQL::Pagination::Connection
17
+ class ConfigurationError < Armory::Error; end
18
+
19
+ CURSOR_VERSION = 1
20
+ PAGEABLE_TYPES = %i[integer string text decimal datetime date boolean uuid].freeze
21
+
22
+ # The forms this connection's own cursors have. A forged decimal like 1e99999999999 would exhaust memory.
23
+ DECIMAL_FORM = /\A-?\d{1,65}(\.\d{1,65})?\z/
24
+ DATE_FORM = /\A\d{4}-\d{2}-\d{2}\z/
25
+ DATETIME_FORM = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})\z/
26
+
27
+ Column = Struct.new(:name, :direction, :attribute, :type, keyword_init: true)
28
+
29
+ # Reads what a relation is ordered by, adds the primary key as the tie-breaker, and refuses what it cannot page.
30
+ module Ordering
31
+ def self.call(relation)
32
+ refuse("a limit") if relation.limit_value
33
+ refuse("an offset") if relation.offset_value
34
+ refuse("a group") if relation.group_values.any?
35
+ refuse("a select") if relation.select_values.any?
36
+ refuse("a join that is not distinct: it can repeat rows") if joined?(relation) && !relation.distinct_value
37
+
38
+ columns = relation.order_values.map { |order| column(relation.klass, order) }.uniq(&:name)
39
+ primary_key = Array(relation.klass.primary_key)
40
+ refuse("a model without a primary key") if primary_key.empty?
41
+
42
+ direction = columns.last&.direction || :asc
43
+ (primary_key - columns.map(&:name)).each { |name| columns << column_named(relation.klass, name, direction) }
44
+ columns.freeze
45
+ end
46
+
47
+ def self.joined?(relation)
48
+ relation.joins_values.any? || relation.left_outer_joins_values.any?
49
+ end
50
+
51
+ def self.column(klass, order)
52
+ direction = { Arel::Nodes::Ascending => :asc, Arel::Nodes::Descending => :desc }[order.class]
53
+ attribute = order.expr if direction
54
+ refuse("an order that is not a plain column: #{order.class}") unless attribute.is_a?(Arel::Attributes::Attribute)
55
+ refuse("an order on another table: #{attribute.relation.name}") unless attribute.relation.name == klass.table_name
56
+
57
+ column_named(klass, attribute.name.to_s, direction)
58
+ end
59
+
60
+ def self.column_named(klass, name, direction)
61
+ definition = klass.columns_hash[name]
62
+ refuse("an order on an unknown column: #{name}") if definition.nil?
63
+ refuse("an order on a nullable column: #{name}") if definition.null && klass.primary_key != name
64
+
65
+ type = klass.type_for_attribute(name)
66
+ refuse("an order on a #{type.type} column: #{name}") unless PAGEABLE_TYPES.include?(type.type)
67
+ refuse("an order on a serialized or encrypted column: #{name}") if transformed?(type)
68
+
69
+ Column.new(name: name, direction: direction, attribute: klass.arel_table[name], type: type)
70
+ end
71
+
72
+ # These report the type they store as, but the database does not order them by the value a cursor holds.
73
+ # `normalizes` wraps the type it is declared over, so the wrapped types count too.
74
+ def self.transformed?(type)
75
+ return true if type.is_a?(ActiveRecord::Type::Serialized) || type.is_a?(ActiveRecord::Encryption::EncryptedAttributeType)
76
+
77
+ type.respond_to?(:cast_type) && transformed?(type.cast_type)
78
+ end
79
+
80
+ def self.refuse(what)
81
+ raise ConfigurationError, "a keyset connection cannot page #{what}"
82
+ end
83
+ end
84
+
85
+ attr_reader :columns
86
+
87
+ # Checks the relation and its ordering; resolvers go through here.
88
+ def self.build(relation, plain_cursors: false)
89
+ raise ConfigurationError, "plain_cursors: must be true or false, got #{plain_cursors.inspect}" unless [true, false].include?(plain_cursors)
90
+ raise ConfigurationError, "a keyset connection needs an ActiveRecord relation, got #{relation.class}" unless relation.respond_to?(:order_values)
91
+
92
+ new(relation, columns: Ordering.(relation), plain_cursors: plain_cursors)
93
+ end
94
+
95
+ # `new` is inert: with no relation it has no rows, no pages and no cursors.
96
+ def initialize(items = nil, columns: [], plain_cursors: false, **options)
97
+ super(columns.empty? ? nil : items, **options)
98
+ @columns = columns
99
+ @plain_cursors = plain_cursors
100
+ end
101
+
102
+ # This connection over the relation the block answers: how a type's scope reaches the rows. A scope that did
103
+ # not change the relation answers the same object, so graphql-ruby does not take the list as narrowed.
104
+ def rescoped
105
+ return self if items.nil?
106
+
107
+ relation = yield(items)
108
+ return self if relation.equal?(items)
109
+
110
+ dup.scope_to(relation, self.class.build(relation, plain_cursors: @plain_cursors).columns)
111
+ end
112
+
113
+ def nodes
114
+ load_page
115
+ @nodes
116
+ end
117
+
118
+ def has_next_page
119
+ return false if items.nil?
120
+
121
+ load_page
122
+ return @more if !@backward && before.nil?
123
+ return false if @backward && before.nil?
124
+
125
+ anchor = @nodes.last
126
+ anchor ? beyond?(key_of(anchor), :after) : beyond?(@before_key, :after, inclusive: true)
127
+ end
128
+
129
+ def has_previous_page
130
+ return false if items.nil?
131
+
132
+ load_page
133
+ return @more if @backward && after.nil?
134
+ return false if !@backward && after.nil?
135
+
136
+ anchor = @nodes.first
137
+ anchor ? beyond?(key_of(anchor), :before) : beyond?(@after_key, :before, inclusive: true)
138
+ end
139
+
140
+ def cursor_for(item)
141
+ return nil if items.nil?
142
+
143
+ refuse_plain_cursors
144
+ values = columns.map { |column| dump(column.type.serialize(item[column.name])) }
145
+ encode(JSON.generate("v" => CURSOR_VERSION, "o" => fingerprint, "k" => values))
146
+ end
147
+
148
+ protected
149
+
150
+ def scope_to(relation, columns)
151
+ @items = relation
152
+ @columns = columns
153
+ self
154
+ end
155
+
156
+ private
157
+
158
+ def load_page
159
+ return if defined?(@nodes)
160
+
161
+ return @nodes = [] if items.nil?
162
+
163
+ refuse_plain_cursors
164
+ raise GraphQL::ExecutionError, "first and last cannot be used together" if first_value && last_value
165
+
166
+ @after_key = after && key_from(after)
167
+ @before_key = before && key_from(before)
168
+ @backward = !last_value.nil?
169
+ limit = @backward ? last : first
170
+
171
+ relation = items
172
+ relation = relation.where(condition(@after_key, :after)) if @after_key
173
+ relation = relation.where(condition(@before_key, :before)) if @before_key
174
+ relation = relation.reorder(columns.map { |column| arel_order(column) })
175
+ relation = relation.limit(limit + 1) if limit
176
+
177
+ rows = relation.to_a
178
+ @more = !limit.nil? && rows.size > limit
179
+ rows = rows.first(limit) if limit
180
+ @nodes = @backward ? rows.reverse : rows
181
+ end
182
+
183
+ def refuse_plain_cursors
184
+ return if @plain_cursors
185
+
186
+ encoder = context&.schema&.cursor_encoder
187
+ return unless encoder.nil? || encoder == GraphQL::Schema::Base64Encoder
188
+
189
+ raise ConfigurationError,
190
+ "a keyset cursor holds the row's ordering values: set an encrypting cursor_encoder on the schema " \
191
+ "(GraphQL::Armory::Encoder), or pass plain_cursors: true if those values are not secret"
192
+ end
193
+
194
+ def arel_order(column)
195
+ forward = column.direction == :asc
196
+ forward = !forward if @backward
197
+ forward ? column.attribute.asc : column.attribute.desc
198
+ end
199
+
200
+ def beyond?(key, side, inclusive: false)
201
+ items.where(condition(key, side, inclusive: inclusive)).exists?
202
+ end
203
+
204
+ # (a > x) OR (a = x AND b > y) OR ...: the rows past `key` on `side`, for any mix of directions.
205
+ def condition(key, side, inclusive: false)
206
+ pairs = columns.zip(key)
207
+ branches = pairs.each_index.map do |index|
208
+ column, value = pairs[index]
209
+ ascending = (column.direction == :asc) == (side == :after)
210
+ past = ascending ? column.attribute.gt(value) : column.attribute.lt(value)
211
+ pairs.first(index).reverse_each.inject(past) { |node, (earlier, equal)| earlier.attribute.eq(equal).and(node) }
212
+ end
213
+ branches << pairs.map { |column, value| column.attribute.eq(value) }.inject(:and) if inclusive
214
+ branches.inject(:or)
215
+ end
216
+
217
+ def key_of(record)
218
+ columns.map { |column| record[column.name] }
219
+ end
220
+
221
+ def fingerprint
222
+ columns.map { |column| "#{column.attribute.relation.name}.#{column.name}:#{column.direction}" }.join(",")
223
+ end
224
+
225
+ def dump(value)
226
+ return value.getutc.iso8601(9) if value.respond_to?(:getutc)
227
+
228
+ case value
229
+ when BigDecimal then value.to_s("F")
230
+ when Date then value.iso8601
231
+ else value
232
+ end
233
+ end
234
+
235
+ # Every cursor that cannot be honoured answers the same error, whatever is wrong with it.
236
+ def key_from(cursor)
237
+ payload = JSON.parse(decoded(cursor))
238
+ raise Encoder::InvalidError unless payload.is_a?(Hash) && payload["v"] == CURSOR_VERSION && payload["o"] == fingerprint
239
+
240
+ values = payload["k"]
241
+ raise Encoder::InvalidError unless values.is_a?(Array) && values.size == columns.size
242
+
243
+ columns.zip(values).map { |column, value| load_value(column, value) }
244
+ rescue JSON::ParserError, EncodingError, ActiveModel::RangeError
245
+ raise Encoder::InvalidError
246
+ end
247
+
248
+ # Anything a custom encoder raises on a bad cursor, or a nil it answers, is one more invalid cursor.
249
+ def decoded(cursor)
250
+ decode(cursor).dup.force_encoding(Encoding::UTF_8).tap { |text| raise Encoder::InvalidError unless text.valid_encoding? }
251
+ rescue StandardError
252
+ raise Encoder::InvalidError
253
+ end
254
+
255
+ def well_formed?(kind, value)
256
+ case kind
257
+ when :integer then value.is_a?(Integer)
258
+ when :boolean then value == true || value == false
259
+ when :decimal then value.is_a?(String) && DECIMAL_FORM.match?(value)
260
+ when :date then value.is_a?(String) && DATE_FORM.match?(value)
261
+ when :datetime then value.is_a?(String) && DATETIME_FORM.match?(value)
262
+ else value.is_a?(String) && !value.include?("\0")
263
+ end
264
+ end
265
+
266
+ def load_value(column, value)
267
+ raise Encoder::InvalidError unless well_formed?(column.type.type, value)
268
+
269
+ cast = column.type.cast(value)
270
+ raise Encoder::InvalidError if cast.nil?
271
+
272
+ column.type.serialize(cast)
273
+ cast
274
+ end
275
+ end
276
+ end
277
+ end
278
+
279
+ require "graphql/armory/keyset/controls"