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,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ class Walk
7
+ # One walk of one query's selected operation. Selections are judged from a work list, never by recursion, and
8
+ # each selection set is judged once per owner type, so a document's depth or its repeated fragment spreads
9
+ # cannot exhaust the stack or multiply the work.
10
+ class Run
11
+ Nodes = GraphQL::Language::Nodes
12
+
13
+ TYPENAME = "__typename"
14
+ INTROSPECTION = %w[__schema __type].freeze
15
+ OPERATIONS = { "mutation" => :mutation, "subscription" => :subscription }.freeze
16
+
17
+ def initialize(query)
18
+ @query = query
19
+ @types = query.types
20
+ @tally = Tally.new
21
+ end
22
+
23
+ def policy
24
+ operation = @query.selected_operation
25
+ return Policy.refused(:no_operation) if operation.nil?
26
+ return Policy.refused(OPERATIONS[operation.operation_type]) if OPERATIONS.key?(operation.operation_type)
27
+
28
+ directive = Directives.refusal(@query.document, @types)
29
+ return Policy.refused(directive) if directive
30
+
31
+ root = @types.query_root
32
+ return Policy.refused(:unknown_field) if root.nil?
33
+
34
+ refusal = catch(:refused) do
35
+ walk(operation.selections, root)
36
+ nil
37
+ end
38
+ refusal ? Policy.refused(refusal) : @tally.policy
39
+ end
40
+
41
+ private
42
+
43
+ def refuse(reason)
44
+ throw :refused, reason
45
+ end
46
+
47
+ def walk(selections, owner)
48
+ pending = [[selections, owner]]
49
+ judged = {}.compare_by_identity
50
+ until pending.empty?
51
+ selections, owner = pending.pop
52
+ next if selections.empty?
53
+
54
+ owners = (judged[selections] ||= Set.new)
55
+ next unless owners.add?(owner)
56
+
57
+ selections.each { |node| select(node, owner, pending) }
58
+ end
59
+ end
60
+
61
+ def select(node, owner, pending)
62
+ case node
63
+ when Nodes::Field
64
+ field(node, owner, pending)
65
+ when Nodes::InlineFragment
66
+ pending << [node.selections, node.type ? condition(node.type.name) : owner]
67
+ when Nodes::FragmentSpread
68
+ definition = @query.fragments[node.name]
69
+ refuse(:invalid_document) if definition.nil?
70
+ pending << [definition.selections, condition(definition.type.name)]
71
+ else
72
+ refuse(:invalid_document)
73
+ end
74
+ end
75
+
76
+ # A fragment's type condition becomes the owner of its selections.
77
+ def condition(type_name)
78
+ type = @types.type(type_name)
79
+ refuse(:invalid_document) unless type&.kind&.composite?
80
+ type
81
+ end
82
+
83
+ def field(node, owner, pending)
84
+ return if node.name == TYPENAME
85
+
86
+ refuse(:introspection) if INTROSPECTION.include?(node.name)
87
+
88
+ definitions(owner, node.name).each { |definition| judge(definition) }
89
+ .map { |definition| definition.type.unwrap }.uniq
90
+ .each do |type|
91
+ next unless type.kind.composite?
92
+
93
+ tag(type)
94
+ pending << [node.selections, type]
95
+ end
96
+ end
97
+
98
+ # The field's definition on its owner and, on an interface, every possible type's own definition of that
99
+ # name: an implementation may override the field with its own declaration, and the most restrictive wins.
100
+ def definitions(owner, name)
101
+ definition = @types.field(owner, name)
102
+ refuse(:unknown_field) if definition.nil?
103
+ return [definition] unless owner.kind.abstract?
104
+
105
+ [definition] + @types.possible_types(owner).map do |type|
106
+ @types.field(type, name) || refuse(:unknown_field)
107
+ end
108
+ end
109
+
110
+ def judge(definition)
111
+ declaration = definition.respond_to?(:armory_cache) ? definition.armory_cache : nil
112
+ if declaration.nil?
113
+ refuse(:undeclared_field) unless Relay.generated?(definition)
114
+ elsif declaration.forbidden?
115
+ refuse(:forbidden_field)
116
+ else
117
+ @tally.declare(declaration)
118
+ end
119
+ definition
120
+ end
121
+
122
+ def tag(type)
123
+ @tally.type(type.graphql_name)
124
+ @types.possible_types(type).each { |possible| @tally.type(possible.graphql_name) } if type.kind.abstract?
125
+ end
126
+ end
127
+ end
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+
5
+ module GraphQL
6
+ module Armory
7
+ module Caching
8
+ class Walk
9
+ # Folds the declarations of every selected field into one Policy: the smallest TTL, `:public` only while
10
+ # every declaration is, and the union of their tags plus the type tags of what the selection returns.
11
+ class Tally
12
+ def initialize
13
+ @ttl = nil
14
+ @public = true
15
+ @tags = Set.new
16
+ end
17
+
18
+ def declare(declaration)
19
+ @ttl = @ttl.nil? ? declaration.ttl : [@ttl, declaration.ttl].min
20
+ @public &&= declaration.public?
21
+ declaration.tags.each { |tag| @tags << Tags.custom(tag) }
22
+ end
23
+
24
+ def type(graphql_name)
25
+ @tags << Tags.type(graphql_name)
26
+ end
27
+
28
+ # Nothing declared a TTL (only `__typename` was selected): there is nothing to cache for.
29
+ def policy
30
+ return Policy.refused(:undeclared_field) if @ttl.nil?
31
+
32
+ Policy.cacheable(ttl: @ttl, scope: @public ? :public : :viewer, tags: @tags.to_a)
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # The operation's policy from its declarations: `walk.(query) -> Policy`.
7
+ #
8
+ # policy = Walk.(query)
9
+ # policy.cacheable? # every selected field is declared, and nothing refuses the operation
10
+ # policy.ttl # the smallest TTL over every selected field
11
+ # policy.scope # :public only if every selected field is :public
12
+ # policy.tags # each declared tag ("tag:catalog") and each type the selection can return ("type:Product")
13
+ # policy.reason # when refused: :undeclared_field, :forbidden_field, :directive, :introspection, ...
14
+ #
15
+ # The walk reads the selected operation's AST and `query.types` (the version- and visibility-aware view, on
16
+ # both engines). It needs no validation and no variables, and every rule fails closed: an invalid document is
17
+ # refused, and graphql-ruby answers its error when it runs. `new` needs nothing: the walk has no dependencies.
18
+ #
19
+ # The policy is memoized per query object only. Visibility is per viewer, so a memo across requests (by
20
+ # document) could judge one viewer's query with another's schema.
21
+ class Walk
22
+ def self.build = new
23
+
24
+ def self.call(query) = new.(query)
25
+
26
+ def initialize
27
+ @memo = ObjectSpace::WeakMap.new
28
+ end
29
+
30
+ def call(query)
31
+ policy = @memo[query]
32
+ return policy if policy
33
+
34
+ policy = Run.new(query).policy
35
+ @memo[query] = policy
36
+ policy
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
42
+
43
+ require "graphql/armory/caching/walk/tally"
44
+ require "graphql/armory/caching/walk/relay"
45
+ require "graphql/armory/caching/walk/directives"
46
+ require "graphql/armory/caching/walk/run"
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ # Whole-response caching for persisted operations, declared per field and type.
6
+ #
7
+ # class AppSchema < GraphQL::Schema
8
+ # use GraphQL::Armory::PersistedQueries, store: PERSISTED, strict: true
9
+ # use GraphQL::Armory::Caching, store: GraphQL::Armory::Caching::MemoryStore.new, release: ENV.fetch("GIT_SHA")
10
+ # end
11
+ #
12
+ # Nothing is cached that is not declared, and a run whose answer depended on an input the key does not hold is
13
+ # not stored. See docs/response-caching.md.
14
+ module Caching
15
+ # Caching's telemetry is the gem's: one Telemetry for every module.
16
+ Telemetry = Armory::Telemetry
17
+ Location = Armory::Location
18
+
19
+ # The schema plugin. Every option is checked at boot; see docs/response-caching.md "Installing".
20
+ def self.use(schema, **options)
21
+ Integration.install(schema, **options)
22
+ end
23
+
24
+ # Purges answers: `all: true`, `viewer: principal` (or `:anonymous`), `tag: "pricing"`, or `type: Types::Invoice`
25
+ # (best effort). Raises `PurgeError` when the store fails: a purge that silently failed serves stale data.
26
+ def self.purge(schema, all: false, viewer: nil, tag: nil, type: nil)
27
+ Integration.purge(schema, all: all, viewer: viewer, tag: tag, type: type)
28
+ end
29
+
30
+ # Runs the block without recording the context reads it makes, for readers whose reads do not change the
31
+ # answer: a tracer, a logger, a limiter's key. A read outside the block is checked as usual. On a context
32
+ # without a recorder (no caching installed, a plain Hash) it simply yields.
33
+ def self.neutral(context, &block)
34
+ recorder = RecordKeys.recorder(context)
35
+ recorder ? recorder.neutral(&block) : yield
36
+ end
37
+ end
38
+ end
39
+ end
40
+
41
+ require "graphql/armory/caching/errors"
42
+ require "graphql/armory/caching/record_keys"
43
+ require "graphql/armory/caching/tags"
44
+ require "graphql/armory/caching/values/declaration"
45
+ require "graphql/armory/caching/values/policy"
46
+ require "graphql/armory/caching/values/key"
47
+ require "graphql/armory/caching/values/entry"
48
+ require "graphql/armory/caching/values/lookup"
49
+ require "graphql/armory/caching/values/decision"
50
+ require "graphql/armory/caching/store"
51
+ require "graphql/armory/caching/memory_store"
52
+ require "graphql/armory/caching/redis_store"
53
+ require "graphql/armory/caching/recorder"
54
+ require "graphql/armory/caching/context_methods"
55
+ require "graphql/armory/caching/digester"
56
+ require "graphql/armory/caching/nulls"
57
+ require "graphql/armory/caching/codec"
58
+ require "graphql/armory/caching/walk"
59
+ require "graphql/armory/caching/canonical"
60
+ require "graphql/armory/caching/schema_identity"
61
+ require "graphql/armory/caching/viewer"
62
+ require "graphql/armory/caching/keyer"
63
+ require "graphql/armory/caching/charge"
64
+ require "graphql/armory/caching/gate/substitute"
65
+ require "graphql/armory/caching/gate"
66
+ require "graphql/armory/caching/base"
67
+ require "graphql/armory/caching/integration"
68
+ require "graphql/armory/caching/controls"
69
+ require "graphql/armory/caching/audit"
@@ -28,6 +28,20 @@ module GraphQL
28
28
  rescue StandardError
