graphql-armory 0.1.0.pre10 → 0.1.0.pre12

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 (35) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +31 -0
  3. data/README.md +3 -3
  4. data/docs/authorization.md +16 -9
  5. data/docs/rate-limiting.md +1 -1
  6. data/lib/graphql/armory/authorization/adapters/pundit.rb +26 -1
  7. data/lib/graphql/armory/authorization/audit/baseline.rb +3 -3
  8. data/lib/graphql/armory/authorization/audit/denial_hooks.rb +3 -3
  9. data/lib/graphql/armory/authorization/audit/edge_rules.rb +1 -1
  10. data/lib/graphql/armory/authorization/audit/findings.rb +5 -4
  11. data/lib/graphql/armory/authorization/audit/foreign_policies.rb +2 -2
  12. data/lib/graphql/armory/authorization/audit/input_loads.rb +1 -1
  13. data/lib/graphql/armory/authorization/audit/interface_rules.rb +3 -3
  14. data/lib/graphql/armory/authorization/audit/introspection_fields.rb +1 -1
  15. data/lib/graphql/armory/authorization/audit/observed_rules.rb +7 -17
  16. data/lib/graphql/armory/authorization/audit/overrides.rb +3 -3
  17. data/lib/graphql/armory/authorization/audit/own_checks.rb +6 -6
  18. data/lib/graphql/armory/authorization/audit/payload_reuse.rb +1 -1
  19. data/lib/graphql/armory/authorization/audit/plain_resolvers.rb +1 -1
  20. data/lib/graphql/armory/authorization/audit/report.rb +11 -4
  21. data/lib/graphql/armory/authorization/audit/type_rules.rb +32 -31
  22. data/lib/graphql/armory/authorization/audit/visibility_models.rb +5 -5
  23. data/lib/graphql/armory/authorization/audit.rb +2 -2
  24. data/lib/graphql/armory/authorization/integration/argument.rb +3 -0
  25. data/lib/graphql/armory/authorization/integration/field.rb +4 -0
  26. data/lib/graphql/armory/authorization/integration/object.rb +7 -3
  27. data/lib/graphql/armory/authorization/integration/resolver.rb +4 -0
  28. data/lib/graphql/armory/authorization/integration/root_check.rb +35 -0
  29. data/lib/graphql/armory/authorization/integration.rb +81 -7
  30. data/lib/graphql/armory/authorization/location.rb +103 -0
  31. data/lib/graphql/armory/authorization/rule.rb +3 -3
  32. data/lib/graphql/armory/authorization.rb +2 -0
  33. data/lib/graphql/armory/rate_limits/analysis_guard.rb +9 -2
  34. data/lib/graphql/armory/version.rb +1 -1
  35. metadata +3 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 306b875ce5c7b3b423266aac6acad20df8cff2fcfb2de8bd2fd617f18f06ee0a
4
- data.tar.gz: 4850e8b8d61f40d0bfe87a25326b5af43a12415c73dc3fcabdfddb1b861cd393
3
+ metadata.gz: 9c903e027989813481b053dbd0b920afdeaabdfab91ef33315000001264fe267
4
+ data.tar.gz: 30e1a989f7bb9180067dea9d58a0b3cd6be71b14d95f69225ee73b643abbce50
5
5
  SHA512:
