Handle None or {} labels in match_selector()

match_selector() has a bug causing it to return True for any
podSelector with any matchLabel and pods without labels at all. This is
totally incorrect, casues issues like applying NPs to pods that should
not be affected by them and probably others.

Change-Id: I47d7e61787675252cf16a9b4ae51871d8a31dc0a
Closes-Bug: 1903067
Closes-Bug: 1903572
This commit is contained in:
Michał Dulko 2020-11-09 18:37:16 +01:00
parent 4ce01a7908
commit 4bfe85db0b
2 changed files with 27 additions and 3 deletions

View File

@ -410,14 +410,15 @@ def match_labels(crd_labels, labels):
def match_selector(selector, labels):
if selector is None:
return True
if labels is None:
labels = {}
crd_labels = selector.get('matchLabels', None)
crd_expressions = selector.get('matchExpressions', None)
match_exp = match_lb = True
if crd_expressions:
match_exp = match_expressions(crd_expressions,
labels)
if crd_labels and labels:
match_exp = match_expressions(crd_expressions, labels)
if crd_labels:
match_lb = match_labels(crd_labels, labels)
return match_exp and match_lb

View File

@ -63,3 +63,26 @@ class TestUtils(test_base.TestCase):
def test_get_network_id_empty(self):
self.assertRaises(exceptions.IntegrityError, utils.get_network_id, {})
def test_match_selector(self):
self.assertFalse(
utils.match_selector({'matchLabels': {'app': 'demo'}}, None))
self.assertFalse(
utils.match_selector({'matchLabels': {'app': 'demo'}}, {}))
self.assertFalse(
utils.match_selector({'matchLabels': {'app': 'demo'}},
{'app': 'foobar'}))
self.assertTrue(
utils.match_selector({'matchLabels': {'app': 'demo'}},
{'app': 'demo'}))
self.assertTrue(
utils.match_selector({'matchLabels': {'app': 'demo'}},
{'app': 'demo', 'foo': 'bar'}))
self.assertTrue(
utils.match_selector({'matchLabels': {'app': 'demo',
'foo': 'bar'}},
{'app': 'demo', 'foo': 'bar'}))
self.assertFalse(
utils.match_selector({'matchLabels': {'app': 'demo',
'foo': 'bar'}},
{'app': 'demo'}))