fix: Clear error message when provided config is not a text file (#11787)

This commit is contained in:
Sebastian Spaink 2022-09-13 11:43:03 -05:00 committed by GitHub
parent 614aec6d3f
commit b5f7ca4e08
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 1 deletions

View File

@ -581,7 +581,17 @@ func LoadConfigFile(config string) ([]byte, error) {
}
// If it isn't a https scheme, try it as a file
return os.ReadFile(config)
buffer, err := os.ReadFile(config)
if err != nil {
return nil, err
}
mimeType := http.DetectContentType(buffer)
if !strings.Contains(mimeType, "text/plain") {
return nil, fmt.Errorf("provided config is not a TOML file: %s", config)
}
return buffer, nil
}
func fetchConfig(u *url.URL) ([]byte, error) {

View File

@ -1,10 +1,13 @@
package config
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strings"
@ -26,6 +29,32 @@ import (
"github.com/influxdata/telegraf/plugins/parsers/json"
)
func TestReadBinaryFile(t *testing.T) {
// Create a temporary binary file using the Telegraf tool custom_builder to pass as a config
wd, err := os.Getwd()
require.NoError(t, err)
t.Cleanup(func() {
err := os.Chdir(wd)
require.NoError(t, err)
})
err = os.Chdir("../")
require.NoError(t, err)
tmpdir := t.TempDir()
binaryFile := filepath.Join(tmpdir, "custom_builder")
cmd := exec.Command("go", "build", "-o", binaryFile, "./tools/custom_builder")
var outb, errb bytes.Buffer
cmd.Stdout = &outb
cmd.Stderr = &errb
err = cmd.Run()
require.NoError(t, err, fmt.Sprintf("stdout: %s, stderr: %s", outb.String(), errb.String()))
c := NewConfig()
err = c.LoadConfig(binaryFile)
require.Error(t, err)
require.ErrorContains(t, err, "provided config is not a TOML file")
}
func TestConfig_LoadSingleInputWithEnvVars(t *testing.T) {
c := NewConfig()
require.NoError(t, os.Setenv("MY_TEST_SERVER", "192.168.1.1"))