Skip to content

Commit

Permalink
Added a field_validator to the config.py that will url encode the pos…
Browse files Browse the repository at this point in the history
…tgres connection string

to translate special characters to url encoding that will not cause the pydantic test to fail.

Added a pytest function to test the encoding
  • Loading branch information
jcadam14 committed Jan 2, 2024
1 parent 219a8ae commit bb85f6b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import os
import logging
import re
from urllib import parse
from typing import Dict, Any

from pydantic import TypeAdapter
from pydantic import TypeAdapter, field_validator, FieldValidationInfo
from pydantic.networks import HttpUrl, PostgresDsn
from pydantic.types import SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
Expand Down Expand Up @@ -31,6 +34,18 @@ def __init__(self, **data):
super().__init__(**data)
self.set_jwt_opts()

@field_validator("inst_conn", mode="before")
@classmethod
def encode_db_password(cls, postgres_dsn, info: FieldValidationInfo) -> Any:
log = logging.getLogger()
pwd = re.search(".*:.*:(.*)@", postgres_dsn)
if pwd:
pwd_str = pwd.group(1)
encoded_password = parse.quote(pwd_str, safe="")
return postgres_dsn.replace(pwd_str, encoded_password)
else:
log.error(f"Postgres DSN did not contain a properly formatted URL: {postgres_dsn}")

def set_jwt_opts(self) -> None:
"""
Converts `jwt_opts_` prefixed settings, and env vars into JWT options dictionary.
Expand Down
6 changes: 6 additions & 0 deletions tests/app/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@
from config import Settings


def test_psql_password_encoding():
mock_config = {"inst_conn": "postgresql+asyncpg://test:\z9-/tgb76@test/test"}
settings = Settings(**mock_config)
assert str(settings.inst_conn) == "postgresql+asyncpg://test:%5Cz9-%2Ftgb76@test/test"


def test_jwt_opts_valid_values():
mock_config = {
"jwt_opts_test1": "true",
Expand Down

0 comments on commit bb85f6b

Please sign in to comment.