forest_liana 9.22.18 → 9.22.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d2876bbcc3a687f4bbb73e23af6d9ca98e91ebce886c749afdcca20eb2fc0bed
4
- data.tar.gz: 2c2fcda6f31a2a176caab533e30e89fbea88f3dd8fbc9e870ffe9a29019e2284
3
+ metadata.gz: 40f4ba483ce36ae181d7065df01a5d9b2984d70d3f4020c0f4079afaa95c6cce
4
+ data.tar.gz: 5fbe9bf4fd893807d7b0d1df3fe01abb5a2c0146d7970dd1ca9d3f942002ff1f
5
5
  SHA512:
6
- metadata.gz: 7ddfedbe5559ec9b55d869fec7e56e61f9e0560d574fd66d035180bb98e39bae8351739346f86d4faf720e07530c21d858660c0cfc8ae9a054d6ab3780d7088f
7
- data.tar.gz: 12be328781a0a455c042c23668e3f3ca6946b437832f620398d97e7bc4bbd29d65733ff3f28b87dc7596e82e35539ed0eaff6f6a82efbb06015c7a7f82f39b1d
6
+ metadata.gz: 9131cea95f456d1f6dd4c792fdafb25d7e7348588fe612de6df1fdd5c8aa2592039608571d957a121bf859955c6f67f060e719332936f97863bf3f7b0d9d5771
7
+ data.tar.gz: 2e1c398ffac85a0a50da4f10c7ce4a9dd3c164394b28f91cee3b29274f5812f7eed44f51b96d59d47444c43e525934881cb39d9d399feda23c11792be7db2617
@@ -57,17 +57,37 @@ module ForestLiana
57
57
  def serialize_model(record, options = {})
58
58
  options[:is_collection] = false
59
59
  options[:context] = { unoptimized: options[:fields].nil? }.merge(options[:context] || {})
60
+ readable = polymorphic_target_readable
61
+ options[:context][:polymorphic_target_readable] ||= readable if readable
60
62
 
61
63
  json = ForestAdmin::JSONAPI::Serializer.serialize(record, options)
62
64
 
63
65
  force_utf8_encoding(json)
64
66
  end
65
67
 
68
+ # The read check passes on the targets a polymorphic relation declares, yet a row may point at
69
+ # any model: the target each row actually points at is checked too, before it is serialized.
70
+ def polymorphic_target_readable
71
+ return unless forest_user && respond_to?(:readable_collection?, true)
72
+
73
+ @polymorphic_target_readable ||= lambda do |relation, target|
74
+ checked = SchemaUtils.polymorphic_models(relation).find { |model| target.is_a?(model) }
75
+ readable_collection?(forest_user, ForestLiana.name_for(checked || target.class))
76
+ rescue ForestLiana::Errors::PermissionsUnavailableError
77
+ # A CSV row is serialized after its 200 went out: withholding the target beats truncating
78
+ # the file.
79
+ FOREST_LOGGER.warn "Polymorphic target withheld, its read permission being unavailable: #{target.class.name}"
80
+ false
81
+ end
82
+ end
83
+
66
84
  def serialize_models(records, options = {}, fields_searched = [])
67
85
  options[:is_collection] = true
68
86
  if options[:fields].nil?
69
87
  options[:context] = { unoptimized: true }.merge(options[:context] || {})
70
88
  end
89
+ readable = polymorphic_target_readable
90
+ options[:context] = (options[:context] || {}).merge(polymorphic_target_readable: readable) if readable
71
91
 
72
92
  json = ForestAdmin::JSONAPI::Serializer.serialize(records, options)
73
93
 
@@ -317,6 +337,9 @@ module ForestLiana
317
337
  # column instead of 403ing the file whenever it doesn't error there either.
318
338
  requested_fields = fields_per_model(params[:fields], model)
319
339
  fields_to_serialize = redact_fields(forest_user, model, requested_fields, named_collections: [])
340
+ # The rows are serialized while the response streams, once the request cache is gone: the
341
+ # read permission of every model a polymorphic row may point at is answered now.
342
+ read_permissions(forest_user, ForestLiana.models.map { |candidate| ForestLiana.name_for(candidate) })
320
343
 
321
344
  set_headers_file
322
345
  set_headers_streaming
@@ -353,6 +376,11 @@ module ForestLiana
353
376
  elsif record_relationships[field_name] &&
354
377
  record_relationships[field_name]['data']
355
378
  relationship_id = record_relationships[field_name]['data']['id']
379
+ # The front names the reference field first, then any sub-field a segment condition
380
+ # reads; it names none for a polymorphic relation, whose export falls back to the id.
381
+ reference_field = params[:fields][field_name].to_s.split(',').first
382
+ next relationship_id if reference_field.blank?
383
+
356
384
  relationship_type = record_relationships[field_name]['data']['type']
357
385
  relationship_object = included.select do |object|
358
386
  object['id'] == relationship_id && object['type'] == relationship_type
@@ -360,7 +388,7 @@ module ForestLiana
360
388
 
361
389
  relationship_object = relationship_object.first
362
390
  if relationship_object && relationship_object['attributes']
363
- relationship_object['attributes'][params[:fields][field_name]]
391
+ relationship_object['attributes'][reference_field]
364
392
  else
365
393
  nil
366
394
  end
