17152: Changes preserve_version semantics, updates related documentation.
[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: ["default"]
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   before_update :preserve_version_exclusive_updates_leave_modified_at_alone,
41     if: Proc.new { |col| col.changes.keys.sort == ['modified_at', 'updated_at', 'preserve_version'].sort }
42   around_update :manage_versioning, unless: :is_past_version?
43
44   api_accessible :user, extend: :common do |t|
45     t.add lambda { |x| x.name || "" }, as: :name
46     t.add :description
47     t.add :properties
48     t.add :portable_data_hash
49     t.add :signed_manifest_text, as: :manifest_text
50     t.add :manifest_text, as: :unsigned_manifest_text
51     t.add :replication_desired
52     t.add :replication_confirmed
53     t.add :replication_confirmed_at
54     t.add :storage_classes_desired
55     t.add :storage_classes_confirmed
56     t.add :storage_classes_confirmed_at
57     t.add :delete_at
58     t.add :trash_at
59     t.add :is_trashed
60     t.add :version
61     t.add :current_version_uuid
62     t.add :preserve_version
63     t.add :file_count
64     t.add :file_size_total
65   end
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
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         if !changes.keys.include?('preserve_version')
292           self.preserve_version = false
293         end
294       end
295
296       yield
297
298       sync_past_versions if syncable_updates.any?
299       if snapshot
300         snapshot.attributes = self.syncable_updates
301         leave_modified_by_user_alone do
302           leave_modified_at_alone do
303             act_as_system_user do
304               snapshot.save
305             end
306           end
307         end
308       end
309     end
310   end
311
312   def preserve_version_exclusive_updates_leave_modified_at_alone
313     self.modified_at = self.modified_at_was
314   end
315
316   def syncable_updates
317     updates = {}
318     if self.changes.any?
319       changes = self.changes
320     else
321       # If called after save...
322       changes = self.saved_changes
323     end
324     (syncable_attrs & changes.keys).each do |attr|
325       if attr == 'uuid'
326         # Point old versions to current version's new UUID
327         updates['current_version_uuid'] = changes[attr].last
328       else
329         updates[attr] = changes[attr].last
330       end
331     end
332     return updates
333   end
334
335   def sync_past_versions
336     updates = self.syncable_updates
337     Collection.where('current_version_uuid = ? AND uuid != ?', self.uuid_before_last_save, self.uuid_before_last_save).each do |c|
338       c.attributes = updates
339       # Use a different validation context to skip the 'past_versions_cannot_be_updated'
340       # validator, as on this case it is legal to update some fields.
341       leave_modified_by_user_alone do
342         leave_modified_at_alone do
343           c.save(context: :update_old_versions)
344         end
345       end
346     end
347   end
348
349   def versionable_updates?(attrs)
350     (['manifest_text', 'description', 'properties', 'name'] & attrs).any?
351   end
352
353   def syncable_attrs
354     ['uuid', 'owner_uuid', 'delete_at', 'trash_at', 'is_trashed', 'replication_desired', 'storage_classes_desired']
355   end
356
357   def is_past_version?
358     # Check for the '_was' values just in case the update operation
359     # includes a change on current_version_uuid or uuid.
360     !(new_record? || self.current_version_uuid_was == self.uuid_was)
361   end
362
363   def should_preserve_version?
364     return false unless (Rails.configuration.Collections.CollectionVersioning && versionable_updates?(self.changes.keys))
365
366     return false if self.is_trashed
367
368     idle_threshold = Rails.configuration.Collections.PreserveVersionIfIdle
369     if !self.preserve_version_was &&
370       !self.preserve_version &&
371       (idle_threshold < 0 ||
372         (idle_threshold > 0 && self.modified_at_was > db_current_time-idle_threshold.seconds))
373       return false
374     end
375     return true
376   end
377
378   def check_encoding
379     if !(manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?)
380       begin
381         # If Ruby thinks the encoding is something else, like 7-bit
382         # ASCII, but its stored bytes are equal to the (valid) UTF-8
383         # encoding of the same string, we declare it to be a UTF-8
384         # string.
385         utf8 = manifest_text
386         utf8.force_encoding Encoding::UTF_8
387         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
388           self.manifest_text = utf8
389           return true
390         end
391       rescue
392       end
393       errors.add :manifest_text, "must use UTF-8 encoding"
394       throw(:abort)
395     end
396   end
397
398   def check_manifest_validity
399     begin
400       Keep::Manifest.validate! manifest_text
401       true
402     rescue ArgumentError => e
403       errors.add :manifest_text, e.message
404       throw(:abort)
405     end
406   end
407
408   def signed_manifest_text
409     if !has_attribute? :manifest_text
410       return nil
411     elsif is_trashed
412       return manifest_text
413     else
414       token = Thread.current[:token]
415       exp = [db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i,
416              trash_at].compact.map(&:to_i).min
417       self.class.sign_manifest manifest_text, token, exp
418     end
419   end
420
421   def self.sign_manifest manifest, token, exp=nil
422     if exp.nil?
423       exp = db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i
424     end
425     signing_opts = {
426       api_token: token,
427       expire: exp,
428     }
429     m = munge_manifest_locators(manifest) do |match|
430       Blob.sign_locator(match[0], signing_opts)
431     end
432     return m
433   end
434
435   def self.munge_manifest_locators manifest
436     # Given a manifest text and a block, yield the regexp MatchData
437     # for each locator. Return a new manifest in which each locator
438     # has been replaced by the block's return value.
439     return nil if !manifest
440     return '' if manifest == ''
441
442     new_lines = []
443     manifest.each_line do |line|
444       line.rstrip!
445       new_words = []
446       line.split(' ').each do |word|
447         if new_words.empty?
448           new_words << word
449         elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
450           new_words << yield(match)
451         else
452           new_words << word
453         end
454       end
455       new_lines << new_words.join(' ')
456     end
457     new_lines.join("\n") + "\n"
458   end
459
460   def self.each_manifest_locator manifest
461     # Given a manifest text and a block, yield the regexp match object
462     # for each locator.
463     manifest.each_line do |line|
464       # line will have a trailing newline, but the last token is never
465       # a locator, so it's harmless here.
466       line.split(' ').each do |word|
467         if match = Keep::Locator::LOCATOR_REGEXP.match(word)
468           yield(match)
469         end
470       end
471     end
472   end
473
474   def self.normalize_uuid uuid
475     hash_part = nil
476     size_part = nil
477     uuid.split('+').each do |token|
478       if token.match(/^[0-9a-f]{32,}$/)
479         raise "uuid #{uuid} has multiple hash parts" if hash_part
480         hash_part = token
481       elsif token.match(/^\d+$/)
482         raise "uuid #{uuid} has multiple size parts" if size_part
483         size_part = token
484       end
485     end
486     raise "uuid #{uuid} has no hash part" if !hash_part
487     [hash_part, size_part].compact.join '+'
488   end
489
490   def self.get_compatible_images(readers, pattern, collections)
491     if collections.empty?
492       return []
493     end
494
495     migrations = Hash[
496       Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
497                  collections.map(&:portable_data_hash),
498                  'docker_image_migration',
499                  system_user_uuid).
500       order('links.created_at asc').
501       map { |l|
502         [l.tail_uuid, l.head_uuid]
503       }]
504
505     migrated_collections = Hash[
506       Collection.readable_by(*readers).
507       where('portable_data_hash in (?)', migrations.values).
508       map { |c|
509         [c.portable_data_hash, c]
510       }]
511
512     collections.map { |c|
513       # Check if the listed image is compatible first, if not, then try the
514       # migration link.
515       manifest = Keep::Manifest.new(c.manifest_text)
516       if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
517         c
518       elsif m = migrated_collections[migrations[c.portable_data_hash]]
519         manifest = Keep::Manifest.new(m.manifest_text)
520         if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
521           m
522         end
523       end
524     }.compact
525   end
526
527   # Resolve a Docker repo+tag, hash, or collection PDH to an array of
528   # Collection objects, sorted by timestamp starting with the most recent
529   # match.
530   #
531   # If filter_compatible_format is true (the default), only return image
532   # collections which are support by the installation as indicated by
533   # Rails.configuration.Containers.SupportedDockerImageFormats.  Will follow
534   # 'docker_image_migration' links if search_term resolves to an incompatible
535   # image, but an equivalent compatible image is available.
536   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
537     readers ||= [Thread.current[:user]]
538     base_search = Link.
539       readable_by(*readers).
540       readable_by(*readers, table_name: "collections").
541       joins("JOIN collections ON links.head_uuid = collections.uuid").
542       order("links.created_at DESC")
543
544     docker_image_formats = Rails.configuration.Containers.SupportedDockerImageFormats.keys.map(&:to_s)
545
546     if (docker_image_formats.include? 'v1' and
547         docker_image_formats.include? 'v2') or filter_compatible_format == false
548       pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
549     elsif docker_image_formats.include? 'v2'
550       pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
551     elsif docker_image_formats.include? 'v1'
552       pattern = /^[0-9A-Fa-f]{64}\.tar$/
553     else
554       raise "Unrecognized configuration for docker_image_formats #{docker_image_formats}"
555     end
556
557     # If the search term is a Collection locator that contains one file
558     # that looks like a Docker image, return it.
559     if loc = Keep::Locator.parse(search_term)
560       loc.strip_hints!
561       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
562       rc = Rails.configuration.RemoteClusters.select{ |k|
563         k != :"*" && k != Rails.configuration.ClusterID}
564       if coll_match.any? or rc.length == 0
565         return get_compatible_images(readers, pattern, coll_match)
566       else
567         # Allow bare pdh that doesn't exist in the local database so
568         # that federated container requests which refer to remotely
569         # stored containers will validate.
570         return [Collection.new(portable_data_hash: loc.to_s)]
571       end
572     end
573
574     if search_tag.nil? and (n = search_term.index(":"))
575       search_tag = search_term[n+1..-1]
576       search_term = search_term[0..n-1]
577     end
578
579     # Find Collections with matching Docker image repository+tag pairs.
580     matches = base_search.
581       where(link_class: "docker_image_repo+tag",
582             name: "#{search_term}:#{search_tag || 'latest'}")
583
584     # If that didn't work, find Collections with matching Docker image hashes.
585     if matches.empty?
586       matches = base_search.
587         where("link_class = ? and links.name LIKE ?",
588               "docker_image_hash", "#{search_term}%")
589     end
590
591     # Generate an order key for each result.  We want to order the results
592     # so that anything with an image timestamp is considered more recent than
593     # anything without; then we use the link's created_at as a tiebreaker.
594     uuid_timestamps = {}
595     matches.each do |link|
596       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
597        -link.created_at.to_i]
598      end
599
600     sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
601       uuid_timestamps[c.uuid]
602     }
603     compatible = get_compatible_images(readers, pattern, sorted)
604     if sorted.length > 0 and compatible.empty?
605       raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
606     end
607     compatible
608   end
609
610   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
611     find_all_for_docker_image(search_term, search_tag, readers).first
612   end
613
614   def self.searchable_columns operator
615     super - ["manifest_text"]
616   end
617
618   def self.full_text_searchable_columns
619     super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed", "current_version_uuid"]
620   end
621
622   def self.where *args
623     SweepTrashedObjects.sweep_if_stale
624     super
625   end
626
627   protected
628
629   # Although the defaults for these columns is already set up on the schema,
630   # collection creation from an API client seems to ignore them, making the
631   # validation on empty desired storage classes return an error.
632   def default_storage_classes
633     if self.storage_classes_desired.nil? || self.storage_classes_desired.empty?
634       self.storage_classes_desired = ["default"]
635     end
636     self.storage_classes_confirmed ||= []
637   end
638
639   # Sets managed properties at creation time
640   def managed_properties
641     managed_props = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
642     if managed_props.empty?
643       return
644     end
645     (managed_props.keys - self.properties.keys).each do |key|
646       if managed_props[key]['Function'] == 'original_owner'
647         self.properties[key] = self.user_owner_uuid
648       elsif managed_props[key]['Value']
649         self.properties[key] = managed_props[key]['Value']
650       else
651         logger.warn "Unidentified default property definition '#{key}': #{managed_props[key].inspect}"
652       end
653     end
654   end
655
656   def portable_manifest_text
657     self.class.munge_manifest_locators(manifest_text) do |match|
658       if match[2] # size
659         match[1] + match[2]
660       else
661         match[1]
662       end
663     end
664   end
665
666   def compute_pdh
667     portable_manifest = portable_manifest_text
668     (Digest::MD5.hexdigest(portable_manifest) +
669      '+' +
670      portable_manifest.bytesize.to_s)
671   end
672
673   def computed_pdh
674     if @computed_pdh_for_manifest_text == manifest_text
675       return @computed_pdh
676     end
677     @computed_pdh = compute_pdh
678     @computed_pdh_for_manifest_text = manifest_text.dup
679     @computed_pdh
680   end
681
682   def ensure_permission_to_save
683     if (not current_user.andand.is_admin)
684       if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
685         not (replication_confirmed_at.nil? and replication_confirmed.nil?)
686         raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
687       end
688       if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
689         not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
690         raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
691       end
692     end
693     super
694   end
695
696   def ensure_storage_classes_desired_is_not_empty
697     if self.storage_classes_desired.empty?
698       raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
699     end
700   end
701
702   def ensure_storage_classes_contain_non_empty_strings
703     (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
704       if !c.is_a?(String) || c == ''
705         raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")
706       end
707     end
708   end
709
710   def past_versions_cannot_be_updated
711     if is_past_version?
712       errors.add(:base, "past versions cannot be updated")
713       false
714     end
715   end
716
717   def protected_managed_properties_updates
718     managed_properties = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
719     if managed_properties.empty? || !properties_changed? || current_user.is_admin
720       return true
721     end
722     protected_props = managed_properties.keys.select do |p|
723       Rails.configuration.Collections.ManagedProperties[p]['Protected']
724     end
725     # Pre-existent protected properties can't be updated
726     invalid_updates = properties_was.keys.select{|p| properties_was[p] != properties[p]} & protected_props
727     if !invalid_updates.empty?
728       invalid_updates.each do |p|
729         errors.add("protected property cannot be updated:", p)
730       end
731       raise PermissionDeniedError.new
732     end
733     true
734   end
735
736   def versioning_metadata_updates
737     valid = true
738     if !is_past_version? && current_version_uuid_changed?
739       errors.add(:current_version_uuid, "cannot be updated")
740       valid = false
741     end
742     if version_changed?
743       errors.add(:version, "cannot be updated")
744       valid = false
745     end
746     valid
747   end
748
749   def assign_uuid
750     super
751     self.current_version_uuid ||= self.uuid
752     true
753   end
754 end