chore: Enable G112 and G114 rules for gosec (#12986)

Co-authored-by: Pawel Zak <Pawel Zak>
This commit is contained in:
Paweł Żak 2023-04-03 15:23:05 +02:00 committed by GitHub
parent 0de59d48ec
commit edcd28650c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 156 additions and 43 deletions

View File

@ -93,6 +93,8 @@ linters-settings:
- G108 - G108
- G109 - G109
- G111 - G111
- G112
- G114
- G201 - G201
- G202 - G202
- G203 - G203

View File

@ -5,6 +5,7 @@ import (
"log" "log"
"net/http" "net/http"
"strings" "strings"
"time"
) )
type Server interface { type Server interface {
@ -33,7 +34,13 @@ func (p *PprofServer) Start(address string) {
log.Printf("I! Starting pprof HTTP server at: %s", pprofHostPort) log.Printf("I! Starting pprof HTTP server at: %s", pprofHostPort)
if err := http.ListenAndServe(address, nil); err != nil { server := &http.Server{
Addr: address,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
if err := server.ListenAndServe(); err != nil {
p.err <- fmt.Errorf("E! %w", err) p.err <- fmt.Errorf("E! %w", err)
} }
close(p.err) close(p.err)

View File

@ -40,6 +40,11 @@ See the [CONFIGURATION.md][CONFIGURATION.md] for more details.
## (Double check the port. Could be 9999 if using OSS Beta) ## (Double check the port. Could be 9999 if using OSS Beta)
service_address = ":8086" service_address = ":8086"
## Maximum duration before timing out read of the request
# read_timeout = "10s"
## Maximum duration before timing out write of the response
# write_timeout = "10s"
## Maximum allowed HTTP request body size in bytes. ## Maximum allowed HTTP request body size in bytes.
## 0 means to use the default of 32MiB. ## 0 means to use the default of 32MiB.
# max_body_size = "32MiB" # max_body_size = "32MiB"

View File

@ -30,7 +30,9 @@ var sampleConfig string
const ( const (
// defaultMaxBodySize is the default maximum request body size, in bytes. // defaultMaxBodySize is the default maximum request body size, in bytes.
// if the request body is over this size, we will return an HTTP 413 error. // if the request body is over this size, we will return an HTTP 413 error.
defaultMaxBodySize = 32 * 1024 * 1024 defaultMaxBodySize = 32 * 1024 * 1024
defaultReadTimeout = 10 * time.Second
defaultWriteTimeout = 10 * time.Second
) )
var ErrEOF = errors.New("EOF") var ErrEOF = errors.New("EOF")
@ -49,10 +51,12 @@ type InfluxDBV2Listener struct {
port int port int
tlsint.ServerConfig tlsint.ServerConfig
MaxBodySize config.Size `toml:"max_body_size"` ReadTimeout config.Duration `toml:"read_timeout"`
Token string `toml:"token"` WriteTimeout config.Duration `toml:"write_timeout"`
BucketTag string `toml:"bucket_tag"` MaxBodySize config.Size `toml:"max_body_size"`
ParserType string `toml:"parser_type"` Token string `toml:"token"`
BucketTag string `toml:"bucket_tag"`
ParserType string `toml:"parser_type"`
timeFunc influx.TimeFunc timeFunc influx.TimeFunc
@ -117,6 +121,13 @@ func (h *InfluxDBV2Listener) Init() error {
h.MaxBodySize = config.Size(defaultMaxBodySize) h.MaxBodySize = config.Size(defaultMaxBodySize)
} }
if h.ReadTimeout < config.Duration(time.Second) {
h.ReadTimeout = config.Duration(defaultReadTimeout)
}
if h.WriteTimeout < config.Duration(time.Second) {
h.WriteTimeout = config.Duration(defaultWriteTimeout)
}
return nil return nil
} }
@ -130,9 +141,11 @@ func (h *InfluxDBV2Listener) Start(acc telegraf.Accumulator) error {
} }
h.server = http.Server{ h.server = http.Server{
Addr: h.ServiceAddress, Addr: h.ServiceAddress,
Handler: h, Handler: h,
TLSConfig: tlsConf, TLSConfig: tlsConf,
ReadTimeout: time.Duration(h.ReadTimeout),
WriteTimeout: time.Duration(h.WriteTimeout),
} }
var listener net.Listener var listener net.Listener

View File

@ -4,6 +4,11 @@
## (Double check the port. Could be 9999 if using OSS Beta) ## (Double check the port. Could be 9999 if using OSS Beta)
service_address = ":8086" service_address = ":8086"
## Maximum duration before timing out read of the request
# read_timeout = "10s"
## Maximum duration before timing out write of the response
# write_timeout = "10s"
## Maximum allowed HTTP request body size in bytes. ## Maximum allowed HTTP request body size in bytes.
## 0 means to use the default of 32MiB. ## 0 means to use the default of 32MiB.
# max_body_size = "32MiB" # max_body_size = "32MiB"

View File

@ -1,6 +1,6 @@
# Webhooks Input Plugin # Webhooks Input Plugin
This is a Telegraf service plugin that start an http server and register This is a Telegraf service plugin that start a http server and register
multiple webhook listeners. multiple webhook listeners.
```sh ```sh
@ -43,6 +43,11 @@ See the [CONFIGURATION.md][CONFIGURATION.md] for more details.
## Address and port to host Webhook listener on ## Address and port to host Webhook listener on
service_address = ":1619" service_address = ":1619"
## Maximum duration before timing out read of the request
# read_timeout = "10s"
## Maximum duration before timing out write of the response
# write_timeout = "10s"
[inputs.webhooks.filestack] [inputs.webhooks.filestack]
path = "/filestack" path = "/filestack"

View File

@ -3,6 +3,11 @@
## Address and port to host Webhook listener on ## Address and port to host Webhook listener on
service_address = ":1619" service_address = ":1619"
## Maximum duration before timing out read of the request
# read_timeout = "10s"
## Maximum duration before timing out write of the response
# write_timeout = "10s"
[inputs.webhooks.filestack] [inputs.webhooks.filestack]
path = "/filestack" path = "/filestack"

View File

@ -7,10 +7,12 @@ import (
"net" "net"
"net/http" "net/http"
"reflect" "reflect"
"time"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs" "github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/inputs/webhooks/artifactory" "github.com/influxdata/telegraf/plugins/inputs/webhooks/artifactory"
"github.com/influxdata/telegraf/plugins/inputs/webhooks/filestack" "github.com/influxdata/telegraf/plugins/inputs/webhooks/filestack"
@ -24,6 +26,11 @@ import (
//go:embed sample.conf //go:embed sample.conf
var sampleConfig string var sampleConfig string
const (
defaultReadTimeout = 10 * time.Second
defaultWriteTimeout = 10 * time.Second
)
type Webhook interface { type Webhook interface {
Register(router *mux.Router, acc telegraf.Accumulator, log telegraf.Logger) Register(router *mux.Router, acc telegraf.Accumulator, log telegraf.Logger)
} }
@ -33,7 +40,9 @@ func init() {
} }
type Webhooks struct { type Webhooks struct {
ServiceAddress string `toml:"service_address"` ServiceAddress string `toml:"service_address"`
ReadTimeout config.Duration `toml:"read_timeout"`
WriteTimeout config.Duration `toml:"write_timeout"`
Github *github.GithubWebhook `toml:"github"` Github *github.GithubWebhook `toml:"github"`
Filestack *filestack.FilestackWebhook `toml:"filestack"` Filestack *filestack.FilestackWebhook `toml:"filestack"`
@ -82,13 +91,24 @@ func (wb *Webhooks) AvailableWebhooks() []Webhook {
} }
func (wb *Webhooks) Start(acc telegraf.Accumulator) error { func (wb *Webhooks) Start(acc telegraf.Accumulator) error {
if wb.ReadTimeout < config.Duration(time.Second) {
wb.ReadTimeout = config.Duration(defaultReadTimeout)
}
if wb.WriteTimeout < config.Duration(time.Second) {
wb.WriteTimeout = config.Duration(defaultWriteTimeout)
}
r := mux.NewRouter() r := mux.NewRouter()
for _, webhook := range wb.AvailableWebhooks() { for _, webhook := range wb.AvailableWebhooks() {
webhook.Register(r, acc, wb.Log) webhook.Register(r, acc, wb.Log)
} }
wb.srv = &http.Server{Handler: r} wb.srv = &http.Server{
Handler: r,
ReadTimeout: time.Duration(wb.ReadTimeout),
WriteTimeout: time.Duration(wb.WriteTimeout),
}
ln, err := net.Listen("tcp", wb.ServiceAddress) ln, err := net.Listen("tcp", wb.ServiceAddress)
if err != nil { if err != nil {

View File

@ -32,8 +32,16 @@ See the [CONFIGURATION.md][CONFIGURATION.md] for more details.
```toml @sample.conf ```toml @sample.conf
# This plugin implements the Zipkin http server to gather trace and timing data needed to troubleshoot latency problems in microservice architectures. # This plugin implements the Zipkin http server to gather trace and timing data needed to troubleshoot latency problems in microservice architectures.
[[inputs.zipkin]] [[inputs.zipkin]]
# path = "/api/v1/spans" # URL path for span data ## URL path for span data
# port = 9411 # Port on which Telegraf listens # path = "/api/v1/spans"
## Port on which Telegraf listens
# port = 9411
## Maximum duration before timing out read of the request
# read_timeout = "10s"
## Maximum duration before timing out write of the response
# write_timeout = "10s"
``` ```
The plugin accepts spans in `JSON` or `thrift` if the `Content-Type` is The plugin accepts spans in `JSON` or `thrift` if the `Content-Type` is
@ -67,7 +75,7 @@ Traces are built by collecting all Spans that share a traceId.
### Tags ### Tags
- __"id":__ The 64 bit ID of the span. - __"id":__ The 64-bit ID of the span.
- __"parent_id":__ An ID associated with a particular child span. If there is no child span, the parent ID is set to ID. - __"parent_id":__ An ID associated with a particular child span. If there is no child span, the parent ID is set to ID.
- __"trace_id":__ The 64 or 128-bit ID of a particular trace. Every span in a trace shares this ID. Concatenation of high and low and converted to hexadecimal. - __"trace_id":__ The 64 or 128-bit ID of a particular trace. Every span in a trace shares this ID. Concatenation of high and low and converted to hexadecimal.
- __"name":__ Defines a span - __"name":__ Defines a span
@ -103,7 +111,7 @@ SHOW TAG VALUES FROM "zipkin" WITH KEY = "service_name"
- __Description:__ returns a list of all `distinct` endpoint service names. - __Description:__ returns a list of all `distinct` endpoint service names.
-__Find spans with longest duration__- -__Find spans with the longest duration__-
```sql ```sql
SELECT max("duration_ns") FROM "zipkin" WHERE "service_name" = 'my_service' AND "name" = 'my_span_name' AND time > now() - 20m GROUP BY "trace_id",time(30s) LIMIT 5 SELECT max("duration_ns") FROM "zipkin" WHERE "service_name" = 'my_service' AND "name" = 'my_span_name' AND time > now() - 20m GROUP BY "trace_id",time(30s) LIMIT 5

View File

@ -1,4 +1,12 @@
# This plugin implements the Zipkin http server to gather trace and timing data needed to troubleshoot latency problems in microservice architectures. # This plugin implements the Zipkin http server to gather trace and timing data needed to troubleshoot latency problems in microservice architectures.
[[inputs.zipkin]] [[inputs.zipkin]]
# path = "/api/v1/spans" # URL path for span data ## URL path for span data
# port = 9411 # Port on which Telegraf listens # path = "/api/v1/spans"
## Port on which Telegraf listens
# port = 9411
## Maximum duration before timing out read of the request
# read_timeout = "10s"
## Maximum duration before timing out write of the response
# write_timeout = "10s"

View File

@ -9,10 +9,12 @@ import (
"net/http" "net/http"
"strconv" "strconv"
"sync" "sync"
"time"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs" "github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/inputs/zipkin/trace" "github.com/influxdata/telegraf/plugins/inputs/zipkin/trace"
) )
@ -21,22 +23,22 @@ import (
var sampleConfig string var sampleConfig string
const ( const (
// DefaultPort is the default port zipkin listens on, which zipkin implementations // defaultPort is the default port zipkin listens on, which zipkin implementations expect.
// expect. defaultPort = 9411
DefaultPort = 9411
// DefaultRoute is the default route zipkin uses, and zipkin implementations // defaultRoute is the default route zipkin uses, and zipkin implementations expect.
// expect. defaultRoute = "/api/v1/spans"
DefaultRoute = "/api/v1/spans"
// DefaultShutdownTimeout is the max amount of time telegraf will wait // defaultShutdownTimeout is the max amount of time telegraf will wait for the plugin to shut down
// for the plugin to shutdown defaultShutdownTimeout = 5 * time.Second
DefaultShutdownTimeout = 5
defaultReadTimeout = 10 * time.Second
defaultWriteTimeout = 10 * time.Second
) )
var ( var (
// DefaultNetwork is the network to listen on; use only in tests. // defaultNetwork is the network to listen on; use only in tests.
DefaultNetwork = "tcp" defaultNetwork = "tcp"
) )
// Recorder represents a type which can record zipkin trace data as well as // Recorder represents a type which can record zipkin trace data as well as
@ -56,9 +58,10 @@ type Handler interface {
// but it also contains fields for the management of a separate, concurrent // but it also contains fields for the management of a separate, concurrent
// zipkin http server // zipkin http server
type Zipkin struct { type Zipkin struct {
ServiceAddress string Port int `toml:"port"`
Port int Path string `toml:"path"`
Path string ReadTimeout config.Duration `toml:"read_timeout"`
WriteTimeout config.Duration `toml:"write_timeout"`
Log telegraf.Logger Log telegraf.Logger
@ -79,6 +82,13 @@ func (z *Zipkin) Gather(_ telegraf.Accumulator) error { return nil }
// Start launches a separate goroutine for collecting zipkin client http requests, // Start launches a separate goroutine for collecting zipkin client http requests,
// passing in a telegraf.Accumulator such that data can be collected. // passing in a telegraf.Accumulator such that data can be collected.
func (z *Zipkin) Start(acc telegraf.Accumulator) error { func (z *Zipkin) Start(acc telegraf.Accumulator) error {
if z.ReadTimeout < config.Duration(time.Second) {
z.ReadTimeout = config.Duration(defaultReadTimeout)
}
if z.WriteTimeout < config.Duration(time.Second) {
z.WriteTimeout = config.Duration(defaultWriteTimeout)
}
z.handler = NewSpanHandler(z.Path) z.handler = NewSpanHandler(z.Path)
var wg sync.WaitGroup var wg sync.WaitGroup
@ -91,11 +101,13 @@ func (z *Zipkin) Start(acc telegraf.Accumulator) error {
} }
z.server = &http.Server{ z.server = &http.Server{
Handler: router, Handler: router,
ReadTimeout: time.Duration(z.ReadTimeout),
WriteTimeout: time.Duration(z.WriteTimeout),
} }
addr := ":" + strconv.Itoa(z.Port) addr := ":" + strconv.Itoa(z.Port)
ln, err := net.Listen(DefaultNetwork, addr) ln, err := net.Listen(defaultNetwork, addr)
if err != nil { if err != nil {
return err return err
} }
@ -115,7 +127,7 @@ func (z *Zipkin) Start(acc telegraf.Accumulator) error {
// Stop shuts the internal http server down with via context.Context // Stop shuts the internal http server down with via context.Context
func (z *Zipkin) Stop() { func (z *Zipkin) Stop() {
ctx, cancel := context.WithTimeout(context.Background(), DefaultShutdownTimeout) ctx, cancel := context.WithTimeout(context.Background(), defaultShutdownTimeout)
defer z.waitGroup.Wait() defer z.waitGroup.Wait()
defer cancel() defer cancel()
@ -123,7 +135,7 @@ func (z *Zipkin) Stop() {
z.server.Shutdown(ctx) //nolint:errcheck // Ignore the returned error as we cannot do anything about it anyway z.server.Shutdown(ctx) //nolint:errcheck // Ignore the returned error as we cannot do anything about it anyway
} }
// Listen creates an http server on the zipkin instance it is called with, and // Listen creates a http server on the zipkin instance it is called with, and
// serves http until it is stopped by Zipkin's (*Zipkin).Stop() method. // serves http until it is stopped by Zipkin's (*Zipkin).Stop() method.
func (z *Zipkin) Listen(ln net.Listener, acc telegraf.Accumulator) { func (z *Zipkin) Listen(ln net.Listener, acc telegraf.Accumulator) {
if err := z.server.Serve(ln); err != nil { if err := z.server.Serve(ln); err != nil {
@ -141,8 +153,8 @@ func (z *Zipkin) Listen(ln net.Listener, acc telegraf.Accumulator) {
func init() { func init() {
inputs.Add("zipkin", func() telegraf.Input { inputs.Add("zipkin", func() telegraf.Input {
return &Zipkin{ return &Zipkin{
Path: DefaultRoute, Path: defaultRoute,
Port: DefaultPort, Port: defaultPort,
} }
}) })
} }

View File

@ -594,7 +594,7 @@ func TestZipkinPlugin(t *testing.T) {
// Workaround for Go 1.8 // Workaround for Go 1.8
// https://github.com/golang/go/issues/18806 // https://github.com/golang/go/issues/18806
DefaultNetwork = "tcp4" defaultNetwork = "tcp4"
z := &Zipkin{ z := &Zipkin{
Log: testutil.Logger{}, Log: testutil.Logger{},

View File

@ -20,6 +20,11 @@ See the [CONFIGURATION.md][CONFIGURATION.md] for more details.
## Address to listen on. ## Address to listen on.
listen = ":9273" listen = ":9273"
## Maximum duration before timing out read of the request
# read_timeout = "10s"
## Maximum duration before timing out write of the response
# write_timeout = "10s"
## Metric version controls the mapping from Prometheus metrics into Telegraf metrics. ## Metric version controls the mapping from Prometheus metrics into Telegraf metrics.
## See "Metric Format Configuration" in plugins/inputs/prometheus/README.md for details. ## See "Metric Format Configuration" in plugins/inputs/prometheus/README.md for details.
## Valid options: 1, 2 ## Valid options: 1, 2

View File

@ -28,10 +28,12 @@ import (
//go:embed sample.conf //go:embed sample.conf
var sampleConfig string var sampleConfig string
var ( const (
defaultListen = ":9273" defaultListen = ":9273"
defaultPath = "/metrics" defaultPath = "/metrics"
defaultExpirationInterval = config.Duration(60 * time.Second) defaultExpirationInterval = config.Duration(60 * time.Second)
defaultReadTimeout = 10 * time.Second
defaultWriteTimeout = 10 * time.Second
) )
type Collector interface { type Collector interface {
@ -42,6 +44,8 @@ type Collector interface {
type PrometheusClient struct { type PrometheusClient struct {
Listen string `toml:"listen"` Listen string `toml:"listen"`
ReadTimeout config.Duration `toml:"read_timeout"`
WriteTimeout config.Duration `toml:"write_timeout"`
MetricVersion int `toml:"metric_version"` MetricVersion int `toml:"metric_version"`
BasicUsername string `toml:"basic_username"` BasicUsername string `toml:"basic_username"`
BasicPassword string `toml:"basic_password"` BasicPassword string `toml:"basic_password"`
@ -141,10 +145,19 @@ func (p *PrometheusClient) Init() error {
return err return err
} }
if p.ReadTimeout < config.Duration(time.Second) {
p.ReadTimeout = config.Duration(defaultReadTimeout)
}
if p.WriteTimeout < config.Duration(time.Second) {
p.WriteTimeout = config.Duration(defaultWriteTimeout)
}
p.server = &http.Server{ p.server = &http.Server{
Addr: p.Listen, Addr: p.Listen,
Handler: mux, Handler: mux,
TLSConfig: tlsConfig, TLSConfig: tlsConfig,
ReadTimeout: time.Duration(p.ReadTimeout),
WriteTimeout: time.Duration(p.WriteTimeout),
} }
return nil return nil

View File

@ -3,6 +3,11 @@
## Address to listen on. ## Address to listen on.
listen = ":9273" listen = ":9273"
## Maximum duration before timing out read of the request
# read_timeout = "10s"
## Maximum duration before timing out write of the response
# write_timeout = "10s"
## Metric version controls the mapping from Prometheus metrics into Telegraf metrics. ## Metric version controls the mapping from Prometheus metrics into Telegraf metrics.
## See "Metric Format Configuration" in plugins/inputs/prometheus/README.md for details. ## See "Metric Format Configuration" in plugins/inputs/prometheus/README.md for details.
## Valid options: 1, 2 ## Valid options: 1, 2