29
29
  raise InvalidError
30
30
  end
31
+
32
+ # It does not encrypt, so it seals and digests nothing (a cache entry it "sealed" could be forged by
33
+ # anyone), and opens nothing: in a chain, the encrypting members open what was sealed.
34
+ def self.seal(_bytes, aad:, purpose:)
35
+ raise ConfigurationError, "#{name} cannot seal: it does not encrypt (put an Encoder first in the chain)"
36
+ end
37
+
38
+ def self.open(_text, aad:, purpose:)
39
+ raise InvalidError
40
+ end
41
+
42
+ def self.mac(_bytes, purpose:)
43
+ raise ConfigurationError, "#{name} cannot digest: it has no key (put an Encoder first in the chain)"
44
+ end
31
45
  end
32
46
  end
33
47
  end
@@ -3,7 +3,8 @@
3
3
  module GraphQL
4
4
  module Armory
5
5
  class Encoder
6
- # The encoder of an object nobody wired: it hands out no ID and honours none.
6
+ # The encoder of an object nobody wired: it hands out no ID and honours none, seals and digests nothing, and
7
+ # opens nothing.
7
8
  module Null
8
9
  def self.encode(_text, nonce: false)
9
10
  raise ConfigurationError, "no encoder wired: give an Encoder (or use Encoder.default)"
