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