Skip to content

Commit

Permalink
validators: add uuid and agent_id validators
Browse files Browse the repository at this point in the history
Add valid_uuid and valid_agent_id validators, and tests for both.

Signed-off-by: Alberto Planas <aplanas@suse.com>
  • Loading branch information
aplanas authored and mpeters committed Jan 27, 2022
1 parent 65c2b73 commit e429e95
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
26 changes: 26 additions & 0 deletions keylime/common/validators.py
Expand Up @@ -32,3 +32,29 @@ def valid_hex(value):
except Exception:
return False
return True


def valid_uuid(uuid: str) -> bool:
"""Check if the string is a valid UUID."""
valid = False
try:
valid = bool(
re.fullmatch(
r"[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
uuid,
re.I,
)
)
except Exception:
pass
return valid


def valid_agent_id(agent_id: str) -> bool:
"""Check if agent_id is valid."""
valid = False
try:
valid = bool(re.fullmatch(r"[\w.-]+", agent_id))
except Exception:
pass
return valid
44 changes: 44 additions & 0 deletions test/test_validators.py
Expand Up @@ -78,5 +78,49 @@ def test_invalid(self):
self.assertFalse(validators.valid_hex("123xyz"))


class TestValidUUID(unittest.TestCase):
"""Tests for valid_uuid."""

def test_none(self):
"""Check that None is not valid."""
self.assertFalse(validators.valid_uuid(None))

def test_empty(self):
"""Check that the empty string is not valid."""
self.assertFalse(validators.valid_uuid(""))

def test_valid(self):
"""Check a valid UUID that mix upper and lower case."""
self.assertTrue(validators.valid_uuid("74a93e15-da24-4ff1-ABC0-55beed02a16a"))

def test_invalid(self):
"""Check an invalid UUID that mix upper and lower case."""
self.assertFalse(validators.valid_uuid("some text"))


class TestValidAgentID(unittest.TestCase):
"""Tests for valid_agent_id."""

def test_none(self):
"""Check that None is not valid."""
self.assertFalse(validators.valid_agent_id(None))

def test_empty(self):
"""Check that the empty string is not valid."""
self.assertFalse(validators.valid_agent_id(""))

def test_valid_uuid(self):
"""Check a valid UUID that mix upper and lower case."""
self.assertTrue(validators.valid_agent_id("74a93e15-da24-4ff1-ABC0-55beed02a16a"))

def test_valid_hostname(self):
"""Check a valid hostname that mix upper and lower case."""
self.assertTrue(validators.valid_agent_id("my-Hostname.example.com"))

def test_invalid(self):
"""Check an invalid user ID with non valid characters."""
self.assertFalse(validators.valid_agent_id("rm -fr *"))


if __name__ == "__main__":
unittest.main()

0 comments on commit e429e95

Please sign in to comment.