graphql-armory 0.1.0.pre11 → 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 (43) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +24 -1
  3. data/README.md +4 -4
  4. data/docs/authorization.md +7 -7
  5. data/docs/rate-limiting.md +1 -1
  6. data/docs/versioning.md +540 -0
  7. data/lib/graphql/armory/authorization/adapters/pundit.rb +26 -1
  8. data/lib/graphql/armory/authorization/audit/findings.rb +6 -1
  9. data/lib/graphql/armory/authorization/audit/overrides.rb +8 -2
  10. data/lib/graphql/armory/authorization/audit/payload_reuse.rb +9 -8
  11. data/lib/graphql/armory/authorization/definitions.rb +8 -92
  12. data/lib/graphql/armory/authorization/integration/object.rb +2 -2
  13. data/lib/graphql/armory/authorization/integration.rb +29 -2
  14. data/lib/graphql/armory/authorization/rule.rb +3 -3
  15. data/lib/graphql/armory/authorization.rb +3 -1
  16. data/lib/graphql/armory/definitions.rb +111 -0
  17. data/lib/graphql/armory/location.rb +101 -0
  18. data/lib/graphql/armory/rate_limits/analysis_guard.rb +9 -2
  19. data/lib/graphql/armory/version.rb +1 -1
  20. data/lib/graphql/armory/versioning/audit/command.rb +43 -0
  21. data/lib/graphql/armory/versioning/audit/own_checks.rb +139 -0
  22. data/lib/graphql/armory/versioning/audit/profiles.rb +123 -0
  23. data/lib/graphql/armory/versioning/audit/subscription_triggers.rb +98 -0
  24. data/lib/graphql/armory/versioning/audit.rb +559 -0
  25. data/lib/graphql/armory/versioning/controls.rb +403 -0
  26. data/lib/graphql/armory/versioning/decision.rb +89 -0
  27. data/lib/graphql/armory/versioning/deprecation.rb +95 -0
  28. data/lib/graphql/armory/versioning/diff/command.rb +49 -0
  29. data/lib/graphql/armory/versioning/diff.rb +349 -0
  30. data/lib/graphql/armory/versioning/dump/command.rb +46 -0
  31. data/lib/graphql/armory/versioning/dump.rb +107 -0
  32. data/lib/graphql/armory/versioning/gate.rb +140 -0
  33. data/lib/graphql/armory/versioning/integration.rb +903 -0
  34. data/lib/graphql/armory/versioning/lifecycle.rb +61 -0
  35. data/lib/graphql/armory/versioning/profiles.rb +122 -0
  36. data/lib/graphql/armory/versioning/rspec.rb +38 -0
  37. data/lib/graphql/armory/versioning/versions.rb +111 -0
  38. data/lib/graphql/armory/versioning/view.rb +61 -0
  39. data/lib/graphql/armory/versioning.rb +132 -0
  40. data/lib/graphql/armory.rb +1 -0
  41. data/lib/tasks/graphql_armory.rake +20 -0
  42. metadata +24 -2
  43. data/lib/graphql/armory/authorization/location.rb +0 -79
@@ -21,6 +21,7 @@ module GraphQL
21
21
  end
22
22
 
23
23
  def call(schema)
24
+ @schema = schema
24
25
  @definitions.each do |type|
25
26
  next if Definitions.introspection?(type)
26
27
 
@@ -47,14 +48,19 @@ module GraphQL
47
48
  levels.flat_map { |level| level.public_send(reader).keys }.uniq.each do |name|
48
49
  definitions = levels.filter_map { |level| [level.public_send(reader)[name]].flatten if level.public_send(reader).key?(name) }
49
50
  definitions.flatten.each { |member| @override_paths[member] ||= "#{prefix}.#{member.public_send(name_reader)}" }
50
- falling = definitions.last.size == 1 ? definitions.flatten[0...-1] : definitions.flatten
51
+ falling = definitions.last.size == 1 || twins?(definitions.last) ? definitions[0...-1].flatten : definitions.flatten
51
52
  falling.each { |member| @falling_back[member] ||= "#{prefix}.#{member.public_send(name_reader)}" }
52
- definitions.select { |level| level.size > 1 }.flatten.each { |member| @duplicates << member }
53
+ definitions.select { |level| level.size > 1 && !twins?(level) }.flatten.each { |member| @duplicates << member }
53
54
  end
