From 4540853a50ca372509139e61dec643dd2b607b23 Mon Sep 17 00:00:00 2001 From: Varadharajan Date: Thu, 6 Apr 2017 14:33:57 +0530 Subject: [PATCH] Pass CSRF token along with Jenkins POST requests (#23250) --- .../web_infrastructure/jenkins_script.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/lib/ansible/modules/web_infrastructure/jenkins_script.py b/lib/ansible/modules/web_infrastructure/jenkins_script.py index 04f20339c78..3d5c31c9feb 100644 --- a/lib/ansible/modules/web_infrastructure/jenkins_script.py +++ b/lib/ansible/modules/web_infrastructure/jenkins_script.py @@ -116,6 +116,8 @@ output: sample: 'Result: true' ''' +import json + from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_url try: @@ -125,6 +127,26 @@ except ImportError: # python3 from urllib.parse import urlencode +def is_csrf_protection_enabled(module): + resp, info = fetch_url(module, + module.params['url'] + '/api/json', + method='GET') + if info["status"] != 200: + module.fail_json(msg="HTTP error " + str(info["status"]) + " " + info["msg"]) + + content = resp.read() + return json.loads(content).get('useCrumbs', False) + +def get_crumb(module): + resp, info = fetch_url(module, + module.params['url'] + '/crumbIssuer/api/json', + method='GET') + if info["status"] != 200: + module.fail_json(msg="HTTP error " + str(info["status"]) + " " + info["msg"]) + + content = resp.read() + return json.loads(content) + def main(): module = AnsibleModule( @@ -153,10 +175,15 @@ def main(): else: script_contents = module.params['script'] + headers = {} + if is_csrf_protection_enabled(module): + crumb = get_crumb(module) + headers = {crumb['crumbRequestField']: crumb['crumb']} resp, info = fetch_url(module, module.params['url'] + "/scriptText", data=urlencode({'script': script_contents}), + headers = headers, method="POST") if info["status"] != 200: