rust_web_utils/uautil/
middleware.rs1use std::future::Future;
2use std::pin::Pin;
3use std::sync::Arc;
4use std::task::{Context, Poll};
5
6use bytes::Bytes;
7use http::header::{CONTENT_TYPE, HeaderValue, X_CONTENT_TYPE_OPTIONS};
8use http::{Request, Response, StatusCode};
9use http_body_util::{Either, Full};
10use tower_layer::Layer;
11use tower_service::Service;
12
13use super::{is_bot, is_browser};
14
15#[derive(Debug, Clone, Copy)]
16enum Rule {
17 BlockBot { allow_legitimate: bool },
18 BrowserOnly,
19}
20
21impl Rule {
22 fn rejects(self, headers: &http::HeaderMap) -> bool {
23 match self {
24 Rule::BlockBot { allow_legitimate } => is_bot(headers, allow_legitimate),
25 Rule::BrowserOnly => !is_browser(headers),
26 }
27 }
28}
29
30#[derive(Debug, Clone)]
40pub struct BlockBotLayer {
41 allow_legitimate: bool,
42 message: Arc<str>,
43}
44
45impl BlockBotLayer {
46 pub fn new(allow_legitimate: bool) -> Self {
48 Self {
49 allow_legitimate,
50 message: Arc::from("Bot access denied"),
51 }
52 }
53
54 pub fn message(mut self, message: &str) -> Self {
56 if !message.is_empty() {
57 self.message = Arc::from(message);
58 }
59 self
60 }
61}
62
63impl<S> Layer<S> for BlockBotLayer {
64 type Service = UaGuard<S>;
65
66 fn layer(&self, inner: S) -> Self::Service {
67 UaGuard {
68 inner,
69 rule: Rule::BlockBot {
70 allow_legitimate: self.allow_legitimate,
71 },
72 message: self.message.clone(),
73 }
74 }
75}
76
77#[derive(Debug, Clone)]
79pub struct BrowserOnlyLayer {
80 message: Arc<str>,
81}
82
83impl BrowserOnlyLayer {
84 pub fn new() -> Self {
86 Self {
87 message: Arc::from("Browser access only"),
88 }
89 }
90
91 pub fn message(mut self, message: &str) -> Self {
93 if !message.is_empty() {
94 self.message = Arc::from(message);
95 }
96 self
97 }
98}
99
100impl Default for BrowserOnlyLayer {
101 fn default() -> Self {
102 Self::new()
103 }
104}
105
106impl<S> Layer<S> for BrowserOnlyLayer {
107 type Service = UaGuard<S>;
108
109 fn layer(&self, inner: S) -> Self::Service {
110 UaGuard {
111 inner,
112 rule: Rule::BrowserOnly,
113 message: self.message.clone(),
114 }
115 }
116}
117
118#[derive(Debug, Clone)]
121pub struct UaGuard<S> {
122 inner: S,
123 rule: Rule,
124 message: Arc<str>,
125}
126
127impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for UaGuard<S>
128where
129 S: Service<Request<ReqBody>, Response = Response<ResBody>>,
130 S::Future: Send + 'static,
131 S::Error: Send + 'static,
132 ResBody: Send + 'static,
133{
134 type Response = Response<Either<ResBody, Full<Bytes>>>;
135 type Error = S::Error;
136 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
137
138 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
139 self.inner.poll_ready(cx)
140 }
141
142 fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
143 if self.rule.rejects(req.headers()) {
144 let resp = forbidden(&self.message);
145 return Box::pin(async move { Ok(resp) });
146 }
147 let fut = self.inner.call(req);
148 Box::pin(async move { Ok(fut.await?.map(Either::Left)) })
149 }
150}
151
152fn forbidden<B>(message: &str) -> Response<Either<B, Full<Bytes>>> {
154 let mut resp = Response::new(Either::Right(Full::new(Bytes::from(format!("{message}\n")))));
155 *resp.status_mut() = StatusCode::FORBIDDEN;
156 let h = resp.headers_mut();
157 h.insert(CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"));
158 h.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
159 resp
160}
161
162#[cfg(test)]
163mod tests {
164 use std::convert::Infallible;
165
166 use http_body_util::BodyExt;
167 use tower::{ServiceBuilder, ServiceExt, service_fn};
168
169 use super::*;
170
171 async fn ok(_req: Request<()>) -> Result<Response<Full<Bytes>>, Infallible> {
172 Ok(Response::new(Full::new(Bytes::from_static(b"ok"))))
173 }
174
175 type Guarded = Response<Either<Full<Bytes>, Full<Bytes>>>;
176
177 async fn run(
178 svc: impl Service<Request<()>, Response = Guarded, Error = Infallible>,
179 ua: Option<&str>,
180 ) -> (StatusCode, String) {
181 let mut req = Request::builder();
182 if let Some(ua) = ua {
183 req = req.header("user-agent", ua);
184 }
185 let resp = svc.oneshot(req.body(()).unwrap()).await.unwrap();
186 let status = resp.status();
187 let body = resp.into_body().collect().await.unwrap().to_bytes();
188 (status, String::from_utf8(body.to_vec()).unwrap())
189 }
190
191 #[tokio::test]
192 async fn block_bot() {
193 let svc = || {
194 ServiceBuilder::new()
195 .layer(BlockBotLayer::new(true))
196 .service(service_fn(ok))
197 };
198 assert_eq!(
199 run(svc(), Some("curl/8")).await,
200 (StatusCode::FORBIDDEN, "Bot access denied\n".into())
201 );
202 assert_eq!(run(svc(), None).await.0, StatusCode::FORBIDDEN);
203 assert_eq!(run(svc(), Some("Googlebot/2.1")).await, (StatusCode::OK, "ok".into()));
204 assert_eq!(run(svc(), Some("Mozilla/5.0 Chrome/130.0")).await.0, StatusCode::OK);
205
206 let strict = ServiceBuilder::new()
207 .layer(BlockBotLayer::new(false).message("nope"))
208 .service(service_fn(ok));
209 assert_eq!(
210 run(strict, Some("Googlebot/2.1")).await,
211 (StatusCode::FORBIDDEN, "nope\n".into())
212 );
213 }
214
215 #[tokio::test]
216 async fn browser_only() {
217 let svc = || {
218 ServiceBuilder::new()
219 .layer(BrowserOnlyLayer::new())
220 .service(service_fn(ok))
221 };
222 assert_eq!(run(svc(), Some("Mozilla/5.0 Firefox/120.0")).await.0, StatusCode::OK);
223 assert_eq!(
224 run(svc(), Some("SomeApp/1.0")).await,
225 (StatusCode::FORBIDDEN, "Browser access only\n".into())
226 );
227 assert_eq!(run(svc(), None).await.0, StatusCode::FORBIDDEN);
228 }
229}