Skip to content

Commit 5d837c7

Browse files
committed
fix: accept parameterized OTLP content types
1 parent 547c511 commit 5d837c7

1 file changed

Lines changed: 245 additions & 5 deletions

File tree

‎src/handlers/http/modal/utils/ingest_utils.rs‎

Lines changed: 245 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
*/
1818

1919
use actix_web::http::header::USER_AGENT;
20+
use actix_web::mime::Mime;
2021
use actix_web::{HttpRequest, web};
2122
use chrono::Utc;
2223
use opentelemetry_proto::tonic::{
@@ -121,6 +122,33 @@ pub async fn process_otel_content(
121122
}
122123
}
123124

125+
/// Payload encodings accepted by the OTEL HTTP endpoints.
126+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127+
enum OtelContentType {
128+
Json,
129+
Protobuf,
130+
}
131+
132+
/// Classifies a raw `Content-Type` header value by its media-type essence
133+
/// (`type/subtype`) only. Everything from the first `;` onwards is ignored,
134+
/// including malformed parameter text, so `application/json; charset=utf-8`
135+
/// is treated as JSON. Only HTTP optional whitespace (SP/HTAB) around the
136+
/// essence is trimmed; type and subtype are compared case-insensitively.
137+
/// Structured-syntax suffixes such as `application/otlp+json` are not aliases.
138+
fn classify_otel_content_type(content_type: &str) -> Option<OtelContentType> {
139+
let essence = content_type
140+
.split(';')
141+
.next()
142+
.unwrap_or_default()
143+
.trim_matches([' ', '\t']);
144+
let mime: Mime = essence.parse().ok()?;
145+
match mime.essence_str() {
146+
CONTENT_TYPE_JSON => Some(OtelContentType::Json),
147+
CONTENT_TYPE_PROTOBUF => Some(OtelContentType::Protobuf),
148+
_ => None,
149+
}
150+
}
151+
124152
#[allow(clippy::too_many_arguments)]
125153
fn handle_otel_ingestion(
126154
body: web::Bytes,
@@ -132,8 +160,8 @@ fn handle_otel_ingestion(
132160
tenant_id: Option<String>,
133161
) -> Result<(), PostError> {
134162
match content_type {
135-
Some(content_type) => {
136-
if content_type == CONTENT_TYPE_JSON {
163+
Some(content_type) => match classify_otel_content_type(&content_type) {
164+
Some(OtelContentType::Json) => {
137165
let json: serde_json::Value = match serde_json::from_slice(&body) {
138166
Ok(v) => v,
139167
Err(e) => {
@@ -155,22 +183,24 @@ fn handle_otel_ingestion(
155183
error!("Ingestion failed for stream {stream_name}: {e}");
156184
return Err(e);
157185
}
158-
} else if content_type == CONTENT_TYPE_PROTOBUF {
186+
}
187+
Some(OtelContentType::Protobuf) => {
159188
error!(
160189
"Ingestion failed for stream {stream_name}: Protobuf ingestion is not supported in Parseable OSS"
161190
);
162191
return Err(PostError::Invalid(anyhow::anyhow!(
163192
"Ingestion failed for stream {stream_name}: Protobuf ingestion is not supported in Parseable OSS"
164193
)));
165-
} else {
194+
}
195+
None => {
166196
error!(
167197
"Ingestion failed for stream {stream_name}: Unsupported Content-Type: {content_type}. Expected application/json or application/x-protobuf"
168198
);
169199
return Err(PostError::Invalid(anyhow::anyhow!(
170200
"Ingestion failed for stream {stream_name}: Unsupported Content-Type: {content_type}. Expected application/json or application/x-protobuf"
171201
)));
172202
}
173-
}
203+
},
174204
None => {
175205
error!(
176206
"Ingestion failed for stream {stream_name}: Missing Content-Type header. Expected application/json or application/x-protobuf"
@@ -628,6 +658,216 @@ mod tests {
628658
assert_eq!(custom_fields.get(SOURCE_IP_KEY).unwrap(), "unknown");
629659
}
630660

661+
#[test]
662+
fn test_classify_otel_content_type_by_essence_only() {
663+
use OtelContentType::{Json, Protobuf};
664+
665+
let cases: &[(&str, Option<OtelContentType>)] = &[
666+
// bare media types
667+
("application/json", Some(Json)),
668+
("application/x-protobuf", Some(Protobuf)),
669+
// charset parameter, plain and quoted
670+
("application/json; charset=utf-8", Some(Json)),
671+
("application/json;charset=utf-8", Some(Json)),
672+
("application/json; charset=\"utf-8\"", Some(Json)),
673+
// unknown and multiple parameters
674+
("application/json; foo=bar", Some(Json)),
675+
("application/json; charset=utf-8; foo=bar", Some(Json)),
676+
// type/subtype are case-insensitive
677+
("APPLICATION/JSON", Some(Json)),
678+
("Application/Json; Charset=UTF-8", Some(Json)),
679+
// outer SP/HTAB around the whole value
680+
(" application/json ", Some(Json)),
681+
("\tapplication/json\t", Some(Json)),
682+
// SP/HTAB around the parameter separator
683+
("application/json ; charset=utf-8", Some(Json)),
684+
("application/json\t;\tcharset=utf-8", Some(Json)),
685+
(" \tapplication/json \t; charset=utf-8", Some(Json)),
686+
// malformed parameter text is ignored (essence-only validation)
687+
("application/json;", Some(Json)),
688+
("application/json;;", Some(Json)),
689+
("application/json; charset", Some(Json)),
690+
("application/json; charset=", Some(Json)),
691+
("application/json; charset=\"utf-8", Some(Json)),
692+
("application/json; =utf-8", Some(Json)),
693+
("application/json; a b c", Some(Json)),
694+
// parameterised and case-varied protobuf still classifies as protobuf
695+
("application/x-protobuf; charset=utf-8", Some(Protobuf)),
696+
("Application/X-Protobuf", Some(Protobuf)),
697+
("APPLICATION/X-PROTOBUF ; proto=foo", Some(Protobuf)),
698+
// whitespace inside the essence is rejected
699+
("application /json", None),
700+
("application/ json", None),
701+
("application\t/json", None),
702+
("application/js on", None),
703+
// malformed essences
704+
("", None),
705+
(" ", None),
706+
(";charset=utf-8", None),
707+
("application", None),
708+
("application/", None),
709+
("/json", None),
710+
("application/json/extra", None),
711+
("\"application/json\"", None),
712+
// unsupported media types and suffix aliases
713+
("*/*", None),
714+
("text/plain", None),
715+
("application/xml", None),
716+
("application/protobuf", None),
717+
("application/jsonl", None),
718+
("application/otlp+json", None),
719+
("application/vnd.api+json", None),
720+
];
721+
722+
for (input, expected) in cases {
723+
assert_eq!(
724+
classify_otel_content_type(input),
725+
*expected,
726+
"classification of {input:?}"
727+
);
728+
}
729+
}
730+
731+
const OTEL_TEST_STREAM: &str = "otel-content-type-test";
732+
const OTEL_SIGNALS: [(TelemetryType, LogSource); 3] = [
733+
(TelemetryType::Logs, LogSource::OtelLogs),
734+
(TelemetryType::Metrics, LogSource::OtelMetrics),
735+
(TelemetryType::Traces, LogSource::OtelTraces),
736+
];
737+
738+
// Malformed JSON body: an accepted JSON content type fails in serde
739+
// before any PARSEABLE/storage access, so no global state is needed.
740+
async fn run_otel_content(
741+
content_type: Option<actix_web::http::header::HeaderValue>,
742+
telemetry_type: TelemetryType,
743+
log_source: &LogSource,
744+
) -> PostError {
745+
let mut req = TestRequest::default();
746+
if let Some(value) = content_type {
747+
req = req.insert_header((actix_web::http::header::CONTENT_TYPE, value));
748+
}
749+
let req = req.to_http_request();
750+
process_otel_content(
751+
&req,
752+
web::Bytes::from_static(b"{not valid json"),
753+
OTEL_TEST_STREAM,
754+
log_source,
755+
telemetry_type,
756+
)
757+
.await
758+
.expect_err("malformed body or rejected content type must fail")
759+
}
760+
761+
async fn assert_bad_request_body(err: &PostError, expected_body: &str) {
762+
use actix_web::ResponseError;
763+
764+
assert_eq!(err.status_code(), actix_web::http::StatusCode::BAD_REQUEST);
765+
let resp = err.error_response();
766+
assert_eq!(resp.status(), actix_web::http::StatusCode::BAD_REQUEST);
767+
assert_eq!(
768+
resp.headers()
769+
.get(actix_web::http::header::CONTENT_TYPE)
770+
.unwrap(),
771+
"text/plain; charset=utf-8"
772+
);
773+
let body = actix_web::body::to_bytes(resp.into_body()).await.unwrap();
774+
assert_eq!(std::str::from_utf8(&body).unwrap(), expected_body);
775+
}
776+
777+
fn header(value: &'static str) -> Option<actix_web::http::header::HeaderValue> {
778+
Some(actix_web::http::header::HeaderValue::from_static(value))
779+
}
780+
781+
#[tokio::test]
782+
async fn test_process_otel_content_accepts_parameterised_json() {
783+
let accepted = [
784+
"application/json",
785+
"application/json; charset=utf-8",
786+
"application/json; charset=\"utf-8\"",
787+
"Application/JSON ; foo=bar; charset=utf-8",
788+
"\tapplication/json\t;\tcharset=utf-8",
789+
"application/json; charset=\"unterminated",
790+
];
791+
for (telemetry_type, log_source) in OTEL_SIGNALS {
792+
for value in accepted {
793+
let err = run_otel_content(header(value), telemetry_type, &log_source).await;
794+
assert!(
795+
matches!(err, PostError::SerdeError(_)),
796+
"{log_source} with {value:?} should reach JSON decoding, got {err:?}"
797+
);
798+
let expected = err.to_string();
799+
assert!(expected.starts_with("Could not deserialize into JSON object, "));
800+
assert_bad_request_body(&err, &expected).await;
801+
}
802+
}
803+
}
804+
805+
#[tokio::test]
806+
async fn test_process_otel_content_missing_or_non_text_content_type() {
807+
let non_text =
808+
actix_web::http::header::HeaderValue::from_bytes(b"application/json\xff").unwrap();
809+
for (telemetry_type, log_source) in OTEL_SIGNALS {
810+
for content_type in [None, Some(non_text.clone())] {
811+
let err = run_otel_content(content_type, telemetry_type, &log_source).await;
812+
assert!(matches!(err, PostError::Invalid(_)), "{err:?}");
813+
assert_bad_request_body(
814+
&err,
815+
&format!(
816+
"Invalid Request: Ingestion failed for stream {OTEL_TEST_STREAM}: Missing Content-Type header. Expected application/json or application/x-protobuf"
817+
),
818+
)
819+
.await;
820+
}
821+
}
822+
}
823+
824+
#[tokio::test]
825+
async fn test_process_otel_content_unsupported_reports_original_value() {
826+
let unsupported = [
827+
"text/plain; charset=utf-8",
828+
"application/otlp+json",
829+
"application /json; charset=utf-8",
830+
" Application/XML ; q=1",
831+
"",
832+
];
833+
for (telemetry_type, log_source) in OTEL_SIGNALS {
834+
for value in unsupported {
835+
let err = run_otel_content(header(value), telemetry_type, &log_source).await;
836+
assert!(matches!(err, PostError::Invalid(_)), "{err:?}");
837+
assert_bad_request_body(
838+
&err,
839+
&format!(
840+
"Invalid Request: Ingestion failed for stream {OTEL_TEST_STREAM}: Unsupported Content-Type: {value}. Expected application/json or application/x-protobuf"
841+
),
842+
)
843+
.await;
844+
}
845+
}
846+
}
847+
848+
#[tokio::test]
849+
async fn test_process_otel_content_protobuf_variants_still_unsupported() {
850+
let protobuf = [
851+
"application/x-protobuf",
852+
"application/x-protobuf; charset=utf-8",
853+
"Application/X-Protobuf",
854+
" APPLICATION/X-PROTOBUF\t;proto=foo",
855+
];
856+
for (telemetry_type, log_source) in OTEL_SIGNALS {
857+
for value in protobuf {
858+
let err = run_otel_content(header(value), telemetry_type, &log_source).await;
859+
assert!(matches!(err, PostError::Invalid(_)), "{err:?}");
860+
assert_bad_request_body(
861+
&err,
862+
&format!(
863+
"Invalid Request: Ingestion failed for stream {OTEL_TEST_STREAM}: Protobuf ingestion is not supported in Parseable OSS"
864+
),
865+
)
866+
.await;
867+
}
868+
}
869+
}
870+
631871
#[test]
632872
fn test_get_custom_fields_from_header_with_peer_address() {
633873
let req = TestRequest::default()

0 commit comments

Comments
 (0)