Skip to content

About

Official axum and tower middleware for the InternetData API. Attach each visitor's IP data to the request, and block by country, anonymity or network.

Topics

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

50 Commits

Folders and files

Repository files navigation

InternetData InternetData axum Middleware

crates.io docs.rs license

The official axum middleware for the InternetData API.

It looks up the visitor behind each request, where they are, which network they come from and whether it's a VPN, a proxy, Tor or a hosting server, and puts the answer on the request. Blocking is opt-in.

It is a tower::Layer, so it works in any tower stack, not only axum.

Getting Started

cargo add internetdata-axum internetdata

Requires Rust 1.85 or newer, and axum 0.8.

No API key is needed to try it: without one a lookup answers the basics, the country, the network, Tor, relay and anycast. The company and the abuse contact behind the address are not in the basics; they come with a free key's full answers or a paid plan. Every lookup your app makes comes from your server's one address, though, so a busy site will use up that address's daily allowance and see its lookups refused. A free key answers more: every field on its organization's first lookups each UTC day, then the basics, which count as a failed lookup (below). A paid plan answers every field, VPN, the proxy flags, hosting, CDN, bots, carrier and satellite space, the service flags, the network's type, the company, the abuse contact and the city among them; create a key in the console.

use axum::{Router, routing::get};
use internetdata::middleware::Options;
use internetdata_axum::{Found, InternetData};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let guard = InternetData::new(
        Options::new().api_key(std::env::var("INTERNETDATA_API_KEY").unwrap_or_default()),
    )?;

    let app = Router::new().route("/", get(hello)).layer(guard);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
    axum::serve(
        listener,
        app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
    )
    .await?;
    Ok(())
}

async fn hello(Found(found): Found) -> String {
    match &found.result {
        Some(result) => format!("Hello, visitor from {}", result.location.country_name),
        None => "Hello".to_owned(),
    }
}

By default nothing is blocked. Every request carries a Lookup and your own handlers decide what it means: a currency to show, a sign-up to review, a page to keep from some countries.

Found rejects with 500 on a route the layer does not cover, which is a wiring mistake rather than something a visitor can cause. Use MaybeFound where that is deliberate.

Blocking

Set a block_condition and a matching request is answered with 403 and never reaches your handlers.

use internetdata::middleware::{Condition, Options};

Options::new().block_condition(vec![Condition::from([(
    "location",
    Condition::from([("country", vec!["CU", "IR", "KP"])]),
)])]);

A condition is written in the shape of a result, keyed by the same names the API uses, and only the members you name are considered, so it can refuse on anything in the answer. The country works on every plan, and so does the first of these:

use internetdata::middleware::{Bound, Condition};

// anycast space or a Tor exit: a list is OR
vec![Condition::from([("is_anycast", true)]), Condition::from([("is_tor", true)])];

// the network's type, on a paid plan or a free key's full answers
Condition::from([("asn", Condition::from([("type", "hosting")]))]);

// traffic from servers, not people
vec![Condition::from([("is_hosting", true)]), Condition::from([("is_cdn", true)])];

// crawlers and other bots, on a paid plan or a free key's full answers
Condition::from([("is_bot", true)]);

// anonymity
vec![
    Condition::from([("is_vpn", true)]),
    Condition::from([("is_tor", true)]),
    Condition::from([("is_resproxy", true)]),
];

// one provider
Condition::new()
    .with("is_vpn", true)
    .with("vpn", Condition::from([("provider", "nordvpn")]));

// a numeric threshold
Condition::from([("resproxy", Condition::from([("hits", Bound::gte(5.0))]))]);

