Merge branch 'master' into 4904-arv-web
[arvados.git] / services / api / test / unit / log_test.rb
1 require 'test_helper'
2
3 class LogTest < ActiveSupport::TestCase
4   include CurrentApiClient
5
6   EVENT_TEST_METHODS = {
7     :create => [:created_at, :assert_nil, :assert_not_nil],
8     :update => [:modified_at, :assert_not_nil, :assert_not_nil],
9     :destroy => [nil, :assert_not_nil, :assert_nil],
10   }
11
12   def setup
13     @start_time = Time.now
14     @log_count = 1
15   end
16
17   def assert_properties(test_method, event, props, *keys)
18     verb = (test_method == :assert_nil) ? 'have nil' : 'define'
19     keys.each do |prop_name|
20       assert_includes(props, prop_name, "log properties missing #{prop_name}")
21       self.send(test_method, props[prop_name],
22                 "#{event.to_s} log should #{verb} #{prop_name}")
23     end
24   end
25
26   def get_logs_about(thing)
27     Log.where(object_uuid: thing.uuid).order("created_at ASC").all
28   end
29
30   def assert_logged(thing, event_type)
31     logs = get_logs_about(thing)
32     assert_equal(@log_count, logs.size, "log count mismatch")
33     @log_count += 1
34     log = logs.last
35     props = log.properties
36     assert_equal(current_user.andand.uuid, log.owner_uuid,
37                  "log is not owned by current user")
38     assert_equal(current_user.andand.uuid, log.modified_by_user_uuid,
39                  "log is not 'modified by' current user")
40     assert_equal(current_api_client.andand.uuid, log.modified_by_client_uuid,
41                  "log is not 'modified by' current client")
42     assert_equal(thing.uuid, log.object_uuid, "log UUID mismatch")
43     assert_equal(event_type.to_s, log.event_type, "log event type mismatch")
44     time_method, old_props_test, new_props_test = EVENT_TEST_METHODS[event_type]
45     if time_method.nil? or (timestamp = thing.send(time_method)).nil?
46       assert(log.event_at >= @start_time, "log timestamp too old")
47     else
48       assert_in_delta(timestamp, log.event_at, 1, "log timestamp mismatch")
49     end
50     assert_properties(old_props_test, event_type, props,
51                       'old_etag', 'old_attributes')
52     assert_properties(new_props_test, event_type, props,
53                       'new_etag', 'new_attributes')
54     yield props if block_given?
55   end
56
57   def assert_auth_logged_with_clean_properties(auth, event_type)
58     assert_logged(auth, event_type) do |props|
59       ['old_attributes', 'new_attributes'].map { |k| props[k] }.compact
60         .each do |attributes|
61         refute_includes(attributes, 'api_token',
62                         "auth log properties include sensitive API token")
63       end
64       yield props if block_given?
65     end
66   end
67
68   test "creating a user makes a log" do
69     set_user_from_auth :admin_trustedclient
70     u = User.new(first_name: "Log", last_name: "Test")
71     u.save!
72     assert_logged(u, :create) do |props|
73       assert_equal(u.etag, props['new_etag'], "new user etag mismatch")
74       assert_equal(u.first_name, props['new_attributes']['first_name'],
75                    "new user first name mismatch")
76       assert_equal(u.last_name, props['new_attributes']['last_name'],
77                    "new user first name mismatch")
78     end
79   end
80
81   test "updating a virtual machine makes a log" do
82     set_user_from_auth :admin_trustedclient
83     vm = virtual_machines(:testvm)
84     orig_etag = vm.etag
85     vm.hostname = 'testvm.testshell'
86     vm.save!
87     assert_logged(vm, :update) do |props|
88       assert_equal(orig_etag, props['old_etag'], "updated VM old etag mismatch")
89       assert_equal(vm.etag, props['new_etag'], "updated VM new etag mismatch")
90       assert_equal('testvm.shell', props['old_attributes']['hostname'],
91                    "updated VM old name mismatch")
92       assert_equal('testvm.testshell', props['new_attributes']['hostname'],
93                    "updated VM new name mismatch")
94     end
95   end
96
97   test "old_attributes preserves values deep inside a hash" do
98     set_user_from_auth :active
99     it = specimens(:owned_by_active_user)
100     it.properties = {'foo' => {'bar' => ['baz', 'qux', {'quux' => 'bleat'}]}}
101     it.save!
102     @log_count += 1
103     it.properties['foo']['bar'][2]['quux'] = 'blert'
104     it.save!
105     assert_logged it, :update do |props|
106       assert_equal 'bleat', props['old_attributes']['properties']['foo']['bar'][2]['quux']
107       assert_equal 'blert', props['new_attributes']['properties']['foo']['bar'][2]['quux']
108     end
109   end
110
111   test "destroying an authorization makes a log" do
112     set_user_from_auth :admin_trustedclient
113     auth = api_client_authorizations(:spectator)
114     orig_etag = auth.etag
115     orig_attrs = auth.attributes
116     orig_attrs.delete 'api_token'
117     auth.destroy
118     assert_logged(auth, :destroy) do |props|
119       assert_equal(orig_etag, props['old_etag'], "destroyed auth etag mismatch")
120       assert_equal(orig_attrs, props['old_attributes'],
121                    "destroyed auth attributes mismatch")
122     end
123   end
124
125   test "saving an unchanged client still makes a log" do
126     set_user_from_auth :admin_trustedclient
127     client = api_clients(:untrusted)
128     client.is_trusted = client.is_trusted
129     client.save!
130     assert_logged(client, :update) do |props|
131       ['old', 'new'].each do |age|
132         assert_equal(client.etag, props["#{age}_etag"],
133                      "unchanged client #{age} etag mismatch")
134         assert_equal(client.attributes, props["#{age}_attributes"],
135                      "unchanged client #{age} attributes mismatch")
136       end
137     end
138   end
139
140   test "updating a group twice makes two logs" do
141     set_user_from_auth :admin_trustedclient
142     group = groups(:empty_lonely_group)
143     name1 = group.name
144     name2 = "#{name1} under test"
145     group.name = name2
146     group.save!
147     assert_logged(group, :update) do |props|
148       assert_equal(name1, props['old_attributes']['name'],
149                    "group start name mismatch")
150       assert_equal(name2, props['new_attributes']['name'],
151                    "group updated name mismatch")
152     end
153     group.name = name1
154     group.save!
155     assert_logged(group, :update) do |props|
156       assert_equal(name2, props['old_attributes']['name'],
157                    "group pre-revert name mismatch")
158       assert_equal(name1, props['new_attributes']['name'],
159                    "group final name mismatch")
160     end
161   end
162
163   test "making a log doesn't get logged" do
164     set_user_from_auth :active_trustedclient
165     log = Log.new
166     log.save!
167     assert_equal(0, get_logs_about(log).size, "made a Log about a Log")
168   end
169
170   test "non-admins can't modify or delete logs" do
171     set_user_from_auth :active_trustedclient
172     log = Log.new(summary: "immutable log test")
173     assert_nothing_raised { log.save! }
174     log.summary = "log mutation test should fail"
175     assert_raise(ArvadosModel::PermissionDeniedError) { log.save! }
176     assert_raise(ArvadosModel::PermissionDeniedError) { log.destroy }
177   end
178
179   test "admins can modify and delete logs" do
180     set_user_from_auth :admin_trustedclient
181     log = Log.new(summary: "admin log mutation test")
182     assert_nothing_raised { log.save! }
183     log.summary = "admin mutated log test"
184     assert_nothing_raised { log.save! }
185     assert_nothing_raised { log.destroy }
186   end
187
188   test "failure saving log causes failure saving object" do
189     Log.class_eval do
190       alias_method :_orig_validations, :perform_validations
191       def perform_validations(options)
192         false
193       end
194     end
195     begin
196       set_user_from_auth :active_trustedclient
197       user = users(:active)
198       user.first_name = 'Test'
199       assert_raise(ActiveRecord::RecordInvalid) { user.save! }
200     ensure
201       Log.class_eval do
202         alias_method :perform_validations, :_orig_validations
203       end
204     end
205   end
206
207   test "don't log changes only to ApiClientAuthorization.last_used_*" do
208     set_user_from_auth :admin_trustedclient
209     auth = api_client_authorizations(:spectator)
210     start_log_count = get_logs_about(auth).size
211     auth.last_used_at = Time.now
212     auth.last_used_by_ip_address = '::1'
213     auth.save!
214     assert_equal(start_log_count, get_logs_about(auth).size,
215                  "log count changed after 'using' ApiClientAuthorization")
216     auth.created_by_ip_address = '::1'
217     auth.save!
218     assert_logged(auth, :update)
219   end
220
221   test "token isn't included in ApiClientAuthorization logs" do
222     set_user_from_auth :admin_trustedclient
223     auth = ApiClientAuthorization.new
224     auth.user = users(:spectator)
225     auth.api_client = api_clients(:untrusted)
226     auth.save!
227     assert_auth_logged_with_clean_properties(auth, :create)
228     auth.expires_at = Time.now
229     auth.save!
230     assert_auth_logged_with_clean_properties(auth, :update)
231     auth.destroy
232     assert_auth_logged_with_clean_properties(auth, :destroy)
233   end
234
235   test "use ownership and permission links to determine which logs a user can see" do
236     c = Log.readable_by(users(:admin)).order("id asc").each.to_a
237     assert_equal 6, c.size
238     assert_equal 1, c[0].id # no-op
239     assert_equal 2, c[1].id # admin changes repository foo, which is owned by active user
240     assert_equal 3, c[2].id # admin changes specimen owned_by_spectator
241     assert_equal 4, c[3].id # foo collection added, readable by active through link
242     assert_equal 5, c[4].id # baz collection added, readable by active and spectator through group 'all users' group membership
243     assert_equal 6, c[5].id # log_owned_by_active
244
245     c = Log.readable_by(users(:active)).order("id asc").each.to_a
246     assert_equal 4, c.size
247     assert_equal 2, c[0].id # admin changes repository foo, which is owned by active user
248     assert_equal 4, c[1].id # foo collection added, readable by active through link
249     assert_equal 5, c[2].id # baz collection added, readable by active and spectator through group 'all users' group membership
250     assert_equal 6, c[3].id # log_owned_by_active
251
252     c = Log.readable_by(users(:spectator)).order("id asc").each.to_a
253     assert_equal 2, c.size
254     assert_equal 3, c[0].id # admin changes specimen owned_by_spectator
255     assert_equal 5, c[1].id # baz collection added, readable by active and spectator through group 'all users' group membership
256   end
257 end