Skip to content

Commit

Permalink
extend filtering to cover tuple and dict arguments for logging
Browse files Browse the repository at this point in the history
  • Loading branch information
staaldraad committed Oct 2, 2024
1 parent dd4cdc1 commit ffe8003
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
2 changes: 1 addition & 1 deletion realtime/_async/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ async def connect(self) -> None:

while retries < self.max_retries:
try:
self.ws_connection = await websockets.connect(self.url)
self.ws_connection = await websockets.connect(self.url, logger=logger)
if self.ws_connection.open:
logger.info("Connection was successful")
return await self._on_connect()
Expand Down
27 changes: 23 additions & 4 deletions realtime/logging_util.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import copy
import logging
import re

Expand All @@ -8,17 +9,35 @@
redact = r"(eyJh[-_\w]*\.)([-_\w]*)\."


def gred(g):
"""Redact the payload of the JWT, keeping the header and signature"""
return f"{g.group(1)}REDACTED." if len(g.groups()) > 1 else g


class TokenMaskingFilter(logging.Filter):
"""Mask access_tokens in logs"""

def filter(self, record):
record.msg = self.sanitize_line(record.msg)
record.args = self.sanitize_args(record.args)
return True

@staticmethod
def sanitize_line(line):
def gred(g):
"""Redact the payload of the JWT, keeping the header and signature"""
return f"{g.group(1)}REDACTED." if len(g.groups()) > 1 else g
def sanitize_args(d):
if isinstance(d, dict):
d = d.copy() # so we don't overwrite anything
for k, v in d.items():
d[k] = self.sanitize_line(v)
elif isinstance(d, tuple):
# need a deepcopy of tuple turned to a list, as to not change the original values
# otherwise we end up changing the items at the original memory location of the passed in tuple
y = copy.deepcopy(list(d))
for x, value in enumerate(y):
if isinstance(value, str):
y[x] = re.sub(redact, gred, value)
return tuple(y) # convert the list back to a tuple
return d

@staticmethod
def sanitize_line(line):
return re.sub(redact, gred, line)

0 comments on commit ffe8003

Please sign in to comment.