graphql-armory 0.1.0.pre12 → 0.1.0.pre13

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 (36) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +11 -1
  3. data/README.md +3 -3
  4. data/docs/versioning.md +540 -0
  5. data/lib/graphql/armory/authorization/audit/findings.rb +6 -1
  6. data/lib/graphql/armory/authorization/audit/overrides.rb +8 -2
  7. data/lib/graphql/armory/authorization/audit/payload_reuse.rb +9 -8
  8. data/lib/graphql/armory/authorization/definitions.rb +8 -92
  9. data/lib/graphql/armory/authorization.rb +3 -1
  10. data/lib/graphql/armory/definitions.rb +111 -0
  11. data/lib/graphql/armory/location.rb +101 -0
  12. data/lib/graphql/armory/version.rb +1 -1
  13. data/lib/graphql/armory/versioning/audit/command.rb +43 -0
  14. data/lib/graphql/armory/versioning/audit/own_checks.rb +139 -0
  15. data/lib/graphql/armory/versioning/audit/profiles.rb +123 -0
  16. data/lib/graphql/armory/versioning/audit/subscription_triggers.rb +98 -0
  17. data/lib/graphql/armory/versioning/audit.rb +559 -0
  18. data/lib/graphql/armory/versioning/controls.rb +403 -0
  19. data/lib/graphql/armory/versioning/decision.rb +89 -0
  20. data/lib/graphql/armory/versioning/deprecation.rb +95 -0
  21. data/lib/graphql/armory/versioning/diff/command.rb +49 -0
  22. data/lib/graphql/armory/versioning/diff.rb +349 -0
  23. data/lib/graphql/armory/versioning/dump/command.rb +46 -0
  24. data/lib/graphql/armory/versioning/dump.rb +107 -0
  25. data/lib/graphql/armory/versioning/gate.rb +140 -0
  26. data/lib/graphql/armory/versioning/integration.rb +903 -0
  27. data/lib/graphql/armory/versioning/lifecycle.rb +61 -0
  28. data/lib/graphql/armory/versioning/profiles.rb +122 -0
  29. data/lib/graphql/armory/versioning/rspec.rb +38 -0
  30. data/lib/graphql/armory/versioning/versions.rb +111 -0
  31. data/lib/graphql/armory/versioning/view.rb +61 -0
  32. data/lib/graphql/armory/versioning.rb +132 -0
  33. data/lib/graphql/armory.rb +1 -0
  34. data/lib/tasks/graphql_armory.rake +20 -0
  35. metadata +24 -2
  36. data/lib/graphql/armory/authorization/location.rb +0 -103