6
- metadata.gz: 197340f48f89963609828eff4da2250a56c49bd7946546fafccb1aae03a8fa0743c4850ae24b5df7e780f89d29633c42b380c0326838ecdd8389b4693efd8f3a
7
- data.tar.gz: b3343756c445fb47b688afc126181cefd94d448396324ac310392a3bbda5a5d17ce789979560fa6761f28d6491d62ddcb4d94a8c9befe9da11ac0ce557056f48
6
+ metadata.gz: 4aab89e6ef2f28c43b63739db0a8014e13ead83a7fbfbc3ce50d412bf90d21217f4cd5f9eebb169544aaa7464a56db31cc36e00f9988601babada43d8c3d7aee
7
+ data.tar.gz: 9ca25dbac00ce73ea8072434e0e54b874f360c3f17440362a4b2f4301147b957c4ed8f5ac8f99f6723f9c36217f777ea0e49ea70244183a7be96539b3dcf6737
data/CHANGELOG.md CHANGED
@@ -2,6 +2,37 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.1.0.pre12 (2026-11-04)
6
+
7
+ This release makes [Authorization](docs/authorization.md) cheaper on lists and gives the audit a file and line for the types graphql-ruby generates, and it fixes a way an analysis your app runs itself could let [Rate limiting](docs/rate-limiting.md) undercount a query. Upgrade if you authorize long lists, read the audit's locations, or call `GraphQL::Analysis.analyze_query` before executing a `Query`. Nothing breaks.
8
+
9
+ ### Changed
10
+
11
+ - Authorizing a list costs a third to a half less per item for one field, and about a fifth less with three. Within one query the gem remembers each type's rule and, with the Pundit adapter (a subclass included), which policies answer for each record class; nothing is kept across queries, so code reloading never serves a stale class. An adapter that wraps Pundit is asked as configured and remembers nothing. [Performance](docs/authorization.md#performance). (#62)
12
+ - The audit gives a location to the types graphql-ruby generates with no constant: a mutation's payload points to its mutation, and a connection or an edge to its node type. Before, their problems had none. Limit: an anonymous subclass of a named type and a subscription's payload still have none. [The audit](docs/authorization.md#the-audit). (#63)
13
+
14
+ ### Fixed
15
+
16
+ - A `Query` your app analyzed itself (`GraphQL::Analysis.analyze_query`) before executing it no longer lets that analysis's answers decide the execution. When an analyzer raised during the execution's analysis, the guard read them as "already charged and visited" and ran the query undercounted. The execution now decides from its own analysis, on both engines: it charges `Points` again, as it already did when nothing raised, takes a second `Concurrency` slot, and charges `Time` only for itself. `Points.headers` no longer report what the app's analysis recorded. Limit: a trace module that runs an analysis inside `analyze_multiplex` must be added after `use`. [Rate limiting](docs/rate-limiting.md). (#61)
17
+
18
+ ## 0.1.0.pre11 (2026-11-03)
19
+
20
+ This release closes the ways an [Authorization](docs/authorization.md) rule under `observe:` could still let a resolver or its arguments run for a user the rule would refuse, and gives every misconfigured observed root the same error on every engine. It also makes [the audit](docs/authorization.md#the-audit) say the file and line of each problem. Anyone using `observe:` or comparing audit problems as whole structs should read Breaking before upgrading.
21
+
22
+ ### Breaking
23
+
24
+ - `Audit::Report::Problem` and `Bypass` have one more member, `location`, so `to_a`, `to_h` and `==` against a `Problem.new(kind, path, message)` built by hand change. To upgrade: compare `kind`, `path` and `message` (or `to_s`), not the whole struct. (#55)
25
+ - A type that inherits a resolver or mutation field with `authorize: true` from a class whose rule is under `observe:` now raises `ConfigurationError` when the type is checked, on every query that reaches it, not only when the field is asked for, including a mutation argument that `loads:` that type (the mutation no longer runs). Before, the field's arguments were prepared (`prepare:` ran) for a user the rule would refuse, and only then did the field raise. The audit already reported this shape as "raises on every query". To upgrade: remove `observe:` from that class, or give the field a rule of its own. Limit: with `max_complexity`, graphql-ruby's complexity analysis still coerces a connection's or a `complexity:` lambda's arguments before any check. (#36, #56)
26
+ - An observed root type holding a resolver or a mutation now raises `ConfigurationError` from `execute` before anything runs, on every engine and past any `rescue_from`; in a multiplex, the whole multiplex raises. Before, the interpreter with graphql 2.6 reported a `NoMethodError`, and a `rescue_from(StandardError)` handler turned it into an empty answer. An invalid document keeps its validation errors, and a partial (`run_partials`) is left to its type's check. To upgrade: run the audit, which names the type, and fix it before deploying. (#37, #57)
27
+
28
+ ### Added
29
+
30
+ - The audit says the file and line of each problem and bypass. `Problem#location` and `Bypass#location` hold it as `"path:line"`, and the printed report and the baseline result add `(at path:line)` to each line. A field or an argument gives the line that declared it (with `Base`), a type, a mutation or a resolver the line of its `authorize`, an own check or a denial hook its method. The baseline ignores it, so moving code does not make an accepted problem new. Limits: `nil` for a schema built from SDL; a field declared by a helper gives the helper's line. [The audit](docs/authorization.md#the-audit). (#55)
31
+
32
+ ### Fixed
33
+
34
+ - An observed type no longer lets a parent's resolver run when a subclass overrides that field with one hidden from the user (`visible_when:` or `visible?`): the legacy Warden served the parent's definition, which the check did not read. It now raises `ConfigurationError`, like any type holding a resolver. Under `Schema::Visibility` there was no fallback. Schemas without `observe:` ask no extra policy question. (#38, #57)
35
+
5
36
  ## 0.1.0.pre10 (2026-11-03)
6
37
 
7
38
  This release closes the ways a client could make an analysis refusal disappear, and makes clients pay for the invalid queries they send. Anyone using [rate limits](docs/rate-limiting.md) together with `max_depth`, `max_complexity` or their own analyzers should read Breaking before upgrading: a query whose analysis keeps raising is now refused instead of run. [Keyset connections](docs/keyset-connections.md) now check the cursor encoder when the app loads.
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.pre10`). The API may change before 1.0.
9
+ > **Status: early development.** Prereleases on RubyGems (`0.1.0.pre12`). The API may change before 1.0.
10
10
 
11
11
  ## Install
12
12
 
13
13
  ```ruby
14
- gem "graphql-armory", "~> 0.1.0.pre10" # a prerelease: `gem install graphql-armory --pre`
14
+ gem "graphql-armory", "~> 0.1.0.pre12" # a prerelease: `gem install graphql-armory --pre`
15
15
  gem "pundit" # or "cancancan", for the authorization module
16
16
  ```
17
17
 
@@ -23,7 +23,7 @@ Status: ✅ released, 🚧 in progress, ⬜ not started. Update this table in th
23
23
 
24
24
  | Order | Module | Status | Docs | Current limits |
25
25
  |---|---|---|---|---|
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. |
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. The audit gives the file and line of each problem from 0.1.0.pre11, and of generated payloads and connections from 0.1.0.pre12. |
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). Operations can be published without a server deploy (`RedisStore`, unreleased). 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
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. Invalid queries are charged `invalid_cost:` from 0.1.0.pre10. |
@@ -163,9 +163,9 @@ When the policy answers `false` or `nil`, **the data is served to a user the rul
163
163
  | A type or field with no rule | Denied: there is no rule to observe |
164
164
  | A mutation or a subscription, including a read in its response | Refused: only a query runs |
165
165
  | A mutation whose response returns a type that cannot be observed | The mutation's own body has already run when that type raises: its write stands |
166
- | A type under `observe:` with a field that has a `resolver:` or a `mutation:`, its own, inherited or from an interface; a definition shadowed in a subclass does not count | Raises `ConfigurationError` on every query that reaches the type, and its resolvers do not run: observing the type would open the only check before them, and they can write. Remove `observe:`, or put it on the type's plain fields |
167
- | The same, on the root type | Runs nothing, but the error depends on the engine: on the interpreter with graphql 2.6, graphql-ruby's own rescue reports a `NoMethodError` caused by the `ConfigurationError`. A `rescue_from` handler can turn it into an empty result, so run the audit, which names the type |
168
- | `authorize: true` with a resolver, where the type's rule is observed | Raises `ConfigurationError`, after graphql-ruby has coerced the arguments: their `prepare:` has run, as it does before any field's rule |
166
+ | A type under `observe:` with a field that has a `resolver:` or a `mutation:`, its own, inherited or from an interface; a definition shadowed in a subclass does not count, unless the override is hidden from the user and the legacy Warden falls back to it | Raises `ConfigurationError` on every query that reaches the type, and its resolvers do not run: observing the type would open the only check before them, and they can write. Remove `observe:`, or put it on the type's plain fields |
167
+ | The same, on the root type of the operation | Raises `ConfigurationError` from `execute` before anything runs, on every engine, past any `rescue_from`; in a multiplex, the whole multiplex raises. An invalid document keeps its validation errors. A partial (`run_partials`) and a query whose `context[:trace]` was built without the schema's trace modules skip this and fall back to the type's check, whose error graphql-ruby hands to `rescue_from` (on the interpreter with graphql 2.6, as a `NoMethodError` caused by it). Below the root, a type that cannot be observed is refused in its own check, so a `rescue_from` can turn it into an empty field: run the audit, which names the type |
168
+ | `authorize: true` with a resolver, where the type's rule is observed | Raises `ConfigurationError` when the type that serves it is checked, on every query that reaches that type, before the field's arguments are coerced during execution. A parent's resolver field a subclass overrides counts when the legacy Warden hides the override from this user and falls back to it. Two exceptions run the arguments' `prepare:` first: objects of a scoped list under `reauthorize_scoped_objects(false)` (the type's check does not run for them, and the field's own check then raises); and a schema with `max_complexity` (or graphql-ruby's complexity analysis), which coerces the arguments of a connection field or a field with a `complexity:` lambda during analysis, before any type or field check, for every field rule |
169
169
  | A list of an object type, a `loads:` or a `find_by:` | Still goes through the user's scope, and an in-memory lookup still asks the policy: rows are lost, and nothing is recorded about them |
170
170
  | A list with no scope: of an interface or a union, `scope: false`, Relay `nodes(ids:)` | **Served row by row and recorded**: the check on each object is all that protects these lists, and it cannot tell it is inside one. A foreign row reaches the user |
171
171
  | `visible_when:` | Still hides: the rule it builds is not observed |
@@ -220,6 +220,13 @@ load "tasks/graphql_armory.rake"
220
220
 
221
221
  **What it reports.** Each problem has a `kind`, a `path` and a `message`. Every declared bypass is listed apart, with its reason.
222
222
 
223
+ **Where it is.** Each problem and bypass also has a `location`, the file and line it is about, relative to the directory the app started in when it is inside it, and the printed report adds it: `Invoice (no_rule): has no rule and no default_action, so it is denied (at app/graphql/types/invoice_type.rb:3)`.
224
+ - A field or an argument gives the line that declared it, when its class includes `Base`; otherwise the line of its type.
225
+ - A type, a mutation or a resolver gives the line of its own `authorize`, or else of its class.
226
+ - An own check or a denial hook gives the line of its method.
227
+
228
+ A type graphql-ruby generates gives the line of the class it came from: a mutation's payload the line of its mutation, a connection or an edge the line of its node type. `location` is `nil` when there is no Ruby line to give: a schema built from SDL, or any other class with no name and no `authorize` of its own, such as an anonymous subclass of a named type or the payload of a subscription. A field declared by a helper method gives the helper's line, and a class reopened in several files gives the first one. The location is not part of a problem for the [baseline](#adopting-it-on-a-schema-with-many-problems): moving code never turns an accepted problem into a new one.
229
+
223
230
  | Kind | What it means | What to do |
224
231
  |---|---|---|
225
232
  | `:plugin` | The schema never installed the plugin. | Add `use GraphQL::Armory::Authorization, adapter: ...`. |
@@ -501,16 +508,16 @@ Both execution engines are tested: the default interpreter and `Execution::Next`
501
508
 
502
509
  ## Performance
503
510
 
504
- `benchmark/authorization.rb`, 1000 invoices, graphql 2.6.2, Ruby 3.2, Docker on Windows:
511
+ `benchmark/authorization.rb`, 1000 invoices, graphql 2.6.14, Ruby 3.2, Docker on Windows. Time per query; the cost of the gem is armory minus plain:
505
512
 
506
513
  | Engine | Query | plain | armory (array) | armory (relation) |
507
514
  |---|---|---|---|---|
508
- | interpreter | `number` | 117.6 i/s | 45.9 i/s | 44.2 i/s |
509
- | interpreter | 3 fields | 58.8 i/s | 21.6 i/s | 21.0 i/s |
510
- | next | `number` | 654.2 i/s | 71.8 i/s | 70.8 i/s |
511
- | next | 3 fields | 417.5 i/s | 42.1 i/s | 39.5 i/s |
515
+ | interpreter | `number` | 7.9 ms | 18.8 ms | 21.9 ms |
516
+ | interpreter | 3 fields | 14.8 ms | 54.9 ms | 59.6 ms |
517
+ | next | `number` | 1.6 ms | 13.8 ms | 16.1 ms |
518
+ | next | 3 fields | 2.4 ms | 37.5 ms | 38.7 ms |
512
519
 
513
- 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).
520
+ That is about 11 to 14 µs per item for one field, a third to a half less than in 0.1.0.pre11. Within one query the gem remembers, for each type, its rule and, for each record class, which Pundit policies answer for it; it never remembers a record or an answer across queries, and the next query looks everything up again, 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, and `PROFILE=1` passed with `docker compose run -e` to see where the time goes).
514
521
 
515
522
  ## Migrating
516
523
 
@@ -317,7 +317,7 @@ Invalid settings raise `RateLimits::ConfigurationError` at boot.
317
317
  - Each query in a multiplex is charged on its own.
318
318
  - With several keys, `Points` reads every balance and then charges, so a refused query leaves the others as they were. Two queries racing between those steps can leave a refused one having charged other keys. `Concurrency` gives back the slots a refused query took at once. `Time` charges every key the whole time; a store failure on one key does not stop the others.
319
319
  - An invalid query (a syntax error, a validation error including a variable of the wrong type or a missing required one, no query string, or a refusal from `PersistedQueries` in strict mode) is charged `invalid_cost:` points after it answers; its answer does not change. This penalises the client's next valid query: it does not stop a flood of invalid ones, which are parsed and validated all the same, and a bucket stops at zero. A query the analyzers refused is not invalid: it is charged as before, also when a multiplex analyzer refuses the whole multiplex. Keys are charged in list order, as if the queries had come one at a time: a key that cannot pay all of it pays what it holds, and the keys after it pay only that much, so sending invalid queries together never costs a client less than sending them apart. Put the narrowest key first: a client with nothing left cannot keep draining a bucket it shares. Keys must not depend on the document or the variables, which an invalid query may not have. Failures here, including a query with no key, go to `on_store_error` and never replace the answer, so a missing key on an invalid query does not raise. A trace does this after the multiplex, also when an exception ends it early: then queries that never reached validation are validated to find the invalid ones. A query run with its own trace (`context[:trace]`, or a class given to `trace_mode`) is not charged.
320
- - An `ExecutionError` raised during analysis, which graphql-ruby would discard before running the query, does not skip a limiter. A refusal already given stands. A limiter not asked yet is asked on its own, so another analyzer's raise still charges the query. A limiter that cannot answer, because a `complexity:` lambda or its `on_store_error` hook raised, refuses the query in hard mode with the code `RATE_LIMIT_NOT_CHARGED`, and in soft mode lets it run and records `charged: false`. A client with no limit still runs, and a query with no key raises `ConfigurationError`. When a query takes this path it is visited once more per limiter not asked yet and per other analyzer (see below), so a `complexity:` lambda can run several times, `key:` and `limit:` are asked again, and a validation timeout can take longer. An analysis your app runs itself outside an execution charges nothing here. A trace that takes no modules from the schema (`context[:trace]` or a class given to `trace_mode`) is outside this: `Points` is not protected on such a trace.
320
+ - An `ExecutionError` raised during analysis, which graphql-ruby would discard before running the query, does not skip a limiter. A refusal already given stands. A limiter not asked yet is asked on its own, so another analyzer's raise still charges the query. A limiter that cannot answer, because a `complexity:` lambda or its `on_store_error` hook raised, refuses the query in hard mode with the code `RATE_LIMIT_NOT_CHARGED`, and in soft mode lets it run and records `charged: false`. A client with no limit still runs, and a query with no key raises `ConfigurationError`. When a query takes this path it is visited once more per limiter not asked yet and per other analyzer (see below), so a `complexity:` lambda can run several times, `key:` and `limit:` are asked again, and a validation timeout can take longer. An analysis your app runs itself (`GraphQL::Analysis.analyze_query`) is not guarded: `Points` charges it and `Concurrency` takes a slot for it, which an analysis the app never executes holds until `stale_after`. If the app then executes the same `Query`, the execution charges `Points` again, takes a second slot (so with a `Concurrency` limit of 1 the execution is refused), charges `Time` only for itself, and decides only from its own analysis, so what the app's analysis answered cannot hide a raise during the execution. An analysis the app runs inside `analyze_multiplex` from a trace module added before `use` is outside this too: it is taken for the execution's own, so a raise during the execution's analysis is not guarded. Add such a module after `use`. A trace that takes no modules from the schema (`context[:trace]` or a class given to `trace_mode`) is outside this: `Points` is not protected on such a trace.
321
321
  - On the same path every query analyzer that is not a limiter is then asked on its own. A refusal it returns stands, such as a `max_depth` or `max_complexity` refusal, and so does an `AnalysisError` it raises from `result`, with its own message. One that raises anything else again cannot answer, and the query is refused with the code `QUERY_LIMIT_UNKNOWN`, in soft mode and for a client with no limit too, because otherwise a client could get past that analyzer by asking for the field that makes it raise. That covers `max_complexity` with a `complexity:` lambda that raises and your own maximums alike. So do not raise `ExecutionError` from a `complexity:` lambda or an analyzer: an authorization check belongs in the field. Multiplex analyzers, including a `max_complexity` for a whole multiplex (which `Schema.multiplex` takes from the schema by default), cannot be asked again. When a raise stopped the visit before its end, a query in a multiplex with any multiplex analyzer is refused the same way. A lambda raises after the visit, when the multiplex analyzers have seen the whole query, so it is not refused for that. Each analyzer is asked once more at most, each with the whole remaining validation timeout, so a query on this path can take one more visit per analyzer, and an analyzer with side effects repeats them. After a validation timeout no other analyzer is asked again, since the query is already refused; a limiter not asked yet still is. Limits: this needs a rate limiter on the schema, since a schema with none keeps graphql-ruby's behaviour and the refusal is lost. An analyzer's refusal stands only if it answers the same way when asked again: one that remembers in the context that it already refused is lost. A refusal an analyzer raises as `AnalysisError` during the visit, followed by an `ExecutionError` from the same analyzer, becomes `QUERY_LIMIT_UNKNOWN` without its message. The multiplex analyzers keep the part of a refused query they saw before its visit raised, though it does not run.
322
322
  - On `Execution::Next`, `validate: false` ignores every refusal from analysis, the limiters' included. Never pass it for a client's query.
323
323
  - A field with `max_page_size: nil` under a schema with `default_max_page_size` is sized by that default, while at runtime it has no maximum, so it is charged less than it returns. Give such a field a number.
@@ -17,8 +17,24 @@ module GraphQL
17
17
  raise ArgumentError, "user_key must be a Symbol or a String, got #{user_key.class}" unless user_key.is_a?(Symbol) || user_key.is_a?(String)
18
18
 
19
19
  @user_key = user_key
20
+ @found = nil
20
21
  end
21
22
 
23
+ # A copy that remembers, for one query, which policies a record's class answers to: every item of a list asks the
24
+ # same few classes. Only the class is remembered, never a record, and a lookup that raises is asked again. A `clone`,
25
+ # so a subclass keeps what its `initialize` stored and an instance keeps the modules and methods added to it.
26
+ def per_query
27
+ copy = clone(freeze: false)
28
+ copy.found = {}
29
+ copy
30
+ end
31
+
32
+ protected
33
+
34
+ attr_writer :found
35
+
36
+ public
37
+
22
38
  def actor(context)
23
39
  context[@user_key]
24
40
  end
@@ -71,8 +87,17 @@ module GraphQL
71
87
  # policy, past the first, or a subclass past its own stricter policy.
72
88
  def policies_for(rule, subject)
73
89
  return [rule.policy] if rule.policy
90
+ # A Symbol's policies depend on the Symbol itself, not only on its class.
91
+ return find_policies(rule.model, subject) if @found.nil? || Symbol === subject
92
+
93
+ # For anything else they depend only on the declared model and the class Pundit is asked about.
94
+ by_target = (@found[rule.model] ||= {}.compare_by_identity)
95
+ target = record_target(subject)
96
+ by_target.fetch(target) { by_target[target] = find_policies(rule.model, subject) }
97
+ end
74
98
 
75
- model = normalize(rule.model) if rule.model
99
+ def find_policies(declared_model, subject)
100
+ model = normalize(declared_model) if declared_model
76
101
  declared = finder(model).policy if model
77
102
  target = model_named?(subject, model) ? subject : record_target(subject)
78
103
  own = finder(target).policy
@@ -42,7 +42,7 @@ module GraphQL
42
42
  sections = [
43
43
  section("#{new_problems.size} new #{plural('problem', new_problems.size)}:", new_problems.map { |problem| new_line(problem) }),
44
44
  section("#{gone.size} accepted #{plural('problem', gone.size)} no longer found (remove them from the baseline):", gone.map { |entry| "#{entry.path} (#{entry.kind}): #{entry.message}" }),
45
- section("#{accepted.size} accepted in the baseline, still open:", accepted),
45
+ section("#{accepted.size} accepted in the baseline, still open:", accepted.map { |problem| Report.line(problem.to_s, problem.location) }),
46
46
  bypasses_text
47
47
  ].compact
48
48
  sections.unshift("Passes only because of its baseline.") if passes? && !accepted.empty?
@@ -54,7 +54,7 @@ module GraphQL
54
54
 
55
55
  def new_line(problem)
56
56
  extra = grown[problem]
57
- extra ? "#{problem} (it now also reaches #{extra.join(', ')})" : problem.to_s
57
+ Report.line(extra ? "#{problem} (it now also reaches #{extra.join(', ')})" : problem.to_s, problem.location)
58
58
  end
59
59
 
60
60
  def section(title, lines)
@@ -64,7 +64,7 @@ module GraphQL
64
64
  end
65
65
 
66
66
  def bypasses_text
67
- section("#{report.bypasses.size} declared #{report.bypasses.size == 1 ? 'bypass' : 'bypasses'}:", report.bypasses.map { |bypass| "#{bypass.path}: #{bypass.reason}" })
67
+ section("#{report.bypasses.size} declared #{report.bypasses.size == 1 ? 'bypass' : 'bypasses'}:", report.bypasses.map { |bypass| Report.line("#{bypass.path}: #{bypass.reason}", bypass.location) })
68
68
  end
69
69
 
70
70
  def plural(word, count)
@@ -13,12 +13,12 @@ module GraphQL
13
13
  path = "Schema.#{hook}"
14
14
  own = schema.method(hook).owner != Integration::Schema
15
15
  if own && declared.key?(hook)
16
- findings.bypass(path, declared[hook])
16
+ findings.bypass(path, declared[hook], at: schema.method(hook))
17
17
  elsif own
18
18
  findings.problem(:hook, path, "the schema's own method runs instead of the plugin's, so on_unauthorized: does not apply and a denial " \
19
- "may reveal what it hides: remove it, or declare it in own_denial_hooks: with a reason")
19
+ "may reveal what it hides: remove it, or declare it in own_denial_hooks: with a reason", at: schema.method(hook))
20
20
  elsif declared.key?(hook)
21
- findings.problem(:hook, path, "named in own_denial_hooks: but the plugin's hook is the one that runs: remove it from the option")
21
+ findings.problem(:hook, path, "named in own_denial_hooks: but the plugin's hook is the one that runs: remove it from the option", at: schema)
22
22
  end
23
23
  end
24
24
  end
@@ -15,7 +15,7 @@ module GraphQL
15
15
 
16
16
  findings.problem(:ignored_rule, type.graphql_name, "the connection's nodes field returns the nodes without building an edge, so this rule does not " \
17
17
  "cover it: put the rule on the field that returns the connection (on a root field, on a resolver: " \
18
- "a field rule asks the parent's policy), or remove the nodes field with has_nodes_field(false)")
18
+ "a field rule asks the parent's policy), or remove the nodes field with has_nodes_field(false)", at: type)
19
19
  end
20
20
  end
21
21
 
@@ -11,16 +11,17 @@ module GraphQL
11
11
  @bypasses = []
12
12
  end
13
13
 
14
- def problem(kind, path, message)
15
- @problems << Report::Problem.new(kind, path, message)
14
+ # `at:` is what the problem is about (a type, a field, an argument or a method), for its file and line.
15
+ def problem(kind, path, message, at: nil)
16
+ @problems << Report::Problem.new(kind, path, message, Location.of(at))
16
17
  end
17
18
 
18
19
  def problem?(kind, path = nil)
19
20
  @problems.any? { |problem| problem.kind == kind && (path.nil? || problem.path == path) }
20
21
  end
21
22
 
22
- def bypass(path, reason)
23
- @bypasses << Report::Bypass.new(path, reason)
23
+ def bypass(path, reason, at: nil)
24
+ @bypasses << Report::Bypass.new(path, reason, Location.of(at))
24
25
  end
25
26
 
26
27
  def report(reach = nil)
@@ -54,7 +54,7 @@ module GraphQL
54
54
  return if same || !@seen.add?([resolver, path, policy])
55
55
 
56
56
  @findings.problem(:foreign_policy, path, "its resolver's rule asks #{asked || "the policy found from its model"}, not #{policy}, the `policy:` of this type. " \
57
- "Name the same `policy:` on the resolver")
57
+ "Name the same `policy:` on the resolver", at: resolver)
58
58
  end
59
59
 
60
60
  def note(member, path, policy, model)
@@ -63,7 +63,7 @@ module GraphQL
63
63
 
64
64
  asked = member.armory_policy || "the policy found from the record"
65
65
  @findings.problem(:foreign_policy, path, "its rule asks #{asked}, not #{policy}, the `policy:` of this type: it is defined on a class that does not name that policy. " \
66
- "Move the rule to the class that names it and remove the original, or name the `policy:` on the class that defines the rule, if it can hold one")
66
+ "Move the rule to the class that names it and remove the original, or name the `policy:` on the class that defines the rule, if it can hold one", at: member)
67
67
  end
68
68
 
69
69
  # With no `policy:` of its own, a rule asks what the adapter finds from the model, which may be the same policy.
@@ -15,7 +15,7 @@ module GraphQL
15
15
  input.all_argument_definitions.select(&:loads).reject(&:from_resolver?).each do |argument|
16
16
  name = GraphQL::Schema::Member::BuildType.underscore(argument.graphql_name)
17
17
  findings.problem(:unscoped_load, "#{input.graphql_name}(#{name})",
18
- "its input object class does not include Base, so it loads through the app's object_from_id, not the user's scope")
18
+ "its input object class does not include Base, so it loads through the app's object_from_id, not the user's scope", at: argument)
19
19
  end
20
20
  end
21
21
  end
@@ -22,15 +22,15 @@ module GraphQL
22
22
  path = "#{interface.graphql_name}.#{field.original_name}"
23
23
  PlainResolvers.report(findings, path, field) if covered && !bypassed && PlainResolvers.open?(field)
24
24
  unless field.respond_to?(:armory_declared)
25
- findings.problem(:unprotected, path, "its field class does not include Base, so it is not checked on a bypassed implementer") if bypassed
25
+ findings.problem(:unprotected, path, "its field class does not include Base, so it is not checked on a bypassed implementer", at: field) if bypassed
26
26
  next
27
27
  end
28
28
 
29
29
  case field.armory_declared
30
30
  when true
31
- findings.problem(:field_without_rule, path, "uses authorize: true, but an interface has no action of its own, so it is always denied")
31
+ findings.problem(:field_without_rule, path, "uses authorize: true, but an interface has no action of its own, so it is always denied", at: field)
32
32
  when nil
33
- findings.problem(:field_without_rule, path, "declares no rule and an implementing type is bypassed, so it is denied") if bypassed
33
+ findings.problem(:field_without_rule, path, "declares no rule and an implementing type is bypassed, so it is denied", at: field) if bypassed
34
34
  end
35
35
  end
36
36
  end
@@ -31,7 +31,7 @@ module GraphQL
31
31
  name = field.graphql_name
32
32
  return if field.owner.superclass.fields[name].equal?(built_in.fields[name])
33
33
 
34
- @findings.problem(:unprotected, "#{field.owner.graphql_name}.#{name}", "is a custom introspection field, so no type's rule runs on it: move it to a type with a rule")
34
+ @findings.problem(:unprotected, "#{field.owner.graphql_name}.#{name}", "is a custom introspection field, so no type's rule runs on it: move it to a type with a rule", at: field)
35
35
  end
36
36
  end
37
37
  end
@@ -9,40 +9,30 @@ module GraphQL
9
9
  def self.call(schema, definitions, findings)
10
10
  definitions.each do |type|
11
11
  rule = type.armory_rule if type.respond_to?(:armory_rule)
12
- report(findings, type.graphql_name, rule.observe, unobservable(type)) if rule&.observed?
12
+ report(findings, type.graphql_name, rule.observe, unobservable(type), at: type) if rule&.observed?
13
13
  next unless type.respond_to?(:fields)
14
14
 
15
15
  Definitions.fields_at_every_level(type).each do |field|
16
- reason = observed_reason(field)
17
- report(findings, "#{type.graphql_name}.#{field.graphql_name}", reason, field.resolver ? field : nil) if reason
16
+ reason = Integration.observed_reason(field)
17
+ report(findings, "#{type.graphql_name}.#{field.graphql_name}", reason, field.resolver ? field : nil, at: field) if reason
18
18
  end
19
19
  end
20
- custom_introspection(schema).each { |field| report(findings, "#{field.owner.graphql_name}.#{field.graphql_name}", field.armory_observe) }
20
+ custom_introspection(schema).each { |field| report(findings, "#{field.owner.graphql_name}.#{field.graphql_name}", field.armory_observe, at: field) }
21
21
  end
22
22
 
23
- def self.report(findings, path, reason, resolver_field = nil)
23
+ def self.report(findings, path, reason, resolver_field = nil, at: nil)
24
24
  effect = if resolver_field
25
25
  "raises on every query, because #{resolver_field.graphql_name} has a resolver or a mutation, which can write (#{reason}): remove observe:"
26
26
  else
27
27
  "serves what this rule would refuse (#{reason}): remove it to enforce the rule"
28
28
  end
29
- findings.problem(:observed, path, "observe: #{effect}")
30
- end
31
-
32
- # Its own observe:, or `authorize: true` on an owner whose rule is observed: if that owner is only a parent, no
33
- # type reports its rule.
34
- def self.observed_reason(field)
35
- return field.armory_observe if field.respond_to?(:armory_observe) && field.armory_observe
36
- return unless field.respond_to?(:armory_declared) && field.armory_declared == true
37
-
38
- rule = field.owner.armory_rule if field.owner.respond_to?(:armory_rule)
39
- rule.observe if rule&.observed?
29
+ findings.problem(:observed, path, "observe: #{effect}", at: at)
40
30
  end
41
31
 
42
32
  def self.unobservable(type)
43
33
  type.all_field_definitions.find(&:resolver)
44
34
  end
45
- private_class_method :observed_reason, :unobservable
35
+ private_class_method :unobservable
46
36
 
47
37
  # Definitions holds what these fields return, not the classes that own them.
48
38
  def self.custom_introspection(schema)
@@ -66,12 +66,12 @@ module GraphQL
66
66
  def note_override(path, member, falls_back)
67
67
  reason = member.armory_override_reason if member.respond_to?(:armory_override_reason)
68
68
  if falls_back && reason
69
- @findings.bypass(path, reason)
69
+ @findings.bypass(path, reason, at: member)
70
70
  elsif falls_back
71
71
  @findings.problem(:ignored_rule, path, "is defined more than once: hidden from a user, it falls back to the other definition, and its own rule, arguments, type and extensions do not apply. " \
72
- "Remove one or declare override_reason:; for a definition on an ancestor, Schema::Visibility with dynamic: true and no profiles also stops the fallback")
72
+ "Remove one or declare override_reason:; for a definition on an ancestor, Schema::Visibility with dynamic: true and no profiles also stops the fallback", at: member)
73
73
  elsif reason
74
- @findings.problem(:ignored_rule, path, "declares override_reason: but nothing falls back from it: remove it")
74
+ @findings.problem(:ignored_rule, path, "declares override_reason: but nothing falls back from it: remove it", at: member)
75
75
  end
76
76
  end
77
77
  end
@@ -71,7 +71,7 @@ module GraphQL
71
71
  readers.each { |reader| note_class_check(reader, :reauthorize_scoped_objects) }
72
72
 
73
73
  setter = reauthorization_setter(type)
74
- @found[[setter, :reauthorize_scoped_objects]] = "#{setter.name || setter.inspect}.reauthorize_scoped_objects" if setter&.instance_variable_get(:@reauthorize_scoped_objects) == false
74
+ @found[[setter, :reauthorize_scoped_objects]] = ["#{setter.name || setter.inspect}.reauthorize_scoped_objects", setter] if setter&.instance_variable_get(:@reauthorize_scoped_objects) == false
75
75
  end
76
76
 
77
77
  # The nearest that set the value, read from the classes so no method of the app runs: graphql-ruby's reader follows
@@ -105,23 +105,23 @@ module GraphQL
105
105
  def note_own_check(klass, method, name, separator)
106
106
  while method
107
107
  holder = LibraryMethods.holder_of(klass, method)
108
- @found[[holder, name]] = "#{holder.name || holder.inspect}#{separator}#{name}" unless LibraryMethods.library_method?(method, holder, GRAPHQL_RUBY_PATH, ARMORY_PATH)
108
+ @found[[holder, name]] = ["#{holder.name || holder.inspect}#{separator}#{name}", method] unless LibraryMethods.library_method?(method, holder, GRAPHQL_RUBY_PATH, ARMORY_PATH)
109
109
  method = method.super_method
110
110
  end
111
111
  end
112
112
 
113
113
  def report(declared)
114
- @found.each do |(holder, name), path|
114
+ @found.each do |(holder, name), (path, method)|
115
115
  reason = declared.fetch(holder, {})[name]
116
- next @findings.bypass(path, reason) if reason
116
+ next @findings.bypass(path, reason, at: method) if reason
117
117
 
118
- @findings.problem(:own_check, path, "#{risk(name)}. Remove it, or declare it in own_checks: with a reason")
118
+ @findings.problem(:own_check, path, "#{risk(name)}. Remove it, or declare it in own_checks: with a reason", at: method)
119
119
  end
120
120
  declared.each do |holder, methods|
121
121
  methods.each_key do |name|
122
122
  next if @found.key?([holder, name])
123
123
 
124
- @findings.problem(:own_check, "#{holder.name || holder.inspect} #{name}", "named in own_checks: but no check of the schema is defined there: remove it from the option")
124
+ @findings.problem(:own_check, "#{holder.name || holder.inspect} #{name}", "named in own_checks: but no check of the schema is defined there: remove it from the option", at: holder)
125
125
  end
126
126
  end
127
127
  end
@@ -67,7 +67,7 @@ module GraphQL
67
67
 
68
68
  @findings.problem(:payload_outside_mutation, "#{type.graphql_name}.#{field.original_name}",
69
69
  "returns #{reused.map(&:graphql_name).sort.join(", ")}, a mutation's payload, whose fields are covered by that mutation's rule: " \
70
- "here no such rule runs, so they are served with no check. Return a type of its own, or, for a public child of a mutation with a rule, give the parent's field `authorize: :none, reason: \"...\"`")
70
+ "here no such rule runs, so they are served with no check. Return a type of its own, or, for a public child of a mutation with a rule, give the parent's field `authorize: :none, reason: \"...\"`", at: field)
71
71
  end
72
72
 
73
73
  # A shadowed definition may name a type that never resolved; it cannot serve anything.
@@ -13,7 +13,7 @@ module GraphQL
13
13
  "serves it, unless its own code refuses. Include Base in the resolver and declare `authorize`, or use a field class that includes Base and declare `authorize: :none, reason: \"...\"`"
14
14
 
15
15
  def self.report(findings, path, field)
16
- findings.problem(:unprotected, path, field.respond_to?(:armory_declared) ? PROBLEM : PLAIN_FIELD_PROBLEM)
16
+ findings.problem(:unprotected, path, field.respond_to?(:armory_declared) ? PROBLEM : PLAIN_FIELD_PROBLEM, at: field)
17
17
  end
18
18
 
19
19
  def self.covering?(rule)
@@ -6,13 +6,20 @@ module GraphQL
6
6
  class Audit
7
7
  # What an audit found: what is not covered, and every bypass someone declared.
8
8
  class Report
9
- Problem = Struct.new(:kind, :path, :message) do
9
+ # `location` is "path:line" where the app wrote what the problem is about (see Location), or nil. It is not part of
10
+ # what a problem is: `to_s` and the baseline leave it out, so moving code changes neither.
11
+ Problem = Struct.new(:kind, :path, :message, :location) do
10
12
  def to_s
11
13
  "#{path} (#{kind}): #{message}"
12
14
  end
13
15
  end
14
16
 
15
- Bypass = Struct.new(:path, :reason)
17
+ Bypass = Struct.new(:path, :reason, :location)
18
+
19
+ # The line the report prints for a problem or a bypass: its text, then where it is.
20
+ def self.line(text, location)
21
+ location ? "#{text} (at #{location})" : text
22
+ end
16
23
 
17
24
  attr_reader :problems, :bypasses
18
25
 
@@ -41,14 +48,14 @@ module GraphQL
41
48
  def problems_text
42
49
  return "No problems." if ok?
43
50
 
44
- ["#{problems.size} #{problems.size == 1 ? 'problem' : 'problems'}:", *problems.map { |problem| " #{problem}" }].join("\n")
51
+ ["#{problems.size} #{problems.size == 1 ? 'problem' : 'problems'}:", *problems.map { |problem| " #{Report.line(problem.to_s, problem.location)}" }].join("\n")
45
52
  end
46
53
 
47
54
  def bypasses_text
48
55
  return if bypasses.empty?
49
56
 
50
57
  ["#{bypasses.size} declared #{bypasses.size == 1 ? 'bypass' : 'bypasses'}:",
51
- *bypasses.map { |bypass| " #{bypass.path}: #{bypass.reason}" }].join("\n")
58
+ *bypasses.map { |bypass| " #{Report.line("#{bypass.path}: #{bypass.reason}", bypass.location)}" }].join("\n")
52
59
  end
53
60
  end
54
61
  end
@@ -16,28 +16,28 @@ module GraphQL
16
16
  def call(type)
17
17
  path = type.graphql_name
18
18
  unless type.respond_to?(:armory_rule)
19
- @findings.problem(:unprotected, path, "its base class does not include GraphQL::Armory::Authorization::Base, so it is open")
19
+ @findings.problem(:unprotected, path, "its base class does not include GraphQL::Armory::Authorization::Base, so it is open", at: type)
20
20
  return
21
21
  end
22
22
 
23
23
  rule = type.armory_rule
24
24
  if rule.nil?
25
- @findings.problem(:no_rule, path, "has no rule and no default_action, so it is denied")
25
+ @findings.problem(:no_rule, path, "has no rule and no default_action, so it is denied", at: type)
26
26
  elsif rule.visible_when && (answer = graphql_ruby_answer(type, :visible?))
27
- @findings.problem(:ignored_rule, path, "graphql-ruby's #{answer} answers visible? here, so visible_when: never runs: remove it")
27
+ @findings.problem(:ignored_rule, path, "graphql-ruby's #{answer} answers visible? here, so visible_when: never runs: remove it", at: type)
28
28
  elsif rule.none?
29
- @findings.bypass(path, rule.reason)
29
+ @findings.bypass(path, rule.reason, at: type)
30
30
  audit_fields(type, model: nil, bypassed: !rule.covers_fields?, reported: Set.new)
31
31
  @foreign_policies.(type, rule.policy) if rule.policy
32
32
  elsif (answer = graphql_ruby_answer(type, :authorized?))
33
33
  @findings.problem(:ignored_rule, path, "graphql-ruby's #{answer} answers authorized? here, so this rule never runs: " \
34
34
  "put the rule on the field that returns it (on a root field, on a resolver: a field rule asks " \
35
- "the parent's policy), and declare `authorize :none, reason: \"...\", covers_fields: true` on this class")
35
+ "the parent's policy), and declare `authorize :none, reason: \"...\", covers_fields: true` on this class", at: type)
36
36
  else
37
37
  model = model_of(type, path)
38
38
  reported = Set.new
39
- check(path, model, rule, reported) if model
40
- check(path, model, Rule.new(rule.visible_when, policy: rule.policy), reported) if model && rule.visible_when
39
+ check(path, model, rule, reported, type) if model
40
+ check(path, model, Rule.new(rule.visible_when, policy: rule.policy), reported, type) if model && rule.visible_when
41
41
  @foreign_policies.(type, rule.policy) if rule.policy
42
42
  audit_fields(type, model: model, bypassed: false, reported: reported)
43
43
  end
@@ -64,14 +64,15 @@ module GraphQL
64
64
  def model_of(type, path)
65
65
  type.armory_model
66
66
  rescue ConfigurationError => error
67
- @findings.problem(:model, path, error.message)
67
+ @findings.problem(:model, path, error.message, at: type)
68
68
  nil
69
69
  end
70
70
 
71
- # An adapter problem shows once per type, however many fields declare an action of their own.
72
- def check(path, model, rule, reported)
71
+ # An adapter problem shows once per type, however many fields declare an action of their own. `at` is what declared
72
+ # the action: the type, a field, an argument or a resolver.
73
+ def check(path, model, rule, reported, at)
73
74
  @adapter.check(model, rule).each do |message|
74
- @findings.problem(:adapter, path, message) if reported.add?(message)
75
+ @findings.problem(:adapter, path, message, at: at) if reported.add?(message)
75
76
  end
76
77
  end
77
78
 
@@ -91,7 +92,7 @@ module GraphQL
91
92
  PlainResolvers.report(@findings, path, field) if served_with_no_rule?(type, field)
92
93
  if bypassed && !inherited && !field.respond_to?(:armory_declared)
93
94
  return @findings.problem(:field_without_rule, path, "its field class does not include Base, so no rule runs on it: its type is bypassed and graphql-ruby's own " \
94
- "authorized? answers true, so the field is served with no check. Use a field class that includes Base")
95
+ "authorized? answers true, so the field is served with no check. Use a field class that includes Base", at: field)
95
96
  end
96
97
  return unless field.respond_to?(:armory_declared)
97
98
  return audit_resolver(field, path) if field.resolver.respond_to?(:armory_rule)
@@ -116,7 +117,7 @@ module GraphQL
116
117
  return if field.owner.respond_to?(:armory_model) && owner_model(field.owner).equal?(model)
117
118
 
118
119
  @findings.problem(:foreign_model, path, "its rule is defined on #{name_of(field.owner)}, so it never asks the policy of #{model}, the model of this type: a record of another class " \
119
- "or a laxer subclass gets past it. Redefine the field on this type with its `authorize:` and an `override_reason:`, or name the same model on #{name_of(field.owner)}")
120
+ "or a laxer subclass gets past it. Redefine the field on this type with its `authorize:` and an `override_reason:`, or name the same model on #{name_of(field.owner)}", at: field)
120
121
  end
121
122
 
122
123
  def owner_model(owner)
@@ -138,41 +139,41 @@ module GraphQL
138
139
  # A RelayClassicMutation's field holds only the generated `input`: its arguments are on the resolver.
139
140
  arguments = (field.all_argument_definitions + resolver.all_argument_definitions).uniq
140
141
  @foreign_policies.arguments(arguments, path, rule.policy, Set.new) if rule&.policy
141
- return @findings.problem(:no_rule, path, "its mutation or resolver declares no `authorize`, so it is denied") if rule.nil?
142
+ return @findings.problem(:no_rule, path, "its mutation or resolver declares no `authorize`, so it is denied", at: resolver) if rule.nil?
142
143
  audit_arguments(arguments, path, reported: Set.new)
143
- return @findings.bypass(path, rule.reason) if rule.none?
144
+ return @findings.bypass(path, rule.reason, at: resolver) if rule.none?
144
145
 
145
146
  model = begin
146
147
  resolver.armory_model
147
148
  rescue ConfigurationError => error
148
- return @findings.problem(:model, path, error.message)
149
+ return @findings.problem(:model, path, error.message, at: resolver)
149
150
  end
150
- check(path, model, rule, Set.new)
151
+ check(path, model, rule, Set.new, resolver)
151
152
  end
152
153
 
153
154
  # The action a field is hidden with is asked of the policy like any other, so it must exist.
154
155
  def audit_visibility(field, path, model:, reported:)
155
156
  return unless model && field.armory_visible_when
156
157
 
157
- check(path.split(".").first, model, Rule.new(field.armory_visible_when, policy: field.armory_policy, attribute: field.original_name), reported)
158
+ check(path.split(".").first, model, Rule.new(field.armory_visible_when, policy: field.armory_policy, attribute: field.original_name), reported, field)
158
159
  end
159
160
 
160
161
  def audit_declaration(type, field, path, model:, bypassed:, reported:)
161
162
  case (declared = field.armory_declared)
162
163
  when :none
163
- @findings.bypass(path, field.armory_reason)
164
+ @findings.bypass(path, field.armory_reason, at: field)
164
165
  when nil, true
165
166
  if denied_payload_field?(field)
166
167
  @findings.problem(:field_without_rule, path, "declares no rule and #{name_of(field.owner)}, which defines it, has none that covers it, so the mutation runs and this field answers null: " \
167
- "a client cannot tell whether it worked. Give the field `authorize: :none, reason: \"...\"`, or use a shared `payload_type`; a public mutation adds `covers_fields: true`")
168
+ "a client cannot tell whether it worked. Give the field `authorize: :none, reason: \"...\"`, or use a shared `payload_type`; a public mutation adds `covers_fields: true`", at: field)
168
169
  elsif bypassed && declared.nil? && served_by_owner?(type, field)
