Skip to content

Commit e7b410e

Browse files
author
luigi liu
authored
Redact private keys in non-UTF-8 bytes and bytearrays
1 parent a799a92 commit e7b410e

2 files changed

Lines changed: 14 additions & 8 deletions

File tree

‎awscli/redaction.py‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -49,17 +49,17 @@ def replacement(match):
4949
def redact(value):
5050
"""Return ``value`` with every registered pattern redacted.
5151
52-
Strings and UTF-8 encoded bytes are redacted, including those nested in
53-
lists, tuples, and mappings. Other values are returned unchanged.
52+
Strings and bytes are redacted, including those nested in lists, tuples,
53+
and mappings. Bytes are matched as UTF-8, and any bytes that aren't valid
54+
UTF-8 are preserved. Other values are returned unchanged.
5455
"""
5556
if isinstance(value, str):
5657
return _redact_text(value)
57-
if isinstance(value, bytes):
58-
try:
59-
text = value.decode('utf-8')
60-
except UnicodeDecodeError:
61-
return value
62-
return _redact_text(text).encode('utf-8')
58+
if isinstance(value, (bytes, bytearray)):
59+
# surrogateescape round-trips bytes that aren't valid UTF-8.
60+
text = value.decode('utf-8', 'surrogateescape')
61+
redacted = _redact_text(text).encode('utf-8', 'surrogateescape')
62+
return type(value)(redacted)
6363
if isinstance(value, (list, tuple)):
6464
items = [redact(item) for item in value]
6565
return items if isinstance(value, list) else tuple(items)

‎tests/unit/test_redaction.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,12 @@ def test_redacts_truncated_base64_private_key():
105105
)
106106

107107

108+
@pytest.mark.parametrize('cls', [bytes, bytearray])
109+
def test_redacts_non_utf8_bytes(cls):
110+
value = cls(b'\xff\xfe' + KEY_PEM.encode('ascii') + b'\x80')
111+
assert redact(value) == cls(b'\xff\xfe' + REDACTED.encode() + b'\n\x80')
112+
113+
108114
def test_redacts_base64_private_key_bytes():
109115
value = b'{"PrivateKey": "' + _b64(KEY_PEM).encode('ascii') + b'"}'
110116
assert redact(value) == b'{"PrivateKey": "' + REDACTED.encode() + b'"}'

0 commit comments

Comments
 (0)