[bug-hunter] metricbeat openmetrics label prefix remover panics on short keys
- Dominant language
- Go
- Stars
- 12.7k
- Forks
- 5k
- Avg merge
- 2d 2h
- Merged PRs (30d)
- 364
Description
## Impact
`metricbeat/helper/openmetrics` can panic at runtime when removing label key prefixes, crashing processing for valid label maps. Any caller using `OpLabelKeyPrefixRemover` with a prefix shorter than 6 can trigger a deterministic `slice bounds out of range` panic when a label key length is between `len(prefix)` and `5`.
## Reproduction Steps
1. From repo root, create and run this minimal repro:
```go
// /tmp/gh-aw/agent/repro_openmetrics_panic.go
package main
import (
"github.com/elastic/elastic-agent-libs/mapstr"
"github.com/elastic/beats/v7/metricbeat/helper/openmetrics"
)
func main() {
labels := mapstr.M{"ex_j": "v"}
openmetrics.OpLabelKeyPrefixRemover("ex_").Process("", nil, labels)
}
```
2. Run:
```bash
go run /tmp/gh-aw/agent/repro_openmetrics_panic.go
```
## Expected vs Actual
**Expected:** Prefix-removal should compare using prefix length and return normally.
**Actual:** Process panics:
```text
panic: runtime error: slice bounds out of range [:6] with length 4
goroutine 1 [running]:
github.com/elastic/beats/v7/metricbeat/helper/openmetrics.opLabelKeyPrefixRemover.Process(...)
/home/runner/work/beats/beats/metricbeat/helper/openmetrics/metric.go:487
main.main()
/tmp/gh-aw/agent/repro_openmetrics_panic.go:12 +0x149
exit status 2
```
## Failing Test
```go
package main
import (
"github.com/elastic/elastic-agent-libs/mapstr"
"github.com/elastic/beats/v7/metricbeat/helper/openmetrics"
)
func main() {
labels := mapstr.M{"ex_j": "v"}
openmetrics.OpLabelKeyPrefixRemover("ex_").Process("", nil, labels)
}
```
## Evidence
- `metricbeat/helper/openmetrics/metric.go:484-488` currently does:
- `if len(k) < len(o.Prefix) { continue }`
- `if k[:6] == o.Prefix { ... }` ← fixed-width slice causes panic for short keys.
- The equivalent logic in prometheus was fixed to dynamic slicing in `metricbeat/helper/prometheus/metric.go:437-441`:
- `if k[:len(o.Prefix)] == o.Prefix { ... }`
- Recent fix commit `ff87e683af624c4bdac64602a36429080f90614b` addressed this class of bug in prometheus path but not openmetrics.
---
[What is this?](https://ela.st/github-ai-tools) | [From workflow: Bug Hunter](https://github.com/elastic/beats/actions/runs/27274981793)
Give us feedback! React with 🚀 if perfect, 👍 if helpful, 👎 if not.
> - [x] expires on Jun 17, 2026, 12:17 PM UTC
Contributor guide
Assessment
This issue has not been assessed yet.