Debian Codegraph @

config/confighttp/server.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package confighttp // import "go.opentelemetry.io/collector/config/confighttp"
5
6 import (
7 "context"
8 "crypto/tls"
9 "errors"
10 "io"
11 "net"
12 "net/http"
13 "time"
14
15 "github.com/rs/cors"
16 "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
17 "go.opentelemetry.io/otel"
18 "go.uber.org/zap"
19 "go.uber.org/zap/zapcore"
20 "golang.org/x/net/http2"
21
22 "go.opentelemetry.io/collector/component"
23 "go.opentelemetry.io/collector/config/configauth"
24 "go.opentelemetry.io/collector/config/confighttp/internal"
25 "go.opentelemetry.io/collector/config/configmiddleware"
26 "go.opentelemetry.io/collector/config/configopaque"
27 "go.opentelemetry.io/collector/config/configoptional"
28 "go.opentelemetry.io/collector/config/configtls"
29 "go.opentelemetry.io/collector/extension/extensionauth"
30 )
31
32 const defaultMaxRequestBodySize = 20 * 1024 * 1024 // 20MiB
33
34 // ServerConfig defines settings for creating an HTTP server.
35 type ServerConfig struct {
36 // Endpoint configures the listening address for the server.
37 Endpoint string `mapstructure:"endpoint,omitempty"`
38
39 // TLS struct exposes TLS client configuration.
40 TLS configoptional.Optional[configtls.ServerConfig] `mapstructure:"tls"`
41
42 // CORS configures the server for HTTP cross-origin resource sharing (CORS).
43 CORS configoptional.Optional[CORSConfig] `mapstructure:"cors"`
44
45 // Auth for this receiver
46 Auth configoptional.Optional[AuthConfig] `mapstructure:"auth,omitempty"`
47
48 // MaxRequestBodySize sets the maximum request body size in bytes. Default: 20MiB.
49 MaxRequestBodySize int64 `mapstructure:"max_request_body_size,omitempty"`
50
51 // IncludeMetadata propagates the client metadata from the incoming requests to the downstream consumers
52 IncludeMetadata bool `mapstructure:"include_metadata,omitempty"`
53
54 // Additional headers attached to each HTTP response sent to the client.
55 // Header values are opaque since they may be sensitive.
56 ResponseHeaders configopaque.MapList `mapstructure:"response_headers,omitempty"`
57
58 // CompressionAlgorithms configures the list of compression algorithms the server can accept. Default: ["", "gzip", "zstd", "zlib", "snappy", "deflate"]
59 CompressionAlgorithms []string `mapstructure:"compression_algorithms,omitempty"`
60
61 // ReadTimeout is the maximum duration for reading the entire
62 // request, including the body. A zero or negative value means
63 // there will be no timeout.
64 //
65 // Because ReadTimeout does not let Handlers make per-request
66 // decisions on each request body's acceptable deadline or
67 // upload rate, most users will prefer to use
68 // ReadHeaderTimeout. It is valid to use them both.
69 ReadTimeout time.Duration `mapstructure:"read_timeout,omitempty"`
70
71 // ReadHeaderTimeout is the amount of time allowed to read
72 // request headers. The connection's read deadline is reset
73 // after reading the headers and the Handler can decide what
74 // is considered too slow for the body. If ReadHeaderTimeout
75 // is zero, the value of ReadTimeout is used. If both are
76 // zero, there is no timeout.
77 ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout"`
78
79 // WriteTimeout is the maximum duration before timing out
80 // writes of the response. It is reset whenever a new
81 // request's header is read. Like ReadTimeout, it does not
82 // let Handlers make decisions on a per-request basis.
83 // A zero or negative value means there will be no timeout.
84 WriteTimeout time.Duration `mapstructure:"write_timeout"`
85
86 // IdleTimeout is the maximum amount of time to wait for the
87 // next request when keep-alives are enabled. If IdleTimeout
88 // is zero, the value of ReadTimeout is used. If both are
89 // zero, there is no timeout.
90 IdleTimeout time.Duration `mapstructure:"idle_timeout"`
91
92 // Middlewares are used to add custom functionality to the HTTP server.
93 // Middleware handlers are called in the order they appear in this list,
94 // with the first middleware becoming the outermost handler.
95 Middlewares []configmiddleware.Config `mapstructure:"middlewares,omitempty"`
96
97 // KeepAlivesEnabled controls whether HTTP keep-alives are enabled.
98 // By default, keep-alives are always enabled. Only very resource-constrained environments should disable them.
99 KeepAlivesEnabled bool `mapstructure:"keep_alives_enabled,omitempty"`
100 }
101
102 // NewDefaultServerConfig returns ServerConfig type object with default values.
103 // We encourage to use this function to create an object of ServerConfig.
104 func NewDefaultServerConfig() ServerConfig {
105 return ServerConfig{
106 WriteTimeout: 30 * time.Second,
107 ReadHeaderTimeout: 1 * time.Minute,
108 IdleTimeout: 1 * time.Minute,
109 KeepAlivesEnabled: true,
110 }
111 }
112
113 type AuthConfig struct {
114 // Auth for this receiver.
115 configauth.Config `mapstructure:",squash"`
116
117 // RequestParameters is a list of parameters that should be extracted from the request and added to the context.
118 // When a parameter is found in both the query string and the header, the value from the query string will be used.
119 RequestParameters []string `mapstructure:"request_params,omitempty"`
120 // prevent unkeyed literal initialization
121 _ struct{}
122 }
123
124 // ToListener creates a net.Listener.
125 func (sc *ServerConfig) ToListener(ctx context.Context) (net.Listener, error) {
126 listener, err := net.Listen("tcp", sc.Endpoint)
127 if err != nil {
128 return nil, err
129 }
130
131 if sc.TLS.HasValue() {
132 var tlsCfg *tls.Config
133 tlsCfg, err = sc.TLS.Get().LoadTLSConfig(ctx)
134 if err != nil {
135 return nil, err
136 }
137 tlsCfg.NextProtos = []string{http2.NextProtoTLS, "http/1.1"}
138 listener = tls.NewListener(listener, tlsCfg)
139 }
140
141 return listener, nil
142 }
143
144 // toServerOptions has options that change the behavior of the HTTP server
145 // returned by ServerConfig.ToServer().
146 type toServerOptions = internal.ToServerOptions
147
148 // ToServerOption is an option to change the behavior of the HTTP server
149 // returned by ServerConfig.ToServer().
150 type ToServerOption = internal.ToServerOption
151
152 // WithErrorHandler overrides the HTTP error handler that gets invoked
153 // when there is a failure inside httpContentDecompressor.
154 func WithErrorHandler(e func(w http.ResponseWriter, r *http.Request, errorMsg string, statusCode int)) ToServerOption {
155 return internal.ToServerOptionFunc(func(opts *toServerOptions) {
156 opts.ErrHandler = e
157 })
158 }
159
160 // WithDecoder provides support for additional decoders to be configured
161 // by the caller.
162 func WithDecoder(key string, dec func(body io.ReadCloser) (io.ReadCloser, error)) ToServerOption {
163 return internal.ToServerOptionFunc(func(opts *toServerOptions) {
164 if opts.Decoders == nil {
165 opts.Decoders = map[string]func(body io.ReadCloser) (io.ReadCloser, error){}
166 }
167 opts.Decoders[key] = dec
168 })
169 }
170
171 // ToServer creates an http.Server from settings object.
172 //
173 // To allow the configuration to reference middleware or authentication extensions,
174 // the `extensions` argument should be the output of `host.GetExtensions()`.
175 // It may also be `nil` in tests where no such extension is expected to be used.
176 func (sc *ServerConfig) ToServer(ctx context.Context, extensions map[component.ID]component.Component, settings component.TelemetrySettings, handler http.Handler, opts ...ToServerOption) (*http.Server, error) {
177 serverOpts := &toServerOptions{}
178 serverOpts.Apply(opts...)
179
180 if sc.MaxRequestBodySize <= 0 {
181 sc.MaxRequestBodySize = defaultMaxRequestBodySize
182 }
183
184 if sc.CompressionAlgorithms == nil {
185 sc.CompressionAlgorithms = defaultCompressionAlgorithms()
186 }
187
188 // Apply middlewares in reverse order so they execute in
189 // forward order. The first middleware runs after
190 // decompression, below, preceded by Auth, CORS, etc.
191 if len(sc.Middlewares) > 0 && extensions == nil {
192 return nil, errors.New("middlewares were configured but this component or its host does not support extensions")
193 }
194 for i := len(sc.Middlewares) - 1; i >= 0; i-- {
195 wrapper, err := sc.Middlewares[i].GetHTTPServerHandler(ctx, extensions)
196 // If we failed to get the middleware
197 if err != nil {
198 return nil, err
199 }
200 handler, err = wrapper(handler)
201 // If we failed to construct a wrapper
202 if err != nil {
203 return nil, err
204 }
205 }
206
207 handler = httpContentDecompressor(
208 handler,
209 sc.MaxRequestBodySize,
210 serverOpts.ErrHandler,
211 sc.CompressionAlgorithms,
212 serverOpts.Decoders,
213 )
214
215 if sc.MaxRequestBodySize > 0 {
216 handler = maxRequestBodySizeInterceptor(handler, sc.MaxRequestBodySize)
217 }
218
219 if sc.Auth.HasValue() {
220 if extensions == nil {
221 return nil, errors.New("authentication was configured but this component or its host does not support extensions")
222 }
223
224 auth := sc.Auth.Get()
225 server, err := auth.GetServerAuthenticator(ctx, extensions)
226 if err != nil {
227 return nil, err
228 }
229
230 handler = authInterceptor(handler, server, auth.RequestParameters, serverOpts)
231 }
232
233 if sc.CORS.HasValue() && len(sc.CORS.Get().AllowedOrigins) > 0 {
234 corsConfig := sc.CORS.Get()
235 co := cors.Options{
236 AllowedOrigins: corsConfig.AllowedOrigins,
237 AllowCredentials: true,
238 AllowedHeaders: corsConfig.AllowedHeaders,
239 MaxAge: corsConfig.MaxAge,
240 }
241 handler = cors.New(co).Handler(handler)
242 }
243 if sc.CORS.HasValue() && len(sc.CORS.Get().AllowedOrigins) == 0 && len(sc.CORS.Get().AllowedHeaders) > 0 {
244 settings.Logger.Warn("The CORS configuration specifies allowed headers but no allowed origins, and is therefore ignored.")
245 }
246
247 if sc.ResponseHeaders != nil {
248 handler = responseHeadersHandler(handler, sc.ResponseHeaders)
249 }
250
251 otelOpts := append(
252 []otelhttp.Option{
253 otelhttp.WithTracerProvider(settings.TracerProvider),
254 otelhttp.WithPropagators(otel.GetTextMapPropagator()),
255 otelhttp.WithSpanNameFormatter(func(_ string, r *http.Request) string {
256 // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#name:
257 //
258 // "HTTP span names SHOULD be {method} {target} if there is a (low-cardinality) target available.
259 // If there is no (low-cardinality) {target} available, HTTP span names SHOULD be {method}.
260 // ...
261 // Instrumentation MUST NOT default to using URI path as a {target}."
262 //
263 if r.Pattern != "" {
264 return r.Method + " " + r.Pattern
265 }
266 return r.Method
267 }),
268 otelhttp.WithMeterProvider(settings.MeterProvider),
269 },
270 serverOpts.OtelhttpOpts...)
271
272 // Enable OpenTelemetry observability plugin.
273 handler = otelhttp.NewHandler(handler, "", otelOpts...)
274
275 // wrap the current handler in an interceptor that will add client.Info to the request's context
276 handler = &clientInfoHandler{
277 next: handler,
278 includeMetadata: sc.IncludeMetadata,
279 }
280
281 errorLog, err := zap.NewStdLogAt(settings.Logger, zapcore.ErrorLevel)
282 if err != nil {
283 return nil, err // If an error occurs while creating the logger, return nil and the error
284 }
285
286 server := &http.Server{
287 Handler: handler,
288 ReadTimeout: sc.ReadTimeout,
289 ReadHeaderTimeout: sc.ReadHeaderTimeout,
290 WriteTimeout: sc.WriteTimeout,
291 IdleTimeout: sc.IdleTimeout,
292 ErrorLog: errorLog,
293 }
294
295 // Set keep-alives enabled/disabled
296 server.SetKeepAlivesEnabled(sc.KeepAlivesEnabled)
297
298 return server, err
299 }
300
301 func responseHeadersHandler(handler http.Handler, headers configopaque.MapList) http.Handler {
302 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
303 h := w.Header()
304
305 for k, v := range headers.Iter {
306 h.Set(k, string(v))
307 }
308
309 handler.ServeHTTP(w, r)
310 })
311 }
312
313 // CORSConfig configures a receiver for HTTP cross-origin resource sharing (CORS).
314 // See the underlying https://github.com/rs/cors package for details.
315 type CORSConfig struct {
316 // AllowedOrigins sets the allowed values of the Origin header for
317 // HTTP/JSON requests to an OTLP receiver. An origin may contain a
318 // wildcard (*) to replace 0 or more characters (e.g.,
319 // "http://*.domain.com", or "*" to allow any origin).
320 AllowedOrigins []string `mapstructure:"allowed_origins,omitempty"`
321
322 // AllowedHeaders sets what headers will be allowed in CORS requests.
323 // The Accept, Accept-Language, Content-Type, and Content-Language
324 // headers are implicitly allowed. If no headers are listed,
325 // X-Requested-With will also be accepted by default. Include "*" to
326 // allow any request header.
327 AllowedHeaders []string `mapstructure:"allowed_headers,omitempty"`
328
329 // MaxAge sets the value of the Access-Control-Max-Age response header.
330 // Set it to the number of seconds that browsers should cache a CORS
331 // preflight response for.
332 MaxAge int `mapstructure:"max_age,omitempty"`
333 // prevent unkeyed literal initialization
334 _ struct{}
335 }
336
337 // NewDefaultCORSConfig creates a default cross-origin resource sharing (CORS) configuration.
338 func NewDefaultCORSConfig() CORSConfig {
339 return CORSConfig{}
340 }
341
342 func authInterceptor(next http.Handler, server extensionauth.Server, requestParams []string, serverOpts *internal.ToServerOptions) http.Handler {
343 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
344 sources := r.Header
345 query := r.URL.Query()
346 for _, param := range requestParams {
347 if val, ok := query[param]; ok {
348 sources[param] = val
349 }
350 }
351 ctx, err := server.Authenticate(r.Context(), sources)
352 if err != nil {
353 if serverOpts.ErrHandler != nil {
354 serverOpts.ErrHandler(w, r, err.Error(), http.StatusUnauthorized)
355 } else {
356 http.Error(w, err.Error(), http.StatusUnauthorized)
357 }
358
359 return
360 }
361
362 next.ServeHTTP(w, r.WithContext(ctx))
363 })
364 }
365
366 func maxRequestBodySizeInterceptor(next http.Handler, maxRecvSize int64) http.Handler {
367 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
368 r.Body = http.MaxBytesReader(w, r.Body, maxRecvSize)
369 next.ServeHTTP(w, r)
370 })
371 }