From 811a6cffc81fe2d915d6e3d3987de9058fcfa630 Mon Sep 17 00:00:00 2001 From: Aigars Mahinovs Date: Mon, 13 Aug 2018 15:41:08 +0200 Subject: [PATCH] Allow adding extra HTTP headers to Jenkins requests In some network setups Jenkins may be hidden behind complex reverse proxy setups that require additional custom headers to be set on each request in order to pass them trough Allow providing such headers using JENKINS_API_EXTRA_HEADERS environment variable Change-Id: If071c5c707f916ba5f4f2c371ec600b7476bf723 --- jenkins/__init__.py | 8 ++++++++ tests/test_jenkins.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/jenkins/__init__.py b/jenkins/__init__.py index 58590ae..7c9c577 100755 --- a/jenkins/__init__.py +++ b/jenkins/__init__.py @@ -321,6 +321,14 @@ class Jenkins(object): self.timeout = timeout self._session = WrappedSession() + extra_headers = os.environ.get("JENKINS_API_EXTRA_HEADERS", "") + if extra_headers: + logging.warning("JENKINS_API_EXTRA_HEADERS adds these HTTP headers: %s", extra_headers.split("\n")) + for token in extra_headers.split("\n"): + if ":" in token: + header, value = token.split(":", 1) + self._session.headers[header] = value.strip() + if os.getenv('PYTHONHTTPSVERIFY', '1') == '0': logging.debug('PYTHONHTTPSVERIFY=0 detected so we will ' 'disable requests library SSL verification to keep ' diff --git a/tests/test_jenkins.py b/tests/test_jenkins.py index 073158a..1bc0624 100644 --- a/tests/test_jenkins.py +++ b/tests/test_jenkins.py @@ -120,6 +120,34 @@ class JenkinsMaybeAddCrumbTest(JenkinsTestBase): self.assertFalse('.crumb' in request.headers) +class JenkinsMaybeAddHeaders(JenkinsTestBase): + @patch('jenkins.requests.Session.send', autospec=True) + def test_simple(self, session_send_mock): + session_send_mock.return_value = build_response_mock( + 404, reason="Not Found") + request = jenkins.requests.Request('GET', 'http://example.com/job/TestJob') + + with patch.dict('os.environ', {}): + j = jenkins.Jenkins(self.base_url, 'test', 'test') + request = j._session.prepare_request(request) + + self.assertEqual(request.headers, self.j._session.headers) + self.assertNotIn("X-Auth", request.headers) + + @patch('jenkins.requests.Session.send', autospec=True) + def test_add_header(self, session_send_mock): + session_send_mock.return_value = build_response_mock( + 404, reason="Not Found") + request = jenkins.requests.Request('GET', 'http://example.com/job/TestJob') + + with patch.dict('os.environ', {"JENKINS_API_EXTRA_HEADERS": "X-Auth: 123\nX-Key: 234"}): + j = jenkins.Jenkins(self.base_url, 'test', 'test') + request = j._session.prepare_request(request) + + self.assertEqual(request.headers["X-Auth"], "123") + self.assertEqual(request.headers["X-Key"], "234") + + class JenkinsOpenTest(JenkinsTestBase): @patch('jenkins.requests.Session.send', autospec=True)