lighthouse-graphql 0.7.2 → 0.8.0

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 (45) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +126 -1
  3. data/docs/authorization.md +33 -1
  4. data/docs/configuration.md +38 -0
  5. data/docs/directives.md +51 -4
  6. data/docs/filtering-and-ordering.md +52 -0
  7. data/docs/getting-started.md +63 -10
  8. data/docs/performance.md +9 -0
  9. data/docs/relay.md +6 -2
  10. data/docs/uploads.md +28 -2
  11. data/lib/lighthouse/ast_builder.rb +14 -5
  12. data/lib/lighthouse/config.rb +18 -2
  13. data/lib/lighthouse/controller.rb +6 -67
  14. data/lib/lighthouse/directive_resolvers/argument_transforms_resolver.rb +7 -1
  15. data/lib/lighthouse/directive_resolvers/association_resolvers.rb +5 -7
  16. data/lib/lighthouse/directive_resolvers/attachment_resolver.rb +139 -0
  17. data/lib/lighthouse/directive_resolvers/base.rb +26 -22
  18. data/lib/lighthouse/directive_resolvers/can_resolvers.rb +29 -5
  19. data/lib/lighthouse/directive_resolvers/model_mutation_resolver.rb +1 -8
  20. data/lib/lighthouse/directives/definitions.rb +2 -2
  21. data/lib/lighthouse/directives/registry.rb +1 -1
  22. data/lib/lighthouse/directives/soft_deletes_directive.rb +23 -6
  23. data/lib/lighthouse/document_ast.rb +6 -0
  24. data/lib/lighthouse/field_resolver_stack.rb +32 -0
  25. data/lib/lighthouse/global_id.rb +16 -5
  26. data/lib/lighthouse/graphql/version.rb +1 -1
  27. data/lib/lighthouse/operations.rb +111 -0
  28. data/lib/lighthouse/pagination.rb +21 -1
  29. data/lib/lighthouse/persisted_queries/manifest.rb +40 -0
  30. data/lib/lighthouse/persisted_queries.rb +9 -27
  31. data/lib/lighthouse/railtie.rb +8 -1
  32. data/lib/lighthouse/rb_lighthouse.rb +6 -0
  33. data/lib/lighthouse/relation_batch.rb +1 -1
  34. data/lib/lighthouse/schema_generator.rb +2 -0
  35. data/lib/lighthouse/schema_printer.rb +100 -0
  36. data/lib/lighthouse/schema_report.rb +161 -0
  37. data/lib/lighthouse/server_directives.rb +63 -0
  38. data/lib/lighthouse/tasks/lighthouse.rake +25 -6
  39. data/lib/lighthouse/upload.rb +2 -1
  40. data/lib/lighthouse/upload_store.rb +53 -2
  41. data/sig/lighthouse/controller.rbs +19 -8
  42. data/sig/lighthouse/directives.rbs +27 -0
  43. data/sig/lighthouse/graphql.rbs +3 -0
  44. data/sig/lighthouse.rbs +11 -2
  45. metadata +7 -1
@@ -32,13 +32,28 @@ module Lighthouse
32
32
  soft_deletes
33
33
  queue_broadcasts broadcast_queue
34
34
  global_id
35
+ schema_output schema_log
35
36
  ].freeze
36
37
 
37
38
  class << self
38
39
  attr_writer :schema_path, :ide_helper, :resolver_namespaces, :on_error, :authenticated_user, :policy_user, :authorizer,
39
40
  :transactional_mutations, :schema_cache, :watch_sdl, :persisted_queries, :persisted_queries_store, :persisted_queries_only,
40
41
  :queue_broadcasts,
41
- :convert_empty_strings_to_null, :feature_checker, :feature_actor, :global_id
42
+ :convert_empty_strings_to_null, :feature_checker, :feature_actor, :global_id, :schema_log
43
+
44
+ # A file development keeps the client schema in (SchemaPrinter): a path
45
+ # (under Rails.root; `.json` for the introspection result), or
46
+ # { path:, schema: 'AppSchema' }. nil (the default): none.
47
+ attr_accessor :schema_output
48
+
49
+ # Log the schema's build on boot and on every reload (SchemaReport): it
50
+ # built (in how long, what changed, the files written) or why not. nil
51
+ # (the default): in a development server, not in rake tasks or the console.
52
+ def schema_log
53
+ return @schema_log unless @schema_log.nil?
54
+
55
+ defined?(::Rails::Server) ? ::Rails.env.development? : false
56
+ end
42
57
 
