21842: Merge branch '21842-improve-sharing'
[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 contain a UUID or PDH as of June 2024/Arvados 3.0.
55       # It's okay if this list gets out-of-date, 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_image",
62       "container_uuid",
63       "current_version_uuid",
64       "for_container_uuid",
65       "frozen_by_uuid",
66       "group_uuid",
67       "head_uuid",
68       "is_locked_by_uuid",
69       "locked_by_uuid",
70       "log_uuid",
71       "modified_by_client_uuid",
72       "modified_by_user_uuid",
73       "node_uuid",
74       "object_owner_uuid",
75       "object_uuid",
76       "output_uuid",
77       "owner_uuid",
78       "perm_origin_uuid",
79       "portable_data_hash",
80       "pri_container_uuid",
81       "redirect_to_user_uuid",
82       "requesting_container_uuid",
83       "starting_uuid",
84       "tail_uuid",
85       "target_uuid",
86       "user_uuid",
87       "uuid",
88     ]
89   end
90
91   def show_errors model
92     return lambda { model.errors.full_messages.inspect }
93   end
94 end
95
96 class ActiveSupport::TestCase
97   include FactoryBot::Syntax::Methods
98   fixtures :all
99
100   include ArvadosTestSupport
101   include CurrentApiClient
102
103   setup do
104     Thread.current[:api_client_ip_address] = nil
105     Thread.current[:api_client_authorization] = nil
106     Thread.current[:token] = nil
107     Thread.current[:user] = nil
108     restore_configuration
109   end
110
111   teardown do
112     # Confirm that any changed configuration doesn't include non-symbol keys
113     $arvados_config.keys.each do |conf_name|
114       conf = Rails.configuration.send(conf_name)
115       confirm_keys_as_symbols(conf, conf_name) if conf.respond_to?('keys')
116     end
117   end
118
119   def assert_equal(expect, *args)
120     if expect.nil?
121       assert_nil(*args)
122     else
123       super
124     end
125   end
126
127   def assert_not_allowed
128     # Provide a block that calls a Rails boolean "true or false" success value,
129     # like model.save or model.destroy.  This method will test that it either
130     # returns false, or raises a Permission Denied exception.
131     begin
132       refute(yield)
133     rescue ArvadosModel::PermissionDeniedError
134     end
135   end
136
137   def add_permission_link from_who, to_what, perm_type
138     act_as_system_user do
139       Link.create!(tail_uuid: from_who.uuid,
140                    head_uuid: to_what.uuid,
141                    link_class: 'permission',
142                    name: perm_type)
143     end
144   end
145
146   def confirm_keys_as_symbols(conf, conf_name)
147     assert(conf.is_a?(ActiveSupport::OrderedOptions), "#{conf_name} should be an OrderedOptions object")
148     conf.keys.each do |k|
149       assert(k.is_a?(Symbol), "Key '#{k}' on section '#{conf_name}' should be a Symbol")
150       confirm_keys_as_symbols(conf[k], "#{conf_name}.#{k}") if conf[k].respond_to?('keys')
151     end
152   end
153
154   def restore_configuration
155     # Restore configuration settings changed during tests
156     ConfigLoader.copy_into_config $arvados_config, Rails.configuration
157     ConfigLoader.copy_into_config $remaining_config, Rails.configuration
158   end
159
160   def set_user_from_auth(auth_name)
161     client_auth = api_client_authorizations(auth_name)
162     client_auth.user.forget_cached_group_perms
163     Thread.current[:api_client_authorization] = client_auth
164     Thread.current[:user] = client_auth.user
165     Thread.current[:token] = client_auth.token
166   end
167
168   def expect_json
169     self.request.headers["Accept"] = "text/json"
170   end
171
172   def authorize_with api_client_auth_name
173     authorize_with_token api_client_authorizations(api_client_auth_name).token
174   end
175
176   def authorize_with_token token
177     t = token
178     t = t.token if t.respond_to? :token
179     ArvadosApiToken.new.call("rack.input" => "",
180                              "HTTP_AUTHORIZATION" => "Bearer #{t}")
181   end
182
183   def salt_token(fixture:, remote:)
184     auth = api_client_authorizations(fixture)
185     uuid = auth.uuid
186     token = auth.api_token
187     hmac = OpenSSL::HMAC.hexdigest('sha1', token, remote)
188     return "v2/#{uuid}/#{hmac}"
189   end
190
191   def self.skip_slow_tests?
192     !(ENV['RAILS_TEST_SHORT'] || '').empty?
193   end
194
195   def self.skip(*args, &block)
196   end
197
198   def self.slow_test(name, &block)
199     test(name, &block) unless skip_slow_tests?
200   end
201 end
202
203 class ActionController::TestCase
204   setup do
205     @test_counter = 0
206     self.request.headers['Accept'] = 'application/json'
207     self.request.headers['Content-Type'] = 'application/json'
208   end
209
210   def check_counter action
211     @test_counter += 1
212     if @test_counter == 2
213       assert_equal 1, 2, "Multiple actions in functional test"
214     end
215   end
216
217   [:get, :post, :put, :patch, :delete].each do |method|
218     define_method method do |action, **kwargs|
219       check_counter action
220       # After Rails 5.0 upgrade, some params don't get properly serialized.
221       # One case are filters: [['attr', 'op', 'val']] become [['attr'], ['op'], ['val']]
222       # if not passed upstream as a JSON string.
223       if kwargs[:params].is_a?(Hash)
224         kwargs[:params].each do |key, _|
225           next if key == :exclude_script_versions # Job Reuse tests
226           # Keys could be: :filters, :where, etc
227           if [Array, Hash].include?(kwargs[:params][key].class)
228             kwargs[:params][key] = SafeJSON.dump(kwargs[:params][key])
229           end
230         end
231       end
232       super action, **kwargs
233     end
234   end
235
236   def self.suite
237     s = super
238     def s.run(*args)
239       @test_case.startup()
240       begin
241         super
242       ensure
243         @test_case.shutdown()
244       end
245     end
246     s
247   end
248   def self.startup; end
249   def self.shutdown; end
250 end
251
252 class ActionDispatch::IntegrationTest
253   teardown do
254     Thread.current[:api_client_ip_address] = nil
255     Thread.current[:api_client_authorization] = nil
256     Thread.current[:token] = nil
257     Thread.current[:user] = nil
258   end
259 end
260
261 # Ensure permissions are computed from the test fixtures.
262 refresh_permissions
263 refresh_trashed