3 class ArvadosModel < ActiveRecord::Base
4 self.abstract_class = true
6 include CurrentApiClient # current_user, current_api_client, etc.
9 attr_protected :created_at
10 attr_protected :modified_by_user_uuid
11 attr_protected :modified_by_client_uuid
12 attr_protected :modified_at
13 after_initialize :log_start_state
14 before_save :ensure_permission_to_save
15 before_save :ensure_owner_uuid_is_permitted
16 before_save :ensure_ownership_path_leads_to_user
17 before_destroy :ensure_owner_uuid_is_permitted
18 before_destroy :ensure_permission_to_destroy
19 before_create :update_modified_by_fields
20 before_update :maybe_update_modified_by_fields
21 after_create :log_create
22 after_update :log_update
23 after_destroy :log_destroy
24 after_find :convert_serialized_symbols_to_strings
25 before_validation :normalize_collection_uuids
26 before_validation :set_default_owner
27 validate :ensure_serialized_attribute_type
28 validate :ensure_valid_uuids
30 # Note: This only returns permission links. It does not account for
31 # permissions obtained via user.is_admin or
32 # user.uuid==object.owner_uuid.
33 has_many :permissions, :foreign_key => :head_uuid, :class_name => 'Link', :primary_key => :uuid, :conditions => "link_class = 'permission'"
35 class PermissionDeniedError < StandardError
41 class AlreadyLockedError < StandardError
47 class UnauthorizedError < StandardError
53 def self.kind_class(kind)
54 kind.match(/^arvados\#(.+)$/)[1].classify.safe_constantize rescue nil
58 "#{current_api_base}/#{self.class.to_s.pluralize.underscore}/#{self.uuid}"
61 def self.selectable_attributes(template=:user)
62 # Return an array of attribute name strings that can be selected
63 # in the given template.
64 api_accessible_attributes(template).map { |attr_spec| attr_spec.first.to_s }
67 def self.searchable_columns operator
68 textonly_operator = !operator.match(/[<=>]/)
69 self.columns.select do |col|
73 when :datetime, :integer, :boolean
81 def self.attribute_column attr
82 self.columns.select { |col| col.name == attr.to_s }.first
85 def self.attributes_required_columns
86 # This method returns a hash. Each key is the name of an API attribute,
87 # and it's mapped to a list of database columns that must be fetched
88 # to generate that attribute.
89 # This implementation generates a simple map of attributes to
90 # matching column names. Subclasses can override this method
91 # to specify that method-backed API attributes need to fetch
92 # specific columns from the database.
93 all_columns = columns.map(&:name)
94 api_column_map = Hash.new { |hash, key| hash[key] = [] }
95 methods.grep(/^api_accessible_\w+$/).each do |method_name|
96 next if method_name == :api_accessible_attributes
97 send(method_name).each_pair do |api_attr_name, col_name|
98 col_name = col_name.to_s
99 if all_columns.include?(col_name)
100 api_column_map[api_attr_name.to_s] |= [col_name]
107 def self.columns_for_attributes(select_attributes)
108 # Given an array of attribute names to select, return an array of column
109 # names that must be fetched from the database to satisfy the request.
110 api_column_map = attributes_required_columns
111 select_attributes.flat_map { |attr| api_column_map[attr] }.uniq
114 def self.default_orders
115 ["#{table_name}.modified_at desc", "#{table_name}.uuid"]
118 # If current user can manage the object, return an array of uuids of
119 # users and groups that have permission to write the object. The
120 # first two elements are always [self.owner_uuid, current user's
123 # If current user can write but not manage the object, return
124 # [self.owner_uuid, current user's uuid].
126 # If current user cannot write this object, just return
129 return [owner_uuid] if not current_user
130 unless (owner_uuid == current_user.uuid or
131 current_user.is_admin or
132 (current_user.groups_i_can(:manage) & [uuid, owner_uuid]).any?)
133 if ((current_user.groups_i_can(:write) + [current_user.uuid]) &
134 [uuid, owner_uuid]).any?
135 return [owner_uuid, current_user.uuid]
140 [owner_uuid, current_user.uuid] + permissions.collect do |p|
141 if ['can_write', 'can_manage'].index p.name
147 # Return a query with read permissions restricted to the union of of the
148 # permissions of the members of users_list, i.e. if something is readable by
149 # any user in users_list, it will be readable in the query returned by this
151 def self.readable_by(*users_list)
152 # Get rid of troublesome nils
155 # Load optional keyword arguments, if they exist.
156 if users_list.last.is_a? Hash
157 kwargs = users_list.pop
162 # Check if any of the users are admin. If so, we're done.
163 if users_list.select { |u| u.is_admin }.any?
167 # Collect the uuids for each user and any groups readable by each user.
168 user_uuids = users_list.map { |u| u.uuid }
169 uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
172 sql_table = kwargs.fetch(:table_name, table_name)
175 # This row is owned by a member of users_list, or owned by a group
176 # readable by a member of users_list
178 # This row uuid is the uuid of a member of users_list
180 # A permission link exists ('write' and 'manage' implicitly include
181 # 'read') from a member of users_list, or a group readable by users_list,
182 # to this row, or to the owner of this row (see join() below).
183 sql_conds += ["#{sql_table}.uuid in (?)"]
184 sql_params += [user_uuids]
187 sql_conds += ["#{sql_table}.owner_uuid in (?)"]
188 sql_params += [uuid_list]
190 sanitized_uuid_list = uuid_list.
191 collect { |uuid| sanitize(uuid) }.join(', ')
192 permitted_uuids = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (#{sanitized_uuid_list}))"
193 sql_conds += ["#{sql_table}.uuid IN #{permitted_uuids}"]
196 if sql_table == "links" and users_list.any?
197 # This row is a 'permission' or 'resources' link class
198 # The uuid for a member of users_list is referenced in either the head
199 # or tail of the link
200 sql_conds += ["(#{sql_table}.link_class in (#{sanitize 'permission'}, #{sanitize 'resources'}) AND (#{sql_table}.head_uuid IN (?) OR #{sql_table}.tail_uuid IN (?)))"]
201 sql_params += [user_uuids, user_uuids]
204 if sql_table == "logs" and users_list.any?
205 # Link head points to the object described by this row
206 sql_conds += ["#{sql_table}.object_uuid IN #{permitted_uuids}"]
208 # This object described by this row is owned by this user, or owned by a group readable by this user
209 sql_conds += ["#{sql_table}.object_owner_uuid in (?)"]
210 sql_params += [uuid_list]
213 # Link head points to this row, or to the owner of this row (the
216 # Link tail originates from this user, or a group that is readable
217 # by this user (the identity with authorization to read)
219 # Link class is 'permission' ('write' and 'manage' implicitly
221 where(sql_conds.join(' OR '), *sql_params)
224 def logged_attributes
228 def self.full_text_searchable_columns
229 self.columns.select do |col|
230 col.type == :string or col.type == :text
234 def self.full_text_tsvector
235 parts = full_text_searchable_columns.collect do |column|
236 "coalesce(#{column},'')"
238 # We prepend a space to the tsvector() argument here. Otherwise,
239 # it might start with a column that has its own (non-full-text)
240 # index, which causes Postgres to use the column index instead of
241 # the tsvector index, which causes full text queries to be just as
242 # slow as if we had no index at all.
243 "to_tsvector('english', ' ' || #{parts.join(" || ' ' || ")})"
248 def ensure_ownership_path_leads_to_user
249 if new_record? or owner_uuid_changed?
250 uuid_in_path = {owner_uuid => true, uuid => true}
252 while (owner_class = ArvadosModel::resource_class_for_uuid(x)) != User
255 # Test for cycles with the new version, not the DB contents
257 elsif !owner_class.respond_to? :find_by_uuid
258 raise ActiveRecord::RecordNotFound.new
260 x = owner_class.find_by_uuid(x).owner_uuid
262 rescue ActiveRecord::RecordNotFound => e
263 errors.add :owner_uuid, "is not owned by any user: #{e}"
268 errors.add :owner_uuid, "would create an ownership cycle"
270 errors.add :owner_uuid, "has an ownership cycle"
274 uuid_in_path[x] = true
280 def set_default_owner
281 if new_record? and current_user and respond_to? :owner_uuid=
282 self.owner_uuid ||= current_user.uuid
286 def ensure_owner_uuid_is_permitted
287 raise PermissionDeniedError if !current_user
289 if self.owner_uuid.nil?
290 errors.add :owner_uuid, "cannot be nil"
291 raise PermissionDeniedError
294 rsc_class = ArvadosModel::resource_class_for_uuid owner_uuid
295 unless rsc_class == User or rsc_class == Group
296 errors.add :owner_uuid, "must be set to User or Group"
297 raise PermissionDeniedError
300 # Verify "write" permission on old owner
301 # default fail unless one of:
302 # owner_uuid did not change
303 # previous owner_uuid is nil
304 # current user is the old owner
305 # current user is this object
306 # current user can_write old owner
307 unless !owner_uuid_changed? or
308 owner_uuid_was.nil? or
309 current_user.uuid == self.owner_uuid_was or
310 current_user.uuid == self.uuid or
311 current_user.can? write: self.owner_uuid_was
312 logger.warn "User #{current_user.uuid} tried to modify #{self.class.to_s} #{uuid} but does not have permission to write old owner_uuid #{owner_uuid_was}"
313 errors.add :owner_uuid, "cannot be changed without write permission on old owner"
314 raise PermissionDeniedError
317 # Verify "write" permission on new owner
318 # default fail unless one of:
319 # current_user is this object
320 # current user can_write new owner, or this object if owner unchanged
321 if new_record? or owner_uuid_changed? or is_a?(ApiClientAuthorization)
322 write_target = owner_uuid
326 unless current_user == self or current_user.can? write: write_target
327 logger.warn "User #{current_user.uuid} tried to modify #{self.class.to_s} #{uuid} but does not have permission to write new owner_uuid #{owner_uuid}"
328 errors.add :owner_uuid, "cannot be changed without write permission on new owner"
329 raise PermissionDeniedError
335 def ensure_permission_to_save
336 unless (new_record? ? permission_to_create : permission_to_update)
337 raise PermissionDeniedError
341 def permission_to_create
342 current_user.andand.is_active
345 def permission_to_update
347 logger.warn "Anonymous user tried to update #{self.class.to_s} #{self.uuid_was}"
350 if !current_user.is_active
351 logger.warn "Inactive user #{current_user.uuid} tried to update #{self.class.to_s} #{self.uuid_was}"
354 return true if current_user.is_admin
355 if self.uuid_changed?
356 logger.warn "User #{current_user.uuid} tried to change uuid of #{self.class.to_s} #{self.uuid_was} to #{self.uuid}"
362 def ensure_permission_to_destroy
363 raise PermissionDeniedError unless permission_to_destroy
366 def permission_to_destroy
370 def maybe_update_modified_by_fields
371 update_modified_by_fields if self.changed? or self.new_record?
375 def update_modified_by_fields
376 current_time = db_current_time
377 self.updated_at = current_time
378 self.owner_uuid ||= current_default_owner if self.respond_to? :owner_uuid=
379 self.modified_at = current_time
380 self.modified_by_user_uuid = current_user ? current_user.uuid : nil
381 self.modified_by_client_uuid = current_api_client ? current_api_client.uuid : nil
385 def self.has_symbols? x
388 return true if has_symbols?(k) or has_symbols?(v)
393 return true if has_symbols?(k)
401 def self.recursive_stringify x
403 Hash[x.collect do |k,v|
404 [recursive_stringify(k), recursive_stringify(v)]
408 recursive_stringify k
417 def ensure_serialized_attribute_type
418 # Specifying a type in the "serialize" declaration causes rails to
419 # raise an exception if a different data type is retrieved from
420 # the database during load(). The validation preventing such
421 # crash-inducing records from being inserted in the database in
422 # the first place seems to have been left as an exercise to the
424 self.class.serialized_attributes.each do |colname, attr|
426 if self.attributes[colname].class != attr.object_class
427 self.errors.add colname.to_sym, "must be a #{attr.object_class.to_s}, not a #{self.attributes[colname].class.to_s}"
428 elsif self.class.has_symbols? attributes[colname]
429 self.errors.add colname.to_sym, "must not contain symbols: #{attributes[colname].inspect}"
435 def convert_serialized_symbols_to_strings
436 # ensure_serialized_attribute_type should prevent symbols from
437 # getting into the database in the first place. If someone managed
438 # to get them into the database (perhaps using an older version)
439 # we'll convert symbols to strings when loading from the
440 # database. (Otherwise, loading and saving an object with existing
441 # symbols in a serialized field will crash.)
442 self.class.serialized_attributes.each do |colname, attr|
443 if self.class.has_symbols? attributes[colname]
444 attributes[colname] = self.class.recursive_stringify attributes[colname]
445 self.send(colname + '=',
446 self.class.recursive_stringify(attributes[colname]))
451 def foreign_key_attributes
452 attributes.keys.select { |a| a.match /_uuid$/ }
455 def skip_uuid_read_permission_check
456 %w(modified_by_client_uuid)
459 def skip_uuid_existence_check
463 def normalize_collection_uuids
464 foreign_key_attributes.each do |attr|
465 attr_value = send attr
466 if attr_value.is_a? String and
467 attr_value.match /^[0-9a-f]{32,}(\+[@\w]+)*$/
469 send "#{attr}=", Collection.normalize_uuid(attr_value)
471 # TODO: abort instead of silently accepting unnormalizable value?
477 @@prefixes_hash = nil
478 def self.uuid_prefixes
479 unless @@prefixes_hash
481 Rails.application.eager_load!
482 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |k|
483 if k.respond_to?(:uuid_prefix)
484 @@prefixes_hash[k.uuid_prefix] = k
491 def self.uuid_like_pattern
492 "_____-#{uuid_prefix}-_______________"
496 %r/[a-z0-9]{5}-#{uuid_prefix}-[a-z0-9]{15}/
499 def ensure_valid_uuids
500 specials = [system_user_uuid]
502 foreign_key_attributes.each do |attr|
503 if new_record? or send (attr + "_changed?")
504 next if skip_uuid_existence_check.include? attr
505 attr_value = send attr
506 next if specials.include? attr_value
508 if (r = ArvadosModel::resource_class_for_uuid attr_value)
509 unless skip_uuid_read_permission_check.include? attr
510 r = r.readable_by(current_user)
512 if r.where(uuid: attr_value).count == 0
513 errors.add(attr, "'#{attr_value}' not found")
530 def self.readable_by (*u)
535 [{:uuid => u[:uuid]}]
539 def self.resource_class_for_uuid(uuid)
540 if uuid.is_a? ArvadosModel
543 unless uuid.is_a? String
548 uuid.match HasUuid::UUID_REGEX do |re|
549 return uuid_prefixes[re[1]] if uuid_prefixes[re[1]]
552 if uuid.match /.+@.+/
559 # ArvadosModel.find_by_uuid needs extra magic to allow it to return
560 # an object in any class.
561 def self.find_by_uuid uuid
562 if self == ArvadosModel
563 # If called directly as ArvadosModel.find_by_uuid rather than via subclass,
564 # delegate to the appropriate subclass based on the given uuid.
565 self.resource_class_for_uuid(uuid).find_by_uuid(uuid)
572 @old_attributes = Marshal.load(Marshal.dump(attributes))
573 @old_logged_attributes = Marshal.load(Marshal.dump(logged_attributes))
576 def log_change(event_type)
577 log = Log.new(event_type: event_type).fill_object(self)
584 log_change('create') do |log|
585 log.fill_properties('old', nil, nil)
591 log_change('update') do |log|
592 log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
598 log_change('destroy') do |log|
599 log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)