From de597a636b9e41b9892b80363dd0126a464af6a7 Mon Sep 17 00:00:00 2001 From: CHAITHANYA <121756953+Chaithanya123123@users.noreply.github.com> Date: Sat, 5 Dec 2026 17:18:48 +0530 Subject: [PATCH 1/3] fix: start download GET at the Databus URL so downloads are counted (#135) The client sent its GET straight to the redirect target found with HEAD, so Databus, which counts only file GET requests, never registered downloads. The GET now starts at the original URL and follows redirects by hand, sending the Databus API key only to the host that requires it. Co-Authored-By: Claude Opus 5.5 --- databusclient/api/download.py | 48 ++++++++++++++++++++--- tests/test_download_redirects.py | 66 +++++++++++++++++++++++++++++++- 2 files changed, 107 insertions(+), 7 deletions(-) diff --git a/databusclient/api/download.py b/databusclient/api/download.py index f2aead78..fbb477f3 100644 --- a/databusclient/api/download.py +++ b/databusclient/api/download.py @@ -427,6 +427,38 @@ def _resolve_checksums_for_urls(file_urls: List[str], databus_key: str | None) - return checksums +_REDIRECT_STATUSES = (301, 302, 303, 307, 308) +_MAX_REDIRECTS = 10 + + +def _get_with_scoped_credentials(url, headers, credentials, credential_host): + """GET ``url``, following redirects so credentials reach only ``credential_host``. + + The request starts at ``url`` itself, so a Databus file URL registers the + download before redirecting to the server that stores the file (Databus + counts file GET requests, not HEAD requests). Redirects are followed here + rather than by requests because requests drops ``Authorization`` on a + cross-host redirect but forwards custom headers such as ``X-API-KEY``. + + Returns the final response and its URL. + """ + for _ in range(_MAX_REDIRECTS + 1): + hop_headers = dict(headers) + if credentials and urlparse(url).hostname == credential_host: + hop_headers.update(credentials) + response = requests.get( + url, headers=hop_headers, stream=True, allow_redirects=False, timeout=30 + ) + location = response.headers.get("Location") + if response.status_code not in _REDIRECT_STATUSES or not location: + return response, url + response.close() + url = urljoin(url, location) + raise requests.exceptions.TooManyRedirects( + f"Exceeded {_MAX_REDIRECTS} redirects while downloading {url}" + ) + + def _download_file( url, localDir, @@ -480,6 +512,8 @@ def _download_file( # --- 1. Get redirect URL by requesting HEAD --- headers = {"User-Agent": DEFAULT_USER_AGENT if user_agent is None else user_agent} + # Credentials go only to the download host found below, never to other hops. + credentials = {} # --- 1a. public databus --- response = requests.head(url, headers=headers, timeout=30, allow_redirects=False) @@ -518,16 +552,18 @@ def _download_file( raise DownloadAuthError( "Databus API key not given for protected download" ) - headers["X-API-KEY"] = databus_key - response = requests.head(url, headers=headers, timeout=30) + credentials["X-API-KEY"] = databus_key + response = requests.head( + url, headers={**headers, **credentials}, timeout=30 + ) - # --- 2. Try direct GET to redirected URL --- + # --- 2. GET from the original URL so Databus counts the download --- + # Databus redirects the GET to the file's source server; the HEAD requests + # above only located that server and are not counted. headers["Accept-Encoding"] = ( "identity" # disable gzip to get correct content-length ) - response = requests.get( - url, headers=headers, stream=True, allow_redirects=True, timeout=30 - ) + response, _ = _get_with_scoped_credentials(source_url, headers, credentials, host) www = response.headers.get( "WWW-Authenticate", "" ) # Check if authentication is required diff --git a/tests/test_download_redirects.py b/tests/test_download_redirects.py index 8a5b456c..2b229b19 100644 --- a/tests/test_download_redirects.py +++ b/tests/test_download_redirects.py @@ -33,6 +33,11 @@ def do_HEAD(self): def do_GET(self): requested_paths.append(self.path) + if self.path == "/entry/file.ttl": + self.send_response(302) + self.send_header("Location", redirect_location) + self.end_headers() + return self.send_response(200) self.send_header("Content-Length", str(len(content))) self.end_headers() @@ -53,5 +58,64 @@ def log_message(self, format, *args): server.shutdown() thread.join() - assert requested_paths == [expected_path] + # The GET starts at the Databus file URL, so Databus counts the download (#135). + assert requested_paths == ["/entry/file.ttl", expected_path] + assert (tmp_path / "file.ttl").read_bytes() == content + + +@pytest.mark.parametrize("protected_host", ["databus", "source"]) +def test_api_key_is_sent_only_to_the_host_that_requires_it(tmp_path, protected_host): + """127.0.0.1 plays the Databus and localhost the source server: two hostnames.""" + content = b" .\n" + gets = [] + + class Handler(BaseHTTPRequestHandler): + def _route(self, send_body): + on_databus = self.headers["Host"].startswith("127.0.0.1") + protected = on_databus == (protected_host == "databus") + key = self.headers.get("X-API-KEY") + if send_body: + gets.append((on_databus, key)) + if on_databus and protected_host == "source": + self.send_response(302) + self.send_header("Location", f"http://localhost:{port}/file.ttl") + self.end_headers() + elif protected and key != "secret": + self.send_response(401) + self.end_headers() + else: + self.send_response(200) + self.send_header("Content-Length", str(len(content))) + self.end_headers() + if send_body: + self.wfile.write(content) + + def do_HEAD(self): + self._route(send_body=False) + + def do_GET(self): + self._route(send_body=True) + + def log_message(self, format, *args): + pass + + with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + port = server.server_port + thread = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}) + thread.start() + try: + _download_file( + f"http://127.0.0.1:{port}/file.ttl", + localDir=str(tmp_path), + databus_key="secret", + ) + finally: + server.shutdown() + thread.join() + + if protected_host == "databus": + assert gets == [(True, "secret")] + else: + # Databus sees the GET (and counts it) without the key; only the source gets it. + assert gets == [(True, None), (False, "secret")] assert (tmp_path / "file.ttl").read_bytes() == content From 104d7f82be00ae35c48e160eb28a0f980795c0af Mon Sep 17 00:00:00 2001 From: CHAITHANYA <121756953+Chaithanya123123@users.noreply.github.com> Date: Sat, 5 Dec 2026 17:19:15 +0530 Subject: [PATCH 2/3] docs: add changelog entry for counted downloads (#135) Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80baae66..fd3b701e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ All notable changes to this project will be documented in this file. ### Changed - File downloads now identify as `databus-python-client/ (https://github.com/dbpedia/databus-python-client)` instead of the Requests library default. +### Fixed +- File downloads now send their GET request to the Databus file URL and follow its redirect, so Databus counts each download. A `--databus-key` is sent only to the host that requires it, not to other hosts in the redirect chain. + ## [0.15] - 2025-12-31 ### Added From cd344f5ff5f15fca295d9d37ee0e235796997965 Mon Sep 17 00:00:00 2001 From: CHAITHANYA <121756953+Chaithanya123123@users.noreply.github.com> Date: Sat, 5 Dec 2026 17:45:23 +0530 Subject: [PATCH 3/3] fix: keep cookies across manually followed download redirects Each hop of the manual redirect loop made a fresh request, so a cookie set by a redirect response was lost and a source that requires it answered 401. Hops now share one cookie jar, which sends each cookie only to the domain that set it. Co-Authored-By: Claude Opus 5.5 --- databusclient/api/download.py | 14 ++++++++- tests/test_download_redirects.py | 52 ++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/databusclient/api/download.py b/databusclient/api/download.py index fbb477f3..547e0bc3 100644 --- a/databusclient/api/download.py +++ b/databusclient/api/download.py @@ -7,6 +7,7 @@ import re import shutil import tempfile +from http.cookiejar import CookieJar from urllib.parse import urljoin, urlparse import requests @@ -439,16 +440,27 @@ def _get_with_scoped_credentials(url, headers, credentials, credential_host): counts file GET requests, not HEAD requests). Redirects are followed here rather than by requests because requests drops ``Authorization`` on a cross-host redirect but forwards custom headers such as ``X-API-KEY``. + Cookies set on one hop are sent on later hops, as automatic redirects would; + the jar sends each cookie only to the domain that set it. Returns the final response and its URL. """ + cookies = requests.cookies.RequestsCookieJar() for _ in range(_MAX_REDIRECTS + 1): hop_headers = dict(headers) if credentials and urlparse(url).hostname == credential_host: hop_headers.update(credentials) response = requests.get( - url, headers=hop_headers, stream=True, allow_redirects=False, timeout=30 + url, + headers=hop_headers, + cookies=cookies, + stream=True, + allow_redirects=False, + timeout=30, ) + hop_cookies = getattr(response, "cookies", None) + if isinstance(hop_cookies, CookieJar): + cookies.update(hop_cookies) location = response.headers.get("Location") if response.status_code not in _REDIRECT_STATUSES or not location: return response, url diff --git a/tests/test_download_redirects.py b/tests/test_download_redirects.py index 2b229b19..f780b9a2 100644 --- a/tests/test_download_redirects.py +++ b/tests/test_download_redirects.py @@ -119,3 +119,55 @@ def log_message(self, format, *args): # Databus sees the GET (and counts it) without the key; only the source gets it. assert gets == [(True, None), (False, "secret")] assert (tmp_path / "file.ttl").read_bytes() == content + + +def test_cookie_set_by_a_redirect_is_sent_on_the_next_hop(tmp_path): + """The source sets a session cookie on a redirect and requires it for the file.""" + content = b" .\n" + gets = [] + + class Handler(BaseHTTPRequestHandler): + def _route(self, send_body): + on_databus = self.headers["Host"].startswith("127.0.0.1") + if send_body: + gets.append((on_databus, self.path)) + if on_databus: + self.send_response(302) + self.send_header("Location", f"http://localhost:{port}/start") + self.end_headers() + elif self.path == "/start": + self.send_response(302) + self.send_header("Set-Cookie", "session=ok; Path=/") + self.send_header("Location", "/file.ttl") + self.end_headers() + elif self.headers.get("Cookie") != "session=ok": + self.send_response(401) + self.end_headers() + else: + self.send_response(200) + self.send_header("Content-Length", str(len(content))) + self.end_headers() + if send_body: + self.wfile.write(content) + + def do_HEAD(self): + self._route(send_body=False) + + def do_GET(self): + self._route(send_body=True) + + def log_message(self, format, *args): + pass + + with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + port = server.server_port + thread = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}) + thread.start() + try: + _download_file(f"http://127.0.0.1:{port}/file.ttl", localDir=str(tmp_path)) + finally: + server.shutdown() + thread.join() + + assert gets == [(True, "/file.ttl"), (False, "/start"), (False, "/file.ttl")] + assert (tmp_path / "file.ttl").read_bytes() == content