@@ -12,6 +13,18 @@ module GraphQL
12
13
  def self.decode(_text, nonce: false)
13
14
  raise InvalidError
14
15
  end
16
+
17
+ def self.seal(_bytes, aad:, purpose:)
18
+ raise ConfigurationError, "#{name} cannot seal: no encoder wired, give an Encoder (or use Encoder.default)"
19
+ end
20
+
21
+ def self.open(_text, aad:, purpose:)
22
+ raise InvalidError
23
+ end
24
+
25
+ def self.mac(_bytes, purpose:)
26
+ raise ConfigurationError, "#{name} cannot digest: no encoder wired, give an Encoder (or use Encoder.default)"
27
+ end
15
28
  end
16
29
  end
17
30
  end
@@ -1,22 +1,32 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "openssl"
4
+
3
5
  module GraphQL
4
6
  module Armory
5
7
  class Encoder
6
8
  # Encodes reversibly without a key or any cryptography, records what it encoded and decoded, and fails when
7
9
  # told: for tests of the objects that use an encoder. Never use it to hand out real IDs: anyone can forge them.
10
+ #
11
+ # It also seals (`seal`/`open`, reversible, still bound to the additional data and purpose so a value moved
12
+ # elsewhere does not open) and digests (`mac`, an unkeyed SHA-256 per purpose), recording each call in `sealed`,
13
+ # `opened` and `macs`. None of it is secret.
8
14
  class Substitute
