diff --git a/tableauserverclient/server/endpoint/auth_endpoint.py b/tableauserverclient/server/endpoint/auth_endpoint.py index 110d38a18..59845a5af 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 typing import TYPE_CHECKING, Any +from urllib.parse import urljoin, urlparse import warnings from defusedxml.ElementTree import fromstring @@ -42,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 @@ -66,6 +81,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 +107,70 @@ 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, 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 + parameters = self._probe_parameters() + probe_url = f"{address}/api/{self.parent_srv.version}/serverInfo" + try: + response = self.parent_srv.session.get(probe_url, **parameters) + except Exception as 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://") :] + 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, **parameters) + except Exception as 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 + 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..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 @@ -19,6 +21,166 @@ 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_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")