graphql-armory 0.1.0.pre13 → 0.1.0.pre14

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 (137) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +17 -0
  3. data/README.md +5 -5
  4. data/docs/authorization.md +4 -0
  5. data/docs/encrypted-ids.md +24 -2
  6. data/docs/persisted-queries.md +4 -0
  7. data/docs/rate-limiting.md +23 -0
  8. data/docs/response-caching.md +590 -0
  9. data/docs/subscriptions.md +261 -0
  10. data/docs/telemetry.md +39 -1
  11. data/docs/versioning.md +4 -0
  12. data/lib/graphql/armory/authorization/authorize.rb +3 -0
  13. data/lib/graphql/armory/authorization/scope.rb +2 -0
  14. data/lib/graphql/armory/caching/audit/command.rb +51 -0
  15. data/lib/graphql/armory/caching/audit/context_class.rb +117 -0
  16. data/lib/graphql/armory/caching/audit/declarations.rb +166 -0
  17. data/lib/graphql/armory/caching/audit/own_checks.rb +150 -0
  18. data/lib/graphql/armory/caching/audit/public_rules.rb +158 -0
  19. data/lib/graphql/armory/caching/audit/report.rb +113 -0
  20. data/lib/graphql/armory/caching/audit.rb +136 -0
  21. data/lib/graphql/armory/caching/base.rb +118 -0
  22. data/lib/graphql/armory/caching/canonical.rb +138 -0
  23. data/lib/graphql/armory/caching/charge.rb +86 -0
  24. data/lib/graphql/armory/caching/codec.rb +108 -0
  25. data/lib/graphql/armory/caching/context_methods.rb +88 -0
  26. data/lib/graphql/armory/caching/controls/app_schema.rb +70 -0
  27. data/lib/graphql/armory/caching/controls/context.rb +30 -0
  28. data/lib/graphql/armory/caching/controls/operations.rb +37 -0
  29. data/lib/graphql/armory/caching/controls/schema.rb +123 -0
  30. data/lib/graphql/armory/caching/controls/store.rb +16 -0
  31. data/lib/graphql/armory/caching/controls/walk_schema.rb +197 -0
  32. data/lib/graphql/armory/caching/controls.rb +19 -0
  33. data/lib/graphql/armory/caching/digester.rb +48 -0
  34. data/lib/graphql/armory/caching/errors.rb +16 -0
  35. data/lib/graphql/armory/caching/gate/admission.rb +67 -0
  36. data/lib/graphql/armory/caching/gate/signals.rb +65 -0
  37. data/lib/graphql/armory/caching/gate/store_check.rb +60 -0
  38. data/lib/graphql/armory/caching/gate/substitute.rb +61 -0
  39. data/lib/graphql/armory/caching/gate.rb +384 -0
  40. data/lib/graphql/armory/caching/integration/guard.rb +55 -0
  41. data/lib/graphql/armory/caching/integration/install.rb +262 -0
  42. data/lib/graphql/armory/caching/integration/query.rb +42 -0
  43. data/lib/graphql/armory/caching/integration.rb +141 -0
  44. data/lib/graphql/armory/caching/keyer.rb +208 -0
  45. data/lib/graphql/armory/caching/memory_store.rb +164 -0
  46. data/lib/graphql/armory/caching/nulls.rb +121 -0
  47. data/lib/graphql/armory/caching/purge.rb +98 -0
  48. data/lib/graphql/armory/caching/record_keys.rb +109 -0
  49. data/lib/graphql/armory/caching/recorder/context.rb +178 -0
  50. data/lib/graphql/armory/caching/recorder/log.rb +142 -0
  51. data/lib/graphql/armory/caching/recorder/null.rb +24 -0
  52. data/lib/graphql/armory/caching/recorder/shared_writes.rb +58 -0
  53. data/lib/graphql/armory/caching/recorder/substitute.rb +119 -0
  54. data/lib/graphql/armory/caching/recorder.rb +34 -0
  55. data/lib/graphql/armory/caching/redis_store/scripts.rb +159 -0
  56. data/lib/graphql/armory/caching/redis_store.rb +162 -0
  57. data/lib/graphql/armory/caching/rspec.rb +25 -0
  58. data/lib/graphql/armory/caching/schema_identity.rb +102 -0
  59. data/lib/graphql/armory/caching/store/null.rb +31 -0
  60. data/lib/graphql/armory/caching/store/substitute.rb +144 -0
  61. data/lib/graphql/armory/caching/store.rb +34 -0
  62. data/lib/graphql/armory/caching/tags.rb +39 -0
  63. data/lib/graphql/armory/caching/values/decision.rb +45 -0
  64. data/lib/graphql/armory/caching/values/declaration.rb +114 -0
  65. data/lib/graphql/armory/caching/values/entry.rb +108 -0
  66. data/lib/graphql/armory/caching/values/key.rb +39 -0
  67. data/lib/graphql/armory/caching/values/lookup.rb +35 -0
  68. data/lib/graphql/armory/caching/values/policy.rb +44 -0
  69. data/lib/graphql/armory/caching/viewer.rb +112 -0
  70. data/lib/graphql/armory/caching/walk/directives.rb +45 -0
  71. data/lib/graphql/armory/caching/walk/relay.rb +54 -0
  72. data/lib/graphql/armory/caching/walk/run.rb +130 -0
  73. data/lib/graphql/armory/caching/walk/tally.rb +38 -0
  74. data/lib/graphql/armory/caching/walk.rb +46 -0
  75. data/lib/graphql/armory/caching.rb +69 -0
  76. data/lib/graphql/armory/encoder/legacy.rb +14 -0
  77. data/lib/graphql/armory/encoder/null.rb +14 -1
  78. data/lib/graphql/armory/encoder/substitute.rb +54 -2
  79. data/lib/graphql/armory/encoder/versioned.rb +36 -0
  80. data/lib/graphql/armory/encoder.rb +80 -1
  81. data/lib/graphql/armory/persisted_queries.rb +8 -1
  82. data/lib/graphql/armory/rate_limits/cached_charge.rb +43 -0
  83. data/lib/graphql/armory/rate_limits/concurrency.rb +12 -5
  84. data/lib/graphql/armory/rate_limits/invalid_queries.rb +3 -2
  85. data/lib/graphql/armory/rate_limits/points.rb +21 -9
  86. data/lib/graphql/armory/rate_limits/time.rb +15 -8
  87. data/lib/graphql/armory/rate_limits.rb +9 -0
  88. data/lib/graphql/armory/subscriptions/ably/key.rb +49 -0
  89. data/lib/graphql/armory/subscriptions/ably/publisher.rb +132 -0
  90. data/lib/graphql/armory/subscriptions/ably/token_request.rb +42 -0
  91. data/lib/graphql/armory/subscriptions/ably/webhook.rb +96 -0
  92. data/lib/graphql/armory/subscriptions/ably.rb +126 -0
  93. data/lib/graphql/armory/subscriptions/audit.rb +92 -0
  94. data/lib/graphql/armory/subscriptions/controls/dependencies.rb +37 -0
  95. data/lib/graphql/armory/subscriptions/controls/event_log.rb +30 -0
  96. data/lib/graphql/armory/subscriptions/controls/id.rb +26 -0
  97. data/lib/graphql/armory/subscriptions/controls/record.rb +34 -0
  98. data/lib/graphql/armory/subscriptions/controls/schema.rb +187 -0
  99. data/lib/graphql/armory/subscriptions/controls/viewer.rb +99 -0
  100. data/lib/graphql/armory/subscriptions/controls.rb +19 -0
  101. data/lib/graphql/armory/subscriptions/core/channels.rb +93 -0
  102. data/lib/graphql/armory/subscriptions/core/clock.rb +40 -0
  103. data/lib/graphql/armory/subscriptions/core/controls.rb +29 -0
  104. data/lib/graphql/armory/subscriptions/core/delivery.rb +250 -0
  105. data/lib/graphql/armory/subscriptions/core/settings.rb +182 -0
  106. data/lib/graphql/armory/subscriptions/core/trigger.rb +63 -0
  107. data/lib/graphql/armory/subscriptions/core/viewer.rb +153 -0
  108. data/lib/graphql/armory/subscriptions/core/write.rb +172 -0
  109. data/lib/graphql/armory/subscriptions/core.rb +200 -0
  110. data/lib/graphql/armory/subscriptions/errors.rb +30 -0
  111. data/lib/graphql/armory/subscriptions/http/null.rb +17 -0
  112. data/lib/graphql/armory/subscriptions/http/substitute.rb +56 -0
  113. data/lib/graphql/armory/subscriptions/http.rb +93 -0
  114. data/lib/graphql/armory/subscriptions/memory_store.rb +115 -0
  115. data/lib/graphql/armory/subscriptions/pusher/signature.rb +45 -0
  116. data/lib/graphql/armory/subscriptions/pusher.rb +192 -0
  117. data/lib/graphql/armory/subscriptions/redis_store/scripts.rb +115 -0
  118. data/lib/graphql/armory/subscriptions/redis_store.rb +157 -0
  119. data/lib/graphql/armory/subscriptions/store/null.rb +23 -0
  120. data/lib/graphql/armory/subscriptions/store/substitute.rb +155 -0
  121. data/lib/graphql/armory/subscriptions/store.rb +38 -0
  122. data/lib/graphql/armory/subscriptions/topic.rb +253 -0
  123. data/lib/graphql/armory/subscriptions/transport/null.rb +28 -0
  124. data/lib/graphql/armory/subscriptions/transport/substitute.rb +150 -0
  125. data/lib/graphql/armory/subscriptions/transport.rb +41 -0
  126. data/lib/graphql/armory/subscriptions/values/capabilities.rb +50 -0
  127. data/lib/graphql/armory/subscriptions/values/message.rb +31 -0
  128. data/lib/graphql/armory/subscriptions/values/outcome.rb +42 -0
  129. data/lib/graphql/armory/subscriptions/values/record.rb +176 -0
  130. data/lib/graphql/armory/subscriptions/webhook_app.rb +31 -0
  131. data/lib/graphql/armory/subscriptions.rb +33 -0
  132. data/lib/graphql/armory/telemetry.rb +8 -4
  133. data/lib/graphql/armory/version.rb +1 -1
  134. data/lib/graphql/armory/versioning/integration.rb +2 -1
  135. data/lib/graphql/armory.rb +2 -0
  136. data/lib/tasks/graphql_armory.rake +9 -0
  137. metadata +110 -1
