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