17755: Merge branch 'main' into 17755-add-singularity-to-compute-image
[arvados.git] / services / api / app / models / collection.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'arvados/keep'
6 require 'sweep_trashed_objects'
7 require 'trashable'
8
9 class Collection < ArvadosModel
10   extend CurrentApiClient
11   extend DbCurrentTime
12   include HasUuid
13   include KindAndEtag
14   include CommonApiTemplate
15   include Trashable
16
17   # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
18   # already know how to properly treat them.
19   attribute :properties, :jsonbHash, default: {}
20   attribute :storage_classes_desired, :jsonbArray, default: lambda { Rails.configuration.DefaultStorageClasses }
21   attribute :storage_classes_confirmed, :jsonbArray, default: []
22
23   before_validation :default_empty_manifest
24   before_validation :default_storage_classes, on: :create
25   before_validation :managed_properties, on: :create
26   before_validation :check_encoding
27   before_validation :check_manifest_validity
28   before_validation :check_signatures
29   before_validation :strip_signatures_and_update_replication_confirmed
30   before_validation :name_null_if_empty
31   validate :ensure_filesystem_compatible_name
32   validate :ensure_pdh_matches_manifest_text
33   validate :ensure_storage_classes_desired_is_not_empty
34   validate :ensure_storage_classes_contain_non_empty_strings
35   validate :versioning_metadata_updates, on: :update
36   validate :past_versions_cannot_be_updated, on: :update
37   validate :protected_managed_properties_updates, on: :update
38   after_validation :set_file_count_and_total_size
39   before_save :set_file_names
40   around_update :manage_versioning, unless: :is_past_version?
41
42   api_accessible :user, extend: :common do |t|
43     t.add lambda { |x| x.name || "" }, as: :name
44     t.add :description
45     t.add :properties
46     t.add :portable_data_hash
47     t.add :signed_manifest_text, as: :manifest_text
48     t.add :manifest_text, as: :unsigned_manifest_text
49     t.add :replication_desired
50     t.add :replication_confirmed
51     t.add :replication_confirmed_at
52     t.add :storage_classes_desired
53     t.add :storage_classes_confirmed
54     t.add :storage_classes_confirmed_at
55     t.add :delete_at
56     t.add :trash_at
57     t.add :is_trashed
58     t.add :version
59     t.add :current_version_uuid
60     t.add :preserve_version
61     t.add :file_count
62     t.add :file_size_total
63   end
64
65   UNLOGGED_CHANGES = ['preserve_version', 'updated_at']
66
67   after_initialize do
68     @signatures_checked = false
69     @computed_pdh_for_manifest_text = false
70   end
71
72   def self.attributes_required_columns
73     super.merge(
74                 # If we don't list manifest_text explicitly, the
75                 # params[:select] code gets confused by the way we
76                 # expose signed_manifest_text as manifest_text in the
77                 # API response, and never let clients select the
78                 # manifest_text column.
79                 #
80                 # We need trash_at and is_trashed to determine the
81                 # correct timestamp in signed_manifest_text.
82                 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
83                 'unsigned_manifest_text' => ['manifest_text'],
84                 'name' => ['name'],
85                 )
86   end
87
88   def self.ignored_select_attributes
89     super + ["updated_at", "file_names"]
90   end
91
92   def self.limit_index_columns_read
93     ["manifest_text"]
94   end
95
96   FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
97   def check_signatures
98     throw(:abort) if self.manifest_text.nil?
99
100     return true if current_user.andand.is_admin
101
102     # Provided the manifest_text hasn't changed materially since an
103     # earlier validation, it's safe to pass this validation on
104     # subsequent passes without checking any signatures. This is
105     # important because the signatures have probably been stripped off
106     # by the time we get to a second validation pass!
107     if @signatures_checked && @signatures_checked == computed_pdh
108       return true
109     end
110
111     if self.manifest_text_changed?
112       # Check permissions on the collection manifest.
113       # If any signature cannot be verified, raise PermissionDeniedError
114       # which will return 403 Permission denied to the client.
115       api_token = Thread.current[:token]
116       signing_opts = {
117         api_token: api_token,
118         now: @validation_timestamp.to_i,
119       }
120       self.manifest_text.each_line do |entry|
121         entry.split.each do |tok|
122           if tok == '.' or tok.starts_with? './'
123             # Stream name token.
124           elsif tok =~ FILE_TOKEN
125             # This is a filename token, not a blob locator. Note that we
126             # keep checking tokens after this, even though manifest
127             # format dictates that all subsequent tokens will also be
128             # filenames. Safety first!
129           elsif Blob.verify_signature tok, signing_opts
130             # OK.
131           elsif Keep::Locator.parse(tok).andand.signature
132             # Signature provided, but verify_signature did not like it.
133             logger.warn "Invalid signature on locator #{tok}"
134             raise ArvadosModel::PermissionDeniedError
135           elsif !Rails.configuration.Collections.BlobSigning
136             # No signature provided, but we are running in insecure mode.
137             logger.debug "Missing signature on locator #{tok} ignored"
138           elsif Blob.new(tok).empty?
139             # No signature provided -- but no data to protect, either.
140           else
141             logger.warn "Missing signature on locator #{tok}"
142             raise ArvadosModel::PermissionDeniedError
143           end
144         end
145       end
146     end
147     @signatures_checked = computed_pdh
148   end
149
150   def strip_signatures_and_update_replication_confirmed
151     if self.manifest_text_changed?
152       in_old_manifest = {}
153       # manifest_text_was could be nil when dealing with a freshly created snapshot,
154       # so we skip this case because there was no real manifest change. (Bug #18005)
155       if (not self.replication_confirmed.nil?) and (not self.manifest_text_was.nil?)
156         self.class.each_manifest_locator(manifest_text_was) do |match|
157           in_old_manifest[match[1]] = true
158         end
159       end
160
161       stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
162         if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
163           # If the new manifest_text contains locators whose hashes
164           # weren't in the old manifest_text, storage replication is no
165           # longer confirmed.
166           self.replication_confirmed_at = nil
167           self.replication_confirmed = nil
168         end
169
170         # Return the locator with all permission signatures removed,
171         # but otherwise intact.
172         match[0].gsub(/\+A[^+]*/, '')
173       end
174
175       if @computed_pdh_for_manifest_text == manifest_text
176         # If the cached PDH was valid before stripping, it is still
177         # valid after stripping.
178         @computed_pdh_for_manifest_text = stripped_manifest.dup
179       end
180
181       self[:manifest_text] = stripped_manifest
182     end
183     true
184   end
185
186   def ensure_pdh_matches_manifest_text
187     if not manifest_text_changed? and not portable_data_hash_changed?
188       true
189     elsif portable_data_hash.nil? or not portable_data_hash_changed?
190       self.portable_data_hash = computed_pdh
191     elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
192       errors.add(:portable_data_hash, "is not a valid locator")
193       false
194     elsif portable_data_hash[0..31] != computed_pdh[0..31]
195       errors.add(:portable_data_hash,
196                  "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
197       false
198     else
199       # Ignore the client-provided size part: always store
200       # computed_pdh in the database.
201       self.portable_data_hash = computed_pdh
202     end
203   end
204
205   def name_null_if_empty
206     if name == ""
207       self.name = nil
208     end
209   end
210
211   def set_file_names
212     if self.manifest_text_changed?
213       self.file_names = manifest_files
214     end
215     true
216   end
217
218   def set_file_count_and_total_size
219     # Only update the file stats if the manifest changed
220     if self.manifest_text_changed?
221       m = Keep::Manifest.new(self.manifest_text)
222       self.file_size_total = m.files_size
223       self.file_count = m.files_count
224     # If the manifest didn't change but the attributes did, ignore the changes
225     elsif self.file_count_changed? || self.file_size_total_changed?
226       self.file_count = self.file_count_was
227       self.file_size_total = self.file_size_total_was
228     end
229     true
230   end
231
232   def manifest_files
233     return '' if !self.manifest_text
234
235     done = {}
236     names = ''
237     self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
238       next if done[name]
239       done[name] = true
240       names << name.first.gsub('\040',' ') + "\n"
241     end
242     self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
243       next if done[stream_name]
244       done[stream_name] = true
245       names << stream_name.first.gsub('\040',' ') + "\n"
246     end
247     names
248   end
249
250   def default_empty_manifest
251     self.manifest_text ||= ''
252   end
253
254   def skip_uuid_existence_check
255     # Avoid checking the existence of current_version_uuid, as it's
256     # assigned on creation of a new 'current version' collection, so
257     # the collection's UUID only lives on memory when the validation check
258     # is performed.
259     ['current_version_uuid']
260   end
261
262   def manage_versioning
263     should_preserve_version = should_preserve_version? # Time sensitive, cache value
264     return(yield) unless (should_preserve_version || syncable_updates.any?)
265
266     # Put aside the changes because with_lock does a record reload
267     changes = self.changes
268     snapshot = nil
269     restore_attributes
270     with_lock do
271       # Copy the original state to save it as old version
272       if should_preserve_version
273         snapshot = self.dup
274         snapshot.uuid = nil # Reset UUID so it's created as a new record
275         snapshot.created_at = self.created_at
276         snapshot.modified_at = self.modified_at_was
277       end
278
279       # Restore requested changes on the current version
280       changes.keys.each do |attr|
281         if attr == 'preserve_version' && changes[attr].last == false && !should_preserve_version
282           next # Ignore false assignment, once true it'll be true until next version
283         end
284         self.attributes = {attr => changes[attr].last}
285         if attr == 'uuid'
286           # Also update the current version reference
287           self.attributes = {'current_version_uuid' => changes[attr].last}
288         end
289       end
290
291       if should_preserve_version
292         self.version += 1
293       end
294
295       yield
296
297       sync_past_versions if syncable_updates.any?
298       if snapshot
299         snapshot.attributes = self.syncable_updates
300         leave_modified_by_user_alone do
301           leave_modified_at_alone do
302             act_as_system_user do
303               snapshot.save
304             end
305           end
306         end
307       end
308     end
309   end
310
311   def maybe_update_modified_by_fields
312     if !(self.changes.keys - ['updated_at', 'preserve_version']).empty?
313       super
314     end
315   end
316
317   def syncable_updates
318     updates = {}
319     if self.changes.any?
320       changes = self.changes
321     else
322       # If called after save...
323       changes = self.saved_changes
324     end
325     (syncable_attrs & changes.keys).each do |attr|
326       if attr == 'uuid'
327         # Point old versions to current version's new UUID
328         updates['current_version_uuid'] = changes[attr].last
329       else
330         updates[attr] = changes[attr].last
331       end
332     end
333     return updates
334   end
335
336   def sync_past_versions
337     updates = self.syncable_updates
338     Collection.where('current_version_uuid = ? AND uuid != ?', self.uuid_before_last_save, self.uuid_before_last_save).each do |c|
339       c.attributes = updates
340       # Use a different validation context to skip the 'past_versions_cannot_be_updated'
341       # validator, as on this case it is legal to update some fields.
342       leave_modified_by_user_alone do
343         leave_modified_at_alone do
344           c.save(context: :update_old_versions)
345         end
346       end
347     end
348   end
349
350   def versionable_updates?(attrs)
351     (['manifest_text', 'description', 'properties', 'name'] & attrs).any?
352   end
353
354   def syncable_attrs
355     ['uuid', 'owner_uuid', 'delete_at', 'trash_at', 'is_trashed', 'replication_desired', 'storage_classes_desired']
356   end
357
358   def is_past_version?
359     # Check for the '_was' values just in case the update operation
360     # includes a change on current_version_uuid or uuid.
361     !(new_record? || self.current_version_uuid_was == self.uuid_was)
362   end
363
364   def should_preserve_version?
365     return false unless (Rails.configuration.Collections.CollectionVersioning && versionable_updates?(self.changes.keys))
366
367     return false if self.is_trashed
368
369     idle_threshold = Rails.configuration.Collections.PreserveVersionIfIdle
370     if !self.preserve_version_was &&
371       !self.preserve_version &&
372       (idle_threshold < 0 ||
373         (idle_threshold > 0 && self.modified_at_was > db_current_time-idle_threshold.seconds))
374       return false
375     end
376     return true
377   end
378
379   def check_encoding
380     if !(manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?)
381       begin
382         # If Ruby thinks the encoding is something else, like 7-bit
383         # ASCII, but its stored bytes are equal to the (valid) UTF-8
384         # encoding of the same string, we declare it to be a UTF-8
385         # string.
386         utf8 = manifest_text
387         utf8.force_encoding Encoding::UTF_8
388         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
389           self.manifest_text = utf8
390           return true
391         end
392       rescue
393       end
394       errors.add :manifest_text, "must use UTF-8 encoding"
395       throw(:abort)
396     end
397   end
398
399   def check_manifest_validity
400     begin
401       Keep::Manifest.validate! manifest_text
402       true
403     rescue ArgumentError => e
404       errors.add :manifest_text, e.message
405       throw(:abort)
406     end
407   end
408
409   def signed_manifest_text
410     if !has_attribute? :manifest_text
411       return nil
412     elsif is_trashed
413       return manifest_text
414     else
415       token = Thread.current[:token]
416       exp = [db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i,
417              trash_at].compact.map(&:to_i).min
418       self.class.sign_manifest manifest_text, token, exp
419     end
420   end
421
422   def self.sign_manifest manifest, token, exp=nil
423     if exp.nil?
424       exp = db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i
425     end
426     signing_opts = {
427       api_token: token,
428       expire: exp,
429     }
430     m = munge_manifest_locators(manifest) do |match|
431       Blob.sign_locator(match[0], signing_opts)
432     end
433     return m
434   end
435
436   def self.munge_manifest_locators manifest
437     # Given a manifest text and a block, yield the regexp MatchData
438     # for each locator. Return a new manifest in which each locator
439     # has been replaced by the block's return value.
440     return nil if !manifest
441     return '' if manifest == ''
442
443     new_lines = []
444     manifest.each_line do |line|
445       line.rstrip!
446       new_words = []
447       line.split(' ').each do |word|
448         if new_words.empty?
449           new_words << word
450         elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
451           new_words << yield(match)
452         else
453           new_words << word
454         end
455       end
456       new_lines << new_words.join(' ')
457     end
458     new_lines.join("\n") + "\n"
459   end
460
461   def self.each_manifest_locator manifest
462     # Given a manifest text and a block, yield the regexp match object
463     # for each locator.
464     manifest.each_line do |line|
465       # line will have a trailing newline, but the last token is never
466       # a locator, so it's harmless here.
467       line.split(' ').each do |word|
468         if match = Keep::Locator::LOCATOR_REGEXP.match(word)
469           yield(match)
470         end
471       end
472     end
473   end
474
475   def self.normalize_uuid uuid
476     hash_part = nil
477     size_part = nil
478     uuid.split('+').each do |token|
479       if token.match(/^[0-9a-f]{32,}$/)
480         raise "uuid #{uuid} has multiple hash parts" if hash_part
481         hash_part = token
482       elsif token.match(/^\d+$/)
483         raise "uuid #{uuid} has multiple size parts" if size_part
484         size_part = token
485       end
486     end
487     raise "uuid #{uuid} has no hash part" if !hash_part
488     [hash_part, size_part].compact.join '+'
489   end
490
491   def self.get_compatible_images(readers, pattern, collections)
492     if collections.empty?
493       return []
494     end
495
496     migrations = Hash[
497       Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
498                  collections.map(&:portable_data_hash),
499                  'docker_image_migration',
500                  system_user_uuid).
501       order('links.created_at asc').
502       map { |l|
503         [l.tail_uuid, l.head_uuid]
504       }]
505
506     migrated_collections = Hash[
507       Collection.readable_by(*readers).
508       where('portable_data_hash in (?)', migrations.values).
509       map { |c|
510         [c.portable_data_hash, c]
511       }]
512
513     collections.map { |c|
514       # Check if the listed image is compatible first, if not, then try the
515       # migration link.
516       manifest = Keep::Manifest.new(c.manifest_text)
517       if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
518         c
519       elsif m = migrated_collections[migrations[c.portable_data_hash]]
520         manifest = Keep::Manifest.new(m.manifest_text)
521         if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
522           m
523         end
524       end
525     }.compact
526   end
527
528   # Resolve a Docker repo+tag, hash, or collection PDH to an array of
529   # Collection objects, sorted by timestamp starting with the most recent
530   # match.
531   #
532   # If filter_compatible_format is true (the default), only return image
533   # collections which are support by the installation as indicated by
534   # Rails.configuration.Containers.SupportedDockerImageFormats.  Will follow
535   # 'docker_image_migration' links if search_term resolves to an incompatible
536   # image, but an equivalent compatible image is available.
537   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
538     readers ||= [Thread.current[:user]]
539     base_search = Link.
540       readable_by(*readers).
541       readable_by(*readers, table_name: "collections").
542       joins("JOIN collections ON links.head_uuid = collections.uuid").
543       order("links.created_at DESC")
544
545     docker_image_formats = Rails.configuration.Containers.SupportedDockerImageFormats.keys.map(&:to_s)
546
547     if (docker_image_formats.include? 'v1' and
548         docker_image_formats.include? 'v2') or filter_compatible_format == false
549       pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
550     elsif docker_image_formats.include? 'v2'
551       pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
552     elsif docker_image_formats.include? 'v1'
553       pattern = /^[0-9A-Fa-f]{64}\.tar$/
554     else
555       raise "Unrecognized configuration for docker_image_formats #{docker_image_formats}"
556     end
557
558     # If the search term is a Collection locator that contains one file
559     # that looks like a Docker image, return it.
560     if loc = Keep::Locator.parse(search_term)
561       loc.strip_hints!
562       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
563       rc = Rails.configuration.RemoteClusters.select{ |k|
564         k != :"*" && k != Rails.configuration.ClusterID}
565       if coll_match.any? or rc.length == 0
566         return get_compatible_images(readers, pattern, coll_match)
567       else
568         # Allow bare pdh that doesn't exist in the local database so
569         # that federated container requests which refer to remotely
570         # stored containers will validate.
571         return [Collection.new(portable_data_hash: loc.to_s)]
572       end
573     end
574
575     if search_tag.nil? and (n = search_term.index(":"))
576       search_tag = search_term[n+1..-1]
577       search_term = search_term[0..n-1]
578     end
579
580     # Find Collections with matching Docker image repository+tag pairs.
581     matches = base_search.
582       where(link_class: "docker_image_repo+tag",
583             name: "#{search_term}:#{search_tag || 'latest'}")
584
585     # If that didn't work, find Collections with matching Docker image hashes.
586     if matches.empty?
587       matches = base_search.
588         where("link_class = ? and links.name LIKE ?",
589               "docker_image_hash", "#{search_term}%")
590     end
591
592     # Generate an order key for each result.  We want to order the results
593     # so that anything with an image timestamp is considered more recent than
594     # anything without; then we use the link's created_at as a tiebreaker.
595     uuid_timestamps = {}
596     matches.each do |link|
597       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
598        -link.created_at.to_i]
599      end
600
601     sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
602       uuid_timestamps[c.uuid]
603     }
604     compatible = get_compatible_images(readers, pattern, sorted)
605     if sorted.length > 0 and compatible.empty?
606       raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
607     end
608     compatible
609   end
610
611   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
612     find_all_for_docker_image(search_term, search_tag, readers).first
613   end
614
615   def self.searchable_columns operator
616     super - ["manifest_text"]
617   end
618
619   def self.full_text_searchable_columns
620     super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed", "current_version_uuid"]
621   end
622
623   def self.where *args
624     SweepTrashedObjects.sweep_if_stale
625     super
626   end
627
628   protected
629
630   # Although the defaults for these columns is already set up on the schema,
631   # collection creation from an API client seems to ignore them, making the
632   # validation on empty desired storage classes return an error.
633   def default_storage_classes
634     if self.storage_classes_desired.nil? || self.storage_classes_desired.empty?
635       self.storage_classes_desired = Rails.configuration.DefaultStorageClasses
636     end
637     self.storage_classes_confirmed ||= []
638   end
639
640   # Sets managed properties at creation time
641   def managed_properties
642     managed_props = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
643     if managed_props.empty?
644       return
645     end
646     (managed_props.keys - self.properties.keys).each do |key|
647       if managed_props[key]['Function'] == 'original_owner'
648         self.properties[key] = self.user_owner_uuid
649       elsif managed_props[key]['Value']
650         self.properties[key] = managed_props[key]['Value']
651       else
652         logger.warn "Unidentified default property definition '#{key}': #{managed_props[key].inspect}"
653       end
654     end
655   end
656
657   def portable_manifest_text
658     self.class.munge_manifest_locators(manifest_text) do |match|
659       if match[2] # size
660         match[1] + match[2]
661       else
662         match[1]
663       end
664     end
665   end
666
667   def compute_pdh
668     portable_manifest = portable_manifest_text
669     (Digest::MD5.hexdigest(portable_manifest) +
670      '+' +
671      portable_manifest.bytesize.to_s)
672   end
673
674   def computed_pdh
675     if @computed_pdh_for_manifest_text == manifest_text
676       return @computed_pdh
677     end
678     @computed_pdh = compute_pdh
679     @computed_pdh_for_manifest_text = manifest_text.dup
680     @computed_pdh
681   end
682
683   def ensure_permission_to_save
684     if (not current_user.andand.is_admin)
685       if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
686         not (replication_confirmed_at.nil? and replication_confirmed.nil?)
687         raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
688       end
689       if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
690         not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
691         raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
692       end
693     end
694     super
695   end
696
697   def ensure_storage_classes_desired_is_not_empty
698     if self.storage_classes_desired.empty?
699       raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
700     end
701   end
702
703   def ensure_storage_classes_contain_non_empty_strings
704     (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
705       if !c.is_a?(String) || c == ''
706         raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")
707       end
708     end
709   end
710
711   def past_versions_cannot_be_updated
712     if is_past_version?
713       errors.add(:base, "past versions cannot be updated")
714       false
715     end
716   end
717
718   def protected_managed_properties_updates
719     managed_properties = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
720     if managed_properties.empty? || !properties_changed? || current_user.is_admin
721       return true
722     end
723     protected_props = managed_properties.keys.select do |p|
724       Rails.configuration.Collections.ManagedProperties[p]['Protected']
725     end
726     # Pre-existent protected properties can't be updated
727     invalid_updates = properties_was.keys.select{|p| properties_was[p] != properties[p]} & protected_props
728     if !invalid_updates.empty?
729       invalid_updates.each do |p|
730         errors.add("protected property cannot be updated:", p)
731       end
732       raise PermissionDeniedError.new
733     end
734     true
735   end
736
737   def versioning_metadata_updates
738     valid = true
739     if !is_past_version? && current_version_uuid_changed?
740       errors.add(:current_version_uuid, "cannot be updated")
741       valid = false
742     end
743     if version_changed?
744       errors.add(:version, "cannot be updated")
745       valid = false
746     end
747     valid
748   end
749
750   def assign_uuid
751     super
752     self.current_version_uuid ||= self.uuid
753     true
754   end
755
756   def log_update
757     super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?
758   end
759 end