vpndetection_axum/lib.rs
1//! The official [axum](https://github.com/tokio-rs/axum) middleware for the
2//! [VPNDetection](https://vpndetection.io) API.
3//!
4//! It classifies the visitor behind each request - VPN, residential proxy, Tor,
5//! hosting, CDN, relay - and puts the answer on the request. Blocking is
6//! opt-in.
7//!
8//! It is a [`tower_layer::Layer`], so it works in any tower stack, not only
9//! axum.
10//!
11//! ```no_run
12//! use axum::{Router, routing::get};
13//! use vpndetection_axum::{Found, VPNDetection};
14//!
15//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
16//! let guard = VPNDetection::new(
17//! vpndetection::middleware::Options::new().api_key(std::env::var("VPNDETECTION_API_KEY")?),
18//! )?;
19//!
20//! let app: Router = Router::new().route("/", get(hello)).layer(guard);
21//!
22//! async fn hello(Found(found): Found) -> &'static str {
23//! match found.result.as_ref().map(|r| r.is_vpn) {
24//! Some(true) => "Hello, VPN user",
25//! _ => "Hello",
26//! }
27//! }
28//! # Ok(())
29//! # }
30//! ```
31//!
32//! By default nothing is blocked. Every request carries a
33//! [`vpndetection::middleware::Lookup`] and your own handlers decide what that
34//! means - which is usually what you want, because whether a VPN visitor is a
35//! problem depends entirely on what they are doing.
36//!
37//! # Where the client address comes from
38//!
39//! By default the middleware reads axum's [`axum::extract::ConnectInfo`], which
40//! is the socket peer - and which is **absent unless you served the app with
41//! [`axum::Router::into_make_service_with_connect_info`]**. Behind nginx, a
42//! load balancer or a CDN, that peer is your proxy: a datacenter address, so a
43//! hosting rule would block every visitor you have. Name your edge's header
44//! instead:
45//!
46//! ```
47//! # use vpndetection::middleware::Options;
48//! Options::new().ip_selector(vpndetection::middleware::header("CF-Connecting-IP"));
49//! ```
50
51use std::net::SocketAddr;
52use std::sync::Arc;
53use std::task::{Context, Poll};
54
55use axum::extract::ConnectInfo;
56use axum::response::{IntoResponse, Response};
57use futures_util::future::BoxFuture;
58use http::{Request, StatusCode};
59use vpndetection::middleware::{Core, Lookup, Options, RequestView};
60
61pub use vpndetection::middleware;
62
63/// How a blocked request is answered, and which requests are classified at all.
64///
65/// Both are here rather than in [`Options`] because both need the framework's
66/// own request type, which the shared core deliberately does not know.
67type Blocked = Arc<dyn Fn(&http::request::Parts, &Lookup) -> Response + Send + Sync>;
68type Skip = Arc<dyn Fn(&http::request::Parts) -> bool + Send + Sync>;
69
70/// The middleware, as a [`tower_layer::Layer`].
71///
72/// `.layer(guard)` on a [`axum::Router`], or anywhere a tower layer goes.
73#[derive(Clone)]
74pub struct VPNDetection {
75 core: Core,
76 on_blocked: Blocked,
77 skip: Option<Skip>,
78}
79
80impl VPNDetection {
81 /// Builds the middleware, refusing a condition that constrains nothing and
82 /// building a client when [`Options::client`] was not set.
83 pub fn new(options: Options) -> Result<Self, vpndetection::Error> {
84 Ok(Self { core: Core::new(options)?, on_blocked: Arc::new(refuse), skip: None })
85 }
86
87 /// Answers a request the condition matched, replacing the `403`.
88 ///
89 /// The handler never runs either way.
90 ///
91 /// ```
92 /// # use axum::response::IntoResponse;
93 /// # use vpndetection::middleware::Options;
94 /// # fn f() -> Result<(), vpndetection::Error> {
95 /// vpndetection_axum::VPNDetection::new(Options::new())?
96 /// .on_blocked(|_parts, found| {
97 /// let why = found.result.as_ref().and_then(|r| r.vpn.as_ref());
98 /// (axum::http::StatusCode::FORBIDDEN, format!("{why:?}")).into_response()
99 /// });
100 /// # Ok(())
101 /// # }
102 /// ```
103 #[must_use]
104 pub fn on_blocked<F>(mut self, on_blocked: F) -> Self
105 where
106 F: Fn(&http::request::Parts, &Lookup) -> Response + Send + Sync + 'static,
107 {
108 self.on_blocked = Arc::new(on_blocked);
109 self
110 }
111
112 /// Skip classification for a request entirely - health checks, static
113 /// assets, anything an app-wide layer would otherwise pay for.
114 #[must_use]
115 pub fn skip<F>(mut self, skip: F) -> Self
116 where
117 F: Fn(&http::request::Parts) -> bool + Send + Sync + 'static,
118 {
119 self.skip = Some(Arc::new(skip));
120 self
121 }
122}
123
124impl<S> tower_layer::Layer<S> for VPNDetection {
125 type Service = VPNDetectionService<S>;
126
127 fn layer(&self, inner: S) -> Self::Service {
128 VPNDetectionService {
129 inner,
130 core: self.core.clone(),
131 on_blocked: Arc::clone(&self.on_blocked),
132 skip: self.skip.clone(),
133 }
134 }
135}
136
137/// What [`VPNDetection`] wraps a service in. You never name this type.
138#[derive(Clone)]
139pub struct VPNDetectionService<S> {
140 inner: S,
141 core: Core,
142 on_blocked: Blocked,
143 skip: Option<Skip>,
144}
145
146impl<S, B> tower_service::Service<Request<B>> for VPNDetectionService<S>
147where
148 S: tower_service::Service<Request<B>, Response = Response> + Clone + Send + 'static,
149 S::Future: Send + 'static,
150 B: Send + 'static,
151{
152 type Response = Response;
153 type Error = S::Error;
154 type Future = BoxFuture<'static, Result<Response, S::Error>>;
155
156 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
157 self.inner.poll_ready(cx)
158 }
159
160 fn call(&mut self, request: Request<B>) -> Self::Future {
161 // The CLONE is the one that was polled ready; `self.inner` may not be.
162 // Swapping rather than cloning in place is the tower idiom, and getting
163 // it backwards is how a middleware calls a service that was never
164 // readied.
165 let clone = self.inner.clone();
166 let mut inner = std::mem::replace(&mut self.inner, clone);
167 let core = self.core.clone();
168 let on_blocked = Arc::clone(&self.on_blocked);
169 let skip = self.skip.clone();
170
171 Box::pin(async move {
172 let (mut parts, body) = request.into_parts();
173 if skip.is_some_and(|skip| skip(&parts)) {
174 return inner.call(Request::from_parts(parts, body)).await;
175 }
176
177 let found = {
178 let header = |name: &str| {
179 parts.headers.get(name).and_then(|v| v.to_str().ok()).map(str::to_owned)
180 };
181 let framework_ip = || {
182 parts
183 .extensions
184 .get::<ConnectInfo<SocketAddr>>()
185 .map(|ConnectInfo(addr)| addr.ip().to_string())
186 };
187 core.evaluate(&RequestView { header: &header, framework_ip: &framework_ip }).await
188 };
189 let found = match found {
190 Ok(found) => found,
191 // A condition naming a member the plan does not serve, with
192 // OnMissingField::Fail. A LOOKUP failure never lands here: it
193 // rides on Lookup::error and the visitor is let through.
194 Err(error) => {
195 return Ok(
196 (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response()
197 );
198 }
199 };
200
201 if found.blocked {
202 return Ok(on_blocked(&parts, &found));
203 }
204 parts.extensions.insert(found);
205 inner.call(Request::from_parts(parts, body)).await
206 })
207 }
208}
209
210fn refuse(_parts: &http::request::Parts, _found: &Lookup) -> Response {
211 // Written out rather than serialized: one fixed object is not worth a
212 // serde_json dependency in a crate that otherwise needs none.
213 (
214 StatusCode::FORBIDDEN,
215 [(http::header::CONTENT_TYPE, "application/json")],
216 r#"{"error":"access denied"}"#,
217 )
218 .into_response()
219}
220
221/// What the middleware found out about this visitor.
222///
223/// ```
224/// use vpndetection_axum::Found;
225///
226/// async fn handler(Found(found): Found) -> String {
227/// format!("{:?}", found.result.map(|r| r.is_vpn))
228/// }
229/// ```
230///
231/// Rejects with `500` when the middleware did not run for this route, which is
232/// a wiring mistake rather than something a visitor can cause. Use
233/// [`MaybeFound`] on a route that is deliberately outside the layer, or one
234/// `skip` claims.
235#[derive(Debug, Clone)]
236pub struct Found(pub Lookup);
237
238/// [`Found`], for a route where the middleware may not have run.
239#[derive(Debug, Clone)]
240pub struct MaybeFound(pub Option<Lookup>);
241
242impl<S: Send + Sync> axum::extract::FromRequestParts<S> for Found {
243 type Rejection = Response;
244
245 async fn from_request_parts(
246 parts: &mut http::request::Parts,
247 _state: &S,
248 ) -> Result<Self, Self::Rejection> {
249 parts.extensions.get::<Lookup>().cloned().map(Self).ok_or_else(|| {
250 (
251 StatusCode::INTERNAL_SERVER_ERROR,
252 "vpndetection: this route is not behind the VPNDetection layer, or `skip` \
253 claimed the request; extract MaybeFound instead",
254 )
255 .into_response()
256 })
257 }
258}
259
260impl<S: Send + Sync> axum::extract::FromRequestParts<S> for MaybeFound {
261 type Rejection = std::convert::Infallible;
262
263 async fn from_request_parts(
264 parts: &mut http::request::Parts,
265 _state: &S,
266 ) -> Result<Self, Self::Rejection> {
267 Ok(Self(parts.extensions.get::<Lookup>().cloned()))
268 }
269}