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