graphql-armory 0.1.0.pre5 → 0.1.0.pre7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +15 -0
- data/README.md +7 -5
- data/docs/authorization.md +9 -1
- data/docs/encrypted-ids.md +16 -1
- data/docs/keyset-connections.md +95 -0
- data/docs/persisted-queries.md +35 -1
- data/docs/rate-limiting.md +76 -5
- data/docs/telemetry.md +227 -0
- data/lib/graphql/armory/authorization/configuration.rb +1 -0
- data/lib/graphql/armory/authorization/integration/object.rb +2 -0
- data/lib/graphql/armory/authorization.rb +5 -1
- data/lib/graphql/armory/ids.rb +21 -10
- data/lib/graphql/armory/keyset/controls.rb +36 -0
- data/lib/graphql/armory/keyset.rb +279 -0
- 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 +2 -0
- metadata +8 -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: 29e27413e39d1f24ffcc5d1ebf7316170b0ebb935f7d07eb0fd17779358cdbd1
|
|
4
|
+
data.tar.gz: 4db014feb0364b2f67773668f99b961a708a30a142141d96979db7da3fed8321
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 3c09fc9ec92e31c68fa01e82fafff46affc1cb2dba224bf0c513d4fb0786904a5bca96ace241a0099cff7b724a80e82738a0cb1361724f3f8c8edb6e2f16165d
|
|
7
|
+
data.tar.gz: 691347bd3ad318eb25bbab16634bf05f03e3587bfc90b8c18e93f75913582aa03ec52435c70c315611f8dc6ea3375a829479b2d8bd84f73d8ac326b7466bffa0
|
data/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 0.1.0.pre7 (2026-10-30)
|
|
6
|
+
|
|
7
|
+
Keyset connections (roadmap module 5). Docs: `docs/keyset-connections.md`.
|
|
8
|
+
|
|
9
|
+
- Keyset connections: `GraphQL::Armory::Keyset.build(relation)`, returned from a resolver, pages an ActiveRecord relation by its ordering columns instead of OFFSET, so rows inserted or deleted between pages neither skip nor repeat items. The primary key breaks ties. Orderings it cannot page raise `Keyset::ConfigurationError`. A cursor holds the ordering values, so the default Base64 encoder is refused unless `plain_cursors: true`. Types with authorization scope the relation inside the connection. Docs: `docs/keyset-connections.md`.
|
|
10
|
+
- Docs: new section "Clients that change identity" in `docs/rate-limiting.md`. A limit per key does not stop a client that gets a new IP or a new account for every request; the page now says so, shows how to share one bucket among new accounts or put a ceiling on everyone, and lists what belongs before GraphQL (signup limits, verification, network blocking). No code change.
|
|
11
|
+
- Docs: how to count probes against a strict persisted-queries endpoint. Strict mode refuses before validating, so a detector that counts validation errors goes blind; `:operation_refused` with `reason: :raw_query` is the strike to count instead. New section in `docs/persisted-queries.md` and a row in the "What to watch for" table of `docs/telemetry.md`. No code change.
|
|
12
|
+
|
|
13
|
+
## 0.1.0.pre6 (2026-10-30)
|
|
14
|
+
|
|
15
|
+
Telemetry for every module, and the processing-time layer of rate limiting. Docs: `docs/telemetry.md`, `docs/rate-limiting.md`.
|
|
16
|
+
|
|
17
|
+
- 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.
|
|
18
|
+
- 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.
|
|
19
|
+
|
|
5
20
|
## 0.1.0.pre5 (2026-10-29)
|
|
6
21
|
|
|
7
22
|
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.pre7`). 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.pre7" # a prerelease: `gem install graphql-armory --pre`
|
|
15
15
|
gem "pundit" # or "cancancan", for the authorization module
|
|
16
16
|
```
|
|
17
17
|
|
|
@@ -26,8 +26,8 @@ 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.
|
|
30
|
-
| 5 | Stable (keyset) connections |
|
|
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
|
+
| 5 | Stable (keyset) connections | ✅ | [docs/keyset-connections.md](docs/keyset-connections.md) | Released in 0.1.0.pre7 (prerelease). `Keyset.build(relation)` per resolver, ActiveRecord only, plain non-null columns of the relation's own table. Base64 cursors refused unless `plain_cursors: true`. No total count. |
|
|
31
31
|
| 6 | Subscriptions over Pusher / Ably | ⬜ | | Research not started. |
|
|
32
32
|
| 7 | Response caching | ⬜ | | Research not started. |
|
|
33
33
|
| 8 | API versioning (changesets) | ⬜ | | 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.pre7 && git push origin v0.1.0.pre7
|
|
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.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# Keyset connections
|
|
2
|
+
|
|
3
|
+
Pagination that stays correct while rows come and go.
|
|
4
|
+
|
|
5
|
+
## The problem
|
|
6
|
+
|
|
7
|
+
graphql-ruby's connection for ActiveRecord pages with `OFFSET`. If a row is inserted or deleted between two pages, every later row moves by one: the client sees a row twice, or never sees it. `OFFSET` also gets slower the deeper the page, because the database still walks the rows it skips.
|
|
8
|
+
|
|
9
|
+
## The solution
|
|
10
|
+
|
|
11
|
+
`GraphQL::Armory::Keyset` pages by the **values of the ordering columns**. The cursor says "after the row with these values", and the next page is a `WHERE` on them. A row inserted earlier in the list, or the deletion of the cursor's own row, changes nothing.
|
|
12
|
+
|
|
13
|
+
Those values are in the cursor, which creates a risk `OFFSET` cursors do not have. With graphql-ruby's default Base64 cursors, a client could read the value of a column you order by, even one that is not in your schema, and could forge a cursor to search it (`salary > X`, again and again, watching which rows appear). So the default encoder is refused unless you say otherwise.
|
|
14
|
+
|
|
15
|
+
## How to use it
|
|
16
|
+
|
|
17
|
+
Encrypt your cursors, and return a keyset connection from the resolver of a connection field:
|
|
18
|
+
|
|
19
|
+
```ruby
|
|
20
|
+
class AppSchema < GraphQL::Schema
|
|
21
|
+
cursor_encoder AppEncoder # a GraphQL::Armory::Encoder subclass
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
class Types::Query < Types::BaseObject
|
|
25
|
+
field :invoices, Types::Invoice.connection_type, null: false
|
|
26
|
+
|
|
27
|
+
def invoices
|
|
28
|
+
GraphQL::Armory::Keyset.build(Invoice.order(created_at: :desc))
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
graphql-ruby fills in `first`, `after`, `last`, `before` and the page sizes, as for any connection. The rest of your connections keep their `OFFSET`: this is chosen per resolver, and not registered for every relation.
|
|
34
|
+
|
|
35
|
+
If the ordering values are not secret (a public list ordered by id), you can keep readable cursors:
|
|
36
|
+
|
|
37
|
+
```ruby
|
|
38
|
+
GraphQL::Armory::Keyset.build(Article.order(:id), plain_cursors: true)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### What it can order by
|
|
42
|
+
|
|
43
|
+
The relation must be ordered by plain, non-null columns of its own table. The primary key is added as the last column, to break ties, so a relation with no order pages by primary key. `build` raises `Keyset::ConfigurationError` for:
|
|
44
|
+
|
|
45
|
+
- a raw SQL or string order (`order("rank ASC")`, `Arel.sql`), an expression, or `nulls_first`;
|
|
46
|
+
- a column of another table;
|
|
47
|
+
- a nullable column: SQL comparisons skip `NULL`, so those rows would be lost;
|
|
48
|
+
- a `float` column: equality on floats is not reliable. Allowed types are integer, string, text, decimal, datetime, date, boolean and uuid;
|
|
49
|
+
- a serialized or encrypted column: the database does not order those by the value a cursor would hold;
|
|
50
|
+
- a relation with `limit`, `offset`, `group` or `select`;
|
|
51
|
+
- a `joins` or `left_joins` without `distinct`, because a join can repeat a row. Add `.distinct`, or filter with a subquery.
|
|
52
|
+
|
|
53
|
+
Add an index on the ordering columns, in that order, ending with the primary key. Without one the database still has to sort.
|
|
54
|
+
|
|
55
|
+
### With authorization
|
|
56
|
+
|
|
57
|
+
A type that includes `GraphQL::Armory::Authorization::Base` scopes the relation inside the connection, as it does for a plain relation, so the page, `hasNextPage` and `hasPreviousPage` only see rows the user may see. A cursor adds a condition to that scope, so someone else's cursor cannot reach outside it. A scope that answers an Array (CanCanCan's `scope: :in_memory`) has nothing to page and raises `ConfigurationError`.
|
|
58
|
+
|
|
59
|
+
If your own type defines `scope_items`, it receives the `Keyset` object and not a relation. Call `items.rescoped { |relation| ... }` there.
|
|
60
|
+
|
|
61
|
+
### Testing
|
|
62
|
+
|
|
63
|
+
`Keyset::Controls::Schema.example(base:, cursor_encoder:, max_page_size:)` is a schema with one connection field, `items`, and `Keyset::Controls::Root.example(connection)` is its root value. `IDs::Controls::Encoder.example` is an encoder with a fixed test key. `Keyset.new`, with nothing wired, has no rows, no pages and no cursors.
|
|
64
|
+
|
|
65
|
+
## Reference
|
|
66
|
+
|
|
67
|
+
`GraphQL::Armory::Keyset.build(relation, plain_cursors: false)`
|
|
68
|
+
|
|
69
|
+
- `relation`: an ActiveRecord relation, checked as above.
|
|
70
|
+
- `plain_cursors:` is `true` or `false`. `true` allows the schema's default Base64 encoder.
|
|
71
|
+
|
|
72
|
+
Errors:
|
|
73
|
+
|
|
74
|
+
| When | What |
|
|
75
|
+
|---|---|
|
|
76
|
+
| Boot or resolver, a relation it cannot page | `Keyset::ConfigurationError` |
|
|
77
|
+
| First page, the schema has the default encoder and no `plain_cursors: true` | `Keyset::ConfigurationError` |
|
|
78
|
+
| A cursor that is tampered, malformed, or made for another ordering | `Invalid ID or cursor`, the same for all |
|
|
79
|
+
| `first` and `last` together | `first and last cannot be used together` |
|
|
80
|
+
|
|
81
|
+
## Guarantees and limits
|
|
82
|
+
|
|
83
|
+
- Every row present for the whole walk is seen exactly once, whatever is inserted or deleted meanwhile.
|
|
84
|
+
- A row whose ordering value **changes** between pages can be skipped or seen twice: it really moved. Order by columns that do not change (a creation time, an id) when this matters.
|
|
85
|
+
- A row inserted behind the cursor is not seen on the way forward, as in any pagination.
|
|
86
|
+
- The encoder check runs on the first page, not at boot, because the connection reads the encoder from the schema of the query.
|
|
87
|
+
- The check only knows the default Base64 encoder. A custom encoder that does not encrypt passes unnoticed: a keyset cursor is only as private as your `cursor_encoder`.
|
|
88
|
+
- With `plain_cursors: true` a client can read the ordering values and forge a cursor. It stays inside the scope and its values are bound, never interpolated, but it can probe those columns.
|
|
89
|
+
- A forged value on a plain cursor must have the form the column's own cursors have (an Integer, a plain decimal, an ISO 8601 date or time) or it is an invalid cursor. A forged value of the right form is honoured: it pages from there.
|
|
90
|
+
- Encryption keeps length, so the length of an encrypted cursor reveals roughly the length of a string ordering value.
|
|
91
|
+
- A value JSON cannot hold, such as Postgres `infinity` in an ordering column, raises when the cursor is built. Avoid it in columns you order by.
|
|
92
|
+
- A decimal of more than 65 digits on either side of the point, possible only on an unconstrained Postgres `numeric`, gets `Invalid ID or cursor` even on its own cursor. Give the column a precision.
|
|
93
|
+
- On `Execution::Next`, a node type with `reauthorize_scoped_objects(false)` skips `authorized?` even when its scope did not narrow the list. A plain relation does the same: it comes from graphql-ruby. Do not combine that setting with a scope that does not filter.
|
|
94
|
+
- There is no total count. `hasNextPage` costs no extra query going forward without `before`, nor does `hasPreviousPage` going backward without `after`; in the other cases each costs one query, only when the client asks for it.
|
|
95
|
+
- ActiveRecord only. The attributes of the ordering columns must be readable on each row, which is why `select` is refused.
|
data/docs/persisted-queries.md
CHANGED
|
@@ -136,6 +136,39 @@ 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
|
+
|
|
156
|
+
### Counting probes in strict mode
|
|
157
|
+
|
|
158
|
+
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
|
+
|
|
160
|
+
```ruby
|
|
161
|
+
count_probes = lambda do |signal, data|
|
|
162
|
+
next unless signal == :operation_refused && data[:reason] == :raw_query
|
|
163
|
+
|
|
164
|
+
AbuseDetection.strike(Current.client_key) # your detector, with the client from your own request context
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
use GraphQL::Armory::PersistedQueries, store: PERSISTED, strict: true, sinks: [count_probes]
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
A signal holds only the reason, so the sink reads who sent the request from your own request context, as in [Telemetry](telemetry.md). 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
|
+
|
|
139
172
|
### Testing with persisted queries
|
|
140
173
|
|
|
141
174
|
`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 +182,11 @@ Deploy the server with the new manifest before, or with, the clients that use it
|
|
|
149
182
|
- `fetch(id)` answers the operation (`id`, `name`, `body`, `document`, all frozen) or nil. `size` counts them.
|
|
150
183
|
- 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
184
|
|
|
152
|
-
`use GraphQL::Armory::PersistedQueries, store:, strict: false`
|
|
185
|
+
`use GraphQL::Armory::PersistedQueries, store:, strict: false, sinks: []`
|
|
153
186
|
|
|
154
187
|
- `store:` answers `fetch(id)` with an object that has `body` and `document`, or nil. A Manifest, or your own store.
|
|
155
188
|
- `strict:` is `true` or `false`.
|
|
189
|
+
- `sinks:` an Array of callables taking `(signal, data)`; see [Watching the rollout](#watching-the-rollout).
|
|
156
190
|
- Works with your own `query_class`, whether it is set before `use`, after it, or in a child schema: the plugin subclasses it.
|
|
157
191
|
- `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
192
|
- 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,43 @@ 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
|
-
|
|
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).
|
|
336
|
+
|
|
337
|
+
### Clients that change identity
|
|
338
|
+
|
|
339
|
+
Every key has its own bucket. A client that gets a new key for each request (a new IP from a proxy, or a new disposable account) starts every time with a full bucket, so a limit per key does not stop it. The limiter does not know who owns a key: opening accounts and choosing IPs happens before it, and so does stopping abuse there.
|
|
340
|
+
|
|
341
|
+
What you can do with the gem:
|
|
342
|
+
|
|
343
|
+
- **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
|
+
|
|
345
|
+
```ruby
|
|
346
|
+
context[:rate_limit_key] = user.created_at > 1.day.ago ? "new-accounts" : "user:#{user.id}"
|
|
347
|
+
|
|
348
|
+
use GraphQL::Armory::RateLimits::Points, store: store, window: 60,
|
|
349
|
+
limit: ->(key, _query) { key == "new-accounts" ? 500 : 1_000 }
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
The cost is that honest new users share that budget, and a burst from an attacker can use it up for them. Start in soft mode and look at `context[:rate_limit_points]` before you refuse anyone. The example has not been run against a real app.
|
|
353
|
+
- **Put a ceiling on everyone.** A key that is the same for every request (`"all"`) with `Concurrency` or `Time` protects your servers from a flood, whoever sends it. It does not tell clients apart: an attacker can leave honest clients without budget.
|
|
283
354
|
|
|
284
|
-
|
|
355
|
+
What this limiter does not do, and you handle before the request reaches GraphQL: limit account creation per IP, subnet or device, verify an email or a phone number before an account can query, block by network reputation, and detect and ban abusive clients. The limiter is the last layer, not a replacement for those.
|
|
285
356
|
|
|
286
357
|
## References
|
|
287
358
|
|