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