33"""
44
55import os
6+ import re
67from typing import Dict , List
78
89
@@ -15,7 +16,8 @@ def __init__(self):
1516 """
1617 Initialize the validator.
1718 """
18- pass
19+ # No state; environment variables are read on demand
20+ return None
1921
2022 def _get_allowed_commands (self ) -> set [str ]:
2123 """Get the set of allowed commands from environment variables"""
@@ -24,14 +26,27 @@ def _get_allowed_commands(self) -> set[str]:
2426 commands = allow_commands + "," + allowed_commands
2527 return {cmd .strip () for cmd in commands .split ("," ) if cmd .strip ()}
2628
29+ def _get_allowed_patterns (self ) -> List [re .Pattern ]:
30+ """Get the list of allowed regex patterns from environment variables"""
31+ allow_patterns = os .environ .get ("ALLOW_PATTERNS" , "" )
32+ patterns = [
33+ pattern .strip () for pattern in allow_patterns .split ("," ) if pattern .strip ()
34+ ]
35+ return [re .compile (pattern ) for pattern in patterns ]
36+
2737 def get_allowed_commands (self ) -> list [str ]:
28- """Get the list of allowed commands from environment variables """
38+ """Public API: return list form of allowed commands"""
2939 return list (self ._get_allowed_commands ())
3040
3141 def is_command_allowed (self , command : str ) -> bool :
32- """Check if a command is in the allowed list"""
42+ """Check if a command is in the allowed list or matches an allowed pattern """
3343 cmd = command .strip ()
34- return cmd in self ._get_allowed_commands ()
44+ if cmd in self ._get_allowed_commands ():
45+ return True
46+ for pattern in self ._get_allowed_patterns ():
47+ if pattern .match (cmd ):
48+ return True
49+ return False
3550
3651 def validate_no_shell_operators (self , cmd : str ) -> None :
3752 """
@@ -92,13 +107,12 @@ def validate_command(self, command: List[str]) -> None:
92107 if not command :
93108 raise ValueError ("Empty command" )
94109
95- allowed_commands = self ._get_allowed_commands ()
96- if not allowed_commands :
110+ if not self ._get_allowed_commands () and not self ._get_allowed_patterns ():
97111 raise ValueError (
98112 "No commands are allowed. Please set ALLOW_COMMANDS environment variable."
99113 )
100114
101115 # Clean and check the first command
102116 cleaned_cmd = command [0 ].strip ()
103- if cleaned_cmd not in allowed_commands :
117+ if not self . is_command_allowed ( cleaned_cmd ) :
104118 raise ValueError (f"Command not allowed: { cleaned_cmd } " )
0 commit comments