76dbdd
From 4f1c3f5be0306da485135544ced4a676753a9373 Mon Sep 17 00:00:00 2001
76dbdd
From: Eduardo Otubo <otubo@redhat.com>
76dbdd
Date: Wed, 16 Oct 2019 12:10:24 +0200
76dbdd
Subject: [PATCH 2/2] util: json.dumps on python 2.7 will handle
76dbdd
 UnicodeDecodeError on binary
76dbdd
76dbdd
RH-Author: Eduardo Otubo <otubo@redhat.com>
76dbdd
Message-id: <20191016121024.23694-1-otubo@redhat.com>
76dbdd
Patchwork-id: 91812
76dbdd
O-Subject: [RHEL-7.8/RHEL-8.1.0 cloud-init PATCH] util: json.dumps on python 2.7 will handle UnicodeDecodeError on binary
76dbdd
Bugzilla: 1744718
76dbdd
RH-Acked-by: Vitaly Kuznetsov <vkuznets@redhat.com>
76dbdd
RH-Acked-by: Mohammed Gamal <mgamal@redhat.com>
76dbdd
76dbdd
commit 067516d7bc917e4921b9f1424b7a64e92cae0ad2
76dbdd
Author: Chad Smith <chad.smith@canonical.com>
76dbdd
Date:   Fri Sep 27 20:46:00 2019 +0000
76dbdd
76dbdd
    util: json.dumps on python 2.7 will handle UnicodeDecodeError on binary
76dbdd
76dbdd
    Since python 2.7 doesn't handle UnicodeDecodeErrors with the default
76dbdd
    handler
76dbdd
76dbdd
    LP: #1801364
76dbdd
76dbdd
Signed-off-by: Eduardo Otubo <otubo@redhat.com>
76dbdd
Signed-off-by: Miroslav Rezanina <mrezanin@redhat.com>
76dbdd
---
76dbdd
 cloudinit/sources/tests/test_init.py | 12 +++++-------
76dbdd
 cloudinit/tests/test_util.py         | 20 ++++++++++++++++++++
76dbdd
 cloudinit/util.py                    | 27 +++++++++++++++++++++++++--
76dbdd
 3 files changed, 50 insertions(+), 9 deletions(-)
76dbdd
76dbdd
diff --git a/cloudinit/sources/tests/test_init.py b/cloudinit/sources/tests/test_init.py
76dbdd
index 6378e98..9698261 100644
76dbdd
--- a/cloudinit/sources/tests/test_init.py
76dbdd
+++ b/cloudinit/sources/tests/test_init.py
76dbdd
@@ -457,19 +457,17 @@ class TestDataSource(CiTestCase):
76dbdd
             instance_json['ds']['meta_data'])
76dbdd
 
76dbdd
     @skipIf(not six.PY2, "Only python2 hits UnicodeDecodeErrors on non-utf8")
76dbdd
-    def test_non_utf8_encoding_logs_warning(self):
76dbdd
-        """When non-utf-8 values exist in py2 instance-data is not written."""
76dbdd
+    def test_non_utf8_encoding_gets_b64encoded(self):
76dbdd
+        """When non-utf-8 values exist in py2 instance-data is b64encoded."""
76dbdd
         tmp = self.tmp_dir()
76dbdd
         datasource = DataSourceTestSubclassNet(
76dbdd
             self.sys_cfg, self.distro, Paths({'run_dir': tmp}),
76dbdd
             custom_metadata={'key1': 'val1', 'key2': {'key2.1': b'ab\xaadef'}})
76dbdd
         self.assertTrue(datasource.get_data())
76dbdd
         json_file = self.tmp_path(INSTANCE_JSON_FILE, tmp)
76dbdd
-        self.assertFalse(os.path.exists(json_file))
76dbdd
-        self.assertIn(
76dbdd
-            "WARNING: Error persisting instance-data.json: 'utf8' codec can't"
76dbdd
-            " decode byte 0xaa in position 2: invalid start byte",
76dbdd
-            self.logs.getvalue())
76dbdd
+        instance_json = util.load_json(util.load_file(json_file))
76dbdd
+        key21_value = instance_json['ds']['meta_data']['key2']['key2.1']
76dbdd
+        self.assertEqual('ci-b64:' + util.b64e(b'ab\xaadef'), key21_value)
76dbdd
 
