Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

validate_hostname_or_raise_error: Improve hostname validation.

Mateusz Mandera99ea0255da6d
diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py
index 8e137674cad..4dccd7ba266 100644
--- a/zerver/tests/test_push_notifications.py
+++ b/zerver/tests/test_push_notifications.py
@@ -5207,6 +5207,12 @@ class PushBouncerSignupTest(ZulipTestCase):
result = self.client_post("/api/v1/remotes/server/register", request)
self.assert_json_error(result, "invalid-host is not a valid hostname")
+ request["hostname"] = "example.com/path"
+ result = self.client_post("/api/v1/remotes/server/register", request)
+ self.assert_json_error(
+ result, "example.com/path contains invalid components (e.g., path, query, fragment)."
+ )
+
def test_push_signup_invalid_zulip_org_id(self) -> None:
zulip_org_id = "x" * RemoteZulipServer.UUID_LENGTH
zulip_org_key = get_random_string(64)
diff --git a/zilencer/views.py b/zilencer/views.py
index 1f6578b38ec..5448f1bd91c 100644
--- a/zilencer/views.py
+++ b/zilencer/views.py
@@ -3,6 +3,7 @@ from collections import Counter
from datetime import datetime, timedelta, timezone
from email.headerregistry import Address
from typing import Annotated, Any, TypedDict, TypeVar
+from urllib.parse import urlsplit
from uuid import UUID
import orjson
@@ -122,8 +123,24 @@ def deactivate_remote_server(
def validate_hostname_or_raise_error(hostname: str) -> None:
+ """
+ Validate that the argument is a valid hostname to be registered
+ with the bouncer.
+
+ Note: The hostname is allowed to contain a port number, as some
+ registration do take this form and without the port we wouldn't
+ actually know how to make requests to the server.
+ """
try:
# TODO: Ideally we'd not abuse the URL validator this way
+ parsed = urlsplit(f"http://{hostname}")
+
+ if parsed.path or parsed.query or parsed.fragment:
+ raise JsonableError(
+ _("{hostname} contains invalid components (e.g., path, query, fragment).").format(
+ hostname=hostname
+ )
+ )
url_validator = URLValidator()
url_validator("http://" + hostname)
except ValidationError: