Skip to content
Back to skills

Fastapi Security

ASecurity

Security for FastAPI backends - authentication (Firebase/JWT) vs authorization (RBAC, object-level), Redis rate limiting, production fail-fast configuration, signed cursors, webhook and metrics tokens, safe uploads, security-event detection rules, tamper-evident HMAC audit log, secrets handling, Nginx/UFW/Docker hardening. Use whenever the user mentions auth, tokens, roles, permissions, admin, rate limit, brute force, upload safety, secrets, audit log, intrusion detection, HTTPS, hardening, "...

  • 2 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added November 27, 2026
developmentrustgofastapidockergitapidatabasebackendsecurity

Works with

  • cursor
  • cli
  • api

Security analysis

A100/100

Scanned November 27, 2026

npx -y skills add amralhorimy/fastapi-pro-skills --skill fastapi-security --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Fastapi Security?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Fastapi Security
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/amralhorimy-fastapi-security/badge)](https://www.skillsdirectory.com/skills/amralhorimy-fastapi-security)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: fastapi-security
description: Security for FastAPI backends - authentication (Firebase/JWT) vs authorization (RBAC, object-level), Redis rate limiting, production fail-fast configuration, signed cursors, webhook and metrics tokens, safe uploads, security-event detection rules, tamper-evident HMAC audit log, secrets handling, Nginx/UFW/Docker hardening. Use whenever the user mentions auth, tokens, roles, permissions, admin, rate limit, brute force, upload safety, secrets, audit log, intrusion detection, HTTPS, hardening, "is this secure", or before any release.
---

# Security

Security is a property of every layer. Apply the checklist per feature and per release; report findings by severity
(critical > high > medium > low) with the exploit path, not just the rule.

## 1. Authentication vs authorization (two different dependencies)
- `get_current_user` = **authentication only**: verify the provider token (Firebase/OIDC/JWT: signature, `exp`, `nbf`, `iss`,
  `aud`, a pinned algorithm allow-list, and appropriate key selection/rotation; reject `none` and algorithm/key confusion).
  Verification off the event loop via `to_thread` if the SDK is blocking. Sets the actor for logging. These checks are required
  implementation properties, not a guarantee provided merely by using a JWT library.
- `ActiveMember` = authenticated **and** registered **and** active. Business routes use only this. Suspended accounts fail here.
- Permissions are **data**: `shared/permissions.py` maps role -> `frozenset[Permission]`; routes declare `require(Permission.X)`.
  No scattered `if user.is_admin`.
- **Never accept the role (or owner id) from the client.** A real bug found in hobby code: the profile-registration body accepted
  `role`, so any user could register as admin. Role is always server-assigned; promotion happens through an admin path/CLI.
- Sensitive staff actions require **fresh sign-in** (`RecentAuthRequired`); protected targets (other admins, self) are refused
  by policy objects in the domain (`policies.py`).
- WebSocket/SSE: authenticate at connect; bound frame size and message length; never leak exception text in frames.

## 2. Object-level authorization
Every use case that takes an id checks the actor against **that object** (`entity.can_be_deleted_by(actor)`), and tests the
deny path. Where existence is sensitive, return the same not-found for "missing" and "not yours".
Reads return only `published/visible` states - a real bug: archived (deleted) posts were readable by id/slug.

## 3. Rate limiting and abuse
- Nginx `limit_req` (coarse) + app-level Redis limiter as a route dependency: `dependencies=[rate_limit("comment_write", limit=20)]`
  keyed by `name:uid`, with a `window`. Reads have limits too (`comment_read`, 120).
- Decide the failure mode **per route**. A low-risk read may fail open with a `ratelimit.unavailable` security/operations
  signal and a bounded fallback; login, credential recovery, expensive/abuse-prone writes, and costly compute need a fail-closed
  or explicitly bounded degraded policy. Do not make fail-open the blanket rule. Protect expensive paths (e.g. LLM) with a
  bounded queue and 429/503 + validated `Retry-After`.

## 4. Fail-fast configuration
`production_problems()` (see foundation templates) stops the process when debug is on, an enabled feature's required secret is
missing/too short/still a placeholder, or `PUSH_PROVIDER=log` would silently drop production notifications. Pass only secrets
required by enabled features, with a minimum byte length and cryptographically random values; length alone does not prove entropy.
Add every enabled secret here + `.env.example`. This check is only effective if the application passes the correct settings.

## 5. Tokens for machine callers
- Webhooks (storage -> API): if using a shared-secret header, compare with `hmac.compare_digest` and protect transport with
  TLS. A secret header alone does not sign/authenticate the body contents; when payload integrity matters, MAC the exact raw
  body plus a timestamp (and relevant delivery metadata), enforce a short freshness window and replay/deduplication policy,
  and rotate the key. Wrong credentials -> `INVALID_WEBHOOK_CREDENTIALS` (map centrally if the event pipeline is wired);
  queue full -> 503 + validated `Retry-After`; handler idempotent. These properties require implementation and tests.
- `/metrics`: enabled only with `METRICS_AUTH_TOKEN` in prod; a wrong token returns **404** (do not reveal the endpoint).
- Feed/page cursors: **HMAC-signed** with `FEED_CURSOR_SECRET` (>= 32 chars); HMAC provides integrity, not confidentiality.
  Invalid -> 422 `INVALID_FEED_CURSOR`; security-event emission depends on the central mapper/sink being configured and tested.

## 6. Input, output, injection
Bound every string/list/page; whitelist filter keys; never put a user dict into a Mongo filter (operator injection).
Extension/file names are labels: validate `[a-z0-9]{1,10}`, cap file counts, generate storage keys server-side (a real bug:
an unvalidated extension reached the object name as `png/../x`). Titles that slugify to empty must return 422, not an empty slug.
Output goes through explicit response models; verify view allow-lists and projections against the actual Mongo query and stored
document shape. MongoDB `$set` to an embedded-document field normally replaces that field's value; dotted `$set` targets a
subfield, and `$mergeObjects` is an explicit merge. Do not infer a data leak from `$set` alone: identify the exact query,
projection and exposure path, then reproduce it with an integration test before reporting a leak.

## 7. Uploads (MinIO/S3)
Presigned URL/POST scoped to key prefix and strict byte-size limits; treat filename/extension and client MIME type as untrusted
labels, not evidence of content. Inspect actual content (magic/signature and a safe parser or scanner appropriate to the format),
bound archive entry count, nesting, expanded bytes and processing time to resist decompression bombs, and quarantine uploads away
from served objects until validation completes. Generate storage keys server-side; storage webhook confirms -> status machine
(`pending -> uploaded`); re-validate after upload; buckets private; serve only approved objects with short-lived presigned GET.

## 8. Detection: security events and rules (data, not code)
- A closed vocabulary of events (`auth.token_invalid`, `authz.denied`, `ratelimit.exceeded`, `input.cursor_invalid`,
  `webhook.auth_failed`, `scan.unmatched_route`, `admin.access`, `admin.mutation`, `audit.chain_broken`).
- Route existing error codes through one centrally wired code-to-event mapper (`ERROR_CODE_EVENTS`) so modules do not emit
  duplicate signals. The `fastapi-errors-logging/references/core.py` reference currently centralizes classification and ordinary
  error logging only: it does **not** implement this event map, security-channel writes, metrics, alerting, or audit storage.
  Do not claim events are emitted until the mapper/sink is integrated and tested.
- Rules as a readable table: `WindowRule(name, events, key_by ip|actor|global, threshold, window_seconds, severity, outcome)` and
  `NoveltyRule` (known account from a never-seen address). One alert per cooldown per key, not ten thousand.
- When the event pipeline is configured, route alerts to the security log channel and metrics; ensure the application's audit
  trail records outcome `denied|success|failure`. These sinks and audit writes must be implemented and verified in that app.

## 9. Audit log (separate module, tamper-evident)
Append-only `audit` module: who, what, target, outcome, reason, request id. A chain can use
`HMAC-SHA256(secret, prev_hash | canonical(entry))`, with a sequenced head/checkpoint and verification. Keep the HMAC key
outside the database and restrict writes; a plain hash chain can be recomputed by an attacker who can rewrite the DB. A head
stored only beside the entries is not an independent anchor: protect or periodically export/checkpoint it in a separately
controlled system to detect tail deletion. Verify canonicalization, concurrency/transaction behavior and recovery in tests;
periodic verification can raise `audit.chain_broken`. HMAC chaining is tamper-evidence under these key/checkpoint assumptions,
not proof of non-repudiation, immutability, or safety after key compromise. In production add DB-level defence (a role that
cannot update/delete the audit collection).
Write audit entries for: logins and failures, denials, role changes, deletes, exports, every staff mutation.

## 10. Secrets
Environment or secret files in `secrets/` (git-ignored, mounted read-only); typed `SecretStr`; never logged (redaction as the
last formatter step). Public repo = zero real secrets, scan history too (`gitleaks`). A private repo that knowingly commits
credentials is a conscious risk: restrict access, rotate on any collaborator change, never reuse those secrets.

## 11. Transport and host
The foundation Compose/Nginx example is **local development only**: it listens on HTTP at `127.0.0.1:8080` and does not
configure TLS. Its sample Mongo and Redis do enable password authentication (Mongo root credentials and Redis `requirepass`),
but that is not service-to-service TLS. Production must separately configure HTTPS/TLS at a trusted edge (and TLS to data
services when required by the deployment threat model), redirect 80->443, enable HSTS only after verifying HTTPS, and set
forwarded-header trust to exact proxy IPs/CIDRs. Add `server_tokens off`; nosniff/frame/referrer headers; explicit CORS. UFW
default-deny (22 restricted, 80, 443); SSH keys only + fail2ban; databases never published; Docker non-root, pinned tags,
healthchecks, resource limits, only Nginx publishes ports; configure and verify Mongo/Redis/MinIO authentication and tested
backups in the actual deployment; `pip-audit` + image scan in CI.

## Review checklist (paste into PRs)
- [ ] New route: `ActiveMember`/permission, object-level check, deny test, rate limit
- [ ] Inputs bounded; no client-supplied role/owner; filters whitelisted
- [ ] Secret added to `production_problems` + `.env.example`; nothing logged
- [ ] Views/projections verified on real Mongo; only public fields leave
- [ ] Security-relevant failures map to an event; staff mutations audited
- [ ] Uploads scoped and confirmed by webhook; webhook idempotent and authenticated

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.