graphql-armory 0.1.0.pre7 → 0.1.0.pre9

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 (62) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +81 -0
  3. data/README.md +6 -5
  4. data/docs/authorization.md +220 -10
  5. data/docs/encrypted-ids.md +1 -1
  6. data/docs/persisted-queries.md +111 -19
  7. data/docs/rate-limiting.md +32 -11
  8. data/docs/telemetry.md +31 -8
  9. data/exe/graphql-armory-publish +6 -0
  10. data/lib/graphql/armory/authorization/adapters/cancan.rb +17 -4
  11. data/lib/graphql/armory/authorization/adapters/pundit.rb +79 -14
  12. data/lib/graphql/armory/authorization/adapters/substitute.rb +4 -1
  13. data/lib/graphql/armory/authorization/audit/baseline.rb +191 -0
  14. data/lib/graphql/armory/authorization/audit/command.rb +57 -8
  15. data/lib/graphql/armory/authorization/audit/denial_hooks.rb +29 -0
  16. data/lib/graphql/armory/authorization/audit/edge_rules.rb +36 -0
  17. data/lib/graphql/armory/authorization/audit/findings.rb +35 -0
  18. data/lib/graphql/armory/authorization/audit/foreign_policies.rb +90 -0
  19. data/lib/graphql/armory/authorization/audit/input_loads.rb +26 -0
  20. data/lib/graphql/armory/authorization/audit/interface_rules.rb +42 -0
  21. data/lib/graphql/armory/authorization/audit/introspection_fields.rb +40 -0
  22. data/lib/graphql/armory/authorization/audit/library_methods.rb +24 -0
  23. data/lib/graphql/armory/authorization/audit/observed_rules.rb +58 -0
  24. data/lib/graphql/armory/authorization/audit/overrides.rb +81 -0
  25. data/lib/graphql/armory/authorization/audit/own_checks.rb +144 -0
  26. data/lib/graphql/armory/authorization/audit/payload_reuse.rb +95 -0
  27. data/lib/graphql/armory/authorization/audit/plain_resolvers.rb +85 -0
  28. data/lib/graphql/armory/authorization/audit/reach.rb +75 -0
  29. data/lib/graphql/armory/authorization/audit/report.rb +7 -1
  30. data/lib/graphql/armory/authorization/audit/type_rules.rb +282 -0
  31. data/lib/graphql/armory/authorization/audit/visibility_models.rb +83 -0
  32. data/lib/graphql/armory/authorization/audit.rb +59 -192
  33. data/lib/graphql/armory/authorization/authorize.rb +35 -9
  34. data/lib/graphql/armory/authorization/configuration.rb +32 -3
  35. data/lib/graphql/armory/authorization/definitions.rb +121 -0
  36. data/lib/graphql/armory/authorization/integration/argument.rb +24 -6
  37. data/lib/graphql/armory/authorization/integration/field.rb +36 -6
  38. data/lib/graphql/armory/authorization/integration/object.rb +9 -1
  39. data/lib/graphql/armory/authorization/integration/resolver.rb +2 -0
  40. data/lib/graphql/armory/authorization/integration/schema.rb +7 -0
  41. data/lib/graphql/armory/authorization/integration.rb +36 -4
  42. data/lib/graphql/armory/authorization/rspec.rb +10 -4
  43. data/lib/graphql/armory/authorization/rule.rb +24 -3
  44. data/lib/graphql/armory/authorization/scope.rb +6 -6
  45. data/lib/graphql/armory/authorization.rb +4 -1
  46. data/lib/graphql/armory/ids.rb +11 -11
  47. data/lib/graphql/armory/persisted_queries/manifest.rb +2 -0
  48. data/lib/graphql/armory/persisted_queries/manifests.rb +69 -0
  49. data/lib/graphql/armory/persisted_queries/publisher.rb +127 -0
  50. data/lib/graphql/armory/persisted_queries/redis_store.rb +137 -0
  51. data/lib/graphql/armory/persisted_queries.rb +55 -16
  52. data/lib/graphql/armory/railtie.rb +10 -0
  53. data/lib/graphql/armory/rate_limits/analysis_guard.rb +79 -0
  54. data/lib/graphql/armory/rate_limits/concurrency.rb +91 -14
  55. data/lib/graphql/armory/rate_limits/points.rb +91 -14
  56. data/lib/graphql/armory/rate_limits/time.rb +107 -19
  57. data/lib/graphql/armory/rate_limits.rb +29 -5
  58. data/lib/graphql/armory/telemetry.rb +71 -9
  59. data/lib/graphql/armory/version.rb +1 -1
  60. data/lib/graphql/armory.rb +1 -0
  61. data/lib/tasks/graphql_armory.rake +11 -4
  62. metadata +28 -3
