
Conducting Api Security Testing
- 433 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Run structured API security tests on REST or GraphQL endpoints before release, covering auth, authorization, input handling, and common exploit paths.
About
Cybersecurity skill from mukul975/anthropic-cybersecurity-skills for conducting API security testing: systematic checks for broken authentication, access control, injection, and misconfiguration on API surfaces.
- API auth and authz testing
- Injection and input abuse checks
- Rate limit and exposure review
- Pre-production security gate
Conducting Api Security Testing by the numbers
- 433 all-time installs (skills.sh)
- +38 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #531 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill conducting-api-security-testingAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 433 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Run structured API security tests on REST or GraphQL endpoints before release, covering auth, authorization, input handling, and common exploit paths.
Files
Conducting API Security Testing
When to Use
- Testing API endpoints for authorization flaws, injection vulnerabilities, and business logic bypasses
- Assessing the security of microservices architecture where APIs are the primary communication method
- Validating that API gateway protections (rate limiting, authentication, input validation) are properly enforced
- Testing third-party API integrations for data exposure and insecure configurations
- Evaluating GraphQL APIs for introspection disclosure, query complexity attacks, and authorization bypasses
Do not use against APIs without written authorization, for load testing or denial-of-service testing unless explicitly scoped, or for testing production APIs that process real financial transactions without safeguards.
Prerequisites
- API documentation (OpenAPI/Swagger, GraphQL schema, Postman collection) or application access to reverse-engineer the API
- Burp Suite Professional configured to intercept API traffic with JSON/XML content type handling
- Postman or Insomnia for organizing and replaying API requests across different authentication contexts
- Valid API tokens or credentials at multiple privilege levels (unauthenticated, standard user, admin)
- Target API base URL and version information
Workflow
Step 1: API Discovery and Documentation
Map the complete API attack surface:
- Import API documentation: Load OpenAPI/Swagger specs into Postman or Burp Suite to catalog all endpoints, methods, parameters, and authentication requirements
- Reverse-engineer undocumented APIs: Proxy the mobile app or web frontend through Burp Suite and exercise all features to capture API calls. Export the Burp sitemap as the baseline endpoint inventory.
- GraphQL introspection: Send an introspection query to discover the full schema:
{"query": "{__schema{types{name,fields{name,args{name,type{name}}}}}}"}- Endpoint enumeration: Fuzz for hidden API versions (
/api/v1/,/api/v2/,/api/internal/), debug endpoints (/api/debug,/api/health,/api/metrics), and administrative endpoints - Document authentication mechanisms: Identify if the API uses API keys, OAuth 2.0 Bearer tokens, JWT, session cookies, or mutual TLS
Step 2: Authentication and Token Testing
Test authentication mechanisms for weaknesses:
- JWT analysis: Decode the JWT and inspect claims (sub, exp, iss, aud, role). Test:
- Algorithm confusion: Change
algtononeand remove the signature - Key confusion: Change
algfrom RS256 to HS256 and sign with the public key - Weak secret: Brute-force the HMAC secret with
hashcat -m 16500 jwt.txt wordlist.txt - Token expiration: Verify tokens expire and cannot be used after expiration
- Claim tampering: Modify role, userId, or permission claims and re-sign
- OAuth 2.0 testing: Check for redirect_uri manipulation, authorization code reuse, token leakage in Referer headers, and missing state parameter (CSRF)
- API key security: Test if API keys are validated per-endpoint, if revoked keys are immediately rejected, and if keys in query strings appear in access logs or analytics
Step 3: Authorization Testing (BOLA/BFLA)
Test for Broken Object Level Authorization (BOLA) and Broken Function Level Authorization (BFLA):
- BOLA (IDOR) testing: For every endpoint that returns user-specific data, replace the object identifier with another user's identifier:
GET /api/users/123/orders->GET /api/users/456/orders- Test with numeric IDs, UUIDs, usernames, and email addresses
- Automate with Burp Autorize extension: configure it with two sessions (attacker and victim) and replay all requests
- BFLA testing: Using a low-privilege token, attempt to access administrative endpoints:
DELETE /api/users/456(admin-only delete)PUT /api/users/456/role(role modification)GET /api/admin/dashboard(admin panel data)- Mass assignment: Send additional JSON properties not shown in the documentation:
PUT /api/users/123
{"name": "Test", "role": "admin", "isVerified": true, "balance": 99999}- HTTP method testing: If GET works on an endpoint, try PUT, PATCH, DELETE, and OPTIONS to discover unprotected methods
Step 4: Input Validation and Injection Testing
Test API inputs for injection and validation flaws:
- SQL injection in API parameters: Test all parameters (path, query, body, headers) with SQL injection payloads. JSON APIs are often overlooked:
{"username": "admin' OR 1=1--", "password": "test"} - NoSQL injection: For MongoDB backends, test with operator injection:
{"username": {"$gt": ""}, "password": {"$gt": ""}} - SSRF via API: Test any parameter that accepts URLs (webhook URLs, avatar URLs, import endpoints) with internal addresses and cloud metadata endpoints
- GraphQL-specific injection: Test for query depth attacks, alias-based batching for brute force, and field suggestion enumeration
- XXE in XML APIs: Submit XML content with external entity declarations to API endpoints that accept XML
- Rate limiting validation: Send 100+ rapid requests to authentication endpoints, password reset, and OTP verification to test for brute force protection
Step 5: Data Exposure and Response Analysis
Check for excessive data exposure in API responses:
- Verbose responses: Compare the data returned in API responses with what the UI displays. APIs often return more fields than needed (internal IDs, creation timestamps, email addresses of other users, role information).
- Error message analysis: Trigger errors by sending malformed input, invalid tokens, and non-existent resources. Check if error messages reveal stack traces, database queries, internal paths, or technology details.
- Pagination and enumeration: Test if enumeration is possible by iterating through paginated responses (
/api/users?page=1,page=2, etc.) to extract all records - GraphQL data exposure: Query for fields not intended for the current user's role. Test nested queries that traverse relationships to access unauthorized data.
- Debug endpoints: Check
/api/debug,/api/status,/metrics,/health,/.env,/api/swagger.jsonfor exposed internal information
Key Concepts
| Term | Definition |
|---|---|
| BOLA | Broken Object Level Authorization (OWASP API #1); failure to verify that the requesting user is authorized to access a specific object, enabling IDOR attacks |
| BFLA | Broken Function Level Authorization (OWASP API #5); failure to restrict administrative or privileged API functions from being accessed by lower-privilege users |
| Mass Assignment | A vulnerability where the API binds client-provided data to internal object properties without filtering, allowing attackers to modify fields they should not have access to |
| GraphQL Introspection | A built-in GraphQL feature that exposes the complete API schema including all types, fields, and relationships; should be disabled in production |
| JWT | JSON Web Token; a self-contained token format used for API authentication containing claims signed with a secret or key pair |
| Rate Limiting | Controls that restrict the number of API requests a client can make within a time window, preventing brute force, enumeration, and abuse |
Tools & Systems
- Burp Suite Professional: HTTP proxy for intercepting, modifying, and replaying API requests with extensions like Autorize for automated authorization testing
- Postman: API development platform used for organizing endpoint collections, scripting tests, and comparing responses across authentication contexts
- GraphQL Voyager: Visual tool for exploring GraphQL schemas obtained through introspection queries
- jwt.io / jwt_tool: Tools for decoding, analyzing, and tampering with JWT tokens to test authentication bypasses
- Nuclei: Template-based scanner with API-specific templates for detecting common misconfigurations and known vulnerabilities
Common Scenarios
Scenario: API Security Assessment for a Fintech Mobile Application
Context: A fintech startup has a mobile banking application with a REST API backend. The API handles account management, fund transfers, bill payments, and transaction history. The tester has Swagger documentation and accounts at user and admin levels.
Approach: 1. Import Swagger spec into Postman, generating 87 endpoint collections across 12 controllers 2. Discover BOLA on /api/v1/accounts/{accountId}/transactions allowing any authenticated user to view any account's transaction history 3. Find mass assignment on the user update endpoint where adding "dailyTransferLimit": 999999 bypasses the configured transfer limit 4. Identify that the fund transfer endpoint lacks rate limiting, allowing unlimited transfer attempts without throttling 5. Discover that JWT tokens have a 30-day expiration with no refresh token rotation, enabling long-lived session hijacking 6. Find that the admin endpoint /api/v1/admin/users is accessible with a standard user token (BFLA) 7. Report all findings with CVSS scores and specific API code-level remediation guidance
Pitfalls:
- Testing only the endpoints documented in Swagger and missing undocumented or deprecated API versions
- Not testing the same endpoint with tokens from every privilege level to detect authorization bypasses
- Ignoring response body analysis for excessive data exposure when the UI only shows a subset of returned fields
- Failing to test for mass assignment by only sending fields shown in the documentation
Output Format
## Finding: Broken Object Level Authorization in Transaction History API
**ID**: API-001
**Severity**: Critical (CVSS 9.1)
**Affected Endpoint**: GET /api/v1/accounts/{accountId}/transactions
**OWASP API Category**: API1:2023 - Broken Object Level Authorization
**Description**:
The transaction history endpoint returns all transactions for the specified
account without verifying that the authenticated user owns the account. Any
authenticated user can view the complete transaction history of any account
by substituting the accountId path parameter.
**Proof of Concept**:
1. Authenticate as User A (account ID: ACC-10045)
2. Request: GET /api/v1/accounts/ACC-10046/transactions
Authorization: Bearer <User_A_token>
3. Response: 200 OK with User B's full transaction history
**Impact**:
Any authenticated user can view the complete financial transaction history of
all 45,000 customer accounts, including amounts, dates, recipients, and
transaction descriptions.
**Remediation**:
Implement server-side authorization check that verifies the authenticated user
owns the requested account before returning data:
const account = await Account.findById(accountId);
if (account.userId !== req.user.id) return res.status(403).json({error: "Forbidden"});
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: API Security Testing Agent
Overview
Tests REST and GraphQL APIs for OWASP API Security Top 10 vulnerabilities including BOLA, BFLA, mass assignment, rate limiting, JWT bypass, and GraphQL introspection disclosure. For authorized penetration testing only.
Dependencies
| Package | Version | Purpose |
|---|---|---|
| requests | >=2.28 | HTTP requests to target APIs |
CLI Usage
python agent.py --base-url https://api.target.com --token <jwt> \
--low-priv-token <jwt> --graphql --output report.jsonArguments
| Argument | Required | Description |
|---|---|---|
--base-url | Yes | Target API base URL |
--token | No | Auth bearer token for authenticated testing |
--low-priv-token | No | Low-privilege token for BFLA testing |
--login-endpoint | No | Login endpoint for rate limiting test (default: /api/auth/login) |
--graphql | No | Test GraphQL introspection disclosure |
--output | No | Output file (default: api_security_report.json) |
Key Functions
test_bola(base_url, endpoint_template, id_field, valid_id, other_id, auth_token)
Tests Broken Object Level Authorization by accessing another user's resource with own credentials.
test_bfla(base_url, admin_endpoints, low_priv_token)
Tests admin endpoints with low-privilege tokens using GET, POST, DELETE methods.
test_mass_assignment(base_url, endpoint, auth_token, extra_fields)
Sends undocumented fields (role, isAdmin) to update endpoints and verifies if they persist.
test_rate_limiting(base_url, endpoint, num_requests)
Sends rapid requests to detect absence of rate limiting on authentication endpoints.
test_jwt_none_algorithm(base_url, endpoint, jwt_token)
Forges JWT with alg: none to test for algorithm confusion vulnerabilities.
test_graphql_introspection(base_url, graphql_endpoint)
Sends introspection query to check if full schema disclosure is enabled.
test_excessive_data_exposure(base_url, endpoint, auth_token, expected_fields)
Compares API response fields against expected fields to identify over-exposure.
OWASP API Top 10 Coverage
| OWASP ID | Vulnerability | Function |
|---|---|---|
| API1:2023 | Broken Object Level Authorization | test_bola |
| API3:2023 | Excessive Data Exposure | test_excessive_data_exposure |
| API4:2023 | Unrestricted Resource Consumption | test_rate_limiting |
| API5:2023 | Broken Function Level Authorization | test_bfla |
| API6:2023 | Mass Assignment | test_mass_assignment |
#!/usr/bin/env python3
# For authorized penetration testing and lab environments only
"""API Security Testing Agent - Tests REST/GraphQL APIs for OWASP API Top 10 vulnerabilities."""
import json
import logging
import argparse
from datetime import datetime
from urllib.parse import urljoin
import requests
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
def test_bola(base_url, endpoint_template, id_field, valid_id, other_id, auth_token):
"""Test for Broken Object Level Authorization (BOLA/IDOR)."""
headers = {"Authorization": f"Bearer {auth_token}"}
own_resp = requests.get(
urljoin(base_url, endpoint_template.replace(f"{{{id_field}}}", str(valid_id))),
headers=headers, timeout=10,
)
other_resp = requests.get(
urljoin(base_url, endpoint_template.replace(f"{{{id_field}}}", str(other_id))),
headers=headers, timeout=10,
)
vulnerable = other_resp.status_code == 200 and len(other_resp.content) > 50
result = {
"test": "BOLA (API1:2023)",
"endpoint": endpoint_template,
"own_status": own_resp.status_code,
"other_status": other_resp.status_code,
"vulnerable": vulnerable,
}
if vulnerable:
logger.warning("BOLA vulnerability found: %s", endpoint_template)
return result
def test_bfla(base_url, admin_endpoints, low_priv_token):
"""Test for Broken Function Level Authorization (BFLA)."""
headers = {"Authorization": f"Bearer {low_priv_token}"}
results = []
for endpoint in admin_endpoints:
for method in ["GET", "POST", "DELETE"]:
try:
resp = requests.request(
method, urljoin(base_url, endpoint),
headers=headers, timeout=10,
)
vulnerable = resp.status_code in (200, 201, 204)
results.append({
"test": "BFLA (API5:2023)",
"endpoint": endpoint,
"method": method,
"status": resp.status_code,
"vulnerable": vulnerable,
})
if vulnerable:
logger.warning("BFLA: %s %s accessible with low-priv token", method, endpoint)
except requests.RequestException:
continue
return results
def test_mass_assignment(base_url, endpoint, auth_token, extra_fields):
"""Test for mass assignment vulnerability."""
headers = {"Authorization": f"Bearer {auth_token}", "Content-Type": "application/json"}
resp = requests.put(
urljoin(base_url, endpoint),
headers=headers, json=extra_fields, timeout=10,
)
verify = requests.get(urljoin(base_url, endpoint), headers=headers, timeout=10)
verify_data = verify.json() if verify.status_code == 200 else {}
vulnerable = False
for key, value in extra_fields.items():
if key in verify_data and verify_data[key] == value:
vulnerable = True
break
return {
"test": "Mass Assignment (API6:2023)",
"endpoint": endpoint,
"injected_fields": list(extra_fields.keys()),
"vulnerable": vulnerable,
"update_status": resp.status_code,
}
def test_rate_limiting(base_url, endpoint, num_requests=100):
"""Test rate limiting on sensitive endpoints."""
statuses = []
for i in range(num_requests):
try:
resp = requests.post(
urljoin(base_url, endpoint),
json={"username": f"test{i}", "password": "wrong"},
timeout=5,
)
statuses.append(resp.status_code)
if resp.status_code == 429:
logger.info("Rate limiting triggered after %d requests", i + 1)
return {
"test": "Rate Limiting (API4:2023)",
"endpoint": endpoint,
"requests_sent": i + 1,
"rate_limited": True,
"vulnerable": False,
}
except requests.RequestException:
break
return {
"test": "Rate Limiting (API4:2023)",
"endpoint": endpoint,
"requests_sent": len(statuses),
"rate_limited": False,
"vulnerable": True,
}
def test_jwt_none_algorithm(base_url, endpoint, jwt_token):
"""Test for JWT 'none' algorithm bypass."""
import base64
parts = jwt_token.split(".")
if len(parts) != 3:
return {"test": "JWT None Algorithm", "vulnerable": False, "error": "Invalid JWT"}
header = json.loads(base64.urlsafe_b64decode(parts[0] + "=="))
header["alg"] = "none"
new_header = base64.urlsafe_b64encode(json.dumps(header).encode()).rstrip(b"=").decode()
forged_token = f"{new_header}.{parts[1]}."
resp = requests.get(
urljoin(base_url, endpoint),
headers={"Authorization": f"Bearer {forged_token}"},
timeout=10,
)
vulnerable = resp.status_code == 200
return {
"test": "JWT None Algorithm",
"endpoint": endpoint,
"forged_status": resp.status_code,
"vulnerable": vulnerable,
}
def test_graphql_introspection(base_url, graphql_endpoint="/graphql"):
"""Test if GraphQL introspection is enabled."""
query = {"query": "{__schema{types{name,fields{name,args{name,type{name}}}}}}"}
resp = requests.post(
urljoin(base_url, graphql_endpoint),
json=query, timeout=10,
)
has_schema = "types" in resp.text if resp.status_code == 200 else False
return {
"test": "GraphQL Introspection Disclosure",
"endpoint": graphql_endpoint,
"status": resp.status_code,
"introspection_enabled": has_schema,
"vulnerable": has_schema,
}
def test_excessive_data_exposure(base_url, endpoint, auth_token, expected_fields):
"""Test for excessive data exposure in API responses."""
headers = {"Authorization": f"Bearer {auth_token}"}
resp = requests.get(urljoin(base_url, endpoint), headers=headers, timeout=10)
if resp.status_code != 200:
return {"test": "Excessive Data Exposure", "endpoint": endpoint, "vulnerable": False}
data = resp.json()
extra_fields = [k for k in data.keys() if k not in expected_fields] if isinstance(data, dict) else []
return {
"test": "Excessive Data Exposure (API3:2023)",
"endpoint": endpoint,
"expected_fields": expected_fields,
"extra_fields": extra_fields,
"vulnerable": len(extra_fields) > 0,
}
def generate_report(findings):
"""Generate API security testing report."""
critical = [f for f in findings if f.get("vulnerable")]
report = {
"timestamp": datetime.utcnow().isoformat(),
"total_tests": len(findings),
"vulnerabilities_found": len(critical),
"findings": findings,
}
logger.info("Report: %d tests, %d vulnerabilities", len(findings), len(critical))
return report
def main():
parser = argparse.ArgumentParser(description="API Security Testing Agent")
parser.add_argument("--base-url", required=True, help="API base URL")
parser.add_argument("--token", help="Auth bearer token")
parser.add_argument("--low-priv-token", help="Low-privilege bearer token for BFLA testing")
parser.add_argument("--login-endpoint", default="/api/auth/login", help="Login endpoint for rate limit test")
parser.add_argument("--graphql", action="store_true", help="Test GraphQL introspection")
parser.add_argument("--output", default="api_security_report.json")
args = parser.parse_args()
findings = []
findings.append(test_rate_limiting(args.base_url, args.login_endpoint, 50))
if args.graphql:
findings.append(test_graphql_introspection(args.base_url))
if args.low_priv_token:
admin_eps = ["/api/admin/users", "/api/admin/settings", "/api/admin/dashboard"]
findings.extend(test_bfla(args.base_url, admin_eps, args.low_priv_token))
if args.token:
findings.append(test_jwt_none_algorithm(args.base_url, "/api/profile", args.token))
report = generate_report(findings)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
logger.info("Report saved to %s", args.output)
if __name__ == "__main__":
main()