Debian Codegraph @

semconv/internal/v3/http_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package internal
5
6 import (
7 "net/http"
8 "net/http/httptest"
9 "net/url"
10 "strconv"
11 "testing"
12
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15
16 "go.opentelemetry.io/otel/attribute"
17 "go.opentelemetry.io/otel/codes"
18 )
19
20 var hc = &HTTPConv{
21 NetConv: nc,
22
23 EnduserIDKey: attribute.Key("enduser.id"),
24 HTTPClientIPKey: attribute.Key("http.client_ip"),
25 HTTPFlavorKey: attribute.Key("http.flavor"),
26 HTTPMethodKey: attribute.Key("http.method"),
27 HTTPRequestContentLengthKey: attribute.Key("http.request_content_length"),
28 HTTPResponseContentLengthKey: attribute.Key("http.response_content_length"),
29 HTTPRouteKey: attribute.Key("http.route"),
30 HTTPSchemeHTTP: attribute.String("http.scheme", "http"),
31 HTTPSchemeHTTPS: attribute.String("http.scheme", "https"),
32 HTTPStatusCodeKey: attribute.Key("http.status_code"),
33 HTTPTargetKey: attribute.Key("http.target"),
34 HTTPURLKey: attribute.Key("http.url"),
35 UserAgentOriginalKey: attribute.Key("user_agent.original"),
36 }
37
38 func TestHTTPClientResponse(t *testing.T) {
39 const stat, n = 201, 397
40 resp := &http.Response{
41 StatusCode: stat,
42 ContentLength: n,
43 }
44 got := hc.ClientResponse(resp)
45 assert.Equal(t, 2, cap(got), "slice capacity")
46 assert.ElementsMatch(t, []attribute.KeyValue{
47 attribute.Key("http.status_code").Int(stat),
48 attribute.Key("http.response_content_length").Int(n),
49 }, got)
50 }
51
52 func TestHTTPSClientRequest(t *testing.T) {
53 req := &http.Request{
54 Method: http.MethodGet,
55 URL: &url.URL{
56 Scheme: "https",
57 Host: "127.0.0.1:443",
58 Path: "/resource",
59 },
60 Proto: "HTTP/1.0",
61 ProtoMajor: 1,
62 ProtoMinor: 0,
63 }
64
65 assert.Equal(
66 t,
67 []attribute.KeyValue{
68 attribute.String("http.method", http.MethodGet),
69 attribute.String("http.flavor", "1.0"),
70 attribute.String("http.url", "https://127.0.0.1:443/resource"),
71 attribute.String("net.peer.name", "127.0.0.1"),
72 },
73 hc.ClientRequest(req),
74 )
75 }
76
77 func TestHTTPClientRequest(t *testing.T) {
78 const (
79 user = "alice"
80 n = 128
81 agent = "Go-http-client/1.1"
82 )
83 req := &http.Request{
84 Method: http.MethodGet,
85 URL: &url.URL{
86 Scheme: "http",
87 Host: "127.0.0.1:8080",
88 Path: "/resource",
89 },
90 Proto: "HTTP/1.0",
91 ProtoMajor: 1,
92 ProtoMinor: 0,
93 Header: http.Header{
94 "User-Agent": []string{agent},
95 },
96 ContentLength: n,
97 }
98 req.SetBasicAuth(user, "pswrd")
99
100 assert.Equal(
101 t,
102 []attribute.KeyValue{
103 attribute.String("http.method", http.MethodGet),
104 attribute.String("http.flavor", "1.0"),
105 attribute.String("http.url", "http://127.0.0.1:8080/resource"),
106 attribute.String("net.peer.name", "127.0.0.1"),
107 attribute.Int("net.peer.port", 8080),
108 attribute.String("user_agent.original", agent),
109 attribute.Int("http.request_content_length", n),
110 attribute.String("enduser.id", user),
111 },
112 hc.ClientRequest(req),
113 )
114 }
115
116 func TestHTTPClientRequestRequired(t *testing.T) {
117 req := new(http.Request)
118 var got []attribute.KeyValue
119 assert.NotPanics(t, func() { got = hc.ClientRequest(req) })
120 want := []attribute.KeyValue{
121 attribute.String("http.method", http.MethodGet),
122 attribute.String("http.flavor", ""),
123 attribute.String("http.url", ""),
124 attribute.String("net.peer.name", ""),
125 }
126 assert.Equal(t, want, got)
127 }
128
129 func TestHTTPServerRequest(t *testing.T) {
130 got := make(chan *http.Request, 1)
131 handler := func(w http.ResponseWriter, r *http.Request) {
132 got <- r
133 w.WriteHeader(http.StatusOK)
134 }
135
136 srv := httptest.NewServer(http.HandlerFunc(handler))
137 defer srv.Close()
138
139 srvURL, err := url.Parse(srv.URL)
140 require.NoError(t, err)
141 srvPort, err := strconv.ParseInt(srvURL.Port(), 10, 32)
142 require.NoError(t, err)
143
144 r, err := http.NewRequestWithContext(t.Context(), http.MethodGet, srv.URL, http.NoBody)
145 require.NoError(t, err)
146
147 resp, err := srv.Client().Do(r)
148 require.NoError(t, err)
149 require.NoError(t, resp.Body.Close())
150
151 req := <-got
152 peer, peerPort := splitHostPort(req.RemoteAddr)
153
154 const user = "alice"
155 req.SetBasicAuth(user, "pswrd")
156
157 const clientIP = "127.0.0.5"
158 req.Header.Add("X-Forwarded-For", clientIP)
159
160 assert.ElementsMatch(t,
161 []attribute.KeyValue{
162 attribute.String("http.method", http.MethodGet),
163 attribute.String("http.scheme", "http"),
164 attribute.String("http.flavor", "1.1"),
165 attribute.String("net.host.name", srvURL.Hostname()),
166 attribute.Int("net.host.port", int(srvPort)),
167 attribute.String("net.sock.peer.addr", peer),
168 attribute.Int("net.sock.peer.port", peerPort),
169 attribute.String("user_agent.original", "Go-http-client/1.1"),
170 attribute.String("enduser.id", user),
171 attribute.String("http.client_ip", clientIP),
172 },
173 hc.ServerRequest("", req))
174 }
175
176 func TestHTTPServerName(t *testing.T) {
177 req := new(http.Request)
178 var got []attribute.KeyValue
179 const (
180 host = "test.semconv.server"
181 port = 8080
182 )
183 portStr := strconv.Itoa(port)
184 server := host + ":" + portStr
185 assert.NotPanics(t, func() { got = hc.ServerRequest(server, req) })
186 assert.Contains(t, got, attribute.String("net.host.name", host))
187 assert.Contains(t, got, attribute.Int("net.host.port", port))
188
189 req = &http.Request{Host: "alt.host.name:" + portStr}
190 // The server parameter does not include a port, ServerRequest should use
191 // the port in the request Host field.
192 assert.NotPanics(t, func() { got = hc.ServerRequest(host, req) })
193 assert.Contains(t, got, attribute.String("net.host.name", host))
194 assert.Contains(t, got, attribute.Int("net.host.port", port))
195 }
196
197 func TestHTTPServerRequestFailsGracefully(t *testing.T) {
198 req := new(http.Request)
199 var got []attribute.KeyValue
200 assert.NotPanics(t, func() { got = hc.ServerRequest("", req) })
201 want := []attribute.KeyValue{
202 attribute.String("http.method", http.MethodGet),
203 attribute.String("http.scheme", "http"),
204 attribute.String("http.flavor", ""),
205 attribute.String("net.host.name", ""),
206 }
207 assert.ElementsMatch(t, want, got)
208 }
209
210 func TestMethod(t *testing.T) {
211 assert.Equal(t, attribute.String("http.method", http.MethodPost), hc.method(http.MethodPost))
212 assert.Equal(t, attribute.String("http.method", http.MethodGet), hc.method(""))
213 assert.Equal(t, attribute.String("http.method", "garbage"), hc.method("garbage"))
214 }
215
216 func TestScheme(t *testing.T) {
217 assert.Equal(t, attribute.String("http.scheme", "http"), hc.scheme(false))
218 assert.Equal(t, attribute.String("http.scheme", "https"), hc.scheme(true))
219 }
220
221 func TestProto(t *testing.T) {
222 tests := map[string]string{
223 "HTTP/1.0": "1.0",
224 "HTTP/1.1": "1.1",
225 "HTTP/2": "2.0",
226 "HTTP/3": "3.0",
227 "SPDY": "SPDY",
228 "QUIC": "QUIC",
229 "other": "other",
230 }
231
232 for proto, want := range tests {
233 expect := attribute.String("http.flavor", want)
234 assert.Equal(t, expect, hc.proto(proto), proto)
235 }
236 }
237
238 func TestServerClientIP(t *testing.T) {
239 tests := []struct {
240 xForwardedFor string
241 want string
242 }{
243 {"", ""},
244 {"127.0.0.1", "127.0.0.1"},
245 {"127.0.0.1,127.0.0.5", "127.0.0.1"},
246 }
247 for _, test := range tests {
248 got := serverClientIP(test.xForwardedFor)
249 assert.Equal(t, test.want, got, test.xForwardedFor)
250 }
251 }
252
253 func TestRequiredHTTPPort(t *testing.T) {
254 tests := []struct {
255 https bool
256 port int
257 want int
258 }{
259 {true, 443, -1},
260 {true, 80, 80},
261 {true, 8081, 8081},
262 {false, 443, 443},
263 {false, 80, -1},
264 {false, 8080, 8080},
265 }
266 for _, test := range tests {
267 got := requiredHTTPPort(test.https, test.port)
268 assert.Equalf(t, test.want, got, "HTTP: %t, Port: %d", test.https, test.port)
269 }
270 }
271
272 func TestFirstHostPort(t *testing.T) {
273 host, port := "127.0.0.1", 8080
274 hostport := "127.0.0.1:8080"
275 sources := [][]string{
276 {hostport},
277 {"", hostport},
278 {"", "", hostport},
279 {"", "", hostport, ""},
280 {"", "", hostport, "127.0.0.3:80"},
281 }
282
283 for _, src := range sources {
284 h, p := firstHostPort(src...)
285 assert.Equal(t, host, h, "%+v", src)
286 assert.Equal(t, port, p, "%+v", src)
287 }
288 }
289
290 func TestRequestHeader(t *testing.T) {
291 ips := []string{"127.0.0.5", "127.0.0.9"}
292 user := []string{"alice"}
293 h := http.Header{"ips": ips, "user": user}
294
295 got := hc.RequestHeader(h)
296 assert.Equal(t, 2, cap(got), "slice capacity")
297 assert.ElementsMatch(t, []attribute.KeyValue{
298 attribute.StringSlice("http.request.header.ips", ips),
299 attribute.StringSlice("http.request.header.user", user),
300 }, got)
301 }
302
303 func TestResponseHeader(t *testing.T) {
304 ips := []string{"127.0.0.5", "127.0.0.9"}
305 user := []string{"alice"}
306 h := http.Header{"ips": ips, "user": user}
307
308 got := hc.ResponseHeader(h)
309 assert.Equal(t, 2, cap(got), "slice capacity")
310 assert.ElementsMatch(t, []attribute.KeyValue{
311 attribute.StringSlice("http.response.header.ips", ips),
312 attribute.StringSlice("http.response.header.user", user),
313 }, got)
314 }
315
316 func TestClientStatus(t *testing.T) {
317 tests := []struct {
318 code int
319 stat codes.Code
320 msg bool
321 }{
322 {0, codes.Error, true},
323 {http.StatusContinue, codes.Unset, false},
324 {http.StatusSwitchingProtocols, codes.Unset, false},
325 {http.StatusProcessing, codes.Unset, false},
326 {http.StatusEarlyHints, codes.Unset, false},
327 {http.StatusOK, codes.Unset, false},
328 {http.StatusCreated, codes.Unset, false},
329 {http.StatusAccepted, codes.Unset, false},
330 {http.StatusNonAuthoritativeInfo, codes.Unset, false},
331 {http.StatusNoContent, codes.Unset, false},
332 {http.StatusResetContent, codes.Unset, false},
333 {http.StatusPartialContent, codes.Unset, false},
334 {http.StatusMultiStatus, codes.Unset, false},
335 {http.StatusAlreadyReported, codes.Unset, false},
336 {http.StatusIMUsed, codes.Unset, false},
337 {http.StatusMultipleChoices, codes.Unset, false},
338 {http.StatusMovedPermanently, codes.Unset, false},
339 {http.StatusFound, codes.Unset, false},
340 {http.StatusSeeOther, codes.Unset, false},
341 {http.StatusNotModified, codes.Unset, false},
342 {http.StatusUseProxy, codes.Unset, false},
343 {306, codes.Error, true},
344 {http.StatusTemporaryRedirect, codes.Unset, false},
345 {http.StatusPermanentRedirect, codes.Unset, false},
346 {http.StatusBadRequest, codes.Error, false},
347 {http.StatusUnauthorized, codes.Error, false},
348 {http.StatusPaymentRequired, codes.Error, false},
349 {http.StatusForbidden, codes.Error, false},
350 {http.StatusNotFound, codes.Error, false},
351 {http.StatusMethodNotAllowed, codes.Error, false},
352 {http.StatusNotAcceptable, codes.Error, false},
353 {http.StatusProxyAuthRequired, codes.Error, false},
354 {http.StatusRequestTimeout, codes.Error, false},
355 {http.StatusConflict, codes.Error, false},
356 {http.StatusGone, codes.Error, false},
357 {http.StatusLengthRequired, codes.Error, false},
358 {http.StatusPreconditionFailed, codes.Error, false},
359 {http.StatusRequestEntityTooLarge, codes.Error, false},
360 {http.StatusRequestURITooLong, codes.Error, false},
361 {http.StatusUnsupportedMediaType, codes.Error, false},
362 {http.StatusRequestedRangeNotSatisfiable, codes.Error, false},
363 {http.StatusExpectationFailed, codes.Error, false},
364 {http.StatusTeapot, codes.Error, false},
365 {http.StatusMisdirectedRequest, codes.Error, false},
366 {http.StatusUnprocessableEntity, codes.Error, false},
367 {http.StatusLocked, codes.Error, false},
368 {http.StatusFailedDependency, codes.Error, false},
369 {http.StatusTooEarly, codes.Error, false},
370 {http.StatusUpgradeRequired, codes.Error, false},
371 {http.StatusPreconditionRequired, codes.Error, false},
372 {http.StatusTooManyRequests, codes.Error, false},
373 {http.StatusRequestHeaderFieldsTooLarge, codes.Error, false},
374 {http.StatusUnavailableForLegalReasons, codes.Error, false},
375 {http.StatusInternalServerError, codes.Error, false},
376 {http.StatusNotImplemented, codes.Error, false},
377 {http.StatusBadGateway, codes.Error, false},
378 {http.StatusServiceUnavailable, codes.Error, false},
379 {http.StatusGatewayTimeout, codes.Error, false},
380 {http.StatusHTTPVersionNotSupported, codes.Error, false},
381 {http.StatusVariantAlsoNegotiates, codes.Error, false},
382 {http.StatusInsufficientStorage, codes.Error, false},
383 {http.StatusLoopDetected, codes.Error, false},
384 {http.StatusNotExtended, codes.Error, false},
385 {http.StatusNetworkAuthenticationRequired, codes.Error, false},
386 {600, codes.Error, true},
387 }
388
389 for _, test := range tests {
390 c, msg := hc.ClientStatus(test.code)
391 assert.Equal(t, test.stat, c)
392 if test.msg && msg == "" {
393 t.Errorf("expected non-empty message for %d", test.code)
394 } else if !test.msg && msg != "" {
395 t.Errorf("expected empty message for %d, got: %s", test.code, msg)
396 }
397 }
398 }
399
400 func TestServerStatus(t *testing.T) {
401 tests := []struct {
402 code int
403 stat codes.Code
404 msg bool
405 }{
406 {0, codes.Error, true},
407 {http.StatusContinue, codes.Unset, false},
408 {http.StatusSwitchingProtocols, codes.Unset, false},
409 {http.StatusProcessing, codes.Unset, false},
410 {http.StatusEarlyHints, codes.Unset, false},
411 {http.StatusOK, codes.Unset, false},
412 {http.StatusCreated, codes.Unset, false},
413 {http.StatusAccepted, codes.Unset, false},
414 {http.StatusNonAuthoritativeInfo, codes.Unset, false},
415 {http.StatusNoContent, codes.Unset, false},
416 {http.StatusResetContent, codes.Unset, false},
417 {http.StatusPartialContent, codes.Unset, false},
418 {http.StatusMultiStatus, codes.Unset, false},
419 {http.StatusAlreadyReported, codes.Unset, false},
420 {http.StatusIMUsed, codes.Unset, false},
421 {http.StatusMultipleChoices, codes.Unset, false},
422 {http.StatusMovedPermanently, codes.Unset, false},
423 {http.StatusFound, codes.Unset, false},
424 {http.StatusSeeOther, codes.Unset, false},
425 {http.StatusNotModified, codes.Unset, false},
426 {http.StatusUseProxy, codes.Unset, false},
427 {306, codes.Error, true},
428 {http.StatusTemporaryRedirect, codes.Unset, false},
429 {http.StatusPermanentRedirect, codes.Unset, false},
430 {http.StatusBadRequest, codes.Unset, false},
431 {http.StatusUnauthorized, codes.Unset, false},
432 {http.StatusPaymentRequired, codes.Unset, false},
433 {http.StatusForbidden, codes.Unset, false},
434 {http.StatusNotFound, codes.Unset, false},
435 {http.StatusMethodNotAllowed, codes.Unset, false},
436 {http.StatusNotAcceptable, codes.Unset, false},
437 {http.StatusProxyAuthRequired, codes.Unset, false},
438 {http.StatusRequestTimeout, codes.Unset, false},
439 {http.StatusConflict, codes.Unset, false},
440 {http.StatusGone, codes.Unset, false},
441 {http.StatusLengthRequired, codes.Unset, false},
442 {http.StatusPreconditionFailed, codes.Unset, false},
443 {http.StatusRequestEntityTooLarge, codes.Unset, false},
444 {http.StatusRequestURITooLong, codes.Unset, false},
445 {http.StatusUnsupportedMediaType, codes.Unset, false},
446 {http.StatusRequestedRangeNotSatisfiable, codes.Unset, false},
447 {http.StatusExpectationFailed, codes.Unset, false},
448 {http.StatusTeapot, codes.Unset, false},
449 {http.StatusMisdirectedRequest, codes.Unset, false},
450 {http.StatusUnprocessableEntity, codes.Unset, false},
451 {http.StatusLocked, codes.Unset, false},
452 {http.StatusFailedDependency, codes.Unset, false},
453 {http.StatusTooEarly, codes.Unset, false},
454 {http.StatusUpgradeRequired, codes.Unset, false},
455 {http.StatusPreconditionRequired, codes.Unset, false},
456 {http.StatusTooManyRequests, codes.Unset, false},
457 {http.StatusRequestHeaderFieldsTooLarge, codes.Unset, false},
458 {http.StatusUnavailableForLegalReasons, codes.Unset, false},
459 {http.StatusInternalServerError, codes.Error, false},
460 {http.StatusNotImplemented, codes.Error, false},
461 {http.StatusBadGateway, codes.Error, false},
462 {http.StatusServiceUnavailable, codes.Error, false},
463 {http.StatusGatewayTimeout, codes.Error, false},
464 {http.StatusHTTPVersionNotSupported, codes.Error, false},
465 {http.StatusVariantAlsoNegotiates, codes.Error, false},
466 {http.StatusInsufficientStorage, codes.Error, false},
467 {http.StatusLoopDetected, codes.Error, false},
468 {http.StatusNotExtended, codes.Error, false},
469 {http.StatusNetworkAuthenticationRequired, codes.Error, false},
470 {600, codes.Error, true},
471 }
472
473 for _, test := range tests {
474 c, msg := hc.ServerStatus(test.code)
475 assert.Equal(t, test.stat, c)
476 if test.msg && msg == "" {
477 t.Errorf("expected non-empty message for %d", test.code)
478 } else if !test.msg && msg != "" {
479 t.Errorf("expected empty message for %d, got: %s", test.code, msg)
480 }
481 }
482 }