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

Add validation to process agent config endpoint #32273

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
21 changes: 21 additions & 0 deletions cmd/process-agent/api/config_set.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.

package api

import (
"net/http"

"github.com/DataDog/datadog-agent/pkg/api/util"
)

func configSetHandler(deps APIServerDeps, w http.ResponseWriter, r *http.Request) {
if err := util.Validate(w, r); err != nil {
deps.Log.Warnf("invalid auth token for %s request to %s: %s", r.Method, r.RequestURI, err)
return
}

deps.Settings.SetValue(w, r)
}
3 changes: 1 addition & 2 deletions cmd/process-agent/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ func SetupAPIServerHandlers(deps APIServerDeps, r *mux.Router) {
r.HandleFunc("/config/all", deps.Settings.GetFullConfig("")).Methods("GET") // Get all fields from process-agent Config object
r.HandleFunc("/config/list-runtime", deps.Settings.ListConfigurable).Methods("GET")
r.HandleFunc("/config/{setting}", deps.Settings.GetValue).Methods("GET")
r.HandleFunc("/config/{setting}", deps.Settings.SetValue).Methods("POST")

r.HandleFunc("/config/{setting}", injectDeps(deps, configSetHandler)).Methods("POST")
r.HandleFunc("/agent/status", injectDeps(deps, statusHandler)).Methods("GET")
r.HandleFunc("/agent/tagger-list", injectDeps(deps, getTaggerList)).Methods("GET")
r.HandleFunc("/agent/workload-list/short", func(w http.ResponseWriter, _ *http.Request) {
Expand Down
5 changes: 5 additions & 0 deletions cmd/process-agent/subcommands/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,11 @@ func getConfigValue(deps dependencies, args []string) error {
}

func getClient(cfg model.Reader) (settings.Client, error) {
err := util.SetAuthToken(cfg)
if err != nil {
return nil, err
}

httpClient := apiutil.GetClient(false)
ipcAddress, err := pkgconfigsetup.GetIPCAddress(pkgconfigsetup.Datadog())

Expand Down
6 changes: 6 additions & 0 deletions cmd/process-agent/subcommands/status/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
log "github.com/DataDog/datadog-agent/comp/core/log/def"
compStatus "github.com/DataDog/datadog-agent/comp/core/status"
"github.com/DataDog/datadog-agent/comp/process"
"github.com/DataDog/datadog-agent/pkg/api/util"
apiutil "github.com/DataDog/datadog-agent/pkg/api/util"
"github.com/DataDog/datadog-agent/pkg/collector/python"
pkgconfigsetup "github.com/DataDog/datadog-agent/pkg/config/setup"
Expand Down Expand Up @@ -147,6 +148,11 @@ func runStatus(deps dependencies) error {
return err
}

err = util.SetAuthToken(deps.Config)
if err != nil {
return err
}

getAndWriteStatus(deps.Log, statusURL, os.Stdout)
return nil
}
5 changes: 5 additions & 0 deletions cmd/process-agent/subcommands/taggerlist/tagger_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/DataDog/datadog-agent/comp/core/config"
log "github.com/DataDog/datadog-agent/comp/core/log/def"
"github.com/DataDog/datadog-agent/comp/core/tagger/api"
"github.com/DataDog/datadog-agent/pkg/api/util"
pkgconfigsetup "github.com/DataDog/datadog-agent/pkg/config/setup"
"github.com/DataDog/datadog-agent/pkg/util/fxutil"
)
Expand Down Expand Up @@ -58,6 +59,10 @@ func taggerList(deps dependencies) error {
return err
}

err = util.SetAuthToken(deps.Config)
if err != nil {
return err
}
return api.GetTaggerList(color.Output, taggerURL)
}

Expand Down
17 changes: 15 additions & 2 deletions comp/process/apiserver/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ import (

"github.com/DataDog/datadog-agent/cmd/process-agent/api"
"github.com/DataDog/datadog-agent/comp/api/authtoken"
log "github.com/DataDog/datadog-agent/comp/core/log/def"
logComp "github.com/DataDog/datadog-agent/comp/core/log/def"
"github.com/DataDog/datadog-agent/pkg/api/util"
pkgconfigsetup "github.com/DataDog/datadog-agent/pkg/config/setup"
"github.com/DataDog/datadog-agent/pkg/util/log"
)

var _ Component = (*apiserver)(nil)
Expand All @@ -31,7 +33,7 @@ type dependencies struct {

Lc fx.Lifecycle

Log log.Component
Log logComp.Component

At authtoken.Component

Expand All @@ -41,6 +43,7 @@ type dependencies struct {
//nolint:revive // TODO(PROC) Fix revive linter
func newApiServer(deps dependencies) Component {
r := mux.NewRouter()
r.Use(validateToken)
api.SetupAPIServerHandlers(deps.APIServerDeps, r) // Set up routes

addr, err := pkgconfigsetup.GetProcessAPIAddressPort(pkgconfigsetup.Datadog())
Expand Down Expand Up @@ -84,3 +87,13 @@ func newApiServer(deps dependencies) Component {

return apiserver
}

func validateToken(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := util.Validate(w, r); err != nil {
log.Warnf("invalid auth token for %s request to %s: %s", r.Method, r.RequestURI, err)
return
}
next.ServeHTTP(w, r)
})
}
60 changes: 54 additions & 6 deletions comp/process/apiserver/apiserver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,31 @@ import (
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/fx"

"github.com/DataDog/datadog-agent/comp/api/authtoken/fetchonlyimpl"
"github.com/DataDog/datadog-agent/comp/core"
"github.com/DataDog/datadog-agent/comp/core/config"
"github.com/DataDog/datadog-agent/comp/core/settings/settingsimpl"
"github.com/DataDog/datadog-agent/comp/core/status"
"github.com/DataDog/datadog-agent/comp/core/status/statusimpl"
tagger "github.com/DataDog/datadog-agent/comp/core/tagger/def"
taggerfx "github.com/DataDog/datadog-agent/comp/core/tagger/fx"
workloadmeta "github.com/DataDog/datadog-agent/comp/core/workloadmeta/def"
workloadmetafx "github.com/DataDog/datadog-agent/comp/core/workloadmeta/fx"
"github.com/DataDog/datadog-agent/pkg/api/util"
pkgconfigsetup "github.com/DataDog/datadog-agent/pkg/config/setup"
"github.com/DataDog/datadog-agent/pkg/util/fxutil"
)

func TestLifecycle(t *testing.T) {
_ = fxutil.Test[Component](t, fx.Options(
Module(),
core.MockBundle(),
fx.Replace(config.MockParams{Overrides: map[string]interface{}{
"process_config.cmd_port": 43424,
}}),
workloadmetafx.Module(workloadmeta.NewParams()),
fx.Supply(
status.Params{
Expand All @@ -43,13 +50,54 @@ func TestLifecycle(t *testing.T) {
fetchonlyimpl.MockModule(),
))

assert.Eventually(t, func() bool {
res, err := http.Get("http://localhost:6162/config")
if err != nil {
return false
}
assert.EventuallyWithT(t, func(c *assert.CollectT) {
req, err := http.NewRequest("GET", "http://localhost:43424/agent/status", nil)
require.NoError(c, err)
util.CreateAndSetAuthToken(pkgconfigsetup.Datadog())
req.Header.Set("Authorization", "Bearer "+util.GetAuthToken())
res, err := util.GetClient(false).Do(req)
require.NoError(c, err)
defer res.Body.Close()
assert.Equal(c, http.StatusOK, res.StatusCode)
}, 5*time.Second, time.Second)
}

func TestPostAuthentication(t *testing.T) {
_ = fxutil.Test[Component](t, fx.Options(
Module(),
core.MockBundle(),
fx.Replace(config.MockParams{Overrides: map[string]interface{}{
"process_config.cmd_port": 43424,
}}),
workloadmetafx.Module(workloadmeta.NewParams()),
fx.Supply(
status.Params{
PythonVersionGetFunc: func() string { return "n/a" },
},
),
taggerfx.Module(tagger.Params{
UseFakeTagger: true,
}),
statusimpl.Module(),
settingsimpl.MockModule(),
fetchonlyimpl.MockModule(),
))

return res.StatusCode == http.StatusOK
assert.EventuallyWithT(t, func(c *assert.CollectT) {
// No authentication
req, err := http.NewRequest("POST", "http://localhost:43424/config/log_level?value=debug", nil)
require.NoError(c, err)
res, err := util.GetClient(false).Do(req)
require.NoError(c, err)
defer res.Body.Close()
assert.Equal(c, http.StatusUnauthorized, res.StatusCode)

// With authentication
util.CreateAndSetAuthToken(pkgconfigsetup.Datadog())
req.Header.Set("Authorization", "Bearer "+util.GetAuthToken())
res, err = util.GetClient(false).Do(req)
require.NoError(c, err)
defer res.Body.Close()
assert.Equal(c, http.StatusOK, res.StatusCode)
}, 5*time.Second, time.Second)
}
5 changes: 5 additions & 0 deletions pkg/flare/archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,11 @@ func getProcessAgentTaggerList() ([]byte, error) {
return nil, fmt.Errorf("wrong configuration to connect to process-agent")
}

err = apiutil.SetAuthToken(pkgconfigsetup.Datadog())
if err != nil {
return nil, err
}

taggerListURL := fmt.Sprintf("http://%s/agent/tagger-list", addressPort)
return getTaggerList(taggerListURL)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Each section from every release note are combined when the
# CHANGELOG.rst is rendered. So the text needs to be worded so that
# it does not depend on any information only available in another
# section. This may mean repeating some details, but each section
# must be readable independently of the other.
#
# Each section note must be formatted as reStructuredText.
---
enhancements:
- |
The process agent endpoint for setting config values now uses authentication.
2 changes: 1 addition & 1 deletion test/new-e2e/tests/process/linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func (s *linuxTestSuite) TestProcessChecksInCoreAgent() {

// Verify that the process agent is not running
assert.EventuallyWithT(t, func(c *assert.CollectT) {
status := s.Env().RemoteHost.MustExecute("/opt/datadog-agent/embedded/bin/process-agent status")
status := s.Env().RemoteHost.MustExecute("sudo /opt/datadog-agent/embedded/bin/process-agent status")
assert.Contains(c, status, "The Process Agent is not running")
}, 1*time.Minute, 5*time.Second)

Expand Down
Loading