169
170
  @findings.problem(:field_without_rule, path, "declares no rule and its type is bypassed, but it is inherited from #{field.owner.name || field.owner.inspect}: a field runs " \
170
- "under the class that defines it, and no rule ran on this type, so the field is served with no check. Give it authorize: where it is defined, or remove it")
171
+ "under the class that defines it, and no rule ran on this type, so the field is served with no check. Give it authorize: where it is defined, or remove it", at: field)
171
172
  elsif bypassed
172
- @findings.problem(:field_without_rule, path, "declares no rule and its type is bypassed, so it is denied")
173
+ @findings.problem(:field_without_rule, path, "declares no rule and its type is bypassed, so it is denied", at: field)
173
174
  end
174
175
  else
175
- check(path.split(".").first, model, Rule.new(declared, policy: field.armory_policy), reported) if model
176
+ check(path.split(".").first, model, Rule.new(declared, policy: field.armory_policy), reported, field) if model
176
177
  end
177
178
  end
178
179
 
@@ -199,7 +200,7 @@ module GraphQL
199
200
 
200
201
  apath = "#{path}(#{argument.keyword})"
201
202
  declared = argument.armory_declared
202
- @findings.bypass(apath, argument.armory_reason) if declared == :none
203
+ @findings.bypass(apath, argument.armory_reason, at: argument) if declared == :none
203
204
  [declared, argument.armory_visible_when].compact.reject { |action| action == :none }.each do |action|
204
205
  audit_argument_action(argument, apath, action, reported)
205
206
  end
@@ -207,9 +208,9 @@ module GraphQL
207
208
  end
208
209
 
209
210
  def audit_argument_action(argument, path, action, reported)
210
- check(path.split(".").first, argument.armory_model, Rule.new(action, policy: argument.armory_policy, attribute: argument.keyword), reported)
211
+ check(path.split(".").first, argument.armory_model, Rule.new(action, policy: argument.armory_policy, attribute: argument.keyword), reported, argument)
211
212
  rescue ConfigurationError => error
212
- @findings.problem(:model, path, error.message)
213
+ @findings.problem(:model, path, error.message, at: argument)
213
214
  end
214
215
 
215
216
  # A list that skips the scope hands over every record: a rule on each one hides its fields, not how many there are.
@@ -217,7 +218,7 @@ module GraphQL
217
218
  return if field.scoped? || generated_list?(type, field) || !list_of_records?(field)
218
219
 
219
220
  @findings.problem(:unscoped_list, path, "skips the user's scope, with scope: false or a list type graphql-ruby does not detect, so a refused user sees how many records it holds: " \
220
- "remove the option, or write the type as [Type]")
221
+ "remove the option, or write the type as [Type]", at: field)
221
222
  end
222
223
 
223
224
  # A connection applies the scope on the field that returns it, and graphql-ruby generates these two with scope: false.
@@ -253,8 +254,8 @@ module GraphQL
253
254
  argument.owner.equal?(field) ? scoped_field?(field) : field.resolver.respond_to?(:armory_rule)
254
255
  end
255
256
 
256
- opted_out_loads(arguments, Set.new).each do |name|
257
- @findings.problem(:unscoped_load, "#{path}(#{name})", "loads through the app's object_from_id, not through the user's scope")
257
+ opted_out_loads(arguments, Set.new).each do |name, argument|
258
+ @findings.problem(:unscoped_load, "#{path}(#{name})", "loads through the app's object_from_id, not through the user's scope", at: argument)
258
259
  end
259
260
  end
260
261
 
@@ -263,11 +264,11 @@ module GraphQL
263
264
  end
264
265
 
265
266
  # Execution::Next loads `loads:` nested in input objects with the field's loader, so a field's opt-out
266
- # reaches them too: list them as `filter.invoice_id`. `seen` stops recursive input types.
267
+ # reaches them too: list them as `filter.invoice_id`. `seen` stops recursive input types. Answers [name, argument].
267
268
  def opted_out_loads(arguments, seen, prefix = nil)
268
269
  arguments.flat_map do |argument|
