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.ignored_select_attributes
108 ["href", "kind", "etag"]
111 def self.columns_for_attributes(select_attributes)
112 if select_attributes.empty?
113 raise ArgumentError.new("Attribute selection list cannot be empty")
115 api_column_map = attributes_required_columns
117 select_attributes.each do |s|
118 next if ignored_select_attributes.include? s
119 if not s.is_a? String or not api_column_map.include? s
123 if not invalid_attrs.empty?
124 raise ArgumentError.new("Invalid attribute(s): #{invalid_attrs.inspect}")
126 # Given an array of attribute names to select, return an array of column
127 # names that must be fetched from the database to satisfy the request.
128 select_attributes.flat_map { |attr| api_column_map[attr] }.uniq
131 def self.default_orders
132 ["#{table_name}.modified_at desc", "#{table_name}.uuid"]
135 def self.unique_columns
139 # If current user can manage the object, return an array of uuids of
140 # users and groups that have permission to write the object. The
141 # first two elements are always [self.owner_uuid, current user's
144 # If current user can write but not manage the object, return
145 # [self.owner_uuid, current user's uuid].
147 # If current user cannot write this object, just return
150 return [owner_uuid] if not current_user
151 unless (owner_uuid == current_user.uuid or
152 current_user.is_admin or
153 (current_user.groups_i_can(:manage) & [uuid, owner_uuid]).any?)
154 if ((current_user.groups_i_can(:write) + [current_user.uuid]) &
155 [uuid, owner_uuid]).any?
156 return [owner_uuid, current_user.uuid]
161 [owner_uuid, current_user.uuid] + permissions.collect do |p|
162 if ['can_write', 'can_manage'].index p.name
168 # Return a query with read permissions restricted to the union of of the
169 # permissions of the members of users_list, i.e. if something is readable by
170 # any user in users_list, it will be readable in the query returned by this
172 def self.readable_by(*users_list)
173 # Get rid of troublesome nils
176 # Load optional keyword arguments, if they exist.
177 if users_list.last.is_a? Hash
178 kwargs = users_list.pop
183 # Check if any of the users are admin. If so, we're done.
184 if users_list.select { |u| u.is_admin }.any?
188 # Collect the uuids for each user and any groups readable by each user.
189 user_uuids = users_list.map { |u| u.uuid }
190 uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
193 sql_table = kwargs.fetch(:table_name, table_name)
196 # This row is owned by a member of users_list, or owned by a group
197 # readable by a member of users_list
199 # This row uuid is the uuid of a member of users_list
201 # A permission link exists ('write' and 'manage' implicitly include
202 # 'read') from a member of users_list, or a group readable by users_list,
203 # to this row, or to the owner of this row (see join() below).
204 sql_conds += ["#{sql_table}.uuid in (?)"]
205 sql_params += [user_uuids]
208 sql_conds += ["#{sql_table}.owner_uuid in (?)"]
209 sql_params += [uuid_list]
211 sanitized_uuid_list = uuid_list.
212 collect { |uuid| sanitize(uuid) }.join(', ')
213 permitted_uuids = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (#{sanitized_uuid_list}))"
214 sql_conds += ["#{sql_table}.uuid IN #{permitted_uuids}"]
217 if sql_table == "links" and users_list.any?
218 # This row is a 'permission' or 'resources' link class
219 # The uuid for a member of users_list is referenced in either the head
220 # or tail of the link
221 sql_conds += ["(#{sql_table}.link_class in (#{sanitize 'permission'}, #{sanitize 'resources'}) AND (#{sql_table}.head_uuid IN (?) OR #{sql_table}.tail_uuid IN (?)))"]
222 sql_params += [user_uuids, user_uuids]
225 if sql_table == "logs" and users_list.any?
226 # Link head points to the object described by this row
227 sql_conds += ["#{sql_table}.object_uuid IN #{permitted_uuids}"]
229 # This object described by this row is owned by this user, or owned by a group readable by this user
230 sql_conds += ["#{sql_table}.object_owner_uuid in (?)"]
231 sql_params += [uuid_list]
234 # Link head points to this row, or to the owner of this row (the
237 # Link tail originates from this user, or a group that is readable
238 # by this user (the identity with authorization to read)
240 # Link class is 'permission' ('write' and 'manage' implicitly
242 where(sql_conds.join(' OR '), *sql_params)
245 def logged_attributes
249 def self.full_text_searchable_columns
250 self.columns.select do |col|
251 col.type == :string or col.type == :text
255 def self.full_text_tsvector
256 parts = full_text_searchable_columns.collect do |column|
257 "coalesce(#{column},'')"
259 # We prepend a space to the tsvector() argument here. Otherwise,
260 # it might start with a column that has its own (non-full-text)
261 # index, which causes Postgres to use the column index instead of
262 # the tsvector index, which causes full text queries to be just as
263 # slow as if we had no index at all.
264 "to_tsvector('english', ' ' || #{parts.join(" || ' ' || ")})"
269 def ensure_ownership_path_leads_to_user
270 if new_record? or owner_uuid_changed?
271 uuid_in_path = {owner_uuid => true, uuid => true}
273 while (owner_class = ArvadosModel::resource_class_for_uuid(x)) != User
276 # Test for cycles with the new version, not the DB contents
278 elsif !owner_class.respond_to? :find_by_uuid
279 raise ActiveRecord::RecordNotFound.new
281 x = owner_class.find_by_uuid(x).owner_uuid
283 rescue ActiveRecord::RecordNotFound => e
284 errors.add :owner_uuid, "is not owned by any user: #{e}"
289 errors.add :owner_uuid, "would create an ownership cycle"
291 errors.add :owner_uuid, "has an ownership cycle"
295 uuid_in_path[x] = true
301 def set_default_owner
302 if new_record? and current_user and respond_to? :owner_uuid=
303 self.owner_uuid ||= current_user.uuid
307 def ensure_owner_uuid_is_permitted
308 raise PermissionDeniedError if !current_user
310 if self.owner_uuid.nil?
311 errors.add :owner_uuid, "cannot be nil"
312 raise PermissionDeniedError
315 rsc_class = ArvadosModel::resource_class_for_uuid owner_uuid
316 unless rsc_class == User or rsc_class == Group
317 errors.add :owner_uuid, "must be set to User or Group"
318 raise PermissionDeniedError
321 # Verify "write" permission on old owner
322 # default fail unless one of:
323 # owner_uuid did not change
324 # previous owner_uuid is nil
325 # current user is the old owner
326 # current user is this object
327 # current user can_write old owner
328 unless !owner_uuid_changed? or
329 owner_uuid_was.nil? or
330 current_user.uuid == self.owner_uuid_was or
331 current_user.uuid == self.uuid or
332 current_user.can? write: self.owner_uuid_was
333 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}"
334 errors.add :owner_uuid, "cannot be changed without write permission on old owner"
335 raise PermissionDeniedError
338 # Verify "write" permission on new owner
339 # default fail unless one of:
340 # current_user is this object
341 # current user can_write new owner, or this object if owner unchanged
342 if new_record? or owner_uuid_changed? or is_a?(ApiClientAuthorization)
343 write_target = owner_uuid
347 unless current_user == self or current_user.can? write: write_target
348 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}"
349 errors.add :owner_uuid, "cannot be changed without write permission on new owner"
350 raise PermissionDeniedError
356 def ensure_permission_to_save
357 unless (new_record? ? permission_to_create : permission_to_update)
358 raise PermissionDeniedError
362 def permission_to_create
363 current_user.andand.is_active
366 def permission_to_update
368 logger.warn "Anonymous user tried to update #{self.class.to_s} #{self.uuid_was}"
371 if !current_user.is_active
372 logger.warn "Inactive user #{current_user.uuid} tried to update #{self.class.to_s} #{self.uuid_was}"
375 return true if current_user.is_admin
376 if self.uuid_changed?
377 logger.warn "User #{current_user.uuid} tried to change uuid of #{self.class.to_s} #{self.uuid_was} to #{self.uuid}"
383 def ensure_permission_to_destroy
384 raise PermissionDeniedError unless permission_to_destroy
387 def permission_to_destroy
391 def maybe_update_modified_by_fields
392 update_modified_by_fields if self.changed? or self.new_record?
396 def update_modified_by_fields
397 current_time = db_current_time
398 self.updated_at = current_time
399 self.owner_uuid ||= current_default_owner if self.respond_to? :owner_uuid=
400 self.modified_at = current_time
401 self.modified_by_user_uuid = current_user ? current_user.uuid : nil
402 self.modified_by_client_uuid = current_api_client ? current_api_client.uuid : nil
406 def self.has_symbols? x
409 return true if has_symbols?(k) or has_symbols?(v)
413 return true if has_symbols?(k)
418 return true if x.start_with?(':') && !x.start_with?('::')
423 def self.recursive_stringify x
425 Hash[x.collect do |k,v|
426 [recursive_stringify(k), recursive_stringify(v)]
430 recursive_stringify k
434 elsif x.is_a? String and x.start_with?(':') and !x.start_with?('::')
441 def ensure_serialized_attribute_type
442 # Specifying a type in the "serialize" declaration causes rails to
443 # raise an exception if a different data type is retrieved from
444 # the database during load(). The validation preventing such
445 # crash-inducing records from being inserted in the database in
446 # the first place seems to have been left as an exercise to the
448 self.class.serialized_attributes.each do |colname, attr|
450 if self.attributes[colname].class != attr.object_class
451 self.errors.add colname.to_sym, "must be a #{attr.object_class.to_s}, not a #{self.attributes[colname].class.to_s}"
452 elsif self.class.has_symbols? attributes[colname]
453 self.errors.add colname.to_sym, "must not contain symbols: #{attributes[colname].inspect}"
459 def convert_serialized_symbols_to_strings
460 # ensure_serialized_attribute_type should prevent symbols from
461 # getting into the database in the first place. If someone managed
462 # to get them into the database (perhaps using an older version)
463 # we'll convert symbols to strings when loading from the
464 # database. (Otherwise, loading and saving an object with existing
465 # symbols in a serialized field will crash.)
466 self.class.serialized_attributes.each do |colname, attr|
467 if self.class.has_symbols? attributes[colname]
468 attributes[colname] = self.class.recursive_stringify attributes[colname]
469 self.send(colname + '=',
470 self.class.recursive_stringify(attributes[colname]))
475 def foreign_key_attributes
476 attributes.keys.select { |a| a.match /_uuid$/ }
479 def skip_uuid_read_permission_check
480 %w(modified_by_client_uuid)
483 def skip_uuid_existence_check
487 def normalize_collection_uuids
488 foreign_key_attributes.each do |attr|
489 attr_value = send attr
490 if attr_value.is_a? String and
491 attr_value.match /^[0-9a-f]{32,}(\+[@\w]+)*$/
493 send "#{attr}=", Collection.normalize_uuid(attr_value)
495 # TODO: abort instead of silently accepting unnormalizable value?
501 @@prefixes_hash = nil
502 def self.uuid_prefixes
503 unless @@prefixes_hash
505 Rails.application.eager_load!
506 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |k|
507 if k.respond_to?(:uuid_prefix)
508 @@prefixes_hash[k.uuid_prefix] = k
515 def self.uuid_like_pattern
516 "_____-#{uuid_prefix}-_______________"
520 %r/[a-z0-9]{5}-#{uuid_prefix}-[a-z0-9]{15}/
523 def ensure_valid_uuids
524 specials = [system_user_uuid]
526 foreign_key_attributes.each do |attr|
527 if new_record? or send (attr + "_changed?")
528 next if skip_uuid_existence_check.include? attr
529 attr_value = send attr
530 next if specials.include? attr_value
532 if (r = ArvadosModel::resource_class_for_uuid attr_value)
533 unless skip_uuid_read_permission_check.include? attr
534 r = r.readable_by(current_user)
536 if r.where(uuid: attr_value).count == 0
537 errors.add(attr, "'#{attr_value}' not found")
554 def self.readable_by (*u)
559 [{:uuid => u[:uuid]}]
563 def self.resource_class_for_uuid(uuid)
564 if uuid.is_a? ArvadosModel
567 unless uuid.is_a? String
572 uuid.match HasUuid::UUID_REGEX do |re|
573 return uuid_prefixes[re[1]] if uuid_prefixes[re[1]]
576 if uuid.match /.+@.+/
583 # ArvadosModel.find_by_uuid needs extra magic to allow it to return
584 # an object in any class.
585 def self.find_by_uuid uuid
586 if self == ArvadosModel
587 # If called directly as ArvadosModel.find_by_uuid rather than via subclass,
588 # delegate to the appropriate subclass based on the given uuid.
589 self.resource_class_for_uuid(uuid).find_by_uuid(uuid)
596 @old_attributes = Marshal.load(Marshal.dump(attributes))
597 @old_logged_attributes = Marshal.load(Marshal.dump(logged_attributes))
600 def log_change(event_type)
601 log = Log.new(event_type: event_type).fill_object(self)
608 log_change('create') do |log|
609 log.fill_properties('old', nil, nil)
615 log_change('update') do |log|
616 log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
622 log_change('destroy') do |log|
623 log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)