forest_liana 9.22.15 → 9.22.17

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: dc9e247d2d65125925e14127a256acb70326504b4c1e2fc90daaf3b792736025
4
- data.tar.gz: 7039ebbb67be595efd366b94d57a35881448f9747cba39cf2e8e35b1f88a083e
3
+ metadata.gz: 10b9f231f7625702c1c63e6c2c2133360ccf2e9eaa6a68069a206669d902e93b
4
+ data.tar.gz: 73c495fa6e0e02428eff8147b57387a640a244c91a4f745e7b0db7ac0d12d146
5
5
  SHA512:
6
- metadata.gz: 3bf2d66f16eaedc067bfca8422a0274255bc9bc6d86057e251bdb65dd41191859e02344f2712356511c437bf03a525c5ff11b2a7f4ebb972104420baafcd1fbc
7
- data.tar.gz: 07b0b79be5105719f3cffbb590717731031d3e1cd0fc81eb6e5d2c72a60f7413e411661f4f301a97294fc08e4cadac9e1d547ceb9c9cec1b9b0bbeadae569b3b
6
+ metadata.gz: c3b01f5f3f3c4572fbad83d6b39436bb2eb12bd266fa61ac7048e0172d5922493b1cb1e0afeb0f6af0f07fe24ef45ac79804c298af2ee826a8221f542b850eb8
7
+ data.tar.gz: 9f699625865575db5ebf7f7104b9004ecf8d091feb2401e490091b3eed83ef049eac4ebda850eeee565c04a80d52a5c7e4273b7c119643718be13d8c28c4e825
@@ -1,5 +1,12 @@
1
1
  module ForestLiana
2
2
  class StripeController < ForestLiana::ApplicationController
3
+ include ForestLiana::Ability
4
+
5
+ rescue_from ForestLiana::Ability::Exceptions::TriggerForbidden, with: :render_error
6
+ rescue_from ForestLiana::Ability::Exceptions::RequireApproval, with: :render_error
7
+ rescue_from ForestLiana::Ability::Exceptions::UnsupportedConditionals, with: :render_error
8
+
9
+ before_action :authorize_refund, only: :refund
3
10
 
4
11
  def payments
