Skip to main content

saluki_components/common/otlp/
mod.rs

1//! Common OTLP server infrastructure.
2//!
3//! Provides shared server setup code for both OTLP receiver (proxy mode) and OTLP source (translation mode).
4
5pub mod attributes;
6pub mod client_spans;
7pub mod origin;
8pub mod proxy;
9pub mod receiver;
10pub mod semantics;
11pub mod source;
12pub mod traces;
13pub mod util;
14pub mod value;
15
16#[cfg(test)]
17mod test_util;
18
19use std::path::PathBuf;
20use std::str::FromStr;
21use std::sync::Arc;
22
23use ::metrics::Counter;
24use async_trait::async_trait;
25use axum::body::Bytes;
26use axum::extract::{DefaultBodyLimit, State};
27use axum::http::{HeaderName, Method, StatusCode};
28use axum::routing::post;
29use axum::Router;
30use otlp_protos::opentelemetry::proto::collector::logs::v1::logs_service_server::{
31    self, LogsService, LogsServiceServer,
32};
33use otlp_protos::opentelemetry::proto::collector::logs::v1::{ExportLogsServiceRequest, ExportLogsServiceResponse};
34use otlp_protos::opentelemetry::proto::collector::metrics::v1::metrics_service_server::{
35    self, MetricsService, MetricsServiceServer,
36};
37use otlp_protos::opentelemetry::proto::collector::metrics::v1::{
38    ExportMetricsServiceRequest, ExportMetricsServiceResponse,
39};
40use otlp_protos::opentelemetry::proto::collector::trace::v1::trace_service_server::{
41    self, TraceService, TraceServiceServer,
42};
43use otlp_protos::opentelemetry::proto::collector::trace::v1::{ExportTraceServiceRequest, ExportTraceServiceResponse};
44use prost::Message;
45use saluki_core::accounting::MemoryLimiter;
46use saluki_core::components::ComponentContext;
47use saluki_core::observability::ComponentMetricsExt;
48use saluki_core::runtime;
49use saluki_error::{generic_error, GenericError};
50use saluki_io::net::server::grpc::unmatched_route;
51use saluki_io::net::server::http::{Http2Config, HttpServer};
52use saluki_io::net::ListenAddress;
53use saluki_metrics::MetricsBuilder;
54use saluki_tls::ServerTLSConfigBuilder;
55use stringtheory::MetaString;
56use tokio::runtime::Handle;
57use tonic::{Request as TonicRequest, Response, Status};
58use tower_http::cors::{AllowOrigin, Any, CorsLayer};
59use tracing::error;
60
61use self::client_spans::ClientSpanCounters;
62use self::proxy::OtlpProxy;
63
64const IMPLICIT_HEADERS: [HeaderName; 4] = [
65    HeaderName::from_static("accept"),
66    HeaderName::from_static("accept-language"),
67    HeaderName::from_static("content-type"),
68    HeaderName::from_static("content-language"),
69];
70
71#[derive(Clone)]
72pub struct Metrics {
73    metrics_received: Counter,
74    logs_received: Counter,
75    logs_dropped_render_failure: Counter,
76    bytes_received: Counter,
77    spans_received: ClientSpanCounters,
78    traces_dropped_span_id_zero: Counter,
79    spans_dropped_span_id_zero: Counter,
80    metrics_errors_decode: Counter,
81    metrics_errors_channel: Counter,
82    metrics_errors_dispatch: Counter,
83    metrics_errors_flush: Counter,
84    spans_dropped_foreign_trace: Counter,
85    spans_malformed_peer_service_truncate: Counter,
86    spans_malformed_peer_service_invalid: Counter,
87    spans_malformed_base_service_truncate: Counter,
88    spans_malformed_base_service_invalid: Counter,
89}
90
91impl Metrics {
92    pub fn metrics_received(&self) -> &Counter {
93        &self.metrics_received
94    }
95
96    pub fn logs_received(&self) -> &Counter {
97        &self.logs_received
98    }
99
100    /// Counter for logs dropped because their content couldn't be rendered.
101    pub fn logs_dropped_render_failure(&self) -> &Counter {
102        &self.logs_dropped_render_failure
103    }
104
105    /// Counters for spans received, resolved by the sending client's SDK language and version.
106    pub fn spans_received(&self) -> &ClientSpanCounters {
107        &self.spans_received
108    }
109
110    /// Counter for traces dropped because they contained a span with a span ID of zero.
111    pub fn traces_dropped_span_id_zero(&self) -> &Counter {
112        &self.traces_dropped_span_id_zero
113    }
114
115    /// Counter for individual spans dropped as part of a trace dropped for containing a span ID of
116    /// zero. Mirrors the Go trace-agent's separate `TracesDropped.SpanIDZero` and `SpansDropped`
117    /// counters, since `component_events_received_total{message_type:otlp_spans}` counts spans.
118    pub fn spans_dropped_span_id_zero(&self) -> &Counter {
119        &self.spans_dropped_span_id_zero
120    }
121
122    pub fn bytes_received(&self) -> &Counter {
123        &self.bytes_received
124    }
125
126    pub fn metrics_errors_decode(&self) -> &Counter {
127        &self.metrics_errors_decode
128    }
129
130    pub fn metrics_errors_channel(&self) -> &Counter {
131        &self.metrics_errors_channel
132    }
133
134    pub fn metrics_errors_dispatch(&self) -> &Counter {
135        &self.metrics_errors_dispatch
136    }
137
138    pub fn metrics_errors_flush(&self) -> &Counter {
139        &self.metrics_errors_flush
140    }
141
142    /// Spans dropped because their trace group mixed spans from different full trace IDs (two
143    /// traces sharing a low 64-bit half).
144    pub fn spans_dropped_foreign_trace(&self) -> &Counter {
145        &self.spans_dropped_foreign_trace
146    }
147
148    pub fn spans_malformed_peer_service_truncate(&self) -> &Counter {
149        &self.spans_malformed_peer_service_truncate
150    }
151
152    pub fn spans_malformed_peer_service_invalid(&self) -> &Counter {
153        &self.spans_malformed_peer_service_invalid
154    }
155
156    pub fn spans_malformed_base_service_truncate(&self) -> &Counter {
157        &self.spans_malformed_base_service_truncate
158    }
159
160    pub fn spans_malformed_base_service_invalid(&self) -> &Counter {
161        &self.spans_malformed_base_service_invalid
162    }
163
164    /// Test-only helper to construct a `Metrics` instance.
165    #[cfg(test)]
166    pub fn for_tests() -> Self {
167        Metrics {
168            metrics_received: Counter::noop(),
169            logs_received: Counter::noop(),
170            logs_dropped_render_failure: Counter::noop(),
171            bytes_received: Counter::noop(),
172            spans_received: ClientSpanCounters::new(MetricsBuilder::default()),
173            traces_dropped_span_id_zero: Counter::noop(),
174            spans_dropped_span_id_zero: Counter::noop(),
175            metrics_errors_decode: Counter::noop(),
176            metrics_errors_channel: Counter::noop(),
177            metrics_errors_dispatch: Counter::noop(),
178            metrics_errors_flush: Counter::noop(),
179            spans_dropped_foreign_trace: Counter::noop(),
180            spans_malformed_peer_service_truncate: Counter::noop(),
181            spans_malformed_peer_service_invalid: Counter::noop(),
182            spans_malformed_base_service_truncate: Counter::noop(),
183            spans_malformed_base_service_invalid: Counter::noop(),
184        }
185    }
186}
187
188/// Builds the metrics for the OTLP server.
189pub fn build_metrics(component_context: &ComponentContext) -> Metrics {
190    let builder = MetricsBuilder::from_component_context(component_context);
191
192    Metrics {
193        metrics_received: builder
194            .register_counter_with_tags("component_events_received_total", [("message_type", "otlp_metrics")]),
195        logs_received: builder
196            .register_counter_with_tags("component_events_received_total", [("message_type", "otlp_logs")]),
197        logs_dropped_render_failure: builder.register_counter_with_tags(
198            "component_events_dropped_total",
199            [
200                "intentional:false",
201                "drop_reason:render_failure",
202                "message_type:otlp_logs",
203            ],
204        ),
205        bytes_received: builder.register_counter_with_tags("component_bytes_received_total", [("source", "otlp")]),
206        spans_received: ClientSpanCounters::new(builder.clone()),
207        traces_dropped_span_id_zero: builder.register_counter_with_tags(
208            "component_events_dropped_total",
209            ["intentional:true", "drop_reason:span_id_zero"],
210        ),
211        spans_dropped_span_id_zero: builder.register_counter_with_tags(
212            "component_events_dropped_total",
213            [
214                "intentional:true",
215                "drop_reason:span_id_zero",
216                "message_type:otlp_spans",
217            ],
218        ),
219        metrics_errors_decode: builder.register_counter_with_tags("component_errors_total", [("reason", "decode")]),
220        metrics_errors_channel: builder.register_counter_with_tags("component_errors_total", [("reason", "channel")]),
221        metrics_errors_dispatch: builder.register_counter_with_tags("component_errors_total", [("reason", "dispatch")]),
222        metrics_errors_flush: builder.register_counter_with_tags("component_errors_total", [("reason", "flush")]),
223        spans_dropped_foreign_trace: builder.register_counter_with_tags(
224            "component_events_dropped_total",
225            [("message_type", "otlp_spans"), ("reason", "foreign_span")],
226        ),
227        spans_malformed_peer_service_truncate: builder.register_counter_with_tags(
228            "component_spans_malformed_total",
229            [("tag", "peer.service"), ("reason", "truncate")],
230        ),
231        spans_malformed_peer_service_invalid: builder.register_counter_with_tags(
232            "component_spans_malformed_total",
233            [("tag", "peer.service"), ("reason", "invalid")],
234        ),
235        spans_malformed_base_service_truncate: builder.register_counter_with_tags(
236            "component_spans_malformed_total",
237            [("tag", "_dd.base_service"), ("reason", "truncate")],
238        ),
239        spans_malformed_base_service_invalid: builder.register_counter_with_tags(
240            "component_spans_malformed_total",
241            [("tag", "_dd.base_service"), ("reason", "invalid")],
242        ),
243    }
244}
245
246/// Handler for OTLP data.
247#[async_trait]
248pub trait OtlpHandler: Send + Sync + 'static {
249    async fn handle_metrics(&self, body: Bytes) -> Result<(), GenericError>;
250    async fn handle_logs(&self, body: Bytes) -> Result<(), GenericError>;
251    async fn handle_traces(&self, body: Bytes) -> Result<(), GenericError>;
252}
253
254/// CORS settings for an OTLP HTTP server.
255#[derive(Clone, Debug, Default, PartialEq, Eq)]
256pub struct CorsConfiguration {
257    /// Origins allowed to make cross-origin requests.
258    pub allowed_origins: Vec<String>,
259    /// Request headers allowed in cross-origin requests.
260    pub allowed_headers: Vec<String>,
261    /// Response headers exposed to browser clients.
262    pub exposed_headers: Vec<String>,
263    /// Seconds browsers may cache a preflight response.
264    pub max_age: u64,
265}
266
267/// TLS configuration for an OTLP receiver, loaded from file paths on disk.
268///
269/// Both `cert_file` and `key_file` are required to enable TLS. When `ca_file` is set, the server requests client
270/// certificates and verifies them if presented, but does not require them (optional verification).
271#[derive(Clone, Debug)]
272pub struct OtlpTlsConfiguration {
273    cert_file: PathBuf,
274    key_file: PathBuf,
275    ca_file: Option<PathBuf>,
276}
277
278impl OtlpTlsConfiguration {
279    /// Creates a new TLS configuration with the given certificate and key file paths.
280    pub fn new(cert_file: PathBuf, key_file: PathBuf) -> Self {
281        Self {
282            cert_file,
283            key_file,
284            ca_file: None,
285        }
286    }
287
288    /// Sets the CA certificate file for optional client certificate verification.
289    pub fn with_ca_file(mut self, ca_file: PathBuf) -> Self {
290        self.ca_file = Some(ca_file);
291        self
292    }
293
294    /// Builds a `rustls::ServerConfig` from the configured file paths.
295    ///
296    /// # Errors
297    ///
298    /// If the certificate or key files cannot be read or parsed, or if the resulting configuration isn't FIPS
299    /// compliant, an error will be returned.
300    fn build(self) -> Result<rustls::ServerConfig, GenericError> {
301        let mut builder = ServerTLSConfigBuilder::new()
302            .with_cert_file(self.cert_file)
303            .with_key_file(self.key_file);
304
305        if let Some(ca_file) = self.ca_file {
306            builder = builder.with_ca_file(ca_file);
307        }
308
309        builder.build()
310    }
311}
312
313/// The default HTTP request body size limit (20 MiB) applied when `max_request_body_size` is `0`.
314const HTTP_DEFAULT_MAX_REQUEST_BODY_SIZE: usize = 20 * 1024 * 1024;
315
316/// Server identifier of the OTLP HTTP endpoint.
317const HTTP_SERVER_ID: &str = "otlp-http";
318
319/// Server identifier of the OTLP gRPC endpoint.
320const GRPC_SERVER_ID: &str = "otlp-grpc";
321
322/// An OTLP signal.
323#[derive(Clone, Copy, Debug, Eq, PartialEq)]
324pub(crate) enum Signal {
325    Metrics,
326    Logs,
327    Traces,
328}
329
330impl Signal {
331    /// Every signal.
332    pub(crate) const ALL: [Self; 3] = [Self::Metrics, Self::Logs, Self::Traces];
333
334    /// Returns the name of the signal.
335    pub(crate) const fn as_str(self) -> &'static str {
336        match self {
337            Self::Metrics => "metrics",
338            Self::Logs => "logs",
339            Self::Traces => "traces",
340        }
341    }
342
343    /// Returns the path of the signal's OTLP/HTTP endpoint.
344    pub(crate) const fn http_path(self) -> &'static str {
345        match self {
346            Self::Metrics => "/v1/metrics",
347            Self::Logs => "/v1/logs",
348            Self::Traces => "/v1/traces",
349        }
350    }
351
352    /// Returns the fully qualified name of the signal's gRPC service.
353    pub(crate) const fn grpc_service_name(self) -> &'static str {
354        match self {
355            Self::Metrics => metrics_service_server::SERVICE_NAME,
356            Self::Logs => logs_service_server::SERVICE_NAME,
357            Self::Traces => trace_service_server::SERVICE_NAME,
358        }
359    }
360}
361
362/// How the OTLP servers serve a signal.
363#[derive(Clone, Copy, Debug, Eq, PartialEq)]
364pub enum OtlpRoute {
365    /// The servers don't serve the signal: a gRPC call gets `UNIMPLEMENTED`, and an HTTP request gets 404.
366    Disabled,
367
368    /// The servers decode the signal's requests and pass them to the OTLP handler.
369    Internal,
370
371    /// The servers stream the signal's requests to an upstream OTLP receiver, and stream its responses back.
372    ///
373    /// The proxy doesn't decode or limit the requests: the upstream receiver enforces its own limits.
374    Proxied,
375}
376
377/// The route of each OTLP signal.
378#[derive(Clone, Copy, Debug, Eq, PartialEq)]
379pub struct OtlpRoutes {
380    /// Route of OTLP metrics.
381    pub metrics: OtlpRoute,
382
383    /// Route of OTLP logs.
384    pub logs: OtlpRoute,
385
386    /// Route of OTLP traces.
387    pub traces: OtlpRoute,
388}
389
390impl OtlpRoutes {
391    /// Every signal internal.
392    pub const ALL_INTERNAL: Self = Self {
393        metrics: OtlpRoute::Internal,
394        logs: OtlpRoute::Internal,
395        traces: OtlpRoute::Internal,
396    };
397
398    /// Every signal disabled.
399    pub const ALL_DISABLED: Self = Self {
400        metrics: OtlpRoute::Disabled,
401        logs: OtlpRoute::Disabled,
402        traces: OtlpRoute::Disabled,
403    };
404
405    const fn get(&self, signal: Signal) -> OtlpRoute {
406        match signal {
407            Signal::Metrics => self.metrics,
408            Signal::Logs => self.logs,
409            Signal::Traces => self.traces,
410        }
411    }
412
413    /// Returns `true` if any signal is proxied.
414    pub fn any_proxied(&self) -> bool {
415        Signal::ALL
416            .into_iter()
417            .any(|signal| self.get(signal) == OtlpRoute::Proxied)
418    }
419
420    /// Returns `true` if any signal is internal.
421    pub(crate) fn any_internal(&self) -> bool {
422        Signal::ALL
423            .into_iter()
424            .any(|signal| self.get(signal) == OtlpRoute::Internal)
425    }
426}
427
428/// OTLP server configuration.
429///
430/// Holds the raw inputs needed to construct and start the OTLP HTTP and gRPC servers. Call [`build`][Self::build] to
431/// validate the configuration and spawn the servers.
432///
433/// A server with no endpoint doesn't start.
434pub struct OtlpServerConfiguration {
435    http_endpoint: Option<ListenAddress>,
436    grpc_endpoint: Option<ListenAddress>,
437    grpc_max_recv_msg_size_bytes: usize,
438    grpc_http2_config: Http2Config,
439    http_max_request_body_size: u64,
440    cors: CorsConfiguration,
441    http_tls: Option<OtlpTlsConfiguration>,
442    grpc_tls: Option<OtlpTlsConfiguration>,
443    http_server_id: MetaString,
444    grpc_server_id: MetaString,
445    routes: OtlpRoutes,
446    proxy: Option<OtlpProxy>,
447}
448
449impl OtlpServerConfiguration {
450    /// Creates a new OTLP server configuration.
451    pub fn new(
452        http_endpoint: Option<ListenAddress>, grpc_endpoint: Option<ListenAddress>, grpc_max_recv_msg_size_bytes: usize,
453    ) -> Self {
454        Self {
455            http_endpoint,
456            grpc_endpoint,
457            grpc_max_recv_msg_size_bytes,
458            grpc_http2_config: Http2Config::grpc_defaults(),
459            http_max_request_body_size: 0,
460            cors: CorsConfiguration::default(),
461            http_tls: None,
462            grpc_tls: None,
463            http_server_id: MetaString::from_static(HTTP_SERVER_ID),
464            grpc_server_id: MetaString::from_static(GRPC_SERVER_ID),
465            routes: OtlpRoutes::ALL_INTERNAL,
466            proxy: None,
467        }
468    }
469
470    /// Sets the route of each signal.
471    ///
472    /// Defaults to [`OtlpRoutes::ALL_INTERNAL`]. A proxied signal also needs a proxy: see
473    /// [`with_proxy`][Self::with_proxy].
474    pub(crate) fn with_routes(mut self, routes: OtlpRoutes) -> Self {
475        self.routes = routes;
476        self
477    }
478
479    /// Sets the proxy that serves the proxied signals.
480    pub(crate) fn with_proxy(mut self, proxy: OtlpProxy) -> Self {
481        self.proxy = Some(proxy);
482        self
483    }
484
485    /// Sets the HTTP/2 settings used by the gRPC endpoint.
486    pub fn with_grpc_http2_config(mut self, config: Http2Config) -> Self {
487        self.grpc_http2_config = config;
488        self
489    }
490
491    /// Sets the maximum HTTP request body size in bytes for the HTTP receiver.
492    ///
493    /// A value of `0` (the default) applies the receiver's 20 MiB compatibility default. A positive
494    /// value sets the limit in bytes.
495    pub fn with_http_max_request_body_size(mut self, max_request_body_size: u64) -> Self {
496        self.http_max_request_body_size = max_request_body_size;
497        self
498    }
499
500    /// Overrides the identifiers used for the HTTP and gRPC servers.
501    ///
502    /// Tests give each server a unique identifier so that concurrently running tests can each find the ephemeral port
503    /// their own server bound to, without picking up another test's listen address assertion.
504    #[cfg(test)]
505    fn with_server_ids(mut self, http_id: impl Into<MetaString>, grpc_id: impl Into<MetaString>) -> Self {
506        self.http_server_id = http_id.into();
507        self.grpc_server_id = grpc_id.into();
508        self
509    }
510
511    /// Sets the CORS configuration for the HTTP receiver.
512    pub fn with_cors(mut self, cors: CorsConfiguration) -> Self {
513        self.cors = cors;
514        self
515    }
516
517    /// Sets the TLS configuration for the HTTP receiver.
518    ///
519    /// When set, the HTTP receiver only accepts encrypted TLS connections.
520    pub fn with_http_tls(mut self, tls: OtlpTlsConfiguration) -> Self {
521        self.http_tls = Some(tls);
522        self
523    }
524
525    /// Sets the TLS configuration for the gRPC receiver.
526    ///
527    /// When set, the gRPC receiver only accepts encrypted TLS connections.
528    pub fn with_grpc_tls(mut self, tls: OtlpTlsConfiguration) -> Self {
529        self.grpc_tls = Some(tls);
530        self
531    }
532
533    /// Builds and starts the OTLP servers (HTTP and gRPC).
534    ///
535    /// Both servers are spawned into the scope of the current process, and they stop as soon as that process is told to
536    /// stop. The handler is dropped once both have exited, so the component can drain a channel that the handler feeds
537    /// until it closes. The servers run on `worker_pool` rather than the component's runtime, since request handling
538    /// shouldn't contend with the runtime driving the topology, and decoding can be compute-heavy for large requests.
539    ///
540    /// # Errors
541    ///
542    /// If the gRPC endpoint isn't a TCP or Unix address, the listen addresses can't be bound, the TLS configuration is
543    /// invalid, or a signal is proxied without a proxy or without a destination for the protocol it arrives on, an
544    /// error is returned.
545    pub async fn build<H: OtlpHandler>(
546        self, handler: H, memory_limiter: MemoryLimiter, metrics: Metrics, worker_pool: &Handle,
547    ) -> Result<(), GenericError> {
548        if self.routes.any_proxied() && self.proxy.is_none() {
549            return Err(generic_error!("An OTLP signal is proxied, but no OTLP proxy is set."));
550        }
551
552        let otlp_handler = Arc::new(handler);
553        let metrics = Arc::new(metrics);
554
555        // Validate TLS configurations before spawning. A server with no endpoint doesn't start, so its TLS
556        // configuration isn't loaded.
557        let http_tls_config = match self.http_tls {
558            Some(tls) if self.http_endpoint.is_some() => Some(tls.build()?),
559            _ => None,
560        };
561        let grpc_tls_config = match self.grpc_tls {
562            Some(tls) if self.grpc_endpoint.is_some() => Some(tls.build()?),
563            _ => None,
564        };
565
566        // Create and spawn the gRPC server.
567        //
568        // The gRPC endpoint is served by an HTTP server: gRPC is HTTP/2 with a distinct route naming convention, so
569        // the generated services are just another route set. It is restricted to HTTP/2 because the OTLP gRPC port
570        // only ever serves gRPC, and an HTTP/1.1 caller belongs on the HTTP endpoint instead.
571        //
572        // A proxied signal takes the whole path prefix of its service, so the upstream answers every method of it. It
573        // replaces the internal service rather than sitting next to it, since both register the same paths.
574        if let Some(grpc_endpoint) = self.grpc_endpoint {
575            let inner_grpc = GrpcServiceImpl::new(otlp_handler.clone(), memory_limiter.clone(), metrics.clone());
576            let max_decoding_message_size = self.grpc_max_recv_msg_size_bytes;
577            let mut grpc_server = HttpServer::from_listen_address(grpc_endpoint);
578            let mut proxied_grpc_routes = Router::new();
579            for signal in Signal::ALL {
580                match (self.routes.get(signal), &self.proxy) {
581                    // The check at the top of `build` rules out a proxied signal without a proxy.
582                    (OtlpRoute::Disabled, _) | (OtlpRoute::Proxied, None) => {}
583                    (OtlpRoute::Internal, _) => {
584                        let inner = inner_grpc.clone();
585                        grpc_server = match signal {
586                            Signal::Metrics => grpc_server.add_grpc_service(
587                                MetricsServiceServer::new(inner).max_decoding_message_size(max_decoding_message_size),
588                            ),
589                            Signal::Logs => grpc_server.add_grpc_service(
590                                LogsServiceServer::new(inner).max_decoding_message_size(max_decoding_message_size),
591                            ),
592                            Signal::Traces => grpc_server.add_grpc_service(
593                                TraceServiceServer::new(inner).max_decoding_message_size(max_decoding_message_size),
594                            ),
595                        };
596                    }
597                    (OtlpRoute::Proxied, Some(proxy)) => {
598                        let path = format!("/{}/{{*method}}", signal.grpc_service_name());
599                        proxied_grpc_routes = proxied_grpc_routes.route(&path, proxy.grpc_service(signal)?);
600                    }
601                }
602            }
603
604            // The server answers misses with `UNIMPLEMENTED` only when it has an internal service, so set that answer
605            // here too, for a server with only proxied or disabled signals.
606            let mut grpc_server = grpc_server
607                .add_routes(proxied_grpc_routes.fallback(unmatched_route))
608                .with_http2_only()
609                .with_http2_config(self.grpc_http2_config)
610                .with_server_id(self.grpc_server_id)
611                .with_worker_pool(worker_pool.clone());
612
613            if let Some(tls_config) = grpc_tls_config {
614                grpc_server = grpc_server.with_tls_config(tls_config);
615            }
616
617            runtime::nested_supervisor(grpc_server.into_supervisor())
618                .needed()
619                .stops_with_owner()
620                .spawn();
621        }
622
623        // Create and spawn the HTTP server.
624        if let Some(http_endpoint) = self.http_endpoint {
625            // Apply an explicit body-size limit. A configured `0` selects the receiver's 20 MiB compatibility default;
626            // a positive value is the limit in bytes. Axum's own default is not the receiver's default and must not be
627            // left implicit.
628            let max_body_size = if self.http_max_request_body_size == 0 {
629                HTTP_DEFAULT_MAX_REQUEST_BODY_SIZE
630            } else {
631                self.http_max_request_body_size as usize
632            };
633
634            // A proxied signal takes every method of its path, so the upstream answers them all, CORS preflights
635            // included. The body limit and CORS layers apply to the internal routes only: the upstream enforces its
636            // own.
637            let mut internal_routes = Router::new();
638            let mut proxied_routes = Router::new();
639            for signal in Signal::ALL {
640                match (self.routes.get(signal), &self.proxy) {
641                    // The check at the top of `build` rules out a proxied signal without a proxy.
642                    (OtlpRoute::Disabled, _) | (OtlpRoute::Proxied, None) => {}
643                    (OtlpRoute::Internal, _) => {
644                        let handler = match signal {
645                            Signal::Metrics => post(http_metrics_handler::<H>),
646                            Signal::Logs => post(http_logs_handler::<H>),
647                            Signal::Traces => post(http_traces_handler::<H>),
648                        };
649                        internal_routes = internal_routes.route(signal.http_path(), handler);
650                    }
651                    (OtlpRoute::Proxied, Some(proxy)) => {
652                        proxied_routes = proxied_routes.route(signal.http_path(), proxy.http_service(signal)?);
653                    }
654                }
655            }
656
657            let router = internal_routes.layer(DefaultBodyLimit::max(max_body_size)).with_state((
658                otlp_handler,
659                memory_limiter,
660                metrics,
661            ));
662
663            // Apply CORS middleware when origins are configured.
664            let router = if !self.cors.allowed_origins.is_empty() {
665                router.layer(build_cors_layer(&self.cors))
666            } else {
667                router
668            };
669            let router = router.merge(proxied_routes);
670
671            let mut http_server = HttpServer::from_listen_address(http_endpoint)
672                .add_routes(router)
673                .with_server_id(self.http_server_id)
674                .with_worker_pool(worker_pool.clone());
675
676            if let Some(tls_config) = http_tls_config {
677                http_server = http_server.with_tls_config(tls_config);
678            }
679
680            runtime::nested_supervisor(http_server.into_supervisor())
681                .needed()
682                .stops_with_owner()
683                .spawn();
684        }
685
686        Ok(())
687    }
688}
689
690/// Builds a CORS layer from the resolved CORS configuration.
691///
692/// A bare `*` in the list of allowed origins enables allow-all; otherwise the first `*` in an origin is a partial wildcard
693/// (for example, `http://*.domain.com` matches `http://foo.domain.com`).
694fn build_cors_layer(cors: &CorsConfiguration) -> CorsLayer {
695    let mut layer = CorsLayer::new();
696    let allowed_origins = cors
697        .allowed_origins
698        .iter()
699        .map(|origin| origin.to_ascii_lowercase())
700        .collect::<Vec<_>>();
701
702    let allows_any_origin = allowed_origins.iter().any(|origin| origin == "*");
703    if allows_any_origin {
704        layer = layer.allow_origin(Any);
705    } else {
706        layer = layer.allow_origin(AllowOrigin::predicate(move |origin, _request_parts| {
707            let Ok(origin) = origin.to_str() else {
708                return false;
709            };
710            let origin = origin.to_ascii_lowercase();
711
712            allowed_origins.iter().any(|pattern| origin_matches(pattern, &origin))
713        }));
714    }
715
716    // Preflight must permit the methods browser exporters use; without this the browser blocks
717    // the actual request even when the origin is allowed.
718    layer = layer.allow_methods([Method::GET, Method::POST, Method::HEAD]);
719
720    if cors.allowed_headers.iter().any(|h| h == "*") {
721        layer = layer.allow_headers(Any);
722    } else {
723        let mut headers: Vec<HeaderName> = cors
724            .allowed_headers
725            .iter()
726            .filter_map(|h| HeaderName::from_str(h).ok())
727            .collect();
728        headers.extend_from_slice(&IMPLICIT_HEADERS);
729        if cors.allowed_headers.is_empty() {
730            headers.push(HeaderName::from_static("x-requested-with"));
731        }
732        layer = layer.allow_headers(headers);
733    }
734
735    // Exposed headers.
736    if !cors.exposed_headers.is_empty() {
737        let headers: Vec<HeaderName> = cors
738            .exposed_headers
739            .iter()
740            .filter_map(|h| HeaderName::from_str(h).ok())
741            .collect();
742        layer = layer.expose_headers(headers);
743    }
744
745    // Max age.
746    if cors.max_age > 0 {
747        layer = layer.max_age(std::time::Duration::from_secs(cors.max_age));
748    }
749
750    // Wildcard CORS responses cannot permit browser credentials.
751    if !allows_any_origin
752        && !cors.allowed_headers.iter().any(|header| header == "*")
753        && !cors.exposed_headers.iter().any(|header| header == "*")
754    {
755        layer = layer.allow_credentials(true);
756    }
757
758    layer
759}
760
761/// Matches an Origin header against an allowed-origin pattern with first-`*` wildcard semantics.
762fn origin_matches(pattern: &str, origin: &str) -> bool {
763    let mut parts = pattern.splitn(2, '*');
764    let prefix = parts.next().unwrap_or("");
765    let Some(suffix) = parts.next() else {
766        return pattern == origin;
767    };
768
769    origin.starts_with(prefix) && origin.ends_with(suffix) && origin.len() >= prefix.len() + suffix.len()
770}
771
772/// HTTP handler for OTLP metrics requests.
773async fn http_metrics_handler<H: OtlpHandler>(
774    State((handler, memory_limiter, metrics)): State<(Arc<H>, MemoryLimiter, Arc<Metrics>)>, body: Bytes,
775) -> (StatusCode, &'static str) {
776    memory_limiter.wait_for_capacity().await;
777
778    metrics.bytes_received().increment(body.len() as u64);
779
780    match handler.handle_metrics(body).await {
781        Ok(()) => (StatusCode::OK, "OK"),
782        Err(e) => {
783            error!(error = %e, "Failed to handle OTLP metrics.");
784            (StatusCode::INTERNAL_SERVER_ERROR, "Internal processing error")
785        }
786    }
787}
788
789/// HTTP handler for OTLP logs requests.
790async fn http_logs_handler<H: OtlpHandler>(
791    State((handler, memory_limiter, metrics)): State<(Arc<H>, MemoryLimiter, Arc<Metrics>)>, body: Bytes,
792) -> (StatusCode, &'static str) {
793    memory_limiter.wait_for_capacity().await;
794
795    metrics.bytes_received().increment(body.len() as u64);
796
797    match handler.handle_logs(body).await {
798        Ok(()) => (StatusCode::OK, "OK"),
799        Err(e) => {
800            error!(error = %e, "Failed to handle OTLP logs.");
801            (StatusCode::INTERNAL_SERVER_ERROR, "Internal processing error")
802        }
803    }
804}
805
806/// HTTP handler for OTLP traces requests.
807async fn http_traces_handler<H: OtlpHandler>(
808    State((handler, memory_limiter, metrics)): State<(Arc<H>, MemoryLimiter, Arc<Metrics>)>, body: Bytes,
809) -> (StatusCode, &'static str) {
810    memory_limiter.wait_for_capacity().await;
811
812    metrics.bytes_received().increment(body.len() as u64);
813
814    match handler.handle_traces(body).await {
815        Ok(()) => (StatusCode::OK, "OK"),
816        Err(e) => {
817            error!(error = %e, "Failed to handle OTLP traces.");
818            (StatusCode::INTERNAL_SERVER_ERROR, "Internal processing error")
819        }
820    }
821}
822
823/// gRPC service implementation that delegates to the handler.
824struct GrpcServiceImpl<H> {
825    handler: Arc<H>,
826    memory_limiter: MemoryLimiter,
827    metrics: Arc<Metrics>,
828}
829
830impl<H> GrpcServiceImpl<H> {
831    fn new(handler: Arc<H>, memory_limiter: MemoryLimiter, metrics: Arc<Metrics>) -> Self {
832        Self {
833            handler,
834            memory_limiter,
835            metrics,
836        }
837    }
838}
839
840impl<H> Clone for GrpcServiceImpl<H> {
841    fn clone(&self) -> Self {
842        Self {
843            handler: self.handler.clone(),
844            memory_limiter: self.memory_limiter.clone(),
845            metrics: self.metrics.clone(),
846        }
847    }
848}
849
850#[async_trait]
851impl<H: OtlpHandler> MetricsService for GrpcServiceImpl<H> {
852    async fn export(
853        &self, request: TonicRequest<ExportMetricsServiceRequest>,
854    ) -> Result<Response<ExportMetricsServiceResponse>, Status> {
855        self.memory_limiter.wait_for_capacity().await;
856
857        let raw_bytes = request.into_inner().encode_to_vec();
858        self.metrics.bytes_received().increment(raw_bytes.len() as u64);
859
860        match self.handler.handle_metrics(Bytes::from(raw_bytes)).await {
861            Ok(()) => Ok(Response::new(ExportMetricsServiceResponse { partial_success: None })),
862            Err(e) => {
863                error!(error = %e, "Failed to handle OTLP metrics.");
864                Err(Status::internal("Internal processing error"))
865            }
866        }
867    }
868}
869
870#[async_trait]
871impl<H: OtlpHandler> LogsService for GrpcServiceImpl<H> {
872    async fn export(
873        &self, request: TonicRequest<ExportLogsServiceRequest>,
874    ) -> Result<Response<ExportLogsServiceResponse>, Status> {
875        self.memory_limiter.wait_for_capacity().await;
876
877        let raw_bytes = request.into_inner().encode_to_vec();
878        self.metrics.bytes_received().increment(raw_bytes.len() as u64);
879
880        match self.handler.handle_logs(Bytes::from(raw_bytes)).await {
881            Ok(()) => Ok(Response::new(ExportLogsServiceResponse { partial_success: None })),
882            Err(e) => {
883                error!(error = %e, "Failed to handle OTLP logs.");
884                Err(Status::internal("Internal processing error"))
885            }
886        }
887    }
888}
889
890#[async_trait]
891impl<H: OtlpHandler> TraceService for GrpcServiceImpl<H> {
892    async fn export(
893        &self, request: TonicRequest<ExportTraceServiceRequest>,
894    ) -> Result<Response<ExportTraceServiceResponse>, Status> {
895        self.memory_limiter.wait_for_capacity().await;
896
897        let raw_bytes = request.into_inner().encode_to_vec();
898        self.metrics.bytes_received().increment(raw_bytes.len() as u64);
899
900        match self.handler.handle_traces(Bytes::from(raw_bytes)).await {
901            Ok(()) => Ok(Response::new(ExportTraceServiceResponse { partial_success: None })),
902            Err(e) => {
903                error!(error = %e, "Failed to handle OTLP traces.");
904                Err(Status::internal("Internal processing error"))
905            }
906        }
907    }
908}
909
910#[cfg(test)]
911mod tests {
912    use std::sync::Arc;
913
914    use axum::{
915        body::Body,
916        http::{header, Request},
917        routing::post,
918    };
919    use rustls::pki_types::ServerName;
920    use saluki_core::{
921        accounting::MemoryLimiter,
922        components::ComponentContext,
923        runtime::{state::IdentifierFilter, test_util::TestSupervisor},
924    };
925    use saluki_io::net::{client::http::HttpProtocol, BoundListenAddress};
926    use saluki_metrics::test::TestRecorder;
927    use saluki_tls::test_util::SelfSignedCert;
928    use tokio::io::{AsyncReadExt, AsyncWriteExt};
929    use tokio_rustls::TlsConnector;
930    use tower::ServiceExt;
931
932    use super::proxy::OtlpProxyDestinations;
933    use super::test_util::{
934        bound_port, grpc_ok, http_ok, proxy_to, wait_for_port, FakeUpstream, RecordingHandler, TestClient, TestServers,
935    };
936    use super::*;
937    use crate::common::datadog::test_util::init_crypto_provider;
938
939    struct NoopHandler;
940
941    #[async_trait]
942    impl OtlpHandler for NoopHandler {
943        async fn handle_metrics(&self, _body: Bytes) -> Result<(), GenericError> {
944            Ok(())
945        }
946
947        async fn handle_logs(&self, _body: Bytes) -> Result<(), GenericError> {
948            Ok(())
949        }
950
951        async fn handle_traces(&self, _body: Bytes) -> Result<(), GenericError> {
952            Ok(())
953        }
954    }
955
956    fn assert_bytes_received(recorder: &TestRecorder, expected_size: u64) {
957        assert_eq!(
958            recorder.counter((
959                "component_bytes_received_total",
960                &[
961                    ("component_id", "otlp_test"),
962                    ("component_type", "source"),
963                    ("source", "otlp"),
964                ]
965            )),
966            Some(expected_size)
967        );
968    }
969
970    fn test_component_context() -> ComponentContext {
971        ComponentContext::test_source("otlp_test")
972    }
973
974    #[tokio::test]
975    async fn grpc_metrics_export_updates_bytes_received() {
976        let recorder = TestRecorder::default();
977        let _local = metrics::set_default_local_recorder(&recorder);
978
979        let metrics = Arc::new(build_metrics(&test_component_context()));
980        let service = GrpcServiceImpl::new(Arc::new(NoopHandler), MemoryLimiter::noop(), metrics);
981        let request = ExportMetricsServiceRequest {
982            resource_metrics: vec![otlp_protos::opentelemetry::proto::metrics::v1::ResourceMetrics::default()],
983        };
984        let expected_size = request.encode_to_vec().len() as u64;
985
986        MetricsService::export(&service, TonicRequest::new(request))
987            .await
988            .unwrap();
989
990        assert_bytes_received(&recorder, expected_size);
991    }
992
993    #[tokio::test]
994    async fn grpc_logs_export_updates_bytes_received() {
995        let recorder = TestRecorder::default();
996        let _local = metrics::set_default_local_recorder(&recorder);
997
998        let metrics = Arc::new(build_metrics(&test_component_context()));
999        let service = GrpcServiceImpl::new(Arc::new(NoopHandler), MemoryLimiter::noop(), metrics);
1000        let request = ExportLogsServiceRequest {
1001            resource_logs: vec![otlp_protos::opentelemetry::proto::logs::v1::ResourceLogs::default()],
1002        };
1003        let expected_size = request.encode_to_vec().len() as u64;
1004
1005        LogsService::export(&service, TonicRequest::new(request)).await.unwrap();
1006
1007        assert_bytes_received(&recorder, expected_size);
1008    }
1009
1010    #[tokio::test]
1011    async fn grpc_traces_export_updates_bytes_received() {
1012        let recorder = TestRecorder::default();
1013        let _local = metrics::set_default_local_recorder(&recorder);
1014
1015        let metrics = Arc::new(build_metrics(&test_component_context()));
1016        let service = GrpcServiceImpl::new(Arc::new(NoopHandler), MemoryLimiter::noop(), metrics);
1017        let request = ExportTraceServiceRequest {
1018            resource_spans: vec![otlp_protos::opentelemetry::proto::trace::v1::ResourceSpans::default()],
1019        };
1020        let expected_size = request.encode_to_vec().len() as u64;
1021
1022        TraceService::export(&service, TonicRequest::new(request))
1023            .await
1024            .unwrap();
1025
1026        assert_bytes_received(&recorder, expected_size);
1027    }
1028
1029    #[test]
1030    fn origin_matcher_matches_rs_cors_patterns() {
1031        assert!(origin_matches("http://*.example.com", "http://foo.example.com"));
1032        assert!(origin_matches("http://*.example.com", "http://.example.com"));
1033        assert!(!origin_matches(
1034            "http://*.example.com",
1035            "http://foo.example.com.evil.com"
1036        ));
1037        assert!(origin_matches("http://*.example.com/*", "http://foo.example.com/*"));
1038        assert!(!origin_matches("http://*.example.com/*", "http://foo.example.com/bar"));
1039        assert!(origin_matches("http://example.com", "http://example.com"));
1040        assert!(!origin_matches("http://example.com", "http://other.com"));
1041    }
1042
1043    #[tokio::test]
1044    async fn cors_layer_matches_partial_wildcard_origin() {
1045        let app = Router::new()
1046            .route("/", post(|| async { StatusCode::NO_CONTENT }))
1047            .layer(build_cors_layer(&CorsConfiguration {
1048                allowed_origins: vec!["HTTP://*.EXAMPLE.COM".to_string()],
1049                ..Default::default()
1050            }));
1051
1052        let response = app
1053            .oneshot(
1054                Request::builder()
1055                    .method("POST")
1056                    .uri("/")
1057                    .header(header::ORIGIN, "http://api.example.com")
1058                    .body(Body::empty())
1059                    .unwrap(),
1060            )
1061            .await
1062            .unwrap();
1063
1064        assert_eq!(
1065            response
1066                .headers()
1067                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
1068                .and_then(|value| value.to_str().ok()),
1069            Some("http://api.example.com")
1070        );
1071        assert_eq!(
1072            response
1073                .headers()
1074                .get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
1075                .and_then(|value| value.to_str().ok()),
1076            Some("true")
1077        );
1078    }
1079
1080    #[tokio::test]
1081    async fn cors_layer_rejects_unrelated_partial_wildcard_origin() {
1082        let app = Router::new()
1083            .route("/", post(|| async { StatusCode::NO_CONTENT }))
1084            .layer(build_cors_layer(&CorsConfiguration {
1085                allowed_origins: vec!["http://*.example.com".to_string()],
1086                ..Default::default()
1087            }));
1088
1089        let response = app
1090            .oneshot(
1091                Request::builder()
1092                    .method("POST")
1093                    .uri("/")
1094                    .header(header::ORIGIN, "https://evil.example")
1095                    .body(Body::empty())
1096                    .unwrap(),
1097            )
1098            .await
1099            .unwrap();
1100
1101        assert!(response.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN).is_none());
1102    }
1103
1104    #[tokio::test]
1105    async fn cors_layer_allows_any_origin_for_bare_wildcard() {
1106        let app = Router::new()
1107            .route("/", post(|| async { StatusCode::NO_CONTENT }))
1108            .layer(build_cors_layer(&CorsConfiguration {
1109                allowed_origins: vec!["*".to_string()],
1110                ..Default::default()
1111            }));
1112
1113        let response = app
1114            .oneshot(
1115                Request::builder()
1116                    .method("POST")
1117                    .uri("/")
1118                    .header(header::ORIGIN, "https://evil.example")
1119                    .body(Body::empty())
1120                    .unwrap(),
1121            )
1122            .await
1123            .unwrap();
1124
1125        assert_eq!(
1126            response
1127                .headers()
1128                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
1129                .and_then(|value| value.to_str().ok()),
1130            Some("*")
1131        );
1132        assert!(response
1133            .headers()
1134            .get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
1135            .is_none());
1136    }
1137
1138    #[tokio::test]
1139    async fn cors_preflight_allows_post_method() {
1140        let app = Router::new()
1141            .route("/", post(|| async { StatusCode::NO_CONTENT }))
1142            .layer(build_cors_layer(&CorsConfiguration {
1143                allowed_origins: vec!["*".to_string()],
1144                ..Default::default()
1145            }));
1146
1147        let response = app
1148            .oneshot(
1149                Request::builder()
1150                    .method("OPTIONS")
1151                    .uri("/")
1152                    .header(header::ORIGIN, "http://example.com")
1153                    .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
1154                    .body(Body::empty())
1155                    .unwrap(),
1156            )
1157            .await
1158            .unwrap();
1159
1160        let allowed_methods = response
1161            .headers()
1162            .get(header::ACCESS_CONTROL_ALLOW_METHODS)
1163            .and_then(|value| value.to_str().ok())
1164            .unwrap_or("");
1165        assert!(allowed_methods.contains("POST"));
1166    }
1167
1168    /// Waits for a Unix socket file to appear, retrying briefly to avoid races with async
1169    /// server startup.
1170    #[cfg(unix)]
1171    async fn wait_for_socket(path: &std::path::Path) {
1172        for _ in 0..100 {
1173            if path.exists() {
1174                return;
1175            }
1176            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
1177        }
1178        panic!("Unix socket at {} did not appear within 500ms", path.display());
1179    }
1180
1181    #[tokio::test]
1182    async fn http_body_limit_rejects_oversized_request() {
1183        // Exercises the full OtlpServerConfiguration wiring: a configured `max_request_body_size` must
1184        // flow through the builder into the axum `DefaultBodyLimit` layer and reject oversized
1185        // requests. See issue #2068 and PR #2494 review.
1186        let supervisor = TestSupervisor::start("otlp-test").await;
1187
1188        let http_server_id = "http-body-limit-rejects-oversized-request";
1189        let grpc_endpoint = ListenAddress::tcp_loopback(0);
1190        let http_endpoint = ListenAddress::tcp_loopback(0);
1191
1192        // Build with a small body limit (64 bytes) through the builder.
1193        let max_body_size: usize = 64;
1194        supervisor
1195            .scope(
1196                OtlpServerConfiguration::new(Some(http_endpoint), Some(grpc_endpoint), 4 * 1024 * 1024)
1197                    .with_server_ids(http_server_id, "grpc-body-limit-rejects-oversized-request")
1198                    .with_http_max_request_body_size(max_body_size as u64)
1199                    .build(
1200                        NoopHandler,
1201                        MemoryLimiter::noop(),
1202                        Metrics::for_tests(),
1203                        &tokio::runtime::Handle::current(),
1204                    ),
1205            )
1206            .await
1207            .expect("build should succeed");
1208
1209        let http_port = bound_port(&supervisor, http_server_id).await;
1210        wait_for_port(http_port).await;
1211
1212        // Send an oversized request and verify it is rejected.
1213        let oversized_body = vec![0u8; max_body_size + 1];
1214        let mut stream = tokio::net::TcpStream::connect(format!("127.0.0.1:{http_port}"))
1215            .await
1216            .expect("should connect to HTTP server");
1217
1218        let request = format!(
1219            "POST /v1/metrics HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/x-protobuf\r\nContent-Length: {}\r\n\r\n",
1220            oversized_body.len()
1221        );
1222        use tokio::io::AsyncWriteExt;
1223        stream.write_all(request.as_bytes()).await.expect("write request line");
1224        stream.write_all(&oversized_body).await.expect("write body");
1225        stream.flush().await.expect("flush");
1226
1227        // Read the response status line.
1228        use tokio::io::AsyncReadExt;
1229        let mut response = Vec::new();
1230        stream.read_to_end(&mut response).await.expect("read response");
1231        let response_str = String::from_utf8_lossy(&response);
1232        assert!(
1233            response_str.starts_with("HTTP/1.1 413"),
1234            "expected 413 PAYLOAD_TOO_LARGE, got: {}",
1235            response_str.lines().next().unwrap_or("<empty>")
1236        );
1237
1238        supervisor
1239            .shutdown()
1240            .await
1241            .expect("supervisor should shut down cleanly");
1242    }
1243
1244    #[tokio::test]
1245    async fn http_body_default_limit_rejects_oversized_request() {
1246        // When `max_request_body_size` is `0` (the default), the receiver applies a 20 MiB limit.
1247        // A request body exceeding 20 MiB must be rejected with 413.
1248        use tokio::io::{AsyncReadExt, AsyncWriteExt};
1249
1250        let supervisor = TestSupervisor::start("otlp-test").await;
1251
1252        let http_server_id = "http-body-default-limit-rejects-oversized-request";
1253        let grpc_endpoint = ListenAddress::tcp_loopback(0);
1254        let http_endpoint = ListenAddress::tcp_loopback(0);
1255
1256        // Build with the default (`max_request_body_size=0` → 20 MiB limit) — no explicit limit set.
1257        supervisor
1258            .scope(
1259                OtlpServerConfiguration::new(Some(http_endpoint), Some(grpc_endpoint), 4 * 1024 * 1024)
1260                    .with_server_ids(http_server_id, "grpc-body-default-limit-rejects-oversized-request")
1261                    .build(
1262                        NoopHandler,
1263                        MemoryLimiter::noop(),
1264                        Metrics::for_tests(),
1265                        &tokio::runtime::Handle::current(),
1266                    ),
1267            )
1268            .await
1269            .expect("build should succeed");
1270
1271        let http_port = bound_port(&supervisor, http_server_id).await;
1272        wait_for_port(http_port).await;
1273
1274        // Send a body of 20 MiB + 1 byte — one byte over the default limit.
1275        let oversized_body = vec![0u8; HTTP_DEFAULT_MAX_REQUEST_BODY_SIZE + 1];
1276        let mut stream = tokio::net::TcpStream::connect(format!("127.0.0.1:{http_port}"))
1277            .await
1278            .expect("should connect to HTTP server");
1279
1280        let request = format!(
1281            "POST /v1/metrics HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/x-protobuf\r\nContent-Length: {}\r\n\r\n",
1282            oversized_body.len()
1283        );
1284        stream.write_all(request.as_bytes()).await.expect("write request line");
1285        stream.write_all(&oversized_body).await.expect("write body");
1286        stream.flush().await.expect("flush");
1287
1288        let mut response = Vec::new();
1289        stream.read_to_end(&mut response).await.expect("read response");
1290        let response_str = String::from_utf8_lossy(&response);
1291        assert!(
1292            response_str.starts_with("HTTP/1.1 413"),
1293            "expected 413 PAYLOAD_TOO_LARGE for body exceeding 20 MiB default, got: {}",
1294            response_str.lines().next().unwrap_or("<empty>")
1295        );
1296
1297        supervisor
1298            .shutdown()
1299            .await
1300            .expect("supervisor should shut down cleanly");
1301    }
1302
1303    #[cfg(unix)]
1304    #[tokio::test]
1305    async fn build_succeeds_with_unix_grpc_endpoint() {
1306        let dir = tempfile::tempdir().expect("temp dir should be created");
1307        let grpc_socket = dir.path().join("grpc.sock");
1308        let grpc_endpoint = ListenAddress::try_from(format!("unix://{}", grpc_socket.display()).as_str())
1309            .expect("Unix gRPC endpoint should parse");
1310        // Use an ephemeral TCP port for HTTP since we are only testing the gRPC path here.
1311        let http_endpoint = ListenAddress::Tcp("127.0.0.1:0".parse().expect("addr should parse"));
1312
1313        let supervisor = TestSupervisor::start("otlp-test").await;
1314
1315        // The servers spawn on the ambient supervisor, so the build has to run under the one they belong to.
1316        let result = supervisor
1317            .scope(
1318                OtlpServerConfiguration::new(Some(http_endpoint), Some(grpc_endpoint), 4 * 1024 * 1024).build(
1319                    NoopHandler,
1320                    MemoryLimiter::noop(),
1321                    Metrics::for_tests(),
1322                    &tokio::runtime::Handle::current(),
1323                ),
1324            )
1325            .await;
1326
1327        assert!(
1328            result.is_ok(),
1329            "build should succeed with a Unix gRPC endpoint, got: {:?}",
1330            result.err()
1331        );
1332
1333        supervisor
1334            .shutdown()
1335            .await
1336            .expect("supervisor should shut down cleanly");
1337    }
1338
1339    #[tokio::test]
1340    async fn build_starts_only_the_servers_with_an_endpoint() {
1341        let supervisor = TestSupervisor::start("otlp-test").await;
1342
1343        // A server with no endpoint doesn't load its TLS files, which here don't exist.
1344        let missing_tls = || OtlpTlsConfiguration::new("/missing/cert.pem".into(), "/missing/key.pem".into());
1345
1346        // The HTTP server alone.
1347        supervisor
1348            .scope(
1349                OtlpServerConfiguration::new(Some(ListenAddress::tcp_loopback(0)), None, 4 * 1024 * 1024)
1350                    .with_server_ids("http-only-http", "http-only-grpc")
1351                    .with_grpc_tls(missing_tls())
1352                    .build(
1353                        NoopHandler,
1354                        MemoryLimiter::noop(),
1355                        Metrics::for_tests(),
1356                        &tokio::runtime::Handle::current(),
1357                    ),
1358            )
1359            .await
1360            .expect("build should succeed with only an HTTP endpoint");
1361
1362        bound_port(&supervisor, "http-only-http").await;
1363        assert_eq!(supervisor.active_children(), 1);
1364        assert_not_bound(&supervisor, "http-only-grpc");
1365
1366        // The gRPC server alone.
1367        supervisor
1368            .scope(
1369                OtlpServerConfiguration::new(None, Some(ListenAddress::tcp_loopback(0)), 4 * 1024 * 1024)
1370                    .with_server_ids("grpc-only-http", "grpc-only-grpc")
1371                    .with_http_tls(missing_tls())
1372                    .build(
1373                        NoopHandler,
1374                        MemoryLimiter::noop(),
1375                        Metrics::for_tests(),
1376                        &tokio::runtime::Handle::current(),
1377                    ),
1378            )
1379            .await
1380            .expect("build should succeed with only a gRPC endpoint");
1381
1382        bound_port(&supervisor, "grpc-only-grpc").await;
1383        assert_eq!(supervisor.active_children(), 2);
1384        assert_not_bound(&supervisor, "grpc-only-http");
1385
1386        supervisor
1387            .shutdown()
1388            .await
1389            .expect("supervisor should shut down cleanly");
1390    }
1391
1392    #[cfg(unix)]
1393    #[tokio::test]
1394    async fn grpc_export_works_over_unix_socket() {
1395        use otlp_protos::opentelemetry::proto::collector::metrics::v1::metrics_service_client::MetricsServiceClient;
1396
1397        let dir = tempfile::tempdir().expect("temp dir should be created");
1398        let grpc_socket = dir.path().join("grpc.sock");
1399        let grpc_endpoint = ListenAddress::try_from(format!("unix://{}", grpc_socket.display()).as_str())
1400            .expect("Unix gRPC endpoint should parse");
1401        let http_endpoint = ListenAddress::Tcp("127.0.0.1:0".parse().expect("addr should parse"));
1402
1403        let supervisor = TestSupervisor::start("otlp-test").await;
1404
1405        supervisor
1406            .scope(
1407                OtlpServerConfiguration::new(Some(http_endpoint), Some(grpc_endpoint), 4 * 1024 * 1024).build(
1408                    NoopHandler,
1409                    MemoryLimiter::noop(),
1410                    Metrics::for_tests(),
1411                    &tokio::runtime::Handle::current(),
1412                ),
1413            )
1414            .await
1415            .expect("build should succeed");
1416
1417        wait_for_socket(&grpc_socket).await;
1418
1419        // Connect a tonic gRPC client over the Unix socket and send a metrics export request.
1420        let endpoint_str = format!("unix://{}", grpc_socket.display());
1421        let channel = tonic::transport::Endpoint::from_shared(endpoint_str)
1422            .expect("endpoint should parse")
1423            .connect()
1424            .await
1425            .expect("should connect to gRPC server over Unix socket");
1426
1427        let mut client = MetricsServiceClient::new(channel);
1428        let request = ExportMetricsServiceRequest {
1429            resource_metrics: vec![otlp_protos::opentelemetry::proto::metrics::v1::ResourceMetrics::default()],
1430        };
1431        let response = client.export(request).await.expect("export should succeed");
1432
1433        // A successful response has an empty partial_success (None).
1434        assert_eq!(response.into_inner().partial_success, None);
1435
1436        supervisor
1437            .shutdown()
1438            .await
1439            .expect("supervisor should shut down cleanly");
1440    }
1441
1442    /// Builds a `rustls::ClientConfig` that trusts the self-signed certificate.
1443    fn self_signed_client_config(cert: &SelfSignedCert) -> rustls::ClientConfig {
1444        let mut root_store = rustls::RootCertStore::empty();
1445        root_store.add(cert.cert_chain().into_iter().next().unwrap()).unwrap();
1446        rustls::ClientConfig::builder()
1447            .with_root_certificates(root_store)
1448            .with_no_client_auth()
1449    }
1450
1451    /// Starts an `OtlpServerConfiguration` with TLS enabled on both HTTP and gRPC, returning the bound ports and
1452    /// the self-signed certificate (so callers can build a matching client config).
1453    async fn start_otlp_server_with_tls(server_id: &str) -> (u16, u16, SelfSignedCert, TestSupervisor) {
1454        let _ = saluki_tls::initialize_default_crypto_provider();
1455        let supervisor = TestSupervisor::start("otlp-tls-test").await;
1456
1457        let cert = SelfSignedCert::localhost();
1458        let http_endpoint = ListenAddress::tcp_loopback(0);
1459        let grpc_endpoint = ListenAddress::tcp_loopback(0);
1460
1461        // Write the cert and key to temp files so OtlpTlsConfiguration can load them.
1462        let tempdir = tempfile::tempdir().expect("temp dir should be created");
1463        let cert_path = tempdir.path().join("cert.pem");
1464        let key_path = tempdir.path().join("key.pem");
1465        cert.write_cert_pem(&cert_path);
1466        cert.write_key_pem(&key_path);
1467
1468        let http_server_id = format!("otlp-http-test-{}", server_id);
1469        let grpc_server_id = format!("otlp-grpc-test-{}", server_id);
1470
1471        let tls_config = OtlpTlsConfiguration::new(cert_path, key_path);
1472        let server_config = OtlpServerConfiguration::new(Some(http_endpoint), Some(grpc_endpoint), 4 * 1024 * 1024)
1473            .with_server_ids(&*http_server_id, &*grpc_server_id)
1474            .with_http_tls(tls_config.clone())
1475            .with_grpc_tls(tls_config);
1476
1477        supervisor
1478            .scope(server_config.build(
1479                NoopHandler,
1480                MemoryLimiter::noop(),
1481                Metrics::for_tests(),
1482                &tokio::runtime::Handle::current(),
1483            ))
1484            .await
1485            .expect("OTLP server with TLS should start");
1486
1487        let http_port = bound_port(&supervisor, &http_server_id).await;
1488        let grpc_port = bound_port(&supervisor, &grpc_server_id).await;
1489        wait_for_port(http_port).await;
1490        wait_for_port(grpc_port).await;
1491
1492        (http_port, grpc_port, cert, supervisor)
1493    }
1494
1495    /// Asserts that the server with identifier `id` has not bound a listen address.
1496    fn assert_not_bound(supervisor: &TestSupervisor, id: &str) {
1497        let id = format!("http-server-{}", id);
1498        let bound = supervisor
1499            .dataspace()
1500            .current_values::<BoundListenAddress>(IdentifierFilter::exact(id.clone()));
1501
1502        assert!(
1503            bound.is_empty(),
1504            "'{id}' should not bind a listen address, got {bound:?}"
1505        );
1506    }
1507
1508    #[tokio::test]
1509    async fn http_tls_handshake_succeeds_with_trusted_cert() {
1510        let (http_port, _grpc_port, cert, supervisor) = start_otlp_server_with_tls("http-tls-handshake-succeeds").await;
1511
1512        // Connect a TLS client to the HTTP port and verify the handshake completes.
1513        let connector = TlsConnector::from(Arc::new(self_signed_client_config(&cert)));
1514        let stream = tokio::net::TcpStream::connect(format!("127.0.0.1:{}", http_port))
1515            .await
1516            .expect("should connect to HTTP port");
1517        let server_name = ServerName::try_from("localhost").unwrap();
1518        let mut tls_stream = connector
1519            .connect(server_name, stream)
1520            .await
1521            .expect("TLS handshake should succeed with trusted self-signed cert");
1522
1523        // Send a minimal HTTP request to confirm the server is serving over TLS.
1524        tls_stream
1525            .write_all(b"GET /v1/traces HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
1526            .await
1527            .expect("should write HTTP request over TLS");
1528
1529        // Read the response — any HTTP response means TLS is working.
1530        let mut buf = [0u8; 1024];
1531        let n = tls_stream
1532            .read(&mut buf)
1533            .await
1534            .expect("should read HTTP response over TLS");
1535        let response = String::from_utf8_lossy(&buf[..n]);
1536        assert!(
1537            response.starts_with("HTTP/"),
1538            "expected an HTTP response, got: {response}"
1539        );
1540
1541        // Close the connection before shutting down the supervisor so the server can drain cleanly.
1542        let _ = tls_stream.shutdown().await;
1543
1544        supervisor
1545            .shutdown()
1546            .await
1547            .expect("supervisor should shut down cleanly");
1548    }
1549
1550    #[tokio::test]
1551    async fn grpc_tls_handshake_succeeds_with_trusted_cert() {
1552        let (_http_port, grpc_port, cert, supervisor) = start_otlp_server_with_tls("grpc-tls-handshake-succeeds").await;
1553
1554        // Connect a TLS client to the gRPC port and verify the handshake completes.
1555        // We use a raw TLS connection rather than a full gRPC client to keep the test simple — completing the
1556        // handshake proves the server is serving TLS.
1557        let connector = TlsConnector::from(Arc::new(self_signed_client_config(&cert)));
1558        let stream = tokio::net::TcpStream::connect(format!("127.0.0.1:{}", grpc_port))
1559            .await
1560            .expect("should connect to gRPC port");
1561        let server_name = ServerName::try_from("localhost").unwrap();
1562        let mut tls_stream = connector
1563            .connect(server_name, stream)
1564            .await
1565            .expect("TLS handshake should succeed with trusted self-signed cert");
1566
1567        // Send an HTTP/2 connection preface to confirm the gRPC server is speaking HTTP/2 over TLS.
1568        tls_stream
1569            .write_all(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
1570            .await
1571            .expect("should write HTTP/2 preface over TLS");
1572
1573        // Read any response — the server may send a settings frame or close. Either way, the handshake succeeded.
1574        let mut buf = [0u8; 1024];
1575        let _ = tls_stream.read(&mut buf).await;
1576
1577        // Close the connection before shutting down the supervisor so the server can drain cleanly.
1578        let _ = tls_stream.shutdown().await;
1579
1580        supervisor
1581            .shutdown()
1582            .await
1583            .expect("supervisor should shut down cleanly");
1584    }
1585
1586    #[tokio::test]
1587    async fn http_tls_handshake_fails_without_trusted_cert() {
1588        let (http_port, _grpc_port, _cert, supervisor) = start_otlp_server_with_tls("http-tls-handshake-fails").await;
1589
1590        // Connect a TLS client with an empty root store — the handshake should fail because the self-signed cert
1591        // is not trusted.
1592        let client_config = rustls::ClientConfig::builder()
1593            .with_root_certificates(rustls::RootCertStore::empty())
1594            .with_no_client_auth();
1595        let connector = TlsConnector::from(Arc::new(client_config));
1596        let stream = tokio::net::TcpStream::connect(format!("127.0.0.1:{}", http_port))
1597            .await
1598            .expect("should connect to HTTP port");
1599        let server_name = ServerName::try_from("localhost").unwrap();
1600        let result = connector.connect(server_name, stream).await;
1601
1602        assert!(result.is_err(), "TLS handshake should fail without trusted cert");
1603
1604        supervisor
1605            .shutdown()
1606            .await
1607            .expect("supervisor should shut down cleanly");
1608    }
1609
1610    /// Sends an empty export request for `signal` over gRPC and returns the resulting status code.
1611    async fn grpc_export_code(port: u16, signal: Signal) -> tonic::Code {
1612        use otlp_protos::opentelemetry::proto::collector::logs::v1::logs_service_client::LogsServiceClient;
1613        use otlp_protos::opentelemetry::proto::collector::metrics::v1::metrics_service_client::MetricsServiceClient;
1614        use otlp_protos::opentelemetry::proto::collector::trace::v1::trace_service_client::TraceServiceClient;
1615
1616        let channel = tonic::transport::Endpoint::from_shared(format!("http://127.0.0.1:{port}"))
1617            .expect("endpoint should parse")
1618            .connect()
1619            .await
1620            .expect("should connect to the gRPC server");
1621        let result = match signal {
1622            Signal::Metrics => MetricsServiceClient::new(channel)
1623                .export(ExportMetricsServiceRequest::default())
1624                .await
1625                .map(|_| ()),
1626            Signal::Logs => LogsServiceClient::new(channel)
1627                .export(ExportLogsServiceRequest::default())
1628                .await
1629                .map(|_| ()),
1630            Signal::Traces => TraceServiceClient::new(channel)
1631                .export(ExportTraceServiceRequest::default())
1632                .await
1633                .map(|_| ()),
1634        };
1635        match result {
1636            Ok(()) => tonic::Code::Ok,
1637            Err(status) => status.code(),
1638        }
1639    }
1640
1641    /// Sends an export request for `signal` over HTTP and returns the response status.
1642    async fn http_export_status(port: u16, signal: Signal, body: Vec<u8>) -> StatusCode {
1643        TestClient::new(HttpProtocol::Http1)
1644            .send(
1645                "POST",
1646                &format!("http://127.0.0.1:{port}{}", signal.http_path()),
1647                &[("content-type", "application/x-protobuf")],
1648                body,
1649            )
1650            .await
1651            .expect("HTTP server should answer")
1652            .status
1653    }
1654
1655    #[tokio::test]
1656    async fn each_signal_is_served_by_its_route() {
1657        // Each signal takes each route once over three runs, with the other signals on the other routes.
1658        const ROUTES: [OtlpRoute; 3] = [OtlpRoute::Disabled, OtlpRoute::Internal, OtlpRoute::Proxied];
1659
1660        for rotation in 0..ROUTES.len() {
1661            let route_of = |signal: Signal| {
1662                let index = Signal::ALL
1663                    .iter()
1664                    .position(|s| *s == signal)
1665                    .expect("signal should be listed");
1666                ROUTES[(index + rotation) % ROUTES.len()]
1667            };
1668            let routes = OtlpRoutes {
1669                metrics: route_of(Signal::Metrics),
1670                logs: route_of(Signal::Logs),
1671                traces: route_of(Signal::Traces),
1672            };
1673            let grpc_upstream = FakeUpstream::tcp(grpc_ok).await;
1674            let http_upstream = FakeUpstream::tcp(http_ok).await;
1675            let handler = RecordingHandler::default();
1676            let servers = TestServers::start(
1677                &format!("routes-{rotation}"),
1678                TestServers::configuration()
1679                    .with_routes(routes)
1680                    .with_proxy(proxy_to(&grpc_upstream, &http_upstream)),
1681                handler.clone(),
1682            )
1683            .await;
1684
1685            for signal in Signal::ALL {
1686                let route = route_of(signal);
1687                let (expected_code, expected_status) = match route {
1688                    OtlpRoute::Disabled => (tonic::Code::Unimplemented, StatusCode::NOT_FOUND),
1689                    OtlpRoute::Internal | OtlpRoute::Proxied => (tonic::Code::Ok, StatusCode::OK),
1690                };
1691                assert_eq!(
1692                    grpc_export_code(servers.grpc_port, signal).await,
1693                    expected_code,
1694                    "gRPC {signal:?} on {route:?}"
1695                );
1696                assert_eq!(
1697                    http_export_status(servers.http_port, signal, Vec::new()).await,
1698                    expected_status,
1699                    "HTTP {signal:?} on {route:?}"
1700                );
1701
1702                let grpc_path = format!("/{}/Export", signal.grpc_service_name());
1703                let proxied = |upstream: &FakeUpstream, path: &str| {
1704                    upstream
1705                        .requests()
1706                        .iter()
1707                        .filter(|request| request.path_and_query == path)
1708                        .count()
1709                };
1710                let (expected_handled, expected_proxied) = match route {
1711                    OtlpRoute::Disabled => (0, 0),
1712                    OtlpRoute::Internal => (2, 0),
1713                    OtlpRoute::Proxied => (0, 1),
1714                };
1715                assert_eq!(handler.count(signal), expected_handled, "{signal:?} on {route:?}");
1716                assert_eq!(
1717                    proxied(&grpc_upstream, &grpc_path),
1718                    expected_proxied,
1719                    "gRPC {signal:?} on {route:?}"
1720                );
1721                assert_eq!(
1722                    proxied(&http_upstream, signal.http_path()),
1723                    expected_proxied,
1724                    "HTTP {signal:?} on {route:?}"
1725                );
1726            }
1727
1728            servers.shutdown().await;
1729        }
1730    }
1731
1732    #[tokio::test]
1733    async fn grpc_server_without_internal_signals_answers_misses_with_unimplemented() {
1734        // With no internal service, the gRPC server has no fallback of its own, so `build` sets one.
1735        for route in [OtlpRoute::Disabled, OtlpRoute::Proxied] {
1736            let upstream = FakeUpstream::tcp(grpc_ok).await;
1737            let servers = TestServers::start(
1738                &format!("grpc-misses-{route:?}"),
1739                TestServers::configuration()
1740                    .with_routes(OtlpRoutes {
1741                        metrics: route,
1742                        logs: route,
1743                        traces: route,
1744                    })
1745                    .with_proxy(proxy_to(&upstream, &upstream)),
1746                RecordingHandler::default(),
1747            )
1748            .await;
1749
1750            let response = TestClient::new(HttpProtocol::Http2)
1751                .send(
1752                    "POST",
1753                    &format!("http://127.0.0.1:{}/unknown.v1.Service/Method", servers.grpc_port),
1754                    &[("content-type", "application/grpc"), ("te", "trailers")],
1755                    Bytes::new(),
1756                )
1757                .await
1758                .expect("gRPC server should answer");
1759            assert_eq!(response.status, StatusCode::OK, "{route:?}");
1760            assert_eq!(response.headers["grpc-status"], "12", "{route:?}");
1761            assert!(upstream.requests().is_empty(), "{route:?}");
1762
1763            servers.shutdown().await;
1764        }
1765    }
1766
1767    #[tokio::test]
1768    async fn http_body_limit_applies_to_internal_signals_only() {
1769        // The upstream receiver enforces its own limit on proxied requests.
1770        let upstream = FakeUpstream::tcp(http_ok).await;
1771        let servers = TestServers::start(
1772            "http-body-limit-internal-only",
1773            TestServers::configuration()
1774                .with_http_max_request_body_size(64)
1775                .with_routes(OtlpRoutes {
1776                    metrics: OtlpRoute::Proxied,
1777                    ..OtlpRoutes::ALL_INTERNAL
1778                })
1779                .with_proxy(proxy_to(&upstream, &upstream)),
1780            RecordingHandler::default(),
1781        )
1782        .await;
1783
1784        let body = vec![7u8; 1024];
1785        assert_eq!(
1786            http_export_status(servers.http_port, Signal::Metrics, body.clone()).await,
1787            StatusCode::OK
1788        );
1789        assert_eq!(
1790            http_export_status(servers.http_port, Signal::Logs, body.clone()).await,
1791            StatusCode::PAYLOAD_TOO_LARGE
1792        );
1793        let requests = upstream.requests();
1794        assert_eq!(requests.len(), 1);
1795        assert_eq!(requests[0].body, body);
1796
1797        servers.shutdown().await;
1798    }
1799
1800    #[tokio::test]
1801    async fn cors_applies_to_internal_signals_only() {
1802        // The upstream answers CORS for a proxied signal, preflights included.
1803        let upstream = FakeUpstream::tcp(|_| {
1804            let mut response = axum::response::Response::new(Body::empty());
1805            *response.status_mut() = StatusCode::NO_CONTENT;
1806            response
1807                .headers_mut()
1808                .insert("x-upstream", header::HeaderValue::from_static("yes"));
1809            response
1810        })
1811        .await;
1812        let servers = TestServers::start(
1813            "cors-internal-only",
1814            TestServers::configuration()
1815                .with_cors(CorsConfiguration {
1816                    allowed_origins: vec!["http://example.com".to_string()],
1817                    ..Default::default()
1818                })
1819                .with_routes(OtlpRoutes {
1820                    metrics: OtlpRoute::Proxied,
1821                    ..OtlpRoutes::ALL_INTERNAL
1822                })
1823                .with_proxy(proxy_to(&upstream, &upstream)),
1824            RecordingHandler::default(),
1825        )
1826        .await;
1827
1828        let mut client = TestClient::new(HttpProtocol::Http1);
1829        let preflight = [
1830            ("origin", "http://example.com"),
1831            ("access-control-request-method", "POST"),
1832        ];
1833        let uri = |signal: Signal| format!("http://127.0.0.1:{}{}", servers.http_port, signal.http_path());
1834
1835        let proxied = client
1836            .send("OPTIONS", &uri(Signal::Metrics), &preflight, Bytes::new())
1837            .await
1838            .expect("proxy should answer");
1839        assert_eq!(proxied.status, StatusCode::NO_CONTENT);
1840        assert_eq!(proxied.headers["x-upstream"], "yes");
1841        assert!(!proxied.headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN));
1842
1843        let proxied = client
1844            .send(
1845                "POST",
1846                &uri(Signal::Metrics),
1847                &[("origin", "http://example.com")],
1848                Bytes::new(),
1849            )
1850            .await
1851            .expect("proxy should answer");
1852        assert!(!proxied.headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN));
1853
1854        let internal = client
1855            .send("OPTIONS", &uri(Signal::Logs), &preflight, Bytes::new())
1856            .await
1857            .expect("server should answer");
1858        assert_eq!(
1859            internal.headers[header::ACCESS_CONTROL_ALLOW_ORIGIN],
1860            "http://example.com"
1861        );
1862        assert!(!internal.headers.contains_key("x-upstream"));
1863
1864        let methods: Vec<_> = upstream.requests().into_iter().map(|request| request.method).collect();
1865        assert_eq!(methods, [Method::OPTIONS, Method::POST]);
1866
1867        servers.shutdown().await;
1868    }
1869
1870    #[tokio::test]
1871    async fn build_fails_for_a_proxied_signal_without_a_proxy() {
1872        let supervisor = TestSupervisor::start("otlp-test").await;
1873        let result = supervisor
1874            .scope(
1875                TestServers::configuration()
1876                    .with_server_ids("http-proxied-without-proxy", "grpc-proxied-without-proxy")
1877                    .with_routes(OtlpRoutes {
1878                        logs: OtlpRoute::Proxied,
1879                        ..OtlpRoutes::ALL_INTERNAL
1880                    })
1881                    .build(
1882                        RecordingHandler::default(),
1883                        MemoryLimiter::noop(),
1884                        Metrics::for_tests(),
1885                        &tokio::runtime::Handle::current(),
1886                    ),
1887            )
1888            .await;
1889
1890        let error = result.expect_err("build should fail");
1891        assert_eq!(
1892            error.to_string(),
1893            "An OTLP signal is proxied, but no OTLP proxy is set."
1894        );
1895
1896        supervisor
1897            .shutdown()
1898            .await
1899            .expect("supervisor should shut down cleanly");
1900    }
1901
1902    #[tokio::test]
1903    async fn build_fails_for_a_proxied_signal_without_a_destination_for_its_protocol() {
1904        let upstream = FakeUpstream::tcp(http_ok).await;
1905        init_crypto_provider();
1906        let proxy = OtlpProxy::new(
1907            &OtlpProxyDestinations {
1908                grpc: None,
1909                http: Some(upstream.destination.clone()),
1910            },
1911            MetricsBuilder::default(),
1912        )
1913        .expect("proxy should build");
1914
1915        let supervisor = TestSupervisor::start("otlp-test").await;
1916        let result = supervisor
1917            .scope(
1918                TestServers::configuration()
1919                    .with_server_ids("http-proxied-without-destination", "grpc-proxied-without-destination")
1920                    .with_routes(OtlpRoutes {
1921                        logs: OtlpRoute::Proxied,
1922                        ..OtlpRoutes::ALL_INTERNAL
1923                    })
1924                    .with_proxy(proxy)
1925                    .build(
1926                        RecordingHandler::default(),
1927                        MemoryLimiter::noop(),
1928                        Metrics::for_tests(),
1929                        &tokio::runtime::Handle::current(),
1930                    ),
1931            )
1932            .await;
1933
1934        let error = result.expect_err("build should fail");
1935        assert_eq!(
1936            error.to_string(),
1937            "An OTLP signal is proxied over gRPC, but the OTLP proxy has no gRPC destination."
1938        );
1939
1940        supervisor
1941            .shutdown()
1942            .await
1943            .expect("supervisor should shut down cleanly");
1944    }
1945}