Skip to content

Commit 1613bed

Browse files
Stop following redirects, so the key never goes to the host they name (#36)
urlopen follows 301/302/303 by re-sending the Authorization header to the Location target as an empty GET. Reports now go through an opener whose redirect handler declines every redirect, so the 3xx reaches the existing non-201 DEBUG line with its own status, as trace-client-java does. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 22199ca commit 1613bed

3 files changed

Lines changed: 47 additions & 2 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,10 @@ key or value is `None` is left out, and every other key and value is sent as a
159159
string. An event with a blank `name` is not sent at all. The server assigns the
160160
timestamp. A `201` is success; anything else is logged at `DEBUG` and dropped.
161161

162+
Redirects are not followed: a `3xx` answer is logged at `DEBUG` with its own
163+
status and the report is dropped, so the key is never re-sent to whatever host
164+
a `Location` header names. Point `base_url` at the server's final address.
165+
162166
The `User-Agent` is `trace-client-python/<client version> (<application>)`. Any
163167
character of the application's name that a header cannot carry (outside printable
164168
Latin-1) becomes `?` there; `application` in the body is always the exact name.

‎tests/test_trace_client.py‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from unittest import mock
2020

2121
from trace_client import MAX_TAG_LENGTH, MAX_TAGS, TraceClient, __version__, environment_opts_out
22+
from trace_client import trace_client as trace_client_module
2223

2324
_ENV_VARS = ("TRACE_USAGE_REPORTING", "DO_NOT_TRACK")
2425

@@ -27,6 +28,7 @@ class _Capture:
2728
def __init__(self):
2829
self.requests = []
2930
self.reply_status = 201
31+
self.location = None # sent as a Location header when set
3032
self.arrived = threading.Event()
3133
self.release = threading.Event()
3234
self.release.set() # by default answer at once
@@ -39,17 +41,22 @@ def do_POST(self):
3941
body = self.rfile.read(length)
4042
capture.release.wait(10)
4143
capture.requests.append({
44+
"method": self.command,
4245
"path": self.path,
4346
"authorization": self.headers.get("Authorization"),
4447
"content_type": self.headers.get("Content-Type"),
4548
"user_agent": self.headers.get("User-Agent"),
4649
"body": body.decode("utf-8"),
4750
})
4851
self.send_response(capture.reply_status)
52+
if capture.location is not None:
53+
self.send_header("Location", capture.location)
4954
self.send_header("Content-Length", "0")
5055
self.end_headers()
5156
capture.arrived.set()
5257

58+
do_GET = do_POST # a followed 301/302/303 arrives as a GET
59+
5360
def log_message(self, *args): # keep test output quiet
5461
pass
5562

@@ -198,6 +205,25 @@ def test_a_success_status_other_than_201_is_logged_as_not_delivered(self):
198205
"only a 201 is success: %s" % [r.getMessage() for r in self.log])
199206
self.assertTrue(all(r.levelno == logging.DEBUG for r in self.log))
200207

208+
def test_a_redirect_is_logged_and_dropped_never_followed_with_the_key(self):
209+
target = _Capture()
210+
target_server = _server(target)
211+
self.addCleanup(target_server.shutdown)
212+
# Another port and another host name: what a redirect elsewhere looks like.
213+
self.capture.location = "http://localhost:%d/elsewhere" % target_server.server_address[1]
214+
for status in (301, 302, 303, 307, 308):
215+
self.log.clear()
216+
self.capture.reply_status = status
217+
client = TraceClient(self.base_url, "MyGame", "1.2.3", key="secret-key")
218+
client.report("startup")
219+
client.close() # joins the sender, so its log line is written by now
220+
self.assertEqual([], target.requests,
221+
"a %d must not carry the key to the host it names" % status)
222+
self.assertTrue(any("answered %d" % status in r.getMessage() for r in self.log),
223+
"the log names the redirect that lost the event: %s"
224+
% [r.getMessage() for r in self.log])
225+
self.assertTrue(all(r.levelno == logging.DEBUG for r in self.log))
226+
201227
def test_an_error_answer_whose_body_cannot_be_read_still_logs_its_status(self):
202228
class Unreadable(urllib.error.HTTPError):
203229
def read(self, *args):
@@ -206,7 +232,7 @@ def read(self, *args):
206232
answer = Unreadable(self.base_url + "/api/metrics", 503, "Service Unavailable", {}, None)
207233
crashes = []
208234
with mock.patch.object(threading, "excepthook", crashes.append), \
209-
mock.patch.object(urllib.request, "urlopen", side_effect=answer):
235+
mock.patch.object(trace_client_module._OPENER, "open", side_effect=answer):
210236
client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k")
211237
client.report("startup") # must not raise
212238
client.close()

‎trace_client/trace_client.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,21 @@
5757
_NOT_IN_A_HEADER = re.compile(r"[^\x20-\x7e\xa0-\xff]")
5858

5959

60+
class _RedirectsNotFollowed(urllib.request.HTTPRedirectHandler):
61+
"""Declines every redirect, so the redirect itself is the answer. Following
62+
one would re-send the key to whatever host ``Location`` names, and a 301,
63+
302 or 303 would turn the POST into an empty GET that loses the event
64+
anyway. trace-client-java does not follow redirects either."""
65+
66+
def redirect_request(self, req, fp, code, msg, headers, newurl):
67+
return None
68+
69+
70+
# Every report goes through this opener rather than urlopen: urlopen follows
71+
# redirects, and install_opener would change the host program's urlopen too.
72+
_OPENER = urllib.request.build_opener(_RedirectsNotFollowed)
73+
74+
6075
def environment_opts_out(environ: Optional[Mapping[str, str]] = None) -> bool:
6176
"""Whether the environment asks for usage reporting to be off, via
6277
``TRACE_USAGE_REPORTING=off`` or ``DO_NOT_TRACK=1``. Only the listed
@@ -322,7 +337,7 @@ def _send(self, body: bytes) -> None:
322337
"Authorization": "Bearer " + self._key,
323338
"User-Agent": _user_agent(self._application),
324339
})
325-
with urllib.request.urlopen(request, timeout=self.TIMEOUT_SECONDS) as response:
340+
with _OPENER.open(request, timeout=self.TIMEOUT_SECONDS) as response:
326341
status = response.status
327342
response.read()
328343
except urllib.error.HTTPError as answered:

0 commit comments

Comments
 (0)