forest_liana 9.22.16 → 9.22.18

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: fc453faf72f6b0f7030087482ead90361fe6e3e16c4d2e7b25e2a53cbc1b5fe4
4
- data.tar.gz: 6b13ab236bf05d9c5099cc8a987bd1616ecc7ba7097f077ffe3938674a428a75
3
+ metadata.gz: d2876bbcc3a687f4bbb73e23af6d9ca98e91ebce886c749afdcca20eb2fc0bed
4
+ data.tar.gz: 2c2fcda6f31a2a176caab533e30e89fbea88f3dd8fbc9e870ffe9a29019e2284
5
5
  SHA512:
6
- metadata.gz: 48fac66a8b958fdf847c8861992d38f1a61efd8ff9df7da04d1254c5470246b684f0f584fd3881c80aff673f69284b115f0d44852f5eb97c62ba438c3f43dad2
7
- data.tar.gz: fae68b2cf78f032cfef3a5609f9309631b69e0784b579cfc3dbe772b298c3202d5bd29a74d92796ee5610fa9b57443f80eb9bce2f8c910433a15ec67bdce2106
6
+ metadata.gz: 7ddfedbe5559ec9b55d869fec7e56e61f9e0560d574fd66d035180bb98e39bae8351739346f86d4faf720e07530c21d858660c0cfc8ae9a054d6ab3780d7088f
7
+ data.tar.gz: 12be328781a0a455c042c23668e3f3ca6946b437832f620398d97e7bc4bbd29d65733ff3f28b87dc7596e82e35539ed0eaff6f6a82efbb06015c7a7f82f39b1d
@@ -231,11 +231,13 @@ module ForestLiana
231
231
  end
232
232
 
233
233
  def apply_live_query_segment
234
+ ScopeManager.assert_can_execute_segment_query!(@user, @collection_name, @params[:segmentQuery])
235
+
234
236
  LiveQueryChecker.new(@params[:segmentQuery], 'Live Query Segment').validate
235
237
 
236
238
  begin
237
239
  segment_query = @params[:segmentQuery].gsub(/\;\s*$/, '')
238
- segment_query = ScopeManager.inject_context_variables_on_query(segment_query, @user)
240
+ segment_query = ScopeManager.inject_context_variables_on_query(segment_query, @user, @resource.connection)
239
241
 