9
15
  PREFIX = "substitute:"
16
+ SEALED_PREFIX = "substitute-sealed:"
10
17
 
11
- attr_reader :encoded, :decoded
18
+ attr_reader :encoded, :decoded, :sealed, :opened, :macs
12
19
 
13
20
  def initialize
14
21
  @encoded = []
15
22
  @decoded = []
23
+ @sealed = []
24
+ @opened = []
25
+ @macs = []
16
26
  @failure = nil
17
27
  end
18
28
 
19
- # Raises `error` from every encode and decode until `recover`.
29
+ # Raises `error` from every encode, decode, seal, open and mac until `recover`.
20
30
  def fail_with(error)
21
31
  @failure = error
22
32
  end
@@ -41,6 +51,48 @@ module GraphQL
41
51
  rescue ArgumentError
42
52
  raise InvalidError
43
53
  end
54
+
55
+ # `substitute-sealed:<purpose>.<aad>.<bytes>`, the last two in base64url.
56
+ def seal(bytes, aad:, purpose:)
57
+ Encoder.check_sealing(purpose: purpose, aad: aad)
58
+ raise ArgumentError, "bytes: must be a String, got #{bytes.class}" unless bytes.is_a?(String)
59
+
60
+ @sealed << { bytes: bytes.b, aad: aad, purpose: purpose }
61
+ raise @failure if @failure
62
+
63
+ SEALED_PREFIX + [purpose, URLSafeBase64.encode(aad.b), URLSafeBase64.encode(bytes.b)].join(".")
64
+ end
65
+
66
+ def open(text, aad:, purpose:)
67
+ Encoder.check_sealing(purpose: purpose, aad: aad)
68
+ @opened << { text: text, aad: aad, purpose: purpose }
69
+ raise @failure if @failure
70
+ raise InvalidError unless text.is_a?(String) && text.start_with?(SEALED_PREFIX)
71
+
72
+ sealed_purpose, sealed_aad, bytes = text.delete_prefix(SEALED_PREFIX).split(".", -1)
73
+ raise InvalidError unless sealed_purpose == purpose && sealed_aad && bytes && base64(sealed_aad) == aad.b
74
+
75
+ base64(bytes)
76
+ end
77
+
78
+ # SHA-256 of the purpose and the bytes: 32 bytes, as a real `mac`, but anyone can compute it.
79
+ def mac(bytes, purpose:)
80
+ Encoder.check_sealing(purpose: purpose)
81
+ raise ArgumentError, "bytes: must be a String, got #{bytes.class}" unless bytes.is_a?(String)
82
+
83
+ @macs << { bytes: bytes.b, purpose: purpose }
84
+ raise @failure if @failure
85
+
86
+ OpenSSL::Digest::SHA256.digest("#{purpose}\0".b + bytes.b)
87
+ end
88
+
89
+ private
90
+
91
+ def base64(text)
92
+ URLSafeBase64.decode(text)
93
+ rescue ArgumentError
94
+ raise InvalidError
95
+ end
44
96
  end
