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 clear_logs_about(thing)
36 Log.where(object_uuid: thing.uuid).delete_all
39 def assert_logged(thing, event_type)
40 logs = get_logs_about(thing)
41 assert_equal(@log_count, logs.size, "log count mismatch")
44 props = log.properties
45 assert_equal(current_user.andand.uuid, log.owner_uuid,
46 "log is not owned by current user")
47 assert_equal(current_user.andand.uuid, log.modified_by_user_uuid,
48 "log is not 'modified by' current user")
49 assert_equal(thing.uuid, log.object_uuid, "log UUID mismatch")
50 assert_equal(event_type.to_s, log.event_type, "log event type mismatch")
51 time_method, old_props_test, new_props_test = EVENT_TEST_METHODS[event_type]
52 if time_method.nil? or (timestamp = thing.send(time_method)).nil?
53 assert(log.event_at >= @start_time, "log timestamp too old")
55 assert_in_delta(timestamp, log.event_at, 1, "log timestamp mismatch")
57 assert_properties(old_props_test, event_type, props,
58 'old_etag', 'old_attributes')
59 assert_properties(new_props_test, event_type, props,
60 'new_etag', 'new_attributes')
61 ['old_attributes', 'new_attributes'].each do |logattr|
62 next if !props[logattr]
63 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)
65 yield props if block_given?
68 def assert_logged_with_clean_properties(obj, event_type, excluded_attr)
69 assert_logged(obj, event_type) do |props|
70 ['old_attributes', 'new_attributes'].map do |logattr|
71 attributes = props[logattr]
72 next if attributes.nil?
73 refute_includes(attributes, excluded_attr,
74 "log #{logattr} includes #{excluded_attr}")
76 yield props if block_given?
80 test "creating a user makes a log" do
81 set_user_from_auth :admin_trustedclient
82 u = User.new(first_name: "Log", last_name: "Test")
84 assert_logged(u, :create) do |props|
85 assert_equal(u.etag, props['new_etag'], "new user etag mismatch")
86 assert_equal(u.first_name, props['new_attributes']['first_name'],
87 "new user first name mismatch")
88 assert_equal(u.last_name, props['new_attributes']['last_name'],
89 "new user first name mismatch")
93 test "updating a virtual machine makes a log" do
94 set_user_from_auth :admin_trustedclient
95 vm = virtual_machines(:testvm)
97 vm.hostname = 'testvm.testshell'
99 assert_logged(vm, :update) do |props|
100 assert_equal(orig_etag, props['old_etag'], "updated VM old etag mismatch")
101 assert_equal(vm.etag, props['new_etag'], "updated VM new etag mismatch")
102 assert_equal('testvm.shell', props['old_attributes']['hostname'],
103 "updated VM old name mismatch")
104 assert_equal('testvm.testshell', props['new_attributes']['hostname'],
105 "updated VM new name mismatch")
109 test "old_attributes preserves values deep inside a hash" do
110 set_user_from_auth :active
111 it = collections(:collection_owned_by_active)
113 it.properties = {'foo' => {'bar' => ['baz', 'qux', {'quux' => 'bleat'}]}}
115 assert_logged it, :update
116 it.properties['foo']['bar'][2]['quux'] = 'blert'
118 assert_logged it, :update do |props|
119 assert_equal 'bleat', props['old_attributes']['properties']['foo']['bar'][2]['quux']
120 assert_equal 'blert', props['new_attributes']['properties']['foo']['bar'][2]['quux']
124 test "destroying an authorization makes a log" do
125 set_user_from_auth :admin_trustedclient
126 auth = api_client_authorizations(:spectator)
127 orig_etag = auth.etag
128 orig_attrs = auth.attributes
129 orig_attrs.delete 'api_token'
131 assert_logged(auth, :delete) do |props|
132 assert_equal(orig_etag, props['old_etag'], "destroyed auth etag mismatch")
133 assert_equal(orig_attrs, props['old_attributes'],
134 "destroyed auth attributes mismatch")
138 test "updating a group twice makes two logs" do
139 set_user_from_auth :admin_trustedclient
140 group = groups(:empty_lonely_group)
142 name2 = "#{name1} under test"
145 assert_logged(group, :update) do |props|
146 assert_equal(name1, props['old_attributes']['name'],
147 "group start name mismatch")
148 assert_equal(name2, props['new_attributes']['name'],
149 "group updated name mismatch")
153 assert_logged(group, :update) do |props|
154 assert_equal(name2, props['old_attributes']['name'],
155 "group pre-revert name mismatch")
156 assert_equal(name1, props['new_attributes']['name'],
157 "group final name mismatch")
161 test "making a log doesn't get logged" do
162 set_user_from_auth :active_trustedclient
165 assert_equal(0, get_logs_about(log).size, "made a Log about a Log")
168 test "non-admins can't modify or delete logs" do
169 set_user_from_auth :active_trustedclient
170 log = Log.new(summary: "immutable log test")
171 assert_nothing_raised { log.save! }
172 log.summary = "log mutation test should fail"
173 assert_raise(ArvadosModel::PermissionDeniedError) { log.save! }
174 assert_raise(ArvadosModel::PermissionDeniedError) { log.destroy }
177 test "admins can modify and delete logs" do
178 set_user_from_auth :admin_trustedclient
179 log = Log.new(summary: "admin log mutation test")
180 assert_nothing_raised { log.save! }
181 log.summary = "admin mutated log test"
182 assert_nothing_raised { log.save! }
183 assert_nothing_raised { log.destroy }
186 test "failure saving log causes failure saving object" do
188 alias_method :_orig_validations, :perform_validations
189 def perform_validations(options)
194 set_user_from_auth :active_trustedclient
195 user = users(:active)
196 user.first_name = 'Test'
197 assert_raise(ActiveRecord::RecordInvalid) { user.save! }
200 alias_method :perform_validations, :_orig_validations
205 test "don't log changes only to ApiClientAuthorization.last_used_*" do
206 set_user_from_auth :admin_trustedclient
207 auth = api_client_authorizations(:spectator)
208 start_log_count = get_logs_about(auth).size
209 auth.last_used_at = Time.now
210 auth.last_used_by_ip_address = '::1'
212 assert_equal(start_log_count, get_logs_about(auth).size,
213 "log count changed after 'using' ApiClientAuthorization")
214 auth.created_by_ip_address = '::1'
216 assert_logged(auth, :update)
219 test "don't log changes only to Collection.preserve_version" do
220 set_user_from_auth :admin_trustedclient
221 col = collections(:collection_owned_by_active)
223 start_log_count = get_logs_about(col).size
224 assert_equal false, col.preserve_version
225 col.preserve_version = true
227 assert_equal(start_log_count, get_logs_about(col).size,
228 "log count changed after updating Collection.preserve_version")
229 col.name = 'updated by admin'
231 assert_logged(col, :update)
234 test "token isn't included in ApiClientAuthorization logs" do
235 set_user_from_auth :admin_trustedclient
236 auth = ApiClientAuthorization.new
237 auth.user = users(:spectator)
239 assert_logged_with_clean_properties(auth, :create, 'api_token')
240 auth.expires_at = Time.now
242 assert_logged_with_clean_properties(auth, :update, 'api_token')
244 assert_logged_with_clean_properties(auth, :delete, 'api_token')
247 test "use ownership and permission links to determine which logs a user can see" do
249 :admin_changes_collection_owned_by_active,
250 :admin_changes_collection_owned_by_foo,
251 :system_adds_foo_file,
253 :log_owned_by_active,
254 :crunchstat_for_running_container]
256 c = Log.readable_by(users(:admin)).order("id asc").each.to_a
257 assert_log_result c, known_logs, known_logs
259 c = Log.readable_by(users(:active)).order("id asc").each.to_a
260 assert_log_result c, known_logs, [:admin_changes_collection_owned_by_active,
261 :system_adds_foo_file, # readable via link
262 :system_adds_baz, # readable via 'all users' group
263 :log_owned_by_active, # log owned by active
264 :crunchstat_for_running_container] # log & job owned by active
266 c = Log.readable_by(users(:spectator)).order("id asc").each.to_a
267 assert_log_result c, known_logs, [:noop, # object_uuid is spectator
268 :system_adds_baz] # readable via 'all users' group
270 c = Log.readable_by(users(:user_foo_in_sharing_group)).order("id asc").each.to_a
271 assert_log_result c, known_logs, [:admin_changes_collection_owned_by_foo] # collection's parent is readable via role group
274 def assert_log_result result, known_logs, expected_logs
275 # All of expected_logs must appear in result. Additional logs can
276 # appear too, but only if they are _not_ listed in known_logs
277 # (i.e., we do not make any assertions about logs not mentioned in
278 # either "known" or "expected".)
279 result_ids = result.collect(&:id)
280 expected_logs.each do |want|
281 assert_includes result_ids, logs(want).id
283 (known_logs - expected_logs).each do |notwant|
284 refute_includes result_ids, logs(notwant).id
288 test "non-empty configuration.unlogged_attributes" do
289 Rails.configuration.AuditLogs.UnloggedAttributes = ConfigLoader.to_OrderedOptions({"manifest_text"=>{}})
290 txt = ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n"
292 act_as_system_user do
293 coll = Collection.create(manifest_text: txt)
294 assert_logged_with_clean_properties(coll, :create, 'manifest_text')
295 coll.name = "testing"
297 assert_logged_with_clean_properties(coll, :update, 'manifest_text')
299 assert_logged_with_clean_properties(coll, :delete, 'manifest_text')
303 test "empty configuration.unlogged_attributes" do
304 Rails.configuration.AuditLogs.UnloggedAttributes = ConfigLoader.to_OrderedOptions({})
305 txt = ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n"
307 act_as_system_user do
308 coll = Collection.create(manifest_text: txt)
309 assert_logged(coll, :create) do |props|
310 assert_equal(txt, props['new_attributes']['manifest_text'])
312 coll.update!(name: "testing")
313 assert_logged(coll, :update) do |props|
314 assert_equal(txt, props['old_attributes']['manifest_text'])
315 assert_equal(txt, props['new_attributes']['manifest_text'])
318 assert_logged(coll, :delete) do |props|
319 assert_equal(txt, props['old_attributes']['manifest_text'])
324 def assert_no_logs_deleted
325 logs_before = Log.unscoped.all.count
326 assert logs_before > 0
328 assert_equal logs_before, Log.unscoped.all.count
331 def remaining_audit_logs
332 Log.unscoped.where('event_type in (?)', %w(create update destroy delete))
335 # Default settings should not delete anything -- some sites rely on
336 # the original "keep everything forever" behavior.
337 test 'retain old audit logs with default settings' do
338 assert_no_logs_deleted do
339 AuditLogs.delete_old(
340 max_age: Rails.configuration.AuditLogs.MaxAge,
341 max_batch: Rails.configuration.AuditLogs.MaxDeleteBatch)
345 # Batch size 0 should retain all logs -- even if max_age is very
346 # short, and even if the default settings (and associated test) have
348 test 'retain old audit logs with max_audit_log_delete_batch=0' do
349 assert_no_logs_deleted do
350 AuditLogs.delete_old(max_age: 1, max_batch: 0)
354 # We recommend a more conservative age of 5 minutes for production,
355 # but 3 minutes suits our test data better (and is test-worthy in
356 # that it's expected to work correctly in production).
357 test 'delete old audit logs with production settings' do
358 initial_log_count = remaining_audit_logs.count
359 assert initial_log_count > 0
360 AuditLogs.delete_old(max_age: 180, max_batch: 100000)
361 assert_operator remaining_audit_logs.count, :<, initial_log_count
364 test 'delete all audit logs in multiple batches' do
365 assert remaining_audit_logs.count > 2
366 AuditLogs.delete_old(max_age: 0.00001, max_batch: 2)
367 assert_equal [], remaining_audit_logs.collect(&:uuid)
370 test 'delete old audit logs in thread' do
371 Rails.configuration.AuditLogs.MaxAge = 20
372 Rails.configuration.AuditLogs.MaxDeleteBatch = 100000
373 Rails.cache.delete 'AuditLogs'
374 initial_audit_log_count = remaining_audit_logs.count
375 assert initial_audit_log_count > 0
376 act_as_system_user do
379 deadline = Time.now + 10
380 while remaining_audit_logs.count == initial_audit_log_count
381 if Time.now > deadline
386 assert_operator remaining_audit_logs.count, :<, initial_audit_log_count