269
270
  name = [prefix, GraphQL::Schema::Member::BuildType.underscore(argument.graphql_name)].compact.join(".")
270
- next [name] if argument.loads
271
+ next [[name, argument]] if argument.loads
271
272
 
272
273
  input = argument.type.unwrap
273
274
  next [] unless input.respond_to?(:kind) && input.kind.input_object? && seen.add?(input)
@@ -39,7 +39,7 @@ module GraphQL
39
39
  def note_type(type)
40
40
  return unless type.respond_to?(:armory_rule) && type.armory_rule&.visible_when && @seen.add?(type)
41
41
 
42
- report(type.graphql_name, model_problem { type.armory_model })
42
+ report(type.graphql_name, model_problem { type.armory_model }, type)
43
43
  end
44
44
 
45
45
  def note_field(field, path)
@@ -50,14 +50,14 @@ module GraphQL
50
50
  else
51
51
  "uses visible_when:, but what defines it cannot name a model, so a request that reads it raises: put it on an object type that includes Base"
52
52
  end
53
- report(path, problem)
53
+ report(path, problem, field)
54
54
  end
55
55
 
56
56
  def note_arguments(path, arguments)
57
57
  arguments.each do |argument|
58
58
  next unless argument.respond_to?(:armory_visible_when) && argument.armory_visible_when && @seen.add?(argument)
59
59
 
60
- report("#{path}(#{argument.keyword})", model_problem { argument.armory_model })
60
+ report("#{path}(#{argument.keyword})", model_problem { argument.armory_model }, argument)
61
61
  end
62
62
  end
63
63
 
@@ -66,8 +66,8 @@ module GraphQL
66
66
  field.owner.respond_to?(:kind) && field.owner.kind.interface? ? field.owner.graphql_name : type.graphql_name
67
67
  end
68
68
 
69
- def report(path, problem)
70
- @findings.problem(:model, path, problem) if problem && !@findings.problem?(:model, path)
69
+ def report(path, problem, at)
70
+ @findings.problem(:model, path, problem, at: at) if problem && !@findings.problem?(:model, path)
71
71
  end
72
72
 
73
73
  def model_problem
@@ -65,7 +65,7 @@ module GraphQL
65
65
  OwnChecks.(schema, definitions, findings)
66
66
  Overrides.(schema, definitions, findings)
67
67
  else
68
- findings.problem(:plugin, "Schema", "never installed the plugin: add `use GraphQL::Armory::Authorization, adapter: ...`")
68
+ findings.problem(:plugin, "Schema", "never installed the plugin: add `use GraphQL::Armory::Authorization, adapter: ...`", at: schema)
69
69
  end
70
70
 
71
71
  foreign_policies = ForeignPolicies.new(adapter, findings)
@@ -79,7 +79,7 @@ module GraphQL
79
79
  ObservedRules.(schema, definitions, findings)
80
80
  VisibilityModels.(schema, definitions, findings)
81
81
  IntrospectionFields.(schema, findings)
82
- findings.problem(:model, "Schema", listing_error.message) if listing_error && !findings.problem?(:model)
82
+ findings.problem(:model, "Schema", listing_error.message, at: schema) if listing_error && !findings.problem?(:model)
83
83
  findings.report(Reach.new(definitions))
84
84
  end
85
85
 
@@ -34,10 +34,13 @@ module GraphQL
34
34
  @armory_model = model
35
35
  @armory_visible_when = visible_when&.to_sym
36
36
  @armory_override_reason = override_reason
37
+ @armory_location = Location.declared
37
38
  Rule.none(reason: reason) if authorize == :none
38
39
  super(*args, **kwargs, &block)
39
40
  end
40
41
 
42
+ # Where the app declared this argument, for the audit.
43
+ attr_reader :armory_location
41
44
  attr_reader :armory_declared, :armory_reason, :armory_visible_when, :armory_override_reason
42
45
 
43
46
  def armory_model
@@ -35,11 +35,15 @@ module GraphQL
35
35
  @armory_reason = reason
36
36
  @armory_visible_when = visible_when&.to_sym
37
37
  @armory_load_through_scope = load_through_scope
38
+ # Before `super`, which runs the block that declares the field's arguments.
39
+ @armory_location = Location.declared
38
40
  Rule.none(reason: reason) if authorize == :none
39
41
  super(*args, **kwargs, &block)
40
42
  extension(Integration::FindBy, key: find_by) if find_by
41
43
  end
42
44
 
45
+ # Where the app declared this field, for the audit.
46
+ attr_reader :armory_location
43
47
  attr_reader :armory_declared, :armory_reason, :armory_observe, :armory_visible_when, :armory_override_reason
44
48
 
45
49
  def armory_load_through_scope?
@@ -14,9 +14,13 @@ module GraphQL
14
14
  end
15
15
 
16
16
  def authorize(action, reason: nil, **options)
17
+ @armory_rule_location = Location.declared
17
18
  @armory_rule = Rule.new(action, reason: reason, **options)
18
19
  end