@@ -14,37 +14,63 @@ module GraphQL
14
14
  @telemetry = telemetry
15
15
  end
16
16
 
17
- def self.build(context, adapter:, sinks: [])
18
- new(adapter: adapter, memo: Memo.build(context), telemetry: Telemetry.build(sinks: sinks))
17
+ def self.build(context, adapter:, sinks: [], on_sink_error: nil)
18
+ new(adapter: adapter, memo: Memo.build(context), telemetry: Telemetry.build(sinks: sinks, on_sink_error: on_sink_error))
19
19
  end
20
20
 
21
- def self.call(subject, rule, context, adapter:, sinks: [])
22
- build(context, adapter: adapter, sinks: sinks).(subject, rule, context)
21
+ def self.call(subject, rule, context, adapter:, sinks: [], on_sink_error: nil)
22
+ build(context, adapter: adapter, sinks: sinks, on_sink_error: on_sink_error).(subject, rule, context)
23
23
  end
24
24
 
25
25
  def call(subject, rule, context)
26
- return bypass(subject, rule) if rule.none?
26
+ return bypass(subject, rule, context) if rule.none?
27
27
 
28
28
  memo.fetch(subject, rule) { decide(subject, rule, context) }
29
29
  end
30
30
 
31
31
  private
32
32
 
33
- def bypass(subject, rule)
34
- telemetry.record(:bypassed, type: subject.class.name, reason: rule.reason)
33
+ def bypass(subject, rule, context)
34
+ telemetry.record(:bypassed, context: context, type: class_name(subject), reason: rule.reason)
35
35
  true
36
36
  end
37
37
 
38
+ # Observing opens one thing only: a clear "no" to a read, with someone listening, from an adapter someone configured.
39
+ # A mutation or a subscription keeps refusing, even on a read inside its response: only a query runs nothing it cannot undo.
40
+ def observes?(rule, context)
41
+ rule.observed? && telemetry.listening? && !adapter.is_a?(Adapters::Null) && read_only?(context)
42
+ end
43
+
44
+ # A partial always answers `query?`, whatever the operation that ran it: only the query it came from can tell.
45
+ def read_only?(context)
46
+ query = context.query if context.respond_to?(:query)
47
+ query = query.query while defined?(GraphQL::Query::Partial) && query.is_a?(GraphQL::Query::Partial)
48
+ query.respond_to?(:query?) && query.query? == true
49
+ end
50
+
51
+ def observe(subject, rule, context)
52
+ telemetry.record(:observed, context: context, type: class_name(subject), action: rule.action, reason: rule.observe)
53
+ true
54
+ end
55
+
56
+ # The record's own `class` can be a data member, and the error for it quotes the record.
57
+ def class_name(subject)
58
+ ::Kernel.instance_method(:class).bind_call(subject).name
59
+ end
60
+
38
61
  def decide(subject, rule, context)
39
62
  answer = adapter.authorized?(adapter.actor(context), subject, rule)
40
63
 
41
64
  case answer
42
65
  when true, false, nil
66
+ return observe(subject, rule, context) if answer != true && observes?(rule, context)
67
+
43
68
  allowed = answer == true
44
- telemetry.record(allowed ? :allowed : :denied, type: subject.class.name, action: rule.action)
69
+ telemetry.record(allowed ? :allowed : :denied, context: context, type: class_name(subject), action: rule.action)
45
70
  allowed
46
71
  else
47
- raise AdapterError, "#{adapter.class} answered #{answer.inspect}; it must answer true, false or nil"
72
+ # The class alone: the answer may be the record, and on a relation `inspect` runs the query.
73
+ raise AdapterError, "#{adapter.class} answered a #{::Kernel.instance_method(:class).bind_call(answer)}; it must answer true, false or nil"
48
74
  end
49
75
  end
50
76
 
@@ -7,21 +7,50 @@ module GraphQL
7
7
  class Configuration
8
8
  MODES = %i[null error raise].freeze
9
9
 
10
- attr_reader :adapter, :on_unauthorized, :sinks
10
+ DENIAL_HOOKS = %i[unauthorized_field unauthorized_object].freeze
11
11
 
12
- def initialize(adapter:, on_unauthorized: :null, sinks: [])
12
+ OWN_CHECKS = %i[authorized? authorizes? authorized_new wrap unauthorized_object visible? scope_items reauthorize_scoped_objects].freeze
13
+
14
+ attr_reader :adapter, :on_unauthorized, :sinks, :on_sink_error, :own_denial_hooks, :own_checks
15
+
16
+ def initialize(adapter:, on_unauthorized: :null, sinks: [], on_sink_error: nil, own_denial_hooks: {}, own_checks: {})
13
17
  unless MODES.include?(on_unauthorized)
14
18
  raise ArgumentError, "on_unauthorized must be one of #{MODES.inspect}, got #{on_unauthorized.inspect}"
15
19
  end
20
+ check_own_denial_hooks(own_denial_hooks)
21
+ check_own_checks(own_checks)
16
22
 
23
+ @own_checks = own_checks.to_h { |holder, methods| [holder, methods.to_h { |name, reason| [name, reason.dup.freeze] }.freeze] }.freeze
17
24
  @adapter = resolve(adapter)
18
25
  @on_unauthorized = on_unauthorized
19
- Telemetry.build(sinks: sinks) # raises at boot when the sinks are not callables
26
+ @own_denial_hooks = own_denial_hooks.to_h { |hook, reason| [hook, reason.dup.freeze] }.freeze
27
+ Telemetry.build(sinks: sinks, on_sink_error: on_sink_error) # raises at boot when the sinks are not callables
20
28
  @sinks = sinks
29
+ @on_sink_error = on_sink_error
21
30
  end
22
31
 
23
32
  private
24
33
 
34
+ def check_own_denial_hooks(hooks)
35
+ valid = hooks.is_a?(Hash) && hooks.all? do |hook, reason|
36
+ DENIAL_HOOKS.include?(hook) && reason.is_a?(String) && !reason.strip.empty?
37
+ end
38
+ return if valid
39
+
40
+ raise ArgumentError, "own_denial_hooks must map #{DENIAL_HOOKS.inspect} to the reason you keep your own, got #{hooks.inspect}"
41
+ end
42
+
43
+ def check_own_checks(checks)
44
+ valid = checks.is_a?(Hash) && checks.all? do |holder, methods|
45
+ holder.is_a?(Module) && methods.is_a?(Hash) && methods.all? do |name, reason|
46
+ OWN_CHECKS.include?(name) && reason.is_a?(String) && !reason.strip.empty?
47
+ end
48
+ end
49
+ return if valid
50
+
51
+ raise ArgumentError, "own_checks must map a class to #{OWN_CHECKS.inspect} and the reason you keep each, got #{checks.inspect}"
52
+ end
53
+
25
54
  def resolve(adapter)
26
55
  case adapter
