graphql-armory 0.1.0.pre6 → 0.1.0.pre8

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 (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +43 -1
  3. data/README.md +6 -5
  4. data/docs/authorization.md +133 -6
  5. data/docs/keyset-connections.md +95 -0
  6. data/docs/persisted-queries.md +16 -0
  7. data/docs/rate-limiting.md +20 -0
  8. data/docs/telemetry.md +1 -0
  9. data/lib/graphql/armory/authorization/adapters/cancan.rb +10 -1
  10. data/lib/graphql/armory/authorization/adapters/pundit.rb +71 -13
  11. data/lib/graphql/armory/authorization/adapters/substitute.rb +4 -1
  12. data/lib/graphql/armory/authorization/audit/denial_hooks.rb +29 -0
  13. data/lib/graphql/armory/authorization/audit/edge_rules.rb +36 -0
  14. data/lib/graphql/armory/authorization/audit/findings.rb +34 -0
  15. data/lib/graphql/armory/authorization/audit/foreign_policies.rb +90 -0
  16. data/lib/graphql/armory/authorization/audit/input_loads.rb +26 -0
  17. data/lib/graphql/armory/authorization/audit/interface_rules.rb +39 -0
  18. data/lib/graphql/armory/authorization/audit/introspection_fields.rb +40 -0
  19. data/lib/graphql/armory/authorization/audit/library_methods.rb +24 -0
  20. data/lib/graphql/armory/authorization/audit/overrides.rb +81 -0
  21. data/lib/graphql/armory/authorization/audit/own_checks.rb +144 -0
  22. data/lib/graphql/armory/authorization/audit/type_rules.rb +265 -0
  23. data/lib/graphql/armory/authorization/audit/visibility_models.rb +83 -0
  24. data/lib/graphql/armory/authorization/audit.rb +50 -191
  25. data/lib/graphql/armory/authorization/authorize.rb +9 -3
  26. data/lib/graphql/armory/authorization/configuration.rb +30 -2
  27. data/lib/graphql/armory/authorization/definitions.rb +114 -0
  28. data/lib/graphql/armory/authorization/integration/argument.rb +24 -6
  29. data/lib/graphql/armory/authorization/integration/field.rb +13 -5
  30. data/lib/graphql/armory/authorization/integration/object.rb +3 -1
  31. data/lib/graphql/armory/authorization/integration/schema.rb +7 -0
  32. data/lib/graphql/armory/authorization/integration.rb +22 -1
  33. data/lib/graphql/armory/authorization/rule.rb +5 -0
  34. data/lib/graphql/armory/authorization.rb +4 -1
  35. data/lib/graphql/armory/keyset/controls.rb +36 -0
  36. data/lib/graphql/armory/keyset.rb +279 -0
  37. data/lib/graphql/armory/version.rb +1 -1
  38. data/lib/graphql/armory.rb +1 -0
  39. metadata +17 -1
@@ -96,13 +96,34 @@ module GraphQL
96
96
 
97
97
  # An interface field with no rule of its own cannot name the type it is resolved on, so it is only
98
98
  # covered when no implementer is a bypass: a field on a bypassed type is denied, and so is this one.
99
+ # `possible_types` is read with no request, so it drops an implementer hidden there.
99
100
  def self.bypassed_implementer?(interface, schema)
100
- schema.possible_types(interface).any? do |type|
101
+ hidden = schema.respond_to?(:armory_implementers) ? schema.armory_implementers(interface) : []
102
+ any_bypass?(schema.possible_types(interface) + hidden)
103
+ end
104
+
105
+ def self.any_bypass?(types)
106
+ types.any? do |type|
101
107
  rule = type.armory_rule if type.respond_to?(:armory_rule)
102
108
  rule && rule.none? && !rule.covers_fields?
103
109
  end
104
110
  end
105
111
 
112
+ # The rule with the model its owner wraps, the one the audit reads: named by the rule, or named like the type.
113
+ def self.with_owner_model(rule, owner)
114
+ return rule if rule.none? || rule.policy || rule.model || !owner.respond_to?(:armory_model)
115
+
116
+ rule.with_model(declared_model(owner) || owner.armory_model)
117
+ rescue ConfigurationError, GraphQL::RequiredImplementationMissingError
118
+ rule
119
+ end
120
+
121
+ # A Symbol or a String stays as written: only that spelling can name a policy for a Symbol the type wraps.
122
+ def self.declared_model(owner)
123
+ owner.armory_rule&.model if owner.respond_to?(:armory_rule)
124
+ end
125
+ private_class_method :declared_model
126
+
106
127
  # One Authorize per query: building it (and its memo and telemetry) once per object is pure overhead.
107
128
  def self.allowed?(subject, rule, context)
108
129
  store = context.namespace(:armory)
@@ -32,6 +32,11 @@ module GraphQL
32
32
  freeze
33
33
  end
34
34
 
35
+ def with_model(model)
36
+ self.class.new(action, policy: policy, subject: subject, attribute: attribute, model: model, scope: scope,
37
+ visible_when: visible_when, covers_fields: covers_fields, reason: reason)
38
+ end
39
+
35
40
  # A bypassed type whose fields are covered by something else, such as the payload of a mutation.
36
41
  def covers_fields?
37
42
  covers_fields
@@ -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), `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)
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ class Keyset
6
+ # Test data for keyset connections, reusable by apps and other gems.
7
+ module Controls
8
+ # A schema with one connection field, `items`, that answers what the root value holds.
9
+ module Schema
10
+ def self.example(base: GraphQL::Schema, cursor_encoder: nil, max_page_size: nil)
11
+ item = Class.new(GraphQL::Schema::Object) do
12
+ graphql_name "Item"
13
+ field :id, String, null: false
14
+ end
15
+ root = Class.new(GraphQL::Schema::Object) do
16
+ graphql_name "Query"
17
+ field :items, item.connection_type, null: false
18
+ end
19
+ Class.new(base) do
20
+ query(root)
21
+ cursor_encoder(cursor_encoder) if cursor_encoder
22
+ default_max_page_size(max_page_size) if max_page_size
23
+ end
24
+ end
25
+ end
26
+
27
+ # The root value `Schema.example` reads its connection from.
28
+ module Root
29
+ def self.example(connection)
30
+ Struct.new(:items).new(connection)
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,279 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module GraphQL
6
+ module Armory
7
+ # A connection that pages an ActiveRecord relation by the values of its ordering columns instead of OFFSET,
8
+ # so rows inserted or deleted between pages neither skip nor repeat items. Return it from a resolver:
9
+ #
10
+ # def invoices
11
+ # GraphQL::Armory::Keyset.build(Invoice.order(created_at: :desc))
12
+ # end
13
+ #
14
+ # A cursor holds the row's ordering values. Base64 cursors would let a client read them and forge them to
15
+ # search a column it cannot see, so the schema's default encoder is refused unless `plain_cursors: true`.
16
+ class Keyset < GraphQL::Pagination::Connection
17
+ class ConfigurationError < Armory::Error; end
18
+
19
+ CURSOR_VERSION = 1
20
+ PAGEABLE_TYPES = %i[integer string text decimal datetime date boolean uuid].freeze
21
+
22
+ # The forms this connection's own cursors have. A forged decimal like 1e99999999999 would exhaust memory.
23
+ DECIMAL_FORM = /\A-?\d{1,65}(\.\d{1,65})?\z/
24
+ DATE_FORM = /\A\d{4}-\d{2}-\d{2}\z/
25
+ DATETIME_FORM = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})\z/
26
+
27
+ Column = Struct.new(:name, :direction, :attribute, :type, keyword_init: true)
28
+
29
+ # Reads what a relation is ordered by, adds the primary key as the tie-breaker, and refuses what it cannot page.
30
+ module Ordering
31
+ def self.call(relation)
32
+ refuse("a limit") if relation.limit_value
33
+ refuse("an offset") if relation.offset_value
34
+ refuse("a group") if relation.group_values.any?
35
+ refuse("a select") if relation.select_values.any?
36
+ refuse("a join that is not distinct: it can repeat rows") if joined?(relation) && !relation.distinct_value
37
+
38
+ columns = relation.order_values.map { |order| column(relation.klass, order) }.uniq(&:name)
39
+ primary_key = Array(relation.klass.primary_key)
40
+ refuse("a model without a primary key") if primary_key.empty?
41
+
42
+ direction = columns.last&.direction || :asc
43
+ (primary_key - columns.map(&:name)).each { |name| columns << column_named(relation.klass, name, direction) }
44
+ columns.freeze
45
+ end
46
+
47
+ def self.joined?(relation)
48
+ relation.joins_values.any? || relation.left_outer_joins_values.any?
49
+ end
50
+
51
+ def self.column(klass, order)
52
+ direction = { Arel::Nodes::Ascending => :asc, Arel::Nodes::Descending => :desc }[order.class]
53
+ attribute = order.expr if direction
54
+ refuse("an order that is not a plain column: #{order.class}") unless attribute.is_a?(Arel::Attributes::Attribute)
55
+ refuse("an order on another table: #{attribute.relation.name}") unless attribute.relation.name == klass.table_name
56
+
57
+ column_named(klass, attribute.name.to_s, direction)
58
+ end
59
+
60
+ def self.column_named(klass, name, direction)
61
+ definition = klass.columns_hash[name]
62
+ refuse("an order on an unknown column: #{name}") if definition.nil?
63
+ refuse("an order on a nullable column: #{name}") if definition.null && klass.primary_key != name
64
+
65
+ type = klass.type_for_attribute(name)
66
+ refuse("an order on a #{type.type} column: #{name}") unless PAGEABLE_TYPES.include?(type.type)
67
+ refuse("an order on a serialized or encrypted column: #{name}") if transformed?(type)
68
+
69
+ Column.new(name: name, direction: direction, attribute: klass.arel_table[name], type: type)
70
+ end
71
+
72
+ # These report the type they store as, but the database does not order them by the value a cursor holds.
73
+ # `normalizes` wraps the type it is declared over, so the wrapped types count too.
74
+ def self.transformed?(type)
75
+ return true if type.is_a?(ActiveRecord::Type::Serialized) || type.is_a?(ActiveRecord::Encryption::EncryptedAttributeType)
76
+
77
+ type.respond_to?(:cast_type) && transformed?(type.cast_type)
78
+ end
79
+
80
+ def self.refuse(what)
81
+ raise ConfigurationError, "a keyset connection cannot page #{what}"
82
+ end
83
+ end
84
+
85
+ attr_reader :columns
86
+
87
+ # Checks the relation and its ordering; resolvers go through here.
88
+ def self.build(relation, plain_cursors: false)
89
+ raise ConfigurationError, "plain_cursors: must be true or false, got #{plain_cursors.inspect}" unless [true, false].include?(plain_cursors)
90
+ raise ConfigurationError, "a keyset connection needs an ActiveRecord relation, got #{relation.class}" unless relation.respond_to?(:order_values)
91
+
92
+ new(relation, columns: Ordering.(relation), plain_cursors: plain_cursors)
93
+ end
94
+
95
+ # `new` is inert: with no relation it has no rows, no pages and no cursors.
96
+ def initialize(items = nil, columns: [], plain_cursors: false, **options)
97
+ super(columns.empty? ? nil : items, **options)
98
+ @columns = columns
99
+ @plain_cursors = plain_cursors
100
+ end
101
+
102
+ # This connection over the relation the block answers: how a type's scope reaches the rows. A scope that did
103
+ # not change the relation answers the same object, so graphql-ruby does not take the list as narrowed.
104
+ def rescoped
105
+ return self if items.nil?
106
+
107
+ relation = yield(items)
108
+ return self if relation.equal?(items)
109
+
110
+ dup.scope_to(relation, self.class.build(relation, plain_cursors: @plain_cursors).columns)
111
+ end
112
+
113
+ def nodes
114
+ load_page
115
+ @nodes
116
+ end
117
+
118
+ def has_next_page
119
+ return false if items.nil?
120
+
121
+ load_page
122
+ return @more if !@backward && before.nil?
123
+ return false if @backward && before.nil?
124
+
125
+ anchor = @nodes.last
126
+ anchor ? beyond?(key_of(anchor), :after) : beyond?(@before_key, :after, inclusive: true)
127
+ end
128
+
129
+ def has_previous_page
130
+ return false if items.nil?
131
+
132
+ load_page
133
+ return @more if @backward && after.nil?
134
+ return false if !@backward && after.nil?
135
+
136
+ anchor = @nodes.first
137
+ anchor ? beyond?(key_of(anchor), :before) : beyond?(@after_key, :before, inclusive: true)
138
+ end
139
+
140
+ def cursor_for(item)
141
+ return nil if items.nil?
142
+
143
+ refuse_plain_cursors
144
+ values = columns.map { |column| dump(column.type.serialize(item[column.name])) }
145
+ encode(JSON.generate("v" => CURSOR_VERSION, "o" => fingerprint, "k" => values))
146
+ end
147
+
148
+ protected
149
+
150
+ def scope_to(relation, columns)
151
+ @items = relation
152
+ @columns = columns
153
+ self
154
+ end
155
+
156
+ private
157
+
158
+ def load_page
159
+ return if defined?(@nodes)
160
+
161
+ return @nodes = [] if items.nil?
162
+
163
+ refuse_plain_cursors
164
+ raise GraphQL::ExecutionError, "first and last cannot be used together" if first_value && last_value
165
+
166
+ @after_key = after && key_from(after)
167
+ @before_key = before && key_from(before)
168
+ @backward = !last_value.nil?
169
+ limit = @backward ? last : first
170
+
171
+ relation = items
172
+ relation = relation.where(condition(@after_key, :after)) if @after_key
173
+ relation = relation.where(condition(@before_key, :before)) if @before_key
174
+ relation = relation.reorder(columns.map { |column| arel_order(column) })
175
+ relation = relation.limit(limit + 1) if limit
176
+
177
+ rows = relation.to_a
178
+ @more = !limit.nil? && rows.size > limit
179
+ rows = rows.first(limit) if limit
180
+ @nodes = @backward ? rows.reverse : rows
181
+ end
182
+
183
+ def refuse_plain_cursors
184
+ return if @plain_cursors
185
+
186
+ encoder = context&.schema&.cursor_encoder
187
+ return unless encoder.nil? || encoder == GraphQL::Schema::Base64Encoder
188
+
189
+ raise ConfigurationError,
190
+ "a keyset cursor holds the row's ordering values: set an encrypting cursor_encoder on the schema " \
191
+ "(GraphQL::Armory::Encoder), or pass plain_cursors: true if those values are not secret"
192
+ end
193
+
194
+ def arel_order(column)
195
+ forward = column.direction == :asc
196
+ forward = !forward if @backward
197
+ forward ? column.attribute.asc : column.attribute.desc
198
+ end
199
+
200
+ def beyond?(key, side, inclusive: false)
201
+ items.where(condition(key, side, inclusive: inclusive)).exists?
202
+ end
203
+
204
+ # (a > x) OR (a = x AND b > y) OR ...: the rows past `key` on `side`, for any mix of directions.
205
+ def condition(key, side, inclusive: false)
206
+ pairs = columns.zip(key)
207
+ branches = pairs.each_index.map do |index|
208
+ column, value = pairs[index]
209
+ ascending = (column.direction == :asc) == (side == :after)
210
+ past = ascending ? column.attribute.gt(value) : column.attribute.lt(value)
211
+ pairs.first(index).reverse_each.inject(past) { |node, (earlier, equal)| earlier.attribute.eq(equal).and(node) }
212
+ end
213
+ branches << pairs.map { |column, value| column.attribute.eq(value) }.inject(:and) if inclusive
214
+ branches.inject(:or)
215
+ end
216
+
217
+ def key_of(record)
218
+ columns.map { |column| record[column.name] }
219
+ end
220
+
221
+ def fingerprint
222
+ columns.map { |column| "#{column.attribute.relation.name}.#{column.name}:#{column.direction}" }.join(",")
223
+ end
224
+
225
+ def dump(value)
226
+ return value.getutc.iso8601(9) if value.respond_to?(:getutc)
227
+
228
+ case value
229
+ when BigDecimal then value.to_s("F")
230
+ when Date then value.iso8601
231
+ else value
232
+ end
233
+ end
234
+
235
+ # Every cursor that cannot be honoured answers the same error, whatever is wrong with it.
236
+ def key_from(cursor)
237
+ payload = JSON.parse(decoded(cursor))
238
+ raise Encoder::InvalidError unless payload.is_a?(Hash) && payload["v"] == CURSOR_VERSION && payload["o"] == fingerprint
239
+
240
+ values = payload["k"]
241
+ raise Encoder::InvalidError unless values.is_a?(Array) && values.size == columns.size
242
+
243
+ columns.zip(values).map { |column, value| load_value(column, value) }
244
+ rescue JSON::ParserError, EncodingError, ActiveModel::RangeError
245
+ raise Encoder::InvalidError
246
+ end
247
+
248
+ # Anything a custom encoder raises on a bad cursor, or a nil it answers, is one more invalid cursor.
249
+ def decoded(cursor)
250
+ decode(cursor).dup.force_encoding(Encoding::UTF_8).tap { |text| raise Encoder::InvalidError unless text.valid_encoding? }
251
+ rescue StandardError
252
+ raise Encoder::InvalidError
253
+ end
254
+
255
+ def well_formed?(kind, value)
256
+ case kind
257
+ when :integer then value.is_a?(Integer)
258
+ when :boolean then value == true || value == false
259
+ when :decimal then value.is_a?(String) && DECIMAL_FORM.match?(value)
260
+ when :date then value.is_a?(String) && DATE_FORM.match?(value)
261
+ when :datetime then value.is_a?(String) && DATETIME_FORM.match?(value)
262
+ else value.is_a?(String) && !value.include?("\0")
263
+ end
264
+ end
265
+
266
+ def load_value(column, value)
267
+ raise Encoder::InvalidError unless well_formed?(column.type.type, value)
268
+
269
+ cast = column.type.cast(value)
270
+ raise Encoder::InvalidError if cast.nil?
271
+
272
+ column.type.serialize(cast)
273
+ cast
274
+ end
275
+ end
276
+ end
277
+ end
278
+
279
+ require "graphql/armory/keyset/controls"
@@ -2,6 +2,6 @@
2
2
 
3
3
  module GraphQL
4
4
  module Armory
5
- VERSION = "0.1.0.pre6"
5
+ VERSION = "0.1.0.pre8"
6
6
  end
7
7
  end
@@ -16,3 +16,4 @@ require "graphql/armory/authorization"
16
16
  require "graphql/armory/ids"
17
17
  require "graphql/armory/persisted_queries"
18
18
  require "graphql/armory/rate_limits"
19
+ require "graphql/armory/keyset"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: graphql-armory
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0.pre6
4
+ version: 0.1.0.pre8
5
5
  platform: ruby
6
6
  authors:
7
7
  - Israel
@@ -43,6 +43,7 @@ files:
43
43
  - README.md
44
44
  - docs/authorization.md
45
45
  - docs/encrypted-ids.md
46
+ - docs/keyset-connections.md
46
47
  - docs/persisted-queries.md
47
48
  - docs/rate-limiting.md
48
49
  - docs/telemetry.md
@@ -55,13 +56,26 @@ files:
55
56
  - lib/graphql/armory/authorization/adapters/substitute.rb
56
57
  - lib/graphql/armory/authorization/audit.rb
57
58
  - lib/graphql/armory/authorization/audit/command.rb
59
+ - lib/graphql/armory/authorization/audit/denial_hooks.rb
60
+ - lib/graphql/armory/authorization/audit/edge_rules.rb
61
+ - lib/graphql/armory/authorization/audit/findings.rb
62
+ - lib/graphql/armory/authorization/audit/foreign_policies.rb
63
+ - lib/graphql/armory/authorization/audit/input_loads.rb
64
+ - lib/graphql/armory/authorization/audit/interface_rules.rb
65
+ - lib/graphql/armory/authorization/audit/introspection_fields.rb
66
+ - lib/graphql/armory/authorization/audit/library_methods.rb
67
+ - lib/graphql/armory/authorization/audit/overrides.rb
68
+ - lib/graphql/armory/authorization/audit/own_checks.rb
58
69
  - lib/graphql/armory/authorization/audit/report.rb
70
+ - lib/graphql/armory/authorization/audit/type_rules.rb
71
+ - lib/graphql/armory/authorization/audit/visibility_models.rb
59
72
  - lib/graphql/armory/authorization/authorize.rb
60
73
  - lib/graphql/armory/authorization/configuration.rb
61
74
  - lib/graphql/armory/authorization/controls/actor.rb
62
75
  - lib/graphql/armory/authorization/controls/context.rb
63
76
  - lib/graphql/armory/authorization/controls/rule.rb
64
77
  - lib/graphql/armory/authorization/controls/subject.rb
78
+ - lib/graphql/armory/authorization/definitions.rb
65
79
  - lib/graphql/armory/authorization/errors.rb
66
80
  - lib/graphql/armory/authorization/integration.rb
67
81
  - lib/graphql/armory/authorization/integration/argument.rb
@@ -84,6 +98,8 @@ files:
84
98
  - lib/graphql/armory/encoder/versioned.rb
85
99
  - lib/graphql/armory/ids.rb
86
100
  - lib/graphql/armory/ids/controls.rb
101
+ - lib/graphql/armory/keyset.rb
102
+ - lib/graphql/armory/keyset/controls.rb
87
103
  - lib/graphql/armory/persisted_queries.rb
88
104
  - lib/graphql/armory/persisted_queries/controls.rb
89
105
  - lib/graphql/armory/persisted_queries/manifest.rb