From 34d236687bc2451eb0336ff434b8e145b12a723d Mon Sep 17 00:00:00 2001 From: Jehiah Czebotar Date: Mon, 23 Nov 2020 16:32:31 -0500 Subject: [PATCH] Auth: set Authorization header on lookupd queries --- api_request.go | 8 +++++--- config.go | 2 ++ consumer.go | 7 ++++++- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/api_request.go b/api_request.go index d4e389c9..d3e97596 100644 --- a/api_request.go +++ b/api_request.go @@ -3,7 +3,6 @@ package nsq import ( "encoding/json" "fmt" - "io" "io/ioutil" "net" "net/http" @@ -46,12 +45,15 @@ type wrappedResp struct { } // stores the result in the value pointed to by ret(must be a pointer) -func apiRequestNegotiateV1(method string, endpoint string, body io.Reader, ret interface{}) error { +func apiRequestNegotiateV1(method string, endpoint string, headers http.Header, ret interface{}) error { httpclient := &http.Client{Transport: newDeadlineTransport(2 * time.Second)} - req, err := http.NewRequest(method, endpoint, body) + req, err := http.NewRequest(method, endpoint, nil) if err != nil { return err } + for k, v := range headers { + req.Header[k] = v + } req.Header.Add("Accept", "application/vnd.nsq; version=1.0") diff --git a/config.go b/config.go index 05a81575..5517be1c 100644 --- a/config.go +++ b/config.go @@ -178,6 +178,8 @@ type Config struct { // secret for nsqd authentication (requires nsqd 0.2.29+) AuthSecret string `opt:"auth_secret"` + // skip using AuthSecret as 'Authorization: Bearer {AuthSecret}' on lookupd queries + SkipLookupdAuthorization bool `opt:"skip_lookupd_authorization"` } // NewConfig returns a new default nsq configuration. diff --git a/consumer.go b/consumer.go index 04cb1f62..ebf5d541 100644 --- a/consumer.go +++ b/consumer.go @@ -8,6 +8,7 @@ import ( "math" "math/rand" "net" + "net/http" "net/url" "os" "strconv" @@ -492,7 +493,11 @@ retry: r.log(LogLevelInfo, "querying nsqlookupd %s", endpoint) var data lookupResp - err := apiRequestNegotiateV1("GET", endpoint, nil, &data) + headers := make(http.Header) + if r.config.AuthSecret != "" && !r.config.SkipLookupdAuthorization { + headers.Set("Authorization", fmt.Sprintf("Bearer %s", r.config.AuthSecret)) + } + err := apiRequestNegotiateV1("GET", endpoint, headers, &data) if err != nil { r.log(LogLevelError, "error querying nsqlookupd (%s) - %s", endpoint, err) retries++