File size: 2,073 Bytes
2a64443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

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
    """
    # Get API key from parameter or environment
    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."
        )
    
    # API endpoint and headers
    url = "https://api.codepal.ai/v1/security-code-scanner/query"
    headers = {
        "Authorization": f"Bearer {api_key}"
    }
    
    # Create multipart form data
    files = {
        'code': (None, code)
    }
    
    try:
        # Make the API request
        response = requests.post(url, headers=headers, files=files)
        response.raise_for_status()  # Raise exception for non-2xx status codes
        
        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__":
    # Example usage
    sample_code = """
    import os
    
    def run_command(user_input):
        os.system(user_input)
    
    run_command("ls")
    """
    
    # For testing, replace this with your actual API key
    # or set the CODEPAL_API_KEY environment variable
    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}")