Handle custom forwarded IP header, but preserve native IP handling

This commit is contained in:
Brandon Thomas committed 2020-07-01 05:15:41 -04:00
1 parent 97fbd58bb7
commit 9730d31a60
2 files changed
+53 -17

No files matched your search

+26 -6
View File
@@ -52,12 +52,32 @@ pub async fn post_speak(request: HttpRequest,
.body("Request has empty text."));
}
// NB: Actually, we want the X-Forwarded-For IP address, since otherwise
// we get the load balancer.
let ip_address = request.connection_info()
.remote()
.unwrap_or("")
.to_string();
let ip_address = match request.headers().get(HeaderName::from_static("x-voder-proxy-for")) {
Some(ip_address) => {
// Unfortunately the upstream Rust proxy is replacing the `forwarded` and `x-forwarded-for`
// headers, so we populate this custom header as a workaround.
info!("Proxied IP address: {:?}", ip_address);
ip_address.to_str()
.unwrap_or("")
.to_string()
},
None => {
// If we're running without the upstream Rust proxy, we can grab 'x-forarded-for', which is
// populated by the Digital Ocean load balancer.
let ip_address_and_port = request.connection_info()
.remote()
.unwrap_or("")
.to_string();
let ip_address = ip_address_and_port.split(":")
.collect::<Vec<&str>>()
.get(0)
.copied()
.unwrap_or("")
.to_string();
info!("Forwarded IP address: {}", &ip_address);
ip_address
},
};
match request.headers().get(HeaderName::from_static("x-forwarded-for")) {
Some(header_value) => {
@@ -1,4 +1,4 @@
use actix_web::http::{StatusCode, header};
use actix_web::http::{StatusCode, header, HeaderName, HeaderValue};
use actix_web::web::{
Data,
Json,
@@ -72,16 +72,32 @@ pub async fn post_speak_with_spectrogram(request: HttpRequest,
.body("Request has empty text.")));
}
for (k, v) in request.headers().iter() {
info!("Header: {:?} = {:?}", k, v);
}
// NB: Actually, we want the X-Forwarded-For IP address, since otherwise
// we get the load balancer.
let ip_address = request.connection_info()
.remote()
.unwrap_or("")
.to_string();
let ip_address = match request.headers().get(HeaderName::from_static("x-voder-proxy-for")) {
Some(ip_address) => {
// Unfortunately the upstream Rust proxy is replacing the `forwarded` and `x-forwarded-for`
// headers, so we populate this custom header as a workaround.
info!("Proxied IP address: {:?}", ip_address);
ip_address.to_str()
.unwrap_or("")
.to_string()
},
None => {
// If we're running without the upstream Rust proxy, we can grab 'x-forarded-for', which is
// populated by the Digital Ocean load balancer.
let ip_address_and_port = request.connection_info()
.remote()
.unwrap_or("")
.to_string();
let ip_address = ip_address_and_port.split(":")
.collect::<Vec<&str>>()
.get(0)
.copied()
.unwrap_or("")
.to_string();
info!("Forwarded IP address: {}", &ip_address);
ip_address
},
};
let sentence_record = NewSentence {
sentence: text.clone(),