43
58
  # The schema's entrypoint, as PHP Lighthouse's `schema_path`: the one file
44
59
  # the schema is read from, importing the others (`#import user.graphql`,
@@ -100,7 +115,8 @@ module Lighthouse
100
115
  # persisted_queries accept Apollo's Automatic Persisted Queries (PersistedQueries)
101
116
  # persisted_queries_store where APQ keeps queries; default Rails.cache
102
117
  # persisted_queries_ttl how long they live there (seconds; nil: until evicted)
103
- # persisted_queries_manifest a manifest of trusted operations, served by hash
118
+ # persisted_queries_manifest a manifest of trusted operations, served by hash: a JSON file,
119
+ # a Hash, or a callable answering either
104
120
  # persisted_queries_only reject any operation not in the manifest
105
121
  attr_accessor :schema_cache_path, :persisted_queries_ttl, :persisted_queries_manifest
106
122
 
@@ -31,9 +31,11 @@ require 'json'
31
31
  #
32
32
  # Hooks, private so they are not actions: `graphql_context` (default:
33
33
  # `{ current_user: current_user }` when the controller has a current_user, else
34
- # `{}`), `graphql_schema` and `graphql_variables(param)`. A controller with an
35
- # action of its own wraps it in `lighthouse_request { ... }` to get the request
36
- # events; a nested call dispatches them once.
34
+ # `{}`), `graphql_schema` and `graphql_variables(param)`, from
35
+ # Lighthouse::GraphQL::Operations, which also gives the controller's own actions
36
+ # `lighthouse_execute`. An action of its own wraps itself in
37
+ # `lighthouse_request { ... }` to get the request events; a nested call
38
+ # dispatches them once.
37
39
  module Lighthouse::GraphQL::Controller
38
40
  extend ActiveSupport::Concern
39
41
 
@@ -42,18 +44,7 @@ module Lighthouse::GraphQL::Controller
42
44
  # schema's rescue_from) catches it on its way out of the operation.
43
45
  class Performed < Exception; end # rubocop:disable Lint/InheritException
44
46
 
45
- included do
46
- class_attribute :lighthouse_schema_source, instance_writer: false
47
- end
48
-
49
- class_methods do
50
- # The schema `execute` runs: a schema class, its name (a String, constantized
51
- # per request so code reloading works) or a block (evaluated in the
52
- # controller, per request).
53
- def lighthouse_schema(schema = nil, &block)
54
- self.lighthouse_schema_source = schema || block
55
- end
56
- end
47
+ include Lighthouse::GraphQL::Operations
57
48
 
58
49
  def execute
59
50
  lighthouse_request do
@@ -74,58 +65,6 @@ module Lighthouse::GraphQL::Controller
74
65
 
75
66
  private
76
67
 
77
- # Dispatch StartRequest, run the block, dispatch EndRequest with the
78
- # response. Only the outermost call dispatches, and stops the block where a
79
- # @throttle `with:` method performed the response.
80
- def lighthouse_request
81
- return yield if @lighthouse_request_started
82
-
83
- @lighthouse_request_started = true
84
- Lighthouse::Events.dispatch(Lighthouse::Events::StartRequest.new(request))
85
- result = begin
86
- yield
87
- rescue Performed
88
- nil
89
- end
90
- Lighthouse::Events.dispatch(Lighthouse::Events::EndRequest.new(response))
91
- result
92
- end
93
-
94
- # The context of the operation: what @guard and the @can* directives read.
95
- def graphql_context
96
- respond_to?(:current_user, true) ? { current_user: current_user } : {}
97
- end
98
-
99
- # graphql_context, with what @throttle reads unless it sets its own: the
100
- # client's IP (rate_limit's default by:) and the controller, whose cache_store,
101
- # controller_path and methods rate_limit uses.
102
- def lighthouse_context
103
- { remote_ip: request.remote_ip, lighthouse_controller: self }.merge(graphql_context)
104
- end
105
-
106
- def graphql_schema
107
- source = lighthouse_schema_source
108
- case source
109
- when nil then raise Lighthouse::DefinitionError, "#{self.class}: name the schema with `lighthouse_schema AppSchema`"
110
- when String, Symbol then source.to_s.constantize
111
- when Proc then instance_exec(&source)
112
- else source
113
- end
114
- end
115
-
116
- # Variables arrive as a JSON string (GET or form posts) or as parameters.
117
- def graphql_variables(param)
118
- case param
119
- when String then param.present? ? JSON.parse(param) || {} : {}
120
- when Hash then param
121
- when nil then {}
122
- else
123
- raise ArgumentError, "Unexpected parameter: #{param}" unless param.respond_to?(:to_unsafe_h)
124
-
125
- param.to_unsafe_h
126
- end
127
- end
128
-
129
68
  # A multipart request's operation(s), a batch (a JSON array body), or the parameters.
