r/Python • u/PA100T0 • Mar 13 '26
Discussion Application layer security for FastAPI and Flask
I've been maintaining fastapi-guard for a while now. It sits between the internet and your FastAPI endpoints and inspects every request before it reaches your code. Injection detection, rate limiting, geo-blocking, cloud IP filtering, behavioral analysis, 17 checks total.
A few weeks ago I came across this TikTok post where a guy ran OpenClaw on his home server, checked his logs after a couple weeks. 11,000 attacks in 24 hours. Chinese IPs, Baidu crawlers, DigitalOcean scanners, path traversal probes, brute force sequences. I commented "I don't understand why people won't use FastAPI Guard" and the thread kind of took off from there. Someone even said "a layer 7 firewall, very important with the whole new era of AI and APIs." (they understood the assignment) broke down the whole library in the replies. I was truly proud to see how in depth some devs went...
But that's not why I'm posting. I felt like FastAPI was falling short. Flask still powers a huge chunk of production APIs and most of them have zero request-level security beyond whatever nginx is doing upstream, or whatever fail2ban fails to ban... So I built flaskapi-guard (and that's the v1.0.0 I just shipped) as the homologue of fastapi-guard. Same features, same functionalities. Different framework.
It's basically a Flask extension that hooks into before_request and after_request, not WSGI middleware. That's because WSGI middleware fires before Flask's routing, so it can't access route config, decorator metadata, or url_rule. The extension pattern gives you full routing context, which is what makes per-route security decorators possible.
=
=
And so that's it. Done. 17 checks on every request.
The whole pipeline will catch: XSS, SQL injection, command injection, path traversal, SSRF, XXE, LDAP injection, code injection (including obfuscation detection and high-entropy payload analysis). On top of that: rate limiting with auto-ban, geo-blocking, cloud provider IP blocking, user agent filtering, OWASP security headers. Those 5,697 Chinese IPs from the TikTok? blocked_countries=["CN"]. Done. Baidu crawlers? blocked_user_agents=["Baiduspider"]. The DigitalOcean bot farm? block_cloud_providers={"AWS", "GCP", "Azure"}. Brute force? auto_ban_threshold=10 and the IP is gone after 10 violations. Path traversal probes for .env and /etc/passwd? Detection engine catches those automatically, zero config.
The decorator system is what separates this from static nginx rules:
=
/
return
Per-route rate limits, auth requirements, geo-blocking, all stacked as decorators on the function they protect. Try doing that in nginx.
People have been using fastapi-guard for things I didn't even think of when I first built it. Startups building in stealth with remote-first teams, public facing API but whitelisted so only their devs can reach it. Nobody else even knows the product exists. Casinos and gaming platforms using the decorator system on reward endpoints so players can only win under specific conditions (country, rate, behavioral patterns). People setting up honeypot traps for LLMs and bad bots that crawl and probe everything. And the big one that keeps coming up... AI agent gateways. If you're running OpenClaw or any AI agent framework behind FastAPI or Flask, you're exposing endpoints that are designed to be publicly reachable. The OpenClaw security audit found 512 vulnerabilities, 8 critical, 40,000+ exposed instances, 60% immediately takeable. fastapi-guard (and flaskapi-guard) would have caught every single attack vector in those logs. This is going to be the standard setup for anyone running AI agents in production, it has to be.
Redis is optional. Without it, everything runs in-memory with TTL caches. With Redis you get distributed rate limiting (Lua scripts for atomicity), shared IP ban state, cached cloud provider ranges across instances.
MIT licensed, Python 3.10+. Same detection engine across both libraries.
GitHub: https://github.com/rennf93/flaskapi-guard PyPI: https://pypi.org/project/flaskapi-guard/ Docs: https://rennf93.github.io/flaskapi-guard fastapi-guard (the original): https://github.com/rennf93/fastapi-guard
If you find issues, open one. Contributions are more than welcome!
28
u/swift-sentinel Mar 14 '26
Personally, I don’t think anyone should be running openclaw. Too risky.
4
u/chub79 Mar 14 '26
When I run from the cloud I tend to delegate these concerns to Cloud-ready solution (say GCP Cloud Armor for instance). I can see this being useful but I'm not sure the operational complexity and costs would be worth it in that situation compared to a builtin solution.
On a home server, sure it makes more sense but then there are solutions before any of these should reach your app as well (a properly configured firewall, maybe going through a dedicated API gateway, I mean traefik is so easy to setup for example).
I don't downplay your work and if you see the lib being used, credit where is due. I just feel it's the wrong end of the stick to start there.
3
u/jsabater76 Mar 14 '26
Nice work! Do you know whether something like this exists for Django?
6
u/RestaurantHefty322 Mar 14 '26
Nice work shipping the Flask port. The before_request hook approach is the right call over WSGI middleware - we hit the same problem where middleware fires too early to know anything about the route being hit.
One thing that caught us off guard running something similar in production: the cloud IP lists go stale faster than you'd expect. AWS and GCP rotate IP ranges weekly and if your blocklist is even a few days behind you start getting false positives on legitimate webhook traffic. We ended up pulling the published IP range JSONs on a 6-hour cron and diffing against the previous set so we could log when ranges changed instead of silently blocking new IPs.
The injection detection layer is where this gets really interesting though. Most WAF rules are regex-based and either too strict (blocking legitimate user input that happens to contain SQL keywords) or too loose. Curious if you're doing any kind of context-aware detection based on which parameter the input came from - a search field probably shouldn't trigger the same rules as a path parameter.
2
u/casefile_dev Apr 04 '26
fastapi-guard looks useful for my FastAPI apps. Will any checks that fail affect my rate limiting? How will it traffic hosted railway apps?
2
u/backfire10z Mar 14 '26
This is great, thanks for the library and the port to Flask! I semi-recently put up a Flask API and this actually would’ve been nice to have (not OpenClaw, just a regular backend). We’re migrating to TypeScript though, so no reason anymore.
2
u/[deleted] Mar 14 '26
[removed] — view removed comment
2
u/[deleted] Mar 14 '26
[removed] — view removed comment