19146: Remove unneeded special case checks, explain the needed one.
[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 desc"]
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   def can_write
277     if respond_to?(:frozen_by_uuid) && frozen_by_uuid
278       # This special case is needed to return the correct value from a
279       # "freeze project" API, during which writable status changes
280       # from true to false.
281       #
282       # current_user.can?(write: self) returns true (which is correct
283       # in the context of permission-checking hooks) but the can_write
284       # value we're returning to the caller here represents the state
285       # _after_ the update, i.e., false.
286       return false
287     else
288       return current_user.can?(write: self)
289     end
290   end
291
292   def can_manage
293     return current_user.can?(manage: self)
294   end
295
296   # Return a query with read permissions restricted to the union of the
297   # permissions of the members of users_list, i.e. if something is readable by
298   # any user in users_list, it will be readable in the query returned by this
299   # function.
300   def self.readable_by(*users_list)
301     # Get rid of troublesome nils
302     users_list.compact!
303
304     # Load optional keyword arguments, if they exist.
305     if users_list.last.is_a? Hash
306       kwargs = users_list.pop
307     else
308       kwargs = {}
309     end
310
311     # Collect the UUIDs of the authorized users.
312     sql_table = kwargs.fetch(:table_name, table_name)
313     include_trash = kwargs.fetch(:include_trash, false)
314     include_old_versions = kwargs.fetch(:include_old_versions, false)
315
316     sql_conds = nil
317     user_uuids = users_list.map { |u| u.uuid }
318     all_user_uuids = []
319
320     admin = users_list.select { |u| u.is_admin }.any?
321
322     # For details on how the trashed_groups table is constructed, see
323     # see db/migrate/20200501150153_permission_table.rb
324
325     # excluded_trash is a SQL expression that determines whether a row
326     # should be excluded from the results due to being trashed.
327     # Trashed items inside frozen projects are invisible to regular
328     # (non-admin) users even when using include_trash, so we have:
329     #
330     # (item_trashed || item_inside_trashed_project)
331     # &&
332     # (!caller_requests_include_trash ||
333     #  (item_inside_frozen_project && caller_is_not_admin))
334     if (admin && include_trash) || sql_table == "api_client_authorizations"
335       excluded_trash = "false"
336     else
337       excluded_trash = "(#{sql_table}.owner_uuid IN (SELECT group_uuid FROM #{TRASHED_GROUPS} " +
338                        "WHERE trash_at <= statement_timestamp()))"
339       if sql_table == "groups" || sql_table == "collections"
340         excluded_trash = "(#{excluded_trash} OR #{sql_table}.trash_at <= statement_timestamp() IS TRUE)"
341       end
342
343       if include_trash
344         # Exclude trash inside frozen projects
345         excluded_trash = "(#{excluded_trash} AND #{sql_table}.owner_uuid IN (SELECT uuid FROM #{FROZEN_GROUPS}))"
346       end
347     end
348
349     if admin
350       # Admin skips most permission checks, but still want to filter
351       # on trashed items.
352       if !include_trash && sql_table != "api_client_authorizations"
353         # Only include records where the owner is not trashed
354         sql_conds = "NOT (#{excluded_trash})"
355       end
356     else
357       # The core of the permission check is a join against the
358       # materialized_permissions table to determine if the user has at
359       # least read permission to either the object itself or its
360       # direct owner (if traverse_owned is true).  See
361       # db/migrate/20200501150153_permission_table.rb for details on
362       # how the permissions are computed.
363
364       # A user can have can_manage access to another user, this grants
365       # full access to all that user's stuff.  To implement that we
366       # need to include those other users in the permission query.
367
368       # This was previously implemented by embedding the subquery
369       # directly into the query, but it was discovered later that this
370       # causes the Postgres query planner to do silly things because
371       # the query heuristics assumed the subquery would have a lot
372       # more rows that it does, and choose a bad merge strategy.  By
373       # doing the query here and embedding the result as a constant,
374       # Postgres also knows exactly how many items there are and can
375       # choose the right query strategy.
376       #
377       # (note: you could also do this with a temporary table, but that
378       # would require all every request be wrapped in a transaction,
379       # which is not currently the case).
380
381       all_user_uuids = ActiveRecord::Base.connection.exec_query %{
382 #{USER_UUIDS_SUBQUERY_TEMPLATE % {user: "'#{user_uuids.join "', '"}'", perm_level: 1}}
383 },
384                                              'readable_by.user_uuids'
385
386       user_uuids_subquery = ":user_uuids"
387
388       # Note: it is possible to combine the direct_check and
389       # owner_check into a single IN (SELECT) clause, however it turns
390       # out query optimizer doesn't like it and forces a sequential
391       # table scan.  Constructing the query with separate IN (SELECT)
392       # clauses enables it to use the index.
393       #
394       # see issue 13208 for details.
395
396       # Match a direct read permission link from the user to the record uuid
397       direct_check = "#{sql_table}.uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
398                      "WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 1)"
399
400       # Match a read permission for the user to the record's
401       # owner_uuid.  This is so we can have a permissions table that
402       # mostly consists of users and groups (projects are a type of
403       # group) and not have to compute and list user permission to
404       # every single object in the system.
405       #
406       # Don't do this for API keys (special behavior) or groups
407       # (already covered by direct_check).
408       #
409       # The traverse_owned flag indicates whether the permission to
410       # read an object also implies transitive permission to read
411       # things the object owns.  The situation where this is important
412       # are determining if we can read an object owned by another
413       # user.  This makes it possible to have permission to read the
414       # user record without granting permission to read things the
415       # other user owns.
416       owner_check = ""
417       if sql_table != "api_client_authorizations" and sql_table != "groups" then
418         owner_check = "#{sql_table}.owner_uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
419                       "WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 1 AND traverse_owned) "
420
421         # We want to do owner_check before direct_check in the OR
422         # clause.  The order of the OR clause isn't supposed to
423         # matter, but in practice, it does -- apparently in the
424         # absence of other hints, it uses the ordering from the query.
425         # For certain types of queries (like filtering on owner_uuid),
426         # every item will match the owner_check clause, so then
427         # Postgres will optimize out the direct_check entirely.
428         direct_check = " OR " + direct_check
429       end
430
431       if Rails.configuration.Users.RoleGroupsVisibleToAll &&
432          sql_table == "groups" &&
433          users_list.select { |u| u.is_active }.any?
434         # All role groups are readable (but we still need the other
435         # direct_check clauses to handle non-role groups).
436         direct_check += " OR #{sql_table}.group_class = 'role'"
437       end
438
439       links_cond = ""
440       if sql_table == "links"
441         # 1) Match permission links incoming or outgoing on the
442         # user, i.e. granting permission on the user, or granting
443         # permission to the user.
444         #
445         # 2) Match permission links which grant permission on an
446         # object that this user can_manage.
447         #
448         links_cond = "OR (#{sql_table}.link_class IN (:permission_link_classes) AND "+
449                      "   ((#{sql_table}.head_uuid IN (#{user_uuids_subquery}) OR #{sql_table}.tail_uuid IN (#{user_uuids_subquery})) OR " +
450                      "    #{sql_table}.head_uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
451                      "    WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 3))) "
452       end
453
454       sql_conds = "(#{owner_check} #{direct_check} #{links_cond}) AND NOT (#{excluded_trash})"
455
456     end
457
458     if !include_old_versions && sql_table == "collections"
459       exclude_old_versions = "#{sql_table}.uuid = #{sql_table}.current_version_uuid"
460       if sql_conds.nil?
461         sql_conds = exclude_old_versions
462       else
463         sql_conds += " AND #{exclude_old_versions}"
464       end
465     end
466
467     self.where(sql_conds,
468                user_uuids: all_user_uuids.collect{|c| c["target_uuid"]},
469                permission_link_classes: ['permission'])
470   end
471
472   def save_with_unique_name!
473     uuid_was = uuid
474     name_was = 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       rescue ActiveRecord::RecordNotUnique => rn
482         raise if max_retries == 0
483         max_retries -= 1
484
485         conn.exec_query 'ROLLBACK TO SAVEPOINT save_with_unique_name'
486
487         # Dig into the error to determine if it is specifically calling out a
488         # (owner_uuid, name) uniqueness violation.  In this specific case, and
489         # the client requested a unique name with ensure_unique_name==true,
490         # update the name field and try to save again.  Loop as necessary to
491         # discover a unique name.  It is necessary to handle name choosing at
492         # this level (as opposed to the client) to ensure that record creation
493         # never fails due to a race condition.
494         err = rn.cause
495         raise unless err.is_a?(PG::UniqueViolation)
496
497         # Unfortunately ActiveRecord doesn't abstract out any of the
498         # necessary information to figure out if this the error is actually
499         # the specific case where we want to apply the ensure_unique_name
500         # behavior, so the following code is specialized to Postgres.
501         detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
502         raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
503
504         new_name = "#{name_was} (#{db_current_time.utc.iso8601(3)})"
505         if new_name == name
506           # If the database is fast enough to do two attempts in the
507           # same millisecond, we need to wait to ensure we try a
508           # different timestamp on each attempt.
509           sleep 0.002
510           new_name = "#{name_was} (#{db_current_time.utc.iso8601(3)})"
511         end
512
513         self[:name] = new_name
514         if uuid_was.nil? && !uuid.nil?
515           self[:uuid] = nil
516           if self.is_a? Collection
517             # Reset so that is assigned to the new UUID
518             self[:current_version_uuid] = nil
519           end
520         end
521         conn.exec_query 'SAVEPOINT save_with_unique_name'
522         retry
523       ensure
524         conn.exec_query 'RELEASE SAVEPOINT save_with_unique_name'
525       end
526     end
527   end
528
529   def user_owner_uuid
530     if self.owner_uuid.nil?
531       return current_user.uuid
532     end
533     owner_class = ArvadosModel.resource_class_for_uuid(self.owner_uuid)
534     if owner_class == User
535       self.owner_uuid
536     else
537       owner_class.find_by_uuid(self.owner_uuid).user_owner_uuid
538     end
539   end
540
541   def logged_attributes
542     attributes.except(*Rails.configuration.AuditLogs.UnloggedAttributes.stringify_keys.keys)
543   end
544
545   def self.full_text_searchable_columns
546     self.columns.select do |col|
547       [:string, :text, :jsonb].include?(col.type)
548     end.map(&:name)
549   end
550
551   def self.full_text_coalesce
552     full_text_searchable_columns.collect do |column|
553       is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
554       cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
555       "coalesce(#{column}#{cast},'')"
556     end
557   end
558
559   def self.full_text_trgm
560     "(#{full_text_coalesce.join(" || ' ' || ")})"
561   end
562
563   def self.full_text_tsvector
564     parts = full_text_searchable_columns.collect do |column|
565       is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
566       cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
567       "coalesce(#{column}#{cast},'')"
568     end
569     "to_tsvector('english', substr(#{parts.join(" || ' ' || ")}, 0, 8000))"
570   end
571
572   def self.apply_filters query, filters
573     ft = record_filters filters, self
574     if not ft[:cond_out].any?
575       return query
576     end
577     ft[:joins].each do |t|
578       query = query.joins(t)
579     end
580     query.where('(' + ft[:cond_out].join(') AND (') + ')',
581                           *ft[:param_out])
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_default_owner if 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     set_attribute_was('runtime_constraints', runtime_constraints)
943     set_attribute_was('scheduling_parameters', scheduling_parameters)
944     clear_changes_information
945   end
946
947   # Fill in implied zero/false values. Invoked by ContainerRequest as
948   # a before_validation hook in order to (a) ensure every key has a
949   # value in the updated database record and (b) ensure the attribute
950   # whitelist doesn't reject a change from an explicit zero/false
951   # value in the database to an implicit zero/false value in an update
952   # request.
953   def fill_container_defaults
954     self.runtime_constraints = {
955       'API' => false,
956       'cuda' => {
957         'device_count' => 0,
958         'driver_version' => '',
959         'hardware_capability' => '',
960       },
961       'keep_cache_ram' => 0,
962       'ram' => 0,
963       'vcpus' => 0,
964     }.merge(attributes['runtime_constraints'] || {})
965     self.scheduling_parameters = {
966       'max_run_time' => 0,
967       'partitions' => [],
968       'preemptible' => false,
969     }.merge(attributes['scheduling_parameters'] || {})
970   end
971
972   # ArvadosModel.find_by_uuid needs extra magic to allow it to return
973   # an object in any class.
974   def self.find_by_uuid uuid
975     if self == ArvadosModel
976       # If called directly as ArvadosModel.find_by_uuid rather than via subclass,
977       # delegate to the appropriate subclass based on the given uuid.
978       self.resource_class_for_uuid(uuid).find_by_uuid(uuid)
979     else
980       super
981     end
982   end
983
984   def is_audit_logging_enabled?
985     return !(Rails.configuration.AuditLogs.MaxAge.to_i == 0 &&
986              Rails.configuration.AuditLogs.MaxDeleteBatch.to_i > 0)
987   end
988
989   def schedule_restoring_changes
990     # This will be checked at log_start_state, to reset any (virtual) changes
991     # produced by the act of reading a serialized attribute.
992     @fresh_from_database = true
993   end
994
995   def log_start_state
996     if is_audit_logging_enabled?
997       @old_attributes = Marshal.load(Marshal.dump(attributes))
998       @old_logged_attributes = Marshal.load(Marshal.dump(logged_attributes))
999       if @fresh_from_database
1000         # This instance was created from reading a database record. Attributes
1001         # haven't been changed, but those serialized attributes will be reported
1002         # as unpersisted, so we restore them to avoid issues with lock!() and
1003         # with_lock().
1004         restore_attributes
1005         @fresh_from_database = nil
1006       end
1007     end
1008   end
1009
1010   def log_change(event_type)
1011     if is_audit_logging_enabled?
1012       log = Log.new(event_type: event_type).fill_object(self)
1013       yield log
1014       log.save!
1015       log_start_state
1016     end
1017   end
1018
1019   def log_create
1020     if is_audit_logging_enabled?
1021       log_change('create') do |log|
1022         log.fill_properties('old', nil, nil)
1023         log.update_to self
1024       end
1025     end
1026   end
1027
1028   def log_update
1029     if is_audit_logging_enabled?
1030       log_change('update') do |log|
1031         log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
1032         log.update_to self
1033       end
1034     end
1035   end
1036
1037   def log_destroy
1038     if is_audit_logging_enabled?
1039       log_change('delete') do |log|
1040         log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
1041         log.update_to nil
1042       end
1043     end
1044   end
1045 end