Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(http source): Add custom response header configuration #20811

Open
wants to merge 21 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
The `http_server` source now allows configuring custom headers to be added to responses via the `custom_response_headers` option.

authors: chriscancompute
114 changes: 113 additions & 1 deletion src/sources/http_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use http::StatusCode;
use http_serde;
use tokio_util::codec::Decoder as _;
use vrl::value::{kind::Collection, Kind};
use warp::http::{HeaderMap, HeaderValue};
use warp::http::{HeaderMap, HeaderName, HeaderValue};

use vector_lib::codecs::{
decoding::{DeserializerConfig, FramingConfig},
Expand Down Expand Up @@ -99,6 +99,14 @@ pub struct SimpleHttpConfig {
#[configurable(metadata(docs::examples = "*"))]
headers: Vec<String>,

/// Custom response headers to be added to the HTTP response
#[serde(default)]
#[configurable(metadata(docs::examples = "example_custom_response_headers()"))]
#[configurable(metadata(
docs::additional_props_description = "A custom response header key-values pair"
))]
custom_response_headers: HashMap<String, Vec<String>>,

/// A list of URL query parameters to include in the log event.
///
/// These override any values included in the body with conflicting names.
Expand Down Expand Up @@ -170,6 +178,13 @@ pub struct SimpleHttpConfig {
keepalive: KeepaliveConfig,
}

fn example_custom_response_headers() -> HashMap<String, Vec<String>> {
HashMap::<String, Vec<String>>::from_iter([(
"Access-Control-Allow-Origin".to_string(),
vec!["my-cool-server".to_string(), "my-other-server".to_string()],
)])
}

