From d31460f7931a3ee46f14d465afd81383c4b68c8a Mon Sep 17 00:00:00 2001 From: Andrew Dunham Date: Wed, 27 Sep 2023 12:07:49 -0400 Subject: [PATCH] net/portmapper: fix invalid UPnP metric name Fixes #9551 Signed-off-by: Andrew Dunham Change-Id: I06f3a15a668be621675be6cbc7e5bdcc006e8570 --- net/portmapper/portmapper.go | 11 ++++++++++- net/portmapper/portmapper_test.go | 11 +++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/net/portmapper/portmapper.go b/net/portmapper/portmapper.go index 880d9d486..3fde487cd 100644 --- a/net/portmapper/portmapper.go +++ b/net/portmapper/portmapper.go @@ -1040,7 +1040,16 @@ func getUPnPErrorsMetric(code int) *clientmetric.Metric { return mm } - mm = clientmetric.NewCounter(fmt.Sprintf("portmap_upnp_errors_with_code_%d", code)) + // Metric names cannot contain a hyphen, so we handle negative numbers + // by prefixing the name with a "minus_". + var codeStr string + if code < 0 { + codeStr = fmt.Sprintf("portmap_upnp_errors_with_code_minus_%d", -code) + } else { + codeStr = fmt.Sprintf("portmap_upnp_errors_with_code_%d", code) + } + + mm = clientmetric.NewCounter(codeStr) mak.Set(&metricUPnPErrorsByCode, code, mm) return mm } diff --git a/net/portmapper/portmapper_test.go b/net/portmapper/portmapper_test.go index 83a2afe66..575ddd6f1 100644 --- a/net/portmapper/portmapper_test.go +++ b/net/portmapper/portmapper_test.go @@ -124,3 +124,14 @@ func TestPCPIntegration(t *testing.T) { t.Errorf("got nil mapping after successful createOrGetMapping") } } + +// Test to ensure that metric names generated by this function do not contain +// invalid characters. +// +// See https://github.com/tailscale/tailscale/issues/9551 +func TestGetUPnPErrorsMetric(t *testing.T) { + // This will panic if the metric name is invalid. + getUPnPErrorsMetric(100) + getUPnPErrorsMetric(0) + getUPnPErrorsMetric(-100) +}