27
56
  when :pundit then Adapters::Pundit.new
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+
5
+ module GraphQL
6
+ module Armory
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`.
11
+ module Definitions
12
+ 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
22
+ end
23
+
24
+ # With only static profiles, graphql-ruby refuses to list types without naming one: the roots still lead everywhere.
25
+ # A `visible_when:` that cannot name its model raises here, on the first listing only. The roots still lead to the
26
+ # rest, and the audit passes a block because it must not say ok after that.
27
+ def self.listed_types(schema)
28
+ schema.types.values
29
+ rescue ConfigurationError => error
30
+ yield error if block_given?
31
+ []
32
+ rescue ArgumentError
33
+ raise unless schema.visibility
34
+
35
+ []
36
+ end
37
+ private_class_method :listed_types
38
+
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
118
+ end
119
+ end
120
+ end
121
+ end
@@ -17,10 +17,11 @@ module GraphQL
17
17
  # The question is asked of the parent object when it is an instance of the model, else of the model's
18
18
  # class (a root field has no record). The model is the one the field's type wraps, or `model:`.
19
19
  module Argument
20
- def initialize(*args, authorize: nil, reason: nil, model: nil, visible_when: nil, **kwargs, &block)
20
+ def initialize(*args, authorize: nil, reason: nil, model: nil, visible_when: nil, override_reason: nil, **kwargs, &block)
21
21
  unless [nil, :none].include?(authorize) || authorize.is_a?(Symbol)
22
22
  raise ArgumentError, "an argument's `authorize:` is an action or :none, not #{authorize.inspect}"
23
23
  end
24
+ raise ConfigurationError, "override_reason: must say why the override is safe" if !override_reason.nil? && override_reason.to_s.strip.empty?
24
25
 
25
26
  if authorize && authorize != :none && kwargs.key?(:default_value)
26
27
  raise ArgumentError,
@@ -32,32 +33,49 @@ module GraphQL
32
33
  @armory_reason = reason
33
34
  @armory_model = model
34
35
  @armory_visible_when = visible_when&.to_sym
36
+ @armory_override_reason = override_reason
35
37
  Rule.none(reason: reason) if authorize == :none
36
38
  super(*args, **kwargs, &block)
37
39
  end
38
40
 
39
- attr_reader :armory_declared, :armory_reason, :armory_visible_when
41
+ attr_reader :armory_declared, :armory_reason, :armory_visible_when, :armory_override_reason
40
42
 
41
43
  def armory_model
42
- @armory_model || armory_field_model
44
+ return armory_field_model unless @armory_model
45
+ return @armory_model unless @armory_model.is_a?(String)
46
+
47
+ armory_named_model
43
48
  end
44
49
 
45
50
  def authorized?(object, value, context)
46
51
  return super if @armory_declared.nil? || @armory_declared == :none
47
52
 
48
53
  model = armory_model
49
- subject = object.is_a?(model) ? object : model
50
- Integration.allowed?(subject, Rule.new(@armory_declared, attribute: keyword), context) && super
54
+ subject = Module === model && object.is_a?(model) ? object : model
55
+ Integration.allowed?(subject, Rule.new(@armory_declared, policy: armory_policy, attribute: keyword, model: model), context) && super
51
56
  end
52
57
 
53
58
  def visible?(context)
54
59
  return super unless @armory_visible_when
55
60
 
56
- super && Integration.visible?(armory_model, Rule.new(@armory_visible_when, attribute: keyword), context)
61
+ super && Integration.visible?(armory_model, Rule.new(@armory_visible_when, policy: armory_policy, attribute: keyword, model: armory_model), context)
62
+ end
63
+
64
+ # The `policy:` of the type or resolver the argument belongs to.
65
+ def armory_policy
66
+ type = owner.respond_to?(:owner) ? owner.owner : owner
67
+ type.armory_rule&.policy if type.respond_to?(:armory_rule)
57
68
  end
58
69
 
59
70
  private
60
71
 
72
+ # `is_a?` needs a Module, and Pundit reads a String as a record. A name with no constant stays a model name.
73
+ def armory_named_model
74
+ Object.const_get(@armory_model)
75
+ rescue NameError
76
+ @armory_model.to_sym
77
+ end
78
+
61
79
  def armory_field_model
62
80
  type = owner.respond_to?(:owner) ? owner.owner : owner
63
81
  model = type.armory_model if type.respond_to?(:armory_model)
@@ -10,6 +10,7 @@ module GraphQL
10
10
  # field :id, ID, authorize: :none, reason: "ids are public" # declared bypass
11
11
  # field :owner_id, ID, authorize: true # the parent type's own action
12
12
  # field :notes, String, authorize: :manage, visible_when: :export # hidden from users who cannot export
13
+ # field :notes, String, authorize: :manage, observe: "rollout" # served and recorded, see Authorize
13
14
  #
14
15
  # A field with no rule is covered by its type's rule, unless the type is bypassed:
15
16
  # coverage does not propagate from a bypass, so that field is denied.
@@ -19,7 +20,17 @@ module GraphQL
19
20
  module Field
20
21
  # `find_by: :id` looks the object up inside the user's scope instead of calling the resolver.
21
22
  # `loads:` arguments also load through the scope unless `load_through_scope: false`.
22
- def initialize(*args, authorize: nil, reason: nil, find_by: nil, load_through_scope: true, visible_when: nil, **kwargs, &block)
23
+ def initialize(*args, authorize: nil, reason: nil, observe: nil, find_by: nil, load_through_scope: true, visible_when: nil, override_reason: nil, **kwargs, &block)
24
+ raise ConfigurationError, "override_reason: must say why the override is safe" if !override_reason.nil? && override_reason.to_s.strip.empty?
25
+
26
+ if !observe.nil? && (!authorize.is_a?(Symbol) || authorize == :none)
27
+ raise ArgumentError, "observe: needs an action of the field's own: `authorize: :manage, observe: \"...\"`"
28
+ end
29
+ raise ArgumentError, "observe: does not apply to a field with a resolver or a mutation: what it runs cannot be undone" if !observe.nil? && kwargs[:resolver_class]
30
+ Rule.new(authorize, observe: observe) unless observe.nil?
31
+
32
+ @armory_observe = observe
33
+ @armory_override_reason = override_reason
23
34
  @armory_declared = authorize
