Reorder name normalization for DNS

Having the truncation step as the last one meant we could truncate to
a trailing hyphen. This could potential cause a failure for an invalid
name. This commit reorders the normalization to put the truncation as
the first step which should avoid that problem.

Change-Id: I2219f6c73d882efc787127f02fda937f3e3b44eb
Closes-Bug: #1545153
This commit is contained in:
Matthew Treinish 2016-02-12 16:21:37 -05:00 committed by Matt Riedemann
parent 8bdd2b2c9b
commit 7e79d83641
2 changed files with 10 additions and 2 deletions

View File

@ -127,6 +127,14 @@ class GenericUtilsTestCase(test.NoDBTestCase):
hostname = "a" * 64
self.assertEqual(63, len(utils.sanitize_hostname(hostname)))
def test_hostname_truncated_no_hyphen(self):
hostname = "a" * 62
hostname = hostname + '-' + 'a'
res = utils.sanitize_hostname(hostname)
# we trim to 63 and then trim the trailing dash
self.assertEqual(62, len(res))
self.assertFalse(res.endswith('-'), 'The hostname ends with a -')
def test_generate_password(self):
password = utils.generate_password()
self.assertTrue([c for c in password if c in '0123456789'])

View File

@ -802,6 +802,7 @@ def sanitize_hostname(hostname, default_name=None):
if six.PY3:
hostname = hostname.decode('latin-1')
hostname = truncate_hostname(hostname)
hostname = re.sub('[ _]', '-', hostname)
hostname = re.sub('[^\w.-]+', '', hostname)
hostname = hostname.lower()
@ -810,8 +811,7 @@ def sanitize_hostname(hostname, default_name=None):
# empty hostname
if hostname == "" and default_name is not None:
return truncate_hostname(default_name)
return truncate_hostname(hostname)
return hostname
@contextlib.contextmanager