Skip to content

Commit a48148a

Browse files
committed
feat: complete APISecurityEngine implementation with MIT License
0 parents  commit a48148a

41 files changed

Lines changed: 3251 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.github/workflows/ci.yml

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
name: CI
2+
3+
on:
4+
push:
5+
branches: [ "main" ]
6+
pull_request:
7+
branches: [ "main" ]
8+
9+
jobs:
10+
test-and-lint:
11+
runs-on: ubuntu-latest
12+
steps:
13+
- uses: actions/checkout@v4
14+
15+
- name: Install uv
16+
uses: astral-sh/setup-uv@v2
17+
with:
18+
version: "latest"
19+
20+
- name: Set up Python
21+
uses: actions/setup-python@v5
22+
with:
23+
python-version: "3.12"
24+
25+
- name: Install dependencies
26+
run: uv sync --all-extras --dev
27+
28+
- name: Run Ruff Linter
29+
run: uv run ruff check .
30+
31+
- name: Run Ruff Formatter
32+
run: uv run ruff format --check .
33+
34+
- name: Run Mypy
35+
run: uv run mypy apisecurityengine/ tests/
36+
37+
- name: Run Pytest
38+
run: uv run pytest tests/ --cov=apisecurityengine

.gitignore

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Environments
2+
.env
3+
.venv
4+
env/
5+
venv/
6+
ENV/
7+
env.bak/
8+
venv.bak/
9+
10+
# uv
11+
uv.lock
12+
13+
# Python
14+
__pycache__/
15+
*.py[cod]
16+
*$py.class
17+
*.so
18+
19+
# Distribution / packaging
20+
build/
21+
develop-eggs/
22+
dist/
23+
downloads/
24+
eggs/
25+
.eggs/
26+
lib/
27+
lib64/
28+
parts/
29+
sdist/
30+
var/
31+
wheels/
32+
share/python-wheels/
33+
*.egg-info/
34+
.installed.cfg
35+
*.egg
36+
MANIFEST
37+
38+
# Pytest / Coverage
39+
.coverage
40+
.tox/
41+
.nox/
42+
.pytest_cache/
43+
coverage.xml
44+
*.cover
45+
*.py,cover
46+
.hypothesis/
47+
48+
# IDEs
49+
.idea/
50+
.vscode/
51+
*.swp
52+
*.swo
53+
54+
# Output reports
55+
reports/
56+
*.json
57+
*.sarif
58+
*.html

