From 3a32188398675793d87f19363af0497035ea9263 Mon Sep 17 00:00:00 2001
From: Alberto Contreras <alberto.contreras@canonical.com>
Date: Thu, 15 Sep 2022 22:19:38 +0200
Subject: [PATCH] cc_ubuntu_advantage: Redact token from logs (#1726)

Reference:https://github.com/canonical/cloud-init/commit/3a32188398675793d87f19363af0497035ea9263
Conflict:test diffs.
---
 cloudinit/config/cc_ubuntu_advantage.py       | 11 ++++----
 .../config/tests/test_ubuntu_advantage.py     | 26 +++++++++----------
 2 files changed, 19 insertions(+), 18 deletions(-)

diff --git a/cloudinit/config/cc_ubuntu_advantage.py b/cloudinit/config/cc_ubuntu_advantage.py
index e55772a..033d4d2 100644
--- a/cloudinit/config/cc_ubuntu_advantage.py
+++ b/cloudinit/config/cc_ubuntu_advantage.py
@@ -85,7 +85,7 @@ schema = {
 __doc__ = get_schema_doc(schema)  # Supplement python help()
 
 LOG = logging.getLogger(__name__)
-
+REDACTED = "REDACTED"
 
 def configure_ua(token=None, enable=None):
     """Call ua commandline client to attach or enable services."""
@@ -108,12 +108,13 @@ def configure_ua(token=None, enable=None):
         enable = []
 
     attach_cmd = ['ua', 'attach', token]
-    LOG.debug('Attaching to Ubuntu Advantage. %s', ' '.join(attach_cmd))
+    redacted_cmd = attach_cmd[:-1] + [REDACTED]
+    LOG.debug("Attaching to Ubuntu Advantage. %s", " ".join(redacted_cmd))
     try:
-        subp.subp(attach_cmd)
+        subp.subp(attach_cmd, logstring=redacted_cmd)
     except subp.ProcessExecutionError as e:
-        msg = 'Failure attaching Ubuntu Advantage:\n{error}'.format(
-            error=str(e))
+        error = str(e).replace(token, REDACTED)
+        msg = f"Failure attaching Ubuntu Advantage:\n{error}"
         util.logexc(LOG, msg)
         raise RuntimeError(msg) from e
     enable_errors = []
diff --git a/cloudinit/config/tests/test_ubuntu_advantage.py b/cloudinit/config/tests/test_ubuntu_advantage.py
index db7fb72..eadeddb 100644
--- a/cloudinit/config/tests/test_ubuntu_advantage.py
+++ b/cloudinit/config/tests/test_ubuntu_advantage.py
@@ -36,23 +36,23 @@ class TestConfigureUA(CiTestCase):
         self.assertEqual(
             'Failure attaching Ubuntu Advantage:\nUnexpected error while'
             ' running command.\nCommand: -\nExit code: -\nReason: -\n'
-            'Stdout: Invalid token SomeToken\nStderr: -',
+            'Stdout: Invalid token REDACTED\nStderr: -',
             str(context_manager.exception))
 
     @mock.patch('%s.subp.subp' % MPATH)
     def test_configure_ua_attach_with_token(self, m_subp):
         """When token is provided, attach the machine to ua using the token."""
         configure_ua(token='SomeToken')
-        m_subp.assert_called_once_with(['ua', 'attach', 'SomeToken'])
+        m_subp.assert_called_once_with(['ua', 'attach', 'SomeToken'], logstring=["ua", "attach", "REDACTED"],)
         self.assertEqual(
-            'DEBUG: Attaching to Ubuntu Advantage. ua attach SomeToken\n',
+            'DEBUG: Attaching to Ubuntu Advantage. ua attach REDACTED\n',
             self.logs.getvalue())
 
     @mock.patch('%s.subp.subp' % MPATH)
     def test_configure_ua_attach_on_service_error(self, m_subp):
         """all services should be enabled and then any failures raised"""
 
-        def fake_subp(cmd, capture=None):
+        def fake_subp(cmd, capture=None, logstring=None):
             fail_cmds = [['ua', 'enable', svc] for svc in ['esm', 'cc']]
             if cmd in fail_cmds and capture:
                 svc = cmd[-1]
@@ -65,7 +65,7 @@ class TestConfigureUA(CiTestCase):
             configure_ua(token='SomeToken', enable=['esm', 'cc', 'fips'])
         self.assertEqual(
             m_subp.call_args_list,
-            [mock.call(['ua', 'attach', 'SomeToken']),
+            [mock.call(['ua', 'attach', 'SomeToken'], logstring=["ua", "attach", "REDACTED"],),
              mock.call(['ua', 'enable', 'esm'], capture=True),
              mock.call(['ua', 'enable', 'cc'], capture=True),
              mock.call(['ua', 'enable', 'fips'], capture=True)])
@@ -87,9 +87,9 @@ class TestConfigureUA(CiTestCase):
     def test_configure_ua_attach_with_empty_services(self, m_subp):
         """When services is an empty list, do not auto-enable attach."""
         configure_ua(token='SomeToken', enable=[])
-        m_subp.assert_called_once_with(['ua', 'attach', 'SomeToken'])
+        m_subp.assert_called_once_with(['ua', 'attach', 'SomeToken'], logstring=["ua", "attach", "REDACTED"],)
         self.assertEqual(
-            'DEBUG: Attaching to Ubuntu Advantage. ua attach SomeToken\n',
+            'DEBUG: Attaching to Ubuntu Advantage. ua attach REDACTED\n',
             self.logs.getvalue())
 
     @mock.patch('%s.subp.subp' % MPATH)
@@ -98,10 +98,10 @@ class TestConfigureUA(CiTestCase):
         configure_ua(token='SomeToken', enable=['fips'])
         self.assertEqual(
             m_subp.call_args_list,
-            [mock.call(['ua', 'attach', 'SomeToken']),
+            [mock.call(['ua', 'attach', 'SomeToken'], logstring=["ua", "attach", "REDACTED"],),
              mock.call(['ua', 'enable', 'fips'], capture=True)])
         self.assertEqual(
-            'DEBUG: Attaching to Ubuntu Advantage. ua attach SomeToken\n',
+            'DEBUG: Attaching to Ubuntu Advantage. ua attach REDACTED\n',
             self.logs.getvalue())
 
     @mock.patch('%s.maybe_install_ua_tools' % MPATH, mock.MagicMock())
@@ -111,12 +111,12 @@ class TestConfigureUA(CiTestCase):
         configure_ua(token='SomeToken', enable='fips')
         self.assertEqual(
             m_subp.call_args_list,
-            [mock.call(['ua', 'attach', 'SomeToken']),
+            [mock.call(['ua', 'attach', 'SomeToken'], logstring=["ua", "attach", "REDACTED"],),
              mock.call(['ua', 'enable', 'fips'], capture=True)])
         self.assertEqual(
             'WARNING: ubuntu_advantage: enable should be a list, not a'
             ' string; treating as a single enable\n'
-            'DEBUG: Attaching to Ubuntu Advantage. ua attach SomeToken\n',
+            'DEBUG: Attaching to Ubuntu Advantage. ua attach REDACTED\n',
             self.logs.getvalue())
 
     @mock.patch('%s.subp.subp' % MPATH)
@@ -125,11 +125,11 @@ class TestConfigureUA(CiTestCase):
         configure_ua(token='SomeToken', enable={'deffo': 'wont work'})
         self.assertEqual(
             m_subp.call_args_list,
-            [mock.call(['ua', 'attach', 'SomeToken'])])
+            [mock.call(['ua', 'attach', 'SomeToken'], logstring=["ua", "attach", "REDACTED"],)])
         self.assertEqual(
             'WARNING: ubuntu_advantage: enable should be a list, not a'
             ' dict; skipping enabling services\n'
-            'DEBUG: Attaching to Ubuntu Advantage. ua attach SomeToken\n',
+            'DEBUG: Attaching to Ubuntu Advantage. ua attach REDACTED\n',
             self.logs.getvalue())
 
 
-- 
2.33.0


