Skip to content

Commit

Permalink
Better exception for bad URL parse (#2415)
Browse files Browse the repository at this point in the history
  • Loading branch information
ahopkins authored Mar 24, 2022
1 parent 0309874 commit 0cb342a
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
4 changes: 4 additions & 0 deletions sanic/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ class InvalidUsage(SanicException):
quiet = True


class BadURL(InvalidUsage):
...


class MethodNotSupported(SanicException):
"""
**Status**: 405 Method Not Allowed
Expand Down
9 changes: 6 additions & 3 deletions sanic/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,11 @@
from urllib.parse import parse_qs, parse_qsl, unquote, urlunparse

from httptools import parse_url # type: ignore
from httptools.parser.errors import HttpParserInvalidURLError # type: ignore

from sanic.compat import CancelledErrors, Header
from sanic.constants import DEFAULT_HTTP_CONTENT_TYPE
from sanic.exceptions import InvalidUsage, ServerError
from sanic.exceptions import BadURL, InvalidUsage, ServerError
from sanic.headers import (
AcceptContainer,
Options,
Expand Down Expand Up @@ -129,8 +130,10 @@ def __init__(
):

self.raw_url = url_bytes
# TODO: Content-Encoding detection
self._parsed_url = parse_url(url_bytes)
try:
self._parsed_url = parse_url(url_bytes)
except HttpParserInvalidURLError:
raise BadURL(f"Bad URL: {url_bytes.decode()}")
self._id: Optional[Union[uuid.UUID, str, int]] = None
self._name: Optional[str] = None
self.app = app
Expand Down
15 changes: 15 additions & 0 deletions tests/test_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pytest

from sanic import Sanic, response
from sanic.exceptions import BadURL
from sanic.request import Request, uuid
from sanic.server import HttpProtocol

Expand Down Expand Up @@ -176,3 +177,17 @@ async def get(request):
"text/x-dvi; q=0.8",
"text/plain; q=0.5",
]


def test_bad_url_parse():
message = "Bad URL: my.redacted-domain.com:443"
with pytest.raises(BadURL, match=message):
Request(
b"my.redacted-domain.com:443",
Mock(),
Mock(),
Mock(),
Mock(),
Mock(),
Mock(),
)

0 comments on commit 0cb342a

Please sign in to comment.