lighthouse-graphql 0.7.3 → 0.8.1

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 +120 -1
  3. data/docs/authorization.md +46 -3
  4. data/docs/configuration.md +38 -0
  5. data/docs/directives.md +44 -0
  6. data/docs/events.md +17 -3
  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/config.rb +19 -5
  12. data/lib/lighthouse/controller.rb +6 -67
  13. data/lib/lighthouse/directive_resolvers/argument_transforms_resolver.rb +7 -1
  14. data/lib/lighthouse/directive_resolvers/attachment_resolver.rb +139 -0
  15. data/lib/lighthouse/directive_resolvers/auth_resolver.rb +1 -1
  16. data/lib/lighthouse/directive_resolvers/can_resolvers.rb +29 -5
  17. data/lib/lighthouse/directive_resolvers/guard_resolver.rb +4 -3
  18. data/lib/lighthouse/directives/registry.rb +1 -1
  19. data/lib/lighthouse/directives/soft_deletes_directive.rb +23 -6
  20. data/lib/lighthouse/errors.rb +17 -3
  21. data/lib/lighthouse/events/execution_trace.rb +2 -2
  22. data/lib/lighthouse/events/lifecycle.rb +20 -6
  23. data/lib/lighthouse/field_resolver_stack.rb +32 -0
  24. data/lib/lighthouse/global_id.rb +16 -5
  25. data/lib/lighthouse/graphql/version.rb +1 -1
  26. data/lib/lighthouse/operations.rb +111 -0
  27. data/lib/lighthouse/pagination.rb +21 -1
  28. data/lib/lighthouse/persisted_queries/manifest.rb +40 -0
  29. data/lib/lighthouse/persisted_queries.rb +9 -27
  30. data/lib/lighthouse/railtie.rb +8 -1
  31. data/lib/lighthouse/rb_lighthouse.rb +6 -0
  32. data/lib/lighthouse/relation_batch.rb +1 -1
  33. data/lib/lighthouse/schema_generator.rb +2 -0
  34. data/lib/lighthouse/schema_printer.rb +100 -0
  35. data/lib/lighthouse/schema_report.rb +161 -0
  36. data/lib/lighthouse/server_directives.rb +63 -0
  37. data/lib/lighthouse/tasks/lighthouse.rake +25 -6
  38. data/lib/lighthouse/upload.rb +2 -1
  39. data/lib/lighthouse/upload_store.rb +53 -2
  40. data/sig/lighthouse/controller.rbs +23 -11
  41. data/sig/lighthouse/directives.rbs +51 -18
  42. data/sig/lighthouse/events.rbs +52 -27
  43. data/sig/lighthouse/graphql.rbs +29 -24
  44. data/sig/lighthouse.rbs +207 -20
  45. metadata +7 -1
@@ -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
 
@@ -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
@@ -18,7 +18,7 @@ class Lighthouse::GraphQL::DirectiveResolvers::AuthDirectiveResolver < Lighthous
18
18
 
19
19
  install(target_type_class, lambda do |obj, arguments, ctx|
20
20
  user = ctx && (ctx[:current_user] || ctx['current_user'])
21
- raise(::GraphQL::ExecutionError, 'Unauthenticated.') unless user
21
+ raise Lighthouse::AuthenticationError unless user
22
22
 
23
23
  inner.call(obj, arguments, ctx)
24
24
  end)
@@ -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
@@ -3,8 +3,9 @@
3
3
  require_relative 'base'
4
4
 
5
5
  # @guard — require an authenticated user before the field resolves.
6
- # Wraps the field's resolver; raises "Unauthenticated." when no user is
7
- # present (per Config.authenticated_user). Mirrors PHP Lighthouse's @guard.
6
+ # Wraps the field's resolver; raises "Unauthenticated." (AuthenticationError,
7
+ # extensions.code UNAUTHENTICATED) when no user is present (per
8
+ # Config.authenticated_user). Mirrors PHP Lighthouse's @guard.
8
9
  class Lighthouse::GraphQL::DirectiveResolvers::GuardDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
9
10
  def self.directive_name = 'guard'
10
11
 
@@ -24,7 +25,7 @@ class Lighthouse::GraphQL::DirectiveResolvers::GuardDirectiveResolver < Lighthou
24
25
  inner = Lighthouse::GraphQL::DirectiveResolvers::Resolution.capture(target_type_class, method_name, @field_def, field_name)