@@ -0,0 +1,261 @@
1
+ # Subscriptions over hosted pub/sub
2
+
3
+ Run graphql-ruby subscriptions over a hosted pub/sub service (Pusher, Ably, or anything with the same shape) without
4
+ letting one subscriber's update reach another, and without a provider SDK.
5
+
6
+ ## The problem
7
+
8
+ graphql-ruby ships an abstract `GraphQL::Subscriptions` backend and an in-process ActionCable one. A backend for a
9
+ hosted service has to decide what to store, whose context an update runs with and who receives the result, and the
10
+ base class's defaults are unsafe for an app with more than one user:
11
+
12
+ - `trigger(..., context: { current_user: admin })` merges that context over every subscriber's own, so each
13
+ subscriber's update runs as the trigger's caller (or under the trigger's API version).
14
+ - Topics are built by joining the field name and argument values with `":"`, unescaped: `room(id: "5:thread:9")` and
15
+ `room(id: "5", thread: "9")` share a topic, and so do the scopes `1` and `"1"`.
16
+ - A subscriber whose `authorized?` check fails on an update gets an error and stays subscribed, so a user who lost
17
+ access keeps a live subscription.
18
+ - A field marked `broadcastable: true` runs once and sends the first subscriber's answer to everyone on the topic,
19
+ whoever they are.
20
+
21
+ On a hosted service there is more: the subscription id is the channel name, so anyone who learns it can listen
22
+ unless the channel is bound to its viewer; no provider tells you reliably when a client is gone; and each provider
23
+ has its own message size limit, from 10 KB on Pusher to 64 or 256 KiB on Ably.
24
+
25
+ ## The solution
26
+
27
+ `GraphQL::Armory::Subscriptions` is a `GraphQL::Subscriptions` backend made of a provider-agnostic core, a store and
28
+ a transport.
29
+
30
+ - **Each delivery runs as its subscriber.** The core stores the subscription as a record sealed with your
31
+ `Encoder`: the document, its variables (as plain JSON, never graphql-ruby's `Serialize`, so a client's `__gid__`
32
+ key is never located), the viewer's id, the API version Versioning decided, the persisted
33
+ operation id and only the context keys you list in `context_keys:`. On a trigger it rebuilds each subscriber's
34
+ context from that record, reloads the viewer with your `viewer: { load: }`, and runs the document through your
35
+ schema's query class, on the engine that created the subscription. Authorization, Versioning and
36
+ PersistedQueries decide it like a request. The trigger's context is never merged: `trigger(..., context: {...})`
37
+ raises.
38
+ - **A subscriber who loses access is unsubscribed.** If the update has no `data`, or its root field is null (a
39
+ denied root with `on_unauthorized: :null`, the default, answers null without an error), the subscriber gets that
40
+ last result with `more: false` and the subscription is deleted. A viewer that no longer loads ends the same way.
41
+ - **Topics cannot collide.** A topic is a keyed digest of a canonical JSON of the field, its arguments taken
42
+ through their definitions (so `5` and `"5"` for an `ID` meet, an enum by Ruby value and by name meet, defaults are
43
+ filled) and a type-tagged scope (`1` and `"1"` differ).
44
+ - **Nothing is broadcast.** Every subscriber is executed with its own context.
45
+ - **Channels are bound to their viewer.** The transport names a channel from the subscription id (and, on Ably, the
46
+ viewer's digest). The core authorizes a channel only for the viewer that created it, compared in constant time,
47
+ and only then does the transport sign the provider's auth answer. The id is built by the server; a client that sets
48
+ `context[:subscription_id]` is refused.
49
+ - **Every subscription ends.** `max_lifetime:` is required. Provider webhooks (Pusher `channel_vacated`, Ably
50
+ presence `leave`), verified in constant time and refused when dated more than 5 minutes before or after now, end one
51
+ sooner.
52
+ - **Deliveries are not rate-charged.** A delivery is marked in `context.namespace(:armory)`, which a request cannot
53
+ write, and RateLimits charges no budget for it, so someone who causes triggers cannot spend another user's budget.
54
+ `max_complexity` and `max_depth` still apply, and caps bound the work: `max_per_viewer:`, `max_per_topic:` and
55
+ `max_executions_per_trigger:`.
56
+
57
+ Transports declare their capabilities: whether they can bind a channel to a viewer, the largest message, the largest
58
+ batch, their webhooks and compression. With a `viewer:`, `use` refuses a transport that cannot bind channels.
59
+
60
+ ## How to use it
61
+
62
+ ```ruby
63
+ class AppSchema < GraphQL::Schema
64
+ subscription Types::Subscription
65
+
66
+ use GraphQL::Armory::Authorization, adapter: :pundit
67
+ use GraphQL::Armory::Subscriptions,
68
+ store: GraphQL::Armory::Subscriptions::RedisStore.build(redis: Redis.new, prefix: "app:{subscriptions}:"),
69
+ transport: GraphQL::Armory::Subscriptions::Pusher.build(
70
+ app_id: ENV["PUSHER_APP_ID"], key: ENV["PUSHER_KEY"], secret: ENV["PUSHER_SECRET"], cluster: "eu"
71
+ ),
72
+ encoder: AppEncoder, # an Encoder subclass: seals records, keys digests
73
+ viewer: {
74
+ dump: ->(context) { context[:current_user]&.to_gid&.to_s },
75
+ load: ->(id, context) { context[:current_user] = GlobalID::Locator.locate(id) },
76
+ sets: [:current_user] # the context keys load sets (a subscription_scope may use them)
77
+ },
78
+ context_keys: { tenant_id: "scopes every query to the subscriber's tenant" },
79
+ max_lifetime: 24 * 3600
80
+ end
81
+ ```
82
+
83
+ The subscribe request is an ordinary GraphQL request. Send the channel back so the client can listen:
84
+
85
+ ```ruby
86
+ result = AppSchema.execute(query, variables:, context:)
87
+ channel = AppSchema.subscriptions.channel_for(result.query)
88
+ response.headers["X-Subscription-ID"] = channel if channel
89
+ ```
90
+
91
+ Trigger from your code, with no context:
92
+
93
+ ```ruby
94
+ AppSchema.subscriptions.trigger(:message_posted, { room_id: room.id }, message, scope: tenant.id)
95
+ AppSchema.subscriptions.trigger(:message_posted, { room_id: room.id }, message, version: "2025-01-01") # with Versioning default: :refuse
96
+ ```
97
+
98
+ Mount the webhook endpoint and run cleanup periodically:
99
+
100
+ ```ruby
101
+ mount GraphQL::Armory::Subscriptions::WebhookApp.new(AppSchema), at: "/graphql/webhooks"
102
+ AppSchema.subscriptions.cleanup # from a periodic job
103
+ ```
104
+
105
+ On the client, the MIT `graphql-ruby-client` links work unchanged: they read `X-Subscription-ID`, listen for the
106
+ `update` event and read `{ result | compressed_result, more }`.
107
+
108
+ ### Pusher
109
+
110
+ ```ruby
111
+ GraphQL::Armory::Subscriptions::Pusher.build(
112
+ app_id: ENV["PUSHER_APP_ID"], key: ENV["PUSHER_KEY"], secret: ENV["PUSHER_SECRET"],
113
+ cluster: "eu", # or host: "soketi.internal:6001", scheme: "http" for a Pusher-compatible server
114
+ prefix: "graphql", # channels are private-<prefix>-<subscription id>
115
+ compress: false # true when the client decompresses compressed_result
116
+ )
117
+ ```
118
+
119
+ Every subscription gets a private channel. `pusher-js` asks your auth endpoint for it:
120
+
121
+ ```ruby
122
+ post "/pusher/auth" do
123
+ auth = AppSchema.subscriptions.authorize_channel(
124
+ channel: params[:channel_name], socket_id: params[:socket_id], context: current_context
125
+ )
126
+ auth ? render(json: auth) : head(:forbidden)
127
+ end
128
+ ```
129
+
130
+ Build `current_context` exactly as your GraphQL endpoint does: the channel is authorized only when its viewer is the
131
+ requester. In the Pusher dashboard, enable the `channel_vacated` webhook and point it at the `WebhookApp`. On the
132
+ client use `PusherLink` (pass it `decompress` with `compress: true`).
133
+
134
+ Limits: 10 KB per event (the compressed form is measured when compression is on) and 10 events per publish. Pusher
135
+ sends `channel_vacated` about 3 seconds after the last client leaves and retries for 5 minutes.
136
+
137
+ ### Ably
138
+
139
+ ```ruby
140
+ GraphQL::Armory::Subscriptions::Ably.build(
141
+ key: ENV.fetch("ABLY_KEY"), # "<appId>.<keyId>:<secret>", with only the publish capability on <prefix>:*
142
+ prefix: "graphql",
143
+ max_payload_bytes: 65_536 # up to 262_144 on plans that allow it
144
+ )
145
+ ```
146
+
147
+ Ably authorizes a connection, not a channel, so a channel is `<prefix>:<viewer digest>:<id>` and your token endpoint
148
+ answers a TokenRequest whose capability is the viewer's own channels only (`presence` and `subscribe`), with the viewer
149
+ digest as its `clientId` (`"anonymous"` in anonymous mode), which Ably's presence, and so the leave webhook, needs:
150
+
151
+ ```ruby
152
+ post "/ably/auth" do
153
+ token = AppSchema.subscriptions.authorize_viewer(context: current_context)
154
+ token ? render(json: token) : head(:unauthorized)
155
+ end
156
+ ```
157
+
158
+ ```js
159
+ const ably = new Ably.Realtime({ authUrl: "/ably/auth", authMethod: "POST" })
160
+ const link = new AblyLink({ ably })
161
+ ```
162
+
163
+ The browser never receives the key. Add a webhook integration for presence events on `<prefix>:*` pointing at the
164
+ `WebhookApp`: a presence `leave` on a subscription channel ends it.
165
+
166
+ Limits: 64 KiB per message (256 KiB on plans that allow it); a batch stays under Ably's 2 MiB request limit, which is
167
+ 15 messages at 64 KiB. A leave arrives about 15 seconds late. A token lasts at most one hour.
168
+
169
+ ### Stores
170
+
171
+ A store holds sealed records and indexes of topic and viewer digests, never a document, a variable or a viewer in
172
+ clear. `MemoryStore.new` keeps everything in one process: for tests, development and single-process servers.
173
+ `RedisStore.build(redis:, prefix:)` is for production: each operation is one Lua script, so the caps hold across
174
+ processes. Times are the caller's clock, so clock skew between your servers and Redis never decides whether a
175
+ subscription is live. Use a Redis with `noeviction` or `volatile-*`. On Redis Cluster the prefix needs a hash tag,
176
+ such as `"app:{subscriptions}:"`. Call `cleanup` periodically: it frees the expiry index.
177
+
178
+ ### The audit
179
+
180
+ ```ruby
181
+ GraphQL::Armory::Subscriptions::Audit.call(AppSchema)
182
+ ```
183
+
184
+ It reports subscription fields marked `broadcastable: true` (ignored), anonymous mode, and every `context_keys:`
185
+ entry with its reason.
186
+
187
+ ## Reference
188
+
189
+ `use GraphQL::Armory::Subscriptions, ...` (`Subscriptions.build(schema, ...)` answers the backend without installing
190
+ it; `Subscriptions.new` is inert: it stores, delivers and authorizes nothing).
191
+
192
+ | Option | Default | |
193
+ |---|---|---|
194
+ | `store:` | required | `MemoryStore` or `RedisStore`; `Store::Null` is refused |
195
+ | `transport:` | required | `Pusher`, `Ably` or your own; `Transport::Null` is refused |
196
+ | `encoder:` | required | an `Encoder` subclass |
197
+ | `max_lifetime:` | required | seconds a subscription lives at most |
198
+ | `viewer:` | | `{ dump: ->(context) { id String }, load: ->(id, context) { ... }, sets: [keys load sets] }` |
199
+ | `anonymous:`, `cap_key:` | | instead of `viewer:`: a reason no subscription depends on the viewer, and a callable answering what the per-client cap counts by (the client IP) |
200
+ | `context_keys:` | `{}` | `{ key: "reason" }`: the only context values stored and restored; values must round-trip through graphql-ruby's `Serialize`. `armory_version`, `operation_id`, `armory_allow_raw_query`, `visibility_profile` and `subscription_id` are reserved |
201
+ | `max_per_viewer:` | 100 | live subscriptions per viewer (or per `cap_key`) |
202
+ | `max_per_topic:` | 10_000 | live subscriptions per topic |
203
+ | `max_executions_per_trigger:` | 10_000 | subscribers executed per trigger, from a random start so repeated triggers reach every subscriber; the rest are skipped and recorded |
204
+ | `on_delivery_error:` | `:record` | `:raise` raises after the whole topic was processed |
205
+ | `sinks:`, `on_sink_error:` | | [Telemetry](telemetry.md#subscriptions) |
206
+
207
+ `use` refuses: unknown options, `broadcast:`, `default_broadcastable:`, `validate_update:`, a viewer with a transport
208
+ that cannot bind channels, a Subscription class overriding `topic_for`, subscription arguments with `loads:` or
209
+ `prepare:`, and a `subscription_scope` key that is neither in `context_keys:` nor in `viewer: { sets: }`.
210
+
211
+ Methods on `AppSchema.subscriptions`: `trigger(event, args, object, scope: nil, version: nil)`, `channel_for(query)`,
212
+ `authorize_channel(channel:, socket_id:, context:)`, `authorize_viewer(context:)`, `webhook(env)`,
213
+ `cleanup(now: nil)`, `delete_subscription(id)`.
214
+
215
+ Error codes a client can read: `SUBSCRIPTION_LIMIT` (a cap), `SUBSCRIPTION_REFUSED` (anything else refused at
216
+ subscribe), and `RESULT_TOO_LARGE` in an update whose result does not fit the transport (the client should refetch).
217
+
218
+ ## Guarantees and limits
219
+
220
+ Guaranteed:
221
+
222
+ 1. A delivery runs with the subscriber's stored keys and reloaded viewer, never the trigger's context.
223
+ 2. Different fields, arguments or scopes never share a topic.
224
+ 3. A subscriber whose update has no data or a null root field is unsubscribed, at the next trigger.
225
+ 4. A subscriber's result goes to that subscriber's channel only.
226
+ 5. With a viewer, a channel is authorized only for the viewer that created it.
227
+ 6. A client cannot choose its subscription id.
228
+ 7. A stored record that was tampered with is deleted, never loaded.
229
+ 8. Every subscription ends by `max_lifetime`.
230
+ 9. A delivery never charges the subscriber's rate-limit budget.
231
+
232
+ Limits:
233
+
234
+ - Between a permission change and the next trigger, nothing is sent, but the subscription exists.
235
+ - A viewer its policy refuses can still create a subscription (there is no object to check yet): it counts against
236
+ `max_per_viewer:` and `max_per_topic:` until the first trigger ends it.
237
+ - A nested null (one hidden field) does not end a subscription; only the root field decides.
238
+ - A null root field ends the subscription, so a trigger whose object one subscriber may not see ends that
239
+ subscriber. To keep it, authorize each event in the subscription's `update` and skip the ones it may not see:
240
+
241
+ ```ruby
242
+ def update(**)
243
+ MessagePolicy.new(context[:current_user], object).show? ? object : NO_UPDATE
244
+ end
245
+ ```
246
+ - Channel auth is as strong as your auth endpoint: it must build the context as your GraphQL endpoint does.
247
+ - Webhooks are lossy and late (about 3 seconds on Pusher, 15 on Ably); `max_lifetime` is what bounds a subscription.
248
+ - An expired subscription gets `{ more: false }` only if a trigger reaches it before `cleanup` removes it; after
249
+ that it just stops.
250
+ - Triggers run in the calling process and synchronously: the request that triggers pays for every subscriber's
251
+ execution, one execution per subscriber.
252
+ - A result larger than the transport's limit is replaced with `RESULT_TOO_LARGE`, never truncated.
253
+ - Subscription arguments with `loads:` or `prepare:` are not supported.
254
+ - Install it on the schema that executes: graphql-ruby shares one backend with child schemas.
255
+ - A subscription's variables must come back the same from JSON: a `Date`, a `Symbol` or another object your own code
256
+ passes as a variable is refused with `SUBSCRIPTION_REFUSED`.
257
+ - `trigger` with a single value for a list argument raises graphql-ruby's own `NoMethodError`: pass a list.
258
+ - The engine a delivery runs on is the one `context[:__graphql_execute_next]` named at subscribe, which graphql-ruby
259
+ sets on `Execution::Next`. An app that copies client input into the context could let a client choose the engine
260
+ its deliveries run on; Authorization applies on both.
261
+ - No ActionCable or AnyCable transport, no broadcast, no Ably end-to-end encryption.
data/docs/telemetry.md CHANGED
@@ -114,6 +114,10 @@ end
114
114
 
115
115
  The sink reads the context through a view that answers `[]`, `fetch`, `dig` and `key?`, and cannot write to it, so a sink cannot change who the query runs as. An object held in the context is your own, and a sink can still change that. The view is empty when the query has none. A sink that takes two arguments, `*arguments` or a defaulted third never receives it, so a sink that logs what it gets does not start logging tokens. What you read from the context is yours to keep out of logs.
116
116
 
117
+ ### With response caching
118
+
119
+ Sinks run inside `GraphQL::Armory::Caching.neutral`: what a sink reads from the context, such as a request id to log, does not count as an input of the answer, so it never keeps [response caching](response-caching.md) from storing one. The same key read by your own resolvers still counts, and so does a read through a view a sink kept and reads after it returned. Your own tracers and loggers can read the same way with `Caching.neutral(context) { ... }`; keep it to reads that cannot change `data`.
120
+
117
121
  ### What to watch for
118
122
 
119
123
  | You see | It usually means | What to do |
@@ -124,6 +128,8 @@ The sink reads the context through a view that answers `[]`, `fetch`, `dig` and
124
128
  | `operation_refused` with `reason: :raw_query` from one client | A client sending raw queries to a strict endpoint: a probe, or a client not migrated yet. Strict mode refuses before validating, so a detector that counts validation errors does not see it | Count it as a strike. See [Counting probes in strict mode](persisted-queries.md#counting-probes-in-strict-mode) |
125
129
  | `raw_query_run` while you are in `strict: false` | Traffic that does not use persisted queries yet | When it reaches zero, turn on `strict: true` |
126
130
  | `denied` rising for one `type` | A new or changed policy for that type | Compare with the release; the [audit](authorization.md#the-audit) lists the types and actions the rules cover |
131
+ | `cache_skipped` with `reason: :context_read` | A run read a context key the cache key does not hold, so its answer was not stored. The signal's `key` names it | Put the input in `vary:` if it changes the answer, or in `neutral_keys:` if it never does. See [Inputs you must declare](response-caching.md#inputs-you-must-declare) |
132
+ | `cache_entry_rejected` rising, or `cache_store_failed` | A store entry that fails a check (`:decrypt` after a key rotation or a foreign writer, `:epoch` after a reset), or a store that raises | A few after a deploy or rotation are normal. A burst of `:decrypt` with no rotation means something else writes the store, or another app shares its prefix. On `cache_store_failed` the queries ran uncached |
127
133
 
128
134
  ## Signals
129
135
 
@@ -166,6 +172,37 @@ The reasons of `:id_refused`:
166
172
 
167
173
  `:raw_query_allowed` is your audit trail of who uses the escape hatch (staff, development).
168
174
 
175
+ ### Response caching
176
+
177
+ | Signal | When | Data |
178
+ |---|---|---|
179
+ | `:cache_hit` | An answer was served from the store | `scope` |
180
+ | `:cache_stored` | A miss ran and its answer was stored | `scope`, `ttl` |
181
+ | `:cache_skipped` | A query was not cacheable, or a miss was not stored | `reason`; `key` only for `:context_read` and `:context_written` |
182
+ | `:cache_entry_rejected` | A stored entry failed a check and the query ran | `reason`: `:format`, `:key`, `:decrypt`, `:expired`, `:epoch`, `:tags`, `:purged` or `:cost_unknown` |
183
+ | `:cache_store_failed` | The store raised, so the query ran uncached | `operation`: `:lookup`, `:write` or `:purge`; `error`: the error's class name |
184
+ | `:cache_purged` | `Caching.purge` succeeded | `kind`: `:all`, `:viewer`, `:tag` or `:type`; `type` for `:type` |
185
+
186
+ The reasons of `:cache_skipped` are listed in [Response caching](response-caching.md#reasons). `key` is a name your own code gave a context key, never something a client sent, and the signal never holds the tag or the viewer of a purge. What the cache did for one query is also in `context[:response_cache]` (`{ status:, reason:, scope:, ttl:, age: }`), for your controller or log.
187
+
188
+ ### Subscriptions
189
+
190
+ | Signal | When | Data |
191
+ |---|---|---|
192
+ | `:subscription_created` | A subscription was stored | `engine`, `events` (how many topics) |
193
+ | `:subscription_refused` | A subscribe request was refused | `reason`, such as `:viewer_cap`, `:topic_cap`, `:client_id`, `:context` or `:variables` |
194
+ | `:subscription_delivered` | An update reached the transport | `subscription`, `complexity`, `bytes` |
195
+ | `:subscription_ended` | A subscription was deleted | `reason`: `:refused`, `:viewer_gone`, `:expired`, `:unsubscribed`, `:gone`, `:webhook` or `:drift`; `subscription` |
196
+ | `:subscription_payload_too_large` | A result did not fit the transport and `RESULT_TOO_LARGE` was sent instead | `subscription`, `bytes`, `limit` |
197
+ | `:subscription_trigger_budget` | A trigger reached `max_executions_per_trigger` | `skipped` |
198
+ | `:subscription_delivery_error` | Executing one subscriber raised | `error`: the error's class name; `subscription` |
199
+ | `:subscription_transport_error` | A publish failed or the transport refused a message | `operation`, `error` or `outcome` and `reason` |
200
+ | `:subscription_record_unreadable` | A stored record did not open (tampered or foreign) and was deleted | `subscription` |
201
+ | `:subscription_webhook_refused` | A webhook request failed verification; nothing was deleted | `reason` |
202
+
203
+ `subscription` is a short keyed digest of the subscription id, never the id itself (the id names the channel). No
204
+ signal holds a viewer id, a variable or a result. See [Subscriptions](subscriptions.md).
205
+
169
206
  ### Rate limiting
170
207
 
171
208
  Rate limiting takes `sinks:` for one signal, when its store fails:
@@ -194,6 +231,7 @@ A signal has a reason and, where it helps, the name of a type or an action. It *
194
231
 
195
232
  - an ID, an operation id or a query, which the client chose;
196
233
  - a rate limit key, a user id or a record attribute;
234
+ - a cache key, a purge tag, a variable's value or the viewer an answer was stored for;
197
235
  - the exception message of a decryption failure.
198
236
 
199
237
  For IDs and persisted queries a test pins it (`spec/security/telemetry_signals_spec.rb`): a forged ID and an attacker-chosen operation id are sent, and neither appears in anything recorded. Keep it that way in your own sinks: add the request id or the user from *your* request context if you need them, as your logger already does.
@@ -224,7 +262,7 @@ use GraphQL::Armory::PersistedQueries, store: store, sinks: [->(signal, data) {
224
262
 
225
263
  ## Reference
226
264
 
227
- - `sinks:` is an option of `use GraphQL::Armory::Authorization`, `use GraphQL::Armory::IDs`, `use GraphQL::Armory::PersistedQueries` and the rate limiters. An Array of callables taking `(signal, data)` or `(signal, data, context)`, called in order; default `[]`.
265
+ - `sinks:` is an option of `use GraphQL::Armory::Authorization`, `use GraphQL::Armory::IDs`, `use GraphQL::Armory::PersistedQueries`, `use GraphQL::Armory::Caching` and the rate limiters. An Array of callables taking `(signal, data)` or `(signal, data, context)`, called in order; default `[]`.
228
266
  - `on_sink_error:` is an option of the same modules except the rate limiters. A callable `(error, signal)` called when a sink raises; by default it warns with the signal and the error's class. Raise from it to fail the request closed.
229
267
  - A sink that could never be called (`->(a) {}`, four required arguments, a required keyword) raises `Telemetry::ConfigurationError` at boot.
230
268
  - `Telemetry.new(sinks: [], on_sink_error: nil)`, `Telemetry.build(sinks: [], on_sink_error: nil)`, `telemetry.record(signal, context: nil, **data)` (answers nil; `data` reaches the sinks frozen).
data/docs/versioning.md CHANGED
@@ -271,6 +271,10 @@ end
271
271
 
272
272
  The plugin decides the schema, never the data: when the data a client gets must differ per version, your resolvers decide it from this. Comparing with a label your list does not hold raises `UnknownVersionError`, so a typo fails loudly. It raises `ConfigurationError` for anything that is not a query's context.
273
273
 
274
+ ### With response caching
275
+
276
+ The plugin's own read of `armory_version`, to decide the version, does not count as an input of the answer for [response caching](response-caching.md): the resolved version is part of the cache key. Your own code reading `context[:armory_version]` does count, since two raw values that resolve to the same version are still two different inputs, and a run that read it is not stored unless the key covers it. Read the version with `Versioning.version(context)` instead, which reads no context value.
277
+
274
278
  ### Dumping a version's schema
275
279
 
276
280
  ```ruby
@@ -58,7 +58,10 @@ module GraphQL
58
58
  ::Kernel.instance_method(:class).bind_call(subject).name
59
59
  end
60
60
 
61
+ # A bypass never gets here. The query is marked before the adapter is asked, so an adapter that raises still
62
+ # leaves it marked: response caching never stores what a policy decided as an answer shared by every viewer.
61
63
  def decide(subject, rule, context)
64
+ Caching::RecordKeys.viewer_dependent!(context)
62
65
  answer = adapter.authorized?(adapter.actor(context), subject, rule)
63
66
 
64
67
  case answer
@@ -27,6 +27,8 @@ module GraphQL
27
27
  return items
28
28
  end
29
29
 
30
+ # Past the bypass the policy decides what is in the list (see Authorize#decide).
31
+ Caching::RecordKeys.viewer_dependent!(context)
30
32
  scoped = adapter.scope(adapter.actor(context), items, rule)
31
33
  telemetry.record(:scoped, context: context, action: rule.action)
32
34
  scoped
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ class Audit
7
+ # What `rake "graphql_armory:cache:audit[YourSchema]"` runs: prints the report and answers an exit status.
8
+ class Command
9
+ # The rake task's action. The app's Rake file may name the task first, to add a prerequisite, so the task existing does
10
+ # not mean this ran: the file looks for this object among its actions.
11
+ RAKE_ACTION = proc do |_task, args|
12
+ Rake::Task[:environment].invoke if Rake::Task.task_defined?(:environment)
13
+ status = new.(args[:schema])
14
+ exit(status) unless status.zero?
15
+ end
16
+
17
+ def initialize(out: $stdout)
18
+ @out = out
19
+ end
20
+
21
+ def call(schema_name)
22
+ return fail_with("Name the schema: rake \"graphql_armory:cache:audit[YourSchema]\"") if schema_name.to_s.empty?
23
+
24
+ schema = find(schema_name)
25
+ return fail_with("No schema named #{schema_name}") unless schema
26
+
27
+ report = Audit.(schema)
28
+ @out.print(report)
29
+ report.ok? ? 0 : 1
30
+ end
31
+
32
+ private
33
+
34
+ # Only a missing constant of the name is "no schema": an error while the app's code loads is the app's.
35
+ def find(schema_name)
36
+ Object.const_get(schema_name)
37
+ rescue NameError => error
38
+ raise unless error.instance_of?(NameError) && schema_name.to_s.split("::").include?(error.name.to_s)
39
+
40
+ nil
41
+ end
42
+
43
+ def fail_with(message)
44
+ @out.puts(message)
45
+ 1
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,117 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ class Audit
7
+ # The recorder sees the context's reads through the methods it overrides. An app's context class that overrides
8
+ # one of them without calling `super` hides its reads; a public method it adds can read the provided Hash directly.
9
+ # Each added public method must be declared in `context_methods:` with a reason (the app's word), and is listed.
10
+ #
11
+ # Whether an override calls `super` is read from its compiled instructions (CRuby's
12
+ # `RubyVM::InstructionSequence`). Where they cannot be read, the override is reported as one the audit cannot
13
+ # clear.
14
+ module ContextClass
15
+ RECORDED = %i[[] fetch dig key? to_h to_hash namespace scoped_context []= delete scoped_merge! scoped_set!].freeze
16
+ LIBRARY_PATHS = OwnChecks::LIBRARY_PATHS
17
+
18
+ def self.call(schema, settings, findings)
19
+ klass = schema.context_class
20
+ app = klass.is_a?(Class) && klass < GraphQL::Query::Context ? app_ancestors(klass) : []
21
+ RECORDED.each { |name| overrides(klass, name, findings) } unless app.empty?
22
+ added(klass, app, settings, findings)
23
+ end
24
+
25
+ # The classes and modules between graphql-ruby's context and the schema's context class that are the app's: the
26
+ # recording wrapper and this gem's own classes are not.
27
+ def self.app_ancestors(klass)
28
+ klass.ancestors.take_while { |ancestor| !ancestor.equal?(GraphQL::Query::Context) }.reject { |ancestor| library?(ancestor) }
29
+ end
30
+
31
+ def self.library?(mod)
32
+ return true if mod.equal?(Recorder::Context::Wrapped)
33
+
34
+ methods = mod.instance_methods(false) + mod.private_instance_methods(false)
35
+ gem_named = mod.name&.start_with?("GraphQL::") == true || wrapper?(mod)
36
+ gem_named && methods.all? { |name| library_method?(mod.instance_method(name), mod) }
37
+ end
38
+
39
+ # `Recorder::Context.wrap` answers an unnamed subclass that includes `Wrapped`.
40
+ def self.wrapper?(mod)
41
+ mod.is_a?(Class) && mod.name.nil? && mod.include?(Recorder::Context::Wrapped)
42
+ end
43
+
44
+ def self.library_method?(method, holder)
45
+ file = method.source_location&.first
46
+ return true if file.nil?
47
+
48
+ Authorization::Audit::LibraryMethods.library_method?(method, holder, *LIBRARY_PATHS) ||
49
+ (wrapper?(holder) && file.start_with?(Authorization::Audit::ARMORY_PATH))
50
+ end
51
+
52
+ def self.overrides(klass, name, findings)
53
+ return unless klass.method_defined?(name) || klass.private_method_defined?(name)
54
+
55
+ method = klass.instance_method(name)
56
+ while method && !GraphQL::Query::Context.ancestors.include?(method.owner)
57
+ unless library_method?(method, method.owner)
58
+ case calls_super?(method)
59
+ when false
60
+ findings.problem(:context_class, "#{label(method.owner)}##{name}", "overrides #{name} without calling super, so the recorder never sees " \
61
+ "its reads and a run that read an input the key does not hold is stored. Call super", at: method)
62
+ when nil
63
+ findings.problem(:context_class, "#{label(method.owner)}##{name}", "overrides #{name}, and this Ruby cannot tell whether it calls super: " \
64
+ "if it does not, the recorder never sees its reads. Call super, or remove it", at: method)
65
+ end
66
+ end
67
+ method = method.super_method
68
+ end
69
+ end
70
+
71
+ # true or false, or nil when the instructions cannot be read.
72
+ def self.calls_super?(method)
73
+ return nil unless defined?(RubyVM::InstructionSequence)
74
+
75
+ iseq = RubyVM::InstructionSequence.of(method)
76
+ iseq && super_in?(iseq.to_a)
77
+ rescue StandardError
78
+ nil
79
+ end
80
+
81
+ def self.super_in?(node)
82
+ case node
83
+ when Array then node.any? { |each| super_in?(each) }
84
+ when Symbol then node.start_with?("invokesuper")
85
+ else false
86
+ end
87
+ end
88
+
89
+ def self.added(klass, app, settings, findings)
90
+ declared = settings.context_methods.to_h { |name, reason| [name.to_sym, reason] }
91
+ # The gate's own rule, so the audit and the runtime never disagree on what counts.
92
+ names = ContextMethods.added(klass)
93
+ names.each do |name|
94
+ method = klass.instance_method(name)
95
+ if declared.key?(name)
96
+ findings.declared(:context_method, "context_methods: #{name.inspect}", declared[name].to_s, at: method)
97
+ else
98
+ findings.problem(:context_class, "#{label(method.owner)}##{name}", "a public method of the app's context class, which can read the provided " \
99
+ "Hash without the recorder seeing it, so nothing is cached. Declare it in " \
100
+ "context_methods: with a reason, or make it private", at: method)
101
+ end
102
+ end
103
+ (declared.keys - names).each do |name|
104
+ findings.problem(:context_class, "context_methods: #{name.inspect}", "names no public method the app's context class adds: remove it from the option")
105
+ end
106
+ end
107
+
108
+ def self.label(mod)
109
+ mod.name || mod.inspect
110
+ end
111
+
112
+ private_class_method :app_ancestors, :library?, :wrapper?, :library_method?, :overrides, :calls_super?, :super_in?, :added, :label
113
+ end
114
+ end
115
+ end
116
+ end
117
+ end