# Rust

> A complete integration with reqwest and tokio. One function that calls the API with a timeout and fails open, typed answers with serde, a policy function, and an axum sign-up handler.

This guide uses `reqwest` with `tokio`, and `serde` for typed answers. The handler example uses `axum`.

```toml title="Cargo.toml"
[dependencies]
reqwest = { version = "0.13", features = ["json"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tracing = "0.1"
# For the handler in step 3:
axum = "0.8"
```

## 1. Call the API

`check_signup` returns Heimdal's answer, or `None` when there is none: a timeout, a network error, or an error status. `None` means "no opinion", and the caller lets the sign-up through. Only the fields the policy reads are typed; serde ignores the rest.

```rust title="src/heimdal.rs"
use std::net::IpAddr;
use std::time::Duration;

use serde::{Deserialize, Serialize};

const CHECK_URL: &str = "https://heimdal.codebrewerz.com/api/v1/check";

#[derive(Serialize)]
struct Query<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    ip: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    email: Option<&'a str>,
}

#[derive(Debug, Deserialize)]
pub struct Answer {
    pub block: bool,
    pub reasons: Vec<String>,
    pub email: Option<EmailSignals>,
    pub ip: Option<IpSignals>,
    pub custom: Custom,
}

#[derive(Debug, Deserialize)]
pub struct EmailSignals {
    pub disposable: bool,
}

#[derive(Debug, Deserialize)]
pub struct IpSignals {
    pub tor: bool,
    pub proxy: bool,
    pub vpn: bool,
    pub bad_isp: bool,
    pub asn: Option<u32>,
}

#[derive(Debug, Deserialize)]
pub struct Custom {
    pub matched: Vec<serde_json::Value>,
}

#[derive(Deserialize)]
struct ErrorBody {
    error: ErrorDetail,
}

#[derive(Deserialize)]
struct ErrorDetail {
    code: String,
    message: String,
}

/// One client for the whole app: it pools connections. Build it once.
pub fn client() -> reqwest::Client {
    reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(2))
        .timeout(Duration::from_secs(2))
        .build()
        .expect("TLS backend available")
}

/// Heimdal's answer, or `None` when the check could not be made.
pub async fn check_signup(
    client: &reqwest::Client,
    api_key: &str,
    ip: Option<&str>,
    email: Option<&str>,
) -> Option<Answer> {
    // An address that is not valid would fail the whole request: leave it out.
    let ip = ip
        .and_then(|value| value.parse::<IpAddr>().ok())
        .map(|addr| addr.to_string());
    let response = client
        .post(CHECK_URL)
        .bearer_auth(api_key)
        .json(&Query { ip, email })
        .send()
        .await;
    let response = match response {
        Ok(response) => response,
        Err(err) => {
            tracing::warn!("Heimdal check failed, sign-up allowed: {err}");
            return None;
        }
    };
    let status = response.status();
    if !status.is_success() {
        match response.json::<ErrorBody>().await {
            Ok(body) => tracing::warn!(
                "Heimdal {status} {}: {}",
                body.error.code,
                body.error.message
            ),
            Err(_) => tracing::warn!("Heimdal {status}"),
        }
        return None;
    }
    match response.json::<Answer>().await {
        Ok(answer) => Some(answer),
        Err(err) => {
            tracing::warn!("Heimdal answer unreadable, sign-up allowed: {err}");
            None
        }
    }
}
```

## 2. Decide

Keep the policy in one function, apart from the HTTP call. This one refuses disposable email, Tor, open proxies and custom-list hits. VPN and hosting networks pass.

```rust title="src/heimdal.rs"
/// The message that refuses this sign-up, or `None` to let it through.
pub fn refusal_for(answer: Option<&Answer>) -> Option<&'static str> {
    let answer = answer?;
    if answer.email.as_ref().is_some_and(|email| email.disposable) {
        return Some("Disposable email addresses can't be used to sign up.");
    }
    if answer.ip.as_ref().is_some_and(|ip| ip.tor || ip.proxy) {
        return Some(
            "Sign-ups from this network aren't allowed. Contact support if this is a mistake.",
        );
    }
    if !answer.custom.matched.is_empty() {
        return Some("This sign-up can't be completed. Contact support if this is a mistake.");
    }
    None
}
```

To use the strict policy instead, refuse whenever `answer.block` is `true`. [Best practices](https://heimdal.codebrewerz.com/docs/guides/best-practices/#choose-a-policy) explains the trade-off.

## 3. Use it in your sign-up handler

The example uses axum. The two calls are the same in any framework.

```rust title="src/main.rs"
mod heimdal;

use std::net::SocketAddr;
use std::sync::Arc;

use axum::extract::{ConnectInfo, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::routing::post;
use axum::{Json, Router};
use serde::Deserialize;

struct AppState {
    heimdal: reqwest::Client,
    api_key: String,
}

#[derive(Deserialize)]
struct Signup {
    email: String,
    password: String,
}

async fn signup(
    State(state): State<Arc<AppState>>,
    // Behind a proxy, read the client address from the header your proxy
    // sets instead: this is the proxy's own address.
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    Json(body): Json<Signup>,
) -> impl IntoResponse {
    let ip = peer.ip().to_string();
    let answer = heimdal::check_signup(
        &state.heimdal,
        &state.api_key,
        Some(&ip),
        Some(&body.email),
    )
    .await;
    if let Some(refusal) = heimdal::refusal_for(answer.as_ref()) {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({ "error": refusal })),
        )
            .into_response();
    }

    // Create the user as you do today, with body.password.
    let _ = &body.password;
    StatusCode::CREATED.into_response()
}

#[tokio::main]
async fn main() {
    let state = Arc::new(AppState {
        heimdal: heimdal::client(),
        api_key: std::env::var("HEIMDAL_API_KEY").expect("Set HEIMDAL_API_KEY"),
    });
    let app = Router::new()
        .route("/signup", post(signup))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(
        listener,
        app.into_make_service_with_connect_info::<SocketAddr>(),
    )
    .await
    .unwrap();
}
```

## What this gets right

- **It fails open.** No answer from Heimdal never blocks a sign-up.
- **It has a timeout.** Connect and the whole request are capped at two seconds.
- **It reuses one client**, so connections to Heimdal are pooled.
- **It sends the visitor's address**, and only when it parses as an IP address.
- **It keeps the key on the server**, in `HEIMDAL_API_KEY`, and refuses to start without it.
- **It reads errors**: every non-2xx answer is `{"error":{"code","message"}}` and is logged with its code.

## Test it

```sh
curl -X POST "http://localhost:3000/signup" \
  -H "Content-Type: application/json" \
  -d '{"email": "test@mailinator.com", "password": "Correct-horse-9"}'
```

```json
{ "error": "Disposable email addresses can't be used to sign up." }
```
