From a663e714b4d84505bb243cbb494146b3f5de58f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Denis=20Krienb=C3=BChl?= Date: Fri, 10 Jan 2025 17:46:23 +0100 Subject: [PATCH] Validate API token before passing it on to Ansible When the token is set to a value that is not a valid HTTP header, Ansible's http client rejects it with an error that reveals the token. This may cause it to be accidentally logged. We now validate the token, to ensure it is a strict subset of valid HTTP header values. It includes a bit more characters than we currently use for our tokens, just in case we change our format. --- plugins/module_utils/api.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/plugins/module_utils/api.py b/plugins/module_utils/api.py index f7c3e385..f4c65de6 100644 --- a/plugins/module_utils/api.py +++ b/plugins/module_utils/api.py @@ -6,6 +6,8 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type +import re + from datetime import datetime, timedelta from time import sleep from copy import deepcopy @@ -14,6 +16,9 @@ from ansible.module_utils._text import to_text +VALID_TOKEN = re.compile(r'^[a-zA-Z0-9-._]+\Z') + + def cloudscale_argument_spec(): return dict( api_url=dict( @@ -44,7 +49,11 @@ def __init__(self, module): if not self._api_url.endswith('/'): self._api_url = self._api_url + '/' - self._auth_header = {'Authorization': 'Bearer %s' % module.params['api_token']} + api_token = module.params['api_token'].strip() + if not VALID_TOKEN.match(api_token): + self._module.fail_json(msg='Invalid API Token') + else: + self._auth_header = {'Authorization': 'Bearer %s' % api_token} def _get(self, api_call): resp, info = fetch_url(self._module, self._api_url + api_call,