.pre-commit-config.yaml

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
repos:
2+
- repo: https://github.com/pre-commit/pre-commit-hooks
3+
rev: v4.5.0
4+
hooks:
5+
- id: trailing-whitespace
6+
- id: end-of-file-fixer
7+
- id: check-yaml
8+
- id: check-added-large-files
9+
10+
- repo: https://github.com/astral-sh/ruff-pre-commit
11+
rev: v0.3.4
12+
hooks:
13+
- id: ruff
14+
args: [ --fix ]
15+
- id: ruff-format
16+
17+
- repo: https://github.com/pre-commit/mirrors-mypy
18+
rev: v1.9.0
19+
hooks:
20+
- id: mypy
21+
additional_dependencies: ["click", "rich"]

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2026 GlitchOrb
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# APISecurityEngine
2+
> Built and Maintained by @GlitchOrb
3+
4+
An API security testing automation tool that ingests OpenAPI/GraphQL/gRPC definitions, generates automated test plans, executes them with safety controls, and produces evidence-based reports mapped to OWASP API Top 10:2023.
5+
6+
## Requirements
7+
- Python 3.12+
8+
- [uv](https://github.com/astral-sh/uv) (recommended) or pip
9+
10+
## Installation & Setup
11+
12+
Using `uv`:
13+
14+
```bash
15+
# Clone the repository
16+
git clone https://github.com/GlitchOrb/APISecurityEngine.git
17+
cd APISecurityEngine
18+
19+
# Install dependencies and sync environment
20+
uv sync
21+
22+
# Run the CLI
23+
uv run ase --help
24+
```
25+
26+
## Development
27+
28+
```bash
29+
# Install pre-commit hooks
30+
uv run pre-commit install
31+
32+
# Run tests
33+
uv run pytest
34+
35+
# Type checking
36+
uv run mypy apisecurityengine/ tests/
37+
38+
# Linting & Formatting
39+
uv run ruff check .
40+
uv run ruff format .
41+
```
42+
43+
## CLI Usage
44+
45+
```bash
46+
# Get help
47+
ase --help
48+
49+
# Scan a target
50+
ase scan --target https://api.example.com --dry-run
51+
```
52+
53+
[![Open in Cloud Shell](https://gstatic.com/cloudssh/images/open-btn.svg)](https://shell.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https://github.com/GlitchOrb/APISecurityEngine.git&cloudshell_tutorial=cloudshell/tutorial.md&show=ide%2Cterminal&cloudshell_workspace=.)
54+
55+
56+
## Security Posture & Incident Patterns
57+
58+
APISecurityEngine includes checks and guidance for common real-world API incident patterns, such as:
59+
- Authorization bypass patterns (BOLA/IDOR) and role boundary violations
60+
- Weak authentication and token handling pitfalls
61+
- Unrestricted resource consumption (rate limiting / cost amplification)
62+
- SSRF-style URL fetch misuse
63+
- Security misconfiguration signals (CORS/headers/debug endpoints)
64+
- Improper API inventory exposure and forgotten endpoints
65+
- Secrets hygiene: preventing API keys/tokens from leaking into source control
66+
67+
> **Note:** APISecurityEngine is a testing and validation tool. It does not “patch” CVEs automatically; it helps identify risky patterns and provides recommended defenses.
68+
69+
| OWASP API Top 10:2023 | Heuristic / Execution Check | CWE Relevance | Defense Snippet Guide |
70+
| --- | --- | --- | --- |
71+
| **API1: BOLA** | Cross-profile parameter swapping (`/users/{id}` vs Profile B) | [CWE-284](https://cwe.mitre.org/data/definitions/284.html) | [Object-Level Auth Defenses](docs/defenses/object_level_auth.md) |
72+
| **API2: Broken Auth** | Unauthenticated execution on routes mapping `requires_auth=True` | [CWE-306](https://cwe.mitre.org/data/definitions/306.html) | [Secrets Hygiene Scanners](docs/defenses/secrets_hygiene.md) |
73+
| **API3: BOPLA** | Permissive payload insertions (`"is_admin": true`) | [CWE-915](https://cwe.mitre.org/data/definitions/915.html) | Explicit DTO Serialization Models |
74+
| **API4: Resource Consumption** | Enumerating missing limits/page schemas on collections | [CWE-770](https://cwe.mitre.org/data/definitions/770.html) | Implement Upper bounds pagination |
75+
| **API5: BFLA** | Profile A executions against isolated admin/dashboard domains | [CWE-285](https://cwe.mitre.org/data/definitions/285.html) | [Function-Level Auth Guards](docs/defenses/function_level_auth.md) |
76+
| **API6: Sensitive Flows** | Tracing business heuristics (`checkout`, `transfer`) | [CWE-799](https://cwe.mitre.org/data/definitions/799.html) | [Rate Limits & Bot Defenses](docs/defenses/rate_limiting.md) |
77+
| **API7: SSRF** | Metadata IPs/Localhost pinging injected via URL query parameters | [CWE-918](https://cwe.mitre.org/data/definitions/918.html) | [SSRF & Rebinding Protections](docs/defenses/ssrf_protection.md) |
78+
| **API8: Misconfigurations** | Trace/OPTIONS header evaluations and CORS misalignments | [CWE-16](https://cwe.mitre.org/data/definitions/16.html) | Enforce Global Proxies Security Headers |
79+
| **API9: Improper Inventory** | Routing bypass attempts natively against version shifting (e.g. `/v2/`) | [CWE-1059](https://cwe.mitre.org/data/definitions/1059.html) | Deprecate and 404 old environments |
80+
| **API10: Unsafe Consumption** | Unprotected webhook validations mapping omitted signature parameters | [CWE-300](https://cwe.mitre.org/data/definitions/300.html) | Always demand HMAC Webhook Signatures |

apisecurityengine/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
"""
2+
APISecurityEngine - Safe DAST automation for APIs.
3+
"""
4+
5+
__version__ = "0.1.0"

apisecurityengine/ai/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""
2+
AI modules for generating dynamic security scenarios.
3+
"""
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
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+
)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""
2+
Security checks mapped to OWASP API Security Top 10:2023.
3+
"""
4+
5+
from abc import ABC, abstractmethod
6+
from collections.abc import AsyncGenerator
7+
8+
from apisecurityengine.models.schemas import Finding, TargetConfig
9+
from apisecurityengine.runtime.http_runtime import HTTPRuntime
10+
from apisecurityengine.spec.endpoint_graph import EndpointGraph, EndpointNode
11+
12+
13+
class BaseCheck(ABC):
14+
"""Abstract base class for all vulnerability checks."""
15+
16+
@abstractmethod
17+
async def execute(
18+
self,
19+
target_config: TargetConfig,
20+
runtime: HTTPRuntime,
21+
graph: EndpointGraph,
22+
auth_profiles: dict[str, dict[str, str]],
23+
) -> AsyncGenerator[Finding, None]:
24+
"""Execute the check and yield findings."""
25+
if False:
26+
yield NotImplemented

0 commit comments

Comments
 (0)