@@ -407,7 +407,9 @@ module ForestLiana
407
407
  serializer.send(serializer_association(a), a.name) {
408
408
  if [:has_one, :belongs_to].include?(a.macro)
409
409
  begin
410
- object.send(a.name)
410
+ target = object.send(a.name)
411
+ readable = @context[:polymorphic_target_readable]
412
+ target && readable && !readable.call(a, target) ? nil : target
411
413
  rescue ActiveRecord::RecordNotFound
412
414
  nil
413
415
  end
@@ -66,6 +66,12 @@ module ForestLiana
66
66
  SmartActionChecker.new(parameters, nil, smart_action, user_data, schema_action.type, user).can_execute?
67
67
  end
68
68
 
69
+ # Asked once per serialized row: a collection already answered allocates nothing.
70
+ def readable_collection?(user, collection_name)
71
+ read_permissions(user, [collection_name]) unless @read_permissions_cache&.key?(collection_name)
72
+ @read_permissions_cache[collection_name]
73
+ end
74
+
69
75
  # +refetch+ drops the cached permissions first. Only a caller about to refuse on a denial asks
70
76
  # for it (a stale, up to TTL-old cache may sit behind a permission granted moments ago): the
71
77
  # refetch rewrites the cluster-wide `forest.collections` entry and this request's copy, so a
@@ -27,8 +27,12 @@ module ForestLiana
27
27
  if @data.nil?
28
28
  new_value = nil
29
29
  else
30
- association_klass = SchemaUtils.polymorphic_models(@association).select { |a| a.name == @data[:type] }.first
31
- new_value = association_klass.find(@data[:id]) if @data && @data[:id]
30
+ association_klass = SchemaUtils.polymorphic_models(@association).find { |model| model.name == @data[:type] }
31
+ unless association_klass
32
+ raise ForestLiana::Errors::HTTP422Error.new("#{@data[:type]} is not a target of #{@association.name}")
33
+ end
34
+
35
+ new_value = association_klass.find(@data[:id]) if @data[:id]
32
36
  end
33
37
  else
34
38
  new_value = @association.klass.find(@data[:id]) if @data && @data[:id]
@@ -315,14 +315,7 @@ module ForestLiana
315
315
  end
316
316
 
317
317
  def get_polymorphic_types(relation)
318
- types = []
319
- ForestLiana.models.each do |model|
320
- unless model.reflect_on_all_associations.select { |association| association.options[:as] == relation.name.to_sym }.empty?
321
- types << model.name
322
- end
323
- end
324
-
325
- types
318
+ SchemaUtils.polymorphic_models(relation).map(&:name)
326
319
  end
327
320
 
328
321
  def automatic_inverse_of(association)
@@ -94,15 +94,34 @@ module ForestLiana
94
94
 
95
95
  end
96
96
 
97
+ # Keyed on the reflection itself, not [owner, name]: a hit must not allocate (see LookupCache).
97
98
  def self.polymorphic_models(relation)
98
- name = relation.name.to_sym
99
- LookupCache.fetch(:polymorphic_models, name) { scan_polymorphic_models(name).freeze }
99
+ LookupCache.fetch(:polymorphic_models, relation) { scan_polymorphic_models(relation).freeze }
100
100
  end
101
101
 
102
- def self.scan_polymorphic_models(name)
103
- ForestLiana.models.select do |model|
104
- model.reflect_on_all_associations.any? { |association| association.options[:as] == name }
102
+ # A relation whose real targets declare no inverse falls back to the namesakes' targets, the
103
+ # only ones it ever had: an empty list would drop it from every response.
104
+ def self.scan_polymorphic_models(relation)
105
+ name = relation.name.to_sym
106
+ owner = relation.active_record
107
+
108
+ inverses = ForestLiana.models.each_with_object({}) do |model, acc|
109
+ matching = model.reflect_on_all_associations.select { |association| association.options[:as] == name }
110
+ acc[model] = matching if matching.any?
105
111
  end
112
+
113
+ owned = inverses.select { |_model, associations| associations.any? { |association| targets_owner?(association, owner) } }.keys
114
+ owned.empty? ? inverses.keys : owned
115
+ end
116
+
117
+ # Both directions for STI: the belongs_to may sit on a subclass while the inverse targets the
118
+ # base class, or the other way round.
119
+ def self.targets_owner?(association, owner)
120
+ target = association.klass
121
+ target <= owner || owner <= target
122
+ rescue NameError
123
+ FOREST_LOGGER.warn "Unknown association #{association.name} on class #{association.active_record.name}"
124
+ false
106
125
  end
107
126
 
108
127
 
@@ -1,3 +1,3 @@
1
1
  module ForestLiana
2
- VERSION = "9.22.18"
2
+ VERSION = "9.22.19"
3
3
  end
@@ -64,27 +64,36 @@ describe 'Lookups by name over the schema' do
64
64
  let(:addressable) { Address.reflect_on_association(:addressable) }
65
65
 
66
66
  it 'scans the models once for repeated lookups of a relation' do
67
- expect(ForestLiana::SchemaUtils).to receive(:scan_polymorphic_models).with(:addressable).once.and_call_original
67
+ expect(ForestLiana::SchemaUtils).to receive(:scan_polymorphic_models).with(addressable).once.and_call_original
68
68
 
69
69
  3.times { expect(ForestLiana::SchemaUtils.polymorphic_models(addressable)).to eq [User] }
70
70
  end
71
71
 
72
+ it 'answers a remembered relation without allocating' do
73
+ ForestLiana::SchemaUtils.polymorphic_models(addressable)
74
+
75
+ allocated = GC.stat(:total_allocated_objects)
76
+ 1_000.times { ForestLiana::SchemaUtils.polymorphic_models(addressable) }
77
+
78
+ expect(GC.stat(:total_allocated_objects) - allocated).to be < 100
79
+ end
80
+
72
81
  it 'returns a frozen list' do
73
82
  expect(ForestLiana::SchemaUtils.polymorphic_models(addressable)).to be_frozen
74
83
  end
75
84
 
76
85
  it 'remembers a relation no model targets' do
77
- orphan = double(name: :orphan)
78
- expect(ForestLiana::SchemaUtils).to receive(:scan_polymorphic_models).with(:orphan).once.and_call_original
86
+ orphan = double(name: :orphan, active_record: Address)
87
+ expect(ForestLiana::SchemaUtils).to receive(:scan_polymorphic_models).with(orphan).once.and_call_original
79
88
 
80
89
  2.times { expect(ForestLiana::SchemaUtils.polymorphic_models(orphan)).to eq [] }
81
90
  end
82
91
 
83
92
  it 'finds a target added to the models after a first lookup' do
84
- target = Class.new(ActiveRecord::Base) do
93
+ target = stub_const('AddressableTree', Class.new(ActiveRecord::Base) do
85
94
  self.table_name = 'trees'
86
95
  has_many :addresses, as: :addressable
87
- end
96
+ end)
88
97
  expect(ForestLiana::SchemaUtils.polymorphic_models(addressable)).to eq [User]
89
98
 
90
99
  ForestLiana.models << target
@@ -0,0 +1,59 @@
1
+ require 'rails_helper'
2
+
3
+ describe 'Exporting a belongsTo to CSV', type: :request do
4
+ let(:auth_headers) do
5
+ token = JWT.encode({ id: 1, email: 'michael.kelso@that70.show', first_name: 'Michael',
6
+ last_name: 'Kelso', team: 'Operations', rendering_id: 16,
7
+ exp: Time.now.to_i + 2.weeks.to_i, permission_level: 'admin' },
8
+ ForestLiana.auth_secret, 'HS256')
9
+ { 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{token}" }
10
+ end
11
+
12
+ let!(:owner) { User.create!(name: 'Michel') }
13
+ let!(:tree) { Tree.create!(name: 'Lemon Tree', owner: owner, cutter: owner) }
14
+
15
+ before do
16
+ Rails.cache.clear
17
+ Rails.cache.write('forest.users', { '1' => { 'id' => 1, 'roleId' => 1, 'rendering_id' => '1' } })
18
+ Rails.cache.write('forest.has_permission', true)
19
+ enabled = { 'roles' => [1] }
20
+ allow_any_instance_of(ForestLiana::Ability::Fetch).to receive(:get_permissions)
21
+ .with('/liana/v4/permissions/environment').and_return(
22
+ 'collections' => %w[Tree User].to_h do |name|
23
+ [name, { 'collection' => %w[browseEnabled readEnabled editEnabled addEnabled deleteEnabled exportEnabled]
24
+ .to_h { |key| [key, enabled] }, 'actions' => {} }]
25
+ end
26
+ )
27
+
28
+ allow(ForestLiana::IpWhitelist).to receive(:retrieve) { true }
29
+ allow(ForestLiana::IpWhitelist).to receive(:is_ip_whitelist_retrieved) { true }
30
+ allow(ForestLiana::IpWhitelist).to receive(:is_ip_valid) { true }
31
+ allow_any_instance_of(ForestLiana::Ability).to receive(:forest_authorize!) { true }
32
+ allow(ForestLiana::ScopeManager).to receive(:fetch_scopes)
33
+ .and_return('scopes' => {}, 'team' => { 'id' => '1', 'name' => 'Operations' })
34
+ end
35
+
36
+ after do
37
+ Tree.destroy_all
38
+ User.destroy_all
39
+ end
40
+
41
+ def export(owner_fields)
42
+ get '/forest/Tree.csv',
43
+ params: { fields: { 'Tree' => 'id,name,owner', 'owner' => owner_fields },
44
+ header: 'id,name,owner', timezone: 'Europe/Paris' },
45
+ headers: auth_headers
46
+
47
+ expect(response.status).to eq(200)
48
+ response.body.lines.second.strip
49
+ end
50
+
51
+ it 'exports the reference field of the target' do
52
+ expect(export('name')).to eq("#{tree.id},Lemon Tree,Michel")
53
+ end
54
+
55
+ # A basic segment condition on another sub-field of the relation adds it after the reference field.
56
+ it 'exports the reference field when the front also names other sub-fields' do
57
+ expect(export('name,title')).to eq("#{tree.id},Lemon Tree,Michel")
58
+ end
59
+ end
@@ -0,0 +1,98 @@
1
+ require 'rails_helper'
2
+
3
+ # PRD-2267: a polymorphic relation was given the targets of every namesake on another owner, so a
4
+ # role reading its real targets still saw it refused.
5
+ describe 'A polymorphic relation sharing its name with another owner\'s', type: :request do
6
+ token = JWT.encode({ id: 1, email: 'michael.kelso@that70.show', first_name: 'Michael',
7
+ last_name: 'Kelso', team: 'Operations', rendering_id: 16,
8
+ exp: Time.now.to_i + 2.weeks.to_i, permission_level: 'admin' },
9
+ ForestLiana.auth_secret, 'HS256')
10
+ headers = { 'Accept' => 'application/json', 'Content-Type' => 'application/json',
11
+ 'Authorization' => "Bearer #{token}" }
12
+
13
+ let!(:user) { User.create!(name: 'Michel') }
14
+ let!(:address) { Address.create!(line1: '1 Palm Street', city: 'Papeete', zipcode: '98713', addressable: user) }
15
+ let(:namesakes) do
16
+ [
17
+ stub_const('PolyNote', Class.new(ActiveRecord::Base) do
18
+ self.table_name = 'articles'
19
+ belongs_to :addressable, polymorphic: true
20
+ end),
21
+ stub_const('PolyHarbor', Class.new(ActiveRecord::Base) do
22
+ self.table_name = 'harbors'
23
+ has_many :poly_notes, as: :addressable
24
+ end)
25
+ ]
26
+ end
27
+
28
+ before do
29
+ # Rails 6.1 remembers the class a name resolved to, across examples.
30
+ ActiveSupport::Dependencies::Reference.clear! if defined?(ActiveSupport::Dependencies::Reference)
31
+ ForestLiana.models.push(*namesakes)
32
+
33
+ Rails.cache.clear
34
+ Rails.cache.write('forest.users', { '1' => { 'id' => 1, 'roleId' => 1, 'rendering_id' => '1' } })
35
+ Rails.cache.write('forest.has_permission', true)
36
+ enabled = { 'roles' => [1] }
37
+ allow_any_instance_of(ForestLiana::Ability::Fetch).to receive(:get_permissions)
38
+ .with('/liana/v4/permissions/environment').and_return(
39
+ 'collections' => %w[Address User].to_h do |name|
40
+ [name, { 'collection' => %w[browseEnabled readEnabled editEnabled addEnabled deleteEnabled exportEnabled]
41
+ .to_h { |key| [key, enabled] }, 'actions' => {} }]
42
+ end
43
+ )
44
+
45
+ allow(ForestLiana::IpWhitelist).to receive(:retrieve) { true }
46
+ allow(ForestLiana::IpWhitelist).to receive(:is_ip_whitelist_retrieved) { true }
47
+ allow(ForestLiana::IpWhitelist).to receive(:is_ip_valid) { true }
48
+ allow_any_instance_of(ForestLiana::Ability).to receive(:forest_authorize!) { true }
49
+ allow(ForestLiana::ScopeManager).to receive(:fetch_scopes)
50
+ .and_return('scopes' => {}, 'team' => { 'id' => '1', 'name' => 'Operations' })
51
+ end
52
+
53
+ after do
54
+ namesakes.each { |model| ForestLiana.models.delete(model) }
55
+ Address.destroy_all
56
+ User.destroy_all
57
+ end
58
+
59
+ it 'serves the relation to a role that reads its own targets' do
60
+ get "/forest/Address/#{address.id}",
61
+ params: { fields: { 'Address' => 'id,line1,addressable', 'addressable' => 'id' }, timezone: 'Europe/Paris' },
62
+ headers: headers
63
+
64
+ expect(response.status).to eq(200)
65
+ relationship = JSON.parse(response.body)['data']['relationships']['addressable']
66
+ expect(relationship['data']).to include('id' => user.id.to_s)
67
+ end
68
+
69
+ it 'keeps the relation column in the CSV export' do
70
+ get '/forest/Address.csv',
71
+ params: { fields: { 'Address' => 'id,line1,addressable', 'addressable' => 'id' },
72
+ header: 'id,line1,addressable', timezone: 'Europe/Paris' },
73
+ headers: headers
74
+
75
+ expect(response.status).to eq(200)
76
+ expect(response.body.lines.first.strip).to eq('id,line1,addressable')
77
+ end
78
+
79
+ it 'exports the id of the target, as the list shows it, when no field of the target is named' do
80
+ get '/forest/Address.csv',
81
+ params: { fields: { 'Address' => 'id,line1,addressable' },
82
+ header: 'id,line1,addressable', timezone: 'Europe/Paris' },
83
+ headers: headers
84
+
85
+ expect(response.status).to eq(200)
86
+ expect(response.body.lines.second.strip).to eq("#{address.id},1 Palm Street,#{user.id}")
87
+ end
88
+
89
+ it 'still exports the named field of the target' do
90
+ get '/forest/Address.csv',
91
+ params: { fields: { 'Address' => 'id,line1,addressable', 'addressable' => 'name' },
92
+ header: 'id,line1,addressable', timezone: 'Europe/Paris' },
93
+ headers: headers
94
+
95
+ expect(response.status).to eq(200)
96
+ expect(response.body.lines.second.strip).to eq("#{address.id},1 Palm Street,Michel")
97
+ end
98
+ end
@@ -0,0 +1,115 @@
1
+ require 'rails_helper'
2
+
3
+ # Rails does not require the targets of a polymorphic relation to declare an inverse, so a row may
4
+ # point at a model the relation's read check never covered.
5
+ describe 'Serving the target a polymorphic relation points at', type: :request do
6
+ let(:auth_headers) do
7
+ token = JWT.encode({ id: 1, email: 'michael.kelso@that70.show', first_name: 'Michael',
8
+ last_name: 'Kelso', team: 'Operations', rendering_id: 16,
9
+ exp: Time.now.to_i + 2.weeks.to_i, permission_level: 'admin' },
10
+ ForestLiana.auth_secret, 'HS256')
11
+ { 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{token}" }
12
+ end
13
+
14
+ let(:readable) { %w[Address User] }
15
+ let!(:user) { User.create!(name: 'Michel') }
16
+ let!(:island) { Island.create!(name: 'Lemon Island') }
17
+ let!(:to_user) { Address.create!(line1: '1 Palm Street', city: 'Papeete', zipcode: '98713', addressable: user) }
18
+ let!(:to_island) { Address.create!(line1: '2 Palm Street', city: 'Papeete', zipcode: '98713', addressable: island) }
19
+
20
+ before do
21
+ Rails.cache.clear
22
+ Rails.cache.write('forest.users', { '1' => { 'id' => 1, 'roleId' => 1, 'rendering_id' => '1' } })
23
+ Rails.cache.write('forest.has_permission', true)
24
+ enabled = { 'roles' => [1] }
25
+ allow_any_instance_of(ForestLiana::Ability::Fetch).to receive(:get_permissions)
26
+ .with('/liana/v4/permissions/environment').and_return(
27
+ 'collections' => readable.to_h do |name|
28
+ [name, { 'collection' => %w[browseEnabled readEnabled editEnabled addEnabled deleteEnabled exportEnabled]
29
+ .to_h { |key| [key, enabled] }, 'actions' => {} }]
30
+ end
31
+ )
32
+
33
+ allow(ForestLiana::IpWhitelist).to receive(:retrieve) { true }
34
+ allow(ForestLiana::IpWhitelist).to receive(:is_ip_whitelist_retrieved) { true }
35
+ allow(ForestLiana::IpWhitelist).to receive(:is_ip_valid) { true }
36
+ allow_any_instance_of(ForestLiana::Ability).to receive(:forest_authorize!) { true }
37
+ allow(ForestLiana::ScopeManager).to receive(:fetch_scopes)
38
+ .and_return('scopes' => {}, 'team' => { 'id' => '1', 'name' => 'Operations' })
39
+ end
40
+
41
+ after do
42
+ Rails.cache.clear
43
+ Address.destroy_all
44
+ Island.destroy_all
45
+ User.destroy_all
46
+ end
47
+
48
+ def get_one(address)
49
+ get "/forest/Address/#{address.id}",
50
+ params: { fields: { 'Address' => 'id,line1,addressable', 'addressable' => 'id' }, timezone: 'Europe/Paris' },
51
+ headers: auth_headers
52
+ expect(response.status).to eq(200)
53
+ JSON.parse(response.body)
54
+ end
55
+
56
+ def served_addressable(body)
57
+ body['data'].dig('relationships', 'addressable', 'data')
58
+ end
59
+
60
+ def export_rows
61
+ get '/forest/Address.csv',
62
+ params: { fields: { 'Address' => 'id,addressable' }, header: 'id,addressable', timezone: 'Europe/Paris' },
63
+ headers: auth_headers
64
+ expect(response.status).to eq(200)
65
+ response.body.lines.drop(1).map(&:strip)
66
+ end
67
+
68
+ it 'serves a target of a model the relation declares' do
69
+ expect(served_addressable(get_one(to_user))).to include('type' => 'User', 'id' => user.id.to_s)
70
+ end
71
+
72
+ it 'withholds a target of a model the role cannot read, though the relation never declared it' do
73
+ body = get_one(to_island)
74
+
75
+ expect(served_addressable(body)).to be_nil
76
+ expect(body.fetch('included', [])).to be_empty
77
+ end
78
+
79
+ context 'when the role reads that model' do
80
+ let(:readable) { %w[Address User Island] }
81
+
82
+ it 'serves the target' do
83
+ expect(served_addressable(get_one(to_island))).to include('type' => 'Island', 'id' => island.id.to_s)
84
+ end
85
+ end
86
+
87
+ context 'with skip_relation_read_permissions' do
88
+ before { allow(ForestLiana).to receive(:skip_relation_read_permissions?).and_return(true) }
89
+
90
+ it 'serves a target of any exposed model' do
91
+ expect(served_addressable(get_one(to_island))).to include('type' => 'Island', 'id' => island.id.to_s)
92
+ end
93
+ end
94
+
95
+ it 'leaves the cell of a withheld target empty in the CSV export' do
96
+ expect(export_rows).to contain_exactly("#{to_user.id},#{user.id}", "#{to_island.id},")
97
+ end
98
+
99
+ # The rows of an export are serialized while the response streams, after the request cache is
100
+ # gone: a permission asked for then could reach the Forest API mid-file.
101
+ it 'answers the read permission of every model before the CSV export streams' do
102
+ expect_any_instance_of(ForestLiana::ResourcesController).to receive(:read_permissions)
103
+ .with(anything, array_including('Island', 'User')).and_call_original
104
+ allow_any_instance_of(ForestLiana::ResourcesController).to receive(:read_permissions).and_call_original
105
+
106
+ export_rows
107
+ end
108
+
109
+ it 'withholds the target rather than failing when its read permission is unavailable' do
110
+ allow_any_instance_of(ForestLiana::ResourcesController).to receive(:readable_collection?)
111
+ .and_raise(ForestLiana::Errors::PermissionsUnavailableError)
112
+
113
+ expect(export_rows).to contain_exactly("#{to_user.id},", "#{to_island.id},")
114
+ end
115
+ end
@@ -19,6 +19,11 @@ describe 'Requesting resources with the Forest-Projection header', :type => :req
19
19
  allow_any_instance_of(ForestLiana::Ability).to receive(:forest_authorize!) { true }
20
20
  allow(ForestLiana::ScopeManager).to receive(:fetch_scopes)
21
21
  .and_return({ 'scopes' => {}, 'team' => { 'id' => '1', 'name' => 'Operations' } })
22
+
23
+ # The permissions another spec left in Rails.cache would otherwise decide these requests.
24
+ Rails.cache.clear
25
+ allow_any_instance_of(ForestLiana::Ability::Fetch).to receive(:get_permissions)
26
+ .with('/liana/v4/permissions/environment').and_return(true)
22
27
  end
23
28
 
24
29
  let(:auth_headers) do
@@ -31,5 +31,40 @@ module ForestLiana
31
31
  expect(described_class.replaces_destructively?(association)).to be false
32
32
  end
33
33
  end
34
+
35
+ describe '#perform on a polymorphic relation' do
36
+ let!(:user) { User.create!(name: 'Michel') }
37
+ let!(:address) { Address.create!(line1: '1 Palm Street', city: 'Papeete', zipcode: '98713', addressable: user) }
38
+ let(:addressable) { Address.reflect_on_association(:addressable) }
39
+
40
+ after do
41
+ Address.destroy_all
42
+ User.destroy_all
43
+ end
44
+
45
+ def perform(type, id)
46
+ updater = described_class.new(Address, addressable, { id: address.id.to_s, 'data' => { type: type, id: id.to_s } })
47
+ updater.perform
48
+ updater
49
+ end
50
+
51
+ it 'links a target of the relation' do
52
+ other = User.create!(name: 'Kelso')
53
+
54
+ expect(perform('User', other.id).errors).to be_nil
55
+ expect(address.reload.addressable).to eq other
56
+ end
57
+
58
+ # A front still holding a schema generated before the relation lost its namesakes' targets
59
+ # offers them.
60
+ it 'refuses a model that is not a target of the relation, with a message naming it' do
61
+ island = Island.create!(name: 'Lemon Island')
62
+
63
+ expect(perform('Island', island.id).errors).to eq [{ detail: 'Island is not a target of addressable' }]
64
+ expect(address.reload.addressable).to eq user
65
+ ensure
66
+ Island.destroy_all
67
+ end
68
+ end
34
69
  end
35
70
  end
@@ -340,6 +340,9 @@ module ForestLiana
340
340
  before do
341
341
  # temporarily add a polymorphic association on Tree
342
342
  Tree.class_eval { belongs_to :addressable, polymorphic: true, optional: true }
343
+ allow(SchemaUtils).to receive(:polymorphic_models).and_call_original
344
+ allow(SchemaUtils).to receive(:polymorphic_models)
345
+ .with(Tree.reflect_on_association(:addressable)).and_return([User, Island])
343
346
 
344
347
  allow_any_instance_of(described_class).to receive(:prepare_query).and_return(nil)
345
348
  allow(ForestLiana).to receive(:name_for).and_return('trees')
@@ -52,6 +52,27 @@ module ForestLiana
52
52
  )
53
53
  end
54
54
 
55
+ it 'leaves out the targets of another owner with a relation of the same name' do
56
+ # Rails 6.1 remembers the class a name resolved to, across examples.
57
+ ActiveSupport::Dependencies::Reference.clear! if defined?(ActiveSupport::Dependencies::Reference)
58
+ note = stub_const('PolyNote', Class.new(ActiveRecord::Base) do
59
+ self.table_name = 'articles'
60
+ belongs_to :addressable, polymorphic: true
61
+ end)
62
+ harbor = stub_const('PolyHarbor', Class.new(ActiveRecord::Base) do
63
+ self.table_name = 'harbors'
64
+ has_many :poly_notes, as: :addressable
65
+ end)
66
+ ForestLiana.models.push(note, harbor)
67
+ adapter = described_class.new(Address)
68
+
69
+ expect(adapter.send(:get_polymorphic_types, Address.reflect_on_association(:addressable))).to eq ['User']
70
+ expect(adapter.send(:get_polymorphic_types, note.reflect_on_association(:addressable))).to eq ['PolyHarbor']
71
+ ensure
72
+ ForestLiana.models.delete(note)
73
+ ForestLiana.models.delete(harbor)
74
+ end
75
+
55
76
  it 'should remove the polymorphic attributes(_id and _type)' do
56
77
  collection = ForestLiana.apimap.find do |object|
57
78
  object.name.to_s == ForestLiana.name_for(Address)
@@ -53,5 +53,84 @@ module ForestLiana
53
53
  expect(field).to include(is_filterable: true, is_sortable: true)
54
54
  end
55
55
  end
56
+
57
+ describe '.polymorphic_models' do
58
+ let(:declared) { [] }
59
+
60
+ def declare(name, superclass = ActiveRecord::Base, &body)
61
+ model = stub_const(name, Class.new(superclass, &body))
62
+ ForestLiana.models << model
63
+ declared << model
64
+ model
65
+ end
66
+
67
+ # Rails 6.1 remembers the class a name resolved to, across examples: PolyNote would resolve to
68
+ # the class an earlier example declared under that name.
69
+ before { ActiveSupport::Dependencies::Reference.clear! if defined?(ActiveSupport::Dependencies::Reference) }
70
+
71
+ after { declared.each { |model| ForestLiana.models.delete(model) } }
72
+
73
+ def targets(model, relation = :addressable)
74
+ described_class.polymorphic_models(model.reflect_on_association(relation))
75
+ end
76
+
77
+ it 'keeps the targets of another owner with a polymorphic relation of the same name apart' do
78
+ note = declare('PolyNote') do
79
+ self.table_name = 'articles'
80
+ belongs_to :addressable, polymorphic: true
81
+ end
82
+ harbor = declare('PolyHarbor') do
83
+ self.table_name = 'harbors'
84
+ has_many :poly_notes, as: :addressable
85
+ end
86
+
87
+ expect(targets(Address)).to eq [User]
88
+ expect(targets(note)).to eq [harbor]
89
+ end
90
+
91
+ it 'falls back to the targets of its namesakes when none of them points back at the owner' do
92
+ note = declare('PolyNote') do
93
+ self.table_name = 'articles'
94
+ belongs_to :addressable, polymorphic: true
95
+ end
96
+
97
+ expect(targets(note)).to eq [User]
98
+ end
99
+
100
+ it 'finds a target whose inverse points at the base class of an STI owner' do
101
+ declare('PolyStop') { self.table_name = 'locations' }
102
+ bus_stop = declare('PolyBusStop', PolyStop) { belongs_to :addressable, polymorphic: true }
103
+ harbor = declare('PolyHarbor') do
104
+ self.table_name = 'harbors'
105
+ has_many :poly_stops, as: :addressable
106
+ end
107
+
108
+ expect(targets(bus_stop)).to eq [harbor]
109
+ end
110
+
111
+ it 'finds a target whose inverse points at a subclass of an STI owner' do
112
+ stop = declare('PolyStop') do
113
+ self.table_name = 'locations'
114
+ belongs_to :addressable, polymorphic: true
115
+ end
116
+ declare('PolyBusStop', stop)
117
+ harbor = declare('PolyHarbor') do
118
+ self.table_name = 'harbors'
119
+ has_many :poly_bus_stops, as: :addressable
120
+ end
121
+
122
+ expect(targets(stop)).to eq [harbor]
123
+ end
124
+
125
+ it 'skips a target whose inverse names a class that does not exist, with a warning' do
126
+ declare('PolyHarbor') do
127
+ self.table_name = 'harbors'
128
+ has_many :poly_ghosts, as: :addressable
129
+ end
130
+
131
+ expect(FOREST_LOGGER).to receive(:warn).with(/poly_ghosts on class PolyHarbor/)
132
+ expect(targets(Address)).to eq [User]
133
+ end
134
+ end
56
135
  end
57
136
  end
metadata CHANGED
@@ -1,14 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: forest_liana
3
3
  version: !ruby/object:Gem::Version
4
- version: 9.22.18
4
+ version: 9.22.19
5
5
  platform: ruby
6
6
  authors:
7
7
  - Sandro Munda
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2026-11-03 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
13
  name: rails
@@ -487,9 +486,12 @@ files:
487
486
  - spec/requests/capabilities_spec.rb
488
487
  - spec/requests/cors_spec.rb
489
488
  - spec/requests/count_spec.rb
489
+ - spec/requests/csv_export_relation_spec.rb
490
490
  - spec/requests/devise_controller_spec.rb
491
491
  - spec/requests/missing_attribute_valve_spec.rb
492
492
  - spec/requests/permissions_cache_footprint_spec.rb
493
+ - spec/requests/polymorphic_relation_namesake_spec.rb
494
+ - spec/requests/polymorphic_target_read_check_spec.rb
493
495
  - spec/requests/projection_header_spec.rb
494
496
  - spec/requests/projection_inherited_loads_spec.rb
495
497
  - spec/requests/query_footprint_spec.rb
@@ -637,7 +639,6 @@ homepage: https://github.com/ForestAdmin/forest-rails
637
639
  licenses:
638
640
  - Apache-2.0
639
641
  metadata: {}
640
- post_install_message:
641
642
  rdoc_options: []
642
643
  require_paths:
643
644
  - lib
@@ -652,97 +653,10 @@ required_rubygems_version: !ruby/object:Gem::Requirement
652
653
  - !ruby/object:Gem::Version
653
654
  version: '0'
654
655
  requirements: []
655
- rubygems_version: 3.4.20
656
- signing_key:
656
+ rubygems_version: 3.6.7
657
657
  specification_version: 4
658
658
  summary: Official Rails Liana for Forest
659
659
  test_files:
660
- - test/dummy/README.rdoc
661
- - test/dummy/Rakefile
662
- - test/dummy/app/assets/config/manifest.js
663
- - test/dummy/app/assets/javascripts/application.js
664
- - test/dummy/app/assets/stylesheets/application.css
665
- - test/dummy/app/controllers/application_controller.rb
666
- - test/dummy/app/helpers/application_helper.rb
667
- - test/dummy/app/models/belongs_to_class_name_field.rb
668
- - test/dummy/app/models/belongs_to_field.rb
669
- - test/dummy/app/models/boolean_field.rb
670
- - test/dummy/app/models/date_field.rb
671
- - test/dummy/app/models/decimal_field.rb
672
- - test/dummy/app/models/float_field.rb
673
- - test/dummy/app/models/has_and_belongs_to_many_field.rb
674
- - test/dummy/app/models/has_many_class_name_field.rb
675
- - test/dummy/app/models/has_many_field.rb
676
- - test/dummy/app/models/has_many_through_field.rb
677
- - test/dummy/app/models/has_one_field.rb
678
- - test/dummy/app/models/integer_field.rb
679
- - test/dummy/app/models/owner.rb
680
- - test/dummy/app/models/polymorphic_field.rb
681
- - test/dummy/app/models/reference.rb
682
- - test/dummy/app/models/serialize_field.rb
683
- - test/dummy/app/models/string_field.rb
684
- - test/dummy/app/models/tree.rb
685
- - test/dummy/app/views/layouts/application.html.erb
686
- - test/dummy/bin/bundle
687
- - test/dummy/bin/rails
688
- - test/dummy/bin/rake
689
- - test/dummy/bin/setup
690
- - test/dummy/config/application.rb
691
- - test/dummy/config/boot.rb
692
- - test/dummy/config/database.yml
693
- - test/dummy/config/environment.rb
694
- - test/dummy/config/environments/development.rb
695
- - test/dummy/config/environments/production.rb
696
- - test/dummy/config/environments/test.rb
697
- - test/dummy/config/initializers/backtrace_silencers.rb
698
- - test/dummy/config/initializers/cookies_serializer.rb
699
- - test/dummy/config/initializers/filter_parameter_logging.rb
700
- - test/dummy/config/initializers/inflections.rb
701
- - test/dummy/config/initializers/mime_types.rb
702
- - test/dummy/config/initializers/session_store.rb
703
- - test/dummy/config/initializers/wrap_parameters.rb
704
- - test/dummy/config/locales/en.yml
705
- - test/dummy/config/routes.rb
706
- - test/dummy/config/secrets.yml
707
- - test/dummy/config/storage.yml
708
- - test/dummy/config.ru
709
- - test/dummy/db/migrate/20150608130516_create_date_field.rb
710
- - test/dummy/db/migrate/20150608131430_create_integer_field.rb
711
- - test/dummy/db/migrate/20150608131603_create_decimal_field.rb
712
- - test/dummy/db/migrate/20150608131610_create_float_field.rb
713
- - test/dummy/db/migrate/20150608132159_create_boolean_field.rb
714
- - test/dummy/db/migrate/20150608132621_create_string_field.rb
715
- - test/dummy/db/migrate/20150608133038_create_belongs_to_field.rb
716
- - test/dummy/db/migrate/20150608133044_create_has_one_field.rb
717
- - test/dummy/db/migrate/20150608150016_create_has_many_field.rb
718
- - test/dummy/db/migrate/20150609114636_create_belongs_to_class_name_field.rb
719
- - test/dummy/db/migrate/20150612112520_create_has_and_belongs_to_many_field.rb
720
- - test/dummy/db/migrate/20150616150629_create_polymorphic_field.rb
721
- - test/dummy/db/migrate/20150623115554_create_has_many_class_name_field.rb
722
- - test/dummy/db/migrate/20150814081918_create_has_many_through_field.rb
723
- - test/dummy/db/migrate/20160627172810_create_owner.rb
724
- - test/dummy/db/migrate/20160627172951_create_tree.rb
725
- - test/dummy/db/migrate/20160628173505_add_timestamps.rb
726
- - test/dummy/db/migrate/20170614141921_create_serialize_field.rb
727
- - test/dummy/db/migrate/20181111162121_create_references_table.rb
728
- - test/dummy/db/schema.rb
729
- - test/dummy/public/404.html
730
- - test/dummy/public/422.html
731
- - test/dummy/public/500.html
732
- - test/dummy/public/favicon.ico
733
- - test/fixtures/belongs_to_field.yml
734
- - test/fixtures/has_many_field.yml
735
- - test/fixtures/has_many_through_field.yml
736
- - test/fixtures/has_one_field.yml
737
- - test/fixtures/owner.yml
738
- - test/fixtures/reference.yml
739
- - test/fixtures/serialize_field.yml
740
- - test/fixtures/string_field.yml
741
- - test/fixtures/tree.yml
742
- - test/forest_liana_test.rb
743
- - test/services/forest_liana/operator_date_interval_parser_test.rb
744
- - test/services/forest_liana/schema_adapter_test.rb
745
- - test/test_helper.rb
746
660
  - spec/config/initializers/errors_spec.rb
747
661
  - spec/config/initializers/logger_spec.rb
748
662
  - spec/deserializers/forest_liana/resource_deserializer_spec.rb
@@ -783,6 +697,7 @@ test_files:
783
697
  - spec/dummy/bin/rails
784
698
  - spec/dummy/bin/rake
785
699
  - spec/dummy/bin/setup
700
+ - spec/dummy/config.ru
786
701
  - spec/dummy/config/application.rb
787
702
  - spec/dummy/config/boot.rb
788
703
  - spec/dummy/config/database.yml
@@ -801,7 +716,6 @@ test_files:
801
716
  - spec/dummy/config/routes.rb
802
717
  - spec/dummy/config/secrets.yml
803
718
  - spec/dummy/config/storage.yml
804
- - spec/dummy/config.ru
805
719
  - spec/dummy/db/garage_schema.rb
806
720
  - spec/dummy/db/migrate/20190226172951_create_user.rb
807
721
  - spec/dummy/db/migrate/20190226173051_create_isle.rb
@@ -853,9 +767,12 @@ test_files:
853
767
  - spec/requests/capabilities_spec.rb
854
768
  - spec/requests/cors_spec.rb
855
769
  - spec/requests/count_spec.rb
770
+ - spec/requests/csv_export_relation_spec.rb
856
771
  - spec/requests/devise_controller_spec.rb
857
772
  - spec/requests/missing_attribute_valve_spec.rb
858
773
  - spec/requests/permissions_cache_footprint_spec.rb
774
+ - spec/requests/polymorphic_relation_namesake_spec.rb
775
+ - spec/requests/polymorphic_target_read_check_spec.rb
859
776
  - spec/requests/projection_header_spec.rb
860
777
  - spec/requests/projection_inherited_loads_spec.rb
861
778
  - spec/requests/query_footprint_spec.rb
@@ -913,3 +830,89 @@ test_files:
913
830
  - spec/spec_helper.rb
914
831
  - spec/support/forest_liana/query_capture.rb
915
832
  - spec/support/forest_liana/query_capture_spec.rb
833
+ - test/dummy/README.rdoc
834
+ - test/dummy/Rakefile
835
+ - test/dummy/app/assets/config/manifest.js
836
+ - test/dummy/app/assets/javascripts/application.js
837
+ - test/dummy/app/assets/stylesheets/application.css
838
+ - test/dummy/app/controllers/application_controller.rb
839
+ - test/dummy/app/helpers/application_helper.rb
840
+ - test/dummy/app/models/belongs_to_class_name_field.rb
841
+ - test/dummy/app/models/belongs_to_field.rb
842
+ - test/dummy/app/models/boolean_field.rb
843
+ - test/dummy/app/models/date_field.rb
844
+ - test/dummy/app/models/decimal_field.rb
845
+ - test/dummy/app/models/float_field.rb
846
+ - test/dummy/app/models/has_and_belongs_to_many_field.rb
847
+ - test/dummy/app/models/has_many_class_name_field.rb
848
+ - test/dummy/app/models/has_many_field.rb
849
+ - test/dummy/app/models/has_many_through_field.rb
850
+ - test/dummy/app/models/has_one_field.rb
851
+ - test/dummy/app/models/integer_field.rb
852
+ - test/dummy/app/models/owner.rb
853
+ - test/dummy/app/models/polymorphic_field.rb
854
+ - test/dummy/app/models/reference.rb
855
+ - test/dummy/app/models/serialize_field.rb
856
+ - test/dummy/app/models/string_field.rb
857
+ - test/dummy/app/models/tree.rb
858
+ - test/dummy/app/views/layouts/application.html.erb
859
+ - test/dummy/bin/bundle
860
+ - test/dummy/bin/rails
861
+ - test/dummy/bin/rake
862
+ - test/dummy/bin/setup
863
+ - test/dummy/config.ru
864
+ - test/dummy/config/application.rb
865
+ - test/dummy/config/boot.rb
866
+ - test/dummy/config/database.yml
867
+ - test/dummy/config/environment.rb
868
+ - test/dummy/config/environments/development.rb
869
+ - test/dummy/config/environments/production.rb
870
+ - test/dummy/config/environments/test.rb
871
+ - test/dummy/config/initializers/backtrace_silencers.rb
872
+ - test/dummy/config/initializers/cookies_serializer.rb
873
+ - test/dummy/config/initializers/filter_parameter_logging.rb
874
+ - test/dummy/config/initializers/inflections.rb
875
+ - test/dummy/config/initializers/mime_types.rb
876
+ - test/dummy/config/initializers/session_store.rb
877
+ - test/dummy/config/initializers/wrap_parameters.rb
878
+ - test/dummy/config/locales/en.yml
879
+ - test/dummy/config/routes.rb
880
+ - test/dummy/config/secrets.yml
881
+ - test/dummy/config/storage.yml
882
+ - test/dummy/db/migrate/20150608130516_create_date_field.rb
883
+ - test/dummy/db/migrate/20150608131430_create_integer_field.rb
884
+ - test/dummy/db/migrate/20150608131603_create_decimal_field.rb
885
+ - test/dummy/db/migrate/20150608131610_create_float_field.rb
886
+ - test/dummy/db/migrate/20150608132159_create_boolean_field.rb
887
+ - test/dummy/db/migrate/20150608132621_create_string_field.rb
888
+ - test/dummy/db/migrate/20150608133038_create_belongs_to_field.rb
889
+ - test/dummy/db/migrate/20150608133044_create_has_one_field.rb
890
+ - test/dummy/db/migrate/20150608150016_create_has_many_field.rb
891
+ - test/dummy/db/migrate/20150609114636_create_belongs_to_class_name_field.rb
892
+ - test/dummy/db/migrate/20150612112520_create_has_and_belongs_to_many_field.rb
893
+ - test/dummy/db/migrate/20150616150629_create_polymorphic_field.rb
894
+ - test/dummy/db/migrate/20150623115554_create_has_many_class_name_field.rb
895
+ - test/dummy/db/migrate/20150814081918_create_has_many_through_field.rb
896
+ - test/dummy/db/migrate/20160627172810_create_owner.rb
897
+ - test/dummy/db/migrate/20160627172951_create_tree.rb
898
+ - test/dummy/db/migrate/20160628173505_add_timestamps.rb
899
+ - test/dummy/db/migrate/20170614141921_create_serialize_field.rb
900
+ - test/dummy/db/migrate/20181111162121_create_references_table.rb
901
+ - test/dummy/db/schema.rb
902
+ - test/dummy/public/404.html
903
+ - test/dummy/public/422.html
904
+ - test/dummy/public/500.html
905
+ - test/dummy/public/favicon.ico
906
+ - test/fixtures/belongs_to_field.yml
907
+ - test/fixtures/has_many_field.yml
908
+ - test/fixtures/has_many_through_field.yml
909
+ - test/fixtures/has_one_field.yml
910
+ - test/fixtures/owner.yml
911
+ - test/fixtures/reference.yml
912
+ - test/fixtures/serialize_field.yml
913
+ - test/fixtures/string_field.yml
914
+ - test/fixtures/tree.yml
915
+ - test/forest_liana_test.rb
916
+ - test/services/forest_liana/operator_date_interval_parser_test.rb
917
+ - test/services/forest_liana/schema_adapter_test.rb
918
+ - test/test_helper.rb