Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
100 commits
Select commit Hold shift + click to select a range
856a402
Uploaded changes in branch
Jul 16, 2024
1d1d777
Merge remote-tracking branch 'refs/remotes/origin/development' into w…
DianaStrauss Sep 3, 2024
923d6ec
fixed shortening of prompt
DianaStrauss Sep 3, 2024
234e6ef
Merge remote-tracking branch 'refs/remotes/origin/development' into w…
DianaStrauss Sep 3, 2024
629489a
Merged development into web_api_testing
DianaStrauss Sep 3, 2024
64699e3
Fixed shorten prompt bug from merge
DianaStrauss Sep 3, 2024
c141954
Updated Tree of thought so that documentation works like chain of tho…
DianaStrauss Oct 8, 2024
3dc2c4b
Implemented in-context learning for documentation
DianaStrauss Oct 15, 2024
53e5c42
refined openapi generation
DianaStrauss Oct 16, 2024
ea8795b
Updated Tree of thought so that documentation works like chain of tho…
DianaStrauss Oct 16, 2024
4409f4b
Updated Tree of thought so that documentation works like chain of tho…
DianaStrauss Oct 16, 2024
8ef5f8b
Adjusted to only record valid information of rest api
DianaStrauss Oct 23, 2024
8eb5048
optimized prompt generation
DianaStrauss Oct 24, 2024
294ca7c
Added configs for documentation and testing
DianaStrauss Oct 25, 2024
98b510f
Added way of retrieving spotify token
DianaStrauss Oct 25, 2024
975ae85
Refactored code to work with spotify benchmark
DianaStrauss Nov 11, 2024
c70a23b
Refined test cases
DianaStrauss Nov 13, 2024
1fbb37b
Added new security endpoint for testing
DianaStrauss Nov 13, 2024
6fa891d
Added new security endpoint for testing
DianaStrauss Nov 13, 2024
86f8b06
Added more testing information for documentation testing and pentesting
DianaStrauss Nov 15, 2024
cee0726
Added evaluations
DianaStrauss Nov 16, 2024
e210104
Refactored code to be more understandable
DianaStrauss Nov 18, 2024
e228cd8
Added evaluation to documentation
DianaStrauss Nov 18, 2024
3b4b4c4
Refactored code
DianaStrauss Nov 19, 2024
2908860
Restructured testing
DianaStrauss Nov 20, 2024
b1f01dc
Refactored code
DianaStrauss Nov 22, 2024
22e64ff
Refactored code so that more endpoints are found
DianaStrauss Nov 25, 2024
b103831
Refactored code to be clearer
DianaStrauss Nov 28, 2024
e4bbdfa
Added owasp config file and owas openapi sepc
DianaStrauss Dec 2, 2024
f5ef612
Fixed some small bgs
DianaStrauss Dec 4, 2024
c6d33fe
Adjusted test cases to get better analysis
DianaStrauss Dec 4, 2024
96a400d
Added setup for automatic testing
DianaStrauss Dec 5, 2024
b0162fc
refactored test cases
DianaStrauss Dec 5, 2024
3e50596
refactored test cases
DianaStrauss Dec 6, 2024
9306dc6
refactored test cases
DianaStrauss Dec 6, 2024
0f8f445
Refactored tree of thought prompt
DianaStrauss Dec 8, 2024
b62bb01
adjusted gitignore
DianaStrauss Dec 11, 2024
dd0c17e
Refactored classification of endpoints
DianaStrauss Dec 11, 2024
1af2564
Adjusted test cases for better testing
DianaStrauss Dec 12, 2024
340280e
made continuous testing easier
DianaStrauss Dec 12, 2024
04ebcfa
Adjusted prompts to be more tailored
DianaStrauss Dec 15, 2024
1ff5fa2
Refactored and adjusted code to work also for crapi benchmark
DianaStrauss Dec 20, 2024
4dca56d
Cleaned up code
DianaStrauss Jan 9, 2025
5535eb0
Refactored test cases for better vulnerability coverage
DianaStrauss Jan 30, 2025
4ea54fc
Refactored code
DianaStrauss Feb 7, 2025
bf3395b
Added test case
DianaStrauss Feb 17, 2025
1aba1b7
adjusted report
Feb 19, 2025
b4e683b
Refactored code
DianaStrauss Mar 17, 2025
285ca9e
Anonymized readme
Mar 17, 2025
90f4028
Cleaned up code from prints and unnecessary code
DianaStrauss Mar 25, 2025
f9e09b5
Merge remote-tracking branch 'origin/web-api-testing' into web-api-te…
DianaStrauss Mar 25, 2025
b0c2b8b
Merge remote-tracking branch 'origin/development' into merge_web_api_…
DianaStrauss Apr 7, 2025
01ee69e
Adjusted code to work with web_api_testing
DianaStrauss Apr 7, 2025
32b73ab
Refactored code for better readability and testing
DianaStrauss Apr 13, 2025
303baf6
added configuration handler to better test
DianaStrauss Apr 13, 2025
4276f0f
Adjusted test of prompt engineer
DianaStrauss Apr 13, 2025
40f4ff1
Adjusted code for test
DianaStrauss Apr 13, 2025
c6b7ecd
Adjusted code and tests
Apr 14, 2025
44710f3
Adjusted tests and refactored code for better readability
Apr 14, 2025
a695971
Added test cases for pentesting information and test handler + refact…
DianaStrauss Apr 17, 2025
6f05e75
Removed unnecessary prints and added documentation
DianaStrauss Apr 22, 2025
ac58b5a
Removed unnecessary comments
DianaStrauss Apr 22, 2025
02c861f
Fixed Linter issue
DianaStrauss Apr 22, 2025
3a22053
Fixed test imports for pipeline
DianaStrauss Apr 22, 2025
0d34191
Added needed dependencies to pyproject.toml
DianaStrauss Apr 22, 2025
970b72d
Added needed dependencies to pyproject.toml
DianaStrauss Apr 22, 2025
4366132
Added needed dependencies to pyproject.toml
DianaStrauss Apr 22, 2025
9d16710
Removed test case that breaks pipeline
DianaStrauss Apr 22, 2025
9b78c6c
Adjusted init for test_handler
DianaStrauss Apr 22, 2025
9ea050b
Added needed dependencies to pyproject.toml
DianaStrauss Apr 22, 2025
424c989
Merge branch 'development' into merge_web_api_testing_development
DianaStrauss Apr 22, 2025
dbfef99
Added missing dependency
DianaStrauss Apr 22, 2025
696e395
Added missing dependency
DianaStrauss Apr 22, 2025
5e3b112
Added imports in __init__
DianaStrauss Apr 22, 2025
a6653ad
Added files
DianaStrauss Apr 22, 2025
ca17dd0
Moved config files to proper locatin
DianaStrauss Apr 22, 2025
5df1e20
updated README.md with correct image
Qsan1 May 1, 2025
a0977af
Merge pull request #120 from CoralStack/development
andreashappe May 1, 2025
e1b70ab
Merge branch 'development' into merge_web_api_testing_development
DianaStrauss May 13, 2025
78b681d
fixed syntax error in .toml
DianaStrauss May 13, 2025
8ae94fb
Fix linting
DianaStrauss May 13, 2025
9c4842f
Fix linting
DianaStrauss May 13, 2025
4d5122f
Fixed wrong import
DianaStrauss May 13, 2025
600ed43
Fixed import in testing
DianaStrauss May 13, 2025
f33c154
Fixed input variables
DianaStrauss May 13, 2025
e1c8cb4
Fixed input variables
DianaStrauss May 13, 2025
be0ff19
Fixed input variables
DianaStrauss May 13, 2025
985d740
Removed helper files
DianaStrauss May 14, 2025
19afc59
Fixed typo in parsed_information.py name
DianaStrauss May 14, 2025
b5f5688
Fixed typo in parsed_information.py name
DianaStrauss May 14, 2025
f748d5f
Update src/hackingBuddyGPT/usecases/web_api_testing/documentation/par…
DianaStrauss May 14, 2025
8d8a72c
Merge pull request #114 from ipa-lab/merge_web_api_testing_development
andreashappe May 14, 2025
290b148
moved prompt generation into utils and adjusted prompt engineer and p…
DianaStrauss May 20, 2025
bb2bd3b
Added prompt file and added logging of prompt
DianaStrauss May 23, 2025
fdf3d71
Added comments to icl
DianaStrauss May 23, 2025
aecb0be
fixed tests
DianaStrauss May 23, 2025
84f6795
Merge pull request #122 from ipa-lab/adapt_prompt_engineer
andreashappe May 23, 2025
f40bbc2
complete tmux local shell integration
ShreyasMahajann Aug 8, 2025
9ee831b
Merge branch 'development' into production
ShreyasMahajann Aug 8, 2025
bc22dff
Merge pull request #127 from ShreyasMahajann/production
andreashappe Aug 27, 2025
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Added evaluation to documentation
  • Loading branch information
