graphql-armory 0.1.0.pre7 → 0.1.0.pre9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +81 -0
- data/README.md +6 -5
- data/docs/authorization.md +220 -10
- data/docs/encrypted-ids.md +1 -1
- data/docs/persisted-queries.md +111 -19
- data/docs/rate-limiting.md +32 -11
- data/docs/telemetry.md +31 -8
- data/exe/graphql-armory-publish +6 -0
- data/lib/graphql/armory/authorization/adapters/cancan.rb +17 -4
- data/lib/graphql/armory/authorization/adapters/pundit.rb +79 -14
- data/lib/graphql/armory/authorization/adapters/substitute.rb +4 -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/denial_hooks.rb +29 -0
- data/lib/graphql/armory/authorization/audit/edge_rules.rb +36 -0
- data/lib/graphql/armory/authorization/audit/findings.rb +35 -0
- data/lib/graphql/armory/authorization/audit/foreign_policies.rb +90 -0
- data/lib/graphql/armory/authorization/audit/input_loads.rb +26 -0
- data/lib/graphql/armory/authorization/audit/interface_rules.rb +42 -0
- data/lib/graphql/armory/authorization/audit/introspection_fields.rb +40 -0
- data/lib/graphql/armory/authorization/audit/library_methods.rb +24 -0
- data/lib/graphql/armory/authorization/audit/observed_rules.rb +58 -0
- data/lib/graphql/armory/authorization/audit/overrides.rb +81 -0
- data/lib/graphql/armory/authorization/audit/own_checks.rb +144 -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 +282 -0
- data/lib/graphql/armory/authorization/audit/visibility_models.rb +83 -0
- data/lib/graphql/armory/authorization/audit.rb +59 -192
- data/lib/graphql/armory/authorization/authorize.rb +35 -9
- data/lib/graphql/armory/authorization/configuration.rb +32 -3
- data/lib/graphql/armory/authorization/definitions.rb +121 -0
- data/lib/graphql/armory/authorization/integration/argument.rb +24 -6
- data/lib/graphql/armory/authorization/integration/field.rb +36 -6
- data/lib/graphql/armory/authorization/integration/object.rb +9 -1
- data/lib/graphql/armory/authorization/integration/resolver.rb +2 -0
- data/lib/graphql/armory/authorization/integration/schema.rb +7 -0
- data/lib/graphql/armory/authorization/integration.rb +36 -4
- data/lib/graphql/armory/authorization/rspec.rb +10 -4
- data/lib/graphql/armory/authorization/rule.rb +24 -3
- data/lib/graphql/armory/authorization/scope.rb +6 -6
- data/lib/graphql/armory/authorization.rb +4 -1
- data/lib/graphql/armory/ids.rb +11 -11
- 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 +79 -0
- data/lib/graphql/armory/rate_limits/concurrency.rb +91 -14
- data/lib/graphql/armory/rate_limits/points.rb +91 -14
- data/lib/graphql/armory/rate_limits/time.rb +107 -19
- data/lib/graphql/armory/rate_limits.rb +29 -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 +28 -3
|
@@ -8,6 +8,7 @@ require "graphql/armory/authorization/adapters/null"
|
|
|
8
8
|
require "graphql/armory/authorization/adapters/substitute"
|
|
9
9
|
require "graphql/armory/authorization/authorize"
|
|
10
10
|
require "graphql/armory/authorization/scope"
|
|
11
|
+
require "graphql/armory/authorization/definitions"
|
|
11
12
|
require "graphql/armory/authorization/audit"
|
|
12
13
|
require "graphql/armory/authorization/controls/rule"
|
|
13
14
|
require "graphql/armory/authorization/controls/context"
|
|
@@ -35,7 +36,9 @@ module GraphQL
|
|
|
35
36
|
module Authorization
|
|
36
37
|
# The schema plugin: `use GraphQL::Armory::Authorization, adapter: :pundit`.
|
|
37
38
|
# Options: `adapter:` (:pundit or an adapter object), `on_unauthorized:` (:null, :error or :raise),
|
|
38
|
-
# `sinks:` (callables that receive each telemetry signal)
|
|
39
|
+
# `sinks:` (callables that receive each telemetry signal), `on_sink_error:` (called with the error and the signal when a sink raises), `own_checks:` (an app's own `authorized?`, `authorizes?`, `authorized_new`, `wrap`,
|
|
40
|
+
# `unauthorized_object`, `visible?`, `scope_items` or `reauthorize_scoped_objects(false)` on a class, with the reason, for the audit), `own_denial_hooks:` (the schema's own
|
|
41
|
+
# `unauthorized_field` or `unauthorized_object`, each with the reason, for the audit).
|
|
39
42
|
def self.use(schema_defn, **options)
|
|
40
43
|
schema_defn.extend(Integration::Schema)
|
|
41
44
|
schema_defn.armory_configuration = Configuration.new(**options)
|
data/lib/graphql/armory/ids.rb
CHANGED
|
@@ -16,8 +16,8 @@ module GraphQL
|
|
|
16
16
|
module IDs
|
|
17
17
|
SEPARATOR = "/"
|
|
18
18
|
|
|
19
|
-
def self.use(schema, encoder: nil, find: nil, sinks: [])
|
|
20
|
-
lookup = Lookup.build(encoder: encoder, find: find, sinks: sinks)
|
|
19
|
+
def self.use(schema, encoder: nil, find: nil, sinks: [], on_sink_error: nil)
|
|
20
|
+
lookup = Lookup.build(encoder: encoder, find: find, sinks: sinks, on_sink_error: on_sink_error)
|
|
21
21
|
schema.define_singleton_method(:id_from_object) { |object, type, _context| lookup.id_for(object, type) }
|
|
22
22
|
schema.define_singleton_method(:object_from_id) { |id, context| lookup.object_for(id, context) }
|
|
23
23
|
end
|
|
@@ -27,8 +27,8 @@ module GraphQL
|
|
|
27
27
|
attr_reader :encoder, :find, :telemetry
|
|
28
28
|
|
|
29
29
|
# Wires the default encoder unless one is given; `use` goes through here.
|
|
30
|
-
def self.build(encoder: nil, find: nil, sinks: [])
|
|
31
|
-
new(encoder: encoder || Encoder.default, find: find, telemetry: Telemetry.build(sinks: sinks))
|
|
30
|
+
def self.build(encoder: nil, find: nil, sinks: [], on_sink_error: nil)
|
|
31
|
+
new(encoder: encoder || Encoder.default, find: find, telemetry: Telemetry.build(sinks: sinks, on_sink_error: on_sink_error))
|
|
32
32
|
end
|
|
33
33
|
|
|
34
34
|
# `new` is inert: with no encoder wired it hands out no ID and honours none. It checks what it is given.
|
|
@@ -52,25 +52,25 @@ module GraphQL
|
|
|
52
52
|
|
|
53
53
|
def object_for(id, context)
|
|
54
54
|
type_name, key = encoder.decode(id).split(SEPARATOR, 2)
|
|
55
|
-
return refuse(:malformed) if key.nil? || key.empty?
|
|
55
|
+
return refuse(:malformed, context) if key.nil? || key.empty?
|
|
56
56
|
|
|
57
57
|
type = visible_type(type_name, context)
|
|
58
|
-
return refuse(:unknown_type) unless node_type?(type)
|
|
58
|
+
return refuse(:unknown_type, context) unless node_type?(type)
|
|
59
59
|
|
|
60
60
|
object = load(type, key, context)
|
|
61
|
-
return refuse(:not_found, type: type.graphql_name) if object.nil?
|
|
61
|
+
return refuse(:not_found, context, type: type.graphql_name) if object.nil?
|
|
62
62
|
|
|
63
|
-
telemetry.record(:id_resolved, type: type.graphql_name)
|
|
63
|
+
telemetry.record(:id_resolved, context: context, type: type.graphql_name)
|
|
64
64
|
object
|
|
65
65
|
rescue Encoder::InvalidError
|
|
66
|
-
refuse(:invalid)
|
|
66
|
+
refuse(:invalid, context)
|
|
67
67
|
end
|
|
68
68
|
|
|
69
69
|
private
|
|
70
70
|
|
|
71
71
|
# Every refusal answers nil, like a missing record; the signal says why, never which ID.
|
|
72
|
-
def refuse(reason, **data)
|
|
73
|
-
telemetry.record(:id_refused, reason: reason, **data)
|
|
72
|
+
def refuse(reason, context, **data)
|
|
73
|
+
telemetry.record(:id_refused, context: context, reason: reason, **data)
|
|
74
74
|
nil
|
|
75
75
|
end
|
|
76
76
|
|
|
@@ -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
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
module RateLimits
|
|
6
|
+
# graphql-ruby discards an ExecutionError raised during analysis, drops what every analyzer answered, and runs the query.
|
|
7
|
+
# A client can choose that by field order when a `complexity:` lambda raises. So on such a raise each limiter still
|
|
8
|
+
# decides: a refusal already given stands, a limiter not asked yet is asked on its own, and a limiter that cannot answer
|
|
9
|
+
# refuses the query in hard mode and records `charged: false` in soft mode. Only the analysis of an execution counts: an
|
|
10
|
+
# analysis the app runs itself takes no slot and charges nothing here. It does not cover a trace that takes no modules
|
|
11
|
+
# from the schema (`context[:trace]`, or a class given to `trace_mode`).
|
|
12
|
+
module AnalysisGuard
|
|
13
|
+
ANSWERS = :limiter_answers
|
|
14
|
+
ASKED = :limiter_asked
|
|
15
|
+
ARMED = :limiter_guard_armed
|
|
16
|
+
NOT_CHARGED = "This query could not be charged to its rate limit."
|
|
17
|
+
|
|
18
|
+
# Runs a limiter, keeping per query and per limiter that it was asked and what it answered. A limiter that raised partway
|
|
19
|
+
# may have charged some of its keys, so it is never asked again.
|
|
20
|
+
def self.answer(query, limiter)
|
|
21
|
+
state = query.context.namespace(Points::NAMESPACE)
|
|
22
|
+
(state[ASKED] ||= {})[limiter] = true
|
|
23
|
+
(state[ANSWERS] ||= {})[limiter] = yield
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def self.decide(query, error)
|
|
27
|
+
analyzers = query.analyzers.select { |analyzer| analyzer.respond_to?(:armory_limiter) }
|
|
28
|
+
state = query.context.namespace(Points::NAMESPACE)
|
|
29
|
+
answers = (state[ANSWERS] ||= {})
|
|
30
|
+
asked = (state[ASKED] ||= {})
|
|
31
|
+
analyzers.reject { |analyzer| asked.key?(analyzer.armory_limiter) }.each { |analyzer| GraphQL::Analysis.analyze_query(query, [analyzer]) }
|
|
32
|
+
|
|
33
|
+
silent = analyzers.map(&:armory_limiter).reject { |limiter| answers.key?(limiter) || exempt?(limiter, query) }
|
|
34
|
+
silent.each { |limiter| query.context[limiter.class::CONTEXT_KEY] = { limit: nil, soft: limiter.soft?, limited: !limiter.soft?, charged: false } }
|
|
35
|
+
|
|
36
|
+
refusals = answers.values.compact
|
|
37
|
+
return refusals unless refusals.empty?
|
|
38
|
+
return [] if silent.all?(&:soft?)
|
|
39
|
+
|
|
40
|
+
[error.is_a?(GraphQL::AnalysisError) ? error : GraphQL::AnalysisError.new(NOT_CHARGED, extensions: { "code" => "RATE_LIMIT_NOT_CHARGED" })]
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# A limit that cannot be asked for does not exempt anyone.
|
|
44
|
+
def self.exempt?(limiter, query)
|
|
45
|
+
limiter.exempt?(query)
|
|
46
|
+
rescue GraphQL::ExecutionError, GraphQL::UnauthorizedError
|
|
47
|
+
false
|
|
48
|
+
end
|
|
49
|
+
private_class_method :exempt?
|
|
50
|
+
|
|
51
|
+
def analyze_multiplex(multiplex:)
|
|
52
|
+
multiplex.queries.each { |query| query.context.namespace(Points::NAMESPACE)[ARMED] = true }
|
|
53
|
+
super
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# The first analysis of each query in an execution. Any other, nested in it or run by the app, passes through, and
|
|
57
|
+
# each analyzer is asked apart, so one that raises leaves the others asked.
|
|
58
|
+
def analyze_query(query:)
|
|
59
|
+
return super unless query.context.namespace(Points::NAMESPACE).delete(ARMED)
|
|
60
|
+
|
|
61
|
+
begin
|
|
62
|
+
super
|
|
63
|
+
rescue GraphQL::ExecutionError, GraphQL::UnauthorizedError => error
|
|
64
|
+
decided(query, error)
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
private
|
|
69
|
+
|
|
70
|
+
def decided(query, error)
|
|
71
|
+
refusals = AnalysisGuard.decide(query, error)
|
|
72
|
+
raise error if refusals.empty?
|
|
73
|
+
|
|
74
|
+
refusals
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|