Skip to content

How to get RightmostXForwardedFor optional #9

@josecelano

Description

@josecelano

I'm trying to get the client IP from the RightmostXForwardedFor header. The problem is the app has two configurations. If the app runs on reverse proxy, I want to use the RightmostXForwardedFor otherwise, I want to use the ConnectInfo (which I suppose is the direct client IP).

Routes configuration:

let secure_client_ip_source = if tracker.config.on_reverse_proxy {
    SecureClientIpSource::RightmostXForwardedFor
} else {
    SecureClientIpSource::ConnectInfo
};

Router::new()
    .route("/announce", get(handle).with_state(tracker.clone()))
    .layer(secure_client_ip_source.into_extension())

The handler:

pub async fn handle(
    State(tracker): State<Arc<Tracker>>,
    ExtractAnnounceRequest(announce_request): ExtractAnnounceRequest,
    secure_ip: SecureClientIp,
) -> Response {
// ...
}

But I want something like this:

pub async fn handle(
    State(tracker): State<Arc<Tracker>>,
    ExtractAnnounceRequest(announce_request): ExtractAnnounceRequest,
    maybe_secure_client_ip: Result<SecureClientIp, StringRejection>,
) -> Response {
// ...
}

But that gives me this error:

the trait bound `fn(axum::extract::State<Arc<Tracker>>, ExtractAnnounceRequest, Result<SecureClientIp, StringRejection>) -> impl futures::Future<Output = axum::http::Response<http_body::combinators::box_body::UnsyncBoxBody<axum::body::Bytes, axum::Error>>> {handle}: Handler<_, _, _>` is not satisfied

The reason I want to make it optional is that I want to send a custom error in the handler if the proxy does not provide the X-Forwarded-For header.

Alternatively, I could:

  • Try to catch the extractor error, if that's possible, in Axum.
  • Build a wrapper for your extractor.
  • Just build my extractor and stop using this crate :-(.

For more context, this is the PR I'm working on.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions