graphql-armory 0.1.0.pre2 → 0.1.0.pre4
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 +17 -0
- data/MIGRATING.md +1 -1
- data/README.md +21 -274
- data/docs/authorization.md +264 -0
- data/docs/encrypted-ids.md +136 -0
- data/docs/persisted-queries.md +184 -0
- data/lib/graphql/armory/authorization/integration.rb +3 -2
- data/lib/graphql/armory/encoder/default.rb +59 -0
- data/lib/graphql/armory/encoder/legacy.rb +34 -0
- data/lib/graphql/armory/encoder/versioned.rb +67 -0
- data/lib/graphql/armory/encoder.rb +137 -0
- data/lib/graphql/armory/ids.rb +76 -0
- data/lib/graphql/armory/persisted_queries/manifest.rb +109 -0
- data/lib/graphql/armory/persisted_queries.rb +144 -0
- data/lib/graphql/armory/version.rb +1 -1
- data/lib/graphql/armory.rb +3 -0
- metadata +11 -1
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
# Authorization
|
|
2
|
+
|
|
3
|
+
Pundit or CanCanCan policies for graphql-ruby, declared once on your types and enforced on every path.
|
|
4
|
+
|
|
5
|
+
## The problem
|
|
6
|
+
|
|
7
|
+
graphql-ruby leaves authorization to you. Each type needs an `authorized?` method, each list a `scope_items`, each `loads:` its own check, and nothing tells you which ones you forgot. One forgotten type is enough for user A to read user B's invoice by its ID (an IDOR), through a root field, a nested association, a list, or an argument that loads a record. And an error that says "not allowed" instead of "not found" tells an attacker the record exists.
|
|
8
|
+
|
|
9
|
+
## The solution
|
|
10
|
+
|
|
11
|
+
graphql-armory plugs your existing policies into graphql-ruby's public hooks:
|
|
12
|
+
|
|
13
|
+
- **Nothing is open by default.** A type or field no rule covers answers `null` (or an error), never data.
|
|
14
|
+
- **Lists only contain what the user may see**, including connections: the scope runs before pagination and counting.
|
|
15
|
+
- **Lookups by ID cannot leak** (IDOR). A record you may not read and a record that does not exist look identical.
|
|
16
|
+
- **An audit tells you what you forgot**, from a rake task or an RSpec matcher, so CI fails instead of production leaking.
|
|
17
|
+
|
|
18
|
+
## How to use it
|
|
19
|
+
|
|
20
|
+
Your policies stay plain Pundit. The only new thing is where the rules are declared:
|
|
21
|
+
|
|
22
|
+
```ruby
|
|
23
|
+
class BaseField < GraphQL::Schema::Field
|
|
24
|
+
include GraphQL::Armory::Authorization::Base
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
class BaseObject < GraphQL::Schema::Object
|
|
28
|
+
include GraphQL::Armory::Authorization::Base
|
|
29
|
+
field_class BaseField
|
|
30
|
+
default_action :read # every type is checked with InvoicePolicy#read?, AccountPolicy#read?...
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
class InvoiceType < BaseObject
|
|
34
|
+
field :number, String, null: false
|
|
35
|
+
field :internal_notes, String, authorize: :manage # this field asks InvoicePolicy#manage?
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
class QueryType < BaseObject
|
|
39
|
+
authorize :none, reason: "root type; each field declares its own rule"
|
|
40
|
+
field :invoices, [InvoiceType], null: false, authorize: :none, reason: "narrowed by InvoicePolicy::Scope"
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
class AppSchema < GraphQL::Schema
|
|
44
|
+
query QueryType
|
|
45
|
+
use GraphQL::Armory::Authorization, adapter: :pundit
|
|
46
|
+
end
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The actor is `context[:current_user]`. A complete, tested version lives in [`examples/invoices.rb`](../examples/invoices.rb).
|
|
50
|
+
|
|
51
|
+
## Rules
|
|
52
|
+
|
|
53
|
+
| Declaration | Meaning |
|
|
54
|
+
|---|---|
|
|
55
|
+
| `default_action :read` | Default rule for every type below this base class. |
|
|
56
|
+
| `authorize :manage` | This type is checked with `manage?` instead. |
|
|
57
|
+
| `authorize :read, model: Invoice` | The model when it is not named like the type. |
|
|
58
|
+
| `field ..., authorize: :manage` | The field asks another question of the same policy. |
|
|
59
|
+
| `authorize :none, reason: "..."` | Explicit bypass. A reason is required and appears in the audit. |
|
|
60
|
+
|
|
61
|
+
A bypass does not propagate: a field of a bypassed type still needs its own rule, or it is denied.
|
|
62
|
+
|
|
63
|
+
## What happens on denial
|
|
64
|
+
|
|
65
|
+
```ruby
|
|
66
|
+
use GraphQL::Armory::Authorization, adapter: :pundit, on_unauthorized: :null # default
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
| Mode | Client sees | Use |
|
|
70
|
+
|---|---|---|
|
|
71
|
+
| `:null` | `null`, no error | Default. Reveals nothing. |
|
|
72
|
+
| `:error` | `"Not found"`, code `NOT_FOUND`, identical on every path | When clients need to tell. |
|
|
73
|
+
| `:raise` | `NotAuthorizedError` naming only the type | When your app rescues it. |
|
|
74
|
+
|
|
75
|
+
Denied non-null fields raise the generic "Not found" error, because GraphQL cannot return `null` there (on Execution::Next a denied object in a non-null position answers graphql-ruby's own "Cannot return null for non-nullable field", and `:raise` messages are prefixed with the field path). `find_by:` lookups always answer `null` in every mode: a missing ID cannot raise, and a foreign ID must look the same.
|
|
76
|
+
|
|
77
|
+
## Lists, connections and lookups
|
|
78
|
+
|
|
79
|
+
Lists of a type are narrowed through `InvoicePolicy::Scope` (relations) or by calling the policy per item (arrays). Return a relation when you can: SQL filters before Ruby sees anything.
|
|
80
|
+
|
|
81
|
+
```ruby
|
|
82
|
+
field :invoice, InvoiceType, authorize: :none, reason: "looked up through the scope", find_by: :id do
|
|
83
|
+
argument :id, ID
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
field :invoice_via_ref, InvoiceType, authorize: :none, reason: "loaded through the scope" do
|
|
87
|
+
argument :invoice_id, ID, loads: InvoiceType
|
|
88
|
+
end
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`find_by:` and `loads:` (also inside input objects whose base class includes `Base`) look the record up **inside the user's scope**, so another tenant's ID answers exactly like a missing one. Opt out of the scope for a field's `loads:` only on purpose, with `load_through_scope: false`; the audit lists it. On `Execution::Next` the opt-out also reaches `loads:` nested in that field's input objects (the interpreter keeps those scoped), and the audit lists them too (`Query.field(filter.invoice_id)`). An input object that overrides `object_from_id` or defines `load_<argument>` itself is honoured on the interpreter and not seen by the audit.
|
|
92
|
+
|
|
93
|
+
**Global IDs.** When your schema defines `object_from_id` (Relay global IDs), `loads:` decodes the id with it, refuses a record of another model, and looks the record up again inside the scope (one extra query per load). Without `object_from_id`, the id is the primary key. `object_from_id` must return the record itself, not a lazy value: a lazy value is denied. A decoder that raises `ActiveRecord::RecordNotFound` (like `GlobalID.find`), `ArgumentError` (a malformed id) or `GraphQL::Armory::Encoder::InvalidError` (see [encrypted IDs](encrypted-ids.md)) is answered like a missing record; other errors propagate. `loads:` of an interface or union (for example `Types::Node`) raises `ConfigurationError`: load a concrete type. Composite primary keys are not supported.
|
|
94
|
+
|
|
95
|
+
## The audit
|
|
96
|
+
|
|
97
|
+
```ruby
|
|
98
|
+
GraphQL::Armory::Authorization::Audit.(AppSchema) # => report with problems
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
```ruby
|
|
102
|
+
# spec/schema_spec.rb
|
|
103
|
+
require "graphql/armory/authorization/rspec"
|
|
104
|
+
expect(AppSchema).to be_fully_authorized
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
```ruby
|
|
108
|
+
# Rakefile (or a Rails task file): exits 1 when anything is uncovered
|
|
109
|
+
load "tasks/graphql_armory.rake"
|
|
110
|
+
# bundle exec rake "graphql_armory:audit[AppSchema]"
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
It reports types nobody protects (a base class that never included `Base`), types and fields with no rule, policies missing the method or `Scope`, `loads:` that skip the scope, and lists every declared bypass with its reason.
|
|
114
|
+
|
|
115
|
+
## CanCanCan
|
|
116
|
+
|
|
117
|
+
Same schema, different adapter. Your types and fields do not change:
|
|
118
|
+
|
|
119
|
+
```ruby
|
|
120
|
+
use GraphQL::Armory::Authorization, adapter: :cancan
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
The actor is `context[:current_ability]` (it wins over `current_user`), or `Ability.new(context[:current_user])` (pass `Adapters::CanCan.new(ability_class: MyAbility)` for another class). It is built once per query.
|
|
124
|
+
|
|
125
|
+
| Question | CanCanCan call |
|
|
126
|
+
|---|---|
|
|
127
|
+
| Can this object be seen? | `ability.can?(:read, object)` |
|
|
128
|
+
| Can this field be seen? | `ability.can?(:manage, object, :internal_notes)` for a field that declares `authorize: :manage`: the attribute is passed, because `can :read, User, [:username]` makes `can?(:read, user)` true for the whole object |
|
|
129
|
+
| Which items of a list? | `Model.accessible_by(ability, :read)`, still a paginable relation; Arrays are filtered with `can?` |
|
|
130
|
+
|
|
131
|
+
**Block-only rules.** `can(:read, Invoice) { |i| ... }` cannot be turned into SQL, so `accessible_by` fails. The adapter raises `MissingScopeError` instead of guessing. To accept the cost, declare it on the type: `authorize :read, scope: :in_memory`. Lists are then filtered with `can?` one by one and efficient pagination is lost; `find_by:` and `loads:` find the record and then ask `can?`. Fields covered by the type's rule are not asked about their attribute: give the ones an attribute rule must hide their own `authorize: :action`. Options the adapter does not understand (`policy:`, another `scope:`) raise `ConfigurationError`.
|
|
132
|
+
|
|
133
|
+
**The audit covers less.** It still reports missing rules, bypasses and unscoped `loads:`, but not whether the `Ability` grants the action: abilities depend on the user.
|
|
134
|
+
|
|
135
|
+
**Guests.** `Ability.new(nil)` is your ability class's decision. Make it deny everything if there is no user.
|
|
136
|
+
|
|
137
|
+
## Visibility
|
|
138
|
+
|
|
139
|
+
Hide a type or a field from users who may not use it, in introspection and in "did you mean" suggestions:
|
|
140
|
+
|
|
141
|
+
```ruby
|
|
142
|
+
class InvoiceExportType < BaseObject
|
|
143
|
+
authorize :read, model: Invoice, visible_when: :export # InvoicePolicy#export? / can?(:export, Invoice)
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
field :internal_notes, String, authorize: :manage, visible_when: :export
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`visible_when:` is an action like any other, but it is asked **of the model's class, with no record**: `InvoicePolicy.new(user, Invoice).export?` with Pundit, `can?(:export, Invoice)` with CanCanCan. Write a method that decides from the user (`user.admin?`), not from the record. Nothing is hidden unless you declare it, and the audit reports a `visible_when:` action the policy does not define.
|
|
150
|
+
|
|
151
|
+
A hidden member also hides what leads only to it: a root field that returns a hidden type disappears with it.
|
|
152
|
+
|
|
153
|
+
**Schema dumps.** graphql 2.6 builds an ordinary context for `to_definition`, which cannot be told apart from an anonymous request, and an anonymous request must never see hidden members. Ask for the full schema explicitly:
|
|
154
|
+
|
|
155
|
+
```ruby
|
|
156
|
+
AppSchema.to_definition(context: { armory_full_schema: true })
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Things to know:
|
|
160
|
+
|
|
161
|
+
- **Hiding is not authorization.** A hidden field is absent from the schema, so a query for it fails like a field that never existed. What the user may *read* is still decided by `authorize`.
|
|
162
|
+
- **The policy receives the class.** A policy that reads the record (`record.account_id`) raises `NoMethodError` for a `visible_when:` action; write that action from the user. The error propagates out of `execute`, so make sure your error handler does not echo it.
|
|
163
|
+
- **CanCanCan conditions are not applied to a class.** `can :export, Invoice, account_id: 1` makes the member visible to anyone who holds the rule. For a field, the attribute is passed: `can?(:export, Invoice, :internal_notes)`.
|
|
164
|
+
- **A subclass that redeclares `authorize` replaces the rule**, `visible_when:` included: repeat it.
|
|
165
|
+
- **`visible_when:` on a field needs a type that includes `Base`** (not an interface or a plain type); otherwise it raises `ConfigurationError` when a query selects it.
|
|
166
|
+
- **Static `Schema::Visibility` profiles are not supported** and raise `ConfigurationError`; plain `use Schema::Visibility`, `dynamic: true` and the default warden work.
|
|
167
|
+
|
|
168
|
+
Visibility is computed per query (and memoized inside it). Role-based profile caching across requests is graphql-ruby's `Schema::Visibility` feature and is not wrapped here.
|
|
169
|
+
|
|
170
|
+
## Arguments
|
|
171
|
+
|
|
172
|
+
An argument with no rule is **covered by its field**: the field already decides whether the user may call it. Declare a rule on the arguments that must be stricter, and they are checked when the client sends them:
|
|
173
|
+
|
|
174
|
+
```ruby
|
|
175
|
+
class BaseArgument < GraphQL::Schema::Argument
|
|
176
|
+
include GraphQL::Armory::Authorization::Base
|
|
177
|
+
end
|
|
178
|
+
# in your base field: argument_class BaseArgument
|
|
179
|
+
|
|
180
|
+
field :invoices, [InvoiceType], authorize: :none, reason: "narrowed by the scope" do
|
|
181
|
+
argument :include_internal, Boolean, required: false, authorize: :manage, model: Invoice
|
|
182
|
+
argument :tag, String, required: false, visible_when: :export, model: Invoice
|
|
183
|
+
argument :status, String, required: false, authorize: :none, reason: "public filter"
|
|
184
|
+
end
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
- **`authorize: :manage`** asks the policy about the parent object when it is an instance of the model, otherwise about the model's class (a root field has no record, so write the action from the user). The model is the one the field's type wraps, or `model:` when it wraps none, as on a root field. A denial denies the whole field, with the usual null or error.
|
|
188
|
+
- **Defaults.** graphql-ruby does not check an argument the client left at its default, and the two engines disagree about it (the interpreter skips the check, `Execution::Next` applies the default), so a restricted argument with a `default_value:` is refused with an `ArgumentError`. Sending `false` explicitly counts as using the argument.
|
|
189
|
+
- **Every argument class needs `Base`.** `argument_class` is not inherited: set it on your base field, and also on resolvers, input objects (for restricted arguments nested in a filter) and directives that need it.
|
|
190
|
+
- **`visible_when:`** hides the argument like it hides a field: it is absent from introspection and from suggestions, and a query that uses it fails like an argument that never existed.
|
|
191
|
+
- **`authorize: :none, reason:`** only declares and documents: the audit lists it with its reason.
|
|
192
|
+
- `authorize: true` is refused on an argument, and an argument with no model to ask about raises `ConfigurationError`.
|
|
193
|
+
|
|
194
|
+
## Mutations and resolvers
|
|
195
|
+
|
|
196
|
+
Include `Base` in your base mutation (or resolver) and declare what each one needs. A mutation is an action, not a read, so `default_action` does not apply and **a mutation with no `authorize` is denied**.
|
|
197
|
+
|
|
198
|
+
```ruby
|
|
199
|
+
class Mutations::BaseMutation < GraphQL::Schema::RelayClassicMutation
|
|
200
|
+
include GraphQL::Armory::Authorization::Base
|
|
201
|
+
argument_class Types::BaseArgument
|
|
202
|
+
field_class Types::BaseField
|
|
203
|
+
object_class Types::BaseObject
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
class Mutations::ApproveInvoice < Mutations::BaseMutation
|
|
207
|
+
authorize :approve, model: Invoice # InvoicePolicy#approve?(invoice) / can?(:approve, invoice)
|
|
208
|
+
argument :invoice_id, ID, loads: Types::Invoice
|
|
209
|
+
field :invoice, Types::Invoice, null: true
|
|
210
|
+
end
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
- **The record is the loaded one.** The rule runs after `loads:`, once per loaded record of the model (with none loaded, the model's class is asked). `loads:` goes through the user's scope, so a foreign id answers like a missing one.
|
|
214
|
+
- **Denial** follows the schema's `on_unauthorized` mode, like a field (`null`, `"Not found"`, or raise). With `on_denied: :errors` the mutation does not run and answers `{ errors: [{ message: "Not allowed", code: "FORBIDDEN" }] }` as data, so the payload needs an `errors` field.
|
|
215
|
+
- **Payload types** are ordinary objects: declare `authorize :none, reason: "...", covers_fields: true` so their fields are covered by the mutation instead of denied.
|
|
216
|
+
- **`authorize :none, reason:`** documents a mutation anyone may call; the audit lists it with its reason. A mutation with no rule appears as `:no_rule` (for example `Mutation.forgotten`), and a rule the policy does not define as `:adapter`.
|
|
217
|
+
- An unknown `on_denied:` raises `ArgumentError`; a mutation with a rule but no model raises `ConfigurationError`.
|
|
218
|
+
- **Class-level answers are weak.** With no loaded record of the model (no `loads:`, an empty `loads: [ID]`, or a `loads:` of another type) the rule is asked about the model's class: CanCan answers true for anyone holding the right, and a Pundit policy that reads `record` attributes raises. Load the record you are authorizing.
|
|
219
|
+
- **`ready?` runs before authorization** (and, on the interpreter, before a failing `loads:`). Keep it free of side effects.
|
|
220
|
+
- **`loads:` inside an input object** goes through the scope only when your base input object includes `Base` (`class Types::BaseInputObject < GraphQL::Schema::InputObject; include GraphQL::Armory::Authorization::Base; end`); otherwise the audit reports it as `:unscoped_load`.
|
|
221
|
+
- **Do not put `authorize:` on a mutation field or on payload fields**; the mutation's own rule is the one that counts. A subclass that redeclares `authorize :none` is open to everyone, on purpose.
|
|
222
|
+
|
|
223
|
+
## Interfaces and unions
|
|
224
|
+
|
|
225
|
+
They are never authorized themselves: graphql-ruby only runs `authorized?` on the concrete type, and every path ends there (root field, association, each list item, `loads:`, union and interface resolution). A foreign object in a list of a union or an interface comes back `null`, like in any other list. So `include Base` in an interface or a union is refused with a message pointing to the possible types; declare the rule on each concrete type.
|
|
226
|
+
|
|
227
|
+
What an interface adds is its fields, declared once and resolved on many types:
|
|
228
|
+
|
|
229
|
+
- A field with no rule is **covered** by the rule of the Base types that implement the interface (a plain implementer runs no check at all), unless one of them is a bypass (`authorize :none`). Then the field is **denied for every implementer**, because it cannot tell which type it runs on, and the audit reports it (`:field_without_rule`, for example `Document.number`). Declare it (`authorize: :none, reason:` or an action) to fix it.
|
|
230
|
+
- `visible_when:` is not supported on an interface field; put it on the concrete types' fields.
|
|
231
|
+
- `authorize: true` is not valid on an interface field: it is always denied, and the audit reports it. Use an action or `:none`.
|
|
232
|
+
- An interface whose field class does not include `Base`, such as graphql-ruby's built-in Relay `Node`, runs no field check, so its `id` stays readable on a bypassed implementer. The audit reports it (`:unprotected`, `Node.id`); give your own `Node` interface a Base field class if that matters.
|
|
233
|
+
- The audit reports an interface field once, on the interface that declares it, not again on each implementer.
|
|
234
|
+
|
|
235
|
+
## Telemetry
|
|
236
|
+
|
|
237
|
+
Pass `sinks: [->(signal, data) {}]`. Signals are `:allowed`, `:denied`, `:bypassed`; data holds only `type`, `action` and `reason`, never record attributes.
|
|
238
|
+
|
|
239
|
+
## Guarantees and limits
|
|
240
|
+
|
|
241
|
+
Covered by the black-box suite in `spec/security`, on both engines: user A cannot read user B's objects by root field, nested association or `loads:`; lists never contain foreign objects; uncovered types fail closed and show in the audit; a field hidden with `visible?` is absent from introspection and error suggestions (that is graphql-ruby's behaviour, pinned by a test).
|
|
242
|
+
|
|
243
|
+
Policies must return `true`/`false`/`nil`; anything else raises `AdapterError`. Do not use `dataloader.request` inside policies; use `dataloader.with(...).load`.
|
|
244
|
+
|
|
245
|
+
## Engines
|
|
246
|
+
|
|
247
|
+
Both execution engines are tested: the default interpreter and `Execution::Next`. In graphql 2.5.26 to 2.6.1, Next crashes on denied fields, so the gem refuses to run on Next there (`ConfigurationError`). Everything else works from graphql 2.4.
|
|
248
|
+
|
|
249
|
+
## Performance
|
|
250
|
+
|
|
251
|
+
`benchmark/authorization.rb`, 1000 invoices, graphql 2.6.2, Ruby 3.2, Docker on Windows:
|
|
252
|
+
|
|
253
|
+
| Engine | Query | plain | armory (array) | armory (relation) |
|
|
254
|
+
|---|---|---|---|---|
|
|
255
|
+
| interpreter | `number` | 117.6 i/s | 45.9 i/s | 44.2 i/s |
|
|
256
|
+
| interpreter | 3 fields | 58.8 i/s | 21.6 i/s | 21.0 i/s |
|
|
257
|
+
| next | `number` | 654.2 i/s | 71.8 i/s | 70.8 i/s |
|
|
258
|
+
| next | 3 fields | 417.5 i/s | 42.1 i/s | 39.5 i/s |
|
|
259
|
+
|
|
260
|
+
The absolute cost is about 13 to 15 ms per 1000 items on both engines; most of it is probably Pundit's policy lookup, which is not cached so code reloading cannot serve stale classes. Run it yourself: `docker compose run --rm test bundle exec ruby benchmark/authorization.rb` (add `GRAPHQL_ARMORY_ENGINE=next` for Next).
|
|
261
|
+
|
|
262
|
+
## Migrating
|
|
263
|
+
|
|
264
|
+
Coming from hand-written `authorized?` and `scope_items`? See [MIGRATING.md](../MIGRATING.md).
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# Encrypted IDs and cursors
|
|
2
|
+
|
|
3
|
+
IDs and pagination cursors that clients can neither read, guess, nor forge.
|
|
4
|
+
|
|
5
|
+
## The problem
|
|
6
|
+
|
|
7
|
+
graphql-ruby's IDs and cursors are base64, which is an encoding, not encryption. A Relay ID such as `SW52b2ljZS80Mg` is `Invoice/42` to anyone who decodes it, and a cursor such as `MTA` is the position `10`. From them a client can:
|
|
8
|
+
|
|
9
|
+
- **Guess other IDs.** `Invoice/43`, `Invoice/44`… or `User/1`, `Admin/1`. Authorization still decides what it may read, but every guess costs you a lookup and probes your API.
|
|
10
|
+
- **Learn about your business.** Sequential IDs tell how many invoices or users you have and how fast they grow.
|
|
11
|
+
- **Edit cursors** to jump anywhere in a list or count its rows.
|
|
12
|
+
|
|
13
|
+
## The solution
|
|
14
|
+
|
|
15
|
+
`GraphQL::Armory::Encoder` encrypts and authenticates them with AES-256-GCM:
|
|
16
|
+
|
|
17
|
+
- **Opaque.** The ID of `Invoice/42` looks like `x0Tn…Qw`; nothing in it can be read.
|
|
18
|
+
- **Tamper-proof.** Change one character, use another key or another tag, and it does not decode. Every failure gives the same error, `Invalid ID or cursor`, without saying why.
|
|
19
|
+
- **Stable IDs.** The same object always has the same ID, so client caches (Apollo, Relay) keep working. Its nonce is derived from the ID, so two different IDs do not share one (a collision needs around 2^48 IDs).
|
|
20
|
+
- **Unpredictable cursors.** The same position gives a different cursor in every response.
|
|
21
|
+
- **IDs and cursors are not interchangeable.** Each uses its own derived key.
|
|
22
|
+
- **One line for the whole schema.** `use GraphQL::Armory::IDs` defines `id_from_object` and `object_from_id`, looking records up inside the user's scope.
|
|
23
|
+
- **Keys can be rotated, and encryption added to an existing API**, without breaking the IDs and cursors clients already hold: a versioned chain reads old values and writes new ones.
|
|
24
|
+
|
|
25
|
+
## How to use it
|
|
26
|
+
|
|
27
|
+
Generate a key once and keep it out of the code: `ruby -rsecurerandom -e 'puts SecureRandom.hex(32)'`, and set it as `GRAPHQL_ARMORY_KEY` (in a Rails app you can skip this: a key is derived from `secret_key_base`, see [the default encoder](#the-default-encoder)).
|
|
28
|
+
|
|
29
|
+
```ruby
|
|
30
|
+
class AppSchema < GraphQL::Schema
|
|
31
|
+
use GraphQL::Armory::Authorization, adapter: :pundit # optional, but recommended
|
|
32
|
+
use GraphQL::Armory::IDs # encrypted global IDs
|
|
33
|
+
cursor_encoder GraphQL::Armory::Encoder.default # encrypted cursors
|
|
34
|
+
end
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`use GraphQL::Armory::IDs` defines `id_from_object` and `object_from_id` for you. An ID holds the type name and the record's id, encrypted. When the schema decodes one:
|
|
38
|
+
|
|
39
|
+
- A type that includes the authorization module's `Base` is looked up **inside the user's scope**, so another tenant's ID answers `null`, like a missing record (in `node(id:)`, `loads:` and anything else that calls `object_from_id`).
|
|
40
|
+
- A tampered ID, an ID made with another key, an unknown type, a type hidden from this user (`visible_when:`), or a type that is not an object type implementing `Node` (root types, payloads, introspection) answer `null` too, with no error.
|
|
41
|
+
- A type without `Base` is loaded only if you say how: `use GraphQL::Armory::IDs, find: ->(type, key, context) { ... }`. Otherwise its IDs answer `null`. `find:` only sees `Node` types; return `nil` for a missing record (`find_by`, not `find`): an error it raises reaches the client.
|
|
42
|
+
- A `Base` type named unlike its model (Rails' `Types::InvoiceType`) needs `authorize :read, model: Invoice`, or every lookup of it raises `ConfigurationError`.
|
|
43
|
+
|
|
44
|
+
Pass your own encoder with `use GraphQL::Armory::IDs, encoder: AppEncoder` (or a versioned chain, below).
|
|
45
|
+
|
|
46
|
+
### Your own encoder
|
|
47
|
+
|
|
48
|
+
```ruby
|
|
49
|
+
class AppEncoder < GraphQL::Armory::Encoder
|
|
50
|
+
key ENV.fetch("GRAPHQL_ARMORY_KEY")
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
class AppSchema < GraphQL::Schema
|
|
54
|
+
use GraphQL::Armory::IDs, encoder: AppEncoder
|
|
55
|
+
cursor_encoder AppEncoder # every built-in connection now uses encrypted cursors
|
|
56
|
+
end
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Without the plugin, call the encoder from your own `id_from_object` and `object_from_id` (`AppEncoder.encode("#{type.graphql_name}/#{object.id}")` and `AppEncoder.decode(id)`). With the [authorization module](authorization.md), an ID the encoder refuses in a `loads:` argument is answered exactly like a missing record.
|
|
60
|
+
|
|
61
|
+
### The default encoder
|
|
62
|
+
|
|
63
|
+
If you do not need your own encoder class, use the default one. It never ships a key: it takes `GRAPHQL_ARMORY_KEY` from the environment or, in a Rails app, derives a key of its own from `secret_key_base` with HKDF (purpose `graphql-armory/ids`, so the Rails secret itself is never used to encrypt). Without either, it raises when the schema loads (at boot, with eager loading) instead of serving unencrypted IDs.
|
|
64
|
+
|
|
65
|
+
```ruby
|
|
66
|
+
class AppSchema < GraphQL::Schema
|
|
67
|
+
cursor_encoder GraphQL::Armory::Encoder.default
|
|
68
|
+
end
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`GRAPHQL_ARMORY_KEY` wins over Rails; an empty value counts as unset, and a value with surrounding whitespace is refused (another process might strip it and get other IDs). Changing `secret_key_base` changes every ID: if you rotate it, keep the old encoder in a versioned chain (below). The key does not depend on any other Rails setting: it does not use `Rails.application.key_generator`, whose digest changes during boot. With `SECRET_KEY_BASE_DUMMY` Rails invents a secret per process, so IDs do not survive a restart; set a real secret where IDs matter. `MyEncoder.default` keeps `MyEncoder`'s tag and codec but replaces its key with the default one.
|
|
72
|
+
|
|
73
|
+
## Rotating keys and migrating from base64
|
|
74
|
+
|
|
75
|
+
Put encoders in a chain, newest first. The chain encodes with the first and decodes with whichever accepts the value, so clients keep working while you change keys:
|
|
76
|
+
|
|
77
|
+
```ruby
|
|
78
|
+
class AppEncoder2026 < GraphQL::Armory::Encoder
|
|
79
|
+
key ENV.fetch("GRAPHQL_ARMORY_KEY")
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
class AppEncoder2025 < GraphQL::Armory::Encoder
|
|
83
|
+
key ENV.fetch("GRAPHQL_ARMORY_OLD_KEY")
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
AppIDs = GraphQL::Armory::Encoder.versioned(AppEncoder2026, AppEncoder2025)
|
|
87
|
+
# cursor_encoder AppIDs, and AppIDs.encode / AppIDs.decode in id_from_object / object_from_id
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Drop the old encoder from the chain once its values have expired (cursors are short-lived; IDs may be bookmarked or cached by clients for longer).
|
|
91
|
+
|
|
92
|
+
**Adding encryption to an existing API.** `GraphQL::Armory::Encoder::Legacy` reads graphql-ruby's default base64 (padded or not, url-safe or standard), so the IDs and cursors clients already hold keep working:
|
|
93
|
+
|
|
94
|
+
```ruby
|
|
95
|
+
AppIDs = GraphQL::Armory::Encoder.versioned(AppEncoder, GraphQL::Armory::Encoder::Legacy)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`Legacy` is not encryption: while it is in the chain, anyone can still forge a base64 value. It only accepts printable text, so a tampered full-length encrypted value does not come back as data (a truncated one may decode to short gibberish, like any forged value). Do not put `GraphQL::Schema::Base64Encoder` in a chain: it would turn tampered values into binary data. To treat old values differently, ask which encoder decoded them:
|
|
99
|
+
|
|
100
|
+
```ruby
|
|
101
|
+
data, encoder = AppIDs.decode_versioned(id)
|
|
102
|
+
return nil if encoder.nil? # nothing in the chain accepted it
|
|
103
|
+
log_legacy_id(id) if encoder == GraphQL::Armory::Encoder::Legacy
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Reference
|
|
107
|
+
|
|
108
|
+
| Declaration | Meaning |
|
|
109
|
+
|---|---|
|
|
110
|
+
| `key "..."` | Required. At least 32 bytes. Subkeys for IDs and cursors are derived from it with HKDF. |
|
|
111
|
+
| `tag "v1"` | Optional authenticated data. An ID made with another tag does not decode: use it to separate apps or environments sharing a key. |
|
|
112
|
+
| `codec MyCodec` | Optional. How the encrypted bytes become text; anything with `encode(bytes)` and `decode(text)`. Default: base64url without padding. Any error it raises while decoding becomes `InvalidError`. |
|
|
113
|
+
|
|
114
|
+
| Call | Returns |
|
|
115
|
+
|---|---|
|
|
116
|
+
| `encode(text)` | A stable, encrypted ID. |
|
|
117
|
+
| `encode(text, nonce: true)` | A cursor, different every time. |
|
|
118
|
+
| `decode(id)` / `decode(cursor, nonce: true)` | The text, or raises `GraphQL::Armory::Encoder::InvalidError` (a `GraphQL::ExecutionError`, so clients see `Invalid ID or cursor`). |
|
|
119
|
+
| `Encoder.versioned(newest, ..., oldest)` | A chain with the same `encode` and `decode`; encodes with `newest`. |
|
|
120
|
+
| `chain.decode_versioned(text, nonce: false)` | `[data, encoder]`, or `[nil, nil]` when no encoder accepts it. |
|
|
121
|
+
| `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`. |
|
|
122
|
+
| `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. |
|
|
123
|
+
|
|
124
|
+
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.
|
|
125
|
+
|
|
126
|
+
## Guarantees and limits
|
|
127
|
+
|
|
128
|
+
Covered by `spec/security/encoder_spec.rb`, `encoder_versioning_spec.rb`, `default_encoder_spec.rb` and `ids_plugin_spec.rb` on both engines: round trips, tampering at several positions, another key, another tag, a cursor used as an ID and the reverse, malformed and truncated input, encrypted pagination and a tampered cursor, rotation and migration from base64 cursors, where the default encoder takes its key, and the plugin answering every ID it cannot honour (foreign, tampered, unknown or non-object type, another model in `loads:`) like a missing one.
|
|
129
|
+
|
|
130
|
+
- **Changing the key invalidates every ID and cursor already handed out**, unless the old encoder stays in a versioned chain.
|
|
131
|
+
- **`Legacy` in a chain can be forged**, and it does not separate IDs from cursors. Keep it only while migrating.
|
|
132
|
+
- **Encryption hides the ID; it does not authorize.** Whoever obtained a valid ID can still send it. What they may read is decided by the authorization module.
|
|
133
|
+
- IDs are longer than base64 ones: 28 extra bytes (nonce and authentication tag) before encoding.
|
|
134
|
+
- graphql-ruby decodes an `after:` cursor once per selection that uses it, so a tampered cursor can produce the same error more than once.
|
|
135
|
+
- Without the plugin, graphql-ruby's own `node(id:)` field does not rescue errors: a refused ID answers `Invalid ID or cursor` while a missing record answers `null`. `use GraphQL::Armory::IDs` answers both with `null`.
|
|
136
|
+
- The plugin builds IDs from `object.id` and looks them up by primary key: composite primary keys are not supported.
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# Persisted queries
|
|
2
|
+
|
|
3
|
+
Your API runs the operations your clients were built with, and nothing else.
|
|
4
|
+
|
|
5
|
+
## The problem
|
|
6
|
+
|
|
7
|
+
A GraphQL endpoint accepts any query anyone writes. Authorization decides what each user may read, but the endpoint still:
|
|
8
|
+
|
|
9
|
+
- **Runs queries you never wrote.** Anyone with a token can send deep, wide or expensive queries, or explore the schema field by field to find something you forgot to protect.
|
|
10
|
+
- **Parses and validates every request.** A large query costs CPU before a single field resolves.
|
|
11
|
+
- **Sends the full query text on every request.** Mobile clients pay that in bandwidth.
|
|
12
|
+
|
|
13
|
+
## The solution
|
|
14
|
+
|
|
15
|
+
Your client's build step (Apollo's persisted query manifest generator, or the Relay compiler's `persistConfig`) writes every operation the app uses to a JSON file. The server loads that file and clients send the operation's id instead of its text:
|
|
16
|
+
|
|
17
|
+
- **An allowlist.** In strict mode the server refuses any query that is not in the file, before validating it, so a raw query cannot even probe field names.
|
|
18
|
+
- **Tamper-evident.** Every id must be the digest (SHA-256 by default) of its query. A manifest edited by hand to put another query behind an id is refused when the app boots.
|
|
19
|
+
- **Parsed once.** Each stored query is parsed at boot and handed to graphql-ruby as a document, so a request skips parsing.
|
|
20
|
+
- **Smaller requests.** The client sends a 64-character id and the variables.
|
|
21
|
+
- **Both engines.** It hooks only `Schema.query_class`, so it works on the interpreter and on `Execution::Next`.
|
|
22
|
+
|
|
23
|
+
## Who does what
|
|
24
|
+
|
|
25
|
+
Two separate pieces work together. Your client tooling writes the list; this gem enforces it on the server.
|
|
26
|
+
|
|
27
|
+
| Piece | Who provides it | What it does |
|
|
28
|
+
|---|---|---|
|
|
29
|
+
| `persisted-queries.json` | Apollo or Relay, in your client's build | Lists every operation the app uses. You do not write or edit it by hand. |
|
|
30
|
+
| `PersistedQueries::Manifest` | this gem | Loads the file at boot and checks that nobody edited it. |
|
|
31
|
+
| `use GraphQL::Armory::PersistedQueries` | this gem | Runs the operation a request names by id, and in strict mode refuses everything else. |
|
|
32
|
+
|
|
33
|
+
Think of an event: the client tooling prints the guest list, and this gem is the guard at the door. A list without a guard stops nobody. Apollo's own router (GraphOS Router, Enterprise plan) can enforce the list; Apollo Server's built-in `persistedQueries` option is only a cache (automatic persisted queries) and still runs any query. Open-source graphql-ruby has no equivalent (GraphQL-Pro has its OperationStore), so without this gem a Ruby API ignores the file and keeps running any query it receives.
|
|
34
|
+
|
|
35
|
+
Your part is to copy the file the client build produced into the server (for example as `persisted-queries.json` in the Rails root) and deploy it.
|
|
36
|
+
|
|
37
|
+
### What the file looks like
|
|
38
|
+
|
|
39
|
+
Apollo's manifest, written by `generate-persisted-query-manifest` (`@apollo/generate-persisted-query-manifest`, see [Apollo's guide](https://www.apollographql.com/docs/react/data/persisted-queries)):
|
|
40
|
+
|
|
41
|
+
```json
|
|
42
|
+
{
|
|
43
|
+
"format": "apollo-persisted-query-manifest",
|
|
44
|
+
"version": 1,
|
|
45
|
+
"operations": [
|
|
46
|
+
{
|
|
47
|
+
"id": "6c5d8a12c92cffe7786b5a6d288f56d479973fd0f35b31bce215a4df9cf554ef",
|
|
48
|
+
"name": "Invoices",
|
|
49
|
+
"type": "query",
|
|
50
|
+
"body": "query Invoices { invoices { number total } }"
|
|
51
|
+
}
|
|
52
|
+
]
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Relay's persisted output, written by `relay-compiler` with `persistConfig` (see [Relay's guide](https://relay.dev/docs/guides/persisted-queries/)), is a flat map of id to query:
|
|
57
|
+
|
|
58
|
+
```json
|
|
59
|
+
{
|
|
60
|
+
"904cd33a4439518767fd75402dd7e47b": "query Invoices { invoices { number total } }"
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Each id is the digest of its exact query text: SHA-256 in Apollo's manifest, MD5 in this Relay example (load it with `digest: :md5`). Change a query without regenerating its id and the app refuses to boot, naming that id.
|
|
65
|
+
|
|
66
|
+
A client then sends only the id and the variables:
|
|
67
|
+
|
|
68
|
+
```json
|
|
69
|
+
{ "operationId": "6c5d8a12c92cffe7786b5a6d288f56d479973fd0f35b31bce215a4df9cf554ef", "variables": {} }
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## How to use it
|
|
73
|
+
|
|
74
|
+
Load the manifest and add the plugin:
|
|
75
|
+
|
|
76
|
+
```ruby
|
|
77
|
+
class AppSchema < GraphQL::Schema
|
|
78
|
+
use GraphQL::Armory::PersistedQueries,
|
|
79
|
+
store: GraphQL::Armory::PersistedQueries::Manifest.load(Rails.root.join("persisted-queries.json")),
|
|
80
|
+
strict: true
|
|
81
|
+
end
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Pass the operation id from the request in the context:
|
|
85
|
+
|
|
86
|
+
```ruby
|
|
87
|
+
class GraphqlController < ApplicationController
|
|
88
|
+
def execute
|
|
89
|
+
result = AppSchema.execute(
|
|
90
|
+
params[:query],
|
|
91
|
+
variables: params[:variables],
|
|
92
|
+
operation_name: params[:operationName],
|
|
93
|
+
context: {
|
|
94
|
+
current_user: current_user,
|
|
95
|
+
operation_id: GraphQL::Armory::PersistedQueries.operation_id(params),
|
|
96
|
+
armory_allow_raw_query: current_user&.staff? || Rails.env.development?
|
|
97
|
+
}
|
|
98
|
+
)
|
|
99
|
+
render json: result
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`PersistedQueries.operation_id(params)` reads the id where clients send it: `operationId`, `extensions.operationId`, or Apollo's `extensions.persistedQuery.sha256Hash` (`extensions` may be a JSON string, as in GET requests). The first one present wins, in that order. It answers nil when there is no id, or when it is not a non-empty String. Params must have String keys, as Rack and Rails params do. An empty `query` sent with an id (a GET request with `query=`) counts as no query.
|
|
105
|
+
|
|
106
|
+
What each request does:
|
|
107
|
+
|
|
108
|
+
| Request | Result |
|
|
109
|
+
|---|---|
|
|
110
|
+
| An id the manifest holds | Runs the stored operation with the request's variables and operation name. |
|
|
111
|
+
| An id plus the same query (Apollo's clients may send both) | Runs the stored operation. |
|
|
112
|
+
| An id plus a different query | Refused: `The operation id and the query do not match`. Neither runs. |
|
|
113
|
+
| An id the manifest does not hold | Refused: `Unknown operation id`. |
|
|
114
|
+
| A raw query, strict mode off | Runs as usual. Use this while clients migrate. |
|
|
115
|
+
| A raw query, strict mode on | Refused: `Only persisted operations are allowed: send an operation id`, unless the context holds `armory_allow_raw_query: true`. |
|
|
116
|
+
|
|
117
|
+
A refused request fails validation with that message as its only error, so nothing resolves, even when the app executes with `validate: false`.
|
|
118
|
+
|
|
119
|
+
### Relay
|
|
120
|
+
|
|
121
|
+
Relay's persisted output is a flat map of id to query text. Tell the manifest which digest Relay was configured with:
|
|
122
|
+
|
|
123
|
+
```ruby
|
|
124
|
+
GraphQL::Armory::PersistedQueries::Manifest.load("persisted-queries.json", digest: :md5)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
`digest: false` accepts ids that are not digests (names such as `invoices-v1`). Then nothing proves an id belongs to its query: anyone who can edit the file can change what an id runs.
|
|
128
|
+
|
|
129
|
+
Relay's example network layer sends the id as `doc_id`. Pass it yourself: `operation_id: params[:doc_id]`.
|
|
130
|
+
|
|
131
|
+
### Rolling it out
|
|
132
|
+
|
|
133
|
+
1. Generate the manifest in the client build and ship it with the server.
|
|
134
|
+
2. Add the plugin with `strict: false`. Clients that send ids get stored operations; everything else keeps working.
|
|
135
|
+
3. When every client in use sends ids, turn on `strict: true`.
|
|
136
|
+
|
|
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
|
+
|
|
139
|
+
## Reference
|
|
140
|
+
|
|
141
|
+
`Manifest.new(data, digest: :sha256)`, `Manifest.load(path, digest: :sha256)`
|
|
142
|
+
|
|
143
|
+
- Reads Apollo's persisted query manifest (`format: "apollo-persisted-query-manifest"`, `version: 1`) or Relay's flat map.
|
|
144
|
+
- `digest:` is `:sha256`, `:sha1`, `:md5` or `false`.
|
|
145
|
+
- `fetch(id)` answers the operation (`id`, `name`, `body`, `document`, all frozen) or nil. `size` counts them.
|
|
146
|
+
- 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.
|
|
147
|
+
|
|
148
|
+
`use GraphQL::Armory::PersistedQueries, store:, strict: false`
|
|
149
|
+
|
|
150
|
+
- `store:` answers `fetch(id)` with an object that has `body` and `document`, or nil. A Manifest, or your own store.
|
|
151
|
+
- `strict:` is `true` or `false`.
|
|
152
|
+
- Works with your own `query_class`, whether it is set before `use`, after it, or in a child schema: the plugin subclasses it.
|
|
153
|
+
- `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.
|
|
154
|
+
- A store whose `fetch` raises or answers something without `document` makes the request raise: it fails closed, as an exception.
|
|
155
|
+
|
|
156
|
+
Context keys: `operation_id` (a String; anything else is an unknown id), `armory_allow_raw_query` (only `true` allows).
|
|
157
|
+
|
|
158
|
+
## Guarantees and limits
|
|
159
|
+
|
|
160
|
+
- A request with an id runs only the stored document for that id, or nothing.
|
|
161
|
+
- In strict mode a raw query runs only when the app's context says `armory_allow_raw_query: true`. The plugin does not decide who is staff: your controller does.
|
|
162
|
+
- Queries built by your own code as `GraphQL::Query` objects (for example in `multiplex`) bypass the plugin's lookup. In strict mode they are not refused either: the check happens when the plugin's query class builds the query.
|
|
163
|
+
- In strict mode, schema introspection run through the plugin is refused too. `Schema.to_json` and `rake graphql:schema:json` need `context: { armory_allow_raw_query: true }` (the rake task's `load_context`). `Schema.to_definition` and `Schema.validate` are not affected.
|
|
164
|
+
- The manifest lives in the server's code: adding an operation needs a deploy. See the runtime store below.
|
|
165
|
+
- Subscriptions: graphql-ruby re-runs a subscription with its printed query, which the plugin accepts when it matches the stored document. Subscriptions are not tested with persisted queries yet.
|
|
166
|
+
|
|
167
|
+
## Planned: a runtime store
|
|
168
|
+
|
|
169
|
+
The manifest is the simplest store: one file, no database, deployed with the code. Teams that ship clients independently of the server (mobile apps, several frontends) need operations published without a server deploy. That is planned for later, behind the same `store:` interface:
|
|
170
|
+
|
|
171
|
+
- **A database table** (ActiveRecord) holding operations per client, with the digest checked on write.
|
|
172
|
+
- **A sync endpoint** the client build calls to publish its operations, authenticated per client with an HMAC of the request body and a secret per client.
|
|
173
|
+
- **Several clients**, each with its own operations and secret, so one client cannot publish under another's name.
|
|
174
|
+
- **Archiving** operations that old app versions no longer use, without deleting their history.
|
|
175
|
+
- **Publishing without redeploying**: the server reads new operations as soon as they are synced.
|
|
176
|
+
|
|
177
|
+
Until then, any object that answers `fetch(id)` with an operation can be passed as `store:`.
|
|
178
|
+
|
|
179
|
+
## References
|
|
180
|
+
|
|
181
|
+
- Apollo Client: [Persisted queries](https://www.apollographql.com/docs/react/data/persisted-queries) — generating the manifest with `@apollo/generate-persisted-query-manifest` and sending ids.
|
|
182
|
+
- Apollo iOS: [Persisted queries](https://www.apollographql.com/docs/ios/fetching/apqs).
|
|
183
|
+
- Relay: [Persisted queries](https://relay.dev/docs/guides/persisted-queries/) — `persistConfig`, local persisting to a file, `doc_id` in the network layer.
|
|
184
|
+
- Relay: [Compiler config](https://relay.dev/docs/getting-started/compiler-config/).
|
|
@@ -78,11 +78,12 @@ module GraphQL
|
|
|
78
78
|
end
|
|
79
79
|
|
|
80
80
|
# `GlobalID.find`, graphql-ruby's documented `object_from_id`, raises for a missing record, and a
|
|
81
|
-
# decoder may raise for a malformed id.
|
|
81
|
+
# decoder may raise for a malformed id (ArgumentError, or the Encoder's InvalidError). All must answer like a
|
|
82
|
+
# record out of scope: nil.
|
|
82
83
|
def self.decode(schema, id, context)
|
|
83
84
|
schema.object_from_id(id, context)
|
|
84
85
|
rescue StandardError => error
|
|
85
|
-
raise unless error.is_a?(ArgumentError) || error.class.name == "ActiveRecord::RecordNotFound"
|
|
86
|
+
raise unless error.is_a?(ArgumentError) || error.is_a?(Encoder::InvalidError) || error.class.name == "ActiveRecord::RecordNotFound"
|
|
86
87
|
|
|
87
88
|
nil
|
|
88
89
|
end
|