1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 require 'arvados_model_updates'
7 require 'record_filters'
9 require 'request_error'
11 class ArvadosModel < ApplicationRecord
12 self.abstract_class = true
14 include ArvadosModelUpdates
15 include CurrentApiClient # current_user, current_api_client, etc.
19 after_initialize :log_start_state
20 before_save :ensure_permission_to_save
21 before_save :ensure_owner_uuid_is_permitted
22 before_save :ensure_ownership_path_leads_to_user
23 before_destroy :ensure_owner_uuid_is_permitted
24 before_destroy :ensure_permission_to_destroy
25 before_create :update_modified_by_fields
26 before_update :maybe_update_modified_by_fields
27 after_create :log_create
28 after_update :log_update
29 after_destroy :log_destroy
30 before_validation :normalize_collection_uuids
31 before_validation :set_default_owner
32 validate :ensure_valid_uuids
34 # Note: This only returns permission links. It does not account for
35 # permissions obtained via user.is_admin or
36 # user.uuid==object.owner_uuid.
37 has_many(:permissions,
38 ->{where(link_class: 'permission')},
39 foreign_key: :head_uuid,
43 # If async is true at create or update, permission graph
44 # update is deferred allowing making multiple calls without the performance
46 attr_accessor :async_permissions_update
48 # Ignore listed attributes on mass assignments
49 def self.protected_attributes
53 class PermissionDeniedError < RequestError
59 class AlreadyLockedError < RequestError
65 class LockFailedError < RequestError
71 class InvalidStateTransitionError < RequestError
77 class UnauthorizedError < RequestError
83 class UnresolvableContainerError < RequestError
89 def self.kind_class(kind)
90 kind.match(/^arvados\#(.+)$/)[1].classify.safe_constantize rescue nil
94 "#{current_api_base}/#{self.class.to_s.pluralize.underscore}/#{self.uuid}"
97 def self.permit_attribute_params raw_params
98 # strong_parameters does not provide security: permissions are
99 # implemented with before_save hooks.
101 # The following permit! is necessary even with
102 # "ActionController::Parameters.permit_all_parameters = true",
103 # because permit_all does not permit nested attributes.
107 raw_params = raw_params.to_hash
108 raw_params.delete_if { |k, _| self.protected_attributes.include? k }
109 serialized_attributes.each do |colname, coder|
110 param = raw_params[colname.to_sym]
113 elsif !param.is_a?(coder.object_class)
114 raise ArgumentError.new("#{colname} parameter must be #{coder.object_class}, not #{param.class}")
115 elsif has_nonstring_keys?(param)
116 raise ArgumentError.new("#{colname} parameter cannot have non-string hash keys")
119 # Check JSONB columns that aren't listed on serialized_attributes
120 columns.select{|c| c.type == :jsonb}.collect{|j| j.name}.each do |colname|
121 if serialized_attributes.include? colname || raw_params[colname.to_sym].nil?
124 if has_nonstring_keys?(raw_params[colname.to_sym])
125 raise ArgumentError.new("#{colname} parameter cannot have non-string hash keys")
129 ActionController::Parameters.new(raw_params).permit!
132 def initialize raw_params={}, *args
133 super(self.class.permit_attribute_params(raw_params), *args)
136 # Reload "old attributes" for logging, too.
142 def self.create raw_params={}, *args
143 super(permit_attribute_params(raw_params), *args)
146 def update_attributes raw_params={}, *args
147 super(self.class.permit_attribute_params(raw_params), *args)
150 def self.selectable_attributes(template=:user)
151 # Return an array of attribute name strings that can be selected
152 # in the given template.
153 api_accessible_attributes(template).map { |attr_spec| attr_spec.first.to_s }
156 def self.searchable_columns operator
157 textonly_operator = !operator.match(/[<=>]/)
158 self.columns.select do |col|
162 when :datetime, :integer, :boolean
170 def self.attribute_column attr
171 self.columns.select { |col| col.name == attr.to_s }.first
174 def self.attributes_required_columns
175 # This method returns a hash. Each key is the name of an API attribute,
176 # and it's mapped to a list of database columns that must be fetched
177 # to generate that attribute.
178 # This implementation generates a simple map of attributes to
179 # matching column names. Subclasses can override this method
180 # to specify that method-backed API attributes need to fetch
181 # specific columns from the database.
182 all_columns = columns.map(&:name)
183 api_column_map = Hash.new { |hash, key| hash[key] = [] }
184 methods.grep(/^api_accessible_\w+$/).each do |method_name|
185 next if method_name == :api_accessible_attributes
186 send(method_name).each_pair do |api_attr_name, col_name|
187 col_name = col_name.to_s
188 if all_columns.include?(col_name)
189 api_column_map[api_attr_name.to_s] |= [col_name]
196 def self.ignored_select_attributes
197 ["href", "kind", "etag"]
200 def self.columns_for_attributes(select_attributes)
201 if select_attributes.empty?
202 raise ArgumentError.new("Attribute selection list cannot be empty")
204 api_column_map = attributes_required_columns
206 select_attributes.each do |s|
207 next if ignored_select_attributes.include? s
208 if not s.is_a? String or not api_column_map.include? s
212 if not invalid_attrs.empty?
213 raise ArgumentError.new("Invalid attribute(s): #{invalid_attrs.inspect}")
215 # Given an array of attribute names to select, return an array of column
216 # names that must be fetched from the database to satisfy the request.
217 select_attributes.flat_map { |attr| api_column_map[attr] }.uniq
220 def self.default_orders
221 ["#{table_name}.modified_at desc", "#{table_name}.uuid"]
224 def self.unique_columns
228 def self.limit_index_columns_read
229 # This method returns a list of column names.
230 # If an index request reads that column from the database,
231 # APIs that return lists will only fetch objects until reaching
232 # max_index_database_read bytes of data from those columns.
236 # If current user can manage the object, return an array of uuids of
237 # users and groups that have permission to write the object. The
238 # first two elements are always [self.owner_uuid, current user's
241 # If current user can write but not manage the object, return
242 # [self.owner_uuid, current user's uuid].
244 # If current user cannot write this object, just return
247 return [owner_uuid] if not current_user
248 unless (owner_uuid == current_user.uuid or
249 current_user.is_admin or
250 (current_user.groups_i_can(:manage) & [uuid, owner_uuid]).any?)
251 if ((current_user.groups_i_can(:write) + [current_user.uuid]) &
252 [uuid, owner_uuid]).any?
253 return [owner_uuid, current_user.uuid]
258 [owner_uuid, current_user.uuid] + permissions.collect do |p|
259 if ['can_write', 'can_manage'].index p.name
265 # Return a query with read permissions restricted to the union of the
266 # permissions of the members of users_list, i.e. if something is readable by
267 # any user in users_list, it will be readable in the query returned by this
269 def self.readable_by(*users_list)
270 # Get rid of troublesome nils
273 # Load optional keyword arguments, if they exist.
274 if users_list.last.is_a? Hash
275 kwargs = users_list.pop
280 # Collect the UUIDs of the authorized users.
281 sql_table = kwargs.fetch(:table_name, table_name)
282 include_trash = kwargs.fetch(:include_trash, false)
283 include_old_versions = kwargs.fetch(:include_old_versions, false)
286 user_uuids = users_list.map { |u| u.uuid }
288 # For details on how the trashed_groups table is constructed, see
289 # see db/migrate/20200501150153_permission_table.rb
291 exclude_trashed_records = ""
292 if !include_trash and (sql_table == "groups" or sql_table == "collections") then
293 # Only include records that are not trashed
294 exclude_trashed_records = "AND (#{sql_table}.trash_at is NULL or #{sql_table}.trash_at > statement_timestamp())"
297 if users_list.select { |u| u.is_admin }.any?
298 # Admin skips most permission checks, but still want to filter on trashed items.
300 if sql_table != "api_client_authorizations"
301 # Only include records where the owner is not trashed
302 sql_conds = "#{sql_table}.owner_uuid NOT IN (SELECT group_uuid FROM #{TRASHED_GROUPS} "+
303 "where trash_at <= statement_timestamp()) #{exclude_trashed_records}"
308 if !include_trash then
309 trashed_check = "AND target_uuid NOT IN (SELECT group_uuid FROM #{TRASHED_GROUPS} where trash_at <= statement_timestamp())"
312 # The core of the permission check is a join against the
313 # materialized_permissions table to determine if the user has at
314 # least read permission to either the object itself or its
315 # direct owner (if traverse_owned is true). See
316 # db/migrate/20200501150153_permission_table.rb for details on
317 # how the permissions are computed.
319 # A user can have can_manage access to another user, this grants
320 # full access to all that user's stuff. To implement that we
321 # need to include those other users in the permission query.
322 user_uuids_subquery = USER_UUIDS_SUBQUERY_TEMPLATE % {user: ":user_uuids", perm_level: 1}
324 # Note: it is possible to combine the direct_check and
325 # owner_check into a single EXISTS() clause, however it turns
326 # out query optimizer doesn't like it and forces a sequential
327 # table scan. Constructing the query with separate EXISTS()
328 # clauses enables it to use the index.
330 # see issue 13208 for details.
332 # Match a direct read permission link from the user to the record uuid
333 direct_check = "#{sql_table}.uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
334 "WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 1 #{trashed_check})"
336 # Match a read permission for the user to the record's
337 # owner_uuid. This is so we can have a permissions table that
338 # mostly consists of users and groups (projects are a type of
339 # group) and not have to compute and list user permission to
340 # every single object in the system.
342 # Don't do this for API keys (special behavior) or groups
343 # (already covered by direct_check).
345 # The traverse_owned flag indicates whether the permission to
346 # read an object also implies transitive permission to read
347 # things the object owns. The situation where this is important
348 # are determining if we can read an object owned by another
349 # user. This makes it possible to have permission to read the
350 # user record without granting permission to read things the
353 if sql_table != "api_client_authorizations" and sql_table != "groups" then
354 owner_check = "OR #{sql_table}.owner_uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
355 "WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 1 #{trashed_check} AND traverse_owned) "
359 if sql_table == "links"
360 # Match any permission link that gives one of the authorized
361 # users some permission _or_ gives anyone else permission to
362 # view one of the authorized users.
363 links_cond = "OR (#{sql_table}.link_class IN (:permission_link_classes) AND "+
364 "(#{sql_table}.head_uuid IN (#{user_uuids_subquery}) OR #{sql_table}.tail_uuid IN (#{user_uuids_subquery})))"
367 sql_conds = "(#{direct_check} #{owner_check} #{links_cond}) #{exclude_trashed_records}"
371 if !include_old_versions && sql_table == "collections"
372 exclude_old_versions = "#{sql_table}.uuid = #{sql_table}.current_version_uuid"
374 sql_conds = exclude_old_versions
376 sql_conds += " AND #{exclude_old_versions}"
380 self.where(sql_conds,
381 user_uuids: user_uuids,
382 permission_link_classes: ['permission', 'resources'])
385 def save_with_unique_name!
390 conn = ActiveRecord::Base.connection
391 conn.exec_query 'SAVEPOINT save_with_unique_name'
394 rescue ActiveRecord::RecordNotUnique => rn
395 raise if max_retries == 0
398 conn.exec_query 'ROLLBACK TO SAVEPOINT save_with_unique_name'
400 # Dig into the error to determine if it is specifically calling out a
401 # (owner_uuid, name) uniqueness violation. In this specific case, and
402 # the client requested a unique name with ensure_unique_name==true,
403 # update the name field and try to save again. Loop as necessary to
404 # discover a unique name. It is necessary to handle name choosing at
405 # this level (as opposed to the client) to ensure that record creation
406 # never fails due to a race condition.
408 raise unless err.is_a?(PG::UniqueViolation)
410 # Unfortunately ActiveRecord doesn't abstract out any of the
411 # necessary information to figure out if this the error is actually
412 # the specific case where we want to apply the ensure_unique_name
413 # behavior, so the following code is specialized to Postgres.
414 detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
415 raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
417 new_name = "#{name_was} (#{db_current_time.utc.iso8601(3)})"
419 # If the database is fast enough to do two attempts in the
420 # same millisecond, we need to wait to ensure we try a
421 # different timestamp on each attempt.
423 new_name = "#{name_was} (#{db_current_time.utc.iso8601(3)})"
426 self[:name] = new_name
427 if uuid_was.nil? && !uuid.nil?
429 if self.is_a? Collection
430 # Reset so that is assigned to the new UUID
431 self[:current_version_uuid] = nil
434 conn.exec_query 'SAVEPOINT save_with_unique_name'
437 conn.exec_query 'RELEASE SAVEPOINT save_with_unique_name'
443 if self.owner_uuid.nil?
444 return current_user.uuid
446 owner_class = ArvadosModel.resource_class_for_uuid(self.owner_uuid)
447 if owner_class == User
450 owner_class.find_by_uuid(self.owner_uuid).user_owner_uuid
454 def logged_attributes
455 attributes.except(*Rails.configuration.AuditLogs.UnloggedAttributes.keys)
458 def self.full_text_searchable_columns
459 self.columns.select do |col|
460 [:string, :text, :jsonb].include?(col.type)
464 def self.full_text_coalesce
465 full_text_searchable_columns.collect do |column|
466 is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
467 cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
468 "coalesce(#{column}#{cast},'')"
472 def self.full_text_trgm
473 "(#{full_text_coalesce.join(" || ' ' || ")})"
476 def self.full_text_tsvector
477 parts = full_text_searchable_columns.collect do |column|
478 is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
479 cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
480 "coalesce(#{column}#{cast},'')"
482 "to_tsvector('english', substr(#{parts.join(" || ' ' || ")}, 0, 8000))"
485 def self.apply_filters query, filters
486 ft = record_filters filters, self
487 if not ft[:cond_out].any?
490 ft[:joins].each do |t|
491 query = query.joins(t)
493 query.where('(' + ft[:cond_out].join(') AND (') + ')',
499 def self.deep_sort_hash(x)
501 x.sort.collect do |k, v|
502 [k, deep_sort_hash(v)]
505 x.collect { |v| deep_sort_hash(v) }
511 def ensure_ownership_path_leads_to_user
512 if new_record? or owner_uuid_changed?
513 uuid_in_path = {owner_uuid => true, uuid => true}
515 while (owner_class = ArvadosModel::resource_class_for_uuid(x)) != User
518 # Test for cycles with the new version, not the DB contents
520 elsif !owner_class.respond_to? :find_by_uuid
521 raise ActiveRecord::RecordNotFound.new
523 x = owner_class.find_by_uuid(x).owner_uuid
525 rescue ActiveRecord::RecordNotFound => e
526 errors.add :owner_uuid, "is not owned by any user: #{e}"
531 errors.add :owner_uuid, "would create an ownership cycle"
533 errors.add :owner_uuid, "has an ownership cycle"
537 uuid_in_path[x] = true
543 def set_default_owner
544 if new_record? and current_user and respond_to? :owner_uuid=
545 self.owner_uuid ||= current_user.uuid
549 def ensure_owner_uuid_is_permitted
550 raise PermissionDeniedError if !current_user
552 if self.owner_uuid.nil?
553 errors.add :owner_uuid, "cannot be nil"
554 raise PermissionDeniedError
557 rsc_class = ArvadosModel::resource_class_for_uuid owner_uuid
558 unless rsc_class == User or rsc_class == Group
559 errors.add :owner_uuid, "must be set to User or Group"
560 raise PermissionDeniedError
563 if new_record? || owner_uuid_changed?
564 # Permission on owner_uuid_was is needed to move an existing
565 # object away from its previous owner (which implies permission
566 # to modify this object itself, so we don't need to check that
567 # separately). Permission on the new owner_uuid is also needed.
568 [['old', owner_uuid_was],
570 ].each do |which, check_uuid|
572 # old_owner_uuid is nil? New record, no need to check.
573 elsif !current_user.can?(write: check_uuid)
574 logger.warn "User #{current_user.uuid} tried to set ownership of #{self.class.to_s} #{self.uuid} but does not have permission to write #{which} owner_uuid #{check_uuid}"
575 errors.add :owner_uuid, "cannot be set or changed without write permission on #{which} owner"
576 raise PermissionDeniedError
577 elsif rsc_class == Group && Group.find_by_uuid(owner_uuid).group_class != "project"
578 errors.add :owner_uuid, "must be a project"
579 raise PermissionDeniedError
583 # If the object already existed and we're not changing
584 # owner_uuid, we only need write permission on the object
586 if !current_user.can?(write: self.uuid)
587 logger.warn "User #{current_user.uuid} tried to modify #{self.class.to_s} #{self.uuid} without write permission"
588 errors.add :uuid, " #{uuid} is not writable by #{current_user.uuid}"
589 raise PermissionDeniedError
596 def ensure_permission_to_save
597 unless (new_record? ? permission_to_create : permission_to_update)
598 raise PermissionDeniedError
602 def permission_to_create
603 current_user.andand.is_active
606 def permission_to_update
608 logger.warn "Anonymous user tried to update #{self.class.to_s} #{self.uuid_was}"
611 if !current_user.is_active
612 logger.warn "Inactive user #{current_user.uuid} tried to update #{self.class.to_s} #{self.uuid_was}"
615 return true if current_user.is_admin
616 if self.uuid_changed?
617 logger.warn "User #{current_user.uuid} tried to change uuid of #{self.class.to_s} #{self.uuid_was} to #{self.uuid}"
623 def ensure_permission_to_destroy
624 raise PermissionDeniedError unless permission_to_destroy
627 def permission_to_destroy
631 def maybe_update_modified_by_fields
632 update_modified_by_fields if self.changed? or self.new_record?
636 def update_modified_by_fields
637 current_time = db_current_time
638 self.created_at ||= created_at_was || current_time
639 self.updated_at = current_time
640 self.owner_uuid ||= current_default_owner if self.respond_to? :owner_uuid=
641 if !anonymous_updater
642 self.modified_by_user_uuid = current_user ? current_user.uuid : nil
645 self.modified_at = current_time
647 self.modified_by_client_uuid = current_api_client ? current_api_client.uuid : nil
651 def self.has_nonstring_keys? x
654 return true if !(k.is_a?(String) || k.is_a?(Symbol)) || has_nonstring_keys?(v)
658 return true if has_nonstring_keys?(v)
664 def self.where_serialized(colname, value, md5: false)
665 colsql = colname.to_s
667 colsql = "md5(#{colsql})"
670 # rails4 stores as null, rails3 stored as serialized [] or {}
671 sql = "#{colsql} is null or #{colsql} IN (?)"
674 sql = "#{colsql} IN (?)"
675 sorted = deep_sort_hash(value)
677 params = [sorted.to_yaml, SafeJSON.dump(sorted)]
679 params = params.map { |x| Digest::MD5.hexdigest(x) }
685 Hash => HashSerializer,
686 Array => ArraySerializer,
689 def self.serialize(colname, type)
690 coder = Serializer[type]
691 @serialized_attributes ||= {}
692 @serialized_attributes[colname.to_s] = coder
693 super(colname, coder)
696 def self.serialized_attributes
697 @serialized_attributes ||= {}
700 def serialized_attributes
701 self.class.serialized_attributes
704 def foreign_key_attributes
705 attributes.keys.select { |a| a.match(/_uuid$/) }
708 def skip_uuid_read_permission_check
709 %w(modified_by_client_uuid)
712 def skip_uuid_existence_check
716 def normalize_collection_uuids
717 foreign_key_attributes.each do |attr|
718 attr_value = send attr
719 if attr_value.is_a? String and
720 attr_value.match(/^[0-9a-f]{32,}(\+[@\w]+)*$/)
722 send "#{attr}=", Collection.normalize_uuid(attr_value)
724 # TODO: abort instead of silently accepting unnormalizable value?
730 @@prefixes_hash = nil
731 def self.uuid_prefixes
732 unless @@prefixes_hash
734 Rails.application.eager_load!
735 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |k|
736 if k.respond_to?(:uuid_prefix)
737 @@prefixes_hash[k.uuid_prefix] = k
744 def self.uuid_like_pattern
745 "#{Rails.configuration.ClusterID}-#{uuid_prefix}-_______________"
749 %r/[a-z0-9]{5}-#{uuid_prefix}-[a-z0-9]{15}/
752 def ensure_valid_uuids
753 specials = [system_user_uuid]
755 foreign_key_attributes.each do |attr|
756 if new_record? or send (attr + "_changed?")
757 next if skip_uuid_existence_check.include? attr
758 attr_value = send attr
759 next if specials.include? attr_value
761 if (r = ArvadosModel::resource_class_for_uuid attr_value)
762 unless skip_uuid_read_permission_check.include? attr
763 r = r.readable_by(current_user)
765 if r.where(uuid: attr_value).count == 0
766 errors.add(attr, "'#{attr_value}' not found")
774 def ensure_filesystem_compatible_name
775 if name == "." || name == ".."
776 errors.add(:name, "cannot be '.' or '..'")
777 elsif Rails.configuration.Collections.ForwardSlashNameSubstitution == "" && !name.nil? && name.index('/')
778 errors.add(:name, "cannot contain a '/' character")
791 def self.readable_by (*u)
796 [{:uuid => u[:uuid]}]
800 def self.resource_class_for_uuid(uuid)
801 if uuid.is_a? ArvadosModel
804 unless uuid.is_a? String
808 uuid.match HasUuid::UUID_REGEX do |re|
809 return uuid_prefixes[re[1]] if uuid_prefixes[re[1]]
812 if uuid.match(/.+@.+/)
819 # ArvadosModel.find_by_uuid needs extra magic to allow it to return
820 # an object in any class.
821 def self.find_by_uuid uuid
822 if self == ArvadosModel
823 # If called directly as ArvadosModel.find_by_uuid rather than via subclass,
824 # delegate to the appropriate subclass based on the given uuid.
825 self.resource_class_for_uuid(uuid).find_by_uuid(uuid)
831 def is_audit_logging_enabled?
832 return !(Rails.configuration.AuditLogs.MaxAge.to_i == 0 &&
833 Rails.configuration.AuditLogs.MaxDeleteBatch.to_i > 0)
837 if is_audit_logging_enabled?
838 @old_attributes = Marshal.load(Marshal.dump(attributes))
839 @old_logged_attributes = Marshal.load(Marshal.dump(logged_attributes))
843 def log_change(event_type)
844 if is_audit_logging_enabled?
845 log = Log.new(event_type: event_type).fill_object(self)
853 if is_audit_logging_enabled?
854 log_change('create') do |log|
855 log.fill_properties('old', nil, nil)
862 if is_audit_logging_enabled?
863 log_change('update') do |log|
864 log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
871 if is_audit_logging_enabled?
872 log_change('delete') do |log|
873 log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)