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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +81 -0
- data/README.md +6 -5
- data/docs/authorization.md +220 -10
- data/docs/encrypted-ids.md +1 -1
- data/docs/persisted-queries.md +111 -19
- data/docs/rate-limiting.md +32 -11
- data/docs/telemetry.md +31 -8
- data/exe/graphql-armory-publish +6 -0
- data/lib/graphql/armory/authorization/adapters/cancan.rb +17 -4
- data/lib/graphql/armory/authorization/adapters/pundit.rb +79 -14
- data/lib/graphql/armory/authorization/adapters/substitute.rb +4 -1
- data/lib/graphql/armory/authorization/audit/baseline.rb +191 -0
- data/lib/graphql/armory/authorization/audit/command.rb +57 -8
- data/lib/graphql/armory/authorization/audit/denial_hooks.rb +29 -0
- data/lib/graphql/armory/authorization/audit/edge_rules.rb +36 -0
- data/lib/graphql/armory/authorization/audit/findings.rb +35 -0
- data/lib/graphql/armory/authorization/audit/foreign_policies.rb +90 -0
- data/lib/graphql/armory/authorization/audit/input_loads.rb +26 -0
- data/lib/graphql/armory/authorization/audit/interface_rules.rb +42 -0
- data/lib/graphql/armory/authorization/audit/introspection_fields.rb +40 -0
- data/lib/graphql/armory/authorization/audit/library_methods.rb +24 -0
- data/lib/graphql/armory/authorization/audit/observed_rules.rb +58 -0
- data/lib/graphql/armory/authorization/audit/overrides.rb +81 -0
- data/lib/graphql/armory/authorization/audit/own_checks.rb +144 -0
- data/lib/graphql/armory/authorization/audit/payload_reuse.rb +95 -0
- data/lib/graphql/armory/authorization/audit/plain_resolvers.rb +85 -0
- data/lib/graphql/armory/authorization/audit/reach.rb +75 -0
- data/lib/graphql/armory/authorization/audit/report.rb +7 -1
- data/lib/graphql/armory/authorization/audit/type_rules.rb +282 -0
- data/lib/graphql/armory/authorization/audit/visibility_models.rb +83 -0
- data/lib/graphql/armory/authorization/audit.rb +59 -192
- data/lib/graphql/armory/authorization/authorize.rb +35 -9
- data/lib/graphql/armory/authorization/configuration.rb +32 -3
- data/lib/graphql/armory/authorization/definitions.rb +121 -0
- data/lib/graphql/armory/authorization/integration/argument.rb +24 -6
- data/lib/graphql/armory/authorization/integration/field.rb +36 -6
- data/lib/graphql/armory/authorization/integration/object.rb +9 -1
- data/lib/graphql/armory/authorization/integration/resolver.rb +2 -0
- data/lib/graphql/armory/authorization/integration/schema.rb +7 -0
- data/lib/graphql/armory/authorization/integration.rb +36 -4
- data/lib/graphql/armory/authorization/rspec.rb +10 -4
- data/lib/graphql/armory/authorization/rule.rb +24 -3
- data/lib/graphql/armory/authorization/scope.rb +6 -6
- data/lib/graphql/armory/authorization.rb +4 -1
- data/lib/graphql/armory/ids.rb +11 -11
- data/lib/graphql/armory/persisted_queries/manifest.rb +2 -0
- data/lib/graphql/armory/persisted_queries/manifests.rb +69 -0
- data/lib/graphql/armory/persisted_queries/publisher.rb +127 -0
- data/lib/graphql/armory/persisted_queries/redis_store.rb +137 -0
- data/lib/graphql/armory/persisted_queries.rb +55 -16
- data/lib/graphql/armory/railtie.rb +10 -0
- data/lib/graphql/armory/rate_limits/analysis_guard.rb +79 -0
- data/lib/graphql/armory/rate_limits/concurrency.rb +91 -14
- data/lib/graphql/armory/rate_limits/points.rb +91 -14
- data/lib/graphql/armory/rate_limits/time.rb +107 -19
- data/lib/graphql/armory/rate_limits.rb +29 -5
- data/lib/graphql/armory/telemetry.rb +71 -9
- data/lib/graphql/armory/version.rb +1 -1
- data/lib/graphql/armory.rb +1 -0
- data/lib/tasks/graphql_armory.rake +11 -4
- metadata +28 -3
data/docs/persisted-queries.md
CHANGED
|
@@ -101,7 +101,7 @@ class GraphqlController < ApplicationController
|
|
|
101
101
|
end
|
|
102
102
|
```
|
|
103
103
|
|
|
104
|
-
`PersistedQueries.operation_id(params)` reads the id where clients send it: `operationId`, `extensions.operationId`,
|
|
104
|
+
`PersistedQueries.operation_id(params)` reads the id where clients send it: `operationId`, `extensions.operationId`, Apollo's `extensions.persistedQuery.sha256Hash`, or Relay's `doc_id` (`extensions` may be a JSON string, as in GET requests). The first one present wins, in that order. It answers nil when there is no id, or when it is not a non-empty String. Params must have String keys, as Rack and Rails params do. An empty `query` sent with an id (a GET request with `query=`) counts as no query.
|
|
105
105
|
|
|
106
106
|
What each request does:
|
|
107
107
|
|
|
@@ -126,7 +126,97 @@ GraphQL::Armory::PersistedQueries::Manifest.load("persisted-queries.json", diges
|
|
|
126
126
|
|
|
127
127
|
`digest: false` accepts ids that are not digests (names such as `invoices-v1`). Then nothing proves an id belongs to its query: anyone who can edit the file can change what an id runs.
|
|
128
128
|
|
|
129
|
-
|
|
129
|
+
### Several clients
|
|
130
|
+
|
|
131
|
+
Each frontend's build, and every mobile version still in use, has its own manifest. `Manifests` puts them behind one `store:`:
|
|
132
|
+
|
|
133
|
+
```ruby
|
|
134
|
+
use GraphQL::Armory::PersistedQueries, store: GraphQL::Armory::PersistedQueries::Manifests.build("config/persisted_queries/*.json"), strict: true
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`Manifests.build` takes a glob pattern, a path or a list of them, and `digest:`. For manifests with different digests, load each one and pass them: `Manifests.new([Manifest.load("web.json"), Manifest.load("relay.json", digest: :md5)])`.
|
|
138
|
+
|
|
139
|
+
A pattern skips dotfiles and drops a missing `{a,b}` alternative, and `[` in a name reads as a pattern, so `a[1].json` loads `a1.json` when that file exists. List exact paths when a pattern could miss something, and avoid `[` in names. It raises at boot when a pattern or a path finds nothing, when a file does not load, or when two manifests hold different queries for one id, which only ids that are not digests can do. Keep a version's manifest for as long as that version is in use: removing it refuses those clients with `:unknown_operation`.
|
|
140
|
+
|
|
141
|
+
They are one allowlist: any client may run any manifest's operation. A new manifest still needs a deploy.
|
|
142
|
+
|
|
143
|
+
### Publishing without a server deploy
|
|
144
|
+
|
|
145
|
+
With a `Manifest`, a new query reaches the server only with a server deploy. When frontends deploy on their own, even minutes apart, their users get `UNKNOWN_OPERATION` until the server catches up, and every query change needs a backend deploy. With `RedisStore`, the frontend's CI publishes its operations before the frontend goes out, and the server reads them as they are asked for, with no deploy and no restart.
|
|
146
|
+
|
|
147
|
+
```mermaid
|
|
148
|
+
sequenceDiagram
|
|
149
|
+
participant CI as Frontend CI
|
|
150
|
+
participant R as Redis
|
|
151
|
+
participant F as Frontend
|
|
152
|
+
participant S as GraphQL server
|
|
153
|
+
|
|
154
|
+
CI->>CI: Build the frontend, generate the manifest
|
|
155
|
+
CI->>R: graphql-armory-publish manifest.json (SET NX per id)
|
|
156
|
+
Note over CI,R: A failure stops the deploy
|
|
157
|
+
CI->>F: Deploy the frontend
|
|
158
|
+
F->>S: Request with an operation id
|
|
159
|
+
alt The server already read this id
|
|
160
|
+
S->>S: Answer from memory
|
|
161
|
+
else First time it sees this id
|
|
162
|
+
S->>R: GET the id
|
|
163
|
+
R-->>S: The query
|
|
164
|
+
S->>S: Check the digest, parse, keep in memory
|
|
165
|
+
end
|
|
166
|
+
S-->>F: The result of the stored query
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
On the server:
|
|
170
|
+
|
|
171
|
+
```ruby
|
|
172
|
+
class AppSchema < GraphQL::Schema
|
|
173
|
+
use GraphQL::Armory::PersistedQueries,
|
|
174
|
+
store: GraphQL::Armory::PersistedQueries::RedisStore.build(
|
|
175
|
+
redis: Redis.new(url: ENV.fetch("PERSISTED_QUERIES_REDIS_URL"), timeout: 0.5, reconnect_attempts: 0),
|
|
176
|
+
on_error: ->(error) { Rails.error.report(error) }
|
|
177
|
+
),
|
|
178
|
+
strict: true
|
|
179
|
+
end
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
In the frontend's CI, before its deploy:
|
|
183
|
+
|
|
184
|
+
```sh
|
|
185
|
+
gem install graphql-armory redis
|
|
186
|
+
REDIS_URL="$PUBLISHER_REDIS_URL" graphql-armory-publish dist/persisted-queries.json
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
It exits 1 on any problem, so the deploy stops. Publishing again is safe, so a failed run can simply run again. It takes several files, `--digest` and `--prefix`, and answers the same as `Publisher.call(manifest, redis:)` in Ruby. A CI with no Ruby can run `SET <prefix><id> <query> NX` itself: the default prefix is `graphql-armory:persisted-queries:` and the value is the query text. Check each answer: a refused `SET` means the id already exists, and it must hold the same query.
|
|
190
|
+
|
|
191
|
+
**Who can publish decides what strict mode allows.** Anyone who can write to these keys can make the server run any query they choose, under its digest. So:
|
|
192
|
+
|
|
193
|
+
- Give the server read access only, and the CI its own write access. With Redis ACLs:
|
|
194
|
+
```
|
|
195
|
+
ACL SETUSER armory-server on >SERVER_PASSWORD ~graphql-armory:persisted-queries:* +get
|
|
196
|
+
ACL SETUSER armory-ci on >CI_PASSWORD ~graphql-armory:persisted-queries:* +get +set
|
|
197
|
+
```
|
|
198
|
+
On a database other than 0, add `+select` to both: the client selects it when it connects.
|
|
199
|
+
- Keep the CI's credential away from pull requests from forks and from the app's own servers.
|
|
200
|
+
- The gem adds no endpoint to your API, so publishing cannot be reached from it.
|
|
201
|
+
|
|
202
|
+
What happens when something fails:
|
|
203
|
+
|
|
204
|
+
| Situation | What the client gets | What you see |
|
|
205
|
+
|---|---|---|
|
|
206
|
+
| Redis is down, the server already read the id | The normal result | Nothing |
|
|
207
|
+
| Redis is down, the server has not read the id | `UNKNOWN_OPERATION`, nothing runs | `on_error` with the error, plus `:operation_refused` |
|
|
208
|
+
| The id was never published | `UNKNOWN_OPERATION`, nothing runs | `:operation_refused` |
|
|
209
|
+
| The stored query is not the digest of its id, or does not parse | `UNKNOWN_OPERATION`, nothing runs | `on_error` with `RedisStore::CorruptOperation`, plus `:operation_refused` |
|
|
210
|
+
| The CI publishes another query under an id that exists | Nothing changes for clients | `PublishError`, exit 1 |
|
|
211
|
+
|
|
212
|
+
By default `on_error` warns with the error's class only: Redis's messages may hold the URL and its password. `warn` prints nothing under `ruby -W0`, so pass your own `on_error` in production. An `on_error` that raises makes the request fail, and nothing runs.
|
|
213
|
+
|
|
214
|
+
Limits:
|
|
215
|
+
|
|
216
|
+
- Set a short Redis timeout, as above: during an outage each id the server does not know waits for it, and a client can send many such ids. Ids are checked for shape first, and one that cannot be an id never reaches Redis.
|
|
217
|
+
- Removing a key does not revoke an operation until every server restarts: a server keeps what it read, with no limit but what was published.
|
|
218
|
+
- They are one allowlist: any client may run any published operation. Use another `prefix:` for each allowlist you want apart. With `digest: false`, do not nest one prefix inside another: an id holding `:` could reach the other allowlist. With a digest, the check refuses it.
|
|
219
|
+
- Keep these keys where they cannot expire or be evicted (`noeviction`, or a Redis of their own). A lost key looks like an id never published.
|
|
130
220
|
|
|
131
221
|
### Rolling it out
|
|
132
222
|
|
|
@@ -153,21 +243,25 @@ use GraphQL::Armory::PersistedQueries, store: PERSISTED, sinks: [GraphQL::Armory
|
|
|
153
243
|
|
|
154
244
|
While you are in `strict: false`, `:raw_query_run` is the traffic still to migrate: turn on `strict: true` when it reaches zero. After a deploy, `:operation_refused` with `:unknown_operation` is a client build whose operations are not in the manifest. Signals never hold the operation id or the query. See [Telemetry](telemetry.md).
|
|
155
245
|
|
|
246
|
+
### Telling a refusal apart
|
|
247
|
+
|
|
248
|
+
Every refusal carries a stable code in `extensions.code`: `RAW_QUERY_REFUSED`, `UNKNOWN_OPERATION` or `OPERATION_MISMATCH`. Match on it instead of on the message.
|
|
249
|
+
|
|
156
250
|
### Counting probes in strict mode
|
|
157
251
|
|
|
158
252
|
In strict mode a raw query is refused before it is validated, so it never produces a validation error. If your abuse detection counts validation errors (`undefinedField`, `argumentNotAccepted`) to spot someone probing your schema, it sees nothing from a strict endpoint. Count the refusal instead: a legitimate client sends operation ids and never a raw query, so `:operation_refused` with `reason: :raw_query` is a clean strike.
|
|
159
253
|
|
|
160
254
|
```ruby
|
|
161
|
-
count_probes = lambda do |signal, data|
|
|
255
|
+
count_probes = lambda do |signal, data, context|
|
|
162
256
|
next unless signal == :operation_refused && data[:reason] == :raw_query
|
|
163
257
|
|
|
164
|
-
AbuseDetection.strike(
|
|
258
|
+
AbuseDetection.strike(context[:client_key]) # your detector, with a client key your controller put in the context
|
|
165
259
|
end
|
|
166
260
|
|
|
167
261
|
use GraphQL::Armory::PersistedQueries, store: PERSISTED, strict: true, sinks: [count_probes]
|
|
168
262
|
```
|
|
169
263
|
|
|
170
|
-
A signal holds only the reason
|
|
264
|
+
A signal holds only the reason. To know who sent the request, a sink that takes three arguments receives the query's context, as in [Telemetry](telemetry.md#who-asked). Do not strike on `:unknown_operation`: after a deploy it is a legitimate client build whose operations are not in the manifest yet. The example has not been run against a live detector.
|
|
171
265
|
|
|
172
266
|
### Testing with persisted queries
|
|
173
267
|
|
|
@@ -182,37 +276,35 @@ A signal holds only the reason, so the sink reads who sent the request from your
|
|
|
182
276
|
- `fetch(id)` answers the operation (`id`, `name`, `body`, `document`, all frozen) or nil. `size` counts them.
|
|
183
277
|
- Raises `PersistedQueries::ConfigurationError` at boot for: invalid JSON, an unreadable file, an unknown format or version, an id that is not the digest of its query, a query that does not parse, a duplicate id, an entry that is not an object, or an empty manifest. Messages never quote the file's queries.
|
|
184
278
|
|
|
185
|
-
`use GraphQL::Armory::PersistedQueries, store:, strict: false, sinks: []`
|
|
279
|
+
`use GraphQL::Armory::PersistedQueries, store:, strict: false, sinks: [], on_sink_error: nil`
|
|
186
280
|
|
|
187
281
|
- `store:` answers `fetch(id)` with an object that has `body` and `document`, or nil. A Manifest, or your own store.
|
|
188
282
|
- `strict:` is `true` or `false`.
|
|
189
|
-
- `sinks:` an Array of callables taking `(signal, data)`; see [Watching the rollout](#watching-the-rollout).
|
|
283
|
+
- `sinks:` an Array of callables taking `(signal, data)` or `(signal, data, context)`; see [Watching the rollout](#watching-the-rollout).
|
|
284
|
+
- `on_sink_error:` a callable `(error, signal)` called when a sink raises; see [Telemetry](telemetry.md#guarantees-and-limits).
|
|
190
285
|
- Works with your own `query_class`, whether it is set before `use`, after it, or in a child schema: the plugin subclasses it.
|
|
191
286
|
- `use` it once per schema hierarchy. A second `use`, on the same schema or a child, raises instead of replacing the first one's settings.
|
|
192
287
|
- A store whose `fetch` raises or answers something without `document` makes the request raise: it fails closed, as an exception.
|
|
193
288
|
|
|
289
|
+
`Manifests.build(paths, digest: :sha256)` loads manifests from a glob pattern, a path or a list. `Manifests.new(manifests = [])` joins `Manifest` objects (subclasses are refused: their `fetch` would not run). `fetch(id)`, `size`, `empty?`. With no manifests it holds nothing, so every id is unknown, and `strict: false` refuses it at boot.
|
|
290
|
+
|
|
291
|
+
`RedisStore.build(redis:, prefix: "graphql-armory:persisted-queries:", digest: :sha256, on_error:)` reads what a publisher stored; `new` with no Redis holds nothing, and `strict: false` refuses it at boot. `Publisher.call(manifest, redis:, prefix:)` answers `published` and `unchanged`, and raises `Publisher::PublishError` rather than change an id. `RedisStore::Client::Substitute` stands in for Redis in tests.
|
|
292
|
+
|
|
194
293
|
Context keys: `operation_id` (a String; anything else is an unknown id), `armory_allow_raw_query` (only `true` allows).
|
|
195
294
|
|
|
196
295
|
## Guarantees and limits
|
|
197
296
|
|
|
297
|
+
- On graphql before 2.6 (checked on 2.4.18 and 2.5.26) with json 3.1, a known id with different text raises instead of answering `OPERATION_MISMATCH` when the stored query holds a string literal, because graphql-ruby's printer passes an option that version of json rejects. Nothing runs.
|
|
198
298
|
- A request with an id runs only the stored document for that id, or nothing.
|
|
199
299
|
- In strict mode a raw query runs only when the app's context says `armory_allow_raw_query: true`. The plugin does not decide who is staff: your controller does.
|
|
200
|
-
- Queries built by your own code as `GraphQL::Query` objects (for example in `multiplex`)
|
|
300
|
+
- Queries built by your own code as `GraphQL::Query` objects (for example in `multiplex`) run their own text, so an operation id means nothing on them. In strict mode they are refused unless the context holds `armory_allow_raw_query: true`, and they are recorded like any raw query. The check is a trace on `execute_query`, so `run_partials` and `validate: false` are covered. Two limits: built text that does not validate gets the ordinary validation errors, with no signal and with field suggestions, because validation runs first (nothing resolves); and your own code can skip the check by choosing another trace: `context[:trace]` on a multiplex (or on a query, on the interpreter), or a `trace_mode` or `default_trace_mode` given a class that does not include `trace_with` modules. A signal is recorded per execution, so each `run_partials` entry records one. On `Execution::Next`, a refused query with `validate: false` and variables that do not coerce, or a validation timeout, returns a nil result: nothing runs, the refusal is recorded and sits in `context.errors`.
|
|
201
301
|
- In strict mode, schema introspection run through the plugin is refused too. `Schema.to_json` and `rake graphql:schema:json` need `context: { armory_allow_raw_query: true }` (the rake task's `load_context`). `Schema.to_definition` and `Schema.validate` are not affected.
|
|
202
|
-
-
|
|
302
|
+
- A `Manifest` lives in the server's code: adding an operation needs a deploy. `RedisStore` does not: see "Publishing without a server deploy".
|
|
203
303
|
- Subscriptions: graphql-ruby re-runs a subscription with its printed query, which the plugin accepts when it matches the stored document. Subscriptions are not tested with persisted queries yet.
|
|
204
304
|
|
|
205
|
-
## Planned:
|
|
206
|
-
|
|
207
|
-
The manifest is the simplest store: one file, no database, deployed with the code. Teams that ship clients independently of the server (mobile apps, several frontends) need operations published without a server deploy. That is planned for later, behind the same `store:` interface:
|
|
208
|
-
|
|
209
|
-
- **A database table** (ActiveRecord) holding operations per client, with the digest checked on write.
|
|
210
|
-
- **A sync endpoint** the client build calls to publish its operations, authenticated per client with an HMAC of the request body and a secret per client.
|
|
211
|
-
- **Several clients**, each with its own operations and secret, so one client cannot publish under another's name.
|
|
212
|
-
- **Archiving** operations that old app versions no longer use, without deleting their history.
|
|
213
|
-
- **Publishing without redeploying**: the server reads new operations as soon as they are synced.
|
|
305
|
+
## Planned: more runtime stores
|
|
214
306
|
|
|
215
|
-
Until then, any object that answers `fetch(id)` with an operation can be passed as `store:`.
|
|
307
|
+
`RedisStore` is one store behind the `store:` interface. Still planned: a database table, an endpoint a client build calls to publish, operations and secrets per client, and archiving what old app versions no longer use. Until then, any object that answers `fetch(id)` with an operation can be passed as `store:`.
|
|
216
308
|
|
|
217
309
|
## References
|
|
218
310
|
|
data/docs/rate-limiting.md
CHANGED
|
@@ -107,7 +107,7 @@ field :create_invoice, mutation: Mutations::CreateInvoice, complexity: 10 # 10
|
|
|
107
107
|
|
|
108
108
|
Three settings make the scores fair. Large public APIs (GitHub, Shopify, see [References](#references)) do the same:
|
|
109
109
|
|
|
110
|
-
- **Paginate every list.** A plain list field (`[Invoice]`) costs its fields **once**, however many items it returns, so 10,000 invoices cost like one. Use connections for anything that can grow. A connection asked for without `first:` or `last:` is sized by the schema's `default_page_size`, or else by `default_max_page_size`. If neither is set, graphql-ruby
|
|
110
|
+
- **Paginate every list.** A plain list field (`[Invoice]`) costs its fields **once**, however many items it returns, so 10,000 invoices cost like one. Use connections for anything that can grow. A connection asked for without `first:` or `last:` is sized by the schema's `default_page_size`, or else by `default_max_page_size`. If neither is set, `Points` refuses that query with `This connection needs first: or last:` (code `PAGE_SIZE_REQUIRED`), in soft mode too, and charges nothing. A raise by another analyzer does not skip that refusal. graphql-ruby's install template sets neither, so set one: without it, a client that does send `first:` chooses its own page size. A schema with `max_complexity` still gets graphql-ruby's server error on that query, because its own analyzer raises it. This refusal leaves no record and no `rateLimit` extension, so it does not appear in your rate limit metrics. GitHub goes further and requires `first:` or `last:` on every connection.
|
|
111
111
|
- **Cap a single query.** graphql-ruby's `max_complexity 1_000` refuses any query above that score, whatever the client's budget. Shopify caps single queries at 1,000 points.
|
|
112
112
|
- **Make writes cost more.** Give mutations a higher `complexity:`: `complexity: 10` charges 10 points for the mutation field itself, plus the fields it selects. Shopify charges 10 points per mutation by default.
|
|
113
113
|
|
|
@@ -229,7 +229,7 @@ To test it, inject a clock: `Time` takes `clock:` (a callable answering seconds)
|
|
|
229
229
|
2. Send what it recorded to your metrics: `result.context[:rate_limit_points]` is `{ key:, cost:, limit:, remaining:, window:, soft:, limited: }`, and `limited: true` marks the queries that would have been refused.
|
|
230
230
|
3. When the limits fit your traffic, set `soft: false`.
|
|
231
231
|
|
|
232
|
-
Rate limiting reports through the query context rather than through `sinks:`, because the context is also where the budget for the response comes from. To see its decisions next to the other modules' signals, send those records to the same place: [Telemetry](telemetry.md#rate-limiting).
|
|
232
|
+
Rate limiting reports its charges through the query context rather than through `sinks:`, because the context is also where the budget for the response comes from. To see its decisions next to the other modules' signals, send those records to the same place: [Telemetry](telemetry.md#rate-limiting).
|
|
233
233
|
|
|
234
234
|
### Sharing limits between processes
|
|
235
235
|
|
|
@@ -247,8 +247,8 @@ end
|
|
|
247
247
|
|
|
248
248
|
- **Atomic.** Each charge, slot taken and slot released is one Lua script, so two requests of the same client never both spend the last points.
|
|
249
249
|
- **One clock.** The time comes from Redis (`TIME`), not from each server, so servers whose clocks drift still agree on when a bucket refills.
|
|
250
|
-
- **Small.** A client costs
|
|
251
|
-
- **Fails open.** When Redis is down or slow, the client raises, the query runs, and `on_store_error` is called: make that hook alert. Set the client's timeouts (for example `Redis.new(url: ..., timeout: 0.2)`) so a slow Redis cannot slow every request.
|
|
250
|
+
- **Small.** A client costs up to three keys, `graphql-armory:rate-limits:points:<key>`, `...:points:time:<key>` for `Time`, and `...:slots:<key>`; all expire once they no longer matter (a window, or `stale_after`, after the last use). Pass `prefix:` to share one Redis with other apps.
|
|
251
|
+
- **Fails open.** When Redis is down or slow, the client raises, the query runs, and `on_store_error` is called: make that hook alert. With `sinks:`, the failure is also recorded as `:rate_limit_store_failed`. Set the client's timeouts (for example `Redis.new(url: ..., timeout: 0.2)`) so a slow Redis cannot slow every request.
|
|
252
252
|
|
|
253
253
|
The gem does not depend on the redis gem: add it to your Gemfile. A single `Redis` client is safe to share between threads.
|
|
254
254
|
|
|
@@ -270,31 +270,32 @@ store.calls # [[:take, "user:1", { cost:
|
|
|
270
270
|
|
|
271
271
|
## Reference
|
|
272
272
|
|
|
273
|
-
`use GraphQL::Armory::RateLimits::Points, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, extensions: false`
|
|
273
|
+
`use GraphQL::Armory::RateLimits::Points, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, sinks: [], extensions: false`
|
|
274
274
|
|
|
275
275
|
- `store:` answers `take(key, cost:, limit:, window:, force:)` with `[taken, remaining]`. `MemoryStore.new(clock: ...)` keeps buckets in the process; `RedisStore` shares them (below).
|
|
276
276
|
- `limit:` a positive Integer, or a callable `(key, query)` answering a positive Integer or nil.
|
|
277
277
|
- `window:` positive seconds over which `limit` points refill, continuously.
|
|
278
278
|
- `soft:` `true` (default) charges and records without refusing; `false` refuses.
|
|
279
|
-
- `key:` a callable `(query)` answering the client key; by default `context[:rate_limit_key]`. It must be a non-empty String.
|
|
279
|
+
- `key:` a callable `(query)` answering the client key; by default `context[:rate_limit_key]`. It must be a non-empty String, or a list of up to 5 different ones for all three limiters: a query runs only if every key allows it. The record, the headers and the extensions show the key that binds, and the record adds `keys:` with each one. The refusals a client sees never name a key. Without one, the query raises `ConfigurationError`, on every query: a key built from something that can be nil (an IP behind a misconfigured balancer) needs a fallback, such as `context[:rate_limit_key] = request.remote_ip.presence || "unknown"`, where all such clients share one bucket.
|
|
280
280
|
- `on_store_error:` a callable `(error, query)` called when the store raises; the query then runs (fails open). By default it warns.
|
|
281
|
+
- `sinks:` callables that hear `:rate_limit_store_failed` when the store raises; see [Telemetry](telemetry.md#rate-limiting).
|
|
281
282
|
- `extensions:` `true` adds `"rateLimit" => { cost, limit, remaining, resetIn }` to every response of a limited client; `false` (default) leaves responses unchanged.
|
|
282
283
|
- `Points.headers(result)` answers the `RateLimit-*` headers for a result, or `{}`.
|
|
283
284
|
- Instrumentation: `context[:rate_limit_points]`.
|
|
284
285
|
|
|
285
|
-
`use GraphQL::Armory::RateLimits::Concurrency, store:, limit:, stale_after: 60, soft: true, key: nil, on_store_error: nil`
|
|
286
|
+
`use GraphQL::Armory::RateLimits::Concurrency, store:, limit:, stale_after: 60, soft: true, key: nil, on_store_error: nil, sinks: []`
|
|
286
287
|
|
|
287
288
|
- `store:` answers `acquire(key, token:, limit:, ttl:, force:)` with `[acquired, active]` and `release(key, token:)`. `MemoryStore` does both.
|
|
288
289
|
- `limit:` operations at once per client: a positive Integer, or a callable `(key, query)` answering a positive Integer or nil.
|
|
289
290
|
- `stale_after:` positive seconds after which a slot that was never released expires.
|
|
290
|
-
- `soft:`, `key:` and `
|
|
291
|
+
- `soft:`, `key:`, `on_store_error:` and `sinks:` as for `Points`. When the store raises on release, `on_store_error` is called and the slot expires after `stale_after`.
|
|
291
292
|
- Instrumentation: `context[:rate_limit_concurrency]`.
|
|
292
293
|
|
|
293
|
-
`use GraphQL::Armory::RateLimits::Time, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, clock: Clock.monotonic, extensions: false`
|
|
294
|
+
`use GraphQL::Armory::RateLimits::Time, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, sinks: [], clock: Clock.monotonic, extensions: false`
|
|
294
295
|
|
|
295
296
|
- `store:` as for `Points`: it is asked for the balance with `take(key, cost: 0, ...)` and charged with `take(key, cost: milliseconds, ..., force: true)`. No store changes are needed.
|
|
296
297
|
- `limit:` milliseconds per `window` per client: a positive Integer, or a callable `(key, query)` answering a positive Integer or nil.
|
|
297
|
-
- `window:`, `soft:`, `key:` and `
|
|
298
|
+
- `window:`, `soft:`, `key:`, `on_store_error:` and `sinks:` as for `Points`.
|
|
298
299
|
- `clock:` a callable answering seconds, read when a multiplex starts and when it ends. By default a monotonic clock.
|
|
299
300
|
- `extensions:` `true` adds `"rateLimitTime" => { limit, remaining, elapsed, resetIn }` to the response of a limited client.
|
|
300
301
|
- `Time.headers(result)` answers the `RateLimit-Time-*` headers for a result, or `{}`.
|
|
@@ -312,9 +313,18 @@ Invalid settings raise `RateLimits::ConfigurationError` at boot.
|
|
|
312
313
|
|
|
313
314
|
- A query this limiter refuses resolves no field and is not charged. A query that fails validation is not charged. A query refused by another analyzer (`max_depth`, `max_complexity`) is still charged: graphql-ruby runs every analyzer.
|
|
314
315
|
- Each query in a multiplex is charged on its own.
|
|
316
|
+
- With several keys, `Points` reads every balance and then charges, so a refused query leaves the others as they were. Two queries racing between those steps can leave a refused one having charged other keys. `Concurrency` gives back the slots a refused query took at once. `Time` charges every key the whole time; a store failure on one key does not stop the others.
|
|
317
|
+
- An `ExecutionError` raised during analysis, which graphql-ruby would discard before running the query, does not skip a limiter. A refusal already given stands. A limiter not asked yet is asked on its own, so another analyzer's raise leaves the query charged and running as before. A limiter that cannot answer, because a `complexity:` lambda or its `on_store_error` hook raised, refuses the query in hard mode with the code `RATE_LIMIT_NOT_CHARGED`, and in soft mode lets it run and records `charged: false`. A client with no limit still runs, and a query with no key raises `ConfigurationError`. When a query takes this path it is visited once more per limiter not asked yet, so a `complexity:` lambda can run several times, `key:` and `limit:` are asked again, and a validation timeout can take longer. An analysis your app runs itself outside an execution charges nothing here. A trace that takes no modules from the schema (`context[:trace]` or a class given to `trace_mode`) is outside this: `Points` is not protected on such a trace.
|
|
318
|
+
- A `max_depth` or `max_complexity` refusal is not a limiter's, so it is lost when an analyzer or a `complexity:` lambda raises `ExecutionError`: graphql-ruby discards every analyzer's answer and runs the query. If a lambda raises for a field a client can pick, the client can choose this. Do not raise `ExecutionError` from a lambda or an analyzer: have the analyzer's `result` return a `GraphQL::AnalysisError`.
|
|
319
|
+
- On `Execution::Next`, `validate: false` ignores every refusal from analysis, the limiters' included. Never pass it for a client's query.
|
|
320
|
+
- A field with `max_page_size: nil` under a schema with `default_max_page_size` is sized by that default, while at runtime it has no maximum, so it is charged less than it returns. Give such a field a number.
|
|
321
|
+
- An `ExecutionError` from a multiplex analyzer's `result` raises to your app: nothing runs and no slot stays held.
|
|
322
|
+
- With several keys, a key whose store fails is left out and `on_store_error` is called for it; the others still decide, so a client cannot cancel a refusal by choosing a key on a dead shard. Only when every key's store fails does the query run unlimited. A list whose members differ only in encoding counts as a duplicate and raises.
|
|
315
323
|
- `Concurrency` takes one slot per query of a multiplex, and releases them all when the multiplex ends, even when the queries share one context hash. If a release fails, that slot expires after `stale_after`; the others are still released.
|
|
316
324
|
- A query run with its own trace (`context: { trace: ... }`) cannot be released by `Concurrency`, so it raises `ConfigurationError` instead of taking a slot.
|
|
317
325
|
- A resolver that runs another query for the same client (a nested `execute`) takes a second slot while the first is held.
|
|
326
|
+
- `Points` and `Time` keep separate budgets on one store and key: `Time` stores its milliseconds under `time:<key>` (`Time.bucket_key(key)`; a custom store sees that key). So do not give `Points` a key starting with `time:` that matches a `Time` key.
|
|
327
|
+
- Two limiters of the same class on one store and key share one bucket: both charge it, and each caps and refills it with its own limit. Give each `use Points` or `use Time` its own store (`RedisStore.new(redis:, prefix:)`) or its own keys.
|
|
318
328
|
- A subscription holds a slot only while its first result runs, not while it stays subscribed.
|
|
319
329
|
- When queries of a multiplex share one context hash, `context[:rate_limit_points]`, `context[:rate_limit_concurrency]` and `context[:rate_limit_time]` hold the last query's record: give each query its own context hash to read every record.
|
|
320
330
|
- The cost is graphql-ruby's estimate before running, not the time a query really takes: a field that is slow but scored 1 costs 1. Score expensive fields, and add `Time` to charge what queries really take.
|
|
@@ -324,10 +334,11 @@ Invalid settings raise `RateLimits::ConfigurationError` at boot.
|
|
|
324
334
|
|
|
325
335
|
### Limits of `Time`
|
|
326
336
|
|
|
337
|
+
- A query `Time` refuses is still charged by `Points` on the same schema, because graphql-ruby runs every analyzer.
|
|
327
338
|
- A running operation is never interrupted: the one that exhausts the budget finishes, and only the next one is refused. Operations that start while a long one is still running all see the balance before it is charged, so together they can spend more than the client has; the balance then stops at zero (there is no debt).
|
|
328
339
|
- `retryAfter` is the time the client needs to regain one millisecond (`window / limit` seconds, at least 1). It lets the client in again, not necessarily for an operation that takes long.
|
|
329
340
|
- A multiplex has one measured time, split equally among the queries this limiter charges, rounded up to whole milliseconds: fields of different queries interleave, so their time cannot be told apart. A query refused by `Time`, and one whose key has no limit (`nil`), are not part of the split, so the time of a query with no limit is carried by the limited ones.
|
|
330
|
-
- A schema may `use Time` more than once (for example per user and per IP
|
|
341
|
+
- A schema may `use Time` more than once, with different stores or keys (for example per user and per IP): each limiter charges only its own. `context[:rate_limit_time]`, the response extension and `Time.headers` then hold the record of the last one.
|
|
331
342
|
- The clock must answer a finite number of seconds: one that does not is refused at boot, and one that breaks later raises instead of letting operations run uncharged. A clock that stands still or goes backwards charges 0.
|
|
332
343
|
- Time spent before analysis finishes (parsing, validation) is charged to no one, and inside a multiplex it ends up on the queries that did run. A query that never reaches analysis (a syntax error) costs the client nothing.
|
|
333
344
|
- The time is wall-clock, so it grows when the server is loaded: the same query costs a client more on a busy server. Choose `limit` with that in mind, and start in soft mode.
|
|
@@ -340,6 +351,16 @@ Every key has its own bucket. A client that gets a new key for each request (a n
|
|
|
340
351
|
|
|
341
352
|
What you can do with the gem:
|
|
342
353
|
|
|
354
|
+
- **Draw from several buckets at once.** A key may be a list of up to 5 different Strings, so rotating one identity leaves the others:
|
|
355
|
+
|
|
356
|
+
```ruby
|
|
357
|
+
context[:rate_limit_key] = ["user:#{user.id}", "ip:#{request.remote_ip}", ("new-accounts" if user.created_at > 1.day.ago)].compact
|
|
358
|
+
|
|
359
|
+
use GraphQL::Armory::RateLimits::Points, store: store, window: 60,
|
|
360
|
+
limit: ->(key, _query) { key.start_with?("user:") ? 1_000 : key.start_with?("ip:") ? 3_000 : 500 }
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
A query runs only if every key has the budget, and each key is charged. `limit:` is asked once per key, and a key it answers `nil` for is left out. The prefixes are yours: they keep kinds of key apart in the store. It costs store round trips on every query, about two per key, so use two or three. Do not build a key from the document or its variables: a client could then spend someone else's budget.
|
|
343
364
|
- **Share one bucket among the clients you do not trust yet.** Build the key from something that is not free to rotate, such as the age of the account, so every new account draws from the same small budget:
|
|
344
365
|
|
|
345
366
|
```ruby
|
data/docs/telemetry.md
CHANGED
|
@@ -100,6 +100,20 @@ end
|
|
|
100
100
|
|
|
101
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
102
|
|
|
103
|
+
### Who asked
|
|
104
|
+
|
|
105
|
+
A sink that requires three arguments also receives the query's context, so it can read who was refused:
|
|
106
|
+
|
|
107
|
+
```ruby
|
|
108
|
+
count_probes = lambda do |signal, data, context|
|
|
109
|
+
next unless signal == :operation_refused && data[:reason] == :raw_query
|
|
110
|
+
|
|
111
|
+
Strikes.add(context[:client_ip])
|
|
112
|
+
end
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
The sink reads the context through a view that answers `[]`, `fetch`, `dig` and `key?`, and cannot write to it, so a sink cannot change who the query runs as. An object held in the context is your own, and a sink can still change that. The view is empty when the query has none. A sink that takes two arguments, `*arguments` or a defaulted third never receives it, so a sink that logs what it gets does not start logging tokens. What you read from the context is yours to keep out of logs.
|
|
116
|
+
|
|
103
117
|
### What to watch for
|
|
104
118
|
|
|
105
119
|
| You see | It usually means | What to do |
|
|
@@ -119,6 +133,7 @@ The gem does not depend on Datadog or on any other backend. The same shape works
|
|
|
119
133
|
|---|---|---|
|
|
120
134
|
| `:allowed` | The policy or ability said yes | `type`, `action` |
|
|
121
135
|
| `:denied` | It said no, nil or anything that is not a clear yes | `type`, `action` |
|
|
136
|
+
| `:observed` | It said no to a rule under `observe:`, so the data was served | `type`, `action`, `reason` |
|
|
122
137
|
| `:bypassed` | The rule is `authorize :none, reason: "..."` | `type` (not on lists), `reason` |
|
|
123
138
|
| `:scoped` | A list or lookup went through the user's scope | `action` |
|
|
124
139
|
|
|
@@ -153,15 +168,21 @@ The reasons of `:id_refused`:
|
|
|
153
168
|
|
|
154
169
|
### Rate limiting
|
|
155
170
|
|
|
156
|
-
Rate limiting
|
|
171
|
+
Rate limiting takes `sinks:` for one signal, when its store fails:
|
|
172
|
+
|
|
173
|
+
| Signal | When | Data |
|
|
174
|
+
|---|---|---|
|
|
175
|
+
| `:rate_limit_store_failed` | The store raised, so the query ran without a limit | `limiter`: `:points`, `:concurrency` or `:time`; `error`: the error's class name |
|
|
176
|
+
|
|
177
|
+
Everything else it records on every query, in the query's context. 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
178
|
|
|
158
179
|
## What telemetry does not cover
|
|
159
180
|
|
|
160
181
|
Signals are counters of the gem's decisions. They are not a replacement for these:
|
|
161
182
|
|
|
162
183
|
- **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.
|
|
164
|
-
- **Rate limiting.**
|
|
184
|
+
- **Who asked, in the signal.** A signal says `id_refused`, not which user or IP. A sink that takes three arguments receives the query's context and can read them from it: see [Who asked](#who-asked).
|
|
185
|
+
- **Rate limiting's decisions.** Its sinks hear only about a failing store: what it charged is 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
186
|
- **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
187
|
- **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
188
|
- **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.
|
|
@@ -203,22 +224,24 @@ use GraphQL::Armory::PersistedQueries, store: store, sinks: [->(signal, data) {
|
|
|
203
224
|
|
|
204
225
|
## Reference
|
|
205
226
|
|
|
206
|
-
- `sinks:` is an option of `use GraphQL::Armory::Authorization`, `use GraphQL::Armory::IDs
|
|
207
|
-
- `
|
|
227
|
+
- `sinks:` is an option of `use GraphQL::Armory::Authorization`, `use GraphQL::Armory::IDs`, `use GraphQL::Armory::PersistedQueries` and the rate limiters. An Array of callables taking `(signal, data)` or `(signal, data, context)`, called in order; default `[]`.
|
|
228
|
+
- `on_sink_error:` is an option of the same modules except the rate limiters. A callable `(error, signal)` called when a sink raises; by default it warns with the signal and the error's class. Raise from it to fail the request closed.
|
|
229
|
+
- A sink that could never be called (`->(a) {}`, four required arguments, a required keyword) raises `Telemetry::ConfigurationError` at boot.
|
|
230
|
+
- `Telemetry.new(sinks: [], on_sink_error: nil)`, `Telemetry.build(sinks: [], on_sink_error: nil)`, `telemetry.record(signal, context: nil, **data)` (answers nil; `data` reaches the sinks frozen).
|
|
208
231
|
- `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,
|
|
232
|
+
- `Telemetry::Substitute`: `record`, `recorded` (an Array of `[signal, data]`), `contexts`, `recorded?(signal)`, and `fail_with(error)` / `recover` to make `record` raise, for code that calls `record` directly: a real `record` does not raise when a sink does.
|
|
210
233
|
- `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
234
|
- `Authorization::Telemetry` is the same class as `Telemetry`.
|
|
212
235
|
|
|
213
236
|
## Guarantees and limits
|
|
214
237
|
|
|
215
238
|
- **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
|
|
239
|
+
- **A sink that raises does not touch the request.** The gem's decision stands, the next sink runs, and `on_sink_error:` is called. By default that prints the signal and the error's class, never its message, which may hold a credential, once per failure: one request can print many. If the record must exist before the data is served (an audit log), raise from `on_sink_error:` to fail the request closed. A `rescue_from` for that error still runs, and the object is denied whatever it answers. In encrypted IDs, an `Encoder::InvalidError` or `ArgumentError` raised from `on_sink_error:` reads as an invalid ID: the client gets `nil`, closed, and an extra `:id_refused` signal is recorded. On a rate limiter a sink always only warns: use `on_store_error:` to act on a failing store.
|
|
217
240
|
- **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
241
|
- **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
242
|
- **Signals are not a security log by themselves.** They tell you what the gem decided; who asked comes from your request context.
|
|
220
243
|
- 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
|
|
244
|
+
- Rate limiting reports its charges through the query context; its sinks hear only about a failing store.
|
|
222
245
|
|
|
223
246
|
## References
|
|
224
247
|
|
|
@@ -9,15 +9,18 @@ module GraphQL
|
|
|
9
9
|
# Answers the core's four questions with CanCanCan's public API.
|
|
10
10
|
#
|
|
11
11
|
# The actor is an Ability: `context[:current_ability]`, else `Ability.new(context[:current_user])`
|
|
12
|
-
# (or the class given as `ability_class:`). It is built once per query.
|
|
12
|
+
# (or the class given as `ability_class:`, and the key given as `user_key:`). It is built once per query.
|
|
13
13
|
#
|
|
14
14
|
# A field that declares its own action (`authorize: :manage`) passes its attribute to `can?`: with
|
|
15
15
|
# `can :read, User, [:username]`, `can?(:read, user)`
|
|
16
16
|
# is true even though only one attribute is readable. Fields covered by their type's rule are not asked
|
|
17
17
|
# about their attribute: declare an action on the ones an attribute rule must hide.
|
|
18
18
|
class CanCan
|
|
19
|
-
def initialize(ability_class: nil)
|
|
19
|
+
def initialize(ability_class: nil, user_key: :current_user)
|
|
20
|
+
raise ArgumentError, "user_key must be a Symbol or a String, got #{user_key.class}" unless user_key.is_a?(Symbol) || user_key.is_a?(String)
|
|
21
|
+
|
|
20
22
|
@ability_class = ability_class
|
|
23
|
+
@user_key = user_key
|
|
21
24
|
end
|
|
22
25
|
|
|
23
26
|
def actor(context)
|
|
@@ -26,6 +29,8 @@ module GraphQL
|
|
|
26
29
|
|
|
27
30
|
def authorized?(ability, subject, rule)
|
|
28
31
|
options!(rule)
|
|
32
|
+
return false if client_symbol?(subject, rule)
|
|
33
|
+
|
|
29
34
|
return ability.can?(rule.action, subject, rule.attribute) if rule.attribute
|
|
30
35
|
|
|
31
36
|
ability.can?(rule.action, subject)
|
|
@@ -34,6 +39,13 @@ module GraphQL
|
|
|
34
39
|
# A relation is narrowed in SQL with `accessible_by`, so it stays paginable. A rule defined only
|
|
35
40
|
# with a block cannot be turned into SQL: it fails, unless the type declared `scope: :in_memory`,
|
|
36
41
|
# which filters with `can?` and gives up efficient pagination.
|
|
42
|
+
# A Symbol names a rule (`can :read, :dashboard`) only as the `model:` the schema author wrote: any other is a
|
|
43
|
+
# record, maybe the client's text.
|
|
44
|
+
def client_symbol?(subject, rule)
|
|
45
|
+
Symbol === subject && subject.to_s != rule.model.to_s
|
|
46
|
+
end
|
|
47
|
+
private :client_symbol?
|
|
48
|
+
|
|
37
49
|
def scope(ability, items, rule)
|
|
38
50
|
options!(rule)
|
|
39
51
|
return in_memory(ability, items, rule) if items.is_a?(Array) || rule.scope == :in_memory
|
|
@@ -72,12 +84,13 @@ module GraphQL
|
|
|
72
84
|
end
|
|
73
85
|
|
|
74
86
|
def in_memory(ability, items, rule)
|
|
75
|
-
items.select { |item| authorized?(ability, item, rule)
|
|
87
|
+
items.select { |item| true.equal?(authorized?(ability, item, rule)) }
|
|
76
88
|
end
|
|
77
89
|
|
|
78
90
|
def ability_for(context)
|
|
79
91
|
store = context.namespace(:armory)
|
|
80
|
-
store[:
|
|
92
|
+
abilities = store[:cancan_abilities] ||= {}
|
|
93
|
+
abilities[self] ||= ability_class.new(context[@user_key])
|
|
81
94
|
end
|
|
82
95
|
|
|
83
96
|
def ability_class
|
|
@@ -8,28 +8,37 @@ module GraphQL
|
|
|
8
8
|
module Adapters
|
|
9
9
|
# Answers the core's four questions with Pundit's public API.
|
|
10
10
|
#
|
|
11
|
-
# The policy is found from the model through Pundit::PolicyFinder, so `policy_class`
|
|
11
|
+
# The policy is found from the model's class through Pundit::PolicyFinder, so `self.policy_class`
|
|
12
12
|
# overrides and namespaced models work. A policy must answer `true`, `false` or `nil`:
|
|
13
13
|
# anything else (a lazy, a record) is handed back as is and the core refuses it.
|
|
14
14
|
class Pundit
|
|
15
|
+
# `user_key:` is the context key that holds the user.
|
|
16
|
+
def initialize(user_key: :current_user)
|
|
17
|
+
raise ArgumentError, "user_key must be a Symbol or a String, got #{user_key.class}" unless user_key.is_a?(Symbol) || user_key.is_a?(String)
|
|
18
|
+
|
|
19
|
+
@user_key = user_key
|
|
20
|
+
end
|
|
21
|
+
|
|
15
22
|
def actor(context)
|
|
16
|
-
context[
|
|
23
|
+
context[@user_key]
|
|
17
24
|
end
|
|
18
25
|
|
|
19
26
|
def authorized?(user, subject, rule)
|
|
20
|
-
policy = policy_class(rule, subject).new(user, subject)
|
|
21
27
|
query = query_for(rule)
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
28
|
+
policies_for(rule, subject).each do |policy_class|
|
|
29
|
+
policy = policy_class.new(user, subject)
|
|
30
|
+
raise AdapterError, "#{policy.class} does not define #{query}" unless policy.respond_to?(query)
|
|
25
31
|
|
|
26
|
-
|
|
32
|
+
answer = policy.public_send(query)
|
|
33
|
+
return answer unless true.equal?(answer)
|
|
34
|
+
end
|
|
35
|
+
true
|
|
27
36
|
end
|
|
28
37
|
|
|
29
38
|
def scope(user, items, rule)
|
|
30
|
-
return items.select { |item| authorized?(user, item, rule)
|
|
39
|
+
return items.select { |item| true.equal?(authorized?(user, item, rule)) } if items.is_a?(Array)
|
|
31
40
|
|
|
32
|
-
policy = policy_class(rule, rule.model || items)
|
|
41
|
+
policy = policy_class(rule, normalize(rule.model) || record_target(items))
|
|
33
42
|
scope_class = scope_constant(policy)
|
|
34
43
|
raise MissingScopeError, "#{policy} has no Scope class" if scope_class.nil?
|
|
35
44
|
|
|
@@ -50,10 +59,65 @@ module GraphQL
|
|
|
50
59
|
problems
|
|
51
60
|
end
|
|
52
61
|
|
|
62
|
+
# The policy a rule that names none asks about this model.
|
|
63
|
+
def found_policy(model)
|
|
64
|
+
finder(normalize(model)).policy
|
|
65
|
+
end
|
|
66
|
+
|
|
53
67
|
private
|
|
54
68
|
|
|
69
|
+
# A rule's `policy:` answers alone. Otherwise the declared model's policy, which is the one the audit reads, and
|
|
70
|
+
# the record's class's must both allow it: one alone lets a record of another class, or a subclass with a laxer
|
|
71
|
+
# policy, past the first, or a subclass past its own stricter policy.
|
|
72
|
+
def policies_for(rule, subject)
|
|
73
|
+
return [rule.policy] if rule.policy
|
|
74
|
+
|
|
75
|
+
model = normalize(rule.model) if rule.model
|
|
76
|
+
declared = finder(model).policy if model
|
|
77
|
+
target = model_named?(subject, model) ? subject : record_target(subject)
|
|
78
|
+
own = finder(target).policy
|
|
79
|
+
return [declared, own].compact.uniq if own
|
|
80
|
+
return [declared] if declared && kind_of_model?(subject, model)
|
|
81
|
+
|
|
82
|
+
raise ::Pundit::NotDefinedError, "no policy found for #{subject_name(target)}"
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
# A Symbol names a policy only when it is the `model:` the schema author wrote: any other is a record, maybe the
|
|
86
|
+
# client's text, as a String is.
|
|
87
|
+
def model_named?(subject, model)
|
|
88
|
+
Symbol === subject && subject.equal?(model)
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def record_target(subject)
|
|
92
|
+
Symbol === subject ? ::Symbol : policy_subject(subject)
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# Only a record of the model inherits its policy: anything else with no policy of its own raises, as it always did.
|
|
96
|
+
def kind_of_model?(subject, model)
|
|
97
|
+
return false unless model.is_a?(Module)
|
|
98
|
+
|
|
99
|
+
target = policy_subject(subject)
|
|
100
|
+
target.is_a?(Module) ? target <= model : model === target
|
|
101
|
+
end
|
|
102
|
+
|
|
55
103
|
def policy_class(rule, subject)
|
|
56
|
-
rule.policy || finder(subject).policy
|
|
104
|
+
rule.policy || finder(policy_subject(subject)).policy || raise(::Pundit::NotDefinedError, "no policy found for #{subject_name(subject)}")
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# Pundit asks the object for `policy_class` and `model_name`, and reads an Array as a namespace. A record's
|
|
108
|
+
# answers can be the client's data (an OpenStruct from JSON), so only its class is asked. A relation's class
|
|
109
|
+
# names no model, so its `klass` is read, but only on a real relation: `klass` on anything else is an answer too.
|
|
110
|
+
def policy_subject(subject)
|
|
111
|
+
return subject if Module === subject || Symbol === subject
|
|
112
|
+
return subject.klass if defined?(::ActiveRecord::Relation) && ::ActiveRecord::Relation === subject
|
|
113
|
+
|
|
114
|
+
::Kernel.instance_method(:class).bind_call(subject)
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# Never `inspect`: Pundit's own message quotes the record, and on a relation it runs the query.
|
|
118
|
+
# Nor the record's own `class` or `is_a?`: on a Struct or OpenStruct, `class` can be a data member.
|
|
119
|
+
def subject_name(subject)
|
|
120
|
+
Module === subject || Symbol === subject ? subject : ::Kernel.instance_method(:class).bind_call(subject)
|
|
57
121
|
end
|
|
58
122
|
|
|
59
123
|
def query_for(rule)
|
|
@@ -61,12 +125,13 @@ module GraphQL
|
|
|
61
125
|
end
|
|
62
126
|
|
|
63
127
|
def finder(subject)
|
|
64
|
-
::Pundit::PolicyFinder.new(
|
|
128
|
+
::Pundit::PolicyFinder.new(subject)
|
|
65
129
|
end
|
|
66
130
|
|
|
67
|
-
# Pundit reads a Symbol as a model name but a String as a plain object.
|
|
68
|
-
|
|
69
|
-
|
|
131
|
+
# Pundit reads a Symbol as a model name but a String as a plain object. Only for a model the schema author
|
|
132
|
+
# wrote: a String a type wraps is a record, maybe the client's text, and must not name its own policy.
|
|
133
|
+
def normalize(model)
|
|
134
|
+
model.is_a?(String) ? model.to_sym : model
|
|
70
135
|
end
|
|
71
136
|
|
|
72
137
|
# Looks the Scope up through the policy's ancestors but never in Object, so a
|