use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use bytes::Bytes;
use http::header::{CONTENT_TYPE, HeaderValue, X_CONTENT_TYPE_OPTIONS};
use http::{Request, Response, StatusCode};
use http_body_util::{Either, Full};
use tower_layer::Layer;
use tower_service::Service;
use super::{is_bot, is_browser};
#[derive(Debug, Clone, Copy)]
enum Rule {
BlockBot { allow_legitimate: bool },
BrowserOnly,
}
impl Rule {
fn rejects(self, headers: &http::HeaderMap) -> bool {
match self {
Rule::BlockBot { allow_legitimate } => is_bot(headers, allow_legitimate),
Rule::BrowserOnly => !is_browser(headers),
}
}
}
#[derive(Debug, Clone)]
pub struct BlockBotLayer {
allow_legitimate: bool,
message: Arc<str>,
}
impl BlockBotLayer {
pub fn new(allow_legitimate: bool) -> Self {
Self {
allow_legitimate,
message: Arc::from("Bot access denied"),
}
}
pub fn message(mut self, message: &str) -> Self {
if !message.is_empty() {
self.message = Arc::from(message);
}
self
}
}
impl<S> Layer<S> for BlockBotLayer {
type Service = UaGuard<S>;
fn layer(&self, inner: S) -> Self::Service {
UaGuard {
inner,
rule: Rule::BlockBot {
allow_legitimate: self.allow_legitimate,
},
message: self.message.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct BrowserOnlyLayer {
message: Arc<str>,
}
impl BrowserOnlyLayer {
pub fn new() -> Self {
Self {
message: Arc::from("Browser access only"),
}
}
pub fn message(mut self, message: &str) -> Self {
if !message.is_empty() {
self.message = Arc::from(message);
}
self
}
}
impl Default for BrowserOnlyLayer {
fn default() -> Self {
Self::new()
}
}
impl<S> Layer<S> for BrowserOnlyLayer {
type Service = UaGuard<S>;
fn layer(&self, inner: S) -> Self::Service {
UaGuard {
inner,
rule: Rule::BrowserOnly,
message: self.message.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct UaGuard<S> {
inner: S,
rule: Rule,
message: Arc<str>,
}
impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for UaGuard<S>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>>,
S::Future: Send + 'static,
S::Error: Send + 'static,
ResBody: Send + 'static,
{
type Response = Response<Either<ResBody, Full<Bytes>>>;
type Error = S::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
if self.rule.rejects(req.headers()) {
let resp = forbidden(&self.message);
return Box::pin(async move { Ok(resp) });
}
let fut = self.inner.call(req);
Box::pin(async move { Ok(fut.await?.map(Either::Left)) })
}
}
fn forbidden<B>(message: &str) -> Response<Either<B, Full<Bytes>>> {
let mut resp = Response::new(Either::Right(Full::new(Bytes::from(format!("{message}\n")))));
*resp.status_mut() = StatusCode::FORBIDDEN;
let h = resp.headers_mut();
h.insert(CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"));
h.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
resp
}
#[cfg(test)]
mod tests {
use std::convert::Infallible;
use http_body_util::BodyExt;
use tower::{ServiceBuilder, ServiceExt, service_fn};
use super::*;
async fn ok(_req: Request<()>) -> Result<Response<Full<Bytes>>, Infallible> {
Ok(Response::new(Full::new(Bytes::from_static(b"ok"))))
}
type Guarded = Response<Either<Full<Bytes>, Full<Bytes>>>;
async fn run(
svc: impl Service<Request<()>, Response = Guarded, Error = Infallible>,
ua: Option<&str>,
) -> (StatusCode, String) {
let mut req = Request::builder();
if let Some(ua) = ua {
req = req.header("user-agent", ua);
}
let resp = svc.oneshot(req.body(()).unwrap()).await.unwrap();
let status = resp.status();
let body = resp.into_body().collect().await.unwrap().to_bytes();
(status, String::from_utf8(body.to_vec()).unwrap())
}
#[tokio::test]
async fn block_bot() {
let svc = || {
ServiceBuilder::new()
.layer(BlockBotLayer::new(true))
.service(service_fn(ok))
};
assert_eq!(
run(svc(), Some("curl/8")).await,
(StatusCode::FORBIDDEN, "Bot access denied\n".into())
);
assert_eq!(run(svc(), None).await.0, StatusCode::FORBIDDEN);
assert_eq!(run(svc(), Some("Googlebot/2.1")).await, (StatusCode::OK, "ok".into()));
assert_eq!(run(svc(), Some("Mozilla/5.0 Chrome/130.0")).await.0, StatusCode::OK);
let strict = ServiceBuilder::new()
.layer(BlockBotLayer::new(false).message("nope"))
.service(service_fn(ok));
assert_eq!(
run(strict, Some("Googlebot/2.1")).await,
(StatusCode::FORBIDDEN, "nope\n".into())
);
}
#[tokio::test]
async fn browser_only() {
let svc = || {
ServiceBuilder::new()
.layer(BrowserOnlyLayer::new())
.service(service_fn(ok))
};
assert_eq!(run(svc(), Some("Mozilla/5.0 Firefox/120.0")).await.0, StatusCode::OK);
assert_eq!(
run(svc(), Some("SomeApp/1.0")).await,
(StatusCode::FORBIDDEN, "Browser access only\n".into())
);
assert_eq!(run(svc(), None).await.0, StatusCode::FORBIDDEN);
}
}