
Performing Api Security Testing With Postman
- 170 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with testing & qa tasks.
About
performing-api-security-testing-with-postman is a Claude Code skill in the Testing & QA category.
- performing-api-security-testing-with-postman
- Testing & QA
- AI-coding skill
Performing Api Security Testing With Postman by the numbers
- 170 all-time installs (skills.sh)
- +24 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #851 of 2,153 Testing & QA 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 performing-api-security-testing-with-postmanAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 170 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with testing & qa tasks.
Files
Performing API Security Testing with Postman
When to Use
- Building repeatable API security test suites for OWASP API Security Top 10 coverage
- Creating automated security regression tests that run in CI/CD pipelines via Newman
- Testing API authentication and authorization across multiple user roles systematically
- Integrating Postman with OWASP ZAP proxy for combined manual and automated security testing
- Establishing a baseline security test collection for new API endpoints before deployment
Do not use against production APIs without authorization. Postman security testing involves sending potentially malicious payloads.
Prerequisites
- Postman Desktop or web application with an active workspace
- Target API with OpenAPI/Swagger specification for collection import
- Test accounts for at least three roles: unauthenticated, regular user, admin
- Newman CLI installed for CI/CD integration:
npm install -g newman - OWASP ZAP configured as local proxy (localhost:8080) for Postman proxy integration
- API environment variables for base URL, tokens, and test data
Workflow
Step 1: Environment and Collection Setup
Create Postman environments for multi-role testing:
// Environment: API Security Test - Regular User
{
"values": [
{"key": "base_url", "value": "https://target-api.example.com/api/v1"},
{"key": "auth_token", "value": ""},
{"key": "user_email", "value": "regular@test.com"},
{"key": "user_password", "value": "TestPass123!"},
{"key": "user_id", "value": ""},
{"key": "other_user_id", "value": "1002"},
{"key": "admin_endpoint", "value": "/admin/users"},
{"key": "test_order_id", "value": ""},
{"key": "other_user_order_id", "value": "5003"}
]
}Pre-request script for automatic authentication:
// Collection-level pre-request script for auto-login
if (!pm.environment.get("auth_token") || pm.environment.get("token_expired")) {
const loginRequest = {
url: pm.environment.get("base_url") + "/auth/login",
method: "POST",
header: {"Content-Type": "application/json"},
body: {
mode: "raw",
raw: JSON.stringify({
email: pm.environment.get("user_email"),
password: pm.environment.get("user_password")
})
}
};
pm.sendRequest(loginRequest, (err, res) => {
if (!err && res.code === 200) {
const token = res.json().access_token;
pm.environment.set("auth_token", token);
pm.environment.set("user_id", res.json().user.id);
}
});
}Step 2: BOLA (API1) Test Collection
// Test: Access other user's profile (BOLA)
// Request: GET {{base_url}}/users/{{other_user_id}}
// Auth: Bearer {{auth_token}}
// Test script:
pm.test("BOLA: Cannot access other user profile", function() {
pm.expect(pm.response.code).to.be.oneOf([401, 403]);
});
pm.test("BOLA: No user data leaked on denial", function() {
if (pm.response.code === 200) {
const body = pm.response.json();
pm.expect(body).to.not.have.property("email");
pm.expect(body).to.not.have.property("phone");
pm.expect(body).to.not.have.property("address");
// Flag as BOLA if full profile returned
console.error("BOLA VULNERABILITY: Full profile returned for other user");
}
});
// Test: Access other user's order
// Request: GET {{base_url}}/orders/{{other_user_order_id}}
pm.test("BOLA: Cannot access other user order", function() {
pm.expect(pm.response.code).to.be.oneOf([401, 403, 404]);
});
// Test: Modify other user's resource
// Request: PATCH {{base_url}}/users/{{other_user_id}}
// Body: {"name": "Hacked"}
pm.test("BOLA: Cannot modify other user profile", function() {
pm.expect(pm.response.code).to.be.oneOf([401, 403]);
});Step 3: Authentication (API2) Test Collection
// Test: Token validation
// Request: GET {{base_url}}/users/me
// Auth: Bearer invalid_token_value
pm.test("Auth: Invalid token rejected", function() {
pm.expect(pm.response.code).to.be.oneOf([401, 403]);
});
// Test: Expired token handling
// Request: GET {{base_url}}/users/me
// Auth: Bearer {{expired_token}}
pm.test("Auth: Expired token rejected", function() {
pm.expect(pm.response.code).to.equal(401);
});
// Test: Missing authentication
// Request: GET {{base_url}}/users/me
// Auth: None
pm.test("Auth: Unauthenticated request rejected", function() {
pm.expect(pm.response.code).to.equal(401);
});
// Test: SQL injection in login
// Request: POST {{base_url}}/auth/login
// Body: {"email": "' OR 1=1--", "password": "test"}
pm.test("Auth: SQLi in login rejected", function() {
pm.expect(pm.response.code).to.not.equal(200);
pm.expect(pm.response.text()).to.not.include("token");
});
// Test: Account enumeration
// Pre-request: Send login with valid email + wrong password, then invalid email + wrong password
pm.test("Auth: No account enumeration", function() {
// Compare with stored response from valid email attempt
const validEmailResponse = pm.environment.get("valid_email_response");
const currentResponse = pm.response.text();
pm.expect(currentResponse).to.equal(validEmailResponse);
});Step 4: Data Exposure (API3) and BFLA (API5) Tests
// Test: Excessive data exposure check
// Request: GET {{base_url}}/users/me
pm.test("Data Exposure: No sensitive fields in response", function() {
const sensitiveFields = [
"password", "password_hash", "passwordHash",
"ssn", "social_security", "credit_card",
"api_key", "secret_key", "mfa_secret",
"refresh_token", "session_id"
];
const responseText = pm.response.text().toLowerCase();
sensitiveFields.forEach(field => {
pm.expect(responseText).to.not.include('"' + field + '"');
});
});
pm.test("Data Exposure: Security headers present", function() {
pm.expect(pm.response.headers.has("X-Content-Type-Options")).to.be.true;
pm.expect(pm.response.headers.has("X-Frame-Options")).to.be.true;
pm.expect(pm.response.headers.get("X-Content-Type-Options")).to.equal("nosniff");
});
pm.test("Data Exposure: No server info leaked", function() {
pm.expect(pm.response.headers.has("Server")).to.be.false;
pm.expect(pm.response.headers.has("X-Powered-By")).to.be.false;
});
// Test: BFLA - Admin endpoint access
// Request: GET {{base_url}}{{admin_endpoint}}
// Auth: Bearer {{auth_token}} (regular user)
pm.test("BFLA: Regular user cannot access admin endpoint", function() {
pm.expect(pm.response.code).to.be.oneOf([401, 403]);
});
// Test: BFLA - Admin function execution
// Request: DELETE {{base_url}}/users/{{other_user_id}}
// Auth: Bearer {{auth_token}} (regular user)
pm.test("BFLA: Regular user cannot delete other users", function() {
pm.expect(pm.response.code).to.be.oneOf([401, 403]);
});Step 5: Mass Assignment and Rate Limiting Tests
// Test: Mass assignment via profile update
// Request: PUT {{base_url}}/users/me
// Body: {"name": "Test", "role": "admin", "is_admin": true}
pm.test("Mass Assignment: Role field not accepted", function() {
if (pm.response.code === 200) {
const user = pm.response.json();
pm.expect(user.role).to.not.equal("admin");
pm.expect(user.is_admin).to.not.equal(true);
}
});
// Test: Rate limiting enforcement
// This test should be run with the Collection Runner at high iteration count
pm.test("Rate Limiting: Returns 429 when limit exceeded", function() {
// This test expects to be rate-limited after many iterations
const iterationCount = pm.info.iteration;
if (iterationCount > 50) {
// After 50 iterations, we should see rate limiting
if (pm.response.code === 429) {
pm.expect(pm.response.headers.has("Retry-After")).to.be.true;
console.log("Rate limiting enforced at iteration " + iterationCount);
}
}
});
// Test: Rate limit headers present
pm.test("Rate Limiting: Rate limit headers present", function() {
const hasRateHeaders = pm.response.headers.has("X-RateLimit-Limit") ||
pm.response.headers.has("X-Rate-Limit-Limit") ||
pm.response.headers.has("RateLimit-Limit");
pm.expect(hasRateHeaders).to.be.true;
});Step 6: Newman CI/CD Integration
# Run security test collection via Newman CLI
newman run "API-Security-Tests.postman_collection.json" \
--environment "Security-Test-Environment.postman_environment.json" \
--reporters cli,htmlextra,junit \
--reporter-htmlextra-export ./reports/security-test-report.html \
--reporter-junit-export ./reports/security-test-results.xml \
--iteration-count 1 \
--timeout-request 10000 \
--delay-request 100 \
--bail
# Run with different user roles
for role in "regular_user" "admin_user" "unauthenticated"; do
echo "Testing with role: $role"
newman run "API-Security-Tests.postman_collection.json" \
--environment "Security-Test-${role}.postman_environment.json" \
--reporters cli,junit \
--reporter-junit-export "./reports/security-${role}.xml"
doneGitHub Actions Integration:
# .github/workflows/api-security-test.yml
name: API Security Tests
on:
pull_request:
paths: ['src/api/**', 'openapi.yaml']
jobs:
security-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm install -g newman newman-reporter-htmlextra
- name: Run API Security Tests
run: |
newman run tests/postman/api-security.json \
--environment tests/postman/env-staging.json \
--reporters cli,htmlextra,junit \
--reporter-htmlextra-export reports/security.html \
--reporter-junit-export reports/security.xml
- uses: actions/upload-artifact@v4
if: always()
with:
name: security-reports
path: reports/Key Concepts
| Term | Definition |
|---|---|
| Postman Collection | Organized group of API requests with test scripts that can be shared, version-controlled, and executed automatically |
| Newman | Command-line companion for Postman that enables running collections in CI/CD pipelines and generating test reports |
| Pre-request Script | JavaScript code that executes before a Postman request, used for dynamic authentication and test data setup |
| Test Script | JavaScript code that executes after a Postman response, used to validate security assertions against the response |
| Collection Runner | Postman feature that executes all requests in a collection sequentially with configurable iterations and delays |
| Environment Variables | Key-value pairs scoped to a Postman environment that parameterize requests for different targets, roles, and configurations |
Tools & Systems
- Postman: API platform for building, testing, and documenting APIs with built-in scripting and collection management
- Newman: CLI runner for Postman collections supporting multiple reporters (HTML, JUnit, JSON) for CI/CD integration
- OWASP ZAP: Open-source security proxy that can be configured as Postman's proxy to scan all requests passively
- newman-reporter-htmlextra: Enhanced HTML reporter for Newman that generates detailed test reports with request/response data
- Postman Flows: Visual workflow builder for chaining complex security test sequences with conditional logic
Common Scenarios
Scenario: API Security Regression Suite for CI/CD
Context: A development team releases API updates bi-weekly. They need an automated security test suite that runs on every pull request to catch authorization and authentication regressions before merge.
Approach: 1. Import the OpenAPI spec into Postman to generate a base collection with all endpoints 2. Create three environments: unauthenticated, regular user, admin with appropriate credentials 3. Add security test scripts to each request: BOLA checks, auth validation, data exposure scanning, header security 4. Create a dedicated "Security Tests" folder with injection payloads, mass assignment tests, and rate limit checks 5. Export the collection and environments to the repository 6. Configure Newman in GitHub Actions to run on every PR affecting API code 7. Set the pipeline to fail on any security test failure, blocking the merge
Pitfalls:
- Hardcoding authentication tokens in collections instead of using pre-request scripts for dynamic token generation
- Not testing with all user roles - only testing authenticated vs unauthenticated misses role-based authorization issues
- Running security tests against production instead of staging environments
- Not updating the collection when new endpoints are added, leaving gaps in coverage
- Ignoring Newman exit codes in CI/CD, allowing failing security tests to pass silently
Output Format
## API Security Test Report - Postman/Newman
**Collection**: API Security Tests v2.3
**Environment**: Staging - Regular User
**Date**: 2024-12-15
**Total Requests**: 85
**Total Tests**: 234
**Passed**: 219
**Failed**: 15
### Failed Tests Summary
| # | Request | Test Name | Severity |
|---|---------|-----------|----------|
| 1 | GET /users/1002 | BOLA: Cannot access other user profile | Critical |
| 2 | GET /orders/5003 | BOLA: Cannot access other user order | Critical |
| 3 | GET /admin/users | BFLA: Regular user cannot access admin endpoint | Critical |
| 4 | PUT /users/me | Mass Assignment: Role field not accepted | High |
| 5 | GET /users/me | Data Exposure: No sensitive fields in response | High |
| 6 | POST /auth/login | Auth: No account enumeration | Medium |
| ... | ... | ... | ... |
### Recommendations
1. Fix BOLA on /users/{id} and /orders/{id} - add object-level authorization checks
2. Fix BFLA on /admin/users - enforce role-based access control middleware
3. Fix mass assignment on PUT /users/me - implement field allowlist
4. Remove password_hash and mfa_secret from user serialization
5. Standardize login error messages to prevent account enumeration
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 Security Testing with Postman — API Reference
Tools
| Tool | Install | Purpose |
|---|---|---|
| Newman | npm install -g newman | CLI runner for Postman collections |
| Postman | Desktop app from postman.com | Collection creation and manual testing |
Newman CLI Commands
| Command | Description |
|---|---|
newman run <collection.json> | Execute collection |
newman run <col> -e <env.json> | Run with environment variables |
newman run <col> --reporters cli,json | Output in CLI and JSON format |
newman run <col> --reporter-json-export out.json | Export JSON results |
newman run <col> --timeout-request 10000 | 10s request timeout |
newman run <col> --delay-request 100 | 100ms delay between requests |
Postman Test Script Functions
| Function | Description |
|---|---|
pm.response.code | HTTP response status code |
pm.response.text() | Response body as string |
pm.response.json() | Parsed JSON response |
pm.expect(val).to.equal(x) | Chai assertion |
pm.expect(val).to.be.oneOf([]) | Value in expected set |
pm.expect(val).to.not.include(s) | String not present |
pm.environment.set(k, v) | Set environment variable |
Collection Schema (v2.1.0)
{
"info": {"name": "...", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},
"item": [{"name": "...", "request": {...}, "event": [{"listen": "test", "script": {...}}]}]
}OWASP API Security Tests
| Test | Postman Assertion |
|---|---|
| BOLA/IDOR | Expect 403/404 when accessing other user's resource |
| Auth bypass | Expect 401 without valid token |
| Mass assignment | Expect role field ignored in response |
| Injection | Expect no 500 or stack trace in response |
| Data exposure | Expect sensitive fields not in response |
External References
#!/usr/bin/env python3
# For authorized testing only
"""Postman API security testing orchestration agent using Newman CLI."""
import json
import argparse
import subprocess
import os
from datetime import datetime
def run_newman_collection(collection_path, environment_path=None, reporters=None):
"""Execute a Postman collection using Newman CLI."""
cmd = ["newman", "run", collection_path]
if environment_path:
cmd.extend(["-e", environment_path])
if reporters:
cmd.extend(["--reporters", reporters])
else:
cmd.extend(["--reporters", "cli,json"])
cmd.extend(["--reporter-json-export", "newman-results.json"])
cmd.extend(["--timeout-request", "10000"])
cmd.extend(["--delay-request", "100"])
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
output = {
"exit_code": result.returncode,
"stdout_tail": result.stdout[-2000:] if result.stdout else "",
"stderr": result.stderr[:500] if result.stderr else "",
}
if os.path.exists("newman-results.json"):
with open("newman-results.json", "r") as f:
output["results"] = json.load(f)
return output
def parse_newman_results(results_path):
"""Parse Newman JSON results for security test outcomes."""
with open(results_path, "r") as f:
data = json.load(f)
run_data = data.get("run", {})
stats = run_data.get("stats", {})
executions = run_data.get("executions", [])
test_results = []
for execution in executions:
item = execution.get("item", {})
response = execution.get("response", {})
assertions = execution.get("assertions", [])
for assertion in assertions:
test_results.append({
"request_name": item.get("name", ""),
"test_name": assertion.get("assertion", ""),
"passed": not assertion.get("error"),
"status_code": response.get("code", 0),
"response_time_ms": response.get("responseTime", 0),
"error": assertion.get("error", {}).get("message", "") if assertion.get("error") else "",
})
failures = [t for t in test_results if not t["passed"]]
return {
"total_requests": stats.get("requests", {}).get("total", 0),
"total_assertions": stats.get("assertions", {}).get("total", 0),
"failed_assertions": stats.get("assertions", {}).get("failed", 0),
"test_results": test_results,
"failures": failures,
}
def generate_bola_collection(base_url, endpoints, user_a_token, user_b_token):
"""Generate Postman collection for BOLA/IDOR testing across two user contexts."""
items = []
for ep in endpoints:
method = ep.get("method", "GET")
path = ep.get("path", "")
items.append({
"name": f"BOLA: {method} {path} (User B accessing User A resource)",
"request": {
"method": method,
"header": [
{"key": "Authorization", "value": f"Bearer {user_b_token}"},
{"key": "Content-Type", "value": "application/json"},
],
"url": {"raw": f"{base_url}{path}", "host": [base_url], "path": path.strip("/").split("/")},
},
"event": [{
"listen": "test",
"script": {
"exec": [
"pm.test('BOLA Check: Should return 403 or 404', function () {",
" pm.expect(pm.response.code).to.be.oneOf([403, 404]);",
"});",
"pm.test('No data leakage in response', function () {",
f" pm.expect(pm.response.text()).to.not.include('{user_a_token[:10]}');",
"});",
],
"type": "text/javascript",
},
}],
})
collection = {
"info": {
"name": "BOLA/IDOR Security Tests",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
},
"item": items,
}
return collection
def generate_injection_collection(base_url, endpoints):
"""Generate Postman collection for injection testing."""
injection_payloads = [
("SQL Injection", "' OR '1'='1"),
("XSS", "<script>alert(1)</script>"),
("Command Injection", "; cat /etc/passwd"),
("SSTI", "{{7*7}}"),
("Path Traversal", "../../../etc/passwd"),
]
items = []
for ep in endpoints:
path = ep.get("path", "")
params = ep.get("params", [])
for param in params:
for payload_name, payload in injection_payloads:
items.append({
"name": f"{payload_name}: {path}?{param}",
"request": {
"method": "GET",
"url": {
"raw": f"{base_url}{path}?{param}={payload}",
"host": [base_url],
"path": path.strip("/").split("/"),
"query": [{"key": param, "value": payload}],
},
},
"event": [{
"listen": "test",
"script": {
"exec": [
f"pm.test('{payload_name} — no 500 error', function () {{",
" pm.expect(pm.response.code).to.not.equal(500);",
"});",
f"pm.test('{payload_name} — no stack trace', function () {{",
" pm.expect(pm.response.text()).to.not.include('Traceback');",
" pm.expect(pm.response.text()).to.not.include('Exception');",
"});",
],
"type": "text/javascript",
},
}],
})
return {
"info": {
"name": "Injection Security Tests",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
},
"item": items,
}
def run_audit(args):
"""Execute Postman API security testing audit."""
print(f"\n{'='*60}")
print(f" POSTMAN API SECURITY TESTING")
print(f" Generated: {datetime.utcnow().isoformat()} UTC")
print(f"{'='*60}\n")
report = {}
if args.collection:
newman = run_newman_collection(args.collection, args.environment)
report["newman_run"] = {"exit_code": newman["exit_code"]}
print(f"--- NEWMAN EXECUTION ---")
print(f" Exit code: {newman['exit_code']}")
if os.path.exists("newman-results.json"):
parsed = parse_newman_results("newman-results.json")
report["test_results"] = parsed
print(f"\n--- TEST RESULTS ---")
print(f" Total requests: {parsed['total_requests']}")
print(f" Total assertions: {parsed['total_assertions']}")
print(f" Failed: {parsed['failed_assertions']}")
for f in parsed["failures"][:15]:
print(f" FAIL: {f['request_name']} — {f['test_name']}")
if f["error"]:
print(f" {f['error'][:80]}")
if args.gen_bola:
endpoints = json.loads(args.gen_bola)
collection = generate_bola_collection(
args.base_url or "http://localhost:8080",
endpoints, args.token_a or "token_a", args.token_b or "token_b",
)
output_path = "bola-tests.postman_collection.json"
with open(output_path, "w") as f_out:
json.dump(collection, f_out, indent=2)
report["bola_collection"] = output_path
print(f"\n--- GENERATED BOLA COLLECTION ---")
print(f" Path: {output_path}")
print(f" Tests: {len(collection['item'])}")
return report
def main():
parser = argparse.ArgumentParser(description="Postman API Security Testing Agent")
parser.add_argument("--collection", help="Postman collection JSON to run with Newman")
parser.add_argument("--environment", help="Postman environment JSON")
parser.add_argument("--gen-bola", help="JSON array of endpoints for BOLA test generation")
parser.add_argument("--base-url", help="Base URL for generated collections")
parser.add_argument("--token-a", help="User A auth token for BOLA tests")
parser.add_argument("--token-b", help="User B auth token for BOLA tests")
parser.add_argument("--output", help="Save report to JSON file")
args = parser.parse_args()
report = run_audit(args)
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"\n[+] Report saved to {args.output}")
if __name__ == "__main__":
main()