Merge branch '17749-s3-prefixes'
[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     all_user_uuids = []
290
291     # For details on how the trashed_groups table is constructed, see
292     # see db/migrate/20200501150153_permission_table.rb
293
294     exclude_trashed_records = ""
295     if !include_trash and (sql_table == "groups" or sql_table == "collections") then
296       # Only include records that are not trashed
297       exclude_trashed_records = "AND (#{sql_table}.trash_at is NULL or #{sql_table}.trash_at > statement_timestamp())"
298     end
299
300     trashed_check = ""
301     if !include_trash && sql_table != "api_client_authorizations"
302       trashed_check = "#{sql_table}.owner_uuid NOT IN (SELECT group_uuid FROM #{TRASHED_GROUPS} " +
303                       "where trash_at <= statement_timestamp()) #{exclude_trashed_records}"
304     end
305
306     if users_list.select { |u| u.is_admin }.any?
307       # Admin skips most permission checks, but still want to filter on trashed items.
308       if !include_trash && sql_table != "api_client_authorizations"
309         # Only include records where the owner is not trashed
310         sql_conds = trashed_check
311       end
312     else
313       # The core of the permission check is a join against the
314       # materialized_permissions table to determine if the user has at
315       # least read permission to either the object itself or its
316       # direct owner (if traverse_owned is true).  See
317       # db/migrate/20200501150153_permission_table.rb for details on
318       # how the permissions are computed.
319
320       # A user can have can_manage access to another user, this grants
321       # full access to all that user's stuff.  To implement that we
322       # need to include those other users in the permission query.
323
324       # This was previously implemented by embedding the subquery
325       # directly into the query, but it was discovered later that this
326       # causes the Postgres query planner to do silly things because
327       # the query heuristics assumed the subquery would have a lot
328       # more rows that it does, and choose a bad merge strategy.  By
329       # doing the query here and embedding the result as a constant,
330       # Postgres also knows exactly how many items there are and can
331       # choose the right query strategy.
332       #
333       # (note: you could also do this with a temporary table, but that
334       # would require all every request be wrapped in a transaction,
335       # which is not currently the case).
336
337       all_user_uuids = ActiveRecord::Base.connection.exec_query %{
338 #{USER_UUIDS_SUBQUERY_TEMPLATE % {user: "'#{user_uuids.join "', '"}'", perm_level: 1}}
339 },
340                                              'readable_by.user_uuids'
341
342       user_uuids_subquery = ":user_uuids"
343
344       # Note: it is possible to combine the direct_check and
345       # owner_check into a single IN (SELECT) clause, however it turns
346       # out query optimizer doesn't like it and forces a sequential
347       # table scan.  Constructing the query with separate IN (SELECT)
348       # clauses enables it to use the index.
349       #
350       # see issue 13208 for details.
351
352       # Match a direct read permission link from the user to the record uuid
353       direct_check = "#{sql_table}.uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
354                      "WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 1)"
355
356       # Match a read permission for the user to the record's
357       # owner_uuid.  This is so we can have a permissions table that
358       # mostly consists of users and groups (projects are a type of
359       # group) and not have to compute and list user permission to
360       # every single object in the system.
361       #
362       # Don't do this for API keys (special behavior) or groups
363       # (already covered by direct_check).
364       #
365       # The traverse_owned flag indicates whether the permission to
366       # read an object also implies transitive permission to read
367       # things the object owns.  The situation where this is important
368       # are determining if we can read an object owned by another
369       # user.  This makes it possible to have permission to read the
370       # user record without granting permission to read things the
371       # other user owns.
372       owner_check = ""
373       if sql_table != "api_client_authorizations" and sql_table != "groups" then
374         owner_check = "#{sql_table}.owner_uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
375                       "WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 1 AND traverse_owned) "
376
377         # We want to do owner_check before direct_check in the OR
378         # clause.  The order of the OR clause isn't supposed to
379         # matter, but in practice, it does -- apparently in the
380         # absence of other hints, it uses the ordering from the query.
381         # For certain types of queries (like filtering on owner_uuid),
382         # every item will match the owner_check clause, so then
383         # Postgres will optimize out the direct_check entirely.
384         direct_check = " OR " + direct_check
385       end
386
387       links_cond = ""
388       if sql_table == "links"
389         # 1) Match permission links incoming or outgoing on the
390         # user, i.e. granting permission on the user, or granting
391         # permission to the user.
392         #
393         # 2) Match permission links which grant permission on an
394         # object that this user can_manage.
395         #
396         links_cond = "OR (#{sql_table}.link_class IN (:permission_link_classes) AND "+
397                      "   ((#{sql_table}.head_uuid IN (#{user_uuids_subquery}) OR #{sql_table}.tail_uuid IN (#{user_uuids_subquery})) OR " +
398                      "    #{sql_table}.head_uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
399                      "    WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 3))) "
400       end
401
402       sql_conds = "(#{owner_check} #{direct_check} #{links_cond}) #{trashed_check.empty? ? "" : "AND"} #{trashed_check}"
403
404     end
405
406     if !include_old_versions && sql_table == "collections"
407       exclude_old_versions = "#{sql_table}.uuid = #{sql_table}.current_version_uuid"
408       if sql_conds.nil?
409         sql_conds = exclude_old_versions
410       else
411         sql_conds += " AND #{exclude_old_versions}"
412       end
413     end
414
415     self.where(sql_conds,
416                user_uuids: all_user_uuids.collect{|c| c["target_uuid"]},
417                permission_link_classes: ['permission'])
418   end
419
420   def save_with_unique_name!
421     uuid_was = uuid
422     name_was = name
423     max_retries = 2
424     transaction do
425       conn = ActiveRecord::Base.connection
426       conn.exec_query 'SAVEPOINT save_with_unique_name'
427       begin
428         save!
429       rescue ActiveRecord::RecordNotUnique => rn
430         raise if max_retries == 0
431         max_retries -= 1
432
433         conn.exec_query 'ROLLBACK TO SAVEPOINT save_with_unique_name'
434
435         # Dig into the error to determine if it is specifically calling out a
436         # (owner_uuid, name) uniqueness violation.  In this specific case, and
437         # the client requested a unique name with ensure_unique_name==true,
438         # update the name field and try to save again.  Loop as necessary to
439         # discover a unique name.  It is necessary to handle name choosing at
440         # this level (as opposed to the client) to ensure that record creation
441         # never fails due to a race condition.
442         err = rn.cause
443         raise unless err.is_a?(PG::UniqueViolation)
444
445         # Unfortunately ActiveRecord doesn't abstract out any of the
446         # necessary information to figure out if this the error is actually
447         # the specific case where we want to apply the ensure_unique_name
448         # behavior, so the following code is specialized to Postgres.
449         detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
450         raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
451
452         new_name = "#{name_was} (#{db_current_time.utc.iso8601(3)})"
453         if new_name == name
454           # If the database is fast enough to do two attempts in the
455           # same millisecond, we need to wait to ensure we try a
456           # different timestamp on each attempt.
457           sleep 0.002
458           new_name = "#{name_was} (#{db_current_time.utc.iso8601(3)})"
459         end
460
461         self[:name] = new_name
462         if uuid_was.nil? && !uuid.nil?
463           self[:uuid] = nil
464           if self.is_a? Collection
465             # Reset so that is assigned to the new UUID
466             self[:current_version_uuid] = nil
467           end
468         end
469         conn.exec_query 'SAVEPOINT save_with_unique_name'
470         retry
471       ensure
472         conn.exec_query 'RELEASE SAVEPOINT save_with_unique_name'
473       end
474     end
475   end
476
477   def user_owner_uuid
478     if self.owner_uuid.nil?
479       return current_user.uuid
480     end
481     owner_class = ArvadosModel.resource_class_for_uuid(self.owner_uuid)
482     if owner_class == User
483       self.owner_uuid
484     else
485       owner_class.find_by_uuid(self.owner_uuid).user_owner_uuid
486     end
487   end
488
489   def logged_attributes
490     attributes.except(*Rails.configuration.AuditLogs.UnloggedAttributes.stringify_keys.keys)
491   end
492
493   def self.full_text_searchable_columns
494     self.columns.select do |col|
495       [:string, :text, :jsonb].include?(col.type)
496     end.map(&:name)
497   end
498
499   def self.full_text_coalesce
500     full_text_searchable_columns.collect do |column|
501       is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
502       cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
503       "coalesce(#{column}#{cast},'')"
504     end
505   end
506
507   def self.full_text_trgm
508     "(#{full_text_coalesce.join(" || ' ' || ")})"
509   end
510
511   def self.full_text_tsvector
512     parts = full_text_searchable_columns.collect do |column|
513       is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
514       cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
515       "coalesce(#{column}#{cast},'')"
516     end
517     "to_tsvector('english', substr(#{parts.join(" || ' ' || ")}, 0, 8000))"
518   end
519
520   def self.apply_filters query, filters
521     ft = record_filters filters, self
522     if not ft[:cond_out].any?
523       return query
524     end
525     ft[:joins].each do |t|
526       query = query.joins(t)
527     end
528     query.where('(' + ft[:cond_out].join(') AND (') + ')',
529                           *ft[:param_out])
530   end
531
532   protected
533
534   def self.deep_sort_hash(x)
535     if x.is_a? Hash
536       x.sort.collect do |k, v|
537         [k, deep_sort_hash(v)]
538       end.to_h
539     elsif x.is_a? Array
540       x.collect { |v| deep_sort_hash(v) }
541     else
542       x
543     end
544   end
545
546   def ensure_ownership_path_leads_to_user
547     if new_record? or owner_uuid_changed?
548       uuid_in_path = {owner_uuid => true, uuid => true}
549       x = owner_uuid
550       while (owner_class = ArvadosModel::resource_class_for_uuid(x)) != User
551         begin
552           if x == uuid
553             # Test for cycles with the new version, not the DB contents
554             x = owner_uuid
555           elsif !owner_class.respond_to? :find_by_uuid
556             raise ActiveRecord::RecordNotFound.new
557           else
558             x = owner_class.find_by_uuid(x).owner_uuid
559           end
560         rescue ActiveRecord::RecordNotFound => e
561           errors.add :owner_uuid, "is not owned by any user: #{e}"
562           throw(:abort)
563         end
564         if uuid_in_path[x]
565           if x == owner_uuid
566             errors.add :owner_uuid, "would create an ownership cycle"
567           else
568             errors.add :owner_uuid, "has an ownership cycle"
569           end
570           throw(:abort)
571         end
572         uuid_in_path[x] = true
573       end
574     end
575     true
576   end
577
578   def set_default_owner
579     if new_record? and current_user and respond_to? :owner_uuid=
580       self.owner_uuid ||= current_user.uuid
581     end
582   end
583
584   def ensure_owner_uuid_is_permitted
585     raise PermissionDeniedError if !current_user
586
587     if self.owner_uuid.nil?
588       errors.add :owner_uuid, "cannot be nil"
589       raise PermissionDeniedError
590     end
591
592     rsc_class = ArvadosModel::resource_class_for_uuid owner_uuid
593     unless rsc_class == User or rsc_class == Group
594       errors.add :owner_uuid, "must be set to User or Group"
595       raise PermissionDeniedError
596     end
597
598     if new_record? || owner_uuid_changed?
599       # Permission on owner_uuid_was is needed to move an existing
600       # object away from its previous owner (which implies permission
601       # to modify this object itself, so we don't need to check that
602       # separately). Permission on the new owner_uuid is also needed.
603       [['old', owner_uuid_was],
604        ['new', owner_uuid]
605       ].each do |which, check_uuid|
606         if check_uuid.nil?
607           # old_owner_uuid is nil? New record, no need to check.
608         elsif !current_user.can?(write: check_uuid)
609           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}"
610           errors.add :owner_uuid, "cannot be set or changed without write permission on #{which} owner"
611           raise PermissionDeniedError
612         elsif rsc_class == Group && Group.find_by_uuid(owner_uuid).group_class != "project"
613           errors.add :owner_uuid, "must be a project"
614           raise PermissionDeniedError
615         end
616       end
617     else
618       # If the object already existed and we're not changing
619       # owner_uuid, we only need write permission on the object
620       # itself.
621       if !current_user.can?(write: self.uuid)
622         logger.warn "User #{current_user.uuid} tried to modify #{self.class.to_s} #{self.uuid} without write permission"
623         errors.add :uuid, " #{uuid} is not writable by #{current_user.uuid}"
624         raise PermissionDeniedError
625       end
626     end
627
628     true
629   end
630
631   def ensure_permission_to_save
632     unless (new_record? ? permission_to_create : permission_to_update)
633       raise PermissionDeniedError
634     end
635   end
636
637   def permission_to_create
638     current_user.andand.is_active
639   end
640
641   def permission_to_update
642     if !current_user
643       logger.warn "Anonymous user tried to update #{self.class.to_s} #{self.uuid_was}"
644       return false
645     end
646     if !current_user.is_active
647       logger.warn "Inactive user #{current_user.uuid} tried to update #{self.class.to_s} #{self.uuid_was}"
648       return false
649     end
650     return true if current_user.is_admin
651     if self.uuid_changed?
652       logger.warn "User #{current_user.uuid} tried to change uuid of #{self.class.to_s} #{self.uuid_was} to #{self.uuid}"
653       return false
654     end
655     return true
656   end
657
658   def ensure_permission_to_destroy
659     raise PermissionDeniedError unless permission_to_destroy
660   end
661
662   def permission_to_destroy
663     if [system_user_uuid, system_group_uuid, anonymous_group_uuid,
664         anonymous_user_uuid, public_project_uuid].include? uuid
665       false
666     else
667       permission_to_update
668     end
669   end
670
671   def maybe_update_modified_by_fields
672     update_modified_by_fields if self.changed? or self.new_record?
673     true
674   end
675
676   def update_modified_by_fields
677     current_time = db_current_time
678     self.created_at ||= created_at_was || current_time
679     self.updated_at = current_time
680     self.owner_uuid ||= current_default_owner if self.respond_to? :owner_uuid=
681     if !anonymous_updater
682       self.modified_by_user_uuid = current_user ? current_user.uuid : nil
683     end
684     if !timeless_updater
685       self.modified_at = current_time
686     end
687     self.modified_by_client_uuid = current_api_client ? current_api_client.uuid : nil
688     true
689   end
690
691   def self.has_nonstring_keys? x
692     if x.is_a? Hash
693       x.each do |k,v|
694         return true if !(k.is_a?(String) || k.is_a?(Symbol)) || has_nonstring_keys?(v)
695       end
696     elsif x.is_a? Array
697       x.each do |v|
698         return true if has_nonstring_keys?(v)
699       end
700     end
701     false
702   end
703
704   def self.where_serialized(colname, value, md5: false)
705     colsql = colname.to_s
706     if md5
707       colsql = "md5(#{colsql})"
708     end
709     if value.empty?
710       # rails4 stores as null, rails3 stored as serialized [] or {}
711       sql = "#{colsql} is null or #{colsql} IN (?)"
712       sorted = value
713     else
714       sql = "#{colsql} IN (?)"
715       sorted = deep_sort_hash(value)
716     end
717     params = [sorted.to_yaml, SafeJSON.dump(sorted)]
718     if md5
719       params = params.map { |x| Digest::MD5.hexdigest(x) }
720     end
721     where(sql, params)
722   end
723
724   Serializer = {
725     Hash => HashSerializer,
726     Array => ArraySerializer,
727   }
728
729   def self.serialize(colname, type)
730     coder = Serializer[type]
731     @serialized_attributes ||= {}
732     @serialized_attributes[colname.to_s] = coder
733     super(colname, coder)
734   end
735
736   def self.serialized_attributes
737     @serialized_attributes ||= {}
738   end
739
740   def serialized_attributes
741     self.class.serialized_attributes
742   end
743
744   def foreign_key_attributes
745     attributes.keys.select { |a| a.match(/_uuid$/) }
746   end
747
748   def skip_uuid_read_permission_check
749     %w(modified_by_client_uuid)
750   end
751
752   def skip_uuid_existence_check
753     []
754   end
755
756   def normalize_collection_uuids
757     foreign_key_attributes.each do |attr|
758       attr_value = send attr
759       if attr_value.is_a? String and
760           attr_value.match(/^[0-9a-f]{32,}(\+[@\w]+)*$/)
761         begin
762           send "#{attr}=", Collection.normalize_uuid(attr_value)
763         rescue
764           # TODO: abort instead of silently accepting unnormalizable value?
765         end
766       end
767     end
768   end
769
770   @@prefixes_hash = nil
771   def self.uuid_prefixes
772     unless @@prefixes_hash
773       @@prefixes_hash = {}
774       Rails.application.eager_load!
775       ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |k|
776         if k.respond_to?(:uuid_prefix)
777           @@prefixes_hash[k.uuid_prefix] = k
778         end
779       end
780     end
781     @@prefixes_hash
782   end
783
784   def self.uuid_like_pattern
785     "#{Rails.configuration.ClusterID}-#{uuid_prefix}-_______________"
786   end
787
788   def self.uuid_regex
789     %r/[a-z0-9]{5}-#{uuid_prefix}-[a-z0-9]{15}/
790   end
791
792   def check_readable_uuid attr, attr_value
793     return if attr_value.nil?
794     if (r = ArvadosModel::resource_class_for_uuid attr_value)
795       unless skip_uuid_read_permission_check.include? attr
796         r = r.readable_by(current_user)
797       end
798       if r.where(uuid: attr_value).count == 0
799         errors.add(attr, "'#{attr_value}' not found")
800       end
801     else
802       # Not a valid uuid or PDH, but that (currently) is not an error.
803     end
804   end
805
806   def ensure_valid_uuids
807     specials = [system_user_uuid]
808
809     foreign_key_attributes.each do |attr|
810       if new_record? or send (attr + "_changed?")
811         next if skip_uuid_existence_check.include? attr
812         attr_value = send attr
813         next if specials.include? attr_value
814         check_readable_uuid attr, attr_value
815       end
816     end
817   end
818
819   def ensure_filesystem_compatible_name
820     if name == "." || name == ".."
821       errors.add(:name, "cannot be '.' or '..'")
822     elsif Rails.configuration.Collections.ForwardSlashNameSubstitution == "" && !name.nil? && name.index('/')
823       errors.add(:name, "cannot contain a '/' character")
824     end
825   end
826
827   class Email
828     def self.kind
829       "email"
830     end
831
832     def kind
833       self.class.kind
834     end
835
836     def self.readable_by (*u)
837       self
838     end
839
840     def self.where (u)
841       [{:uuid => u[:uuid]}]
842     end
843   end
844
845   def self.resource_class_for_uuid(uuid)
846     if uuid.is_a? ArvadosModel
847       return uuid.class
848     end
849     unless uuid.is_a? String
850       return nil
851     end
852
853     uuid.match HasUuid::UUID_REGEX do |re|
854       return uuid_prefixes[re[1]] if uuid_prefixes[re[1]]
855     end
856
857     if uuid.match(/.+@.+/)
858       return Email
859     end
860
861     nil
862   end
863
864   # Fill in implied zero/false values in database records that were
865   # created before #17014 made them explicit, and reset the Rails
866   # "changed" state so the record doesn't appear to have been modified
867   # after loading.
868   #
869   # Invoked by Container and ContainerRequest models as an after_find
870   # hook.
871   def fill_container_defaults_after_find
872     fill_container_defaults
873     set_attribute_was('runtime_constraints', runtime_constraints)
874     set_attribute_was('scheduling_parameters', scheduling_parameters)
875     clear_changes_information
876   end
877
878   # Fill in implied zero/false values. Invoked by ContainerRequest as
879   # a before_validation hook in order to (a) ensure every key has a
880   # value in the updated database record and (b) ensure the attribute
881   # whitelist doesn't reject a change from an explicit zero/false
882   # value in the database to an implicit zero/false value in an update
883   # request.
884   def fill_container_defaults
885     self.runtime_constraints = {
886       'API' => false,
887       'keep_cache_ram' => 0,
888       'ram' => 0,
889       'vcpus' => 0,
890     }.merge(attributes['runtime_constraints'] || {})
891     self.scheduling_parameters = {
892       'max_run_time' => 0,
893       'partitions' => [],
894       'preemptible' => false,
895     }.merge(attributes['scheduling_parameters'] || {})
896   end
897
898   # ArvadosModel.find_by_uuid needs extra magic to allow it to return
899   # an object in any class.
900   def self.find_by_uuid uuid
901     if self == ArvadosModel
902       # If called directly as ArvadosModel.find_by_uuid rather than via subclass,
903       # delegate to the appropriate subclass based on the given uuid.
904       self.resource_class_for_uuid(uuid).find_by_uuid(uuid)
905     else
906       super
907     end
908   end
909
910   def is_audit_logging_enabled?
911     return !(Rails.configuration.AuditLogs.MaxAge.to_i == 0 &&
912              Rails.configuration.AuditLogs.MaxDeleteBatch.to_i > 0)
913   end
914
915   def schedule_restoring_changes
916     # This will be checked at log_start_state, to reset any (virtual) changes
917     # produced by the act of reading a serialized attribute.
918     @fresh_from_database = true
919   end
920
921   def log_start_state
922     if is_audit_logging_enabled?
923       @old_attributes = Marshal.load(Marshal.dump(attributes))
924       @old_logged_attributes = Marshal.load(Marshal.dump(logged_attributes))
925       if @fresh_from_database
926         # This instance was created from reading a database record. Attributes
927         # haven't been changed, but those serialized attributes will be reported
928         # as unpersisted, so we restore them to avoid issues with lock!() and
929         # with_lock().
930         restore_attributes
931         @fresh_from_database = nil
932       end
933     end
934   end
935
936   def log_change(event_type)
937     if is_audit_logging_enabled?
938       log = Log.new(event_type: event_type).fill_object(self)
939       yield log
940       log.save!
941       log_start_state
942     end
943   end
944
945   def log_create
946     if is_audit_logging_enabled?
947       log_change('create') do |log|
948         log.fill_properties('old', nil, nil)
949         log.update_to self
950       end
951     end
952   end
953
954   def log_update
955     if is_audit_logging_enabled?
956       log_change('update') do |log|
957         log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
958         log.update_to self
959       end
960     end
961   end
962
963   def log_destroy
964     if is_audit_logging_enabled?
965       log_change('delete') do |log|
966         log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
967         log.update_to nil
968       end
969     end
970   end
971 end