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