19
20
 
21
+ # Where this class declared its own rule, for the audit; nil when it has none of its own.
22
+ attr_reader :armory_rule_location
23
+
20
24
  # Own rule, then an inherited one, then the default action. Nil means: nothing covers this type.
21
25
  def armory_rule
22
26
  return @armory_rule if @armory_rule
@@ -57,11 +61,11 @@ module GraphQL
57
61
  end
58
62
 
59
63
  def authorized?(object, context)
60
- rule = armory_rule
64
+ rule = Integration.type_rule(self, context)
61
65
  return false if rule.nil?
62
66
 
63
- Integration.refuse_unobservable(self, context) if rule.observed?
64
- Integration.allowed?(object, Integration.with_owner_model(rule, self), context) && super
67
+ Integration.refuse_unobservable(self, rule, context)
68
+ Integration.allowed?(object, rule, context) && super
65
69
  rescue GraphQL::UnauthorizedError
66
70
  raise
67
71
  rescue StandardError => error
@@ -24,9 +24,13 @@ module GraphQL
24
24
  raise ArgumentError, "observe: does not apply to a mutation or a resolver: what it runs cannot be undone" if options.key?(:observe)
25
25
 
26
26
  @armory_on_denied = on_denied
27
+ @armory_rule_location = Location.declared
27
28
  @armory_rule = Rule.new(action, reason: reason, **options)
28
29
  end
29
30
 
31
+ # Where this class declared its own rule, for the audit; nil when it has none of its own.
32
+ attr_reader :armory_rule_location
33
+
30
34
  def armory_rule
31
35
  @armory_rule || (superclass.armory_rule if superclass.respond_to?(:armory_rule))
32
36
  end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Authorization
6
+ module Integration
7
+ # Refuses an operation whose root type cannot be observed before anything runs. Inside the root type's own check,
8
+ # graphql-ruby hands the error to the app's `rescue_from`, which can turn it into an empty answer, and on the
9
+ # interpreter of graphql 2.6 its handling fails with a NoMethodError first. Raised here, it is the same
10
+ # ConfigurationError on every engine. The check in `Object#authorized?` stays for a query that runs with its own
11
+ # trace (`context[:trace]`).
12
+ module RootCheck
13
+ def execute_multiplex(multiplex:)
14
+ multiplex.queries.each { |query| RootCheck.(query) }
15
+ super
16
+ end
17
+
18
+ # A partial runs on its own type, not the operation's root, and is left to that type's check. An invalid query
19
+ # keeps its validation errors (and what a rate limiter charges for them).
20
+ def self.call(query)
21
+ return if defined?(GraphQL::Query::Partial) && query.is_a?(GraphQL::Query::Partial)
22
+
23
+ operation = query.selected_operation
24
+ return unless operation && query.valid?
25
+
26
+ # Query#root_type is graphql 2.5+; the schema answers the same on 2.4.
27
+ type = query.schema.root_type_for_operation(operation.operation_type || "query")
28
+ rule = type.armory_rule if type.respond_to?(:armory_rule)
29
+ Integration.refuse_unobservable(type, rule, query.context) if rule
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "graphql/armory/authorization/integration/schema"
4
+ require "graphql/armory/authorization/integration/root_check"
4
5
  require "graphql/armory/authorization/integration/object"
5
6
  require "graphql/armory/authorization/integration/find_by"
6
7
  require "graphql/armory/authorization/integration/field"
@@ -41,7 +42,7 @@ module GraphQL
41
42
  return Adapters::Null.new.scope(nil, items, rule) if rule.nil?
42
43
 
43
44
  configuration = configuration(context)
44
- Scope.(items, rule, context, adapter: configuration.adapter, sinks: configuration.sinks, on_sink_error: configuration.on_sink_error)
45
+ Scope.(items, rule, context, adapter: query_adapter(context), sinks: configuration.sinks, on_sink_error: configuration.on_sink_error)
45
46
  end
46
47
 
47
48
  # Looks an object up inside the user's scope, by primary key unless a key is given.
@@ -109,6 +110,16 @@ module GraphQL
109
110
  end
110
111
  end
111
112
 
113
+ # The rule a type checks its objects with, model included, worked out once per type per query: every item of a list
114
+ # asks it. Nil when nothing covers the type. A rule declared while a query runs applies from the next query.
115
+ def self.type_rule(type, context)
116
+ rules = context.namespace(:armory)[:type_rules] ||= {}.compare_by_identity
117
+ rules.fetch(type) do
118
+ rule = type.armory_rule
119
+ rules[type] = rule && with_owner_model(rule, type)
120
+ end
121
+ end
122
+
112
123
  # The rule with the model its owner wraps, the one the audit reads: named by the rule, or named like the type.
113
124
  def self.with_owner_model(rule, owner)
114
125
  return rule if rule.none? || rule.policy || rule.model || !owner.respond_to?(:armory_model)
@@ -125,14 +136,60 @@ module GraphQL
125
136
  private_class_method :declared_model
126
137
 
127
138
  # Observing a type opens the only check that stands before everything inside it, whatever class its fields are. A
128
- # resolver or a mutation can write, and a write cannot be undone, so a type holding one cannot be observed.
129
- def self.refuse_unobservable(type, context)
139
+ # resolver or a mutation can write, and a write cannot be undone, so a type holding one cannot be observed. Nor can
140
+ # a resolver field take an observed rule from the class that declared it (`authorize: true`). Both are refused
141
+ # here, at the type, because graphql-ruby prepares a field's arguments before the field's own check. Only what can
142
+ # run is read: a field a subclass overrides is not, unless the override is hidden from this user and the legacy
143
+ # Warden falls back to it.
144
+ def self.refuse_unobservable(type, rule, context)
130
145
  known = context.namespace(:armory)[:observable] ||= {}.compare_by_identity
131
- field = known.fetch(type) { known[type] = type.all_field_definitions.find(&:resolver) }
146
+ field = known.fetch(type) do
147
+ unobservable = ->(each) { each.resolver && (rule.observed? || observed_reason(each)) }
148
+ known[type] = live_fields(type, context, unobservable).find(&unobservable)
149
+ end
132
150
  return unless field
133
151
 
134
- raise ConfigurationError, "#{type.graphql_name} cannot be observed: its field #{field.graphql_name} has a resolver or a mutation, which can write. " \
135
- "Remove observe:, or put it on its plain fields"
152
+ if rule.observed?
153
+ raise ConfigurationError, "#{type.graphql_name} cannot be observed: its field #{field.graphql_name} has a resolver or a mutation, which can write. " \
154
+ "Remove observe:, or put it on its plain fields"
155
+ end
156
+
157
+ owner = field.owner.graphql_name
158
+ raise ConfigurationError, "#{type.graphql_name}.#{field.graphql_name} has a resolver or a mutation, which can write, so it cannot take the " \
159
+ "observed rule of #{owner} (#{observed_reason(field)}). Remove observe: from #{owner}, or give the field a rule of its own"
160
+ end
161
+
162
+ # The fields merged by name, plus, for each name whose shadowed definition would be refused, the definition the
163
+ # legacy Warden serves this user: it skips a hidden override and serves the parent's. Only those names are asked,
164
+ # so a type that is not observed, or has nothing shadowed to refuse, asks no policy and loads no field block.
165
+ # A Visibility profile never falls back.
166
+ def self.live_fields(type, context, unobservable)
167
+ fields = type.all_field_definitions
168
+ return fields if visibility_profile?(context)
169
+
170
+ levels = type.ancestors.select { |ancestor| ancestor.respond_to?(:own_fields) }
171
+ shadowed = levels.flat_map { |ancestor| ancestor.own_fields.values.flatten }.select(&unobservable) - fields
172
+ return fields if shadowed.empty?
173
+
174
+ served = shadowed.map(&:graphql_name).uniq.flat_map { |name| Array(type.get_field(name, context)) }
175
+ fields + served
176
+ end
177
+ private_class_method :live_fields
178
+
179
+ def self.visibility_profile?(context)
180
+ defined?(GraphQL::Schema::Visibility::Profile) && context.respond_to?(:types) &&
181
+ context.types.is_a?(GraphQL::Schema::Visibility::Profile)
182
+ end
183
+ private_class_method :visibility_profile?
184
+
185
+ # Why a field is observed: its own observe:, or `authorize: true` on an owner whose rule is observed. Nil when it is
186
+ # not. The audit asks the same question.
187
+ def self.observed_reason(field)
188
+ return field.armory_observe if field.respond_to?(:armory_observe) && field.armory_observe
189
+ return unless field.respond_to?(:armory_declared) && field.armory_declared == true
190
+
191
+ rule = field.owner.armory_rule if field.owner.respond_to?(:armory_rule)
192
+ rule.observe if rule&.observed?
136
193
  end
137
194
 
138
195
  # One Authorize per query: building it (and its memo and telemetry) once per object is pure overhead.
@@ -140,12 +197,29 @@ module GraphQL
140
197
  store = context.namespace(:armory)
141
198
  authorize = store[:authorize] ||= begin
142
199
  configuration = configuration(context)
143
- Authorize.build(context, adapter: configuration.adapter, sinks: configuration.sinks, on_sink_error: configuration.on_sink_error)
200
+ Authorize.build(context, adapter: query_adapter(context), sinks: configuration.sinks, on_sink_error: configuration.on_sink_error)
144
201
  end
145
202
 
146
203
  authorize.(subject, rule, context)
147
204
  end
148
205
 
206
+ # The adapter this query asks, shared by the checks and the scopes. The Pundit adapter, a subclass included, gets a
207
+ # copy of its own that remembers lookups for this query. Any other adapter is asked as configured: a wrapper around
208
+ # Pundit keeps its own answers, it only remembers nothing.
209
+ def self.query_adapter(context)
210
+ store = context.namespace(:armory)
211
+ store[:adapter] ||= begin
212
+ adapter = configuration(context).adapter
213
+ pundit?(adapter) ? adapter.per_query : adapter
214
+ end
215
+ end
216
+
217
+ # Never loads Pundit: while its adapter is not loaded, no adapter can be one.
218
+ def self.pundit?(adapter)
219
+ !Adapters.autoload?(:Pundit) && Adapters::Pundit === adapter
220
+ end
221
+ private_class_method :pundit?
222
+
149
223
  # Whether a type or field may appear in the schema this user sees. The question is asked of the
150
224
  # model's class, with no record, so the rule's action must be one a policy can answer that way.
151
225
  # `Schema.types` with no context sees the whole schema. A schema dump asks for it explicitly with
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Authorization
6
+ # Where something of the app's schema was written, as "path:line", for the audit's report. graphql-ruby keeps no
7
+ # location for a field or an argument, so the plugin's field and argument classes record the line that declared them,
8
+ # and a type records the line of its `authorize`. Anything else falls back to the line of its class, and a type
9
+ # graphql-ruby generated (a mutation's payload, a connection, an edge) to the class it was generated from.
10
+ #
11
+ # Limits: a schema built from SDL has no Ruby lines; a field declared by a helper method points to the helper; a class
12
+ # reopened in several files gives the first one.
13
+ module Location
14
+ GRAPHQL_RUBY_PATH = "#{File.dirname(GraphQL::Schema.method(:from_definition).source_location.first)}/"
15
+ ARMORY_PATH = "#{File.expand_path('..', __dir__)}/"
16
+ # The directory the app started in, read once: a later `Dir.chdir` must not change the report's text. None when the
17
+ # directory is gone, and then paths stay absolute.
18
+ ROOT = begin
19
+ "#{Dir.pwd}/"
20
+ rescue SystemCallError
21
+ nil
22
+ end
23
+
24
+ # The first line of the caller's stack outside graphql-ruby and this gem: where the app declared it. An `initialize`
25
+ # is skipped too: an app's field or argument class, or another gem's module, may define one that calls super into
26
+ # the plugin's, and its line is the same for every field.
27
+ def self.declared
28
+ found = caller_locations(2, 40)&.find do |location|
29
+ path = location.absolute_path || location.path
30
+ !path.start_with?("<", GRAPHQL_RUBY_PATH, ARMORY_PATH) && location.base_label != "initialize"
31
+ end
32
+ found && "#{found.absolute_path || found.path}:#{found.lineno}"
33
+ end
34
+
35
+ # "path:line" for a method, a field, an argument, a type or a class, relative to the directory the app started in
36
+ # when it is inside it, or nil when there is no line to give.
37
+ def self.of(thing)
38
+ relative(absolute(thing))
39
+ end
40
+
41
+ def self.absolute(thing)
42
+ case thing
43
+ when nil then nil
44
+ when String then thing
45
+ when Method, UnboundMethod then join(thing.source_location)
46
+ when GraphQL::Schema::Field, GraphQL::Schema::Argument
47
+ (thing.armory_location if thing.respond_to?(:armory_location)) || absolute(thing.owner)
48
+ when Module
49
+ (thing.armory_rule_location if thing.respond_to?(:armory_rule_location)) || constant(thing) || generated_from(thing)
50
+ end
51
+ end
52
+ private_class_method :absolute
53
+
54
+ # graphql-ruby generates some types as classes with no constant: a mutation's payload, and a type's connection and
55
+ # edge. They point to the class they were generated from, which was written somewhere.
56
+ # Only an object type is followed: a schema also answers `mutation`, with its root type. A connection of connections
57
+ # can lead back to itself, so each class is visited once, and the walk stops after a few steps.
58
+ def self.generated_from(type)
59
+ seen = {}.compare_by_identity
60
+ while type.is_a?(Class) && type < GraphQL::Schema::Object && !seen.key?(type) && seen.size < 16
61
+ seen[type] = true
62
+ source = type.mutation if type.respond_to?(:mutation)
63
+ source = nil unless source.is_a?(Class) && source < GraphQL::Schema::Resolver
64
+ source ||= type.node_type if type.respond_to?(:node_type)
65
+ return unless source.is_a?(Module)
66
+
67
+ found = (source.armory_rule_location if source.respond_to?(:armory_rule_location)) || constant(source)
68
+ return found if found
69
+
70
+ type = source
71
+ end
72
+ rescue StandardError, NotImplementedError
73
+ nil
74
+ end
75
+ private_class_method :generated_from
76
+
77
+ # Only when the name leads back to this class: a class may answer another constant's name. A location is never worth
78
+ # failing the audit, so a `name` that raises gives none.
79
+ def self.constant(mod)
80
+ name = mod.name
81
+ return if !name.is_a?(String) || name.empty? || !Object.const_get(name).equal?(mod)
82
+
83
+ join(Object.const_source_location(name))
84
+ rescue StandardError, NotImplementedError
85
+ nil
86
+ end
87
+ private_class_method :constant
88
+
89
+ def self.join(pair)
90
+ pair && !pair.empty? && pair.first ? "#{pair.first}:#{pair.last}" : nil
91
+ end
92
+ private_class_method :join
93
+
94
+ def self.relative(location)
95
+ return location if location.nil? || ROOT.nil?
96
+
97
+ location.start_with?(ROOT) ? location.delete_prefix(ROOT) : location
98
+ end
99
+ private_class_method :relative
100
+ end
101
+ end
102
+ end
103
+ end
@@ -32,6 +32,8 @@ module GraphQL
32
32
  raise ArgumentError, "observe: needs a text saying why this rule is observed, got #{observe.class}" unless observe.nil? || (observe.is_a?(String) && !observe.strip.empty?)
33
33
  raise ArgumentError, "observe: does not apply to a bypass, which refuses nothing" if observe && none?
34
34
 
35
+ # Every answer is remembered under its rule, once per item: the hash is computed once.
36
+ @hash = members.hash
35
37
  freeze
36
38
  end
37
39
 
@@ -67,9 +69,7 @@ module GraphQL
67
69
  end
68
70
  alias eql? ==
69
71
 
70
- def hash
71
- members.hash
72
- end
72
+ attr_reader :hash
73
73
 
74
74
  protected
75
75
 
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "graphql/armory/authorization/errors"
4
+ require "graphql/armory/authorization/location"
4
5
  require "graphql/armory/authorization/configuration"
5
6
  require "graphql/armory/authorization/rule"
6
7
  require "graphql/armory/authorization/memo"
@@ -42,6 +43,7 @@ module GraphQL
42
43
  def self.use(schema_defn, **options)
43
44
  schema_defn.extend(Integration::Schema)
44
45
  schema_defn.armory_configuration = Configuration.new(**options)
46
+ schema_defn.trace_with(Integration::RootCheck)
45
47
  end
46
48
  end
47
49
  end
@@ -10,8 +10,10 @@ module GraphQL
10
10
  # own: a refusal it returns or raises stands, and one that raises anything else cannot answer, so unless another refusal
11
11
  # stands the query is refused with QUERY_LIMIT_UNKNOWN. A multiplex analyzer cannot be asked again, so when the raise
12
12
  # stopped the visit before its end, a query of a multiplex with multiplex analyzers is refused the same way.
13
- # Only the analysis of an execution counts: an analysis the app runs itself takes no slot and charges nothing here. It
14
- # does not cover a trace that takes no modules from the schema (`context[:trace]`, or a class given to `trace_mode`).
13
+ # Only the analysis of an execution decides here. An analysis the app runs itself is not guarded: its limiters still
14
+ # charge and take a slot, and the execution charges again; what it answered is dropped when the execution's analysis
15
+ # starts. It does not cover a trace that takes no modules from the schema (`context[:trace]`, or a class given to
16
+ # `trace_mode`).
15
17
  module AnalysisGuard
16
18
  ANSWERS = :limiter_answers
17
19
  ASKED = :limiter_asked
@@ -21,6 +23,7 @@ module GraphQL
21
23
  REASK = :limiter_guard_reask
22
24
  RAISED = :limiter_guard_raised
23
25
  VISITED = :limiter_guard_visited
26
+ STALE = [ASKED, ANSWERS, VISITED, RAISED, :points, :time_charges].freeze
24
27
  NOT_CHARGED = "This query could not be charged to its rate limit."
25
28
  LIMIT_UNKNOWN = "The limits of this query could not be computed."
26
29
 
@@ -147,6 +150,10 @@ module GraphQL
147
150
  return reasked(state) { super } if state.delete(REASK)
148
151
  return super unless state.delete(ARMED)
149
152
 
153
+ # An analysis the app ran itself on this Query left its answers and its visit: the execution decides from its own.
154
+ # Time's debt from that analysis goes too, so a query the execution refuses is not charged for it. A Concurrency
155
+ # slot it took stays recorded, so that the end of the execution releases it.
156
+ STALE.each { |key| state.delete(key) }
150
157
  begin
151
158
  super
152
159
  rescue GraphQL::ExecutionError, GraphQL::UnauthorizedError => error
@@ -2,6 +2,6 @@
2
2
 
3
3
  module GraphQL
4
4
  module Armory
5
- VERSION = "0.1.0.pre10"
5
+ VERSION = "0.1.0.pre12"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: graphql-armory
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0.pre10
4
+ version: 0.1.0.pre12
5
5
  platform: ruby
6
6
  authors:
7
7
  - Israel
@@ -92,7 +92,9 @@ files:
92
92
  - lib/graphql/armory/authorization/integration/input_object.rb
93
93
  - lib/graphql/armory/authorization/integration/object.rb
94
94
  - lib/graphql/armory/authorization/integration/resolver.rb
95
+ - lib/graphql/armory/authorization/integration/root_check.rb
95
96
  - lib/graphql/armory/authorization/integration/schema.rb
97
+ - lib/graphql/armory/authorization/location.rb
96
98
  - lib/graphql/armory/authorization/memo.rb
97
99
  - lib/graphql/armory/authorization/rspec.rb
98
100
  - lib/graphql/armory/authorization/rule.rb