45
97
  end
46
98
  end
@@ -39,8 +39,44 @@ module GraphQL
39
39
  [nil, nil]
40
40
  end
41
41
 
42
+ # Seals with the newest encoder, so a rotated key is used at once.
43
+ def seal(bytes, aad:, purpose:)
44
+ newest(:seal).seal(bytes, aad: aad, purpose: purpose)
45
+ end
46
+
47
+ # Opens with whichever encoder sealed the value: values sealed before a rotation keep opening while the old
48
+ # encoder stays in the chain. Members that cannot open (Legacy, a custom ID encoder) are skipped.
49
+ def open(text, aad:, purpose:)
50
+ Encoder.check_sealing(purpose: purpose, aad: aad)
51
+ encoders.each do |encoder|
52
+ next unless encoder.respond_to?(:open)
53
+
54
+ bytes = encoder.open(text, aad: aad, purpose: purpose)
55
+ return bytes if bytes.is_a?(String)
56
+ rescue ConfigurationError, ArgumentError
57
+ raise
58
+ rescue StandardError
59
+ next
60
+ end
61
+ raise InvalidError
62
+ end
63
+
64
+ # Digests with the newest encoder: rotating the key changes every digest (response cache keys and tags), so
65
+ # entries stored under the old key are no longer found.
66
+ def mac(bytes, purpose:)
67
+ newest(:mac).mac(bytes, purpose: purpose)
68
+ end
69
+
42
70
  private
43
71
 
72
+ def newest(operation)
73
+ encoder = encoders.first
74
+ return encoder if encoder.respond_to?(operation)
75
+
76
+ verb = operation == :seal ? "seal" : "digest"
77
+ raise ConfigurationError, "#{encoder.inspect} cannot #{verb}: put an Encoder first in the chain"
78
+ end
79
+
44
80
  # Fails at boot for a member that would otherwise refuse every value at request time.
45
81
  def check(encoder)
46
82
  unless %i[encode decode].all? { |name| encoder.respond_to?(name) }
@@ -15,6 +15,9 @@ module GraphQL
15
15
  # never gives the same cursor. IDs must be stable, so their nonce is derived from the ID itself with an
16
16
  # HMAC: the same ID always encrypts the same way, and two different IDs never share a nonce.
17
17
  # IDs and cursors use separate keys, so one is never accepted as the other.
18
+ #
19
+ # It also seals other data for storage (`seal`/`open`, response cache entries) and answers keyed digests (`mac`),
20
+ # each under a key derived for its purpose, so a sealed value is never an ID or a cursor and the reverse.
18
21
  class Encoder
19
22
  # Raised for anything that does not decode: tampered, foreign, malformed. The message never says which.
20
23
  class InvalidError < GraphQL::ExecutionError
@@ -40,6 +43,17 @@ module GraphQL
40
43
  NONCE_BYTES = 12
41
44
  AUTH_TAG_BYTES = 16
42
45
  CIPHER = "aes-256-gcm"
46
+ # A purpose for `seal`, `open` and `mac` (`cache`, `cache-digest`): lowercase words joined by dashes. With no
47
+ # `/` in it, its HKDF info (`seal/<purpose>/cipher`, `mac/<purpose>/hmac`) never equals another purpose's, nor
48
+ # the IDs' and cursors'.
49
+ PURPOSE = /\A[a-z0-9]+(?:-[a-z0-9]+)*\z/
50
+
51
+ # Checks the arguments every `seal`, `open` and `mac` takes, before anything is encrypted. Raises ArgumentError:
52
+ # a wrong purpose or additional data is a bug in the caller, never an input to hide behind InvalidError.
53
+ def self.check_sealing(purpose:, aad: "")
54
+ raise ArgumentError, "purpose: must be lowercase words joined by dashes (\"cache\"), got #{purpose.inspect}" unless purpose.is_a?(String) && PURPOSE.match?(purpose)
55
+ raise ArgumentError, "aad: must be a String, got #{aad.class}" unless aad.is_a?(String)
56
+ end
43
57
 
