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