Home › Security › API route security .claude/rules file
API route security .claude/rules file
A path-scoped Claude Code rules file for API routes and handlers: auth, ownership checks, validation, and safe errors.
Claude Code (CLAUDE.md)Security
How to use
Save this as .claude/rules/api-security.md in your repository root, commit it, and your agent will pick it up automatically. Edit the commands to match your project.
Note: Review and test before use. Provided as is, without warranty. See Terms.
.claude/rules/api-security.mdDownload ---
paths:
- "app/api/**"
- "src/routes/**"
- "src/api/**"
- "**/controllers/**"
- "**/handlers/**"
- "**/routes/**"
---
# API handler security
Loaded when editing request handlers. Apply to every endpoint you add or change.
1. **Authenticate:** require a session/token unless the endpoint is intentionally public; say so in a comment if it is.
2. **Authorize the object:** load records scoped to the caller (`where owner_id = current_user.id` / tenant id). Never trust ids, roles, prices, or tenant ids from the body or query.
3. **Validate input** with a schema (types, lengths, enums, formats) before using it. Reject unknown fields on writes.
4. **Use safe sinks:** parameterized queries/ORM only; no shell, `eval`, or template rendering with raw input; fetch user URLs only through an allowlist.
5. **Limit:** paginate lists with a max page size; cap body size; rate-limit auth, signup, password reset, and expensive endpoints.
6. **Respond safely:** correct status codes; generic error messages to clients, details in server logs; never return secrets, password hashes, or internal stack traces.
7. **Webhooks:** verify signatures on the raw body and handle replays idempotently.
8. **Log** security-relevant events (denied access, failed logins) without tokens or PII.
Add tests for: unauthenticated (401), another user's resource (403/404), and invalid input (400/422).