Skip to content

fix: prevent body DoS and Prometheus label injection in telemetry handler#4

Open
tym83 wants to merge 1 commit intocozystack:mainfrom
tym83:fix/telemetry-handler-security
Open

fix: prevent body DoS and Prometheus label injection in telemetry handler#4
tym83 wants to merge 1 commit intocozystack:mainfrom
tym83:fix/telemetry-handler-security

Conversation

@tym83
Copy link
Copy Markdown

@tym83 tym83 commented Apr 8, 2026

Summary

Two security issues found during review of #3, both in the existing telemetry ingestion handler:

  • Memory exhaustion (DoS): io.ReadAll(r.Body) had no size limit — any client could POST an arbitrarily large body and exhaust pod memory. Fixed with http.MaxBytesReader capped at 10 MB.
  • Prometheus label injection: X-Cluster-ID header value was used directly as a Prometheus label value without validation. A value containing ", \n, or } would corrupt the text-format output forwarded to VictoriaMetrics (e.g. X-Cluster-ID: foo",injected="bar would produce broken metrics). Fixed by validating the header against [a-zA-Z0-9._-] (max 253 chars, matching Kubernetes naming rules) and rejecting with 400 otherwise.

Test plan

  • POST with a body > 10 MB returns 413
  • POST with X-Cluster-ID: foo"bar returns 400
  • POST with X-Cluster-ID: valid-cluster.name_01 is accepted as before

🤖 Generated with Claude Code

- Limit incoming POST body to 10 MB via http.MaxBytesReader to prevent
  memory exhaustion from arbitrarily large telemetry payloads
- Validate X-Cluster-ID against [a-zA-Z0-9._-] (max 253 chars) before
  use as a Prometheus label value; reject with 400 otherwise. Without
  this check a value containing '"' or newline corrupts the text-format
  output forwarded to VictoriaMetrics

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
-e
Signed-off-by: tym83 <6355522@gmail.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 8, 2026

Warning

Rate limit exceeded

@tym83 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 14 minutes and 0 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 14 minutes and 0 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 61f9959d-5494-4c32-b40d-bf68e44e1a6b

📥 Commits

Reviewing files that changed from the base of the PR and between d32e2b7 and 3c36863.

📒 Files selected for processing (1)
  • main.go
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a 10MB limit on telemetry request bodies and adds validation for the X-Cluster-ID header to prevent injection. The review feedback identifies a bug where exceeding the body size limit results in redundant error responses and suggests handling *http.MaxBytesError specifically. Additionally, it recommends using a regular expression for header validation to improve code idiomaticity and maintainability.

return
}

r.Body = http.MaxBytesReader(w, r.Body, maxTelemetryBodySize)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

Using http.MaxBytesReader is correct for limiting the request body size. However, the error handling for io.ReadAll on the subsequent lines is now incomplete. When the size limit is exceeded, io.ReadAll returns a *http.MaxBytesError. The http.Server automatically sends a 413 response in this case. The current code at lines 144-147 will then attempt to write another error response, which will cause a superfluous response.WriteHeader error log on the server.

You should specifically check for *http.MaxBytesError and return without writing another response.

body, err := io.ReadAll(r.Body)
if err != nil {
    var maxBytesErr *http.MaxBytesError
    if errors.As(err, &maxBytesErr) {
        // http.Server automatically sends a 413 response.
        // We don't need to write another error, just log and return.
        log.Printf("Request rejected: body exceeded %d bytes limit", maxBytesErr.Limit)
        return
    }
    log.Printf("Error reading request body: %v", err)
    http.Error(w, fmt.Sprintf("Error reading request: %v", err), http.StatusBadRequest)
    return
}

You will also need to import the errors package.

Comment on lines +113 to +124
func isValidClusterID(s string) bool {
if s == "" || len(s) > 253 {
return false
}
for _, c := range s {
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.') {
return false
}
}
return true
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For validating string formats like this, using a compiled regular expression is a common and idiomatic approach in Go. It's more declarative and can be easier to read and maintain than manual character-by-character iteration.

Consider replacing this function with a regex-based implementation for better readability and maintainability:

// At package level, to compile once:
// var isValidClusterIDRegexp = regexp.MustCompile(`^[a-zA-Z0-9._-]{1,253}$`)

func isValidClusterID(s string) bool {
	// Assumes isValidClusterIDRegexp is defined at package level
	// and 'regexp' package is imported.
	return isValidClusterIDRegexp.MatchString(s)
}

This would make the validation logic more concise and align with common Go practices for this type of task. You would need to add an import for the regexp package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant