graphql-armory 0.1.0.pre → 0.1.0.pre3

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.
Files changed (46) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +29 -0
  3. data/LICENSE +0 -0
  4. data/MIGRATING.md +1 -1
  5. data/README.md +26 -266
  6. data/docs/authorization.md +264 -0
  7. data/docs/encrypted-ids.md +136 -0
  8. data/lib/graphql/armory/authorization/adapters/cancan.rb +0 -0
  9. data/lib/graphql/armory/authorization/adapters/null.rb +0 -0
  10. data/lib/graphql/armory/authorization/adapters/pundit.rb +0 -0
  11. data/lib/graphql/armory/authorization/adapters/substitute.rb +0 -0
  12. data/lib/graphql/armory/authorization/audit/command.rb +0 -0
  13. data/lib/graphql/armory/authorization/audit/report.rb +0 -0
  14. data/lib/graphql/armory/authorization/audit.rb +53 -11
  15. data/lib/graphql/armory/authorization/authorize.rb +0 -0
  16. data/lib/graphql/armory/authorization/configuration.rb +0 -0
  17. data/lib/graphql/armory/authorization/controls/actor.rb +0 -0
  18. data/lib/graphql/armory/authorization/controls/context.rb +0 -0
  19. data/lib/graphql/armory/authorization/controls/rule.rb +0 -0
  20. data/lib/graphql/armory/authorization/controls/subject.rb +0 -0
  21. data/lib/graphql/armory/authorization/errors.rb +0 -0
  22. data/lib/graphql/armory/authorization/integration/argument.rb +0 -0
  23. data/lib/graphql/armory/authorization/integration/base.rb +3 -1
  24. data/lib/graphql/armory/authorization/integration/field.rb +1 -1
  25. data/lib/graphql/armory/authorization/integration/find_by.rb +0 -0
  26. data/lib/graphql/armory/authorization/integration/input_object.rb +31 -0
  27. data/lib/graphql/armory/authorization/integration/object.rb +0 -0
  28. data/lib/graphql/armory/authorization/integration/resolver.rb +1 -1
  29. data/lib/graphql/armory/authorization/integration/schema.rb +0 -0
  30. data/lib/graphql/armory/authorization/integration.rb +32 -0
  31. data/lib/graphql/armory/authorization/memo.rb +0 -0
  32. data/lib/graphql/armory/authorization/rspec.rb +0 -0
  33. data/lib/graphql/armory/authorization/rule.rb +0 -0
  34. data/lib/graphql/armory/authorization/scope.rb +0 -0
  35. data/lib/graphql/armory/authorization/telemetry.rb +0 -0
  36. data/lib/graphql/armory/authorization.rb +0 -0
  37. data/lib/graphql/armory/encoder/default.rb +59 -0
  38. data/lib/graphql/armory/encoder/legacy.rb +34 -0
  39. data/lib/graphql/armory/encoder/versioned.rb +67 -0
  40. data/lib/graphql/armory/encoder.rb +137 -0
  41. data/lib/graphql/armory/ids.rb +76 -0
  42. data/lib/graphql/armory/version.rb +1 -1
  43. data/lib/graphql/armory.rb +2 -0
  44. data/lib/graphql-armory.rb +0 -0
  45. data/lib/tasks/graphql_armory.rake +0 -0
  46. metadata +13 -9
@@ -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.
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -38,6 +38,7 @@ module GraphQL
38
38
 
39
39
  audited_types(schema).each { |type| audit_type(type, findings) }
40
40
  schema.types.each_value { |type| audit_interface(type, schema, findings) if type.kind.interface? && !type.introspection? }
41
+ schema.types.each_value { |type| audit_input_loads(type, findings) if type.kind.input_object? && !type.introspection? }
41
42
  findings.report
42
43
  end
43
44
 
@@ -72,18 +73,32 @@ module GraphQL
72
73
  end
73
74
  end
74
75
 
75
- # An interface field with no rule is denied when any implementer is a bypass; the fix is to declare it.
76
+ # Interface fields are reported once, on the interface that declares them, not on every implementer.
77
+ # Undeclared ones are denied when an implementer is a bypass; ones whose field class lacks Base are
78
+ # never checked, so on a bypassed implementer they are open; `authorize: true` names no action.
76
79
  def audit_interface(interface, schema, findings)
77
- return unless Integration.bypassed_implementer?(interface, schema)
78
-
79
- interface.fields.each_value do |field|
80
- next unless field.respond_to?(:armory_declared) && field.armory_declared.nil?
80
+ bypassed = Integration.bypassed_implementer?(interface, schema)
81
+ interface.own_fields.each_value do |field|
82
+ path = "#{interface.graphql_name}.#{field.original_name}"
83
+ unless field.respond_to?(:armory_declared)
84
+ findings.problem(:unprotected, path, "its field class does not include Base, so it is not checked on a bypassed implementer") if bypassed
85
+ next
86
+ end
81
87
 
82
- findings.problem(:field_without_rule, "#{interface.graphql_name}.#{field.original_name}",
83
- "declares no rule and an implementing type is bypassed, so it is denied")
88
+ case field.armory_declared
89
+ when true
90
+ findings.problem(:field_without_rule, path, "uses authorize: true, but an interface has no action of its own, so it is always denied")
91
+ when nil
92
+ findings.problem(:field_without_rule, path, "declares no rule and an implementing type is bypassed, so it is denied") if bypassed
93
+ end
84
94
  end
85
95
  end
86
96
 
97
+ # A field an implementer inherits from an interface is reported on the interface.
98
+ def interface_field?(field)
99
+ field.owner.respond_to?(:kind) && field.owner.kind.interface?
100
+ end
101
+
87
102
  def model_of(type, path, findings)
88
103
  type.armory_model
89
104
  rescue ConfigurationError => error
@@ -101,11 +116,13 @@ module GraphQL
101
116
  def audit_fields(type, findings, model:, bypassed:, reported:)
102
117
  type.all_field_definitions.each do |field|
103
118
  path = "#{type.graphql_name}.#{field.original_name}"
104
- next findings.problem(:field_without_rule, path, "its field class does not include Base, so it is denied") if bypassed && !field.respond_to?(:armory_declared)
119
+ # An inherited interface field is reported as uncovered on its interface; every other check still runs here.
120
+ inherited = bypassed && interface_field?(field)
121
+ next findings.problem(:field_without_rule, path, "its field class does not include Base, so it is denied") if bypassed && !inherited && !field.respond_to?(:armory_declared)
105
122
  next unless field.respond_to?(:armory_declared)
106
123
  next audit_resolver(field, path, findings) if field.resolver.respond_to?(:armory_rule)
107
124
 
108
- audit_declaration(field, path, findings, model: model, bypassed: bypassed, reported: reported)
125
+ audit_declaration(field, path, findings, model: model, bypassed: bypassed && !inherited, reported: reported)
109
126
  audit_visibility(field, path, findings, model: model, reported: reported)
110
127
  audit_loads(field, path, findings)
111
128
  audit_arguments(field, path, findings, reported: reported)
@@ -170,12 +187,37 @@ module GraphQL
170
187
  def audit_loads(field, path, findings)
171
188
  return if field.armory_load_through_scope?
172
189
 
173
- field.all_argument_definitions.select(&:loads).each do |argument|
174
- name = GraphQL::Schema::Member::BuildType.underscore(argument.graphql_name)
190
+ opted_out_loads(field.all_argument_definitions, Set.new).each do |name|
175
191
  findings.problem(:unscoped_load, "#{path}(#{name})", "loads through the app's object_from_id, not through the user's scope")
176
192
  end
177
193
  end
178
194
 
195
+ # Execution::Next loads `loads:` nested in input objects with the field's loader, so a field's opt-out
196
+ # reaches them too: list them as `filter.invoice_id`. `seen` stops recursive input types.
197
+ def opted_out_loads(arguments, seen, prefix = nil)
198
+ arguments.flat_map do |argument|
199
+ name = [prefix, GraphQL::Schema::Member::BuildType.underscore(argument.graphql_name)].compact.join(".")
200
+ next [name] if argument.loads
201
+
202
+ input = argument.type.unwrap
203
+ next [] unless input.kind.input_object? && seen.add?(input)
204
+
205
+ opted_out_loads(input.all_argument_definitions, seen, name)
206
+ end
207
+ end
208
+
209
+ # An input object loads its own `loads:` arguments; without Base they skip the user's scope.
210
+ def audit_input_loads(input, findings)
211
+ return if input.respond_to?(:armory_scoped_loads?)
212
+
213
+ # A mutation's generated input (`from_resolver`) is loaded, scoped, by the mutation itself.
214
+ input.all_argument_definitions.select(&:loads).reject(&:from_resolver?).each do |argument|
215
+ name = GraphQL::Schema::Member::BuildType.underscore(argument.graphql_name)
216
+ findings.problem(:unscoped_load, "#{input.graphql_name}(#{name})",
217
+ "its input object class does not include Base, so it loads through the app's object_from_id, not the user's scope")
218
+ end
219
+ end
220
+
179
221
  # Collects what one audit finds.
180
222
  class Findings
181
223
  def initialize
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -21,11 +21,13 @@ module GraphQL
21
21
  elsif base <= GraphQL::Schema::Resolver
22
22
  base.extend(Integration::ResolverClass)
23
23
  base.include(Integration::Resolver)
24
+ elsif base <= GraphQL::Schema::InputObject
25
+ base.extend(Integration::InputObject)
24
26
  elsif base <= GraphQL::Schema::Argument
25
27
  base.include(Integration::Argument)
26
28
  else
27
29
  raise ArgumentError,
28
- "GraphQL::Armory::Authorization::Base can only be included in a GraphQL object, field, argument, resolver or mutation class, not #{base}. Interfaces and unions are not authorized themselves: declare the rule on their possible types"
30
+ "GraphQL::Armory::Authorization::Base can only be included in a GraphQL object, field, argument, input object, resolver or mutation class, not #{base}. Interfaces and unions are not authorized themselves: declare the rule on their possible types"
29
31
  end
30
32
  end
31
33
  end
@@ -38,7 +38,7 @@ module GraphQL
38
38
  def object_from_id(type, id, context)
39
39
  return super unless @armory_load_through_scope
40
40
 
41
- Integration.find(type, nil, id, context)
41
+ Integration.load(type, id, context)
42
42
  end
43
43
 
44
44
  # A `loads:` id that is not found is answered like a denial, so the client cannot tell the two apart.
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Authorization
6
+ module Integration
7
+ # Extended into an input object class by `include GraphQL::Armory::Authorization::Base`.
8
+ # graphql-ruby loads an input object's `loads:` arguments with the class's own loader, not the
9
+ # field's, so the scoped lookup has to live here too.
10
+ #
11
+ # class Types::BaseInputObject < GraphQL::Schema::InputObject
12
+ # include GraphQL::Armory::Authorization::Base
13
+ # end
14
+ module InputObject
15
+ def armory_scoped_loads?
16
+ true
17
+ end
18
+
19
+ def object_from_id(type, id, context)
20
+ Integration.load(type, id, context)
21
+ end
22
+
23
+ # A `loads:` id that is not found is answered like a denial, so the client cannot tell the two apart.
24
+ def load_application_object_failed(error)
25
+ raise GraphQL::UnauthorizedError.new(object: nil, type: error.argument.loads, context: error.context)
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -55,7 +55,7 @@ module GraphQL
55
55
 
56
56
  # `loads:` arguments are looked up inside the user's scope, so a foreign id answers like a missing one.
57
57
  def object_from_id(type, id, context)
58
- Integration.find(type, nil, id, context)
58
+ Integration.load(type, id, context)
59
59
  end
60
60
 
61
61
  def load_application_object_failed(error)