44
58
  class << self
45
59
  # The key, at least 32 bytes. With no argument, answers it (inherited from the parent class).
@@ -107,6 +121,58 @@ module GraphQL
107
121
  raise InvalidError
108
122
  end
109
123
 
124
+ # Encrypts and authenticates `bytes` for storage with AES-256-GCM, a random nonce and a key derived for
125
+ # `purpose` alone; `aad` (additional data, such as the store key the value is written under) and the
126
+ # encoder's tag are authenticated, not stored, so the value opens only with the same `aad`, `purpose`, key
127
+ # and tag. Answers base64url text without padding, whatever `codec` IDs use.
128
+ def seal(bytes, aad:, purpose:)
129
+ Encoder.check_sealing(purpose: purpose, aad: aad)
130
+ raise ArgumentError, "bytes: must be a String, got #{bytes.class}" unless bytes.is_a?(String)
131
+
132
+ iv = OpenSSL::Random.random_bytes(NONCE_BYTES)
133
+ cipher = OpenSSL::Cipher.new(CIPHER).encrypt
134
+ cipher.key = subkey(sealing(purpose), :cipher)
135
+ cipher.iv = iv
136
+ cipher.auth_data = framed(aad)
137
+ sealed = cipher_update(cipher, bytes.b) + cipher.final
138
+ URLSafeBase64.encode(iv + sealed + cipher.auth_tag)
139
+ end
140
+
141
+ # The bytes `seal` sealed under the same `aad` and `purpose`, as binary. Raises InvalidError for anything
142
+ # else (tampered, moved under other additional data, another key, tag or purpose, an ID or a cursor).
143
+ def open(text, aad:, purpose:)
144
+ Encoder.check_sealing(purpose: purpose, aad: aad)
145
+ raise InvalidError unless text.is_a?(String)
146
+
147
+ key = subkey(sealing(purpose), :cipher)
148
+ begin
149
+ bytes = URLSafeBase64.decode(text)
150
+ # One text form only, as for IDs.
151
+ raise InvalidError unless URLSafeBase64.encode(bytes) == text
152
+ raise InvalidError if bytes.bytesize < NONCE_BYTES + AUTH_TAG_BYTES
153
+
154
+ cipher = OpenSSL::Cipher.new(CIPHER).decrypt
155
+ cipher.key = key
156
+ cipher.iv = bytes[0, NONCE_BYTES]
157
+ cipher.auth_tag = bytes[-AUTH_TAG_BYTES..]
158
+ cipher.auth_data = framed(aad)
159
+ cipher_update(cipher, bytes[NONCE_BYTES...-AUTH_TAG_BYTES]) + cipher.final
160
+ rescue StandardError
161
+ # Whatever base64 or OpenSSL raise, the caller learns only that it did not open.
162
+ raise InvalidError
163
+ end
164
+ end
165
+
166
+ # The raw 32-byte HMAC-SHA256 of `bytes` (and the encoder's tag) under a key derived for `purpose` alone:
167
+ # keyed digests, such as response cache keys and tags, that whoever reads the store cannot confirm a guess
168
+ # against.
169
+ def mac(bytes, purpose:)
170
+ Encoder.check_sealing(purpose: purpose)
171
+ raise ArgumentError, "bytes: must be a String, got #{bytes.class}" unless bytes.is_a?(String)
172
+
173
+ OpenSSL::HMAC.digest("SHA256", subkey("mac/#{purpose}", :hmac), framed(bytes))
174
+ end
175
+
110
176
  private
111
177
 
112
178
  def setting(ivar, default)
@@ -119,8 +185,21 @@ module GraphQL
119
185
  OpenSSL::HMAC.digest("SHA256", subkey(:id, :nonce), tag.b + "\0".b + bytes)[0, NONCE_BYTES]
120
186
  end
121
187
 
