Skip to content

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

Merged
kvaps merged 2 commits intocozystack:mainfrom
tym83:fix/telemetry-handler-security
Apr 17, 2026
Merged

fix: prevent body DoS and Prometheus label injection in telemetry handler#4
kvaps merged 2 commits intocozystack:mainfrom
tym83:fix/telemetry-handler-security

Conversation

@tym83
Copy link
Copy Markdown
Contributor

@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

Summary by CodeRabbit

  • Bug Fixes
    • Implemented a 10 MB size limit for incoming telemetry request bodies to prevent resource exhaustion.
    • Enhanced cluster ID header validation with stricter format requirements and more descriptive error messages for invalid or missing values.
    • Improved error handling to gracefully manage oversized requests.

- 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

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

The main.go file adds telemetry request validation and safety constraints. A 10 MB body size limit is enforced via http.MaxBytesReader, a isValidClusterID function validates the X-Cluster-ID header using alphanumeric and specific special character rules, and error handling now detects and logs oversized request bodies with the errors package.

Changes

Cohort / File(s) Summary
Telemetry Request Safety
main.go
Added maxTelemetryBodySize constant and http.MaxBytesReader to limit incoming request bodies to 10 MB. Introduced isValidClusterID() to validate X-Cluster-ID header format (rejects empty, >253 chars, invalid characters). Enhanced error handling with errors.As() to detect http.MaxBytesError and log early exits. Updated handleTelemetry validation to reject invalid or missing cluster IDs.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 Hops with glee, a guardian's care,
Bounds are set with validation fair,
Ten megs max, no oversized feast,
Cluster IDs checked (at the least),
Safety guards our telemetry streams! 🛡️

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main security fixes in the changeset: body DoS prevention via MaxBytesReader and Prometheus label injection prevention via X-Cluster-ID validation.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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.

Comment thread main.go
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 thread main.go
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.

When io.ReadAll returns *http.MaxBytesError, http.Server has already sent
the 413 response. Writing another http.Error produces a "superfluous
response.WriteHeader" log. Detect the specific error via errors.As and
return without writing again.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
@kvaps kvaps merged commit 3c061c5 into cozystack:main Apr 17, 2026
1 of 2 checks passed
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.

2 participants