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

#519 in Network programming

Download history 9/week @ 2023-12-31 7/week @ 2024-01-28 46/week @ 2024-02-25 141/week @ 2024-03-10 12/week @ 2024-03-17 11/week @ 2024-03-31 121/week @ 2024-04-07 2/week @ 2024-04-14

136 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
~51K SLoC