7 releases (breaking)

0.6.1 Mar 14, 2024
0.6.0 Feb 4, 2024
0.5.0 Jan 31, 2024
0.4.0 Jan 2, 2024
0.1.0 Aug 7, 2023

#4 in #allowed

Download history 40/week @ 2024-03-15 2/week @ 2024-03-22 11/week @ 2024-03-29 3/week @ 2024-04-05 120/week @ 2024-04-12

287 downloads per month

MIT license

27KB
510 lines

TOWER ALLOWED HOSTS

Project status & info:

License Crates Version Docs
License: MIT Crate Docs

Tower service which limits request from only hosts

Add as dependencies

Edit Cargo.toml file to add tower_allowed_hosts as dependencies

[dependencies]
tower_allowed_hosts = "0.6.1"

Usage

To use non regex based hosts you can use

let tower_layer = tower_allowed_hosts::AllowedHostLayer::default().extend(&["127.0.0.1".to_string()]);

If you need to use wildcard based host matching you need to enable wildcard feature for crate than you can use

let tower_layer = tower_allowed_hosts::AllowedHostLayer::default().extend_wildcard(&["127.0.0.*".to_string()]);

If you need to use regex based host matching you need to enable regex feature for crate than you can use

let tower_layer = tower_allowed_hosts::AllowedHostLayer::default().extend_regex(&[regex::Regex::new("^127.0.0.1$")?]);

After creation of layer you can use layer in library which supports tower as component

For example to use tower allowed hosts in axum you also needs to add HandleErrorLayer so error gets handled properly

use axum::{
    error_handling::HandleErrorLayer,
    http::StatusCode,
    Router
};
use tower::ServiceBuilder;
use tower_allowed_hosts::AllowedHostLayer;

fn router() -> Router {
    let handle_error_layer = HandleErrorLayer::new(handle_box_error);

    let allowed_hosts_layer = AllowedHostLayer::default()
        .extend_wildcard(&["127.0.0.*".to_string()]);

     let layer = ServiceBuilder::new()
        .layer(handle_error_layer)
        .layer(allowed_hosts_layer);

    Router::new().layer(layer)
}

async fn handle_box_error(err: tower::BoxError) -> (StatusCode, String) {
    if err.is::<tower_allowed_hosts::error::Error>() {
        return (StatusCode::BAD_REQUEST, err.to_string());
    }
    return (StatusCode::INTERNAL_SERVER_ERROR, "".to_string())
}

There is also extension added after successfully parsing allowed host and allowing host which can be access using tower_allowed_hosts::Host struct Extension

Dependencies

~1.7–2.9MB
~52K SLoC