Skip to content

Commit

Permalink
Auth: set Authorization header on lookupd queries
Browse files Browse the repository at this point in the history
  • Loading branch information
jehiah committed Nov 23, 2020
1 parent d71da5b commit 34d2366
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
8 changes: 5 additions & 3 deletions api_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package nsq
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
Expand Down Expand Up @@ -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")

Expand Down
2 changes: 2 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 6 additions & 1 deletion consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"math"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"strconv"
Expand Down Expand Up @@ -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++
Expand Down

0 comments on commit 34d2366

Please sign in to comment.