Last active
June 25, 2024 22:11
-
-
Save scottzach1/123d0d405ce8e32eaf7dba2a83349b09 to your computer and use it in GitHub Desktop.
A minimal wrapper to redact credentials in sys.stdout and sys.stderr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io | |
import sys | |
class RedactIO(io.IOBase): | |
""" | |
A minimal io wrapper to redact sensitive data. | |
""" | |
def __init__(self, buffer, redactions: dict[str, str], **kwargs) -> None: | |
self.buffer = buffer | |
self.redactions = redactions | |
super().__init__(**kwargs) | |
def write(self, __s): | |
for k, v in self.redactions.items(): | |
__s = __s.replace(v, f"{{{k}}}") | |
self.buffer.write(__s) | |
if __name__ == "__main__": | |
SENSITIVE_DATA = {"PASSWORD": "Password123"} | |
sys.stdout = RedactIO(sys.stdout, SENSITIVE_DATA) | |
sys.stderr = RedactIO(sys.stderr, SENSITIVE_DATA) | |
print(SENSITIVE_DATA) # [stdout]: `{'PASSWORD': '{{PASSWORD}}'}` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment