Merge branch '15964-fix-docs' refs #15964
[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   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   after_initialize do
66     @signatures_checked = false
67     @computed_pdh_for_manifest_text = false
68   end
69
70   def self.attributes_required_columns
71     super.merge(
72                 # If we don't list manifest_text explicitly, the
73                 # params[:select] code gets confused by the way we
74                 # expose signed_manifest_text as manifest_text in the
75                 # API response, and never let clients select the
76                 # manifest_text column.
77                 #
78                 # We need trash_at and is_trashed to determine the
79                 # correct timestamp in signed_manifest_text.
80                 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
81                 'unsigned_manifest_text' => ['manifest_text'],
82                 'name' => ['name'],
83                 )
84   end
85
86   def self.ignored_select_attributes
87     super + ["updated_at", "file_names"]
88   end
89
90   def self.limit_index_columns_read
91     ["manifest_text"]
92   end
93
94   FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
95   def check_signatures
96     throw(:abort) if self.manifest_text.nil?
97
98     return true if current_user.andand.is_admin
99
100     # Provided the manifest_text hasn't changed materially since an
101     # earlier validation, it's safe to pass this validation on
102     # subsequent passes without checking any signatures. This is
103     # important because the signatures have probably been stripped off
104     # by the time we get to a second validation pass!
105     if @signatures_checked && @signatures_checked == computed_pdh
106       return true
107     end
108
109     if self.manifest_text_changed?
110       # Check permissions on the collection manifest.
111       # If any signature cannot be verified, raise PermissionDeniedError
112       # which will return 403 Permission denied to the client.
113       api_token = Thread.current[:token]
114       signing_opts = {
115         api_token: api_token,
116         now: @validation_timestamp.to_i,
117       }
118       self.manifest_text.each_line do |entry|
119         entry.split.each do |tok|
120           if tok == '.' or tok.starts_with? './'
121             # Stream name token.
122           elsif tok =~ FILE_TOKEN
123             # This is a filename token, not a blob locator. Note that we
124             # keep checking tokens after this, even though manifest
125             # format dictates that all subsequent tokens will also be
126             # filenames. Safety first!
127           elsif Blob.verify_signature tok, signing_opts
128             # OK.
129           elsif Keep::Locator.parse(tok).andand.signature
130             # Signature provided, but verify_signature did not like it.
131             logger.warn "Invalid signature on locator #{tok}"
132             raise ArvadosModel::PermissionDeniedError
133           elsif !Rails.configuration.Collections.BlobSigning
134             # No signature provided, but we are running in insecure mode.
135             logger.debug "Missing signature on locator #{tok} ignored"
136           elsif Blob.new(tok).empty?
137             # No signature provided -- but no data to protect, either.
138           else
139             logger.warn "Missing signature on locator #{tok}"
140             raise ArvadosModel::PermissionDeniedError
141           end
142         end
143       end
144     end
145     @signatures_checked = computed_pdh
146   end
147
148   def strip_signatures_and_update_replication_confirmed
149     if self.manifest_text_changed?
150       in_old_manifest = {}
151       if not self.replication_confirmed.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       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
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         self.preserve_version = false
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           act_as_system_user do
298             snapshot.save
299           end
300         end
301       end
302     end
303   end
304
305   def syncable_updates
306     updates = {}
307     if self.changes.any?
308       changes = self.changes
309     else
310       # If called after save...
311       changes = self.saved_changes
312     end
313     (syncable_attrs & changes.keys).each do |attr|
314       if attr == 'uuid'
315         # Point old versions to current version's new UUID
316         updates['current_version_uuid'] = changes[attr].last
317       else
318         updates[attr] = changes[attr].last
319       end
320     end
321     return updates
322   end
323
324   def sync_past_versions
325     updates = self.syncable_updates
326     Collection.where('current_version_uuid = ? AND uuid != ?', self.uuid_before_last_save, self.uuid_before_last_save).each do |c|
327       c.attributes = updates
328       # Use a different validation context to skip the 'past_versions_cannot_be_updated'
329       # validator, as on this case it is legal to update some fields.
330       leave_modified_by_user_alone do
331         leave_modified_at_alone do
332           c.save(context: :update_old_versions)
333         end
334       end
335     end
336   end
337
338   def versionable_updates?(attrs)
339     (['manifest_text', 'description', 'properties', 'name'] & attrs).any?
340   end
341
342   def syncable_attrs
343     ['uuid', 'owner_uuid', 'delete_at', 'trash_at', 'is_trashed', 'replication_desired', 'storage_classes_desired']
344   end
345
346   def is_past_version?
347     # Check for the '_was' values just in case the update operation
348     # includes a change on current_version_uuid or uuid.
349     !(new_record? || self.current_version_uuid_was == self.uuid_was)
350   end
351
352   def should_preserve_version?
353     return false unless (Rails.configuration.Collections.CollectionVersioning && versionable_updates?(self.changes.keys))
354
355     return false if self.is_trashed
356
357     idle_threshold = Rails.configuration.Collections.PreserveVersionIfIdle
358     if !self.preserve_version_was &&
359       (idle_threshold < 0 ||
360         (idle_threshold > 0 && self.modified_at_was > db_current_time-idle_threshold.seconds))
361       return false
362     end
363     return true
364   end
365
366   def check_encoding
367     if !(manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?)
368       begin
369         # If Ruby thinks the encoding is something else, like 7-bit
370         # ASCII, but its stored bytes are equal to the (valid) UTF-8
371         # encoding of the same string, we declare it to be a UTF-8
372         # string.
373         utf8 = manifest_text
374         utf8.force_encoding Encoding::UTF_8
375         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
376           self.manifest_text = utf8
377           return true
378         end
379       rescue
380       end
381       errors.add :manifest_text, "must use UTF-8 encoding"
382       throw(:abort)
383     end
384   end
385
386   def check_manifest_validity
387     begin
388       Keep::Manifest.validate! manifest_text
389       true
390     rescue ArgumentError => e
391       errors.add :manifest_text, e.message
392       throw(:abort)
393     end
394   end
395
396   def signed_manifest_text
397     if !has_attribute? :manifest_text
398       return nil
399     elsif is_trashed
400       return manifest_text
401     else
402       token = Thread.current[:token]
403       exp = [db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i,
404              trash_at].compact.map(&:to_i).min
405       self.class.sign_manifest manifest_text, token, exp
406     end
407   end
408
409   def self.sign_manifest manifest, token, exp=nil
410     if exp.nil?
411       exp = db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i
412     end
413     signing_opts = {
414       api_token: token,
415       expire: exp,
416     }
417     m = munge_manifest_locators(manifest) do |match|
418       Blob.sign_locator(match[0], signing_opts)
419     end
420     return m
421   end
422
423   def self.munge_manifest_locators manifest
424     # Given a manifest text and a block, yield the regexp MatchData
425     # for each locator. Return a new manifest in which each locator
426     # has been replaced by the block's return value.
427     return nil if !manifest
428     return '' if manifest == ''
429
430     new_lines = []
431     manifest.each_line do |line|
432       line.rstrip!
433       new_words = []
434       line.split(' ').each do |word|
435         if new_words.empty?
436           new_words << word
437         elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
438           new_words << yield(match)
439         else
440           new_words << word
441         end
442       end
443       new_lines << new_words.join(' ')
444     end
445     new_lines.join("\n") + "\n"
446   end
447
448   def self.each_manifest_locator manifest
449     # Given a manifest text and a block, yield the regexp match object
450     # for each locator.
451     manifest.each_line do |line|
452       # line will have a trailing newline, but the last token is never
453       # a locator, so it's harmless here.
454       line.split(' ').each do |word|
455         if match = Keep::Locator::LOCATOR_REGEXP.match(word)
456           yield(match)
457         end
458       end
459     end
460   end
461
462   def self.normalize_uuid uuid
463     hash_part = nil
464     size_part = nil
465     uuid.split('+').each do |token|
466       if token.match(/^[0-9a-f]{32,}$/)
467         raise "uuid #{uuid} has multiple hash parts" if hash_part
468         hash_part = token
469       elsif token.match(/^\d+$/)
470         raise "uuid #{uuid} has multiple size parts" if size_part
471         size_part = token
472       end
473     end
474     raise "uuid #{uuid} has no hash part" if !hash_part
475     [hash_part, size_part].compact.join '+'
476   end
477
478   def self.get_compatible_images(readers, pattern, collections)
479     if collections.empty?
480       return []
481     end
482
483     migrations = Hash[
484       Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
485                  collections.map(&:portable_data_hash),
486                  'docker_image_migration',
487                  system_user_uuid).
488       order('links.created_at asc').
489       map { |l|
490         [l.tail_uuid, l.head_uuid]
491       }]
492
493     migrated_collections = Hash[
494       Collection.readable_by(*readers).
495       where('portable_data_hash in (?)', migrations.values).
496       map { |c|
497         [c.portable_data_hash, c]
498       }]
499
500     collections.map { |c|
501       # Check if the listed image is compatible first, if not, then try the
502       # migration link.
503       manifest = Keep::Manifest.new(c.manifest_text)
504       if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
505         c
506       elsif m = migrated_collections[migrations[c.portable_data_hash]]
507         manifest = Keep::Manifest.new(m.manifest_text)
508         if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
509           m
510         end
511       end
512     }.compact
513   end
514
515   # Resolve a Docker repo+tag, hash, or collection PDH to an array of
516   # Collection objects, sorted by timestamp starting with the most recent
517   # match.
518   #
519   # If filter_compatible_format is true (the default), only return image
520   # collections which are support by the installation as indicated by
521   # Rails.configuration.Containers.SupportedDockerImageFormats.  Will follow
522   # 'docker_image_migration' links if search_term resolves to an incompatible
523   # image, but an equivalent compatible image is available.
524   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
525     readers ||= [Thread.current[:user]]
526     base_search = Link.
527       readable_by(*readers).
528       readable_by(*readers, table_name: "collections").
529       joins("JOIN collections ON links.head_uuid = collections.uuid").
530       order("links.created_at DESC")
531
532     docker_image_formats = Rails.configuration.Containers.SupportedDockerImageFormats.keys.map(&:to_s)
533
534     if (docker_image_formats.include? 'v1' and
535         docker_image_formats.include? 'v2') or filter_compatible_format == false
536       pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
537     elsif docker_image_formats.include? 'v2'
538       pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
539     elsif docker_image_formats.include? 'v1'
540       pattern = /^[0-9A-Fa-f]{64}\.tar$/
541     else
542       raise "Unrecognized configuration for docker_image_formats #{docker_image_formats}"
543     end
544
545     # If the search term is a Collection locator that contains one file
546     # that looks like a Docker image, return it.
547     if loc = Keep::Locator.parse(search_term)
548       loc.strip_hints!
549       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
550       rc = Rails.configuration.RemoteClusters.select{ |k|
551         k != :"*" && k != Rails.configuration.ClusterID}
552       if coll_match.any? or rc.length == 0
553         return get_compatible_images(readers, pattern, coll_match)
554       else
555         # Allow bare pdh that doesn't exist in the local database so
556         # that federated container requests which refer to remotely
557         # stored containers will validate.
558         return [Collection.new(portable_data_hash: loc.to_s)]
559       end
560     end
561
562     if search_tag.nil? and (n = search_term.index(":"))
563       search_tag = search_term[n+1..-1]
564       search_term = search_term[0..n-1]
565     end
566
567     # Find Collections with matching Docker image repository+tag pairs.
568     matches = base_search.
569       where(link_class: "docker_image_repo+tag",
570             name: "#{search_term}:#{search_tag || 'latest'}")
571
572     # If that didn't work, find Collections with matching Docker image hashes.
573     if matches.empty?
574       matches = base_search.
575         where("link_class = ? and links.name LIKE ?",
576               "docker_image_hash", "#{search_term}%")
577     end
578
579     # Generate an order key for each result.  We want to order the results
580     # so that anything with an image timestamp is considered more recent than
581     # anything without; then we use the link's created_at as a tiebreaker.
582     uuid_timestamps = {}
583     matches.each do |link|
584       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
585        -link.created_at.to_i]
586      end
587
588     sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
589       uuid_timestamps[c.uuid]
590     }
591     compatible = get_compatible_images(readers, pattern, sorted)
592     if sorted.length > 0 and compatible.empty?
593       raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
594     end
595     compatible
596   end
597
598   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
599     find_all_for_docker_image(search_term, search_tag, readers).first
600   end
601
602   def self.searchable_columns operator
603     super - ["manifest_text"]
604   end
605
606   def self.full_text_searchable_columns
607     super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed", "current_version_uuid"]
608   end
609
610   def self.where *args
611     SweepTrashedObjects.sweep_if_stale
612     super
613   end
614
615   protected
616
617   # Although the defaults for these columns is already set up on the schema,
618   # collection creation from an API client seems to ignore them, making the
619   # validation on empty desired storage classes return an error.
620   def default_storage_classes
621     if self.storage_classes_desired.nil? || self.storage_classes_desired.empty?
622       self.storage_classes_desired = ["default"]
623     end
624     self.storage_classes_confirmed ||= []
625   end
626
627   # Sets managed properties at creation time
628   def managed_properties
629     managed_props = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
630     if managed_props.empty?
631       return
632     end
633     (managed_props.keys - self.properties.keys).each do |key|
634       if managed_props[key]['Function'] == 'original_owner'
635         self.properties[key] = self.user_owner_uuid
636       elsif managed_props[key]['Value']
637         self.properties[key] = managed_props[key]['Value']
638       else
639         logger.warn "Unidentified default property definition '#{key}': #{managed_props[key].inspect}"
640       end
641     end
642   end
643
644   def portable_manifest_text
645     self.class.munge_manifest_locators(manifest_text) do |match|
646       if match[2] # size
647         match[1] + match[2]
648       else
649         match[1]
650       end
651     end
652   end
653
654   def compute_pdh
655     portable_manifest = portable_manifest_text
656     (Digest::MD5.hexdigest(portable_manifest) +
657      '+' +
658      portable_manifest.bytesize.to_s)
659   end
660
661   def computed_pdh
662     if @computed_pdh_for_manifest_text == manifest_text
663       return @computed_pdh
664     end
665     @computed_pdh = compute_pdh
666     @computed_pdh_for_manifest_text = manifest_text.dup
667     @computed_pdh
668   end
669
670   def ensure_permission_to_save
671     if (not current_user.andand.is_admin)
672       if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
673         not (replication_confirmed_at.nil? and replication_confirmed.nil?)
674         raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
675       end
676       if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
677         not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
678         raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
679       end
680     end
681     super
682   end
683
684   def ensure_storage_classes_desired_is_not_empty
685     if self.storage_classes_desired.empty?
686       raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
687     end
688   end
689
690   def ensure_storage_classes_contain_non_empty_strings
691     (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
692       if !c.is_a?(String) || c == ''
693         raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")
694       end
695     end
696   end
697
698   def past_versions_cannot_be_updated
699     if is_past_version?
700       errors.add(:base, "past versions cannot be updated")
701       false
702     end
703   end
704
705   def protected_managed_properties_updates
706     managed_properties = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
707     if managed_properties.empty? || !properties_changed? || current_user.is_admin
708       return true
709     end
710     protected_props = managed_properties.keys.select do |p|
711       Rails.configuration.Collections.ManagedProperties[p]['Protected']
712     end
713     # Pre-existent protected properties can't be updated
714     invalid_updates = properties_was.keys.select{|p| properties_was[p] != properties[p]} & protected_props
715     if !invalid_updates.empty?
716       invalid_updates.each do |p|
717         errors.add("protected property cannot be updated:", p)
718       end
719       raise PermissionDeniedError.new
720     end
721     true
722   end
723
724   def versioning_metadata_updates
725     valid = true
726     if !is_past_version? && current_version_uuid_changed?
727       errors.add(:current_version_uuid, "cannot be updated")
728       valid = false
729     end
730     if version_changed?
731       errors.add(:version, "cannot be updated")
732       valid = false
733     end
734     valid
735   end
736
737   def assign_uuid
738     super
739     self.current_version_uuid ||= self.uuid
740     true
741   end
742 end