<!-- AUTO-GENERATED by export-plugins.py — DO NOT EDIT -->
npx claudepluginhub frank-luongt/faos-skills-marketplace --plugin faos-security-engineerThis skill uses the workspace's default tool permissions.
Implements structured self-debugging workflow for AI agent failures: capture errors, diagnose patterns like loops or context overflow, apply contained recoveries, and generate introspection reports.
Designs and optimizes AI agent action spaces, tool definitions, observation formats, error recovery, and context for higher task completion rates.
Compares coding agents like Claude Code and Aider on custom YAML-defined codebase tasks using git worktrees, measuring pass rate, cost, time, and consistency.
The OWASP API Security Top 10 is a standardized awareness document for API-specific security risks. Unlike the general OWASP Top 10 (which focuses on web applications), this list addresses the unique attack surface of APIs -- broken object-level authorization, mass assignment, rate limiting gaps, and more. APIs are the backbone of modern architectures (microservices, mobile backends, SaaS integrations), making them a primary target for attackers.
This skill covers all 10 risks from the 2023 edition, provides concrete attack scenarios, and maps each risk to prevention patterns applicable to Python/FastAPI codebases.
Catalog every API endpoint in the system. Use OpenAPI/Swagger specs as the source of truth. For each endpoint, document the HTTP method, path, required authentication, authorization scope, and data sensitivity classification.
# Extract all routes from a FastAPI app
python -c "
from app.main import app
for route in app.routes:
if hasattr(route, 'methods'):
for method in route.methods:
print(f'{method:7s} {route.path}')
"
Map each endpoint's request/response payloads to sensitivity tiers:
| Tier | Examples | Controls Required |
|---|---|---|
| Critical | Passwords, tokens, PII, financial data | Encryption at rest + transit, audit logging, field-level access control |
| High | Email, phone, user preferences | Access control, audit logging |
| Medium | Public profile data, non-sensitive metadata | Authentication required |
| Low | Health checks, public catalog data | Rate limiting only |
For every endpoint, define:
Run automated scans using OWASP ZAP, Burp Suite, or Nuclei against staging environments:
# OWASP ZAP API scan with OpenAPI spec
docker run -t ghcr.io/zaproxy/zaproxy:stable zap-api-scan.py \
-t https://staging.example.com/openapi.json \
-f openapi \
-r zap-report.html
# Nuclei scan for API-specific vulnerabilities
nuclei -u https://staging.example.com/api \
-t http/vulnerabilities/ \
-t http/misconfiguration/ \
-severity critical,high
Apply the prevention patterns below for each of the 10 risks. Prioritize by likelihood and impact in your specific architecture.
Description: APIs expose endpoints that handle object identifiers, creating a wide attack surface. An attacker substitutes the ID of a resource they own with the ID of a resource belonging to another user. Lack of authorization checks lets the attacker access or modify the target resource.
Attack Scenario: GET /api/v1/invoices/12345 -- attacker changes 12345 to 12346 and receives another tenant's invoice because the endpoint only checks authentication, not ownership.
Prevention:
Description: Authentication mechanisms are implemented incorrectly, allowing attackers to compromise tokens, exploit implementation flaws, or assume other users' identities.
Attack Scenario: Credential stuffing against /api/v1/auth/login with no rate limiting or account lockout. Weak JWT validation accepts tokens signed with alg: none.
Prevention:
Description: APIs expose object properties that the user should not be able to read (excessive data exposure) or modify (mass assignment). This combines the former API3 (Excessive Data Exposure) and API6 (Mass Assignment) from the 2019 edition.
Attack Scenario: GET /api/v1/users/me returns {"name": "Alice", "role": "user", "internal_credit_score": 780}. Or: PUT /api/v1/users/me with {"role": "admin"} succeeds because the endpoint blindly accepts all fields.
Prevention:
Description: APIs do not limit the size or number of resources that can be requested, leading to denial of service, brute-force attacks, or cost escalation (e.g., SMS/email flooding).
Attack Scenario: GET /api/v1/products?page_size=999999 returns the entire catalog in one response. Or: /api/v1/otp/send is called 10,000 times with no rate limit, running up SMS costs.
Prevention:
Description: Attackers send API calls to endpoints they should not have access to. These may be administrative functions or endpoints of a different user role. The API relies on the client to enforce access control.
Attack Scenario: Regular user calls DELETE /api/v1/admin/users/42 or POST /api/v1/admin/config -- admin endpoints exist but authorization middleware is missing or misconfigured.
Prevention:
Description: APIs expose business flows (purchasing, posting reviews, booking) that can be automated and abused at scale without proper anti-automation controls.
Attack Scenario: Bot purchases all limited-edition items via /api/v1/checkout faster than human users. Or: automated review posting to manipulate ratings.
Prevention:
Description: An API fetches a remote resource based on a user-supplied URL without validating the target. Attackers use SSRF to access internal services, cloud metadata endpoints, or port-scan internal networks.
Attack Scenario: POST /api/v1/webhooks {"url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/"} -- the server fetches AWS credentials from the metadata service.
Prevention:
Description: APIs and their supporting infrastructure (API gateways, cloud services, frameworks) are misconfigured, leaving default credentials, unnecessary HTTP methods, verbose error messages, or missing security headers.
Attack Scenario: CORS set to Access-Control-Allow-Origin: * with credentials. Debug mode enabled in production exposes stack traces. TLS 1.0/1.1 still enabled.
Prevention:
Description: Organizations lose track of API versions, deprecated endpoints, and shadow APIs. Old or unmanaged API versions remain exposed without security patches.
Attack Scenario: Production runs API v3 with proper auth, but v1 (/api/v1/users) is still accessible with weaker authentication and returns more data than v3.
Prevention:
Description: Developers trust data from third-party APIs without validation. If a third-party API is compromised or returns malicious data, the consuming application becomes vulnerable.
Attack Scenario: Application consumes a partner API that returns user display names. A compromised partner injects <script> tags in names, causing stored XSS when rendered.
Prevention:
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth import get_current_user, CurrentUser
from app.database import get_db
router = APIRouter(prefix="/api/v1/invoices", tags=["invoices"])
# BAD: No ownership check -- vulnerable to BOLA
@router.get("/{invoice_id}")
async def get_invoice_insecure(invoice_id: int, db: AsyncSession = Depends(get_db)):
invoice = await db.get(Invoice, invoice_id)
if not invoice:
raise HTTPException(status_code=404)
return invoice # Any authenticated user can access any invoice
# GOOD: Ownership check prevents BOLA
@router.get("/{invoice_id}")
async def get_invoice_secure(
invoice_id: int,
current_user: CurrentUser = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
invoice = await db.get(Invoice, invoice_id)
if not invoice:
raise HTTPException(status_code=404)
# Enforce object-level authorization
if invoice.tenant_id != current_user.tenant_id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not authorized to access this resource",
)
return InvoiceResponse.model_validate(invoice) # Explicit response schema
from fastapi import FastAPI, Request
from slowapi import Limiter
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
limiter = Limiter(
key_func=get_remote_address,
default_limits=["100/minute"],
storage_uri="redis://localhost:6379/0",
)
app = FastAPI()
app.state.limiter = limiter
app.add_middleware(SlowAPIMiddleware)
# Stricter limit on authentication endpoints (API2 + API4)
@app.post("/api/v1/auth/login")
@limiter.limit("5/minute")
async def login(request: Request):
...
# Stricter limit on sensitive business flows (API6)
@app.post("/api/v1/checkout")
@limiter.limit("3/minute")
async def checkout(request: Request):
...
# Standard limit on data endpoints with pagination enforcement (API4)
@app.get("/api/v1/products")
@limiter.limit("60/minute")
async def list_products(request: Request, page: int = 1, page_size: int = 20):
MAX_PAGE_SIZE = 100
page_size = min(page_size, MAX_PAGE_SIZE) # Enforce ceiling
...
# openapi-inventory.yaml -- central API inventory for API9 prevention
openapi: "3.1.0"
info:
title: "FAOS Platform API Inventory"
version: "2024-01-15"
description: "Canonical inventory of all active API endpoints"
paths:
/api/v3/users:
get:
summary: "List users (current version)"
x-api-status: active
x-data-classification: high
x-auth-required: true
x-auth-scopes: ["users:read"]
/api/v1/users:
get:
summary: "List users (DEPRECATED)"
x-api-status: deprecated
x-deprecation-date: "2023-06-01"
x-sunset-date: "2024-03-01"
x-migration-guide: "https://docs.example.com/migrate-v1-v3"
deprecated: true
# CI check: fail build if any path has x-api-status: deprecated past x-sunset-date
# CI script to enforce API inventory hygiene
#!/usr/bin/env bash
set -euo pipefail
TODAY=$(date +%Y-%m-%d)
DEPRECATED=$(yq '.paths | to_entries[] |
select(.value[].x-api-status == "deprecated") |
select(.value[]."x-sunset-date" < env(TODAY)) |
.key' openapi-inventory.yaml)
if [ -n "$DEPRECATED" ]; then
echo "ERROR: The following deprecated APIs are past their sunset date:"
echo "$DEPRECATED"
exit 1
fi
* with allow_credentials=Truealg: none)