Skip to content

Commit 79c11dd

Browse files
authored
Merge pull request #75 from RobGeada/AddImportFromValidation
Let custom detector code access environment variables
2 parents 2622279 + a680e7a commit 79c11dd

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

detectors/built_in/custom_detectors_wrapper.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,11 @@ def static_code_analysis(module_path, forbidden_imports=None, forbidden_calls=No
135135
issues.append(f"- Forbidden import: {alias.name} (line {node.lineno})")
136136
if isinstance(node, ast.ImportFrom):
137137
if node.module and node.module.split(".")[0] in forbidden_imports:
138+
# Allow specific exception: from os import environ
139+
if node.module == "os" and len(node.names) == 1 and node.names[0].name in {"environ", "getenv"}:
140+
continue
138141
issues.append(f"- Forbidden import: {node.module} (line {node.lineno})")
142+
139143
# Check for forbidden function calls
140144
if isinstance(node, ast.Call):
141145
func_name = ""

tests/detectors/builtIn/test_custom.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,17 @@ def evil(text: str) -> bool:
2222
return True
2323
'''
2424

25+
UNSAFE_CODE_IMPORT_FROM = '''
26+
from sys import path
27+
def func(text: str) -> bool:
28+
return True
29+
'''
30+
31+
SAFE_CODE_IMPORT_FROM_ENVIRON = '''
32+
from os import environ
33+
def func(text: str) -> bool:
34+
return True
35+
'''
2536

2637
def write_code_to_custom_detectors(code: str):
2738
with open(CUSTOM_DETECTORS_PATH, "w") as f:
@@ -134,6 +145,23 @@ def test_unsafe_code(self, client):
134145
assert "Forbidden import: os" in str(excinfo.value) or "os.system" in str(excinfo.value)
135146

136147

148+
def test_unsafe_code_import_from(self, client):
149+
write_code_to_custom_detectors(UNSAFE_CODE_IMPORT_FROM)
150+
from detectors.built_in.custom_detectors_wrapper import CustomDetectorRegistry
151+
with pytest.raises(ImportError) as excinfo:
152+
CustomDetectorRegistry()
153+
assert "Unsafe code detected" in str(excinfo.value)
154+
assert "Forbidden import: sys" in str(excinfo.value) or "sys.path" in str(excinfo.value)
155+
156+
157+
def test_safe_code_import_from_environ(self, client):
158+
# from os import environ <- should not trigger the unsafe import error
159+
write_code_to_custom_detectors(SAFE_CODE_IMPORT_FROM_ENVIRON)
160+
from detectors.built_in.custom_detectors_wrapper import CustomDetectorRegistry
161+
CustomDetectorRegistry()
162+
assert True
163+
164+
137165
def test_custom_detectors_func_doesnt_exist(self, client):
138166
payload = {
139167
"contents": ["What is an apple?"],

0 commit comments

Comments
 (0)