Skip to content

Commit

Permalink
refactor: move password padding logic to a staticmethod
Browse files Browse the repository at this point in the history
  • Loading branch information
waketzheng committed Dec 27, 2024
1 parent 660dfed commit 6cb4a8a
Showing 1 changed file with 20 additions and 19 deletions.
39 changes: 20 additions & 19 deletions tortoise/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from inspect import isclass
from types import ModuleType
from typing import Any, Callable, Coroutine, Iterable, Type, cast
from urllib.parse import quote_plus

from pypika import Query, Table

Expand Down Expand Up @@ -500,24 +499,7 @@ async def init(
cls.table_name_generator = table_name_generator

if logger.isEnabledFor(logging.DEBUG):
# Mask passwords in logs output
passwords = []
for name, info in connections_config.items():
if isinstance(info, str):
info = expand_db_url(info)
if password := info.get("credentials", {}).get("password"):
passwords.append(password)

str_connection_config = str(connections_config)
for password in passwords:
# Show one third of the password at beginning (may be better for debugging purposes)
star_passwd = f"{password[0:len(password) // 3]}***"
if (quoted_passwd := quote_plus(password)) in str_connection_config:
str_connection_config = str_connection_config.replace(
quoted_passwd, star_passwd
)
else:
str_connection_config = str_connection_config.replace(password, star_passwd)
str_connection_config = cls.star_password(connections_config)
logger.debug(
"Tortoise-ORM startup\n connections: %s\n apps: %s",
str_connection_config,
Expand All @@ -531,6 +513,25 @@ async def init(

cls._inited = True

@staticmethod
def star_password(connections_config) -> str:
# Mask passwords to hide sensitive information in logs output
passwords = []
for name, info in connections_config.items():
if isinstance(info, str):
info = expand_db_url(info)
if password := info.get("credentials", {}).get("password"):
passwords.append(password)

str_connection_config = str(connections_config)
for password in passwords:
str_connection_config = str_connection_config.replace(
password,
# Show one third of the password at beginning (may be better for debugging purposes)
f"{password[0:len(password) // 3]}***",
)
return str_connection_config

@classmethod
def _init_routers(cls, routers: list[str | type] | None = None) -> None:
from tortoise.router import router
Expand Down

0 comments on commit 6cb4a8a

Please sign in to comment.