130
69
  def lighthouse_operations
131
70
  Lighthouse::GraphQL::MultipartRequest.operations(params) || params[:_json] || params
@@ -112,8 +112,14 @@ class Lighthouse::GraphQL::DirectiveResolvers::ArgumentTransformsResolver < Ligh
112
112
  trim_all = phase == :rewrite && self.class.trims_all?(@field_def)
113
113
  inner = capture_inner(target_type_class)
114
114
 
115
- install(target_type_class, lambda do |obj, args, ctx|
115
+ resolve = lambda do |obj, args, ctx|
116
116
  inner.call(obj, args.is_a?(Hash) ? me.transform_hash(argument_defs, args, ctx, trim_all) : args, ctx)
117
+ end
118
+ return install(target_type_class, resolve) if phase == :rewrite
119
+
120
+ # A field that fails leaves no file @upload stored for it behind.
121
+ install(target_type_class, lambda do |obj, args, ctx|
122
+ Lighthouse::GraphQL::UploadStore.purge_on_failure(ctx) { resolve.call(obj, args, ctx) }
117
123
  end)
118
124
  end
119
125
 
@@ -74,18 +74,16 @@ module Lighthouse::GraphQL::DirectiveResolvers
74
74
  directive_arg('scopes') || Lighthouse::GraphQL::DirectiveResolvers::BuilderApplier.any?(@field_def.ast_node) || filtered?(args)
75
75
  end
76
76
 
77
+ # A supplied argument, or input field at any depth, with a filter directive
78
+ # (@eq, @where, ...), or a supplied where-conditions argument.
77
79
  def filtered?(args)
78
- registry = Lighthouse::DirectiveRegistry.default
80
+ return true if filtering?(args)
81
+
79
82
  (@field_def.ast_node&.arguments || []).any? do |argument|
80
- args.key?(argument.name.underscore.to_sym) && argument.directives.any? { |d| filter_directive?(registry, d) }
83
+ args.key?(argument.name.underscore.to_sym) && argument.directives.any? { |d| CONDITION_DIRECTIVES.include?(d.name) }
81
84
  end
82
85
  end
83
86
 
84
- # An argument builder (@eq, @where, ...) or a where-conditions filter.
85
- def filter_directive?(registry, directive)
86
- registry.arg_builder_class(directive.name) || CONDITION_DIRECTIVES.include?(directive.name)
87
- end
88
-
89
87
  def constrained(relation, args, ctx)
90
88
  relation = apply_where_filters(scoped(relation), args, ctx)
91
89
  self.class.collection? ? relation : relation.first
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base'
4
+
5
+ # @attachment — the URL of an ActiveStorage attachment of the parent: the read
6
+ # side of @upload, Lighthouse's (Laravel has no ActiveStorage).
7
+ #
8
+ # type User {
9
+ # avatarUrl: String @attachment # has_one_attached :avatar
10
+ # avatarThumbUrl: String @attachment(name: "avatar", variant: "thumb")
11
+ # photoUrls: [String!]! @attachment(url: PROXY) # has_many_attached :photos
12
+ # }
13
+ #
14
+ # Every parent's attachments and their blobs are loaded at once
15
+ # (`avatar_attachment: :blob`, what `User.with_attached_avatar` loads), through
16
+ # the Dataloader when the schema uses it. `name` defaults to the field's name
17
+ # without its Url / Urls suffix: avatarUrl reads `avatar`, photoUrls `photos`.
18
+ #
19
+ # `url` says how the URL serves the file: REDIRECT (Rails' redirect to the
20
+ # service, the default), PROXY (streamed through the app) or DIRECT (the
21
+ # service's own URL, signed for `expiresIn` on a private one). A REDIRECT or
22
+ # PROXY URL is absolute when the request's host is known (the controller in the
23
+ # context, else the routes' default_url_options), else a path. A variant is
24
+ # processed when its URL is first followed, except DIRECT, which processes it
25
+ # while resolving.
26
+ class Lighthouse::GraphQL::DirectiveResolvers::AttachmentDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
27
+ TYPE_DEFINITIONS = {
28
+ 'AttachmentUrl' => <<~GRAPHQL.chomp
29
+ "How an @attachment URL serves the file."
30
+ enum AttachmentUrl {
31
+ "Rails' redirect to the storage service (rails_storage_redirect_url)."
32
+ REDIRECT
33
+ "Streamed through the app (rails_storage_proxy_url)."
34
+ PROXY
35
+ "The storage service's own URL, signed for expiresIn on a private service."
36
+ DIRECT
37
+ }
38
+ GRAPHQL
39
+ }.freeze
40
+
41
+ def self.directive_name = 'attachment'
42
+
43
+ def self.type_definitions = TYPE_DEFINITIONS
44
+
45
+ def self.definition
46
+ <<~GRAPHQL.chomp
47
+ """
48
+ The URL of an ActiveStorage attachment of the parent, or the URLs of a has_many_attached.
49
+ Every parent's attachments and blobs are loaded at once.
50
+ """
51
+ directive @attachment(
52
+ "The attachment's name. Defaults to the field's name without its Url / Urls suffix."
53
+ name: String
54
+ "A named variant of the attachment (`has_one_attached :avatar { |a| a.variant :thumb, ... }`)."
55
+ variant: String
56
+ "How the URL serves the file."
57
+ url: AttachmentUrl = REDIRECT
58
+ "How many seconds a DIRECT URL is valid. Defaults to ActiveStorage.service_urls_expire_in."
59
+ expiresIn: Int
60
+ ) on FIELD_DEFINITION
61
+ GRAPHQL
62
+ end
63
+
64
+ def define_resolver(target_type_class)
65
+ me = self
66
+ install(target_type_class, ->(obj, _args, ctx) { me.send(:resolve, obj, ctx) })
67
+ end
68
+
69
+ protected
70
+
71
+ def resolve(record, ctx)
72
+ return if record.nil?
73
+
74
+ reflection = reflection(record)
75
+ preload(record, reflection, ctx)
76
+ attached = record.public_send(attachment_name)
77
+ return attached.attachments.filter_map { |attachment| url(attachment, ctx) } if reflection.macro == :has_many_attached
78
+
79
+ url(attached.attachment, ctx) if attached.attached?
80
+ end
81
+
82
+ def attachment_name
83
+ @attachment_name ||= (directive_arg('name') || default_name).to_s
84
+ end
85
+
86
+ # avatarUrl -> avatar, photoUrls -> photos, avatar -> avatar.
87
+ def default_name
88
+ attribute = Lighthouse::Support::Naming.attribute(@field_def.name)
89
+ attribute.end_with?('_urls') ? attribute.delete_suffix('_urls').pluralize : attribute.delete_suffix('_url')
90
+ end
91
+
92
+ def reflection(record)
93
+ reflection = record.class.respond_to?(:reflect_on_attachment) && record.class.reflect_on_attachment(attachment_name)
94
+ return reflection if reflection
95
+
96
+ raise Lighthouse::DefinitionError,
97
+ "@attachment on #{@type_def.graphql_name}.#{@field_def.name}: #{record.class.name} has no attachment `#{attachment_name}`."
98
+ end
99
+
100
+ def preload(record, reflection, ctx)
101
+ dataloader = Lighthouse::Support::Batching.dataloader(ctx)
102
+ return unless dataloader
103
+
104
+ association = reflection.macro == :has_many_attached ? :"#{attachment_name}_attachments" : :"#{attachment_name}_attachment"
105
+ dataloader.with(Lighthouse::GraphQL::DataloaderSources::PreloadLoader, [{ association => :blob }], []).load(record)
106
+ end
107
+
108
+ def url(attachment, ctx)
109
+ variant = directive_arg('variant')
110
+ return if variant && !attachment.variable?
111
+
112
+ target = variant ? attachment.variant(variant.to_sym) : attachment
113
+ options = url_options(ctx)
114
+ case directive_arg('url')
115
+ when 'DIRECT' then direct_url(target, options)
116
+ when 'PROXY' then route(:rails_storage_proxy, target, options)
117
+ else route(:rails_storage_redirect, target, options)
118
+ end
119
+ end
120
+
121
+ def route(name, target, options)
122
+ helpers = ::Rails.application.routes.url_helpers
123
+ options[:host] ? helpers.public_send(:"#{name}_url", target, **options) : helpers.public_send(:"#{name}_path", target)
124
+ end
125
+
126
+ # The service signs the URL; the Disk service builds it from ActiveStorage::Current's host.
127
+ def direct_url(target, options)
128
+ target = target.processed if target.respond_to?(:processed)
129
+ expires_in = directive_arg('expiresIn')&.seconds || ::ActiveStorage.service_urls_expire_in
130
+ ::ActiveStorage::Current.set(url_options: options.slice(:host, :port, :protocol)) { target.url(expires_in: expires_in) }
131
+ end
132
+
133
+ # The request's, through the controller in the context, else the routes' defaults.
134
+ def url_options(ctx)
135
+ controller = ctx.respond_to?(:[]) ? ctx[:lighthouse_controller] : nil
136
+ options = controller.respond_to?(:url_options) ? controller.url_options : ::Rails.application.routes.default_url_options
137
+ options.to_h.symbolize_keys.slice(:host, :port, :protocol, :script_name)
138
+ end
139
+ end
@@ -47,13 +47,13 @@ class Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
47
47
  # Compose argument-builder directives (@eq, @neq, @in, @notIn, @like,
48
48
  # @where, @orderBy, @whereConditions, @whereHasConditions) onto the relation, in SDL argument order, for each
49
49
  # field argument that carries one and that the client supplied a value
50
- # for — and for the input fields of an argument carrying @nest.
50
+ # for — and for the fields of the input objects the client sent, at any depth.
51
51
  def apply_arg_builders(relation, args_h, ctx = nil)
52
52
  return relation unless relation.respond_to?(:where)
53
53
  return relation unless @field_def.ast_node
54
54
 
55
- arg_builders.each do |path, arg_node, dnode, builder_class|
56
- relation = apply_arg_builder(relation, args_h, ctx, [path, arg_node, dnode, builder_class])
55
+ arg_builders(args_h).each do |values, node, dnode, builder_class|
56
+ relation = apply_arg_builder(relation, values, ctx, [[node.name], node, dnode, builder_class])
57
57
  end
58
58
 
59
59
  relation
@@ -141,35 +141,39 @@ class Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
141
141
  hash.is_a?(Hash) && Lighthouse::Support::Naming.candidate_keys(path.last).any? { |key| hash.key?(key) }
142
142
  end
143
143
 
144
- # [path, node, directive, builder class] for every argument-builder
145
- # directive, in SDL order. An argument carrying @nest adds its input type's
146
- # fields', at any depth, with their path into the value.
147
- def arg_builders
148
- (@field_def.ast_node.arguments || []).flat_map do |arg_node|
149
- builders_of(arg_node, [arg_node.name], @field_def.arguments[arg_node.name])
150
- end
144
+ # Did the client send an argument or input field, at any depth, that
145
+ # carries an argument-builder directive? As PHP Lighthouse's wouldEnhanceBuilder.
146
+ def filtering?(args_h)
147
+ arg_builders(args_h).any? { |values, node, _dnode, _builder_class| arg_present?(values, [node.name]) }
148
+ end
149
+
150
+ # [values, node, directive, builder class] for every argument-builder
151
+ # directive on the field's arguments, in SDL order, then on the fields of the
152
+ # input objects the client sent for them (each of a list), at any depth,
153
+ # as PHP Lighthouse's applyArgBuilderDirectives goes through them. `values`
154
+ # holds the node's value: the arguments, or the input object it is a field of.
155
+ def arg_builders(args_h)
156
+ builders_in(@field_def.ast_node.arguments || [], @field_def.arguments, args_h)
151
157
  end
152
158
 
153
- def builders_of(node, path, argument)
159
+ def builders_in(nodes, arguments, values)
154
160
  registry = Lighthouse::DirectiveRegistry.default
155
- own = (node.directives || []).filter_map do |dnode|
156
- builder_class = dnode.name == 'builder' ? :builder : registry.arg_builder_class(dnode.name)
157
- [path, node, dnode, builder_class] if builder_class
161
+ nodes.flat_map do |node|
162
+ own = (node.directives || []).filter_map do |dnode|
163
+ builder_class = dnode.name == 'builder' ? :builder : registry.arg_builder_class(dnode.name)
164
+ [values, node, dnode, builder_class] if builder_class
165
+ end
166
+ own + nested_builders(arguments[node.name], dig_arg(values, [node.name]))
158
167
  end
159
- own + (argument && nest?(node) ? nested_builders(argument, path) : [])
160
168
  end
161
169
 
162
- def nest?(node)
163
- (node.directives || []).any? { |d| d.name == 'nest' }
164
- end
170
+ def nested_builders(argument, value)
171
+ return [] if argument.nil? || value.nil?
165
172
 
166
- def nested_builders(argument, path)
167
173
  type = argument.type.unwrap
168
174
  return [] unless type.kind.input_object?
169
175
 
170
- type.arguments.each_value.flat_map do |field|
171
- field.ast_node ? builders_of(field.ast_node, path + [field.ast_node.name], field) : []
172
- end
176
+ [value].flatten.compact.flat_map { |input| builders_in(type.arguments.values.filter_map(&:ast_node), type.arguments, input) }
173
177
  end
174
178
 
175
179
  # The client's value at `path` (an argument, then input fields), or nil.
@@ -49,14 +49,14 @@ module Lighthouse::GraphQL::DirectiveResolvers
49
49
  def self.type_definitions = TYPE_DEFINITIONS
50
50
 
51
51
  # The SDL of a @can* directive: `description`, the arguments they share, then the `extra` ones.
52
- def self.definition_with(description, extra = [])
52
+ def self.definition_with(description, extra = [], locations: 'FIELD_DEFINITION')
53
53
  <<~GRAPHQL.chomp
54
54
  """
55
55
  #{description}
56
56
  """
57
57
  directive @#{directive_name}(
58
58
  #{[*COMMON_ARGUMENTS, *extra].join("\n")}
59
- ) repeatable on FIELD_DEFINITION
59
+ ) repeatable on #{locations}
60
60
  GRAPHQL
