Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(confighttp): add max_redirects configuration option #10877

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
1b19038
feat(confighttp): add max_redirects configuration option
rogercoll Aug 13, 2024
cc94080
chore: fix linter
rogercoll Aug 13, 2024
26bd593
rollback auto formatting changes
rogercoll Aug 14, 2024
af76a71
use componenttest for nop testint host
rogercoll Aug 14, 2024
87d151e
docs: add max_redirects confighttp option
rogercoll Aug 14, 2024
4ca354e
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Aug 14, 2024
ea719b5
chore: rollback removed space
rogercoll Aug 14, 2024
c502bb3
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Aug 14, 2024
ed51bde
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Aug 20, 2024
5001cda
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Aug 22, 2024
a3bf503
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Aug 23, 2024
4aefcbb
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Aug 26, 2024
b96ecc1
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Aug 29, 2024
e434e4b
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Sep 12, 2024
b985772
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Sep 16, 2024
4033e56
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Sep 18, 2024
77008ab
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Sep 19, 2024
18d431d
fix: use require for error test cases
rogercoll Sep 19, 2024
aef83ac
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Sep 22, 2024
c98fe0a
fix: match max redirects with total requests
rogercoll Sep 22, 2024
a038f96
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Oct 5, 2024
4ca761b
Update config/confighttp/confighttp.go
rogercoll Oct 8, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .chloggen/add_max_redirects_confighttp.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: 'enhancement'

# The name of the component, or a single word describing the area of concern, (e.g. otlpreceiver)
component: confighttp

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Add the max_redirects configuration option

# One or more tracking issues or pull requests related to the change
issues: [10870]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:

# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: []
2 changes: 2 additions & 0 deletions config/confighttp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ README](../configtls/README.md).
- [`http2_ping_timeout`](https://pkg.go.dev/golang.org/x/net/http2#Transport)
- [`cookies`](https://pkg.go.dev/net/http#CookieJar)
- [`enabled`] if enabled, the client will store cookies from server responses and reuse them in subsequent requests.
- `max_redirects`: Maximum number of redirections to follow, if not defined, the [Client uses its default policy](https://pkg.go.dev/net/http#Client), which is to stop after 10 consecutive requests.

Example:

Expand All @@ -55,6 +56,7 @@ exporter:
compression: zstd
cookies:
enabled: true
max_redirects: 5
```

## Server Configuration
Expand Down
24 changes: 21 additions & 3 deletions config/confighttp/confighttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,9 @@ type ClientConfig struct {
HTTP2PingTimeout time.Duration `mapstructure:"http2_ping_timeout"`
// Cookies configures the cookie management of the HTTP client.
Cookies *CookiesConfig `mapstructure:"cookies"`

// Maximum number of redirections to follow, if not defined, the Client uses its default policy, which is to stop after 10 consecutive requests.
MaxRedirects *int `mapstructure:"max_redirects"`
Copy link
Member

Choose a reason for hiding this comment

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

I think we can even keep it int with 10 by default. That should be cleaner. The only problem is it'll be a significant breaking change (no redirects) for a component that doesn't use NewDefaultClientConfig, but I don't think we have any of those in contrib. Maybe we can check... All components should use that anyway. WDYT?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I am totally open to adding this, but I am concert about receivers initiating the config without using the default method (max_redirects will be set to 0). Also, the only difference is that maybe we should align with the Go library error message after 10 redirects:

func defaultCheckRedirect(req *Request, via []*Request) error {
	if len(via) >= 10 {
		return errors.New("stopped after 10 redirects")
	}
	return nil
}

There is this ongoing effort to use the NewDefaultClientConfig: open-telemetry/opentelemetry-collector-contrib#35457

}

// CookiesConfig defines the configuration of the HTTP client regarding cookies served by the server.
Expand Down Expand Up @@ -242,12 +245,27 @@ func (hcs *ClientConfig) ToClient(ctx context.Context, host component.Host, sett
}

return &http.Client{
Transport: clientTransport,
Timeout: hcs.Timeout,
Jar: jar,
CheckRedirect: makeCheckRedirect(hcs.MaxRedirects),
Transport: clientTransport,
Timeout: hcs.Timeout,
Jar: jar,
}, nil
}

// makeCheckRedirect checks if max redirects are exceeded
func makeCheckRedirect(max *int) func(*http.Request, []*http.Request) error {
if max == nil {
return nil
}

return func(_ *http.Request, via []*http.Request) error {
if len(via) > *max {
return http.ErrUseLastResponse
}
return nil
}
}

// Custom RoundTripper that adds headers.
type headerRoundTripper struct {
transport http.RoundTripper
Expand Down
91 changes: 91 additions & 0 deletions config/confighttp/confighttp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,97 @@ func TestHTTPClientSettingsError(t *testing.T) {
}
}

func TestMaxRedirects(t *testing.T) {
toIntPtr := func(i int) *int {
return &i
}
tests := []struct {
name string
settings ClientConfig
expectedRequests int
expectedErrStr string
}{
{
name: "No redirects config",
settings: ClientConfig{},
expectedRequests: 10,
// default client returns an error, custom implementations should return a ErrUseLastResponse which the internal http package will skip it to let the users select the previous response without closing the body.
expectedErrStr: "stopped after 10 redirects",
},
{
name: "Zero redirects",
settings: ClientConfig{MaxRedirects: toIntPtr(0)},
expectedRequests: 1,
},
{
name: "One redirect",
settings: ClientConfig{MaxRedirects: toIntPtr(1)},
expectedRequests: 2,
},
{
name: "Defined max redirects",
settings: ClientConfig{MaxRedirects: toIntPtr(5)},
expectedRequests: 6,
},
}

countRequests := func(resp *http.Response) int {
counter := 0
for resp != nil {
resp = resp.Request.Response
counter++
}
return counter
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
client, err := test.settings.ToClient(context.Background(), componenttest.NewNopHost(), componenttest.NewNopTelemetrySettings())
require.NoError(t, err)

hss := &ServerConfig{
Endpoint: "localhost:0",
}

ln, err := hss.ToListener(context.Background())
require.NoError(t, err)

url := fmt.Sprintf("http://%s", ln.Addr().String())

// always return a redirection to itself
s, err := hss.ToServer(
context.Background(),
componenttest.NewNopHost(),
componenttest.NewNopTelemetrySettings(),
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, url, http.StatusMovedPermanently)
}))
require.NoError(t, err)

go func() {
_ = s.Serve(ln)
}()

req, err := http.NewRequest(http.MethodOptions, url, nil)
require.NoError(t, err)
resp, err := client.Do(req)

if test.expectedErrStr != "" {
require.ErrorContains(t, err, test.expectedErrStr)
} else {
require.NoError(t, err)
}
assert.Equal(t, http.StatusMovedPermanently, resp.StatusCode)

defer resp.Body.Close()

require.Equal(t, test.expectedRequests, countRequests(resp))

require.NoError(t, s.Close())
})
}
}

func TestHTTPClientSettingWithAuthConfig(t *testing.T) {
tests := []struct {
name string
Expand Down
Loading