Answer security round 1: 0 🔴, 0 🟡 (0 misread); follow no redirect, so the token reaches only the server named
CI / tests (pull_request) Successful in 2m22s

This commit is contained in:
2026-11-11 22:25:34 +01:00
parent 5588270e43
commit f10170bf8b
2 changed files with 20 additions and 2 deletions
+13 -2
View File
@@ -17,6 +17,16 @@ TIMEOUT = 10
Http = typing.Callable[[str, str, str, object], object]
class NoRedirect(urllib.request.HTTPRedirectHandler):
"""Follows no redirect: urllib resends the token to the new location, even one off https, and Mattermost's API answers without one."""
def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None:
return None
OPENER = urllib.request.build_opener(NoRedirect)
@dataclasses.dataclass(frozen=True)
class Config:
url: str
@@ -89,10 +99,11 @@ def http_json(method: str, url: str, token: str, body: object) -> object:
data = None if body is None else json.dumps(body).encode()
request = urllib.request.Request(url, data, {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, method=method)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
with OPENER.open(request, timeout=TIMEOUT) as response:
raw = response.read()
except urllib.error.HTTPError as failure:
return Failure(f"{request_name} answered {failure.code}: {error_message(failure.read()) or failure.reason}")
with failure:
return Failure(f"{request_name} answered {failure.code}: {error_message(failure.read()) or failure.reason}")
except (OSError, ValueError) as failure:
server = urllib.parse.urlunsplit(urllib.parse.urlsplit(url)[:2] + ("", "", ""))
return Failure(f"cannot reach {server}: {getattr(failure, 'reason', failure)}")
+7
View File
@@ -114,6 +114,8 @@ class Recorded(http.server.BaseHTTPRequestHandler):
self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined]
status, body = self.server.script.pop(0) # type: ignore[attr-defined]
self.send_response(status)
if 300 <= status < 400:
self.send_header("Location", "/elsewhere")
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
@@ -143,6 +145,11 @@ class HttpJson(unittest.TestCase):
base = self.serve((401, b'{"message": "Invalid or expired session, please login again."}'))
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "bad", None), Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again."))
def test_follows_no_redirect_so_the_token_goes_only_to_the_server_named(self):
base = self.serve((302, b"{}"))
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 302: Found"))
self.assertEqual(len(self.server.got), 1) # type: ignore[attr-defined]
def test_fails_on_an_answer_that_is_not_json(self):
base = self.serve((200, b"<html>"))
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered with something other than JSON"))