Skip to content

Commit

Permalink
Don't allow leading or trailing whitespace in group names
Browse files Browse the repository at this point in the history
  • Loading branch information
seanh committed Jul 31, 2024
1 parent 8318839 commit ad4124f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
11 changes: 10 additions & 1 deletion h/schemas/api/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,21 @@ def validate(self, data):
:rtype: dict
"""

appstruct = super().validate(data)
appstruct = self._whitelisted_fields_only(appstruct)
self._validate_name(appstruct)
self._validate_groupid(appstruct)

return appstruct

def _validate_name(self, appstruct):
name = appstruct.get("name")

if name and name.strip() != name:
raise ValidationError(
"Group names can't have leading or trailing whitespace."
)

def _validate_groupid(self, appstruct):
"""
Validate the ``groupid`` to make sure it adheres to authority restrictions.
Expand Down
28 changes: 28 additions & 0 deletions tests/unit/h/schemas/api/group_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,34 @@ def test_it_raises_if_name_too_long(self, schema):
with pytest.raises(ValidationError, match="name:.*is too long"):
schema.validate({"name": "o" * (GROUP_NAME_MAX_LENGTH + 1)})

def test_it_raises_if_name_isnt_a_string(self, schema):
name = 42

with pytest.raises(
ValidationError, match=f"name: {name} is not of type 'string'"
):
schema.validate({"name": name})

@pytest.mark.parametrize(
"name",
[
f" {'o' * GROUP_NAME_MIN_LENGTH}",
f"{'o' * GROUP_NAME_MIN_LENGTH} ",
" " * GROUP_NAME_MIN_LENGTH,
],
)
def test_it_raises_if_name_has_leading_or_trailing_whitespace(self, schema, name):
with pytest.raises(
ValidationError,
match="Group names can't have leading or trailing whitespace.",
):
schema.validate({"name": name})

def test_it_validates_with_no_data(self, schema):
appstruct = schema.validate({})

assert appstruct == {}

def test_it_validates_with_valid_name(self, schema):
appstruct = schema.validate({"name": "Perfectly Fine"})

Expand Down

0 comments on commit ad4124f

Please sign in to comment.