|
| 1 | +import json |
| 2 | + |
| 3 | +from apisecurityengine.models.scenario import ScenarioPlan |
| 4 | +from apisecurityengine.spec.endpoint_graph import EndpointGraph |
| 5 | + |
| 6 | + |
| 7 | +class ScenarioAgent: |
| 8 | + """ |
| 9 | + Module for building and validating multi-step API security test scenarios. |
| 10 | + Maintained by @GlitchOrb |
| 11 | + """ |
| 12 | + |
| 13 | + PROMPT_TEMPLATE = """ |
| 14 | +You are a senior API Security Engineer. |
| 15 | +Based on the following endpoint graph, generate a multi-step attack scenario to test for complex vulnerabilities (e.g., IDOR across different endpoints, state manipulation). |
| 16 | +
|
| 17 | +GRAPH SUMMARY: |
| 18 | +{graph_summary} |
| 19 | +
|
| 20 | +RULES: |
| 21 | +1. Return ONLY valid JSON matching the exact schema below. |
| 22 | +2. DO NOT include explanations outside the JSON (no markdown fences, just pure JSON). |
| 23 | +3. Steps modifying state (POST, PUT, PATCH, DELETE) MUST have "is_destructive": true. |
| 24 | +4. Paths must be relative and MUST strictly start with "/". |
| 25 | +5. Use recognizable HTTP methods (e.g., GET, POST, DELETE). |
| 26 | +
|
| 27 | +REQUIRED JSON SCHEMA: |
| 28 | +{{ |
| 29 | + "name": "string", |
| 30 | + "description": "string", |
| 31 | + "steps": [ |
| 32 | + {{ |
| 33 | + "id": "string", |
| 34 | + "description": "string", |
| 35 | + "request": {{ |
| 36 | + "method": "string", |
| 37 | + "path": "string", |
| 38 | + "headers": {{"string": "string"}}, |
| 39 | + "body": "string | null" |
| 40 | + }}, |
| 41 | + "is_destructive": boolean |
| 42 | + }} |
| 43 | + ], |
| 44 | + "expected_signals": ["string"], |
| 45 | + "stop_conditions": ["string"] |
| 46 | +}} |
| 47 | +""" |
| 48 | + |
| 49 | + @staticmethod |
| 50 | + def build_prompt(graph: EndpointGraph) -> str: |
| 51 | + """Create the prompt injected with the endpoint graph context.""" |
| 52 | + summary_lines = [] |
| 53 | + for e in graph.endpoints: |
| 54 | + params = [p.get("name") for p in e.parameters if p.get("name")] |
| 55 | + summary_lines.append(f"- {e.method} {e.path} (params: {', '.join(params)})") # type: ignore |
| 56 | + graph_summary = "\n".join(summary_lines) |
| 57 | + return ScenarioAgent.PROMPT_TEMPLATE.format(graph_summary=graph_summary) |
| 58 | + |
| 59 | + @staticmethod |
| 60 | + def parse_and_validate(json_str: str) -> ScenarioPlan: |
| 61 | + """Parses the generator output and executes a deterministic safety validation sequence.""" |
| 62 | + data = json.loads(json_str.strip()) |
| 63 | + plan = ScenarioPlan(**data) |
| 64 | + |
| 65 | + # Safety Validations |
| 66 | + for step in plan.steps: |
| 67 | + method = step.request.method.upper() |
| 68 | + |
| 69 | + # Method Check |
| 70 | + if method not in ["GET", "OPTIONS", "HEAD", "TRACE", "POST", "PUT", "PATCH", "DELETE"]: |
| 71 | + raise ValueError(f"Step '{step.id}' uses an unrecognized method: {method}") |
| 72 | + |
| 73 | + # Safety Flag Check (Mutative actions must be marked) |
| 74 | + is_mutative = method in ["POST", "PUT", "PATCH", "DELETE"] |
| 75 | + if is_mutative and not step.is_destructive: |
| 76 | + raise ValueError( |
| 77 | + f"Step '{step.id}' uses mutative method {method} but 'is_destructive' is False. " |
| 78 | + "All mutative operations must explicitly be marked destructive." |
| 79 | + ) |
| 80 | + |
| 81 | + # Routing Check (Ensure relative routing bounding) |
| 82 | + if not step.request.path.startswith("/"): |
| 83 | + raise ValueError( |
| 84 | + f"Step '{step.id}' has an invalid path '{step.request.path}'. " |
| 85 | + "Paths must be absolute relative to the target base_url (starting with '/')." |
| 86 | + ) |
| 87 | + |
| 88 | + return plan |
| 89 | + |
| 90 | + @staticmethod |
| 91 | + def generate_mock_response(graph: EndpointGraph) -> str: |
| 92 | + """A deterministic mock payload mimicking a generator output matching the constraints.""" |
| 93 | + return json.dumps( |
| 94 | + { |
| 95 | + "name": "BOLA Sequence Test", |
| 96 | + "description": "Creates an object with Profile A, attempts to fetch it with Profile B.", |
| 97 | + "steps": [ |
| 98 | + { |
| 99 | + "id": "step_1", |
| 100 | + "description": "Create object", |
| 101 | + "request": { |
| 102 | + "method": "POST", |
| 103 | + "path": "/users", |
| 104 | + "headers": {"Content-Type": "application/json"}, |
| 105 | + "body": '{"name": "test"}', |
| 106 | + }, |
| 107 | + "is_destructive": True, |
| 108 | + }, |
| 109 | + { |
| 110 | + "id": "step_2", |
| 111 | + "description": "Fetch object", |
| 112 | + "request": {"method": "GET", "path": "/users/123", "headers": {}}, |
| 113 | + "is_destructive": False, |
| 114 | + }, |
| 115 | + ], |
| 116 | + "expected_signals": ["201 Created on step_1", "403 Forbidden on step_2"], |
| 117 | + "stop_conditions": ["Failed to create object in step_1"], |
| 118 | + } |
| 119 | + ) |
0 commit comments