25
26
 
26
27
  wrapper = lambda do |obj, arguments, ctx|
27
- raise(::GraphQL::ExecutionError, 'Unauthenticated.') unless Lighthouse::Support::Authorization.authenticated?(ctx)
28
+ raise Lighthouse::AuthenticationError unless Lighthouse::Support::Authorization.authenticated?(ctx)
28
29
 
29
30
  inner.call(obj, arguments, ctx)
30
31
  end
@@ -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)
@@ -6,10 +6,24 @@ module Lighthouse
6
6
  # missing @validator class. A server bug, so not a client-facing error.
7
7
  class DefinitionError < StandardError; end
8
8
 
9
- # Raised by the @can* family when the policy denies the ability.
9
+ # Raised by @guard and @auth when no user is signed in. PHP Lighthouse's
10
+ # message; `extensions.code` is Apollo's UNAUTHENTICATED, so a client can
11
+ # tell it apart without matching the text (send the user to sign in).
12
+ class AuthenticationError < ::GraphQL::ExecutionError
13
+ CODE = 'UNAUTHENTICATED'
14
+
15
+ def initialize(message = 'Unauthenticated.', extensions: {}, **options)
16
+ super(message, extensions: { 'code' => CODE }.merge(extensions), **options)
17
+ end
18
+ end
19
+
20
+ # Raised by the @can* family when the policy denies the ability, with
21
+ # Apollo's FORBIDDEN as `extensions.code`.
10
22
  class AuthorizationError < ::GraphQL::ExecutionError
11
- def initialize(message = 'This action is unauthorized.', **options)
12
- super
23
+ CODE = 'FORBIDDEN'
24
+
25
+ def initialize(message = 'This action is unauthorized.', extensions: {}, **options)
26
+ super(message, extensions: { 'code' => CODE }.merge(extensions), **options)
13
27
  end
14
28
  end
15
29
 
@@ -23,7 +23,7 @@ module Lighthouse::Events::ExecutionTrace
23
23
  class << self
24
24
  def start(schema, query)
25
25
  Lighthouse::Events.dispatch(
26
- Lighthouse::Events::StartExecution.new(schema, query.document, query.provided_variables, query.operation_name, query.context)
26
+ Lighthouse::Events::StartExecution.new(schema, query.document, query.provided_variables, query.operation_name, query.context, query)
27
27
  )
28
28
  end
29
29
 
@@ -38,7 +38,7 @@ module Lighthouse::Events::ExecutionTrace
38
38
  manipulate = Lighthouse::Events::ManipulateResult.new(result)
39
39
  Lighthouse::Events.dispatch(manipulate)
40
40
  result.replace(manipulate.result) unless manipulate.result.equal?(result)
41
- Lighthouse::Events.dispatch(Lighthouse::Events::EndExecution.new(result))
41
+ Lighthouse::Events.dispatch(Lighthouse::Events::EndExecution.new(result, query))
42
42
  end
43
43
 
44
44
  def merge_extensions(result, responses)
@@ -55,17 +55,23 @@ module Lighthouse::Events
55
55
  end
56
56
 
57
57
  # A query is about to run. `query` is its parsed GraphQL::Language::Nodes::Document
58
- # (nil if it does not parse). Fires once per operation of a multiplex.
58
+ # (nil if it does not parse), `operation_name` the one the client gave.
59
+ # Fires once per operation of a multiplex: in a batch, every StartExecution
60
+ # comes before any EndExecution, as graphql-ruby runs the operations
61
+ # together. `graphql_query` (the GraphQL::Query) is the one the operation's
62
+ # EndExecution carries too, to pair them.
59
63
  class StartExecution < Event
60
- attr_reader :schema, :query, :variables, :operation_name, :context
64
+ attr_reader :schema, :query, :variables, :operation_name, :context, :graphql_query
61
65
 
62
- def initialize(schema, query, variables, operation_name, context)
66
+ # PHP Lighthouse's five, positional as there, then the query.
67
+ def initialize(schema, query, variables, operation_name, context, graphql_query = nil) # rubocop:disable Metrics/ParameterLists
63
68
  super()
64
69
  @schema = schema
65
70
  @query = query
