Skip to content

oauth: out_http: add user-agent option for oauth#11830

Open
rja5 wants to merge 4 commits into
fluent:masterfrom
rja5:add-oauth-user-agent
Open

oauth: out_http: add user-agent option for oauth#11830
rja5 wants to merge 4 commits into
fluent:masterfrom
rja5:add-oauth-user-agent

Conversation

@rja5
Copy link
Copy Markdown

@rja5 rja5 commented May 20, 2026

I added the ability to supply an optional User-Agent header to the HTTP OAuth call.

Fixes feature request/issue #11826


Enter [N/A] in the box, if an item is not applicable to your change.

Testing
Before we can approve your change; please submit the following in a comment:

  • [y] Example configuration file for the change
    add this to any HTTP OAuth config:

[OUTPUT]
oauth2.user_agent test-agent

  • [N/A] Debug log output from testing the change
  • [y] Attached Valgrind output that shows no leaks or memory corruption was found

If this is a change to packaging of containers or native binaries then please confirm it works for all targets.

  • [N/A] Run local packaging test showing all targets (including any new ones) build.
  • [N/A] Set ok-package-test label to test for all targets (requires maintainer to do).

Documentation

  • Documentation required for this feature

Backporting

  • [N/A] Backport to latest stable release.

Fluent Bit is licensed under Apache 2.0, by submitting this pull request I understand that this code will be released under the terms of that license.

Summary by CodeRabbit

  • New Features

    • Added an optional oauth2.user_agent setting to customize the User-Agent header sent with OAuth2 token requests; when unset, behavior is unchanged. Configured value is retained across configuration lifecycle operations.
  • Tests

    • Added tests verifying the User-Agent is omitted by default and included when configured; test suite updated to cover both scenarios.

Review Change Stack

@rja5 rja5 requested review from cosmo0920 and edsiper as code owners May 20, 2026 17:18
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 20, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds an optional oauth2.user_agent field to the OAuth2 config, exposes it in the HTTP plugin config, applies it as a User-Agent header on token requests when set, and adds tests that observe and assert the header presence/value.

Changes

OAuth2 User-Agent Configuration Support

Layer / File(s) Summary
OAuth2 config structure and lifecycle
include/fluent-bit/flb_oauth2.h, src/flb_oauth2.c
flb_oauth2_config gains a user_agent field that is initialized to NULL, cloned with allocation-failure handling, and freed on config destruction.
HTTP plugin configuration
plugins/out_http/http.c
The HTTP output plugin's config map now exposes oauth2.user_agent as a configurable string property for setting the token request User-Agent header.
OAuth2 token request integration
src/flb_oauth2.c
The oauth2_http_request function conditionally adds a User-Agent header to token POST requests when ctx->cfg.user_agent is configured.
Test infrastructure and verification
tests/internal/oauth2.c
Mock server now captures User-Agent headers; request_header_value() helper parses HTTP headers; refactored context creation supports optional user-agent; new test_user_agent_header_optional verifies behavior for configured and unconfigured cases.

Sequence Diagram(s)

sequenceDiagram
  participant Test as test_user_agent_header_optional
  participant Plugin as HTTP plugin (out_http)
  participant OAuth2 as oauth2_http_request
  participant Mock as oauth2_mock_server
  Test->>Plugin: create context (with/without oauth2.user_agent)
  Test->>OAuth2: initiate token request
  OAuth2->>Mock: POST /token (with optional User-Agent header)
  Mock->>OAuth2: respond with token
  Test->>Mock: assert token_user_agent_seen / token_user_agent value
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Suggested reviewers

  • edsiper
  • cosmo0920

Poem

🐰 I hopped to add a header line, soft as a note,
A tiny User-Agent tucked where token requests float,
Tests peek and whisper, "we saw the sign,"
Configured or not, the flow stays fine,
A rabbit's small cheer for a neat little change.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding a user-agent option for OAuth in the HTTP output plugin, which aligns with the primary purpose of this pull request.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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

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

🧹 Nitpick comments (3)
tests/internal/oauth2.c (1)

157-190: ⚡ Quick win

Make header extraction line-anchored and case-insensitive in the mock parser.

Current strstr(request, header_name) can match unintended substrings and depends on exact casing. Parsing header lines explicitly will make the test less brittle.

Proposed parser hardening diff
 static int request_header_value(const char *request, const char *header_name,
                                 char *out, size_t out_size)
 {
     int header_len;
+    const char *line_start;
+    const char *line_end;
     const char *end;
     const char *start;
     size_t value_len;
 
-    start = strstr(request, header_name);
+    header_len = strlen(header_name);
+    line_start = request;
+    start = NULL;
+
+    while (line_start && *line_start != '\0') {
+        line_end = strstr(line_start, "\r\n");
+        if (!line_end) {
+            break;
+        }
+
+        if ((size_t) (line_end - line_start) >= (size_t) header_len &&
+            strncasecmp(line_start, header_name, header_len) == 0) {
+            start = line_start + header_len;
+            break;
+        }
+
+        line_start = line_end + 2;
+    }
+
     if (!start) {
         return -1;
     }
 
-    header_len = strlen(header_name);
-    start += header_len;
     while (*start == ' ') {
         start++;
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/internal/oauth2.c` around lines 157 - 190, The mock header parser
request_header_value uses strstr which can match mid-line and is case-sensitive;
change it to scan the request line-by-line and perform a case-insensitive,
line-anchored match for the header name (i.e., accept header at start of string
or immediately after "\r\n"), ensure you match header_name followed by ':'
(allow optional spaces), then capture the value up to the next "\r\n"; use a
case-insensitive compare like strncasecmp (or equivalent) against the header
name length and only accept the header when the following character is ':' to
avoid substring matches, then copy the trimmed value into out.
plugins/out_http/http.c (1)

746-750: ⚡ Quick win

Document the new oauth2.user_agent setting in HTTP output docs.

This is a user-facing config key; adding a docs entry/example in the HTTP output plugin docs will prevent discoverability gaps.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@plugins/out_http/http.c` around lines 746 - 750, Add a user-facing docs entry
for the new oauth2.user_agent config key (backing field oauth2_config.user_agent
in struct flb_out_http) to the HTTP output plugin configuration docs: describe
it as an optional string that sets the User-Agent header for OAuth2 token
requests (default: unset/null), include an example showing oauth2.user_agent =
"MyAgent/1.0" within the plugin config, and place it alongside other
OAuth2-related settings in the HTTP output plugin's config options and examples
so users can discover and copy it easily.
src/flb_oauth2.c (1)

1134-1140: ⚡ Quick win

Harden oauth2.user_agent against CR/LF before adding it as a header.

If oauth2.user_agent contains \r or \n, the outgoing request can become malformed and potentially inject unintended headers. Reject or ignore such values before flb_http_add_header.

Proposed hardening diff
-    if (ctx->cfg.user_agent) {
-        flb_http_add_header(c,
-                            "User-Agent",
-                            10,
-                            ctx->cfg.user_agent,
-                            flb_sds_len(ctx->cfg.user_agent));
-    }
+    if (ctx->cfg.user_agent) {
+        if (strpbrk(ctx->cfg.user_agent, "\r\n") != NULL) {
+            flb_warn("[oauth2] ignoring oauth2.user_agent: contains CR/LF");
+        }
+        else {
+            flb_http_add_header(c,
+                                "User-Agent",
+                                10,
+                                ctx->cfg.user_agent,
+                                flb_sds_len(ctx->cfg.user_agent));
+        }
+    }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/flb_oauth2.c` around lines 1134 - 1140, Check ctx->cfg.user_agent for CR
or LF characters before calling flb_http_add_header and skip adding the header
(or clear the value) if any '\r' or '\n' is found; update the code around the
existing flb_http_add_header call that uses ctx->cfg.user_agent to perform this
validation (e.g., inspect flb_sds or the string bytes) and only call
flb_http_add_header when the user_agent is free of CR/LF.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@plugins/out_http/http.c`:
- Around line 746-750: Add a user-facing docs entry for the new
oauth2.user_agent config key (backing field oauth2_config.user_agent in struct
flb_out_http) to the HTTP output plugin configuration docs: describe it as an
optional string that sets the User-Agent header for OAuth2 token requests
(default: unset/null), include an example showing oauth2.user_agent =
"MyAgent/1.0" within the plugin config, and place it alongside other
OAuth2-related settings in the HTTP output plugin's config options and examples
so users can discover and copy it easily.

In `@src/flb_oauth2.c`:
- Around line 1134-1140: Check ctx->cfg.user_agent for CR or LF characters
before calling flb_http_add_header and skip adding the header (or clear the
value) if any '\r' or '\n' is found; update the code around the existing
flb_http_add_header call that uses ctx->cfg.user_agent to perform this
validation (e.g., inspect flb_sds or the string bytes) and only call
flb_http_add_header when the user_agent is free of CR/LF.

In `@tests/internal/oauth2.c`:
- Around line 157-190: The mock header parser request_header_value uses strstr
which can match mid-line and is case-sensitive; change it to scan the request
line-by-line and perform a case-insensitive, line-anchored match for the header
name (i.e., accept header at start of string or immediately after "\r\n"),
ensure you match header_name followed by ':' (allow optional spaces), then
capture the value up to the next "\r\n"; use a case-insensitive compare like
strncasecmp (or equivalent) against the header name length and only accept the
header when the following character is ':' to avoid substring matches, then copy
the trimmed value into out.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b2d428ca-531a-4f6d-aef6-0e4d1640cd4e

📥 Commits

Reviewing files that changed from the base of the PR and between bcc2436 and ab7d19f.

📒 Files selected for processing (4)
  • include/fluent-bit/flb_oauth2.h
  • plugins/out_http/http.c
  • src/flb_oauth2.c
  • tests/internal/oauth2.c

@rja5
Copy link
Copy Markdown
Author

rja5 commented May 20, 2026

Added fluent-bit-docs pull request: fluent/fluent-bit-docs#2578

@rja5
Copy link
Copy Markdown
Author

rja5 commented May 20, 2026

Example conifig section:

[OUTPUT]
    Name  http
    Match cmgw.mis
    Host  collector.mis.lab.ppops.net
    Port  443
    tls   On
    URI   /v2/event/message
    compress gzip
    format json_lines
    oauth2.enable On
    oauth2.token_url https://example.oauth2/v1/token
    oauth2.client_id exampleClientId
    oauth2.client_secret exampleClientSecret
    oauth2.auth_method post
    oauth2.user_agent exampleUserAgent
    Json_Date_Key     false
    allow_duplicated_headers false
    Header        Content-Type text/plain

@rja5
Copy link
Copy Markdown
Author

rja5 commented May 20, 2026

valgrind output
valgrind_report.log

@rja5 rja5 force-pushed the add-oauth-user-agent branch from ab7d19f to 713d438 Compare May 21, 2026 04:33
@cosmo0920 cosmo0920 changed the title add user-agent option for oauth oauth: out_http: add user-agent option for oauth May 21, 2026
@cosmo0920
Copy link
Copy Markdown
Contributor

We need to split from the one commit into two or more commit to follow our commit linter:

❌ Commit 713d438591 failed:
Missing prefix in commit subject: 'add user-agent option for oauth'
Commit prefix validation failed.

This should be complained that your only one commit is not followed our commit guideline.
So, we have to follow our guideline like:

oauth2: Add a member of user_agent
out_http: Add a capability to handle user_agent option

Copy link
Copy Markdown

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

Caution

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

⚠️ Outside diff range comments (1)
tests/internal/oauth2.c (1)

515-541: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Move the opening brace to the next line.

Per the coding guidelines, function opening braces should be on the next line after the signature.

📐 Proposed fix
 static struct flb_oauth2 *create_oauth_ctx_with_user_agent(struct flb_config *config,
                                                            struct oauth2_mock_server *server,
                                                            int refresh_skew,
-                                                           const char *user_agent)
-{
+                                                           const char *user_agent)
+{
     struct flb_oauth2_config cfg;

As per coding guidelines: "Put function opening braces on the next line, formatted as: int fn(void)\n{ ... }"

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/internal/oauth2.c` around lines 515 - 541, The function declaration for
create_oauth_ctx_with_user_agent should follow the project's brace style by
placing the opening brace on the next line; edit the signature line for
create_oauth_ctx_with_user_agent(...) so the "{" is moved from the end of the
signature to its own following line, keeping the rest of the function body
(memset, cfg setup, flb_sds_printf, flb_oauth2_create_from_config,
flb_oauth2_config_destroy, return ctx) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@tests/internal/oauth2.c`:
- Around line 515-541: The function declaration for
create_oauth_ctx_with_user_agent should follow the project's brace style by
placing the opening brace on the next line; edit the signature line for
create_oauth_ctx_with_user_agent(...) so the "{" is moved from the end of the
signature to its own following line, keeping the rest of the function body
(memset, cfg setup, flb_sds_printf, flb_oauth2_create_from_config,
flb_oauth2_config_destroy, return ctx) unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1e3b2fb1-d223-4412-927b-0205786ce7af

📥 Commits

Reviewing files that changed from the base of the PR and between 0e12fd9 and 8d3e7cd.

📒 Files selected for processing (3)
  • plugins/out_http/http.c
  • src/flb_oauth2.c
  • tests/internal/oauth2.c

@rja5
Copy link
Copy Markdown
Author

rja5 commented May 21, 2026

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)

🤖 Prompt for all review comments with AI agents

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@tests/internal/oauth2.c`:
- Around line 515-541: The function declaration for
create_oauth_ctx_with_user_agent should follow the project's brace style by
placing the opening brace on the next line; edit the signature line for
create_oauth_ctx_with_user_agent(...) so the "{" is moved from the end of the
signature to its own following line, keeping the rest of the function body
(memset, cfg setup, flb_sds_printf, flb_oauth2_create_from_config,
flb_oauth2_config_destroy, return ctx) unchanged.

ℹ️ Review info

I don't see anything wrong with the code here.
The proposed fix is:

static struct flb_oauth2 *create_oauth_ctx_with_user_agent(struct flb_config *config,
                                                            struct oauth2_mock_server *server,
                                                            int refresh_skew,
-                                                           const char *user_agent)
-{
+                                                           const char *user_agent)
+{

Those are exactly the same.

@cosmo0920
Copy link
Copy Markdown
Contributor

cosmo0920 commented May 22, 2026

We don't want to contaminate test codes into implementation commits.
So, you need to split out_http commit because our commit linter still complains like as:

❌ Commit cd3f66479e failed:
Subject prefix 'out_http:' does not match files changed.
Expected one of: oauth2:, out_http:, tests:


Commit prefix validation failed.

@cosmo0920
Copy link
Copy Markdown
Contributor

cosmo0920 commented May 25, 2026

This commit 13c96e0 is still contaminated of the oauth2 related file.

oauth2 related files should be committed in this kind of commit: oauth2: Add user-agent member field

And we just need to include out_http only files' changes in out_http: prefixed commit.

❌ Commit 13c96e0979 failed:
Subject prefix 'out_http:' does not match files changed.
Expected one of: oauth2:, out_http:

rja5 added 3 commits May 24, 2026 21:19
Signed-off-by: rja5 <rallen99@gmail.com>
Signed-off-by: rja5 <rallen99@gmail.com>
Signed-off-by: rja5 <rallen99@gmail.com>
@rja5 rja5 force-pushed the add-oauth-user-agent branch from 24dad59 to 63c80b4 Compare May 25, 2026 03:34
@rja5
Copy link
Copy Markdown
Author

rja5 commented May 25, 2026

This commit 13c96e0 is still contaminated of the oauth2 related file.

oauth2 related files should be committed in this kind of commit: oauth2: Add user-agent member field

And we just need to include out_http only files' changes in out_http: prefixed commit.

❌ Commit 13c96e0979 failed:
Subject prefix 'out_http:' does not match files changed.
Expected one of: oauth2:, out_http:

Hopefully the newest one is correct.

Copy link
Copy Markdown
Contributor

@cosmo0920 cosmo0920 left a comment

Choose a reason for hiding this comment

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

The most of this PR looks good but I found an inappropriate addition.
So, could you address it?

Comment thread src/flb_oauth2.c Outdated
Signed-off-by: rja5 <rallen99@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants