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_find :schedule_restoring_changes
20 after_initialize :log_start_state
21 before_save :ensure_permission_to_save
22 before_save :ensure_owner_uuid_is_permitted
23 before_save :ensure_ownership_path_leads_to_user
24 before_destroy :ensure_owner_uuid_is_permitted
25 before_destroy :ensure_permission_to_destroy
26 before_create :update_modified_by_fields
27 before_update :maybe_update_modified_by_fields
28 after_create :log_create
29 after_update :log_update
30 after_destroy :log_destroy
31 before_validation :normalize_collection_uuids
32 before_validation :set_default_owner
33 validate :ensure_valid_uuids
35 # Note: This only returns permission links. It does not account for
36 # permissions obtained via user.is_admin or
37 # user.uuid==object.owner_uuid.
38 has_many(:permissions,
39 ->{where(link_class: 'permission')},
40 foreign_key: :head_uuid,
44 # If async is true at create or update, permission graph
45 # update is deferred allowing making multiple calls without the performance
47 attr_accessor :async_permissions_update
49 # Ignore listed attributes on mass assignments
50 def self.protected_attributes
54 class PermissionDeniedError < RequestError
60 class AlreadyLockedError < RequestError
66 class LockFailedError < RequestError
72 class InvalidStateTransitionError < RequestError
78 class UnauthorizedError < RequestError
84 class UnresolvableContainerError < RequestError
90 def self.kind_class(kind)
91 kind.match(/^arvados\#(.+)$/)[1].classify.safe_constantize rescue nil
95 "#{current_api_base}/#{self.class.to_s.pluralize.underscore}/#{self.uuid}"
98 def self.permit_attribute_params raw_params
99 # strong_parameters does not provide security: permissions are
100 # implemented with before_save hooks.
102 # The following permit! is necessary even with
103 # "ActionController::Parameters.permit_all_parameters = true",
104 # because permit_all does not permit nested attributes.
108 raw_params = raw_params.to_hash
109 raw_params.delete_if { |k, _| self.protected_attributes.include? k }
110 serialized_attributes.each do |colname, coder|
111 param = raw_params[colname.to_sym]
114 elsif !param.is_a?(coder.object_class)
115 raise ArgumentError.new("#{colname} parameter must be #{coder.object_class}, not #{param.class}")
116 elsif has_nonstring_keys?(param)
117 raise ArgumentError.new("#{colname} parameter cannot have non-string hash keys")
120 # Check JSONB columns that aren't listed on serialized_attributes
121 columns.select{|c| c.type == :jsonb}.collect{|j| j.name}.each do |colname|
122 if serialized_attributes.include? colname || raw_params[colname.to_sym].nil?
125 if has_nonstring_keys?(raw_params[colname.to_sym])
126 raise ArgumentError.new("#{colname} parameter cannot have non-string hash keys")
130 ActionController::Parameters.new(raw_params).permit!
133 def initialize raw_params={}, *args
134 super(self.class.permit_attribute_params(raw_params), *args)
137 # Reload "old attributes" for logging, too.
144 def self.create raw_params={}, *args
145 super(permit_attribute_params(raw_params), *args)
148 def update_attributes raw_params={}, *args
149 super(self.class.permit_attribute_params(raw_params), *args)
152 def self.selectable_attributes(template=:user)
153 # Return an array of attribute name strings that can be selected
154 # in the given template.
155 api_accessible_attributes(template).map { |attr_spec| attr_spec.first.to_s }
158 def self.searchable_columns operator
159 textonly_operator = !operator.match(/[<=>]/)
160 self.columns.select do |col|
164 when :datetime, :integer, :boolean
172 def self.attribute_column attr
173 self.columns.select { |col| col.name == attr.to_s }.first
176 def self.attributes_required_columns
177 # This method returns a hash. Each key is the name of an API attribute,
178 # and it's mapped to a list of database columns that must be fetched
179 # to generate that attribute.
180 # This implementation generates a simple map of attributes to
181 # matching column names. Subclasses can override this method
182 # to specify that method-backed API attributes need to fetch
183 # specific columns from the database.
184 all_columns = columns.map(&:name)
185 api_column_map = Hash.new { |hash, key| hash[key] = [] }
186 methods.grep(/^api_accessible_\w+$/).each do |method_name|
187 next if method_name == :api_accessible_attributes
188 send(method_name).each_pair do |api_attr_name, col_name|
189 col_name = col_name.to_s
190 if all_columns.include?(col_name)
191 api_column_map[api_attr_name.to_s] |= [col_name]
198 def self.ignored_select_attributes
199 ["href", "kind", "etag"]
202 def self.columns_for_attributes(select_attributes)
203 if select_attributes.empty?
204 raise ArgumentError.new("Attribute selection list cannot be empty")
206 api_column_map = attributes_required_columns
208 select_attributes.each do |s|
209 next if ignored_select_attributes.include? s
210 if not s.is_a? String or not api_column_map.include? s
214 if not invalid_attrs.empty?
215 raise ArgumentError.new("Invalid attribute(s): #{invalid_attrs.inspect}")
217 # Given an array of attribute names to select, return an array of column
218 # names that must be fetched from the database to satisfy the request.
219 select_attributes.flat_map { |attr| api_column_map[attr] }.uniq
222 def self.default_orders
223 ["#{table_name}.modified_at desc", "#{table_name}.uuid desc"]
226 def self.unique_columns
230 def self.limit_index_columns_read
231 # This method returns a list of column names.
232 # If an index request reads that column from the database,
233 # APIs that return lists will only fetch objects until reaching
234 # max_index_database_read bytes of data from those columns.
238 # If current user can manage the object, return an array of uuids of
239 # users and groups that have permission to write the object. The
240 # first two elements are always [self.owner_uuid, current user's
243 # If current user can write but not manage the object, return
244 # [self.owner_uuid, current user's uuid].
246 # If current user cannot write this object, just return
249 # Return [] if this is a frozen project and the current user can't
251 return [] if respond_to?(:frozen_by_uuid) && frozen_by_uuid &&
252 (Rails.configuration.API.UnfreezeProjectRequiresAdmin ?
253 !current_user.andand.is_admin :
254 !current_user.can?(manage: uuid))
255 # Return [] if nobody can write because this object is inside a
257 return [] if FrozenGroup.where(uuid: owner_uuid).any?
258 return [owner_uuid] if not current_user
259 unless (owner_uuid == current_user.uuid or
260 current_user.is_admin or
261 (current_user.groups_i_can(:manage) & [uuid, owner_uuid]).any?)
262 if ((current_user.groups_i_can(:write) + [current_user.uuid]) &
263 [uuid, owner_uuid]).any?
264 return [owner_uuid, current_user.uuid]
269 [owner_uuid, current_user.uuid] + permissions.collect do |p|
270 if ['can_write', 'can_manage'].index p.name
277 if respond_to?(:frozen_by_uuid) && frozen_by_uuid
280 return owner_uuid == current_user.uuid ||
281 current_user.is_admin ||
282 current_user.can?(write: uuid)
287 return owner_uuid == current_user.uuid ||
288 current_user.is_admin ||
289 current_user.can?(manage: uuid)
292 # Return a query with read permissions restricted to the union of the
293 # permissions of the members of users_list, i.e. if something is readable by
294 # any user in users_list, it will be readable in the query returned by this
296 def self.readable_by(*users_list)
297 # Get rid of troublesome nils
300 # Load optional keyword arguments, if they exist.
301 if users_list.last.is_a? Hash
302 kwargs = users_list.pop
307 # Collect the UUIDs of the authorized users.
308 sql_table = kwargs.fetch(:table_name, table_name)
309 include_trash = kwargs.fetch(:include_trash, false)
310 include_old_versions = kwargs.fetch(:include_old_versions, false)
313 user_uuids = users_list.map { |u| u.uuid }
316 admin = users_list.select { |u| u.is_admin }.any?
318 # For details on how the trashed_groups table is constructed, see
319 # see db/migrate/20200501150153_permission_table.rb
321 # excluded_trash is a SQL expression that determines whether a row
322 # should be excluded from the results due to being trashed.
323 # Trashed items inside frozen projects are invisible to regular
324 # (non-admin) users even when using include_trash, so we have:
326 # (item_trashed || item_inside_trashed_project)
328 # (!caller_requests_include_trash ||
329 # (item_inside_frozen_project && caller_is_not_admin))
330 if (admin && include_trash) || sql_table == "api_client_authorizations"
331 excluded_trash = "false"
333 excluded_trash = "(#{sql_table}.owner_uuid IN (SELECT group_uuid FROM #{TRASHED_GROUPS} " +
334 "WHERE trash_at <= statement_timestamp()))"
335 if sql_table == "groups" || sql_table == "collections"
336 excluded_trash = "(#{excluded_trash} OR #{sql_table}.trash_at <= statement_timestamp() IS TRUE)"
340 # Exclude trash inside frozen projects
341 excluded_trash = "(#{excluded_trash} AND #{sql_table}.owner_uuid IN (SELECT uuid FROM #{FROZEN_GROUPS}))"
346 # Admin skips most permission checks, but still want to filter
348 if !include_trash && sql_table != "api_client_authorizations"
349 # Only include records where the owner is not trashed
350 sql_conds = "NOT (#{excluded_trash})"
353 # The core of the permission check is a join against the
354 # materialized_permissions table to determine if the user has at
355 # least read permission to either the object itself or its
356 # direct owner (if traverse_owned is true). See
357 # db/migrate/20200501150153_permission_table.rb for details on
358 # how the permissions are computed.
360 # A user can have can_manage access to another user, this grants
361 # full access to all that user's stuff. To implement that we
362 # need to include those other users in the permission query.
364 # This was previously implemented by embedding the subquery
365 # directly into the query, but it was discovered later that this
366 # causes the Postgres query planner to do silly things because
367 # the query heuristics assumed the subquery would have a lot
368 # more rows that it does, and choose a bad merge strategy. By
369 # doing the query here and embedding the result as a constant,
370 # Postgres also knows exactly how many items there are and can
371 # choose the right query strategy.
373 # (note: you could also do this with a temporary table, but that
374 # would require all every request be wrapped in a transaction,
375 # which is not currently the case).
377 all_user_uuids = ActiveRecord::Base.connection.exec_query %{
378 #{USER_UUIDS_SUBQUERY_TEMPLATE % {user: "'#{user_uuids.join "', '"}'", perm_level: 1}}
380 'readable_by.user_uuids'
382 user_uuids_subquery = ":user_uuids"
384 # Note: it is possible to combine the direct_check and
385 # owner_check into a single IN (SELECT) clause, however it turns
386 # out query optimizer doesn't like it and forces a sequential
387 # table scan. Constructing the query with separate IN (SELECT)
388 # clauses enables it to use the index.
390 # see issue 13208 for details.
392 # Match a direct read permission link from the user to the record uuid
393 direct_check = "#{sql_table}.uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
394 "WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 1)"
396 # Match a read permission for the user to the record's
397 # owner_uuid. This is so we can have a permissions table that
398 # mostly consists of users and groups (projects are a type of
399 # group) and not have to compute and list user permission to
400 # every single object in the system.
402 # Don't do this for API keys (special behavior) or groups
403 # (already covered by direct_check).
405 # The traverse_owned flag indicates whether the permission to
406 # read an object also implies transitive permission to read
407 # things the object owns. The situation where this is important
408 # are determining if we can read an object owned by another
409 # user. This makes it possible to have permission to read the
410 # user record without granting permission to read things the
413 if sql_table != "api_client_authorizations" and sql_table != "groups" then
414 owner_check = "#{sql_table}.owner_uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
415 "WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 1 AND traverse_owned) "
417 # We want to do owner_check before direct_check in the OR
418 # clause. The order of the OR clause isn't supposed to
419 # matter, but in practice, it does -- apparently in the
420 # absence of other hints, it uses the ordering from the query.
421 # For certain types of queries (like filtering on owner_uuid),
422 # every item will match the owner_check clause, so then
423 # Postgres will optimize out the direct_check entirely.
424 direct_check = " OR " + direct_check
427 if Rails.configuration.Users.RoleGroupsVisibleToAll &&
428 sql_table == "groups" &&
429 users_list.select { |u| u.is_active }.any?
430 # All role groups are readable (but we still need the other
431 # direct_check clauses to handle non-role groups).
432 direct_check += " OR #{sql_table}.group_class = 'role'"
436 if sql_table == "links"
437 # 1) Match permission links incoming or outgoing on the
438 # user, i.e. granting permission on the user, or granting
439 # permission to the user.
441 # 2) Match permission links which grant permission on an
442 # object that this user can_manage.
444 links_cond = "OR (#{sql_table}.link_class IN (:permission_link_classes) AND "+
445 " ((#{sql_table}.head_uuid IN (#{user_uuids_subquery}) OR #{sql_table}.tail_uuid IN (#{user_uuids_subquery})) OR " +
446 " #{sql_table}.head_uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
447 " WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 3))) "
450 sql_conds = "(#{owner_check} #{direct_check} #{links_cond}) AND NOT (#{excluded_trash})"
454 if !include_old_versions && sql_table == "collections"
455 exclude_old_versions = "#{sql_table}.uuid = #{sql_table}.current_version_uuid"
457 sql_conds = exclude_old_versions
459 sql_conds += " AND #{exclude_old_versions}"
463 self.where(sql_conds,
464 user_uuids: all_user_uuids.collect{|c| c["target_uuid"]},
465 permission_link_classes: ['permission'])
468 def save_with_unique_name!
473 conn = ActiveRecord::Base.connection
474 conn.exec_query 'SAVEPOINT save_with_unique_name'
477 rescue ActiveRecord::RecordNotUnique => rn
478 raise if max_retries == 0
481 conn.exec_query 'ROLLBACK TO SAVEPOINT save_with_unique_name'
483 # Dig into the error to determine if it is specifically calling out a
484 # (owner_uuid, name) uniqueness violation. In this specific case, and
485 # the client requested a unique name with ensure_unique_name==true,
486 # update the name field and try to save again. Loop as necessary to
487 # discover a unique name. It is necessary to handle name choosing at
488 # this level (as opposed to the client) to ensure that record creation
489 # never fails due to a race condition.
491 raise unless err.is_a?(PG::UniqueViolation)
493 # Unfortunately ActiveRecord doesn't abstract out any of the
494 # necessary information to figure out if this the error is actually
495 # the specific case where we want to apply the ensure_unique_name
496 # behavior, so the following code is specialized to Postgres.
497 detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
498 raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
500 new_name = "#{name_was} (#{db_current_time.utc.iso8601(3)})"
502 # If the database is fast enough to do two attempts in the
503 # same millisecond, we need to wait to ensure we try a
504 # different timestamp on each attempt.
506 new_name = "#{name_was} (#{db_current_time.utc.iso8601(3)})"
509 self[:name] = new_name
510 if uuid_was.nil? && !uuid.nil?
512 if self.is_a? Collection
513 # Reset so that is assigned to the new UUID
514 self[:current_version_uuid] = nil
517 conn.exec_query 'SAVEPOINT save_with_unique_name'
520 conn.exec_query 'RELEASE SAVEPOINT save_with_unique_name'
526 if self.owner_uuid.nil?
527 return current_user.uuid
529 owner_class = ArvadosModel.resource_class_for_uuid(self.owner_uuid)
530 if owner_class == User
533 owner_class.find_by_uuid(self.owner_uuid).user_owner_uuid
537 def logged_attributes
538 attributes.except(*Rails.configuration.AuditLogs.UnloggedAttributes.stringify_keys.keys)
541 def self.full_text_searchable_columns
542 self.columns.select do |col|
543 [:string, :text, :jsonb].include?(col.type)
547 def self.full_text_coalesce
548 full_text_searchable_columns.collect do |column|
549 is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
550 cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
551 "coalesce(#{column}#{cast},'')"
555 def self.full_text_trgm
556 "(#{full_text_coalesce.join(" || ' ' || ")})"
559 def self.full_text_tsvector
560 parts = full_text_searchable_columns.collect do |column|
561 is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
562 cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
563 "coalesce(#{column}#{cast},'')"
565 "to_tsvector('english', substr(#{parts.join(" || ' ' || ")}, 0, 8000))"
568 def self.apply_filters query, filters
569 ft = record_filters filters, self
570 if not ft[:cond_out].any?
573 ft[:joins].each do |t|
574 query = query.joins(t)
576 query.where('(' + ft[:cond_out].join(') AND (') + ')',
582 def self.deep_sort_hash(x)
584 x.sort.collect do |k, v|
585 [k, deep_sort_hash(v)]
588 x.collect { |v| deep_sort_hash(v) }
594 def ensure_ownership_path_leads_to_user
595 if new_record? or owner_uuid_changed?
596 uuid_in_path = {owner_uuid => true, uuid => true}
598 while (owner_class = ArvadosModel::resource_class_for_uuid(x)) != User
601 # Test for cycles with the new version, not the DB contents
603 elsif !owner_class.respond_to? :find_by_uuid
604 raise ActiveRecord::RecordNotFound.new
606 x = owner_class.find_by_uuid(x).owner_uuid
608 rescue ActiveRecord::RecordNotFound => e
609 errors.add :owner_uuid, "is not owned by any user: #{e}"
614 errors.add :owner_uuid, "would create an ownership cycle"
616 errors.add :owner_uuid, "has an ownership cycle"
620 uuid_in_path[x] = true
626 def set_default_owner
627 if new_record? and current_user and respond_to? :owner_uuid=
628 self.owner_uuid ||= current_user.uuid
632 def ensure_owner_uuid_is_permitted
633 raise PermissionDeniedError if !current_user
635 if self.owner_uuid.nil?
636 errors.add :owner_uuid, "cannot be nil"
637 raise PermissionDeniedError
640 rsc_class = ArvadosModel::resource_class_for_uuid owner_uuid
641 unless rsc_class == User or rsc_class == Group
642 errors.add :owner_uuid, "must be set to User or Group"
643 raise PermissionDeniedError
646 if new_record? || owner_uuid_changed?
647 # Permission on owner_uuid_was is needed to move an existing
648 # object away from its previous owner (which implies permission
649 # to modify this object itself, so we don't need to check that
650 # separately). Permission on the new owner_uuid is also needed.
651 [['old', owner_uuid_was],
653 ].each do |which, check_uuid|
655 # old_owner_uuid is nil? New record, no need to check.
656 elsif !current_user.can?(write: check_uuid)
657 if FrozenGroup.where(uuid: check_uuid).any?
658 errors.add :owner_uuid, "cannot be set or changed because #{which} owner is frozen"
660 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}"
661 errors.add :owner_uuid, "cannot be set or changed without write permission on #{which} owner"
663 raise PermissionDeniedError
664 elsif rsc_class == Group && Group.find_by_uuid(owner_uuid).group_class != "project"
665 errors.add :owner_uuid, "must be a project"
666 raise PermissionDeniedError
670 # If the object already existed and we're not changing
671 # owner_uuid, we only need write permission on the object
672 # itself. (If we're in the act of unfreezing, we only need
673 # :unfreeze permission, which means "what write permission would
674 # be if target weren't frozen")
675 unless ((respond_to?(:frozen_by_uuid) && frozen_by_uuid_was && !frozen_by_uuid) ?
676 current_user.can?(unfreeze: uuid) :
677 current_user.can?(write: uuid))
678 logger.warn "User #{current_user.uuid} tried to modify #{self.class.to_s} #{self.uuid} without write permission"
679 errors.add :uuid, " #{uuid} is not writable by #{current_user.uuid}"
680 raise PermissionDeniedError
687 def ensure_permission_to_save
688 unless (new_record? ? permission_to_create : permission_to_update)
689 raise PermissionDeniedError
693 def permission_to_create
694 return current_user.andand.is_active
697 def permission_to_update
699 logger.warn "Anonymous user tried to update #{self.class.to_s} #{self.uuid_was}"
702 if !current_user.is_active
703 logger.warn "Inactive user #{current_user.uuid} tried to update #{self.class.to_s} #{self.uuid_was}"
706 return true if current_user.is_admin
707 if self.uuid_changed?
708 logger.warn "User #{current_user.uuid} tried to change uuid of #{self.class.to_s} #{self.uuid_was} to #{self.uuid}"
714 def ensure_permission_to_destroy
715 raise PermissionDeniedError unless permission_to_destroy
718 def permission_to_destroy
719 if [system_user_uuid, system_group_uuid, anonymous_group_uuid,
720 anonymous_user_uuid, public_project_uuid].include? uuid
727 def maybe_update_modified_by_fields
728 update_modified_by_fields if self.changed? or self.new_record?
732 def update_modified_by_fields
733 current_time = db_current_time
734 self.created_at ||= created_at_was || current_time
735 self.updated_at = current_time
736 self.owner_uuid ||= current_default_owner if self.respond_to? :owner_uuid=
737 if !anonymous_updater
738 self.modified_by_user_uuid = current_user ? current_user.uuid : nil
741 self.modified_at = current_time
743 self.modified_by_client_uuid = current_api_client ? current_api_client.uuid : nil
747 def self.has_nonstring_keys? x
750 return true if !(k.is_a?(String) || k.is_a?(Symbol)) || has_nonstring_keys?(v)
754 return true if has_nonstring_keys?(v)
760 def self.where_serialized(colname, value, md5: false, multivalue: false)
761 colsql = colname.to_s
763 colsql = "md5(#{colsql})"
766 # rails4 stores as null, rails3 stored as serialized [] or {}
767 sql = "#{colsql} is null or #{colsql} IN (?)"
770 sql = "#{colsql} IN (?)"
771 sorted = deep_sort_hash(value)
777 params << SafeJSON.dump(v)
780 params << sorted.to_yaml
781 params << SafeJSON.dump(sorted)
784 params = params.map { |x| Digest::MD5.hexdigest(x) }
790 Hash => HashSerializer,
791 Array => ArraySerializer,
794 def self.serialize(colname, type)
795 coder = Serializer[type]
796 @serialized_attributes ||= {}
797 @serialized_attributes[colname.to_s] = coder
798 super(colname, coder)
801 def self.serialized_attributes
802 @serialized_attributes ||= {}
805 def serialized_attributes
806 self.class.serialized_attributes
809 def foreign_key_attributes
810 attributes.keys.select { |a| a.match(/_uuid$/) }
813 def skip_uuid_read_permission_check
814 %w(modified_by_client_uuid)
817 def skip_uuid_existence_check
821 def normalize_collection_uuids
822 foreign_key_attributes.each do |attr|
823 attr_value = send attr
824 if attr_value.is_a? String and
825 attr_value.match(/^[0-9a-f]{32,}(\+[@\w]+)*$/)
827 send "#{attr}=", Collection.normalize_uuid(attr_value)
829 # TODO: abort instead of silently accepting unnormalizable value?
835 @@prefixes_hash = nil
836 def self.uuid_prefixes
837 unless @@prefixes_hash
839 Rails.application.eager_load!
840 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |k|
841 if k.respond_to?(:uuid_prefix)
842 @@prefixes_hash[k.uuid_prefix] = k
849 def self.uuid_like_pattern
850 "#{Rails.configuration.ClusterID}-#{uuid_prefix}-_______________"
854 %r/[a-z0-9]{5}-#{uuid_prefix}-[a-z0-9]{15}/
857 def check_readable_uuid attr, attr_value
858 return if attr_value.nil?
859 if (r = ArvadosModel::resource_class_for_uuid attr_value)
860 unless skip_uuid_read_permission_check.include? attr
861 r = r.readable_by(current_user)
863 if r.where(uuid: attr_value).count == 0
864 errors.add(attr, "'#{attr_value}' not found")
867 # Not a valid uuid or PDH, but that (currently) is not an error.
871 def ensure_valid_uuids
872 specials = [system_user_uuid]
874 foreign_key_attributes.each do |attr|
875 if new_record? or send (attr + "_changed?")
876 next if skip_uuid_existence_check.include? attr
877 attr_value = send attr
878 next if specials.include? attr_value
879 check_readable_uuid attr, attr_value
884 def ensure_filesystem_compatible_name
885 if name == "." || name == ".."
886 errors.add(:name, "cannot be '.' or '..'")
887 elsif Rails.configuration.Collections.ForwardSlashNameSubstitution == "" && !name.nil? && name.index('/')
888 errors.add(:name, "cannot contain a '/' character")
901 def self.readable_by (*u)
906 [{:uuid => u[:uuid]}]
910 def self.resource_class_for_uuid(uuid)
911 if uuid.is_a? ArvadosModel
914 unless uuid.is_a? String
918 uuid.match HasUuid::UUID_REGEX do |re|
919 return uuid_prefixes[re[1]] if uuid_prefixes[re[1]]
922 if uuid.match(/.+@.+/)
929 # Fill in implied zero/false values in database records that were
930 # created before #17014 made them explicit, and reset the Rails
931 # "changed" state so the record doesn't appear to have been modified
934 # Invoked by Container and ContainerRequest models as an after_find
936 def fill_container_defaults_after_find
937 fill_container_defaults
938 set_attribute_was('runtime_constraints', runtime_constraints)
939 set_attribute_was('scheduling_parameters', scheduling_parameters)
940 clear_changes_information
943 # Fill in implied zero/false values. Invoked by ContainerRequest as
944 # a before_validation hook in order to (a) ensure every key has a
945 # value in the updated database record and (b) ensure the attribute
946 # whitelist doesn't reject a change from an explicit zero/false
947 # value in the database to an implicit zero/false value in an update
949 def fill_container_defaults
950 self.runtime_constraints = {
954 'driver_version' => '',
955 'hardware_capability' => '',
957 'keep_cache_ram' => 0,
960 }.merge(attributes['runtime_constraints'] || {})
961 self.scheduling_parameters = {
964 'preemptible' => false,
965 }.merge(attributes['scheduling_parameters'] || {})
968 # ArvadosModel.find_by_uuid needs extra magic to allow it to return
969 # an object in any class.
970 def self.find_by_uuid uuid
971 if self == ArvadosModel
972 # If called directly as ArvadosModel.find_by_uuid rather than via subclass,
973 # delegate to the appropriate subclass based on the given uuid.
974 self.resource_class_for_uuid(uuid).find_by_uuid(uuid)
980 def is_audit_logging_enabled?
981 return !(Rails.configuration.AuditLogs.MaxAge.to_i == 0 &&
982 Rails.configuration.AuditLogs.MaxDeleteBatch.to_i > 0)
985 def schedule_restoring_changes
986 # This will be checked at log_start_state, to reset any (virtual) changes
987 # produced by the act of reading a serialized attribute.
988 @fresh_from_database = true
992 if is_audit_logging_enabled?
993 @old_attributes = Marshal.load(Marshal.dump(attributes))
994 @old_logged_attributes = Marshal.load(Marshal.dump(logged_attributes))
995 if @fresh_from_database
996 # This instance was created from reading a database record. Attributes
997 # haven't been changed, but those serialized attributes will be reported
998 # as unpersisted, so we restore them to avoid issues with lock!() and
1001 @fresh_from_database = nil
1006 def log_change(event_type)
1007 if is_audit_logging_enabled?
1008 log = Log.new(event_type: event_type).fill_object(self)
1016 if is_audit_logging_enabled?
1017 log_change('create') do |log|
1018 log.fill_properties('old', nil, nil)
1025 if is_audit_logging_enabled?
1026 log_change('update') do |log|
1027 log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
1034 if is_audit_logging_enabled?
1035 log_change('delete') do |log|
1036 log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)