From d83db44561e2157f9dbbe3410b59618ca8afc1d2 Mon Sep 17 00:00:00 2001 From: Giles Knap Date: Wed, 18 May 2022 19:50:44 +0100 Subject: [PATCH] feat: add bind_addr to run_local_server --- google_auth_oauthlib/flow.py | 8 +++++++- tests/unit/test_flow.py | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/google_auth_oauthlib/flow.py b/google_auth_oauthlib/flow.py index 61d501c..72cb13f 100644 --- a/google_auth_oauthlib/flow.py +++ b/google_auth_oauthlib/flow.py @@ -443,6 +443,7 @@ def run_console( def run_local_server( self, host="localhost", + bind_addr=None, port=8080, authorization_prompt_message=_DEFAULT_AUTH_PROMPT_MESSAGE, success_message=_DEFAULT_WEB_SUCCESS_MESSAGE, @@ -463,6 +464,11 @@ def run_local_server( Args: host (str): The hostname for the local redirect server. This will be served over http, not https. + bind_addr (str): Optionally provide an ip address for the redirect + server to listen on when it is not the same as host + (e.g. in a container). Default value is None, + which means that the redirect server will listen + on the ip address specified in the host parameter. port (int): The port for the local redirect server. authorization_prompt_message (str): The message to display to tell the user to navigate to the authorization URL. @@ -483,7 +489,7 @@ def run_local_server( # Fail fast if the address is occupied wsgiref.simple_server.WSGIServer.allow_reuse_address = False local_server = wsgiref.simple_server.make_server( - host, port, wsgi_app, handler_class=_WSGIRequestHandler + bind_addr or host, port, wsgi_app, handler_class=_WSGIRequestHandler ) redirect_uri_format = ( diff --git a/tests/unit/test_flow.py b/tests/unit/test_flow.py index 03eb4bd..8b5da64 100644 --- a/tests/unit/test_flow.py +++ b/tests/unit/test_flow.py @@ -403,6 +403,24 @@ def assign_last_request_uri(host, port, wsgi_app, **kwargs): assert not webbrowser_mock.open.called + @mock.patch("google_auth_oauthlib.flow.webbrowser", autospec=True) + @mock.patch("wsgiref.simple_server.make_server", autospec=True) + def test_run_local_server_bind_addr( + self, make_server_mock, webbrowser_mock, instance, mock_fetch_token + ): + def assign_last_request_uri(host, port, wsgi_app, **kwargs): + wsgi_app.last_request_uri = self.REDIRECT_REQUEST_PATH + return mock.Mock() + + make_server_mock.side_effect = assign_last_request_uri + + my_ip = socket.gethostbyname(socket.gethostname()) + instance.run_local_server(bind_addr=my_ip, host="localhost") + + assert webbrowser_mock.open.called + name, args, kwargs = make_server_mock.mock_calls[0] + assert args[0] == my_ip + @pytest.mark.webtest @mock.patch("google_auth_oauthlib.flow.webbrowser", autospec=True) def test_run_local_server_occupied_port(