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