Keep query-string tokens out of the uvicorn, nginx and Traefik access logs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013GAeg4Jo6xjZzjwy9QDWMQ
This commit is contained in:
@@ -4,6 +4,7 @@ import hashlib
|
||||
import inspect
|
||||
import ipaddress
|
||||
import logging
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
from collections.abc import AsyncIterator, Callable, Coroutine
|
||||
@@ -58,6 +59,30 @@ from fluksio.flow.workers import PythonWorkerPool
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: A credential in a query string: the live socket's and a worker's `?token=`.
|
||||
_TOKEN_IN_QUERY = re.compile(r"([?&][\w-]*token=)[^&\s]+")
|
||||
|
||||
|
||||
class _RedactTokens(logging.Filter):
|
||||
"""Keep query-string credentials out of uvicorn's request lines.
|
||||
|
||||
uvicorn logs each request and websocket handshake with its query string,
|
||||
and the live socket and a worker's attach carry their token there.
|
||||
"""
|
||||
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
if isinstance(record.args, tuple):
|
||||
record.args = tuple(
|
||||
_TOKEN_IN_QUERY.sub(r"\1***", arg) if isinstance(arg, str) else arg
|
||||
for arg in record.args
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
# The handshake lines go to `uvicorn.error`, the request lines to `uvicorn.access`.
|
||||
for _name in ("uvicorn.access", "uvicorn.error"):
|
||||
logging.getLogger(_name).addFilter(_RedactTokens())
|
||||
|
||||
|
||||
def custom_generate_unique_id(route: APIRoute) -> str:
|
||||
return f"{route.tags[0]}-{route.name}"
|
||||
|
||||
Reference in New Issue
Block a user