graphql-armory 0.1.0.pre8 → 0.1.0.pre10
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +64 -0
- data/README.md +7 -7
- data/docs/authorization.md +123 -5
- data/docs/encrypted-ids.md +1 -1
- data/docs/keyset-connections.md +28 -4
- data/docs/persisted-queries.md +111 -19
- data/docs/rate-limiting.md +37 -13
- data/docs/telemetry.md +31 -8
- data/exe/graphql-armory-publish +6 -0
- data/lib/graphql/armory/authorization/adapters/cancan.rb +7 -3
- data/lib/graphql/armory/authorization/adapters/pundit.rb +8 -1
- data/lib/graphql/armory/authorization/audit/baseline.rb +191 -0
- data/lib/graphql/armory/authorization/audit/command.rb +57 -8
- data/lib/graphql/armory/authorization/audit/findings.rb +3 -2
- data/lib/graphql/armory/authorization/audit/interface_rules.rb +4 -1
- data/lib/graphql/armory/authorization/audit/observed_rules.rb +58 -0
- data/lib/graphql/armory/authorization/audit/payload_reuse.rb +95 -0
- data/lib/graphql/armory/authorization/audit/plain_resolvers.rb +85 -0
- data/lib/graphql/armory/authorization/audit/reach.rb +75 -0
- data/lib/graphql/armory/authorization/audit/report.rb +7 -1
- data/lib/graphql/armory/authorization/audit/type_rules.rb +19 -2
- data/lib/graphql/armory/authorization/audit.rb +12 -4
- data/lib/graphql/armory/authorization/authorize.rb +28 -8
- data/lib/graphql/armory/authorization/configuration.rb +4 -3
- data/lib/graphql/armory/authorization/definitions.rb +7 -0
- data/lib/graphql/armory/authorization/integration/field.rb +26 -4
- data/lib/graphql/armory/authorization/integration/object.rb +8 -0
- data/lib/graphql/armory/authorization/integration/resolver.rb +2 -0
- data/lib/graphql/armory/authorization/integration.rb +14 -3
- data/lib/graphql/armory/authorization/rspec.rb +10 -4
- data/lib/graphql/armory/authorization/rule.rb +19 -3
- data/lib/graphql/armory/authorization/scope.rb +6 -6
- data/lib/graphql/armory/authorization.rb +1 -1
- data/lib/graphql/armory/ids.rb +11 -11
- data/lib/graphql/armory/keyset/encoder_check.rb +113 -0
- data/lib/graphql/armory/keyset.rb +23 -3
- data/lib/graphql/armory/persisted_queries/manifest.rb +2 -0
- data/lib/graphql/armory/persisted_queries/manifests.rb +69 -0
- data/lib/graphql/armory/persisted_queries/publisher.rb +127 -0
- data/lib/graphql/armory/persisted_queries/redis_store.rb +137 -0
- data/lib/graphql/armory/persisted_queries.rb +55 -16
- data/lib/graphql/armory/railtie.rb +10 -0
- data/lib/graphql/armory/rate_limits/analysis_guard.rb +175 -0
- data/lib/graphql/armory/rate_limits/concurrency.rb +93 -14
- data/lib/graphql/armory/rate_limits/invalid_queries.rb +75 -0
- data/lib/graphql/armory/rate_limits/points.rb +129 -15
- data/lib/graphql/armory/rate_limits/time.rb +140 -22
- data/lib/graphql/armory/rate_limits.rb +30 -5
- data/lib/graphql/armory/telemetry.rb +71 -9
- data/lib/graphql/armory/version.rb +1 -1
- data/lib/graphql/armory.rb +1 -0
- data/lib/tasks/graphql_armory.rake +11 -4
- metadata +17 -3
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module GraphQL
|
|
6
|
+
module Armory
|
|
7
|
+
class Keyset < GraphQL::Pagination::Connection
|
|
8
|
+
# Asks an encoder whether it can keep a keyset cursor private, raising `ConfigurationError` when it cannot. It catches
|
|
9
|
+
# what is common: no encryption, a reversible form, a fixed key, and a chain that decodes forged text. It cannot prove
|
|
10
|
+
# encryption. It has no dependencies, so `new` is ready at once and there is nothing to `build`.
|
|
11
|
+
class EncoderCheck
|
|
12
|
+
NEEDLE = "graphql-armory-probe"
|
|
13
|
+
# Shaped like a real cursor, because an encoder may parse what it is given. They differ in their first value.
|
|
14
|
+
PROBE = JSON.generate({ "v" => 1, "o" => "0" * 32, "k" => ["#{NEEDLE}-values"] }).freeze
|
|
15
|
+
# Differ from PROBE near the start and at the end: a chained mode with a fixed IV changes every block after a change
|
|
16
|
+
# near the start, and only the last block after a change at the end.
|
|
17
|
+
OTHERS = [PROBE.sub('"v":1', '"v":2'), PROBE.sub('-values"', '-valuez"')].map(&:freeze).freeze
|
|
18
|
+
|
|
19
|
+
def self.call(encoder)
|
|
20
|
+
new.(encoder)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def call(encoder)
|
|
24
|
+
# Every member of a chain decodes what a client sends, so each one is checked on its own.
|
|
25
|
+
encoder.encoders.each { |member| call(member) } if encoder.is_a?(Encoder::Versioned)
|
|
26
|
+
first = encoded(encoder, PROBE)
|
|
27
|
+
refuse("does not give back what it encoded") unless decoded(encoder, first) == PROBE
|
|
28
|
+
refuse("leaves the cursor readable: it holds the ordering values") if readable?(first)
|
|
29
|
+
if OTHERS.any? { |other| local?(first, encoded(encoder, other)) }
|
|
30
|
+
refuse("changes only part of its output when the input changes, as a fixed key or a fixed nonce does")
|
|
31
|
+
end
|
|
32
|
+
refuse("decodes forged text, so a client can make its own cursors") if forged?(encoder)
|
|
33
|
+
nil
|
|
34
|
+
rescue ConfigurationError => error
|
|
35
|
+
raise if error.equal?(@refusal)
|
|
36
|
+
|
|
37
|
+
refuse("could not be probed: #{error.class}")
|
|
38
|
+
rescue StandardError, NotImplementedError => error
|
|
39
|
+
# The class only: an encoder's message may hold a key.
|
|
40
|
+
refuse("could not be probed: #{error.class}")
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
private
|
|
44
|
+
|
|
45
|
+
def encoded(encoder, text)
|
|
46
|
+
answer = encoder.encode(text, nonce: true)
|
|
47
|
+
answer.is_a?(String) ? answer.b : refuse("answers #{answer.class}, not a String")
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def decoded(encoder, text)
|
|
51
|
+
answer = encoder.decode(text, nonce: true)
|
|
52
|
+
answer.is_a?(String) ? answer.b : answer
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def readable?(output)
|
|
56
|
+
needle = NEEDLE.b
|
|
57
|
+
[output, output.reverse, output.tr("A-Za-z", "N-ZA-Mn-za-m")].any? do |form|
|
|
58
|
+
([form, form.delete("\0")] + unpacked(form)).any? { |text| text.include?(needle) }
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Each long run of Base64 or hex inside the output, decoded from every offset, so a prefix of any length does not hide it.
|
|
63
|
+
def unpacked(form)
|
|
64
|
+
base64 = form.scan(%r{[A-Za-z0-9+/_-]{16,}}).flat_map do |run|
|
|
65
|
+
(0..3).map { |offset| run[offset..].tr("-_", "+/").unpack1("m").b }
|
|
66
|
+
end
|
|
67
|
+
hex = form.scan(/\h{16,}/).flat_map { |run| (0..1).map { |offset| [run[offset..]].pack("H*").b } }
|
|
68
|
+
base64 + hex
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# A one-byte change near the start changes most of what a sound encoder answers.
|
|
72
|
+
def local?(one, other)
|
|
73
|
+
size = [one.size, other.size].max
|
|
74
|
+
changed = (0...size).count { |index| one.getbyte(index) != other.getbyte(index) }
|
|
75
|
+
changed < size / 2
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def forged?(encoder)
|
|
79
|
+
[PROBE, [PROBE].pack("m0"), [PROBE].pack("m0").tr("+/", "-_").delete("=")].any? do |forgery|
|
|
80
|
+
decoded(encoder, forgery) == PROBE.b
|
|
81
|
+
rescue StandardError
|
|
82
|
+
false
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# Remembers its own refusal, so an encoder that raises a ConfigurationError of its own is named by class, like any other.
|
|
87
|
+
def refuse(what)
|
|
88
|
+
@refusal = ConfigurationError.new(
|
|
89
|
+
"this cursor_encoder #{what}. A keyset cursor holds the row's ordering values: use a GraphQL::Armory::Encoder " \
|
|
90
|
+
"subclass, or `use GraphQL::Armory::Keyset, plain_cursors: true` if those values are not secret"
|
|
91
|
+
)
|
|
92
|
+
raise @refusal
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# What `use GraphQL::Armory::Keyset` adds to a schema. A subclass inherits it, so an encoder set there is checked too.
|
|
97
|
+
module SchemaChecks
|
|
98
|
+
def armory_keyset_plain_cursors
|
|
99
|
+
return @armory_keyset_plain_cursors unless @armory_keyset_plain_cursors.nil?
|
|
100
|
+
|
|
101
|
+
superclass.respond_to?(:armory_keyset_plain_cursors) ? superclass.armory_keyset_plain_cursors : false
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
attr_writer :armory_keyset_plain_cursors
|
|
105
|
+
|
|
106
|
+
def cursor_encoder(new_encoder = nil)
|
|
107
|
+
EncoderCheck.(new_encoder) if new_encoder && !armory_keyset_plain_cursors
|
|
108
|
+
super
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
end
|
|
@@ -84,9 +84,26 @@ module GraphQL
|
|
|
84
84
|
|
|
85
85
|
attr_reader :columns
|
|
86
86
|
|
|
87
|
-
# Checks the
|
|
88
|
-
|
|
87
|
+
# Checks the encoder when the schema loads, and keeps checking any encoder set later on it or on a subclass. Put it
|
|
88
|
+
# below `cursor_encoder`: graphql-ruby runs `use` at once, with no hook for the end of the class body.
|
|
89
|
+
def self.use(schema, plain_cursors: false)
|
|
89
90
|
raise ConfigurationError, "plain_cursors: must be true or false, got #{plain_cursors.inspect}" unless [true, false].include?(plain_cursors)
|
|
91
|
+
|
|
92
|
+
unless plain_cursors
|
|
93
|
+
if schema.cursor_encoder == GraphQL::Schema::Base64Encoder
|
|
94
|
+
raise ConfigurationError, "no cursor_encoder is set on this schema: put cursor_encoder above `use GraphQL::Armory::Keyset`, or pass plain_cursors: true"
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
EncoderCheck.(schema.cursor_encoder)
|
|
98
|
+
end
|
|
99
|
+
schema.extend(SchemaChecks)
|
|
100
|
+
schema.armory_keyset_plain_cursors = plain_cursors
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# Checks the relation and its ordering; resolvers go through here. With no `plain_cursors:`, the schema's setting
|
|
104
|
+
# decides when the page loads.
|
|
105
|
+
def self.build(relation, plain_cursors: nil)
|
|
106
|
+
raise ConfigurationError, "plain_cursors: must be true, false or nil, got #{plain_cursors.inspect}" unless [true, false, nil].include?(plain_cursors)
|
|
90
107
|
raise ConfigurationError, "a keyset connection needs an ActiveRecord relation, got #{relation.class}" unless relation.respond_to?(:order_values)
|
|
91
108
|
|
|
92
109
|
new(relation, columns: Ordering.(relation), plain_cursors: plain_cursors)
|
|
@@ -181,9 +198,11 @@ module GraphQL
|
|
|
181
198
|
end
|
|
182
199
|
|
|
183
200
|
def refuse_plain_cursors
|
|
201
|
+
schema = context&.schema
|
|
202
|
+
return if @plain_cursors.nil? && schema.respond_to?(:armory_keyset_plain_cursors) && schema.armory_keyset_plain_cursors
|
|
184
203
|
return if @plain_cursors
|
|
185
204
|
|
|
186
|
-
encoder =
|
|
205
|
+
encoder = schema&.cursor_encoder
|
|
187
206
|
return unless encoder.nil? || encoder == GraphQL::Schema::Base64Encoder
|
|
188
207
|
|
|
189
208
|
raise ConfigurationError,
|
|
@@ -277,3 +296,4 @@ module GraphQL
|
|
|
277
296
|
end
|
|
278
297
|
|
|
279
298
|
require "graphql/armory/keyset/controls"
|
|
299
|
+
require "graphql/armory/keyset/encoder_check"
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
module PersistedQueries
|
|
6
|
+
# Several manifests behind one `store:`: each frontend's build, and every mobile version still in use.
|
|
7
|
+
#
|
|
8
|
+
# use GraphQL::Armory::PersistedQueries, store: Manifests.build("config/persisted_queries/*.json"), strict: true
|
|
9
|
+
#
|
|
10
|
+
# A client's id is looked up across all of them, so any client may run any manifest's operation: they are one
|
|
11
|
+
# allowlist, not one per client. Any problem raises at boot.
|
|
12
|
+
class Manifests
|
|
13
|
+
GLOB = /[*?\[{]/
|
|
14
|
+
|
|
15
|
+
# `paths` is a glob pattern, a path, or a list of them. One that finds nothing raises: in strict mode its clients
|
|
16
|
+
# would all be refused. A glob skips dotfiles, and drops a missing `{a,b}` alternative: list exact paths to be sure.
|
|
17
|
+
def self.build(paths, digest: :sha256)
|
|
18
|
+
names = paths.is_a?(Array) ? paths : [paths]
|
|
19
|
+
raise ConfigurationError, "no manifest found in an empty list" if names.empty?
|
|
20
|
+
|
|
21
|
+
files = names.flat_map { |name| files_of(name) }.uniq
|
|
22
|
+
new(files.map { |file| Manifest.load(file, digest: digest) })
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def self.files_of(name)
|
|
26
|
+
raise ConfigurationError, "manifest paths must be Strings or Pathnames, found a #{name.class}" unless name.is_a?(String) || name.respond_to?(:to_path)
|
|
27
|
+
|
|
28
|
+
path = name.is_a?(String) ? name : name.to_path
|
|
29
|
+
return [path] unless path.match?(GLOB)
|
|
30
|
+
|
|
31
|
+
found = Dir.glob(path).sort
|
|
32
|
+
found = [path] if found.empty? && File.file?(path) # a name with a `[`, which matched nothing as a pattern
|
|
33
|
+
raise ConfigurationError, "no manifest found in #{path}" if found.empty?
|
|
34
|
+
|
|
35
|
+
found
|
|
36
|
+
end
|
|
37
|
+
private_class_method :files_of
|
|
38
|
+
|
|
39
|
+
# `new` is inert: with no manifests it holds no operation, so every id is unknown.
|
|
40
|
+
def initialize(manifests = [])
|
|
41
|
+
unless manifests.is_a?(Array) && manifests.all? { |manifest| manifest.instance_of?(Manifest) }
|
|
42
|
+
raise ConfigurationError, "manifests must be an Array of Manifest; use Manifests.build for paths"
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
@operations = manifests.each_with_object({}) do |manifest, operations|
|
|
46
|
+
manifest.operations.each do |id, operation|
|
|
47
|
+
kept = operations[id] ||= operation
|
|
48
|
+
next if kept.body == operation.body
|
|
49
|
+
|
|
50
|
+
raise ConfigurationError, "two manifests hold different queries for #{id.match?(Manifest::ID_LIKE) ? "the id #{id}" : "one id"}"
|
|
51
|
+
end
|
|
52
|
+
end.freeze
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def fetch(id)
|
|
56
|
+
@operations[id]
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def size
|
|
60
|
+
@operations.size
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def empty?
|
|
64
|
+
@operations.empty?
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "optparse"
|
|
4
|
+
|
|
5
|
+
module GraphQL
|
|
6
|
+
module Armory
|
|
7
|
+
module PersistedQueries
|
|
8
|
+
# Publishes a client build's manifest to Redis, for `RedisStore` to read. It only adds: an id that already holds
|
|
9
|
+
# another query raises and stays as it was. Publishing again is safe, so a failed run can simply run again.
|
|
10
|
+
#
|
|
11
|
+
# GraphQL::Armory::PersistedQueries::Publisher.call(Manifest.load("manifest.json"), redis: Redis.new(url: url))
|
|
12
|
+
class Publisher
|
|
13
|
+
# An id it could not store, or that holds another query. The message quotes neither query.
|
|
14
|
+
class PublishError < Armory::Error; end
|
|
15
|
+
|
|
16
|
+
Result = Struct.new(:published, :unchanged, keyword_init: true)
|
|
17
|
+
|
|
18
|
+
def self.build(redis:, prefix: RedisStore::DEFAULT_PREFIX)
|
|
19
|
+
raise ConfigurationError, "redis: must answer get and set, like Redis.new from the redis gem" unless redis.respond_to?(:get) && redis.respond_to?(:set)
|
|
20
|
+
raise ConfigurationError, "prefix: must be a non-empty String, got #{prefix.inspect}" unless prefix.is_a?(String) && !prefix.empty?
|
|
21
|
+
|
|
22
|
+
new(redis: redis, prefix: prefix)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def self.call(manifest, **options)
|
|
26
|
+
build(**options).(manifest)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# `new` is inert: with no Redis wired, nothing is stored and `call` raises.
|
|
30
|
+
def initialize(redis: RedisStore::Client::Null.new, prefix: RedisStore::DEFAULT_PREFIX)
|
|
31
|
+
@redis = redis
|
|
32
|
+
@prefix = prefix
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def call(manifest)
|
|
36
|
+
raise ConfigurationError, "publish a Manifest: Manifest.load checks every id and query" unless manifest.instance_of?(Manifest)
|
|
37
|
+
|
|
38
|
+
check_ids(manifest)
|
|
39
|
+
published = manifest.operations.count { |id, operation| publish(id, operation.body) }
|
|
40
|
+
Result.new(published: published, unchanged: manifest.size - published)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
private
|
|
44
|
+
|
|
45
|
+
# Before anything is stored: `RedisStore` never asks for an id of another shape.
|
|
46
|
+
def check_ids(manifest)
|
|
47
|
+
manifest.operations.keys.each_with_index do |id, index|
|
|
48
|
+
raise ConfigurationError, "the operation at entry #{index} has an id RedisStore cannot read" unless id.match?(Manifest::ID_LIKE)
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# Answers whether it was new. SET NX, so two runs at once cannot overwrite each other.
|
|
53
|
+
def publish(id, body)
|
|
54
|
+
key = "#{@prefix}#{id}"
|
|
55
|
+
return true if @redis.set(key, body, nx: true)
|
|
56
|
+
|
|
57
|
+
stored = @redis.get(key)
|
|
58
|
+
raise PublishError, "operation #{id} was not stored" if stored.nil?
|
|
59
|
+
raise PublishError, "operation #{id} already holds another query: published operations never change" unless stored.b == body.b
|
|
60
|
+
|
|
61
|
+
false
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# The `graphql-armory-publish` executable, for a client's CI. Answers the exit code. Redis's messages may hold
|
|
65
|
+
# the URL and its password, so only the error's class is printed.
|
|
66
|
+
class Command
|
|
67
|
+
USAGE = "Usage: graphql-armory-publish [--digest sha256|sha1|md5|false] [--prefix PREFIX] MANIFEST...\nReads REDIS_URL."
|
|
68
|
+
|
|
69
|
+
def self.call(argv = ARGV, env: ENV, out: $stdout, err: $stderr, client: nil)
|
|
70
|
+
new(env: env, out: out, err: err, client: client).(argv)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def initialize(env: {}, out: $stdout, err: $stderr, client: nil)
|
|
74
|
+
@env = env
|
|
75
|
+
@out = out
|
|
76
|
+
@err = err
|
|
77
|
+
@client = client
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def call(argv)
|
|
81
|
+
digest, prefix, paths = options(argv)
|
|
82
|
+
return fail_with(USAGE) if paths.empty?
|
|
83
|
+
|
|
84
|
+
url = @env["REDIS_URL"]
|
|
85
|
+
return fail_with("REDIS_URL is not set") if url.to_s.empty?
|
|
86
|
+
|
|
87
|
+
manifests = paths.map { |path| [path, Manifest.load(path, digest: digest)] }
|
|
88
|
+
publisher = Publisher.build(redis: @client || redis(url), prefix: prefix)
|
|
89
|
+
manifests.each do |path, manifest|
|
|
90
|
+
result = publisher.(manifest)
|
|
91
|
+
@out.puts "#{path}: #{result.published} published, #{result.unchanged} unchanged"
|
|
92
|
+
end
|
|
93
|
+
0
|
|
94
|
+
rescue OptionParser::ParseError, Armory::Error => error
|
|
95
|
+
fail_with(error.message)
|
|
96
|
+
rescue LoadError
|
|
97
|
+
fail_with("graphql-armory-publish needs the redis gem: gem install redis")
|
|
98
|
+
rescue StandardError => error
|
|
99
|
+
fail_with("publishing failed (#{error.class})")
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
private
|
|
103
|
+
|
|
104
|
+
def options(argv)
|
|
105
|
+
digest = :sha256
|
|
106
|
+
prefix = RedisStore::DEFAULT_PREFIX
|
|
107
|
+
paths = OptionParser.new do |parser|
|
|
108
|
+
parser.on("--digest NAME") { |name| digest = name == "false" ? false : name.to_sym }
|
|
109
|
+
parser.on("--prefix PREFIX") { |given| prefix = given }
|
|
110
|
+
end.parse(argv)
|
|
111
|
+
[digest, prefix, paths]
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def redis(url)
|
|
115
|
+
require "redis"
|
|
116
|
+
Redis.new(url: url)
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
def fail_with(message)
|
|
120
|
+
@err.puts message
|
|
121
|
+
1
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
end
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
module PersistedQueries
|
|
6
|
+
# Operations a client's CI published with `Publisher`, read while the server runs, so a new frontend needs no
|
|
7
|
+
# server deploy.
|
|
8
|
+
#
|
|
9
|
+
# store = GraphQL::Armory::PersistedQueries::RedisStore.build(redis: Redis.new(url: ENV.fetch("REDIS_URL")))
|
|
10
|
+
#
|
|
11
|
+
# An operation it read stays in memory: published operations never change, so what it already knows keeps working
|
|
12
|
+
# when Redis fails. An id it cannot find, or cannot check, is unknown: nothing runs. This gem does not depend on
|
|
13
|
+
# the redis gem: the app adds it.
|
|
14
|
+
class RedisStore
|
|
15
|
+
DEFAULT_PREFIX = "graphql-armory:persisted-queries:"
|
|
16
|
+
DEFAULT_ON_ERROR = ->(error) { warn "graphql-armory: persisted query store failed (#{error.class})" }
|
|
17
|
+
|
|
18
|
+
# A stored value that does not parse, or is not the digest of its id. The message quotes neither.
|
|
19
|
+
class CorruptOperation < Armory::Error; end
|
|
20
|
+
|
|
21
|
+
# What the store and the publisher need from Redis.
|
|
22
|
+
module Client
|
|
23
|
+
# The Redis of a store nobody wired: it holds nothing and stores nothing.
|
|
24
|
+
class Null
|
|
25
|
+
def get(_key)
|
|
26
|
+
nil
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def set(_key, _value, nx: false)
|
|
30
|
+
nil
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# Holds its keys in memory like Redis, records its calls and fails when told: for tests.
|
|
35
|
+
class Substitute
|
|
36
|
+
attr_reader :calls
|
|
37
|
+
|
|
38
|
+
def initialize
|
|
39
|
+
@data = {}
|
|
40
|
+
@calls = []
|
|
41
|
+
@failure = nil
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# Raises `error` from every call until `recover`.
|
|
45
|
+
def fail_with(error)
|
|
46
|
+
@failure = error
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def recover
|
|
50
|
+
@failure = nil
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def get(key)
|
|
54
|
+
@calls << [:get, key]
|
|
55
|
+
raise @failure if @failure
|
|
56
|
+
|
|
57
|
+
@data[key]
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def set(key, value, nx: false)
|
|
61
|
+
@calls << [:set, key]
|
|
62
|
+
raise @failure if @failure
|
|
63
|
+
return false if nx && @data.key?(key)
|
|
64
|
+
|
|
65
|
+
@data[key] = value
|
|
66
|
+
true
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# Validates the settings and wires the real Redis client.
|
|
72
|
+
def self.build(redis:, prefix: DEFAULT_PREFIX, digest: :sha256, on_error: DEFAULT_ON_ERROR)
|
|
73
|
+
raise ConfigurationError, "redis: must answer get and set, like Redis.new from the redis gem" unless redis.respond_to?(:get) && redis.respond_to?(:set)
|
|
74
|
+
raise ConfigurationError, "prefix: must be a non-empty String, got #{prefix.inspect}" unless prefix.is_a?(String) && !prefix.empty?
|
|
75
|
+
unless digest == false || Manifest::DIGESTS.key?(digest)
|
|
76
|
+
raise ConfigurationError, "unknown digest #{digest.inspect}: use #{Manifest::DIGESTS.keys.map(&:inspect).join(", ")} or false"
|
|
77
|
+
end
|
|
78
|
+
raise ConfigurationError, "on_error: must be a callable that takes the error" unless on_error.respond_to?(:call)
|
|
79
|
+
|
|
80
|
+
new(redis: redis, prefix: prefix, digest: digest, on_error: on_error)
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# `new` is inert: with no Redis wired it holds no operation, so every id is unknown.
|
|
84
|
+
def initialize(redis: Client::Null.new, prefix: DEFAULT_PREFIX, digest: :sha256, on_error: DEFAULT_ON_ERROR)
|
|
85
|
+
@redis = redis
|
|
86
|
+
@prefix = prefix
|
|
87
|
+
@digest = digest == false ? nil : Manifest::DIGESTS.fetch(digest)
|
|
88
|
+
@on_error = on_error
|
|
89
|
+
@operations = {}
|
|
90
|
+
@mutex = Mutex.new
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def fetch(id)
|
|
94
|
+
# Bytes: a regexp raises on a client's broken encoding.
|
|
95
|
+
return unless id.is_a?(String) && id.b.match?(Manifest::ID_LIKE)
|
|
96
|
+
|
|
97
|
+
@operations[id] || read(id)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Only an unwired store is known to be empty: `strict: false` refuses it at boot, as it does the Null store.
|
|
101
|
+
def empty?
|
|
102
|
+
@redis.is_a?(Client::Null)
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
private
|
|
106
|
+
|
|
107
|
+
# Only what it found is remembered: an unknown id may be published a moment later.
|
|
108
|
+
def read(id)
|
|
109
|
+
body = @redis.get("#{@prefix}#{id}")
|
|
110
|
+
return if body.nil?
|
|
111
|
+
|
|
112
|
+
operation = operation(id, body)
|
|
113
|
+
@mutex.synchronize { @operations[id] ||= operation }
|
|
114
|
+
rescue StandardError => error
|
|
115
|
+
@on_error.call(error)
|
|
116
|
+
nil
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
def operation(id, stored)
|
|
120
|
+
raise CorruptOperation, "operation #{id} is not text" unless stored.is_a?(String)
|
|
121
|
+
|
|
122
|
+
# redis-rb may answer in another encoding; a query compares as text with what the client sends.
|
|
123
|
+
body = stored.dup.force_encoding(Encoding::UTF_8).freeze
|
|
124
|
+
raise CorruptOperation, "operation #{id} is not the digest of its query" if @digest && @digest.hexdigest(body) != id
|
|
125
|
+
|
|
126
|
+
Manifest::Operation.new(id: id.dup.freeze, body: body, document: parse(id, body)).freeze
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
def parse(id, body)
|
|
130
|
+
GraphQL.parse(body)
|
|
131
|
+
rescue GraphQL::ParseError
|
|
132
|
+
raise CorruptOperation, "operation #{id} does not parse"
|
|
133
|
+
end
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
end
|
|
@@ -25,6 +25,16 @@ module GraphQL
|
|
|
25
25
|
# What a refused request holds: nothing to run.
|
|
26
26
|
EMPTY_DOCUMENT = GraphQL::Language::Nodes::Document.new(definitions: [])
|
|
27
27
|
|
|
28
|
+
# What a client reads in `extensions.code`, so an app can tell a refusal from a query that failed for another reason.
|
|
29
|
+
REFUSAL_CODES = { UNKNOWN_OPERATION => "UNKNOWN_OPERATION", MISMATCH => "OPERATION_MISMATCH", RAW_QUERY_REFUSED => "RAW_QUERY_REFUSED" }.freeze
|
|
30
|
+
|
|
31
|
+
# A validation error with its code.
|
|
32
|
+
class RefusalError < GraphQL::StaticValidation::Error
|
|
33
|
+
def to_h
|
|
34
|
+
super.merge("extensions" => { "code" => REFUSAL_CODES.fetch(message, "OPERATION_REFUSED") })
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
|
|
28
38
|
# Validates nothing and answers the refusal, through the query's public `static_validator:` option.
|
|
29
39
|
class Refusal < GraphQL::StaticValidation::Validator
|
|
30
40
|
def initialize(schema, message)
|
|
@@ -33,14 +43,14 @@ module GraphQL
|
|
|
33
43
|
end
|
|
34
44
|
|
|
35
45
|
def validate(_query, **)
|
|
36
|
-
{ errors: [
|
|
46
|
+
{ errors: [RefusalError.new(@message)], remaining_timeout: nil }
|
|
37
47
|
end
|
|
38
48
|
end
|
|
39
49
|
|
|
40
|
-
# `store:` answers `fetch(id)` with an operation (`body` and `document`) or nil: a Manifest, or your own.
|
|
50
|
+
# `store:` answers `fetch(id)` with an operation (`body` and `document`) or nil: a Manifest, a RedisStore, or your own.
|
|
41
51
|
# `strict: true` refuses raw queries unless the context holds `armory_allow_raw_query: true`.
|
|
42
|
-
def self.use(schema, store:, strict: false, sinks: [])
|
|
43
|
-
gate = Gate.build(store: store, strict: strict, sinks: sinks)
|
|
52
|
+
def self.use(schema, store:, strict: false, sinks: [], on_sink_error: nil)
|
|
53
|
+
gate = Gate.build(store: store, strict: strict, sinks: sinks, on_sink_error: on_sink_error)
|
|
44
54
|
|
|
45
55
|
if schema.singleton_class.include?(Guard)
|
|
46
56
|
raise ConfigurationError, "#{schema} already uses PersistedQueries (here or in a parent schema): use it once"
|
|
@@ -49,6 +59,7 @@ module GraphQL
|
|
|
49
59
|
schema.instance_variable_set(:@armory_persisted_queries, gate)
|
|
50
60
|
schema.singleton_class.prepend(Guard)
|
|
51
61
|
schema.query_class(schema.query_class)
|
|
62
|
+
schema.trace_with(BuiltQueries)
|
|
52
63
|
end
|
|
53
64
|
|
|
54
65
|
# Decides what a request runs: answers `[refusal, document]`, where a refusal is the error message, a
|
|
@@ -56,8 +67,8 @@ module GraphQL
|
|
|
56
67
|
# as it came.
|
|
57
68
|
class Gate
|
|
58
69
|
# Wires the app's store with `use`'s defaults; `use` goes through here.
|
|
59
|
-
def self.build(store:, strict: false, sinks: [])
|
|
60
|
-
new(store: store, strict: strict, telemetry: Telemetry.build(sinks: sinks))
|
|
70
|
+
def self.build(store:, strict: false, sinks: [], on_sink_error: nil)
|
|
71
|
+
new(store: store, strict: strict, telemetry: Telemetry.build(sinks: sinks, on_sink_error: on_sink_error))
|
|
61
72
|
end
|
|
62
73
|
|
|
63
74
|
# `new` is inert: with no store wired it refuses every request. It checks what it is given, so it never
|
|
@@ -67,7 +78,7 @@ module GraphQL
|
|
|
67
78
|
raise ConfigurationError, "store: must answer fetch(id) with an operation or nil, like a Manifest"
|
|
68
79
|
end
|
|
69
80
|
raise ConfigurationError, "strict: must be true or false, got #{strict.inspect}" unless strict == true || strict == false
|
|
70
|
-
raise ConfigurationError, "strict: false needs a store: with
|
|
81
|
+
raise ConfigurationError, "strict: false needs a store that holds operations: with an empty one only raw queries would run" if !strict && (store.is_a?(Store::Null) || (store.respond_to?(:empty?) && store.empty?))
|
|
71
82
|
|
|
72
83
|
@store = store
|
|
73
84
|
@strict = strict
|
|
@@ -76,30 +87,40 @@ module GraphQL
|
|
|
76
87
|
|
|
77
88
|
def call(context, text, document)
|
|
78
89
|
operation_id = context[:operation_id] if context.respond_to?(:[])
|
|
90
|
+
sink_context = context.respond_to?(:[]) ? context : {}
|
|
79
91
|
|
|
80
92
|
if !operation_id.nil?
|
|
81
93
|
operation = operation_id.is_a?(String) ? @store.fetch(operation_id) : nil
|
|
82
94
|
if operation.nil?
|
|
83
|
-
refuse(UNKNOWN_OPERATION, :unknown_operation)
|
|
95
|
+
refuse(UNKNOWN_OPERATION, :unknown_operation, sink_context)
|
|
84
96
|
elsif document || (text && !same_query?(text, operation))
|
|
85
|
-
refuse(MISMATCH, :mismatch)
|
|
97
|
+
refuse(MISMATCH, :mismatch, sink_context)
|
|
86
98
|
else
|
|
87
|
-
@telemetry.record(:operation_persisted)
|
|
99
|
+
@telemetry.record(:operation_persisted, context: sink_context)
|
|
88
100
|
[nil, operation.document]
|
|
89
101
|
end
|
|
90
102
|
elsif @strict && !(context.respond_to?(:[]) && context[:armory_allow_raw_query] == true)
|
|
91
|
-
refuse(RAW_QUERY_REFUSED, :raw_query)
|
|
103
|
+
refuse(RAW_QUERY_REFUSED, :raw_query, sink_context)
|
|
92
104
|
else
|
|
93
|
-
@telemetry.record(@strict ? :raw_query_allowed : :raw_query_run) if text || document
|
|
105
|
+
@telemetry.record(@strict ? :raw_query_allowed : :raw_query_run, context: sink_context) if text || document
|
|
94
106
|
[nil, nil]
|
|
95
107
|
end
|
|
96
108
|
end
|
|
97
109
|
|
|
110
|
+
# A query the app built itself, which never went through the lookup. It runs its own text, so an operation id means
|
|
111
|
+
# nothing on it. Answers the refusal, or nil to let it run.
|
|
112
|
+
def built_query(context)
|
|
113
|
+
return refuse(RAW_QUERY_REFUSED, :raw_query, context).first if @strict && context[:armory_allow_raw_query] != true
|
|
114
|
+
|
|
115
|
+
@telemetry.record(@strict ? :raw_query_allowed : :raw_query_run, context: context)
|
|
116
|
+
nil
|
|
117
|
+
end
|
|
118
|
+
|
|
98
119
|
private
|
|
99
120
|
|
|
100
121
|
# The signal says why, never which operation id or query: a client chooses those.
|
|
101
|
-
def refuse(message, reason)
|
|
102
|
-
@telemetry.record(:operation_refused, reason: reason)
|
|
122
|
+
def refuse(message, reason, context)
|
|
123
|
+
@telemetry.record(:operation_refused, context: context, reason: reason)
|
|
103
124
|
[message, nil]
|
|
104
125
|
end
|
|
105
126
|
|
|
@@ -109,6 +130,21 @@ module GraphQL
|
|
|
109
130
|
end
|
|
110
131
|
end
|
|
111
132
|
|
|
133
|
+
# A `GraphQL::Query` the app builds itself skips the schema's query class. The check sits where a query starts running,
|
|
134
|
+
# on both engines: an analyzer can be skipped by a variable error, swallowed by another analyzer's ExecutionError, or
|
|
135
|
+
# ignored with `validate: false`. A `run_partials` answers for the query it came from.
|
|
136
|
+
module BuiltQueries
|
|
137
|
+
def execute_query(query:)
|
|
138
|
+
built = query.respond_to?(:query) ? query.query : query
|
|
139
|
+
unless Lookup === built
|
|
140
|
+
refusal = built.schema.armory_persisted_queries.built_query(built.context)
|
|
141
|
+
raise GraphQL::ExecutionError.new(refusal, extensions: { "code" => REFUSAL_CODES.fetch(refusal) }) if refusal
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
super
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
|
|
112
148
|
# Keeps the lookup in every query class the schema uses, including one set after `use` or by a child schema.
|
|
113
149
|
module Guard
|
|
114
150
|
UNSET = Object.new.freeze
|
|
@@ -126,7 +162,7 @@ module GraphQL
|
|
|
126
162
|
end
|
|
127
163
|
|
|
128
164
|
# The operation id a request sent, from Rack or Rails params: `operationId`, `extensions.operationId` or
|
|
129
|
-
# Apollo's `extensions.persistedQuery.sha256Hash` (`extensions` may arrive as a JSON string on GET).
|
|
165
|
+
# Apollo's `extensions.persistedQuery.sha256Hash`, or Relay's `doc_id` (`extensions` may arrive as a JSON string on GET).
|
|
130
166
|
# Answers nil when there is none, or when it is not a non-empty String.
|
|
131
167
|
def self.operation_id(params)
|
|
132
168
|
params = plain(params)
|
|
@@ -135,7 +171,7 @@ module GraphQL
|
|
|
135
171
|
extensions = plain(extensions)
|
|
136
172
|
persisted_query = plain(extensions["persistedQuery"])
|
|
137
173
|
|
|
138
|
-
[params["operationId"], extensions["operationId"], persisted_query["sha256Hash"]].find do |candidate|
|
|
174
|
+
[params["operationId"], extensions["operationId"], persisted_query["sha256Hash"], params["doc_id"]].find do |candidate|
|
|
139
175
|
candidate.is_a?(String) && !candidate.empty?
|
|
140
176
|
end
|
|
141
177
|
end
|
|
@@ -174,5 +210,8 @@ module GraphQL
|
|
|
174
210
|
end
|
|
175
211
|
|
|
176
212
|
require "graphql/armory/persisted_queries/manifest"
|
|
213
|
+
require "graphql/armory/persisted_queries/manifests"
|
|
177
214
|
require "graphql/armory/persisted_queries/store"
|
|
215
|
+
require "graphql/armory/persisted_queries/redis_store"
|
|
216
|
+
require "graphql/armory/persisted_queries/publisher"
|
|
178
217
|
require "graphql/armory/persisted_queries/controls"
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
# Makes `rake graphql_armory:audit[YourSchema]` available in a Rails app. Rails is not a dependency: this loads only when it is there.
|
|
6
|
+
class Railtie < ::Rails::Railtie
|
|
7
|
+
rake_tasks { load "tasks/graphql_armory.rake" }
|
|
8
|
+
end
|
|
9
|
+
end
|
|
10
|
+
end
|