Korzen
Bot Protection
In these docs

FastAPI

Bot Protection in FastAPI: the tag, Korzen's Python package as ASGI middleware for the call, and uvicorn behind a proxy.

This guide is for FastAPI on Python 3.11 or later, served by uvicorn, and works the same in any Starlette app. Korzen's package for Python, korzen-bot-protection, is an ASGI middleware: it asks /v1/decide on threads of its own, never on the event loop, gives up at your timeout and lets the visitor through on any error.

Payment, login and sign-up routes: turn on protected_action=True, so a script that never loads your page cannot take the action. Protecting a checkout

The tag

Put the tag in the <head> of the template your sign-up, sign-in and checkout pages extend:

<script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script>

For visitors whose network blocks Korzen's host, first_party=True serves the tag and its beacon from your own domain. First-party mode

The call

Behind Cloudflare? A Worker can do this without changing your app. Cloudflare Workers

Install the package from PyPI:

pip install korzen-bot-protection

Then add KorzenASGI to the app. On the paths you name, it asks before your route runs, answers a block itself, and leaves the answer in request.scope["korzen.decision"], or None when there is none (Form needs python-multipart):

# main.py
import os
from typing import Annotated

from fastapi import FastAPI, Form, Request
from fastapi.responses import PlainTextResponse, RedirectResponse
from korzen_bot_protection import Client, KorzenASGI

app = FastAPI()
# One for the process. The timeout for your server's region: https://korzen.dev/bot-protection/docs/server-call#latency
korzen = Client(os.environ["KORZEN_API_KEY"], url="https://eu.korzen.dev", timeout=0.2)


async def blocked(scope, receive, send, decision):
    """A blocked sign-up gets the form's own error, so a bot learns nothing."""
    await PlainTextResponse("We could not create your account.", status_code=400)(scope, receive, send)
    return True


app.add_middleware(
    KorzenASGI,
    client=korzen,
    prefixes=["/signup"],
    protected_action=True,  # sign-up, login and payment: a script that never loaded your page holds no token; a page load spends none
    on_block=blocked,
)


@app.post("/signup")
async def signup(request: Request, email: Annotated[str, Form()]):
    d = request.scope["korzen.decision"]  # a Decision, or None
    user = await create_account(email)  # your own code
    await save_request_id(user, d and d.request_id)  # see "Apply the action"
    return RedirectResponse("/welcome", status_code=303)

The middleware sends the request's headers in the order they came, which ASGI keeps in the scope; behind nginx, a load balancer or Cloudflare, that is the order the last hop forwards them in. To ask inside a route instead, await asyncio.to_thread(korzen.decide, from_asgi(request.scope, path="/signup")) returns the answer, or None on any error; it never raises.

The visitor's IP

The middleware takes the scope's client, the connection's address unless uvicorn trusts the proxy in front. uvicorn reads X-Forwarded-For from the addresses --forwarded-allow-ips names (127.0.0.1 by default) and sets the client to the last entry they did not add: run it with your load balancer's address, such as uvicorn main:app --forwarded-allow-ips 10.0.0.5, or the network it is on. Behind Cloudflare, pass ip=cloudflare_ip, which reads CF-Connecting-IP, if your server only takes traffic from Cloudflare.

Apply the action

The middleware applies action: on block it answers 403, or what your on_block sends, and your route never runs. Make that answer the error the form shows when it fails for any other reason, so a bot learns nothing. The account starts in monitor mode, where action is always allow: nothing changes for visitors until you turn on block mode.

Keep the answer's request_id with what the action created, such as the account or the order: it names that decision when you ask us about it. The answer

Test it on your machine

Run uvicorn main:app --reload and open it on localhost. Pages on localhost always accept the tag and are never listed as a domain. Locally the IP is 127.0.0.1 or ::1, and that is fine. In Docker on your machine, the app sees the bridge's address instead, such as 172.17.0.1, and that is fine too.

  1. Set KORZEN_API_KEY in the environment and open the sign-up page. In the browser's developer tools, the _kz cookie appears after a few seconds.
  2. Sign up. The decision shows on the dashboard's Decisions page, under the path you sent.
  3. Check fail open: set a wrong key and sign up again. The call answers 401, and the sign-up goes through.

Common mistakes

  • --forwarded-allow-ips '*'. It trusts every hop, so the client becomes the first entry of X-Forwarded-For, which the visitor writes.
  • A new Client for each request. Make one for the process: it keeps the connection open between calls.
  • Calling /v1/decide from the browser. The API key would reach every visitor; the call belongs on your server.
  • A line in your log that starts korzen: the visitor's IP sent to Bot Protection. The client writes it once, at the first decision whose IP is your own network's (a load balancer's, a proxy's, a container's), which Bot Protection judges as no IP: set ip to the visitor's address (the visitor's IP). In Docker on your machine it is the bridge's address, and harmless there.