From df0c6027af7c7eabf57ba43a9f6f1d8ba5f6cf27 Mon Sep 17 00:00:00 2001 From: Ranjith Guggilla Date: Sat, 21 Nov 2026 20:55:39 -0600 Subject: [PATCH 1/2] fix: sign in over HTTPS when the server requires it An http sign-in against a server that only accepts https fails with 405 after the credentials have already been sent. Probe the unauthenticated serverInfo endpoint first and switch the address to https when that probe redirects or when http is refused and https answers. --- .../server/endpoint/auth_endpoint.py | 46 +++++++++++++++ test/test_auth.py | 57 +++++++++++++++++++ 2 files changed, 103 insertions(+) diff --git a/tableauserverclient/server/endpoint/auth_endpoint.py b/tableauserverclient/server/endpoint/auth_endpoint.py index 110d38a18..8773e39a8 100644 --- a/tableauserverclient/server/endpoint/auth_endpoint.py +++ b/tableauserverclient/server/endpoint/auth_endpoint.py @@ -1,5 +1,6 @@ import logging from typing import TYPE_CHECKING +from urllib.parse import urljoin, urlparse import warnings from defusedxml.ElementTree import fromstring @@ -66,6 +67,7 @@ def sign_in(self, auth_req: "Credentials") -> contextmgr: >>> # call the sign-in method with the auth object >>> server.auth.sign_in(tableau_auth) """ + self._use_https_if_the_server_requires_it() url = f"{self.baseurl}/signin" signin_req = RequestFactory.Auth.signin_req(auth_req) # Route through _make_request so signin gets the same redirect handling @@ -91,6 +93,50 @@ def sign_in(self, auth_req: "Credentials") -> contextmgr: self.parent_srv.use_server_version() return Auth.contextmgr(self.sign_out) + def _use_https_if_the_server_requires_it(self) -> None: + """Switch an http address to https before the sign-in POST. + + An http sign-in against a server that requires https is rejected with + 405, after the credentials have already been sent in cleartext. Probe + the unauthenticated serverInfo endpoint first. A redirect to https on + the same host, or an http refusal that succeeds over https, updates + the stored address. An http-only server is left unchanged. + """ + address = self.parent_srv.server_address + parsed = urlparse(address) + if parsed.scheme != "http": + return + timeout = self.parent_srv.http_options.get("timeout") + verify = self.parent_srv.http_options.get("verify", True) + probe_url = f"{address}/api/{self.parent_srv.version}/serverInfo" + try: + response = self.parent_srv.session.get(probe_url, allow_redirects=False, timeout=timeout, verify=verify) + except Exception as exc: + logger.info("Could not probe %s before sign-in: %s", probe_url, exc) + return + + https_address = "https://" + address[len("http://") :] + if response.is_redirect or response.status_code in (301, 302, 303, 307, 308): + location = response.headers.get("Location") or "" + target = urlparse(urljoin(probe_url, location)) + if target.scheme == "https" and target.netloc == parsed.netloc: + self.parent_srv._server_address = https_address + logger.info("Server requires HTTPS; signing in at %s", https_address) + return + if response.status_code not in (400, 403, 405): + return + https_probe = f"{https_address}/api/{self.parent_srv.version}/serverInfo" + try: + https_response = self.parent_srv.session.get( + https_probe, allow_redirects=False, timeout=timeout, verify=verify + ) + except Exception as exc: + logger.info("Could not probe %s before sign-in: %s", https_probe, exc) + return + if https_response.status_code == 200: + self.parent_srv._server_address = https_address + logger.info("Server requires HTTPS; signing in at %s", https_address) + # We use the same request that username/password login uses for all auth types. # The distinct methods are mostly useful for explicitly showing api version support for each auth type @api(version="3.6") diff --git a/test/test_auth.py b/test/test_auth.py index c50f4d29b..47f355ff5 100644 --- a/test/test_auth.py +++ b/test/test_auth.py @@ -19,6 +19,63 @@ def server() -> TSC.Server: return server_instance +def test_sign_in_switches_to_https_when_the_probe_redirects() -> None: + server = TSC.Server("http://tableau.example", False) + response_xml = SIGN_IN_XML.read_text() + with requests_mock.mock() as m: + m.get( + "http://tableau.example/api/2.4/serverInfo", + status_code=301, + headers={"Location": "https://tableau.example/api/2.4/serverInfo"}, + ) + m.post("https://tableau.example/api/2.4/auth/signin", text=response_xml) + server.auth.sign_in(TSC.TableauAuth("testuser", "password", site_id="Samples")) + + assert server.server_address == "https://tableau.example" + assert [call.method for call in m.request_history] == ["GET", "POST"] + assert m.request_history[1].url.startswith("https://tableau.example/") + + +def test_sign_in_stays_on_http_when_the_server_accepts_it() -> None: + server = TSC.Server("http://plain.example", False) + response_xml = SIGN_IN_XML.read_text() + info_xml = """ + + + 10.0.0 + 2.4 + + """ + with requests_mock.mock() as m: + m.get("http://plain.example/api/2.4/serverInfo", text=info_xml) + m.post("http://plain.example/api/2.4/auth/signin", text=response_xml) + server.auth.sign_in(TSC.TableauAuth("testuser", "password")) + + assert server.server_address == "http://plain.example" + assert m.request_history[1].url.startswith("http://plain.example/") + + +def test_sign_in_switches_to_https_when_http_is_rejected() -> None: + server = TSC.Server("http://secure.example", False) + response_xml = SIGN_IN_XML.read_text() + info_xml = """ + + + 2024.1.0 + 3.22 + + """ + with requests_mock.mock() as m: + m.get("http://secure.example/api/2.4/serverInfo", status_code=405) + m.get("https://secure.example/api/2.4/serverInfo", text=info_xml) + m.post("https://secure.example/api/2.4/auth/signin", text=response_xml) + server.auth.sign_in(TSC.TableauAuth("testuser", "password")) + + assert server.server_address == "https://secure.example" + assert m.request_history[0].method == "GET" + assert m.request_history[-1].url.startswith("https://secure.example/") + + def test_sign_in(server: TSC.Server) -> None: with open(SIGN_IN_XML, "rb") as f: response_xml = f.read().decode("utf-8") From da68bc7e97d1a871097fcc6b149a744a1323daf5 Mon Sep 17 00:00:00 2001 From: Ranjith Guggilla Date: Tue, 1 Dec 2026 03:03:39 -0600 Subject: [PATCH 2/2] fix: probe serverInfo with the same HTTP options as sign-in The probe sent only timeout and verify, so a proxy or client certificate made it fail and left sign-in on http. It now uses Endpoint.set_parameters and still does not follow redirects. A failed https probe is a warning that says sign-in is continuing over HTTP, and the docstring says the stored address changes only for the same host and port. --- .../server/endpoint/auth_endpoint.py | 58 ++++++++-- test/test_auth.py | 105 ++++++++++++++++++ 2 files changed, 151 insertions(+), 12 deletions(-) diff --git a/tableauserverclient/server/endpoint/auth_endpoint.py b/tableauserverclient/server/endpoint/auth_endpoint.py index 8773e39a8..59845a5af 100644 --- a/tableauserverclient/server/endpoint/auth_endpoint.py +++ b/tableauserverclient/server/endpoint/auth_endpoint.py @@ -1,5 +1,5 @@ import logging -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from urllib.parse import urljoin, urlparse import warnings @@ -43,6 +43,20 @@ def sign_in(self, auth_req: "Credentials") -> contextmgr: Creates a context manager that will sign out of the server upon exit. + When ``server_address`` is ``http``, sign-in first sends an + unauthenticated ``GET`` of ``serverInfo``, using the same HTTP options + as other requests (proxy, client certificate, headers, timeout, + verify, and User-Agent) and no auth token. That probe does not follow + redirects. A redirect to ``https`` on the same host and port, or an + http refusal followed by a successful https probe, changes + ``server.server_address`` from ``http`` to ``https`` before the + credentials are posted. The new address keeps the original host and + port and only changes the scheme. A redirect to another host or + another port, including ``https`` on port 443 when the original URL + had no port, leaves the address on ``http``. Read ``server_address`` + again after sign-in if you cached it. If either probe fails, sign-in + continues at the original ``http`` address. + Parameters ---------- auth_req : Credentials @@ -93,26 +107,44 @@ def sign_in(self, auth_req: "Credentials") -> contextmgr: self.parent_srv.use_server_version() return Auth.contextmgr(self.sign_out) + def _probe_parameters(self) -> dict[str, Any]: + options = dict(self.parent_srv.http_options) + headers = options.get("headers") + if isinstance(headers, dict): + options["headers"] = dict(headers) + parameters = Endpoint.set_parameters(options, None, None, None, {"allow_redirects": False}) + # The probe has to see the redirect itself. A caller's allow_redirects + # setting would hide it inside requests. + parameters["allow_redirects"] = False + return parameters + def _use_https_if_the_server_requires_it(self) -> None: """Switch an http address to https before the sign-in POST. An http sign-in against a server that requires https is rejected with 405, after the credentials have already been sent in cleartext. Probe - the unauthenticated serverInfo endpoint first. A redirect to https on - the same host, or an http refusal that succeeds over https, updates - the stored address. An http-only server is left unchanged. + the unauthenticated serverInfo endpoint first, with the same HTTP + options as the sign-in request and no auth token. A redirect to https + on the same host and port, or an http refusal that succeeds over + https, updates the stored address. The new address keeps that host + and port and only changes the scheme, matching the redirect walker. + A different host or port is left on http. An http-only server is left + unchanged. A failed probe is logged and sign-in continues over http. """ address = self.parent_srv.server_address parsed = urlparse(address) if parsed.scheme != "http": return - timeout = self.parent_srv.http_options.get("timeout") - verify = self.parent_srv.http_options.get("verify", True) + parameters = self._probe_parameters() probe_url = f"{address}/api/{self.parent_srv.version}/serverInfo" try: - response = self.parent_srv.session.get(probe_url, allow_redirects=False, timeout=timeout, verify=verify) + response = self.parent_srv.session.get(probe_url, **parameters) except Exception as exc: - logger.info("Could not probe %s before sign-in: %s", probe_url, exc) + logger.warning( + "Could not probe %s before sign-in (%s). Signing in continues over HTTP.", + probe_url, + exc, + ) return https_address = "https://" + address[len("http://") :] @@ -127,11 +159,13 @@ def _use_https_if_the_server_requires_it(self) -> None: return https_probe = f"{https_address}/api/{self.parent_srv.version}/serverInfo" try: - https_response = self.parent_srv.session.get( - https_probe, allow_redirects=False, timeout=timeout, verify=verify - ) + https_response = self.parent_srv.session.get(https_probe, **parameters) except Exception as exc: - logger.info("Could not probe %s before sign-in: %s", https_probe, exc) + logger.warning( + "HTTPS probe %s was not reachable (%s). Signing in continues over HTTP.", + https_probe, + exc, + ) return if https_response.status_code == 200: self.parent_srv._server_address = https_address diff --git a/test/test_auth.py b/test/test_auth.py index 47f355ff5..d18d38cd0 100644 --- a/test/test_auth.py +++ b/test/test_auth.py @@ -1,6 +1,8 @@ +import logging from pathlib import Path import pytest +import requests import requests_mock import tableauserverclient as TSC @@ -76,6 +78,109 @@ def test_sign_in_switches_to_https_when_http_is_rejected() -> None: assert m.request_history[-1].url.startswith("https://secure.example/") +def test_sign_in_stays_on_http_when_the_probe_raises(caplog: pytest.LogCaptureFixture) -> None: + server = TSC.Server("http://plain.example", False) + response_xml = SIGN_IN_XML.read_text() + with requests_mock.mock() as m: + m.get("http://plain.example/api/2.4/serverInfo", exc=requests.ConnectionError("down")) + m.post("http://plain.example/api/2.4/auth/signin", text=response_xml) + with caplog.at_level(logging.WARNING, logger="TSC"): + server.auth.sign_in(TSC.TableauAuth("testuser", "password")) + + assert server.server_address == "http://plain.example" + assert m.request_history[-1].url.startswith("http://plain.example/") + assert "continues over HTTP" in caplog.text + + +def test_sign_in_stays_on_http_when_https_is_unreachable(caplog: pytest.LogCaptureFixture) -> None: + server = TSC.Server("http://secure.example", False) + response_xml = SIGN_IN_XML.read_text() + with requests_mock.mock() as m: + m.get("http://secure.example/api/2.4/serverInfo", status_code=405) + m.get("https://secure.example/api/2.4/serverInfo", exc=requests.ConnectionError("tls")) + m.post("http://secure.example/api/2.4/auth/signin", text=response_xml) + with caplog.at_level(logging.WARNING, logger="TSC"): + server.auth.sign_in(TSC.TableauAuth("testuser", "password")) + + assert server.server_address == "http://secure.example" + assert m.request_history[-1].url.startswith("http://secure.example/") + assert "HTTPS probe" in caplog.text + assert "continues over HTTP" in caplog.text + + +def test_sign_in_stays_on_http_when_the_redirect_changes_host() -> None: + server = TSC.Server("http://tableau.example", False) + response_xml = SIGN_IN_XML.read_text() + with requests_mock.mock() as m: + m.get( + "http://tableau.example/api/2.4/serverInfo", + status_code=301, + headers={"Location": "https://other.example/api/2.4/serverInfo"}, + ) + m.post("http://tableau.example/api/2.4/auth/signin", text=response_xml) + server.auth.sign_in(TSC.TableauAuth("testuser", "password")) + + assert server.server_address == "http://tableau.example" + assert m.request_history[-1].url.startswith("http://tableau.example/") + + +def test_sign_in_stays_on_http_when_the_redirect_changes_port() -> None: + server = TSC.Server("http://tableau.example:8080", False) + response_xml = SIGN_IN_XML.read_text() + with requests_mock.mock() as m: + m.get( + "http://tableau.example:8080/api/2.4/serverInfo", + status_code=301, + headers={"Location": "https://tableau.example:8443/api/2.4/serverInfo"}, + ) + m.post("http://tableau.example:8080/api/2.4/auth/signin", text=response_xml) + server.auth.sign_in(TSC.TableauAuth("testuser", "password")) + + assert server.server_address == "http://tableau.example:8080" + + +def test_probe_uses_http_options() -> None: + server = TSC.Server("http://tableau.example", False) + caller_headers = {"X-Test": "1"} + server.add_http_options( + { + "timeout": 7, + "verify": False, + "proxies": {"http": "http://proxy:8080"}, + "cert": "client.pem", + "headers": caller_headers, + "allow_redirects": True, + } + ) + seen: dict = {} + + class _Response: + is_redirect = True + status_code = 301 + headers = {"Location": "https://tableau.example/api/2.4/serverInfo"} + + def fake_get(url, **kwargs): + seen["url"] = url + seen["kwargs"] = kwargs + return _Response() + + server.session.get = fake_get # type: ignore[method-assign] + server.auth._use_https_if_the_server_requires_it() + + assert seen["url"] == "http://tableau.example/api/2.4/serverInfo" + kwargs = seen["kwargs"] + assert kwargs["timeout"] == 7 + assert kwargs["verify"] is False + assert kwargs["proxies"] == {"http": "http://proxy:8080"} + assert kwargs["cert"] == "client.pem" + assert kwargs["allow_redirects"] is False + assert kwargs["headers"]["X-Test"] == "1" + assert kwargs["headers"]["User-Agent"].startswith("Tableau Server Client/") + assert "x-tableau-auth" not in {name.lower() for name in kwargs["headers"]} + assert "User-Agent" not in caller_headers + assert server.server_address == "https://tableau.example" + + def test_sign_in(server: TSC.Server) -> None: with open(SIGN_IN_XML, "rb") as f: response_xml = f.read().decode("utf-8")