@@ -0,0 +1,903 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Versioning
6
+ # Translates graphql-ruby's hooks: `query_class` to decide each query's version, `visible?` to answer from it.
7
+ module Integration
8
+ PARTIAL = defined?(GraphQL::Query::Partial) ? GraphQL::Query::Partial : nil
9
+
10
+ # The Version a context sees, for `visible?`:
11
+ #
12
+ # - `NullContext` (graphql-ruby asking with no query): the latest version.
13
+ # - A query's context: the version `Lookup` stored for it. A second context graphql-ruby builds for a query
14
+ # (`Visibility::Migration`'s) and a `Query::Partial`'s see that query's version. A `GraphQL::Query` the app built
15
+ # itself is decided once from its own `armory_version`, recording nothing.
16
+ # - The frozen Hash of a named `Schema::Visibility` profile built by `Versioning.profiles`: its version.
17
+ # - Anything else, such as an app's own profile Hash: refused, fail closed.
18
+ def self.version(context)
19
+ return Version::LATEST if context.is_a?(GraphQL::Query::NullContext)
20
+ return profile_version(context) unless context.respond_to?(:namespace)
21
+
22
+ store = context.namespace(:armory)
23
+ store.fetch(:version) do
24
+ refusal = store[:version_refusal]
25
+ raise refusal.error if refusal
26
+
27
+ store[:version] = undecided(context)
28
+ end
29
+ end
30
+
31
+ # A profile's Hash carries no schema: it carries the gate's own list instead, and a served label of it.
32
+ def self.profile_version(context)
33
+ versions = context.is_a?(Hash) ? context[:armory_versions] : nil
34
+ unless versions.is_a?(Versions)
35
+ named = context.is_a?(Hash) && context[:visibility_profile] ? " (visibility profile #{context[:visibility_profile].inspect})" : ""
36
+ raise ConfigurationError, "versioned members need a query's context or a profile from Versioning.profiles, got a #{context.class}#{named}: " \
37
+ "pass `profiles: GraphQL::Armory::Versioning.profiles(Schema)` to Schema::Visibility, with " \
38
+ "`use GraphQL::Armory::Versioning, ..., profiles: true`, or use dynamic: true and no named profiles"
39
+ end
40
+
41
+ version = versions.fetch(context[:armory_version])
42
+ raise ConfigurationError, "the visibility profile #{context[:visibility_profile].inspect} names #{version.label}, which is retired" if version.retired?
43
+
44
+ version
45
+ end
46
+ private_class_method :profile_version
47
+
48
+ def self.undecided(context)
49
+ query = context.query
50
+ # `Visibility::Migration` builds a second context for the same query; a Partial reads its parent's schema.
51
+ return version(query.context) if query.respond_to?(:context) && !query.context.equal?(context)
52
+ return version(query.query.context) if PARTIAL && query.is_a?(PARTIAL)
53
+
54
+ # A query built without the schema's query class skipped `Lookup`, and with it the schema check.
55
+ check_schema(context.schema)
56
+ decision = gate(context.schema).resolve(context[:armory_version])
57
+ raise decision.error if decision.refused?
58
+
59
+ decision.version
60
+ end
61
+ private_class_method :undecided
62
+
63
+ def self.gate(schema)
64
+ return schema.armory_versioning if schema.respond_to?(:armory_versioning)
65
+
66
+ raise ConfigurationError, "#{schema} has versioned members but never installed the plugin: add `use GraphQL::Armory::Versioning, versions: ..., default: ...`"
67
+ end
68
+
69
+ # `Schema::AlwaysVisible` answers every `visible?` with true, so nothing would be versioned.
70
+ def self.refuse_always_visible(schema)
71
+ return unless schema.is_a?(GraphQL::Schema::AlwaysVisible)
72
+
73
+ raise ConfigurationError, "#{schema} uses GraphQL::Schema::AlwaysVisible, which never asks visible?: nothing would be versioned. Remove it"
74
+ end
75
+
76
+ # What every versioned member keeps: its lifecycle, built from `added:` and `removed:`, which it strips before `super`.
77
+ module Member
78
+ def initialize(*args, added: nil, removed: nil, deprecated: nil, **kwargs, &block)
79
+ unless deprecated.nil?
80
+ raise ConfigurationError, "#{kwargs[:name] || args.first}: deprecated: needs the class that defines it to include " "GraphQL::Armory::Versioning::Base, which makes its two definitions"
81
+ end
82
+ begin
83
+ @armory_lifecycle = Lifecycle.build(added: added, removed: removed)
84
+ rescue ConfigurationError => error
85
+ raise error.class, "#{kwargs[:name] || args.first}: #{error.message}"
86
+ end
87
+ late_bound = Integration.late_bound_name(kwargs.key?(:type) ? kwargs[:type] : args[1])
88
+ super(*args, **kwargs, &block)
89
+ Integration.mark_late_bound(self, late_bound) if late_bound
90
+ end
91
+
92
+ # When the member lives, for the audit and for tooling.
93
+ attr_reader :armory_lifecycle
94
+
95
+ # The definition before `deprecated:`'s version, when `deprecated:` wrote this one: the two are one member.
96
+ def armory_deprecated_of = @armory_deprecated_of
97
+
98
+ # The GraphQL names its type was given by, when it was a `LateBoundType`: the schema check refuses one that has
99
+ # twins.
100
+ def armory_late_bound = @armory_late_bound || []
101
+
102
+ private
103
+
104
+ def armory_versioned? = !Lifecycle::EVERYWHERE.equal?(@armory_lifecycle)
105
+
106
+ # The other definitions of this name on the same owner, found once.
107
+ def armory_twins
108
+ @armory_twins ||= Integration.twins_of(self).freeze
109
+ end
110
+ end
111
+
112
+ # Included in a field class by `include GraphQL::Armory::Versioning::Base`.
113
+ #
114
+ # field :total, Integer, null: false, added: "2024-06-01" # from 2024-06-01 on
115
+ # field :amount, Integer, null: false, removed: "2025-01-01" # up to 2024-06-01
116
+ module Field
117
+ include Member
118
+ include Deprecation::Arguments
119
+
120
+ # A field also leaves with the type that declared it: an interface that includes a versioned interface would
121
+ # otherwise keep that interface's fields where it does not live.
122
+ # `type` given inside the field's block is recorded like the positional one.
123
+ def type(*args)
124
+ name = Integration.late_bound_name(args.first) unless args.empty?
125
+ Integration.mark_late_bound(self, name) if name
126
+ super
127
+ end
128
+
129
+ def visible?(context)
130
+ Integration.refuse_twin_overlap(self, armory_twins, context, field: true)
131
+ return false unless super
132
+
133
+ version = Integration.version(context)
134
+ @armory_lifecycle.covers?(version) && Integration.lifecycle_of(owner).covers?(version)
135
+ rescue ConfigurationError => error
136
+ raise error.class, "#{owner.graphql_name}.#{graphql_name}: #{error.message}"
137
+ end
138
+ end
139
+
140
+ # Included in an argument class: arguments of fields, input-object fields and arguments of executable directives.
141
+ #
142
+ # argument :first, Integer, required: false, added: "2025-01-01"
143
+ #
144
+ # When it is asked, it also refuses what graphql-ruby would serve outside the version anyway: a default value naming a
145
+ # member the version does not have, a versioned argument shadowing a parent's of the same name, and, on a directive
146
+ # used in the SDL, a lifecycle or a type with versioned members.
147
+ module Argument
148
+ include Member
149
+
150
+ # Where graphql-ruby runs a directive while executing a query. Any other location is the schema's own (SDL), where
151
+ # applied arguments are printed as the latest version sees them, without asking `visible?`.
152
+ EXECUTABLE = %i[QUERY MUTATION SUBSCRIPTION FIELD FRAGMENT_DEFINITION FRAGMENT_SPREAD INLINE_FRAGMENT VARIABLE_DEFINITION].freeze
153
+
154
+ def visible?(context)
155
+ Integration.refuse_twin_overlap(self, armory_twins, context)
156
+ return false unless super
157
+
158
+ armory_refuse_on_schema_directive if owner.is_a?(Class) && owner < GraphQL::Schema::Directive
159
+ in_default = armory_default_members
160
+ loaded = armory_loaded_lifecycle
161
+ return true if !armory_versioned? && in_default.empty? && loaded.nil?
162
+
163
+ version = Integration.version(context)
164
+ return false unless @armory_lifecycle.covers?(version)
165
+ # A `loads:` argument takes an ID, so graphql-ruby never hides it with the loaded type: it is hidden here.
166
+ return false if loaded && !loaded.covers?(version)
167
+
168
+ # Each entry lists the definitions the default may mean (an enum value renamed across versions keeps its Ruby value).
169
+ missing = in_default.reject { |choices| choices.any? { |member| Integration.covers?(member, version) } }
170
+ return true if missing.empty?
171
+
172
+ raise ConfigurationError, "its default_value names #{missing.map { |choices| choices.first.path }.join(', ')}, not in " \
173
+ "#{Integration.label(version)}: introspection would print it and the field would run without it. " \
174
+ "Use a default every version of this argument has"
175
+ rescue ConfigurationError => error
176
+ raise error.class, "#{path}: #{error.message}"
177
+ end
178
+
179
+ private
180
+
181
+ # The versioned members the default value names, found once, after the check that refuses a shadowing definition.
182
+ def armory_default_members
183
+ return @armory_default_members if defined?(@armory_default_members)
184
+
185
+ Integration.refuse_shadowing(self, armory_inherited_arguments) if armory_versioned?
186
+ @armory_default_members = default_value? ? Integration.members_in(type, default_value).freeze : [].freeze
187
+ end
188
+
189
+ def armory_loaded_lifecycle
190
+ return @armory_loaded_lifecycle if defined?(@armory_loaded_lifecycle)
191
+
192
+ # graphql-ruby checks an object loaded as an interface or union against members asked with no context.
193
+ if loads && loads.kind.abstract? && Integration.versioned_memberships?(loads)
194
+ raise ConfigurationError, "it loads #{loads.graphql_name}, which has a membership with a lifecycle: graphql-ruby would load " \
195
+ "an object that is not a member in the query's version. Load the object types instead"
196
+ end
197
+
198
+ lifecycle = loads && Integration.lifecycle_of(loads)
199
+ @armory_loaded_lifecycle = lifecycle && !Lifecycle::EVERYWHERE.equal?(lifecycle) ? lifecycle : nil
200
+ end
201
+
202
+ def armory_inherited_arguments
203
+ sources = []
204
+ sources << owner.resolver if owner.is_a?(GraphQL::Schema::Field) && owner.resolver
205
+ sources << owner.superclass if owner.is_a?(Class) && owner.superclass.respond_to?(:all_argument_definitions)
206
+ sources.flat_map(&:all_argument_definitions)
207
+ end
208
+
209
+ # Asked every time, not remembered: a subclass defined later may add a location, and an argument's owner is the
210
+ # class that declared it, so the subclasses' locations count too.
211
+ def armory_refuse_on_schema_directive
212
+ schema_locations = Integration.directive_locations(owner) - EXECUTABLE
213
+ return if schema_locations.empty?
214
+
215
+ where = "is on a directive used in the SDL (#{schema_locations.join(', ')}), which prints applied arguments as the latest version sees them"
216
+ raise ConfigurationError, "#{where}: it cannot have a lifecycle" if armory_versioned?
217
+
218
+ reached = Integration.versioned_members_of(type)
219
+ return if reached.empty?
220
+
221
+ raise ConfigurationError, "#{where}: its type cannot reach versioned members (#{reached.first(3).map(&:path).join(', ')})"
222
+ end
223
+ end
224
+
225
+ # Included in an enum value class.
226
+ #
227
+ # value "VOID", added: "2024-06-01"
228
+ module EnumValue
229
+ include Member
230
+
231
+ def visible?(context)
232
+ Integration.refuse_twin_overlap(self, armory_twins, context)
233
+ return false unless super
234
+ return true unless armory_versioned?
235
+
236
+ unless defined?(@armory_checked)
237
+ parent = owner.superclass
238
+ Integration.refuse_shadowing(self, parent.respond_to?(:all_enum_value_definitions) ? parent.all_enum_value_definitions : [])
239
+ @armory_checked = true
240
+ end
241
+ @armory_lifecycle.covers?(Integration.version(context))
242
+ rescue ConfigurationError => error
243
+ raise error.class, "#{path}: #{error.message}"
244
+ end
245
+ end
246
+
247
+ # Extended into a type class (object, input object, enum, scalar, union, resolver or mutation) and included into an
248
+ # interface's definition methods by `include GraphQL::Armory::Versioning::Base`.
249
+ #
250
+ # class Types::Contract < Types::BaseObject
251
+ # lifecycle added: "2025-01-01"
252
+ # end
253
+ #
254
+ # A class without its own lifecycle takes its mutation's (a generated payload or input type) or its superclass's.
255
+ # An interface takes nothing from the interfaces it includes, and objects take nothing from their interfaces.
256
+ module Type
257
+ def lifecycle(added: nil, removed: nil)
258
+ if added.nil? && removed.nil?
259
+ raise ConfigurationError, "lifecycle needs added:, removed: or both; a type with neither lives in every version"
260
+ end
261
+
262
+ @armory_lifecycle = Lifecycle.build(added: added, removed: removed)
263
+ rescue ConfigurationError => error
264
+ raise error.class, "#{graphql_name}: #{error.message}"
265
+ end
266
+
267
+ # When the type lives, for the audit and for tooling.
268
+ def armory_lifecycle
269
+ return @armory_lifecycle if defined?(@armory_lifecycle)
270
+
271
+ source = Integration.lifecycle_source(self)
272
+ source ? source.armory_lifecycle : Lifecycle::EVERYWHERE
273
+ end
274
+
275
+ def visible?(context)
276
+ return false unless super
277
+
278
+ Integration.refuse_membership_conflicts(self)
279
+ lifecycle = armory_lifecycle
280
+ return true if Lifecycle::EVERYWHERE.equal?(lifecycle)
281
+
282
+ version = Integration.version(context)
283
+ return false unless lifecycle.covers?(version)
284
+
285
+ Integration.refuse_wider_than_parent(self, version)
286
+ true
287
+ rescue ConfigurationError => error
288
+ raise error.class, "#{graphql_name}: #{error.message}"
289
+ end
290
+ end
291
+
292
+ # Extended into object types. An argument that `loads:` an abstract type checks the loaded object's type against the
293
+ # abstract type's members with no context, so an object of a type outside the version would load: it is not
294
+ # authorized there, and the resolver never runs with it.
295
+ module Authorized
296
+ def authorized?(object, context)
297
+ lifecycle = armory_lifecycle
298
+ return super if Lifecycle::EVERYWHERE.equal?(lifecycle)
299
+
300
+ lifecycle.covers?(Integration.version(context)) && super
301
+ rescue ConfigurationError => error
302
+ raise error.class, "#{graphql_name}: #{error.message}"
303
+ end
304
+ end
305
+
306
+ # Included in a type membership class, which the app sets as `type_membership_class` on its base interface and
307
+ # base union, so `implements X, added:` and `possible_types Y, added:` carry a lifecycle.
308
+ module Membership
309
+ def initialize(abstract_type, object_type, added: nil, removed: nil, **options)
310
+ @armory_lifecycle = Lifecycle.build(added: added, removed: removed)
311
+ unless Lifecycle::EVERYWHERE.equal?(@armory_lifecycle)
312
+ Integration.refuse_unguarded_membership(abstract_type, object_type)
313
+ Integration.mark_versioned_membership(abstract_type)
314
+ end
315
+ super(abstract_type, object_type, **options)
316
+ end
317
+
318
+ # When the membership lives, for the audit and for tooling.
319
+ attr_reader :armory_lifecycle
320
+
321
+ def visible?(context)
322
+ return false unless super
323
+ return true if Lifecycle::EVERYWHERE.equal?(@armory_lifecycle)
324
+
325
+ @armory_lifecycle.covers?(Integration.version(context))
326
+ rescue ConfigurationError => error
327
+ raise error.class, "#{path}: #{error.message}"
328
+ end
329
+ end
330
+
331
+ # `implements` with `added:` or `removed:` checks every interface before graphql-ruby adds any, since graphql-ruby
332
+ # would ignore the keywords, apply them partly or fail halfway.
333
+ module Implements
334
+ def implements(*interfaces, added: nil, removed: nil, **options)
335
+ Integration.refuse_deprecated_membership(options, "implements")
336
+ interfaces.each do |interface|
337
+ name = Integration.late_bound_name(interface)
338
+ Integration.mark_late_bound(self, name) if name
339
+ end
340
+ return super(*interfaces, **options) if added.nil? && removed.nil?
341
+
342
+ Integration.check_implements(self, interfaces, added, removed)
343
+ super(*interfaces, added: added, removed: removed, **options)
344
+ end
345
+ end
346
+
347
+ # GraphQL cannot deprecate a membership, and graphql-ruby would keep the keyword without a word.
348
+ def self.refuse_deprecated_membership(options, method)
349
+ return unless options.key?(:deprecated) || options.key?(:deprecation_reason)
350
+
351
+ raise ConfigurationError, "#{method} cannot take deprecated: or deprecation_reason:: GraphQL has no deprecated " \
352
+ "membership. Use removed: instead"
353
+ end
354
+
355
+ # The same for a union's `possible_types`. Called with no types, it is graphql-ruby's reader.
356
+ module Members
357
+ def possible_types(*types, added: nil, removed: nil, **options)
358
+ Integration.refuse_deprecated_membership(options, "possible_types")
359
+ return super(*types, **options) if added.nil? && removed.nil?
360
+
361
+ Integration.check_possible_types(self, types, added, removed)
362
+ super(*types, added: added, removed: removed, **options)
363
+ end
364
+ end
365
+
366
+ def self.check_implements(type, interfaces, added, removed)
367
+ name = type.graphql_name
368
+ raise ConfigurationError, "#{name}: an interface cannot implement another with added: or removed:" unless type.is_a?(Class)
369
+
370
+ build_lifecycle(name, added, removed)
371
+ interfaces.each do |interface|
372
+ unless interface.is_a?(Module)
373
+ raise ConfigurationError, "#{name}: implements #{interface.inspect} with added: or removed: needs the interface's module, not a name"
374
+ end
375
+
376
+ check_membership_class(name, "implements #{interface.graphql_name}", interface)
377
+ next if interface.interfaces.empty?
378
+
379
+ raise ConfigurationError, "#{name}: implements #{interface.graphql_name} with added: or removed:, but #{interface.graphql_name} " \
380
+ "implements other interfaces, which graphql-ruby would add without the lifecycle. Implement each one directly"
381
+ end
382
+ end
383
+
384
+ def self.check_possible_types(union, types, added, removed)
385
+ name = union.graphql_name
386
+ build_lifecycle(name, added, removed)
387
+ types.each do |type|
388
+ next if type.is_a?(Class)
389
+
390
+ raise ConfigurationError, "#{name}: possible_types #{type.inspect} with added: or removed: needs the object's class, not a name"
391
+ end
392
+ check_membership_class(name, "possible_types", union)
393
+ end
394
+
395
+ def self.build_lifecycle(name, added, removed)
396
+ Lifecycle.build(added: added, removed: removed)
397
+ rescue ConfigurationError => error
398
+ raise error.class, "#{name}: #{error.message}"
399
+ end
400
+
401
+ def self.check_membership_class(name, what, abstract_type)
402
+ return if abstract_type.type_membership_class.include?(Membership)
403
+
404
+ raise ConfigurationError, "#{name}: #{what} with added: or removed: needs #{abstract_type.graphql_name}'s type_membership_class " \
405
+ "to include GraphQL::Armory::Versioning::Base"
406
+ end
407
+
408
+ # The checks of a versioned membership run from the types that include `Base`, so a membership between types
409
+ # without it is refused: graphql-ruby would pass it the keywords and serve it unchecked.
410
+ def self.refuse_unguarded_membership(abstract_type, object_type)
411
+ guarded = object_type.is_a?(Class) && object_type.singleton_class.include?(Type) &&
412
+ abstract_type.is_a?(Module) && abstract_type.singleton_class.include?(Type)
413
+ return if guarded
414
+
415
+ names = [abstract_type, object_type].map { |type| type.respond_to?(:graphql_name) ? display_name(type) : type.inspect }
416
+ raise ConfigurationError, "#{names.last} and #{names.first}: a membership with added: or removed: needs an object class and " \
417
+ "an interface or union that include GraphQL::Armory::Versioning::Base"
418
+ end
419
+
420
+ def self.mark_versioned_membership(abstract_type)
421
+ abstract_type.instance_variable_set(:@armory_versioned_memberships, true) if abstract_type.is_a?(Module)
422
+ @versioned_memberships = (@versioned_memberships || 0) + 1
423
+ end
424
+
425
+ def self.versioned_membership_count = @versioned_memberships || 0
426
+
427
+ # The GraphQL name a type expression binds late: a `LateBoundType`, bare, wrapped or in a list (`[T, null: true]`
428
+ # included). A String is a Ruby constant, bound to one class at once.
429
+ def self.late_bound_name(expression)
430
+ case expression
431
+ when GraphQL::Schema::LateBoundType then expression.graphql_name
432
+ when GraphQL::Schema::Wrapper then late_bound_name(expression.of_type)
433
+ when Array then late_bound_name(expression.first)
434
+ end
435
+ end
436
+
437
+ def self.mark_late_bound(member, name)
438
+ member.instance_variable_set(:@armory_late_bound, [*member.instance_variable_get(:@armory_late_bound), name])
439
+ @late_bound = (@late_bound || 0) + 1
440
+ end
441
+
442
+ def self.late_bound_count = @late_bound || 0
443
+
444
+ # Every type the schema holds, twins included: Warden's `schema.types` keeps one per name, the one the latest
445
+ # version sees, and nil where none does.
446
+ def self.definitions(schema)
447
+ Armory::Definitions.(schema, schema.extra_types).reject { |type| Armory::Definitions.introspection?(type) }
448
+ end
449
+
450
+ # Every argument a type holds, at every level of its fields, twins included.
451
+ def self.arguments_in(type)
452
+ return type.all_argument_definitions if type.kind.input_object?
453
+
454
+ Armory::Definitions.fields_at_every_level(type).flat_map(&:all_argument_definitions)
455
+ end
456
+
457
+ # graphql-ruby binds a late-bound name to the first type registered with it, whatever the version: one that has
458
+ # twins would serve the wrong one. Only members that include `Base` are known.
459
+ def self.refuse_late_bound_twins(types, directives)
460
+ # A base interface module brought in with `include` has no name of its own.
461
+ named = types.group_by do |type|
462
+ type.graphql_name
463
+ rescue GraphQL::RequiredImplementationMissingError
464
+ nil
465
+ end
466
+ twins = named.select { |name, list| name && list.size > 1 }
467
+ return if twins.empty?
468
+
469
+ members = types.flat_map { |type| [type, *Armory::Definitions.fields_at_every_level(type), *arguments_in(type)] }
470
+ members.concat(directives.flat_map(&:all_argument_definitions))
471
+ members.each do |member|
472
+ names = member.instance_variable_get(:@armory_late_bound)
473
+ twin = names&.find { |name| twins.key?(name) }
474
+ next unless twin
475
+
476
+ at = member.respond_to?(:path) ? member.path : display_name(member)
477
+ raise ConfigurationError, "#{at}: names #{twin} by name, and #{twin} has more than one definition: graphql-ruby binds the " \
478
+ "name to the first one registered, in every version. Reference the class instead"
479
+ end
480
+ end
481
+
482
+ # Every argument of the schema that loads an interface or union with a versioned membership, whatever its class:
483
+ # an argument class without `Base` never asks. Walked only when a versioned membership exists.
484
+ def self.refuse_abstract_loads(types)
485
+ types.each do |type|
486
+ arguments_in(type).each do |argument|
487
+ loads = argument.loads
488
+ next unless loads && loads.kind.abstract? && versioned_memberships?(loads)
489
+
490
+ raise ConfigurationError, "#{argument.path}: it loads #{loads.graphql_name}, which has a membership with a lifecycle: " \
491
+ "graphql-ruby would load an object that is not a member in the query's version. Load the object types instead"
492
+ end
493
+ end
494
+ end
495
+
496
+ def self.versioned_memberships?(abstract_type)
497
+ abstract_type.instance_variable_defined?(:@armory_versioned_memberships)
498
+ end
499
+
500
+ # graphql-ruby serves a membership when any membership to the same abstract type is visible, and `get_field` answers
501
+ # a hidden interface's definition of a name another source also declares, so both are refused. Checked when the
502
+ # object or union is asked, again when its memberships change.
503
+ def self.refuse_membership_conflicts(type)
504
+ memberships = type.is_a?(Class) && type < GraphQL::Schema::Union ? type.type_memberships : object_memberships(type)
505
+ return if memberships.nil? || type.instance_variable_get(:@armory_memberships_checked) == memberships.size
506
+
507
+ versioned = memberships.select { |membership| membership.respond_to?(:armory_lifecycle) && !Lifecycle::EVERYWHERE.equal?(membership.armory_lifecycle) }
508
+ versioned.each do |membership|
509
+ target = type < GraphQL::Schema::Union ? membership.object_type : membership.abstract_type
510
+ others = memberships.reject { |other| other.equal?(membership) || !other.respond_to?(:abstract_type) }
511
+ union = type < GraphQL::Schema::Union
512
+ # Another membership to the same type, or, for an object, to an interface that includes it.
513
+ overridden = others.any? do |other|
514
+ reached = union ? other.object_type : other.abstract_type
515
+ reached.equal?(target) || (!union && reached.is_a?(Module) && reached.include?(target))
516
+ end
517
+ if overridden
518
+ raise ConfigurationError, "#{union ? 'lists' : 'implements'} #{target.graphql_name} with a lifecycle, but another membership " \
519
+ "to #{target.graphql_name}, or to an interface that includes it, makes it a member in every version. Keep one"
520
+ end
521
+ refuse_shared_fields(type, target, others) unless type < GraphQL::Schema::Union
522
+ end
523
+ type.instance_variable_set(:@armory_memberships_checked, memberships.size)
524
+ end
525
+
526
+ # Every definition of each field name a type declares or inherits, twins included, read without a query.
527
+ def self.field_definitions(type, own_only: false)
528
+ levels = own_only ? [type] : type.ancestors.select { |ancestor| ancestor.respond_to?(:own_fields) }
529
+ levels.each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |level, found|
530
+ level.own_fields.each { |name, definitions| found[name].concat(Array(definitions)) }
531
+ end
532
+ end
533
+
534
+ def self.display_name(type)
535
+ type.graphql_name
536
+ rescue GraphQL::RequiredImplementationMissingError
537
+ type.name || type.inspect
538
+ end
539
+
540
+ def self.object_memberships(type)
541
+ type.interface_type_memberships if type.is_a?(Class) && type < GraphQL::Schema::Object
542
+ end
543
+
544
+ def self.refuse_shared_fields(object, interface, others)
545
+ own = object.own_fields
546
+ sources = others.map(&:abstract_type).select { |other| other.is_a?(Module) }.map { |other| [other, field_definitions(other)] }
547
+ object.ancestors.each do |ancestor|
548
+ next unless ancestor.is_a?(Class) && ancestor < GraphQL::Schema::Object && !ancestor.equal?(object)
549
+
550
+ sources << [ancestor, field_definitions(ancestor, own_only: true)]
551
+ end
552
+ field_definitions(interface).each do |name, definitions|
553
+ next if own.key?(name)
554
+
555
+ source = sources.find { |_, fields| fields.key?(name) && !(fields[name] - definitions).empty? }
556
+ next unless source
557
+
558
+ raise ConfigurationError, "implements #{interface.graphql_name} with a lifecycle, but " \
559
+ "#{interface.graphql_name}.#{name} is also declared by #{display_name(source.first)}, so graphql-ruby could serve " \
560
+ "#{interface.graphql_name}'s definition where the membership does not live. Declare #{name} on " \
561
+ "#{object.graphql_name}, or rename one"
562
+ end
563
+ end
564
+
565
+ # The class a type without its own lifecycle takes it from: its mutation (a generated payload or input type), else its
566
+ # superclass. Modules (interfaces) take it from nothing.
567
+ def self.lifecycle_source(type)
568
+ return unless type.is_a?(Class)
569
+
570
+ mutation = type.mutation if type.respond_to?(:mutation)
571
+ return mutation if mutation.is_a?(Class) && !mutation.equal?(type) && mutation.respond_to?(:armory_lifecycle)
572
+
573
+ parent = type.superclass
574
+ parent if parent.respond_to?(:armory_lifecycle)
575
+ end
576
+
577
+ # A type must not live where any versioned ancestor does not: the legacy Warden checks the parents' visibility for the
578
+ # memberships a subclass inherits. Every ancestor counts, since an intermediate one may never be asked.
579
+ def self.refuse_wider_than_parent(type, version)
580
+ return unless type.is_a?(Class)
581
+
582
+ parent = type.superclass
583
+ while parent.respond_to?(:armory_lifecycle)
584
+ unless parent.armory_lifecycle.covers?(version)
585
+ raise ConfigurationError, "lives in #{label(version)} but its parent #{parent.graphql_name} does not: a subclass's lifecycle " \
586
+ "must fit inside its parent's"
587
+ end
588
+ parent = parent.superclass
589
+ end
590
+ end
591
+
592
+ # Checked when a query of a schema is built, and by `Versioning.types`: graphql-ruby answers these without asking
593
+ # `visible?` with the query's context. Checked again when the roots or `extra_types` change.
594
+ def self.check_schema(schema)
595
+ checked = [schema.query, schema.mutation, schema.subscription, versioned_membership_count, late_bound_count, *schema.extra_types]
596
+ return if schema.instance_variable_get(:@armory_schema_checked) == checked
597
+
598
+ schema_checks(schema).each(&:call)
599
+ schema.instance_variable_set(:@armory_schema_checked, checked)
600
+ end
601
+
602
+ # Each schema-level check on its own, in the order `check_schema` runs them: the audit runs every one and reports
603
+ # each refusal.
604
+ def self.schema_checks(schema)
605
+ # Under `Schema::Visibility` such a type counts as referenced and its members are filtered.
606
+ visibility = schema.respond_to?(:use_visibility_profile?) && schema.use_visibility_profile?
607
+ abstract_loads = versioned_membership_count.positive? && !visibility
608
+ types = nil
609
+ walked = -> { types ||= definitions(schema) }
610
+ checks = []
611
+ checks << -> { refuse_abstract_loads(walked.()) } if abstract_loads
612
+ checks << -> { refuse_late_bound_twins(walked.(), schema.directives.values) } if late_bound_count.positive?
613
+ checks << -> { refuse_subscription_twins(schema) }
614
+ [schema.query, schema.mutation, schema.subscription].compact.each do |root|
615
+ checks << lambda do
616
+ next unless versioned_type?(root)
617
+
618
+ raise ConfigurationError, "#{root.graphql_name}: a root type cannot have a lifecycle: a version without it would have no " \
619
+ "#{root.graphql_name} root. Version its fields instead"
620
+ end
621
+ end
622
+ schema.extra_types.each do |type|
623
+ checks << lambda do
624
+ next unless versioned_type?(type)
625
+
626
+ raise ConfigurationError, "#{type.graphql_name}: a type with a lifecycle cannot be in extra_types: `__type` and the SDL " \
627
+ "read extra_types without asking visible?"
628
+ end
629
+ end
630
+ checks
631
+ end
632
+
633
+ # Twins: other definitions of a member's name on its own owner.
634
+ def self.twins_of(member)
635
+ holder = member.owner
636
+ definitions = case member
637
+ when GraphQL::Schema::Field then holder.own_fields[member.graphql_name] if holder.respond_to?(:own_fields)
638
+ when GraphQL::Schema::Argument then holder.own_arguments[member.graphql_name] if holder.respond_to?(:own_arguments)
639
+ when GraphQL::Schema::EnumValue
640
+ holder.all_enum_value_definitions.select { |value| value.owner.equal?(holder) && value.graphql_name == member.graphql_name }
641
+ end
642
+ Array(definitions).reject { |definition| definition.equal?(member) }
643
+ end
644
+
645
+ # graphql-ruby 2.4.0 to 2.4.8 fail with NoMethodError under Schema::Visibility when no twin of a field is visible.
646
+ FIELD_TWINS = Gem::Version.new(GraphQL::VERSION) >= Gem::Version.new("2.4.9")
647
+
648
+ # Two definitions of one name that a version would both see: graphql-ruby would raise DuplicateNamesError on every
649
+ # query that asks for it. Checked before any other `visible?`, so the answer never depends on the user.
650
+ def self.refuse_twin_overlap(member, twins, context, field: false)
651
+ return if twins.empty?
652
+ raise ConfigurationError, "has two definitions, which needs graphql 2.4.9 or later" if field && !FIELD_TWINS
653
+
654
+ version = version(context)
655
+ return unless covers?(member, version) && twins.any? { |twin| covers?(twin, version) }
656
+
657
+ raise ConfigurationError, "is defined more than once for #{label(version)}: graphql-ruby would refuse every query that asks " \
658
+ "for it. Give the definitions lifecycles that do not overlap"
659
+ end
660
+
661
+ # graphql-ruby's subscription trigger reads the arguments of a subscription field with no query, where twins raise.
662
+ def self.refuse_subscription_twins(schema)
663
+ root = schema.subscription
664
+ return unless root
665
+
666
+ seen = {}.compare_by_identity
667
+ root.all_field_definitions.each do |field|
668
+ refuse_argument_twins(field.path, field.path, field.all_argument_definitions, seen)
669
+ end
670
+ end
671
+
672
+ def self.refuse_argument_twins(at, holder, arguments, seen)
673
+ arguments.group_by(&:graphql_name).each do |name, definitions|
674
+ if definitions.size > 1
675
+ raise ConfigurationError, "#{at}: #{holder}.#{name} has two definitions, and graphql-ruby's subscription trigger reads " \
676
+ "arguments with no version, where they raise. Keep one definition (deprecated: makes two)"
677
+ end
678
+
679
+ input = definitions.first.type.unwrap
680
+ refuse_enum_twins(definitions.first.path, input) if input.kind.enum?
681
+ next unless input.kind.input_object? && !seen.key?(input)
682
+
683
+ seen[input] = true
684
+ refuse_argument_twins(definitions.first.path, input.graphql_name, input.all_argument_definitions, seen)
685
+ end
686
+ end
687
+
688
+ # An enum value with two definitions coerces, with no version, to the latest one's Ruby value.
689
+ def self.refuse_enum_twins(at, enum)
690
+ name, = enum.all_enum_value_definitions.group_by(&:graphql_name).find { |_, values| values.size > 1 }
691
+ return unless name
692
+
693
+ raise ConfigurationError, "#{at}: #{enum.graphql_name}.#{name} has two definitions, and graphql-ruby's subscription trigger reads " "arguments with no version, where they raise or coerce to the latest. Keep one definition"
694
+ end
695
+
696
+ # graphql-ruby serves a parent's definition of a name when the local one is hidden (enum values on every path,
697
+ # arguments under the legacy Warden), so a versioned member must not shadow one.
698
+ def self.refuse_shadowing(member, inherited)
699
+ shadowed = inherited.find { |other| !other.equal?(member) && other.graphql_name == member.graphql_name }
700
+ return unless shadowed
701
+
702
+ raise ConfigurationError, "shadows #{shadowed.path}, so graphql-ruby would serve that one in the versions where this " \
703
+ "one is hidden. Version the parent's definition, or give this one another name"
704
+ end
705
+
706
+ # The members with a lifecycle that a Ruby default value names, through lists and nested input objects, as a list of
707
+ # choices: the default is fine in a version where any definition of a choice lives. A choice with a definition that
708
+ # lives everywhere is left out.
709
+ def self.members_in(type, value, found = [])
710
+ return found if value.nil?
711
+ return members_in(type.of_type, value, found) if type.non_null?
712
+
713
+ if type.list?
714
+ (value.is_a?(Array) ? value : [value]).each { |item| members_in(type.of_type, item, found) }
715
+ elsif type.kind.enum?
716
+ choices = type.all_enum_value_definitions.select { |defn| defn.value == value || defn.graphql_name == value.to_s }
717
+ found << choices if !choices.empty? && choices.all? { |defn| versioned?(defn) }
718
+ elsif type.kind.input_object? && value.respond_to?(:each_pair)
719
+ value.each_pair do |key, item|
720
+ arguments = input_fields(type, key.to_s)
721
+ next if arguments.empty?
722
+
723
+ found << arguments if arguments.all? { |argument| versioned?(argument) }
724
+ members_in(arguments.first.type, item, found)
725
+ end
726
+ end
727
+ found
728
+ end
729
+
730
+ # graphql-ruby accepts a default's key as the field's GraphQL name, its keyword (`as:`) or its underscored name.
731
+ def self.input_fields(type, key)
732
+ camelized = GraphQL::Schema::Member::BuildType.camelize(key)
733
+ type.all_argument_definitions.select do |defn|
734
+ defn.graphql_name == key || defn.graphql_name == camelized || defn.keyword.to_s == key
735
+ end
736
+ end
737
+
738
+ # Every versioned type, enum value and input field a type can reach, through lists and nested input objects.
739
+ def self.versioned_members_of(type, seen = {}.compare_by_identity)
740
+ type = type.unwrap
741
+ return [] if seen.key?(type)
742
+
743
+ seen[type] = true
744
+ own = versioned_type?(type) ? [type] : []
745
+ if type.kind.enum?
746
+ own + type.all_enum_value_definitions.select { |defn| versioned?(defn) }
747
+ elsif type.kind.input_object?
748
+ own + type.all_argument_definitions.flat_map { |defn| (versioned?(defn) ? [defn] : []) + versioned_members_of(defn.type, seen) }
749
+ else
750
+ own
751
+ end
752
+ end
753
+
754
+ # A directive's locations and those of every subclass, since an inherited argument's owner is the parent.
755
+ def self.directive_locations(directive)
756
+ directive.subclasses.reduce(directive.locations) { |locations, subclass| locations | directive_locations(subclass) }
757
+ end
758
+
759
+ def self.lifecycle_of(member)
760
+ member.respond_to?(:armory_lifecycle) ? member.armory_lifecycle : Lifecycle::EVERYWHERE
761
+ end
762
+
763
+ def self.versioned_type?(type) = !Lifecycle::EVERYWHERE.equal?(lifecycle_of(type))
764
+
765
+ # A member is versioned by its own lifecycle, or, for an argument or input field, by its type's.
766
+ def self.versioned?(member)
767
+ versioned_type?(member) || (member.is_a?(GraphQL::Schema::Argument) && versioned_type?(member.type.unwrap))
768
+ end
769
+
770
+ def self.covers?(member, version)
771
+ return false unless lifecycle_of(member).covers?(version)
772
+
773
+ typed = member.is_a?(GraphQL::Schema::Argument) || member.is_a?(GraphQL::Schema::Field)
774
+ !typed || lifecycle_of(member.type.unwrap).covers?(version)
775
+ end
776
+
777
+ def self.label(version)
778
+ Version::LATEST.equal?(version) ? "the latest version" : version.label
779
+ end
780
+
781
+ # Keeps the lookup in every query class the schema uses, including one set after `use` or by a child schema.
782
+ module Guard
783
+ UNSET = Object.new.freeze
784
+
785
+ def query_class(new_query_class = UNSET)
786
+ return super() if UNSET.equal?(new_query_class)
787
+ return super(new_query_class) if new_query_class.include?(Lookup)
788
+
789
+ super(Class.new(new_query_class) { include Lookup })
790
+ end
791
+
792
+ def armory_versioning
793
+ @armory_versioning || superclass.armory_versioning
794
+ end
795
+
796
+ # The named profiles `use ..., profiles: true` runs queries under, or `Profiles::Off`.
797
+ def armory_versioning_profiles
798
+ @armory_versioning_profiles || superclass.armory_versioning_profiles
799
+ end
800
+ end
801
+
802
+ # Decides the query's version after the query is built, from its own context, so a version set by a custom
803
+ # `context_class` is seen. A refused query fails validation with the refusal as its only error, through the
804
+ # public `validate=` and `static_validator=` setters, so neither engine runs anything, even with `validate: false`.
805
+ module Lookup
806
+ def initialize(schema, query_string = nil, **options)
807
+ Integration.refuse_always_visible(schema)
808
+ Integration.check_schema(schema)
809
+ profiles = schema.armory_versioning_profiles
810
+ super(schema, query_string, **profiles.options(schema.armory_versioning, options))
811
+
812
+ decision = schema.armory_versioning.(context)
813
+ profiles.check(self, decision)
814
+ store = context.namespace(:armory)
815
+ return store[:version] = decision.version unless decision.refused?
816
+
817
+ store[:version_refusal] = decision
818
+ # A PersistedQueries refusal already runs nothing: its code stands. Any other validator is replaced.
819
+ @armory_refusal = static_validator.is_a?(PersistedQueries::Refusal) ? static_validator : Refusal.new(schema, decision)
820
+ self.validate = true
821
+ self.static_validator = @armory_refusal
822
+ end
823
+
824
+ # A refused query keeps refusing: code that sets these after the query is built cannot turn the refusal off.
825
+ # Execution::Next skips validation when `validate` is false.
826
+ def validate=(value)
827
+ super(@armory_refusal ? true : value)
828
+ end
829
+
830
+ def static_validator=(validator)
831
+ super(@armory_refusal || validator)
832
+ end
833
+ end
834
+
835
+ # A validation error with its code.
836
+ class RefusalError < GraphQL::StaticValidation::Error
837
+ def initialize(decision)
838
+ super(decision.message)
839
+ @code = decision.code
840
+ end
841
+
842
+ def to_h
843
+ super.merge("extensions" => { "code" => @code })
844
+ end
845
+ end
846
+
847
+ # Validates nothing and answers the refusal, through the query's public `static_validator`.
848
+ class Refusal < GraphQL::StaticValidation::Validator
849
+ def initialize(schema, decision)
850
+ super(schema: schema)
851
+ @decision = decision
852
+ end
853
+
854
+ def validate(_query, **)
855
+ { errors: [RefusalError.new(@decision)], remaining_timeout: nil }
856
+ end
857
+ end
858
+ end
859
+
860
+ # Goes in your base classes: fields, arguments, enum values, objects, interfaces (after `include
861
+ # GraphQL::Schema::Interface`), unions, enums, scalars, input objects, resolvers and mutations.
862
+ #
863
+ # class Types::BaseField < GraphQL::Schema::Field
864
+ # include GraphQL::Armory::Versioning::Base
865
+ # argument_class Types::BaseArgument
866
+ # end
867
+ # class Types::BaseObject < GraphQL::Schema::Object
868
+ # include GraphQL::Armory::Versioning::Base
869
+ # field_class Types::BaseField
870
+ # end
871
+ # module Types::BaseInterface
872
+ # include GraphQL::Schema::Interface
873
+ # include GraphQL::Armory::Versioning::Base
874
+ # end
875
+ module Base
876
+ # Instances (members) get `added:`/`removed:`; classes (types) get `lifecycle`.
877
+ MEMBERS = {
878
+ GraphQL::Schema::Field => :Field, GraphQL::Schema::Argument => :Argument, GraphQL::Schema::EnumValue => :EnumValue,
879
+ GraphQL::Schema::TypeMembership => :Membership
880
+ }.freeze
881
+ TYPES = {
882
+ GraphQL::Schema::Object => %i[Type Implements Authorized Fields], GraphQL::Schema::Union => %i[Type Members],
883
+ GraphQL::Schema::InputObject => %i[Type Arguments], GraphQL::Schema::Enum => %i[Type Values], GraphQL::Schema::Scalar => %i[Type],
884
+ GraphQL::Schema::Resolver => %i[Type Arguments Fields]
885
+ }.freeze
886
+
887
+ def self.included(base)
888
+ if !base.is_a?(Class) && base.include?(GraphQL::Schema::Interface)
889
+ modules = [Integration::Type, Integration::Implements, Deprecation::Fields]
890
+ base.definition_methods { modules.each { |mod| include mod } }
891
+ elsif base.is_a?(Class) && (member = MEMBERS.find { |parent, _| base <= parent })
892
+ base.include(Integration.const_get(member.last))
893
+ elsif base.is_a?(Class) && (type = TYPES.find { |parent, _| base <= parent })
894
+ type.last.each { |name| base.extend(Integration.const_defined?(name, false) ? Integration.const_get(name) : Deprecation.const_get(name)) }
895
+ else
896
+ raise ArgumentError, "GraphQL::Armory::Versioning::Base goes in a field, argument, enum value, type membership, object, interface, union, enum, " \
897
+ "scalar, input object, resolver or mutation class, not #{base}. In an interface, include GraphQL::Schema::Interface first"
898
+ end
899
+ end
900
+ end
901
+ end
902
+ end
903
+ end