240
242
  @records = @records.where(
241
243
  "#{@resource.table_name}.#{@resource.primary_key} IN (SELECT id FROM (#{segment_query}) as ids)"
@@ -2,6 +2,7 @@ module ForestLiana
2
2
  class ScopeManager
3
3
  # 5 minutes expiration cache
4
4
  @@scope_cache_expiration_delta = 300
5
+ SEGMENT_UNION_SEPARATOR = '/*MULTI-SEGMENTS-QUERIES-UNION*/ UNION '
5
6
 
6
7
  def self.apply_scopes_on_records(records, user, collection_name, timezone)
7
8
  scope_filters = get_scope(collection_name, user)
@@ -55,33 +56,79 @@ module ForestLiana
55
56
  Utils::ContextVariablesInjector.inject_context_in_filter(filter, context_variables)
56
57
  end
57
58
 
58
- def self.inject_context_variables_on_query(query, user)
59
+ def self.inject_context_variables_on_query(query, user, connection = ActiveRecord::Base.connection)
60
+ return query unless query.match?(Utils::ContextVariablesInjector::PLACEHOLDER)
61
+
59
62
  retrieve = fetch_scopes(user['rendering_id'])
60
63
  context_variables = Utils::ContextVariables.new(retrieve['team'], user)
61
64
 
62
- Utils::ContextVariablesInjector.inject_context_in_value(query, context_variables)
65
+ Utils::LiveQueryInjector.inject(query, context_variables, nil, connection, error_prefix: '')
63
66
  end
64
67
 
65
68
  def self.invalidate_scope_cache(rendering_id)
66
- Rails.cache.delete('forest.scopes.' + rendering_id.to_s)
67
- RequestCache.delete("forest.scopes.#{rendering_id}")
68
- end
69
-
70
- def self.fetch_scopes(rendering_id)
71
- RequestCache.fetch("forest.scopes.#{rendering_id}") do
72
- Rails.cache.fetch("forest.scopes.#{rendering_id}", expires_in: @@scope_cache_expiration_delta) do
73
- response = ForestLiana::ForestApiRequester.get("/liana/v4/permissions/renderings/#{rendering_id}")
74
- raise 'Unable to fetch scopes' unless response.is_a?(Net::HTTPOK)
75
- parsed_response = JSON.parse(response.body)
76
-
77
- {
78
- 'scopes' => decode_scope(parsed_response['collections']),
79
- 'team' => parsed_response['team']
80
- }
81
- end
69
+ Rails.cache.delete(scope_cache_key(rendering_id))
70
+ RequestCache.delete(scope_cache_key(rendering_id))
71
+ end
72
+
73
+ def self.assert_can_execute_segment_query!(user, collection_name, query)
74
+ return if Ability::ALLOWED_PERMISSION_LEVELS.include?(user['permission_level'])
75
+ raise Ability::Exceptions::AccessDenied.new unless query.is_a?(String)
76
+ return if segment_query_allowed?(segment_scopes(user['rendering_id']), collection_name, query)
77
+ return if segment_query_allowed?(segment_scopes(user['rendering_id'], force_fetch: true), collection_name, query)
78
+
79
+ raise Ability::Exceptions::AccessDenied.new
80
+ end
81
+
82
+ def self.segment_query_allowed?(scopes, collection_name, query)
83
+ allowed_queries = (scopes['segments'] || {})[collection_name]
84
+ return false if allowed_queries.nil?
85
+
86
+ allowed_set = allowed_queries.map { |allowed| normalize_segment_query(allowed) }
87
+ return true if allowed_set.include?(normalize_segment_query(query))
88
+
89
+ parts = query.split(SEGMENT_UNION_SEPARATOR)
90
+ parts.any? && parts.all? { |part| allowed_set.include?(normalize_segment_query(part)) }
91
+ end
92
+
93
+ def self.normalize_segment_query(query)
94
+ query.sub(/[\s;]+\z/, '').strip
95
+ end
96
+
97
+ def self.fetch_scopes(rendering_id, force_fetch: false)
98
+ key = scope_cache_key(rendering_id)
99
+ return RequestCache.write(key, cached_scopes(key, rendering_id, force_fetch)) if force_fetch
100
+
101
+ RequestCache.fetch(key) { cached_scopes(key, rendering_id, force_fetch) }
102
+ end
103
+
104
+ def self.segment_scopes(rendering_id, force_fetch: false)
105
+ fetch_scopes(rendering_id, force_fetch: force_fetch)
106
+ rescue StandardError
107
+ raise Errors::PermissionsUnavailableError.new
108
+ end
109
+
110
+ def self.cached_scopes(key, rendering_id, force_fetch)
111
+ Rails.cache.fetch(key, expires_in: @@scope_cache_expiration_delta, force: force_fetch) do
112
+ load_scopes(rendering_id)
82
113
  end
83
114
  end
84
115
 
116
+ def self.load_scopes(rendering_id)
117
+ response = ForestLiana::ForestApiRequester.get("/liana/v4/permissions/renderings/#{rendering_id}")
118
+ raise 'Unable to fetch scopes' unless response.is_a?(Net::HTTPOK)
119
+ parsed_response = JSON.parse(response.body)
120
+
121
+ {
122
+ 'scopes' => decode_scope(parsed_response['collections']),
123
+ 'segments' => decode_segments(parsed_response['collections']),
124
+ 'team' => parsed_response['team']
125
+ }
126
+ end
127
+
128
+ def self.scope_cache_key(rendering_id)
129
+ "forest.scopes.#{rendering_id}"
130
+ end
131
+
85
132
  def self.decode_scope(raw_scopes)
86
133
  scopes = {}
87
134
  raw_scopes.each do |collection_name, value|
@@ -90,5 +137,14 @@ module ForestLiana
90
137
 
91
138
  scopes
92
139
  end
140
+
141
+ def self.decode_segments(raw_collections)
142
+ raw_collections.each_with_object({}) do |(collection_name, value), segments|
143
+ segments[collection_name] = value['segments'] unless value['segments'].nil?
144
+ end
145
+ end
146
+
147
+ private_class_method :segment_query_allowed?, :normalize_segment_query, :segment_scopes, :cached_scopes,
148
+ :load_scopes, :scope_cache_key
93
149
  end
94
150
  end
@@ -24,21 +24,7 @@ module ForestLiana
24
24
  def self.inject_context_in_value_custom(value)
25
25
  return value unless value.is_a?(String)
26
26
 
27
- value_with_context_variables_injected = value
28
- encountered_variables = []
29
-
30
- while (match = PLACEHOLDER.match(value_with_context_variables_injected))
31
- context_variable_key = match[1]
32
-
33
- value_with_context_variables_injected = value_with_context_variables_injected.gsub(
34
- /{{#{context_variable_key}}}/,
35
- yield(context_variable_key)
36
- )
37
-
38
- encountered_variables.push(context_variable_key)
39
- end
40
-
41
- value_with_context_variables_injected
27
+ value.gsub(PLACEHOLDER) { yield(Regexp.last_match(1)) }
42
28
  end
43
29
 
44
30
  def self.inject_context_in_filter(filter, context_variables)
@@ -4,7 +4,7 @@ module ForestLiana
4
4
  module Utils
5
5
  class LiveQueryInjector
6
6
  PLACEHOLDER = Regexp.union(ContextVariablesInjector::PLACEHOLDER, '?')
7
- VERBATIM_VALUE = /\A(?:\d+(?:\.\d+)?(?:,\d+(?:\.\d+)?)*|true|false)\z/i
7
+ VERBATIM_VALUE = /\A(?:\d+(?:\.\d+)?(?:\s*,\s*\d+(?:\.\d+)?)*|true|false)\z/i
8
8
  CHARACTERS_CLOSING_QUOTED_TEXT = /["`'\\$\]\r\n\0]/
9
9
  LINE_COMMENT = /--[^\n]*/
10
10
  MYSQL_LINE_COMMENT = /--(?=[[:space:][:cntrl:]]|\z)[^\n]*/
@@ -14,20 +14,31 @@ module ForestLiana
14
14
  WORD = /[[:alpha:]_][[:alnum:]_$]*/
15
15
  STRING_CONTINUATION = /[ \t\f\r]*\n[[:space:]]*(?=')/
16
16
  DOLLAR_QUOTED = /\$([[:alpha:]_][[:alnum:]_]*|)\$.*?(?:\$\1\$|\z)/m
17
+ # Every character next_token can open a token on, besides letters and underscores.
18
+ TOKEN_OPENERS = %q('"`$[{?-/#)
19
+ NEUTRAL_TEXT = /[^[:alpha:]_#{Regexp.escape(TOKEN_OPENERS)}]+/
20
+ QUOTED_PATTERNS = ["'", '"', '`'].product([false, true]).to_h do |quote, backslash_escapes|
21
+ escaped = Regexp.escape(quote)
22
+ content = backslash_escapes ? "[^#{escaped}\\\\]|\\\\.|#{escaped}#{escaped}" : "[^#{escaped}]|#{escaped}#{escaped}"
23
+ [[quote, backslash_escapes], /#{escaped}(?:#{content})*#{escaped}?/m]
24
+ end.freeze
17
25
 
18
- def self.inject(query, context_variables, record_id, connection = ActiveRecord::Base.connection)
19
- new(context_variables, record_id, connection).inject(query)
26
+ def self.inject(query, context_variables, record_id, connection = ActiveRecord::Base.connection, error_prefix: 'Live Query Chart: ')
27
+ new(context_variables, record_id, connection, error_prefix).inject(query)
20
28
  end
21
29
 
22
- def initialize(context_variables, record_id, connection)
30
+ def initialize(context_variables, record_id, connection, error_prefix = 'Live Query Chart: ')
23
31
  @context_variables = context_variables
32
+ @error_prefix = error_prefix
24
33
  @record_id = record_id
25
34
  @connection = connection
26
35
  @mysql = connection.adapter_name.match?(/mysql|trilogy/i)
27
36
  @postgresql = connection.adapter_name.match?(/postg/i)
28
37
  @bracket_quotes = connection.adapter_name.match?(/sqlite|sqlserver/i)
29
38
  @nested_comments = @postgresql || connection.adapter_name.match?(/sqlserver/i)
30
- @backslash_escapes = @mysql && mysql_backslash_escapes?
39
+ sql_mode = @mysql ? mysql_sql_mode : ''
40
+ @backslash_escapes = @mysql && !sql_mode.include?('NO_BACKSLASH_ESCAPES')
41
+ @double_quoted_strings = @mysql && !sql_mode.include?('ANSI_QUOTES')
31
42
  end
32
43
 
33
44
  def inject(query)
@@ -40,14 +51,22 @@ module ForestLiana
40
51
  private
41
52
 
42
53
  def next_token(scanner)
43
- if (comment = scan_comment(scanner))
54
+ if (neutral = scanner.scan(NEUTRAL_TEXT))
55
+ neutral
56
+ elsif (comment = scan_comment(scanner))
44
57
  comment
45
58
  elsif (word = scanner.scan(WORD))
46
59
  return word unless @postgresql && word.casecmp?('e') && scanner.peek(1) == "'"
47
60
 
48
- word + inject_in_string(scan_escape_string(scanner), backslash_escapes: true, escape_backslashes: true)
61
+ word + inject_in_string(scan_escape_string(scanner), backslash_escapes: true) do |text|
62
+ text.gsub(/[\\']/) { |character| character * 2 }
63
+ end
49
64
  elsif (string = scanner.scan(quoted_pattern("'", backslash_escapes: @backslash_escapes)))
50
- inject_in_string(string, backslash_escapes: @backslash_escapes, escape_backslashes: false)
65
+ inject_in_string(string, backslash_escapes: @backslash_escapes) { |text| @connection.quote_string(text) }
66
+ elsif @double_quoted_strings && (string = scanner.scan(quoted_pattern('"', backslash_escapes: @backslash_escapes)))
67
+ inject_in_string(string, backslash_escapes: @backslash_escapes) do |text|
68
+ @backslash_escapes ? @connection.quote_string(text) : text.gsub('"', '""')
69
+ end
51
70
  elsif (quoted = scan_quoted_text(scanner))
52
71
  inject_in_quoted_text(quoted)
53
72
  elsif (placeholder = scanner.scan(PLACEHOLDER))
@@ -57,8 +76,10 @@ module ForestLiana
57
76
  end
58
77
  end
59
78
 
60
- def mysql_backslash_escapes?
61
- !@connection.select_value('SELECT @@SESSION.sql_mode').to_s.include?('NO_BACKSLASH_ESCAPES')
79
+ def mysql_sql_mode
80
+ RequestCache.fetch([:mysql_sql_mode, @connection]) do
81
+ @connection.select_value('SELECT @@SESSION.sql_mode').to_s
82
+ end
62
83
  end
63
84
 
64
85
  def scan_comment(scanner)
@@ -83,9 +104,7 @@ module ForestLiana
83
104
  end
84
105
 
85
106
  def quoted_pattern(quote, backslash_escapes: false)
86
- escaped = Regexp.escape(quote)
87
- content = backslash_escapes ? "[^#{escaped}\\\\]|\\\\.|#{escaped}#{escaped}" : "[^#{escaped}]|#{escaped}#{escaped}"
88
- /#{escaped}(?:#{content})*#{escaped}?/m
107
+ QUOTED_PATTERNS[[quote, backslash_escapes]]
89
108
  end
90
109
 
91
110
  def inject_in_code(placeholder)
@@ -94,14 +113,14 @@ module ForestLiana
94
113
  end
95
114
  end
96
115
 
97
- def inject_in_string(string, backslash_escapes:, escape_backslashes:)
116
+ def inject_in_string(string, backslash_escapes:, &escape)
98
117
  replace_placeholders(string) do |text, placeholder, preceding_text|
99
118
  if backslash_escapes && preceding_text[/\\*\z/].length.odd?
100
119
  raise ForestLiana::Errors::LiveQueryError.new(
101
- "Live Query Chart: #{placeholder} cannot follow a backslash inside a string."
120
+ "#{@error_prefix}#{placeholder} cannot follow a backslash inside a string."
102
121
  )
103
122
  end
104
- escape_backslashes ? text.gsub(/[\\']/) { |character| character * 2 } : @connection.quote_string(text)
123
+ escape.call(text)
105
124
  end
106
125
  end
107
126
 
@@ -109,7 +128,7 @@ module ForestLiana
109
128
  replace_placeholders(quoted) do |text, placeholder|
110
129
  if text.match?(CHARACTERS_CLOSING_QUOTED_TEXT)
111
130
  raise ForestLiana::Errors::LiveQueryError.new(
112
- "Live Query Chart: The value of #{placeholder} cannot contain quotes, brackets, backslashes, " \
131
+ "#{@error_prefix}The value of #{placeholder} cannot contain quotes, brackets, backslashes, " \
113
132
  'dollar signs or line breaks when it is written inside a quoted identifier or a dollar-quoted string.'
114
133
  )
115
134
  end
@@ -1,3 +1,3 @@
1
1
  module ForestLiana
2
- VERSION = "9.22.16"
2
+ VERSION = "9.22.18"
3
3
  end
@@ -635,6 +635,89 @@ describe 'Requesting Tree resources', :type => :request do
635
635
  end
636
636
  end
637
637
 
638
+ describe 'live query segment permission' do
639
+ let(:listed_segment_query) { 'SELECT id FROM trees WHERE name IS NOT NULL' }
640
+ let(:unlisted_segment_query) { 'SELECT id FROM trees WHERE 1 = 0' }
641
+
642
+ restricted_token = JWT.encode({
643
+ id: 1,
644
+ email: 'michael.kelso@that70.show',
645
+ first_name: 'Michael',
646
+ last_name: 'Kelso',
647
+ team: 'Operations',
648
+ rendering_id: 16,
649
+ exp: Time.now.to_i + 2.weeks.to_i,
650
+ permission_level: 'user'
651
+ }, ForestLiana.auth_secret, 'HS256')
652
+
653
+ restricted_headers = headers.merge('Authorization' => "Bearer #{restricted_token}")
654
+
655
+ let(:list_params) {
656
+ {
657
+ fields: { 'Tree' => 'id,name' },
658
+ page: { 'number' => '1', 'size' => '10' },
659
+ searchExtended: '0',
660
+ sort: '-id',
661
+ timezone: 'Europe/Paris'
662
+ }
663
+ }
664
+
665
+ it 'refuses a listing whose segment query is not one of the team segments' do
666
+ get '/forest/Tree', params: list_params.merge(segmentQuery: unlisted_segment_query), headers: restricted_headers
667
+
668
+ expect(response.status).to eq(403)
669
+ expect(JSON.parse(response.body)['errors'][0]['name']).to eq('AccessDenied')
670
+ end
671
+
672
+ it 'serves the listing when the rendering lists that exact segment query' do
673
+ allow(ForestLiana::ScopeManager).to receive(:fetch_scopes).and_return(
674
+ 'scopes' => {},
675
+ 'segments' => { 'Tree' => [listed_segment_query] },
676
+ 'team' => { 'id' => '1', 'name' => 'Operations' }
677
+ )
678
+
679
+ get '/forest/Tree', params: list_params.merge(segmentQuery: listed_segment_query), headers: restricted_headers
680
+
681
+ expect(response.status).to eq(200)
682
+ expect(JSON.parse(response.body)['data'][0]['attributes']['name']).to eq('Lemon Tree')
683
+ end
684
+
685
+ it 'refuses the count the same way' do
686
+ get '/forest/Tree/count', params: { segmentQuery: unlisted_segment_query, timezone: 'Europe/Paris' }, headers: restricted_headers
687
+
688
+ expect(response.status).to eq(403)
689
+ end
690
+
691
+ it 'refuses the csv export the same way' do
692
+ get '/forest/Tree.csv', params: { segmentQuery: unlisted_segment_query, header: 'id,name' }, headers: restricted_headers
693
+
694
+ expect(response.status).to eq(403)
695
+ end
696
+
697
+ it 'refuses a select-all bulk delete without deleting anything' do
698
+ params = {
699
+ data: {
700
+ attributes: {
701
+ collection_name: 'Tree',
702
+ all_records: true,
703
+ all_records_subset_query: { segmentQuery: unlisted_segment_query }
704
+ }
705
+ }
706
+ }
707
+
708
+ delete '/forest/Tree', params: JSON.dump(params), headers: restricted_headers
709
+
710
+ expect(response.status).to eq(403)
711
+ expect(Tree.count).to eq(1)
712
+ end
713
+
714
+ it 'still serves an admin an unlisted segment query' do
715
+ get '/forest/Tree', params: list_params.merge(segmentQuery: unlisted_segment_query), headers: headers
716
+
717
+ expect(response.status).to eq(200)
718
+ end
719
+ end
720
+
638
721
  describe 'csv' do
639
722
  it 'should return CSV with correct headers and data' do
640
723
  params = {
@@ -305,6 +305,55 @@ module ForestLiana
305
305
  )
306
306
  end
307
307
 
308
+ describe 'with a live query segment on the "select all" selection' do
309
+ let(:segment_query) { "SELECT id FROM isle WHERE name = 'foo'" }
310
+
311
+ before do
312
+ Rails.cache.write('forest.has_permission', false)
313
+ end
314
+
315
+ def select_all_parameters_with_segment
316
+ select_all_params = params.deep_dup
317
+ select_all_params['data']['attributes'][:all_records] = true
318
+ select_all_params['data']['attributes'][:ids] = []
319
+ select_all_params['data']['attributes'][:all_records_subset_query] =
320
+ select_all_params['data']['attributes'][:all_records_subset_query].merge('segmentQuery' => segment_query)
321
+ ActionController::Parameters.new(select_all_params).permit!
322
+ end
323
+
324
+ it 'refuses with AccessDenied when the query is not one of the requester\'s segments' do
325
+ allow(ForestLiana::ScopeManager).to receive(:fetch_scopes).and_return(
326
+ 'scopes' => {}, 'segments' => {}, 'team' => {'id' => '1', 'name' => 'Operations'}
327
+ )
328
+ action['approvalRequired'] = [1]
329
+ action['userApprovalEnabled'] = [7]
330
+ smart_action_checker = ForestLiana::Ability::Permission::SmartActionChecker.new(
331
+ select_all_parameters_with_segment, Island, action, user, nil, forest_user
332
+ )
333
+
334
+ expect { smart_action_checker.can_execute? }
335
+ .to raise_error(ForestLiana::Ability::Exceptions::AccessDenied)
336
+ end
337
+
338
+ it 'resolves the record ids when the query is one of the requester\'s segments' do
339
+ allow(ForestLiana::ScopeManager).to receive(:fetch_scopes).and_return(
340
+ 'scopes' => {},
341
+ 'segments' => { 'Island' => [segment_query] },
342
+ 'team' => {'id' => '1', 'name' => 'Operations'}
343
+ )
344
+ action['approvalRequired'] = [1]
345
+ action['userApprovalEnabled'] = [7]
346
+ smart_action_checker = ForestLiana::Ability::Permission::SmartActionChecker.new(
347
+ select_all_parameters_with_segment, Island, action, user, nil, forest_user
348
+ )
349
+
350
+ expect { smart_action_checker.can_execute? }
351
+ .to raise_error(ForestLiana::Ability::Exceptions::RequireApproval) do |error|
352
+ expect(error.data[:recordIds]).to eq(['1'])
353
+ end
354
+ end
355
+ end
356
+
308
357
  it 'should raise RequireApproval error if match approvalRequiredConditions' do
309
358
  parameters = ActionController::Parameters.new(params).permit!
310
359
  action['approvalRequired'] = [1]
@@ -153,6 +153,13 @@ module ForestLiana
153
153
 
154
154
  describe 'when a live query segment uses a context variable' do
155
155
  let(:user) { { 'id' => '1', 'name' => 'Michel', 'rendering_id' => rendering_id } }
156
+ let(:scopes) {
157
+ {
158
+ 'scopes' => {},
159
+ 'segments' => { 'User' => ["SELECT id FROM users WHERE name = '{{currentUser.name}}'"] },
160
+ 'team' => {'id' => '1', 'name' => 'Operations'}
161
+ }
162
+ }
156
163
  let(:getter) do
157
164
  described_class.new(resource, {
158
165
  page: { size: pageSize, number: pageNumber },
@@ -166,6 +173,71 @@ module ForestLiana
166
173
 
167
174
  expect(getter.records.map(&:name)).to eq(['Michel'])
168
175
  end
176
+
177
+ describe 'when the variable value carries SQL' do
178
+ let(:user) { { 'id' => '1', 'name' => "Michel' OR '1'='1", 'rendering_id' => rendering_id } }
179
+
180
+ it 'matches the value as a literal in the records' do
181
+ getter.perform
182
+
183
+ expect(getter.records).to be_empty
184
+ end
185
+
186
+ it 'matches the value as a literal in the count' do
187
+ getter.count
188
+
189
+ expect(getter.count).to eq 0
190
+ end
191
+ end
192
+
193
+ describe 'when every record of the segment is selected' do
194
+ def ids_from_request(user)
195
+ params = ActionController::Parameters.new(
196
+ data: {
197
+ attributes: {
198
+ collection_name: 'User',
199
+ all_records: true,
200
+ all_records_subset_query: {
201
+ segmentQuery: "SELECT id FROM users WHERE name = '{{currentUser.name}}'",
202
+ },
203
+ },
204
+ },
205
+ )
206
+ described_class.get_ids_from_request(params, user)
207
+ end
208
+
209
+ it 'injects the variable into the query that selects the ids' do
210
+ expect(ids_from_request(user)).to eq(User.where(name: 'Michel').pluck(:id))
211
+ end
212
+
213
+ it 'matches a value carrying SQL as a literal' do
214
+ expect(ids_from_request(user.merge('name' => "Michel' OR '1'='1"))).to be_empty
215
+ end
216
+ end
217
+ end
218
+
219
+ describe 'when the live query segment is not one of the user\'s rendering segments' do
220
+ let(:getter) do
221
+ described_class.new(resource, {
222
+ page: { size: pageSize, number: pageNumber },
223
+ fields: { 'User' => 'id,name' },
224
+ segmentQuery: 'SELECT id FROM users WHERE name IS NOT NULL',
225
+ }, user)
226
+ end
227
+
228
+ it 'raises AccessDenied from the constructor, before any SQL runs' do
229
+ queries = []
230
+ subscriber = ActiveSupport::Notifications.subscribe('sql.active_record') do |*, payload|
231
+ queries << payload[:sql] unless payload[:name] == 'SCHEMA' || payload[:cached]
232
+ end
233
+ begin
234
+ expect { getter }.to raise_error(ForestLiana::Ability::Exceptions::AccessDenied)
235
+ ensure
236
+ ActiveSupport::Notifications.unsubscribe(subscriber)
237
+ end
238
+
239
+ expect(queries).to be_empty
240
+ end
169
241
  end
170
242
 
171
243
  describe 'when there are more records than the page size' do
@@ -70,6 +70,7 @@ module ForestLiana
70
70
  expect(Rails.cache.read('forest.scopes.' + rendering_id.to_s)).to eq(
71
71
  {
72
72
  'scopes' => {'User' => {'aggregator' => 'and', 'conditions'=>[{'field' => 'id', 'operator' => 'greater_than', 'value' => '1'}]}},
73
+ 'segments' => {'User' => []},
73
74
  'team' => {'id' => '1', 'name' => 'Operations'},
74
75
  })
75
76
  end
@@ -120,6 +121,7 @@ module ForestLiana
120
121
  expect(Rails.cache.read('forest.scopes.' + rendering_id.to_s)).to eq(
121
122
  {
122
123
  'scopes' => {'User' => {'aggregator' => 'and', 'conditions'=>[{'field' => 'email', 'operator' => 'equal', 'value' => '{{currentUser.email}}'}]}},
124
+ 'segments' => {'User' => []},
123
125
  'team' => {'id' => '1', 'name' => 'Operations'},
124
126
  }
125
127
  )
@@ -165,6 +167,7 @@ module ForestLiana
165
167
  expect(Rails.cache.read('forest.scopes.' + rendering_id.to_s)).to eq(
166
168
  {
167
169
  'scopes' => {},
170
+ 'segments' => {'User' => []},
168
171
  'team' => {'id' => '1', 'name' => 'Operations'},
169
172
  }
170
173
  )
@@ -172,6 +175,165 @@ module ForestLiana
172
175
  end
173
176
  end
174
177
 
178
+ describe '.assert_can_execute_segment_query!' do
179
+ let(:segment_query) { 'SELECT id FROM users WHERE name IS NOT NULL' }
180
+ let(:other_segment_query) { 'SELECT id FROM users WHERE id > 10;' }
181
+ let(:scopes_body) {
182
+ {
183
+ 'collections' => {
184
+ 'User' => { 'scope' => nil, 'segments' => [segment_query, other_segment_query] }
185
+ },
186
+ 'team' => {'id' => '1', 'name' => 'Operations'}
187
+ }
188
+ }
189
+
190
+ let(:rendering_path) { "/liana/v4/permissions/renderings/#{rendering_id}" }
191
+
192
+ def api_response(body)
193
+ body = JSON.generate(body)
194
+ response = Net::HTTPOK.new({}, 200, body)
195
+ allow(response).to receive(:body).and_return(body)
196
+ response
197
+ end
198
+
199
+ before do
200
+ allow(ForestLiana::ForestApiRequester).to receive(:get).and_return(api_response(scopes_body))
201
+ end
202
+
203
+ it 'accepts a query the rendering lists for the collection' do
204
+ expect {
205
+ described_class.assert_can_execute_segment_query!(user, collection_name, segment_query)
206
+ }.not_to raise_error
207
+ end
208
+
209
+ it 'refuses a query the rendering does not list' do
210
+ expect {
211
+ described_class.assert_can_execute_segment_query!(user, collection_name, 'SELECT id FROM users WHERE 1 = 0')
212
+ }.to raise_error(ForestLiana::Ability::Exceptions::AccessDenied)
213
+ end
214
+
215
+ it 'refuses a collection the rendering payload carries no segments for' do
216
+ expect {
217
+ described_class.assert_can_execute_segment_query!(user, 'Island', segment_query)
218
+ }.to raise_error(ForestLiana::Ability::Exceptions::AccessDenied)
219
+ end
220
+
221
+ it 'accepts a UNION of configured segments, ignoring their trailing semicolons' do
222
+ union = "#{segment_query}/*MULTI-SEGMENTS-QUERIES-UNION*/ UNION SELECT id FROM users WHERE id > 10"
223
+
224
+ expect {
225
+ described_class.assert_can_execute_segment_query!(user, collection_name, union)
226
+ }.not_to raise_error
227
+ end
228
+
229
+ it 'refuses a UNION holding one unconfigured segment' do
230
+ union = "#{segment_query}/*MULTI-SEGMENTS-QUERIES-UNION*/ UNION SELECT id FROM users WHERE 1 = 0"
231
+
232
+ expect {
233
+ described_class.assert_can_execute_segment_query!(user, collection_name, union)
234
+ }.to raise_error(ForestLiana::Ability::Exceptions::AccessDenied)
235
+ end
236
+
237
+ it 'accepts a configured query sent without its trailing semicolon' do
238
+ expect {
239
+ described_class.assert_can_execute_segment_query!(user, collection_name, 'SELECT id FROM users WHERE id > 10')
240
+ }.not_to raise_error
241
+ end
242
+
243
+ it 'accepts a configured segment that itself holds the union separator' do
244
+ union_segment = "#{segment_query}/*MULTI-SEGMENTS-QUERIES-UNION*/ UNION SELECT id FROM users WHERE id = 1"
245
+ scopes_body['collections']['User']['segments'] = [union_segment]
246
+ allow(ForestLiana::ForestApiRequester).to receive(:get).and_return(api_response(scopes_body))
247
+
248
+ expect {
249
+ described_class.assert_can_execute_segment_query!(user, collection_name, union_segment)
250
+ }.not_to raise_error
251
+ end
252
+
253
+ it 'answers 503 when the rendering cannot be fetched on a cold cache' do
254
+ allow(ForestLiana::ForestApiRequester).to receive(:get)
255
+ .and_return(Net::HTTPServiceUnavailable.new({}, 503, ''))
256
+
257
+ expect {
258
+ described_class.assert_can_execute_segment_query!(user, collection_name, segment_query)
259
+ }.to raise_error(ForestLiana::Errors::PermissionsUnavailableError)
260
+ end
261
+
262
+ it 'refuses an empty query' do
263
+ expect {
264
+ described_class.assert_can_execute_segment_query!(user, collection_name, '')
265
+ }.to raise_error(ForestLiana::Ability::Exceptions::AccessDenied)
266
+ end
267
+
268
+ it 'refuses a query that is not a string, without fetching the rendering' do
269
+ expect {
270
+ described_class.assert_can_execute_segment_query!(user, collection_name, [segment_query])
271
+ }.to raise_error(ForestLiana::Ability::Exceptions::AccessDenied)
272
+ expect(ForestLiana::ForestApiRequester).not_to have_received(:get)
273
+ end
274
+
275
+ %w[admin editor developer].each do |permission_level|
276
+ it "lets a #{permission_level} run any query, without fetching the rendering" do
277
+ expect {
278
+ described_class.assert_can_execute_segment_query!(
279
+ user.merge('permission_level' => permission_level), collection_name, 'SELECT id FROM users WHERE 1 = 0'
280
+ )
281
+ }.not_to raise_error
282
+
283
+ expect(ForestLiana::ForestApiRequester).not_to have_received(:get)
284
+ end
285
+ end
286
+
287
+ describe 'when the cached rendering may be stale' do
288
+ let(:scopes_without_the_segment) {
289
+ body = scopes_body.deep_dup
290
+ body['collections']['User']['segments'] = []
291
+ body
292
+ }
293
+
294
+ it 'refetches the rendering once before refusing a fresher rendering could allow' do
295
+ allow(ForestLiana::ForestApiRequester).to receive(:get)
296
+ .and_return(api_response(scopes_without_the_segment), api_response(scopes_body))
297
+
298
+ expect {
299
+ described_class.assert_can_execute_segment_query!(user, collection_name, segment_query)
300
+ }.not_to raise_error
301
+ expect(ForestLiana::ForestApiRequester).to have_received(:get).with(rendering_path).exactly(2).times
302
+ end
303
+
304
+ it 'still refuses when the refetched rendering denies it too' do
305
+ allow(ForestLiana::ForestApiRequester).to receive(:get)
306
+ .and_return(api_response(scopes_without_the_segment))
307
+
308
+ expect {
309
+ described_class.assert_can_execute_segment_query!(user, collection_name, segment_query)
310
+ }.to raise_error(ForestLiana::Ability::Exceptions::AccessDenied)
311
+ expect(ForestLiana::ForestApiRequester).to have_received(:get).with(rendering_path).exactly(2).times
312
+ end
313
+
314
+ it 'keeps the cached rendering and answers 503 when the refetch fails' do
315
+ unavailable = Net::HTTPServiceUnavailable.new({}, 503, '')
316
+ allow(ForestLiana::ForestApiRequester).to receive(:get)
317
+ .and_return(api_response(scopes_without_the_segment), unavailable)
318
+
319
+ expect {
320
+ described_class.assert_can_execute_segment_query!(user, collection_name, segment_query)
321
+ }.to raise_error(ForestLiana::Errors::PermissionsUnavailableError)
322
+ expect(Rails.cache.read("forest.scopes.#{rendering_id}")['segments']).to eq('User' => [])
323
+ end
324
+
325
+ it 'refetches a cache entry from before segments were cached, before deciding' do
326
+ Rails.cache.write("forest.scopes.#{rendering_id}", {'scopes' => {}, 'team' => {}})
327
+ allow(ForestLiana::ForestApiRequester).to receive(:get).and_return(api_response(scopes_body))
328
+
329
+ expect {
330
+ described_class.assert_can_execute_segment_query!(user, collection_name, segment_query)
331
+ }.not_to raise_error
332
+ expect(ForestLiana::ForestApiRequester).to have_received(:get).with(rendering_path).once
333
+ end
334
+ end
335
+ end
336
+
175
337
  describe '#append_scope_for_user' do
176
338
  let(:filters) { described_class.append_scope_for_user(existing_filter, user, collection_name) }
177
339
 
@@ -366,6 +528,46 @@ module ForestLiana
366
528
 
367
529
  expect(query).to eq "SELECT id FROM users WHERE email = '{{currentUser.email}}'"
368
530
  end
531
+
532
+ it 'should escape a value written inside a string' do
533
+ user['first_name'] = "x' OR '1'='1"
534
+
535
+ expect(described_class.inject_context_variables_on_query(
536
+ "SELECT id FROM users WHERE first_name = '{{currentUser.first_name}}'", user
537
+ )).to eq "SELECT id FROM users WHERE first_name = 'x'' OR ''1''=''1'"
538
+ end
539
+
540
+ it 'should quote a value written outside a string' do
541
+ user['first_name'] = '0 OR 1=1'
542
+
543
+ expect(described_class.inject_context_variables_on_query(
544
+ 'SELECT id FROM users WHERE first_name = {{currentUser.first_name}}', user
545
+ )).to eq "SELECT id FROM users WHERE first_name = '0 OR 1=1'"
546
+ end
547
+
548
+ it 'should inject a numeric value as is' do
549
+ expect(described_class.inject_context_variables_on_query(
550
+ 'SELECT id FROM users WHERE id = {{currentUser.id}}', user
551
+ )).to eq 'SELECT id FROM users WHERE id = 1'
552
+ end
553
+
554
+ it 'should not fetch the scopes when the query has no context variable' do
555
+ query_without_variable = 'SELECT id FROM users WHERE id > 1'
556
+
557
+ expect(described_class.inject_context_variables_on_query(query_without_variable, user))
558
+ .to eq query_without_variable
559
+ expect(ForestLiana::ForestApiRequester).not_to have_received(:get)
560
+ end
561
+
562
+ it 'should not prefix the error it raises with the chart label' do
563
+ user['first_name'] = 'a"b'
564
+
565
+ expect {
566
+ described_class.inject_context_variables_on_query(
567
+ 'SELECT id FROM users WHERE "{{currentUser.first_name}}" = 1', user
568
+ )
569
+ }.to raise_error(ForestLiana::Errors::LiveQueryError, /\AThe value of {{currentUser.first_name}}/)
570
+ end
369
571
  end
370
572
  end
371
573
  end
@@ -51,6 +51,26 @@ module ForestLiana
51
51
 
52
52
  expect(result).to eq('It should be POWER of rank RANK. But POWER can be duplicated.')
53
53
  end
54
+
55
+ it 'does not inject variables again into an injected value' do
56
+ result = described_class.inject_context_in_value_custom('Hi {{currentUser.firstName}}') do
57
+ '{{currentUser.firstName}}'
58
+ end
59
+
60
+ expect(result).to eq('Hi {{currentUser.firstName}}')
61
+ end
62
+
63
+ it 'inserts a value holding backslash sequences as is' do
64
+ result = described_class.inject_context_in_value_custom('Hi {{currentUser.firstName}}!') { "\\0 \\' \\1" }
65
+
66
+ expect(result).to eq("Hi \\0 \\' \\1!")
67
+ end
68
+
69
+ it 'replaces a variable whose key holds regular expression characters' do
70
+ result = described_class.inject_context_in_value_custom('Hi {{currentUser.tags.a+b}}') { |key| key }
71
+
72
+ expect(result).to eq('Hi currentUser.tags.a+b')
73
+ end
54
74
  end
55
75
 
56
76
  context('when inject_context_in_value is called') do
@@ -30,13 +30,46 @@ module ForestLiana
30
30
  connection
31
31
  end
32
32
 
33
+ # NEUTRAL_TEXT is only a shortcut: a token opener missing from TOKEN_OPENERS shows up as a different outcome without it.
33
34
  def inject(query, connection, record_id: nil)
34
- LiveQueryInjector.inject(query, context_variables, record_id, connection)
35
+ outcome = injection_outcome(query, connection, record_id)
36
+ neutral_text = LiveQueryInjector::NEUTRAL_TEXT
37
+ stub_const('ForestLiana::Utils::LiveQueryInjector::NEUTRAL_TEXT', /(?!)/)
38
+ outcome_without_shortcut = injection_outcome(query, connection, record_id)
39
+ stub_const('ForestLiana::Utils::LiveQueryInjector::NEUTRAL_TEXT', neutral_text)
40
+
41
+ expect(outcome_without_shortcut.map { |value| value.is_a?(Exception) ? value.message : value })
42
+ .to eq(outcome.map { |value| value.is_a?(Exception) ? value.message : value })
43
+ injected, error = outcome
44
+ raise error if error
45
+
46
+ injected
47
+ end
48
+
49
+ def injection_outcome(query, connection, record_id)
50
+ [LiveQueryInjector.inject(query, context_variables, record_id, connection), nil]
51
+ rescue ForestLiana::Errors::LiveQueryError => error
52
+ [nil, error]
35
53
  end
36
54
 
37
55
  describe 'on MySQL' do
38
56
  let(:request_context_variables) { { 'x.value' => '0 OR 1=1' } }
39
57
 
58
+ it 'reads the session sql_mode once per request and connection' do
59
+ connection = mysql_connection
60
+ other_connection = mysql_connection
61
+
62
+ query = 'SELECT 1 FROM t WHERE id = {{x.value}}'
63
+ RequestCache.with do
64
+ 2.times { LiveQueryInjector.inject(query, context_variables, nil, connection) }
65
+ LiveQueryInjector.inject(query, context_variables, nil, other_connection)
66
+ end
67
+ LiveQueryInjector.inject(query, context_variables, nil, connection)
68
+
69
+ expect(connection).to have_received(:select_value).with('SELECT @@SESSION.sql_mode').twice
70
+ expect(other_connection).to have_received(:select_value).with('SELECT @@SESSION.sql_mode').once
71
+ end
72
+
40
73
  it 'reads a backslash-escaped quote as part of the string literal' do
41
74
  expect(inject("SELECT 1 FROM t WHERE a = 'it\\'s' AND id = {{x.value}}", mysql_connection))
42
75
  .to eq("SELECT 1 FROM t WHERE a = 'it\\'s' AND id = '0 OR 1=1'")
@@ -56,10 +89,25 @@ module ForestLiana
56
89
  .to eq('SELECT 1 FROM t WHERE a = "Aragorn"')
57
90
  end
58
91
 
59
- it 'refuses a value holding a quote inside a double-quoted string' do
92
+ it 'escapes a value injected inside a double-quoted string with the connection' do
93
+ request_context_variables['x.value'] = %q(O'Brien" OR "1)
94
+
95
+ expect(inject('SELECT 1 FROM t WHERE a = "{{x.value}}"', mysql_connection))
96
+ .to eq(%q(SELECT 1 FROM t WHERE a = "O\'Brien\" OR \"1"))
97
+ end
98
+
99
+ it 'refuses a value placed right after a backslash inside a double-quoted string' do
100
+ request_context_variables['x.value'] = '" OR true -- '
101
+
102
+ expect { inject('SELECT 1 FROM t WHERE a = "\\{{x.value}}"', mysql_connection) }
103
+ .to raise_error(ForestLiana::Errors::LiveQueryError)
104
+ end
105
+
106
+ it 'refuses a value holding a quote inside a double-quoted identifier when the session uses ANSI quotes' do
60
107
  request_context_variables['x.value'] = 'a" OR "1'
108
+ connection = mysql_connection(sql_mode: 'REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI')
61
109
 
62
- expect { inject('SELECT 1 FROM t WHERE a = "{{x.value}}"', mysql_connection) }
110
+ expect { inject('SELECT 1 FROM t WHERE "{{x.value}}" = 1', connection) }
63
111
  .to raise_error(ForestLiana::Errors::LiveQueryError)
64
112
  end
65
113
 
@@ -120,6 +168,13 @@ module ForestLiana
120
168
  expect(inject("SELECT 1 FROM t WHERE a = '\\{{x.value}}'", connection))
121
169
  .to eq("SELECT 1 FROM t WHERE a = '\\a''b'")
122
170
  end
171
+
172
+ it 'doubles the double quotes of a value injected inside a double-quoted string' do
173
+ request_context_variables['x.value'] = %q(O'Brien" OR "1)
174
+
175
+ expect(inject('SELECT 1 FROM t WHERE a = "\\{{x.value}}"', connection))
176
+ .to eq(%q(SELECT 1 FROM t WHERE a = "\\O'Brien"" OR ""1"))
177
+ end
123
178
  end
124
179
 
125
180
  it 'leaves a hash comment untouched' do
@@ -228,6 +283,23 @@ module ForestLiana
228
283
  .to raise_error(ForestLiana::Errors::LiveQueryError)
229
284
  end
230
285
 
286
+ it 'prefixes the error with the chart label by default' do
287
+ request_context_variables['x.value'] = 'users]'
288
+
289
+ expect { inject('SELECT COUNT(*) AS value FROM [{{x.value}}]', sqlite_connection) }
290
+ .to raise_error(ForestLiana::Errors::LiveQueryError, /\ALive Query Chart: The value of {{x.value}}/)
291
+ end
292
+
293
+ it 'prefixes the error with the prefix it is given' do
294
+ request_context_variables['x.value'] = 'users]'
295
+
296
+ expect {
297
+ LiveQueryInjector.inject(
298
+ 'SELECT COUNT(*) AS value FROM [{{x.value}}]', context_variables, nil, sqlite_connection, error_prefix: ''
299
+ )
300
+ }.to raise_error(ForestLiana::Errors::LiveQueryError, /\AThe value of {{x.value}}/)
301
+ end
302
+
231
303
  it 'reads a nested block comment marker as plain comment text' do
232
304
  request_context_variables['x.value'] = '0 OR 1=1'
233
305
 
@@ -255,6 +327,7 @@ module ForestLiana
255
327
  'n.value' => '42',
256
328
  'd.value' => '4.5',
257
329
  'l.value' => '1,2,3',
330
+ 'spaced.value' => '1, 2 ,3',
258
331
  'b.value' => 'FALSE',
259
332
  'neg.value' => '-1',
260
333
  's.value' => 'DESC'
@@ -262,10 +335,10 @@ module ForestLiana
262
335
  end
263
336
 
264
337
  it 'injects unsigned numbers, lists of numbers and booleans as they are, everything else as a string' do
265
- query = 'SELECT {{n.value}}, {{d.value}}, ({{l.value}}), {{b.value}}, {{neg.value}}, {{s.value}}'
338
+ query = 'SELECT {{n.value}}, {{d.value}}, ({{l.value}}), ({{spaced.value}}), {{b.value}}, {{neg.value}}, {{s.value}}'
266
339
 
267
340
  expect(inject(query, postgresql_connection))
268
- .to eq("SELECT 42, 4.5, (1,2,3), FALSE, '-1', 'DESC'")
341
+ .to eq("SELECT 42, 4.5, (1,2,3), (1, 2 ,3), FALSE, '-1', 'DESC'")
269
342
  end
270
343
  end
271
344
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: forest_liana
3
3
  version: !ruby/object:Gem::Version
4
- version: 9.22.16
4
+ version: 9.22.18
5
5
  platform: ruby
6
6
  authors:
7
7
  - Sandro Munda
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-30 00:00:00.000000000 Z
11
+ date: 2026-11-03 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rails