Skip to content

Commit 9047c0e

Browse files
authored
[receiver/otlp, internal, featuregate] Add featuregate to switch to localhost defaults for server-like components (#8622)
**Description:** - Define `component.UseLocalHostAsDefaultHost` in the `internal/localhostgate` package. - Define `featuregate.ErrIsAlreadyRegistered` error, returned by `Register` when a gate is already registered. - Adds support for the localhost gate on the OTLP receiver. This PR does not remove the current warning in any way, we can remove this separately. **Link to tracking Issue:** Updates #8510 **Testing:** Adds unit tests **Documentation:** Document on OTLP receiver template and add related logging.
1 parent 5cf53ac commit 9047c0e

File tree

13 files changed

+220
-19
lines changed

13 files changed

+220
-19
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Use this changelog template to create an entry for release notes.
2+
3+
# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
4+
change_type: enhancement
5+
6+
# The name of the component, or a single word describing the area of concern, (e.g. otlpreceiver)
7+
component: component
8+
9+
# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
10+
note: "Add `component.UseLocalHostAsDefaultHost` feature gate that changes default endpoints from 0.0.0.0 to localhost"
11+
12+
# One or more tracking issues or pull requests related to the change
13+
issues: [8510]
14+
15+
# (Optional) One or more lines of additional information to render under the primary note.
16+
# These lines will be padded with 2 spaces and then inserted directly into the document.
17+
# Use pipe (|) for multiline entries.
18+
subtext: |
19+
The only component in this repository affected by this is the OTLP receiver.
20+
# Optional: The change log or logs in which this entry should be included.
21+
# e.g. '[user]' or '[user, api]'
22+
# Include 'user' if the change is relevant to end users.
23+
# Include 'api' if there is a change to a library API.
24+
# Default: '[user]'
25+
change_logs: []
26+
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Use this changelog template to create an entry for release notes.
2+
3+
# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
4+
change_type: enhancement
5+
6+
# The name of the component, or a single word describing the area of concern, (e.g. otlpreceiver)
7+
component: featuregate
8+
9+
# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
10+
note: "Add the `featuregate.ErrAlreadyRegistered` error, which is returned by `featuregate.Registry`'s `Register` when adding a feature gate that is already registered."
11+
12+
# One or more tracking issues or pull requests related to the change
13+
issues: [8622]
14+
15+
# (Optional) One or more lines of additional information to render under the primary note.
16+
# These lines will be padded with 2 spaces and then inserted directly into the document.
17+
# Use pipe (|) for multiline entries.
18+
subtext: |
19+
Use `errors.Is` to check for this error.
20+
21+
# Optional: The change log or logs in which this entry should be included.
22+
# e.g. '[user]' or '[user, api]'
23+
# Include 'user' if the change is relevant to end users.
24+
# Include 'api' if there is a change to a library API.
25+
# Default: '[user]'
26+
change_logs: [api]

config/internal/go.mod

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,30 @@ go 1.20
44

55
require (
66
github.com/stretchr/testify v1.8.4
7+
go.opentelemetry.io/collector v0.92.0
78
go.uber.org/goleak v1.3.0
89
go.uber.org/zap v1.26.0
910
)
1011

1112
require (
1213
github.com/davecgh/go-spew v1.1.1 // indirect
13-
github.com/kr/pretty v0.3.1 // indirect
14+
github.com/hashicorp/go-version v1.6.0 // indirect
1415
github.com/pmezard/go-difflib v1.0.0 // indirect
15-
github.com/rogpeppe/go-internal v1.10.0 // indirect
16+
go.opentelemetry.io/collector/featuregate v1.0.1 // indirect
1617
go.uber.org/multierr v1.11.0 // indirect
17-
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
1818
gopkg.in/yaml.v3 v3.0.1 // indirect
1919
)
20+
21+
replace go.opentelemetry.io/collector => ../../
22+
23+
replace go.opentelemetry.io/collector/featuregate => ../../featuregate
24+
25+
replace go.opentelemetry.io/collector/confmap => ../../confmap
26+
27+
replace go.opentelemetry.io/collector/config/configtelemetry => ../configtelemetry
28+
29+
replace go.opentelemetry.io/collector/pdata => ../../pdata
30+
31+
replace go.opentelemetry.io/collector/consumer => ../../consumer
32+
33+
replace go.opentelemetry.io/collector/component => ../../component

config/internal/go.sum

Lines changed: 2 additions & 10 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

config/internal/warning.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ import (
99
"strings"
1010

1111
"go.uber.org/zap"
12+
13+
"go.opentelemetry.io/collector/internal/localhostgate"
1214
)
1315

1416
func shouldWarn(endpoint string) bool {
@@ -38,11 +40,12 @@ func shouldWarn(endpoint string) bool {
3840
func WarnOnUnspecifiedHost(logger *zap.Logger, endpoint string) {
3941
if shouldWarn(endpoint) {
4042
logger.Warn(
41-
"Using the 0.0.0.0 address exposes this server to every network interface, which may facilitate Denial of Service attacks",
43+
"Using the 0.0.0.0 address exposes this server to every network interface, which may facilitate Denial of Service attacks. Enable the feature gate to change the default and remove this warning.",
4244
zap.String(
4345
"documentation",
4446
"https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/security-best-practices.md#safeguards-against-denial-of-service-attacks",
4547
),
48+
zap.String("feature gate ID", localhostgate.UseLocalHostAsDefaultHostID),
4649
)
4750
}
4851
}

docs/security-best-practices.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,8 @@ receivers:
148148
Generally, `localhost`-like addresses should be preferred over the 0.0.0.0 address.
149149
For more information, see [CWE-1327](https://cwe.mitre.org/data/definitions/1327.html).
150150

151+
To change the default endpoint to be `localhost`-bound in all components, enable the `component.UseLocalHostAsDefaultHost` feature gate. This feature gate will be enabled by default in the Collector in a future release.
152+
151153
## Processors
152154

153155
Processors sit between receivers and exporters. They are responsible for

featuregate/registry.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
package featuregate // import "go.opentelemetry.io/collector/featuregate"
55

66
import (
7+
"errors"
78
"fmt"
89
"net/url"
910
"regexp"
@@ -22,6 +23,11 @@ var (
2223
idRegexp = regexp.MustCompile(`^[0-9a-zA-Z\.]*$`)
2324
)
2425

26+
var (
27+
// ErrAlreadyRegistered is returned when adding a Gate that is already registered.
28+
ErrAlreadyRegistered = errors.New("gate is already registered")
29+
)
30+
2531
// GlobalRegistry returns the global Registry.
2632
func GlobalRegistry() *Registry {
2733
return globalRegistry
@@ -157,7 +163,7 @@ func (r *Registry) Register(id string, stage Stage, opts ...RegisterOption) (*Ga
157163
}
158164

159165
if _, loaded := r.gates.LoadOrStore(id, g); loaded {
160-
return nil, fmt.Errorf("attempted to add pre-existing gate %q", id)
166+
return nil, fmt.Errorf("failed to register %q: %w", id, ErrAlreadyRegistered)
161167
}
162168
return g, nil
163169
}

featuregate/registry_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ func TestRegistry(t *testing.T) {
3333
assert.False(t, g.IsEnabled())
3434

3535
_, err = r.Register(id, StageBeta)
36-
assert.Error(t, err)
36+
assert.ErrorIs(t, err, ErrAlreadyRegistered)
3737
assert.Panics(t, func() {
3838
r.MustRegister(id, StageBeta)
3939
})

internal/localhostgate/featuregate.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Copyright The OpenTelemetry Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
// package localhostgate defines a feature gate that controls whether server-like receivers and extensions use localhost as the default host for their endpoints.
5+
// This package is duplicated across core and contrib to avoid exposing the feature gate as part of the public API.
6+
// To do this we define a `registerOrLoad` helper and try to register the gate in both modules.
7+
// IMPORTANT NOTE: ANY CHANGES TO THIS PACKAGE MUST BE MIRRORED IN THE CONTRIB COUNTERPART.
8+
package localhostgate // import "go.opentelemetry.io/collector/internal/localhostgate"
9+
10+
import (
11+
"errors"
12+
"fmt"
13+
14+
"go.uber.org/zap"
15+
16+
"go.opentelemetry.io/collector/featuregate"
17+
)
18+
19+
const UseLocalHostAsDefaultHostID = "component.UseLocalHostAsDefaultHost"
20+
21+
// useLocalHostAsDefaultHostfeatureGate is the feature gate that controls whether
22+
// server-like receivers and extensions such as the OTLP receiver use localhost as the default host for their endpoints.
23+
var useLocalHostAsDefaultHostfeatureGate = mustRegisterOrLoad(
24+
featuregate.GlobalRegistry(),
25+
UseLocalHostAsDefaultHostID,
26+
featuregate.StageAlpha,
27+
featuregate.WithRegisterDescription("controls whether server-like receivers and extensions such as the OTLP receiver use localhost as the default host for their endpoints"),
28+
)
29+
30+
// mustRegisterOrLoad tries to register the feature gate and loads it if it already exists.
31+
// It panics on any other error.
32+
func mustRegisterOrLoad(reg *featuregate.Registry, id string, stage featuregate.Stage, opts ...featuregate.RegisterOption) *featuregate.Gate {
33+
gate, err := reg.Register(id, stage, opts...)
34+
35+
if errors.Is(err, featuregate.ErrAlreadyRegistered) {
36+
// Gate is already registered; find it.
37+
// Only a handful of feature gates are registered, so it's fine to iterate over all of them.
38+
reg.VisitAll(func(g *featuregate.Gate) {
39+
if g.ID() == id {
40+
gate = g
41+
return
42+
}
43+
})
44+
} else if err != nil {
45+
panic(err)
46+
}
47+
48+
return gate
49+
}
50+
51+
// EndpointForPort gets the endpoint for a given port using localhost or 0.0.0.0 depending on the feature gate.
52+
func EndpointForPort(port int) string {
53+
host := "localhost"
54+
if !useLocalHostAsDefaultHostfeatureGate.IsEnabled() {
55+
host = "0.0.0.0"
56+
}
57+
return fmt.Sprintf("%s:%d", host, port)
58+
}
59+
60+
// LogAboutUseLocalHostAsDefault logs about the upcoming change from 0.0.0.0 to localhost on server-like components.
61+
func LogAboutUseLocalHostAsDefault(logger *zap.Logger) {
62+
if !useLocalHostAsDefaultHostfeatureGate.IsEnabled() {
63+
logger.Warn(
64+
"The default endpoints for all servers in components will change to use localhost instead of 0.0.0.0 in a future version. Use the feature gate to preview the new default.",
65+
zap.String("feature gate ID", UseLocalHostAsDefaultHostID),
66+
)
67+
}
68+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Copyright The OpenTelemetry Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package localhostgate
5+
6+
import (
7+
"testing"
8+
9+
"github.com/stretchr/testify/assert"
10+
"github.com/stretchr/testify/require"
11+
12+
"go.opentelemetry.io/collector/featuregate"
13+
)
14+
15+
func setFeatureGateForTest(t testing.TB, gate *featuregate.Gate, enabled bool) func() {
16+
originalValue := gate.IsEnabled()
17+
require.NoError(t, featuregate.GlobalRegistry().Set(gate.ID(), enabled))
18+
return func() {
19+
require.NoError(t, featuregate.GlobalRegistry().Set(gate.ID(), originalValue))
20+
}
21+
}
22+
23+
func TestEndpointForPort(t *testing.T) {
24+
tests := []struct {
25+
port int
26+
enabled bool
27+
endpoint string
28+
}{
29+
{
30+
port: 4317,
31+
enabled: false,
32+
endpoint: "0.0.0.0:4317",
33+
},
34+
{
35+
port: 4317,
36+
enabled: true,
37+
endpoint: "localhost:4317",
38+
},
39+
{
40+
port: 0,
41+
enabled: false,
42+
endpoint: "0.0.0.0:0",
43+
},
44+
{
45+
port: 0,
46+
enabled: true,
47+
endpoint: "localhost:0",
48+
},
49+
}
50+
51+
for _, tt := range tests {
52+
t.Run(tt.endpoint, func(t *testing.T) {
53+
defer setFeatureGateForTest(t, useLocalHostAsDefaultHostfeatureGate, tt.enabled)()
54+
assert.Equal(t, EndpointForPort(tt.port), tt.endpoint)
55+
})
56+
}
57+
}

0 commit comments

Comments
 (0)