rust-web-utils 0.1.0

Lightweight web utilities: client IP & trusted proxies, bot/browser detection, unified JSON response, business timezone, auth cookies + CSRF, cron guards, Next.js static export hosting
Documentation
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),
        }
    }
}

/// 拦截机器人的 tower 中间件: 命中时返回 403 纯文本, 默认文案 `Bot access denied`。
///
/// ```
/// use rust_web_utils::uautil::BlockBotLayer;
///
/// // 前台页面放行搜索引擎; 后台 / 内部接口传 false
/// let layer = BlockBotLayer::new(true).message("Bot access denied");
/// # let _ = layer;
/// ```
#[derive(Debug, Clone)]
pub struct BlockBotLayer {
    allow_legitimate: bool,
    message: Arc<str>,
}

impl BlockBotLayer {
    /// `allow_legitimate` 为 `true` 时放行合法搜索引擎爬虫
    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(),
        }
    }
}

/// 仅允许浏览器访问的 tower 中间件: 非浏览器返回 403 纯文本, 默认文案 `Browser access only`
#[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(),
        }
    }
}

/// [`BlockBotLayer`] / [`BrowserOnlyLayer`] 包装后的服务; 响应体为
/// `Either<内层响应体, Full<Bytes>>`, 可直接用于 Axum `Router::layer`
#[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)) })
    }
}

/// 与 Go `http.Error` 一致的 403 纯文本响应
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);
    }
}