16007: Lots and lots lots of method documentation via code comments.
[arvados.git] / services / api / app / models / arvados_model.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'arvados_model_updates'
6 require 'has_uuid'
7 require 'record_filters'
8 require 'serializers'
9 require 'request_error'
10
11 class ArvadosModel < ApplicationRecord
12   self.abstract_class = true
13
14   include ArvadosModelUpdates
15   include CurrentApiClient      # current_user, current_api_client, etc.
16   include DbCurrentTime
17   extend RecordFilters
18
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
33
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,
40            class_name: 'Link',
41            primary_key: :uuid)
42
43   # If async is true at create or update, permission graph
44   # update is deferred allowing making multiple calls without the performance
45   # penalty.
46   attr_accessor :async_permissions_update
47
48   # Ignore listed attributes on mass assignments
49   def self.protected_attributes
50     []
51   end
52
53   class PermissionDeniedError < RequestError
54     def http_status
55       403
56     end
57   end
58
59   class AlreadyLockedError < RequestError
60     def http_status
61       422
62     end
63   end
64
65   class LockFailedError < RequestError
66     def http_status
67       422
68     end
69   end
70
71   class InvalidStateTransitionError < RequestError
72     def http_status
73       422
74     end
75   end
76
77   class UnauthorizedError < RequestError
78     def http_status
79       401
80     end
81   end
82
83   class UnresolvableContainerError < RequestError
84     def http_status
85       422
86     end
87   end
88
89   def self.kind_class(kind)
90     kind.match(/^arvados\#(.+)$/)[1].classify.safe_constantize rescue nil
91   end
92
93   def href
94     "#{current_api_base}/#{self.class.to_s.pluralize.underscore}/#{self.uuid}"
95   end
96
97   def self.permit_attribute_params raw_params
98     # strong_parameters does not provide security: permissions are
99     # implemented with before_save hooks.
100     #
101     # The following permit! is necessary even with
102     # "ActionController::Parameters.permit_all_parameters = true",
103     # because permit_all does not permit nested attributes.
104     raw_params ||= {}
105
106     if raw_params
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]
111         if param.nil?
112           # ok
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")
117         end
118       end
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?
122           next
123         end
124         if has_nonstring_keys?(raw_params[colname.to_sym])
125           raise ArgumentError.new("#{colname} parameter cannot have non-string hash keys")
126         end
127       end
128     end
129     ActionController::Parameters.new(raw_params).permit!
130   end
131
132   def initialize raw_params={}, *args
133     super(self.class.permit_attribute_params(raw_params), *args)
134   end
135
136   # Reload "old attributes" for logging, too.
137   def reload(*args)
138     super
139     log_start_state
140   end
141
142   def self.create raw_params={}, *args
143     super(permit_attribute_params(raw_params), *args)
144   end
145
146   def update_attributes raw_params={}, *args
147     super(self.class.permit_attribute_params(raw_params), *args)
148   end
149
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 }
154   end
155
156   def self.searchable_columns operator
157     textonly_operator = !operator.match(/[<=>]/)
158     self.columns.select do |col|
159       case col.type
160       when :string, :text
161         true
162       when :datetime, :integer, :boolean
163         !textonly_operator
164       else
165         false
166       end
167     end.map(&:name)
168   end
169
170   def self.attribute_column attr
171     self.columns.select { |col| col.name == attr.to_s }.first
172   end
173
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]
190         end
191       end
192     end
193     api_column_map
194   end
195
196   def self.ignored_select_attributes
197     ["href", "kind", "etag"]
198   end
199
200   def self.columns_for_attributes(select_attributes)
201     if select_attributes.empty?
202       raise ArgumentError.new("Attribute selection list cannot be empty")
203     end
204     api_column_map = attributes_required_columns
205     invalid_attrs = []
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
209         invalid_attrs << s
210       end
211     end
212     if not invalid_attrs.empty?
213       raise ArgumentError.new("Invalid attribute(s): #{invalid_attrs.inspect}")
214     end
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
218   end
219
220   def self.default_orders
221     ["#{table_name}.modified_at desc", "#{table_name}.uuid"]
222   end
223
224   def self.unique_columns
225     ["id", "uuid"]
226   end
227
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.
233     []
234   end
235
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
239   # uuid].
240   #
241   # If current user can write but not manage the object, return
242   # [self.owner_uuid, current user's uuid].
243   #
244   # If current user cannot write this object, just return
245   # [self.owner_uuid].
246   def writable_by
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]
254       else
255         return [owner_uuid]
256       end
257     end
258     [owner_uuid, current_user.uuid] + permissions.collect do |p|
259       if ['can_write', 'can_manage'].index p.name
260         p.tail_uuid
261       end
262     end.compact.uniq
263   end
264
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
268   # function.
269   def self.readable_by(*users_list)
270     # Get rid of troublesome nils
271     users_list.compact!
272
273     # Load optional keyword arguments, if they exist.
274     if users_list.last.is_a? Hash
275       kwargs = users_list.pop
276     else
277       kwargs = {}
278     end
279
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)
284
285     sql_conds = nil
286     user_uuids = users_list.map { |u| u.uuid }
287
288     # For details on how the trashed_groups table is constructed, see
289     # see db/migrate/20200501150153_permission_table.rb
290
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())"
295     end
296
297     if users_list.select { |u| u.is_admin }.any?
298       # Admin skips most permission checks, but still want to filter on trashed items.
299       if !include_trash
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}"
304         end
305       end
306     else
307       trashed_check = ""
308       if !include_trash then
309         trashed_check = "AND target_uuid NOT IN (SELECT group_uuid FROM #{TRASHED_GROUPS} where trash_at <= statement_timestamp())"
310       end
311
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.  See
316       # db/migrate/20200501150153_permission_table.rb for details on
317       # how the permissions are computed.
318
319       # Note: it is possible to combine the direct_check and
320       # owner_check into a single EXISTS() clause, however it turns
321       # out query optimizer doesn't like it and forces a sequential
322       # table scan.  Constructing the query with separate EXISTS()
323       # clauses enables it to use the index.
324       #
325       # see issue 13208 for details.
326
327       # Match a direct read permission link from the user to the record uuid
328       direct_check = "#{sql_table}.uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
329                      "WHERE user_uuid IN (:user_uuids) AND perm_level >= 1 #{trashed_check})"
330
331       # Match a read permission for the user to the record's
332       # owner_uuid.  This is so we can have a permissions table that
333       # mostly consists of users and groups (projects are a type of
334       # group) and not have to compute and list user permission to
335       # every single object in the system.
336       #
337       # Don't do this for API keys (special behavior) or groups
338       # (already covered by direct_check).
339       #
340       # The traverse_owned flag indicates whether the permission to
341       # read an object also implies transitive permission to read
342       # things the object owns.  The situation where this is important
343       # are determining if we can read an object owned by another
344       # user.  This makes it possible to have permission to read the
345       # user record without granting permission to read things the
346       # other user owns.
347       owner_check = ""
348       if sql_table != "api_client_authorizations" and sql_table != "groups" then
349         owner_check = "OR #{sql_table}.owner_uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
350           "WHERE user_uuid IN (:user_uuids) AND perm_level >= 1 #{trashed_check} AND traverse_owned) "
351       end
352
353       links_cond = ""
354       if sql_table == "links"
355         # Match any permission link that gives one of the authorized
356         # users some permission _or_ gives anyone else permission to
357         # view one of the authorized users.
358         links_cond = "OR (#{sql_table}.link_class IN (:permission_link_classes) AND "+
359                        "(#{sql_table}.head_uuid IN (:user_uuids) OR #{sql_table}.tail_uuid IN (:user_uuids)))"
360       end
361
362       sql_conds = "(#{direct_check} #{owner_check} #{links_cond}) #{exclude_trashed_records}"
363
364     end
365
366     if !include_old_versions && sql_table == "collections"
367       exclude_old_versions = "#{sql_table}.uuid = #{sql_table}.current_version_uuid"
368       if sql_conds.nil?
369         sql_conds = exclude_old_versions
370       else
371         sql_conds += " AND #{exclude_old_versions}"
372       end
373     end
374
375     self.where(sql_conds,
376                user_uuids: user_uuids,
377                permission_link_classes: ['permission', 'resources'])
378   end
379
380   def save_with_unique_name!
381     uuid_was = uuid
382     name_was = name
383     max_retries = 2
384     transaction do
385       conn = ActiveRecord::Base.connection
386       conn.exec_query 'SAVEPOINT save_with_unique_name'
387       begin
388         save!
389       rescue ActiveRecord::RecordNotUnique => rn
390         raise if max_retries == 0
391         max_retries -= 1
392
393         conn.exec_query 'ROLLBACK TO SAVEPOINT save_with_unique_name'
394
395         # Dig into the error to determine if it is specifically calling out a
396         # (owner_uuid, name) uniqueness violation.  In this specific case, and
397         # the client requested a unique name with ensure_unique_name==true,
398         # update the name field and try to save again.  Loop as necessary to
399         # discover a unique name.  It is necessary to handle name choosing at
400         # this level (as opposed to the client) to ensure that record creation
401         # never fails due to a race condition.
402         err = rn.cause
403         raise unless err.is_a?(PG::UniqueViolation)
404
405         # Unfortunately ActiveRecord doesn't abstract out any of the
406         # necessary information to figure out if this the error is actually
407         # the specific case where we want to apply the ensure_unique_name
408         # behavior, so the following code is specialized to Postgres.
409         detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
410         raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
411
412         new_name = "#{name_was} (#{db_current_time.utc.iso8601(3)})"
413         if new_name == name
414           # If the database is fast enough to do two attempts in the
415           # same millisecond, we need to wait to ensure we try a
416           # different timestamp on each attempt.
417           sleep 0.002
418           new_name = "#{name_was} (#{db_current_time.utc.iso8601(3)})"
419         end
420
421         self[:name] = new_name
422         if uuid_was.nil? && !uuid.nil?
423           self[:uuid] = nil
424           if self.is_a? Collection
425             # Reset so that is assigned to the new UUID
426             self[:current_version_uuid] = nil
427           end
428         end
429         conn.exec_query 'SAVEPOINT save_with_unique_name'
430         retry
431       ensure
432         conn.exec_query 'RELEASE SAVEPOINT save_with_unique_name'
433       end
434     end
435   end
436
437   def user_owner_uuid
438     if self.owner_uuid.nil?
439       return current_user.uuid
440     end
441     owner_class = ArvadosModel.resource_class_for_uuid(self.owner_uuid)
442     if owner_class == User
443       self.owner_uuid
444     else
445       owner_class.find_by_uuid(self.owner_uuid).user_owner_uuid
446     end
447   end
448
449   def logged_attributes
450     attributes.except(*Rails.configuration.AuditLogs.UnloggedAttributes.keys)
451   end
452
453   def self.full_text_searchable_columns
454     self.columns.select do |col|
455       [:string, :text, :jsonb].include?(col.type)
456     end.map(&:name)
457   end
458
459   def self.full_text_coalesce
460     full_text_searchable_columns.collect do |column|
461       is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
462       cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
463       "coalesce(#{column}#{cast},'')"
464     end
465   end
466
467   def self.full_text_trgm
468     "(#{full_text_coalesce.join(" || ' ' || ")})"
469   end
470
471   def self.full_text_tsvector
472     parts = full_text_searchable_columns.collect do |column|
473       is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
474       cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
475       "coalesce(#{column}#{cast},'')"
476     end
477     "to_tsvector('english', substr(#{parts.join(" || ' ' || ")}, 0, 8000))"
478   end
479
480   def self.apply_filters query, filters
481     ft = record_filters filters, self
482     if not ft[:cond_out].any?
483       return query
484     end
485     ft[:joins].each do |t|
486       query = query.joins(t)
487     end
488     query.where('(' + ft[:cond_out].join(') AND (') + ')',
489                           *ft[:param_out])
490   end
491
492   protected
493
494   def self.deep_sort_hash(x)
495     if x.is_a? Hash
496       x.sort.collect do |k, v|
497         [k, deep_sort_hash(v)]
498       end.to_h
499     elsif x.is_a? Array
500       x.collect { |v| deep_sort_hash(v) }
501     else
502       x
503     end
504   end
505
506   def ensure_ownership_path_leads_to_user
507     if new_record? or owner_uuid_changed?
508       uuid_in_path = {owner_uuid => true, uuid => true}
509       x = owner_uuid
510       while (owner_class = ArvadosModel::resource_class_for_uuid(x)) != User
511         begin
512           if x == uuid
513             # Test for cycles with the new version, not the DB contents
514             x = owner_uuid
515           elsif !owner_class.respond_to? :find_by_uuid
516             raise ActiveRecord::RecordNotFound.new
517           else
518             x = owner_class.find_by_uuid(x).owner_uuid
519           end
520         rescue ActiveRecord::RecordNotFound => e
521           errors.add :owner_uuid, "is not owned by any user: #{e}"
522           throw(:abort)
523         end
524         if uuid_in_path[x]
525           if x == owner_uuid
526             errors.add :owner_uuid, "would create an ownership cycle"
527           else
528             errors.add :owner_uuid, "has an ownership cycle"
529           end
530           throw(:abort)
531         end
532         uuid_in_path[x] = true
533       end
534     end
535     true
536   end
537
538   def set_default_owner
539     if new_record? and current_user and respond_to? :owner_uuid=
540       self.owner_uuid ||= current_user.uuid
541     end
542   end
543
544   def ensure_owner_uuid_is_permitted
545     raise PermissionDeniedError if !current_user
546
547     if self.owner_uuid.nil?
548       errors.add :owner_uuid, "cannot be nil"
549       raise PermissionDeniedError
550     end
551
552     rsc_class = ArvadosModel::resource_class_for_uuid owner_uuid
553     unless rsc_class == User or rsc_class == Group
554       errors.add :owner_uuid, "must be set to User or Group"
555       raise PermissionDeniedError
556     end
557
558     if new_record? || owner_uuid_changed?
559       # Permission on owner_uuid_was is needed to move an existing
560       # object away from its previous owner (which implies permission
561       # to modify this object itself, so we don't need to check that
562       # separately). Permission on the new owner_uuid is also needed.
563       [['old', owner_uuid_was],
564        ['new', owner_uuid]
565       ].each do |which, check_uuid|
566         if check_uuid.nil?
567           # old_owner_uuid is nil? New record, no need to check.
568         elsif !current_user.can?(write: check_uuid)
569           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}"
570           errors.add :owner_uuid, "cannot be set or changed without write permission on #{which} owner"
571           raise PermissionDeniedError
572         end
573       end
574     else
575       # If the object already existed and we're not changing
576       # owner_uuid, we only need write permission on the object
577       # itself.
578       if !current_user.can?(write: self.uuid)
579         logger.warn "User #{current_user.uuid} tried to modify #{self.class.to_s} #{self.uuid} without write permission"
580         errors.add :uuid, "is not writable"
581         raise PermissionDeniedError
582       end
583     end
584
585     true
586   end
587
588   def ensure_permission_to_save
589     unless (new_record? ? permission_to_create : permission_to_update)
590       raise PermissionDeniedError
591     end
592   end
593
594   def permission_to_create
595     current_user.andand.is_active
596   end
597
598   def permission_to_update
599     if !current_user
600       logger.warn "Anonymous user tried to update #{self.class.to_s} #{self.uuid_was}"
601       return false
602     end
603     if !current_user.is_active
604       logger.warn "Inactive user #{current_user.uuid} tried to update #{self.class.to_s} #{self.uuid_was}"
605       return false
606     end
607     return true if current_user.is_admin
608     if self.uuid_changed?
609       logger.warn "User #{current_user.uuid} tried to change uuid of #{self.class.to_s} #{self.uuid_was} to #{self.uuid}"
610       return false
611     end
612     return true
613   end
614
615   def ensure_permission_to_destroy
616     raise PermissionDeniedError unless permission_to_destroy
617   end
618
619   def permission_to_destroy
620     permission_to_update
621   end
622
623   def maybe_update_modified_by_fields
624     update_modified_by_fields if self.changed? or self.new_record?
625     true
626   end
627
628   def update_modified_by_fields
629     current_time = db_current_time
630     self.created_at ||= created_at_was || current_time
631     self.updated_at = current_time
632     self.owner_uuid ||= current_default_owner if self.respond_to? :owner_uuid=
633     if !anonymous_updater
634       self.modified_by_user_uuid = current_user ? current_user.uuid : nil
635     end
636     if !timeless_updater
637       self.modified_at = current_time
638     end
639     self.modified_by_client_uuid = current_api_client ? current_api_client.uuid : nil
640     true
641   end
642
643   def self.has_nonstring_keys? x
644     if x.is_a? Hash
645       x.each do |k,v|
646         return true if !(k.is_a?(String) || k.is_a?(Symbol)) || has_nonstring_keys?(v)
647       end
648     elsif x.is_a? Array
649       x.each do |v|
650         return true if has_nonstring_keys?(v)
651       end
652     end
653     false
654   end
655
656   def self.where_serialized(colname, value, md5: false)
657     colsql = colname.to_s
658     if md5
659       colsql = "md5(#{colsql})"
660     end
661     if value.empty?
662       # rails4 stores as null, rails3 stored as serialized [] or {}
663       sql = "#{colsql} is null or #{colsql} IN (?)"
664       sorted = value
665     else
666       sql = "#{colsql} IN (?)"
667       sorted = deep_sort_hash(value)
668     end
669     params = [sorted.to_yaml, SafeJSON.dump(sorted)]
670     if md5
671       params = params.map { |x| Digest::MD5.hexdigest(x) }
672     end
673     where(sql, params)
674   end
675
676   Serializer = {
677     Hash => HashSerializer,
678     Array => ArraySerializer,
679   }
680
681   def self.serialize(colname, type)
682     coder = Serializer[type]
683     @serialized_attributes ||= {}
684     @serialized_attributes[colname.to_s] = coder
685     super(colname, coder)
686   end
687
688   def self.serialized_attributes
689     @serialized_attributes ||= {}
690   end
691
692   def serialized_attributes
693     self.class.serialized_attributes
694   end
695
696   def foreign_key_attributes
697     attributes.keys.select { |a| a.match(/_uuid$/) }
698   end
699
700   def skip_uuid_read_permission_check
701     %w(modified_by_client_uuid)
702   end
703
704   def skip_uuid_existence_check
705     []
706   end
707
708   def normalize_collection_uuids
709     foreign_key_attributes.each do |attr|
710       attr_value = send attr
711       if attr_value.is_a? String and
712           attr_value.match(/^[0-9a-f]{32,}(\+[@\w]+)*$/)
713         begin
714           send "#{attr}=", Collection.normalize_uuid(attr_value)
715         rescue
716           # TODO: abort instead of silently accepting unnormalizable value?
717         end
718       end
719     end
720   end
721
722   @@prefixes_hash = nil
723   def self.uuid_prefixes
724     unless @@prefixes_hash
725       @@prefixes_hash = {}
726       Rails.application.eager_load!
727       ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |k|
728         if k.respond_to?(:uuid_prefix)
729           @@prefixes_hash[k.uuid_prefix] = k
730         end
731       end
732     end
733     @@prefixes_hash
734   end
735
736   def self.uuid_like_pattern
737     "#{Rails.configuration.ClusterID}-#{uuid_prefix}-_______________"
738   end
739
740   def self.uuid_regex
741     %r/[a-z0-9]{5}-#{uuid_prefix}-[a-z0-9]{15}/
742   end
743
744   def ensure_valid_uuids
745     specials = [system_user_uuid]
746
747     foreign_key_attributes.each do |attr|
748       if new_record? or send (attr + "_changed?")
749         next if skip_uuid_existence_check.include? attr
750         attr_value = send attr
751         next if specials.include? attr_value
752         if attr_value
753           if (r = ArvadosModel::resource_class_for_uuid attr_value)
754             unless skip_uuid_read_permission_check.include? attr
755               r = r.readable_by(current_user)
756             end
757             if r.where(uuid: attr_value).count == 0
758               errors.add(attr, "'#{attr_value}' not found")
759             end
760           end
761         end
762       end
763     end
764   end
765
766   def ensure_filesystem_compatible_name
767     if name == "." || name == ".."
768       errors.add(:name, "cannot be '.' or '..'")
769     elsif Rails.configuration.Collections.ForwardSlashNameSubstitution == "" && !name.nil? && name.index('/')
770       errors.add(:name, "cannot contain a '/' character")
771     end
772   end
773
774   class Email
775     def self.kind
776       "email"
777     end
778
779     def kind
780       self.class.kind
781     end
782
783     def self.readable_by (*u)
784       self
785     end
786
787     def self.where (u)
788       [{:uuid => u[:uuid]}]
789     end
790   end
791
792   def self.resource_class_for_uuid(uuid)
793     if uuid.is_a? ArvadosModel
794       return uuid.class
795     end
796     unless uuid.is_a? String
797       return nil
798     end
799
800     uuid.match HasUuid::UUID_REGEX do |re|
801       return uuid_prefixes[re[1]] if uuid_prefixes[re[1]]
802     end
803
804     if uuid.match(/.+@.+/)
805       return Email
806     end
807
808     nil
809   end
810
811   # ArvadosModel.find_by_uuid needs extra magic to allow it to return
812   # an object in any class.
813   def self.find_by_uuid uuid
814     if self == ArvadosModel
815       # If called directly as ArvadosModel.find_by_uuid rather than via subclass,
816       # delegate to the appropriate subclass based on the given uuid.
817       self.resource_class_for_uuid(uuid).find_by_uuid(uuid)
818     else
819       super
820     end
821   end
822
823   def is_audit_logging_enabled?
824     return !(Rails.configuration.AuditLogs.MaxAge.to_i == 0 &&
825              Rails.configuration.AuditLogs.MaxDeleteBatch.to_i > 0)
826   end
827
828   def log_start_state
829     if is_audit_logging_enabled?
830       @old_attributes = Marshal.load(Marshal.dump(attributes))
831       @old_logged_attributes = Marshal.load(Marshal.dump(logged_attributes))
832     end
833   end
834
835   def log_change(event_type)
836     if is_audit_logging_enabled?
837       log = Log.new(event_type: event_type).fill_object(self)
838       yield log
839       log.save!
840       log_start_state
841     end
842   end
843
844   def log_create
845     if is_audit_logging_enabled?
846       log_change('create') do |log|
847         log.fill_properties('old', nil, nil)
848         log.update_to self
849       end
850     end
851   end
852
853   def log_update
854     if is_audit_logging_enabled?
855       log_change('update') do |log|
856         log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
857         log.update_to self
858       end
859     end
860   end
861
862   def log_destroy
863     if is_audit_logging_enabled?
864       log_change('delete') do |log|
865         log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
866         log.update_to nil
867       end
868     end
869   end
870 end