20640: Fix crash on limit_database_read.
[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_create :add_uuid_to_name, :if => Proc.new { @_add_uuid_to_name }
28   before_update :maybe_update_modified_by_fields
29   after_create :log_create
30   after_update :log_update
31   after_destroy :log_destroy
32   before_validation :normalize_collection_uuids
33   before_validation :set_default_owner
34   validate :ensure_valid_uuids
35
36   # Note: This only returns permission links. It does not account for
37   # permissions obtained via user.is_admin or
38   # user.uuid==object.owner_uuid.
39   has_many(:permissions,
40            ->{where(link_class: 'permission')},
41            foreign_key: 'head_uuid',
42            class_name: 'Link',
43            primary_key: 'uuid')
44
45   # If async is true at create or update, permission graph
46   # update is deferred allowing making multiple calls without the performance
47   # penalty.
48   attr_accessor :async_permissions_update
49
50   # Ignore listed attributes on mass assignments
51   def self.protected_attributes
52     []
53   end
54
55   class PermissionDeniedError < RequestError
56     def http_status
57       403
58     end
59   end
60
61   class AlreadyLockedError < RequestError
62     def http_status
63       422
64     end
65   end
66
67   class LockFailedError < RequestError
68     def http_status
69       422
70     end
71   end
72
73   class InvalidStateTransitionError < RequestError
74     def http_status
75       422
76     end
77   end
78
79   class UnauthorizedError < RequestError
80     def http_status
81       401
82     end
83   end
84
85   class UnresolvableContainerError < RequestError
86     def http_status
87       422
88     end
89   end
90
91   def self.kind_class(kind)
92     kind.match(/^arvados\#(.+)$/)[1].classify.safe_constantize rescue nil
93   end
94
95   def href
96     "#{current_api_base}/#{self.class.to_s.pluralize.underscore}/#{self.uuid}"
97   end
98
99   def self.permit_attribute_params raw_params
100     # strong_parameters does not provide security: permissions are
101     # implemented with before_save hooks.
102     #
103     # The following permit! is necessary even with
104     # "ActionController::Parameters.permit_all_parameters = true",
105     # because permit_all does not permit nested attributes.
106     raw_params ||= {}
107
108     if raw_params
109       raw_params = raw_params.to_hash
110       raw_params.delete_if { |k, _| self.protected_attributes.include? k }
111       serialized_attributes.each do |colname, coder|
112         param = raw_params[colname.to_sym]
113         if param.nil?
114           # ok
115         elsif !param.is_a?(coder.object_class)
116           raise ArgumentError.new("#{colname} parameter must be #{coder.object_class}, not #{param.class}")
117         elsif has_nonstring_keys?(param)
118           raise ArgumentError.new("#{colname} parameter cannot have non-string hash keys")
119         end
120       end
121       # Check JSONB columns that aren't listed on serialized_attributes
122       columns.select{|c| c.type == :jsonb}.collect{|j| j.name}.each do |colname|
123         if serialized_attributes.include? colname || raw_params[colname.to_sym].nil?
124           next
125         end
126         if has_nonstring_keys?(raw_params[colname.to_sym])
127           raise ArgumentError.new("#{colname} parameter cannot have non-string hash keys")
128         end
129       end
130     end
131     ActionController::Parameters.new(raw_params).permit!
132   end
133
134   def initialize raw_params={}, *args
135     super(self.class.permit_attribute_params(raw_params), *args)
136   end
137
138   # Reload "old attributes" for logging, too.
139   def reload(*args)
140     super
141     log_start_state
142     self
143   end
144
145   def self.create raw_params={}, *args
146     super(permit_attribute_params(raw_params), *args)
147   end
148
149   def update raw_params={}, *args
150     super(self.class.permit_attribute_params(raw_params), *args)
151   end
152
153   def self.selectable_attributes(template=:user)
154     # Return an array of attribute name strings that can be selected
155     # in the given template.
156     api_accessible_attributes(template).map { |attr_spec| attr_spec.first.to_s }
157   end
158
159   def self.searchable_columns operator
160     textonly_operator = !operator.match(/[<=>]/) && !operator.in?(['in', 'not in'])
161     self.columns.select do |col|
162       case col.type
163       when :string, :text
164         true
165       when :datetime, :integer, :boolean
166         !textonly_operator
167       else
168         false
169       end
170     end.map(&:name)
171   end
172
173   def self.attributes_required_columns
174     # This method returns a hash.  Each key is the name of an API attribute,
175     # and it's mapped to a list of database columns that must be fetched
176     # to generate that attribute.
177     # This implementation generates a simple map of attributes to
178     # matching column names.  Subclasses can override this method
179     # to specify that method-backed API attributes need to fetch
180     # specific columns from the database.
181     all_columns = columns.map(&:name)
182     api_column_map = Hash.new { |hash, key| hash[key] = [] }
183     methods.grep(/^api_accessible_\w+$/).each do |method_name|
184       next if method_name == :api_accessible_attributes
185       send(method_name).each_pair do |api_attr_name, col_name|
186         col_name = col_name.to_s
187         if all_columns.include?(col_name)
188           api_column_map[api_attr_name.to_s] |= [col_name]
189         end
190       end
191     end
192     api_column_map
193   end
194
195   def self.ignored_select_attributes
196     ["href", "kind", "etag"]
197   end
198
199   def self.columns_for_attributes(select_attributes)
200     if select_attributes.empty?
201       raise ArgumentError.new("Attribute selection list cannot be empty")
202     end
203     api_column_map = attributes_required_columns
204     invalid_attrs = []
205     select_attributes.each do |s|
206       next if ignored_select_attributes.include? s
207       if not s.is_a? String or not api_column_map.include? s
208         invalid_attrs << s
209       end
210     end
211     if not invalid_attrs.empty?
212       raise ArgumentError.new("Invalid attribute(s): #{invalid_attrs.inspect}")
213     end
214     # Given an array of attribute names to select, return an array of column
215     # names that must be fetched from the database to satisfy the request.
216     select_attributes.flat_map { |attr| api_column_map[attr] }.uniq
217   end
218
219   def self.default_orders
220     ["#{table_name}.modified_at desc", "#{table_name}.uuid desc"]
221   end
222
223   def self.unique_columns
224     ["id", "uuid"]
225   end
226
227   def self.limit_index_columns_read
228     # This method returns a list of column names.
229     # If an index request reads that column from the database,
230     # APIs that return lists will only fetch objects until reaching
231     # max_index_database_read bytes of data from those columns.
232     []
233   end
234
235   # If current user can manage the object, return an array of uuids of
236   # users and groups that have permission to write the object. The
237   # first two elements are always [self.owner_uuid, current user's
238   # uuid].
239   #
240   # If current user can write but not manage the object, return
241   # [self.owner_uuid, current user's uuid].
242   #
243   # If current user cannot write this object, just return
244   # [self.owner_uuid].
245   def writable_by
246     # Return [] if this is a frozen project and the current user can't
247     # unfreeze
248     return [] if respond_to?(:frozen_by_uuid) && frozen_by_uuid &&
249                  (Rails.configuration.API.UnfreezeProjectRequiresAdmin ?
250                     !current_user.andand.is_admin :
251                     !current_user.can?(manage: uuid))
252     # Return [] if nobody can write because this object is inside a
253     # frozen project
254     return [] if FrozenGroup.where(uuid: owner_uuid).any?
255     return [owner_uuid] if not current_user
256     unless (owner_uuid == current_user.uuid or
257             current_user.is_admin or
258             (current_user.groups_i_can(:manage) & [uuid, owner_uuid]).any?)
259       if ((current_user.groups_i_can(:write) + [current_user.uuid]) &
260           [uuid, owner_uuid]).any?
261         return [owner_uuid, current_user.uuid]
262       else
263         return [owner_uuid]
264       end
265     end
266     [owner_uuid, current_user.uuid] + permissions.collect do |p|
267       if ['can_write', 'can_manage'].index p.name
268         p.tail_uuid
269       end
270     end.compact.uniq
271   end
272
273   def can_write
274     if respond_to?(:frozen_by_uuid) && frozen_by_uuid
275       # This special case is needed to return the correct value from a
276       # "freeze project" API, during which writable status changes
277       # from true to false.
278       #
279       # current_user.can?(write: self) returns true (which is correct
280       # in the context of permission-checking hooks) but the can_write
281       # value we're returning to the caller here represents the state
282       # _after_ the update, i.e., false.
283       return false
284     else
285       return current_user.can?(write: self)
286     end
287   end
288
289   def can_manage
290     return current_user.can?(manage: self)
291   end
292
293   # Return a query with read permissions restricted to the union of the
294   # permissions of the members of users_list, i.e. if something is readable by
295   # any user in users_list, it will be readable in the query returned by this
296   # function.
297   def self.readable_by(*users_list)
298     # Get rid of troublesome nils
299     users_list.compact!
300
301     # Load optional keyword arguments, if they exist.
302     if users_list.last.is_a? Hash
303       kwargs = users_list.pop
304     else
305       kwargs = {}
306     end
307
308     # Collect the UUIDs of the authorized users.
309     sql_table = kwargs.fetch(:table_name, table_name)
310     include_trash = kwargs.fetch(:include_trash, false)
311     include_old_versions = kwargs.fetch(:include_old_versions, false)
312
313     sql_conds = nil
314     user_uuids = users_list.map { |u| u.uuid }
315     all_user_uuids = []
316
317     admin = users_list.select { |u| u.is_admin }.any?
318
319     # For details on how the trashed_groups table is constructed, see
320     # see db/migrate/20200501150153_permission_table.rb
321
322     # excluded_trash is a SQL expression that determines whether a row
323     # should be excluded from the results due to being trashed.
324     # Trashed items inside frozen projects are invisible to regular
325     # (non-admin) users even when using include_trash, so we have:
326     #
327     # (item_trashed || item_inside_trashed_project)
328     # &&
329     # (!caller_requests_include_trash ||
330     #  (item_inside_frozen_project && caller_is_not_admin))
331     if (admin && include_trash) || sql_table == "api_client_authorizations"
332       excluded_trash = "false"
333     else
334       excluded_trash = "(#{sql_table}.owner_uuid IN (SELECT group_uuid FROM #{TRASHED_GROUPS} " +
335                        "WHERE trash_at <= statement_timestamp()))"
336       if sql_table == "groups" || sql_table == "collections"
337         excluded_trash = "(#{excluded_trash} OR #{sql_table}.trash_at <= statement_timestamp() IS TRUE)"
338       end
339
340       if include_trash
341         # Exclude trash inside frozen projects
342         excluded_trash = "(#{excluded_trash} AND #{sql_table}.owner_uuid IN (SELECT uuid FROM #{FROZEN_GROUPS}))"
343       end
344     end
345
346     if admin
347       # Admin skips most permission checks, but still want to filter
348       # on trashed items.
349       if !include_trash && sql_table != "api_client_authorizations"
350         # Only include records where the owner is not trashed
351         sql_conds = "NOT (#{excluded_trash})"
352       end
353     else
354       # The core of the permission check is a join against the
355       # materialized_permissions table to determine if the user has at
356       # least read permission to either the object itself or its
357       # direct owner (if traverse_owned is true).  See
358       # db/migrate/20200501150153_permission_table.rb for details on
359       # how the permissions are computed.
360
361       # A user can have can_manage access to another user, this grants
362       # full access to all that user's stuff.  To implement that we
363       # need to include those other users in the permission query.
364
365       # This was previously implemented by embedding the subquery
366       # directly into the query, but it was discovered later that this
367       # causes the Postgres query planner to do silly things because
368       # the query heuristics assumed the subquery would have a lot
369       # more rows that it does, and choose a bad merge strategy.  By
370       # doing the query here and embedding the result as a constant,
371       # Postgres also knows exactly how many items there are and can
372       # choose the right query strategy.
373       #
374       # (note: you could also do this with a temporary table, but that
375       # would require all every request be wrapped in a transaction,
376       # which is not currently the case).
377
378       all_user_uuids = ActiveRecord::Base.connection.exec_query %{
379 #{USER_UUIDS_SUBQUERY_TEMPLATE % {user: "'#{user_uuids.join "', '"}'", perm_level: 1}}
380 },
381                                              'readable_by.user_uuids'
382
383       user_uuids_subquery = ":user_uuids"
384
385       # Note: it is possible to combine the direct_check and
386       # owner_check into a single IN (SELECT) clause, however it turns
387       # out query optimizer doesn't like it and forces a sequential
388       # table scan.  Constructing the query with separate IN (SELECT)
389       # clauses enables it to use the index.
390       #
391       # see issue 13208 for details.
392
393       # Match a direct read permission link from the user to the record uuid
394       direct_check = "#{sql_table}.uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
395                      "WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 1)"
396
397       # Match a read permission for the user to the record's
398       # owner_uuid.  This is so we can have a permissions table that
399       # mostly consists of users and groups (projects are a type of
400       # group) and not have to compute and list user permission to
401       # every single object in the system.
402       #
403       # Don't do this for API keys (special behavior) or groups
404       # (already covered by direct_check).
405       #
406       # The traverse_owned flag indicates whether the permission to
407       # read an object also implies transitive permission to read
408       # things the object owns.  The situation where this is important
409       # are determining if we can read an object owned by another
410       # user.  This makes it possible to have permission to read the
411       # user record without granting permission to read things the
412       # other user owns.
413       owner_check = ""
414       if sql_table != "api_client_authorizations" and sql_table != "groups" then
415         owner_check = "#{sql_table}.owner_uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
416                       "WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 1 AND traverse_owned) "
417
418         # We want to do owner_check before direct_check in the OR
419         # clause.  The order of the OR clause isn't supposed to
420         # matter, but in practice, it does -- apparently in the
421         # absence of other hints, it uses the ordering from the query.
422         # For certain types of queries (like filtering on owner_uuid),
423         # every item will match the owner_check clause, so then
424         # Postgres will optimize out the direct_check entirely.
425         direct_check = " OR " + direct_check
426       end
427
428       if Rails.configuration.Users.RoleGroupsVisibleToAll &&
429          sql_table == "groups" &&
430          users_list.select { |u| u.is_active }.any?
431         # All role groups are readable (but we still need the other
432         # direct_check clauses to handle non-role groups).
433         direct_check += " OR #{sql_table}.group_class = 'role'"
434       end
435
436       links_cond = ""
437       if sql_table == "links"
438         # 1) Match permission links incoming or outgoing on the
439         # user, i.e. granting permission on the user, or granting
440         # permission to the user.
441         #
442         # 2) Match permission links which grant permission on an
443         # object that this user can_manage.
444         #
445         links_cond = "OR (#{sql_table}.link_class IN (:permission_link_classes) AND "+
446                      "   ((#{sql_table}.head_uuid IN (#{user_uuids_subquery}) OR #{sql_table}.tail_uuid IN (#{user_uuids_subquery})) OR " +
447                      "    #{sql_table}.head_uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
448                      "    WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 3))) "
449       end
450
451       sql_conds = "(#{owner_check} #{direct_check} #{links_cond}) AND NOT (#{excluded_trash})"
452
453     end
454
455     if !include_old_versions && sql_table == "collections"
456       exclude_old_versions = "#{sql_table}.uuid = #{sql_table}.current_version_uuid"
457       if sql_conds.nil?
458         sql_conds = exclude_old_versions
459       else
460         sql_conds += " AND #{exclude_old_versions}"
461       end
462     end
463
464     return self if sql_conds == nil
465     self.where(sql_conds,
466                user_uuids: all_user_uuids.collect{|c| c["target_uuid"]},
467                permission_link_classes: ['permission'])
468   end
469
470   def save_with_unique_name!
471     max_retries = 2
472     transaction do
473       conn = ActiveRecord::Base.connection
474       conn.exec_query 'SAVEPOINT save_with_unique_name'
475       begin
476         save!
477         conn.exec_query 'RELEASE SAVEPOINT save_with_unique_name'
478       rescue ActiveRecord::RecordNotUnique => rn
479         raise if max_retries == 0
480         max_retries -= 1
481
482         # Dig into the error to determine if it is specifically calling out a
483         # (owner_uuid, name) uniqueness violation.  In this specific case, and
484         # the client requested a unique name with ensure_unique_name==true,
485         # update the name field and try to save again.  Loop as necessary to
486         # discover a unique name.  It is necessary to handle name choosing at
487         # this level (as opposed to the client) to ensure that record creation
488         # never fails due to a race condition.
489         err = rn.cause
490         raise unless err.is_a?(PG::UniqueViolation)
491
492         # Unfortunately ActiveRecord doesn't abstract out any of the
493         # necessary information to figure out if this the error is actually
494         # the specific case where we want to apply the ensure_unique_name
495         # behavior, so the following code is specialized to Postgres.
496         detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
497         raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
498
499         conn.exec_query 'ROLLBACK TO SAVEPOINT save_with_unique_name'
500
501         if uuid_was.nil?
502           # new record, the uuid caused a name collision (very
503           # unlikely but possible), so generate new uuid
504           self[:uuid] = nil
505           if self.is_a? Collection
506             # Also needs to be reset
507             self[:current_version_uuid] = nil
508           end
509           # need to adjust the name after the uuid has been generated
510           add_uuid_to_make_unique_name
511         else
512           # existing record, just update the name directly.
513           add_uuid_to_name
514         end
515         retry
516       end
517     end
518   end
519
520   def user_owner_uuid
521     if self.owner_uuid.nil?
522       return current_user.uuid
523     end
524     owner_class = ArvadosModel.resource_class_for_uuid(self.owner_uuid)
525     if owner_class == User
526       self.owner_uuid
527     else
528       owner_class.find_by_uuid(self.owner_uuid).user_owner_uuid
529     end
530   end
531
532   def logged_attributes
533     attributes.except(*Rails.configuration.AuditLogs.UnloggedAttributes.stringify_keys.keys)
534   end
535
536   def self.full_text_searchable_columns
537     self.columns.select do |col|
538       [:string, :text, :jsonb].include?(col.type) and
539       col.name !~ /(^|_)(hash|uuid)$/
540     end.map(&:name)
541   end
542
543   def self.full_text_coalesce
544     full_text_searchable_columns.collect do |column|
545       is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
546       cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
547       "coalesce(#{column}#{cast},'')"
548     end
549   end
550
551   def self.full_text_trgm
552     "(#{full_text_coalesce.join(" || ' ' || ")})"
553   end
554
555   def self.full_text_tsvector
556     parts = full_text_searchable_columns.collect do |column|
557       is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
558       cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
559       "coalesce(#{column}#{cast},'')"
560     end
561     "to_tsvector('english', substr(#{parts.join(" || ' ' || ")}, 0, 8000))"
562   end
563
564   @_add_uuid_to_name = false
565   def add_uuid_to_make_unique_name
566     @_add_uuid_to_name = true
567   end
568
569   def add_uuid_to_name
570     # Incorporate the random part of the UUID into the name.  This
571     # lets us prevent name collision but the part we add to the name
572     # is still somewhat meaningful (instead of generating a second
573     # random meaningless string).
574     #
575     # Because ArvadosModel is an abstract class and assign_uuid is
576     # part of HasUuid (which is included by the other concrete
577     # classes) the assign_uuid hook gets added (and run) after this
578     # one.  So we need to call assign_uuid here to make sure we have a
579     # uuid.
580     assign_uuid
581     self.name = "#{self.name[0..236]} (#{self.uuid[-15..-1]})"
582   end
583
584   protected
585
586   def self.deep_sort_hash(x)
587     if x.is_a? Hash
588       x.sort.collect do |k, v|
589         [k, deep_sort_hash(v)]
590       end.to_h
591     elsif x.is_a? Array
592       x.collect { |v| deep_sort_hash(v) }
593     else
594       x
595     end
596   end
597
598   def ensure_ownership_path_leads_to_user
599     if new_record? or owner_uuid_changed?
600       uuid_in_path = {owner_uuid => true, uuid => true}
601       x = owner_uuid
602       while (owner_class = ArvadosModel::resource_class_for_uuid(x)) != User
603         begin
604           if x == uuid
605             # Test for cycles with the new version, not the DB contents
606             x = owner_uuid
607           elsif !owner_class.respond_to? :find_by_uuid
608             raise ActiveRecord::RecordNotFound.new
609           else
610             x = owner_class.find_by_uuid(x).owner_uuid
611           end
612         rescue ActiveRecord::RecordNotFound => e
613           errors.add :owner_uuid, "is not owned by any user: #{e}"
614           throw(:abort)
615         end
616         if uuid_in_path[x]
617           if x == owner_uuid
618             errors.add :owner_uuid, "would create an ownership cycle"
619           else
620             errors.add :owner_uuid, "has an ownership cycle"
621           end
622           throw(:abort)
623         end
624         uuid_in_path[x] = true
625       end
626     end
627     true
628   end
629
630   def set_default_owner
631     if new_record? and current_user and respond_to? :owner_uuid=
632       self.owner_uuid ||= current_user.uuid
633     end
634   end
635
636   def ensure_owner_uuid_is_permitted
637     raise PermissionDeniedError if !current_user
638
639     if self.owner_uuid.nil?
640       errors.add :owner_uuid, "cannot be nil"
641       raise PermissionDeniedError
642     end
643
644     rsc_class = ArvadosModel::resource_class_for_uuid owner_uuid
645     unless rsc_class == User or rsc_class == Group
646       errors.add :owner_uuid, "must be set to User or Group"
647       raise PermissionDeniedError
648     end
649
650     if new_record? || owner_uuid_changed?
651       # Permission on owner_uuid_was is needed to move an existing
652       # object away from its previous owner (which implies permission
653       # to modify this object itself, so we don't need to check that
654       # separately). Permission on the new owner_uuid is also needed.
655       [['old', owner_uuid_was],
656        ['new', owner_uuid]
657       ].each do |which, check_uuid|
658         if check_uuid.nil?
659           # old_owner_uuid is nil? New record, no need to check.
660         elsif !current_user.can?(write: check_uuid)
661           if FrozenGroup.where(uuid: check_uuid).any?
662             errors.add :owner_uuid, "cannot be set or changed because #{which} owner is frozen"
663           else
664             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}"
665             errors.add :owner_uuid, "cannot be set or changed without write permission on #{which} owner"
666           end
667           raise PermissionDeniedError
668         elsif rsc_class == Group && Group.find_by_uuid(owner_uuid).group_class != "project"
669           errors.add :owner_uuid, "must be a project"
670           raise PermissionDeniedError
671         end
672       end
673     else
674       # If the object already existed and we're not changing
675       # owner_uuid, we only need write permission on the object
676       # itself. (If we're in the act of unfreezing, we only need
677       # :unfreeze permission, which means "what write permission would
678       # be if target weren't frozen")
679       unless ((respond_to?(:frozen_by_uuid) && frozen_by_uuid_was && !frozen_by_uuid) ?
680                 current_user.can?(unfreeze: uuid) :
681                 current_user.can?(write: uuid))
682         logger.warn "User #{current_user.uuid} tried to modify #{self.class.to_s} #{self.uuid} without write permission"
683         errors.add :uuid, " #{uuid} is not writable by #{current_user.uuid}"
684         raise PermissionDeniedError
685       end
686     end
687
688     true
689   end
690
691   def ensure_permission_to_save
692     unless (new_record? ? permission_to_create : permission_to_update)
693       raise PermissionDeniedError
694     end
695   end
696
697   def permission_to_create
698     return current_user.andand.is_active
699   end
700
701   def permission_to_update
702     if !current_user
703       logger.warn "Anonymous user tried to update #{self.class.to_s} #{self.uuid_was}"
704       return false
705     end
706     if !current_user.is_active
707       logger.warn "Inactive user #{current_user.uuid} tried to update #{self.class.to_s} #{self.uuid_was}"
708       return false
709     end
710     return true if current_user.is_admin
711     if self.uuid_changed?
712       logger.warn "User #{current_user.uuid} tried to change uuid of #{self.class.to_s} #{self.uuid_was} to #{self.uuid}"
713       return false
714     end
715     return true
716   end
717
718   def ensure_permission_to_destroy
719     raise PermissionDeniedError unless permission_to_destroy
720   end
721
722   def permission_to_destroy
723     if [system_user_uuid, system_group_uuid, anonymous_group_uuid,
724         anonymous_user_uuid, public_project_uuid].include? uuid
725       false
726     else
727       permission_to_update
728     end
729   end
730
731   def maybe_update_modified_by_fields
732     update_modified_by_fields if self.changed? or self.new_record?
733     true
734   end
735
736   def update_modified_by_fields
737     current_time = db_current_time
738     self.created_at ||= created_at_was || current_time
739     self.updated_at = current_time
740     self.owner_uuid ||= current_user.uuid if current_user && self.respond_to?(:owner_uuid=)
741     if !anonymous_updater
742       self.modified_by_user_uuid = current_user ? current_user.uuid : nil
743     end
744     if !timeless_updater
745       self.modified_at = current_time
746     end
747     self.modified_by_client_uuid = current_api_client ? current_api_client.uuid : nil
748     true
749   end
750
751   def self.has_nonstring_keys? x
752     if x.is_a? Hash
753       x.each do |k,v|
754         return true if !(k.is_a?(String) || k.is_a?(Symbol)) || has_nonstring_keys?(v)
755       end
756     elsif x.is_a? Array
757       x.each do |v|
758         return true if has_nonstring_keys?(v)
759       end
760     end
761     false
762   end
763
764   def self.where_serialized(colname, value, md5: false, multivalue: false)
765     colsql = colname.to_s
766     if md5
767       colsql = "md5(#{colsql})"
768     end
769     if value.empty?
770       # rails4 stores as null, rails3 stored as serialized [] or {}
771       sql = "#{colsql} is null or #{colsql} IN (?)"
772       sorted = value
773     else
774       sql = "#{colsql} IN (?)"
775       sorted = deep_sort_hash(value)
776     end
777     params = []
778     if multivalue
779       sorted.each do |v|
780         params << v.to_yaml
781         params << SafeJSON.dump(v)
782       end
783     else
784       params << sorted.to_yaml
785       params << SafeJSON.dump(sorted)
786     end
787     if md5
788       params = params.map { |x| Digest::MD5.hexdigest(x) }
789     end
790     where(sql, params)
791   end
792
793   Serializer = {
794     Hash => HashSerializer,
795     Array => ArraySerializer,
796   }
797
798   def self.serialize(colname, type)
799     coder = Serializer[type]
800     @serialized_attributes ||= {}
801     @serialized_attributes[colname.to_s] = coder
802     super(colname, coder)
803   end
804
805   def self.serialized_attributes
806     @serialized_attributes ||= {}
807   end
808
809   def serialized_attributes
810     self.class.serialized_attributes
811   end
812
813   def foreign_key_attributes
814     attributes.keys.select { |a| a.match(/_uuid$/) }
815   end
816
817   def skip_uuid_read_permission_check
818     %w(modified_by_client_uuid)
819   end
820
821   def skip_uuid_existence_check
822     []
823   end
824
825   def normalize_collection_uuids
826     foreign_key_attributes.each do |attr|
827       attr_value = send attr
828       if attr_value.is_a? String and
829           attr_value.match(/^[0-9a-f]{32,}(\+[@\w]+)*$/)
830         begin
831           send "#{attr}=", Collection.normalize_uuid(attr_value)
832         rescue
833           # TODO: abort instead of silently accepting unnormalizable value?
834         end
835       end
836     end
837   end
838
839   @@prefixes_hash = nil
840   def self.uuid_prefixes
841     unless @@prefixes_hash
842       @@prefixes_hash = {}
843       Rails.application.eager_load!
844       ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |k|
845         if k.respond_to?(:uuid_prefix)
846           @@prefixes_hash[k.uuid_prefix] = k
847         end
848       end
849     end
850     @@prefixes_hash
851   end
852
853   def self.uuid_like_pattern
854     "#{Rails.configuration.ClusterID}-#{uuid_prefix}-_______________"
855   end
856
857   def self.uuid_regex
858     %r/[a-z0-9]{5}-#{uuid_prefix}-[a-z0-9]{15}/
859   end
860
861   def check_readable_uuid attr, attr_value
862     return if attr_value.nil?
863     if (r = ArvadosModel::resource_class_for_uuid attr_value)
864       unless skip_uuid_read_permission_check.include? attr
865         r = r.readable_by(current_user)
866       end
867       if r.where(uuid: attr_value).count == 0
868         errors.add(attr, "'#{attr_value}' not found")
869       end
870     else
871       # Not a valid uuid or PDH, but that (currently) is not an error.
872     end
873   end
874
875   def ensure_valid_uuids
876     specials = [system_user_uuid]
877
878     foreign_key_attributes.each do |attr|
879       if new_record? or send (attr + "_changed?")
880         next if skip_uuid_existence_check.include? attr
881         attr_value = send attr
882         next if specials.include? attr_value
883         check_readable_uuid attr, attr_value
884       end
885     end
886   end
887
888   def ensure_filesystem_compatible_name
889     if name == "." || name == ".."
890       errors.add(:name, "cannot be '.' or '..'")
891     elsif Rails.configuration.Collections.ForwardSlashNameSubstitution == "" && !name.nil? && name.index('/')
892       errors.add(:name, "cannot contain a '/' character")
893     end
894   end
895
896   class Email
897     def self.kind
898       "email"
899     end
900
901     def kind
902       self.class.kind
903     end
904
905     def self.readable_by (*u)
906       self
907     end
908
909     def self.where (u)
910       [{:uuid => u[:uuid]}]
911     end
912   end
913
914   def self.resource_class_for_uuid(uuid)
915     if uuid.is_a? ArvadosModel
916       return uuid.class
917     end
918     unless uuid.is_a? String
919       return nil
920     end
921
922     uuid.match HasUuid::UUID_REGEX do |re|
923       return uuid_prefixes[re[1]] if uuid_prefixes[re[1]]
924     end
925
926     if uuid.match(/.+@.+/)
927       return Email
928     end
929
930     nil
931   end
932
933   # Fill in implied zero/false values in database records that were
934   # created before #17014 made them explicit, and reset the Rails
935   # "changed" state so the record doesn't appear to have been modified
936   # after loading.
937   #
938   # Invoked by Container and ContainerRequest models as an after_find
939   # hook.
940   def fill_container_defaults_after_find
941     fill_container_defaults
942     clear_changes_information
943   end
944
945   # Fill in implied zero/false values. Invoked by ContainerRequest as
946   # a before_validation hook in order to (a) ensure every key has a
947   # value in the updated database record and (b) ensure the attribute
948   # whitelist doesn't reject a change from an explicit zero/false
949   # value in the database to an implicit zero/false value in an update
950   # request.
951   def fill_container_defaults
952     # Make sure this is correctly sorted by key, because we merge in
953     # whatever is in the database on top of it, this will be the order
954     # that gets used downstream rather than the order the keys appear
955     # in the database.
956     self.runtime_constraints = {
957       'API' => false,
958       'cuda' => {
959         'device_count' => 0,
960         'driver_version' => '',
961         'hardware_capability' => '',
962       },
963       'keep_cache_disk' => 0,
964       'keep_cache_ram' => 0,
965       'ram' => 0,
966       'vcpus' => 0,
967     }.merge(attributes['runtime_constraints'] || {})
968     self.scheduling_parameters = {
969       'max_run_time' => 0,
970       'partitions' => [],
971       'preemptible' => false,
972       'supervisor' => false,
973     }.merge(attributes['scheduling_parameters'] || {})
974   end
975
976   # ArvadosModel.find_by_uuid needs extra magic to allow it to return
977   # an object in any class.
978   def self.find_by_uuid uuid
979     if self == ArvadosModel
980       # If called directly as ArvadosModel.find_by_uuid rather than via subclass,
981       # delegate to the appropriate subclass based on the given uuid.
982       self.resource_class_for_uuid(uuid).find_by_uuid(uuid)
983     else
984       super
985     end
986   end
987
988   def is_audit_logging_enabled?
989     return !(Rails.configuration.AuditLogs.MaxAge.to_i == 0 &&
990              Rails.configuration.AuditLogs.MaxDeleteBatch.to_i > 0)
991   end
992
993   def schedule_restoring_changes
994     # This will be checked at log_start_state, to reset any (virtual) changes
995     # produced by the act of reading a serialized attribute.
996     @fresh_from_database = true
997   end
998
999   def log_start_state
1000     if is_audit_logging_enabled?
1001       @old_attributes = Marshal.load(Marshal.dump(attributes))
1002       @old_logged_attributes = Marshal.load(Marshal.dump(logged_attributes))
1003       if @fresh_from_database
1004         # This instance was created from reading a database record. Attributes
1005         # haven't been changed, but those serialized attributes will be reported
1006         # as unpersisted, so we restore them to avoid issues with lock!() and
1007         # with_lock().
1008         restore_attributes
1009         @fresh_from_database = nil
1010       end
1011     end
1012   end
1013
1014   def log_change(event_type)
1015     if is_audit_logging_enabled?
1016       log = Log.new(event_type: event_type).fill_object(self)
1017       yield log
1018       log.save!
1019       log_start_state
1020     end
1021   end
1022
1023   def log_create
1024     if is_audit_logging_enabled?
1025       log_change('create') do |log|
1026         log.fill_properties('old', nil, nil)
1027         log.update_to self
1028       end
1029     end
1030   end
1031
1032   def log_update
1033     if is_audit_logging_enabled?
1034       log_change('update') do |log|
1035         log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
1036         log.update_to self
1037       end
1038     end
1039   end
1040
1041   def log_destroy
1042     if is_audit_logging_enabled?
1043       log_change('delete') do |log|
1044         log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
1045         log.update_to nil
1046       end
1047     end
1048   end
1049 end