graphql-armory 0.1.0.pre4 → 0.1.0.pre6
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +18 -0
- data/README.md +6 -4
- data/docs/authorization.md +9 -1
- data/docs/encrypted-ids.md +20 -1
- data/docs/persisted-queries.md +23 -1
- data/docs/rate-limiting.md +344 -0
- data/docs/telemetry.md +226 -0
- data/lib/graphql/armory/authorization/configuration.rb +1 -0
- data/lib/graphql/armory/authorization.rb +5 -1
- data/lib/graphql/armory/encoder/null.rb +18 -0
- data/lib/graphql/armory/encoder/substitute.rb +47 -0
- data/lib/graphql/armory/encoder.rb +2 -0
- data/lib/graphql/armory/ids/controls.rb +24 -0
- data/lib/graphql/armory/ids.rb +32 -8
- data/lib/graphql/armory/persisted_queries/controls.rb +41 -0
- data/lib/graphql/armory/persisted_queries/store.rb +48 -0
- data/lib/graphql/armory/persisted_queries.rb +64 -30
- data/lib/graphql/armory/rate_limits/clock.rb +35 -0
- data/lib/graphql/armory/rate_limits/concurrency.rb +127 -0
- data/lib/graphql/armory/rate_limits/controls.rb +56 -0
- data/lib/graphql/armory/rate_limits/memory_store.rb +64 -0
- data/lib/graphql/armory/rate_limits/points.rb +126 -0
- data/lib/graphql/armory/rate_limits/redis_store.rb +133 -0
- data/lib/graphql/armory/rate_limits/store.rb +114 -0
- data/lib/graphql/armory/rate_limits/time.rb +209 -0
- data/lib/graphql/armory/rate_limits.rb +131 -0
- data/lib/graphql/armory/telemetry.rb +82 -0
- data/lib/graphql/armory/version.rb +1 -1
- data/lib/graphql/armory.rb +2 -0
- metadata +18 -2
- data/lib/graphql/armory/authorization/telemetry.rb +0 -42
data/docs/telemetry.md
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
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
|
+
| `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` |
|
|
111
|
+
| `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 |
|
|
112
|
+
|
|
113
|
+
## Signals
|
|
114
|
+
|
|
115
|
+
### Authorization
|
|
116
|
+
|
|
117
|
+
| Signal | When | Data |
|
|
118
|
+
|---|---|---|
|
|
119
|
+
| `:allowed` | The policy or ability said yes | `type`, `action` |
|
|
120
|
+
| `:denied` | It said no, nil or anything that is not a clear yes | `type`, `action` |
|
|
121
|
+
| `:bypassed` | The rule is `authorize :none, reason: "..."` | `type` (not on lists), `reason` |
|
|
122
|
+
| `:scoped` | A list or lookup went through the user's scope | `action` |
|
|
123
|
+
|
|
124
|
+
`type` is the Ruby class name of the object, `action` the rule's action. Record attributes are never included.
|
|
125
|
+
|
|
126
|
+
### Encrypted IDs
|
|
127
|
+
|
|
128
|
+
| Signal | When | Data |
|
|
129
|
+
|---|---|---|
|
|
130
|
+
| `:id_resolved` | An ID was honoured and its record found | `type` (GraphQL type name) |
|
|
131
|
+
| `:id_refused` | An ID was not honoured. The client gets `nil` in every case | `reason`, and `type` for `:not_found` |
|
|
132
|
+
|
|
133
|
+
The reasons of `:id_refused`:
|
|
134
|
+
|
|
135
|
+
| Reason | The ID |
|
|
136
|
+
|---|---|
|
|
137
|
+
| `:invalid` | Did not decrypt: forged, tampered, made with another key or tag, or garbage |
|
|
138
|
+
| `:malformed` | Decrypted, but is not `Type/key` |
|
|
139
|
+
| `:unknown_type` | Names a type the schema does not have, that is not visible to this client, or that does not implement `Node` |
|
|
140
|
+
| `: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 |
|
|
141
|
+
|
|
142
|
+
### Persisted queries
|
|
143
|
+
|
|
144
|
+
| Signal | When | Data |
|
|
145
|
+
|---|---|---|
|
|
146
|
+
| `:operation_persisted` | A request ran the stored operation its id names | none |
|
|
147
|
+
| `: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) |
|
|
148
|
+
| `:raw_query_run` | A raw query ran because the plugin is not strict | none |
|
|
149
|
+
| `:raw_query_allowed` | A raw query ran in strict mode because the context holds `armory_allow_raw_query: true` | none |
|
|
150
|
+
|
|
151
|
+
`:raw_query_allowed` is your audit trail of who uses the escape hatch (staff, development).
|
|
152
|
+
|
|
153
|
+
### Rate limiting
|
|
154
|
+
|
|
155
|
+
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.
|
|
156
|
+
|
|
157
|
+
## What telemetry does not cover
|
|
158
|
+
|
|
159
|
+
Signals are counters of the gem's decisions. They are not a replacement for these:
|
|
160
|
+
|
|
161
|
+
- **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.
|
|
162
|
+
- **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.
|
|
163
|
+
- **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.
|
|
164
|
+
- **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.
|
|
165
|
+
- **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.
|
|
166
|
+
- **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.
|
|
167
|
+
- **History.** The gem keeps nothing: the signals are as durable as the place you send them.
|
|
168
|
+
|
|
169
|
+
## What a signal never holds
|
|
170
|
+
|
|
171
|
+
A signal has a reason and, where it helps, the name of a type or an action. It **never** holds:
|
|
172
|
+
|
|
173
|
+
- an ID, an operation id or a query, which the client chose;
|
|
174
|
+
- a rate limit key, a user id or a record attribute;
|
|
175
|
+
- the exception message of a decryption failure.
|
|
176
|
+
|
|
177
|
+
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.
|
|
178
|
+
|
|
179
|
+
## Testing
|
|
180
|
+
|
|
181
|
+
`Telemetry::Substitute` keeps what was recorded, so a test reads it instead of mocking:
|
|
182
|
+
|
|
183
|
+
```ruby
|
|
184
|
+
telemetry = GraphQL::Armory::Telemetry::Substitute.new
|
|
185
|
+
lookup = GraphQL::Armory::IDs::Lookup.new(
|
|
186
|
+
encoder: GraphQL::Armory::IDs::Controls::Encoder.example,
|
|
187
|
+
telemetry: telemetry
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
lookup.object_for("forged", context)
|
|
191
|
+
|
|
192
|
+
telemetry.recorded # => [[:id_refused, { reason: :invalid }]]
|
|
193
|
+
telemetry.recorded?(:id_refused) # => true
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
Through `use`, a sink that collects is enough:
|
|
197
|
+
|
|
198
|
+
```ruby
|
|
199
|
+
seen = []
|
|
200
|
+
use GraphQL::Armory::PersistedQueries, store: store, sinks: [->(signal, data) { seen << [signal, data] }]
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
## Reference
|
|
204
|
+
|
|
205
|
+
- `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 `[]`.
|
|
206
|
+
- `Telemetry.new(sinks: [])`, `Telemetry.build(sinks: [])`, `telemetry.record(signal, **data)` (answers nil; `data` reaches the sinks frozen).
|
|
207
|
+
- `Telemetry::Notifications`: a sink that calls `ActiveSupport::Notifications.instrument("<signal>.graphql_armory", data)`. `Notifications.available?` tells whether ActiveSupport::Notifications is loaded.
|
|
208
|
+
- `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.
|
|
209
|
+
- `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.
|
|
210
|
+
- `Authorization::Telemetry` is the same class as `Telemetry`.
|
|
211
|
+
|
|
212
|
+
## Guarantees and limits
|
|
213
|
+
|
|
214
|
+
- **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.
|
|
215
|
+
- **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.
|
|
216
|
+
- **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.
|
|
217
|
+
- **One request can record many signals**, one per decision (a list of invoices is several), and each query of a batch records its own.
|
|
218
|
+
- **Signals are not a security log by themselves.** They tell you what the gem decided; who asked comes from your request context.
|
|
219
|
+
- 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.
|
|
220
|
+
- Rate limiting reports through the query context, not through sinks.
|
|
221
|
+
|
|
222
|
+
## References
|
|
223
|
+
|
|
224
|
+
- 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).
|
|
225
|
+
- 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).
|
|
226
|
+
- 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.
|
|
@@ -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
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
class Encoder
|
|
6
|
+
# The encoder of an object nobody wired: it hands out no ID and honours none.
|
|
7
|
+
module Null
|
|
8
|
+
def self.encode(_text, nonce: false)
|
|
9
|
+
raise ConfigurationError, "no encoder wired: give an Encoder (or use Encoder.default)"
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
def self.decode(_text, nonce: false)
|
|
13
|
+
raise InvalidError
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
end
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
class Encoder
|
|
6
|
+
# Encodes reversibly without a key or any cryptography, records what it encoded and decoded, and fails when
|
|
7
|
+
# told: for tests of the objects that use an encoder. Never use it to hand out real IDs: anyone can forge them.
|
|
8
|
+
class Substitute
|
|
9
|
+
PREFIX = "substitute:"
|
|
10
|
+
|
|
11
|
+
attr_reader :encoded, :decoded
|
|
12
|
+
|
|
13
|
+
def initialize
|
|
14
|
+
@encoded = []
|
|
15
|
+
@decoded = []
|
|
16
|
+
@failure = nil
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# Raises `error` from every encode and decode until `recover`.
|
|
20
|
+
def fail_with(error)
|
|
21
|
+
@failure = error
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def recover
|
|
25
|
+
@failure = nil
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def encode(text, nonce: false)
|
|
29
|
+
@encoded << text.to_s
|
|
30
|
+
raise @failure if @failure
|
|
31
|
+
|
|
32
|
+
PREFIX + URLSafeBase64.encode(text.to_s.b)
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def decode(text, nonce: false)
|
|
36
|
+
@decoded << text.to_s
|
|
37
|
+
raise @failure if @failure
|
|
38
|
+
raise InvalidError unless text.to_s.start_with?(PREFIX)
|
|
39
|
+
|
|
40
|
+
URLSafeBase64.decode(text.to_s.delete_prefix(PREFIX)).force_encoding(Encoding::UTF_8)
|
|
41
|
+
rescue ArgumentError
|
|
42
|
+
raise InvalidError
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
module IDs
|
|
6
|
+
# Test data for encrypted IDs, reusable by apps and other gems.
|
|
7
|
+
module Controls
|
|
8
|
+
# An Encoder subclass with a fixed test key. Never use its key in production.
|
|
9
|
+
module Encoder
|
|
10
|
+
def self.example(key: "k" * 32)
|
|
11
|
+
Class.new(Armory::Encoder) { key(key) }
|
|
12
|
+
end
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# A record with an id, as `id_from_object` receives it.
|
|
16
|
+
module Record
|
|
17
|
+
def self.example(id: 1)
|
|
18
|
+
Struct.new(:id).new(id)
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
end
|
data/lib/graphql/armory/ids.rb
CHANGED
|
@@ -16,19 +16,31 @@ module GraphQL
|
|
|
16
16
|
module IDs
|
|
17
17
|
SEPARATOR = "/"
|
|
18
18
|
|
|
19
|
-
def self.use(schema, encoder: nil, find: nil)
|
|
20
|
-
lookup = Lookup.
|
|
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
|
+
|
|
29
|
+
# Wires the default encoder unless one is given; `use` goes through here.
|
|
30
|
+
def self.build(encoder: nil, find: nil, sinks: [])
|
|
31
|
+
new(encoder: encoder || Encoder.default, find: find, telemetry: Telemetry.build(sinks: sinks))
|
|
32
|
+
end
|
|
33
|
+
|
|
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, telemetry: Telemetry.new)
|
|
36
|
+
unless %i[encode decode].all? { |name| encoder.respond_to?(name) }
|
|
37
|
+
raise Encoder::ConfigurationError, "encoder: must answer encode and decode, like an Encoder subclass"
|
|
38
|
+
end
|
|
39
|
+
raise Encoder::ConfigurationError, "find: must be nil or a callable taking the type, the key and the context" unless find.nil? || find.respond_to?(:call)
|
|
28
40
|
|
|
29
|
-
def initialize(encoder:, find: nil)
|
|
30
41
|
@encoder = encoder
|
|
31
42
|
@find = find
|
|
43
|
+
@telemetry = telemetry
|
|
32
44
|
end
|
|
33
45
|
|
|
34
46
|
def id_for(object, type)
|
|
@@ -40,18 +52,28 @@ module GraphQL
|
|
|
40
52
|
|
|
41
53
|
def object_for(id, context)
|
|
42
54
|
type_name, key = encoder.decode(id).split(SEPARATOR, 2)
|
|
43
|
-
return
|
|
55
|
+
return refuse(:malformed) if key.nil? || key.empty?
|
|
44
56
|
|
|
45
57
|
type = visible_type(type_name, context)
|
|
46
|
-
return
|
|
58
|
+
return refuse(:unknown_type) unless node_type?(type)
|
|
47
59
|
|
|
48
|
-
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
|
|
49
65
|
rescue Encoder::InvalidError
|
|
50
|
-
|
|
66
|
+
refuse(:invalid)
|
|
51
67
|
end
|
|
52
68
|
|
|
53
69
|
private
|
|
54
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
|
+
|
|
55
77
|
# Through the query's own view of the schema: `Schema.get_type(name, context)` does not apply `visible?`
|
|
56
78
|
# when graphql-ruby runs without `Schema::Visibility`, `context.types` does in both modes.
|
|
57
79
|
def visible_type(type_name, context)
|
|
@@ -74,3 +96,5 @@ module GraphQL
|
|
|
74
96
|
end
|
|
75
97
|
end
|
|
76
98
|
end
|
|
99
|
+
|
|
100
|
+
require "graphql/armory/ids/controls"
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
module PersistedQueries
|
|
6
|
+
# Test data for persisted queries, reusable by apps and other gems.
|
|
7
|
+
module Controls
|
|
8
|
+
# The operations a client build would persist for Query.example.
|
|
9
|
+
module Operations
|
|
10
|
+
def self.invoices = "query Invoices { invoices }"
|
|
11
|
+
def self.greeting = "query Greeting($name: String!) { greeting(name: $name) }"
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
# A Query type with two persisted operations' fields and a `secret` no operation asks for.
|
|
15
|
+
module Query
|
|
16
|
+
def self.example
|
|
17
|
+
Class.new(GraphQL::Schema::Object) do
|
|
18
|
+
graphql_name "Query"
|
|
19
|
+
field :invoices, [String], null: false
|
|
20
|
+
field :greeting, String, null: false do
|
|
21
|
+
argument :name, String
|
|
22
|
+
end
|
|
23
|
+
field :secret, String, null: false
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# The root object for Query.example; it adds the name of each field it resolves to `resolved`.
|
|
29
|
+
module Root
|
|
30
|
+
def self.example(resolved = [])
|
|
31
|
+
Class.new do
|
|
32
|
+
define_method(:invoices) { resolved << :invoices; ["A-1"] }
|
|
33
|
+
define_method(:greeting) { |name:| resolved << :greeting; "Hello #{name}" }
|
|
34
|
+
define_method(:secret) { resolved << :secret; "s3cr3t" }
|
|
35
|
+
end.new
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
|
|
5
|
+
module GraphQL
|
|
6
|
+
module Armory
|
|
7
|
+
module PersistedQueries
|
|
8
|
+
# What the plugin fetches operations from: a `Manifest`, or any object answering `fetch(id)`. `Null` and
|
|
9
|
+
# `Substitute` are the inert and the test stand-ins.
|
|
10
|
+
module Store
|
|
11
|
+
# The store of a plugin nobody wired: it holds no operation, so every id is unknown.
|
|
12
|
+
class Null
|
|
13
|
+
def fetch(_id)
|
|
14
|
+
nil
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# Holds the given queries under the SHA-256 of each, like an Apollo manifest, records the ids it was asked
|
|
19
|
+
# for and fails when told: for tests, instead of hand-written stores.
|
|
20
|
+
class Substitute
|
|
21
|
+
attr_reader :fetched
|
|
22
|
+
|
|
23
|
+
def initialize(*queries)
|
|
24
|
+
@manifest = Manifest.new(queries.to_h { |query| [Digest::SHA256.hexdigest(query), query] })
|
|
25
|
+
@fetched = []
|
|
26
|
+
@failure = nil
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Raises `error` from every fetch until `recover`.
|
|
30
|
+
def fail_with(error)
|
|
31
|
+
@failure = error
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def recover
|
|
35
|
+
@failure = nil
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def fetch(id)
|
|
39
|
+
@fetched << id
|
|
40
|
+
raise @failure if @failure
|
|
41
|
+
|
|
42
|
+
@manifest.fetch(id)
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
end
|
|
@@ -39,21 +39,76 @@ module GraphQL
|
|
|
39
39
|
|
|
40
40
|
# `store:` answers `fetch(id)` with an operation (`body` and `document`) or nil: a Manifest, or your own.
|
|
41
41
|
# `strict: true` refuses raw queries unless the context holds `armory_allow_raw_query: true`.
|
|
42
|
-
def self.use(schema, store:, strict: false)
|
|
43
|
-
|
|
44
|
-
raise ConfigurationError, "store: must answer fetch(id) with an operation or nil, like a Manifest"
|
|
45
|
-
end
|
|
46
|
-
raise ConfigurationError, "strict: must be true or false, got #{strict.inspect}" unless strict == true || strict == false
|
|
42
|
+
def self.use(schema, store:, strict: false, sinks: [])
|
|
43
|
+
gate = Gate.build(store: store, strict: strict, sinks: sinks)
|
|
47
44
|
|
|
48
45
|
if schema.singleton_class.include?(Guard)
|
|
49
46
|
raise ConfigurationError, "#{schema} already uses PersistedQueries (here or in a parent schema): use it once"
|
|
50
47
|
end
|
|
51
48
|
|
|
52
|
-
schema.instance_variable_set(:@armory_persisted_queries,
|
|
49
|
+
schema.instance_variable_set(:@armory_persisted_queries, gate)
|
|
53
50
|
schema.singleton_class.prepend(Guard)
|
|
54
51
|
schema.query_class(schema.query_class)
|
|
55
52
|
end
|
|
56
53
|
|
|
54
|
+
# Decides what a request runs: answers `[refusal, document]`, where a refusal is the error message, a
|
|
55
|
+
# document is the stored operation to run instead of the request's text, and `[nil, nil]` runs the request
|
|
56
|
+
# as it came.
|
|
57
|
+
class Gate
|
|
58
|
+
# Wires the app's store with `use`'s defaults; `use` goes through here.
|
|
59
|
+
def self.build(store:, strict: false, sinks: [])
|
|
60
|
+
new(store: store, strict: strict, telemetry: Telemetry.build(sinks: sinks))
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# `new` is inert: with no store wired it refuses every request. It checks what it is given, so it never
|
|
64
|
+
# lets raw queries through without a store either.
|
|
65
|
+
def initialize(store: Store::Null.new, strict: true, telemetry: Telemetry.new)
|
|
66
|
+
if store.is_a?(Hash) || !store.respond_to?(:fetch)
|
|
67
|
+
raise ConfigurationError, "store: must answer fetch(id) with an operation or nil, like a Manifest"
|
|
68
|
+
end
|
|
69
|
+
raise ConfigurationError, "strict: must be true or false, got #{strict.inspect}" unless strict == true || strict == false
|
|
70
|
+
raise ConfigurationError, "strict: false needs a store: with the Null store only raw queries would run" if !strict && store.is_a?(Store::Null)
|
|
71
|
+
|
|
72
|
+
@store = store
|
|
73
|
+
@strict = strict
|
|
74
|
+
@telemetry = telemetry
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def call(context, text, document)
|
|
78
|
+
operation_id = context[:operation_id] if context.respond_to?(:[])
|
|
79
|
+
|
|
80
|
+
if !operation_id.nil?
|
|
81
|
+
operation = operation_id.is_a?(String) ? @store.fetch(operation_id) : nil
|
|
82
|
+
if operation.nil?
|
|
83
|
+
refuse(UNKNOWN_OPERATION, :unknown_operation)
|
|
84
|
+
elsif document || (text && !same_query?(text, operation))
|
|
85
|
+
refuse(MISMATCH, :mismatch)
|
|
86
|
+
else
|
|
87
|
+
@telemetry.record(:operation_persisted)
|
|
88
|
+
[nil, operation.document]
|
|
89
|
+
end
|
|
90
|
+
elsif @strict && !(context.respond_to?(:[]) && context[:armory_allow_raw_query] == true)
|
|
91
|
+
refuse(RAW_QUERY_REFUSED, :raw_query)
|
|
92
|
+
else
|
|
93
|
+
@telemetry.record(@strict ? :raw_query_allowed : :raw_query_run) if text || document
|
|
94
|
+
[nil, nil]
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
private
|
|
99
|
+
|
|
100
|
+
# The signal says why, never which operation id or query: a client chooses those.
|
|
101
|
+
def refuse(message, reason)
|
|
102
|
+
@telemetry.record(:operation_refused, reason: reason)
|
|
103
|
+
[message, nil]
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# Apollo's clients may send the query with its id; graphql-ruby's subscriptions resend it printed.
|
|
107
|
+
def same_query?(text, operation)
|
|
108
|
+
text == operation.body || text == operation.document.to_query_string
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
|
|
57
112
|
# Keeps the lookup in every query class the schema uses, including one set after `use` or by a child schema.
|
|
58
113
|
module Guard
|
|
59
114
|
UNSET = Object.new.freeze
|
|
@@ -101,25 +156,9 @@ module GraphQL
|
|
|
101
156
|
# Swaps the request's query for the stored document, or for nothing with an error when it is refused.
|
|
102
157
|
module Lookup
|
|
103
158
|
def initialize(schema, query_string = nil, **options)
|
|
104
|
-
store, strict = schema.armory_persisted_queries
|
|
105
|
-
context = options[:context]
|
|
106
|
-
operation_id = context[:operation_id] if context.respond_to?(:[])
|
|
107
159
|
text = query_string || options[:query]
|
|
108
160
|
text = nil if text == ""
|
|
109
|
-
|
|
110
|
-
refusal, document =
|
|
111
|
-
if !operation_id.nil?
|
|
112
|
-
operation = operation_id.is_a?(String) ? store.fetch(operation_id) : nil
|
|
113
|
-
if operation.nil?
|
|
114
|
-
UNKNOWN_OPERATION
|
|
115
|
-
elsif options[:document] || (text && !same_query?(text, operation))
|
|
116
|
-
MISMATCH
|
|
117
|
-
else
|
|
118
|
-
[nil, operation.document]
|
|
119
|
-
end
|
|
120
|
-
elsif strict && !(context.respond_to?(:[]) && context[:armory_allow_raw_query] == true)
|
|
121
|
-
RAW_QUERY_REFUSED
|
|
122
|
-
end
|
|
161
|
+
refusal, document = schema.armory_persisted_queries.(options[:context], text, options[:document])
|
|
123
162
|
|
|
124
163
|
return super if refusal.nil? && document.nil?
|
|
125
164
|
return super(schema, nil, **options, query: nil, document: document) if refusal.nil?
|
|
@@ -129,16 +168,11 @@ module GraphQL
|
|
|
129
168
|
# with its own validator.
|
|
130
169
|
super(schema, nil, **options, query: nil, document: options[:document] || EMPTY_DOCUMENT, validate: true, static_validator: Refusal.new(schema, refusal))
|
|
131
170
|
end
|
|
132
|
-
|
|
133
|
-
private
|
|
134
|
-
|
|
135
|
-
# Apollo's clients may send the query with its id; graphql-ruby's subscriptions resend it printed.
|
|
136
|
-
def same_query?(text, operation)
|
|
137
|
-
text == operation.body || text == operation.document.to_query_string
|
|
138
|
-
end
|
|
139
171
|
end
|
|
140
172
|
end
|
|
141
173
|
end
|
|
142
174
|
end
|
|
143
175
|
|
|
144
176
|
require "graphql/armory/persisted_queries/manifest"
|
|
177
|
+
require "graphql/armory/persisted_queries/store"
|
|
178
|
+
require "graphql/armory/persisted_queries/controls"
|