Values are matched by equality, strings without regard to case. A Vec means any-of. A member the answer holds as a list (web's rows, pubproxy.protocols) matches when any one element does, an object term against a single row. Bound::gte, gt, lte and lt compare numbers and chain into a range (Bound::gte(5.0).and_lt(100.0)); every bound you give must hold. Members set to false or Value::Null are ignored, so a condition states the signals you act on; one that constrains nothing would match every request, and is refused when the middleware is built rather than silently blocking all your traffic.

A policy that lives in your app's config rather than in its source is read with from_json, which takes the same shape:

let condition = internetdata::middleware::from_json(&serde_json::json!({
    "location": { "country": ["CU", "IR", "KP"] },
}))?;
# Ok::<(), Box<dyn std::error::Error>>(())

Let verified crawlers through

allow_bots(true) sends a request's own User-Agent with its lookup when it names a crawler, and a request whose answer's user_agent verdict is verified, a real Googlebot say, is never refused, whatever block_condition matches. The answer still reaches your handler, its user_agent naming the agent and the verdict:

use internetdata::middleware::{Condition, Options};

Options::new()
    .api_key(std::env::var("INTERNETDATA_API_KEY")?)
    .allow_bots(true)
    .block_condition(vec![Condition::from([("is_hosting", true)])]);
# Ok::<(), Box<dyn std::error::Error>>(())

It is off by default, so the cache holds one answer per address rather than one per agent. Any other agent, or none, is not sent, since its verdict could only be not_bot. One address is looked up with at most four crawler agents an hour: past those its lookup sends none, and a request passes as a crawler only where the answer's bot.verified is true. A verdict comes with a paid plan or a free key's full answers: without a key, or past them, no answer carries one, so nothing is let through and the middleware says so once, as on_missing_field says. With it on, a condition can name the verdict too: Condition::from([("user_agent", Condition::from([("verdict", "spoofed")]))]) refuses a request posing as a crawler.

Replace the refusal with on_blocked:

# use axum::response::IntoResponse;
# use internetdata::middleware::Options;
# fn f() -> Result<(), internetdata::Error> {
internetdata_axum::InternetData::new(Options::new())?
    .on_blocked(|_parts, _found| {
        (axum::http::StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS, "Not available in your country")
            .into_response()
    });
# Ok(())
# }

Where the client address comes from

This is the setting that decides whether any of the above works, and it is the one thing only you can get right.

By default the middleware reads axum's ConnectInfo<SocketAddr>, which is the socket peer, and which is absent entirely unless you serve the app with into_make_service_with_connect_info, as the example above does. Behind nginx, a load balancer, or a CDN, that peer is your proxy, and that is the address that gets looked up: every visitor gets your proxy's country and network, and if it is a hosting address, a hosting rule blocks everyone. nginx on the same machine is 127.0.0.1 and a load balancer usually has a private address, which the middleware answers locally without a lookup, as an address with no country, and logs a warning.

For an edge that writes the address into its own header, name the header:

use internetdata::middleware::{Options, header};

Options::new().ip_selector(header("CF-Connecting-IP")); // or True-Client-IP

xff(0) reads the left-most X-Forwarded-For entry. Be aware that the left-most entry is whatever the caller sent, because proxies append to that header, so it's only trustworthy when an edge you control overwrites it. If you know how many proxies sit in front, count from the right instead: xff(1) is the address your nearest proxy saw.

Anything else, pass your own closure. It receives a RequestView and returns an address:

use std::sync::Arc;
use internetdata::middleware::{IpSelector, Options};

let mine: IpSelector = Arc::new(|view| (view.header)("x-real-ip"));
Options::new().ip_selector(mine);

If the address resolves to a private one, the middleware says so once through on_warn. That is expected on localhost and is the signal to fix your configuration anywhere else.

When a lookup fails

The request is let through, and the reason is on Lookup::error. Our outage should not become yours, so a network failure, a rate limit or a rejected key all fail open.

# use internetdata_axum::Found;
async fn handler(Found(found): Found) -> &'static str {
    if let Some(error) = &found.error {
        tracing::warn!(%error, "internetdata unavailable");
    }
    "ok"
}

Set fail_closed(true) to block instead. Private addresses are answered locally and never fail, so this will not lock you out in development.

A key whose organization has used up its lookups with every field (a free key's for the UTC day, a paid key's quota or overage cap) is answered the basics, and internetdata raises that answer as quota_exceeded. Here it is a failed lookup like any other: nothing is attached (found.result is None) and the request goes on, or is refused under fail_closed(true). The error is on found.error, and its capped() still holds the basics:

# use internetdata_axum::Found;
async fn hello(Found(found): Found) -> String {
    match found.error.as_deref().and_then(|error| error.capped()).and_then(|capped| capped.lookup())
    {
        Some(basics) => {
            format!("Hello, visitor from {} (basics only)", basics.location.country_name)
        }
        None => "Hello".to_owned(),
    }
}

A site that fails open would not otherwise hear of it, so the middleware logs it at error level, naming quota_exceeded, at most once a minute. It goes to standard error unless you say where:

# use std::sync::Arc;
# use internetdata::middleware::Options;
Options::new().on_error(Arc::new(|message| tracing::error!("{message}")));

Cost and latency

Answers are cached per middleware for an hour, so a returning visitor costs nothing, and private addresses never leave the process. A cache miss is one request to our API, bounded at 2500 ms by default and not retried: on a request path, failing open quickly beats holding a visitor while we try again. Both are adjustable, and so is the cache, through a client you build yourself and pass as client.

Layer the routes that matter rather than the whole router, or skip what you do not care about:

# use internetdata::middleware::Options;
# fn f() -> Result<(), internetdata::Error> {
internetdata_axum::InternetData::new(Options::new())?
    .skip(|parts| parts.uri.path().starts_with("/healthz"));
# Ok(())
# }

If you already hold an internetdata::Client, pass it as client and the middleware will share it rather than building a second cache.

Beyond a few million distinct visitors a day, stop calling the API per request: look addresses up locally in our databases instead.

Absent is not false

The basics, which a lookup with no key gets, and a free key past its day's full answers, leave out is_vpn, is_hosting, is_cdn, the four proxy flags, is_bot and the carrier, satellite and service flags, the detail behind them, company and abuse, and the paid members inside location and asn, such as location.city. A field the answer leaves out is None, which means "not in this answer" rather than "checked, and no". That is every member, is_bot, is_carrier, is_satellite, is_ssh, is_smtp, is_web, is_dns_resolver and is_bittorrent, asn.type, company and abuse included, with no exception; a block_condition on one still reports the gap, by the object's name for a term inside company or abuse.

# fn f(result: &internetdata::Lookup) -> bool {
result.is_vpn.unwrap_or(false);   // when you only want the flag
result.is_bot.is_none();          // in the basics: not served
result.company.is_none();         // in the basics: no company
# }

A block_condition naming a member your plan does not serve, location.city, asn.type, company or is_bot in the basics included, can never match, so the middleware warns once instead of failing silently. Set on_missing_field(OnMissingField::Fail) to make it an error.

Other Libraries

There are official InternetData client libraries available for many languages including PHP, Python, Go, Java, and Ruby. See our GitHub at https://github.com/internetdata for more.

About InternetData

Geolocation, anonymity, ownership, network, service and domain data for any IP address, AS or domain, by API or as databases you download.

InternetData

License

This project is licensed under the MIT License.

About

Official axum and tower middleware for the InternetData API. Attach each visitor's IP data to the request, and block by country, anonymity or network.

Topics

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages