Merge branch '21910-remove-api_client_id'
[arvados.git] / services / api / test / test_helper.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require_relative '../lib/update_permissions'
6
7 ENV["RAILS_ENV"] = "test"
8 unless ENV["NO_COVERAGE_TEST"]
9   begin
10     verbose_orig = $VERBOSE
11     begin
12       $VERBOSE = nil
13       require 'simplecov'
14       require 'simplecov-rcov'
15     ensure
16       $VERBOSE = verbose_orig
17     end
18     class SimpleCov::Formatter::MergedFormatter
19       def format(result)
20         SimpleCov::Formatter::HTMLFormatter.new.format(result)
21         SimpleCov::Formatter::RcovFormatter.new.format(result)
22       end
23     end
24     SimpleCov.formatter = SimpleCov::Formatter::MergedFormatter
25     SimpleCov.start do
26       add_filter '/test/'
27       add_filter 'initializers/secret_token'
28     end
29   rescue Exception => e
30     $stderr.puts "SimpleCov unavailable (#{e}). Proceeding without."
31   end
32 end
33
34 require File.expand_path('../../config/environment', __FILE__)
35 require 'rails/test_help'
36 require 'mocha'
37 require 'mocha/minitest'
38
39 module ArvadosTestSupport
40   def json_response
41     Oj.strict_load response.body
42   end
43
44   def api_token(api_client_auth_name)
45     api_client_authorizations(api_client_auth_name).token
46   end
47
48   def auth(api_client_auth_name)
49     {'HTTP_AUTHORIZATION' => "Bearer #{api_token(api_client_auth_name)}"}
50   end
51
52   def full_text_excluded_columns
53     [
54       # All the columns that end with "hash" or "uuid" as of June 2024/Arvados 3.0.
55       # It's okay if this list isn't complete, it just needs to be complete
56       # enough to test that full text indexes exclude the right columns.
57       "authorized_user_uuid",
58       "auth_uuid",
59       "cancelled_by_client_uuid",
60       "cancelled_by_user_uuid",
61       "container_uuid",
62       "current_version_uuid",
63       "for_container_uuid",
64       "frozen_by_uuid",
65       "group_uuid",
66       "head_uuid",
67       "is_locked_by_uuid",
68       "locked_by_uuid",
69       "log_uuid",
70       "modified_by_client_uuid",
71       "modified_by_user_uuid",
72       "node_uuid",
73       "object_owner_uuid",
74       "object_uuid",
75       "output_uuid",
76       "owner_uuid",
77       "perm_origin_uuid",
78       "portable_data_hash",
79       "pri_container_uuid",
80       "redirect_to_user_uuid",
81       "requesting_container_uuid",
82       "starting_uuid",
83       "tail_uuid",
84       "target_uuid",
85       "user_uuid",
86       "uuid",
87     ]
88   end
89
90   def show_errors model
91     return lambda { model.errors.full_messages.inspect }
92   end
93 end
94
95 class ActiveSupport::TestCase
96   include FactoryBot::Syntax::Methods
97   fixtures :all
98
99   include ArvadosTestSupport
100   include CurrentApiClient
101
102   setup do
103     Thread.current[:api_client_ip_address] = nil
104     Thread.current[:api_client_authorization] = nil
105     Thread.current[:token] = nil
106     Thread.current[:user] = nil
107     restore_configuration
108   end
109
110   teardown do
111     # Confirm that any changed configuration doesn't include non-symbol keys
112     $arvados_config.keys.each do |conf_name|
113       conf = Rails.configuration.send(conf_name)
114       confirm_keys_as_symbols(conf, conf_name) if conf.respond_to?('keys')
115     end
116   end
117
118   def assert_equal(expect, *args)
119     if expect.nil?
120       assert_nil(*args)
121     else
122       super
123     end
124   end
125
126   def assert_not_allowed
127     # Provide a block that calls a Rails boolean "true or false" success value,
128     # like model.save or model.destroy.  This method will test that it either
129     # returns false, or raises a Permission Denied exception.
130     begin
131       refute(yield)
132     rescue ArvadosModel::PermissionDeniedError
133     end
134   end
135
136   def add_permission_link from_who, to_what, perm_type
137     act_as_system_user do
138       Link.create!(tail_uuid: from_who.uuid,
139                    head_uuid: to_what.uuid,
140                    link_class: 'permission',
141                    name: perm_type)
142     end
143   end
144
145   def confirm_keys_as_symbols(conf, conf_name)
146     assert(conf.is_a?(ActiveSupport::OrderedOptions), "#{conf_name} should be an OrderedOptions object")
147     conf.keys.each do |k|
148       assert(k.is_a?(Symbol), "Key '#{k}' on section '#{conf_name}' should be a Symbol")
149       confirm_keys_as_symbols(conf[k], "#{conf_name}.#{k}") if conf[k].respond_to?('keys')
150     end
151   end
152
153   def restore_configuration
154     # Restore configuration settings changed during tests
155     ConfigLoader.copy_into_config $arvados_config, Rails.configuration
156     ConfigLoader.copy_into_config $remaining_config, Rails.configuration
157   end
158
159   def set_user_from_auth(auth_name)
160     client_auth = api_client_authorizations(auth_name)
161     client_auth.user.forget_cached_group_perms
162     Thread.current[:api_client_authorization] = client_auth
163     Thread.current[:user] = client_auth.user
164     Thread.current[:token] = client_auth.token
165   end
166
167   def expect_json
168     self.request.headers["Accept"] = "text/json"
169   end
170
171   def authorize_with api_client_auth_name
172     authorize_with_token api_client_authorizations(api_client_auth_name).token
173   end
174
175   def authorize_with_token token
176     t = token
177     t = t.token if t.respond_to? :token
178     ArvadosApiToken.new.call("rack.input" => "",
179                              "HTTP_AUTHORIZATION" => "Bearer #{t}")
180   end
181
182   def salt_token(fixture:, remote:)
183     auth = api_client_authorizations(fixture)
184     uuid = auth.uuid
185     token = auth.api_token
186     hmac = OpenSSL::HMAC.hexdigest('sha1', token, remote)
187     return "v2/#{uuid}/#{hmac}"
188   end
189
190   def self.skip_slow_tests?
191     !(ENV['RAILS_TEST_SHORT'] || '').empty?
192   end
193
194   def self.skip(*args, &block)
195   end
196
197   def self.slow_test(name, &block)
198     test(name, &block) unless skip_slow_tests?
199   end
200 end
201
202 class ActionController::TestCase
203   setup do
204     @test_counter = 0
205     self.request.headers['Accept'] = 'application/json'
206     self.request.headers['Content-Type'] = 'application/json'
207   end
208
209   def check_counter action
210     @test_counter += 1
211     if @test_counter == 2
212       assert_equal 1, 2, "Multiple actions in functional test"
213     end
214   end
215
216   [:get, :post, :put, :patch, :delete].each do |method|
217     define_method method do |action, **kwargs|
218       check_counter action
219       # After Rails 5.0 upgrade, some params don't get properly serialized.
220       # One case are filters: [['attr', 'op', 'val']] become [['attr'], ['op'], ['val']]
221       # if not passed upstream as a JSON string.
222       if kwargs[:params].is_a?(Hash)
223         kwargs[:params].each do |key, _|
224           next if key == :exclude_script_versions # Job Reuse tests
225           # Keys could be: :filters, :where, etc
226           if [Array, Hash].include?(kwargs[:params][key].class)
227             kwargs[:params][key] = SafeJSON.dump(kwargs[:params][key])
228           end
229         end
230       end
231       super action, **kwargs
232     end
233   end
234
235   def self.suite
236     s = super
237     def s.run(*args)
238       @test_case.startup()
239       begin
240         super
241       ensure
242         @test_case.shutdown()
243       end
244     end
245     s
246   end
247   def self.startup; end
248   def self.shutdown; end
249 end
250
251 class ActionDispatch::IntegrationTest
252   teardown do
253     Thread.current[:api_client_ip_address] = nil
254     Thread.current[:api_client_authorization] = nil
255     Thread.current[:token] = nil
256     Thread.current[:user] = nil
257   end
258 end
259
260 # Ensure permissions are computed from the test fixtures.
261 refresh_permissions
262 refresh_trashed