66
71
  @variables = variables
67
72
  @operation_name = operation_name
68
73
  @context = context
74
+ @graphql_query = graphql_query
69
75
  end
70
76
  end
71
77
 
@@ -95,14 +101,22 @@ module Lighthouse::Events
95
101
  end
96
102
  end
97
103
 
98
- # A query ran and its result is final.
104
+ # A query ran and its result is final. `graphql_query` is the GraphQL::Query
105
+ # its StartExecution carried; `operation_name` the operation that ran (nil
106
+ # for an anonymous one), and `context` its context. PHP Lighthouse's carries
107
+ # the result only, where a batch runs its operations one after the other.
99
108
  class EndExecution < Event
100
- attr_reader :result
109
+ attr_reader :result, :graphql_query
101
110
 
102
- def initialize(result)
111
+ def initialize(result, graphql_query = nil)
103
112
  super()
104
113
  @result = result
114
+ @graphql_query = graphql_query
105
115
  end
116
+
117
+ def operation_name = graphql_query&.selected_operation_name
118
+
119
+ def context = graphql_query&.context
106
120
  end
107
121
 
108
122
  # The operation(s) ran: the result, or for a batch an Array of results.
@@ -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) }]
@@ -11,8 +11,10 @@ require 'base64'
11
11
  # A schema that implements graphql-ruby's Relay ids, `id_from_object` and
12
12
  # `object_from_id` (graphql-ruby's install writes them, on Rails' GlobalID),
13
13
  # has one kind of global id: @globalId encodes an object's own id with
14
- # `id_from_object`, and decodes with `object_from_id`, as graphql-ruby's
15
- # Query.node and Node's `id` do.
14
+ # `id_from_object`, as graphql-ruby's Node `id` does. It decodes one as PHP
15
+ # Lighthouse's GlobalId does, without reading the database: Rails' GlobalID
16
+ # names the model and the id. Only an id of another format is decoded
17
+ # through `object_from_id`, which loads the record.
16
18
  module Lighthouse::GraphQL::GlobalId
17
19
  module_function
18
20
 
@@ -26,11 +28,11 @@ module Lighthouse::GraphQL::GlobalId
26
28
  []
27
29
  end
28
30
 
29
- # [type, id] for a global id a client sent, through the schema's
30
- # object_from_id (schema_ids?) or Config.global_id; a
31
+ # [type, id] for a global id a client sent, from Rails' GlobalID or the
32
+ # schema's object_from_id (schema_ids?), else Config.global_id; a
31
33
  # GraphQL::ExecutionError when it is not one.
32
34
  def decode!(global_id, context = nil)
33
- type, id = schema_ids?(context&.schema) ? decode_object(global_id, context) : Lighthouse::Config.global_id.decode(global_id)
35
+ type, id = schema_ids?(context&.schema) ? decode_schema_id(global_id, context) : Lighthouse::Config.global_id.decode(global_id)
34
36
  return [type, id] if type.present? && !id.nil?
35
37
 
36
38
  raise ::GraphQL::ExecutionError, "#{global_id.inspect} is not a valid global id."
@@ -49,6 +51,15 @@ module Lighthouse::GraphQL::GlobalId
49
51
  schema.respond_to?(:object_from_id) && schema.method(:object_from_id).owner != ::GraphQL::Schema.singleton_class
50
52
  end
51
53
 
54
+ # A Rails GlobalID (`to_gid_param`, graphql-ruby's install's
55
+ # id_from_object) names its model and id, so the record needs no SELECT,
56
+ # and one a default scope hides (a soft-deleted record @restore looks for)
57
+ # decodes too. Any other id goes through object_from_id.
58
+ def decode_schema_id(global_id, context)
59
+ gid = defined?(::GlobalID) && global_id.is_a?(String) ? ::GlobalID.parse(global_id) : nil
60
+ gid ? [gid.model_name.demodulize, gid.model_id] : decode_object(global_id, context)
61
+ end
62
+
52
63
  # [type, id] of the object the schema's object_from_id finds.
53
64
  def decode_object(global_id, context)
54
65
  object = context.schema.object_from_id(global_id, context)
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Lighthouse
4
4
  module GraphQL
5
- VERSION = '0.7.3'
5
+ VERSION = '0.8.1'
6
6
  end
7
7
  end