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