|
|
|
import requests |
|
import os |
|
import json |
|
from typing import Dict, Any, Optional |
|
|
|
def scan_code_for_security( |
|
code: str, |
|
api_key: Optional[str] = None |
|
) -> Dict[str, Any]: |
|
""" |
|
Scan code for security vulnerabilities using the CodePal Security Scanner API. |
|
|
|
Args: |
|
code: The code to scan as a string |
|
api_key: Your CodePal API key (falls back to environment variable) |
|
|
|
Returns: |
|
Dict containing the API response |
|
|
|
Raises: |
|
ValueError: If API key is not provided |
|
requests.RequestException: If the API request fails |
|
""" |
|
|
|
api_key = api_key or os.environ.get('CODEPAL_API_KEY') |
|
|
|
if not api_key: |
|
raise ValueError( |
|
"API key is required. Either pass it as a parameter or set " |
|
"the CODEPAL_API_KEY environment variable." |
|
) |
|
|
|
|
|
url = "https://api.codepal.ai/v1/security-code-scanner/query" |
|
headers = { |
|
"Authorization": f"Bearer {api_key}" |
|
} |
|
|
|
|
|
files = { |
|
'code': (None, code) |
|
} |
|
|
|
try: |
|
|
|
response = requests.post(url, headers=headers, files=files) |
|
response.raise_for_status() |
|
|
|
return response.json() |
|
except requests.RequestException as e: |
|
print(f"Error scanning code: {e}") |
|
if response and hasattr(response, 'text'): |
|
print(f"Response content: {response.text}") |
|
raise |
|
|
|
if __name__ == "__main__": |
|
|
|
sample_code = """ |
|
import os |
|
|
|
def run_command(user_input): |
|
os.system(user_input) |
|
|
|
run_command("ls") |
|
""" |
|
|
|
|
|
|
|
try: |
|
result = scan_code_for_security(sample_code) |
|
print(json.dumps(result, indent=2)) |
|
except Exception as e: |
|
print(f"Failed to scan code: {e}") |
|
|