54
55
  end
55
56
 
56
57
  # graphql-ruby skips the fallback to a lower level only when the request carries a visibility profile. A static
57
58
  # profile runs with a plain Hash, so only `Schema::Visibility` with no profiles, not turned off below, rules it out.
59
+ # Versioning's twins: definitions on one level that no served version sees together are one member.
60
+ def twins?(level)
61
+ level.size > 1 && defined?(Versioning) && Versioning.respond_to?(:disjoint?) && Versioning.disjoint?(@schema, level)
62
+ end
63
+
58
64
  def visibility_without_fallback?(schema)
59
65
  visibility = schema.visibility
60
66
  return false unless visibility
@@ -27,7 +27,7 @@ module GraphQL
27
27
  end
28
28
  return if payloads.empty?
29
29
 
30
- named = definitions.to_h { |type| [type.graphql_name, type] }
30
+ named = definitions.group_by(&:graphql_name)
31
31
  fields.each { |type, field| note(type, field, objects, payloads, named) }
32
32
  end
33
33
 
@@ -61,21 +61,22 @@ module GraphQL
61
61
  end
62
62
 
63
63
  def note(type, field, objects, payloads, named)
64
- target = returned_type(field, named) or return
65
- reused = members(target, objects) & payloads
66
- return if reused.empty? || own_payload?(field, target)
64
+ targets = returned_types(field, named)
65
+ reused = targets.flat_map { |target| members(target, objects) }.uniq & payloads
66
+ return if reused.empty? || (targets.one? && own_payload?(field, targets.first))
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
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
- # A shadowed definition may name a type that never resolved; it cannot serve anything.
74
- def returned_type(field, named)
73
+ # A shadowed definition may name a type that never resolved; it cannot serve anything. A late-bound name with
74
+ # several definitions (Versioning's type twins) may mean any of them.
75
+ def returned_types(field, named)
75
76
  type = field.type.unwrap
76
- type.is_a?(GraphQL::Schema::LateBoundType) ? named[type.graphql_name] : type
77
+ type.is_a?(GraphQL::Schema::LateBoundType) ? named.fetch(type.graphql_name, []) : [type]
77
78
  rescue NameError, GraphQL::Error
78
- nil
79
+ []
79
80
  end
80
81
 
81
82
  def members(target, objects)
@@ -1,24 +1,15 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "set"
3
+ require "graphql/armory/definitions"
4
4
 
5
5
  module GraphQL
6
6
  module Armory
7
7
  module Authorization
8
- # Every definition a schema holds, hidden or not. `schema.types` is read with no request, so it leaves out what is
9
- # hidden there and a request can still reach: a type or field hidden by `visible?`, or one of several definitions of
10
- # a name. This follows the definitions themselves from the roots and `orphan_types`.
8
+ # Every definition a schema holds, hidden or not (`Armory::Definitions`), plus what `schema.types` lists, which the
9
+ # audit must not miss either.
11
10
  module Definitions
12
11
  def self.call(schema, &on_listing_error)
13
- found = Set.new.compare_by_identity
14
- pending = [schema.query, schema.mutation, schema.subscription, *schema.orphan_types, *directive_types(schema), *introspection_field_types(schema), *listed_types(schema, &on_listing_error)]
15
- until pending.empty?
16
- type = pending.pop
17
- next if !type.respond_to?(:kind) || !found.add?(type)
18
-
19
- pending.concat(referenced_types(type))
20
- end
21
- found.to_a
12
+ Armory::Definitions.(schema, listed_types(schema, &on_listing_error))
22
13
  end
23
14
 
24
15
  # With only static profiles, graphql-ruby refuses to list types without naming one: the roots still lead everywhere.
@@ -36,85 +27,10 @@ module GraphQL
36
27
  end
37
28
  private_class_method :listed_types
38
29
 
39
- # A directive argument is client input like any other, and only `schema.types` used to reach its input objects.
40
- def self.directive_types(schema)
41
- schema.directives.values.flat_map { |directive| arguments_of(directive) }.compact
42
- end
43
- private_class_method :directive_types
44
-
45
- # `introspection(true)` is a flag anyone can set, and graphql-ruby serves such a type like any other. The `__` prefix
46
- # is reserved for introspection by the GraphQL spec: built-in types, what `Schema.introspection` replaces them with,
47
- # and their copies all carry it.
48
- def self.introspection?(type)
49
- type.introspection? && type.graphql_name.start_with?("__")
50
- end
51
-
52
- # `Schema.introspection` can add entry points and dynamic fields, which no type holds and a client can reach.
53
- def self.introspection_field_types(schema)
54
- system = schema.introspection_system
55
- (system.entry_points + system.dynamic_fields).flat_map { |field| references_of(field) }.flatten.compact
56
- end
57
- private_class_method :introspection_field_types
58
-
59
- def self.connection?(type)
60
- type.is_a?(Class) && type.include?(GraphQL::Types::Relay::ConnectionBehaviors)
61
- end
62
-
63
- def self.referenced_types(type)
64
- references = []
65
- references << fields_of(type)
66
- references << arguments_of(type) if type.kind.input_object?
67
- references.concat(type.interface_type_memberships.map(&:abstract_type)) if type.respond_to?(:interface_type_memberships)
68
- references.concat(type.orphan_types) if type.kind.interface?
69
- references.concat(included_interfaces(type)) if type.kind.interface?
70
- references.concat(type.type_memberships.map(&:object_type)) if type.kind.union?
71
- references << type.node_type if connection?(type)
72
- references.flatten.compact
73
- end
74
- private_class_method :referenced_types
75
-
76
- # An interface brought in with `include` makes no type membership, and its fields are served all the same.
77
- def self.included_interfaces(type)
78
- type.ancestors.select { |ancestor| !ancestor.equal?(type) && ancestor.respond_to?(:kind) && ancestor.kind.interface? }
79
- end
80
- private_class_method :included_interfaces
81
-
82
- # Every definition of every field, nearest first: a hidden one falls back to the next of its name, and
83
- # `all_field_definitions` merges them by name. `field ... do ... end` blocks are loaded here, because only
84
- # `schema.types` or a request loads them, and the audit reads arguments from them.
85
- def self.fields_at_every_level(type)
86
- return [] unless type.respond_to?(:all_field_definitions)
87
-
88
- fields = type.ancestors.select { |ancestor| ancestor.respond_to?(:own_fields) }.flat_map { |ancestor| ancestor.own_fields.values.flatten }
89
- fields.each { |field| field.ensure_loaded if field.respond_to?(:ensure_loaded) }
90
- fields.uniq
91
- end
92
-
93
- # A shadowed definition is only served by a fallback, so one whose type cannot load fails nothing that runs today.
94
- def self.shadowed?(type, field)
95
- !type.all_field_definitions.include?(field)
96
- end
97
-
98
- def self.fields_of(type)
99
- fields_at_every_level(type).map do |field|
100
- references_of(field)
101
- rescue GraphQL::Error
102
- raise unless shadowed?(type, field)
103
-
104
- nil
105
- end
106
- end
107
- private_class_method :fields_of
108
-
109
- def self.references_of(field)
110
- [field.type.unwrap, arguments_of(field)]
111
- end
112
- private_class_method :references_of
113
-
114
- def self.arguments_of(member)
115
- member.all_argument_definitions.flat_map { |argument| [argument.type.unwrap, argument.loads] }
116
- end
117
- private_class_method :arguments_of
30
+ def self.introspection?(type) = Armory::Definitions.introspection?(type)
31
+ def self.connection?(type) = Armory::Definitions.connection?(type)
32
+ def self.fields_at_every_level(type) = Armory::Definitions.fields_at_every_level(type)
33
+ def self.shadowed?(type, field) = Armory::Definitions.shadowed?(type, field)
118
34
  end
119
35
  end
120
36
  end
@@ -61,11 +61,11 @@ module GraphQL
61
61
  end
62
62
 
63
63
  def authorized?(object, context)
64
- rule = armory_rule
64
+ rule = Integration.type_rule(self, context)
65
65
  return false if rule.nil?
66
66
 
67
67
  Integration.refuse_unobservable(self, rule, context)
68
- Integration.allowed?(object, Integration.with_owner_model(rule, self), context) && super
68
+ Integration.allowed?(object, rule, context) && super
69
69
  rescue GraphQL::UnauthorizedError
70
70
  raise
71
71
  rescue StandardError => error
@@ -42,7 +42,7 @@ module GraphQL
42
42
  return Adapters::Null.new.scope(nil, items, rule) if rule.nil?
43
43
 
44
44
  configuration = configuration(context)
45
- 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)
46
46
  end
47
47
 
48
48
  # Looks an object up inside the user's scope, by primary key unless a key is given.
@@ -110,6 +110,16 @@ module GraphQL
110
110
  end
111
111
  end
112
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
+
113
123
  # The rule with the model its owner wraps, the one the audit reads: named by the rule, or named like the type.
114
124
  def self.with_owner_model(rule, owner)
115
125
  return rule if rule.none? || rule.policy || rule.model || !owner.respond_to?(:armory_model)
@@ -187,12 +197,29 @@ module GraphQL
187
197
  store = context.namespace(:armory)
188
198
  authorize = store[:authorize] ||= begin
189
199
  configuration = configuration(context)
190
- 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)
191
201
  end
192
202
 
193
203
  authorize.(subject, rule, context)
194
204
  end
195
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
+
196
223
  # Whether a type or field may appear in the schema this user sees. The question is asked of the
197
224
  # model's class, with no record, so the rule's action must be one a policy can answer that way.
198
225
  # `Schema.types` with no context sees the whole schema. A schema dump asks for it explicitly with
@@ -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,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "graphql/armory/authorization/errors"
4
- require "graphql/armory/authorization/location"
4
+ require "graphql/armory/location"
5
5
  require "graphql/armory/authorization/configuration"
6
6
  require "graphql/armory/authorization/rule"
7
7
  require "graphql/armory/authorization/memo"
@@ -30,6 +30,8 @@ module GraphQL
30
30
  module Authorization
31
31
  # Authorization's telemetry is the gem's: one Telemetry for every module.
32
32
  Telemetry = Armory::Telemetry
33
+ # So is Location, which Versioning's audit uses too.
34
+ Location = Armory::Location
33
35
  end
34
36
 