impl SimpleHttpConfig {
/// Builds the `schema::Definition` for this source using the provided `LogNamespace`.
fn schema_definition(&self, log_namespace: LogNamespace) -> Definition {
Expand Down Expand Up @@ -265,6 +280,7 @@ impl Default for SimpleHttpConfig {
address: "0.0.0.0:8080".parse().unwrap(),
encoding: None,
headers: Vec::new(),
custom_response_headers: HashMap::new(),
query_parameters: Vec::new(),
tls: None,
auth: None,
Expand Down Expand Up @@ -355,6 +371,7 @@ impl SourceConfig for SimpleHttpConfig {

let source = SimpleHttpSource {
headers: build_param_matcher(&remove_duplicates(self.headers.clone(), "headers"))?,
custom_response_headers: self.custom_response_headers.clone(),
query_parameters: remove_duplicates(self.query_parameters.clone(), "query_parameters"),
path_key: self.path_key.clone(),
host_key: self.host_key.clone(),
Expand Down Expand Up @@ -403,6 +420,7 @@ impl SourceConfig for SimpleHttpConfig {
#[derive(Clone)]
struct SimpleHttpSource {
headers: Vec<HttpConfigParamKind>,
custom_response_headers: HashMap<String, Vec<String>>,
query_parameters: Vec<String>,
path_key: OptionalValuePath,
host_key: OptionalValuePath,
Expand Down Expand Up @@ -544,10 +562,31 @@ impl HttpSource for SimpleHttpSource {
fn enable_source_ip(&self) -> bool {
self.host_key.path.is_some()
}

/// Enriches the warp::reply::Reply with custom headers
///
/// This method adds the custom headers specified in the configuration
/// to the HTTP response.
fn enrich_reply<T: warp::Reply + 'static>(&self, reply: T) -> Box<dyn warp::Reply> {
let mut response = reply.into_response();
let header_map = response.headers_mut();

for (key, values) in &self.custom_response_headers {
let header_name: HeaderName = key.parse().unwrap();
Copy link
Member

@jszwedko jszwedko Aug 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we do this parsing and validation earlier? That is: parse the configured headers into a HeaderMap during source start time? I think that would have the advantage of:

  • Only parsing the headers once
  • Being able to return an error at start time if a name is invalid, rather than panic'ing at runtime

if let Some((first, rest)) = values.split_first() {
header_map.insert(header_name.clone(), first.parse().unwrap());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can just use append rather than needing to split and insert the first one:

Inserts a key-value pair into the map.

If the map did not previously have this key present, then false is returned.

If the map did have this key present, the new value is pushed to the end of the list of values currently associated with the key. The key is not updated, though; this matters for types that can be == without being identical.

https://docs.rs/http/0.2.12/http/header/struct.HeaderMap.html#method.append

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From the docs you point, I understand that if you append without inserting first, it would fail

Thats why I suggested to insert the first and append the rest

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it fails. It just returns false if the key didn't already exist and true if it did but either way the value is inserted.

See the implementation: https://docs.rs/http/0.2.12/src/http/header/map.rs.html#1415-1449

Copy link
Contributor

@jorgehermo9 jorgehermo9 Aug 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, you're right, didn't see the implementation. I think I understood wrong the documentation. I see that Inserts a key-value pair into the map is not fallible and will be done always. Thanks!!!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For sure :) I can see why you would have been confused.

for value in rest {
header_map.append(header_name.clone(), value.parse().unwrap());
}
}
}
Box::new(response)
}
}

#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::str::FromStr;
use std::{io::Write, net::SocketAddr};

Expand Down Expand Up @@ -591,6 +630,7 @@ mod tests {
#[allow(clippy::too_many_arguments)]
async fn source<'a>(
headers: Vec<String>,
custom_response_headers: HashMap<String, Vec<String>>,
query_parameters: Vec<String>,
path_key: &'a str,
host_key: &'a str,
Expand Down Expand Up @@ -619,6 +659,7 @@ mod tests {
SimpleHttpConfig {
address,
headers,
custom_response_headers,
encoding: None,
query_parameters,
response_code,
Expand Down Expand Up @@ -730,6 +771,7 @@ mod tests {

let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -776,6 +818,7 @@ mod tests {
let mut events = assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async move {
let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -815,6 +858,7 @@ mod tests {
let mut events = assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async move {
let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -848,6 +892,7 @@ mod tests {
let mut events = assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async {
let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -886,6 +931,7 @@ mod tests {
let mut events = assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async {
let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -931,6 +977,7 @@ mod tests {
let mut events = assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async {
let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -982,6 +1029,7 @@ mod tests {
let mut events = assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async {
let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -1068,6 +1116,7 @@ mod tests {
"X-*".to_string(),
"AbsentHeader".to_string(),
],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -1112,6 +1161,7 @@ mod tests {

let (rx, addr) = source(
vec!["*".to_string()],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -1145,11 +1195,65 @@ mod tests {
}
}

#[tokio::test]
async fn http_custom_response_headers() {
async fn send(address: SocketAddr, body: &str) -> reqwest::Response {
reqwest::Client::new()
.post(&format!("http://{}/", address))
.body(body.to_owned())
.send()
.await
.unwrap()
}

assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async {
let mut custom_headers: HashMap<String, Vec<String>> = HashMap::new();
custom_headers.insert(
"Access-Control-Allow-Origin".to_string(),
vec!["example.com".to_string(), "example2.com".to_string()],
);

let (rx, addr) = source(
vec!["*".to_string()],
custom_headers,
vec![],
"http_path",
"remote_ip",
"/",
"POST",
StatusCode::OK,
true,
EventStatus::Delivered,
true,
None,
Some(JsonDeserializerConfig::default().into()),
)
.await;

spawn_collect_n(
async move {
let response = send(addr, "{\"key1\":\"value1\"}").await;
let response_headers = response.headers();
let view = response_headers.get_all("Access-Control-Allow-Origin");
let mut iter = view.iter();
assert_eq!(&"example.com", iter.next().unwrap());
assert_eq!(&"example2.com", iter.next().unwrap());
assert!(iter.next().is_none());
},
rx,
1,
)
.await
})
.await;
}

#[tokio::test]
async fn http_query() {
let mut events = assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async {
let (rx, addr) = source(
vec![],
HashMap::new(),
vec![
"source".to_string(),
"region".to_string(),
Expand Down Expand Up @@ -1206,6 +1310,7 @@ mod tests {

let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -1237,6 +1342,7 @@ mod tests {
let mut events = assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async {
let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"vector_http_path",
"vector_remote_ip",
Expand Down Expand Up @@ -1278,6 +1384,7 @@ mod tests {
let mut events = assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async {
let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"vector_http_path",
"vector_remote_ip",
Expand Down Expand Up @@ -1339,6 +1446,7 @@ mod tests {
components::init_test();
let (_rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"vector_http_path",
"vector_remote_ip",
Expand All @@ -1364,6 +1472,7 @@ mod tests {
assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async move {
let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -1398,6 +1507,7 @@ mod tests {
assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async {
let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -1429,6 +1539,7 @@ mod tests {
let events = assert_source_compliance(&HTTP_PUSH_SOURCE_TAGS, async {
let (rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down Expand Up @@ -1462,6 +1573,7 @@ mod tests {
components::init_test();
let (_rx, addr) = source(
vec![],
HashMap::new(),
vec![],
"http_path",
"remote_ip",
Expand Down
39 changes: 28 additions & 11 deletions src/sources/util/http/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ pub trait HttpSource: Clone + Send + Sync + 'static {
decode(encoding_header, body)
}

// This function can be defined to enrich `warp::Reply`s.
fn enrich_reply<T: warp::Reply + 'static>(&self, reply: T) -> Box<dyn warp::Reply> {
Box::new(reply)
}

#[allow(clippy::too_many_arguments)]
fn run(
self,
Expand All @@ -90,6 +95,7 @@ pub trait HttpSource: Clone + Send + Sync + 'static {
let path = path.to_owned();
let acknowledgements = cx.do_acknowledgements(acknowledgements);
let enable_source_ip = self.enable_source_ip();
let self_clone = self.clone();

Ok(Box::pin(async move {
let mut filter: BoxedFilter<()> = match method {
Expand Down Expand Up @@ -170,21 +176,32 @@ pub trait HttpSource: Clone + Send + Sync + 'static {
events
});

handle_request(events, acknowledgements, response_code, cx.out.clone())
handle_request(events, acknowledgements, response_code, cx.out.clone()).map(
{
let self_clone = self.clone();
move |result| {
result.map(move |reply| self_clone.enrich_reply(reply))
}
},
)
},
);

let ping = warp::get().and(warp::path("ping")).map(|| "pong");
let routes = svc.or(ping).recover(|r: Rejection| async move {
if let Some(e_msg) = r.find::<ErrorMessage>() {
let json = warp::reply::json(e_msg);
Ok(warp::reply::with_status(json, e_msg.status_code()))
} else {
//other internal error - will return 500 internal server error
emit!(HttpInternalError {
message: &format!("Internal error: {:?}", r)
});
Err(r)
let routes = svc.or(ping).recover(move |r: Rejection| {
let self_clone = self_clone.clone();
async move {
if let Some(e_msg) = r.find::<ErrorMessage>() {
let json = warp::reply::json(e_msg);
Ok(self_clone
.enrich_reply(warp::reply::with_status(json, e_msg.status_code())))
} else {
//other internal error - will return 500 internal server error
emit!(HttpInternalError {
message: &format!("Internal error: {:?}", r)
});
Err(r)
}
}
});

Expand Down
Loading
Loading