DianaStrauss committed Nov 18, 2024
commit e228cd8bd9903a19bb4644247d84767b7306bd96
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ def __init__(self, llm_handler: LLMHandler, response_handler: ResponseHandler, s
"""
self.response_handler = response_handler
self.schemas = {}
self.query_params = {}
print(f'Name:{name}')
self.endpoint_methods = {}
self.filename = f"{name.lower()}_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.yaml"
Expand Down Expand Up @@ -119,6 +120,7 @@ def update_openapi_spec(self, resp, result, result_str):
)
self.schemas = self.openapi_spec["components"]["schemas"]


# Add example and reference to the method's responses if available
if example or reference or status_message == "No Content":
if path in endpoints.keys() and method.lower() not in endpoints[path].values():
Expand All @@ -143,6 +145,25 @@ def update_openapi_spec(self, resp, result, result_str):
# Ensure uniqueness of methods for each path
endpoint_methods[path] = list(set(endpoint_methods[path]))

# Add query parameters to the OpenAPI path item object
query_params_dict = self.pattern_matcher.extract_query_params(path)
if query_params_dict != {}:
query_params = query_params_dict.keys()
endpoints[path][method.lower()].setdefault('parameters', [])
for param, value in query_params.items():
param_entry = {
"name": param,
"in": "query",
"required": True, # Change this as needed
"schema": {
"type": self.get_type(value) # Adjust the type based on actual data type
}
}
endpoints[path][method.lower()]['parameters'].append(param_entry)
if path not in self.query_params.keys():
self.query_params[path] = []
self.query_params[path].append(param)

return list(self.openapi_spec["endpoints"].keys())

def write_openapi_to_yaml(self):
Expand Down Expand Up @@ -213,18 +234,16 @@ def found_all_endpoints(self):
else:
return True

def match_patterns(self, path):
if bool(re.search(r"/\d+", path)):
path = re.sub(r"/\d+", "/:id", path)

# Check if the path matches the pattern
if re.match(r"^/api/books/\d+/characters\?page=\d+$", path):
path = re.sub(r"(?<=page=)\d+", ":id", path)
pattern = r"^characters\?page=\d+&pageSize=\d+$"
pattern = r"^characters\?page=\d+&pageSize=\d+$"
# Check if the pattern matches the entire string
if re.match(pattern, path ):
updated_path = re.sub(r"(page=)\d+", r"\1{page}", path)
updated_path = re.sub(r"(pageSize=)\d+", r"\1{pagesize}", updated_path)

return path


def get_type(self, value):
def is_double(s):
# Matches numbers like -123.456, +7.890, and excludes integers
return re.fullmatch(r"[+-]?(\d+\.\d*|\.\d+)([eE][+-]?\d+)?", s) is not None
if value.isdigit():
return "integer"
elif is_double(value):
return "double"
else:
return "string"

Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ def replace_according_to_pattern(self, path):
return self.replace_parameters(path)
return path

def extract_query_params(self, path):
# Extract query parameters from a path and return them as a dictionary
params = {}
matches = self.patterns['query_params'].findall(path)
for _, param, value in matches:
params[param] = value
return params


if __name__ == "__main__":
# Example usage
Expand All @@ -67,3 +75,9 @@ def replace_according_to_pattern(self, path):

print(modified_path)
print(modified_nested_path)
print(f'{example_path}')

print(f'extracted parameters: {matcher.extract_query_params(example_path)}')
print(f'{example_nested_path}')

print(f'extracted parameters: {matcher.extract_query_params(example_nested_path)}')
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ def evaluate_result(self, result: Any, prompt_history: Prompt) -> Any:
def extract_key_elements_of_response(self, raw_response: Any) ->str:
status_code, headers, body = self.response_analyzer.parse_http_response(raw_response)
return "Status Code: " + str(status_code) + "\nHeaders:"+ str(headers)+ "\nBody"+ str(body)
def evaluate_response(self, response, completion, prompt_history, log, categorized_endpoints):
def handle_response(self, response, completion, prompt_history, log, categorized_endpoints):
"""
Evaluates the response to determine if it is acceptable.

Expand All @@ -310,6 +310,15 @@ def evaluate_response(self, response, completion, prompt_history, log, categoriz
self.repeat_counter = 0
self.prompt_helper.hint_for_next_round = f'Try this endpoint in the next round {next(self.common_endpoints)}'

if response.__class__.__name__ == "RecordNote":
prompt_history.append(tool_message(response, tool_call_id))
return False, prompt_history, None, None

else:
return self.handle_http_response(response, prompt_history, log, completion, message, categorized_endpoints, tool_call_id)


def handle_http_response(self, response: Any, prompt_history: Any, log: Any, completion: Any, message: Any, categorized_endpoints, tool_call_id) -> Any:
parts = parts = [part for part in response.action.path.split("/") if part]
if response.action.path == self.last_path or response.action.path in self.prompt_helper.unsuccessful_paths or response.action.path in self.prompt_helper.found_endpoints:
self.prompt_helper.hint_for_next_round = f"DO not try this path {self.last_path}. You already tried this before!"
Expand Down Expand Up @@ -377,7 +386,6 @@ def evaluate_response(self, response, completion, prompt_history, log, categoriz
categorized_endpoints)
self.query_counter = 0

# Append status message to prompt history
prompt_history.append(tool_message(status_message, tool_call_id))

return is_successful, prompt_history, result, result_str
Expand All @@ -402,3 +410,4 @@ def extract_json(self, response: str) -> dict:
except (ValueError, json.JSONDecodeError) as e:
print(f"Error extracting JSON: {e}")
return {}

Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ def run_documentation(self, turn: int, move_type: str) -> None:
while not is_good:
prompt = self.prompt_engineer.generate_prompt(turn=turn, move_type=move_type,log=self._log , prompt_history=self._prompt_history, llm_handler =self.llm_handler)
response, completion = self.llm_handler.execute_prompt(prompt=prompt)
is_good, self._prompt_history, result, result_str = self.response_handler.evaluate_response(response, completion, self._prompt_history, self._log, self.categorized_endpoints)
is_good, self._prompt_history, result, result_str = self.response_handler.handle_response(response, completion, self._prompt_history, self._log, self.categorized_endpoints)
if result == None:
continue
self._prompt_history, self.prompt_engineer = self.documentation_handler.document_response(
Expand All @@ -238,16 +238,10 @@ def run_documentation(self, turn: int, move_type: str) -> None:
is_good = True
self.all_steps_done = True

# Use evaluator to record routes and parameters found
#routes_found = self.all_http_methods_found(turn)
#query_params_found = self.evaluator.all_query_params_found(turn) # This function should return the number found
#false_positives = self.evaluator.check_false_positives(response) # Define this function to determine FP count
self.evaluator.evaluate_response(turn, response, self.prompt_engineer.prompt_helper.found_endpoints)

# Record these results in the evaluator
#self.evaluator.results["routes_found"].append(routes_found)
#self.evaluator.results["query_params_found"].append(query_params_found)
#self.evaluator.results["false_positives"].append(false_positives)
# self.finalize_documentation_metrics()

self.finalize_documentation_metrics()

self.all_http_methods_found(turn)

Expand Down
52 changes: 30 additions & 22 deletions src/hackingBuddyGPT/usecases/web_api_testing/utils/evaluator.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
from hackingBuddyGPT.usecases.web_api_testing.documentation.pattern_matcher import PatternMatcher


class Evaluator:
def __init__(self, num_runs=10, config:str=""):
def __init__(self, num_runs=10, config=None):
self.pattern_matcher = PatternMatcher()
self.documented_query_params = config.get("query_params")
self.num_runs = num_runs
self.get_routes_documented = 20 # Example documented GET routes
self.query_params_documented = 12 # Example documented query parameters
Expand All @@ -13,11 +18,11 @@ def calculate_metrics(self):
Calculate evaluation metrics based on the simulated runs.
"""
# Average percentages of documented routes and parameters found
avg_routes_found = sum(self.results["routes_found"]) / self.num_runs
avg_query_params_found = sum(self.results["query_params_found"]) / self.num_runs
routes_found = len(self.results["routes_found"])
query_params_found = len(self.results["query_params_found"])

percent_routes_found = (avg_routes_found / self.get_routes_documented) * 100
percent_params_found = (avg_query_params_found / self.query_params_documented) * 100
percent_routes_found = (routes_found / self.get_routes_documented) * 100
percent_params_found = (query_params_found / self.query_params_documented) * 100

# Average false positives
avg_false_positives = sum(self.results["false_positives"]) / self.num_runs
Expand All @@ -38,7 +43,7 @@ def calculate_metrics(self):

return metrics

def check_false_positives(self, response):
def check_false_positives(self, path):
"""
Identify and count false positive query parameters in the response.

Expand All @@ -49,13 +54,11 @@ def check_false_positives(self, response):
int: The count of false positive query parameters.
"""
# Example list of documented query parameters
documented_query_params = ["user_id", "post_id", "page", "limit"]

# Extract the query parameters from the response
response_query_params = self.extract_query_params_from_response_data(response)
response_query_params = self.pattern_matcher.extract_query_params(path).keys()

# Identify false positives
false_positives = [param for param in response_query_params if param not in documented_query_params]
false_positives = [param for param in response_query_params if param not in self.documented_query_params]

return len(false_positives)

Expand All @@ -72,7 +75,7 @@ def extract_query_params_from_response_data(self, response):
# Placeholder code: Replace with actual logic to parse response and extract query parameters
return response.get("query_params", [])

def all_query_params_found(self, turn):
def all_query_params_found(self, path):
"""
Count the number of documented query parameters found in a response.

Expand All @@ -83,17 +86,16 @@ def all_query_params_found(self, turn):
int: The count of documented query parameters found in this turn.
"""
# Example list of documented query parameters
documented_query_params = ["user_id", "post_id", "page", "limit"]

# Simulate response query parameters found (this would usually come from the response data)
response_query_params = self.extract_query_params_from_response(turn)
response_query_params = self.pattern_matcher.extract_query_params(path).keys()

# Count the valid query parameters found in the response
valid_query_params = [param for param in response_query_params if param in documented_query_params]
valid_query_params = [param for param in response_query_params if param in self.documented_query_params]

return len(valid_query_params)

def extract_query_params_from_response(self, turn):
def extract_query_params_from_response(self, path):
"""
Extract query parameters from the response in a specific turn.

Expand All @@ -104,11 +106,17 @@ def extract_query_params_from_response(self, turn):
list: A list of query parameter names found in the response.
"""
# Placeholder code: Replace this with actual extraction logic
# Here, you should parse the actual API response to identify query parameters
example_responses = {
1: ["user_id", "page", "unknown_param"],
2: ["post_id", "limit"],
3: ["user_id", "limit", "extra_param"],
}
return example_responses.get(turn, [])
return self.pattern_matcher.extract_query_params(path).keys()

def evaluate_response(self, turn, response, routes_found):
# Use evaluator to record routes and parameters found
if response.__class__.__name__ != "RecordNote":
path = response.action.path
query_params_found = self.all_query_params_found(path) # This function should return the number found
false_positives = self.check_false_positives(path) # Define this function to determine FP count

# Record these results in the evaluator
self.results["routes_found"].append(routes_found)
self.results["query_params_found"].append(query_params_found)
self.results["false_positives"].append(false_positives)