Korzen
Bot Protection
In these docs

Rust (Axum, Actix Web)

Bot Protection in a Rust server with the korzen-bot-protection crate: a tower layer for Axum, the same call in Actix Web and the visitor's IP.

The client is the crate korzen-bot-protection: a tower layer for Axum 0.8, on tokio, that asks /v1/decide before the handler, gives up at its timeout and lets the visitor through on any error. One Client for the process keeps its connections open, so a call costs one round trip and not a new TLS handshake.

Payment, login and sign-up routes: turn on protected_action in the layer's Options, 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 layout that renders your sign-up, sign-in and checkout pages:

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

In the page, before the form is sent, call await window.korzen?.ready(): it reports what the visitor did since the tag last reported, and resolves within a few seconds whatever happens. The tag

The call

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

cargo add korzen-bot-protection

Or, in Cargo.toml:

[dependencies]
korzen-bot-protection = "3.0"

Axum

The layer on the routes that create an account or take a payment. It answers a block with 403, and otherwise calls your handler with the decision in the request's extensions. Serve the app with ConnectInfo, so the layer reads the address the connection came from:

use std::net::SocketAddr;
use std::time::Duration;

use axum::{Extension, Router, routing::post};
use korzen_bot_protection::{Client, Decision, Ip, Options};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // The timeout for your server's region: https://korzen.dev/bot-protection/docs/server-call#latency
    let korzen = Client::builder(std::env::var("KORZEN_API_KEY").unwrap_or_default())
        .url("https://eu.korzen.dev")
        .timeout(Duration::from_millis(200))
        .build();
    let app = Router::new()
        .route("/signup", post(signup))
        // sign-up, login and payment: a script that never loaded your page holds no token
        .layer(korzen.layer(Options::new().ip(Ip::Peer).protected_action(true)));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
    Ok(())
}

async fn signup(decision: Option<Extension<Decision>>) -> &'static str {
    let request_id = decision.map(|Extension(d)| d.request_id).unwrap_or_default();
    // create the account, and keep request_id with it (see "Apply the action")
    "welcome"
}

To answer a block yourself, give the layer on_block. Every option, with what it does, is in the crate's documentation on docs.rs.

Actix Web

The layer is for tower, so in Actix Web the handler that creates the account makes the call itself with decide, with the client registered once as web::Data. On any error, unwrap_or_default() is an allow:

use actix_web::{HttpRequest, HttpResponse, web};
use korzen_bot_protection::{ALLOW, Client, FORWARDED, Request, TOKEN_COOKIE};

async fn signup(req: HttpRequest, korzen: web::Data<Client>) -> HttpResponse {
    let header = |name: &str| req.headers().get(name).and_then(|v| v.to_str().ok()).map(str::to_owned);
    let decision = korzen
        .decide(Request {
            ip: req.peer_addr().map(|a| a.ip().to_string()).unwrap_or_default(),
            ip_from: "peer".into(),
            user_agent: header("user-agent").unwrap_or_default(),
            headers: FORWARDED.iter().filter_map(|n| Some((n.to_string(), header(n)?))).collect(),
            token: req.cookie(TOKEN_COOKIE).map(|c| c.value().to_owned()).unwrap_or_default(),
            method: req.method().to_string(),
            path: req.path().to_owned(),
            protected_action: true,
            ..Request::default()
        })
        .await
        .unwrap_or_default();
    if decision.action != ALLOW {
        return HttpResponse::BadRequest().body("We could not create your account.");
    }
    // create the account, and keep decision.request_id with it
    HttpResponse::Ok().body("welcome")
}

The visitor's IP

Ip::Peer reads the address the connection came from. That is the visitor only when nothing stands in front of your server. Behind a load balancer or nginx, use Ip::LastForwarded, the address it put in X-Forwarded-For, and only when every request comes through it. Behind Cloudflare, use Ip::Cloudflare, which reads CF-Connecting-IP, if your server only takes traffic from Cloudflare.

Apply the action

Read only action. On block, answer with the same error the action 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 cargo run and open http://localhost:3000. 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

  • A new Client per request. Each opens a TLS connection to Germany: one or two more round trips. Build one, and clone it where you need it.
  • Serving the app without into_make_service_with_connect_info. With Ip::Peer, the decision then goes without the visitor's address.
  • Calling /v1/decide from the browser. The API key would reach every visitor; the call belongs on your server.