61
61
  end
62
62
 
@@ -136,7 +136,7 @@ module Lighthouse::GraphQL::DirectiveResolvers
136
136
 
137
137
  def authorize_before(_obj, args, ctx)
138
138
  model = model_class
139
- ids = Lighthouse::Support::Arguments.dig(Lighthouse::Support::Arguments.plain(args), directive_arg('find')).flatten.uniq
139
+ ids = ids_to_find(Lighthouse::Support::Arguments.plain(args))
140
140
  records = scoped(model.where(model.primary_key => ids)).to_a
141
141
  if directive_arg('findOrFail') != false && records.size < ids.size
142
142
  missing = ids.map(&:to_s) - records.map { |r| r.public_send(model.primary_key).to_s }
@@ -145,21 +145,45 @@ module Lighthouse::GraphQL::DirectiveResolvers
145
145
 
146
146
  authorize_each!(ctx, records, args)
147
147
  end
148
+
149
+ # The ids at the `find:` path. Nothing there (a misspelt path, an argument
150
+ # the client left out) is an error, as in PHP Lighthouse, so the field never
151
+ # resolves with nothing checked. A `*` over an empty list finds no model to check.
152
+ def ids_to_find(args)
153
+ find = directive_arg('find').to_s
154
+ ids = Lighthouse::Support::Arguments.dig(args, find)
155
+ return ids.flatten.uniq unless ids.empty? && !empty_list_at?(args, find)
156
+
157
+ raise ::GraphQL::ExecutionError, "Got no key to find a model at the expected input path: #{find}."
158
+ end
159
+
160
+ def empty_list_at?(args, find)
161
+ return false unless find.include?('*')
162
+
163
+ lists = Lighthouse::Support::Arguments.dig(args, find.split('.*').first)
164
+ lists.any? && lists.all? { |list| list.respond_to?(:empty?) && list.empty? }
165
+ end
148
166
  end
