Debian Codegraph @

semconv/internal/v2/http.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package internal provides common semconv functionality.
5 package internal // import "go.opentelemetry.io/otel/semconv/internal/v2"
6
7 import (
8 "fmt"
9 "net/http"
10 "strings"
11
12 "go.opentelemetry.io/otel/attribute"
13 "go.opentelemetry.io/otel/codes"
14 )
15
16 // HTTPConv are the HTTP semantic convention attributes defined for a version
17 // of the OpenTelemetry specification.
18 type HTTPConv struct {
19 NetConv *NetConv
20
21 EnduserIDKey attribute.Key
22 HTTPClientIPKey attribute.Key
23 HTTPFlavorKey attribute.Key
24 HTTPMethodKey attribute.Key
25 HTTPRequestContentLengthKey attribute.Key
26 HTTPResponseContentLengthKey attribute.Key
27 HTTPRouteKey attribute.Key
28 HTTPSchemeHTTP attribute.KeyValue
29 HTTPSchemeHTTPS attribute.KeyValue
30 HTTPStatusCodeKey attribute.Key
31 HTTPTargetKey attribute.Key
32 HTTPURLKey attribute.Key
33 HTTPUserAgentKey attribute.Key
34 }
35
36 // ClientResponse returns attributes for an HTTP response received by a client
37 // from a server. The following attributes are returned if the related values
38 // are defined in resp: "http.status.code", "http.response_content_length".
39 //
40 // This does not add all OpenTelemetry required attributes for an HTTP event,
41 // it assumes ClientRequest was used to create the span with a complete set of
42 // attributes. If a complete set of attributes can be generated using the
43 // request contained in resp. For example:
44 //
45 // append(ClientResponse(resp), ClientRequest(resp.Request)...)
46 func (c *HTTPConv) ClientResponse(resp *http.Response) []attribute.KeyValue {
47 var n int
48 if resp.StatusCode > 0 {
49 n++
50 }
51 if resp.ContentLength > 0 {
52 n++
53 }
54
55 attrs := make([]attribute.KeyValue, 0, n)
56 if resp.StatusCode > 0 {
57 attrs = append(attrs, c.HTTPStatusCodeKey.Int(resp.StatusCode))
58 }
59 if resp.ContentLength > 0 {
60 attrs = append(attrs, c.HTTPResponseContentLengthKey.Int(int(resp.ContentLength)))
61 }
62 return attrs
63 }
64
65 // ClientRequest returns attributes for an HTTP request made by a client. The
66 // following attributes are always returned: "http.url", "http.flavor",
67 // "http.method", "net.peer.name". The following attributes are returned if the
68 // related values are defined in req: "net.peer.port", "http.user_agent",
69 // "http.request_content_length", "enduser.id".
70 func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue {
71 n := 3 // URL, peer name, proto, and method.
72 var h string
73 if req.URL != nil {
74 h = req.URL.Host
75 }
76 peer, p := firstHostPort(h, req.Header.Get("Host"))
77 port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", p)
78 if port > 0 {
79 n++
80 }
81 useragent := req.UserAgent()
82 if useragent != "" {
83 n++
84 }
85 if req.ContentLength > 0 {
86 n++
87 }
88 userID, _, hasUserID := req.BasicAuth()
89 if hasUserID {
90 n++
91 }
92 attrs := make([]attribute.KeyValue, 0, n)
93
94 attrs = append(attrs, c.method(req.Method), c.proto(req.Proto))
95
96 var u string
97 if req.URL != nil {
98 // Remove any username/password info that may be in the URL.
99 userinfo := req.URL.User
100 req.URL.User = nil
101 u = req.URL.String()
102 // Restore any username/password info that was removed.
103 req.URL.User = userinfo
104 }
105 attrs = append(
106 attrs,
107 c.HTTPURLKey.String(u),
108 c.NetConv.PeerName(peer),
109 )
110 if port > 0 {
111 attrs = append(attrs, c.NetConv.PeerPort(port))
112 }
113
114 if useragent != "" {
115 attrs = append(attrs, c.HTTPUserAgentKey.String(useragent))
116 }
117
118 if l := req.ContentLength; l > 0 {
119 attrs = append(attrs, c.HTTPRequestContentLengthKey.Int64(l))
120 }
121
122 if hasUserID {
123 attrs = append(attrs, c.EnduserIDKey.String(userID))
124 }
125
126 return attrs
127 }
128
129 // ServerRequest returns attributes for an HTTP request received by a server.
130 //
131 // The server must be the primary server name if it is known. For example this
132 // would be the ServerName directive
133 // (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache
134 // server, and the server_name directive
135 // (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an
136 // nginx server. More generically, the primary server name would be the host
137 // header value that matches the default virtual host of an HTTP server. It
138 // should include the host identifier and if a port is used to route to the
139 // server that port identifier should be included as an appropriate port
140 // suffix.
141 //
142 // If the primary server name is not known, server should be an empty string.
143 // The req Host will be used to determine the server instead.
144 //
145 // The following attributes are always returned: "http.method", "http.scheme",
146 // "http.flavor", "http.target", "net.host.name". The following attributes are
147 // returned if they related values are defined in req: "net.host.port",
148 // "net.sock.peer.addr", "net.sock.peer.port", "http.user_agent", "enduser.id",
149 // "http.client_ip".
150 func (c *HTTPConv) ServerRequest(server string, req *http.Request) []attribute.KeyValue {
151 // TODO: This currently does not add the specification required
152 // `http.target` attribute. It has too high of a cardinality to safely be
153 // added. An alternate should be added, or this comment removed, when it is
154 // addressed by the specification. If it is ultimately decided to continue
155 // not including the attribute, the HTTPTargetKey field of the HTTPConv
156 // should be removed as well.
157
158 n := 4 // Method, scheme, proto, and host name.
159 var host string
160 var p int
161 if server == "" {
162 host, p = splitHostPort(req.Host)
163 } else {
164 // Prioritize the primary server name.
165 host, p = splitHostPort(server)
166 if p < 0 {
167 _, p = splitHostPort(req.Host)
168 }
169 }
170 hostPort := requiredHTTPPort(req.TLS != nil, p)
171 if hostPort > 0 {
172 n++
173 }
174 peer, peerPort := splitHostPort(req.RemoteAddr)
175 if peer != "" {
176 n++
177 if peerPort > 0 {
178 n++
179 }
180 }
181 useragent := req.UserAgent()
182 if useragent != "" {
183 n++
184 }
185 userID, _, hasUserID := req.BasicAuth()
186 if hasUserID {
187 n++
188 }
189 clientIP := serverClientIP(req.Header.Get("X-Forwarded-For"))
190 if clientIP != "" {
191 n++
192 }
193 attrs := make([]attribute.KeyValue, 0, n)
194
195 attrs = append(
196 attrs,
197 c.method(req.Method),
198 c.scheme(req.TLS != nil),
199 c.proto(req.Proto),
200 c.NetConv.HostName(host),
201 )
202
203 if hostPort > 0 {
204 attrs = append(attrs, c.NetConv.HostPort(hostPort))
205 }
206
207 if peer != "" {
208 // The Go HTTP server sets RemoteAddr to "IP:port", this will not be a
209 // file-path that would be interpreted with a sock family.
210 attrs = append(attrs, c.NetConv.SockPeerAddr(peer))
211 if peerPort > 0 {
212 attrs = append(attrs, c.NetConv.SockPeerPort(peerPort))
213 }
214 }
215
216 if useragent != "" {
217 attrs = append(attrs, c.HTTPUserAgentKey.String(useragent))
218 }
219
220 if hasUserID {
221 attrs = append(attrs, c.EnduserIDKey.String(userID))
222 }
223
224 if clientIP != "" {
225 attrs = append(attrs, c.HTTPClientIPKey.String(clientIP))
226 }
227
228 return attrs
229 }
230
231 func (c *HTTPConv) method(method string) attribute.KeyValue {
232 if method == "" {
233 return c.HTTPMethodKey.String(http.MethodGet)
234 }
235 return c.HTTPMethodKey.String(method)
236 }
237
238 func (c *HTTPConv) scheme(https bool) attribute.KeyValue { // nolint:revive
239 if https {
240 return c.HTTPSchemeHTTPS
241 }
242 return c.HTTPSchemeHTTP
243 }
244
245 func (c *HTTPConv) proto(proto string) attribute.KeyValue {
246 switch proto {
247 case "HTTP/1.0":
248 return c.HTTPFlavorKey.String("1.0")
249 case "HTTP/1.1":
250 return c.HTTPFlavorKey.String("1.1")
251 case "HTTP/2":
252 return c.HTTPFlavorKey.String("2.0")
253 case "HTTP/3":
254 return c.HTTPFlavorKey.String("3.0")
255 default:
256 return c.HTTPFlavorKey.String(proto)
257 }
258 }
259
260 func serverClientIP(xForwardedFor string) string {
261 if idx := strings.Index(xForwardedFor, ","); idx >= 0 {
262 xForwardedFor = xForwardedFor[:idx]
263 }
264 return xForwardedFor
265 }
266
267 func requiredHTTPPort(https bool, port int) int { // nolint:revive
268 if https {
269 if port > 0 && port != 443 {
270 return port
271 }
272 } else {
273 if port > 0 && port != 80 {
274 return port
275 }
276 }
277 return -1
278 }
279
280 // Return the request host and port from the first non-empty source.
281 func firstHostPort(source ...string) (host string, port int) {
282 for _, hostport := range source {
283 host, port = splitHostPort(hostport)
284 if host != "" || port > 0 {
285 break
286 }
287 }
288 return host, port
289 }
290
291 // RequestHeader returns the contents of h as OpenTelemetry attributes.
292 func (c *HTTPConv) RequestHeader(h http.Header) []attribute.KeyValue {
293 return c.header("http.request.header", h)
294 }
295
296 // ResponseHeader returns the contents of h as OpenTelemetry attributes.
297 func (c *HTTPConv) ResponseHeader(h http.Header) []attribute.KeyValue {
298 return c.header("http.response.header", h)
299 }
300
301 func (*HTTPConv) header(prefix string, h http.Header) []attribute.KeyValue {
302 key := func(k string) attribute.Key {
303 k = strings.ToLower(k)
304 k = strings.ReplaceAll(k, "-", "_")
305 k = fmt.Sprintf("%s.%s", prefix, k)
306 return attribute.Key(k)
307 }
308
309 attrs := make([]attribute.KeyValue, 0, len(h))
310 for k, v := range h {
311 attrs = append(attrs, key(k).StringSlice(v))
312 }
313 return attrs
314 }
315
316 // ClientStatus returns a span status code and message for an HTTP status code
317 // value received by a client.
318 func (*HTTPConv) ClientStatus(code int) (codes.Code, string) {
319 stat, valid := validateHTTPStatusCode(code)
320 if !valid {
321 return stat, fmt.Sprintf("Invalid HTTP status code %d", code)
322 }
323 return stat, ""
324 }
325
326 // ServerStatus returns a span status code and message for an HTTP status code
327 // value returned by a server. Status codes in the 400-499 range are not
328 // returned as errors.
329 func (*HTTPConv) ServerStatus(code int) (codes.Code, string) {
330 stat, valid := validateHTTPStatusCode(code)
331 if !valid {
332 return stat, fmt.Sprintf("Invalid HTTP status code %d", code)
333 }
334
335 if code/100 == 4 {
336 return codes.Unset, ""
337 }
338 return stat, ""
339 }
340
341 type codeRange struct {
342 fromInclusive int
343 toInclusive int
344 }
345
346 func (r codeRange) contains(code int) bool {
347 return r.fromInclusive <= code && code <= r.toInclusive
348 }
349
350 var validRangesPerCategory = map[int][]codeRange{
351 1: {
352 {http.StatusContinue, http.StatusEarlyHints},
353 },
354 2: {
355 {http.StatusOK, http.StatusAlreadyReported},
356 {http.StatusIMUsed, http.StatusIMUsed},
357 },
358 3: {
359 {http.StatusMultipleChoices, http.StatusUseProxy},
360 {http.StatusTemporaryRedirect, http.StatusPermanentRedirect},
361 },
362 4: {
363 {http.StatusBadRequest, http.StatusTeapot}, // yes, teapot is so useful…
364 {http.StatusMisdirectedRequest, http.StatusUpgradeRequired},
365 {http.StatusPreconditionRequired, http.StatusTooManyRequests},
366 {http.StatusRequestHeaderFieldsTooLarge, http.StatusRequestHeaderFieldsTooLarge},
367 {http.StatusUnavailableForLegalReasons, http.StatusUnavailableForLegalReasons},
368 },
369 5: {
370 {http.StatusInternalServerError, http.StatusLoopDetected},
371 {http.StatusNotExtended, http.StatusNetworkAuthenticationRequired},
372 },
373 }
374
375 // validateHTTPStatusCode validates the HTTP status code and returns
376 // corresponding span status code. If the `code` is not a valid HTTP status
377 // code, returns span status Error and false.
378 func validateHTTPStatusCode(code int) (codes.Code, bool) {
379 category := code / 100
380 ranges, ok := validRangesPerCategory[category]
381 if !ok {
382 return codes.Error, false
383 }
384 ok = false
385 for _, crange := range ranges {
386 ok = crange.contains(code)
387 if ok {
388 break
389 }
390 }
391 if !ok {
392 return codes.Error, false
393 }
394 if category > 0 && category < 4 {
395 return codes.Unset, true
396 }
397 return codes.Error, true
398 }