MCPcopy
hub / github.com/caddyserver/caddy / TestMetricsCardinalityProtection

Function TestMetricsCardinalityProtection

modules/caddyhttp/metrics_test.go:377–432  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

375}
376
377func TestMetricsCardinalityProtection(t *testing.T) {
378 ctx, _ := caddy.NewContext(caddy.Context{Context: context.Background()})
379
380 // Test 1: Without AllowCatchAllHosts, arbitrary hosts should be mapped to "_other"
381 metrics := &Metrics{
382 PerHost: true,
383 ObserveCatchallHosts: false, // Default - should map unknown hosts to "_other"
384 init: sync.Once{},
385 httpMetrics: &httpMetrics{},
386 allowedHosts: make(map[string]struct{}),
387 }
388
389 // Add one allowed host
390 metrics.allowedHosts["allowed.com"] = struct{}{}
391
392 h := HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
393 w.Write([]byte("hello"))
394 return nil
395 })
396
397 ih := newMetricsInstrumentedRoute(ctx, "test", h, metrics)
398
399 // Test request to allowed host
400 r1 := httptest.NewRequest("GET", "http://allowed.com/", nil)
401 r1.Host = "allowed.com"
402 w1 := httptest.NewRecorder()
403 ih.ServeHTTP(w1, r1)
404
405 // Test request to unknown host (should be mapped to "_other")
406 r2 := httptest.NewRequest("GET", "http://attacker.com/", nil)
407 r2.Host = "attacker.com"
408 w2 := httptest.NewRecorder()
409 ih.ServeHTTP(w2, r2)
410
411 // Test request to another unknown host (should also be mapped to "_other")
412 r3 := httptest.NewRequest("GET", "http://evil.com/", nil)
413 r3.Host = "evil.com"
414 w3 := httptest.NewRecorder()
415 ih.ServeHTTP(w3, r3)
416
417 // Check that metrics contain:
418 // - One entry for "allowed.com"
419 // - One entry for "_other" (aggregating attacker.com and evil.com)
420 expected := `
421 # HELP caddy_http_requests_total Counter of HTTP(S) requests made.
422 # TYPE caddy_http_requests_total counter
423 caddy_http_requests_total{handler="test",host="_other",server="UNKNOWN"} 2
424 caddy_http_requests_total{handler="test",host="allowed.com",server="UNKNOWN"} 1
425 `
426
427 if err := testutil.GatherAndCompare(ctx.GetMetricsRegistry(), strings.NewReader(expected),
428 "caddy_http_requests_total",
429 ); err != nil {
430 t.Errorf("Cardinality protection test failed: %s", err)
431 }
432}
433
434func TestMetricsHTTPSCatchAll(t *testing.T) {

Callers

nothing calls this directly

Calls 5

GetMetricsRegistryMethod · 0.95
HandlerFuncFuncType · 0.85
ServeHTTPMethod · 0.65
WriteMethod · 0.45

Tested by

no test coverage detected