149
167
 
150
168
  class CanModelDirectiveResolver < CanDirectiveResolver
151
169
  def self.directive_name = 'canModel'
152
170
 
153
171
  def self.definition
154
- definition_with(<<~TEXT.chomp, [MODEL_ARGUMENT])
172
+ definition_with(<<~TEXT.chomp, [MODEL_ARGUMENT], locations: 'FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION')
155
173
  Check a policy against the model class itself, before the field resolves,
156
- e.g. `create?` before a @create.
174
+ e.g. `create?` before a @create. On an argument or input field, only when
175
+ the client gives it a value: who may use it, e.g. `trashed`.
157
176
  TEXT
158
177
  end
159
178
 
160
179
  protected
161
180
 
181
+ # On an argument (FieldResolverStack passes its path as `argument:`), only
182
+ # when the client gave it a value.
162
183
  def authorize_before(_obj, args, ctx)
184
+ path = @opts[:argument]
185
+ return if path && Lighthouse::Support::Arguments.dig(Lighthouse::Support::Arguments.plain(args), path).empty?
186
+
163
187
  authorize!(ctx, model_class, args)
164
188
  end
165
189
  end
@@ -254,7 +254,7 @@ module Lighthouse::GraphQL::DirectiveResolvers
254
254
  # to the data, as PHP Lighthouse does; the others are still modified.
