Datasets:

Modalities:
Text
Formats:
parquet
Size:
< 1K
ArXiv:
DOI:
Libraries:
Datasets
pandas
License:
File size: 6,636 Bytes
6ffdbc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a78bad
6ffdbc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import json
import os
import random
import pickle
import time
from openai import OpenAI
from tqdm import tqdm
from functools import partial
import multiprocessing
from datasets import load_dataset
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np

client = OpenAI()

def load_cache():
    if os.path.exists('cache.pkl'):
        with open('cache.pkl', 'rb') as f:
            return pickle.load(f)
    return {}

def save_cache(cache):
    with open('cache.pkl', 'wb') as f:
        pickle.dump(cache, f)

def fetch_dataset_examples(prompt, num_examples=3, use_similarity=True):
    dataset = load_dataset("patched-codes/synth-vuln-fixes", split="train")
    
    if use_similarity:
        user_messages = [
            next(msg['content'] for msg in item['messages'] if msg['role'] == 'user')
            for item in dataset
        ]
        
        vectorizer = TfidfVectorizer().fit(user_messages + [prompt])
        user_vectors = vectorizer.transform(user_messages)
        prompt_vector = vectorizer.transform([prompt])
        
        similarities = cosine_similarity(prompt_vector, user_vectors)[0]
        top_indices = np.argsort(similarities)[-num_examples:][::-1]
    else:
        top_indices = np.random.choice(len(dataset), num_examples, replace=False)
    
    few_shot_messages = []
    for index in top_indices:
        py_index = int(index)
        messages = dataset[py_index]["messages"]
        
        dialogue = [msg for msg in messages if msg['role'] != 'system']
        few_shot_messages.extend(dialogue)
    
    return few_shot_messages

def get_fixed_code_fine_tuned(prompt, few_shot_messages):
    system_message = (
        "You are an AI assistant specialized in fixing code vulnerabilities. "
        "Your task is to provide corrected code that addresses the reported security issue. "
        "Always maintain the original functionality while improving security. "
        "Be precise and make only necessary changes. "
        "Maintain the original code style and formatting unless it directly relates to the vulnerability. "
        "Pay attention to data flow between sources and sinks when provided."
    )

    messages = [
        {"role": "system", "content": system_message},
    ]
    
    messages.extend(few_shot_messages)
    messages.append({"role": "user", "content": prompt})

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
        max_tokens=512,
        temperature=0.2,
        top_p=0.95
    )

    try:
        return response.choices[0].message.content
    except Exception as e:
        raise Exception(f"API call failed: {str(e)}")

def process_file(test_case, cache):
    file_name = test_case["file_name"]
    input_file = "staticeval/" + file_name
    
    if input_file in cache:
        tqdm.write(f"Skipping {input_file} (cached)")
        return cache[input_file]

    file_text = test_case["source"]
    test_cwe = test_case["cwe"].strip()
    output_file = input_file + "_fixed.py"
    tmp_file = input_file + ".output.json"

    with open(input_file, "w") as file_object:
        file_object.write(file_text)

    if os.path.exists(tmp_file):
        os.remove(tmp_file)
        
    tqdm.write("Scanning file " + input_file + "...")
    scan_command_input = f"semgrep --config p/python {input_file} --output {tmp_file} --json > /dev/null 2>&1"
    os.system(scan_command_input)
    
    with open(tmp_file, 'r') as jf:
        data = json.load(jf)
    
    if len(data["errors"]) == 0:
        if len(data["results"]) == 0:
            tqdm.write(input_file + " has no vulnerabilities")
            result = False
        else:
            tqdm.write("Vulnerability found in " + input_file + "...")
            cwe = data["results"][0]["extra"]["metadata"]["cwe"][0]
            lines = data["results"][0]["extra"]["lines"]
            message = data["results"][0]["extra"]["message"]
            
            prompt = f"""Vulnerability Report:
- Type: {cwe}
- Location: {lines}
- Description: {message}

Original Code:
```
{file_text}
```

Task: Fix the vulnerability in the code above. Provide only the complete fixed code without explanations or comments. Make minimal changes necessary to address the security issue while preserving the original functionality."""
            
            few_shot_messages = fetch_dataset_examples(prompt, 3, True)
            response = get_fixed_code_fine_tuned(prompt, [])
            
            if "```python" in response:
                idx = response.find("```python")
                shift = len("```python")
                fixed_code = response[idx + shift :]
            else:
                fixed_code = response
            
            stop_words = ["```", "assistant"]
            for w in stop_words:
                if w in fixed_code:
                    fixed_code = fixed_code[:fixed_code.find(w)]
            
            if len(fixed_code) < 400 or all(line.strip().startswith("#") for line in fixed_code.split('\n') if line.strip()):
                result = False
            else:
                with open(output_file, 'w') as wf:
                    wf.write(fixed_code)
                
                scan_command_output = f"semgrep --config p/python {output_file} --output {tmp_file} --json > /dev/null 2>&1"
                os.system(scan_command_output)
                
                with open(tmp_file, 'r') as jf:
                    data = json.load(jf)
                
                if len(data["errors"]) == 0 and len(data["results"]) == 0:
                    tqdm.write("Passing response for " + input_file + " at 1 ...")
                    result = True
                else:
                    result = False

    if os.path.exists(tmp_file):
        os.remove(tmp_file)

    cache[input_file] = result
    save_cache(cache)
    return result

def process_test_case(test_case, cache):
    return process_file(test_case, cache)

def main():
    dataset = load_dataset("patched-codes/static-analysis-eval", split="train")
    data = [{"file_name": item["file_name"], "source": item["source"], "cwe": item["cwe"]} for item in dataset]

    cache = load_cache()
    total_tests = len(data)

    process_func = partial(process_test_case, cache=cache)

    with multiprocessing.Pool() as pool:
        results = list(tqdm(pool.imap_unordered(process_func, data), total=total_tests))

    passing_tests = sum(results)

    print(f"Results for StaticAnalysisEval: {passing_tests/total_tests*100}%")

if __name__ == '__main__':
    main()