From c36f240a871d65b38a477291bcac64f10f32bb94 Mon Sep 17 00:00:00 2001 From: Erik Johnson Date: Thu, 27 Aug 2015 21:46:18 -0500 Subject: [PATCH] Add HTTPS Basic Auth funcs to salt.utils.url --- salt/utils/url.py | 53 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/salt/utils/url.py b/salt/utils/url.py index 6adca2147e..f964871230 100644 --- a/salt/utils/url.py +++ b/salt/utils/url.py @@ -6,6 +6,7 @@ URL utils # Import python libs from __future__ import absolute_import import re +import sys # Import salt libs from salt.ext.six.moves.urllib.parse import urlparse, urlunparse # pylint: disable=import-error,no-name-in-module @@ -146,3 +147,55 @@ def strip_proto(url): was present. ''' return re.sub('^[^:/]+://', '', url) + + +def add_http_basic_auth(url, + https_user=None, + https_pass=None, + https_only=False): + ''' + Return a string with http basic auth incorporated into it + ''' + if https_user is None and https_pass is None: + return url + else: + urltuple = urlparse(url) + if https_only and urltuple.scheme != 'https': + raise ValueError('Basic Auth only supported for HTTPS') + if https_pass is None: + netloc = '{0}@{1}'.format( + https_user, + urltuple.netloc + ) + urltuple = urltuple._replace(netloc=netloc) + return urlunparse(urltuple) + else: + netloc = '{0}:{1}@{2}'.format( + https_user, + https_pass, + urltuple.netloc + ) + urltuple = urltuple._replace(netloc=netloc) + return urlunparse(urltuple) + + +def redact_http_basic_auth(output): + ''' + Remove HTTP user and password + ''' + # We can't use re.compile because re.compile(someregex).sub() doesn't + # support flags even in Python 2.7. + url_re = '(https?)://.*@' + redacted = r'\1://@' + if sys.version_info >= (2, 7): + # re.sub() supports flags as of 2.7, use this to do a case-insensitive + # match. + return re.sub(url_re, redacted, output, flags=re.IGNORECASE) + else: + # We're on python 2.6, test if a lowercased version of the output + # string matches the regex... + if re.search(url_re, output.lower()): + # ... and if it does, perform the regex substitution. + return re.sub(url_re, redacted, output.lower()) + # No match, just return the original string + return output