Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unquote username and password in DatabaseURL #247 #248

Merged
merged 7 commits into from
Oct 19, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 25 additions & 7 deletions databases/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import sys
import typing
from types import TracebackType
from urllib.parse import SplitResult, parse_qsl, urlsplit
from urllib.parse import SplitResult, parse_qsl, urlsplit, unquote

from sqlalchemy import text
from sqlalchemy.sql import ClauseElement
Expand Down Expand Up @@ -389,7 +389,12 @@ def __bool__(self) -> bool:

class DatabaseURL:
def __init__(self, url: typing.Union[str, "DatabaseURL"]):
self._url = str(url)
if isinstance(url, DatabaseURL):
self._url = url._url
elif isinstance(url, str):
self._url = url
else:
raise TypeError(f"Invalid type for DatabaseURL. Expected str or DatabaseURL, got {type(url)}")

@property
def components(self) -> SplitResult:
Expand All @@ -411,13 +416,26 @@ def driver(self) -> str:
return ""
return self.components.scheme.split("+", 1)[1]

@property
def userinfo(self) -> typing.Optional[bytes]:
if self.components.username:
info = self.components.username
if self.components.password:
info += ":" + self.components.password
return info.encode("ascii")
return None

@property
def username(self) -> typing.Optional[str]:
return self.components.username
if self.components.username is None:
return None
return unquote(self.components.username)

@property
def password(self) -> typing.Optional[str]:
return self.components.password
if self.components.password is None:
return None
return unquote(self.components.password)

@property
def hostname(self) -> typing.Optional[str]:
Expand All @@ -436,7 +454,7 @@ def database(self) -> str:
path = self.components.path
if path.startswith("/"):
path = path[1:]
return path
return unquote(path)

@property
def options(self) -> dict:
Expand All @@ -453,8 +471,8 @@ def replace(self, **kwargs: typing.Any) -> "DatabaseURL":
):
hostname = kwargs.pop("hostname", self.hostname)
port = kwargs.pop("port", self.port)
username = kwargs.pop("username", self.username)
password = kwargs.pop("password", self.password)
username = kwargs.pop("username", self.components.username)
password = kwargs.pop("password", self.components.password)

netloc = hostname
if port is not None:
Expand Down
17 changes: 17 additions & 0 deletions tests/test_database_url.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from databases import DatabaseURL
from urllib.parse import quote


def test_database_url_repr():
Expand All @@ -11,6 +12,9 @@ def test_database_url_repr():
u = DatabaseURL("postgresql://username:password@localhost/name")
assert repr(u) == "DatabaseURL('postgresql://username:********@localhost/name')"

u = DatabaseURL(f"postgresql://username:{quote('[password')}@localhost/name")
assert repr(u) == "DatabaseURL('postgresql://username:********@localhost/name')"


def test_database_url_properties():
u = DatabaseURL("postgresql+asyncpg://username:password@localhost:123/mydatabase")
Expand All @@ -23,6 +27,19 @@ def test_database_url_properties():
assert u.database == "mydatabase"


def test_database_url_escape():
u = DatabaseURL(f"postgresql://username:{quote('[password')}@localhost/mydatabase")
assert u.username == "username"
assert u.password == "[password"
assert u.userinfo == f"username:{quote('[password')}".encode("ascii")

u2 = DatabaseURL(u)
assert u2.password == "[password"

u3 = DatabaseURL(str(u))
assert u3.password == "[password"


def test_database_url_options():
u = DatabaseURL("postgresql://localhost/mydatabase?pool_size=20&ssl=true")
assert u.options == {"pool_size": "20", "ssl": "true"}
Expand Down