Skip to content

Instantly share code, notes, and snippets.

@scottzach1
Last active June 25, 2024 22:11
Show Gist options
  • Save scottzach1/123d0d405ce8e32eaf7dba2a83349b09 to your computer and use it in GitHub Desktop.
Save scottzach1/123d0d405ce8e32eaf7dba2a83349b09 to your computer and use it in GitHub Desktop.
A minimal wrapper to redact credentials in sys.stdout and sys.stderr
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