Skip to content

Conversation

tothandras
Copy link
Contributor

@tothandras tothandras commented Aug 28, 2025

Summary by CodeRabbit

  • New Features
    • Added support for custom HTTP headers in the Prometheus input, enabling users to send headers (e.g., auth tokens, custom user agents) with all API requests.
  • Documentation
    • Updated configuration examples to demonstrate how to set optional headers in the Prometheus input.
    • Clarified that header configuration is optional and backward-compatible.

Copy link
Contributor

coderabbitai bot commented Aug 28, 2025

📝 Walkthrough

Walkthrough

Adds optional custom HTTP headers support to the Prometheus Benthos input by introducing a headers map in config, propagating it through initialization, and wrapping the HTTP client with a custom RoundTripper to inject headers into all Prometheus API requests. Existing scraping and scheduling logic remains unchanged.

Changes

Cohort / File(s) Summary of changes
Prometheus input headers support
`collector/benthos/input/prometheus.go`
Added optional headers field to config and input struct; parsed and propagated headers in newPrometheusInput; introduced headerRoundTripper to inject headers per request; conditionally wrapped Prometheus client transport to apply headers; updated YAML example documentation.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/collector-prometheus-headers

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@tothandras tothandras marked this pull request as ready for review August 28, 2025 20:50
@tothandras tothandras requested a review from a team as a code owner August 28, 2025 20:50
@tothandras tothandras added the release-note/feature Release note: Exciting New Features label Aug 28, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
collector/benthos/input/prometheus.go (1)

390-406: RoundTripper: add nil guards and ensure Header map exists.
Prevents panics if Header is nil and avoids NPE if next is unset.

 func (h *headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
   reqClone := req.Clone(req.Context())
 
+  if reqClone.Header == nil {
+    reqClone.Header = make(http.Header)
+  }
   for key, value := range h.headers {
     reqClone.Header.Set(key, value)
   }
 
-  return h.next.RoundTrip(reqClone)
+  next := h.next
+  if next == nil {
+    next = http.DefaultTransport
+  }
+  return next.RoundTrip(reqClone)
 }

I can add a small httptest validating header injection end-to-end.

🧹 Nitpick comments (2)
collector/benthos/input/prometheus.go (2)

65-67: Example: prefer env/secret over hardcoded credentials.
Use an env var in the example to discourage committing secrets.

-    headers:
-      Authorization: "Basic <base64 encoded credentials>"
+    headers:
+      Authorization: "Bearer ${PROMETHEUS_TOKEN}"

129-136: Header parsing LGTM; consider minimal validation.
Optionally warn on empty header keys/values to catch misconfigurations early.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ceaa4f8 and 2e5612b.

📒 Files selected for processing (1)
  • collector/benthos/input/prometheus.go (8 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Code Generators
  • GitHub Check: Analyze (go)
🔇 Additional comments (4)
collector/benthos/input/prometheus.go (4)

6-6: Import addition looks correct.


25-25: New config key constant is fine.


105-105: Struct field addition is appropriate.


214-214: Passing headers into the input is correct.

Comment on lines +53 to 59
service.NewStringMapField(fieldPrometheusHeaders).
Description("Optional HTTP headers to send with Prometheus queries. Useful for authentication or routing.").
Example(map[string]any{
"Authorization": "Basic <base64 encoded credentials>",
}).
Optional(),
).Example("Basic Configuration", "Collect Prometheus metrics with a scrape interval of 1 minute and a scrape offset of 30 seconds to account for delays in metric availability.", `
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Mark headers as sensitive to avoid leaking secrets.
If the Benthos service field API supports marking a map field as sensitive/redacted, please enable it; otherwise ensure configs aren’t logged verbatim and redact header values in any error messages.


🏁 Script executed:

#!/bin/bash
# Locate the constructor for StringMapField
rg -n "func NewStringMapField" -C3
# Inspect the StringMapField type for available methods
rg -n "type StringMapField" -C5
# Search for any sensitive/redaction support in the service package
rg -R "Sensitive" -n -C3 service
rg -R "Redact" -n -C3 service

Length of output: 943


🏁 Script executed:

#!/bin/bash
# Identify the collector directory
find . -maxdepth 2 -type d -name collector
# Locate the prometheus.go file
find . -type f -iname "prometheus.go"
# Identify the service package directory
find . -maxdepth 2 -type d -name service
# Search for NewStringMapField usage
grep -R "NewStringMapField" -n .
# Search for any map-field types and methods in service package
grep -R "MapField" -n service
# Look for methods containing 'Sensitive' or 'Redact'
grep -RE "(Sensitive|Redact)" -n service

Length of output: 462


🏁 Script executed:

#!/bin/bash
# Print the first 50 lines of go.mod to identify the Benthos service import path
sed -n '1,50p' go.mod

Length of output: 1844


🏁 Script executed:

#!/bin/bash
sed -n '1,50p' collector/benthos/input/prometheus.go

Length of output: 1585


🌐 Web query:

pkg.go.dev github.com/benthosdev/benthos/v4/public/service NewStringMapField

💡 Result:

Signature:
func NewStringMapField(name string) *ConfigField

Description:
Defines a config field that is an object (map) of arbitrary keys with string values. Use ParsedConfig.FieldStringMap(...) to extract the map from a parsed config. [1]

Sources:
[1] pkg.go.dev — github.com/benthosdev/benthos/v4/public/service (NewStringMapField, FieldStringMap).


Add .Secret() to the headers field definition
The Benthos service API’s ConfigField supports a Secret() method—chain .Secret() on the service.NewStringMapField(fieldPrometheusHeaders) call in collector/benthos/input/prometheus.go to mark header values as sensitive and ensure they’re redacted in logs and errors. (pkg.go.dev)

🤖 Prompt for AI Agents
In collector/benthos/input/prometheus.go around lines 53 to 59, the Prometheus
headers field uses service.NewStringMapField(fieldPrometheusHeaders) but does
not mark values as secrets; chain the .Secret() method onto the
NewStringMapField call (i.e., service.NewStringMapField(...).Secret()...) so
header values are treated as sensitive and will be redacted in logs and errors,
leaving the rest of the field builder chain (Description, Example, Optional)
unchanged.

Comment on lines +184 to 197
// Create Prometheus client with custom headers
clientConfig := api.Config{
Address: url,
})
}

if len(headers) > 0 {
clientConfig.RoundTripper = &headerRoundTripper{
next: api.DefaultRoundTripper,
headers: headers,
}
}

client, err := api.NewClient(clientConfig)
if err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Wrap RoundTripper defensively to allow future composition.
Use any pre-set RoundTripper as the next hop when present; fall back to the Prom client default.

- if len(headers) > 0 {
-   clientConfig.RoundTripper = &headerRoundTripper{
-     next:    api.DefaultRoundTripper,
-     headers: headers,
-   }
- }
+ if len(headers) > 0 {
+   next := clientConfig.RoundTripper
+   if next == nil {
+     next = api.DefaultRoundTripper
+   }
+   clientConfig.RoundTripper = &headerRoundTripper{
+     next:    next,
+     headers: headers,
+   }
+ }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Create Prometheus client with custom headers
clientConfig := api.Config{
Address: url,
})
}
if len(headers) > 0 {
clientConfig.RoundTripper = &headerRoundTripper{
next: api.DefaultRoundTripper,
headers: headers,
}
}
client, err := api.NewClient(clientConfig)
if err != nil {
// Create Prometheus client with custom headers
clientConfig := api.Config{
Address: url,
}
if len(headers) > 0 {
next := clientConfig.RoundTripper
if next == nil {
next = api.DefaultRoundTripper
}
clientConfig.RoundTripper = &headerRoundTripper{
next: next,
headers: headers,
}
}
client, err := api.NewClient(clientConfig)
if err != nil {
// ...
}
🤖 Prompt for AI Agents
In collector/benthos/input/prometheus.go around lines 184 to 197, the
headerRoundTripper is currently hard-coded to wrap api.DefaultRoundTripper;
instead, detect any existing clientConfig.RoundTripper and use it as the next
hop (falling back to api.DefaultRoundTripper if nil) so future composition
works. Change the construction to pick next := clientConfig.RoundTripper; if
next == nil { next = api.DefaultRoundTripper } and pass that next into
headerRoundTripper, leaving the headers logic unchanged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
release-note/feature Release note: Exciting New Features
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants