graphql-armory 0.1.0.pre13 → 0.1.0.pre15

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 (138) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +25 -0
  3. data/README.md +5 -5
  4. data/docs/authorization.md +4 -0
  5. data/docs/encrypted-ids.md +24 -2
  6. data/docs/persisted-queries.md +4 -0
  7. data/docs/rate-limiting.md +23 -0
  8. data/docs/response-caching.md +590 -0
  9. data/docs/subscriptions.md +261 -0
  10. data/docs/telemetry.md +39 -1
  11. data/docs/versioning.md +5 -0
  12. data/lib/graphql/armory/authorization/authorize.rb +3 -0
  13. data/lib/graphql/armory/authorization/scope.rb +2 -0
  14. data/lib/graphql/armory/caching/audit/command.rb +51 -0
  15. data/lib/graphql/armory/caching/audit/context_class.rb +117 -0
  16. data/lib/graphql/armory/caching/audit/declarations.rb +166 -0
  17. data/lib/graphql/armory/caching/audit/own_checks.rb +150 -0
  18. data/lib/graphql/armory/caching/audit/public_rules.rb +158 -0
  19. data/lib/graphql/armory/caching/audit/report.rb +113 -0
  20. data/lib/graphql/armory/caching/audit.rb +136 -0
  21. data/lib/graphql/armory/caching/base.rb +118 -0
  22. data/lib/graphql/armory/caching/canonical.rb +138 -0
  23. data/lib/graphql/armory/caching/charge.rb +86 -0
  24. data/lib/graphql/armory/caching/codec.rb +108 -0
  25. data/lib/graphql/armory/caching/context_methods.rb +88 -0
  26. data/lib/graphql/armory/caching/controls/app_schema.rb +70 -0
  27. data/lib/graphql/armory/caching/controls/context.rb +30 -0
  28. data/lib/graphql/armory/caching/controls/operations.rb +37 -0
  29. data/lib/graphql/armory/caching/controls/schema.rb +123 -0
  30. data/lib/graphql/armory/caching/controls/store.rb +16 -0
  31. data/lib/graphql/armory/caching/controls/walk_schema.rb +197 -0
  32. data/lib/graphql/armory/caching/controls.rb +19 -0
  33. data/lib/graphql/armory/caching/digester.rb +48 -0
  34. data/lib/graphql/armory/caching/errors.rb +16 -0
  35. data/lib/graphql/armory/caching/gate/admission.rb +67 -0
  36. data/lib/graphql/armory/caching/gate/signals.rb +65 -0
  37. data/lib/graphql/armory/caching/gate/store_check.rb +60 -0
  38. data/lib/graphql/armory/caching/gate/substitute.rb +61 -0
  39. data/lib/graphql/armory/caching/gate.rb +384 -0
  40. data/lib/graphql/armory/caching/integration/guard.rb +55 -0
  41. data/lib/graphql/armory/caching/integration/install.rb +262 -0
  42. data/lib/graphql/armory/caching/integration/query.rb +42 -0
  43. data/lib/graphql/armory/caching/integration.rb +141 -0
  44. data/lib/graphql/armory/caching/keyer.rb +208 -0
  45. data/lib/graphql/armory/caching/memory_store.rb +164 -0
  46. data/lib/graphql/armory/caching/nulls.rb +121 -0
  47. data/lib/graphql/armory/caching/purge.rb +98 -0
  48. data/lib/graphql/armory/caching/record_keys.rb +109 -0
  49. data/lib/graphql/armory/caching/recorder/context.rb +178 -0
  50. data/lib/graphql/armory/caching/recorder/log.rb +142 -0
  51. data/lib/graphql/armory/caching/recorder/null.rb +24 -0
  52. data/lib/graphql/armory/caching/recorder/shared_writes.rb +58 -0
  53. data/lib/graphql/armory/caching/recorder/substitute.rb +119 -0
  54. data/lib/graphql/armory/caching/recorder.rb +34 -0
  55. data/lib/graphql/armory/caching/redis_store/scripts.rb +159 -0
  56. data/lib/graphql/armory/caching/redis_store.rb +162 -0
  57. data/lib/graphql/armory/caching/rspec.rb +25 -0
  58. data/lib/graphql/armory/caching/schema_identity.rb +102 -0
  59. data/lib/graphql/armory/caching/store/null.rb +31 -0
  60. data/lib/graphql/armory/caching/store/substitute.rb +144 -0
  61. data/lib/graphql/armory/caching/store.rb +34 -0
  62. data/lib/graphql/armory/caching/tags.rb +39 -0
  63. data/lib/graphql/armory/caching/values/decision.rb +45 -0
  64. data/lib/graphql/armory/caching/values/declaration.rb +114 -0
  65. data/lib/graphql/armory/caching/values/entry.rb +108 -0
  66. data/lib/graphql/armory/caching/values/key.rb +39 -0
  67. data/lib/graphql/armory/caching/values/lookup.rb +35 -0
  68. data/lib/graphql/armory/caching/values/policy.rb +44 -0
  69. data/lib/graphql/armory/caching/viewer.rb +112 -0
  70. data/lib/graphql/armory/caching/walk/directives.rb +45 -0
  71. data/lib/graphql/armory/caching/walk/relay.rb +54 -0
  72. data/lib/graphql/armory/caching/walk/run.rb +130 -0
  73. data/lib/graphql/armory/caching/walk/tally.rb +38 -0
  74. data/lib/graphql/armory/caching/walk.rb +46 -0
  75. data/lib/graphql/armory/caching.rb +69 -0
  76. data/lib/graphql/armory/encoder/legacy.rb +14 -0
  77. data/lib/graphql/armory/encoder/null.rb +14 -1
  78. data/lib/graphql/armory/encoder/substitute.rb +54 -2
  79. data/lib/graphql/armory/encoder/versioned.rb +36 -0
  80. data/lib/graphql/armory/encoder.rb +80 -1
  81. data/lib/graphql/armory/persisted_queries.rb +8 -1
  82. data/lib/graphql/armory/rate_limits/cached_charge.rb +43 -0
  83. data/lib/graphql/armory/rate_limits/concurrency.rb +12 -5
  84. data/lib/graphql/armory/rate_limits/invalid_queries.rb +3 -2
  85. data/lib/graphql/armory/rate_limits/points.rb +21 -9
  86. data/lib/graphql/armory/rate_limits/time.rb +15 -8
  87. data/lib/graphql/armory/rate_limits.rb +9 -0
  88. data/lib/graphql/armory/subscriptions/ably/key.rb +49 -0
  89. data/lib/graphql/armory/subscriptions/ably/publisher.rb +132 -0
  90. data/lib/graphql/armory/subscriptions/ably/token_request.rb +42 -0
  91. data/lib/graphql/armory/subscriptions/ably/webhook.rb +96 -0
  92. data/lib/graphql/armory/subscriptions/ably.rb +126 -0
  93. data/lib/graphql/armory/subscriptions/audit.rb +92 -0
  94. data/lib/graphql/armory/subscriptions/controls/dependencies.rb +37 -0
  95. data/lib/graphql/armory/subscriptions/controls/event_log.rb +30 -0
  96. data/lib/graphql/armory/subscriptions/controls/id.rb +26 -0
  97. data/lib/graphql/armory/subscriptions/controls/record.rb +34 -0
  98. data/lib/graphql/armory/subscriptions/controls/schema.rb +187 -0
  99. data/lib/graphql/armory/subscriptions/controls/viewer.rb +99 -0
  100. data/lib/graphql/armory/subscriptions/controls.rb +19 -0
  101. data/lib/graphql/armory/subscriptions/core/channels.rb +93 -0
  102. data/lib/graphql/armory/subscriptions/core/clock.rb +40 -0
  103. data/lib/graphql/armory/subscriptions/core/controls.rb +29 -0
  104. data/lib/graphql/armory/subscriptions/core/delivery.rb +250 -0
  105. data/lib/graphql/armory/subscriptions/core/settings.rb +182 -0
  106. data/lib/graphql/armory/subscriptions/core/trigger.rb +63 -0
  107. data/lib/graphql/armory/subscriptions/core/viewer.rb +153 -0
  108. data/lib/graphql/armory/subscriptions/core/write.rb +172 -0
  109. data/lib/graphql/armory/subscriptions/core.rb +200 -0
  110. data/lib/graphql/armory/subscriptions/errors.rb +30 -0
  111. data/lib/graphql/armory/subscriptions/http/null.rb +17 -0
  112. data/lib/graphql/armory/subscriptions/http/substitute.rb +56 -0
  113. data/lib/graphql/armory/subscriptions/http.rb +93 -0
  114. data/lib/graphql/armory/subscriptions/memory_store.rb +115 -0
  115. data/lib/graphql/armory/subscriptions/pusher/signature.rb +45 -0
  116. data/lib/graphql/armory/subscriptions/pusher.rb +192 -0
  117. data/lib/graphql/armory/subscriptions/redis_store/scripts.rb +115 -0
  118. data/lib/graphql/armory/subscriptions/redis_store.rb +157 -0
  119. data/lib/graphql/armory/subscriptions/store/null.rb +23 -0
  120. data/lib/graphql/armory/subscriptions/store/substitute.rb +155 -0
  121. data/lib/graphql/armory/subscriptions/store.rb +38 -0
  122. data/lib/graphql/armory/subscriptions/topic.rb +253 -0
  123. data/lib/graphql/armory/subscriptions/transport/null.rb +28 -0
  124. data/lib/graphql/armory/subscriptions/transport/substitute.rb +150 -0
  125. data/lib/graphql/armory/subscriptions/transport.rb +41 -0
  126. data/lib/graphql/armory/subscriptions/values/capabilities.rb +50 -0
  127. data/lib/graphql/armory/subscriptions/values/message.rb +31 -0
  128. data/lib/graphql/armory/subscriptions/values/outcome.rb +42 -0
  129. data/lib/graphql/armory/subscriptions/values/record.rb +176 -0
  130. data/lib/graphql/armory/subscriptions/webhook_app.rb +31 -0
  131. data/lib/graphql/armory/subscriptions.rb +33 -0
  132. data/lib/graphql/armory/telemetry.rb +8 -4
  133. data/lib/graphql/armory/version.rb +1 -1
  134. data/lib/graphql/armory/versioning/audit.rb +1 -9
  135. data/lib/graphql/armory/versioning/integration.rb +60 -2
  136. data/lib/graphql/armory.rb +2 -0
  137. data/lib/tasks/graphql_armory.rake +9 -0
  138. metadata +110 -1
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "graphql/armory/authorization/audit"
4
+ require "graphql/armory/caching/audit/report"
5
+ require "graphql/armory/caching/audit/declarations"
6
+ require "graphql/armory/caching/audit/public_rules"
7
+ require "graphql/armory/caching/audit/own_checks"
8
+ require "graphql/armory/caching/audit/context_class"
9
+ require "graphql/armory/caching/audit/command"
10
+
11
+ module GraphQL
12
+ module Armory
13
+ module Caching
14
+ # Walks a schema's declarations, without running a query, and reports every place a cached answer could reach a
15
+ # viewer it was not computed for, or could never be used. Every declaration someone made is listed apart, with its
16
+ # reason, so a reviewer can read them.
17
+ #
18
+ # report = GraphQL::Armory::Caching::Audit.(AppSchema)
19
+ # report.ok? # false when a :public declaration stands over a rule, a check it cannot read, ...
20
+ # puts report
21
+ # GraphQL::Armory::Caching::Audit.(AppSchema, own_checks: { Types::Product => { authorized?: "reads the class only" } })
22
+ # GraphQL::Armory::Caching::Audit.(AppSchema, strict: true) # information (:directive) fails it too
23
+ #
24
+ # It walks every type the roots, the orphan types and `schema.types` reach, hidden or not, so every version of a
25
+ # Versioning schema is read at once. It never runs at boot or during a request. Its `ok?` covers only what
26
+ # Authorization's chokepoints decide: an answer that depends on something they do not see (`Current.user`, a
27
+ # thread-local tenant) passes it (docs/response-caching.md "Guarantees and limits").
28
+ class Audit
29
+ OWN_CHECKS = %i[visible? authorized? scope_items authorized_new wrap].freeze
30
+
31
+ attr_reader :configuration, :own_checks
32
+
33
+ # `new` is inert: with no configuration, caching counts as not installed, so a schema that declares anything is
34
+ # reported as `:plugin`. `configuration` is what `use GraphQL::Armory::Caching` installed (the schema's
35
+ # `armory_caching`); see `Settings` for the attributes read.
36
+ def initialize(configuration: nil, own_checks: {}, strict: false)
37
+ check_own_checks(own_checks)
38
+ @configuration = configuration
39
+ @own_checks = own_checks.to_h { |holder, methods| [holder, methods.to_h { |name, reason| [name, reason.dup.freeze] }.freeze] }.freeze
40
+ @strict = strict == true
41
+ freeze
42
+ end
43
+
44
+ def self.build(schema, own_checks: {}, strict: false)
45
+ configuration = schema.respond_to?(:armory_caching) ? schema.armory_caching : nil
46
+ new(configuration: configuration, own_checks: own_checks, strict: strict)
47
+ end
48
+
49
+ def self.call(schema, own_checks: {}, strict: false)
50
+ build(schema, own_checks: own_checks, strict: strict).(schema)
51
+ end
52
+
53
+ def call(schema)
54
+ findings = Findings.new
55
+ settings = Settings.new(@configuration)
56
+ plugin(schema, settings, findings)
57
+ definitions = Audit.definitions(schema)
58
+ declarations = Declarations.new(schema, definitions, settings, findings)
59
+ declarations.()
60
+ pairs = declarations.public_pairs
61
+ PublicRules.new(definitions, findings).(pairs)
62
+ OwnChecks.new(definitions, findings).(pairs, own_checks_of(settings))
63
+ ContextClass.(schema, settings, findings) if settings.installed?
64
+ findings.report(strict: @strict)
65
+ end
66
+
67
+ # Every definition the schema holds, hidden or not: what the roots and the orphan types reach, what `schema.types`
68
+ # lists, and Versioning's extra types. Introspection types are left out: they hold nothing an app declares.
69
+ def self.definitions(schema)
70
+ extra = schema.respond_to?(:extra_types) ? Array(schema.extra_types) : []
71
+ Armory::Definitions.(schema, Authorization::Definitions.(schema) + extra).reject { |type| Armory::Definitions.introspection?(type) }
72
+ end
73
+
74
+ private
75
+
76
+ def plugin(schema, settings, findings)
77
+ if !settings.installed?
78
+ return unless Declarations.uses_base?(schema)
79
+
80
+ findings.problem(:plugin, "Schema", "includes GraphQL::Armory::Caching::Base but never installed the plugin: its declarations cache nothing. " \
81
+ "Add `use GraphQL::Armory::Caching, store: ..., release: ...`", at: schema)
82
+ elsif !persisted_queries?(schema)
83
+ findings.problem(:plugin, "Schema", "installs caching without PersistedQueries, so its first request raises: only persisted operations are cached. " \
84
+ "Add `use GraphQL::Armory::PersistedQueries, store: ...`", at: schema)
85
+ end
86
+ end
87
+
88
+ def persisted_queries?(schema)
89
+ schema.respond_to?(:armory_persisted_queries) && !schema.armory_persisted_queries.nil?
90
+ rescue NoMethodError
91
+ false
92
+ end
93
+
94
+ # The audit's own `own_checks:`, plus the installed configuration's when it carries any.
95
+ def own_checks_of(settings)
96
+ settings.own_checks.merge(@own_checks) { |_holder, installed, given| installed.merge(given) }
97
+ end
98
+
99
+ def check_own_checks(checks)
100
+ valid = checks.is_a?(Hash) && checks.all? do |holder, methods|
101
+ holder.is_a?(Module) && methods.is_a?(Hash) && methods.all? do |name, reason|
102
+ OWN_CHECKS.include?(name) && reason.is_a?(String) && !reason.strip.empty?
103
+ end
104
+ end
105
+ return if valid
106
+
107
+ raise ArgumentError, "own_checks must map a class to #{OWN_CHECKS.inspect} and the reason you keep each, got #{checks.inspect}"
108
+ end
109
+
110
+ # What the audit reads from the installed configuration, duck-typed: an attribute it does not answer takes the
111
+ # `use` default. With no configuration, caching is not installed.
112
+ class Settings
113
+ DEFAULTS = { viewer: nil, anonymous: :uncacheable, anonymous_reason: nil, neutral_keys: {}, context_methods: {},
114
+ max_ttl: 3600, max_viewer_ttl: 300, own_checks: {} }.freeze
115
+
116
+ DEFAULTS.each_key do |name|
117
+ define_method(name) { @values.fetch(name) }
118
+ end
119
+
120
+ def initialize(configuration)
121
+ @installed = !configuration.nil?
122
+ @values = DEFAULTS.to_h do |name, default|
123
+ value = configuration.respond_to?(name) ? configuration.public_send(name) : nil
124
+ [name, value.nil? ? default : value]
125
+ end
126
+ freeze
127
+ end
128
+
129
+ def installed?
130
+ @installed
131
+ end
132
+ end
133
+ end
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # Goes in your base classes: fields, objects, interfaces (after `include GraphQL::Schema::Interface`) and
7
+ # directives.
8
+ #
9
+ # class Types::BaseField < GraphQL::Schema::Field
10
+ # include GraphQL::Armory::Caching::Base
11
+ # end
12
+ # class Types::BaseObject < GraphQL::Schema::Object
13
+ # include GraphQL::Armory::Caching::Base
14
+ # field_class Types::BaseField
15
+ # end
16
+ #
17
+ # class Types::Product < Types::BaseObject
18
+ # cache_fields ttl: 300, scope: :public, tags: ["catalog"], reason: "the same for every viewer and tenant"
19
+ # field :price, Money, null: false, cache: { ttl: 60, tags: ["pricing"] } # narrower
20
+ # field :stock_level, Integer, null: false, cache: false # never cached
21
+ # end
22
+ #
23
+ # `cache_fields` is the default for the fields the type declares itself, never for fields it inherits: a field
24
+ # keeps the declaration of the class or interface that declared it. A field may only narrow that default.
25
+ module Base
26
+ def self.included(base)
27
+ if !base.is_a?(Class) && base.include?(GraphQL::Schema::Interface)
28
+ base.definition_methods { include Base::Type }
29
+ elsif base.is_a?(Class) && base <= GraphQL::Schema::Field
30
+ base.include(Base::Field)
31
+ elsif base.is_a?(Class) && base <= GraphQL::Schema::Object
32
+ base.extend(Base::Type)
33
+ elsif base.is_a?(Class) && base <= GraphQL::Schema::Directive
34
+ base.extend(Base::Directive)
35
+ else
36
+ raise ArgumentError, "GraphQL::Armory::Caching::Base goes in a field, object, interface or directive class, not #{base}. " \
37
+ "In an interface, include GraphQL::Schema::Interface first"
38
+ end
39
+ end
40
+
41
+ # Included in field classes: `cache: { ttl:, scope:, tags:, reason: }` or `cache: false`.
42
+ module Field
43
+ def initialize(*args, cache: nil, **kwargs, &block)
44
+ @armory_cache_own = Declaration.from_option(cache)
45
+ super(*args, **kwargs, &block)
46
+ # Widening is refused at definition when the owner already declared its default; `cache_fields` declared
47
+ # later checks the fields already defined.
48
+ armory_cache if @armory_cache_own && (armory_owner_default || @armory_cache_own.complete?)
49
+ rescue ConfigurationError => error
50
+ raise error.class, "#{armory_cache_label(args, kwargs)}: #{error.message}"
51
+ end
52
+
53
+ # What the field itself declared (partial, `Declaration::FORBIDDEN`, or nil).
54
+ attr_reader :armory_cache_own
55
+
56
+ # The declaration that applies: the field's own, completed from its declaring owner's `cache_fields`.
57
+ # nil when neither declares anything (the walk refuses the field).
58
+ def armory_cache
59
+ default = armory_owner_default
60
+ memo = @armory_cache_memo
61
+ return memo.last if memo && memo.first.equal?(default)
62
+
63
+ declaration = Declaration.narrow(default, @armory_cache_own)
64
+ @armory_cache_memo = [default, declaration] unless frozen?
65
+ declaration
66
+ end
67
+
68
+ private
69
+
70
+ def armory_owner_default
71
+ owner = self.owner
72
+ owner.respond_to?(:armory_cache_fields) ? owner.armory_cache_fields : nil
73
+ end
74
+
75
+ def armory_cache_label(args, kwargs)
76
+ owner_name = kwargs[:owner].respond_to?(:graphql_name) ? kwargs[:owner].graphql_name : nil
77
+ [owner_name, kwargs[:name] || args.first].compact.join(".")
78
+ end
79
+ end
80
+
81
+ # Extended into object types and included into interfaces' definition methods.
82
+ module Type
83
+ def cache_fields(ttl:, scope: :viewer, tags: [], reason: nil)
84
+ @armory_cache_fields = Declaration.build(ttl: ttl, scope: scope, tags: tags, reason: reason)
85
+ own_fields.each_value { |defined| Array(defined).each { |field| field.armory_cache if field.respond_to?(:armory_cache) } }
86
+ @armory_cache_fields
87
+ rescue ConfigurationError => error
88
+ raise error.class, "#{graphql_name}: #{error.message}"
89
+ end
90
+
91
+ # This type's own default, never a superclass's: fields keep their declaring owner's default.
92
+ def armory_cache_fields
93
+ instance_variable_defined?(:@armory_cache_fields) ? @armory_cache_fields : nil
94
+ end
95
+ end
96
+
97
+ # Extended into directive classes. A directive that does not change the data (a client hint, a trace label)
98
+ # declares `cache_safe`; any other directive anywhere in an operation makes it uncacheable.
99
+ module Directive
100
+ def cache_safe(reason:)
101
+ raise ConfigurationError, "#{graphql_name}: cache_safe reason: must be a non-empty String" unless reason.is_a?(String) && !reason.strip.empty?
102
+
103
+ @armory_cache_safe = reason.dup.freeze
104
+ end
105
+
106
+ # Own only: a subclass declares it again.
107
+ def armory_cache_safe?
108
+ instance_variable_defined?(:@armory_cache_safe)
109
+ end
110
+
111
+ def armory_cache_safe_reason
112
+ instance_variable_defined?(:@armory_cache_safe) ? @armory_cache_safe : nil
113
+ end
114
+ end
115
+ end
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # The one encoding of a key's components, so two requests share a key only when every component is the same value
7
+ # of the same type. Written by hand, not with a JSON library's generator, so a library upgrade or a global option
8
+ # never changes a key.
9
+ #
10
+ # Canonical.json(["armory-cache/2", 1, 1.0, nil]) # => "[\"armory-cache/2\",1,1.0,null]"
11
+ # Canonical.typed(:en) # => ["sym", "en"]
12
+ # Canonical.typed("en") # => ["str", "en"]
13
+ #
14
+ # Every method raises `Canonical::Unsupported` for a value it cannot encode without ambiguity; the keyer turns it
15
+ # into a refusal (`:variables`, `:vary_value`). The message names the type, never the value.
16
+ module Canonical
17
+ class Unsupported < Error; end
18
+
19
+ # Deeper than any JSON a parser accepts by default (Ruby's `max_nesting` is 100); also stops a cyclic Array.
20
+ MAX_DEPTH = 100
21
+
22
+ ESCAPES = { '"' => '\\"', "\\" => "\\\\" }.freeze
23
+ ESCAPED = /["\\\x00-\x1f]/
24
+
25
+ module_function
26
+
27
+ # JSON for String, Integer, finite Float, true, false, nil, Array and Hash with String keys. A Hash keeps its
28
+ # key order: two orders are two keys, never one answer for two inputs. `1` and `1.0` stay apart.
29
+ def json(value)
30
+ out = +""
31
+ write(value, out, 0)
32
+ out
33
+ end
34
+
35
+ # A `vary:` value with its type, recursively: a Symbol and a String, or `1` and `"1"`, never collide.
36
+ def typed(value, depth = 0)
37
+ raise Unsupported, "a value nested deeper than #{MAX_DEPTH}" if depth > MAX_DEPTH
38
+
39
+ case value
40
+ when String then ["str", utf8(value)]
41
+ when Symbol then ["sym", utf8(value.name)]
42
+ when Integer then ["int", value]
43
+ when Float then ["float", finite(value)]
44
+ when true, false then ["bool", value]
45
+ when nil then ["nil"]
46
+ when Array then ["arr", value.map { |item| typed(item, depth + 1) }]
47
+ when Hash then ["hash", value.map { |key, item| [typed(key, depth + 1), typed(item, depth + 1)] }]
48
+ else raise Unsupported, "a #{value.class}"
49
+ end
50
+ end
51
+
52
+ # `[name, provided?, value]` for each variable the operation declares, sorted by name. `provided?` keeps a variable
53
+ # not sent apart from one sent as null; variables the operation does not declare are ignored, as graphql-ruby
54
+ # ignores them. The values are the client's, before coercion (a scalar's `coerce_input` may read the context).
55
+ # Top-level names may be Strings or Symbols, as graphql-ruby stringifies them; one name given both ways raises.
56
+ def variables(operation, provided)
57
+ provided = {} if provided.nil?
58
+ raise Unsupported, "variables given as a #{provided.class}, not a Hash" unless provided.is_a?(Hash)
59
+
60
+ given = {}
61
+ provided.each do |name, value|
62
+ raise Unsupported, "a variable named by a #{name.class}" unless name.is_a?(String) || name.is_a?(Symbol)
63
+ raise Unsupported, "a variable given twice, as a String and a Symbol" if given.key?(name.to_s)
64
+
65
+ given[name.to_s] = value
66
+ end
67
+
68
+ operation.variables.map(&:name).sort.map do |name|
69
+ sent = given.key?(name)
70
+ value = sent ? given[name] : nil
71
+ json(value)
72
+ [name, sent, value]
73
+ end
74
+ end
75
+
76
+ def write(value, out, depth)
77
+ raise Unsupported, "a value nested deeper than #{MAX_DEPTH}" if depth > MAX_DEPTH
78
+
79
+ case value
80
+ when String then string(value, out)
81
+ when Integer then out << value.to_s
82
+ when Float then out << finite(value).to_s
83
+ when true then out << "true"
84
+ when false then out << "false"
85
+ when nil then out << "null"
86
+ when Array then array(value, out, depth)
87
+ when Hash then object(value, out, depth)
88
+ else raise Unsupported, "a #{value.class}"
89
+ end
90
+ end
91
+
92
+ def array(value, out, depth)
93
+ out << "["
94
+ value.each_with_index do |item, index|
95
+ out << "," if index.positive?
96
+ write(item, out, depth + 1)
97
+ end
98
+ out << "]"
99
+ end
100
+
101
+ def object(value, out, depth)
102
+ out << "{"
103
+ value.each_with_index do |(key, item), index|
104
+ raise Unsupported, "a Hash key that is a #{key.class}, not a String" unless key.is_a?(String)
105
+
106
+ out << "," if index.positive?
107
+ string(key, out)
108
+ out << ":"
109
+ write(item, out, depth + 1)
110
+ end
111
+ out << "}"
112
+ end
113
+
114
+ def string(value, out)
115
+ out << '"' << utf8(value).gsub(ESCAPED) { |char| ESCAPES[char] || format("\\u%04x", char.ord) } << '"'
116
+ end
117
+
118
+ # The same characters in another encoding are the same String; bytes that are not text are refused.
119
+ def utf8(value)
120
+ text = value.encoding == Encoding::UTF_8 ? value : value.encode(Encoding::UTF_8)
121
+ raise Unsupported, "a String that is not valid UTF-8" unless text.valid_encoding?
122
+
123
+ text
124
+ rescue EncodingError
125
+ raise Unsupported, "a String that is not valid UTF-8"
126
+ end
127
+
128
+ def finite(value)
129
+ raise Unsupported, "a Float that is not finite" unless value.finite?
130
+
131
+ value
132
+ end
133
+
134
+ private_class_method :write, :array, :object, :string, :utf8, :finite
135
+ end
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # Charges a hit the Points its run cost. A hit runs no analyzer, so the gate calls this instead: it
7
+ # calls `Points#charge_cached` on every Points limiter of the query's schema, found through `query_analyzers` and
8
+ # the `armory_limiter` reader Points defines on its analyzer. Time does not bound hits, and Concurrency takes no
9
+ # slot for one.
10
+ #
11
+ # charge = Charge.build(schema)
12
+ # charge.limited?(query) # is any Points limiter installed? (a run must record its cost to be stored)
13
+ # Charge.recorded_cost(query) # after a run: the Integer cost it was charged, or nil
14
+ # refusal = charge.(query, cost) # on a hit: nil (charged, serve it) or a GraphQL::Query::Result to answer
15
+ # Charge.result(query, "data" => data) # the hit's Result, with the extensions the charge added
16
+ #
17
+ # `Charge.new` is inert: it finds no limiter and charges nothing, like `Charge::Null`.
18
+ class Charge
19
+ # graphql-ruby keeps a query's response extensions in this context namespace (`Context#response_extensions`) and
20
+ # copies it into the result when it exists.
21
+ EXTENSIONS = :__query_result_extensions__
22
+
23
+ def self.build(schema)
24
+ unless schema.is_a?(Class) && schema <= GraphQL::Schema
25
+ raise ConfigurationError, "Charge.build needs a GraphQL::Schema class, got #{schema.inspect}"
26
+ end
27
+
28
+ new(schema: schema)
29
+ end
30
+
31
+ # The Points cost the query's own run was charged, from its own record (`namespace(:graphql_armory)[:points]`),
32
+ # never from `context[:rate_limit_points]`: queries of a multiplex may share one context Hash, where the last
33
+ # query's record wins. Nil when the run recorded no cost (no Points limiter, a store that failed, a limiter that
34
+ # could not charge) or was charged as an invalid query.
35
+ def self.recorded_cost(query)
36
+ info = query.context.namespace(RateLimits::Points::NAMESPACE)[:points]
37
+ return nil if info.nil? || info[:invalid]
38
+
39
+ cost = info[:cost]
40
+ cost if cost.is_a?(Integer) && !cost.negative?
41
+ end
42
+
43
+ # The Result graphql-ruby would build for `query` with these `values` ("data", or "errors"): the response
44
+ # extensions are added under "extensions" when the query has any, as both engines do. A charge with
45
+ # `extensions: true` puts `rateLimit` there.
46
+ def self.result(query, values)
47
+ values = values.dup
48
+ values["extensions"] = query.context.namespace(EXTENSIONS) if query.context.namespace?(EXTENSIONS)
49
+ GraphQL::Query::Result.new(query: query, values: values)
50
+ end
51
+
52
+ def initialize(schema: nil)
53
+ @schema = schema
54
+ end
55
+
56
+ # Charges `cost` to every Points limiter, in the order the schema has them, as a run's analysis does: each
57
+ # limiter is charged even when an earlier one refused. Answers nil when every limiter let the hit through, or the
58
+ # Result a run refused by its limiters answers: `{ "errors" => [each refusal's to_h], "extensions" => ... }`.
59
+ # Raises ArgumentError when a limiter is installed and `cost` is not a non-negative Integer.
60
+ def call(query, cost)
61
+ refusals = limiters(query).filter_map { |points| points.charge_cached(query, cost: cost) }
62
+ return nil if refusals.empty?
63
+
64
+ self.class.result(query, "errors" => refusals.map(&:to_h))
65
+ end
66
+
67
+ # Whether a Points limiter is installed on the query's schema (or, without a query, on the schema built with).
68
+ def limited?(query = nil)
69
+ !limiters(query).empty?
70
+ end
71
+
72
+ # Looked up on every call, not at build: the response cache is built at `use`, and Points may be `use`d after it.
73
+ # A query of a subclass is charged by the subclass's limiters, as its run would be.
74
+ def limiters(query = nil)
75
+ return [] if @schema.nil?
76
+
77
+ schema = query && query.schema.is_a?(Class) && query.schema <= @schema ? query.schema : @schema
78
+ schema.query_analyzers.filter_map do |analyzer|
79
+ limiter = analyzer.armory_limiter if analyzer.respond_to?(:armory_limiter)
80
+ limiter if limiter.is_a?(RateLimits::Points)
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module GraphQL
6
+ module Armory
7
+ module Caching
8
+ # Turns an Entry into the String a store keeps, and back. JSON only: a store's contents are never handed to a
9
+ # deserializer that can build objects.
10
+ #
11
+ # Codec.new # plain JSON: for a process-local store nobody else can write
12
+ # Codec.build(encoder: AppEncoder) # sealed with `encoder.seal` (AES-256-GCM, purpose "cache")
13
+ # codec.encode(entry, key_digest) # => String
14
+ # codec.decode(blob, key_digest) # => Entry, or raises Entry::Rejected (:format, :key or :decrypt)
15
+ #
16
+ # A sealed entry is bound to the entry format and to the key digest it was written under (the additional
17
+ # data), and to the encoder's key and tag (`Encoder.seal` binds them): an entry moved under another key, forged
18
+ # in clear, edited, or written by another app does not open (`:decrypt`). Whatever opens must still name the
19
+ # same key inside (`:key`) and parse as an entry of this format (`:format`).
20
+ class Codec
21
+ PURPOSE = "cache"
22
+ AAD_LABEL = "graphql-armory/cache-entry"
23
+
24
+ # Encrypts nothing: the plain JSON codec's sealer.
25
+ module Plain
26
+ def self.seal(bytes, aad:, purpose:) = bytes
27
+ def self.open(text, aad:, purpose:) = text
28
+ end
29
+
30
+ # The additional data an entry under `key_digest` is sealed with: the entry format and the key digest.
31
+ def self.additional_data(key_digest)
32
+ check_key(key_digest)
33
+
34
+ "#{AAD_LABEL}/#{Entry::FORMAT}\0#{key_digest}"
35
+ end
36
+
37
+ # Seals with `encoder` (an Encoder subclass, `Encoder.versioned(...)`, or anything with `seal` and `open`).
38
+ # Tries one seal and open at boot, so an encoder without a key, `Encoder::Null` or `Encoder::Legacy` fails
39
+ # here instead of on the first request.
40
+ def self.build(encoder:)
41
+ unless %i[seal open].all? { |name| encoder.respond_to?(name) }
42
+ raise ConfigurationError, "encoder: must answer seal and open (an Encoder subclass), got #{encoder.inspect}"
43
+ end
44
+
45
+ probe(encoder)
46
+ new(sealer: encoder)
47
+ end
48
+
49
+ def self.probe(encoder)
50
+ aad = additional_data("0" * 64)
51
+ sealed = encoder.seal("{}", aad: aad, purpose: PURPOSE)
52
+ raise ConfigurationError, "encoder: #{encoder.inspect} did not open what it sealed" unless encoder.open(sealed, aad: aad, purpose: PURPOSE) == "{}".b
53
+ rescue Encoder::ConfigurationError, Encoder::InvalidError => error
54
+ raise ConfigurationError, "encoder: #{encoder.inspect} cannot seal cache entries (#{error.message})"
55
+ end
56
+ private_class_method :probe
57
+
58
+ def self.check_key(key_digest)
59
+ raise ArgumentError, "key digest: must be 64 hex characters" unless key_digest.is_a?(String) && Key::HEX.match?(key_digest)
60
+ end
61
+ private_class_method :check_key
62
+
63
+ def initialize(sealer: Plain)
64
+ @sealer = sealer
65
+ end
66
+
67
+ def encode(entry, key_digest)
68
+ raise ArgumentError, "a Codec encodes an Entry, got #{entry.class}" unless entry.is_a?(Entry)
69
+ raise ArgumentError, "the entry's key is not the key digest it is written under" unless entry.key == key_digest
70
+
71
+ @sealer.seal(entry.to_json_string, aad: self.class.additional_data(key_digest), purpose: PURPOSE)
72
+ end
73
+
74
+ def decode(blob, key_digest)
75
+ aad = self.class.additional_data(key_digest)
76
+ raise Entry::Rejected, :format unless blob.is_a?(String)
77
+
78
+ entry = Entry.parse(utf8(open(blob, aad)))
79
+ raise Entry::Rejected, :key unless OpenSSL.fixed_length_secure_compare(entry.key, key_digest)
80
+
81
+ entry
82
+ end
83
+
84
+ def sealed? = !@sealer.equal?(Plain)
85
+
86
+ def inspect = "#<#{self.class.name} sealed=#{sealed?}>"
87
+
88
+ private
89
+
90
+ def open(blob, aad)
91
+ @sealer.open(blob, aad: aad, purpose: PURPOSE)
92
+ rescue Encoder::ConfigurationError, ConfigurationError, ArgumentError
93
+ raise
94
+ rescue StandardError
95
+ # Tampered, moved, forged, foreign, or the encoder failed: a miss, never an error the request sees.
96
+ raise Entry::Rejected, :decrypt
97
+ end
98
+
99
+ def utf8(bytes)
100
+ text = bytes.dup.force_encoding(Encoding::UTF_8)
101
+ raise Entry::Rejected, :format unless text.valid_encoding?
102
+
103
+ text
104
+ end
105
+ end
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # The public methods an app adds to its query contexts. The recorder sees reads through the context's own methods
7
+ # only; an added method such as `def current_user = @provided_values[:current_user]` reads the provided Hash
8
+ # without being recorded (docs/response-caching.md "Inputs you must declare"). So a query whose context class
9
+ # answers such a method the app did not declare in `context_methods:` with a reason runs uncached.
10
+ #
11
+ # ContextMethods.added(AppContext) # => [:current_user, :tenant]
12
+ # ContextMethods.undeclared(AppContext, { tenant: "reads Current" }) # => [:current_user]
13
+ #
14
+ # Counted: every public method the class answers, from the class itself, its ancestors up to
15
+ # `GraphQL::Query::Context`, that class itself and every module prepended to or included in it, plus
16
+ # `method_missing` whatever its visibility, since it answers any name. Not counted: a method whose code is
17
+ # graphql-ruby's or this gem's (by its source file), and a name graphql-ruby's context answers when this gem
18
+ # loads: the wrapper records those it reads through when they call `super`, and the audit reports those that do
19
+ # not. A method reopened onto `GraphQL::Query::Context` itself, or added by a module prepended to it, counts
20
+ # like one in the app's own class.
21
+ module ContextMethods
22
+ BASE = GraphQL::Query::Context
23
+ DYNAMIC = :method_missing
24
+ GRAPHQL_ROOT = File.dirname(BASE.instance_method(:query).source_location.first, 2).freeze
25
+ ARMORY_ROOT = File.dirname(__FILE__, 2).freeze
26
+ # graphql-ruby's own public context methods, taken when this gem loads, before any app code: some are defined
27
+ # through Forwardable, whose source file is not graphql-ruby's. Object's methods are never the context's.
28
+ GRAPHQL_NAMES = (BASE.public_instance_methods - Object.public_instance_methods).to_h { |name| [name, true] }.freeze
29
+
30
+ module_function
31
+
32
+ def added(klass)
33
+ check(klass)
34
+ names = owners(klass).flat_map do |owner|
35
+ dynamic = owner.private_instance_methods(false).include?(DYNAMIC) ? [DYNAMIC] : []
36
+ owner.public_instance_methods(false) + dynamic
37
+ end
38
+ names.uniq.reject { |name| recorded_name?(name) || graphql_name?(name) || trusted?(klass.instance_method(name)) }.sort
39
+ end
40
+
41
+ # The added methods not named in `declared` (a Hash of name => reason, or a list of names).
42
+ def undeclared(klass, declared)
43
+ names = (declared.respond_to?(:keys) ? declared.keys : Array(declared)).map(&:to_sym)
44
+ added(klass) - names
45
+ end
46
+
47
+ # Changes when a method is added to the class or to any module it answers through, so a memo of `added`
48
+ # keyed by it sees methods defined after the class's first query.
49
+ def signature(klass)
50
+ check(klass)
51
+ owners(klass).map { |owner| [owner, owner.public_instance_methods(false).size, owner.private_method_defined?(DYNAMIC, false)] }
52
+ end
53
+
54
+ def owners(klass)
55
+ (klass.ancestors - Object.ancestors).reject { |owner| own?(owner) }
56
+ end
57
+
58
+ # A name the recording wrapper overrides: it records the read before any app code under it runs.
59
+ def recorded_name?(name)
60
+ Recorder::Context.wrap(BASE).public_method_defined?(name, false)
61
+ end
62
+
63
+ # A name graphql-ruby itself defines publicly on the context (an override of it is the wrapper's to record, or
64
+ # the audit's to report).
65
+ def graphql_name?(name)
66
+ GRAPHQL_NAMES.key?(name)
67
+ end
68
+
69
+ def trusted?(method)
70
+ own?(method.owner) || from?(method, GRAPHQL_ROOT) || from?(method, ARMORY_ROOT)
71
+ end
72
+
73
+ def from?(method, root)
74
+ file = method.source_location&.first
75
+ !file.nil? && file.start_with?(root + File::SEPARATOR, root + "/")
76
+ end
77
+
78
+ def own?(owner)
79
+ Recorder::Context.wrapper?(owner) || owner.equal?(Recorder::Context::Wrapped)
80
+ end
81
+
82
+ def check(klass)
83
+ raise ArgumentError, "expected a GraphQL::Query::Context subclass, got #{klass.inspect}" unless klass.is_a?(Class) && klass <= BASE
84
+ end
85
+ end
86
+ end
87
+ end
88
+ end