Skip to content

Commit

Permalink
reload HOST token on query (#310)
Browse files Browse the repository at this point in the history
  • Loading branch information
jpinsonneau committed Mar 24, 2023
1 parent ca87bd1 commit be861fb
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 23 deletions.
9 changes: 7 additions & 2 deletions pkg/handler/loki.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -43,8 +44,12 @@ func newLokiClient(cfg *loki.Config, requestHeader http.Header) httpclient.Calle
} else {
hlog.Debug("Missing Authorization token in user request")
}
} else if cfg.Authorization != "" {
headers[auth.AuthHeader] = []string{cfg.Authorization}
} else if cfg.TokenPath != "" {
bytes, err := os.ReadFile(cfg.TokenPath)
if err != nil {
hlog.WithError(err).Fatalf("failed to parse authorization path: %s", cfg.TokenPath)
}
headers[auth.AuthHeader] = []string{"Bearer " + string(bytes)}
}

if cfg.UseMocks {
Expand Down
17 changes: 2 additions & 15 deletions pkg/loki/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,17 @@ package loki

import (
"net/url"
"os"
"time"

"github.com/netobserv/network-observability-console-plugin/pkg/utils"
"github.com/sirupsen/logrus"
)

var log = logrus.WithField("module", "loki config")

type Config struct {
URL *url.URL
StatusURL *url.URL
Timeout time.Duration
TenantID string
Authorization string
TokenPath string
SkipTLS bool
CAPath string
UseMocks bool
Expand All @@ -25,21 +21,12 @@ type Config struct {
}

func NewConfig(url *url.URL, statusURL *url.URL, timeout time.Duration, tenantID string, tokenPath string, forwardUserToken bool, skipTLS bool, capath string, useMocks bool, labels []string) Config {
authorization := ""
if tokenPath != "" {
bytes, err := os.ReadFile(tokenPath)
if err != nil {
log.WithError(err).Fatalf("failed to parse authorization path: %s", tokenPath)
}
authorization = "Bearer " + string(bytes)
}

return Config{
URL: url,
StatusURL: statusURL,
Timeout: timeout,
TenantID: tenantID,
Authorization: authorization,
TokenPath: tokenPath,
SkipTLS: skipTLS,
CAPath: capath,
UseMocks: useMocks,
Expand Down
44 changes: 38 additions & 6 deletions pkg/server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -373,25 +373,44 @@ func TestLokiConfigurationForTableHistogram(t *testing.T) {
assert.NotNil(t, qr.Result)
}

func prepareTokenFile(t *testing.T) (string, *os.File) {
tmpDir, err := os.MkdirTemp("", "server-test")
require.NoError(t, err)
tokensPath := filepath.Join(tmpDir, "/var/run/secrets/tokens/")
err = os.MkdirAll(tokensPath, os.ModePerm)
require.NoError(t, err)
dummyfile := filepath.Join(tokensPath, "netobserv-plugin")
f, err := os.Create(dummyfile)
require.NoError(t, err)
_, err = f.WriteString("XXX")
require.NoError(t, err)
err = os.Chdir(tmpDir)
require.NoError(t, err)
return tmpDir, f
}

func TestLokiConfiguration_MultiTenant(t *testing.T) {
tmpDir, file := prepareTokenFile(t)
defer os.RemoveAll(tmpDir)

lokiMock := httpMock{}
lokiMock.On("ServeHTTP", mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
_, _ = args.Get(0).(http.ResponseWriter).Write([]byte("{}"))
}).Once()
}).Twice()
authM := &authMock{}
authM.MockGranted()
lokiSvc := httptest.NewServer(&lokiMock)
defer lokiSvc.Close()
lokiURL, err := url.Parse(lokiSvc.URL)
require.NoError(t, err)

// GIVEN a NOO console plugin backend configured for Multi tenant mode
// GIVEN a NOO console plugin backend configured for HOST Multi tenant mode
backendRoutes := setupRoutes(&Config{
Loki: loki.Config{
URL: lokiURL,
Timeout: time.Second,
TenantID: "my-organisation",
Authorization: "Bearer XXX",
URL: lokiURL,
Timeout: time.Second,
TenantID: "my-organisation",
TokenPath: tmpDir + "/var/run/secrets/tokens/netobserv-plugin",
},
}, authM)
backendSvc := httptest.NewServer(backendRoutes)
Expand All @@ -405,6 +424,19 @@ func TestLokiConfiguration_MultiTenant(t *testing.T) {
req := lokiMock.Calls[0].Arguments[1].(*http.Request)
assert.Equal(t, "my-organisation", req.Header.Get("X-Scope-OrgID"))
assert.Equal(t, "Bearer XXX", req.Header.Get("Authorization"))

// UPDATE token file
_, err = file.WriteString("+updated")
require.NoError(t, err)

// RUN another query
_, err = backendSvc.Client().Get(backendSvc.URL + "/api/loki/flows")
require.NoError(t, err)

// THEN Bearer token is correctly updated
req = lokiMock.Calls[1].Arguments[1].(*http.Request)
assert.Equal(t, "my-organisation", req.Header.Get("X-Scope-OrgID"))
assert.Equal(t, "Bearer XXX+updated", req.Header.Get("Authorization"))
}

type httpMock struct {
Expand Down

0 comments on commit be861fb

Please sign in to comment.