255
255
  def mutate(model, _obj, args, ctx)
256
256
  args = Lighthouse::Support::Arguments.shallow(args)
257
- raise ::GraphQL::ExecutionError, WOULD_MODIFY_ALL unless filtered?(args)
257
+ raise ::GraphQL::ExecutionError, WOULD_MODIFY_ALL unless filtering?(args)
258
258
 
259
259
  records = apply_where_filters(records_of(model), args, ctx).to_a
260
260
  records.each do |record|
@@ -272,13 +272,6 @@ module Lighthouse::GraphQL::DirectiveResolvers
272
272
  def modify(_record)
273
273
  raise NotImplementedError
274
274
  end
275
-
276
- def filtered?(args)
277
- registry = Lighthouse::DirectiveRegistry.default
278
- (@field_def.ast_node.arguments || []).any? do |argument|
279
- args.key?(argument.name.underscore.to_sym) && argument.directives.any? { |d| registry.arg_builder_class(d.name) }
280
- end
281
- end
282
275
  end
283
276
 
284
277
  # @delete — destroy the models the field's argument filters select
@@ -10,8 +10,8 @@ module Lighthouse::GraphQL::Directives::Definitions
10
10
  PASSIVE = {
11
11
  'nest' => <<~GRAPHQL.chomp,
12
12
  """
13
- On an argument of an input object type, apply the filters of the input's fields
14
- (@eq, @where, ...; at any depth, for those that carry @nest too) as if they were the field's own arguments.
13
+ Accepted on an argument or input field of an input object type, as PHP Lighthouse's SDL
14
+ writes it. The filters of input fields (@eq, @where, ...) apply at any depth without it.
15
15
  """
16
16
  directive @nest on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION
17
17
  GRAPHQL
@@ -202,7 +202,7 @@ class Lighthouse::DirectiveRegistry
202
202
  CacheDirectiveResolver ClearCacheDirectiveResolver EventDirectiveResolver
203
203
  ValidatorDirectiveResolver ConvertEmptyStringsToNullDirectiveResolver
204
204
  SubscriptionDirectiveResolver BroadcastDirectiveResolver
205
- WithDirectiveResolver WithCountDirectiveResolver LazyLoadDirectiveResolver
205
+ WithDirectiveResolver WithCountDirectiveResolver LazyLoadDirectiveResolver AttachmentDirectiveResolver
206
206
  GlobalIdDirectiveResolver NamespacedDirectiveResolver ThrottleDirectiveResolver AsyncDirectiveResolver
207
207
  ].freeze
208
208
 
@@ -6,6 +6,12 @@
6
6
  #
7
7
  # tasks: [Task!]! @all @softDeletes -> tasks(trashed: Trashed @trashed): [Task!]! @all
8
8
  #
9
+ # `ability:` puts a @canModel on the argument, so only who the policy allows
10
+ # may use it (Lighthouse's, not PHP Lighthouse's):
11
+ #
12
+ # tasks: [Task!]! @all @softDeletes(ability: "view_trashed")
13
+ # -> tasks(trashed: Trashed @trashed @canModel(ability: "view_trashed")): [Task!]! @all
14
+ #
9
15
  # The `Trashed` enum is added once whenever a `@trashed` argument is in the
10
16
  # schema (generated here or written by hand), unless the app declares its own.
11
17
  class Lighthouse::GraphQL::Directives::SoftDeletesDirective
@@ -16,7 +22,10 @@ class Lighthouse::GraphQL::Directives::SoftDeletesDirective
16
22
  This manipulates the schema by adding the argument
17
23
  `trashed: Trashed @trashed` to the field.
18
24
  """
19
- directive @softDeletes on FIELD_DEFINITION
25
+ directive @softDeletes(
26
+ "The policy ability a user needs to pass `trashed` (a @canModel on it). Without it, anyone may."
27
+ ability: String
28
+ ) on FIELD_DEFINITION
20
29
  GRAPHQL
21
30
  }.freeze
22
31
 
@@ -98,19 +107,27 @@ class Lighthouse::GraphQL::Directives::SoftDeletesDirective
98
107
  end
99
108
 
100
109
  def soft_delete(field)
101
- if field.directives.any? { |directive| directive.name == 'softDeletes' }
110
+ directive = field.directives.find { |node| node.name == 'softDeletes' }
111
+ if directive
102
112
  @rewritten = true
103
- field = field.merge(arguments: with_trashed_argument(field.arguments),
104
- directives: field.directives.reject { |directive| directive.name == 'softDeletes' })
113
+ field = field.merge(arguments: with_trashed_argument(field.arguments, ability(directive)),
114
+ directives: field.directives.reject { |node| node.name == 'softDeletes' })
105
115
  end
106
116
  @trashed ||= field.arguments.any? { |argument| trashed?(argument) }
107
117
  field
108
118
  end
109
119
 
110
- def with_trashed_argument(arguments)
120
+ # The field's arguments with `trashed`, unless it has one of its own;
121
+ # behind @canModel(ability:) when `ability` is given.
122
+ def with_trashed_argument(arguments, ability)
111
123
  return arguments if arguments.any? { |argument| argument.name == 'trashed' }
112
124
 
113
- arguments + ::GraphQL::Language::Parser.parse(ARGUMENT).definitions.first.fields.first.arguments
125
+ sdl = ability ? ARGUMENT.sub('@trashed', "@trashed @canModel(ability: #{ability.to_json})") : ARGUMENT
126
+ arguments + ::GraphQL::Language::Parser.parse(sdl).definitions.first.fields.first.arguments
127
+ end
128
+
129
+ def ability(directive)
130
+ Lighthouse::Support::DirectiveArgs.literal(directive, 'ability')
114
131
  end
115
132
 
116
133
  def trashed?(node)
@@ -73,6 +73,12 @@ class Lighthouse::GraphQL::DocumentAST
73
73
  self
74
74
  end
75
75
 
76
+ # Drops the directive definition of that name, if any.
77
+ def remove_directive(name)
78
+ @directives.delete(name)
79
+ self
80
+ end
81
+
76
82
  # Adds the type parsed from `sdl`, unless the document has a type of that name.
77
83
  def define_type(name, sdl = nil)
78
84
  return @types[name] if @types.key?(name)
@@ -22,6 +22,7 @@ module Lighthouse::GraphQL::FieldResolverStack
22
22
  steps << own_step(type, field_def, root_kind, bases, type_class) unless resolving_directive?(directives)
23
23
  steps << validator_step(type, field_def, opts) if input_validation?(field_def, directives)
24
24
  steps.concat(argument_steps(type, field_def, directives, opts))
25
+ steps.concat(argument_authorization_steps(type, field_def, opts))
25
26
 
26
27
  steps.compact.each_with_index.sort_by { |(order, _), index| [order, index] }.each { |(_, step), _| step.call }
27
28
  end
@@ -110,6 +111,37 @@ module Lighthouse::GraphQL::FieldResolverStack
110
111
  steps
111
112
  end
112
113
 
114
+ # A @canModel on an argument or input field, at any depth: who may use it.
115
+ # Ordered with the field's @can* directives; it checks only when the client
116
+ # gave the argument a value (CanModelDirectiveResolver).
117
+ def argument_authorization_steps(type, field_def, opts)
118
+ resolver = Lighthouse::GraphQL::DirectiveResolvers::CanModelDirectiveResolver
119
+ order = Lighthouse::DirectiveRegistry.default.resolution_order(resolver.directive_name)
120
+ authorized_arguments(field_def.arguments).map do |path, dnode|
121
+ [order, -> { resolver.new(field_def, type, dnode, opts.merge(argument: path)).define_resolver(type) }]
122
+ end
123
+ end
124
+
125
+ # [dot path ("filter.trashed", "inputs.*.status"), @canModel node] for every
126
+ # argument and input field carrying @canModel; an input type is not walked
127
+ # twice on one path.
128
+ def authorized_arguments(arguments, prefix = nil, seen = Set.new)
129
+ arguments.each_value.flat_map do |argument|
130
+ path = [prefix, argument.graphql_name].compact.join('.')
131
+ own = (argument.ast_node&.directives || []).select { |d| d.name == 'canModel' }.map { |dnode| [path, dnode] }
132
+ own + authorized_input_fields(argument, path, seen)
133
+ end
134
+ end
135
+
136
+ # Those of the input type an argument takes; `*` steps into each of a list.
137
+ def authorized_input_fields(argument, path, seen)
138
+ type = argument.type.unwrap
139
+ return [] unless type.kind.input_object? && seen.exclude?(type.graphql_name)
140
+
141
+ list = (argument.type.non_null? ? argument.type.of_type : argument.type).list?
142
+ authorized_arguments(type.arguments, list ? "#{path}.*" : path, seen | [type.graphql_name])
143
+ end
144
+
113
145
  # Around whatever resolves the field, as @lazyLoad: the result is cut to the client's @limit.
114
146
  def limit_step(type, field_def, opts)
115
147
  [1, -> { Lighthouse::GraphQL::DirectiveResolvers::LimitResolver.new(field_def, type, nil, opts).define_resolver(type) }]