graphql-armory 0.1.0.pre5 → 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 +7 -0
- data/README.md +6 -4
- data/docs/authorization.md +9 -1
- data/docs/encrypted-ids.md +16 -1
- data/docs/persisted-queries.md +19 -1
- data/docs/rate-limiting.md +57 -6
- 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/ids.rb +21 -10
- data/lib/graphql/armory/persisted_queries.rb +17 -8
- data/lib/graphql/armory/rate_limits/clock.rb +35 -0
- data/lib/graphql/armory/rate_limits/controls.rb +16 -0
- data/lib/graphql/armory/rate_limits/time.rb +209 -0
- data/lib/graphql/armory/rate_limits.rb +15 -0
- data/lib/graphql/armory/telemetry.rb +82 -0
- data/lib/graphql/armory/version.rb +1 -1
- data/lib/graphql/armory.rb +1 -0
- metadata +5 -2
- data/lib/graphql/armory/authorization/telemetry.rb +0 -42
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 1a108044cb6fe2eeb2557d7d315b3e16e4ff0d31d086b7421a958c3a1d4c664b
|
|
4
|
+
data.tar.gz: f756db6daa9fc11ec6b7f1de72757002f75555d9935d1876985aae9f4e6f7690
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: a4e6bd7f6cb48c4b2a864fbb06a2bf26fdf5a4944478092acfea14769cab1744696759fe930fd35409378f70844aa6a1397c552c3ee2561bf786c3121ddbff53
|
|
7
|
+
data.tar.gz: 44fa76ca88941a4ba55b604c04b61e2d5f52b8029e7b97bd918ce8e53f83e692c6f90de7f1bd4b3f4b82cf68f40412abc76cf21e0ddd1e5a9fbf2bf0fb682cb5
|
data/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 0.1.0.pre6 (2026-10-30)
|
|
6
|
+
|
|
7
|
+
Telemetry for every module, and the processing-time layer of rate limiting. Docs: `docs/telemetry.md`, `docs/rate-limiting.md`.
|
|
8
|
+
|
|
9
|
+
- Telemetry for every module. `GraphQL::Armory::Telemetry` (the class authorization already used, now shared; `Authorization::Telemetry` is the same class) takes `sinks:` in `use GraphQL::Armory::IDs` and `use GraphQL::Armory::PersistedQueries`, as it does in authorization. IDs record `:id_resolved` and `:id_refused` (with `reason`: `:invalid`, `:malformed`, `:unknown_type`, `:not_found`); persisted queries record `:operation_persisted`, `:operation_refused` (`:unknown_operation`, `:mismatch`, `:raw_query`), `:raw_query_run` and `:raw_query_allowed`. A signal never holds an ID, an operation id or a query. `Telemetry::Notifications` reports them to `ActiveSupport::Notifications` as `<signal>.graphql_armory`. A `sinks:` that is not an Array of callables now raises `Telemetry::ConfigurationError` at boot, also in authorization (before, at the first query); the message names the offending class and never prints the value. Every sink receives the same frozen data. New page `docs/telemetry.md`: every signal, what to watch for, how to test.
|
|
10
|
+
- Rate limiting, processing time: `use GraphQL::Armory::RateLimits::Time, store:, limit:, window: 60` charges each client the wall-clock milliseconds its operations took, against a bucket of milliseconds that refills over the window. A query analyzer refuses a client with no milliseconds left before any field resolves (`RATE_LIMITED`, with `retryAfter`); a trace measures the multiplex with a monotonic clock and charges it when it ends, even when it raises, split equally among its queries. Soft mode is the default; `extensions: true` adds `rateLimitTime` to the response and `Time.headers(result)` answers `RateLimit-Time-*`. It needs no store changes. `RateLimits::Clock::Substitute` and `Controls::Time.example` are there for your specs.
|
|
11
|
+
|
|
5
12
|
## 0.1.0.pre5 (2026-10-29)
|
|
6
13
|
|
|
7
14
|
Rate limiting (roadmap module 4). Docs: `docs/rate-limiting.md`. All four modules now follow the Useful Objects doctrine.
|
data/README.md
CHANGED
|
@@ -6,12 +6,12 @@
|
|
|
6
6
|
|
|
7
7
|
Open-source extensions for [graphql-ruby](https://github.com/rmosolgo/graphql-ruby), built on its public extension points: no fork, no monkey patching. One gem, one module at a time; each module has its own page in [`docs/`](docs) with the problem it solves, how to use it, and its limits.
|
|
8
8
|
|
|
9
|
-
> **Status: early development.** Prereleases on RubyGems (`0.1.0.
|
|
9
|
+
> **Status: early development.** Prereleases on RubyGems (`0.1.0.pre6`). The API may change before 1.0.
|
|
10
10
|
|
|
11
11
|
## Install
|
|
12
12
|
|
|
13
13
|
```ruby
|
|
14
|
-
gem "graphql-armory", "~> 0.1.0.
|
|
14
|
+
gem "graphql-armory", "~> 0.1.0.pre6" # a prerelease: `gem install graphql-armory --pre`
|
|
15
15
|
gem "pundit" # or "cancancan", for the authorization module
|
|
16
16
|
```
|
|
17
17
|
|
|
@@ -26,7 +26,7 @@ Status: ✅ released, 🚧 in progress, ⬜ not started. Update this table in th
|
|
|
26
26
|
| 1 | Authorization (Pundit, CanCanCan) | ✅ | [docs/authorization.md](docs/authorization.md) | Released in 0.1.0.pre2 (prerelease). Pundit and CanCanCan (the audit checks less with CanCanCan). Global IDs in `loads:` decoded through `object_from_id`; `loads:` inside input objects scoped with `include Base`. `Execution::Next` needs graphql >= 2.6.2. |
|
|
27
27
|
| 2 | Encrypted, versioned IDs and cursors | ✅ | [docs/encrypted-ids.md](docs/encrypted-ids.md) | Released in 0.1.0.pre4 (prerelease). `Encoder` (AES-256-GCM), versioned chains and `Legacy`, `Encoder.default` (ENV or Rails), `use GraphQL::Armory::IDs`. Composite primary keys not supported. |
|
|
28
28
|
| 3 | Persisted queries / operation allowlist | ✅ | [docs/persisted-queries.md](docs/persisted-queries.md) | Released in 0.1.0.pre4 (prerelease). Allowlist from a build manifest (Apollo, Relay), `use GraphQL::Armory::PersistedQueries` with strict mode. A runtime store (database, sync endpoint) is planned for later. |
|
|
29
|
-
| 4 | Rate limiting | ✅ | [docs/rate-limiting.md](docs/rate-limiting.md) | Released in 0.1.0.pre5 (prerelease). Points per client (query complexity) and operations at the same time, `MemoryStore` and `RedisStore`, the budget in response extensions and headers.
|
|
29
|
+
| 4 | Rate limiting | ✅ | [docs/rate-limiting.md](docs/rate-limiting.md) | Released in 0.1.0.pre5 (prerelease); `RateLimits::Time` in 0.1.0.pre6. Points per client (query complexity) and operations at the same time, `MemoryStore` and `RedisStore`, the budget in response extensions and headers. `RateLimits::Time` charges the wall-clock milliseconds operations take. |
|
|
30
30
|
| 5 | Stable (keyset) connections | ⬜ | | Research not started. |
|
|
31
31
|
| 6 | Subscriptions over Pusher / Ably | ⬜ | | Research not started. |
|
|
32
32
|
| 7 | Response caching | ⬜ | | Research not started. |
|
|
@@ -38,6 +38,8 @@ Each module starts with its own research before design. A module is ✅ only whe
|
|
|
38
38
|
|
|
39
39
|
Every module page follows the same outline: **The problem**, **The solution**, **How to use it**, reference sections, **Guarantees and limits**.
|
|
40
40
|
|
|
41
|
+
Across modules: [Telemetry](docs/telemetry.md) shows how to see what the gem allowed, refused and ran, in your logs and metrics, without recording anything a client chose.
|
|
42
|
+
|
|
41
43
|
## Development
|
|
42
44
|
|
|
43
45
|
Ruby is not required on the host:
|
|
@@ -53,7 +55,7 @@ GRAPHQL_VERSION="~> 2.4.0" docker compose run --rm test # another graphq
|
|
|
53
55
|
Releases are published from GitHub Actions with RubyGems Trusted Publishing (`.github/workflows/release.yml`): no API key is stored and no OTP is asked. Bump `GraphQL::Armory::VERSION` and the CHANGELOG on `main`, then push the matching tag:
|
|
54
56
|
|
|
55
57
|
```
|
|
56
|
-
git tag v0.1.0.
|
|
58
|
+
git tag v0.1.0.pre6 && git push origin v0.1.0.pre6
|
|
57
59
|
```
|
|
58
60
|
|
|
59
61
|
The workflow checks that the tag matches the version, runs the specs and pushes the gem. It only publishes a tag on a commit of `main`. The `release` environment can require a maintainer's approval first (on a public repository, or a private one on a paid GitHub plan).
|
data/docs/authorization.md
CHANGED
|
@@ -234,7 +234,15 @@ What an interface adds is its fields, declared once and resolved on many types:
|
|
|
234
234
|
|
|
235
235
|
## Telemetry
|
|
236
236
|
|
|
237
|
-
|
|
237
|
+
The decisions are visible to you and not to the client. Pass `sinks:` to hear each one:
|
|
238
|
+
|
|
239
|
+
```ruby
|
|
240
|
+
use GraphQL::Armory::Authorization, adapter: :pundit,
|
|
241
|
+
sinks: [->(signal, data) { Rails.logger.info("armory #{signal} #{data}") }]
|
|
242
|
+
# armory denied {:type=>"Invoice", :action=>:read}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
Signals are `:allowed`, `:denied`, `:bypassed` (an `authorize :none` rule ran) and `:scoped` (a list went through the user's scope). Data holds only `type`, `action` and `reason`, never record attributes. `GraphQL::Armory::Telemetry::Notifications` reports them to `ActiveSupport::Notifications`. Every signal, what to watch for and how to test it: [Telemetry](telemetry.md). A `sinks:` that is not an Array of callables raises `Telemetry::ConfigurationError` at boot.
|
|
238
246
|
|
|
239
247
|
## Guarantees and limits
|
|
240
248
|
|
data/docs/encrypted-ids.md
CHANGED
|
@@ -103,6 +103,21 @@ return nil if encoder.nil? # nothing in the cha
|
|
|
103
103
|
log_legacy_id(id) if encoder == GraphQL::Armory::Encoder::Legacy
|
|
104
104
|
```
|
|
105
105
|
|
|
106
|
+
### Seeing what was refused
|
|
107
|
+
|
|
108
|
+
Every ID the schema does not honour answers `nil`, like a missing record, so the client learns nothing. You do not have to be as blind. Pass `sinks:` and each lookup says what happened:
|
|
109
|
+
|
|
110
|
+
```ruby
|
|
111
|
+
use GraphQL::Armory::IDs, sinks: [GraphQL::Armory::Telemetry::Notifications]
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
| Signal | Data |
|
|
115
|
+
|---|---|
|
|
116
|
+
| `:id_resolved` | `type` |
|
|
117
|
+
| `:id_refused` | `reason`: `:invalid` (did not decrypt), `:malformed` (not `Type/key`), `:unknown_type` (not in the schema, not visible, or not a `Node`), `:not_found` (missing or outside the user's scope, plus `type`) |
|
|
118
|
+
|
|
119
|
+
The signal never holds the ID, the key or the record. A rising `:invalid` is someone sending forged IDs, or clients still holding IDs from a key you rotated away; `:not_found` bursts from one client are an enumeration attempt. See [Telemetry](telemetry.md) for how to send them to your logs and metrics.
|
|
120
|
+
|
|
106
121
|
### Testing with IDs
|
|
107
122
|
|
|
108
123
|
`Encoder::Substitute` encodes reversibly without a key and records what it encoded and decoded, for specs of code that uses an encoder; never hand out real IDs with it. `IDs::Controls::Encoder.example` is an Encoder subclass with a fixed test key, and `IDs::Controls::Record.example(id:)` a record to build IDs from. `IDs::Lookup.new`, with nothing wired, hands out no ID and honours none (`Encoder::Null`); `IDs::Lookup.build(encoder:, find:)` takes the same settings as `use`.
|
|
@@ -122,7 +137,7 @@ log_legacy_id(id) if encoder == GraphQL::Armory::Encoder::Legacy
|
|
|
122
137
|
| `decode(id)` / `decode(cursor, nonce: true)` | The text, or raises `GraphQL::Armory::Encoder::InvalidError` (a `GraphQL::ExecutionError`, so clients see `Invalid ID or cursor`). |
|
|
123
138
|
| `Encoder.versioned(newest, ..., oldest)` | A chain with the same `encode` and `decode`; encodes with `newest`. |
|
|
124
139
|
| `chain.decode_versioned(text, nonce: false)` | `[data, encoder]`, or `[nil, nil]` when no encoder accepts it. |
|
|
125
|
-
| `use GraphQL::Armory::IDs, encoder: nil, find: nil` | Defines `id_from_object` and `object_from_id`; `encoder` defaults to `Encoder.default`; `find:` loads types without `Base
|
|
140
|
+
| `use GraphQL::Armory::IDs, encoder: nil, find: nil, sinks: []` | Defines `id_from_object` and `object_from_id`; `encoder` defaults to `Encoder.default`; `find:` loads types without `Base`; `sinks:` hears `:id_resolved` and `:id_refused` ([Telemetry](telemetry.md)). |
|
|
126
141
|
| `Encoder.default` | An encoder keyed by `GRAPHQL_ARMORY_KEY`, else by a key derived with HKDF from Rails' `secret_key_base`; raises `ConfigurationError` without either. |
|
|
127
142
|
|
|
128
143
|
A subclass inherits `key`, `tag` and `codec`, and can override any of them. Passing `nil` to any of them raises `ConfigurationError`, so an unset environment variable fails at boot instead of being ignored.
|
data/docs/persisted-queries.md
CHANGED
|
@@ -136,6 +136,23 @@ Relay's example network layer sends the id as `doc_id`. Pass it yourself: `opera
|
|
|
136
136
|
|
|
137
137
|
Deploy the server with the new manifest before, or with, the clients that use its new operations: until then they get `Unknown operation id`. Keep old operations in the file while old app versions are still in use.
|
|
138
138
|
|
|
139
|
+
### Watching the rollout
|
|
140
|
+
|
|
141
|
+
A refused request tells the client only `Unknown operation id` or `Only persisted operations are allowed`. To know how many, and from whom, pass `sinks:`:
|
|
142
|
+
|
|
143
|
+
```ruby
|
|
144
|
+
use GraphQL::Armory::PersistedQueries, store: PERSISTED, sinks: [GraphQL::Armory::Telemetry::Notifications]
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
| Signal | When |
|
|
148
|
+
|---|---|
|
|
149
|
+
| `:operation_persisted` | A request ran the stored operation its id names |
|
|
150
|
+
| `:operation_refused` | Refused, with `reason`: `:unknown_operation`, `:mismatch` or `:raw_query` |
|
|
151
|
+
| `:raw_query_run` | A raw query ran because you are not strict yet |
|
|
152
|
+
| `:raw_query_allowed` | A raw query ran in strict mode because the context holds `armory_allow_raw_query: true` |
|
|
153
|
+
|
|
154
|
+
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
|
+
|
|
139
156
|
### Testing with persisted queries
|
|
140
157
|
|
|
141
158
|
`PersistedQueries::Store::Substitute.new(*queries)` holds the given queries under their SHA-256, like an Apollo manifest, and records the ids it was asked for (`fetched`). `PersistedQueries::Controls::Operations`, `Query.example` and `Root.example` are a small schema and its operations to test against. The decision itself is `PersistedQueries::Gate`: `Gate.build(store:, strict:)` takes the same settings as `use`, and `gate.(context, query_text, document)` answers `[refusal, document]`. `Gate.new`, with nothing wired, refuses every request (`Store::Null`, strict).
|
|
@@ -149,10 +166,11 @@ Deploy the server with the new manifest before, or with, the clients that use it
|
|
|
149
166
|
- `fetch(id)` answers the operation (`id`, `name`, `body`, `document`, all frozen) or nil. `size` counts them.
|
|
150
167
|
- 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.
|
|
151
168
|
|
|
152
|
-
`use GraphQL::Armory::PersistedQueries, store:, strict: false`
|
|
169
|
+
`use GraphQL::Armory::PersistedQueries, store:, strict: false, sinks: []`
|
|
153
170
|
|
|
154
171
|
- `store:` answers `fetch(id)` with an object that has `body` and `document`, or nil. A Manifest, or your own store.
|
|
155
172
|
- `strict:` is `true` or `false`.
|
|
173
|
+
- `sinks:` an Array of callables taking `(signal, data)`; see [Watching the rollout](#watching-the-rollout).
|
|
156
174
|
- Works with your own `query_class`, whether it is set before `use`, after it, or in a child schema: the plugin subclasses it.
|
|
157
175
|
- `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.
|
|
158
176
|
- A store whose `fetch` raises or answers something without `document` makes the request raise: it fails closed, as an exception.
|
data/docs/rate-limiting.md
CHANGED
|
@@ -22,7 +22,7 @@ A limit of 100 requests per minute lets a client send 100 of the second kind, by
|
|
|
22
22
|
- **Per client.** Each client key (a user, an API token, an IP) has its own bucket; you can give each key its own limit.
|
|
23
23
|
- **Safe to roll out.** Soft mode, the default, charges and records but refuses nothing, so you can watch real traffic before turning it on.
|
|
24
24
|
|
|
25
|
-
`GraphQL::Armory::RateLimits::Concurrency` adds a second rule: at most N operations running at the same time per client ([Operations at the same time](#operations-at-the-same-time)). Both keep their state in a store: `MemoryStore` for tests and one process, `RedisStore` for production ([Sharing limits between processes](#sharing-limits-between-processes)).
|
|
25
|
+
`GraphQL::Armory::RateLimits::Concurrency` adds a second rule: at most N operations running at the same time per client ([Operations at the same time](#operations-at-the-same-time)). Both keep their state in a store: `MemoryStore` for tests and one process, `RedisStore` for production ([Sharing limits between processes](#sharing-limits-between-processes)). `GraphQL::Armory::RateLimits::Time` adds a third: a budget of wall-clock milliseconds per client, charged for the time its operations really took ([Time spent running](#time-spent-running)).
|
|
26
26
|
|
|
27
27
|
## How to use it
|
|
28
28
|
|
|
@@ -192,12 +192,45 @@ It uses the same `rate_limit_key`. Before an operation runs it takes one of the
|
|
|
192
192
|
|
|
193
193
|
A process that crashes never gives its slots back, so each slot expires after `stale_after:` seconds (60 by default). Set it above your longest request timeout. Soft mode, per-key limits (`limit: ->(key, query) { ... }`) and `on_store_error:` work as for `Points`; what happened is in `result.context[:rate_limit_concurrency]` (`{ key:, limit:, active:, soft:, limited: }`).
|
|
194
194
|
|
|
195
|
+
### Time spent running
|
|
196
|
+
|
|
197
|
+
The cost of a query is an estimate made before it runs. A field scored 1 that waits three seconds on a slow service still occupies a server thread for three seconds, and points never see it. `Time` charges what really happened: the wall-clock milliseconds each operation took, against a bucket of milliseconds per client that refills over a window.
|
|
198
|
+
|
|
199
|
+
```ruby
|
|
200
|
+
class AppSchema < GraphQL::Schema
|
|
201
|
+
use GraphQL::Armory::RateLimits::Time,
|
|
202
|
+
store: store, # the same store as Points
|
|
203
|
+
limit: 10_000, # milliseconds per window, per client
|
|
204
|
+
window: 60,
|
|
205
|
+
soft: false
|
|
206
|
+
end
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
It uses the same `rate_limit_key`. Before an operation runs it asks the store for the client's balance; a client with no milliseconds left is refused before any field resolves, and charged nothing:
|
|
210
|
+
|
|
211
|
+
```json
|
|
212
|
+
{
|
|
213
|
+
"errors": [{
|
|
214
|
+
"message": "Rate limit exceeded: this client used its 10000 ms of processing time every 60 seconds. Retry in 1 seconds.",
|
|
215
|
+
"extensions": { "code": "RATE_LIMITED", "limit": 10000, "retryAfter": 1 }
|
|
216
|
+
}]
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
When the operation ends, even if it raised, the milliseconds it took (measured with a monotonic clock) are charged. The time is wall-clock, not CPU: waiting on a database or an external service counts, because that is what keeps a server thread busy. A running operation is never interrupted, so the one that spends the last milliseconds finishes and the next one is refused; the balance never goes below zero, and the client recovers `limit` milliseconds per `window`.
|
|
221
|
+
|
|
222
|
+
Soft mode (the default), per-key limits (`limit: ->(key, query) { ... }`) and `on_store_error:` work as for `Points`. To show clients their budget, pass `extensions: true`, which adds `"rateLimitTime" => { limit, remaining, elapsed, resetIn }` (milliseconds, and seconds for `resetIn`; `elapsed` appears once the operation ran, so a refused one has none) to the response, or send `Time.headers(result)`: `RateLimit-Time-Limit`, `RateLimit-Time-Remaining` and `RateLimit-Time-Reset`, prefixed so they never clash with the `Points` headers. What happened is in `result.context[:rate_limit_time]`: `{ key:, limit:, remaining:, elapsed:, window:, soft:, limited: }`, where `elapsed` is nil for an operation that was refused.
|
|
223
|
+
|
|
224
|
+
To test it, inject a clock: `Time` takes `clock:` (a callable answering seconds), and `RateLimits::Clock::Substitute` is one your test moves. `Controls::Time.example(clock, seconds: 0.25)` is a root for `Controls::Query.example` whose every field takes that long on the clock.
|
|
225
|
+
|
|
195
226
|
### Rolling it out
|
|
196
227
|
|
|
197
228
|
1. Install it in soft mode (leave out `soft:`). Queries run as before; each one records what it cost.
|
|
198
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.
|
|
199
230
|
3. When the limits fit your traffic, set `soft: false`.
|
|
200
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).
|
|
233
|
+
|
|
201
234
|
### Sharing limits between processes
|
|
202
235
|
|
|
203
236
|
`MemoryStore` keeps buckets in one process: with four Puma workers on two servers, a client gets the limit eight times over, and a restart refills every bucket. In production use `RedisStore`, which keeps them in Redis, shared by every process:
|
|
@@ -257,6 +290,16 @@ store.calls # [[:take, "user:1", { cost:
|
|
|
257
290
|
- `soft:`, `key:` and `on_store_error:` as for `Points`. When the store raises on release, `on_store_error` is called and the slot expires after `stale_after`.
|
|
258
291
|
- Instrumentation: `context[:rate_limit_concurrency]`.
|
|
259
292
|
|
|
293
|
+
`use GraphQL::Armory::RateLimits::Time, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, clock: Clock.monotonic, extensions: false`
|
|
294
|
+
|
|
295
|
+
- `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
|
+
- `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 `on_store_error:` as for `Points`.
|
|
298
|
+
- `clock:` a callable answering seconds, read when a multiplex starts and when it ends. By default a monotonic clock.
|
|
299
|
+
- `extensions:` `true` adds `"rateLimitTime" => { limit, remaining, elapsed, resetIn }` to the response of a limited client.
|
|
300
|
+
- `Time.headers(result)` answers the `RateLimit-Time-*` headers for a result, or `{}`.
|
|
301
|
+
- Instrumentation: `context[:rate_limit_time]`.
|
|
302
|
+
|
|
260
303
|
`GraphQL::Armory::RateLimits::RedisStore.new(redis:, prefix: "graphql-armory:rate-limits:", clock: nil)`
|
|
261
304
|
|
|
262
305
|
- `redis:` a redis-rb client (>= 4.8), or anything answering `eval(script, keys:, argv:)` and `evalsha(sha, keys:, argv:)` the same way. Needs Redis 5 or later. Works with Redis Cluster: each script touches one key.
|
|
@@ -273,15 +316,23 @@ Invalid settings raise `RateLimits::ConfigurationError` at boot.
|
|
|
273
316
|
- A query run with its own trace (`context: { trace: ... }`) cannot be released by `Concurrency`, so it raises `ConfigurationError` instead of taking a slot.
|
|
274
317
|
- A resolver that runs another query for the same client (a nested `execute`) takes a second slot while the first is held.
|
|
275
318
|
- A subscription holds a slot only while its first result runs, not while it stays subscribed.
|
|
276
|
-
- When queries of a multiplex share one context hash, `context[:rate_limit_points]` and `context[:
|
|
277
|
-
- 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
|
|
319
|
+
- 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
|
+
- 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.
|
|
278
321
|
- Field scores are yours: graphql-ruby treats a negative or NaN complexity as 0, so such a field is free, like `complexity: 0`. A complexity that is nil or a String makes graphql-ruby raise before the limiter runs, so the query does not run.
|
|
279
322
|
- When the store fails, queries run unlimited and `on_store_error` is called. Choose that hook to alert. `RedisStore` also counts a bucket whose fields were changed into something that is not a number as a store failure, rather than reading it as full.
|
|
280
323
|
- `MemoryStore` keeps buckets and slots in one process and forgets them on restart: with several processes, each one gives a client the full limit. It keeps one entry per client key it has seen. Use `RedisStore` in production.
|
|
281
324
|
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
-
|
|
325
|
+
### Limits of `Time`
|
|
326
|
+
|
|
327
|
+
- 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
|
+
- `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
|
+
- 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, with different stores and keys): 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
|
+
- 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
|
+
- 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
|
+
- 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.
|
|
334
|
+
- A query run with its own trace (`context: { trace: ... }`) cannot be charged, so it raises `ConfigurationError`, as with `Concurrency`.
|
|
335
|
+
- When the store fails, operations run unlimited and `on_store_error` is called; a failed charge never raises into the query (unless your hook does).
|
|
285
336
|
|
|
286
337
|
## References
|
|
287
338
|
|
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
|
data/lib/graphql/armory/ids.rb
CHANGED
|
@@ -16,23 +16,23 @@ module GraphQL
|
|
|
16
16
|
module IDs
|
|
17
17
|
SEPARATOR = "/"
|
|
18
18
|
|
|
19
|
-
def self.use(schema, encoder: nil, find: nil)
|
|
20
|
-
lookup = Lookup.build(encoder: encoder, find: find)
|
|
19
|
+
def self.use(schema, encoder: nil, find: nil, sinks: [])
|
|
20
|
+
lookup = Lookup.build(encoder: encoder, find: find, sinks: sinks)
|
|
21
21
|
schema.define_singleton_method(:id_from_object) { |object, type, _context| lookup.id_for(object, type) }
|
|
22
22
|
schema.define_singleton_method(:object_from_id) { |id, context| lookup.object_for(id, context) }
|
|
23
23
|
end
|
|
24
24
|
|
|
25
25
|
# Turns records into IDs and IDs back into records.
|
|
26
26
|
class Lookup
|
|
27
|
-
attr_reader :encoder, :find
|
|
27
|
+
attr_reader :encoder, :find, :telemetry
|
|
28
28
|
|
|
29
29
|
# Wires the default encoder unless one is given; `use` goes through here.
|
|
30
|
-
def self.build(encoder: nil, find: nil)
|
|
31
|
-
new(encoder: encoder || Encoder.default, find: find)
|
|
30
|
+
def self.build(encoder: nil, find: nil, sinks: [])
|
|
31
|
+
new(encoder: encoder || Encoder.default, find: find, telemetry: Telemetry.build(sinks: sinks))
|
|
32
32
|
end
|
|
33
33
|
|
|
34
34
|
# `new` is inert: with no encoder wired it hands out no ID and honours none. It checks what it is given.
|
|
35
|
-
def initialize(encoder: Encoder::Null, find: nil)
|
|
35
|
+
def initialize(encoder: Encoder::Null, find: nil, telemetry: Telemetry.new)
|
|
36
36
|
unless %i[encode decode].all? { |name| encoder.respond_to?(name) }
|
|
37
37
|
raise Encoder::ConfigurationError, "encoder: must answer encode and decode, like an Encoder subclass"
|
|
38
38
|
end
|
|
@@ -40,6 +40,7 @@ module GraphQL
|
|
|
40
40
|
|
|
41
41
|
@encoder = encoder
|
|
42
42
|
@find = find
|
|
43
|
+
@telemetry = telemetry
|
|
43
44
|
end
|
|
44
45
|
|
|
45
46
|
def id_for(object, type)
|
|
@@ -51,18 +52,28 @@ module GraphQL
|
|
|
51
52
|
|
|
52
53
|
def object_for(id, context)
|
|
53
54
|
type_name, key = encoder.decode(id).split(SEPARATOR, 2)
|
|
54
|
-
return
|
|
55
|
+
return refuse(:malformed) if key.nil? || key.empty?
|
|
55
56
|
|
|
56
57
|
type = visible_type(type_name, context)
|
|
57
|
-
return
|
|
58
|
+
return refuse(:unknown_type) unless node_type?(type)
|
|
58
59
|
|
|
59
|
-
load(type, key, context)
|
|
60
|
+
object = load(type, key, context)
|
|
61
|
+
return refuse(:not_found, type: type.graphql_name) if object.nil?
|
|
62
|
+
|
|
63
|
+
telemetry.record(:id_resolved, type: type.graphql_name)
|
|
64
|
+
object
|
|
60
65
|
rescue Encoder::InvalidError
|
|
61
|
-
|
|
66
|
+
refuse(:invalid)
|
|
62
67
|
end
|
|
63
68
|
|
|
64
69
|
private
|
|
65
70
|
|
|
71
|
+
# Every refusal answers nil, like a missing record; the signal says why, never which ID.
|
|
72
|
+
def refuse(reason, **data)
|
|
73
|
+
telemetry.record(:id_refused, reason: reason, **data)
|
|
74
|
+
nil
|
|
75
|
+
end
|
|
76
|
+
|
|
66
77
|
# Through the query's own view of the schema: `Schema.get_type(name, context)` does not apply `visible?`
|
|
67
78
|
# when graphql-ruby runs without `Schema::Visibility`, `context.types` does in both modes.
|
|
68
79
|
def visible_type(type_name, context)
|
|
@@ -39,8 +39,8 @@ 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
|
-
gate = Gate.build(store: store, strict: strict)
|
|
42
|
+
def self.use(schema, store:, strict: false, sinks: [])
|
|
43
|
+
gate = Gate.build(store: store, strict: strict, sinks: sinks)
|
|
44
44
|
|
|
45
45
|
if schema.singleton_class.include?(Guard)
|
|
46
46
|
raise ConfigurationError, "#{schema} already uses PersistedQueries (here or in a parent schema): use it once"
|
|
@@ -56,13 +56,13 @@ module GraphQL
|
|
|
56
56
|
# as it came.
|
|
57
57
|
class Gate
|
|
58
58
|
# Wires the app's store with `use`'s defaults; `use` goes through here.
|
|
59
|
-
def self.build(store:, strict: false)
|
|
60
|
-
new(store: store, strict: strict)
|
|
59
|
+
def self.build(store:, strict: false, sinks: [])
|
|
60
|
+
new(store: store, strict: strict, telemetry: Telemetry.build(sinks: sinks))
|
|
61
61
|
end
|
|
62
62
|
|
|
63
63
|
# `new` is inert: with no store wired it refuses every request. It checks what it is given, so it never
|
|
64
64
|
# lets raw queries through without a store either.
|
|
65
|
-
def initialize(store: Store::Null.new, strict: true)
|
|
65
|
+
def initialize(store: Store::Null.new, strict: true, telemetry: Telemetry.new)
|
|
66
66
|
if store.is_a?(Hash) || !store.respond_to?(:fetch)
|
|
67
67
|
raise ConfigurationError, "store: must answer fetch(id) with an operation or nil, like a Manifest"
|
|
68
68
|
end
|
|
@@ -71,6 +71,7 @@ module GraphQL
|
|
|
71
71
|
|
|
72
72
|
@store = store
|
|
73
73
|
@strict = strict
|
|
74
|
+
@telemetry = telemetry
|
|
74
75
|
end
|
|
75
76
|
|
|
76
77
|
def call(context, text, document)
|
|
@@ -79,21 +80,29 @@ module GraphQL
|
|
|
79
80
|
if !operation_id.nil?
|
|
80
81
|
operation = operation_id.is_a?(String) ? @store.fetch(operation_id) : nil
|
|
81
82
|
if operation.nil?
|
|
82
|
-
|
|
83
|
+
refuse(UNKNOWN_OPERATION, :unknown_operation)
|
|
83
84
|
elsif document || (text && !same_query?(text, operation))
|
|
84
|
-
|
|
85
|
+
refuse(MISMATCH, :mismatch)
|
|
85
86
|
else
|
|
87
|
+
@telemetry.record(:operation_persisted)
|
|
86
88
|
[nil, operation.document]
|
|
87
89
|
end
|
|
88
90
|
elsif @strict && !(context.respond_to?(:[]) && context[:armory_allow_raw_query] == true)
|
|
89
|
-
|
|
91
|
+
refuse(RAW_QUERY_REFUSED, :raw_query)
|
|
90
92
|
else
|
|
93
|
+
@telemetry.record(@strict ? :raw_query_allowed : :raw_query_run) if text || document
|
|
91
94
|
[nil, nil]
|
|
92
95
|
end
|
|
93
96
|
end
|
|
94
97
|
|
|
95
98
|
private
|
|
96
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
|
+
|
|
97
106
|
# Apollo's clients may send the query with its id; graphql-ruby's subscriptions resend it printed.
|
|
98
107
|
def same_query?(text, operation)
|
|
99
108
|
text == operation.body || text == operation.document.to_query_string
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
module RateLimits
|
|
6
|
+
# What a limiter reads the time from: a callable answering seconds, like `Clock.monotonic`.
|
|
7
|
+
module Clock
|
|
8
|
+
def self.monotonic
|
|
9
|
+
MemoryStore.monotonic_clock
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
# A clock the test moves (`advance`, `now`) and that counts how often it was read: for tests, instead of
|
|
13
|
+
# hand-written fakes.
|
|
14
|
+
class Substitute
|
|
15
|
+
attr_accessor :now
|
|
16
|
+
attr_reader :reads
|
|
17
|
+
|
|
18
|
+
def initialize(now: 0.0)
|
|
19
|
+
@now = now
|
|
20
|
+
@reads = 0
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def call
|
|
24
|
+
@reads += 1
|
|
25
|
+
@now
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def advance(seconds)
|
|
29
|
+
@now += seconds
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
@@ -28,6 +28,22 @@ module GraphQL
|
|
|
28
28
|
end
|
|
29
29
|
end
|
|
30
30
|
|
|
31
|
+
# A root for Query.example whose every field takes `seconds` on `clock` (a Clock::Substitute) before it
|
|
32
|
+
# answers, so a spec decides how long an operation took.
|
|
33
|
+
module Time
|
|
34
|
+
def self.example(clock, resolved = [], seconds: 0.25)
|
|
35
|
+
root = Root.example(resolved)
|
|
36
|
+
Class.new do
|
|
37
|
+
%i[cheap report broken].each do |field|
|
|
38
|
+
define_method(field) do
|
|
39
|
+
clock.advance(seconds)
|
|
40
|
+
root.public_send(field)
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end.new
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
|
|
31
47
|
# A query context naming its client.
|
|
32
48
|
module Context
|
|
33
49
|
def self.example(key: "user:1", **context)
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
module RateLimits
|
|
6
|
+
# Charges each client the wall-clock milliseconds its operations take, against a bucket of milliseconds per
|
|
7
|
+
# client that refills over a window:
|
|
8
|
+
#
|
|
9
|
+
# use GraphQL::Armory::RateLimits::Time, store: GraphQL::Armory::RateLimits::MemoryStore.new,
|
|
10
|
+
# limit: 10_000, window: 60, soft: false
|
|
11
|
+
#
|
|
12
|
+
# A query analyzer asks the store for the client's balance before the operation runs and refuses it, before any
|
|
13
|
+
# field resolves, when none is left. A trace measures the multiplex with a monotonic clock and charges the
|
|
14
|
+
# elapsed milliseconds when it ends, even when it raises. A running operation is never interrupted: the one
|
|
15
|
+
# that spends the last milliseconds finishes, and the next is refused. Soft mode (the default) charges and
|
|
16
|
+
# records but refuses nothing. What happened is in `context[:rate_limit_time]`.
|
|
17
|
+
class Time
|
|
18
|
+
CONTEXT_KEY = :rate_limit_time
|
|
19
|
+
NAMESPACE = :graphql_armory
|
|
20
|
+
|
|
21
|
+
def self.use(schema, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, clock: Clock.monotonic, extensions: false)
|
|
22
|
+
build(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, clock: clock, extensions: extensions).install(schema)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# HTTP headers for the budget a result recorded: `RateLimit-Time-Limit` and `RateLimit-Time-Remaining` in
|
|
26
|
+
# milliseconds, and `RateLimit-Time-Reset` (seconds until the bucket is full again). Prefixed so they never
|
|
27
|
+
# clash with the `Points` headers. Empty when the query had no limit.
|
|
28
|
+
def self.headers(result)
|
|
29
|
+
info = result.context.namespace(NAMESPACE)[:time]
|
|
30
|
+
return {} unless info && info[:limit] && info[:remaining]
|
|
31
|
+
|
|
32
|
+
{
|
|
33
|
+
"RateLimit-Time-Limit" => info[:limit].to_s,
|
|
34
|
+
"RateLimit-Time-Remaining" => info[:remaining].to_s,
|
|
35
|
+
"RateLimit-Time-Reset" => Points.reset_in(info).to_s
|
|
36
|
+
}
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Wires the app's store with `use`'s defaults (soft mode); `use` goes through here.
|
|
40
|
+
def self.build(store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, clock: Clock.monotonic, extensions: false)
|
|
41
|
+
new(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, clock: clock, extensions: extensions)
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# `new` is inert: with no store wired it refuses every query. It checks every setting, so no partial
|
|
45
|
+
# configuration lets a query through either.
|
|
46
|
+
def initialize(store: Store::Null.new, limit: 1, window: 60, soft: false, key: nil, on_store_error: nil, clock: Clock.monotonic, extensions: false)
|
|
47
|
+
unless Settings.store_answers?(store, take: %i[cost limit window force])
|
|
48
|
+
raise ConfigurationError, "store: must answer take(key, cost:, limit:, window:, force:), like a MemoryStore"
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
@store = store
|
|
52
|
+
@limit = Settings.wired_limit(limit, store)
|
|
53
|
+
@window = Settings.seconds(:window, window)
|
|
54
|
+
@soft = Settings.wired_soft(soft, store)
|
|
55
|
+
@key = Settings.key_reader(key)
|
|
56
|
+
@on_store_error = Settings.store_error_handler(on_store_error)
|
|
57
|
+
@clock = Settings.clock(clock)
|
|
58
|
+
now # a clock that answers anything but a finite number fails here, not by charging nothing
|
|
59
|
+
@extensions = Settings.extensions(extensions)
|
|
60
|
+
@trace = measuring_trace
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Adds the analyzer and the trace to the schema.
|
|
64
|
+
def install(schema)
|
|
65
|
+
time = self
|
|
66
|
+
schema.query_analyzer(Class.new(Analyzer) { define_method(:time) { time } })
|
|
67
|
+
schema.trace_with(@trace)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# The refusal for a client with no milliseconds left, or nil to let the operation run (and be charged).
|
|
71
|
+
def call(query)
|
|
72
|
+
unless query.current_trace.is_a?(@trace)
|
|
73
|
+
raise ConfigurationError, "this query runs with its own trace (context[:trace]), so Time could never charge it: remove context[:trace] or add trace_with to that trace"
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
key = Settings.key_for(@key, query)
|
|
77
|
+
limit = Settings.limit_for(@limit, key, query)
|
|
78
|
+
if limit.nil?
|
|
79
|
+
record(query, key: key, limit: nil, remaining: nil, limited: false)
|
|
80
|
+
return nil
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
answer = begin
|
|
84
|
+
@store.take(key, cost: 0, limit: limit, window: @window, force: false)
|
|
85
|
+
rescue StandardError => error
|
|
86
|
+
# Fail open, and still measure: the charge may find the store back.
|
|
87
|
+
query.context[CONTEXT_KEY] = nil
|
|
88
|
+
@on_store_error.call(error, query)
|
|
89
|
+
owe(query, key, limit)
|
|
90
|
+
return nil
|
|
91
|
+
end
|
|
92
|
+
_taken, remaining = Settings.checked(answer, :take, "the Integer milliseconds left")
|
|
93
|
+
|
|
94
|
+
limited = remaining.zero?
|
|
95
|
+
info = record(query, key: key, limit: limit, remaining: remaining, limited: limited)
|
|
96
|
+
extension = announce(query, info) if @extensions
|
|
97
|
+
return refusal(limit) if limited && !@soft
|
|
98
|
+
|
|
99
|
+
owe(query, key, limit, info, extension)
|
|
100
|
+
nil
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# The clock's reading, for the trace. A reading that is not a finite number would make the charge
|
|
104
|
+
# impossible, so it raises instead of letting operations run uncharged.
|
|
105
|
+
def now
|
|
106
|
+
reading = @clock.call
|
|
107
|
+
return reading if reading.is_a?(Numeric) && reading.finite?
|
|
108
|
+
|
|
109
|
+
raise ConfigurationError, "clock: answered #{reading.inspect}: it must answer a finite number of seconds"
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# Charges the elapsed time since `started`, split equally among the queries of the multiplex that ran.
|
|
113
|
+
def charge(multiplex, started)
|
|
114
|
+
return if started.nil?
|
|
115
|
+
|
|
116
|
+
# A clock that stands still or goes backwards charges nothing.
|
|
117
|
+
seconds = [now - started, 0].max
|
|
118
|
+
# Each limiter takes only its own debts: a schema may `use` several, with different stores and keys.
|
|
119
|
+
owed = multiplex.queries.filter_map do |query|
|
|
120
|
+
debt = query.context.namespace(NAMESPACE)[:time_charges]&.delete(self)
|
|
121
|
+
[query, debt] if debt
|
|
122
|
+
end
|
|
123
|
+
return if owed.empty?
|
|
124
|
+
|
|
125
|
+
share = (seconds * 1000 / owed.size.to_f).ceil
|
|
126
|
+
# Every query is charged even if one hook raises; the first such error is raised afterwards.
|
|
127
|
+
failure = nil
|
|
128
|
+
owed.each do |query, debt|
|
|
129
|
+
charge_one(query, debt, share)
|
|
130
|
+
rescue StandardError => error
|
|
131
|
+
failure ||= error
|
|
132
|
+
end
|
|
133
|
+
raise failure if failure
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
private
|
|
137
|
+
|
|
138
|
+
def charge_one(query, debt, cost)
|
|
139
|
+
answer = @store.take(debt[:key], cost: cost, limit: debt[:limit], window: @window, force: true)
|
|
140
|
+
_taken, remaining = Settings.checked(answer, :take, "the Integer milliseconds left")
|
|
141
|
+
settle(query, debt, cost, remaining)
|
|
142
|
+
rescue StandardError => error
|
|
143
|
+
@on_store_error.call(error, query)
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
# What the client has left once the charge is in, in the record and in the extensions announced earlier.
|
|
147
|
+
def settle(query, debt, cost, remaining)
|
|
148
|
+
info = (debt[:info] || base_record(key: debt[:key], limit: debt[:limit], limited: false)).merge(remaining: remaining, elapsed: cost)
|
|
149
|
+
query.context.namespace(NAMESPACE)[:time] = info
|
|
150
|
+
query.context[CONTEXT_KEY] = info
|
|
151
|
+
debt[:extension]&.merge!("remaining" => remaining, "elapsed" => cost, "resetIn" => Points.reset_in(info))
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
# Per query and per limiter, not in the context hash: queries of a multiplex may share one hash, and a
|
|
155
|
+
# schema may use several limiters.
|
|
156
|
+
def owe(query, key, limit, info = nil, extension = nil)
|
|
157
|
+
charges = (query.context.namespace(NAMESPACE)[:time_charges] ||= {})
|
|
158
|
+
charges[self] = { key: key, limit: limit, info: info, extension: extension }
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
def record(query, **info)
|
|
162
|
+
info = base_record(**info)
|
|
163
|
+
query.context.namespace(NAMESPACE)[:time] = info
|
|
164
|
+
query.context[CONTEXT_KEY] = info
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
# `elapsed` is nil until the operation ends and is charged; it stays nil for a refused one.
|
|
168
|
+
def base_record(key:, limit:, limited:, remaining: nil)
|
|
169
|
+
{ key: key, limit: limit, remaining: remaining, elapsed: nil, window: @window, soft: @soft, limited: limited }
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# The budget before the run; the charge completes the same hash, which the response already holds.
|
|
173
|
+
def announce(query, info)
|
|
174
|
+
extension = { "limit" => info[:limit], "remaining" => info[:remaining], "resetIn" => Points.reset_in(info) }
|
|
175
|
+
query.context.response_extensions["rateLimitTime"] = extension
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
def refusal(limit)
|
|
179
|
+
retry_after = [(@window / limit.to_f).ceil, 1].max
|
|
180
|
+
GraphQL::AnalysisError.new(
|
|
181
|
+
"Rate limit exceeded: this client used its #{limit} ms of processing time every #{@window} seconds. Retry in #{retry_after} seconds.",
|
|
182
|
+
extensions: { "code" => "RATE_LIMITED", "limit" => limit, "retryAfter" => retry_after }
|
|
183
|
+
)
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
# One module per limiter, so the trace reads this limiter's clock and charges this limiter's store.
|
|
187
|
+
def measuring_trace
|
|
188
|
+
time = self
|
|
189
|
+
Module.new do
|
|
190
|
+
# `define_method` does not forward the block implicitly, as `def` with `super` does.
|
|
191
|
+
define_method(:execute_multiplex) do |multiplex:, &block|
|
|
192
|
+
started = time.now
|
|
193
|
+
super(multiplex: multiplex, &block)
|
|
194
|
+
ensure
|
|
195
|
+
time.charge(multiplex, started)
|
|
196
|
+
end
|
|
197
|
+
end
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
# Asks for the balance during analysis, before anything runs.
|
|
201
|
+
class Analyzer < GraphQL::Analysis::Analyzer
|
|
202
|
+
def result
|
|
203
|
+
time.(query)
|
|
204
|
+
end
|
|
205
|
+
end
|
|
206
|
+
end
|
|
207
|
+
end
|
|
208
|
+
end
|
|
209
|
+
end
|
|
@@ -97,6 +97,19 @@ module GraphQL
|
|
|
97
97
|
raise ConfigurationError, "store: #{method} answered #{answer.inspect}: it must answer [true or false, #{meaning}]"
|
|
98
98
|
end
|
|
99
99
|
|
|
100
|
+
def extensions(value)
|
|
101
|
+
raise ConfigurationError, "extensions: must be true or false, got #{value.inspect}" unless value == true || value == false
|
|
102
|
+
|
|
103
|
+
value
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# A callable answering seconds, like `Clock.monotonic`.
|
|
107
|
+
def clock(value)
|
|
108
|
+
raise ConfigurationError, "clock: must be a callable answering seconds, got #{value.inspect}" unless value.respond_to?(:call)
|
|
109
|
+
|
|
110
|
+
value
|
|
111
|
+
end
|
|
112
|
+
|
|
100
113
|
def store_error_handler(handler)
|
|
101
114
|
return ->(error, _query) { warn("graphql-armory rate limit store failed, query let through: #{error.class}: #{error.message}") } if handler.nil?
|
|
102
115
|
raise ConfigurationError, "on_store_error: must be a callable that takes the error and the query" unless handler.respond_to?(:call)
|
|
@@ -110,7 +123,9 @@ end
|
|
|
110
123
|
|
|
111
124
|
require "graphql/armory/rate_limits/memory_store"
|
|
112
125
|
require "graphql/armory/rate_limits/store"
|
|
126
|
+
require "graphql/armory/rate_limits/clock"
|
|
113
127
|
require "graphql/armory/rate_limits/redis_store"
|
|
114
128
|
require "graphql/armory/rate_limits/points"
|
|
115
129
|
require "graphql/armory/rate_limits/concurrency"
|
|
130
|
+
require "graphql/armory/rate_limits/time"
|
|
116
131
|
require "graphql/armory/rate_limits/controls"
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
# Records what a module decided (a request allowed, an ID refused, an operation run) and hands it to its sinks.
|
|
6
|
+
# A sink is anything that responds to `call(signal, data)`: a lambda that logs, a metrics client, or
|
|
7
|
+
# `Telemetry::Notifications`. Never put record attributes, IDs, keys or queries in `data`: a client chooses
|
|
8
|
+
# those, and they would end up in the app's logs.
|
|
9
|
+
class Telemetry
|
|
10
|
+
class ConfigurationError < Armory::Error; end
|
|
11
|
+
|
|
12
|
+
def self.build(sinks: [])
|
|
13
|
+
new(sinks: sinks)
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def initialize(sinks: [])
|
|
17
|
+
# Messages name a class, never `inspect` a value: a metrics client holds its API key.
|
|
18
|
+
raise ConfigurationError, "sinks: must be an Array of callables taking (signal, data), got #{sinks.class}" unless sinks.is_a?(Array)
|
|
19
|
+
|
|
20
|
+
sinks.each do |sink|
|
|
21
|
+
raise ConfigurationError, "sinks: must be an Array of callables taking (signal, data), found a #{sink.class}" unless sink.respond_to?(:call)
|
|
22
|
+
next unless sink.respond_to?(:available?) && !sink.available?
|
|
23
|
+
|
|
24
|
+
raise ConfigurationError, "sink #{sink.is_a?(Module) ? sink.name : sink.class} is not available: the library it reports to is not loaded"
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
@sinks = sinks.dup.freeze
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# Every sink gets the same frozen data, so one sink (or a subscriber) cannot change what the next one sees.
|
|
31
|
+
def record(signal, **data)
|
|
32
|
+
return nil if @sinks.empty?
|
|
33
|
+
|
|
34
|
+
data = data.to_h { |key, value| [key, value.is_a?(String) ? value.dup.freeze : value] }.freeze
|
|
35
|
+
@sinks.each { |sink| sink.call(signal, data) }
|
|
36
|
+
nil
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Reports every signal as an ActiveSupport::Notifications event named "<signal>.graphql_armory", with the
|
|
40
|
+
# signal's data as payload: `sinks: [GraphQL::Armory::Telemetry::Notifications]`.
|
|
41
|
+
module Notifications
|
|
42
|
+
def self.available?
|
|
43
|
+
defined?(::ActiveSupport::Notifications) ? true : false
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def self.call(signal, data)
|
|
47
|
+
::ActiveSupport::Notifications.instrument("#{signal}.graphql_armory", data.dup) # ActiveSupport may add keys to its payload
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Keeps what was recorded and fails when told, for tests.
|
|
52
|
+
class Substitute
|
|
53
|
+
attr_reader :recorded
|
|
54
|
+
|
|
55
|
+
def initialize
|
|
56
|
+
@recorded = []
|
|
57
|
+
@failure = nil
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Raises `error` from every `record` until `recover`, like a sink that cannot reach its service.
|
|
61
|
+
def fail_with(error)
|
|
62
|
+
@failure = error
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def recover
|
|
66
|
+
@failure = nil
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def record(signal, **data)
|
|
70
|
+
raise @failure if @failure
|
|
71
|
+
|
|
72
|
+
@recorded << [signal, data]
|
|
73
|
+
nil
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def recorded?(signal)
|
|
77
|
+
@recorded.any? { |recorded_signal, _| recorded_signal == signal }
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
end
|
data/lib/graphql/armory.rb
CHANGED
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: graphql-armory
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.1.0.
|
|
4
|
+
version: 0.1.0.pre6
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Israel
|
|
@@ -45,6 +45,7 @@ files:
|
|
|
45
45
|
- docs/encrypted-ids.md
|
|
46
46
|
- docs/persisted-queries.md
|
|
47
47
|
- docs/rate-limiting.md
|
|
48
|
+
- docs/telemetry.md
|
|
48
49
|
- lib/graphql-armory.rb
|
|
49
50
|
- lib/graphql/armory.rb
|
|
50
51
|
- lib/graphql/armory/authorization.rb
|
|
@@ -75,7 +76,6 @@ files:
|
|
|
75
76
|
- lib/graphql/armory/authorization/rspec.rb
|
|
76
77
|
- lib/graphql/armory/authorization/rule.rb
|
|
77
78
|
- lib/graphql/armory/authorization/scope.rb
|
|
78
|
-
- lib/graphql/armory/authorization/telemetry.rb
|
|
79
79
|
- lib/graphql/armory/encoder.rb
|
|
80
80
|
- lib/graphql/armory/encoder/default.rb
|
|
81
81
|
- lib/graphql/armory/encoder/legacy.rb
|
|
@@ -89,12 +89,15 @@ files:
|
|
|
89
89
|
- lib/graphql/armory/persisted_queries/manifest.rb
|
|
90
90
|
- lib/graphql/armory/persisted_queries/store.rb
|
|
91
91
|
- lib/graphql/armory/rate_limits.rb
|
|
92
|
+
- lib/graphql/armory/rate_limits/clock.rb
|
|
92
93
|
- lib/graphql/armory/rate_limits/concurrency.rb
|
|
93
94
|
- lib/graphql/armory/rate_limits/controls.rb
|
|
94
95
|
- lib/graphql/armory/rate_limits/memory_store.rb
|
|
95
96
|
- lib/graphql/armory/rate_limits/points.rb
|
|
96
97
|
- lib/graphql/armory/rate_limits/redis_store.rb
|
|
97
98
|
- lib/graphql/armory/rate_limits/store.rb
|
|
99
|
+
- lib/graphql/armory/rate_limits/time.rb
|
|
100
|
+
- lib/graphql/armory/telemetry.rb
|
|
98
101
|
- lib/graphql/armory/version.rb
|
|
99
102
|
- lib/tasks/graphql_armory.rake
|
|
100
103
|
homepage: https://github.com/israelb/graphql-armory
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
module GraphQL
|
|
4
|
-
module Armory
|
|
5
|
-
module Authorization
|
|
6
|
-
# Records what happened (allowed, denied, bypassed, scoped) and hands it to its sinks.
|
|
7
|
-
# A sink is anything that responds to `call(signal, data)`. Never put record attributes in `data`.
|
|
8
|
-
class Telemetry
|
|
9
|
-
def self.build(sinks: [])
|
|
10
|
-
new(sinks: sinks)
|
|
11
|
-
end
|
|
12
|
-
|
|
13
|
-
def initialize(sinks: [])
|
|
14
|
-
@sinks = sinks
|
|
15
|
-
end
|
|
16
|
-
|
|
17
|
-
def record(signal, **data)
|
|
18
|
-
@sinks.each { |sink| sink.call(signal, data) }
|
|
19
|
-
nil
|
|
20
|
-
end
|
|
21
|
-
|
|
22
|
-
# Keeps what was recorded, for tests.
|
|
23
|
-
class Substitute
|
|
24
|
-
attr_reader :recorded
|
|
25
|
-
|
|
26
|
-
def initialize
|
|
27
|
-
@recorded = []
|
|
28
|
-
end
|
|
29
|
-
|
|
30
|
-
def record(signal, **data)
|
|
31
|
-
@recorded << [signal, data]
|
|
32
|
-
nil
|
|
33
|
-
end
|
|
34
|
-
|
|
35
|
-
def recorded?(signal)
|
|
36
|
-
@recorded.any? { |recorded_signal, _| recorded_signal == signal }
|
|
37
|
-
end
|
|
38
|
-
end
|
|
39
|
-
end
|
|
40
|
-
end
|
|
41
|
-
end
|
|
42
|
-
end
|