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