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