diff --git a/CHANGELOG.md b/CHANGELOG.md index 80baae6..fd3b701 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 diff --git a/databusclient/api/download.py b/databusclient/api/download.py index f2aead7..547e0bc 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 @@ -427,6 +428,49 @@ 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``. + 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, + 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 + 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 +524,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 +564,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 8a5b456..f780b9a 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,116 @@ 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 + + +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