20300: Call safe_load explicitly instead of using safe_yaml gem.
[arvados.git] / services / api / lib / serializers.rb
index 41379f308fb11834cc1fe63e9edd31ac804d0a2b..c25b9060b4100871e2ec832e318120829db9ef4e 100644 (file)
@@ -1,12 +1,22 @@
+# Copyright (C) The Arvados Authors. All rights reserved.
+#
+# SPDX-License-Identifier: AGPL-3.0
+
 require 'safe_json'
 
 class Serializer
+  class TypeMismatch < ArgumentError
+  end
+
   def self.dump(val)
+    if !val.is_a?(object_class)
+      raise TypeMismatch.new("cannot serialize #{val.class} as #{object_class}")
+    end
     SafeJSON.dump(val)
   end
 
   def self.legacy_load(s)
-    val = Psych.safe_load(s)
+    val = Psych.safe_load(s, permitted_classes: [Time])
     if val.is_a? String
       # If apiserver was downgraded to a YAML-only version after
       # storing JSON in the database, the old code would have loaded
@@ -22,7 +32,10 @@ class Serializer
   end
 
   def self.load(s)
-    if s.nil?
+    if s.is_a?(object_class)
+      # Rails already deserialized for us
+      s
+    elsif s.nil?
       object_class.new()
     elsif s[0] == first_json_char
       SafeJSON.load(s)