5
12
  getter = StripePaymentsGetter.new(params, request.headers['Stripe-Secret-Key'],
@@ -27,7 +34,7 @@ module ForestLiana
27
34
 
28
35
  def refund
29
36
  begin
30
- refunder = StripePaymentRefunder.new(params)
37
+ refunder = StripePaymentRefunder.new(@refund_parameters)
31
38
  refunder.perform
32
39
 
33
40
  render serializer: nil, json: {}
@@ -137,5 +144,24 @@ module ForestLiana
137
144
  def get_serializer_type(suffix)
138
145
  "#{params[:collection]}_#{suffix}"
139
146
  end
147
+
148
+ private
149
+
150
+ def authorize_refund
151
+ raise ForestLiana::Errors::HTTP422Error.new if params.dig(:data, :attributes, :requester_id).present?
152
+
153
+ parameters = refund_request_parameters
154
+ collection_name = parameters.dig(:data, :attributes, :collection_name).to_s
155
+ is_integration_action_authorized?(forest_user, collection_name, 'Refund', params)
156
+ @refund_parameters = parameters
157
+ end
158
+
159
+ def refund_request_parameters
160
+ return params.permit! unless params.dig(:data, :attributes, :signed_approval_request)
161
+
162
+ ForestLiana::Ability::Permission::RequestPermission.decodeSignedApprovalRequest(params.permit!)
163
+ rescue JWT::DecodeError
164
+ raise ForestLiana::Errors::HTTP400Error.new('Invalid signed action parameters')
165
+ end
140
166
  end
141
167
  end
@@ -0,0 +1,17 @@
1
+ module ForestLiana
2
+ module Ability
3
+ module Exceptions
4
+ class UnsupportedConditionals < ForestLiana::Errors::ExpectedError
5
+ def initialize(backtrace = nil)
6
+ super(
7
+ 422,
8
+ :unprocessable_entity,
9
+ 'The roles conditions (conditional smart actions) are not supported with Smart Collection. Please contact an administrator.',
10
+ 'UnsupportedConditionalsFeatureError',
11
+ backtrace
12
+ )
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -43,7 +43,7 @@ module ForestLiana
43
43
  elsif @smart_action['approvalRequired'].include?(@user['roleId'])
44
44
  if condition_by_role_id(@smart_action['approvalRequiredConditions']).blank? || match_conditions('approvalRequiredConditions')
45
45
  # Global actions target no specific records — never resolve.
46
- if @parameters[:data][:attributes][:all_records] && @action_type != 'global'
46
+ if @parameters[:data][:attributes][:all_records] && @action_type != 'global' && @collection
47
47
  record_ids = select_all_record_ids
48
48
  end
49
49
 
@@ -83,6 +83,8 @@ module ForestLiana
83
83
  end
84
84
 
85
85
  def match_conditions(condition_name)
86
+ raise ForestLiana::Ability::Exceptions::UnsupportedConditionals.new unless @collection
87
+
86
88
  begin
87
89
  attributes = @parameters[:data][:attributes]
88
90
  condition = condition_by_role_id(@smart_action[condition_name])
@@ -53,6 +53,19 @@ module ForestLiana
53
53
  end
54
54
  end
55
55
 
56
+ # An integration collection (`<Model>_stripe_payments`, …) has no model: a select-all is not
57
+ # resolved for its approval, and a role condition on its action is refused as unsupported.
58
+ def is_integration_action_authorized?(user, collection_name, action_name, parameters)
59
+ return true unless has_permission_system?
60
+
61
+ schema_action = find_integration_action(collection_name, action_name)
62
+ user_data = get_user_data(user['id'])
63
+ smart_action = schema_action && get_collections_permissions_data.dig(collection_name, :actions, action_name)
64
+ raise ForestLiana::Ability::Exceptions::TriggerForbidden.new unless user_data && smart_action
65
+
66
+ SmartActionChecker.new(parameters, nil, smart_action, user_data, schema_action.type, user).can_execute?
67
+ end
68
+
56
69
  # +refetch+ drops the cached permissions first. Only a caller about to refuse on a denial asks
57
70
  # for it (a stale, up to TTL-old cache may sit behind a permission granted moments ago): the
58
71
  # refetch rewrites the cluster-wide `forest.collections` entry and this request's copy, so a
@@ -367,6 +380,12 @@ module ForestLiana
367
380
  nil
368
381
  end
369
382
 
383
+ def find_integration_action(collection_name, action_name)
384
+ collection = ForestLiana.apimap.find { |candidate| candidate.name.to_s == collection_name && candidate.integration.present? }
385
+
386
+ collection&.actions&.find { |action| action.name == action_name }
387
+ end
388
+
370
389
  def find_action_from_endpoint(collection_name, endpoint, http_method)
371
390
  collection = ForestLiana.apimap.find { |collection| collection.name.to_s == collection_name }
372
391
 
@@ -235,7 +235,7 @@ module ForestLiana
235
235
 
236
236
  begin
237
237
  segment_query = @params[:segmentQuery].gsub(/\;\s*$/, '')
238
- segment_query = ScopeManager.inject_context_variables_on_query(segment_query, @user)
238
+ segment_query = ScopeManager.inject_context_variables_on_query(segment_query, @user, @resource.connection)
239
239
 
240
240
  @records = @records.where(
241
241
  "#{@resource.table_name}.#{@resource.primary_key} IN (SELECT id FROM (#{segment_query}) as ids)"
@@ -55,11 +55,13 @@ module ForestLiana
55
55
  Utils::ContextVariablesInjector.inject_context_in_filter(filter, context_variables)
56
56
  end
57
57
 
58
- def self.inject_context_variables_on_query(query, user)
58
+ def self.inject_context_variables_on_query(query, user, connection = ActiveRecord::Base.connection)
59
+ return query unless query.match?(Utils::ContextVariablesInjector::PLACEHOLDER)
60
+
59
61
  retrieve = fetch_scopes(user['rendering_id'])
60
62
  context_variables = Utils::ContextVariables.new(retrieve['team'], user)
61
63
 
62
- Utils::ContextVariablesInjector.inject_context_in_value(query, context_variables)
64
+ Utils::LiveQueryInjector.inject(query, context_variables, nil, connection, error_prefix: '')
63
65
  end
64
66
 
65
67
  def self.invalidate_scope_cache(rendering_id)
@@ -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.15"
2
+ VERSION = "9.22.17"
3
3
  end
@@ -0,0 +1,292 @@
1
+ require 'rails_helper'
2
+
3
+ describe 'Stripe payments refund', type: :request do
4
+ let(:rendering_id) { 13 }
5
+ let(:user_id) { 38 }
6
+ let(:role_id) { 1 }
7
+ let(:approver_role_id) { 3 }
8
+ let(:trigger_roles) { [role_id] }
9
+ let(:approval_roles) { [] }
10
+ let(:user_approval_roles) { [] }
11
+ let(:trigger_conditions) { [] }
12
+ let(:permissions_users) { [{ 'id' => user_id, 'roleId' => role_id }] }
13
+ let(:has_permission_system) { true }
14
+ let(:cache) { ActiveSupport::Cache::MemoryStore.new }
15
+ let(:refunder) { instance_double(ForestLiana::StripePaymentRefunder, perform: nil) }
16
+ let(:refund_requests) { [] }
17
+ let(:payments_collection) do
18
+ ForestLiana::Model::Collection.new(
19
+ name: 'Island_stripe_payments',
20
+ integration: 'stripe',
21
+ is_virtual: true,
22
+ actions: [ForestLiana::Model::Action.new(name: 'Refund', endpoint: '/forest/stripe_payments/refunds')]
23
+ )
24
+ end
25
+
26
+ let(:token) do
27
+ JWT.encode({
28
+ id: user_id,
29
+ email: 'michael.kelso@that70.show',
30
+ first_name: 'Michael',
31
+ last_name: 'Kelso',
32
+ team: 'Operations',
33
+ rendering_id: rendering_id,
34
+ exp: Time.now.to_i + 2.weeks.to_i,
35
+ permission_level: 'user'
36
+ }, ForestLiana.auth_secret, 'HS256')
37
+ end
38
+
39
+ let(:headers) do
40
+ {
41
+ 'Accept' => 'application/json',
42
+ 'Content-Type' => 'application/json',
43
+ 'Authorization' => "Bearer #{token}"
44
+ }
45
+ end
46
+
47
+ let(:attributes) do
48
+ {
49
+ collection_name: 'Island_stripe_payments',
50
+ ids: ['ch_1', 'ch_2'],
51
+ values: {},
52
+ all_records: false,
53
+ smart_action_id: 'Island_stripe_payments-Refund'
54
+ }
55
+ end
56
+
57
+ let(:params) { { data: { attributes: attributes, type: 'custom-action-requests' }, timezone: 'Europe/Paris' } }
58
+
59
+ def environment_permissions
60
+ enabled = { 'roles' => [role_id, approver_role_id] }
61
+ crud = %w[browseEnabled readEnabled editEnabled addEnabled deleteEnabled exportEnabled].to_h { |key| [key, enabled] }
62
+ refund = {
63
+ 'triggerEnabled' => { 'roles' => trigger_roles },
64
+ 'triggerConditions' => trigger_conditions,
65
+ 'approvalRequired' => { 'roles' => approval_roles },
66
+ 'approvalRequiredConditions' => [],
67
+ 'userApprovalEnabled' => { 'roles' => user_approval_roles },
68
+ 'userApprovalConditions' => [],
69
+ 'selfApprovalEnabled' => { 'roles' => [] }
70
+ }
71
+
72
+ { 'collections' => { 'Island_stripe_payments' => { 'collection' => crud, 'actions' => { 'Refund' => refund } } } }
73
+ end
74
+
75
+ def signed_approval_request(ids:, requester_id:)
76
+ JWT.encode({
77
+ data: {
78
+ attributes: attributes.merge(ids: ids, requester_id: requester_id),
79
+ type: 'custom-action-requests'
80
+ }
81
+ }, ForestLiana.env_secret, 'HS256')
82
+ end
83
+
84
+ def refund(request_headers = headers)
85
+ post '/forest/stripe_payments/refunds', params: JSON.dump(params), headers: request_headers
86
+ end
87
+
88
+ def refunded_ids
89
+ refund_requests.map { |refund_params| refund_params[:data][:attributes][:ids] }
90
+ end
91
+
92
+ before do
93
+ ForestLiana.apimap << payments_collection
94
+
95
+ allow(Rails).to receive(:cache).and_return(cache)
96
+ allow_any_instance_of(ForestLiana::Ability::Fetch).to receive(:get_permissions) do |_, path|
97
+ case path
98
+ when '/liana/v4/permissions/environment' then has_permission_system ? environment_permissions : true
99
+ when '/liana/v4/permissions/users' then permissions_users
100
+ end
101
+ end
102
+
103
+ allow(ForestLiana::StripePaymentRefunder).to receive(:new) do |refund_params|
104
+ refund_requests << refund_params
105
+ refunder
106
+ end
107
+ allow(ForestLiana::IpWhitelist).to receive(:is_ip_whitelist_retrieved) { true }
108
+ allow(ForestLiana::IpWhitelist).to receive(:is_ip_valid) { true }
109
+ end
110
+
111
+ after { ForestLiana.apimap.delete(payments_collection) }
112
+
113
+ context 'when the role is allowed to trigger the Refund action' do
114
+ it 'responds 200 and refunds each requested charge' do
115
+ refund
116
+
117
+ expect(response.status).to eq(200)
118
+ expect(refunded_ids).to eq([['ch_1', 'ch_2']])
119
+ expect(refunder).to have_received(:perform).with(no_args)
120
+ end
121
+ end
122
+
123
+ context 'when the project has no permission system' do
124
+ let(:has_permission_system) { false }
125
+ let(:trigger_roles) { [] }
126
+
127
+ it 'responds 200 and refunds each requested charge' do
128
+ refund
129
+
130
+ expect(response.status).to eq(200)
131
+ expect(refunded_ids).to eq([['ch_1', 'ch_2']])
132
+ end
133
+ end
134
+
135
+ context 'when the role is not allowed to trigger the Refund action' do
136
+ let(:trigger_roles) { [approver_role_id] }
137
+
138
+ it 'responds 403 and refunds nothing' do
139
+ refund
140
+
141
+ expect(response.status).to eq(403)
142
+ expect(JSON.parse(response.body)['errors'].first['name']).to eq('CustomActionTriggerForbiddenError')
143
+ expect(ForestLiana::StripePaymentRefunder).not_to have_received(:new)
144
+ end
145
+ end
146
+
147
+ context 'when the user is no longer in the permissions system' do
148
+ let(:permissions_users) { [] }
149
+
150
+ it 'responds 403 and refunds nothing' do
151
+ refund
152
+
153
+ expect(response.status).to eq(403)
154
+ expect(ForestLiana::StripePaymentRefunder).not_to have_received(:new)
155
+ end
156
+ end
157
+
158
+ context 'when the Refund action requires approval for the role' do
159
+ let(:approval_roles) { [role_id] }
160
+ let(:user_approval_roles) { [approver_role_id] }
161
+
162
+ it 'responds 403 with the roles allowed to approve and refunds nothing' do
163
+ refund
164
+
165
+ expect(response.status).to eq(403)
166
+ error = JSON.parse(response.body)['errors'].first
167
+ expect(error['name']).to eq('CustomActionRequiresApprovalError')
168
+ expect(error['data']).to eq('roleIdsAllowedToApprove' => [approver_role_id])
169
+ expect(ForestLiana::StripePaymentRefunder).not_to have_received(:new)
170
+ end
171
+ end
172
+
173
+ context 'when an approver sends a signed approval request' do
174
+ let(:role_id) { approver_role_id }
175
+ let(:trigger_roles) { [] }
176
+ let(:user_approval_roles) { [approver_role_id] }
177
+ let(:attributes) do
178
+ super().merge(ids: ['ch_99'], signed_approval_request: signed_approval_request(ids: ['ch_1'], requester_id: 12))
179
+ end
180
+
181
+ it 'responds 200 and refunds the charges of the approved request' do
182
+ refund
183
+
184
+ expect(response.status).to eq(200)
185
+ expect(refunded_ids).to eq([['ch_1']])
186
+ end
187
+ end
188
+
189
+ context 'when the approval request is not signed with the environment secret' do
190
+ let(:role_id) { approver_role_id }
191
+ let(:trigger_roles) { [] }
192
+ let(:user_approval_roles) { [approver_role_id] }
193
+ let(:attributes) do
194
+ forged = JWT.encode({ data: { attributes: { collection_name: 'Island_stripe_payments', ids: ['ch_1'], requester_id: 12 } } }, 'another-secret', 'HS256')
195
+ super().merge(signed_approval_request: forged)
196
+ end
197
+
198
+ it 'responds 400 and refunds nothing' do
199
+ refund
200
+
201
+ expect(response.status).to eq(400)
202
+ expect(JSON.parse(response.body)['errors'].first['detail']).to eq('Invalid signed action parameters')
203
+ expect(ForestLiana::StripePaymentRefunder).not_to have_received(:new)
204
+ end
205
+ end
206
+
207
+ context 'when the body carries a requester id outside a signed approval request' do
208
+ let(:attributes) { super().merge(requester_id: 12) }
209
+
210
+ it 'responds 422 and refunds nothing, even for a role allowed to trigger the Refund action' do
211
+ refund
212
+
213
+ expect(response.status).to eq(422)
214
+ expect(ForestLiana::StripePaymentRefunder).not_to have_received(:new)
215
+ end
216
+ end
217
+
218
+ context 'when the role can trigger the Refund action only under a condition' do
219
+ let(:trigger_conditions) do
220
+ [{ 'roleId' => role_id, 'filter' => { 'field' => 'amount', 'operator' => 'greater_than', 'value' => 0, 'source' => 'data' } }]
221
+ end
222
+
223
+ it 'responds 422 and refunds nothing, since role conditions are not supported on Stripe payments' do
224
+ refund
225
+
226
+ expect(response.status).to eq(422)
227
+ expect(JSON.parse(response.body)['errors'].first['name']).to eq('UnsupportedConditionalsFeatureError')
228
+ expect(ForestLiana::StripePaymentRefunder).not_to have_received(:new)
229
+ end
230
+ end
231
+
232
+ context 'when a role needing approval selects every payment' do
233
+ let(:approval_roles) { [role_id] }
234
+ let(:user_approval_roles) { [approver_role_id] }
235
+ let(:attributes) { super().merge(all_records: true, all_records_ids_excluded: []) }
236
+
237
+ it 'responds 403 with the roles allowed to approve and refunds nothing' do
238
+ refund
239
+
240
+ expect(response.status).to eq(403)
241
+ error = JSON.parse(response.body)['errors'].first
242
+ expect(error['name']).to eq('CustomActionRequiresApprovalError')
243
+ expect(error['data']).to eq('roleIdsAllowedToApprove' => [approver_role_id])
244
+ expect(ForestLiana::StripePaymentRefunder).not_to have_received(:new)
245
+ end
246
+ end
247
+
248
+ context 'when the request names a collection without the Stripe Refund action' do
249
+ let(:attributes) { super().merge(collection_name: 'Island') }
250
+
251
+ it 'responds 403 and refunds nothing' do
252
+ refund
253
+
254
+ expect(response.status).to eq(403)
255
+ expect(JSON.parse(response.body)['errors'].first['name']).to eq('CustomActionTriggerForbiddenError')
256
+ expect(ForestLiana::StripePaymentRefunder).not_to have_received(:new)
257
+ end
258
+ end
259
+
260
+ context 'when the request names no collection' do
261
+ let(:attributes) { super().except(:collection_name) }
262
+
263
+ it 'responds 403 and refunds nothing' do
264
+ refund
265
+
266
+ expect(response.status).to eq(403)
267
+ expect(JSON.parse(response.body)['errors'].first['name']).to eq('CustomActionTriggerForbiddenError')
268
+ expect(ForestLiana::StripePaymentRefunder).not_to have_received(:new)
269
+ end
270
+ end
271
+
272
+ context 'when the project has no permission system and the request names no collection' do
273
+ let(:has_permission_system) { false }
274
+ let(:attributes) { super().except(:collection_name) }
275
+
276
+ it 'responds 200 and refunds each requested charge' do
277
+ refund
278
+
279
+ expect(response.status).to eq(200)
280
+ expect(refunded_ids).to eq([['ch_1', 'ch_2']])
281
+ end
282
+ end
283
+
284
+ context 'when the request is not authenticated' do
285
+ it 'responds 401 and refunds nothing' do
286
+ refund(headers.except('Authorization'))
287
+
288
+ expect(response.status).to eq(401)
289
+ expect(ForestLiana::StripePaymentRefunder).not_to have_received(:new)
290
+ end
291
+ end
292
+ end
@@ -166,6 +166,47 @@ module ForestLiana
166
166
 
167
167
  expect(getter.records.map(&:name)).to eq(['Michel'])
168
168
  end
169
+
170
+ describe 'when the variable value carries SQL' do
171
+ let(:user) { { 'id' => '1', 'name' => "Michel' OR '1'='1", 'rendering_id' => rendering_id } }
172
+
173
+ it 'matches the value as a literal in the records' do
174
+ getter.perform
175
+
176
+ expect(getter.records).to be_empty
177
+ end
178
+
179
+ it 'matches the value as a literal in the count' do
180
+ getter.count
181
+
182
+ expect(getter.count).to eq 0
183
+ end
184
+ end
185
+
186
+ describe 'when every record of the segment is selected' do
187
+ def ids_from_request(user)
188
+ params = ActionController::Parameters.new(
189
+ data: {
190
+ attributes: {
191
+ collection_name: 'User',
192
+ all_records: true,
193
+ all_records_subset_query: {
194
+ segmentQuery: "SELECT id FROM users WHERE name = '{{currentUser.name}}'",
195
+ },
196
+ },
197
+ },
198
+ )
199
+ described_class.get_ids_from_request(params, user)
200
+ end
201
+
202
+ it 'injects the variable into the query that selects the ids' do
203
+ expect(ids_from_request(user)).to eq(User.where(name: 'Michel').pluck(:id))
204
+ end
205
+
206
+ it 'matches a value carrying SQL as a literal' do
207
+ expect(ids_from_request(user.merge('name' => "Michel' OR '1'='1"))).to be_empty
208
+ end
209
+ end
169
210
  end
170
211
 
171
212
  describe 'when there are more records than the page size' do
@@ -366,6 +366,46 @@ module ForestLiana
366
366
 
367
367
  expect(query).to eq "SELECT id FROM users WHERE email = '{{currentUser.email}}'"
368
368
  end
369
+
370
+ it 'should escape a value written inside a string' do
371
+ user['first_name'] = "x' OR '1'='1"
372
+
373
+ expect(described_class.inject_context_variables_on_query(
374
+ "SELECT id FROM users WHERE first_name = '{{currentUser.first_name}}'", user
375
+ )).to eq "SELECT id FROM users WHERE first_name = 'x'' OR ''1''=''1'"
376
+ end
377
+
378
+ it 'should quote a value written outside a string' do
379
+ user['first_name'] = '0 OR 1=1'
380
+
381
+ expect(described_class.inject_context_variables_on_query(
382
+ 'SELECT id FROM users WHERE first_name = {{currentUser.first_name}}', user
383
+ )).to eq "SELECT id FROM users WHERE first_name = '0 OR 1=1'"
384
+ end
385
+
386
+ it 'should inject a numeric value as is' do
387
+ expect(described_class.inject_context_variables_on_query(
388
+ 'SELECT id FROM users WHERE id = {{currentUser.id}}', user
389
+ )).to eq 'SELECT id FROM users WHERE id = 1'
390
+ end
391
+
392
+ it 'should not fetch the scopes when the query has no context variable' do
393
+ query_without_variable = 'SELECT id FROM users WHERE id > 1'
394
+
395
+ expect(described_class.inject_context_variables_on_query(query_without_variable, user))
396
+ .to eq query_without_variable
397
+ expect(ForestLiana::ForestApiRequester).not_to have_received(:get)
398
+ end
399
+
400
+ it 'should not prefix the error it raises with the chart label' do
401
+ user['first_name'] = 'a"b'
402
+
403
+ expect {
404
+ described_class.inject_context_variables_on_query(
405
+ 'SELECT id FROM users WHERE "{{currentUser.first_name}}" = 1', user
406
+ )
407
+ }.to raise_error(ForestLiana::Errors::LiveQueryError, /\AThe value of {{currentUser.first_name}}/)
408
+ end
369
409
  end
370
410
  end
371
411
  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.15
4
+ version: 9.22.17
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
@@ -286,6 +286,7 @@ files:
286
286
  - app/services/forest_liana/ability/exceptions/unauthorized_query_field_error.rb
287
287
  - app/services/forest_liana/ability/exceptions/unexposed_query_collection_error.rb
288
288
  - app/services/forest_liana/ability/exceptions/unknown_collection.rb
289
+ - app/services/forest_liana/ability/exceptions/unsupported_conditionals.rb
289
290
  - app/services/forest_liana/ability/fetch.rb
290
291
  - app/services/forest_liana/ability/permission.rb
291
292
  - app/services/forest_liana/ability/permission/request_permission.rb
@@ -498,6 +499,7 @@ files:
498
499
  - spec/requests/smart_field_named_like_unexposed_relation_spec.rb
499
500
  - spec/requests/stats_spec.rb
500
501
  - spec/requests/sti_record_conversion_spec.rb
502
+ - spec/requests/stripe_refund_spec.rb
501
503
  - spec/requests/test.ru
502
504
  - spec/requests/unresolved_polymorphic_relation_spec.rb
503
505
  - spec/requests/workflow_executions_spec.rb
@@ -863,6 +865,7 @@ test_files:
863
865
  - spec/requests/smart_field_named_like_unexposed_relation_spec.rb
864
866
  - spec/requests/stats_spec.rb
865
867
  - spec/requests/sti_record_conversion_spec.rb
868
+ - spec/requests/stripe_refund_spec.rb
866
869
  - spec/requests/test.ru
867
870
  - spec/requests/unresolved_polymorphic_relation_spec.rb
868
871
  - spec/requests/workflow_executions_spec.rb