1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
8 class LogTest < ActiveSupport::TestCase
9 include CurrentApiClient
11 EVENT_TEST_METHODS = {
12 :create => [:created_at, :assert_nil, :assert_not_nil],
13 :update => [:modified_at, :assert_not_nil, :assert_not_nil],
14 :delete => [nil, :assert_not_nil, :assert_nil],
18 @start_time = Time.now
22 def assert_properties(test_method, event, props, *keys)
23 verb = (test_method == :assert_nil) ? 'have nil' : 'define'
24 keys.each do |prop_name|
25 assert_includes(props, prop_name, "log properties missing #{prop_name}")
26 self.send(test_method, props[prop_name],
27 "#{event.to_s} log should #{verb} #{prop_name}")
31 def get_logs_about(thing)
32 Log.where(object_uuid: thing.uuid).order("created_at ASC").all
35 def assert_logged(thing, event_type)
36 logs = get_logs_about(thing)
37 assert_equal(@log_count, logs.size, "log count mismatch")
40 props = log.properties
41 assert_equal(current_user.andand.uuid, log.owner_uuid,
42 "log is not owned by current user")
43 assert_equal(current_user.andand.uuid, log.modified_by_user_uuid,
44 "log is not 'modified by' current user")
45 assert_equal(current_api_client.andand.uuid, log.modified_by_client_uuid,
46 "log is not 'modified by' current client")
47 assert_equal(thing.uuid, log.object_uuid, "log UUID mismatch")
48 assert_equal(event_type.to_s, log.event_type, "log event type mismatch")
49 time_method, old_props_test, new_props_test = EVENT_TEST_METHODS[event_type]
50 if time_method.nil? or (timestamp = thing.send(time_method)).nil?
51 assert(log.event_at >= @start_time, "log timestamp too old")
53 assert_in_delta(timestamp, log.event_at, 1, "log timestamp mismatch")
55 assert_properties(old_props_test, event_type, props,
56 'old_etag', 'old_attributes')
57 assert_properties(new_props_test, event_type, props,
58 'new_etag', 'new_attributes')
59 ['old_attributes', 'new_attributes'].each do |logattr|
60 next if !props[logattr]
61 assert_match /"created_at":"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{9}Z"/, Oj.dump(props, mode: :compat)
63 yield props if block_given?
66 def assert_logged_with_clean_properties(obj, event_type, excluded_attr)
67 assert_logged(obj, event_type) do |props|
68 ['old_attributes', 'new_attributes'].map do |logattr|
69 attributes = props[logattr]
70 next if attributes.nil?
71 refute_includes(attributes, excluded_attr,
72 "log #{logattr} includes #{excluded_attr}")
74 yield props if block_given?
78 test "creating a user makes a log" do
79 set_user_from_auth :admin_trustedclient
80 u = User.new(first_name: "Log", last_name: "Test")
82 assert_logged(u, :create) do |props|
83 assert_equal(u.etag, props['new_etag'], "new user etag mismatch")
84 assert_equal(u.first_name, props['new_attributes']['first_name'],
85 "new user first name mismatch")
86 assert_equal(u.last_name, props['new_attributes']['last_name'],
87 "new user first name mismatch")
91 test "updating a virtual machine makes a log" do
92 set_user_from_auth :admin_trustedclient
93 vm = virtual_machines(:testvm)
95 vm.hostname = 'testvm.testshell'
97 assert_logged(vm, :update) do |props|
98 assert_equal(orig_etag, props['old_etag'], "updated VM old etag mismatch")
99 assert_equal(vm.etag, props['new_etag'], "updated VM new etag mismatch")
100 assert_equal('testvm.shell', props['old_attributes']['hostname'],
101 "updated VM old name mismatch")
102 assert_equal('testvm.testshell', props['new_attributes']['hostname'],
103 "updated VM new name mismatch")
107 test "old_attributes preserves values deep inside a hash" do
108 set_user_from_auth :active
109 it = specimens(:owned_by_active_user)
110 it.properties = {'foo' => {'bar' => ['baz', 'qux', {'quux' => 'bleat'}]}}
113 it.properties['foo']['bar'][2]['quux'] = 'blert'
115 assert_logged it, :update do |props|
116 assert_equal 'bleat', props['old_attributes']['properties']['foo']['bar'][2]['quux']
117 assert_equal 'blert', props['new_attributes']['properties']['foo']['bar'][2]['quux']
121 test "destroying an authorization makes a log" do
122 set_user_from_auth :admin_trustedclient
123 auth = api_client_authorizations(:spectator)
124 orig_etag = auth.etag
125 orig_attrs = auth.attributes
126 orig_attrs.delete 'api_token'
128 assert_logged(auth, :delete) do |props|
129 assert_equal(orig_etag, props['old_etag'], "destroyed auth etag mismatch")
130 assert_equal(orig_attrs, props['old_attributes'],
131 "destroyed auth attributes mismatch")
135 test "saving an unchanged client still makes a log" do
136 set_user_from_auth :admin_trustedclient
137 client = api_clients(:untrusted)
138 client.is_trusted = client.is_trusted
140 assert_logged(client, :update) do |props|
141 ['old', 'new'].each do |age|
142 assert_equal(client.etag, props["#{age}_etag"],
143 "unchanged client #{age} etag mismatch")
144 assert_equal(client.attributes, props["#{age}_attributes"],
145 "unchanged client #{age} attributes mismatch")
150 test "updating a group twice makes two logs" do
151 set_user_from_auth :admin_trustedclient
152 group = groups(:empty_lonely_group)
154 name2 = "#{name1} under test"
157 assert_logged(group, :update) do |props|
158 assert_equal(name1, props['old_attributes']['name'],
159 "group start name mismatch")
160 assert_equal(name2, props['new_attributes']['name'],
161 "group updated name mismatch")
165 assert_logged(group, :update) do |props|
166 assert_equal(name2, props['old_attributes']['name'],
167 "group pre-revert name mismatch")
168 assert_equal(name1, props['new_attributes']['name'],
169 "group final name mismatch")
173 test "making a log doesn't get logged" do
174 set_user_from_auth :active_trustedclient
177 assert_equal(0, get_logs_about(log).size, "made a Log about a Log")
180 test "non-admins can't modify or delete logs" do
181 set_user_from_auth :active_trustedclient
182 log = Log.new(summary: "immutable log test")
183 assert_nothing_raised { log.save! }
184 log.summary = "log mutation test should fail"
185 assert_raise(ArvadosModel::PermissionDeniedError) { log.save! }
186 assert_raise(ArvadosModel::PermissionDeniedError) { log.destroy }
189 test "admins can modify and delete logs" do
190 set_user_from_auth :admin_trustedclient
191 log = Log.new(summary: "admin log mutation test")
192 assert_nothing_raised { log.save! }
193 log.summary = "admin mutated log test"
194 assert_nothing_raised { log.save! }
195 assert_nothing_raised { log.destroy }
198 test "failure saving log causes failure saving object" do
200 alias_method :_orig_validations, :perform_validations
201 def perform_validations(options)
206 set_user_from_auth :active_trustedclient
207 user = users(:active)
208 user.first_name = 'Test'
209 assert_raise(ActiveRecord::RecordInvalid) { user.save! }
212 alias_method :perform_validations, :_orig_validations
217 test "don't log changes only to ApiClientAuthorization.last_used_*" do
218 set_user_from_auth :admin_trustedclient
219 auth = api_client_authorizations(:spectator)
220 start_log_count = get_logs_about(auth).size
221 auth.last_used_at = Time.now
222 auth.last_used_by_ip_address = '::1'
224 assert_equal(start_log_count, get_logs_about(auth).size,
225 "log count changed after 'using' ApiClientAuthorization")
226 auth.created_by_ip_address = '::1'
228 assert_logged(auth, :update)
231 test "token isn't included in ApiClientAuthorization logs" do
232 set_user_from_auth :admin_trustedclient
233 auth = ApiClientAuthorization.new
234 auth.user = users(:spectator)
235 auth.api_client = api_clients(:untrusted)
237 assert_logged_with_clean_properties(auth, :create, 'api_token')
238 auth.expires_at = Time.now
240 assert_logged_with_clean_properties(auth, :update, 'api_token')
242 assert_logged_with_clean_properties(auth, :delete, 'api_token')
245 test "use ownership and permission links to determine which logs a user can see" do
247 :admin_changes_repository2,
248 :admin_changes_specimen,
249 :system_adds_foo_file,
251 :log_owned_by_active,
252 :crunchstat_for_running_job]
254 c = Log.readable_by(users(:admin)).order("id asc").each.to_a
255 assert_log_result c, known_logs, known_logs
257 c = Log.readable_by(users(:active)).order("id asc").each.to_a
258 assert_log_result c, known_logs, [:admin_changes_repository2, # owned by active
259 :system_adds_foo_file, # readable via link
260 :system_adds_baz, # readable via 'all users' group
261 :log_owned_by_active, # log owned by active
262 :crunchstat_for_running_job] # log & job owned by active
264 c = Log.readable_by(users(:spectator)).order("id asc").each.to_a
265 assert_log_result c, known_logs, [:noop, # object_uuid is spectator
266 :admin_changes_specimen, # object_uuid is a specimen owned by spectator
267 :system_adds_baz] # readable via 'all users' group
270 def assert_log_result result, known_logs, expected_logs
271 # All of expected_logs must appear in result. Additional logs can
272 # appear too, but only if they are _not_ listed in known_logs
273 # (i.e., we do not make any assertions about logs not mentioned in
274 # either "known" or "expected".)
275 result_ids = result.collect(&:id)
276 expected_logs.each do |want|
277 assert_includes result_ids, logs(want).id
279 (known_logs - expected_logs).each do |notwant|
280 refute_includes result_ids, logs(notwant).id
284 test "non-empty configuration.unlogged_attributes" do
285 Rails.configuration.AuditLogs.UnloggedAttributes = {"manifest_text"=>{}}
286 txt = ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n"
288 act_as_system_user do
289 coll = Collection.create(manifest_text: txt)
290 assert_logged_with_clean_properties(coll, :create, 'manifest_text')
291 coll.name = "testing"
293 assert_logged_with_clean_properties(coll, :update, 'manifest_text')
295 assert_logged_with_clean_properties(coll, :delete, 'manifest_text')
299 test "empty configuration.unlogged_attributes" do
300 Rails.configuration.AuditLogs.UnloggedAttributes = {}
301 txt = ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n"
303 act_as_system_user do
304 coll = Collection.create(manifest_text: txt)
305 assert_logged(coll, :create) do |props|
306 assert_equal(txt, props['new_attributes']['manifest_text'])
308 coll.update_attributes!(name: "testing")
309 assert_logged(coll, :update) do |props|
310 assert_equal(txt, props['old_attributes']['manifest_text'])
311 assert_equal(txt, props['new_attributes']['manifest_text'])
314 assert_logged(coll, :delete) do |props|
315 assert_equal(txt, props['old_attributes']['manifest_text'])
320 def assert_no_logs_deleted
321 logs_before = Log.unscoped.all.count
323 assert_equal logs_before, Log.unscoped.all.count
326 def remaining_audit_logs
327 Log.unscoped.where('event_type in (?)', %w(create update destroy delete))
330 # Default settings should not delete anything -- some sites rely on
331 # the original "keep everything forever" behavior.
332 test 'retain old audit logs with default settings' do
333 assert_no_logs_deleted do
334 AuditLogs.delete_old(
335 max_age: Rails.configuration.AuditLogs.MaxAge,
336 max_batch: Rails.configuration.AuditLogs.MaxDeleteBatch)
340 # Batch size 0 should retain all logs -- even if max_age is very
341 # short, and even if the default settings (and associated test) have
343 test 'retain old audit logs with max_audit_log_delete_batch=0' do
344 assert_no_logs_deleted do
345 AuditLogs.delete_old(max_age: 1, max_batch: 0)
349 # We recommend a more conservative age of 5 minutes for production,
350 # but 3 minutes suits our test data better (and is test-worthy in
351 # that it's expected to work correctly in production).
352 test 'delete old audit logs with production settings' do
353 initial_log_count = Log.unscoped.all.count
354 AuditLogs.delete_old(max_age: 180, max_batch: 100000)
355 assert_operator remaining_audit_logs.count, :<, initial_log_count
358 test 'delete all audit logs in multiple batches' do
359 AuditLogs.delete_old(max_age: 0.00001, max_batch: 2)
360 assert_equal [], remaining_audit_logs.collect(&:uuid)
363 test 'delete old audit logs in thread' do
365 Rails.configuration.AuditLogs.MaxAge = 20
366 Rails.configuration.AuditLogs.MaxDeleteBatch = 100000
367 Rails.cache.delete 'AuditLogs'
368 initial_log_count = Log.unscoped.all.count + 1
369 act_as_system_user do
371 initial_log_count += 1
373 deadline = Time.now + 10
374 while remaining_audit_logs.count == initial_log_count
375 if Time.now > deadline
380 assert_operator remaining_audit_logs.count, :<, initial_log_count
382 # The test framework rolls back our transactions, but that
383 # doesn't undo the deletes we did from separate threads.
384 ActiveRecord::Base.connection.exec_query 'ROLLBACK'
387 dc = DatabaseController.new
388 dc.define_singleton_method :render do |*args| end
391 ActiveRecord::Base.connection.close