diff options
-rwxr-xr-x | cmd2/cmd2.py | 19 | ||||
-rw-r--r-- | tests/test_cmd2.py | 11 |
2 files changed, 30 insertions, 0 deletions
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 401d2046..661dd20e 100755 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -730,6 +730,19 @@ class Cmd(cmd.Cmd): # If this string is non-empty, then this warning message will print if a broken pipe error occurs while printing self.broken_pipe_warning = '' + # regular expression to test for invalid characters in aliases + invalid_items = [] + invalid_items.extend(constants.REDIRECTION_CHARS) + invalid_items.extend(self.terminators) + # escape each item so it will for sure get treated as a literal + invalid_items = [re.escape(x) for x in invalid_items] + # don't allow whitespace + invalid_items.append(r'\s') + # join them up with a pipe + expr = '|'.join(invalid_items) + # and compile it into a pattern + self.invalid_alias_pattern = re.compile(expr) + # If a startup script is provided, then add it in the queue to load if startup_script is not None: startup_script = os.path.expanduser(startup_script) @@ -2434,6 +2447,12 @@ Usage: Usage: alias [name] | [<name> <value>] name = arglist[0] value = ' '.join(arglist[1:]) + # Validate the alias to ensure it doesn't include wierd characters + # like terminators, output redirection, or whitespace + if self.invalid_alias_pattern.search(name): + self.perror('Alias names can not contain special characters.', traceback_war=False) + return + # Set the alias self.aliases[name] = value self.poutput("Alias {!r} created".format(name)) diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index 33f5d86e..9dcfe692 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -1705,6 +1705,17 @@ def test_unalias_non_existing(base_app, capsys): out, err = capsys.readouterr() assert "does not exist" in err +@pytest.mark.parametrize('alias_name', [ + '">"', + '"no>pe"' + '"no spaces"', + '"nopipe|"', + '"noterm;"', +]) +def test_create_invalid_alias(base_app, alias_name, capsys): + run_cmd(base_app, 'alias {} help'.format(alias_name)) + out, err = capsys.readouterr() + assert "can not contain" in err def test_ppaged(base_app): msg = 'testing...' |