3 class ArvadosModel < ActiveRecord::Base
4 self.abstract_class = true
6 include CurrentApiClient # current_user, current_api_client, etc.
8 attr_protected :created_at
9 attr_protected :modified_by_user_uuid
10 attr_protected :modified_by_client_uuid
11 attr_protected :modified_at
12 after_initialize :log_start_state
13 before_save :ensure_permission_to_save
14 before_save :ensure_owner_uuid_is_permitted
15 before_save :ensure_ownership_path_leads_to_user
16 before_destroy :ensure_owner_uuid_is_permitted
17 before_destroy :ensure_permission_to_destroy
18 before_create :update_modified_by_fields
19 before_update :maybe_update_modified_by_fields
20 after_create :log_create
21 after_update :log_update
22 after_destroy :log_destroy
23 after_find :convert_serialized_symbols_to_strings
24 validate :ensure_serialized_attribute_type
25 validate :normalize_collection_uuids
26 validate :ensure_valid_uuids
28 # Note: This only returns permission links. It does not account for
29 # permissions obtained via user.is_admin or
30 # user.uuid==object.owner_uuid.
31 has_many :permissions, :foreign_key => :head_uuid, :class_name => 'Link', :primary_key => :uuid, :conditions => "link_class = 'permission'"
33 class PermissionDeniedError < StandardError
39 class UnauthorizedError < StandardError
45 def self.kind_class(kind)
46 kind.match(/^arvados\#(.+)$/)[1].classify.safe_constantize rescue nil
50 "#{current_api_base}/#{self.class.to_s.pluralize.underscore}/#{self.uuid}"
53 def self.searchable_columns operator
54 textonly_operator = !operator.match(/[<=>]/)
55 self.columns.collect do |col|
56 if [:string, :text].index(col.type)
58 elsif !textonly_operator and [:datetime, :integer].index(col.type)
64 def self.attribute_column attr
65 self.columns.select { |col| col.name == attr.to_s }.first
68 # Return nil if current user is not allowed to see the list of
69 # writers. Otherwise, return a list of user_ and group_uuids with
70 # write permission. (If not returning nil, current_user is always in
71 # the list because can_manage permission is needed to see the list
74 unless (owner_uuid == current_user.uuid or
75 current_user.is_admin or
76 current_user.groups_i_can(:manage).index(owner_uuid))
79 [owner_uuid, current_user.uuid] + permissions.collect do |p|
80 if ['can_write', 'can_manage'].index p.name
86 # Return a query with read permissions restricted to the union of of the
87 # permissions of the members of users_list, i.e. if something is readable by
88 # any user in users_list, it will be readable in the query returned by this
90 def self.readable_by(*users_list)
91 # Get rid of troublesome nils
94 # Check if any of the users are admin. If so, we're done.
95 if users_list.select { |u| u.is_admin }.empty?
97 # Collect the uuids for each user and any groups readable by each user.
98 user_uuids = users_list.map { |u| u.uuid }
99 uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
100 sanitized_uuid_list = uuid_list.
101 collect { |uuid| sanitize(uuid) }.join(', ')
106 # This row is owned by a member of users_list, or owned by a group
107 # readable by a member of users_list
109 # This row uuid is the uuid of a member of users_list
111 # A permission link exists ('write' and 'manage' implicitly include
112 # 'read') from a member of users_list, or a group readable by users_list,
113 # to this row, or to the owner of this row (see join() below).
114 permitted_uuids = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (#{sanitized_uuid_list}))"
116 sql_conds += ["#{table_name}.owner_uuid in (?)",
117 "#{table_name}.uuid in (?)",
118 "#{table_name}.uuid IN #{permitted_uuids}"]
119 sql_params += [uuid_list, user_uuids]
121 if self == Link and users_list.any?
122 # This row is a 'permission' or 'resources' link class
123 # The uuid for a member of users_list is referenced in either the head
124 # or tail of the link
125 sql_conds += ["(#{table_name}.link_class in (#{sanitize 'permission'}, #{sanitize 'resources'}) AND (#{table_name}.head_uuid IN (?) OR #{table_name}.tail_uuid IN (?)))"]
126 sql_params += [user_uuids, user_uuids]
129 if self == Log and users_list.any?
130 # Link head points to the object described by this row
131 sql_conds += ["#{table_name}.object_uuid IN #{permitted_uuids}"]
133 # This object described by this row is owned by this user, or owned by a group readable by this user
134 sql_conds += ["#{table_name}.object_owner_uuid in (?)"]
135 sql_params += [uuid_list]
138 # Link head points to this row, or to the owner of this row (the thing to be read)
140 # Link tail originates from this user, or a group that is readable by this
141 # user (the identity with authorization to read)
143 # Link class is 'permission' ('write' and 'manage' implicitly include 'read')
144 where(sql_conds.join(' OR '), *sql_params)
146 # At least one user is admin, so don't bother to apply any restrictions.
151 def logged_attributes
157 def ensure_ownership_path_leads_to_user
158 if new_record? or owner_uuid_changed?
159 uuid_in_path = {owner_uuid => true, uuid => true}
161 while (owner_class = self.class.resource_class_for_uuid(x)) != User
164 # Test for cycles with the new version, not the DB contents
166 elsif !owner_class.respond_to? :find_by_uuid
167 raise ActiveRecord::RecordNotFound.new
169 x = owner_class.find_by_uuid(x).owner_uuid
171 rescue ActiveRecord::RecordNotFound => e
172 errors.add :owner_uuid, "is not owned by any user: #{e}"
177 errors.add :owner_uuid, "would create an ownership cycle"
179 errors.add :owner_uuid, "has an ownership cycle"
183 uuid_in_path[x] = true
189 def ensure_owner_uuid_is_permitted
190 raise PermissionDeniedError if !current_user
191 if respond_to? :owner_uuid=
192 self.owner_uuid ||= current_user.uuid
194 if self.owner_uuid_changed?
197 elsif current_user.uuid == self.owner_uuid or
198 current_user.can? write: self.owner_uuid
199 # current_user is, or has :write permission on, the new owner
201 logger.warn "User #{current_user.uuid} tried to change owner_uuid of #{self.class.to_s} #{self.uuid} to #{self.owner_uuid} but does not have permission to write to #{self.owner_uuid}"
202 raise PermissionDeniedError
207 elsif current_user.uuid == self.owner_uuid_was or
208 current_user.uuid == self.uuid or
209 current_user.can? write: self.owner_uuid_was
210 # current user is, or has :write permission on, the previous owner
213 logger.warn "User #{current_user.uuid} tried to modify #{self.class.to_s} #{self.uuid} but does not have permission to write #{self.owner_uuid_was}"
214 raise PermissionDeniedError
218 def ensure_permission_to_save
219 unless (new_record? ? permission_to_create : permission_to_update)
220 raise PermissionDeniedError
224 def permission_to_create
225 current_user.andand.is_active
228 def permission_to_update
230 logger.warn "Anonymous user tried to update #{self.class.to_s} #{self.uuid_was}"
233 if !current_user.is_active
234 logger.warn "Inactive user #{current_user.uuid} tried to update #{self.class.to_s} #{self.uuid_was}"
237 return true if current_user.is_admin
238 if self.uuid_changed?
239 logger.warn "User #{current_user.uuid} tried to change uuid of #{self.class.to_s} #{self.uuid_was} to #{self.uuid}"
245 def ensure_permission_to_destroy
246 raise PermissionDeniedError unless permission_to_destroy
249 def permission_to_destroy
253 def maybe_update_modified_by_fields
254 update_modified_by_fields if self.changed? or self.new_record?
258 def update_modified_by_fields
259 self.updated_at = Time.now
260 self.owner_uuid ||= current_default_owner if self.respond_to? :owner_uuid=
261 self.modified_at = Time.now
262 self.modified_by_user_uuid = current_user ? current_user.uuid : nil
263 self.modified_by_client_uuid = current_api_client ? current_api_client.uuid : nil
267 def self.has_symbols? x
270 return true if has_symbols?(k) or has_symbols?(v)
275 return true if has_symbols?(k)
283 def self.recursive_stringify x
285 Hash[x.collect do |k,v|
286 [recursive_stringify(k), recursive_stringify(v)]
290 recursive_stringify k
299 def ensure_serialized_attribute_type
300 # Specifying a type in the "serialize" declaration causes rails to
301 # raise an exception if a different data type is retrieved from
302 # the database during load(). The validation preventing such
303 # crash-inducing records from being inserted in the database in
304 # the first place seems to have been left as an exercise to the
306 self.class.serialized_attributes.each do |colname, attr|
308 if self.attributes[colname].class != attr.object_class
309 self.errors.add colname.to_sym, "must be a #{attr.object_class.to_s}, not a #{self.attributes[colname].class.to_s}"
310 elsif self.class.has_symbols? attributes[colname]
311 self.errors.add colname.to_sym, "must not contain symbols: #{attributes[colname].inspect}"
317 def convert_serialized_symbols_to_strings
318 # ensure_serialized_attribute_type should prevent symbols from
319 # getting into the database in the first place. If someone managed
320 # to get them into the database (perhaps using an older version)
321 # we'll convert symbols to strings when loading from the
322 # database. (Otherwise, loading and saving an object with existing
323 # symbols in a serialized field will crash.)
324 self.class.serialized_attributes.each do |colname, attr|
325 if self.class.has_symbols? attributes[colname]
326 attributes[colname] = self.class.recursive_stringify attributes[colname]
327 self.send(colname + '=',
328 self.class.recursive_stringify(attributes[colname]))
333 def foreign_key_attributes
334 attributes.keys.select { |a| a.match /_uuid$/ }
337 def skip_uuid_read_permission_check
338 %w(modified_by_client_uuid)
341 def skip_uuid_existence_check
345 def normalize_collection_uuids
346 foreign_key_attributes.each do |attr|
347 attr_value = send attr
348 if attr_value.is_a? String and
349 attr_value.match /^[0-9a-f]{32,}(\+[@\w]+)*$/
351 send "#{attr}=", Collection.normalize_uuid(attr_value)
353 # TODO: abort instead of silently accepting unnormalizable value?
359 @@UUID_REGEX = /^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/
361 @@prefixes_hash = nil
362 def self.uuid_prefixes
363 unless @@prefixes_hash
365 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |k|
366 if k.respond_to?(:uuid_prefix)
367 @@prefixes_hash[k.uuid_prefix] = k
374 def self.uuid_like_pattern
375 "_____-#{uuid_prefix}-_______________"
378 def ensure_valid_uuids
379 specials = [system_user_uuid, 'd41d8cd98f00b204e9800998ecf8427e+0']
381 foreign_key_attributes.each do |attr|
382 if new_record? or send (attr + "_changed?")
383 next if skip_uuid_existence_check.include? attr
384 attr_value = send attr
385 next if specials.include? attr_value
387 if (r = ArvadosModel::resource_class_for_uuid attr_value)
388 unless skip_uuid_read_permission_check.include? attr
389 r = r.readable_by(current_user)
391 if r.where(uuid: attr_value).count == 0
392 errors.add(attr, "'#{attr_value}' not found")
409 def self.readable_by (*u)
414 [{:uuid => u[:uuid]}]
418 def self.resource_class_for_uuid(uuid)
419 if uuid.is_a? ArvadosModel
422 unless uuid.is_a? String
425 if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/
430 Rails.application.eager_load!
431 uuid.match @@UUID_REGEX do |re|
432 return uuid_prefixes[re[1]] if uuid_prefixes[re[1]]
435 if uuid.match /.+@.+/
444 @old_attributes = logged_attributes
447 def log_change(event_type)
448 log = Log.new(event_type: event_type).fill_object(self)
451 connection.execute "NOTIFY logs, '#{log.id}'"
456 log_change('create') do |log|
457 log.fill_properties('old', nil, nil)
463 log_change('update') do |log|
464 log.fill_properties('old', @old_etag, @old_attributes)
470 log_change('destroy') do |log|
471 log.fill_properties('old', @old_etag, @old_attributes)