188
+ def sealing(purpose) = "seal/#{purpose}"
189
+
190
+ # OpenSSL refuses to update with no data; sealing nothing still authenticates the additional data.
191
+ def cipher_update(cipher, bytes)
192
+ bytes.empty? ? "".b : cipher.update(bytes)
193
+ end
194
+
195
+ # The encoder's tag, length-prefixed, then `bytes`: no tag and data can be split another way.
196
+ def framed(bytes)
197
+ [tag.bytesize].pack("N") + tag.b + bytes.b
198
+ end
199
+
122
200
  # Separate keys per purpose and use, derived with HKDF and cached by the secret they come from, so a key
123
- # changed later (here or in a parent class) is used at once.
201
+ # changed later (here or in a parent class) is used at once. IDs use `id/cipher` and `id/nonce`, cursors
202
+ # `cursor/cipher`, sealed values `seal/<purpose>/cipher` and digests `mac/<purpose>/hmac`: no two share a key.
124
203
  def subkey(purpose, use)
125
204
  secret = key or raise ConfigurationError, "#{name || "Encoder"} has no key: call `key` in its class body"
126
205
  @subkeys ||= {}
@@ -197,7 +197,14 @@ module GraphQL
197
197
  refusal, document = schema.armory_persisted_queries.(options[:context], text, options[:document])
198
198
 
199
199
  return super if refusal.nil? && document.nil?
200
- return super(schema, nil, **options, query: nil, document: document) if refusal.nil?
200
+
201
+ if refusal.nil?
202
+ super(schema, nil, **options, query: nil, document: document)
203
+ # Only here, the stored operation: in a namespace the client cannot write, unlike `operation_id`. Response
204
+ # caching serves and stores answers only for queries with this mark.
205
+ Caching::RecordKeys.persisted!(context)
206
+ return
207
+ end
201
208
 
202
209
  # A refused request fails validation with the refusal as its only error, so neither engine runs it. Its
203
210
  # text is never parsed; a document the app built itself is kept, for `Schema.validate`, which validates it
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module RateLimits
6
+ # Charges a response the cache answers instead of running it. A hit runs no analyzer, so without this it would be
7
+ # free, and a budget that does not move tells the client that someone else asked the same question first. Mixed
8
+ # into `Points`; the response cache reaches it through `Caching::Charge`.
9
+ module CachedCharge
10
+ # Charges `cost`, the points the query's run was charged, exactly as a run is charged: the same keys, limits,
11
+ # soft mode and store, the same records (`context[:rate_limit_points]` and the query's own namespace), the same
12
+ # `rateLimit` extension and so the same `Points.headers`. Answers nil when the hit may be served, or the
13
+ # limiter's own `RATE_LIMITED` refusal, the `GraphQL::AnalysisError` a run would answer. A store that fails lets
14
+ # the hit through and is reported to `on_store_error`, as for a run.
15
+ #
16
+ # A `key:` or `limit:` callable that raises a GraphQL::ExecutionError is handled as `AnalysisGuard` handles it
17
+ # for a run: in hard mode the refusal is that error when it is an AnalysisError, else RATE_LIMIT_NOT_CHARGED; in
18
+ # soft mode the hit is served and recorded `charged: false`.
19
+ def charge_cached(query, cost:)
20
+ unless cost.is_a?(Integer) && !cost.negative?
21
+ raise ArgumentError, "cost: must be the non-negative Integer of points the run was charged, got #{cost.inspect}"
22
+ end
23
+
24
+ call(query, cost)
25
+ rescue GraphQL::ExecutionError, GraphQL::UnauthorizedError => error
26
+ uncharged(query, error)
27
+ end
28
+
29
+ private
30
+
31
+ def uncharged(query, error)
32
+ Caching.neutral(query.context) do
33
+ query.context[self.class::CONTEXT_KEY] = { limit: nil, soft: soft?, limited: !soft?, charged: false }
34
+ end
35
+ return nil if soft?
36
+ return error if error.is_a?(GraphQL::AnalysisError)
37
+
38
+ GraphQL::AnalysisError.new(AnalysisGuard::NOT_CHARGED, extensions: { "code" => "RATE_LIMIT_NOT_CHARGED" })
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end