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 24 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
24 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
67c1704
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Oct 24, 2024
76807a3
Merge branch 'main' into add_max_redirects_confighttp
rogercoll Oct 28, 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: []
35 changes: 30 additions & 5 deletions config/confighttp/confighttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,11 @@ import (
"go.opentelemetry.io/collector/extension/auth"
)

const headerContentEncoding = "Content-Encoding"
const defaultMaxRequestBodySize = 20 * 1024 * 1024 // 20MiB
const (
atoulme marked this conversation as resolved.
Show resolved Hide resolved
headerContentEncoding = "Content-Encoding"
defaultMaxRequestBodySize = 20 * 1024 * 1024 // 20MiB
)

var defaultCompressionAlgorithms = []string{"", "gzip", "zstd", "zlib", "snappy", "deflate"}

// ClientConfig defines settings for creating an HTTP client.
Expand Down Expand Up @@ -102,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 @@ -238,12 +244,31 @@ 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
} else if *max == 0 {
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this case needed here? if max is set to 0, will the check at line 266 return on the first call the same as is this block here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Great catch! Actually, this branch is not needed and resulted in the same output when max_redirects was set to either 0 or 1. The max redirects function is always called when a redirect response is returned, meaning that at least one request has already been made. The variable via []*http.Request on line 265 will always be > 0.

If max_redirects is set to 0, the http client should not follow any redirect response (one request). If max_redirects is 1, only one redirect response should be followed (2 total requests). max_redirects = total_requests - 1

Fixed in c98fe0a

Thanks!

return func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
}
}

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

// Custom RoundTripper that adds headers.
type headerRoundTripper struct {
transport http.RoundTripper
Expand Down
99 changes: 93 additions & 6 deletions config/confighttp/confighttp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ import (
"go.opentelemetry.io/collector/internal/localhostgate"
)

type customRoundTripper struct {
}
type customRoundTripper struct{}
atoulme marked this conversation as resolved.
Show resolved Hide resolved

var _ http.RoundTripper = (*customRoundTripper)(nil)

Expand Down Expand Up @@ -219,7 +218,6 @@ func TestPartialHTTPClientSettings(t *testing.T) {
assert.EqualValues(t, 0, transport.MaxConnsPerHost)
assert.EqualValues(t, 90*time.Second, transport.IdleConnTimeout)
assert.EqualValues(t, false, transport.DisableKeepAlives)

atoulme marked this conversation as resolved.
Show resolved Hide resolved
})
}
}
Expand Down Expand Up @@ -335,6 +333,96 @@ 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: "Defined max redirects",
settings: ClientConfig{MaxRedirects: toIntPtr(5)},
expectedRequests: 5,
},
}

host := &mockHost{
atoulme marked this conversation as resolved.
Show resolved Hide resolved
ext: map[component.ID]component.Component{},
}

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(), host, 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 != "" {
assert.ErrorContains(t, err, test.expectedErrStr)
} else {
assert.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 Expand Up @@ -430,7 +518,8 @@ func TestHTTPClientSettingWithAuthConfig(t *testing.T) {
host: &mockHost{
ext: map[component.ID]component.Component{
mockID: &authtest.MockClient{
ResultRoundTripper: &customRoundTripper{}, MustError: true},
ResultRoundTripper: &customRoundTripper{}, MustError: true,
},
atoulme marked this conversation as resolved.
Show resolved Hide resolved
},
},
},
Expand Down Expand Up @@ -560,7 +649,6 @@ func TestHTTPServerWarning(t *testing.T) {
require.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), test.len)
})
}

atoulme marked this conversation as resolved.
Show resolved Hide resolved
}

func TestHttpReception(t *testing.T) {
Expand Down Expand Up @@ -1307,7 +1395,6 @@ func TestServerWithDecoder(t *testing.T) {
srv.Handler.ServeHTTP(response, req)
// verify
assert.Equal(t, response.Result().StatusCode, http.StatusOK)

atoulme marked this conversation as resolved.
Show resolved Hide resolved
}

func TestServerWithDecompression(t *testing.T) {
Expand Down
Loading