24
35
  @armory_reason = reason
25
36
  @armory_visible_when = visible_when&.to_sym
@@ -29,7 +40,7 @@ module GraphQL
29
40
  extension(Integration::FindBy, key: find_by) if find_by
30
41
  end
31
42
 
32
- attr_reader :armory_declared, :armory_reason, :armory_visible_when
43
+ attr_reader :armory_declared, :armory_reason, :armory_observe, :armory_visible_when, :armory_override_reason
33
44
 
34
45
  def armory_load_through_scope?
35
46
  @armory_load_through_scope
@@ -57,15 +68,34 @@ module GraphQL
57
68
  raise ConfigurationError, "#{owner.graphql_name}.#{original_name} uses visible_when:, so its type must include Base"
58
69
  end
59
70
 
60
- rule = Rule.new(@armory_visible_when, attribute: original_name)
71
+ rule = Rule.new(@armory_visible_when, policy: armory_policy, attribute: original_name)
61
72
  super && Integration.visible?(owner.armory_model, rule, context)
62
73
  end
63
74
 
75
+ # The `policy:` of the type that defines the field: a rule on the field asks it another question.
76
+ def armory_policy
77
+ owner.armory_rule&.policy if owner.respond_to?(:armory_rule)
78
+ end
79
+
64
80
  def authorized?(object, args, context)
65
81
  rule = armory_rule_for(owner, context)
66
82
  return false if rule.nil?
83
+ if resolver && rule.is_a?(Rule) && rule.observed?
84
+ raise ConfigurationError, "#{owner.graphql_name}.#{graphql_name} has a resolver or a mutation, which can write, so it cannot use an observed rule"
85
+ end
86
+
87
+ (rule == :covered || Integration.allowed?(object, Integration.with_owner_model(rule, owner), context)) && super
88
+ end
89
+
90
+ # Asked of a field with no resolver. True when it declares no rule of its own and the class that declared it does not cover it. It asks that class
91
+ # and not the type being served: a field a payload inherits keeps the parent mutation as its owner.
92
+ def armory_denied_by_owner?
93
+ return false unless [nil, true].include?(@armory_declared) && owner.respond_to?(:armory_rule)
94
+
95
+ rule = owner.armory_rule
96
+ return true if rule.nil?
67
97
 
68
- (rule == :covered || Integration.allowed?(object, rule, context)) && super
98
+ @armory_declared.nil? ? rule.none? && !rule.covers_fields? : rule.none?
69
99
  end
70
100
 
71
101
  private
@@ -86,13 +116,13 @@ module GraphQL
86
116
  return Integration.bypassed_implementer?(type, context.schema) ? nil : :covered if type.respond_to?(:kind) && type.kind.interface?
87
117
  return :covered unless type.respond_to?(:armory_rule)
88
118
 
89
- type_rule && (!type_rule.none? || type_rule.covers_fields?) ? :covered : nil
119
+ armory_denied_by_owner? ? nil : :covered
90
120
  when true
91
121
  type_rule unless type_rule&.none?
92
122
  when :none
93
123
  Rule.none(reason: @armory_reason)
94
124
  else
95
- Rule.new(@armory_declared, attribute: original_name)
125
+ Rule.new(@armory_declared, policy: armory_policy, attribute: original_name, observe: @armory_observe)
96
126
  end
97
127
  end
98
128
  end
@@ -60,7 +60,15 @@ module GraphQL
60
60
  rule = armory_rule
61
61
  return false if rule.nil?
62
62
 
63
- Integration.allowed?(object, rule, context) && super
63
+ Integration.refuse_unobservable(self, context) if rule.observed?
64
+ Integration.allowed?(object, Integration.with_owner_model(rule, self), context) && super
65
+ rescue GraphQL::UnauthorizedError
66
+ raise
67
+ rescue StandardError => error
68
+ # graphql-ruby reads what a rescue_from answers here as the authorization, on both engines, so a handler that logs
69
+ # and answers true would serve the object. The handler runs, its answer does not count. No public hook does this.
70
+ context.query.handle_or_reraise(error)
71
+ false
64
72
  end
65
73
  end
66
74
  end
@@ -21,6 +21,8 @@ module GraphQL
21
21
  def authorize(action, reason: nil, on_denied: :default, **options)
22
22
  raise ArgumentError, "on_denied must be one of #{ON_DENIED.inspect}, got #{on_denied.inspect}" unless ON_DENIED.include?(on_denied)
23
23
 
24
+ raise ArgumentError, "observe: does not apply to a mutation or a resolver: what it runs cannot be undone" if options.key?(:observe)
25
+
24
26
  @armory_on_denied = on_denied
25
27
  @armory_rule = Rule.new(action, reason: reason, **options)
26
28
  end
@@ -16,6 +16,13 @@ module GraphQL
16
16
  (superclass.armory_configuration if superclass.respond_to?(:armory_configuration))
17
17
  end
18
18
 
19
+ # Read when a query first needs it, after the schema is defined; each schema holds its own.
20
+ def armory_implementers(interface)
21
+ @armory_definitions ||= Definitions.(self)
22
+ @armory_implementers ||= {}.compare_by_identity
23
+ @armory_implementers[interface] ||= @armory_definitions.select { |type| type.kind.object? && type <= interface }
24
+ end
25
+
19
26
  # `loads:` asks the schema which type an object is. For an object type the answer is known:
20
27
  # the lookup went through that type's model. Abstract types and foreign objects are the app's call.
21
28
  def resolve_type(type, object, context)
@@ -41,7 +41,7 @@ module GraphQL
41
41
  return Adapters::Null.new.scope(nil, items, rule) if rule.nil?
42
42
 
43
43
  configuration = configuration(context)
44
- Scope.(items, rule, context, adapter: configuration.adapter, sinks: configuration.sinks)
44
+ Scope.(items, rule, context, adapter: configuration.adapter, sinks: configuration.sinks, on_sink_error: configuration.on_sink_error)
45
45
  end
46
46
 
47
47
  # Looks an object up inside the user's scope, by primary key unless a key is given.
@@ -60,7 +60,7 @@ module GraphQL
60
60
 
61
61
  # An in-memory scope yields an Array, which cannot look one record up: find it, then ask the rule.
62
62
  record = model.find_by(conditions)
63
- record if record && allowed?(record, rule, context)
63
+ record if record && allowed?(record, rule.enforced, context)
64
64
  end
65
65
 
66
66
  # Loads a `loads:` argument inside the user's scope. When the schema defines `object_from_id` (global
@@ -96,19 +96,51 @@ module GraphQL
96
96
 
97
97
  # An interface field with no rule of its own cannot name the type it is resolved on, so it is only
98
98
  # covered when no implementer is a bypass: a field on a bypassed type is denied, and so is this one.
99
+ # `possible_types` is read with no request, so it drops an implementer hidden there.
99
100
  def self.bypassed_implementer?(interface, schema)
100
- schema.possible_types(interface).any? do |type|
101
+ hidden = schema.respond_to?(:armory_implementers) ? schema.armory_implementers(interface) : []
102
+ any_bypass?(schema.possible_types(interface) + hidden)
103
+ end
104
+
105
+ def self.any_bypass?(types)
106
+ types.any? do |type|
101
107
  rule = type.armory_rule if type.respond_to?(:armory_rule)
