Skills watch

api-security-and-bot-protection

Use when building or editing API endpoints, authentication, JWT/session handling, or public forms. Enforces auth/ownership checks, Turnstile/reCAPTCHA server validation, rate limits, input validation, security headers, and safe API boundaries.

Score 49coding Ganesh-Dark/ai-coding-agent-skills source file first seen 2026-12-01

Why it scored this

named +4 · described +6 · substantial +6 · right length +4 · examples +5 · code-fences +3 · active +5 · unseen-before +8 · specific-vocabulary +8

The file

---
name: api-security-and-bot-protection
description: Use when building or editing API endpoints, authentication, JWT/session handling, or public forms. Enforces auth/ownership checks, Turnstile/reCAPTCHA server validation, rate limits, input validation, security headers, and safe API boundaries.
---

# API Security and Bot Protection

Coding agents often make endpoints "work" by decoding JWTs without verifying signatures, skipping ownership checks, or trusting client-side CAPTCHA checks. Those shortcuts leave APIs open to account takeover, data leaks, and bot abuse.

## Key Layers

### 1. Authentication & Authorization
- **API Keys:** Simple tokens passed in headers; fine for server-to-server, not for public clients. Never put API keys in URLs—they end up in logs.
- **OAuth 2.0 / OpenID Connect:** Standard for delegated access; use this for user-facing apps.
- **JWT:** Always verify signature, expiry (`exp`), issuer (`iss`), and audience (`aud`) (`jwt.decode(token, key, algorithms=["HS256"])`), never `verify_signature: False` or `"alg": "none"`.
- **Ownership (BOLA/IDOR):** Always check that the authenticated user owns or has permission for the requested record (`record.user_id == current_user.id`).

### 2. Rate Limiting, Throttling & Bot Defense
- Limit requests per IP, per user, and per API key (e.g., 100 req/min).
- Return `429 Too Many Requests` with a `Retry-After` header (via nginx, API Gateway, Cloudflare, or Redis counters).
- Use account lockout and verify Turnstile/reCAPTCHA tokens **server-side** (`success`, `hostname`, `action`) on login, signup, password reset, and public forms.

### 3. Input Validation
- Never trust incoming data—validate types, lengths, and formats on every field using a schema validator (like Pydantic).
- Reject unexpected fields (do not silently ignore them) to block mass assignment.
- Protect against SQL injection and NoSQL injection with parameterized queries or ORMs.

### 4. HTTPS Only
- Never serve an API over plain HTTP in production.
- Redirect HTTP to HTTPS at the server or load balancer level and use HSTS headers.

### 5. CORS (Cross-Origin Resource Sharing)
- Whitelist only the domains that should call your API.
- Avoid `Access-Control-Allow-Origin: *` on authenticated endpoints and never allow credentials with wildcard origins.

### 6. Sensitive Data Handling
- Never return passwords, secrets, or internal IDs in responses.
- Strip internal fields before serializing (use DTOs / response schemas) and mask PII in logs.

### 7. Security Headers
Add these to every response:
```text
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000
Content-Security-Policy: default-src 'none'
```

### 8. Error Handling
- Never expose stack traces, DB errors, or file paths in error responses.
- Return generic messages to clients (`Something went wrong` or RFC 7807 Problem Details) and log details server-side.

### 9. Logging & Monitoring
- Log every request with timestamp, IP, endpoint, status code, and user ID (not the full payload).
- Alert on sudden spikes, repeated `401`/`403` responses (brute-force signals), and unusual patterns.

### 10. API Versioning & Deprecation
- Version your API (`/v1/`, `/v2/`) so you can retire insecure endpoints cleanly instead of leaving old endpoints alive indefinitely.

## Example

Bad:
A `/signup` route only checks `if payload.get("captcha_passed"):` from the frontend, and `/orders/<order_id>` runs `db.get(Order, order_id)` using an unverified JWT (`options={"verify_signature": False}`) and returns raw DB errors on failure.

Good:
`/signup` validates the Pydantic schema and verifies the Turnstile/reCAPTCHA token server-side with `requests.post(...)`, and `/orders/<order_id>` verifies the JWT signature, queries `Order.filter_by(id=order_id, user_id=verified_user.id)`, and returns a response DTO with security headers.