From 08cc6edc642af3518905343b923dd9a030d131ee Mon Sep 17 00:00:00 2001 From: Sven Wegener Date: Wed, 9 Dec 2020 09:46:32 +0100 Subject: [PATCH] vault: Read stdin data as binary on python3 (#52229) On python3 sys.stdin is an encoded file object that does not support reading raw binary data. Use the supplied buffer object to do so. Signed-off-by: Sven Wegener Co-authored-by: Sven Wegener --- .../52229-vault-python3-binary-stdin.yml | 2 ++ lib/ansible/parsing/vault/__init__.py | 5 ++++- test/units/parsing/vault/test_vault_editor.py | 17 +++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 changelogs/fragments/52229-vault-python3-binary-stdin.yml diff --git a/changelogs/fragments/52229-vault-python3-binary-stdin.yml b/changelogs/fragments/52229-vault-python3-binary-stdin.yml new file mode 100644 index 00000000000..c622ee15235 --- /dev/null +++ b/changelogs/fragments/52229-vault-python3-binary-stdin.yml @@ -0,0 +1,2 @@ +bugfixes: + - vault - Support reading raw binary data from stdin under python3 diff --git a/lib/ansible/parsing/vault/__init__.py b/lib/ansible/parsing/vault/__init__.py index 1360630988a..c64422ecc0d 100644 --- a/lib/ansible/parsing/vault/__init__.py +++ b/lib/ansible/parsing/vault/__init__.py @@ -1038,7 +1038,10 @@ class VaultEditor: try: if filename == '-': - data = sys.stdin.read() + if PY3: + data = sys.stdin.buffer.read() + else: + data = sys.stdin.read() else: with open(filename, "rb") as fh: data = fh.read() diff --git a/test/units/parsing/vault/test_vault_editor.py b/test/units/parsing/vault/test_vault_editor.py index 8aa9b37c31a..5601c49ca7c 100644 --- a/test/units/parsing/vault/test_vault_editor.py +++ b/test/units/parsing/vault/test_vault_editor.py @@ -22,6 +22,7 @@ __metaclass__ = type import os import tempfile +from io import BytesIO, StringIO import pytest @@ -32,6 +33,7 @@ from ansible import errors from ansible.parsing import vault from ansible.parsing.vault import VaultLib, VaultEditor, match_encrypt_secret +from ansible.module_utils.six import PY3 from ansible.module_utils._text import to_bytes, to_text from units.mock.vault_helper import TextVaultSecret @@ -113,6 +115,21 @@ class TestVaultEditor(unittest.TestCase): self.assertNotEqual(src_contents, b_ciphertext) + def test_stdin_binary(self): + stdin_data = '\0' + + if PY3: + fake_stream = StringIO(stdin_data) + fake_stream.buffer = BytesIO(to_bytes(stdin_data)) + else: + fake_stream = BytesIO(to_bytes(stdin_data)) + + with patch('sys.stdin', fake_stream): + ve = self._vault_editor() + data = ve.read_data('-') + + self.assertEqual(data, b'\0') + @patch('ansible.parsing.vault.subprocess.call') def test_edit_file_helper_call_exception(self, mock_sp_call): self._test_dir = self._create_test_dir()