102
108
  rule && rule.none? && !rule.covers_fields?
103
109
  end
104
110
  end
105
111
 
112
+ # The rule with the model its owner wraps, the one the audit reads: named by the rule, or named like the type.
113
+ def self.with_owner_model(rule, owner)
114
+ return rule if rule.none? || rule.policy || rule.model || !owner.respond_to?(:armory_model)
115
+
116
+ rule.with_model(declared_model(owner) || owner.armory_model)
117
+ rescue ConfigurationError, GraphQL::RequiredImplementationMissingError
118
+ rule
119
+ end
120
+
121
+ # A Symbol or a String stays as written: only that spelling can name a policy for a Symbol the type wraps.
122
+ def self.declared_model(owner)
123
+ owner.armory_rule&.model if owner.respond_to?(:armory_rule)
124
+ end
125
+ private_class_method :declared_model
126
+
127
+ # Observing a type opens the only check that stands before everything inside it, whatever class its fields are. A
128
+ # resolver or a mutation can write, and a write cannot be undone, so a type holding one cannot be observed.
129
+ def self.refuse_unobservable(type, context)
130
+ known = context.namespace(:armory)[:observable] ||= {}.compare_by_identity
131
+ field = known.fetch(type) { known[type] = type.all_field_definitions.find(&:resolver) }
132
+ return unless field
133
+
134
+ raise ConfigurationError, "#{type.graphql_name} cannot be observed: its field #{field.graphql_name} has a resolver or a mutation, which can write. " \
135
+ "Remove observe:, or put it on its plain fields"
136
+ end
137
+
106
138
  # One Authorize per query: building it (and its memo and telemetry) once per object is pure overhead.
107
139
  def self.allowed?(subject, rule, context)
108
140
  store = context.namespace(:armory)
109
141
  authorize = store[:authorize] ||= begin
110
142
  configuration = configuration(context)
111
- Authorize.build(context, adapter: configuration.adapter, sinks: configuration.sinks)
143
+ Authorize.build(context, adapter: configuration.adapter, sinks: configuration.sinks, on_sink_error: configuration.on_sink_error)
112
144
  end
113
145
 
114
146
  authorize.(subject, rule, context)
@@ -5,10 +5,16 @@ require "rspec/expectations"
5
5
  # `require "graphql/armory/authorization/rspec"` in your spec helper, then:
6
6
  #
7
7
  # expect(AppSchema).to be_fully_authorized
8
- RSpec::Matchers.define :be_fully_authorized do
8
+ # expect(AppSchema).to be_fully_authorized(baseline: "config/graphql_armory_baseline.json") # fails only on new problems
9
+ RSpec::Matchers.define :be_fully_authorized do |*positional, baseline: nil|
10
+ raise ArgumentError, "be_fully_authorized takes baseline: path" unless positional.empty?
11
+
9
12
  match do |schema|
10
- @report = GraphQL::Armory::Authorization::Audit.(schema)
11
- @report.ok?
13
+ report = GraphQL::Armory::Authorization::Audit.(schema)
14
+ next (@report = report).ok? unless baseline
15
+
16
+ @report = GraphQL::Armory::Authorization::Audit::Baseline.load(baseline).(report)
17
+ @report.passes?
12
18
  end
13
19
 
14
20
  failure_message do |schema|
@@ -16,6 +22,6 @@ RSpec::Matchers.define :be_fully_authorized do
16
22
  end
17
23
 
18
24
  failure_message_when_negated do |schema|
19
- "expected #{schema} not to be fully authorized, but the audit found no problems"
25
+ baseline ? "expected #{schema} not to pass its baseline, but it did:\n#{@report}" : "expected #{schema} not to be fully authorized, but the audit found no problems"
20
26
  end
21
27
  end
@@ -6,13 +6,13 @@ module GraphQL
6
6
  # Immutable value holding what was declared, e.g. `authorize :read`.
7
7
  # Each adapter reads the parts it needs (policy, subject, attribute, model, scope).
8
8
  class Rule