76dbdd
     def test_get_hostname_subclass_support(self):
76dbdd
         """Validate get_hostname signature on all subclasses of DataSource."""
76dbdd
diff --git a/cloudinit/tests/test_util.py b/cloudinit/tests/test_util.py
76dbdd
index e3d2dba..f4f95e9 100644
76dbdd
--- a/cloudinit/tests/test_util.py
76dbdd
+++ b/cloudinit/tests/test_util.py
76dbdd
@@ -2,7 +2,9 @@
76dbdd
 
76dbdd
 """Tests for cloudinit.util"""
76dbdd
 
76dbdd
+import base64
76dbdd
 import logging
76dbdd
+import json
76dbdd
 import platform
76dbdd
 
76dbdd
 import cloudinit.util as util
76dbdd
@@ -528,6 +530,24 @@ class TestGetLinuxDistro(CiTestCase):
76dbdd
         self.assertEqual(('foo', '1.1', 'aarch64'), dist)
76dbdd
 
76dbdd
 
76dbdd
+class TestJsonDumps(CiTestCase):
76dbdd
+    def test_is_str(self):
76dbdd
+        """json_dumps should return a string."""
76dbdd
+        self.assertTrue(isinstance(util.json_dumps({'abc': '123'}), str))
76dbdd
+
76dbdd
+    def test_utf8(self):
76dbdd
+        smiley = '\\ud83d\\ude03'
76dbdd
+        self.assertEqual(
76dbdd
+            {'smiley': smiley},
76dbdd
+            json.loads(util.json_dumps({'smiley': smiley})))
76dbdd
+
76dbdd
+    def test_non_utf8(self):
76dbdd
+        blob = b'\xba\x03Qx-#y\xea'
76dbdd
+        self.assertEqual(
76dbdd
+            {'blob': 'ci-b64:' + base64.b64encode(blob).decode('utf-8')},
76dbdd
+            json.loads(util.json_dumps({'blob': blob})))
76dbdd
+
76dbdd
+
76dbdd
 @mock.patch('os.path.exists')
76dbdd
 class TestIsLXD(CiTestCase):
76dbdd
 
76dbdd
diff --git a/cloudinit/util.py b/cloudinit/util.py
76dbdd
index a84112a..2c9ac66 100644
76dbdd
--- a/cloudinit/util.py
76dbdd
+++ b/cloudinit/util.py
76dbdd
@@ -1590,10 +1590,33 @@ def json_serialize_default(_obj):
76dbdd
         return 'Warning: redacted unserializable type {0}'.format(type(_obj))
76dbdd
 
76dbdd
 
76dbdd
+def json_preserialize_binary(data):
76dbdd
+    """Preserialize any discovered binary values to avoid json.dumps issues.
76dbdd
+
76dbdd
+    Used only on python 2.7 where default type handling is not honored for
76dbdd
+    failure to encode binary data. LP: #1801364.
76dbdd
+    TODO(Drop this function when py2.7 support is dropped from cloud-init)
76dbdd
+    """
76dbdd
+    data = obj_copy.deepcopy(data)
76dbdd
+    for key, value in data.items():
76dbdd
+        if isinstance(value, (dict)):
76dbdd
+            data[key] = json_preserialize_binary(value)
76dbdd
+        if isinstance(value, bytes):
76dbdd
+            data[key] = 'ci-b64:{0}'.format(b64e(value))
76dbdd
+    return data
76dbdd
+
76dbdd
+
76dbdd
 def json_dumps(data):
76dbdd
     """Return data in nicely formatted json."""
76dbdd
-    return json.dumps(data, indent=1, sort_keys=True,
76dbdd
-                      separators=(',', ': '), default=json_serialize_default)
76dbdd
+    try:
76dbdd
+        return json.dumps(
76dbdd
+            data, indent=1, sort_keys=True, separators=(',', ': '),
76dbdd
+            default=json_serialize_default)
76dbdd
+    except UnicodeDecodeError:
76dbdd
+        if sys.version_info[:2] == (2, 7):
76dbdd
+            data = json_preserialize_binary(data)
76dbdd
+            return json.dumps(data)
76dbdd
+        raise
76dbdd
 
76dbdd
 
76dbdd
 def yaml_dumps(obj, explicit_start=True, explicit_end=True):
76dbdd
-- 
76dbdd
1.8.3.1
76dbdd