35
37
  # Deny-by-default authorization. The core (Authorize, Scope) knows nothing about
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+
5
+ module GraphQL
6
+ module Armory
7
+ # Every definition a schema holds, hidden or not, read with no request. graphql-ruby's lookups with no request leave
8
+ # out what is hidden there and a request can still reach: a type or field hidden by `visible?`, or one of several
9
+ # definitions of a name. This follows the definitions themselves from the roots, `orphan_types` and `extra`.
10
+ module Definitions
11
+ def self.call(schema, extra = [])
12
+ found = Set.new.compare_by_identity
13
+ pending = [schema.query, schema.mutation, schema.subscription, *schema.orphan_types, *directive_types(schema), *introspection_field_types(schema), *extra]
14
+ until pending.empty?
15
+ type = pending.pop
16
+ next if !type.respond_to?(:kind) || !found.add?(type)
17
+
18
+ pending.concat(referenced_types(type))
19
+ end
20
+ found.to_a
21
+ end
22
+
23
+ # A directive argument is client input like any other, and only `schema.types` used to reach its input objects.
24
+ def self.directive_types(schema)
25
+ schema.directives.values.flat_map { |directive| arguments_of(directive) }.compact
26
+ end
27
+ private_class_method :directive_types
28
+
29
+ # `introspection(true)` is a flag anyone can set, and graphql-ruby serves such a type like any other. The `__` prefix
30
+ # is reserved for introspection by the GraphQL spec: built-in types, what `Schema.introspection` replaces them with,
31
+ # and their copies all carry it.
32
+ def self.introspection?(type)
33
+ type.introspection? && type.graphql_name.start_with?("__")
34
+ end
35
+
36
+ # `Schema.introspection` can add entry points and dynamic fields, which no type holds and a client can reach.
37
+ def self.introspection_field_types(schema)
38
+ system = schema.introspection_system
39
+ (system.entry_points + system.dynamic_fields).flat_map { |field| references_of(field) }.flatten.compact
40
+ end
41
+ private_class_method :introspection_field_types
42
+
43
+ def self.connection?(type)
44
+ type.is_a?(Class) && type.include?(GraphQL::Types::Relay::ConnectionBehaviors)
45
+ end
46
+
47
+ def self.referenced_types(type)
48
+ references = []
49
+ references << fields_of(type)
50
+ references << arguments_of(type) if type.kind.input_object?
51
+ references.concat(interfaces_of(type)) if type.respond_to?(:interface_type_memberships)
52
+ references.concat(type.orphan_types) if type.kind.interface?
53
+ references.concat(included_interfaces(type)) if type.kind.interface?
54
+ references.concat(type.type_memberships.map(&:object_type)) if type.kind.union?
55
+ references << type.node_type if connection?(type)
56
+ references.flatten.compact
57
+ end
58
+ private_class_method :referenced_types
59
+
60
+ # A String or `LateBoundType` that graphql-ruby never matched to an interface stays a bare membership: it has no
61
+ # type to follow.
62
+ def self.interfaces_of(type)
63
+ type.interface_type_memberships.filter_map { |membership| membership.abstract_type if membership.respond_to?(:abstract_type) }
64
+ end
65
+ private_class_method :interfaces_of
66
+
67
+ # An interface brought in with `include` makes no type membership, and its fields are served all the same.
68
+ def self.included_interfaces(type)
69
+ type.ancestors.select { |ancestor| !ancestor.equal?(type) && ancestor.respond_to?(:kind) && ancestor.kind.interface? }
70
+ end
71
+ private_class_method :included_interfaces
72
+
73
+ # Every definition of every field, nearest first: a hidden one falls back to the next of its name, and
74
+ # `all_field_definitions` merges them by name. `field ... do ... end` blocks are loaded here, because only
75
+ # `schema.types` or a request loads them, and the audit reads arguments from them.
76
+ def self.fields_at_every_level(type)
77
+ return [] unless type.respond_to?(:all_field_definitions)
78
+
79
+ fields = type.ancestors.select { |ancestor| ancestor.respond_to?(:own_fields) }.flat_map { |ancestor| ancestor.own_fields.values.flatten }
80
+ fields.each { |field| field.ensure_loaded if field.respond_to?(:ensure_loaded) }
81
+ fields.uniq
82
+ end
83
+
84
+ # A shadowed definition is only served by a fallback, so one whose type cannot load fails nothing that runs today.
85
+ def self.shadowed?(type, field)
86
+ !type.all_field_definitions.include?(field)
87
+ end
88
+
89
+ def self.fields_of(type)
90
+ fields_at_every_level(type).map do |field|
91
+ references_of(field)
92
+ rescue GraphQL::Error
93
+ raise unless shadowed?(type, field)
94
+
95
+ nil
96
+ end
97
+ end
98
+ private_class_method :fields_of
99
+
100
+ def self.references_of(field)
101
+ [field.type.unwrap, arguments_of(field)]
102
+ end
103
+ private_class_method :references_of
104
+
105
+ def self.arguments_of(member)
106
+ member.all_argument_definitions.flat_map { |argument| [argument.type.unwrap, argument.loads] }
107
+ end
108
+ private_class_method :arguments_of
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ # Where something of the app's schema was written, as "path:line", for the audit's report. graphql-ruby keeps no
6
+ # location for a field or an argument, so the plugin's field and argument classes record the line that declared them,
7
+ # and a type records the line of its `authorize`. Anything else falls back to the line of its class, and a type
8
+ # graphql-ruby generated (a mutation's payload, a connection, an edge) to the class it was generated from.
9
+ #
10
+ # Limits: a schema built from SDL has no Ruby lines; a field declared by a helper method points to the helper; a class
11
+ # reopened in several files gives the first one.
12
+ module Location
13
+ GRAPHQL_RUBY_PATH = "#{File.dirname(GraphQL::Schema.method(:from_definition).source_location.first)}/"
14
+ ARMORY_PATH = "#{__dir__}/"
15
+ # The directory the app started in, read once: a later `Dir.chdir` must not change the report's text. None when the
16
+ # directory is gone, and then paths stay absolute.
17
+ ROOT = begin
18
+ "#{Dir.pwd}/"
19
+ rescue SystemCallError
20
+ nil
21
+ end
22
+
23
+ # The first line of the caller's stack outside graphql-ruby and this gem: where the app declared it. An `initialize`
24
+ # is skipped too: an app's field or argument class, or another gem's module, may define one that calls super into
25
+ # the plugin's, and its line is the same for every field.
26
+ def self.declared
27
+ found = caller_locations(2, 40)&.find do |location|
28
+ path = location.absolute_path || location.path
29
+ !path.start_with?("<", GRAPHQL_RUBY_PATH, ARMORY_PATH) && location.base_label != "initialize"
30
+ end
31
+ found && "#{found.absolute_path || found.path}:#{found.lineno}"
32
+ end
33
+
34
+ # "path:line" for a method, a field, an argument, a type or a class, relative to the directory the app started in
35
+ # when it is inside it, or nil when there is no line to give.
36
+ def self.of(thing)
37
+ relative(absolute(thing))
38
+ end
39
+
40
+ def self.absolute(thing)
41
+ case thing
42
+ when nil then nil
43
+ when String then thing
44
+ when Method, UnboundMethod then join(thing.source_location)
45
+ when GraphQL::Schema::Field, GraphQL::Schema::Argument
46
+ (thing.armory_location if thing.respond_to?(:armory_location)) || absolute(thing.owner)
47
+ when Module
48
+ (thing.armory_rule_location if thing.respond_to?(:armory_rule_location)) || constant(thing) || generated_from(thing)
49
+ end
50
+ end
51
+ private_class_method :absolute
52
+
53
+ # graphql-ruby generates some types as classes with no constant: a mutation's payload, and a type's connection and
54
+ # edge. They point to the class they were generated from, which was written somewhere.
55
+ # Only an object type is followed: a schema also answers `mutation`, with its root type. A connection of connections
56
+ # can lead back to itself, so each class is visited once, and the walk stops after a few steps.
57
+ def self.generated_from(type)
58
+ seen = {}.compare_by_identity
59
+ while type.is_a?(Class) && type < GraphQL::Schema::Object && !seen.key?(type) && seen.size < 16
60
+ seen[type] = true
61
+ source = type.mutation if type.respond_to?(:mutation)
62
+ source = nil unless source.is_a?(Class) && source < GraphQL::Schema::Resolver
63
+ source ||= type.node_type if type.respond_to?(:node_type)
64
+ return unless source.is_a?(Module)
65
+
66
+ found = (source.armory_rule_location if source.respond_to?(:armory_rule_location)) || constant(source)
67
+ return found if found
68
+
69
+ type = source
70
+ end
71
+ rescue StandardError, NotImplementedError
72
+ nil
73
+ end
74
+ private_class_method :generated_from
75
+
76
+ # Only when the name leads back to this class: a class may answer another constant's name. A location is never worth
77
+ # failing the audit, so a `name` that raises gives none.
78
+ def self.constant(mod)
79
+ name = mod.name
80
+ return if !name.is_a?(String) || name.empty? || !Object.const_get(name).equal?(mod)
81
+
82
+ join(Object.const_source_location(name))
83
+ rescue StandardError, NotImplementedError
84
+ nil
85
+ end
86
+ private_class_method :constant
87
+
88
+ def self.join(pair)
89
+ pair && !pair.empty? && pair.first ? "#{pair.first}:#{pair.last}" : nil
90
+ end
91
+ private_class_method :join
92
+
93
+ def self.relative(location)
94
+ return location if location.nil? || ROOT.nil?
95
+
96
+ location.start_with?(ROOT) ? location.delete_prefix(ROOT) : location
97
+ end
98
+ private_class_method :relative
99
+ end
100
+ end
101
+ 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.pre11"
5
+ VERSION = "0.1.0.pre13"
6
6
  end
7
7
  end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Versioning
6
+ class Audit
7
+ # What `rake "graphql_armory:versions: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:versions:audit[YourSchema]\"") if schema_name.to_s.empty?
23
+
24
+ report = Audit.(Object.const_get(schema_name))
25
+ @out.print(report)
26
+ report.ok? ? 0 : 1
27
+ rescue NameError => error
28
+ raise unless schema_name.to_s.split("::").include?(error.name.to_s)
29
+
30
+ fail_with("No schema named #{schema_name}")
31
+ end
32
+
33
+ private
34
+
35
+ def fail_with(message)
36
+ @out.puts(message)
37
+ 1
38
+ end
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end