9
- attr_reader :action, :policy, :subject, :attribute, :model, :scope, :visible_when, :covers_fields, :reason
9
+ attr_reader :action, :policy, :subject, :attribute, :model, :scope, :visible_when, :covers_fields, :reason, :observe
10
10
 
11
11
  def self.none(reason:)
12
12
  new(:none, reason: reason)
13
13
  end
14
14
 
15
- def initialize(action, policy: nil, subject: nil, attribute: nil, model: nil, scope: nil, visible_when: nil, covers_fields: false, reason: nil)
15
+ def initialize(action, policy: nil, subject: nil, attribute: nil, model: nil, scope: nil, visible_when: nil, covers_fields: false, reason: nil, observe: nil)
16
16
  raise ArgumentError, "a rule needs an action" if action.nil?
17
17
 
18
18
  @action = action.to_sym
@@ -24,14 +24,35 @@ module GraphQL
24
24
  @visible_when = visible_when&.to_sym
25
25
  @covers_fields = covers_fields
26
26
  @reason = reason
27
+ @observe = observe
27
28
 
28
29
  raise ArgumentError, "a bypass needs a reason" if none? && reason.to_s.strip.empty?
29
30
 
30
31
  raise ArgumentError, "covers_fields only applies to a bypass (`authorize :none`)" if covers_fields && !none?
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
+ raise ArgumentError, "observe: does not apply to a bypass, which refuses nothing" if observe && none?
31
34
 
32
35
  freeze
33
36
  end
34
37
 
38
+ def with_model(model)
39
+ self.class.new(action, policy: policy, subject: subject, attribute: attribute, model: model, scope: scope,
40
+ visible_when: visible_when, covers_fields: covers_fields, reason: reason, observe: observe)
41
+ end
42
+
43
+ # The same rule with no observation, for what must keep refusing: lookups through a scope.
44
+ def enforced
45
+ return self unless observed?
46
+
47
+ self.class.new(action, policy: policy, subject: subject, attribute: attribute, model: model, scope: scope,
48
+ visible_when: visible_when, covers_fields: covers_fields, reason: reason)
49
+ end
50
+
51
+ # A clear "no" to this rule, on a read, is served and recorded instead of refused. See Authorize.
52
+ def observed?
53
+ !observe.nil?
54
+ end
55
+
35
56
  # A bypassed type whose fields are covered by something else, such as the payload of a mutation.
36
57
  def covers_fields?
37
58
  covers_fields
@@ -53,7 +74,7 @@ module GraphQL
53
74
  protected
54
75
 
55
76
  def members
56
- [action, policy, subject, attribute, model, scope, visible_when, covers_fields, reason]
77
+ [action, policy, subject, attribute, model, scope, visible_when, covers_fields, reason, observe]
57
78
  end
58
79
  end
59
80
  end
@@ -13,22 +13,22 @@ module GraphQL
13
13
  @telemetry = telemetry
14
14
  end
15
15
 
16
- def self.build(adapter:, sinks: [])
17
- new(adapter: adapter, telemetry: Telemetry.build(sinks: sinks))
16
+ def self.build(adapter:, sinks: [], on_sink_error: nil)
17
+ new(adapter: adapter, telemetry: Telemetry.build(sinks: sinks, on_sink_error: on_sink_error))
18
18
  end
19
19
 
20
- def self.call(items, rule, context, adapter:, sinks: [])
21
- build(adapter: adapter, sinks: sinks).(items, rule, context)
20
+ def self.call(items, rule, context, adapter:, sinks: [], on_sink_error: nil)
21
+ build(adapter: adapter, sinks: sinks, on_sink_error: on_sink_error).(items, rule, context)
22
22
  end
23
23
 
24
24
  def call(items, rule, context)
25
25
  if rule.none?
26
- telemetry.record(:bypassed, reason: rule.reason)
26
+ telemetry.record(:bypassed, context: context, reason: rule.reason)
27
27
  return items
28
28
  end
29
29
 
30
30
  scoped = adapter.scope(adapter.actor(context), items, rule)
31
- telemetry.record(:scoped, action: rule.action)
31
+ telemetry.record(:scoped, context: context, action: rule.action)
32
32
  scoped
33
33
  end
34
34
  end